# サービスロボット導入シミュレーション Log#52 | 搬送ロボットの立ち往生1件を、病院の3Dで見せる

- 記録: LOG526（サービスロボット導入シミュレーション）
- 公開: 2026/11/17
- 記事のページ: https://pixelstomotors.com/record/hospital-robot-stuck-30-seconds-in-3d
- サイト: Pixels to Motors（ADAPT DESIGN / 島津 栄一） https://pixelstomotors.com/
- 要約: 廊下の真ん中で車いすを止めて看護師2人が立ち話をすると、搬送ロボットが通れる幅はどこにも残らない。声をかけて気づいてもらうと25秒で通れ、気づかれないと50秒動けず「立ち往生」1件になる場面を、Unity の3Dで作った。

> AI が読むための記事の全文です（コード・実行ログを含む）。引用するときは上の「記事のページ」の住所を使ってください。

---

廊下の真ん中で車いすを止めて看護師2人が立ち話をすると、手すりの間が1.68mの病院の廊下には、薬を運ぶ搬送ロボットが通れる幅（0.842m）がどこにも残らない。**実物ではなく Unity の3DCGで作った病院の場面で、搬送ロボット「ハコブくん」が止まって5秒で「すみません、通ります」と声をかけると25.0秒で通れたが、声をかけても気づかれないと動けない時間は49.7秒になり、病院の1日のシミュレーションで数えている「立ち往生」（30秒以上動けず、人が動かした）の1件になった。**

この回でできるようになったことです。

- [サービスロボット導入シミュレーションのページ](https://pixelstomotors.com/series8#scenes) の「3Dで見る現場の場面」に、⑨-1「声をかけて通る」と⑨-2「立ち往生になる」を足した。どちらも真上から見た動画つきで、⑧車いすに道を譲る にも真上の動画を足した。看護師・患者・ハコブくんの声つき
- 病院の1日のシミュレーション（丸と四角で動く版）で数えている「立ち往生 1件」が、現場ではどんな場面で、何秒の差で分かれるのかを、セリフと時刻で見せられるようになった
- 看護師の寺島さん（マンガの寺島由美さん）の3Dモデルを作った。大城さんと骨の位置・名前が同じなので、大城さんの動き（歩く・話す・よける）がそのまま使える。3人目の人で、作り方のコードとモデルは GitHub に置いた
- 真上の動画に、床の線（通り道の目安）と、車いす・ハコブくんの通った跡を引いた。どこにいて、どう動いたかが1本の動画で分かる
- 時間：寺島さんのモデルは作り始めてから服の色が決まるまで約30分（21時00分〜21時30分）。Unity への依頼は9本で、作り直しも含めて 20時59分〜翌8時49分（夜中は回し係が順に回した）。前のやり方と比べられる時間は測っていない

困っていたのは、「立ち往生」が1日に何件、と数字で出ても、それが現場でどれくらい起きそうなことなのか、だれが何をすれば防げるのかが、丸と四角の動きでは伝わらないことでした。車いすを止めて話し込む、というのは病棟の廊下でふつうにあることです。止まった車いすの横に残る幅（0.514m）と、ハコブくんが通るのに要る幅（0.842m）を並べると、ハコブくんの側からはどうにもできないことが数字で分かります。分かれ目は、人が気づくかどうかでした。

| やったこと | 何を・なぜ | 結果 |
|---|---|---|
| 寺島さんの3D | 立ち話の相手。大城さんを写して、髪・めがね・胴の厚みを変えた。服は病棟でそろえて青 | 三角形 57,820。大城さんの骨と位置のずれ 0 |
| 依頼230・232・234・236 | ⑧の真上の動画に、床の線と通った跡を足し、線を体の下に描いた | 車いすや人の上・すき間に線が見えるコマ 0 |
| 依頼231・233 | ⑨を作る前に、通れる形があるかを計算した | 2回とも作る前に止まった（立ち位置の誤り、寄せ方の決まりが合わない） |
| 依頼235 | 止まった車いすは、その場で向きを変えて寄せる決まりにして2本を作った | 当たり 0。茂さんの声かけが不自然、「通れません」の顔が小さい |
| 依頼237・238 | 2本でやり取りを分け、横を通るときのお礼を足し、声をかけるのを5秒に早めた | ⑨-1 は25.0秒で通る、⑨-2 は49.7秒で立ち往生 1件 |
| サイト | /series8 の3Dの場面に⑨-1・⑨-2 と、⑧の真上の動画を足した | 場面は10本になった |

[図解: LOG526_stuck_30s.html](https://pixelstomotors.com/embeds/LOG526_stuck_30s.html)

配膳ロボットを自分の店に入れたらどうなるかは、このシリーズの試算をもとにした別のページで試せます。

[配膳ロボットの導入前シミュレーション](https://pixelstomotors.com/serving-robot-one-less-staff)


## 作業ログ ― ⑧の真上の動画で、車いすがどこにいてどう動いたかを見えるようにした

前の回（LOG523）で作った⑧車いすに道を譲る では、車いすが手すり側へ14cm寄せる動きを、真上からの動画でも撮っていました。その動画を見たエイイチの指摘です。

> 真上の動画だけど、車椅子がどの位置にいて動いたのかさっぱりわからないね。

真上のカメラがハコブくんのまわり（幅およそ6m）しか写しておらず、車いすは12.5秒ごろに右の端から入ってくるので、始めの位置も寄せる所もほとんど写っていませんでした。床に目印もないので、写っても14cmの違いは見分けられません。

### 依頼230：カメラを広げ、床の線と通った跡を引いた

真上のカメラを正射影（遠近のない写し方）にして、車いすが寄せ始める1秒前の位置から、ハコブくんを1.5m過ぎるまでが入る広さにしました。床には、廊下の中心の線、車いすの始めの線（+0.28）、寄せたあとの線（+0.42）、ハコブくんのふだんの線（−0.33）を引き、車いすとハコブくんが通った所には太い線を引いていきます。寄せ始め・寄せ終わり・寄り始め・止まった所には、印と時刻を出しました。左上の字は大きくして、秒・車いすの横の位置・すき間の3つにしぼりました。前の版で6.5秒ごろに出ていた「3402823…000 m」という壊れた値（すき間が測れない時に、測れないことを表す最大の数がそのまま出ていた）も、「—」にしました。

- ねらい：真上の動画だけで、車いすがどこから来て、いつ、どれだけ寄せたかを読めるようにする
- 変わったこと：車いすは、始めの線（+0.28）から寄せたあとの線（+0.42）へ、10.3〜13.8秒の間に跡を残して移る。寄せる前から終わりまで、画面から出ない
- 見込める効果：「14cm寄せた」を数字で読まなくても、線と跡で見て分かる。⑨の真上の動画も同じ作りで撮れる

### 依頼232・234・236：点線を、ハコブくん・人・車いすの下に描いた

> 点線はハコブくんや看護師、車椅子の下に表示した方がいいね。

依頼230 では、床の線を体の上に重ねて描いていました。依頼232 で、体だけを白く写した型を真上のカメラでコマごとに撮り、その白い所では床の線を消してから重ねる形にしました。直した動画を見たエイイチの指摘です。

> まだチラチラ点線が見えるね。

車いすの枠や車輪のすき間、茂さんの脚のあいだからは床がのぞくので、そこで点線が見えていました。車いすが動くとすき間の形が変わるので、ちらちらします。依頼234 で、ハコブくん・車いすと茂さん・大城さんを、それぞれ中の穴を埋めた外形にしてから線を消すようにし、床の線は通った跡の線の下にも描くようにしました。それでも大城さんの胴・腕と車いすの押し手で囲まれた床から、770コマのうち400コマで線が見えていたので、依頼236 で、大城さんが握りに手をのせている間は大城さんと車いすを1つのものとして穴を埋めました。

![真上の動画の12秒のコマの寄り。上は依頼234（ものごとに穴を埋めた版）で、大城さんの腕と押し手のあいだに点線が残っている。下は依頼236（押している間の大城さんと車いすを1つとして埋めた版）で、そこにも線が見えない](https://pixelstomotors.com/media/LOG526_06_top_mask.jpg)

| 版 | 線の描き方 | 体の所に見える線 |
|---|---|---|
| 依頼230 | 体の上に重ねる | 770コマのうち604コマで体に重なる |
| 依頼232 | 体の型で消す | 体の上は0。すき間からは見える |
| 依頼234 | ものごとに穴を埋めた外形で消す | すき間は0。大城さんと押し手のあいだが400コマ |
| 依頼236 | 押している間は大城さんと車いすを1つにまとめる | 0 |


## 作業ログ ― ⑨車いすが廊下の真ん中で止まる を考えた

⑧のあと、エイイチから次の場面を考えるよう頼まれました。

> ⑧の動画の続きを考えてください。もっといろんな場面が考えられます。

Claude が出した案は7つでした。病院の1日のシミュレーションで数えている問題（立ち往生・待ち時間・車いすの前を横切った）と同じ場面にすると、数字の1件が3Dで見えるので、その視点で選んでいます。

| 案 | 場面 | 1日のシミュレーションとの関係 |
|---|---|---|
| 1 | すれ違ったあと、看護師にお礼を言われる | ― |
| 2 | 車いすが廊下の真ん中で止まる（立ち話） | 立ち往生 |
| 3 | 患者に、何を運んでいるか聞かれる | ―（⑦のカードで確かめる話と対になる） |
| 4 | 同じ向きにゆっくり進む車いすに、後ろから追いつく | 待ち時間 |
| 5 | 曲がり角で出会う | 止まるまでの距離 |
| 6 | ストレッチャーが来て、くぼみまで下がる | ― |
| 7 | 自分でこぐ車いす・点滴スタンドの人 | ― |

エイイチが選んだのは2と3を先に作ることで、3は2の待ち時間の中に入れることにしました。2の終わり方は「声をかけて寄せてもらう（立ち往生にならない）」と「声をかけても気づかれず、30秒たって立ち往生になる」の2本です。止まる理由は、大城さんが知り合いと立ち話をする形にしました。カードを持っていない患者に聞かれたときのハコブくんの答えは「病棟へのお届け物です」で、行き先・中身・数は言いません。

### 病院の1日のシミュレーションの「立ち往生」は、30秒以上動けず、人が動かした回

立ち往生の決まりは、サイトの条件の表（tools/hospital_sim/hospital-unity-params.json の count_rules.stuck_s）に合わせました。30秒以上動けず、人が動かしに行った回を1件と数えます。⑨-2 では、30秒になった所で動画の左下に「立ち往生 1件（30 秒以上動けず、人が動かした）」を3秒出します。


## 作業ログ ― 立ち話の相手、看護師の寺島さんの3Dを作った

立ち話の相手は、マンガの看護師・寺島由美さんにしました。大城さんの3Dモデル（tools/sim_people/nurse_oshiro/）を写して、変えたのは髪（前髪のある、あごの下までのボブ）・丸めがね（こげ茶の細い縁。茂さんの作りを写した）・胴の厚み（少しふっくら）の3つだけです。骨の位置と名前、口の5つの形、目と眉の骨は大城さんと同じなので、大城さんを動かすコードがそのまま使えます。作り方は大城さんと同じく、形の式（距離の場）から Blender で書き出しています（Blender の説明は LOG523）。

最初はマンガの見分けやすさに合わせて、服をローズにしました。見た目を見たエイイチの指示です。

> 服の色は青で統一してください。

同じ病棟の看護師なので、服の色はそろえ、2人は髪型とめがねで見分けることにしました。

![左は今の大城さんの3D（正面・横・後ろ）、右は寺島さんの3D（正面・横・顔の寄り）。服は同じロイヤルブルーで、寺島さんは前髪のあるボブと丸めがね](https://pixelstomotors.com/media/LOG526_03_terashima.jpg)

Unity に読み込んだ Claude Code の報告では、骨は46本で、大城さんと位置・向きのずれは 0.0000、Humanoid の割り当て41本も名前の違いは0でした。


## 作業ログ ― 依頼231・233：作る前に、通れる形があるかを計算して止まった

### 依頼231：寺島さんを手すり側に立たせたので、寺島さんの逃げ場がなかった

依頼231 では、寺島さんを大城さんの横、ハコブくんが通る側の手すり寄りに立たせていました。Claude Code は作る前に、止まった所の両横の幅と、道を空ける時の形を計算し、成り立たないことを見つけて止めました。寺島さんの背中から手すりまで0.150mしかなく、0.5mよけると手すりの外へ0.350m出てしまいます。寺島さんがそこにいるかぎり、ハコブくんの通る幅も0.310m足りません。Claude の依頼文の誤りでした。

![依頼231 で Claude Code が計算した、止まった所の真上の図。車いすが廊下の真ん中、寺島さんがハコブくんの通る側の手すり寄りにいて、どちらの横にもハコブくんが通れる幅が残らない](https://pixelstomotors.com/media/LOG526_07_geo.jpg)

### 依頼233：⑧の「向き8°まで」の寄せ方では、前へ3m進まないと横へ寄れなかった

寺島さんを反対側に立たせ直した依頼233 では、別の理由で止まりました。⑧で決めた寄せ方（車いすの向きは最大8°まで変え、進みながら寄せる）だと、車いすを横へ42cmずらすのに前へ2.99m以上進む必要があります。車いすの前に空いているのは、ハコブくんが止まる所まで2.30mでした。⑧の寄せ方は、すれ違いながら少しずつ寄せる時の決まりで、止まっている車いすをその場で寄せ直す時には合いませんでした。

![依頼233 で Claude Code が計算した図。左は止まった所で、車いすの両横は0.514mずつ、ハコブくんが通るのに要る幅は0.842m。右は⑧の寄せ方で+0.42まで寄せると前へ3.59m進む必要があり、ハコブくんにぶつかる](https://pixelstomotors.com/media/LOG526_08_geo.jpg)

もう1つ、寺島さんが大城さんの真横にいると、大城さんは顔を約99°回さないと寺島さんを見られないことも、作る前に見つかりました。エイイチに聞いて決めたのは次の2つです。

- 止まっている車いすは、その場で向きを最大30°まで変えて寄せ、最後にまっすぐに戻す（速さは0.3m/秒まで、向きの変わる速さは25°/秒まで）
- 立ち話の間、大城さんは寺島さんから遠い側の手を握りからはなし、体ごと寺島さんのほうを向く。寄せる前に両手で握り直す

声は、茂さんの分がまだありませんでした。Claude Code が使っている ElevenLabs の鍵には声の一覧を読む権限がなく、新しい声を選べなかったためです。

> 声は今まで作った声を使っていいですよ。前に色々作っているのでLOGを見直してください。

解説動画の決まり（video_rules.md）に、ElevenLabs の自分で作れる声が10個で上限になった時に「森田茂さん＝田中先生の声」と決めた記録がありました。⑨に田中先生は出ないので、そのまま使いました。


## 作業ログ ― 依頼235：その場で寄せる形で、2本を作った

依頼235 では、決めた寄せ方で道があるかを先に計算し、「回る +12° → 前へ 0.84m → 回る −17° → 後ろへ 0.73m → 回る −10° → 後ろへ 0.19m → 回る 0°」という道を見つけてから作りました。実際の動きでは、向きの最大は17°、前へ0.822m、足のせとハコブくんのあいだの最小は1.568mです。ハコブくんが通る時のすき間の最小は、車いす0.232m・大城さん0.287m・寺島さん0.645mで、当たったコマは2本とも0でした。

動画を見たエイイチの指摘は3つでした。

> 通れませんのハコブくんの顔が小さいので修正。それと茂さんがハコブくんに声かけるのが不自然だね（セリフが良くないのか、タイミングが良くないのか、あとどっちも同じセリフだと芸がないね）

> ハコブくんが車椅子横を通る時声をかけるか、ニコッと笑う描写くらいはあった方がいいね。

茂さんの「何を運んでるの？」は、止まって3〜4秒で、何のきっかけもなく話しかけていました。2本とも同じセリフでした。


## 作業ログ ― 依頼237・238：2本でやり取りを分け、通るときのお礼を足した

### 茂さんのセリフを、2本の流れに合わせて分けた

Claude が出したセリフの案を、エイイチが選びました。⑨-1 では、茂さんはハコブくんの声に気づいて大城さんに取り次ぎ、横を通る時に何を運んでいるか聞きます。⑨-2 では、看護師2人が気づかないまま20秒たったあとに、自分では動けない茂さんが、同じく待たされているハコブくんに声をかけます。

| | ⑨-1 声をかけて通る | ⑨-2 立ち往生になる |
|---|---|---|
| 声をかける | 止まって5秒で「すみません、通ります」 | 10秒と20秒で「すみません、通ります」。2人は気づかない |
| 茂さん | 「大城さん、ロボットさんが通るって」 | 「あんたも待たされてるのかい」→ ハコブ「はい、お待ちしています」 |
| 気づく | 大城さん「あ、ごめんね」 | 30秒で画面が黄色の「通れません」→ 寺島さん「あ、ハコブくん」→ 大城さん「あ、ごめんね」 |
| 横を通る | 茂さん「何を運んでるんだい？」→ ハコブ「病棟へのお届け物です。ありがとうございます」と目まで笑う顔 | ハコブ「ありがとうございます」と目まで笑う顔。茂さんが小さくうなずく |
| 動けない時間 | 25.0秒 | 49.7秒（立ち往生 1件） |

依頼237 の版では、茂さんの最初のセリフは「おい、ロボットさんが通るって」でした。

> 茂さんのおいっ、が結構強い言い方すぎるかもね。

看護師を名前で呼ぶ「大城さん、ロボットさんが通るって」に替えました。名前で呼ぶと、大城さんが茂さんの後ろにいて、茂さんが大城さんに伝えていることも分かりやすくなります。

### 「声をかければすぐ解決する」版が、30秒まで0.2秒しかなかった

依頼237 の⑨-1 は、動けない時間が29.833秒でした。声をかけて解決する話なのに、立ち往生の30秒とほとんど同じ長さです。止まって10秒で声をかけ、そのあと茂さんが取り次いで、大城さんが握り直してその場で寄せるまでに時間がかかるためでした。依頼238 で、声をかけるのを止まって5秒に早めました。

- ねらい：⑨-1 と⑨-2 の違い（人が気づくかどうか）が、動けない時間の差としてはっきり見えるようにする
- 変わったこと：⑨-1 の動けない時間は 29.833秒 → 25.033秒。⑨-2 は 49.666秒のまま
- 見込める効果：30秒の線をはさんで、25秒と50秒に分かれる。病院の1日のシミュレーションで、声をかけるまでの秒数を変えると立ち往生の件数がどう変わるかを見る時の、3Dの見本になる（1日のシミュレーションではまだ試していない）

![⑨-1 声をかけて通る（依頼238）。左上は立ち話の車いすの前でハコブくんが止まった所、右上は「大城さん、ロボットさんが通るって」と取り次ぐ茂さん、左下は大城さんがその場で車いすを寄せている所、右下は横を通るときの「ありがとうございます」の目まで笑う顔](https://pixelstomotors.com/media/LOG526_01_stop_voice.jpg)

![⑨-2 立ち往生になる（依頼237）。左上は「あんたも待たされてるのかい」と言う茂さん、右上は30秒で黄色の「通れません」になった画面（顔はふだんの大きさ）、左下は動画の左下に出る「立ち往生 1件（30 秒以上動けず、人が動かした）」、右下は横を通るときの目まで笑う顔](https://pixelstomotors.com/media/LOG526_02_stop_stuck.jpg)

![⑨-1 の真上の動画のコマ。大城さんがその場で向きを変えて車いすを寄せていて、寺島さんは手すり沿いへ下がっている。左はハコブくん](https://pixelstomotors.com/media/LOG526_05_shift_top.jpg)

「通れません」の顔は、ほかの帯（「お待ちしています」など）の顔と画素で同じ大きさになりました（目の高さ 258・幅 124・目の間 553 画素。依頼235 は 78 画素）。画面に行き先・中身・数が出たコマは、2本とも0です。


## 作業ログ ― サイトの3Dの場面に、⑨-1・⑨-2 と⑧の真上の動画を足した

[サービスロボット導入シミュレーションのページ](https://pixelstomotors.com/series8#scenes) の「3Dで見る現場の場面」は、src/data/sim_scenes.json に場面ごとの動画・説明・時刻を書いて並べています。⑨-1 を「09 立ち話の車いすに声をかけて通る」、⑨-2 を「10 立ち話の車いすで立ち往生になる」として足し、どちらにも本番のカメラと真上からの2つの角度を付けました。⑧には、依頼236 の真上の動画を2つ目の角度として足しました。動画と表紙の画像は R2（p2m-media）に入れています。

### sim_scenes.json の差分

```diff
diff --git a/src/data/sim_scenes.json b/src/data/sim_scenes.json
index e3674f2..3f8872d 100644
--- a/src/data/sim_scenes.json
+++ b/src/data/sim_scenes.json
@@ -1,8 +1,8 @@
 {
-  "about": "サービスロボット導入シミュレーション（/series8）の「3Dの場面」に並べる動画と、場面ごとの説明（2026-11-13・LOG503）。動画は R2（p2m-media）の /media/。時刻は本番のカメラの動画の秒。看護師とハコブくんは実物ではなく Unity の3DCG。⑤⑥は 2026-11-15 に追加（依頼205・214）、2026-11-16 に画面の「2個」を「1個」に直した v2（依頼221）へ差し替え。⑦は依頼222。⑧は依頼229（2026-11-16・患者と車いすのモデルは tools/sim_people/morita_shigeru/）",
+  "about": "サービスロボット導入シミュレーション（/series8）の「3Dの場面」に並べる動画と、場面ごとの説明（2026-11-13・LOG503）。動画は R2（p2m-media）の /media/。時刻は本番のカメラの動画の秒。看護師とハコブくんは実物ではなく Unity の3DCG。⑤⑥は 2026-11-15 に追加（依頼205・214）、2026-11-16 に画面の「2個」を「1個」に直した v2（依頼221）へ差し替え。⑦は依頼222。⑧は依頼229（2026-11-16・患者と車いすのモデルは tools/sim_people/morita_shigeru/）。⑧の真上の動画は依頼236。⑨⑩は依頼238・237（2026-11-17・LOG526。看護師の寺島さんのモデルは tools/sim_people/nurse_terashima/）",
   "groups": ["薬剤部", "病棟", "廊下"],
   "title": "3Dで見る、看護師と搬送ロボットのやり取り",
-  "note": "試算や病院の1日のシミュレーションでは、人とロボットは丸や四角で動きます。ここでは、その中の要所を、看護師と搬送ロボット「ハコブくん」の3DCGで短く切り取りました。薬を積む・受け取る・廊下ですれ違うに加え、受け取る人が来ない・認証に失敗する・廊下で話しかけられる・車いすに道を譲る、といった場面も入れています。動きの速さは現場に合わせています（Unity・実物ではありません）。",
+  "note": "試算や病院の1日のシミュレーションでは、人とロボットは丸や四角で動きます。ここでは、その中の要所を、看護師と搬送ロボット「ハコブくん」の3DCGで短く切り取りました。薬を積む・受け取る・廊下ですれ違うに加え、受け取る人が来ない・認証に失敗する・廊下で話しかけられる・車いすに道を譲る・立ち話の車いすで通れない、といった場面も入れています。動きの速さは現場に合わせています（Unity・実物ではありません）。",
   "log": { "label": "作り方とコードの記録（LOG503）", "href": "/record/hospital-robot-nurse-3d-scenes-at-real-speed" },
   "scenes": [
     {
@@ -196,7 +196,8 @@
       "situation": "薬を運ぶハコブくんの前から、看護師が患者の車いすを押して来ます。ハコブくんと車いすはどちらも幅0.65mで、並ぶと手すりの間の8割をふさぎます。ハコブくんは減速して手すりに寄って止まり、画面と声で「お先にどうぞ」と伝えます。看護師も車いすを少し手すり側へ寄せて通りすぎ、看護師が1m以上離れてから、ハコブくんが走り出します。",
       "points": ["6m手前で見つけ、減速して手すりに寄り、車いすの2.3m手前で止まる", "そのまま進めばすき間は9cm。手すりに寄って止まり、看護師も寄せて22cm空ける", "看護師が1m以上離れるまで、ハコブくんは動かない（0m）"],
       "angles": [
-        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_08_yield_v1.mp4", "sec": 25.7, "timed": true, "note": "声あり（音を出して見てください）。ハコブくんと看護師の声は AI 音声です" }
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_08_yield_v1.mp4", "sec": 25.7, "timed": true, "note": "声あり（音を出して見てください）。ハコブくんと看護師の声は AI 音声です" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_08_yield_top_v1.mp4", "sec": 25.7, "timed": true, "note": "床の点線は通り道の目安。オレンジは車いす、緑はハコブくんの通った跡。左上に車いすの横の位置とすき間を出しています" }
       ],
       "steps": [
         { "t": 0.0, "text": "ハコブくんが薬を載せて廊下を走る。向こうから車いすが来る" },
@@ -208,6 +209,64 @@
         { "t": 15.6, "text": "車いすがハコブくんの横を通りすぎる" },
         { "t": 20.5, "text": "看護師が1m以上離れてから、ハコブくんが走り出す" }
       ]
+    },
+    {
+      "id": "stop_voice",
+      "group": "廊下",
+      "num": "09",
+      "name": "立ち話の車いすに声をかけて通る",
+      "short": "止まって5秒で声をかけ、25秒で通れた",
+      "poster": "/media/scene3d_09_stop_voice_poster_v1.jpg",
+      "place": "幅1.8mの病棟の廊下（両側に手すり）",
+      "who": "看護師2人（車いすを押す人と、立ち話の相手）・入院中の患者（車いすに乗る人）・ハコブくん（薬を載せて走っている）",
+      "situation": "看護師が患者の車いすを押していると、後ろから同僚の看護師が声をかけ、廊下の真ん中で車いすを止めて立ち話を始めます。車いすの両横に残るのは0.514mずつで、ハコブくんが通るのに要る0.842mはどちらにもありません。ハコブくんは止まって5秒で「すみません、通ります」と声をかけ、患者が看護師に取り次ぎ、看護師がその場で車いすを手すり側へ寄せます。横を通るとき、患者に何を運んでいるか聞かれても、ハコブくんは行き先も中身も言いません。",
+      "points": ["車いすを真ん中に止めると、どちらの横にもハコブくんが通れる幅は残らない", "止まって5秒で声をかけ、動けない時間は25.0秒（立ち往生の30秒より短い）", "カードを持たない患者に聞かれても「病棟へのお届け物です」とだけ答える"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_09_stop_voice_v1.mp4", "sec": 49.5, "timed": true, "note": "声あり（音を出して見てください）。看護師・患者・ハコブくんの声は AI 音声です" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_09_stop_voice_top_v1.mp4", "sec": 49.5, "timed": true, "note": "床の点線は通り道の目安。車いすがその場で向きを変えて寄せる動きが見えます" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが薬を載せて廊下を走る。前を看護師が車いすを押していく" },
+        { "t": 5.1, "text": "同僚の看護師「大城さん」" },
+        { "t": 7.9, "text": "看護師が車いすを廊下の真ん中で止めて振り返り、立ち話を始める" },
+        { "t": 12.2, "text": "ハコブくんが通れずに止まる。画面「お待ちしています」" },
+        { "t": 17.2, "text": "「すみません、通ります」" },
+        { "t": 19.1, "text": "患者「大城さん、ロボットさんが通るって」" },
+        { "t": 21.7, "text": "看護師「あ、ごめんね」。両手で握り直し、その場で車いすを寄せる" },
+        { "t": 37.2, "text": "ハコブくんが走り出す（動けない時間 25.0秒）" },
+        { "t": 41.1, "text": "患者「何を運んでるんだい？」" },
+        { "t": 42.7, "text": "「病棟へのお届け物です。ありがとうございます」と目まで笑う顔" }
+      ]
+    },
+    {
+      "id": "stop_stuck",
+      "group": "廊下",
+      "num": "10",
+      "name": "立ち話の車いすで立ち往生になる",
+      "short": "声をかけても気づかれず、50秒動けない",
+      "poster": "/media/scene3d_10_stop_stuck_poster_v1.jpg",
+      "place": "幅1.8mの病棟の廊下（両側に手すり）",
+      "who": "看護師2人（車いすを押す人と、立ち話の相手）・入院中の患者（車いすに乗る人）・ハコブくん（薬を載せて走っている）",
+      "situation": "⑨と同じく、看護師2人が廊下の真ん中で車いすを止めて立ち話をしています。ハコブくんは10秒と20秒で「すみません、通ります」と声をかけますが、2人は話に夢中で気づきません。自分では動けない患者が「あんたも待たされてるのかい」とハコブくんに声をかけます。30秒たつと画面が黄色の「通れません」に変わり、それに気づいた看護師が車いすを寄せて、やっと通れます。病院の1日のシミュレーションでは、この1回を「立ち往生」1件と数えます。",
+      "points": ["30秒以上動けず、人が車いすを動かしてやっと通れた → 立ち往生 1件", "動けない時間は49.7秒。⑨との差は、人が声に気づいたかどうか", "30秒で画面を黄色の「通れません」に変え、離れた人にも知らせる"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_10_stop_stuck_v1.mp4", "sec": 69.7, "timed": true, "note": "声あり（音を出して見てください）。10〜20秒の間は早回し（×4）で、右上に実際の時刻を出しています" },
+        { "id": "top", "label": "真上から", "src": "/media/scene3d_10_stop_stuck_top_v1.mp4", "sec": 69.7, "timed": true, "note": "床の点線は通り道の目安。オレンジは車いす、緑はハコブくんの通った跡" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが薬を載せて廊下を走る。前を看護師が車いすを押していく" },
+        { "t": 5.1, "text": "同僚の看護師「大城さん」" },
+        { "t": 7.9, "text": "看護師が車いすを廊下の真ん中で止めて振り返り、立ち話を始める" },
+        { "t": 12.2, "text": "ハコブくんが通れずに止まる。画面「お待ちしています」" },
+        { "t": 22.2, "text": "「すみません、通ります」。2人は気づかない（このあと早回し）" },
+        { "t": 27.7, "text": "もう一度「すみません、通ります」。まだ気づかない" },
+        { "t": 31.7, "text": "患者「あんたも待たされてるのかい」／「はい、お待ちしています」" },
+        { "t": 37.7, "text": "30秒。画面が黄色の「通れません」→ 立ち往生 1件" },
+        { "t": 40.1, "text": "同僚の看護師「あ、ハコブくん」" },
+        { "t": 41.8, "text": "看護師「あ、ごめんね」。車いすをその場で寄せる" },
+        { "t": 57.3, "text": "ハコブくんが走り出す（動けない時間 49.7秒）" },
+        { "t": 63.6, "text": "「ありがとうございます」と目まで笑う顔。患者が小さくうなずく" }
+      ]
     }
   ]
 }
```


## 作業ログ ― 寺島さんを作るコード（p2m-site の tools/sim_people/nurse_terashima/）

大城さんの nurse_build.py を写し、髪の関数を前髪のあるボブに、めがねの関数を足し、胴と服の数字を替えたものです。描く・姿勢を付けるコードは、大城さんのものを名前だけ替えて写しました。

### README.md

```markdown
# 看護師（寺島さん・寺島由美）の3Dモデル（サービスロボット導入シミュレーション・病院の場面の人）

要所の場面 ⑨車いすが廊下の真ん中で止まる のための人（2026-11-16）。大城さんが車いすを止めて立ち話をする相手。マンガの寺島由美さんの三面図（terashima_ref.jpg）を元に、大城さん（../nurse_oshiro/）を写して作った。

- 大城さんから変えたのは3つだけ：髪（前髪のある、あごの下までのボブ）・丸めがね（こげ茶の細い縁。茂さんの作りを写した）・胴の厚み（少しふっくら）
- 服の色は大城さんと同じロイヤルブルー（病棟で統一・2026-11-16 エイイチ）。2人は髪とめがねで見分ける
- 大きさ・骨の位置と名前・口の5つの形・目と眉の骨は大城さんと同じ。**大城さんを動かすコードがそのまま使える**（Humanoid で読める）
- 根は Nurse_Terashima。部品は Terashima_Skin・Terashima_Hair・Terashima_Glasses・Terashima_Top など（大城さんの Nurse_ を Terashima_ に替えた名前）。めがねと髪は Head の骨だけで動く

## 作り方

1. `pip install bpy==5.3.0 scikit-image`
2. `python3 terashima_build.py <出力フォルダ> --vox 0.0025`：nurse_terashima.fbx・terashima_clay.blend・terashima_report.json
3. 確認用の絵（GitHub に入れない。iCloud の サービスロボット導入シミュレーション/hospital/people_3d/）
   - `python3 terashima_render.py <出力>/terashima_clay.blend <絵のフォルダ> front side back persp face upper`
   - `python3 terashima_pose.py <出力>/terashima_clay.blend <絵のフォルダ>`：大城さんと同じ8つの姿勢。服や肌が破れないかの確認用

## 中身（三角形 57,820）

Skin 15,258・Hair 6,008・Glasses 3,692・Top 10,474・Sleeves 4,222・Pants 6,614・Shoes 2,520・Eyes 2,616・Brows 1,004・口5つ（smile が既定で表示）

## 気をつけること

- 髪はあごの下まであるので、首を大きく横へ回す（45° を超える）と、毛先が肩に少し入る
- Unity の ServiceSim では、依頼231 で Assets/ServiceSim/Closeups/Models_terashima/ に写して使っている（iCloud の hospital/people_3d/terashima/ から）
```

### terashima_build.py

```python
"""粘土のような簡略化した看護師（寺島さん・寺島由美）を、形の式（距離の場）から作る。
大城さん（../nurse_oshiro/nurse_build.py）を写して、髪（前髪のあるボブ）・丸めがね・胴の厚みだけを変えた（服の色は大城さんと同じ）。
骨の位置と名前は大城さんと同じ（同じ動かし方のコードが使える）。
python3 terashima_build.py <out_dir> [--vox 0.0025]
前が -y、上が z、単位は m。身長 1.65 m。
出力：terashima_clay.blend・nurse_terashima.fbx・terashima_report.json（部品ごとの三角形の数・骨の名前）
FBX は Unity 向け（顔が Unity の +Z、上が +Y）。骨は Unity の Humanoid の名前（Hips・LeftUpperArm など）。
口は5つの形（smile・flat・worried・talk・surprised）を別の部品で入れてあり、Unity で表示を切り替える。
"""
import math
import os
import sys

import bpy  # noqa: I001  bpy を先に読む
import numpy as np
from skimage.measure import marching_cubes

OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)
VOX = float(sys.argv[sys.argv.index("--vox") + 1]) if "--vox" in sys.argv else 0.0025


# ---------- 形の式 ----------
def length(v):
    return np.sqrt(np.sum(v * v, axis=0))


def ellipsoid(p, c, r):
    q = (p - np.array(c).reshape(3, 1)) / np.array(r).reshape(3, 1)
    k0 = length(q)
    k1 = length(q / np.array(r).reshape(3, 1))
    return k0 * (k0 - 1.0) / np.maximum(k1, 1e-9)


def capsule(p, a, b, ra, rb):
    a = np.array(a, float).reshape(3, 1)
    b = np.array(b, float).reshape(3, 1)
    ba = b - a
    h = np.clip(np.sum((p - a) * ba, axis=0) / np.sum(ba * ba), 0, 1)
    return length(p - a - ba * h) - (ra + (rb - ra) * h)


def smin(a, b, k):
    h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1)
    return b + (a - b) * h - k * h * (1 - h)


def smax(a, b, k):
    return -smin(-a, -b, k)


def union(ds, k):
    d = ds[0]
    for e in ds[1:]:
        d = smin(d, e, k)
    return d


def shell(d, t):
    return np.maximum(d, -(d + t))


# ---------- 寸法 ----------
HC = np.array([0.0, 0.0, 1.516])          # 頭の中心


def H(x, y, z):
    return (HC + np.array([x, y, z])).tolist()


SH = 0.150                                  # 肩の関節の横の位置
ARM_OUT = math.radians(9)                   # 腕の開き
ARM_FWD = math.radians(4)


def arm_points(side):
    s = 1 if side > 0 else -1
    sh = np.array([s * SH, 0.01, 1.300])
    d1 = np.array([s * math.sin(ARM_OUT), -math.sin(ARM_FWD), -math.cos(ARM_OUT)])
    d1 /= np.linalg.norm(d1)
    el = sh + d1 * 0.250
    d2 = np.array([s * math.sin(ARM_OUT * 0.6), -math.sin(math.radians(14)), -1.0])
    d2 /= np.linalg.norm(d2)
    wr = el + d2 * 0.220
    return sh, el, wr, d1, d2


def hand_geo(side):
    """手の形の骨組み（手首・手のひら・指の関節の位置）。形と骨の両方で使う。
    u＝手首から指先の向き、n＝手のひらの向き（体のほう）、w＝親指のほう（前）"""
    s = 1 if side > 0 else -1
    _, _, wr, _, u = arm_points(side)
    n = np.array([-s, 0.0, 0.0])            # 手のひらは体のほうを向く
    n = n - u * np.dot(n, u)
    n /= np.linalg.norm(n)
    w = np.cross(u, n) * s                  # 前（-y）向きにそろえる
    if w[1] > 0:
        w = -w
    base = wr + u * 0.085
    fingers = {}
    for name, off, ln, r in (("Index", 0.026, 0.070, 0.0105), ("Middle", 0.009, 0.078, 0.0108),
                             ("Ring", -0.009, 0.074, 0.0105), ("Little", -0.025, 0.060, 0.0095)):
        a = base + w * off
        d_1 = u * math.cos(math.radians(14)) + n * math.sin(math.radians(14))
        b = a + d_1 * ln * 0.52
        d_2 = u * math.cos(math.radians(38)) + n * math.sin(math.radians(38))
        c = b + d_2 * ln * 0.48
        fingers[name] = (a, b, c, r)
    ta = wr + u * 0.03 + w * 0.024 + n * 0.006
    td = u * 0.55 + w * 0.65 + n * 0.45
    td /= np.linalg.norm(td)
    tb = ta + td * 0.04
    td2 = u * 0.75 + w * 0.3 + n * 0.6
    td2 /= np.linalg.norm(td2)
    tc = tb + td2 * 0.032
    return {"wr": wr, "u": u, "n": n, "w": w, "palm_end": base, "fingers": fingers, "thumb": (ta, tb, tc)}


def palm(p, side):
    g = hand_geo(side)
    wr, u, w = g["wr"], g["u"], g["w"]
    ds = [ellipsoid(p, (wr + u * 0.048).tolist(), (0.024, 0.024, 0.024))]
    # 手のひらは平たい楕円。軸に沿って並べた小さい楕円で作る
    for t in (0.02, 0.045, 0.07):
        c = wr + u * t
        ds.append(capsule(p, (c - w * 0.022).tolist(), (c + w * 0.022).tolist(), 0.019, 0.019))
    return union(ds, 0.010)


def finger_segs(p, side):
    """指の節ごとの形：{骨の名前の後ろ半分: 形}"""
    g = hand_geo(side)
    out = {}
    for name, (a, b, c, r) in g["fingers"].items():
        out[name + "Proximal"] = capsule(p, a.tolist(), b.tolist(), r, r * 0.95)
        out[name + "Intermediate"] = capsule(p, b.tolist(), c.tolist(), r * 0.95, r * 0.88)
    ta, tb, tc = g["thumb"]
    out["ThumbProximal"] = capsule(p, ta.tolist(), tb.tolist(), 0.0135, 0.012)
    out["ThumbIntermediate"] = capsule(p, tb.tolist(), tc.tolist(), 0.012, 0.0105)
    return out


def hand(p, side):
    return union([palm(p, side)] + list(finger_segs(p, side).values()), 0.010)


def head_solid(p):
    cr = ellipsoid(p, H(0, 0, 0), (0.098, 0.106, 0.108))
    jaw = ellipsoid(p, H(0, -0.010, -0.055), (0.080, 0.082, 0.072))
    d = smin(cr, jaw, 0.03)
    cheeks = [ellipsoid(p, H(s * 0.044, -0.055, -0.045), (0.040, 0.036, 0.035)) for s in (-1, 1)]
    d = union([d] + cheeks, 0.03)
    nose = ellipsoid(p, H(0, -0.099, -0.026), (0.011, 0.011, 0.014))
    d = smin(d, nose, 0.010)
    ears = [ellipsoid(p, H(s * 0.096, 0.008, -0.020), (0.014, 0.021, 0.029)) for s in (-1, 1)]
    return union([d] + ears, 0.008)


def skin(p):
    ds = [head_solid(p)]
    ds.append(capsule(p, (0, 0.012, 1.30), (0, 0.006, 1.45), 0.044, 0.041))
    ds.append(ellipsoid(p, (0, 0.012, 1.27), (0.10, 0.066, 0.08)))
    for sd in (-1, 1):   # 首の付け根から肩へ（服の内側を肌で埋める）
        ds.append(capsule(p, (sd * 0.045, 0.015, 1.335), (sd * 0.12, 0.015, 1.31), 0.024, 0.022))
    d = union(ds, 0.03)
    arms = []
    for side in (-1, 1):
        sh, el, wr, _, _ = arm_points(side)
        a = smin(capsule(p, sh.tolist(), el.tolist(), 0.040, 0.037),
                 capsule(p, el.tolist(), wr.tolist(), 0.036, 0.029), 0.02)
        arms.append(smin(a, hand(p, side), 0.012))
    d = union([d] + arms, 0.01)
    # 袖の中に隠れる腕の付け根の肌は作らない（腕を上げて服がのびたとき、肌が服から突き出ないように）
    for side in (-1, 1):
        sh, _, _, d1, _ = arm_points(side)
        q = p - sh.reshape(3, 1)
        proj = np.sum(q * d1.reshape(3, 1), axis=0)
        radial = length(q - d1.reshape(3, 1) * proj)
        inside = np.maximum(np.maximum(-0.12 - proj, proj - 0.134), radial - 0.065)
        d = smax(d, -inside, 0.005)
    return d


BANG_Z = HC[2] + 0.036                      # 前髪の下の端（眉の少し上）
BOB_Z = HC[2] - 0.118                       # 毛先の高さ（あごの下くらい）


def hair(p):
    """前髪のあるボブ。顔の前（左右 62° まで・前髪より下）だけを抜き、横と後ろはあごの下まで下ろす。
    毛先は外へ少しはねて、ゆるく波打つ"""
    x = p[0] - HC[0]
    y = p[1] - (HC[1] + 0.005)
    th = np.degrees(np.arctan2(x, -y))
    a = np.abs(th)
    crown = ellipsoid(p, H(0, 0.012, 0.004), (0.118, 0.124, 0.124))
    body = ellipsoid(p, H(0, 0.020, -0.060), (0.122, 0.118, 0.085))
    flare = ellipsoid(p, H(0, 0.022, -0.100), (0.134, 0.112, 0.036))      # 毛先のはね
    d = union([crown, body, flare], 0.03)
    bottom = BOB_Z + 0.005 * np.sin(np.radians(th) * 7.0)
    d = smax(d, bottom - p[2], 0.008)
    # 顔の前を抜く：向きが 62° より前で、前髪の下の端より下
    face = np.maximum(np.radians(a - 62.0) * 0.11, p[2] - BANG_Z)
    d = smax(d, -face, 0.010)
    # 首の前（あごの下）も抜く
    neck = np.maximum(np.radians(a - 80.0) * 0.11, p[2] - (HC[2] - 0.060))
    return smax(d, -neck, 0.010)


def top(p):
    rr = 0.068
    c = np.array([0.0, 0.010, 1.085]).reshape(3, 1)
    b = np.array([0.160 - rr, 0.106 - rr, 0.30 - rr]).reshape(3, 1)
    qq = np.abs(p - c) - b
    d = length(np.maximum(qq, 0)) + np.minimum(qq.max(axis=0), 0) - rr
    # 首から肩へのなで肩の線
    ax = np.abs(p[0])
    slope = (p[2] - (1.372 - 0.25 * np.clip(ax - 0.05, 0, 0.09) - 0.16 * np.maximum(ax - 0.14, 0))) / 1.03
    d = smax(d, slope, 0.06)
    bust = [ellipsoid(p, (s * 0.061, -0.062, 1.175), (0.059, 0.057, 0.054)) for s in (-1, 1)]
    d = union([d] + bust, 0.045)
    outer = d
    d = shell(d, 0.007)
    d = smax(d, 0.80 - p[2], 0.004)                         # すそ
    neck = np.sqrt(p[0] ** 2 + (p[1] - 0.010) ** 2) - 0.051
    vee = np.maximum(p[1] + 0.02, (1.288 + 1.15 * np.abs(p[0])) - p[2]) / 1.5
    cut = smin(np.maximum(neck, 1.30 - p[2]), vee, 0.02)    # 丸い首まわりと V を角なしでつなぐ
    d = smax(d, -cut, 0.009)                                 # えりぐり（後ろは丸く、前は V）
    # ポケット：表面に貼った薄い板（胸の左に1つ、すその左右に1つずつ）
    for cx, cz, hw, hh in ((0.068, 1.19, 0.034, 0.038), (0.088, 0.875, 0.046, 0.046), (-0.088, 0.875, 0.046, 0.046)):
        rect = np.maximum(np.abs(p[0] - cx) - hw, np.abs(p[2] - cz) - hh)
        layer = np.maximum(outer - 0.0035, -outer - 0.004)
        d = np.minimum(d, np.maximum(np.maximum(rect, layer), p[1]))
    return d


def sleeves(p):
    """袖は胴とつなげず、別の部品にする（胴とつなげると、腕を動かしたとき継ぎ目が裂ける）。
    袖の上の丸みは胴の肩の中に入っていて、腕を上げても袖の筒がそのまま腕といっしょに回る"""
    sl = []
    for side in (-1, 1):
        sh, el, _, d1, _ = arm_points(side)
        # 袖の上の丸みは胴の肩より低くして、肩の線から飛び出さないようにする
        c = capsule(p, (sh + d1 * 0.035).tolist(), (sh + d1 * 0.2).tolist(), 0.051, 0.051)
        c = shell(c, 0.006)
        proj = np.sum((p - sh.reshape(3, 1)) * d1.reshape(3, 1), axis=0)
        sl.append(smax(c, proj - 0.14, 0.004))
    return np.minimum(sl[0], sl[1])


def pants(p):
    ds = [ellipsoid(p, (0, 0.012, 0.86), (0.152, 0.092, 0.10))]
    for s in (-1, 1):
        ds.append(capsule(p, (s * 0.080, 0.01, 0.82), (s * 0.095, 0.0, 0.08), 0.074, 0.062))
    d = union(ds, 0.03)
    return smax(d, 0.075 - p[2], 0.004)


def shoes(p):
    ds = []
    for s in (-1, 1):
        ds.append(ellipsoid(p, (s * 0.096, -0.035, 0.028), (0.048, 0.115, 0.052)))
    d = union(ds, 0.01)
    return smax(d, -p[2], 0.006)


def surface_y(x, z):
    """顔の正面の表面の y を、前から光線を進めて求める。"""
    y = -0.2
    for _ in range(200):
        d = float(head_solid(np.array([[x], [y], [z]]))[0])
        if d < 1e-5:
            break
        y += max(d * 0.8, 1e-5)
    return y


EYE_Z = HC[2] - 0.012


def eye_center(side):
    x = side * 0.038
    return np.array([x, surface_y(x, EYE_Z) + 0.0035, EYE_Z])


def eyes(p):
    ds = []
    for s in (-1, 1):
        x, yc, z = eye_center(s)
        # ハコブくんの縦長の丸い目に寄せる：縦のカプセル（側面がまっすぐ）と楕円の中間の形
        k = 0.0118 / 0.0062
        ps = p.copy()
        ps[1] = (p[1] - yc) * k + yc
        pill = capsule(ps, (x, yc, z - 0.0072), (x, yc, z + 0.0072), 0.0118, 0.0118) / k
        ell = ellipsoid(p, (x, yc, z), (0.0128, 0.0062, 0.0188))
        ds.append(0.65 * pill + 0.35 * ell)
    return union(ds, 0.002)


def glasses(p):
    """丸めがね（細い縁）。つるは耳まで（耳は髪の中）。茂さん（../morita_shigeru）の作りを写した"""
    ds = []
    R, r = 0.0205, 0.0015
    for s in (-1, 1):
        x, yc, z = eye_center(s)
        y = yc - 0.015
        qx, qy, qz = p[0] - x, p[1] - y, p[2] - z
        ring = np.sqrt((np.sqrt(qx ** 2 + qz ** 2) - R) ** 2 + qy ** 2) - r
        ds.append(ring)
        ds.append(capsule(p, (x + s * R, y + 0.002, z + 0.004), (s * 0.099, HC[1] + 0.008, HC[2] - 0.006), 0.0013, 0.0013))
        ds.append(capsule(p, (s * 0.099, HC[1] + 0.008, HC[2] - 0.006), (s * 0.097, HC[1] + 0.032, HC[2] - 0.030), 0.0013, 0.0013))
    xl, yl, zl = eye_center(1)
    xr, _, _ = eye_center(-1)
    yb = yl - 0.017
    ds.append(capsule(p, (xr + R * 0.96, yb, zl + 0.004), (0.0, yb - 0.003, zl + 0.008), 0.0013, 0.0013))
    ds.append(capsule(p, (0.0, yb - 0.003, zl + 0.008), (xl - R * 0.96, yb, zl + 0.004), 0.0013, 0.0013))
    return union(ds, 0.0008)


def brow_points(side):
    xs = np.linspace(0.022, 0.056, 8)
    pts = [(side * x0, 0.0275 + 0.003 * (1 - ((x0 - 0.037) / 0.019) ** 2)) for x0 in xs]
    q = [(x0, surface_y(x0, HC[2] + z0) + 0.0012, HC[2] + z0) for x0, z0 in pts]
    rs = [0.0021 + 0.0005 * (1 - abs(x0 - 0.034) / 0.022) for x0 in xs]
    return q, rs


def brows(p):
    ds = []
    for s in (-1, 1):
        q, rs = brow_points(s)
        for i in range(len(q) - 1):
            ds.append(capsule(p, q[i], q[i + 1], rs[i], rs[i + 1]))
    return union(ds, 0.002)


MOUTH_Z = HC[2] - 0.068


def mouth_line(p, half_w, curve, z0=MOUTH_Z, r=0.0017):
    """横の線の口。curve＞0 で端が上がる（笑顔）、＜0 で端が下がる（困り顔）"""
    xs = np.linspace(-half_w, half_w, 13)
    q = []
    for x0 in xs:
        z = z0 + curve * (x0 / half_w) ** 2
        q.append((x0, surface_y(x0, z) + 0.0012, z))
    ds = [capsule(p, q[i], q[i + 1], r, r) for i in range(len(q) - 1)]
    return union(ds, 0.002)


def mouth_open(p, rx, rz, flat_top=True, z0=MOUTH_Z):
    """開いた口（話す・驚く）。flat_top で上がまっすぐ・下が丸い形"""
    y = surface_y(0.0, z0)
    zc = z0 + (rz * 0.35 if flat_top else 0.0)
    d = ellipsoid(p, (0.0, y + 0.0028, zc), (rx, 0.0045, rz))
    if flat_top:
        d = smax(d, p[2] - (zc - rz * 0.05), 0.0015)
    return d


MOUTHS = {   # 口の形（Unity で表示を切り替える。既定は smile）
    "smile": lambda p: mouth_line(p, 0.015, 0.006),
    "flat": lambda p: mouth_line(p, 0.012, 0.0),
    "worried": lambda p: mouth_line(p, 0.011, -0.004, z0=MOUTH_Z - 0.002),
    "talk": lambda p: mouth_open(p, 0.011, 0.0085),
    "surprised": lambda p: mouth_open(p, 0.0065, 0.0085, flat_top=False),
}


# ---------- 格子で面にする ----------
def mesh_of(fn, lo, hi, vox):
    lo, hi = np.array(lo, float) + vox * 0.37, np.array(hi, float)   # 格子の点が平らな面にちょうど乗らないようにずらす
    n = np.ceil((hi - lo) / vox).astype(int) + 1
    xs = lo[0] + np.arange(n[0]) * vox
    ys = lo[1] + np.arange(n[1]) * vox
    zs = lo[2] + np.arange(n[2]) * vox
    vol = np.empty((n[0], n[1], n[2]), np.float32)
    gx, gy = np.meshgrid(xs, ys, indexing="ij")
    step = 24
    for k0 in range(0, n[2], step):
        zz = zs[k0:k0 + step]
        P = np.stack([np.repeat(gx[..., None], len(zz), 2), np.repeat(gy[..., None], len(zz), 2),
                      np.broadcast_to(zz, (n[0], n[1], len(zz)))]).reshape(3, -1)
        vol[:, :, k0:k0 + step] = fn(P).reshape(n[0], n[1], len(zz))
    v, f, _, _ = marching_cubes(vol, 0.0, spacing=(vox, vox, vox))
    return v + lo, f


def to_blender(name, v, f, col, rough=0.6, sss=0.0, ratio=None):
    me = bpy.data.meshes.new(name)
    me.from_pydata(v.tolist(), [], f.tolist())   # marching_cubes の向きのままで外向き（逆にすると Unity で全部の面が裏返った・依頼162）
    me.update()
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    if ratio:
        m = ob.modifiers.new("dec", "DECIMATE")
        m.ratio = ratio
        bpy.context.view_layer.objects.active = ob
        bpy.ops.object.modifier_apply(modifier="dec")
    for poly in ob.data.polygons:
        poly.use_smooth = True
    mat = bpy.data.materials.new(name + "_Mat")
    mat.use_nodes = True
    b = mat.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*[(c / 255) ** 2.2 for c in col], 1)
    b.inputs["Roughness"].default_value = rough
    if sss:
        b.inputs["Subsurface Weight"].default_value = sss
        b.inputs["Subsurface Radius"].default_value = (0.02, 0.008, 0.005)
    ob.data.materials.append(mat)
    print(name, len(ob.data.polygons), "faces")
    return ob


SKIN = (232, 180, 142)
HAIR = (38, 30, 27)
ROYAL = (44, 84, 170)        # 服の色は大城さんと同じロイヤルブルー（病棟で統一・2026-11-16 エイイチ）
FRAME = (92, 72, 64)        # めがねの縁（こげ茶）
WHITE = (238, 238, 234)
DARK = (44, 34, 30)
LIP = (150, 72, 66)

# ---------- 骨 ----------
# Unity の Humanoid がそのまま読み取れる名前にする（Left＝本人の左＝+x。前は -y）。
# 目・眉の骨は Humanoid に入れない追加の骨（まばたき・眉の上げ下げをスクリプトで動かす）。
def leg_points(side):
    s = 1 if side > 0 else -1
    hip = np.array([s * 0.085, 0.010, 0.860])
    knee = np.array([s * 0.090, 0.000, 0.470])
    ankle = np.array([s * 0.095, 0.004, 0.085])
    ball = np.array([s * 0.096, -0.075, 0.025])
    tip = np.array([s * 0.096, -0.140, 0.022])
    return hip, knee, ankle, ball, tip


FWD = (0, -1, 0)


def bone_layout():
    """{骨の名前: (根元, 先, 親, 骨の z 軸を向ける向き)}"""
    B = {
        "Hips": ((0, 0.012, 0.90), (0, 0.012, 0.98), None, FWD),
        "Spine": ((0, 0.012, 0.98), (0, 0.012, 1.11), "Hips", FWD),
        "Chest": ((0, 0.012, 1.11), (0, 0.012, 1.30), "Spine", FWD),
        "Neck": ((0, 0.012, 1.31), (0, 0.006, 1.42), "Chest", FWD),
        "Head": ((0, 0.006, 1.42), (0, 0.0, 1.62), "Neck", FWD),
    }
    for side, L, tag in ((1, "Left", "L"), (-1, "Right", "R")):
        s = side
        sh, el, wr, _, _ = arm_points(side)
        g = hand_geo(side)
        n = g["n"]
        B[L + "Shoulder"] = ((s * 0.030, 0.012, 1.325), sh, "Chest", FWD)
        B[L + "UpperArm"] = (sh, el, L + "Shoulder", FWD)
        B[L + "LowerArm"] = (el, wr, L + "UpperArm", FWD)
        B[L + "Hand"] = (wr, g["palm_end"], L + "LowerArm", n)
        for fname, (a, b, c, _) in g["fingers"].items():
            B[L + fname + "Proximal"] = (a, b, L + "Hand", n)
            B[L + fname + "Intermediate"] = (b, c, L + fname + "Proximal", n)
        ta, tb, tc = g["thumb"]
        B[L + "ThumbProximal"] = (ta, tb, L + "Hand", n)
        B[L + "ThumbIntermediate"] = (tb, tc, L + "ThumbProximal", n)
        hip, knee, ankle, ball, tip = leg_points(side)
        B[L + "UpperLeg"] = (hip, knee, "Hips", FWD)
        B[L + "LowerLeg"] = (knee, ankle, L + "UpperLeg", FWD)
        B[L + "Foot"] = (ankle, ball, L + "LowerLeg", (0, 0, 1))
        B[L + "Toes"] = (ball, tip, L + "Foot", (0, 0, 1))
        ec = eye_center(side)
        B["Eye_" + tag] = (ec, ec + np.array([0, -0.015, 0]), "Head", (0, 0, 1))
        q, _ = brow_points(side)
        bc = np.mean(np.array(q), axis=0)
        B["Brow_" + tag] = (bc, bc + np.array([0, -0.012, 0]), "Head", (0, 0, 1))
    return B


def band(p, z0, z1):
    return np.maximum(z0 - p[2], p[2] - z1)


def regions(kind, p):
    """部品の種類ごとに、骨ごとの「その骨の受け持つ形までの距離」を返す。重みはここから決める"""
    R = {}
    if kind == "skin":
        R["Head"] = head_solid(p)
        R["Neck"] = capsule(p, (0, 0.012, 1.30), (0, 0.006, 1.45), 0.044, 0.041)
        R["Chest"] = ellipsoid(p, (0, 0.012, 1.27), (0.10, 0.066, 0.08))
        for side, L in ((1, "Left"), (-1, "Right")):
            sh, el, wr, _, _ = arm_points(side)
            R[L + "Shoulder"] = capsule(p, (side * 0.045, 0.015, 1.335), (side * 0.12, 0.015, 1.31), 0.024, 0.022)
            R[L + "UpperArm"] = capsule(p, sh.tolist(), el.tolist(), 0.040, 0.037)
            R[L + "LowerArm"] = capsule(p, el.tolist(), wr.tolist(), 0.036, 0.029)
            R[L + "Hand"] = palm(p, side)
            for k, v in finger_segs(p, side).items():
                R[L + k] = v
    elif kind == "top":
        rr = 0.068
        c = np.array([0.0, 0.010, 1.085]).reshape(3, 1)
        b = np.array([0.160 - rr, 0.106 - rr, 0.30 - rr]).reshape(3, 1)
        qq = np.abs(p - c) - b
        torso = length(np.maximum(qq, 0)) + np.minimum(qq.max(axis=0), 0) - rr
        R["Hips"] = np.maximum(torso, band(p, 0.60, 0.94))
        R["Spine"] = np.maximum(torso, band(p, 0.94, 1.10))
        R["Chest"] = np.maximum(torso, band(p, 1.10, 1.45))
        for side, L in ((1, "Left"), (-1, "Right")):
            sh, _, _, _, _ = arm_points(side)
            R[L + "Shoulder"] = capsule(p, (side * 0.045, 0.012, 1.33), sh.tolist(), 0.045, 0.045)
    elif kind == "pants":
        R["Hips"] = ellipsoid(p, (0, 0.012, 0.86), (0.152, 0.092, 0.10))
        for side, L in ((1, "Left"), (-1, "Right")):
            hip, knee, ankle, _, _ = leg_points(side)
            R[L + "UpperLeg"] = capsule(p, hip.tolist(), knee.tolist(), 0.074, 0.066)
            R[L + "LowerLeg"] = capsule(p, knee.tolist(), ankle.tolist(), 0.066, 0.062)
    elif kind == "shoes":
        for side, L in ((1, "Left"), (-1, "Right")):
            _, _, ankle, ball, tip = leg_points(side)
            R[L + "Foot"] = capsule(p, ankle.tolist(), ball.tolist(), 0.05, 0.05)
            R[L + "Toes"] = capsule(p, ball.tolist(), tip.tolist(), 0.045, 0.04)
    return R


def tau_of(bone):
    if any(k in bone for k in ("Index", "Middle", "Ring", "Little")):
        return 0.0022
    if "Thumb" in bone:
        return 0.0025
    if bone.endswith("Hand"):
        return 0.005
    if bone in ("Hips", "Spine", "Chest"):
        return 0.018
    if "Leg" in bone or "Foot" in bone or "Toes" in bone:
        return 0.018
    return 0.011


def weight_mesh(ob, kind):
    P = np.array([v.co for v in ob.data.vertices]).T          # 根は原点・回転なしなので形の座標そのまま
    R = regions(kind, P)
    names = list(R)
    D = np.stack([R[k] for k in names])
    dmin = D.min(axis=0)
    # パンツは腰と太ももの境目を広くなだらかにする（しゃがむと付け根の面が細かく折れた・依頼162）
    tau = (lambda k: 0.045 if k == "Hips" or "UpperLeg" in k else tau_of(k)) if kind == "pants" else tau_of
    W = np.stack([np.exp(-np.maximum(D[i] - dmin, 0) / tau(k)) for i, k in enumerate(names)])
    W = W / W.sum(axis=0)
    top4 = np.argsort(-W, axis=0)[:4]
    groups = {k: ob.vertex_groups.new(name=k) for k in names}
    for vi in range(P.shape[1]):
        idx = top4[:, vi]
        w = W[idx, vi]
        w = w / w.sum()
        for j, ww in zip(idx, w):
            if ww > 0.01:
                groups[names[j]].add([vi], float(ww), "REPLACE")


def weight_sleeves(ob):
    """袖はまるごと上腕の骨に付ける（付け根を肩の骨と分け合うと、腕を上げた時に袖の山がゆがんだ）。
    袖の山は肩の関節のすぐ外にあるので、腕と一緒に回しても肩から離れない"""
    for side, L in ((1, "Left"), (-1, "Right")):
        g = ob.vertex_groups.new(name=L + "UpperArm")
        g.add([v.index for v in ob.data.vertices if v.co.x * side > 0], 1.0, "REPLACE")


def weight_whole(ob, bone):
    g = ob.vertex_groups.new(name=bone)
    g.add(list(range(len(ob.data.vertices))), 1.0, "REPLACE")


def weight_by_side(ob, prefix):
    for tag, sgn in (("L", 1), ("R", -1)):
        g = ob.vertex_groups.new(name=prefix + tag)
        g.add([v.index for v in ob.data.vertices if v.co.x * sgn > 0], 1.0, "REPLACE")


def build_armature():
    from mathutils import Vector
    arm = bpy.data.armatures.new("Nurse_Terashima_Rig")
    rig = bpy.data.objects.new("Nurse_Terashima", arm)          # 根：床の中心
    bpy.context.scene.collection.objects.link(rig)
    bpy.context.view_layer.objects.active = rig
    bpy.ops.object.mode_set(mode="EDIT")
    B = bone_layout()
    eb = {}
    for name, (h, t, _, _) in B.items():
        b = arm.edit_bones.new(name)
        b.head = Vector([float(x) for x in h])
        b.tail = Vector([float(x) for x in t])
        eb[name] = b
    for name, (_, _, parent, zdir) in B.items():
        if parent:
            eb[name].parent = eb[parent]
        eb[name].align_roll(Vector([float(x) for x in zdir]))
    bpy.ops.object.mode_set(mode="OBJECT")
    return rig


SKIN = (232, 180, 142)
HAIR = (38, 30, 27)
ROYAL = (44, 84, 170)        # 服の色は大城さんと同じロイヤルブルー（病棟で統一・2026-11-16 エイイチ）
FRAME = (92, 72, 64)        # めがねの縁（こげ茶）
WHITE = (238, 238, 234)
DARK = (44, 34, 30)
LIP = (150, 72, 66)
MOUTH_IN = (120, 48, 46)

bpy.ops.wm.read_factory_settings(use_empty=True)
FACE_LO, FACE_HI = (-0.08, -0.14, HC[2] - 0.04), (0.08, -0.06, HC[2] + 0.05)
MOUTH_LO, MOUTH_HI = (-0.03, -0.13, HC[2] - 0.095), (0.03, -0.07, HC[2] - 0.05)
# (名前, 形, 範囲, 格子, 色, 粗さ, 肌の透け, 三角形を残す割合, 重みの付け方)
parts = [
    ("Skin", skin, (-0.34, -0.18, 0.58), (0.34, 0.15, 1.67), VOX, SKIN, 0.55, 0.12, 0.07, ("mesh", "skin")),
    ("Hair", hair, (-0.16, -0.17, 1.36), (0.16, 0.18, 1.67), VOX, HAIR, 0.5, 0, 0.06, ("whole", "Head")),
    ("Glasses", glasses, (-0.12, -0.15, HC[2] - 0.05), (0.12, 0.06, HC[2] + 0.03), 0.0007, FRAME, 0.35, 0, 0.12, ("whole", "Head")),
    ("Top", top, (-0.30, -0.15, 0.78), (0.30, 0.15, 1.40), VOX, ROYAL, 0.75, 0, 0.025, ("mesh", "top")),
    ("Sleeves", sleeves, (-0.30, -0.12, 1.08), (0.30, 0.12, 1.40), VOX, ROYAL, 0.75, 0, 0.05, ("sleeves", None)),
    ("Pants", pants, (-0.20, -0.13, 0.05), (0.20, 0.14, 1.0), VOX * 1.4, ROYAL, 0.75, 0, 0.04, ("mesh", "pants")),
    ("Shoes", shoes, (-0.17, -0.17, -0.01), (0.17, 0.10, 0.11), VOX, WHITE, 0.5, 0, 0.05, ("mesh", "shoes")),
    ("Eyes", eyes, FACE_LO, FACE_HI, 0.0008, DARK, 0.35, 0, 0.15, ("side", "Eye_")),
    ("Brows", brows, FACE_LO, FACE_HI, 0.0008, DARK, 0.35, 0, 0.15, ("side", "Brow_")),
]
for k, fn in MOUTHS.items():
    col = MOUTH_IN if k in ("talk", "surprised") else LIP
    parts.append(("Mouth_" + k, fn, MOUTH_LO, MOUTH_HI, 0.0006, col, 0.5, 0, 0.3, ("whole", "Head")))

rig = build_armature()
tris = {}
for name, fn, lo, hi, vox, col, rough, sss, ratio, how in parts:
    v, f = mesh_of(fn, lo, hi, vox)
    ob = to_blender("Terashima_" + name, v, f, col, rough, sss, ratio)
    if how[0] == "mesh":
        weight_mesh(ob, how[1])
    elif how[0] == "sleeves":
        weight_sleeves(ob)
    elif how[0] == "whole":
        weight_whole(ob, how[1])
    else:
        weight_by_side(ob, how[1])
    ob.parent = rig
    mod = ob.modifiers.new("Armature", "ARMATURE")
    mod.object = rig
    if name.startswith("Mouth_") and name != "Mouth_smile":
        ob.hide_render = True                                  # 既定の顔は笑顔。ほかの口は隠しておく
        ob.hide_viewport = True
    tris[ob.name] = sum(len(p.vertices) - 2 for p in ob.data.polygons)
tris["_total_triangles"] = sum(tris.values())
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "terashima_clay.blend"))
for ob in bpy.data.objects:      # FBX には隠した口も入れる（Unity で切り替える）
    ob.hide_viewport = False
bpy.ops.export_scene.fbx(
    filepath=os.path.join(OUT, "nurse_terashima.fbx"), use_selection=False, object_types={"ARMATURE", "MESH"},
    apply_unit_scale=True, apply_scale_options="FBX_SCALE_ALL",
    axis_forward="-Z", axis_up="Y", bake_space_transform=False,
    mesh_smooth_type="FACE", use_mesh_modifiers=False, use_triangles=True,
    add_leaf_bones=False, primary_bone_axis="Y", secondary_bone_axis="X", armature_nodetype="NULL",
    bake_anim=False, path_mode="STRIP", embed_textures=False,
)
import json  # noqa: E402
json.dump({"height_m": 1.65, "triangles": tris, "bones": list(bone_layout())},
          open(os.path.join(OUT, "terashima_report.json"), "w"), ensure_ascii=False, indent=1)
print(json.dumps(tris, ensure_ascii=False))
```

### terashima_render.py

```python
"""粘土の人を描く（大城さんの nurse_render.py を写した）。python3 terashima_render.py <blend> <out_dir> [views...]"""
import math
import os
import sys

import bpy  # noqa: I001
from mathutils import Vector

bpy.ops.wm.open_mainfile(filepath=sys.argv[1])
out = sys.argv[2]
want = sys.argv[3:]
os.makedirs(out, exist_ok=True)
H = 1.65
sc = bpy.context.scene
sc.render.engine = "CYCLES"
sc.cycles.device = "CPU"
sc.cycles.samples = 24
sc.cycles.use_denoising = True
sc.view_settings.view_transform = "Standard"
w = bpy.data.worlds.new("W")
sc.world = w
w.use_nodes = True
bg = w.node_tree.nodes["Background"]
bg.inputs["Color"].default_value = (0.80, 0.90, 0.89, 1)
bg.inputs["Strength"].default_value = 0.65
key = bpy.data.lights.new("K", "AREA")
key.energy = 380
key.size = 3
ko = bpy.data.objects.new("K", key)
ko.location = (-2.2, -2.8, 3.0)
ko.rotation_euler = (Vector((0, 0, 1.0)) - Vector(ko.location)).to_track_quat("-Z", "Y").to_euler()
sc.collection.objects.link(ko)
fill = bpy.data.lights.new("F", "AREA")
fill.energy = 130
fill.size = 4
fo = bpy.data.objects.new("F", fill)
fo.location = (2.8, -2.0, 1.4)
fo.rotation_euler = (Vector((0, 0, 1.0)) - Vector(fo.location)).to_track_quat("-Z", "Y").to_euler()
sc.collection.objects.link(fo)
views = {
    "front": ((0, -6, H / 2), (0, 0, H / 2), H * 1.08, (520, 1000)),
    "side": ((-6, 0, H / 2), (0, 0, H / 2), H * 1.08, (520, 1000)),
    "back": ((0, 6, H / 2), (0, 0, H / 2), H * 1.08, (520, 1000)),
    "persp": ((1.5, -3.2, 1.25), (0, 0, H * 0.52), None, (600, 1000)),
    "face": ((0.32, -1.3, 1.53), (0, 0, 1.49), 0.36, (640, 640)),
    "neck": ((0.55, -0.75, 1.42), (0.03, 0, 1.34), 0.26, (640, 640)),
    "neckback": ((-0.5, 0.9, 1.45), (0, 0, 1.34), 0.30, (640, 640)),
    "upper": ((-0.9, -2.2, 1.45), (0, 0, 1.2), None, (700, 800)),
}
for name, (loc, tgt, ortho, res) in views.items():
    if want and name not in want:
        continue
    cam = bpy.data.cameras.new("C")
    if ortho:
        cam.type = "ORTHO"
        cam.ortho_scale = ortho
    else:
        cam.lens = 55 if name == "persp" else 70
    co = bpy.data.objects.new("C", cam)
    co.location = loc
    co.rotation_euler = (Vector(tgt) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
    sc.collection.objects.link(co)
    sc.camera = co
    sc.render.resolution_x, sc.render.resolution_y = res
    sc.render.filepath = os.path.join(out, f"{name}.png")
    bpy.ops.render.render(write_still=True)
    print("wrote", name)
```

### terashima_pose.py

```python
"""骨の動きを確かめる：決めた姿勢を付けて描く。
python3 terashima_pose.py <nurse_clay.blend> <出力フォルダ> [姿勢の名前...]
姿勢：rest give receive drawer point bow worried talk
（Unity では Humanoid の動き・腕の IK で動かす。ここの姿勢は、骨と重みで服や肌が破れないかの確認用）
"""
import math
import os
import sys

import bpy  # noqa: I001
from mathutils import Matrix, Vector

src, out = sys.argv[1], sys.argv[2]
want = sys.argv[3:]
os.makedirs(out, exist_ok=True)


def setup_scene():
    sc = bpy.context.scene
    sc.render.engine = "CYCLES"
    sc.cycles.device = "CPU"
    sc.cycles.samples = 20
    sc.cycles.use_denoising = True
    sc.view_settings.view_transform = "Standard"
    w = bpy.data.worlds.new("W")
    sc.world = w
    w.use_nodes = True
    bg = w.node_tree.nodes["Background"]
    bg.inputs["Color"].default_value = (0.80, 0.90, 0.89, 1)
    bg.inputs["Strength"].default_value = 0.65
    for nm, en, sz, loc in (("K", 380, 3, (-2.2, -2.8, 3.0)), ("F", 130, 4, (2.8, -2.0, 1.4))):
        L = bpy.data.lights.new(nm, "AREA")
        L.energy, L.size = en, sz
        o = bpy.data.objects.new(nm, L)
        o.location = loc
        o.rotation_euler = (Vector((0, 0, 1.0)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
        sc.collection.objects.link(o)
    return sc


def rot_world(rig, bone, axis, deg, about=None):
    """骨を、ワールドの軸 axis のまわりに deg 度回す（回す中心は骨の根元）"""
    pb = rig.pose.bones[bone]
    h = Vector(about) if about is not None else pb.head.copy()
    R = Matrix.Rotation(math.radians(deg), 4, Vector(axis).normalized())
    pb.matrix = Matrix.Translation(h) @ R @ Matrix.Translation(-h) @ pb.matrix
    bpy.context.view_layer.update()


def twist(rig, bone, deg):
    """骨を自分の向きのまわりにねじる"""
    pb = rig.pose.bones[bone]
    rot_world(rig, bone, pb.tail - pb.head, deg)


def curl(rig, side, deg, fingers=("Index", "Middle", "Ring", "Little"), thumb=None):
    """指を手のひらのほうへ曲げる（骨の z 軸を手のひらに向けてあるので、x 軸まわりに回す）"""
    for f in fingers:
        for seg, k in (("Proximal", 1.0), ("Intermediate", 1.2)):
            pb = rig.pose.bones[side + f + seg]
            pb.rotation_mode = "XYZ"
            pb.rotation_euler.x = math.radians(deg * k)
    if thumb is not None:
        for seg in ("Proximal", "Intermediate"):
            pb = rig.pose.bones[side + "Thumb" + seg]
            pb.rotation_mode = "XYZ"
            pb.rotation_euler.x = math.radians(thumb)
    bpy.context.view_layer.update()


def mouth(kind):
    for ob in bpy.data.objects:
        if ob.name.startswith("Terashima_Mouth_"):
            on = ob.name == "Terashima_Mouth_" + kind
            ob.hide_render = not on
            ob.hide_viewport = not on


def brows(rig, deg, lift=0.0):
    """眉：deg＞0 で眉頭が上がる（困り顔）。lift は上へ（m）"""
    for tag, sgn in (("L", 1), ("R", -1)):
        pb = rig.pose.bones["Brow_" + tag]
        rot_world(rig, "Brow_" + tag, (0, 1, 0), deg * sgn)
        pb.matrix = Matrix.Translation((0, 0, lift)) @ pb.matrix
        bpy.context.view_layer.update()


def reset(rig):
    for pb in rig.pose.bones:
        pb.matrix_basis = Matrix.Identity(4)
    bpy.context.view_layer.update()
    mouth("smile")


X, Y, Z = (1, 0, 0), (0, 1, 0), (0, 0, 1)


def arm_forward(rig, S, up_deg, elbow_deg, palm_up=0.0):
    """腕を前へ上げる（up_deg）。ひじを曲げて前腕をさらに上げる（elbow_deg）。palm_up で手のひらを上へ"""
    rot_world(rig, S + "UpperArm", X, -up_deg)
    rot_world(rig, S + "LowerArm", X, -elbow_deg)
    if palm_up:
        sgn = 1 if S == "Right" else -1
        twist(rig, S + "LowerArm", sgn * palm_up * 0.5)
        twist(rig, S + "Hand", sgn * palm_up * 0.5)


POSES = {}


def pose(fn):
    POSES[fn.__name__] = fn
    return fn


@pose
def rest(rig):
    pass


@pose
def give(rig):      # 片手で物を差し出す
    arm_forward(rig, "Right", 55, 30, palm_up=80)
    curl(rig, "Right", 12, thumb=5)
    rot_world(rig, "Head", X, 8)
    rot_world(rig, "LeftUpperArm", Y, 4)


@pose
def receive(rig):   # 両手で受け取る
    for S in ("Left", "Right"):
        arm_forward(rig, S, 40, 35, palm_up=80)
        curl(rig, S, 15, thumb=5)
    rot_world(rig, "Chest", X, 6)
    rot_world(rig, "Head", X, 10)


@pose
def drawer(rig):    # 前かがみで引き出しの中の物をつかむ
    rot_world(rig, "Spine", X, 12)
    rot_world(rig, "Chest", X, 12)
    for S in ("Left", "Right"):
        arm_forward(rig, S, 35, 10)
        curl(rig, S, 55, thumb=30)
    rot_world(rig, "Head", X, 12)


@pose
def point(rig):     # 指で示す（話しながら）
    arm_forward(rig, "Right", 75, 5)
    rot_world(rig, "RightUpperArm", Z, -18)
    curl(rig, "Right", 85, fingers=("Middle", "Ring", "Little"), thumb=40)
    rot_world(rig, "Head", Z, -12)
    mouth("talk")


@pose
def bow(rig):       # おじぎ
    rot_world(rig, "Spine", X, 18)
    rot_world(rig, "Chest", X, 14)
    rot_world(rig, "Head", X, 6)
    for S, sgn in (("Left", -1), ("Right", 1)):
        rot_world(rig, S + "UpperArm", Y, sgn * -6)
        rot_world(rig, S + "UpperArm", X, -12)


@pose
def worried(rig):   # 困った：首をかしげ、手を口元へ
    rot_world(rig, "Head", Y, 10)
    rot_world(rig, "Head", X, 6)
    arm_forward(rig, "Right", 25, 115)
    rot_world(rig, "RightUpperArm", Z, -8)
    curl(rig, "Right", 30, thumb=10)
    brows(rig, 16, lift=0.002)
    mouth("worried")


@pose
def talk(rig):      # 話しかける：手のひらを見せる
    arm_forward(rig, "Left", 30, 55, palm_up=60)
    curl(rig, "Left", 10, thumb=0)
    rot_world(rig, "Head", Z, 8)
    brows(rig, 0, lift=0.003)
    mouth("talk")


bpy.ops.wm.open_mainfile(filepath=src)
rig = bpy.data.objects["Nurse_Terashima"]
sc = setup_scene()
H = 1.65
views = {"full": ((1.6, -3.0, 1.15), (0, -0.1, 0.95), 50, (520, 820)),
         "close": ((0.75, -1.25, 1.42), (0, -0.15, 1.22), 50, (560, 560))}
for name in (want or list(POSES)):
    reset(rig)
    POSES[name](rig)
    for vname, (loc, tgt, lens, res) in views.items():
        for o in [o for o in bpy.data.objects if o.type == "CAMERA"]:
            bpy.data.objects.remove(o)
        cam = bpy.data.cameras.new("C")
        cam.lens = lens
        co = bpy.data.objects.new("C", cam)
        co.location = loc
        co.rotation_euler = (Vector(tgt) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
        sc.collection.objects.link(co)
        sc.camera = co
        sc.render.resolution_x, sc.render.resolution_y = res
        sc.render.filepath = os.path.join(out, f"pose_{name}_{vname}.png")
        bpy.ops.render.render(write_still=True)
    print("wrote", name)
```



## 作業ログ ― 依頼箱に置いた依頼文

### 依頼230 の依頼文（20261116_230_車いすに道を譲る場面の真上の動画を位置と動きが分かる形に撮り直す.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 120
---
# 依頼230：⑧車いすに道を譲る（依頼229）の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す

依頼229 の依頼文と報告（claude_code_reports/20261116_closeup_229.txt）と、真上の動画 closeup229_yield_top.mp4（KIOXIA の service_sim/unity/closeup/20261116_closeup229/）を見てから始める。台本 closeup229_script.json・Editor/Closeup229.cs（cs:161）を写して Editor/Closeup230.cs を作り、写した先で変える。**229 の台本・コード・出力には触らない。台本（人・車いす・ハコブくんの動き）は 229 のものをそのまま読む。**

## エイイチの指摘（2026-11-16・229 の真上の動画を見て）
真上の動画では、車いすがどの位置にいて、どう動いたのかがさっぱり分からない。

Claude の見立て：
- 真上のカメラがハコブくんのまわり（幅およそ6 m）しか写していない。車いすは 12.5 秒ごろに右の端から入ってくるので、始めの位置（x +0.28）も、寄せる所（10.3〜13.8 秒）もほとんど写っていない
- 床に目印が無いので、写っても x +0.28 と x +0.42 の違い（14 cm）が見分けられない
- 左上の文字が小さく、項目が多い。6.5 秒ごろに「3402823…000 m」という壊れた値が出る

## 1. 変えること（真上の動画だけ）
- **カメラ**：真上から見下ろすのは同じ。動かさない（1本の動画の間ずっと同じ位置・同じ広さ）。写す範囲は、廊下の長い向きが画面の横になる向きで、「車いすが寄せ始める 1 秒前の位置」から「車いすがハコブくんの後ろの端を 1.5 m 過ぎた位置」までが全部入る広さにする。始めから写せる広さに収まるなら、車いすの始めの位置も入れる。廊下の幅（手すりから手すりまで）が画面の高さの 1/4 以上になる広さにする（足りない時は、範囲の端を削るほうを選び、何をどれだけ削ったかを報告に書く）
- **床の目印**（真上の動画だけに出す。本番の動画には出さない）：
  - 廊下の中心の線（細い実線・灰色）
  - 車いすの始めの線 x +0.28 と、寄せたあとの線 x +0.42（それぞれ破線・色を分ける）。線の端に「始め +0.28」「寄せたあと +0.42」と字を置く
  - ハコブくんのふだんの線 x −0.33（破線・ハコブくんの輪の色に近い色）
- **車いすの通った跡**：車いすの後ろの車軸の真ん中が通った所に、太めの線を引いていく（通った所から順に伸びていく。消さない）。寄せ始めと寄せ終わりの所に印（丸）と「寄せ始め 10.3秒」のような字を、その時刻になったら出す
- **ハコブくんの通った跡**：同じ作り方で別の色の線。寄り始めた所と止まった所に印と字
- **左上の文字**：字を大きくして（今の 2 倍以上）、項目を 3 つにする：動画の秒・車いすの横の位置（x の値・cm で）・ハコブくんと車いす・人のすき間。値が無い時は「—」を出す。3402823… のような値が出ないことを確かめる
- 色と線の太さ・字の大きさは、縮めて見ても分かることを優先して決め、決めた値を報告に書く

## 2. 変えないこと
台本の中身（動き・時刻・セリフ・声）、本番の動画 closeup229_yield.mp4、静止画（229 のまま使う）、①〜⑧ の台本・コード・出力。指示していない所は変えない。
**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・最新の check-in が cs:161 以降

## 3. 確かめ（違えば 4 は撮らずに止める）
- 動きが 229 と同じ：車いす・人・ハコブくんの位置を全部のコマで 229 と比べ、差の最大を書く（0 のはず）
- 目印の線の位置：x +0.28・+0.42・−0.33・中心の線が、床の上の正しい位置にあること（線の位置を数字で書く）
- 通った跡の線が、車いすの後ろの車軸の真ん中・ハコブくんの真ん中の位置と、各コマで 1 cm 以内
- 寄せ始め・寄せ終わりの印が出る時刻が、229 の報告の時刻（10.300 秒・13.833 秒）とそろっている
- 動画の最初から最後まで、車いす（とハコブくん）が画面から出ていない時間を書く。寄せ始めの 1 秒前から寄せ終わりまでは、車いすがずっと画面の中にあること
- 左上の値に、壊れた値（とても大きい数・NaN）が 1 コマも無い

## 4. 撮る
- 真上の動画 1 本（closeup230_yield_top.mp4）。長さは 229 と同じ
- 静止画 3 枚：寄せ始め・寄せ終わり・最後のコマ（跡が全部引かれた所）
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup230/、iCloud の hospital/closeup230/ に写す（md5 を確かめる）
- check-in（Mixamo のフォルダは除く）

## 5. 報告
claude_code_reports/20261116_closeup_230.txt（KIOXIA にも写し）。カメラの位置と写す範囲（m）、削った範囲、目印・跡・字の色と太さと大きさ、3 の確かめ（表）、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／止めた」を書く。
```

### 依頼231 の依頼文（20261116_231_車いすが廊下の真ん中で止まる場面を2本作って撮る.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 240
---
# 依頼231：要所の場面⑨「車いすが廊下の真ん中で止まる」（⑩「茂さんに何を運んでいるか聞かれる」を中に入れる）を2本作って撮る

依頼228・229 の依頼文と報告（claude_code_reports/20261116_closeup_228.txt・_229.txt）、依頼203（⑤受け取る人が来ない・早回しと時計の出し方）と 218〜224（⑦話しかけられる・声と口と帯）の依頼文と報告を読んでから始める。廊下・ハコブくん・大城さん・茂さんと車いす・声の作り方は 229 を土台にする。⑨は新しい台本 closeup231_script.json と Editor/Closeup231.cs で作る。**①〜⑧（229・230 を含む）の台本・コード・出力には触らない。**

## エイイチと決めたこと（2026-11-16）
- 大城さんが茂さんの車いすを押していて、知り合いの看護師（寺島さん）と出会い、廊下の真ん中で車いすを止めて立ち話をする。ハコブくんは通れない
- 待っている間に、茂さんがハコブくんに何を運んでいるかを聞く（⑩をここに入れる）。ハコブくんは中身も行き先も言わず「病棟へのお届け物です」とだけ答える（茂さんはカードを持っていない）
- 終わり方は2本：⑨-1 ハコブくんが声をかけて寄せてもらう（立ち往生にならない）／⑨-2 声をかけても気づかれず、30 秒動けずに立ち往生になってから寄せてもらう
- 病院の1日のシミュレーションの立ち往生の決まり（tools/hospital_sim/hospital-unity-params.json の count_rules.stuck_s：30 秒以上動けず、人が動かしに行った）に合わせる

## 0. 新しい人：寺島さん
- Claude が作った寺島さんのモデルを使う：iCloud の サービスロボット導入シミュレーション/hospital/people_3d/terashima/nurse_terashima.fbx（作り方は同じフォルダの README.md）。Assets/ServiceSim/Closeups/Models_terashima/ に写して使う（Models/ には入れない）
- 骨の位置と名前・口の5つの形・目と眉の骨は大城さんと同じ。大城さんを動かすコードをそのまま使う。部品の名前は Nurse_ ではなく Terashima_、根は Nurse_Terashima
- 立って話す、うなずく、笑う、半歩よける、歩くは、大城さんで作った動きを使う。新しい動きは足さない

## 1. 置き方（2本とも同じ）
- 廊下は 229 と同じ。ハコブくんは 229 と同じ向き・速さ（0.8 m/秒）・決まりで進む
- 大城さんは、ハコブくんの進む向きと向かい合わせに、茂さんの車いすを押して来る（229 と同じ速さ）。茂さんは、ハコブくんのほうを向いている
- 寺島さんは、大城さんの後ろから追いつく（大城さんと同じ向きに 1.2 m/秒くらいで歩く）。大城さんの横に並んで「大城さん」と声をかけ、大城さんは車いすを止めて振り返る
- 止まった所：車いすは廊下の真ん中（x 0.00、向き 0°）。寺島さんは大城さんの横、手すり側（−x 側）に、大城さんのほうを向いて立つ。**どちらの横にも、ハコブくんが決まりのすき間を取って通れる幅が残らない**ように置く（置いた位置と、両側に残る幅を報告に書く）。足りなければ、寺島さんの立つ所だけを動かして合わせる
- 大城さんと寺島さんは、車いすのうしろ・横で向かい合って話す（話の中身の声は出さない。口だけ talk を動かし、ときどき笑う smile・うなずく）

## 2. 流れとセリフ（声は 217〜229 と同じ道具。大城さん・寺島さん・ハコブくんの Voice ID は _制作ベース/声の一覧.json の「大城」「寺島」「ハコブ_イケボ」）

| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1 | ハコブくんが廊下を進む。向こうから大城さんが茂さんの車いすを押して来る。寺島さんが後ろから追いつく | 寺島「大城さん」 | 「基本」 |
| 2 | 大城さんが車いすを真ん中で止めて振り返り、2人が話し始める | 大城「あ、寺島さん。おつかれさま」 | 「基本」 |
| 3 | ハコブくんが、通れないことを見つけて減速し、止まる。止まるのは 229 と同じく車いすの前の端（足のせ）と 2.0〜3.0 m あいている所。止まった時から「動けない時間」を数える | ― | 止まったら、帯（ミント）「お待ちしています」。顔は「基本」をふだんの大きさで帯の下に |
| 4 | 止まって 3〜4 秒後、茂さんがハコブくんに気づいて、顔を向け（20〜30°）、聞く | 茂「何を運んでるの？」 | 帯のまま |
| 5 | ハコブくんが答える | ハコブ「病棟へのお届け物です」 | 帯を「お届け中」に替える。**行き先・中身・数は出さない** |
| 6 | 茂さんが小さくうなずく（10°・1回）。顔を2人のほうへ戻す | ― | 帯「お待ちしています」に戻す |

ここから2本に分ける。

**⑨-1 声をかけて寄せてもらう**

| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 7 | 止まって 10 秒たったら、ハコブくんが声をかける | ハコブ「すみません、通ります」 | 帯「通ります」 |
| 8 | 大城さんがハコブくんに気づき、車いすを +x の手すり側へ寄せる（229 の寄せ方と同じ決まり）。寺島さんは −x の手すり側へ半歩（0.5 m）よける（hospital-unity-params.json の standing_yield のよけ方） | 大城「あ、ごめんね」 | 帯のまま |
| 9 | ハコブくんが、空いた間を 0.6 m/秒で通る（すき間は 229 と同じ決まり）。通り過ぎたら 0.8 m/秒 に戻す。寺島さんは元の所へ戻る | ― | 帯を消し、目まで笑う顔（224 と同じ）を 1.5 秒 → 「基本」 |

動けない時間は 30 秒より短いので、立ち往生にならない。

**⑨-2 立ち往生になる**

| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 7 | 止まって 10 秒たったら、ハコブくんが声をかける。2人は話に夢中で気づかない | ハコブ「すみません、通ります」 | 帯「通ります」→ 3 秒で「お待ちしています」へ戻す |
| 8 | 止まって 20 秒で、もう一度声をかける。まだ気づかない | ハコブ「すみません、通ります」 | 同じ |
| 9 | 止まって 30 秒になったら、画面と輪で知らせる。輪の色は⑤の「待っている」色 | ― | 帯（黄）「通れません」。顔は⑤の困り顔 |
| 10 | 茂さんが気づいて、大城さんの腕をとんとんと軽くたたく（右手を上げて 2 回）。大城さんが振り返り、⑨-1 の 8・9 と同じ流れで寄せて通る | 大城「あ、ごめんね」 | ⑨-1 と同じ |

- ⑨-2 の待っている間（声と動きが無い所）は⑤と同じく早回しにする（×3〜×5。どの区間を何倍にしたかを報告に書く）。早回しの間は右上に実際の時計と速さを出す
- 30 秒になった所で、画面の左下に「立ち往生 1件（30 秒以上動けず、人が動かした）」の字を 3 秒出す（動画の上に出す字。ハコブくんの画面ではない）。⑨-1 には出さない
- 茂さんが大城さんの腕をたたく動きは、ここだけの新しい動き。茂さんは座ったまま、右手を上げて前の大城さんの腕へ届く所までにする。届かなければ、大城さんのほうへ顔を向けて「大城さん」と言う形に替え（セリフ：茂「大城さん」）、替えたことを報告に書く

## 3. 声
- 茂さんの声はまだ無い。ElevenLabs の声から、年配の男性の日本語の声を 3 つ選んで、茂さんのセリフ（「何を運んでるの？」）を作り、名前と Voice ID を報告に並べる。動画には 1 つ目を使う。声の一覧.json には足さない
- セリフの間（前の声が終わってから次の声まで）は 0.4〜0.7 秒。2人の立ち話の口の動きの間は声を出さない
- 声の大きさは 217〜229 と同じ（−20 LUFS）

## 4. カメラ（2本とも）
- 本番：229 の本番のカメラ。ハコブくんの後ろから、止まった車いすの3人が見える向き
- 寄り：ハコブくんの画面（「お待ちしています」「お届け中」「通ります」「通れません」が出た所）、茂さんが聞く所の茂さんの顔、大城さんが気づく所の大城さんの顔
- 真上：1本ずつ。230 の真上の動画の作り（写す範囲・床の目印・通った跡・左上の字）があればそれを使う。230 が終わっていなければ、229 の真上のカメラのまま撮り、230 の作りに合わせていないことを報告に書く

## 5. 確かめ・止める決まり
229 の「必ず守る」「できるだけ守る」と同じ（当たったコマ 0・手が握りから離れない・車輪が横にすべらない・1 コマで骨が動く量 6 cm 以内 など）。加えて：
- 止まった時、車いすと寺島さんの両横に残る幅が、ハコブくんが決まりのすき間で通れる幅より狭いこと（数字で書く）
- 動けない時間：⑨-1 は 30 秒未満、⑨-2 は 30 秒以上（それぞれ何秒かを書く）。⑨-2 で「立ち往生」の字が出た時刻と、動けない時間が 30 秒になった時刻が 0.1 秒以内でそろう
- ハコブくんの画面に、行き先・中身・数が一度も出ていない
- 寺島さんが半歩よけて戻る時刻・距離が standing_yield の決まりに合っている

## 6. 撮る
- 動画：closeup231_stop_voice.mp4（⑨-1）・closeup231_stop_stuck.mp4（⑨-2）・それぞれの真上の動画。声あり
- 静止画：寺島さんが声をかける所・車いすが止まって3人で話す所・ハコブくんが止まった所（本番と寄り）・茂さんが聞く所（寄り）・「お届け中」（寄り）・「通ります」（寄り）・⑨-2 の「通れません」と「立ち往生 1件」の所・大城さんが寄せる所（本番と真上）・ハコブくんが通る所
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup231/、iCloud の hospital/closeup231/ に動画と静止画を写す（md5 を確かめる）。声の mp3 は KIOXIA の出力の audio/ に置く
- 作業の区切りで check-in（Mixamo のフォルダは除く）

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。** おじぎ・吹き出し・手を振るなどは入れない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・最新の check-in が cs:161 以降・寺島さんの FBX が iCloud にある

## 7. 報告
claude_code_reports/20261116_closeup_231.txt（KIOXIA にも写し）。寺島さんの読み込み方（大城さんの動きがそのまま使えたか）、置いた位置と両側に残る幅、2本それぞれのセリフごとの時刻の表（動画の秒・実際の秒・声の長さ）、早回しの区間、動けない時間、カメラの切りかえの表、茂さんの声の候補 3 つ、確かめの表（必ず守る・できるだけ守る）、動画の長さ、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／一部外れて撮った／止めた」を書く。
```

### 依頼232 の依頼文（20261116_232_真上の動画の床の線を人とハコブくんの下に描く.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 90
---
# 依頼232：真上の動画の床の線（点線と中心の線）を、ハコブくん・人・車いすの下に描く（⑧の依頼230 と ⑨の依頼231 の真上の動画）

依頼230 の依頼文と報告（claude_code_reports/20261116_closeup_230.txt）と、230 の真上の動画 closeup230_yield_top.mp4 を見てから始める。依頼231 の報告（claude_code_reports/20261116_closeup_231.txt）も読む。

## エイイチの指摘（2026-11-16・230 の真上の動画を見て）
点線は、ハコブくんや看護師、車いすの下に表示したほうがいい。

## 1. 変えること
- 床の目印の線（廊下の中心の線・始め +0.28・寄せたあと +0.42・ハコブくんのふだん −0.33 の点線）と、線の端の字（「始め +0.28」など）を、床の上に描く。ハコブくん・大城さん・茂さん・車いす（231 では寺島さんも）が線の上を通る時は、体のほうが前に見え、線は体に隠れる
- 床の上に描く方法（床に貼る・カメラの描く順を変える など）は任せる。どの方法にしたかを報告に書く
- 通った跡の線・寄り始め／寄せ始めなどの印と字・左上の字は、230 のまま（体の上に重ねて描く）

## 2. 撮り直すもの
- ⑧：Editor/Closeup230.cs を写して Closeup232.cs を作り、写した先で変える。closeup232_yield_top.mp4 を撮る
- ⑨：依頼231 が終わっていて、真上の動画を 230 の作りで撮っていれば、231 の2本の真上の動画も同じ直しで撮り直す（closeup232_stop_voice_top.mp4・closeup232_stop_stuck_top.mp4）。231 のコードは写した先で変える。231 が止めた・230 の作りを使わなかった場合は、⑨は撮らずに報告に書く
- 本番の動画・静止画・台本は撮り直さない

## 3. 変えないこと
動き・時刻・カメラの位置と写す範囲・線の位置と色と太さ・字の大きさ・跡と印の描き方。230・231 の台本・コード・出力には触らない。
**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み

## 4. 確かめ（違えば撮らずに止める）
- 線が体の下になっている：線が体に重なるコマを 3 つ以上選び、その寄りの静止画で、体の所に線が見えていないこと
- 動き・線の位置・跡・印・左上の字の値が、230（231）と同じ（全部のコマで差の最大を書く）

## 5. 出力と報告
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup232/、iCloud の hospital/closeup232/ に動画と、確かめの寄りの静止画を写す（md5 を確かめる）
- 作業の区切りで check-in（Mixamo のフォルダは除く）
- 報告：claude_code_reports/20261116_closeup_232.txt（KIOXIA にも写し）。描き方、確かめの表、撮った動画、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／止めた」を書く
```

### 依頼233 の依頼文（20261116_233_車いすが廊下の真ん中で止まる場面を立ち位置と声を直して2本作る.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 240
---
# 依頼233：⑨車いすが廊下の真ん中で止まる（⑩を中に入れる）を、立ち位置・速さ・声を直して2本作って撮る（依頼231 の作り直し）

依頼231 の依頼文と報告（claude_code_reports/20261116_closeup_231.txt）を読んでから始める。231 で作った寺島さんの読み込み（Models_terashima/・NurseTerashima.prefab・Editor/Closeup231Terashima.cs）・置き方の計算（KIOXIA の closeup/20261116_closeup231/geo/・tools/）・声（audio/）は使ってよい。231 の依頼文の流れ・セリフ・カメラ・確かめ・撮るもの・報告は、**下の「231 から変えること」のほかは 231 のとおり**にする。⑨は新しい台本 closeup233_script.json と Editor/Closeup233.cs で作る（231 のコードは写した先で変える）。①〜⑧・230・232 の台本・コード・出力には触らない。

## 231 の「決めてほしいこと」への答え（2026-11-16 エイイチ・Claude）

1. **寺島さんの立つ側を反対にする**（231 の依頼文の誤り）
   - 寺島さんは、大城さんの横の **+x 側（ハコブくんが通らない側の手すり寄り）** に、大城さんのほうを向いて立って話す。車いすは 231 のとおり廊下の真ん中（x 0.00）なので、通れないのは変わらない（両横に残る幅を報告に書く）
   - 道を空ける時：大城さんが車いすを +x の手すり側へ寄せる（229 の寄せ方と同じ決まり）。寺島さんは、大城さんが寄る所をふさがないよう、**大城さんの後ろ（ハコブくんから遠い側）へ下がって、+x の手すり沿いに立つ**（歩いて下がる。下がる距離は大城さんと当たらない一番短い距離・1.0 m まで）。ハコブくんが通り過ぎたら、話していた所へ戻る（戻らなくてもよい。どちらにしたかを書く）
   - ハコブくんは、ふだんの通り道（x −0.33）のまま、229 のすき間の決まりで通る。通れる形があるかを先に計算してから作り、無ければ何がどれだけ足りないかを書いて止める
2. **茂さんの声**：新しく作らない。今までの声を使う。**田中先生の声（Voice ID `ydyMD3g4SbEeNpF0wahP`、_制作ベース/声の一覧.json の「田中」）** を茂さんの声にする（video_rules.md の決まり：森田茂さん＝田中先生の声。⑨に田中先生は出ない）。声の一覧を読む必要はない（Voice ID で直接作る）
3. **ハコブくんの速さ**：229 と同じ決まり（0.6 m/秒）。231 の依頼文の 0.8 m/秒は誤り
4. **ハコブくんの声**：⑤〜⑧と同じ **`gWJpc8whMBqnF7Y0kc9f`**。231 で「ハコブ_イケボ」で作った2つは使わず、作り直す
5. **⑨-2 の気づき方を替える**：茂さんは大城さんの前にいるので、腕はたたかない。代わりに、**寺島さんがハコブくんの画面の「通れません」に気づいて、大城さんに知らせる**
   - 30 秒になって画面が「通れません」に変わってから 1.0〜1.5 秒後に、寺島さんがハコブくんのほうへ顔を向け（20〜35°）、大城さんへ顔を戻して言う：寺島「あ、ハコブくん」（声は「寺島」 `yWM6Fym2UxDGZqWRoGLB`）
   - 大城さんが振り返り「あ、ごめんね」→ 1 の道の空け方
   - 茂さんの新しい動き（手を上げる）は作らない

## そのほか（231 のまま）
- ⑩：止まって 3〜4 秒後に茂さんが顔を向けて「何を運んでるの？」→ ハコブ「病棟へのお届け物です」→ 茂さんが小さくうなずく。画面に行き先・中身・数を出さない
- ⑨-1：10 秒で「すみません、通ります」→ 大城「あ、ごめんね」→ 道を空けて通る（立ち往生にならない）
- ⑨-2：10 秒・20 秒で声をかけても気づかない → 30 秒で画面「通れません」・輪を⑤の待つ色・動画の左下に「立ち往生 1件（30 秒以上動けず、人が動かした）」を 3 秒 → 上の 5
- 真上の動画は、232 が終わっていれば 232 の描き方（床の線は体の下）、終わっていなければ 230 の描き方で撮り、どちらにしたかを書く

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。**
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・最新の check-in が cs:163 以降

## 出力と報告
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup233/、iCloud の hospital/closeup233/（md5 を確かめる）。動画の名前は closeup233_stop_voice.mp4・closeup233_stop_stuck.mp4 と、それぞれの _top.mp4
- 報告：claude_code_reports/20261116_closeup_233.txt（KIOXIA にも写し）。231 の依頼文の 7 の項目に加えて、寺島さんが下がった距離と時刻・大城さんとのすき間の最小、使った Voice ID の表。最後に「判定：合格／一部外れて撮った／止めた」を書く
```

### 依頼234 の依頼文（20261116_234_真上の動画で車いすや人のすき間から点線が見えるのを消す.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 60
---
# 依頼234：⑧の真上の動画（依頼232）で、車いすや人のすき間から点線がちらちら見えるのを消す

依頼232 の依頼文と報告（claude_code_reports/20261116_closeup_232.txt）と、道具 make232.py・Editor/Closeup232.cs を読んでから始める。

## エイイチの指摘（2026-11-16・232 の動画を見て）
まだ点線がちらちら見える。

Claude の見立て：232 の報告の「決めてほしいこと 1」のとおり、車いすの枠・車輪・足のせのすき間や、人の脚のあいだから床が見えるので、そこで点線が見える。車いすが動くとすき間の形が変わるので、ちらちらする。

## 232 の「決めてほしいこと」への答え
1. **すき間からも線を見せない。** 体を白く写した型を、もの（ハコブくん・車いすと茂さん・大城さん）ごとに、**中の穴を埋めた外形**にしてから線を消す。穴を埋めるやり方（穴埋め・数画素の閉じる処理・もの全体を囲む形 など）は任せるが、外形が実際の体より外へ大きくふくらまないこと（ふくらんだ量の最大を画素と cm で書く）
2. **床の線（中心の線・点線・線の端の字）は、通った跡の線の下にも描く。** 重ねる順は下から：床 → 床の線 → 体 → 通った跡 → 印と印の字 → 左上の字

## 変えないこと
動き・カメラ・線の位置と色と太さ・跡と印の描き方・字。232 の道具・コード・出力には触らない（make232.py を写して make234.py、Closeup232.cs を写して Closeup234.cs にし、写した先で変える）。
**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み

## 確かめ（違えば撮らずに止める）
- 全部のコマで、ものの外形の中に床の線の画素が 0
- 232 で外形の中のすき間に線が見えていたコマの数（232 の値）と、234 の値（0 のはず）
- 外形のふくらみの最大（画素・cm）
- 体の無い所は、線と跡の重ねる順のほかは 232 と同じ（違う画素の数を書き、どれも重ねる順の所だけであること）

## 出力と報告
- closeup234_yield_top.mp4 と、232 と同じ時刻の寄りの静止画 4 枚（232 と 234 を並べたもの）
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup234/、iCloud の hospital/closeup234/（md5 を確かめる）
- 依頼233（⑨）の真上の動画がこの時点でできていれば、同じ直しで撮り直す（closeup234_stop_voice_top.mp4・closeup234_stop_stuck_top.mp4）。できていなければ撮らずに書く
- 作業の区切りで check-in（Mixamo のフォルダは除く）
- 報告：claude_code_reports/20261116_closeup_234.txt（KIOXIA にも写し）。穴の埋め方、確かめの表、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／止めた」を書く
```

### 依頼235 の依頼文（20261116_235_車いすが廊下の真ん中で止まる場面をその場で寄せる形で2本作る.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 240
---
# 依頼235：⑨車いすが廊下の真ん中で止まる（⑩入り）を、その場で向きを変えて寄せる形で2本作って撮る（依頼233 の続き）

依頼231・233 の依頼文と報告（claude_code_reports/20261116_closeup_231.txt・_233.txt）、KIOXIA の closeup/20261116_closeup233/（feas233.txt・geo233_top.png・audio/）、依頼234 の報告を読んでから始める。**流れ・セリフ・声・画面・カメラ・確かめ・撮るもの・報告は、下に書いた所のほかは 233 の依頼文（とそこから読む 231 の依頼文）のとおり。** 声は 233 で作ったもの（audio/）をそのまま使う。⑨は新しい台本 closeup235_script.json と Editor/Closeup235.cs で作る。①〜⑧・230〜234 の台本・コード・出力には触らない。

## 233 の「決めてほしいこと」への答え（2026-11-16 エイイチ）

### 1. 寄せ方：その場で向きを変えて寄せる
- 止まっている車いすを寄せる時は、⑧（229）の「向き 8° まで」の決まりを使わない。代わりに次の決まりにする
  - 大城さんが両手で握り直してから、車いすの向きを +x 側へ最大 30° まで変え、前へ（または少し後ろへ）動かしながら x +0.42 へ寄せ、最後に向きを 0° に戻す
  - 前へ進んでよいのは、足のせの前の端とハコブくんの前の端のあいだが 0.6 m 以上残る所まで。後ろへ下がるのは 1.0 m まで
  - 速さは 0.3 m/秒まで、向きの変わる速さは 25°/秒まで。後ろの車輪は横へすべらない（車軸の向きにだけ進む・その場で回る時は左右の車輪が逆に回る）。前の車輪は進む向きの後ろへ付いていく
  - 作る前に、この決まりで寄せられる道があるかを計算する。無ければ何がどれだけ足りないかを書いて止める
- 寺島さんは 233 の依頼文のとおり +x 側に立ち、寄せる時は大城さんが寄る所をふさがないよう、大城さんの後ろ（ハコブくんから遠い側）へ下がって +x の手すり沿いに立つ（1.0 m まで）。下がらなくてよい形なら下がらない

### 2. 大城さんの立ち話の向き：握りから手をはなして体ごと向く
- 車いすを止めて振り返る所で、大城さんは**寺島さんから遠い側の手を握りからはなし、体（腰から上と足の向き）ごと寺島さんのほうへ回す**。寺島さんに近い側の手は握りにのせたまま。顔は体の向きから 30° 以内で寺島さんを見る
- 寄せる前に、体を車いすのほうへ戻して両手で握り直す
- 足は踏み替えて向きを変える（足が床をすべらない。228 と同じ基準）。手の届かない形になる時は、寺島さんの立つ位置を前後に 0.3 m まで動かして合わせる

### 3. ハコブくんの通る位置：229 の決まりどおりでよい
止まる時に寄った所（x −0.4643）から、そのまま通る。通り過ぎてから、ふだんの位置（x −0.33）へ戻る。

## 真上の動画
- 234 の描き方（ものごとに穴を埋めた外形の中に床の線を描かない・床の線は通った跡の下）で撮る
- **加えて、大城さんと車いす（茂さんを含む）は、大城さんが握りに手をのせている間は 1 つのものとして穴を埋める**（234 の報告の「決めてほしいこと 1」の答え）。寺島さんとハコブくんは別のもの。閉じる処理の半径は 234 の 6 画素のまま

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。**
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・最新の check-in が cs:165 以降（違う番号ならその番号を書いて続ける）

## 確かめに足すこと
- 寄せる道：向きの最大・速さの最大・前へ進んだ距離・後ろへ下がった距離・足のせとハコブくんのあいだの最小・車輪の横すべり
- 大城さんの体の向き・顔の向き（体から）の最大、握りから手をはなしていた時刻、握り直した時刻、足のすべり
- ハコブくんが通る時の、車いす・大城さん・寺島さんとのすき間の最小（0.15 m 以上）

## 出力と報告
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup235/、iCloud の hospital/closeup235/（md5 を確かめる）。動画は closeup235_stop_voice.mp4・closeup235_stop_stuck.mp4 と、それぞれの _top.mp4
- 報告：claude_code_reports/20261116_closeup_235.txt（KIOXIA にも写し）。233 の依頼文の報告の項目に、上の確かめを足す。最後に「判定：合格／一部外れて撮った／止めた」を書く
```

### 依頼236 の依頼文（20261116_236_真上の動画で大城さんと車いすのあいだから点線が見えるのを消す.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 60
---
# 依頼236：⑧の真上の動画（依頼234）で、大城さんと車いすのあいだから点線が見えるのを消す

依頼234 の依頼文と報告（claude_code_reports/20261116_closeup_234.txt）と、道具 make234.py・Editor/Closeup234.cs を読んでから始める。

## 234 の「決めてほしいこと」への答え（2026-11-16）
1. **大城さんと車いす（茂さんを含む）は、大城さんが握りに手をのせている間は 1 つのものとして穴を埋める。** ハコブくんは別のもの。大城さんの胴・腕と押し手で囲まれた床から、線が見えないようにする
2. 閉じる処理の半径は 6 画素（3.2 cm）でよい

## 変えないこと
234 の描き方のほかの所すべて（動き・カメラ・線・跡・印・字・重ねる順）。234 の道具・コード・出力には触らない（写して make236.py・Closeup236.cs にし、写した先で変える）。
**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み

## 確かめ（違えば撮らずに止める）
- 全部のコマで、大城さんと車いすをまとめた外形の中に床の線の画素が 0（234 の値 400／770 コマ・最大 644 画素と並べる）
- 外形のふくらみの最大（画素・cm）。大城さんと押し手のあいだを埋めたほかに、体の外へふくらんでいないこと
- 体の無い所は 234 と同じ（違う画素 0）

## 出力と報告
- closeup236_yield_top.mp4 と、234 と同じ時刻の寄りの静止画 4 枚（234 と 236 を並べたもの）
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup236/、iCloud の hospital/closeup236/（md5 を確かめる）
- 作業の区切りで check-in（Mixamo のフォルダは除く）
- 報告：claude_code_reports/20261116_closeup_236.txt（KIOXIA にも写し）。埋め方、確かめの表、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／止めた」を書く
```

### 依頼237 の依頼文（20261117_237_車いすが止まる場面のやり取りを2本で分けて作り直す.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 240
---
# 依頼237：⑨車いすが廊下の真ん中で止まる（依頼235）の、茂さんとハコブくんのやり取りを2本で分けて作り直し、「通れません」の顔を大きくし、横を通る時のお礼を足して撮る

依頼235 の依頼文と報告（claude_code_reports/20261116_closeup_235.txt）と、235 の台本 closeup235_script.json・make_script235.py・Editor/Closeup235.cs・2本の動画を見てから始める。写して closeup237_script.json・make_script237.py・Editor/Closeup237.cs を作り、写した先で変える。**235 の台本・コード・出力には触らない。** 下に書いた所のほかは 235 のとおり（寄せ方・立ち話・寺島さんの動き・ハコブくんの止まり方と通り方・早回し・「立ち往生 1件」の字・カメラ・真上の動画の描き方）。

## エイイチの指摘（2026-11-17・235 の動画を見て）
1. 「通れません」の時のハコブくんの顔が小さい
2. 茂さんがハコブくんに声をかけるのが不自然（止まって 3〜4 秒で、きっかけ無く話しかけていた）。2本とも同じセリフなのも芸がない
3. ハコブくんが車いすの横を通る時に、声をかけるか、にこっと笑うくらいはあった方がいい

## 1. 「通れません」の顔
帯（黄）「通れません」の下の顔を、ほかの帯（「お待ちしています」など）と同じ、ふだんの大きさにする（223 で直した大きさ）。顔の形は 235 の困り顔のまま。

## 2. 235 の⑩（止まって 3〜4 秒で茂さんが「何を運んでるの？」）は2本とも消す。代わりに次のとおり

### ⑨-1 声をかけて通る
| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1〜3 | 235 のとおり（寺島さんが声をかける・立ち話・ハコブくんが止まる） | 235 のとおり | 「お待ちしています」 |
| 4 | 止まって 10 秒でハコブくんが声をかける | ハコブ「すみません、通ります」 | 帯「通ります」 |
| 5 | 茂さんが先に気づき、後ろの大城さんのほうへ顔を向けて（30〜45°）言う | 茂「おい、ロボットさんが通るって」 | 帯のまま |
| 6 | 大城さんが振り返り、235 のとおり握り直して寄せる | 大城「あ、ごめんね」 | 帯のまま |
| 7 | ハコブくんが走り出し、車いすに近づいた所で、茂さんがハコブくんのほうへ顔を向けて聞く | 茂「何を運んでるんだい？」 | 「基本」 |
| 8 | ハコブくんは止まらずに答える。答えの「ありがとうございます」と合わせて、目まで笑う顔（224 と同じ）を 1.5 秒 | ハコブ「病棟へのお届け物です。ありがとうございます」 | 帯（ミント）「お届け中」→ 目まで笑う顔 → 「基本」。**行き先・中身・数は出さない** |
| 9 | 茂さんは小さくうなずき（10°・1回）、顔を前に戻す | ― | 「基本」 |

- 7・8 は、ハコブくんが車いすの横を通っている間に声が終わるように時刻を決める。足りなければ、7 の茂さんの声を走り出しの直前に始めてよい（いつにしたかを書く）
- 動けない時間は 30 秒未満のまま

### ⑨-2 立ち往生になる
| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1〜3 | 235 のとおり | 235 のとおり | 「お待ちしています」 |
| 4 | 止まって 10 秒・20 秒で声をかける。看護師 2 人は気づかない | ハコブ「すみません、通ります」（2回） | 235 のとおり |
| 5 | 20 秒の声のあと（声が終わってから 2〜4 秒）、茂さんがハコブくんのほうへ顔を向けて（20〜30°）言う | 茂「あんたも待たされてるのかい」 | 帯のまま |
| 6 | ハコブくんが答える。茂さんは顔を 2 人のほうへ戻す | ハコブ「はい、お待ちしています」 | 帯「お待ちしています」 |
| 7 | 30 秒で「通れません」（顔はふだんの大きさ）→ 235 のとおり 寺島「あ、ハコブくん」→ 大城「あ、ごめんね」→ 寄せる | 235 のとおり | 235 のとおり |
| 8 | ハコブくんが車いすの横を通る時に言う。目まで笑う顔を 1.5 秒。茂さんは小さくうなずく（10°・1回） | ハコブ「ありがとうございます」 | 目まで笑う顔 → 「基本」 |

- 5・6 は早回しの区間に入れない（1倍で見せる）。早回しは 6 のあとから 30 秒の手前まで
- 動けない時間は 30 秒以上のまま

## 3. 声（233 と同じ作り・−20 LUFS）
| 誰 | セリフ | Voice ID |
|---|---|---|
| 茂さん | おい、ロボットさんが通るって／何を運んでるんだい？／あんたも待たされてるのかい | ydyMD3g4SbEeNpF0wahP（田中先生の声） |
| ハコブくん | 病棟へのお届け物です。ありがとうございます／はい、お待ちしています／ありがとうございます | gWJpc8whMBqnF7Y0kc9f |

ほかのセリフは 233 の声をそのまま使う。233 の「何を運んでるの？」「病棟へのお届け物です」は使わない。

## 4. 235 の「決めてほしいこと」への答え
1. ハコブくんが走り出す決まり（前の物が 0.5 秒動かず、寄った位置で 0.15 m 以上あけて通れたら走り出す）：このままでよい
2. 寄せる道の計算の余り（手すり 0.05 m・寺島さん 0.05 m）：このままでよい
3. 「大城さん」→「あ、寺島さん…」の間 2.10 秒：このままでよい（大城さんが止まって振り返る間）
4. 寺島さんがハコブくんの通過後も手すり沿いに立ったまま：このままでよい

## 確かめに足すこと
- 「通れません」の顔の大きさが、ほかの帯の時の顔と同じ（画素で比べる）
- セリフごとの時刻の表（2本）。⑨-1 の 7・8 の声が、ハコブくんが車いすの横にいる間（ハコブくんの前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）のどこからどこまでか
- 茂さんの顔の向きの最大・うなずきの角度
- 画面に行き先・中身・数が一度も出ていない

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。**
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・最新の check-in が cs:167 以降（違う番号ならその番号を書いて続ける）

## 出力と報告
- 出力は KIOXIA の service_sim/unity/closeup/20261117_closeup237/、iCloud の hospital/closeup237/（md5 を確かめる）。動画は closeup237_stop_voice.mp4・closeup237_stop_stuck.mp4 と、それぞれの _top.mp4。静止画は 235 と同じ並びに、「通れません」（寄り）・⑨-1 の 5・7・8・⑨-2 の 5・8 を足す
- 報告：claude_code_reports/20261117_closeup_237.txt（KIOXIA にも写し）。235 と同じ項目に、上の確かめを足す。最後に「判定：合格／一部外れて撮った／止めた」を書く
```

### 依頼238 の依頼文（20261117_238_声をかけて通る版の茂さんのセリフと声をかける時刻を直す.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 180
---
# 依頼238：⑨-1 声をかけて通る（依頼237）の、茂さんのセリフを替え、声をかける時刻を早めて撮り直す

依頼237 の依頼文と報告（claude_code_reports/20261117_closeup_237.txt）と、237 の台本 closeup237_script.json・make_script237.py・Editor/Closeup237.cs を読んでから始める。写して closeup238_script.json・make_script238.py・Editor/Closeup238.cs を作り、写した先で変える。**237 の台本・コード・出力には触らない。** 撮り直すのは ⑨-1 だけ（⑨-2 は 237 のまま使う）。

## エイイチの指摘と決めたこと（2026-11-17・237 の動画を見て）
1. **茂さんの「おい、ロボットさんが通るって」は言い方が強すぎる。** セリフを **茂「大城さん、ロボットさんが通るって」** に替える（声は 233 と同じ作り・Voice ID `ydyMD3g4SbEeNpF0wahP`・−20 LUFS）。顔を向ける向きと角度は 237 のまま
2. **ハコブくんが「すみません、通ります」と声をかけるのを、止まって 10 秒 → 5 秒にする。** 237 では動けない時間が 29.833 秒で、30 秒の立ち往生とほとんど差が無かったため。そのあとの流れ（茂さん → 大城さん → 握り直して寄せる → 通る → 茂さんの問い → お礼）は 237 のまま、時刻だけ前へずらす
3. 237 の「決めてほしいこと」1〜4 は、このままでよい（茂さんが向く側・お礼の時だけ画面の寄り・目まで笑う顔はお礼の時だけ・⑨-2 の早回し）

## 変えないこと
上の 1・2 のほかすべて（寄せ方・立ち話・寺島さんの動き・ハコブくんの止まり方と通り方・画面・カメラの切りかえの考え方・真上の動画の描き方）。
**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**指示していない動作は足さない。**
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・最新の check-in が cs:168 以降（違う番号ならその番号を書いて続ける）

## 確かめ
- 237 と同じ確かめ（当たったコマ 0・寄せる道・すき間・手と握り・画面に行き先・中身・数が出ない など）
- 動けない時間（237 の 29.833 秒と並べる）
- セリフごとの時刻の表（237 と並べる）。「何を運んでるんだい？」と答えが、ハコブくんが車いすの横にいる間に入っているか（237 と同じ書き方）

## 出力と報告
- 出力は KIOXIA の service_sim/unity/closeup/20261117_closeup238/、iCloud の hospital/closeup238/（md5 を確かめる）。動画は closeup238_stop_voice.mp4 と closeup238_stop_voice_top.mp4。静止画は 237 の ⑨-1 と同じ並び
- 報告：claude_code_reports/20261117_closeup_238.txt（KIOXIA にも写し）。237 と同じ項目に、上の確かめを足す。最後に「判定：合格／一部外れて撮った／止めた」を書く
```



## 作業ログ ― Claude Code の報告

KIOXIA の `service_sim/unity/closeup/{日付}_closeup{番号}/report{番号}.txt` の全文です。

### 依頼230 の報告（report230.txt）

```text
依頼230：⑧ 車いすに道を譲る（依頼229）の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直した（2026-11-16）

依頼229 の報告と、真上の動画 closeup229_yield_top.mp4 を見てから始めた（指摘のとおり、カメラはハコブくんの上の幅およそ 6.5 m だけで、6.5 秒ごろに「手すりと 3402822…000 m」と出ていた。手すりが近くに無いコマで、測っていない値〔float の一番大きい数〕をそのまま字にしていたため）。
コードは Closeup229.cs を写して Editor/Closeup230.cs にし、写した先で変えた。台本は 229 の closeup229_script.json をそのまま読む（写していない・変えていない）。
新しいカメラの値は台本に入れず、新しいファイル closeup230_top.json に置いた。
触ったのは Assets/ServiceSim/Closeups/ の中の新しい 4 ファイルだけ。229 の台本・コード・出力、本番の動画 closeup229_yield.mp4、229 の静止画、①〜⑧ の台本・コード・出力、Models/、病院の1日の場面、配膳の場面、共通の部品、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。場面のファイルは保存していない。

結論：3 の確かめはすべて合った。動きは 229 と全部のコマで同じ（差 0）。寄せ始めの 1 秒前から寄せ終わりまで、車いすはずっと全部が画面の中にある。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:161 で変更なし）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 最新の check-in：cs:161（依頼229）

■ 作り方
- Unity（Closeup230.cs）：229 と同じ台本・同じ計算で全部のコマを回し、真上のコマだけを新しいカメラで撮る（本番のカメラのコマ・静止画は撮らない）。
  コマごとに、車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中＝車いすの根の後ろ 0.15 m）とハコブくんの根の、床の位置と画面の位置（Unity のカメラで写した値）を top230.csv に出す。
  あわせて、車いす（頂点 12,173 個）・ハコブくん（外形の四隅）・大城さん（骨）が画面の中かを数える
- 重ねる（make230.py）：目印の線・通った跡・印・字は、Unity が出した画面の位置に、2 倍の大きさで描いて縮めて重ねる（真上の動画だけ。本番の動画には出ない）。
  目印と跡は、人や車いすの上に重ねて描いている（床に描いて人の下に隠れる形ではない）

■ カメラ（1 本の動画の間ずっと同じ。動かない）
- 真上から真下を向く。画面の上が −x（ハコブくんの側の手すり）・右が +z（車いすが来る側）。229 と同じ向き
- 正射影（遠近の無い写し方）にした。229 は遠近のあるカメラ（高さ 7.6 m・画角 27°）だった。遠近があると、高さのある物（ハコブくん 1.15 m・人）が画面の端ほど床の目印からずれて見えるので、床の線と位置を正しく重ねるために変えた（決めてほしいことの 1）
- 位置：廊下の原点から x −0.500・高さ 10.0 m・z 7.825（廊下の中心より 0.5 m ハコブくんの側に寄せて、廊下を画面の少し下に置き、上に字の場所をとった）
- 写す範囲：z 2.700〜12.950（横 10.250 m）・x −3.383〜+2.383（縦 5.766 m）。1 m ＝ 187.3 px（1 px ＝ 5.3 mm）
- 入れると決まっている範囲：
  ・寄せ始めの 1 秒前（動画 9.300 秒）の車いす：根 z 11.826・後ろの端 z 12.256・前の端 z 11.186（大城さんの根 z 12.420）
  ・車いすがハコブくんの後ろの端を 1.5 m 過ぎた所：ハコブくんの後ろの端 z 5.529（止まった位置 z 5.909 − 0.380）→ 車いすの後ろの端 z 4.029・その時の前の端 z 2.959
  → z 2.959〜12.256 が要る範囲。その外に 0.26 m／0.69 m（大城さんの体も入る）の余りをとって z 2.70〜12.95 にした
- 廊下の幅（手すりの内側の面から内側の面まで 1.68 m）：画面の高さの 29.1%（314.7 px／1080 px）。1/4 以上
- 削った範囲：無し
- 車いすの始めの位置（動画 0 秒・根 z 19.506）は入れていない。入れると横 17 m 近くが要り、廊下の幅が画面の高さの約 17% になって 1/4 に足りないため（「収まるなら入れる」に当たらない）。車いすは x +0.28 のまま来て、動画 7.1 秒から画面の右の端に入る

■ 目印・跡・字（1920×1080 の画面での値。2 倍で描いて縮めた）
| もの | 形 | 色 | 太さ・大きさ |
| 廊下の中心の線 x 0 | 細い実線 | 灰色 (120,120,120) | 3 px |
| 車いすの始めの線 x +0.28 | 破線（28 px 引いて 16 px あける） | 青 (21,101,192) | 5 px。字「始め +0.28」は左の端・線の上 |
| 寄せたあとの線 x +0.42 | 破線（同じ） | 紫 (142,36,170) | 5 px。字「寄せたあと +0.42」は左の端・線の下 |
| ハコブくんのふだんの線 x −0.33 | 破線（同じ） | 緑 (46,173,107)（ハコブくんの輪の光は白に近い薄い緑なので、同じ色みで濃くした） | 5 px。字「ハコブくんのふだん −0.33」は右の端・線の上 |
| 車いすの通った跡（後ろの車軸の真ん中） | 実線・通った所から順に伸びる・消さない | 橙 (239,108,0) | 10 px |
| ハコブくんの通った跡（根） | 同じ | 深い青緑 (0,105,92) | 10 px |
| 印（丸） | 跡の色の丸に白い縁 | 跡と同じ色 | 半径 13 px・縁 3 px。印から字まで 3 px の線で引き出す |
| 印の字 | 「寄せ始め 10.3秒」「寄せ終わり 13.8秒」（廊下の下）・「寄り始め 9.7秒」「止まった 12.5秒」（廊下の上） | 跡と同じ色の字・白い札（縁も同じ色） | 40 px |
| 線の端の字 | 白い札（縁は線の色） | 線の色 | 36 px |
| 左上の字 | 白い札（不透明 92%）・黒い字 | (25,25,25) | 70 px（229 の 34 px の 2.06 倍）・行の間 88 px |
- 線の端の字の置き場所：+0.28 と +0.42 の字は左の端に置いた。右の端は車いすが入ってくる所（7.1〜8.4 秒）なので、字が車いすを隠さないようにした。左の端は車いすが出ていく所（20.8〜22.2 秒）で、その間は字が車いすの一部に重なる
- 破線は通った跡の上に描いた（跡が線の上を通っても、線が見えるように）
- 左上の字は 3 項目：「10.3 秒」（動画の秒）・「車いすの横の位置 x +28.0 cm」（車いすの根の x。229 の報告の +0.28／+0.42 と同じ所）・「ハコブくんと車いす・人のすき間 0.86 m」
  すき間は 229 と同じ測り方で、1.5 m より近い時だけ測っている（1.5 m より遠いと値が無い）。値が無い時は「—」を出す（決めてほしいことの 2）

■ 3. 確かめ
| 項目 | 基準 | 結果 | 合否 |
| 動きが 229 と同じ | 差 0 | 台本の全部のコマ 800 コマ（動画は 770 コマ）で、frames（ハコブくん・車いす・大城さんの位置と向きなど 38 列）・bones（大城さんの骨 41 本の位置 125 列）・wc（車いすの位置・向き・車輪 17 列）・feet（足 6 列）の値が 229 と全部同じ（違うセル 0・差の最大 0）。check と events も 229 と同じ | 合う |
| 目印の線の位置 | 床の正しい位置 | 中心 x 0 → 画面の y 633.66 px・+0.28 → 686.11 px・+0.42 → 712.33 px・−0.33 → 571.84 px（画面から戻した x は 0.00000・+0.28000・+0.42000・−0.33000）。+0.28 と +0.42 の線のあいだ 26.2 px（14 cm）。写し方は Unity のカメラで床の 3 点を写して決めた。Unity で撮った絵の手すりの内側の面（x ±0.84）は y 476〜477・790〜791 px にあり、写し方の 476.31・791.00 px と 1 px 以内（5 mm 以内） | 合う |
| 通った跡の線と本当の位置 | 各コマで 1 cm 以内 | 跡の点と本当の位置のずれの最大：車いすの後ろの車軸の真ん中 0.167 cm・ハコブくんの根 0.178 cm（770 コマ。描く点を 2 倍の画面の整数の点にそろえた分のずれ） | 合う |
| 寄せ始め・寄せ終わりの印の時刻 | 10.300・13.833 秒 | 10.300 秒・13.833 秒に出た（台本の shift t0 11.3000・t1 14.8333 − 1.000）。ハコブくんの印：寄り始め（決まりに当たった）9.700 秒・止まった 12.533 秒（229 の報告と同じ） | 合う |
| 画面の中にいる時間（動画の秒） | 寄せ始めの 1 秒前〜寄せ終わりは車いすがずっと中 | 車いす：外 0.000〜7.067／一部 7.100〜8.400／全部 8.433〜20.800／一部 20.833〜22.133／外 22.167〜25.633。動画 9.300〜13.833 の間で全部が中でないコマ 0。ハコブくん：外 0.000〜5.467／一部 5.500〜6.767／全部 6.800〜25.633（最後まで）。大城さん（骨）：外 0.000〜8.300／一部 8.333〜8.800／全部 8.833〜22.000／一部 22.033〜22.400／外 22.433〜25.633 | 合う |
| 左上の値に壊れた値が無い | 0 コマ | 壊れた値（5 桁以上の数・NaN・無限）のコマ 0。車いすの横の位置は全部のコマで値あり（+28.0〜+42.0 cm）。すき間は 555 コマで「—」（1.5 m より遠い・値が無い）、215 コマで値（最小 0.22 m） | 合う |
| 動画の長さ | 229 と同じ | 25.667 秒・770 コマ（229 の真上の動画と同じ） | 合う |

■ 4. 撮ったもの（1920×1080・30 コマ/秒・音なし）
- closeup230_yield_top.mp4：25.667 秒・770 コマ（md5 e6da3a614c909513f383466dd4b01fb1・1,454,764 バイト）
- 静止画 3 枚（stills/）：s1_shift_start（寄せ始め 10.300 秒）・s2_shift_end（寄せ終わり 13.833 秒）・s3_last（最後のコマ 25.633 秒・跡が全部引かれた所）
  md5 3b3fa95cc7ef6f468e55af827f693ff6・5637675eaf402374768e8f4099c596bc・c99422a01766e092e155e9d69a59b11f

■ 出力の場所（写した後に md5 を確かめた。すべて同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup230/
  closeup230_yield_top.mp4・stills/（3 枚）
  out/：check230_top.txt（3 の確かめ）・cmp230.txt（229 との比べ）・top230.csv（コマごとの車軸の真ん中・ハコブくんの根の床と画面の位置・画面の中か）・top230_cam.json（カメラと写し方）・frames230.csv・bones230.csv・feet230.csv・wc230.csv・check230.txt・events230.txt・unity.log
  tools/：make230.py（重ねて動画と静止画を作る）・cmp230.py（229 と比べる）・run230.sh・Closeup230.cs と closeup230_top.json の写し
  report230.txt（この報告の写し）
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup230/（動画・stills/ 3 枚）
- 試しの走り（1 回め：カメラを廊下の中心に置いた版）は /tmp/c230 にあり、KIOXIA には写していない

■ check-in
- cs:162（4 件：Closeups/closeup230_top.json と .meta・Closeups/Editor/Closeup230.cs と .meta を追加）。保留は無し

■ 決めてほしいこと
1. 真上のカメラを、229 の遠近のあるカメラから正射影（遠近の無い写し方）に変えた。床の目印と人・車いす・ハコブくんの位置が画面の端でもずれないようにするため。「真上から見下ろす」の中で決めたが、これでよいか
2. 左上のすき間は 229 と同じく 1.5 m より近い時だけ測っているので、1.5 m より遠い時（555 コマ）は「値が無い」として「—」を出した。「—」を「1.5 m より遠い」の意味で使ってよいか
3. 目印の線と通った跡は、人・車いす・ハコブくんの上に重ねて描いた（床に描いて体の下に隠れる形ではない）。左の端の線の字は、車いすが出ていく 20.8〜22.2 秒に車いすの一部に重なる。これでよいか
4. ハコブくんの通った跡は「ハコブくんの根」（外形の真ん中と 1 mm ずれ）の位置で引いた。車いすの横の位置の字は車いすの根の x（229 の報告と同じ所）、車いすの跡は依頼のとおり後ろの車軸の真ん中で引いた（まっすぐの所では同じ x。寄せている間は最大 1.4 cm ちがう）。これでよいか
5. 229 の決めてほしいこと 1〜5（と 228 の 1〜8）は答えを受けていないので、229 のまま

判定：合格
```

### 依頼231 の報告（report231.txt）

```text
依頼231：要所の場面⑨「車いすが廊下の真ん中で止まる」（⑩「茂さんに何を運んでいるか聞かれる」を中に入れる）を2本作って撮る（2026-11-16）

依頼228・229 の報告（230 の報告も）と、203・217〜224 の作り方の記録を読んでから始めた。
結論：寺島さんの読み込み・止まった所の置き方の確かめ・声（茂さんのほか）までは作った。
⑨-1 の 8・9 と ⑨-2 の 10（大城さんが車いすを寄せ、寺島さんが −x へ半歩 0.5 m よけ、ハコブくんが 229 のすき間の決まりで間を通る）は、廊下の幅（手すりの間 1.68 m）では成り立たないことが数字でわかったので止めた。
2 本とも終わり方がこの所で決まり、寺島さんの立つ所もそれで変わるので、台本 closeup231_script.json・コード Editor/Closeup231.cs・動画・静止画は作っていない。
茂さんの声は、ElevenLabs の鍵に声の一覧を読む権限が無く、候補を選べなかったので止めた。
触ったのは Assets/ServiceSim/Closeups/ の中だけ（新しい Models_terashima/ と Editor/Closeup231Terashima.cs）。①〜⑧（229・230 を含む）の台本・コード・出力、Models/、CloseupNurse.cs・CloseupDirector.cs、病院の1日の場面、配膳の場面、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:162 で変更なし。Mixamo のフォルダは無視の設定のまま）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 最新の check-in：cs:162（依頼230）
- 寺島さんの FBX：iCloud の hospital/people_3d/terashima/nurse_terashima.fbx がある（md5 329a18f158f54f807f9302c0a0e36dea・README.md あり）

■ 0. 寺島さんの読み込み（Editor/Closeup231Terashima.cs。出力 import/terashima231.txt）
- FBX を Assets/ServiceSim/Closeups/Models_terashima/ に写した（写した後も md5 同じ）。Models/ には入れていない
- 読み方は大城さん（CloseupImport.ImportNurse）と同じ手順を写して使った：Rig＝Humanoid・骨は名前どおりに割り当て（41 本・必須の骨はすべてある）・腕を T ポーズに直して Avatar（isValid・isHuman）・材質は Models_terashima/Materials/ に 14 個（FBX の色〔linear〕を sRGB に直した Standard。服 #2853AB・肌 #E9B58F・髪 #211814・めがね #5C463E など。大城さんと同じ色の物は同じ値）・プレハブ NurseTerashima.prefab
- Unity の自動の割り当ては目とあごに Eye_L を入れる（大城さんと同じ）ので使わず、名前で割り当てた
- 大城さんとの比べ（作った時の姿勢・根を原点にそろえて）：
  ・骨 46 本ずつ。違うのは根の名前だけ（Nurse_Oshiro／Nurse_Terashima）
  ・同じ名前の骨の位置のずれ 最大 0.0000 m・親からの位置 0.0000 m・親からの向き 0.0000°
  ・Humanoid の割り当て 41 本のうち、大城さんと骨の名前が違うもの 0 本
  → 骨の回し方（大城さんの動き）はそのまま同じ形になる
- 部品：Terashima_Skin・Hair・Glasses・Top・Sleeves・Pants・Shoes・Eyes・Brows・Mouth_flat／smile／surprised／talk／worried（README のとおり）
  ・口の 5 つの部品は、Unity では 5 つとも表示されている（README の「smile が既定で表示」ではない。茂さんの時と同じ）。使う時は 1 つだけを出す形にする必要がある
  ・大城さんを動かすコード（CloseupNurse.cs・Closeup229.cs）は部品を「Nurse_Skin」「Nurse_Mouth_」などの名前で探す作り。寺島さんにそのまま使うには、置いた寺島さんの部品の名前を Nurse_ に付け替える（共通の部品の CloseupNurse.cs は変えない）形になる。今回は台本とコードを作っていないので、立って話す・うなずく・笑う・歩くを寺島さんで実際に動かしてはいない
- 寸法（作った時の姿勢。腕は下に下ろした形）：
  | | 大城さん | 寺島さん |
  | 背の高さ | 1.642 m | 1.644 m（髪） |
  | 幅（腕を含む） | 0.476 m | 0.476 m |
  | 奥行（全体） | 0.307 m | 0.290 m |
  | 奥行（胸の高さ 1.00〜1.45 m の胴） | 0.274 m | 0.264 m |
- 並べた静止画：import/terashima231_front.png（前）・_side.png（横）・_face.png（顔）。形は README のとおり（前髪のあるボブ・丸めがね・ロイヤルブルーの服）

■ 1. 止まった所の置き方と、両横に残る幅（tools/geo231.py。出力 geo/geo231.txt・geo/geo231_top.png）
値の出どころ：廊下＝229 の台本（手すりの内の面 x ±0.84・壁 ±0.90）。ハコブくんの幅＝229（x −0.33 で手すりと 0.1905 m → 幅 0.639 m）。決まりのすき間＝229 の robot_rule（手すりと 0.053 m・人や車いすと 0.15 m より狭ければ止まる）。車いすの幅＝228 の報告（後ろの車輪の外 0.653 m）。寺島さん・大城さんの寸法＝上の表。
- ハコブくんが手すりの側を通るのに要る幅：0.053＋0.639＋0.15＝0.842 m
- 依頼どおりに置いた場合（車いす x 0.00・向き 0°、大城さん x 0.00〔車いすの後ろ〕、寺島さん x −0.55〔大城さんの −x 側、+x を向く。寺島さんの前と大城さんの体の −x の端 0.162 m〕）
  | 所 | −x 側に残る幅 | +x 側に残る幅 | 要る幅 | 通れるか |
  | 車いすの所 | 0.513 m | 0.513 m | 0.842 m | 両側とも通れない |
  | 大城さん・寺島さんの所 | 0.150 m（寺島さんの背中と手すり） | 0.602 m（大城さんと手すり） | 0.842 m | 両側とも通れない |
  車いすだけで両側とも狭いので、寺島さんの立つ所を動かす必要は無かった（「通れない」は満たせる）

■ 2. 止めた所：寄せて通る所（⑨-1 の 8・9、⑨-2 の 10）
(1) 寺島さんが −x の手すり側へ半歩 0.5 m よけられない
  ・寺島さんの背中から手すりまで 0.150 m（壁まで 0.210 m）。0.5 m よけると背中は x −1.190 で、手すりの外 0.350 m・壁の外 0.290 m になる
  ・よけた後も手すりの内に収まるには、はじめの寺島さんの根が x ≥ −0.200 でないといけない。大城さんの体（−x の端 −0.238）とぶつからないのは x ≤ −0.388。両方を満たす所は無い
  ・standing_yield の「よけ方」（進む向きの線から遠い側へ半歩、無理なら反対側。ロボットの帯・ほかの人から 0.35 m の中は除く）に当てはめると、遠い側（−x）は無理で、反対側（+x）はハコブくんの通る所の中になる
(2) 寺島さんが −x 側にいる間は、ハコブくんが「空いた間」を通れない
  ・大城さんが車いすを 229 と同じ x +0.42 へ寄せた時、−x の手すりから車いすの一番近い点（229 で測った x 0.079）までの幅は 0.919 m
  ・寺島さんがこの間に残る時に要る幅＝寺島さんの奥行 0.290＋すき間 0.15＋ハコブくん 0.639＋すき間 0.15＝1.229 m → 0.310 m 足りない（大城さんの所でも幅 1.022 m で 0.207 m 足りない）
  ・寺島さんが手すりに背中を付けても、寄った位置（x −0.4643）のハコブくんと 0.234 m 重なる
  → 依頼の 8・9 の形（寺島さんは −x の手すり側・ハコブくんはその横を 229 のすき間で通る）は、どう置いても成り立たない。寺島さんがどこへ・どうよけるかは決まりの決め方に当たるので、決めずに止めた（決めてほしいことの 1）
- 2 本とも終わり方がこの所を通り、寺島さんの立つ所（1 の置き方）もここの決め方で変わるので、1〜7 だけの台本・動画も作らなかった

■ 3. 声（KIOXIA の audio/）
- 217〜229 と同じ道具（動画/_制作ベース/tts_eleven.py --try・モデル eleven_v4・種 7・道具の既定の設定）。1 文ずつ −20 LUFS にそろえ、48 kHz の wav も作った
  | 名前 | 誰 | セリフ | Voice ID | 長さ | 元 → 直し |
  | V1_terashima_oshirosan | 寺島 | 大城さん | yWM6Fym2UxDGZqWRoGLB | 0.880 秒（声 0.738） | −16.2 LUFS → −3.8 dB |
  | V2_oshiro_otsukare | 大城 | あ、寺島さん。おつかれさま | PrFsT9a2iZebpuiWVeug | 2.320 秒 | −19.5 → −0.5 dB |
  | V5_hakobu_otodoke | ハコブ | 病棟へのお届け物です | N2Gsbfc4IcGM8KYgkrUz（ハコブ_イケボ） | 2.080 秒（声 1.955） | −18.9 → −1.1 dB |
  | V7_hakobu_toorimasu | ハコブ | すみません、通ります | N2Gsbfc4IcGM8KYgkrUz | 2.000 秒（声 1.847） | −16.9 → −3.1 dB |
  | V8_oshiro_gomenne | 大城 | あ、ごめんね | PrFsT9a2iZebpuiWVeug | 1.360 秒 | −23.4 → +3.4 dB |
- 読みの確かめ（217 と同じ MFCC-DTW）：「病棟へのお届け物です」の声と、ひらがなの「びょうとうへの…」0.906・「びょういんへの…」1.086 → びょうとう に近い。耳では聞いていない
- ハコブくんの Voice ID は、依頼どおり声の一覧.json の「ハコブ_イケボ」（N2Gsbfc4…）を使った。228・229 のハコブくんの声は gWJpc8whMBqnF7Y0kc9f で、違う声になる（決めてほしいことの 4）
- 茂さんの声（止めた）
  ・ElevenLabs の声の一覧（自分の声・共有の声）を読もうとしたが、鍵に voices_read の権限が無く 401 で読めなかった
  ・声の候補/森田茂/候補.json の 3 つ（m6t5TiWjcuPNNJR1BQ1x・RrWOAehcOxbYKTCgk4I2・T2l24fxTQZnWjpeFa5rY。2026-10-24 の Voice Design の下書き）は、保存された声ではないので読み上げに使えない（1 つ目で試して 404 voice_not_found）
  ・下書きを声として保存する（voice_design.py save）と ElevenLabs のアカウントに声が増えるので、しなかった。茂さんの声の候補 3 つの名前と Voice ID は出せていない（決めてほしいことの 2）
- セリフの間・口の動き・動画の音は、動画を作っていないので無い

■ 4. そのほか気づいたこと
- ハコブくんの速さ：依頼は「229 と同じ向き・速さ（0.8 m/秒）」だが、229 のハコブくんの決まりは cruise 0.6 m/秒・寄る時 0.5 m/秒（0.8 m/秒は大城さんが車いすを押す速さ）。どちらに合わせるか決めていない（決めてほしいことの 3）
- ⑨-2 の 10「茂さんが右手を上げて前の大城さんの腕へ」：大城さんは車いすの後ろ（茂さんの後ろ）で押しているので、茂さんから見て大城さんは前ではなく後ろになる。茂さんの右手（−z を向いて座るので −x 側＝寺島さんの側）で後ろの大城さんの腕へ届くかは、終わり方と一緒に止めたので確かめていない
- 230 は終わっている（cs:162・合格）。真上の動画は 230 の作り（closeup230_top.json の写す範囲・Python で描く床の線・通った跡・左上の字）を使える

■ 5. 確かめの表・カメラの切りかえの表・セリフごとの時刻の表・早回しの区間・動けない時間・動画の長さ
- 台本・動画を作っていないので、無い

■ 出力の場所（写した後に md5 を確かめた。18 ファイルのうち 17 が同じ。lufs.txt だけは KIOXIA の方に読みの確かめの 1 行を足したので違う）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup231/
  audio/（V1・V2・V5・V7・V8 の mp3 と 48 kHz の wav・lufs.txt・reading_check/）
  import/（terashima231.txt・terashima231_front／side／face.png・unity.log）
  geo/（geo231.txt・geo231_top.png：止まった所と、寄せて通る所の真上の図）
  tools/（Closeup231Terashima.cs の写し・geo231.py・readchk217.py）
  report231.txt（この報告の写し）
- iCloud の hospital/closeup231/：動画・静止画を作っていないので作っていない

■ check-in
- cs:163（38 件：Closeups/Models_terashima/〔nurse_terashima.fbx・Materials/ 14 個・NurseTerashima.prefab と .meta〕・Closeups/Editor/Closeup231Terashima.cs と .meta を追加）。保留は無し（Mixamo のフォルダは無視の設定のまま）

■ 決めてほしいこと
1. 寄せて通る所：廊下（手すりの間 1.68 m）では、寺島さんが −x の手すり側へ 0.5 m よけることも（手すりまで 0.150 m しか無い）、寺島さんが −x 側にいる間にハコブくんが 229 のすき間（手すり 0.053 m・人 0.15 m）で通ることも（0.310 m 足りない）できない。寺島さんがどこへどうよけるか（またはハコブくんの通り方）をどうするか
2. 茂さんの声：ElevenLabs の鍵に声の一覧を読む権限（voices_read）が無く、共有の声から年配の男性の日本語の声を選べなかった。声の候補/森田茂 の 3 つは保存されていない下書きで使えない。鍵の権限を足すか、下書きを声として保存するか、使う Voice ID を決めるか
3. ハコブくんの速さ：依頼の「229 と同じ速さ（0.8 m/秒）」と 229 の決まり（0.6 m/秒）が違う。どちらにするか
4. ハコブくんの声：依頼どおり「ハコブ_イケボ」（N2Gsbfc4…）で作ったが、228・229 は gWJpc8whMBqnF7Y0kc9f。⑧と⑨で声が変わってよいか
5. ⑨-2 の 10 で、茂さんが「前の大城さん」の腕をたたく所：大城さんは茂さんの後ろにいる。後ろへ手を伸ばす形でよいか

判定：止めた
```

### 依頼232 の報告（report232.txt）

```text
依頼232：⑧ 車いすに道を譲る（依頼230）の真上の動画で、床の線（点線と中心の線）と線の端の字を、ハコブくん・大城さん・茂さん・車いすの下に描いた（2026-11-16）

依頼230 の報告と真上の動画 closeup230_yield_top.mp4、依頼231 の報告を読んでから始めた。
コードは Editor/Closeup230.cs を写して Editor/Closeup232.cs にし、写した先で変えた。重ねる道具は make230.py を写して make232.py にした。
台本は 229 の closeup229_script.json、カメラは 230 の closeup230_top.json をそのまま読む（写していない・変えていない）。
触ったのは Assets/ServiceSim/Closeups/Editor/Closeup232.cs と .meta（新しい 2 ファイル）だけ。230・231 の台本・コード・出力、本番の動画・静止画・台本、Models/、病院の1日の場面、配膳の場面、共通の部品、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。場面のファイルは保存していない。

結論：⑧ の真上の動画を撮り直した。4 の確かめはすべて合った。⑨ は依頼231 が止めた（寺島さんの読み込みと声だけで、真上の動画は撮っていない）ので撮っていない。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:163 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み

■ 描き方（床の上に描く方法）
- 「体だけの型」を Unity で撮り、床の線の層をその型の所で消してから重ねる方法にした（床に貼る・カメラの描く順を変える方法ではない）
- Unity（Closeup232.cs）：230 と同じ真上のコマを撮ったあと、同じコマで、真上のカメラを写した別のカメラ（MaskCam232）で「体だけを白く写した型」を撮る（frames/yield_top_mask/、黒＝床など・白＝体）。
  体に数えた部品は 42：ハコブくん（体・引き出し・トレイ 4・検体の袋・帯・顔・輪）、車いす（枠・座・背・車輪・キャスター）、大城さんと茂さんの写しの部品（肌・服・髪・目・口など）。
  廊下（壁・扉・手すり・床など）103 は入れていない（一覧は out/events232.txt）。
  型を撮る間だけ体の部品を層 29 に移して白い Unlit/Color で写し、写した後に層・材料を元に戻す（影・光は型に入らない。車いすの枠のすき間からは床が見えるので、すき間の所の線は見える）。
  真上のコマ（重ねる前）は 230 と 770 コマ全部で 1 画素も違わない（差 0）
- 重ねる（make232.py）：床の線の層（中心の線・+0.28・+0.42・−0.33 の点線と、線の端の字 3 つ）の濃さに「1 − 型」を掛けてから重ねる。型のふちはなめらか（2 倍で撮って縮めた）
- 重ねる順は 230 のまま：コマ → 通った跡 → 床の線 → 印 → 左上の字。だから体の無い所では、230 と同じく点線が跡の上に見える。通った跡・印と印の字・左上の字は 230 のまま体の上に重ねる
- 線の位置・色・太さ・破線の長さ、字の大きさと置き場所、跡・印の描き方、カメラ、動きは変えていない

■ 4. 確かめ
| 項目 | 基準 | 結果 | 合否 |
| 線が体の下（寄りの静止画） | 線が体に重なるコマを 3 つ以上選び、体の所に線が見えない | 4 コマで確かめた（stills_zoom/、上が 230・下が 232、2.5 倍に寄せた）。230 で線が体に重なっていた画素 → 232 で体の所に残る線の画素：8.000 秒 ハコブくんと −0.33 の線 1,052 → 0・12.000 秒 寄せている車いす・茂さん・大城さんと +0.28／+0.42 の線 2,805 → 0・16.000 秒 ハコブくんの横を通る車いすと +0.28／+0.42 の線 2,304 → 0・21.500 秒 左の端の字「始め +0.28」「寄せたあと +0.42」の上を通る車いす・大城さん 9,063 → 0。目で見ても体の所に線は見えない | 合う |
| 線が体の下（全部のコマ） | 体の所に線が残らない | 230 で線が体に重なっていたコマ 604／770（1 コマの最大 16,018 画素）。型が白い所に線の層が残る画素：全部のコマで 0 | 合う |
| 体の無い所が 230 と同じ | 差 0 | 型が 0 の所で、232 の絵と 230 の重ね方の絵が違う画素：全部のコマの合計 0（＝線の位置・色・太さ、跡、印、左上の字は体の外で 230 と画素まで同じ） | 合う |
| 230 の重ね方を作り直すと 230 の動画と同じ | md5 が同じ | make232.py が同時に作った 230 の重ね方の動画 closeup232_as230.mp4 の md5 e6da3a614c909513f383466dd4b01fb1 は 230 の closeup230_yield_top.mp4 と同じ | 合う |
| 動きが 230 と同じ | 全部のコマで差 0 | 台本の全部のコマ 800 コマで frames（38 列）・bones（125 列）・wc（17 列）・feet（6 列）・top（車軸の真ん中とハコブくんの根の床と画面の位置・画面の中か、13 列）の値が 230 と全部同じ（違うセル 0・差の最大 0）。top_cam（写し方）・check・events も同じ（events は依頼232 の部品の一覧を除く） | 合う |
| 線の位置 | 230 と同じ | 中心 633.66 px・+0.28 686.11 px・+0.42 712.33 px・−0.33 571.84 px（230 と同じ写し方・同じ値） | 合う |
| 跡・印・左上の字の値 | 230 と同じ | 跡のずれの最大 車軸の真ん中 0.167 cm・ハコブくんの根 0.178 cm、印 10.300・13.833・9.700・12.533 秒、左上の字の壊れた値 0 コマ・すき間「—」555 コマ（すべて 230 と同じ） | 合う |
| 動画の長さ | 230 と同じ | 25.667 秒・770 コマ・1920×1080・30 コマ/秒 | 合う |

■ 撮った動画（音なし）
- closeup232_yield_top.mp4：25.667 秒・770 コマ（md5 c8e28e4ca26e8e4213fb6bac22f4023a・1,415,418 バイト）
- 確かめの寄りの静止画（stills_zoom/、上 230・下 232）：
  z_08.000s_f270.png d7ab43cd891015aee2abe987f1ca3277・z_12.000s_f390.png 073c3caf30764e59d28664486e09d398・
  z_16.000s_f510.png ebbab1abbdb4d65427e4d37145534fc0・z_21.500s_f675.png 6b6687414197ff5ff56f4a3b0d5e3885
- 230 と同じ時刻の静止画 3 枚（stills/、KIOXIA だけ）：s1_shift_start e4c359fe9f88e96124f5d5f1be3fba30・s2_shift_end 554b5c5255222e2db1389b65f2dfbb3f・s3_last 95bac503ab1fc8a8f7b3ebac1d5b7d4b
- ⑨（closeup232_stop_voice_top.mp4・closeup232_stop_stuck_top.mp4）：撮っていない。依頼231 は止めた（寺島さんの読み込みと声と幅の計算だけで、真上の動画は 230 の作りで撮っていない）ため

■ 出力の場所（写した後に md5 を確かめた。すべて同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup232/
  closeup232_yield_top.mp4・stills_zoom/（4 枚）・stills/（3 枚）
  out/：check232_top.txt（確かめ）・cmp232.txt（230 との比べ）・per232.csv（コマごとの型の外の差・体に残る線・230 で体に重なっていた線の画素）・closeup232_as230.mp4・top232.csv・top232_cam.json・frames232.csv・bones232.csv・feet232.csv・wc232.csv・check232.txt・events232.txt（体に数えた部品の一覧を含む）・unity.log・make232_out.txt
  tools/：make232.py・cmp232.py・run232.sh・Closeup232.cs の写し
  report232.txt（この報告の写し）
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup232/（closeup232_yield_top.mp4・stills_zoom/ 4 枚）
- 試しの走り（13 秒まで）は /tmp/c232/try1 にあり、KIOXIA には写していない

■ check-in
- cs:164（2 件：Closeups/Editor/Closeup232.cs と .meta を追加）。保留は無し

■ 決めてほしいこと
1. 車いすの枠や車輪のすき間（体の部品の無い所）からは床が見えるので、そこの線は見えるままにした（230 の 21.5 秒の左の端の字も、車いすのすき間からは字の一部が見える）。これでよいか
2. 体の無い所の重ねる順は 230 のまま（点線が通った跡の上）にした。床の線を跡の下にもするかは決めていない
3. 230 の決めてほしいこと 1〜5（と 229・228 のもの）は答えを受けていないので、230 のまま

判定：合格
```

### 依頼233 の報告（report233.txt）

```text
依頼233：⑨「車いすが廊下の真ん中で止まる」（⑩を中に入れる）を、立ち位置・速さ・声を直して2本作って撮る（依頼231 の作り直し）（2026-11-16）

依頼231 の依頼文と報告、228・229・230・232 の報告、229 の依頼文（寄せ方の決まり）を読んでから始めた。
結論：依頼の 1 のとおり、作る前に「寄せて通る形」があるかを計算した。229 の寄せ方の決まり（前へ進みながら・向き 8° まで・寄せ終わりで向き 0°）では、車いすを x 0.00 から +0.42 へ寄せるのに前へ 2.99 m 以上（向きが一瞬で変わるとしても）進む必要がある。車いすの前に空いているのは 2.30 m（ハコブくんが止まる所まで）なので、その場で寄せて寺島さんが下がる形は作れない。決まりに合う形は「車いすが前へ 3.3〜4.0 m 進み、ハコブくんの横まで行って寄せる」だけで、この時は寺島さんが下がる必要が無くなる（下がる距離 0 m）。依頼の形と違うので、決めずに止めた。
2 本とも終わり方（寄せて通る所）がこの所を通るので、台本 closeup233_script.json・コード Editor/Closeup233.cs・動画・静止画は作っていない（231 と同じ扱い）。声は 4 つ新しく作り、計算と図を出した。
Unity の中（Assets/ServiceSim/Closeups/ を含む）は何も変えていない。①〜⑧・230・231・232 の台本・コード・出力、Models/、病院の1日の場面、配膳の場面、共通の部品、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:164 で変更なし。Mixamo のフォルダは無視の設定のまま）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 最新の check-in：cs:164（依頼232）

■ 1. 止まった所の置き方と両横に残る幅（tools/feas233.py。出力 geo/feas233.txt・geo/geo233_top.png の左）
寸法は 231 と同じ（廊下 手すりの内の面 ±0.84、車いす 根から x ±0.326・前 0.640・後ろ 0.430、ハコブくん 幅 0.639〔手すりの高さ〕、大城さん 幅 ±0.238、寺島さん 前 0.150・後ろ 0.140・幅 ±0.238）
- 置き方：車いす x 0.00・向き 0°、大城さん x 0.00（車いすの後ろ）、寺島さんは大城さんの +x 側で −x（大城さんのほう）を向く。大城さんとのすき間 0.10〜0.15 m にすると根 x +0.488〜+0.538・背中と手すり 0.212〜0.162 m
| 所 | −x 側に残る幅 | +x 側に残る幅 | 要る幅 | 通れるか |
| 車いすの所 | 0.514 m | 0.514 m | 0.842 m | 両側とも通れない |
| 大城さん・寺島さんの所 | 0.602 m（大城さんと手すり） | 0.162〜0.212 m（寺島さんの背中と手すり） | 0.842 m | 両側とも通れない |

■ 2. 止めた所：寄せて通る形があるか（⑨-1 の 8・9、⑨-2 の 10。依頼の答え 1）
(1) 寄せるのに要る前へ進む長さ（229 の決まり：向き 8° まで。横の長さ ÷ tan 8°。向きが一瞬で変わるとしても、これより短くはならない）
| 寄せる先 | 横の長さ | 前へ進む長さの下限 |
| x +0.42（229 と同じ） | 0.420 m | 2.988 m |
| x +0.346（寄った位置 x −0.4643 のハコブくんと 0.15 m あく一番小さい所。229 は +0.42 で 0.224 m） | 0.346 m | 2.462 m |
| x +0.4805（ふだんの位置 x −0.33 のハコブくんと 0.15 m あく一番小さい所。+0.42 では 0.0895 m） | 0.4805 m | 3.419 m |
(2) 車いすの前に空いている長さ：ハコブくんは 229 の決まりで止まると、足のせの前の端と 2.30 m（できるだけ守る 2.0〜3.0 m）。ハコブくんの前の端と 0.15 m までなら前へ 2.15 m
| あいだ | 向きの変わる所 | 寄せられる横の長さ | x +0.42 まで | x +0.346 まで |
| 2.3 m | 0 m（一瞬で変わる） | 0.302 m | 0.118 m 足りない | 0.044 m 足りない |
| 2.3 m | 0.6 m | 0.218 m | 0.202 m 足りない | 0.128 m 足りない |
| 3.0 m | 0 m | 0.401 m | 0.019 m 足りない | 足りる |
| 3.0 m | 0.6 m | 0.316 m | 0.104 m 足りない | 0.030 m 足りない |
  → 依頼の形（車いすの前の所で寄せ、空いた間をハコブくんが通る）は、前へ進める長さが 0.69 m（2.99−2.30。下限で数えて）以上足りない
(3) 当たらずに寄せられる形（決まりに合う形）は、車いすが前へ 3.3〜4.0 m 進み、ハコブくんの横まで行って寄せ終わる形だけ（長方形の近似で、ハコブくんと車いす・大城さんのすき間の最小 0.17〜0.22 m・向きの変わる所 0.3〜1.0 m・あいだ 2.3 m）。寄せ終わった時、足のせの前の端はハコブくんの前の端を 1.0〜1.7 m 越えていて、車いすと大城さんはハコブくんの横に並ぶ（図の右）
  ・この形では、大城さんは寺島さんから前へ離れていくので、寺島さんが下がらなくても当たらない（大城さん・車いすとのすき間の最小 0.062 m）。「下がる距離は大城さんと当たらない一番短い距離」は 0 m になり、依頼の「大城さんの後ろへ下がって、+x の手すり沿いに立つ」「通り過ぎたら戻る」が起きない
  ・大城さんは寺島さんと話していた所から 3.3〜4.0 m 前へ行くことになる
  → どちらの形にするか（車いすが前へ進んでハコブくんの横まで行く・寄せ方の決まりを変える・ほか）は決め方に当たるので、決めずに止めた（決めてほしいことの 1）
- 寺島さんが下がった距離と時刻・大城さんとのすき間の最小：作っていないので無い（上の (3) の形なら 0 m・0.062 m）

■ 3. 作る前に見つけたこと（台本を作る時に当たる所。止めた所とは別）
- 大城さんが「振り返る」所：寺島さんが大城さんの横（同じ前後の位置・すき間 0.15 m）にいると、大城さんが寺島さんの顔を見るには顔を約 99° 回す必要がある。大城さんの顔は Head の骨だけで回す作り（CloseupNurse の headYawDeg）で、228・229 の最大は 34°。手を握りに置いたまま体を回す動きは今は無い（新しい動きは足さない決まり）。寺島さんを前（車いすの横）へ出すと顔の向きは小さくなるが、前を向いて歩いたまま車いすの横（車いすの +x の端 0.326）を通ると寺島さん（幅 0.476 m）は手すりに届く（決めてほしいことの 2）
- 寺島さんが後ろから追いついて横に並ぶ所：大城さんの +x の端と手すりの間は 0.602 m で、寺島さん（腕を含む幅 0.476 m）が真ん中を歩くと両側 0.063 m ずつ（当たりはしない）

■ 4. 声（KIOXIA の audio/。217〜231 と同じ道具 動画/_制作ベース/tts_eleven.py --try・モデル eleven_v4・種 7・道具の既定の設定。1 文ずつ −20 LUFS にそろえ、48 kHz の wav も作った）
| 名前 | 誰 | セリフ | Voice ID | 長さ | 元 → 直し | 作り |
| M1_morita_nani | 茂さん | 何を運んでるの？ | ydyMD3g4SbEeNpF0wahP（田中先生の声） | 1.360 秒 | −17.5 LUFS → −2.5 dB | 新しく作った |
| H1_hakobu_otodoke | ハコブ | 病棟へのお届け物です | gWJpc8whMBqnF7Y0kc9f | 1.840 秒 | −18.5 → −1.5 dB | 作り直した |
| H2_hakobu_toorimasu | ハコブ | すみません、通ります | gWJpc8whMBqnF7Y0kc9f | 1.680 秒 | −17.8 → −2.2 dB | 作り直した |
| T2_terashima_hakobukun | 寺島 | あ、ハコブくん | yWM6Fym2UxDGZqWRoGLB | 1.440 秒 | −18.9 → −1.1 dB | 新しく作った |
| V1_terashima_oshirosan | 寺島 | 大城さん | yWM6Fym2UxDGZqWRoGLB | 0.880 秒 | （231 のまま −20.0） | 231 の声を写した |
| V2_oshiro_otsukare | 大城 | あ、寺島さん。おつかれさま | PrFsT9a2iZebpuiWVeug | 2.320 秒 | （231 のまま） | 231 の声を写した |
| V8_oshiro_gomenne | 大城 | あ、ごめんね | PrFsT9a2iZebpuiWVeug | 1.360 秒 | （231 のまま） | 231 の声を写した |
- 231 で「ハコブ_イケボ」（N2Gsbfc4…）で作った V5・V7 は使っていない
- 読みの確かめ（231 と同じ MFCC-DTW）：「病棟へのお届け物です」の声と、ひらがなの「びょうとうへの…」1.015・「びょういんへの…」1.213 → びょうとう に近い（同じ声・同じ種のひらがなの声 2 つを試しに作った。reading_check/）。耳では聞いていない
- 声は動画に使っていない（動画を作っていないため）。セリフの間・口の動きは無い

■ 5. 231 の 7 の項目のうち、作っていないので無いもの
寺島さんを動かした結果（大城さんの動きがそのまま使えたかは 231 の読み込みの比べ〔骨の位置・名前・割り当てが同じ〕まで）、2 本のセリフごとの時刻の表、早回しの区間、動けない時間、カメラの切りかえの表、確かめの表（必ず守る・できるだけ守る）、動画の長さ、真上の動画（232 は終わっているので、作る時は 232 の描き方を使える）

■ 出力の場所（写した後に md5 を確かめた。22 ファイルすべて同じ。lufs.txt は KIOXIA の方に読みの確かめの 1 行を足した）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup233/
  audio/（M1・H1・H2・T2 の mp3 と 48 kHz の wav、231 から写した V1・V2・V8、lufs.txt、reading_check/）
  geo/（feas233.txt：計算の全部・geo233_top.png：止まった所と、229 の寄せ方で寄せる形の真上の図）
  tools/（feas233.py・fig233.py・readchk.py）
  report233.txt（この報告の写し）
- iCloud の hospital/closeup233/：動画・静止画を作っていないので作っていない

■ check-in
- 無し（Unity のプロジェクトの中は変えていない。cs:164 のまま・保留無し）

■ 決めてほしいこと
1. 寄せて通る所：229 の寄せ方（向き 8° まで）では、車いすを x +0.42 へ寄せるのに前へ 2.99 m 以上要り、車いすの前の 2.30 m（ハコブくんが止まる所まで）では足りない（その場で寄せる形は 0.69 m 以上足りない）。決まりに合うのは、車いすが前へ 3.3〜4.0 m 進んでハコブくんの横まで行く形だけで、その時は寺島さんが下がる必要が無い（0 m）。寄せ方と寺島さんの動きをどうするか
2. 大城さんが寺島さんを「振り返る」所：寺島さんが大城さんの横にいると顔を約 99° 回す必要があり、今の作り（顔は Head の骨だけ・228/229 の最大 34°・手は握りのまま）ではできない。寺島さんの立つ前後の位置か、大城さんの振り返り方をどうするか
3. ハコブくんの通る所の「ふだんの通り道（x −0.33）のまま」：ふだんの位置のままでは、+0.42 へ寄せた車いすとのすき間は 0.0895 m（0.15 m より狭い）。229 の決まり（止まる時は x −0.4643 へ寄る）のとおりに寄った位置から通るのでよいか

判定：止めた
```

### 依頼234 の報告（report234.txt）

```text
依頼234：⑧ 車いすに道を譲る（依頼232）の真上の動画で、車いすや人のすき間から点線がちらちら見えるのを消した（2026-11-16）

依頼232 の依頼文・報告・make232.py・Closeup232.cs を読んでから始めた。
コードは Editor/Closeup232.cs を写して Editor/Closeup234.cs にし、写した先で変えた。重ねる道具は make232.py を写して make234.py にした。
台本は 229 の closeup229_script.json、カメラは 230 の closeup230_top.json をそのまま読む（写していない・変えていない）。
触ったのは Assets/ServiceSim/Closeups/Editor/Closeup234.cs と .meta（新しい 2 ファイル）だけ。232 の道具・コード・出力、Models/、病院の1日の場面、配膳の場面、共通の部品、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。場面のファイルは保存していない。

結論：⑧ の真上の動画を撮り直した。確かめはすべて合った。⑨ は依頼233 が止めた（声だけで真上の動画は無い）ので撮っていない。
ただし、もの「どうし」のあいだ（大城さんの腕と車いすの押し手のあいだの床など）は、答え 1 の「ものごとに」のとおり埋めていないので、そこでは線がまだ見える（決めてほしいこと 1）。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:164 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み

■ 穴の埋め方
- Unity（Closeup234.cs）：232 と同じ真上のコマと 232 と同じ体の型（frames/yield_top_mask）を撮ったうえで、もの別の型 frames/yield_top_obj を足した。
  ものを 1 つずつ別々に白く写し（3 回撮る。ほかのものに隠された所も入る）、1 枚の色の画像にまとめた：赤＝ハコブくん（10 部品）・緑＝車いすと茂さん（車いす 11 部品＋茂さん 12 部品）・青＝大城さん（9 部品）。
  写し方は 232 と同じ（層 29 に移して白い Unlit/Color で写し、写した後に戻す）
- 重ねる（make234.py）：ものごとに、型の写った所（0 より大きい所）を
  ① 半径 6 画素（3.20 cm）の円で「閉じる処理」（広げてから同じだけ縮める。幅 12 画素＝約 6.4 cm より狭いすき間・切れこみがふさがる）
  ② 中の穴埋め（まわりを囲まれた床をすべて埋める）
  の順で外形にした。足した所（体の部品が写っていない所で外形の中）は線を全部消し、体の部品が写っている所は 232 と同じ型（ふちはなめらか）で線を消す。
  これで車いすの背もたれと押し手のあいだ・車輪と枠のすき間・足のせのあいだ・茂さんの脚のあいだ・大城さんの腕と胴のすき間がふさがる。
  半径は 2・4・6・8・10・12 画素で試し、車いすと茂さんの足した量は 6 画素でほぼ頭打ち（6→12 で 3,228→3,369 画素）、大城さんのふくらみは半径にほぼ比例して増えるので 6 画素にした
- 重ねる順（答え 2）：下から 床と体（真上のコマ）→ 床の線（中心の線・点線・線の端の字。外形の所は消す）→ 通った跡 → 印と印の字 → 左上の字
- 線の位置・色・太さ・破線の長さ、字、跡・印の描き方、カメラ、動きは変えていない

■ 確かめ
| 項目 | 結果 | 合否 |
| 外形の中（型が全部白い所と埋めた所）に床の線の画素 | 全部のコマ（770）で 0（合計 0） | 合う |
| 232 で外形の中のすき間（埋めた所）に線が見えていたコマ | 232：459／770 コマ（画素の合計 370,344・1 コマの最大 2,715）→ 234：0 コマ | 合う |
| 外形のふくらみの最大（外形のふちの足した画素の、体の部品の写った所からの距離） | ハコブくん 1.00 画素（0.53 cm）・車いすと茂さん 6.00 画素（3.20 cm）・大城さん 5.39 画素（2.87 cm）。中の穴の中まで含めた足した画素の距離の最大は 車いすと茂さん 9.85 画素（5.26 cm。背もたれと押し手のあいだの穴の真ん中。外形の外へは出ない） | 合う（最大 6 画素＝3.2 cm） |
| 体の無い所（型 0）で 232 と違う画素 | 566 コマ・合計 4,536,518 画素（1 コマの最大 15,585）。そのうち「通った跡と床の線が重なる所」の外にある画素は 0 ＝ 違うのは重ねる順の所だけ | 合う |
| 232 の重ね方を作り直すと 232 の動画と同じ | make234.py が同時に作った closeup234_as232.mp4 の md5 c8e28e4ca26e8e4213fb6bac22f4023a は 232 の closeup232_yield_top.mp4 と同じ（＝上の「232 と比べた値」は本当の 232 と比べている） | 合う |
| 真上のコマ・232 の型が 232 と同じ | 770 コマ全部で、真上のコマ・体の型とも 232 とバイトまで同じ（違うコマ 0） | 合う |
| 動きが 232 と同じ | 台本の 800 コマで frames（38 列）・bones（125 列）・wc（17 列）・feet（6 列）・top（13 列）の違うセル 0。top_cam・check・events も同じ（events は依頼234 のもの別の部品の一覧を除く） | 合う |
| 動画の長さ | 25.667 秒・770 コマ・1920×1080・30 コマ/秒（232 と同じ） | 合う |
| 体のふちのなめらかな所（型が 0 と 255 のあいだ）に薄く残る線 | 1 コマの最大 987 画素（604 コマ）。232 と同じ扱い（体のふちの 1 画素ほどのにじみ） | 参考 |
| 寄りの静止画（上 232・下 234、232 と同じ範囲を 2.5 倍） | 8.000 秒（ハコブくん）・12.000 秒・16.000 秒・21.500 秒（車いす）。このコマで 232 のすき間に見えていた線（画面全体）428・338・594・1,871 画素 → 234 で外形の中に残る線 0・0・0・0 | 合う |

■ 撮った動画（音なし）
- closeup234_yield_top.mp4：25.667 秒・770 コマ（md5 b782b184d7a55f8b2cd0e5c3b7879a22・1,346,198 バイト）
- 寄りの静止画（stills_zoom/、上 232・下 234）：
  z_08.000s_f270.png db71d6d5795b5aa38347e51ca9da8cd3・z_12.000s_f390.png fb6e2f53f869cb25132b75d6fb440b55・
  z_16.000s_f510.png 6fe50ddc6ef63ef49c7d3d7f135742d1・z_21.500s_f675.png 9f882aed045445d2cc8ce47d305ceadc
- 232 と同じ時刻の静止画 3 枚（stills/、KIOXIA だけ）：s1_shift_start 902e1448aebdec79248e8d9406304300・s2_shift_end 007efeed859fc34f451d9bf3c3e1b4d4・s3_last 5dee75ede4d2a31148bf6f131ca0dee9
- ⑨（closeup234_stop_voice_top.mp4・closeup234_stop_stuck_top.mp4）：撮っていない。依頼233 は止めた（声と幅の計算だけで、⑨ の真上の動画はできていない）ため

■ 出力の場所（写した後に md5 を確かめた。すべて同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup234/
  closeup234_yield_top.mp4・stills_zoom/（4 枚）・stills/（3 枚）
  out/：check234_top.txt（確かめ）・cmp234.txt（232 との比べ）・per234.csv（コマごとの外形の中の線・ふちの線・232 のすき間の線・型の外の 232 との差・重ねる順の外の差・もの別の足した画素）・
        between234.txt（もののあいだの床の線の数え）・closeup234_as232.mp4・top234.csv・top234_cam.json・frames234.csv・bones234.csv・feet234.csv・wc234.csv・check234.txt・events234.txt（もの別の部品の一覧を含む）・unity.log・make234_out.txt
  tools/：make234.py・cmp234.py・between234.py・run234.sh・Closeup234.cs の写し
  report234.txt（この報告の写し）
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup234/（closeup234_yield_top.mp4・stills_zoom/ 4 枚）
- コマ（真上・型・もの別の型 各 770 枚）は /tmp/c234/full/frames にあり、KIOXIA には写していない

■ check-in
- cs:165（2 件：Closeups/Editor/Closeup234.cs と .meta を追加）。保留は無し

■ 決めてほしいこと
1. もの「どうし」のあいだの床は埋めていない（答え 1 の「ものごとに」のとおり）。大城さんの胴・腕と車いすの押し手で囲まれた床などから線がまだ見えるコマが 400／770 ある（画素の合計 70,972・1 コマの最大 644 画素＝動画 20.467 秒。21.500 秒の寄りの静止画でも「寄せたあと +0.42」の字の一部が大城さんと押し手のあいだに見える）。大城さんが歩くと形が変わるので、ここはまだちらつく見込み。このままでよいか
2. 閉じる処理の半径を 6 画素（3.20 cm）にした。この値でよいか
3. 232 の決めてほしいこと 3（230・229・228 のもの）は答えを受けていないので、そのまま

判定：合格
```

### 依頼235 の報告（report235.txt）

```text
依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）を、その場で向きを変えて寄せる形で 2 本作って撮った（依頼233 の続き）（2026-11-16〜17）

依頼231・233 の依頼文と報告、KIOXIA の closeup/20261116_closeup233/（feas233.txt・geo233_top.png・audio/）、依頼234 の報告を読んでから始めた。
⑨は新しい台本 closeup235_script.json（make_script235.py が作る。場面 stop_voice＝⑨-1・stop_stuck＝⑨-2）と Editor/Closeup235.cs（Closeup234.cs の写し）で作った。
声は 233 の audio/ をそのまま使った（新しく作っていない）。
触ったのは Assets/ServiceSim/Closeups/ の中の新しいファイルだけ（closeup235_script.json・Editor/Closeup235.cs・Textures/c235_*.png 4 枚と、それぞれの .meta）。
①〜⑧・230〜234 の台本・コード・出力、Models/、病院の1日の場面、配膳の場面、共通の部品（CloseupDirector.cs・CloseupNurse.cs を含む）、Packages、実行ファイルには触っていない。場面のファイルは保存していない。
Mixamo の FBX は使っていない・写していない・check-in していない。

結論：答え 1〜3 のとおりに 2 本作って撮った。寄せる道は決まりの中にあり（向き最大 17°・速さ 0.280 m/秒・向きの変わる速さ 23°/秒・前へ 0.822 m・後ろへ 0.054 m・足のせとハコブくんのあいだ最小 1.568 m・車輪の横すべり 0.00001 m/コマ）、
当たったコマはどれも 0、ハコブくんが通る時のすき間は 0.232 m（車いす）・0.287 m（大城さん）・0.645 m（寺島さん）。
外れたのは、寺島さん「大城さん」→大城さん「あ、寺島さん。おつかれさま」のセリフの間が 2.10 秒（決まりは 0.4〜0.7 秒）になったこと（大城さんが車いすを止めて体を回す間がはさまるため。下の 6）。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:165 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 最新の check-in：cs:165（依頼234）

■ 1. 作る前の計算：その場で寄せる道があるか（答え 1。tools/feas235.py。出力 geo/feas235.txt・geo/path235.json）
真上の 2 次元・長方形で近似し、「その場で回る（車軸の中心で）」「まっすぐ前／後ろ（車軸の向きにだけ進む＝横にすべらない）」をつなぐ道を探した（hybrid A*）。
寸法は 233 と同じ（車いす 車軸の中心から 横 ±0.326・前 0.790・後ろ 0.280、大城さん 車軸の後ろ 0.444・幅 ±0.2381・奥行 ±0.157、寺島さん 前 0.150・後ろ 0.140・幅 ±0.2381、手すりの内の面 ±0.84）。
決まり：向き ±30° まで・足のせの前の端とハコブくんの前の端 0.6 m 以上・後ろへ 1.0 m まで。計算で使った余り：手すりと 0.05 m・寺島さんと 0.05 m（どちらも私が置いた値）
| 寺島さん | 道 |
| いない | ある（後ろへ 1.0 m まで：7 区切り・後ろへ 0.98 m／後ろへ 0 m でも：9 区切り・前へ 0.85 m・足のせとハコブくん 0.607 m） |
| 立ち話の所（大城さんの真横・すき間 0.15）のまま | ある（9 区切り・前へ／後ろへを 3 回くり返す・16.7 秒）。ただし下の 2 の理由でこの立ち位置は使えない |
| 下がった所（x +0.65・大城さんの止まった根から後ろ 0.69 m） | ある。使った道：回る +12° → 前へ 0.84 m → 回る −17° → 後ろへ 0.73 m → 回る −10° → 後ろへ 0.19 m → 回る 0°（7 区切り・計算 12.95 秒・向き最大 17°） |
- 2 本とも同じ道。前へ多く進んで後ろへは少しだけ下がる形を選んだ（大城さんが寺島さんのほうへ下がる量が小さい）
- 道をたどる速さ：車軸の速さ 0.28 m/秒・向きの変わる速さ 23°/秒を上限にした台形の速さ（立ち上がり 0.3 秒／0.2 秒）・区切りのあいだ 0.15 秒止まる。寄せる時間 11.37 秒
- 前の車輪は、支柱に引っぱられて進む向きの後ろへ付いていく作り（228 のまま）。後ろへ進む所では 180° 向きを変える（「前の車輪の向きの最大 180°」）

■ 2. 立ち話の向き（答え 2。tools/turn235.py。出力 geo/turn235.txt）
- 大城さんは右手（寺島さんから遠い側）を握りからはなし、体を 29° 寺島さんへ回す（足は 2 歩踏み替える）。左手は左の握りのまま（的は止めた時の握りの位置に止める）。顔は体から −29.4°（30° 以内）で寺島さんを見る
- 寺島さんの立つ前後：大城さんの真横（前後 0）だと、左手を握りにのせたまま顔を 30° 以内にするには体を 75° 回して根を 0.13 m 車いすの側へ動かす必要があり、胴が車いすの背と重なる。
  答え 2 の「手の届かない形になる時は…前後に 0.3 m まで動かして合わせる」により、寺島さんを 0.3 m 前（車いすの +x の横）に立たせた。この時、体を 29° 回すだけで左の肩と握りは 0.430 m（押す形は 0.398 m）
- 寄せる前に、体を車いすのほうへ戻し（2 歩）、右手を握りの上 0.15 m・後ろ 0.20 m の所から下ろして握り直す（握りの筒・背を通らないようにした）
- 大城さんの体の向き（車いすから）の最大 29.00°・顔（体から）の最大 29.42°・寺島さんの目への角度の最小 6.3°
- 右手をはなした時刻：8.733 秒（2 本とも）／握り直した時刻：⑨-1 26.667 秒・⑨-2 48.800 秒（台本の秒。右手の重みが 1 を下回った／1 に戻ったコマ）
- 足のすべり（228 と同じ基準）：0.00 cm（2 本とも）

■ 3. 止まった所の置き方と両横に残る幅
- 車いす x 0.00・向き 0°（根 z 9.120）、大城さん x 0.00・根 z 9.714、寺島さん 根 x +0.538・z 9.414（大城さんの 0.3 m 前）・大城さんの根のほうを向く（向き 299°）
| 所 | −x 側 | +x 側 | 要る幅 | 通れるか |
| 車いすの所 | 0.514 m | 寺島さんが立つので 寺島さんの背と手すり 0.162 m（寺島さんの前と車いすの +x の端 0.062 m） | 0.842 m | 両側とも通れない |
| 大城さんの所 | 0.602 m | 0.602 m | 0.842 m | 両側とも通れない |
- ハコブくんは 229 の決まりのまま止まった：13.167 秒・x −0.4643・足のせの前の端とのあいだ 2.400 m（できるだけ守る 2.0〜3.0 m）

■ 4. 寺島さんの読み込みと動かし方
- 231 で入れたプレハブ（Models_terashima/NurseTerashima.prefab）を置き、部品の名前 Terashima_ を Nurse_ に替えて CloseupNurse を付け、2 つめの CloseupDirector で台本の場面 <場面>__tera を動かした
  （共通の部品は変えていない。大城さんの歩き・足を出す区切り・顔の向き・うなずき・口 talk の作りをそのまま使えた。新しい動きは足していない）
- 寺島さんは後ろから 1.2 m/秒で追いつき、大城さんの横に並んで「大城さん」、減速して止まりながら大城さんへ向く
- 下がる（答え 1）：大城さんの「あ、ごめんね」の始まり＋0.3 秒から、向きを変え（+z へ）・x +0.538 のまま後ろへ歩き・最後に手すりを背に −x を向きながら x +0.65 へ。下がった距離 0.9963 m（1.0 m まで）。
  ⑨-1 25.533〜28.700 秒・⑨-2 47.667〜50.833 秒。ハコブくんが通り過ぎた後は戻らない（手すり沿いのまま。235 の依頼文に戻る指示が無いため）
- 寺島さんの当たり：壁/手すり 0・大城さん 0・車いす 0（2 本とも）

■ 5. ハコブくんの通る位置（答え 3）と、走り出しの決まり
- 止まる時に寄った所（x −0.4643）のまま通り、物（車いす・茂さん・大城さん・寺島さん）の一番後ろを通り過ぎてから x −0.33 へ戻る
- 走り出し：229 の決まりには「止まった物が寄せ終わったら走り出す」所が無いので足した：「前の物（車いす・大城さん・寺島さんの根と向き）が 0.5 秒動かず、寄った位置で 0.15 m（gap_stop_m）以上あけて通れる時」（決めてほしいことの 1）
| | ⑨-1 | ⑨-2 |
| 止まった | 13.167 秒 | 13.167 秒 |
| 走り出し | 40.700 秒 | 62.833 秒 |
| 動けない時間 | 27.533 秒（30 秒未満） | 49.666 秒（30 秒以上） |
| 物の一番後ろを通り過ぎた | 50.533 秒 | 72.667 秒 |
| 通る時のすき間の最小（0.15 m 以上） | 車いす 0.232・茂さん 0.318・大城さん 0.287・寺島さん 0.645 m | 同じ値 |
| ハコブくんと手すり | 0.053 m（止まっている間 0.055） | 同じ |

■ 6. セリフごとの時刻（台本の秒・動画の秒＝台本の秒−1.0、⑨-2 は早回しの分を引く）・声の長さ
⑨-1（closeup235_stop_voice.mp4）
| セリフ | 誰 | 台本の秒 | 動画の秒 | 声の長さ |
| 大城さん | 寺島 | 6.107〜6.808 | 5.107〜5.808 | 0.700 |
| あ、寺島さん。おつかれさま | 大城 | 8.908〜11.068 | 7.908〜10.068 | 2.160 |
| 何を運んでるの？ | 茂 | 16.667〜17.717 | 15.667〜16.717 | 1.050 |
| 病棟へのお届け物です | ハコブ | 18.267〜19.967 | 17.267〜18.967 | 1.700 |
| すみません、通ります | ハコブ | 23.167〜24.667 | 22.167〜23.667 | 1.500 |
| あ、ごめんね | 大城 | 25.217〜26.547 | 24.217〜25.547 | 1.330 |
⑨-2（closeup235_stop_stuck.mp4）
| セリフ | 誰 | 台本の秒 | 動画の秒 | 声の長さ |
| 大城さん | 寺島 | 6.107〜6.808 | 5.107〜5.808 | 0.700 |
| あ、寺島さん。おつかれさま | 大城 | 8.908〜11.068 | 7.908〜10.068 | 2.160 |
| 何を運んでるの？ | 茂 | 16.667〜17.717 | 15.667〜16.717 | 1.050 |
| 病棟へのお届け物です | ハコブ | 18.267〜19.967 | 17.267〜18.967 | 1.700 |
| すみません、通ります（10 秒） | ハコブ | 23.167〜24.667 | 22.167〜23.667 | 1.500 |
| すみません、通ります（20 秒） | ハコブ | 33.167〜34.667 | 27.667〜29.167 | 1.500 |
| あ、ハコブくん | 寺島 | 45.567〜46.797 | 35.567〜36.797 | 1.230 |
| あ、ごめんね | 大城 | 47.347〜48.677 | 37.347〜38.677 | 1.330 |
- セリフの間：茂→ハコブ 0.550・（通ります/あ、ハコブくん）→あ、ごめんね 0.550 秒は決まりの中。
  寺島「大城さん」→大城「あ、寺島さん…」は 2.100 秒（0.4〜0.7 秒より長い）：大城さんが「大城さん」を聞いてから減速して止まり（1.6 秒）、体を回し始めてから話すため。
  ほかの間（止まって 3.5 秒・10 秒・20 秒・30 秒＋目を向ける）は依頼の時刻で決まる
- ⑩：止まって 3.5 秒で茂さんが顔を 25° 向けて聞く（16.333 秒から向き始め）・ハコブ「病棟へのお届け物です」の間は帯「お届け中」・答えの後に茂さんが 10° うなずき（1 回）・顔を戻して帯「お待ちしています」へ
- ⑨-2：30 秒で帯（黄）「通れません」＋⑤の困り顔・輪を⑤の待つ色（#F2C230）。30 秒＋1.2 秒で寺島さんがハコブくんの側へ顔を 30° 向け（0.4 秒）、戻して（0.4 秒）「あ、ハコブくん」
- 茂さんの口：話す間は Morita_Mouth_talk に替えた（茂さんの話す口はこの場面が初めて）

■ 7. 早回し（⑨-2 だけ・×4。右上に「早回し ×4　実際の時間 m:ss」。音は無し＝声の無い所だけ）
| 台本の秒 | 長さ | 動画の秒 |
| 26.567〜32.567 | 6.0 秒 | 25.567〜27.067 |
| 36.567〜42.567 | 6.0 秒 | 31.067〜32.567 |
（うなずきの後〜10 秒の声のあいだは 1 秒に満たないので早回しにしていない）

■ 8. 「立ち往生 1件（30 秒以上動けず、人が動かした）」の字（⑨-2・左下・3 秒）
- 字が出た 43.200 秒（動画 33.200）・動けない時間が 30 秒になった 43.167 秒 → 差 0.033 秒（0.1 秒以内）。⑨-1 には出していない

■ 9. カメラの切りかえ（台本の秒 → 動画の秒）
⑨-1：本番 0.000→0.000／ハコブくんの画面 13.067→12.067／本番 14.767→13.767／茂さんの顔 16.333→15.333／画面 18.133→17.133／本番 21.633→20.633／画面 23.033→22.033／大城さんの顔 24.833→23.833／本番 26.900→25.900（終わりまで）
⑨-2：本番 0.000→0.000／画面 13.067→12.067／本番 14.767→13.767／茂さんの顔 16.333→15.333／画面 18.133→17.133／本番 21.633→20.633／画面 23.033→22.033／本番 24.833→23.833／画面 33.033→27.533／本番 34.833→29.333／画面（通れません）43.067→33.067／本番 44.167→34.167／大城さんの顔 46.933→36.933／本番 49.033→39.033（終わりまで）
- 本番のカメラは 229 と同じ置き方（ハコブくんの後ろ・止まった車いすの 3 人が見える向き。見る点だけ 0.7 m 奥へ）

■ 10. 画面の変わり目（2 本とも、行き先・中身・数は一度も出ていない：使った絵は c235_wait_band「お待ちしています」・c235_deliv_band「お届け中」・c235_pass_band「通ります」・c235_stuck「通れません」＋困り顔だけ）
⑨-1：基本 → 13.367 お待ちしています → 18.267 お届け中 → 21.233 お待ちしています → 23.167 通ります → 40.700 目まで笑う顔（走り出し）→ 42.200 基本
⑨-2：… 23.167 通ります → 26.167 お待ちしています → 33.167 通ります → 36.167 お待ちしています → 43.167 通れません＋輪の待つ色 → 62.833 目まで笑う顔（輪も戻す）→ 64.333 基本
- 帯の絵は 228 の screen228.py と同じ描き方（同じ描き方で「お届け完了」を描くと c223_done_band.png と同じになることを確かめた）

■ 11. 確かめの表
必ず守る（229 と同じ＋依頼235）
| 項目 | ⑨-1 | ⑨-2 | 合否 |
| 当たったコマ（ハコブくんと物・車いす/茂さんと壁・ハコブくんと壁・看護師と車いす・手が握りの中・看護師と壁） | 0・0・0・0・0・0 | 0・0・0・0・0・0 | 合う |
| 寺島さんの当たり（壁/手すり・大城さん・車いす） | 0・0・0 | 0・0・0 | 合う |
| 手が握りから離れない（両手で握っている間） | 手のひらの中心と握りの面 0.0212 m・的とのずれ 0.0000 m | 同じ | 合う |
| 車輪の横すべり（後ろ・前） | 0.00001・0.00000 m/コマ | 同じ | 合う |
| 1 コマで骨が動く量（根の動きを除く） | 4.50 cm | 4.50 cm | 合う（6 cm 以内） |
| 足のすべり | 0.00 cm | 0.00 cm | 合う |
| 寄せる道：向きの最大 | 17.00° | 17.00° | 合う（30° まで） |
| 寄せる道：速さの最大（後ろの車軸） | 0.2802 m/秒 | 0.2803 m/秒 | 合う（0.3 まで） |
| 寄せる道：向きの変わる速さの最大 | 23.00°/秒 | 23.00°/秒 | 合う（25 まで） |
| 寄せる道：前へ進んだ距離・後ろへ下がった距離 | 0.8216・0.0540 m | 同じ | 合う（後ろへ 1.0 まで） |
| 足のせの前の端とハコブくんの前の端（止まってから走り出すまで）の最小 | 1.5682 m | 1.5681 m | 合う（0.6 m 以上） |
| 大城さんの顔（体から）の最大 | 29.42° | 29.42° | 合う（30° 以内） |
| 寺島さんの下がった距離 | 0.9963 m | 0.9963 m | 合う（1.0 m まで） |
| ハコブくんが通る時のすき間の最小 | 0.232 m（車いす） | 0.232 m | 合う（0.15 以上） |
| 動けない時間 | 27.533 秒 | 49.666 秒 | 合う（30 未満／30 以上） |
| 立ち往生の字と 30 秒のずれ | — | 0.033 秒 | 合う（0.1 以内） |
| 行き先・中身・数が画面に出ない | 出ない | 出ない | 合う |
できるだけ守る
| 項目 | 値 | 合否 |
| 止まった時の足のせとのあいだ | 2.400 m | 合う（2.0〜3.0） |
| 茂さんが聞くのは止まって 3〜4 秒 | 3.500 秒 | 合う |
| 茂さんの顔の向き・うなずき | 25.0°・10.0° 1 回 | 合う（20〜30°） |
| 寺島さんが気づく顔の向き（⑨-2） | 30.00° | 合う（20〜35°） |
| 「通れません」から寺島さんが向くまで（⑨-2） | 1.2 秒 | 合う（1.0〜1.5） |
| セリフの間 | 寺島「大城さん」→大城「あ、寺島さん…」2.100 秒・ほか 0.550 秒 | 一部外れ（1 か所） |
| 手すりとのすき間 | 車いす/茂さん 0.174 m・看護師 0.122 m・ハコブくん 0.053 m | 参考 |

■ 12. 撮ったもの（声あり 2 本・真上 2 本）
| 動画 | 長さ | md5 |
| closeup235_stop_voice.mp4（⑨-1） | 52.067 秒・1562 コマ | 7a78ab3bcfb1e59e2131c18c58b5d209 |
| closeup235_stop_voice_top.mp4 | 52.067 秒 | 55e65683b3a2094ab7ec70eefe8a243c |
| closeup235_stop_stuck.mp4（⑨-2） | 65.200 秒・1956 コマ（早回し ×4 の所を含む） | 3258a01cb42af781efe00dcc8045b04d |
| closeup235_stop_stuck_top.mp4 | 65.200 秒（同じコマ） | 31ffbcd9f9fd1757d2a5d4ccff0a5301 |
- 終わり：ハコブくんが物の一番後ろを通り過ぎてから 2.5 秒
- 真上の動画：234 の描き方（ものごとに 半径 6 画素の閉じる処理→中の穴埋めをした外形の中に床の線を描かない・重ねる順は コマ→床の線→通った跡→印→左上の字）。
  もの：ハコブくん・車いすと茂さん・大城さん・寺島さんを別々に写した型。大城さんが両手で握りにのせている間（台本 c235.grip_both）は大城さんと車いす・茂さんを 1 つのものとして埋めた（答え）。
  外形の中に残った線の画素：2 本とも 0。床の線は 真ん中 0.00・寄せたあと +0.42・ハコブくんのふだん −0.33（230 の +0.28 は⑨に無いので描いていない）。カメラは 230 の動かない真上のカメラ（closeup230_top.json）
- 静止画（stills/、場面名を頭に付けた）：s01 寺島さんが声をかける・s02 3 人で話す・s03/s04 ハコブくんが止まった（本番・寄り）・s05 茂さんが聞く（寄り）・s06 お届け中（寄り）・s07 通ります（寄り）・
  ⑨-1 s08 大城さんが気づく（大城さんの顔）・⑨-2 s08_toremasen 通れません（寄り）と s08_stuck_label 立ち往生 1件（動画から取り出したコマ）・s09 寄せる所（本番・真上）・s10 ハコブくんが通る
- 撮り方：Unity は 13 分ほど動くと止められた（2 回とも Killed: 9。メモリは 1 GB ほどで増えていない。ライセンスの終わりの記録の直後）ので、台本の秒で区切って撮り（決まった動きなので区切りをつなげても同じ）、
  確かめの値は区切らずに最後まで回した回の値を使った。⑨-1 は右手の握り直しを直した後に 8.4〜28.0 秒を撮り直した（ほかの所は右手の値が同じ）。
  つなぎの確かめ：今の台本で 30.0 秒のコマを撮り直して、つないだコマと比べた → 本番 25 画素だけ違う（差の最大 7/255）・真上 1 画素（差 1）・型 0・もの別の型 0。
  8.367 秒のコマ（右手を上げ始める最初のコマ）は前の台本で撮っていたので、撮り直したコマに替えて動画を作り直した（out/splice_check/）

■ 13. 声（233 の audio/ をそのまま使った・−20 LUFS・48 kHz）
| 名前 | 誰 | セリフ | Voice ID |
| V1_terashima_oshirosan | 寺島 | 大城さん | yWM6Fym2UxDGZqWRoGLB |
| V2_oshiro_otsukare | 大城 | あ、寺島さん。おつかれさま | PrFsT9a2iZebpuiWVeug |
| M1_morita_nani | 茂 | 何を運んでるの？ | ydyMD3g4SbEeNpF0wahP（田中先生の声） |
| H1_hakobu_otodoke | ハコブ | 病棟へのお届け物です | gWJpc8whMBqnF7Y0kc9f |
| H2_hakobu_toorimasu | ハコブ | すみません、通ります | gWJpc8whMBqnF7Y0kc9f |
| T2_terashima_hakobukun | 寺島 | あ、ハコブくん | yWM6Fym2UxDGZqWRoGLB |
| V8_oshiro_gomenne | 大城 | あ、ごめんね | PrFsT9a2iZebpuiWVeug |

■ 出力の場所（写した後に md5 を確かめた。KIOXIA 80 ファイル（出力 68・道具と計算 12）・iCloud 27 ファイル、すべて同じ。報告の写しも同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup235/
  動画 4 本・stills/（23 枚）・stills_check/・audio/（mix235_stop_voice.wav・mix235_stop_stuck.wav）・
  out/splice_check（つなぎの確かめのコマ）・out/stop_voice・out/stop_stuck（check235.txt・events235.txt・frames235.csv・bones235.csv・feet235.csv・wc235.csv・top235.csv・an235_*.txt・vmap235_*.json・per235_*.csv・unity の記録）・
  geo/（feas235.txt・turn235.txt・path235.json）・tools/（feas235.py・turn235.py・make_script235.py・screen235.py・make235.py・an235.py・run235.sh・run235b.sh・Closeup235.cs の写し）・report235.txt
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup235/（動画 4 本・stills/ 23 枚）

■ check-in
- cs:166（12 件：closeup235_script.json・Editor/Closeup235.cs・Textures/c235_wait_band・c235_deliv_band・c235_pass_band・c235_stuck の png と .meta）。保留は無し

■ 決めてほしいこと
1. ハコブくんの走り出しの決まりを足した：「前の物が 0.5 秒動かず、寄った位置（x −0.4643）で 0.15 m 以上あけて通れる時に走り出す」。0.5 秒と、この決め方でよいか（229 の決まりには、止まった物が寄せ終わった時に走り出す所が無かった）
2. 寄せる道の計算で、手すりと 0.05 m・寺島さんと 0.05 m の余りを置いた（決まりに無い値）。この値でよいか
3. 寺島さん「大城さん」→大城さん「あ、寺島さん。おつかれさま」の間が 2.10 秒（0.4〜0.7 秒より長い）。大城さんが止まって体を回し始めてから話す形にしたため。このままでよいか、止まる前に話し始める形にするか
4. 寺島さんはハコブくんが通り過ぎた後も手すり沿いに立ったまま（戻らない）。このままでよいか

判定：一部外れて撮った
```

### 依頼236 の報告（report236.txt）

```text
依頼236：⑧の真上の動画（依頼234）で、大城さんと車いすのあいだから点線が見えるのを消した（2026-11-17）

依頼234 の依頼文と報告・make234.py・Editor/Closeup234.cs を読んでから始めた。
コードは Editor/Closeup234.cs を写して Editor/Closeup236.cs にし、出力の名前（-c236*・*236.csv など）だけ変えた（撮るものは 234 と同じ）。
重ねる道具は make234.py を写して make236.py にし、写した先で変えた。台本は 229 の closeup229_script.json、カメラは 230 の closeup230_top.json をそのまま読む（写していない・変えていない）。
触ったのは Assets/ServiceSim/Closeups/Editor/Closeup236.cs と .meta（新しい 2 ファイル）だけ。234 の道具・コード・出力、Models/、病院の1日の場面、配膳の場面、共通の部品、Packages、実行ファイルには触っていない。
Mixamo の FBX は使っていない・写していない・check-in していない。場面のファイルは保存していない。

結論：⑧ の真上の動画を作り直した。確かめはすべて合った。大城さんと車いす（茂さんを含む）のあいだで囲まれた床に見えていた線は、全部のコマで 0 になった。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:166 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み

■ 埋め方
- Unity（Closeup236.cs）：234 と同じ真上のコマ・232 の体の型・もの別の型（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん）を撮り直した。
  770 コマ全部で、3 種類のコマとも 234 とバイトまで同じ（違うコマ 0）。frames・bones・feet・wc・top の表、check、カメラの写し方も 234 と同じファイル（＝動きは変わっていない）
- 重ねる（make236.py）：
  ① 大城さんが握りに手をのせているコマを、frames236.csv の両手の「手のひらと握りの距離」が 228 の握った形の値 0.0212 m から 1 mm 以内のコマとした。
     この動画では 770／770 コマ全部が握ったまま（左右とも 0.0212〜0.0212 m）なので、全部のコマで 1 つのものにした
  ② そのコマでは、もの別の型の緑と青を合わせて 1 つのものとし、半径 6 画素（3.20 cm）の円で「閉じる処理」→ 中の穴埋め（答え 2 のとおり 234 と同じ半径）。
     ハコブくんは 234 と同じく別のもの。234 でものごとに足した所も残す（236 の外形は 234 の外形を必ず含む）
  ③ 外形の型は 234 と同じ作り方（体の部品が写っている所は 232 の型・足した所は 255）。この型で床の線（中心の線・点線・線の端の字）を消す
- 手が握りから離れるコマがあれば、そのコマは 234 と同じくものごとに埋める（この動画には無い）
- 動き・カメラ・線・跡・印・字・重ねる順（床と体 → 床の線 → 跡 → 印 → 左上の字）は 234 のまま

■ 確かめ
| 項目 | 234 | 236 | 合否 |
| 大城さんと車いすをまとめた外形の中（型 255）に床の線の画素 | （ものごとの外形なので、あいだに見える） | 全部のコマ（770）で 0（合計 0） | 合う |
| もののあいだで囲まれた床に見える線（between234.py と同じ数え方） | 400／770 コマ・合計 70,972 画素・1 コマの最大 644 画素（動画 20.467 秒） | 0／770 コマ・合計 0 | 合う |
| 外形の中（全部のもの・型 255）に残る線 | 0 | 0 | 合う |
| 234 の動画で、236 が新しく埋めた所に見えていた線 | 408／770 コマ・合計 74,559 画素・1 コマの最大 682 | （消えた） | 参考 |
| 外形のふくらみの最大（外形のふちの足した画素の、体の部品の写った所からの距離） | 車いすと茂さん 6.00 画素（3.20 cm）・大城さん 5.39 画素（2.87 cm）・ハコブくん 1.00 画素（0.53 cm） | 大城さんと車いす 6.00 画素（3.20 cm。234 の車いすと同じ所・コマ 341）・ハコブくん 1.00 画素（0.53 cm） | 合う（半径 6 画素を超えない） |
| 1 つにして新しく足した所 | — | 1 コマの最大 831 画素（コマ 644）。そのうち外形のふちにある画素の体からの距離の最大 5.00 画素（2.67 cm）。新しく足した画素はどれも車いすと茂さんから 11.55 cm 以内・大城さんから 8.01 cm 以内（＝大城さんと押し手のあいだだけで、体の外へはふくらんでいない） | 合う |
| 体の無い所（236 の型 0）で 234 と違う画素 | — | 合計 0・1 コマの最大 0 | 合う |
| 234 の型 0 で、236 が新しく埋めた所の外で 234 と違う画素 | — | 0（画面全体で違う画素は 398 コマ・合計 55,513 で、すべて新しく埋めた所の中） | 合う |
| 236 の方が 234 より床の線が濃い画素 | — | 0 | 合う |
| 234 の重ね方を作り直すと 234 の動画と同じ | — | make236.py が同時に作った closeup236_as234.mp4 の md5 b782b184d7a55f8b2cd0e5c3b7879a22 は 234 の closeup234_yield_top.mp4 と同じ（＝上の「234 と比べた値」は本当の 234 と比べている） | 合う |
| 体のふちのなめらかな所（0<型<255）に薄く残る線 | 1 コマの最大 987 | 1 コマの最大 987（234 と同じ扱い） | 参考 |
| 動画の長さ | 25.667 秒・770 コマ | 25.667 秒・770 コマ・1920×1080・30 コマ/秒 | 合う |
| 寄りの静止画（上 234・下 236、234 と同じ範囲を 2.5 倍） | このコマのもののあいだの線（画面全体）8.000 秒 0・12.000 秒 117・16.000 秒 150・21.500 秒 578 | 0・0・0・0（まとめた外形の中に残る線も 0・0・0・0） | 合う |

途中で 1 回作り直した：はじめは緑＋青をまとめて埋めた所だけを使ったため、大城さんの体のふちのなめらかな所で 234 より薄い線がわずかに戻った（ふちの線の最大 987→995）。
234 でものごとに足した所も残すように直して作り直し、「236 の方が 234 より線が濃い画素 0」を確かめに足した。上の表は直した後の値。

■ 撮った動画（音なし）
- closeup236_yield_top.mp4：25.667 秒・770 コマ（md5 8e11c54ea385811eebdc04e2d26bfd35・1,333,960 バイト）
- 寄りの静止画（stills_zoom/、上 234・下 236）：
  z_08.000s_f270.png b07869923fad7faf14914b71b777c8e4・z_12.000s_f390.png 38712ca52de1904df67d2b8a242908be・
  z_16.000s_f510.png fb9ffa5fb3807b09b8861e51fa5b3562・z_21.500s_f675.png 87709e807a6e1c978ba7796a052f6551
- 234 と同じ時刻の静止画 3 枚（stills/、KIOXIA だけ）：s1_shift_start fd96a6d7d37eeabd27a1cdc50447f146・s2_shift_end 00e87edd4b30b8c1b1df788106d8461a・s3_last 5dee75ede4d2a31148bf6f131ca0dee9

■ 出力の場所（写した後に md5 を確かめた。すべて同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup236/
  closeup236_yield_top.mp4・stills_zoom/（4 枚）・stills/（3 枚）
  out/：check236_top.txt（確かめ）・per236.csv（コマごとの握り・外形の中の線・まとめた外形の中の線・ふちの線・もののあいだの線 234/236・234 で新しく埋めた所に見えていた線・234 との差・足した画素）・
        closeup236_as234.mp4・top236.csv・top236_cam.json・frames236.csv・bones236.csv・feet236.csv・wc236.csv・check236.txt・events236.txt・unity.log・make236_out.txt
  tools/：make236.py・run236.sh・Closeup236.cs の写し
  report236.txt（この報告の写し）
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup236/（closeup236_yield_top.mp4・stills_zoom/ 4 枚）
- コマ（真上・型・もの別の型 各 770 枚）は /tmp/c236/full/frames にあり、KIOXIA には写していない

■ check-in
- cs:167（2 件：Closeups/Editor/Closeup236.cs と .meta を追加）。保留は無し

■ 決めてほしいこと
1. 「握りに手をのせている間」を、両手の手のひらと握りの距離が 228 の握った形の値 0.0212 m から 1 mm 以内のコマとした。この動画では全部のコマが当たるので結果には効かないが、手を離す場面を作るときのためにこの決め方でよいか
2. 232 の決めてほしいこと 3（230・229・228 のもの）は答えを受けていないので、そのまま

判定：合格
```

### 依頼237 の報告（report237.txt）

```text
依頼237：⑨「車いすが廊下の真ん中で止まる」（依頼235）の茂さんとハコブくんのやり取りを 2 本で分けて作り直し、「通れません」の顔をふだんの大きさにし、横を通る時のお礼を足して撮った（2026-11-17）

依頼235 の依頼文と報告、235 の台本・make_script235.py・Editor/Closeup235.cs・2 本の動画（静止画）を見てから始めた。
写して closeup237_script.json（make_script237.py が作る）・Editor/Closeup237.cs・tools（make237.py・an237.py・screen237.py・run237.sh・run237b.sh）を作り、写した先で変えた。
235 の台本・コード・出力には触っていない。触ったのは Assets/ServiceSim/Closeups/ の中の新しいファイルだけ
（closeup237_script.json・Editor/Closeup237.cs・Textures/c237_stuck_band.png・face237_trouble_albedo.png・face237_trouble_emission.png と、それぞれの .meta）。
Models/、病院の1日の場面、配膳の場面、共通の部品（CloseupDirector.cs・CloseupNurse.cs を含む）、Packages、実行ファイルには触っていない。場面のファイルは保存していない。
Mixamo の FBX は使っていない・写していない・check-in していない。場面の名前は 235 と同じ stop_voice・stop_stuck のまま（まばたきの種が同じ）。

結論：依頼のとおり 2 本を作って撮った。決まりはすべて守れた（当たったコマ 0・動けない時間 ⑨-1 29.833 秒＜30／⑨-2 49.666 秒≧30・「通れません」の顔は画素で同じ大きさ・⑨-1 の 7・8 の声は 2 つとも横にいる間に終わった・行き先/中身/数は出ていない）。
私が決めた所（下の「決めてほしいこと」）がある：茂さんが大城さんのほうへ向く向き（+x の側）・通る時のカメラの切りかえ・新しいセリフの間を 0.4 秒にしたこと・走り出した時の目まで笑う顔をやめたこと・早回しの区間。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は cs:167 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 最新の check-in：cs:167（依頼236）

■ 1. 「通れません」の顔
- 235 の c235_stuck.png（帯の下を黒で塗り、⑤の小さな困り顔を描いた絵）をやめ、帯（黄 #F2C230）「通れません」だけの絵 c237_stuck_band.png を重ねる形にした（ほかの帯と同じ。帯の行は c235_stuck.png と画素まで同じ・帯の下は透明）
- 顔の板の絵に、235 の困り顔（hakobu.py の表情集 trouble：目 open・困り眉・口 frown）を、ふだんの大きさで描いた face237_trouble_{albedo,emission}.png を作った（tools/screen237.py。218 の顔の板の作り方：もとの顔の絵の口を消して frown の口・目の上に困り眉。目はもとの絵のまま＝目の白い画素は もと 7619/7616 と同じ）
- 確かめ（画素で比べる・tools/facesize237.py、223 の測り方）：寄り（screen_close）・ハコブくんが止まっている間のコマの目
| 画面 | コマ | 目の高さ | 目の幅 | 2 つの目の中心の間 | 2 つの目の面積 |
| 「通れません」（⑨-2） | 30 | 258.0 | 124.0 | 553.0 | 56917 |
| 「通ります」（⑨-2／⑨-1） | 100／50 | 258.0 | 124.0 | 553.0 | 56917 |
| 「お待ちしています」（⑨-2／⑨-1） | 113／46 | 258.0 | 124.0 | 553.0 | 56917 |
| 基本（帯なし） | 9 | 258.0 | 124.0 | 553.0 | 56916〜56919 |
| 参考：235 の「通れません」の静止画 | 1 | 78.0 | 37.5 | 141.6 | 5188 |
→ 「通れません」の顔は、ほかの帯の時の顔と同じ大きさ（画素で同じ）

■ 2. やり取り（235 の⑩は 2 本とも消した）
⑨-1（closeup237_stop_voice.mp4）
- 4：止まって 10 秒（23.167）でハコブ「すみません、通ります」・帯「通ります」
- 5：声が終わって 0.05 秒から茂さんが顔を −40°（+x の側＝大城さんが体を向けている側）へ 0.45 秒で向け、0.4 秒あけて「おい、ロボットさんが通るって」（帯のまま）
- 6：235 のとおり大城さんが気づいて振り返り（顔をハコブくんへ・体を戻して握り直す）「あ、ごめんね」→ 寺島さんが下がる → 寄せる。茂さんは「あ、ごめんね」の後に顔を前へ戻す
- 7：ハコブくんが走り出し（43.000・画面は「基本」）、車いすに近づいた所で茂さんが顔をハコブくんへ 38°（声の真ん中の時刻のハコブくんの画面の向き）向けて「何を運んでるんだい？」
  茂さんの声は走り出しの後（走り出しから 3.93 秒）に始めた。走り出しの直前にはしていない
- 8：ハコブくんは止まらずに「病棟へのお届け物です。ありがとうございます」：帯（ミント）「お届け中」→「ありがとうございます」の始まり（50.467）から目まで笑う顔（224 と同じ。口は声に合わせて動く）1.5 秒 → 「基本」
- 9：答えの後 0.25 秒で茂さんが 10° うなずき（1 回）、0.3 秒後に顔を前へ戻す
- 動けない時間 29.833 秒（30 秒未満）。235 は 27.533 秒で、茂さんのセリフ（2.06 秒）が入った分のびた。30 秒未満にするため、新しいセリフの間は 0.4 秒（235 の 0.4〜0.7 の短いほう）にした
⑨-2（closeup237_stop_stuck.mp4）
- 4：10 秒・20 秒で「すみません、通ります」（235 のとおり。看護師 2 人は気づかない）
- 5：20 秒の声が終わって 2.5 秒（37.167）で茂さんが顔をハコブくんへ 25°（235 の⑩と同じ）向けて「あんたも待たされてるのかい」
- 6：0.4 秒あけてハコブ「はい、お待ちしています」（帯「お待ちしています」）。答えの後 0.3 秒で茂さんは顔を前（0°＝5 の前の向き）へ戻す
- 7：30 秒（43.167）で帯（黄）「通れません」＋困り顔（ふだんの大きさ）＋輪の待つ色 → 235 のとおり 寺島「あ、ハコブくん」→ 大城「あ、ごめんね」→ 寄せる。走り出し（62.833）で「基本」
- 8：車いすの横にいる間の真ん中でハコブ「ありがとうございます」＋目まで笑う顔 1.5 秒（69.067〜70.567）→「基本」。声の後 0.25 秒で茂さんが 10° うなずく（1 回）
- 5・6 は 1 倍。早回し（×4）は 10〜20 秒の間（235 のまま 26.567〜32.567）だけ。「6 のあとから 30 秒の手前まで」は、235 と同じ決め方（動きが終わって 0.6 秒後〜30 秒の 0.6 秒前・1 秒以上の時だけ）で 42.017〜42.567 の 0.55 秒になり、早回しにしていない（茂さんが顔を戻し終わるのが 41.417 のため。決めてほしいことの 4）
- 動けない時間 49.666 秒（30 秒以上）
- 235 にあった「走り出した時の目まで笑う顔 1.5 秒」は 2 本ともやめ、走り出しは「基本」にした（目まで笑う顔はお礼の時だけ。決めてほしいことの 3）

■ 3. セリフごとの時刻（台本の秒・動画の秒＝台本の秒−1.0、⑨-2 は早回しの分を引く）
⑨-1（54.333 秒・1630 コマ）
| セリフ | 誰 | 台本の秒 | 動画の秒 | 声の長さ |
| 大城さん | 寺島 | 6.107〜6.808 | 5.107〜5.808 | 0.700 |
| あ、寺島さん。おつかれさま | 大城 | 8.908〜11.068 | 7.908〜10.068 | 2.160 |
| すみません、通ります | ハコブ | 23.167〜24.667 | 22.167〜23.667 | 1.500 |
| おい、ロボットさんが通るって | 茂 | 25.067〜27.127 | 24.067〜26.127 | 2.060 |
| あ、ごめんね | 大城 | 27.527〜28.857 | 26.527〜27.857 | 1.330 |
| 何を運んでるんだい？ | 茂 | 46.930〜48.050 | 45.930〜47.050 | 1.120 |
| 病棟へのお届け物です。ありがとうございます | ハコブ | 48.450〜51.430 | 47.450〜50.430 | 2.980（「ありがとうございます」は 50.480 から）|
⑨-2（69.667 秒・2090 コマ）
| セリフ | 誰 | 台本の秒 | 動画の秒 | 声の長さ |
| 大城さん | 寺島 | 6.107〜6.808 | 5.107〜5.808 | 0.700 |
| あ、寺島さん。おつかれさま | 大城 | 8.908〜11.068 | 7.908〜10.068 | 2.160 |
| すみません、通ります（10 秒） | ハコブ | 23.167〜24.667 | 22.167〜23.667 | 1.500 |
| すみません、通ります（20 秒） | ハコブ | 33.167〜34.667 | 27.667〜29.167 | 1.500 |
| あんたも待たされてるのかい | 茂 | 37.167〜38.677 | 31.667〜33.177 | 1.510 |
| はい、お待ちしています | ハコブ | 39.077〜40.517 | 33.577〜35.017 | 1.440 |
| あ、ハコブくん | 寺島 | 45.567〜46.797 | 40.067〜41.297 | 1.230 |
| あ、ごめんね | 大城 | 47.347〜48.677 | 41.847〜43.177 | 1.330 |
| ありがとうございます | ハコブ | 69.053〜70.113 | 63.553〜64.613 | 1.060 |
- セリフの間：通ります→おい 0.400・おい→あ、ごめんね 0.400・何を運んでる→病棟へ 0.400・あんたも→はい 0.400（20 秒の声の終わり→あんたも 2.500）・あ、ハコブくん→あ、ごめんね 0.550（235 のまま）・大城さん→あ、寺島さん 2.100（235 のまま。4 の答えでこのまま）

■ 4. ハコブくんが車いすの横にいる間と、⑨-1 の 7・8 の声（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで。Unity の中で毎コマ測った）
| | 横にいる間 | 声 | 横にいる間との関係 |
| ⑨-1 茂「何を運んでるんだい？」 | 48.000〜51.500 | 46.930〜48.050 | 横に来る 1.070 秒前に始まり、横に来て 0.050 秒で終わる（近づいた所で聞く） |
| ⑨-1 ハコブ「病棟へのお届け物です。ありがとうございます」 | 48.000〜51.500 | 48.450〜51.430 | 全部が横にいる間（始まり＋0.450・終わり−0.070） |
| ⑨-2 ハコブ「ありがとうございます」 | 67.833〜71.333 | 69.053〜70.113 | 全部が横にいる間（真ん中） |
- 2 つの声と間（1.12＋0.4＋2.98＝4.50 秒）は横にいる間（3.50 秒）より長いので、2 つとも横にいる間に「終わる」ように置いた（茂さんの声の始まりは横に来る前。走り出しの後なので「走り出しの直前」にはしていない）
- 時刻は 2 回まわして決めた（1 回目の Unity で走り出し・横にいる間を測り、2 回目の台本に入れた。2 回目も同じ値：⑨-1 43.000・48.000〜51.500、⑨-2 62.833・67.833〜71.333）

■ 5. 茂さんの顔の向き・うなずき（frames237.csv の m_yaw・m_nod）
| | 顔の向きの最大 | うなずき |
| ⑨-1 | 大城さんのほうへ −40.0°（30〜45°）・ハコブくんへ 38.0° → 最大 40.0° | 10.0°・1 回 |
| ⑨-2 | ハコブくんへ 25.0°（20〜30°） | 10.0°・1 回 |
- 茂さんの 1 コマの骨の動き（車いすから）：⑨-1 0.84 cm・⑨-2 0.52 cm
- 茂さんの口：話す間は Morita_Mouth_talk（235 と同じ）

■ 6. 画面の変わり目（2 本とも、行き先・中身・数は一度も出ていない）
使った絵は c235_wait_band「お待ちしています」・c235_pass_band「通ります」・c235_deliv_band「お届け中」・c237_stuck_band「通れません」（帯だけ）と、顔の板の face218_*（基本・話す口）・face224_happy_*／face218_happy（目まで笑う顔）・face237_trouble（困り顔）だけ。どれにも行き先・中身・数の字は無い
⑨-1：0.000 基本 → 13.367 お待ちしています → 23.167 通ります → 43.000 基本（走り出し）→ 48.433 お届け中 → 50.467 目まで笑う顔 → 51.967 基本
⑨-2：0.000 基本 → 13.367 お待ちしています → 23.167 通ります → 26.167 お待ちしています → 33.167 通ります → 36.167 お待ちしています → 43.167 通れません＋困り顔＋輪の待つ色 → 62.833 基本（輪も戻す）→ 69.067 目まで笑う顔 → 70.567 基本
- 「病棟へのお届け物です」は声だけ（画面には出していない）

■ 7. カメラの切りかえ（台本の秒 → 動画の秒）
⑨-1：本番 0.000→0.000／画面 13.067→12.067／本番 14.767→13.767／画面 23.033→22.033／茂さんの顔 24.833→23.833／大城さんの顔 27.267→26.267／本番 29.200→28.200／画面 48.300→47.300／本番 52.133→51.133（終わりまで）
⑨-2：本番 0.000→0.000／画面 13.067→12.067／本番 14.767→13.767／画面 23.033→22.033／本番 24.833→23.833／画面 33.033→27.533／本番 34.833→29.333／茂さんの顔 36.833→31.333／画面 38.933→33.433／本番 40.933→35.433／画面（通れません）43.067→37.567／本番 44.167→38.667／大城さんの顔 46.933→41.433／本番 49.033→43.533／画面 68.900→63.400／本番 70.700→65.200（終わりまで）
- 235 の⑩の切りかえの作り（茂さんが話す時は茂さんの顔・ハコブくんが話す時は画面の寄り）を新しいやり取りに使った
- 通る時（⑨-1 の 8・⑨-2 の 8）は、本番のカメラはハコブくんの後ろなので画面が見えない。235 の作り（ハコブくんが話す時は画面の寄り）で、ハコブくんの声の 0.15 秒前から目まで笑う顔の終わり＋0.15 秒まで画面の寄り（ハコブくんに付いて動く）にした。
  ⑨-1 の 7（茂さん「何を運んでるんだい？」）は本番のまま（茂さんの顔のカメラはハコブくんの通る所にあるため使えない）（決めてほしいことの 2）

■ 8. 確かめの表
必ず守る
| 項目 | ⑨-1 | ⑨-2 | 合否 |
| 当たったコマ（ハコブくんと物・車いす/茂さんと壁・ハコブくんと壁・看護師と車いす・手が握りの中・看護師と壁） | 0・0・0・0・0・0 | 0・0・0・0・0・0 | 合う |
| 寺島さんの当たり（壁/手すり・大城さん・車いす） | 0・0・0 | 0・0・0 | 合う |
| 手が握りから離れない | 手のひらの中心と握りの面 0.0212 m・的とのずれ 0.0000 m | 同じ | 合う |
| 車輪の横すべり（後ろ・前） | 0.00001・0.00000 m/コマ | 同じ | 合う |
| 1 コマで骨が動く量（根の動きを除く） | 4.50 cm | 4.50 cm | 合う（6 cm 以内） |
| 足のすべり | 0.00 cm | 0.00 cm | 合う |
| 寄せる道（向き・速さ・向きの変わる速さ・前へ・後ろへ） | 17.00°・0.2803 m/秒・23.00°/秒・0.8216・0.0540 m | 同じ | 合う（235 と同じ値） |
| 足のせの前の端とハコブくんの前の端の最小 | 1.5682 m | 1.5681 m | 合う |
| 大城さんの顔（体から）の最大 | 29.42° | 29.42° | 合う |
| 寺島さんの下がった距離 | 0.9962 m | 0.9963 m | 合う |
| ハコブくんが通る時のすき間の最小 | 車いす 0.232・茂さん 0.318・大城さん 0.287・寺島さん 0.645 m | 同じ | 合う |
| 動けない時間 | 29.833 秒 | 49.666 秒 | 合う（30 未満／30 以上） |
| 立ち往生の字と 30 秒のずれ | — | 0.033 秒（字 43.200・30 秒 43.167） | 合う |
| 「通れません」の顔の大きさ | — | ほかの帯と画素で同じ（上の 1） | 合う |
| ⑨-1 の 7・8 の声が横にいる間に終わる | 茂 48.050・ハコブ 51.430（横 48.000〜51.500） | — | 合う |
| 行き先・中身・数が画面に出ない | 出ない | 出ない | 合う |
できるだけ守る
| 項目 | 値 | 合否 |
| 茂さんの顔の向き | ⑨-1 大城さんへ 40°（30〜45）・⑨-2 25°（20〜30） | 合う |
| うなずき | 10°・1 回（2 本とも） | 合う |
| ⑨-2 の 5 は 20 秒の声が終わってから 2〜4 秒 | 2.500 秒 | 合う |
| 目まで笑う顔 | 1.5 秒（2 本とも）・⑨-1 は「ありがとうございます」の始まりと同じコマ | 合う |
| セリフの間 | 新しい所 0.400 秒・235 のままの所 0.550／2.100 秒 | 235 のとおり（2.10 秒は答え 3 でこのまま） |
| 止まった時の足のせとのあいだ | 2.400 m | 合う |

■ 9. 撮ったもの（声あり 2 本・真上 2 本）
| 動画 | 長さ | md5 |
| closeup237_stop_voice.mp4（⑨-1） | 54.333 秒・1630 コマ | 5b1bb9e07de0fd58f26ff6a6bf9c8c42 |
| closeup237_stop_voice_top.mp4 | 54.333 秒 | d782be0c2e6e87c6d8155d8bdba00584 |
| closeup237_stop_stuck.mp4（⑨-2） | 69.667 秒・2090 コマ（早回し ×4 の所を含む） | 3226da506a264506cbd94dcef9f1e27f |
| closeup237_stop_stuck_top.mp4 | 69.667 秒 | a968f846ecfd095ae1e25c34f73be2a4 |
- 終わり：ハコブくんが物の一番後ろを通り過ぎてから 2.5 秒（235 のまま）
- 真上の動画：235 の描き方のまま（make237.py は make235.py の名前だけを替えた写し）。外形の中に残った線の画素 2 本とも 0
- 静止画（stills/、場面名を頭に付けた。235 と同じ並び＋足した所。235 の s05・s06 は⑩の絵なので無い）：
  s01 寺島さんが声をかける・s02 3 人で話す・s03/s04 ハコブくんが止まった・s07 通ります・
  ⑨-1 s08 大城さんが気づく・⑨-2 s08_toremasen 通れません（寄り）と s08_stuck_label（動画から取り出したコマ）・s09 寄せる所（本番・真上）・s10 ハコブくんが通る、
  足したもの：⑨-1 s11_morita_tooru（5）・s12_morita_nanida（7）・s13_otodokechu・s13_arigato_happy・s13_arigato_main（8）／⑨-2 s11_morita_matasare（5）・s13_arigato_happy・s13_arigato_main（8）
  stills_check/ に握りの確かめと c237_face_compare.png（もとの顔・困り顔の顔の板・235 の通れません）
- 撮り方：確かめの値は区切らずに最後まで回した回（out/check_full_*）。コマは台本の秒で区切って撮った（1 回 3〜8 分。235 のような途中で止められることは無かった）。
  区切って撮った回の frames237.csv・bones237.csv・wc237.csv・top237.csv・feet237.csv・check237.txt は、区切らない回と同じ（md5。frames237.csv は通る時のカメラの切りかえを足した所の cam の列だけ違う）
  通る時のカメラの切りかえは撮った後に足したので、⑨-1 は 47 秒から終わりまでを撮り直した（ほかの所はカメラが同じ）。⑨-2 は 56 秒からの区切りが足した後の台本

■ 10. 声（−20 LUFS・48 kHz。tts_eleven.py --try・eleven_v4・種 7・道具の既定の設定＝233 と同じ作り）
| 名前 | 誰 | セリフ | Voice ID | 長さ | 元 → 直し |
| M2_morita_tooru | 茂 | おい、ロボットさんが通るって | ydyMD3g4SbEeNpF0wahP | 2.240 秒 | −14.8 → −5.2 dB |
| M3_morita_nanida | 茂 | 何を運んでるんだい？ | ydyMD3g4SbEeNpF0wahP | 1.520 秒 | −18.2 → −1.8 dB |
| M4_morita_matasare | 茂 | あんたも待たされてるのかい | ydyMD3g4SbEeNpF0wahP | 1.840 秒 | −17.0 → −3.0 dB |
| H3_hakobu_otodoke_arigato | ハコブ | 病棟へのお届け物です。ありがとうございます | gWJpc8whMBqnF7Y0kc9f | 3.120 秒 | −17.1 → −2.9 dB |
| H4_hakobu_omachi | ハコブ | はい、お待ちしています | gWJpc8whMBqnF7Y0kc9f | 1.600 秒 | −18.2 → −1.8 dB |
| H5_hakobu_arigato | ハコブ | ありがとうございます | gWJpc8whMBqnF7Y0kc9f | 1.280 秒 | −16.4 → −3.6 dB |
- ほかのセリフは 233 の声をそのまま（V1・V2・H2・T2・V8）。233 の「何を運んでるの？」「病棟へのお届け物です」は使っていない
- 読みの確かめ（233 と同じ MFCC-DTW）：H3 の声と ひらがな「びょうとうへの…」0.741・「びょういんへの…」0.948 → びょうとう に近い。耳では聞いていない

■ 出力の場所（写した後に md5 を確かめた）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261117_closeup237/
  動画 4 本・stills/・stills_check/・audio/（mix237_*.wav・voice/ 新しい声 6 つの mp3・wav と lufs.txt・reading_check/）・
  out/（stop_voice・stop_stuck・check_full_*：check237.txt・events237.txt・frames237.csv・bones237.csv・feet237.csv・wc237.csv・top237.csv・an237_*.txt・vmap237_*.json・per237_*.csv・facesize237_*.csv・unity の記録、times.json）・
  geo/path235.json（235 の道の写し）・tools/（make_script237.py・screen237.py・make237.py・an237.py・facesize237.py・run237.sh・run237b.sh・batch_check.sh・batch_render.sh・Closeup237.cs の写し）・report237.txt
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup237/（動画 4 本・stills/）

■ check-in
- cs:168（10 件：closeup237_script.json・Editor/Closeup237.cs・Textures/c237_stuck_band.png・face237_trouble_albedo.png・face237_trouble_emission.png と .meta）。保留は無し

■ 決めてほしいこと
1. ⑨-1 の 5 で茂さんが向く側：大城さんは真後ろにいるので、大城さんが体を向けている +x の側（寺島さんの側）へ −40° にした。寄りの絵では寺島さんを見ているようにも見える。反対の側（ハコブくんの側）がよいか
2. 通る時のカメラ：本番のカメラ（235 のまま）ではハコブくんの画面が見えないので、ハコブくんが話す時は画面の寄り（235 の作り）にして、お礼の目まで笑う顔を見せた（⑨-1 47.3〜51.1 秒・⑨-2 63.4〜65.2 秒、動画の秒）。このままでよいか
3. 235 の「走り出した時の目まで笑う顔 1.5 秒」はやめ、目まで笑う顔はお礼の時だけにした。このままでよいか
4. ⑨-2 の早回し：「6 のあとから 30 秒の手前まで」は 0.55 秒しか無く早回しにしていない。10〜20 秒の間の早回し（235 のまま）は残した。これでよいか
5. ⑨-1 の動けない時間 29.833 秒は 30 秒まで 0.167 秒しかない（新しいセリフの間を 0.4 秒にして収めた）。間をのばすなら茂さんのセリフを短くする等が要る

判定：合格
```

### 依頼238 の報告（report238.txt）

```text
依頼238：⑨-1「声をかけて通る」（依頼237）の、茂さんのセリフを「大城さん、ロボットさんが通るって」に替え、ハコブくんが声をかけるのを止まって 10 秒 → 5 秒にして撮り直した（2026-11-17）

依頼237 の依頼文と報告、237 の台本 closeup237_script.json・make_script237.py・Editor/Closeup237.cs を読んでから始めた。
写して closeup238_script.json（make_script238.py が作る）・Editor/Closeup238.cs・tools（make238.py・an238.py・run238.sh・run238b.sh・batch_check.sh・batch_render.sh）を作り、写した先で変えた。
237 の台本・コード・出力には触っていない。触ったのは Assets/ServiceSim/Closeups/ の中の新しいファイルだけ（closeup238_script.json・Editor/Closeup238.cs と、それぞれの .meta）。
Models/、病院の1日の場面、配膳の場面、共通の部品（CloseupDirector.cs・CloseupNurse.cs を含む）、Packages、実行ファイルには触っていない。場面のファイルは保存していない。
Mixamo の FBX は使っていない・写していない・check-in していない。撮り直したのは ⑨-1 だけ（⑨-2 は 237 の closeup237_stop_stuck.mp4 をそのまま使う）。場面の名前は 237 と同じ stop_voice（まばたきの種が同じ）。

結論：依頼のとおり ⑨-1 を撮り直した。決まりはすべて守れた（当たったコマ 0・動けない時間 25.033 秒（237 は 29.833 秒）・7・8 の声は 2 つとも横にいる間に終わった・行き先/中身/数は出ていない）。
変えたのは 1（茂さんのセリフ）と 2（声をかける時刻）だけ。寄せ方・立ち話・寺島さんの動き・ハコブくんの止まり方と通り方・画面・カメラの切りかえの考え方・真上の動画の描き方は 237 の作りのまま（時刻だけ前へずれた）。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status --all は cs:168 で変更なし。Mixamo のフォルダも保留に出ていない）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- 最新の check-in：cs:168（依頼237）

■ 写し方の確かめ（237 と同じになるか）
- make_script238.py を「止まって 10 秒・237 の声 M2_morita_tooru.wav」に戻して回すと、237 の台本の stop_voice・stop_voice__tera と、台本の共通の値・声の並び mix237_stop_voice.wav がすべて同じになった（台本の名前 c237→c238 と about だけ違う）。写した所に誤りは無い
- Closeup238.cs は Closeup237.cs の名前だけを 238 に替えたもの（Closeup238・-c238*・台本の c238・出力 *238.*。「通れません」の絵 c237_stuck_band・face237_trouble は 237 のまま参照）

■ 1. 茂さんのセリフ
- 「おい、ロボットさんが通るって」→「大城さん、ロボットさんが通るって」
- 声：tts_eleven.py --try・eleven_v4・種 7・道具の既定の設定（233・237 と同じ作り）・Voice ID ydyMD3g4SbEeNpF0wahP
| 名前 | セリフ | 長さ（ファイル） | 声のある長さ | 元 → 直し |
| M2_morita_oshirosan_tooru | 大城さん、ロボットさんが通るって | 2.400 秒 | 2.250 秒（237 の M2 は 2.060 秒） | −18.0 LUFS → −2.0 dB → −20.0 LUFS（48 kHz モノラル） |
- 読みの確かめ（233 の readchk.py・MFCC-DTW。同じ声・同じ種で ひらがな の 2 通りを作って比べた）：
  文全体 おおしろ 1.161・だいじょう 1.271／頭の 0.6 秒（名前の所）おおしろ 1.156・だいじょう 1.724 → おおしろ に近い。耳では聞いていない
- 顔を向ける向き・角度は 237 のまま（声をかけ終わって 0.05 秒から −40°（+x の側）へ 0.45 秒・0.4 秒あけて話す・「あ、ごめんね」の後に前へ戻す）
- 口：話す間は Morita_Mouth_talk（237 と同じ。声の大きさに合わせて開く）

■ 2. 声をかける時刻
- ハコブ「すみません、通ります」：止まって 10 秒（23.167）→ 5 秒（18.167）
- そのあとの流れ（茂さん → 大城さん → 握り直して寄せる → 通る → 茂さんの問い → お礼）は 237 の決め方のまま。時刻は、茂さんの声が 0.19 秒長くなった分だけ 5 秒より少なくずれた（「あ、ごめんね」から後は −4.81〜−4.80 秒）
- 走り出しと横にいる間の時刻は 237 と同じく 2 回まわして決めた（1 回目の Unity で走り出し 38.200・横にいる間 43.200〜46.700・通り過ぎ 48.033 を測り、2 回目の台本に入れた。2 回目も同じ値）。
  茂さんが「何を運んでるんだい？」で向く角度も 237 と同じ決め方（声の真ん中の時刻のハコブくんの画面の向き）で 38°（1 回目 42.667〜42.700 秒で 37.66〜38.19°・237 と同じ値）

■ 3. 動けない時間
| | 止まった | 走り出し | 動けない時間 |
| 237 | 13.167 | 43.000 | 29.833 秒 |
| 238 | 13.167 | 38.200 | 25.033 秒（−4.800） |

■ 4. セリフごとの時刻（台本の秒・動画の秒＝台本の秒−1.0）
⑨-1（238：49.533 秒・1486 コマ／237：54.333 秒・1630 コマ）
| セリフ | 誰 | 238 台本の秒 | 238 動画の秒 | 237 台本の秒 | ずれ | 声の長さ |
| 大城さん | 寺島 | 6.107〜6.808 | 5.107〜5.808 | 6.107〜6.808 | 0 | 0.700 |
| あ、寺島さん。おつかれさま | 大城 | 8.908〜11.068 | 7.908〜10.068 | 8.908〜11.068 | 0 | 2.160 |
| すみません、通ります | ハコブ | 18.167〜19.667 | 17.167〜18.667 | 23.167〜24.667 | −5.000 | 1.500 |
| 大城さん、ロボットさんが通るって（237：おい、ロボットさんが通るって） | 茂 | 20.067〜22.317 | 19.067〜21.317 | 25.067〜27.127 | −5.000（始まり） | 2.250（237 2.060） |
| あ、ごめんね | 大城 | 22.717〜24.047 | 21.717〜23.047 | 27.527〜28.857 | −4.810 | 1.330 |
| 何を運んでるんだい？ | 茂 | 42.130〜43.250 | 41.130〜42.250 | 46.930〜48.050 | −4.800 | 1.120 |
| 病棟へのお届け物です。ありがとうございます | ハコブ | 43.650〜46.630 | 42.650〜45.630 | 48.450〜51.430 | −4.800 | 2.980（「ありがとうございます」は 45.680 から） |
- セリフの間：通ります→大城さん、 0.400・大城さん、→あ、ごめんね 0.400・何を運んでる→病棟へ 0.400（237 と同じ）・大城さん→あ、寺島さん 2.100（237 のまま）

■ 5. ハコブくんが車いすの横にいる間と、7・8 の声（237 と同じ書き方。前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで。Unity の中で毎コマ測った）
| | 横にいる間 | 声 | 横にいる間との関係 |
| 238 茂「何を運んでるんだい？」 | 43.200〜46.700 | 42.130〜43.250 | 横に来る 1.070 秒前に始まり、横に来て 0.050 秒で終わる（近づいた所で聞く）＝237 と同じ |
| 238 ハコブ「病棟へのお届け物です。ありがとうございます」 | 43.200〜46.700 | 43.650〜46.630 | 全部が横にいる間（始まり＋0.450・終わり−0.070）＝237 と同じ |
| 237（参考） | 48.000〜51.500 | 茂 46.930〜48.050・ハコブ 48.450〜51.430 | 同上 |

■ 6. 茂さんの顔の向き・うなずき（frames238.csv）
- 顔の向き：大城さんのほうへ −40.0°・ハコブくんへ 38.0° → 最大 40.0°（237 と同じ）・うなずき 10.0°・1 回
- 茂さんの 1 コマの骨の動き（車いすから）0.84 cm（237 と同じ）・向けている間の画面への角度の最小 8.8°

■ 7. 画面の変わり目（行き先・中身・数は一度も出ていない。使った絵は 237 の ⑨-1 と同じ：c235_wait_band・c235_pass_band・c235_deliv_band、顔の板の face218_*・face224_happy_*／face218_happy）
238：0.000 基本 → 13.367 お待ちしています → 18.167 通ります → 38.200 基本（走り出し）→ 43.667 お届け中 → 45.667 目まで笑う顔 → 47.167 基本
237：0.000 基本 → 13.367 お待ちしています → 23.167 通ります → 43.000 基本 → 48.433 お届け中 → 50.467 目まで笑う顔 → 51.967 基本
- 目まで笑う顔 1.5 秒は「ありがとうございます」の始まり（45.680）と同じコマから（237 と同じ）。「病棟へのお届け物です」は声だけ

■ 8. カメラの切りかえ（台本の秒 → 動画の秒。237 と同じ決め方）
238：本番 0.000→0.000／画面 13.067→12.067／本番 14.767→13.767／画面 18.033→17.033／茂さんの顔 19.833→18.833／大城さんの顔 22.467→21.467／本番 24.400→23.400／画面 43.500→42.500／本番 47.333→46.333（終わりまで）
237：本番 0.000／画面 13.067／本番 14.767／画面 23.033／茂さんの顔 24.833／大城さんの顔 27.267／本番 29.200／画面 48.300／本番 52.133

■ 9. 確かめの表（⑨-1）
必ず守る
| 項目 | 238 | 237 | 合否 |
| 当たったコマ（ハコブくんと物・車いす/茂さんと壁・ハコブくんと壁・看護師と車いす・手が握りの中・看護師と壁） | 0・0・0・0・0・0 | 0・0・0・0・0・0 | 合う |
| 寺島さんの当たり（壁/手すり・大城さん・車いす） | 0・0・0 | 0・0・0 | 合う |
| 手が握りから離れない | 手のひらの中心と握りの面 0.0212 m・的とのずれ 0.0000 m | 同じ | 合う |
| 手の頂点と握りの面の一番近い所 | 0.0034 m（中に入っていない） | — | 合う |
| 車輪の横すべり（後ろ・前） | 0.00001・0.00000 m/コマ | 同じ | 合う |
| 1 コマで骨が動く量（根の動きを除く） | 4.50 cm | 4.50 cm | 合う（6 cm 以内） |
| 足のすべり | 0.00 cm | 0.00 cm | 合う |
| 寄せる道（向き・速さ・向きの変わる速さ・前へ・後ろへ） | 17.00°・0.2802 m/秒・23.00°/秒・0.8216・0.0540 m | 17.00°・0.2803・23.00・0.8216・0.0540 | 合う（速さの 4 けた目だけ違う＝寄せる時刻がずれたコマの刻みの違い） |
| 寄せる間の車いすの横の速さ（根・足のせの前の端） | 0.0819・0.3172 m/秒 | — | 参考 |
| 足のせの前の端とハコブくんの前の端の最小 | 1.5682 m | 1.5682 m | 合う |
| 大城さんの顔（体から）の最大 | 29.42° | 29.42° | 合う |
| 寺島さんの下がった距離 | 0.9963 m | 0.9962 m | 合う |
| ハコブくんが通る時のすき間の最小 | 車いす 0.232・茂さん 0.318・大城さん 0.287・寺島さん 0.645 m | 同じ | 合う |
| 手すりとのすき間 | ハコブくん 0.053 m・車いす/茂さん 0.174 m・看護師 0.122 m | — | 合う |
| 動けない時間 | 25.033 秒 | 29.833 秒 | 合う（30 未満） |
| 7・8 の声が横にいる間に終わる | 茂 43.250・ハコブ 46.630（横 43.200〜46.700） | 茂 48.050・ハコブ 51.430（横 48.000〜51.500） | 合う |
| 行き先・中身・数が画面に出ない | 出ない | 出ない | 合う |
できるだけ守る
| 項目 | 値 | 合否 |
| 茂さんの顔の向き | 大城さんへ 40°・ハコブくんへ 38° | 237 のまま |
| うなずき | 10°・1 回 | 合う |
| 目まで笑う顔 | 1.5 秒・「ありがとうございます」の始まりと同じコマ | 合う |
| 止まった時の足のせとのあいだ | 2.400 m | 合う |

■ 10. 撮ったもの
| 動画 | 長さ | md5 |
| closeup238_stop_voice.mp4（⑨-1） | 49.533 秒・1486 コマ | 9e2976ab1c380270d3aec8ad1eec3838 |
| closeup238_stop_voice_top.mp4 | 49.533 秒・1486 コマ | ede2bb4b85bad7427538a21bf65a465b |
- 終わり：ハコブくんが物の一番後ろを通り過ぎてから 2.5 秒（237 のまま）
- 真上の動画：237 の描き方のまま（make238.py は make237.py の名前だけを替えた写し）。外形の中に残った線の画素 0
- 静止画（stills/、237 の ⑨-1 と同じ並び 14 枚）：s01 寺島さんが声をかける・s02 3 人で話す・s03/s04 ハコブくんが止まった・s07 通ります・s08 大城さんが気づく・
  s09 寄せる所（本番・真上）・s10 ハコブくんが通る・s11_morita_tooru（茂さん「大城さん、ロボットさんが通るって」）・s12_morita_nanida・s13_otodokechu・s13_arigato_happy・s13_arigato_main
  stills_check/ に握りの確かめ 2 枚
- 撮り方：確かめの値は区切らずに最後まで回した回（out/check_full_stop_voice、5 分 15 秒）。コマは台本の秒で 3 つに区切って撮った（0〜17・17〜34・34〜終わり、各 3.7〜7.9 分。止められることは無かった）。
  区切って撮った回の frames238.csv・bones238.csv・feet238.csv・wc238.csv・top238.csv・check238.txt は、区切らない回と同じ（cmp で一致）
- 237 の動画・台本・出力は消していない・変えていない（⑨-2 は 237 の closeup237_stop_stuck.mp4・_top.mp4 を使う）

■ 出力の場所（写した後に md5 を確かめた：動画 2 本・静止画 14 枚・声・道具）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261117_closeup238/
  動画 2 本・stills/・stills_check/・audio/（mix238_stop_voice.wav・voice/ 新しい声の mp3・wav と lufs.txt・reading_check/）・
  out/（stop_voice・check_full_stop_voice：check238.txt・events238.txt・frames238.csv・bones238.csv・feet238.csv・wc238.csv・top238.csv・an238_stop_voice.txt・vmap238_stop_voice.json・per238_stop_voice.csv・unity の記録、times.json・times_pass1.json・events238_pass1.txt・make_script238_out.json）・
  geo/path235.json・tools/（make_script238.py・make238.py・an238.py・run238.sh・run238b.sh・batch_check.sh・batch_render.sh・Closeup238.cs の写し）・report238.txt
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup238/（動画 2 本・stills/）

■ check-in
- cs:169（4 件：closeup238_script.json・Editor/Closeup238.cs と .meta）。保留は無し

■ 決めてほしいこと
なし（237 の「決めてほしいこと」1〜4 は依頼のとおり 237 のままにした。237 の 5（動けない時間が 30 秒に近い）は 25.033 秒になり、30 秒まで 4.967 秒あいた。セリフの間 0.4 秒は 237 のまま変えていない）

判定：合格
```



## 作業ログ ― Unity の場面のコードと、確かめ・計算の道具（Claude Code が書いた版）

KIOXIA の `service_sim/unity/closeup/{日付}_closeup{番号}/tools/` と `geo/` に置いた写しです。Unity では `Assets/ServiceSim/Closeups/Editor/` にあります（名前の末尾が .copy のものは、Unity の中のファイルの写し）。

### 依頼230

#### tools/Closeup230.cs（依頼230）

```csharp
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>
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top230.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top230_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c230Views top）・静止画なし（-c230Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup230.Run \
    ///                 -c230Out <出力フォルダ> [-c230Script closeup229_script.json] [-c230Frames on|off] [-c230Stills on|off] [-c230Views main,top] [-c230From 秒] [-c230To 秒] [-c230Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames230.csv・bones230.csv・feet230.csv・wc230.csv・check230.txt・events230.txt
    /// </summary>
    public static class Closeup230
    {
        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 LayerChair = 30, LayerNurse = 31;

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c230Out", "");
            if (outDir == "") throw new Exception("-c230Out がない");
            string scriptName = CloseupArgs.Get("-c230Script", "closeup229_script.json");
            bool frames = CloseupArgs.Get("-c230Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c230Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c230Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c230From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c230To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk") talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.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;

                string shotName = "yield";
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c229"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                Texture2D bandTex = ScreenTex(TexDir + "/" + C["band"].S() + ".png");
                float bandOn = C["band_on"].F(), bandOff = C["band_off"].F(), happyFrom = C["happy_from"].F(), happyTo = C["happy_to"].F();
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                var SH = C["shift"]; float shT0 = SH["t0"].F(1e9f), shT1 = SH["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c230Until", "1e9"), IC)) * fps);
                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);
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        if (mode == "stop" && stopped && behindN >= R.passBehind) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師
                    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;
                    chair.SetPositionAndRotation(nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead), nr.rotation);
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    bool bandNow = t >= bandOn - 1e-4f && t < bandOff - 1e-4f;
                    bool happyNow = t >= happyFrom - 1e-4f && t < happyTo - 1e-4f;
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", bandTex); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy" : 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 ? "帯" : "") + (happyNow ? "目まで笑う顔" : "基本") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        float d = RobotDist(rs, lr, Mathf.Min(gap, 1.5f));
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000"));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top230_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && inRange)
                    {
                        syncProxies(); scaleMouth();
                        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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, 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();
                        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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames230.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top230.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones230.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet230.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc230.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check230.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events230.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C230] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 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);
        }
    }
}
```

#### tools/closeup230_top.json（依頼230）

```json
{
  "about": "依頼230：⑧ 車いすに道を譲る（229）の真上の動画の、動かない真上のカメラ（正射影）。値は廊下の原点から（m）。画面の上が -x（ハコブくんの側）・右が +z。写す範囲 z 2.70〜12.95（10.25 m）・x -3.383〜+2.383（5.766 m。廊下を画面の下寄りに置き、上に字の場所をとる）",
  "center_x": -0.5,
  "center_z": 7.825,
  "height": 10.0,
  "ortho_size": 2.8828125,
  "width_px": 1920,
  "height_px": 1080
}
```

#### tools/cmp230.py（依頼230）

```python
"""依頼230：229 と 230 の動きを全部のコマで比べる（frames・bones・wc の数の列）。使い方: python3 cmp230.py <229 の out> <230 の出力>"""
import csv, sys
A, B = sys.argv[1:3]
def load(p): return list(csv.DictReader(open(p)))
for name in ["frames", "bones", "wc", "feet"]:
    ra, rb = load(f"{A}/{name}229.csv"), load(f"{B}/{name}230.csv")
    assert len(ra) == len(rb), (name, len(ra), len(rb))
    assert list(ra[0].keys()) == list(rb[0].keys()), name
    worst = {}; ndiff = 0
    for a, b in zip(ra, rb):
        for k in a:
            if a[k] == b[k]: continue
            ndiff += 1
            try: d = abs(float(a[k]) - float(b[k]))
            except ValueError: d = float("inf")
            if d > worst.get(k, (-1,))[0]: worst[k] = (d, a["t"], a[k], b[k])
    print(f"{name}: {len(ra)} コマ・{len(ra[0])} 列・違うセル {ndiff}", worst if worst else "")
```

#### tools/make230.py（依頼230）

```python
"""依頼230：229 の真上のコマ（Closeup230.cs が動かない真上のカメラで撮った frames/yield_top）に、床の目印・通った跡・印・左上の字を重ねて
closeup230_yield_top.mp4（音なし）と静止画 3 枚を作り、確かめ（check230_top.txt）を書く。
目印・跡は Unity のカメラで写した位置（top230.csv の画面の位置・top230_cam.json の写し方）に 2 倍の大きさで描いて縮める。
時刻は動画の秒（台本の秒 − video_from）。
使い方: python3 make230.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile
from PIL import Image, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, VD = sys.argv[1:4]
os.makedirs(VD, exist_ok=True)
C = json.load(open(SC))["shots"][0]["c229"]
CAM = json.load(open(os.path.join(D, "top230_cam.json")))
FPS, W, H, S = 30, 1920, 1080, 2          # S：描く倍率（2 倍で描いて縮める）
f0, f1 = int(round(C["video_from"] * FPS)), int(round(C["video_to"] * FPS))
n = f1 - f0 + 1
vt = lambda f: (f - f0) / FPS             # 動画の秒

# ---- 決めた値（1920×1080 の画面での px）
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {
    "center": (120, 120, 120),       # 廊下の中心の線（細い実線・灰色）
    "x028": (21, 101, 192),          # 車いすの始めの線 +0.28（破線・青）
    "x042": (142, 36, 170),          # 寄せたあとの線 +0.42（破線・紫）
    "lane": (46, 173, 107),          # ハコブくんのふだんの線 −0.33（破線・ハコブくんの輪の光に近い緑）
    "chair": (239, 108, 0),          # 車いすの通った跡（実線・橙）
    "robot": (0, 105, 92),           # ハコブくんの通った跡（実線・深い青緑）
}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16

# ---- 床の点 → 画面（Unity のカメラで写した 3 点から。正射影なので一次式）
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)   # (x, z)

rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames230.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top230.csv")))}
ev = open(os.path.join(D, "events230.txt"), encoding="utf-8").read()
t_trig = float(re.search(r"([\d.]+) 秒 決まりに当たった", ev).group(1))
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_sh0, t_sh1 = C["shift"]["t0"], C["shift"]["t1"]
# 印：(どれ, 台本の秒, 字の頭)。出す時刻 = その秒のコマ
MARKS = [("chair", t_sh0, "寄せ始め"), ("chair", t_sh1, "寄せ終わり"), ("robot", t_trig, "寄り始め"), ("robot", t_stop, "止まった")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]

def font(px): return ImageFont.truetype(FONT_PATH, px * S)
FL, FM, FH = font(LINE_LABEL_PX), font(MARK_LABEL_PX), font(HUD_PX)
def sc(p): return (p[0] * S, p[1] * S)

def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy
    bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)

def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1)
    L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L
    s = 0.0
    while s < L:
        e = min(L, s + DASH * S)
        d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S)
        s += (DASH + GAP) * S

def down(layer): return layer.resize((W, H), Image.LANCZOS)

# ---- 動かない層：中心の線・目印の線と字
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x028": 0.28, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x028", "x042", "lane"):
    dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
# 字：始め +0.28（線の上）と寄せたあと +0.42（線の下）は左の端（車いすが来るのは右の端なので、入ってくる所と寄せる所を隠さない）、ハコブくんのふだん −0.33 は右の端（ハコブくんが行かない側）
text_box(d, (sc((14, line_py["x028"] - 8))), "始め +0.28", FL, COL["x028"], "lb", edge=COL["x028"])
text_box(d, (sc((14, line_py["x042"] + 8))), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, (sc((W - 14, line_py["lane"] - 8))), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st)

# ---- 印の層（時刻になったら出す）。字は車いすの印は廊下の下、ハコブくんの印は廊下の上へ引き出す
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    nrob = 0
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (0 if head == "寄せ始め" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "止まった" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        text_box(d, sc((px, ly)), f"{head} {vt(mark_f[i]):.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)

# ---- 左上の字
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]
    cx = num_ok(r["chair_x"]); g = num_ok(r["gap_m"])
    return [f"{vt(f):.1f} 秒",
            "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None else "—")]

# ---- コマを作る
tmp = tempfile.mkdtemp(prefix="m230_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}
shown = [False] * len(MARKS); mcache = mark_layer(shown)
chk = {"trail_err_m": {"chair": 0.0, "robot": 0.0}, "mark_first": [None] * len(MARKS), "hud_bad": 0, "hud_dash": {1: 0, 2: 0}, "hud_texts": []}
stills = {}
for k, f in enumerate(range(f0, f1 + 1)):
    r = top[f]
    for who, kx, ky, wx, wz in (("chair", "axle_px", "axle_py", "axle_x", "axle_z"), ("robot", "robot_px", "robot_py", "robot_x", "robot_z")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)   # 描く点（2 倍の画面の整数の点）
        bx, bz = from_px(*p)
        chk["trail_err_m"][who] = max(chk["trail_err_m"][who], math.hypot(bx - float(r[wx]), bz - float(r[wz])))
        if prev[who] is not None:
            td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2
        td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))   # 線のつなぎ目を丸く
        prev[who] = p
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True; chk["mark_first"][i] = vt(f)
    if changed: mcache = mark_layer(shown)
    im = Image.open(os.path.join(D, "frames", "yield_top", f"f_{f:05d}.png")).convert("RGBA")
    im.alpha_composite(down(trail)); im.alpha_composite(static); im.alpha_composite(mcache)
    lines = hud_lines(f)
    for i in (1, 2):
        if lines[i].endswith("—"): chk["hud_dash"][i] += 1
    if any(re.search(r"\d{5,}|nan|inf", s, re.I) for s in lines): chk["hud_bad"] += 1
    if k % 30 == 0: chk["hud_texts"].append(" / ".join(lines))
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl)
    x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im.alpha_composite(down(hl))
    out = im.convert("RGB"); out.save(os.path.join(tmp, f"v_{k:05d}.png"))
    for name, ff in (("s1_shift_start", mark_f[0]), ("s2_shift_end", mark_f[1]), ("s3_last", f1)):
        if f == ff: stills[name] = out.copy()
vid = os.path.join(VD, "closeup230_yield_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vid], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for name, im in stills.items(): im.save(os.path.join(sd, name + ".png"))

# ---- 確かめ
o = []
o.append(f"コマ {n}（{f0}〜{f1}）・動画 {n / FPS:.3f} 秒")
o.append(f"写し方：画面の点 = ({ox:.4f}, {oy:.4f}) + x×({xx:.4f}, {xy:.4f}) + z×({zx:.4f}, {zy:.4f}) px（1 m = {math.hypot(zx, zy):.3f} px・1 px = {1000 / math.hypot(zx, zy):.2f} mm）")
o.append(f"写す範囲：z {z_lo:.3f}〜{z_hi:.3f}（{z_hi - z_lo:.3f} m）・x {from_px(0, 0)[0]:.3f}〜{from_px(0, H)[0]:.3f}（{from_px(0, H)[0] - from_px(0, 0)[0]:.3f} m）")
for k2, x in LINES.items():
    py = line_py[k2]; back = from_px(W / 2, py)[0]
    o.append(f"目印の線 {k2}：x {x:+.2f} → 画面の y {py:.2f} px（画面から戻した x {back:+.5f}）")
o.append(f"手すり（内側の面 x ±0.84）：画面の y {to_px(-0.84, 0)[1]:.2f}〜{to_px(0.84, 0)[1]:.2f} px（{to_px(0.84, 0)[1] - to_px(-0.84, 0)[1]:.1f} px ＝ 画面の高さの {(to_px(0.84, 0)[1] - to_px(-0.84, 0)[1]) / H * 100:.1f}%）")
o.append(f"通った跡の点と本当の位置のずれの最大：車いすの後ろの車軸の真ん中 {chk['trail_err_m']['chair'] * 100:.3f} cm・ハコブくんの根 {chk['trail_err_m']['robot'] * 100:.3f} cm")
for (who, t, head), fv in zip(MARKS, chk["mark_first"]):
    o.append(f"印 {who} {head}：台本 {t:.4f} 秒（動画 {t - C['video_from']:.3f} 秒）→ 出たコマの動画の秒 {fv:.3f}")
o.append(f"左上の字：壊れた値のコマ {chk['hud_bad']}・車いすの横の位置が「—」のコマ {chk['hud_dash'][1]}・すき間が「—」のコマ {chk['hud_dash'][2]}")
o += ["  " + s for s in chk["hud_texts"]]
# 画面の中か（2＝全部・1＝一部・0＝外）
def spans(key):
    out, cur = [], None
    for f in range(f0, f1 + 1):
        v = int(top[f][key])
        if cur is None or cur[0] != v: cur = [v, vt(f), vt(f)]; out.append(cur)
        else: cur[2] = vt(f)
    return " ／ ".join(f"{['外', '一部', '全部'][v]} {a:.3f}〜{b:.3f}" for v, a, b in out)
for key, nm in (("chair_in", "車いす"), ("robot_in", "ハコブくん"), ("nurse_in", "大城さん")):
    o.append(f"{nm}が画面の中か：{spans(key)}")
a, b = int(round((t_sh0 - 1.0) * FPS)), int(round(t_sh1 * FPS))
o.append(f"寄せ始めの 1 秒前〜寄せ終わり（動画 {vt(a):.3f}〜{vt(b):.3f}）の車いす：全部が画面の中でないコマ {sum(1 for f in range(a, b + 1) if int(top[f]['chair_in']) != 2)}")
open(os.path.join(D, "check230_top.txt"), "w", encoding="utf-8").write("\n".join(o) + "\n")
print("\n".join(o)); print("動画", vid)
```

#### tools/run230.sh（依頼230）

```bash
#!/bin/bash
# 依頼230 使い方: run230.sh <出力フォルダ> <コマ on|off> [views] [until]
OUT="$1"; FR="${2:-off}"; VW="${3:-top}"; UNTIL="${4:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup230.Run \
   -c230Out "$OUT" -c230Frames "$FR" -c230Stills off -c230Script closeup229_script.json -c230Views "$VW" -c230Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

### 依頼231

#### tools/Closeup231Terashima.cs（依頼231）

```csharp
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼231：寺島さん（Closeups/Models_terashima/nurse_terashima.fbx）を読む・大城さんと比べる・測る。
    ///   ・読み方は大城さん（CloseupImport.ImportNurse）と同じ：Humanoid・骨は名前どおり・腕を T ポーズに直して Avatar・FBX の色（linear）→ sRGB の Standard
    ///   ・材質とプレハブは Models_terashima/ の中に作る（Models/ には入れない）
    ///   ・大城さんの FBX・プレハブは読むだけ
    ///   ・出力：terashima231.txt（読み込み・骨の比べ・部品・寸法）、terashima231_front.png / _side.png（大城さんと並べた静止画）
    /// コマンド
    ///   Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup231Terashima.Run -c231Out <出力フォルダ>
    /// </summary>
    public static class Closeup231Terashima
    {
        public const string Dir = "Assets/ServiceSim/Closeups/Models_terashima";
        public const string Fbx = Dir + "/nurse_terashima.fbx";
        public const string Prefab = Dir + "/NurseTerashima.prefab";
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string F(float v) { return v.ToString("0.0000", IC); }
        static string V(Vector3 v) { return "(" + F(v.x) + "," + F(v.y) + "," + F(v.z) + ")"; }
        static string Hex(Color c) { return "#" + ColorUtility.ToHtmlStringRGB(c); }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c231Out", "/tmp/c231/import");
            Directory.CreateDirectory(outDir);
            var sb = new StringBuilder();
            try
            {
                Import(sb);
                AssetDatabase.SaveAssets();
                Compare(sb, outDir);
            }
            catch (Exception e)
            {
                sb.AppendLine("ERROR " + e);
                Debug.LogError(e);
            }
            File.WriteAllText(Path.Combine(outDir, "terashima231.txt"), sb.ToString(), new UTF8Encoding(false));
            Debug.Log("[C231] terashima\n" + sb);
        }

        // ---------------------------------------------------------------- 読み込み（CloseupImport.ImportNurse と同じ手順。置き場所と名前だけ違う）
        static void Import(StringBuilder sb)
        {
            sb.AppendLine("== 寺島さんの読み込み（" + Fbx + "）");
            var mi = (ModelImporter)AssetImporter.GetAtPath(Fbx);
            if (mi == null) throw new Exception("FBX が無い: " + Fbx);
            foreach (var kv in mi.GetExternalObjectMap()) mi.RemoveRemap(kv.Key);
            mi.isReadable = true;
            mi.importAnimation = false;
            mi.materialImportMode = ModelImporterMaterialImportMode.ImportStandard;
            mi.animationType = ModelImporterAnimationType.Human;
            mi.avatarSetup = ModelImporterAvatarSetup.CreateFromThisModel;
            var hd0 = mi.humanDescription;
            hd0.human = new HumanBone[0];
            hd0.skeleton = new SkeletonBone[0];
            mi.humanDescription = hd0;
            mi.SaveAndReimport();

            var auto = mi.humanDescription;
            var autoMap = new Dictionary<string, string>();
            if (auto.human != null) foreach (var hb in auto.human) autoMap[hb.humanName] = hb.boneName;
            var autoLines = new List<string>();
            foreach (var kv in autoMap) if (kv.Key.Replace(" ", "") != kv.Value) autoLines.Add(kv.Key + "=" + kv.Value);
            sb.AppendLine("自動の割り当て " + autoMap.Count + " 本・名前と違うもの: " + (autoLines.Count == 0 ? "なし" : string.Join(", ", autoLines.ToArray())) + "（使わない。名前で割り当てる）");

            var src = AssetDatabase.LoadAssetAtPath<GameObject>(Fbx);
            var go = (GameObject)PrefabUtility.InstantiatePrefab(src);
            PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
            var anim = go.GetComponent<Animator>();
            if (anim != null) UnityEngine.Object.DestroyImmediate(anim);
            var bones = new Dictionary<string, Transform>();
            foreach (var t in go.GetComponentsInChildren<Transform>()) if (!bones.ContainsKey(t.name)) bones[t.name] = t;

            var human = new List<HumanBone>();
            var missingReq = new List<string>();
            string[] names = HumanTrait.BoneName;
            for (int i = 0; i < names.Length; i++)
            {
                string want = names[i].Replace(" ", "");
                if (bones.ContainsKey(want))
                {
                    var hb = new HumanBone { humanName = names[i], boneName = want };
                    hb.limit.useDefaultValues = true;
                    human.Add(hb);
                }
                else if (HumanTrait.RequiredBone(i)) missingReq.Add(names[i]);
            }
            sb.AppendLine("名前で割り当てた骨 " + human.Count + " 本・必須なのに無い骨: " + (missingReq.Count == 0 ? "なし" : string.Join(", ", missingReq.ToArray())));

            foreach (var side in new[] { "Left", "Right" })
            {
                Vector3 outward = side == "Left" ? Vector3.left : Vector3.right;
                Align(bones, side + "UpperArm", side + "LowerArm", outward);
                Align(bones, side + "LowerArm", side + "Hand", outward);
                Align(bones, side + "Hand", side + "MiddleProximal", outward);
            }
            var skel = new List<SkeletonBone>();
            foreach (var t in go.GetComponentsInChildren<Transform>())
                skel.Add(new SkeletonBone { name = t == go.transform ? src.name : t.name, position = t.localPosition, rotation = t.localRotation, scale = t.localScale });

            string matDir = Dir + "/Materials";
            if (!AssetDatabase.IsValidFolder(matDir)) AssetDatabase.CreateFolder(Dir, "Materials");
            var shader = Shader.Find("Standard");
            sb.AppendLine("材質（FBX の色 linear → sRGB）:");
            foreach (var o in AssetDatabase.LoadAllAssetsAtPath(Fbx))
            {
                var fm = o as Material;
                if (fm == null) continue;
                string mp = matDir + "/" + fm.name + ".mat";
                var nm = AssetDatabase.LoadAssetAtPath<Material>(mp);
                if (nm == null) { nm = new Material(shader); AssetDatabase.CreateAsset(nm, mp); }
                nm.shader = shader;
                Color lin = fm.color;
                nm.color = lin.gamma;
                nm.SetFloat("_Glossiness", fm.name.Contains("Eyes") || fm.name.Contains("Mouth") || fm.name.Contains("Glasses") ? 0.4f : 0.2f);
                EditorUtility.SetDirty(nm);
                mi.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), fm.name), nm);
                sb.AppendLine("  " + fm.name + " " + Hex(lin) + " → " + Hex(nm.color));
            }
            var hd = mi.humanDescription;
            hd.human = human.ToArray();
            hd.skeleton = skel.ToArray();
            hd.hasTranslationDoF = false;
            mi.humanDescription = hd;
            mi.SaveAndReimport();

            Avatar av = null;
            foreach (var o in AssetDatabase.LoadAllAssetsAtPath(Fbx)) if (o is Avatar) av = (Avatar)o;
            sb.AppendLine("Avatar " + (av == null ? "なし" : av.name + " isValid=" + av.isValid + " isHuman=" + av.isHuman));
            UnityEngine.Object.DestroyImmediate(go);

            var go2 = (GameObject)PrefabUtility.InstantiatePrefab(src);
            PrefabUtility.UnpackPrefabInstance(go2, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
            go2.name = "NurseTerashima";
            var an = go2.GetComponent<Animator>();
            if (an == null) an = go2.AddComponent<Animator>();
            an.avatar = av;
            an.applyRootMotion = false;
            an.cullingMode = AnimatorCullingMode.AlwaysAnimate;
            foreach (var smr in go2.GetComponentsInChildren<SkinnedMeshRenderer>()) smr.updateWhenOffscreen = true;
            PrefabUtility.SaveAsPrefabAsset(go2, Prefab);
            UnityEngine.Object.DestroyImmediate(go2);
        }

        // ---------------------------------------------------------------- 大城さんと比べる・測る
        static void Compare(StringBuilder sb, string outDir)
        {
            var oshiro = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(CloseupImport.NursePrefab));
            var tera = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(Prefab));
            oshiro.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
            tera.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
            sb.AppendLine();
            sb.AppendLine("== 骨の比べ（作った時の姿勢・根を原点にそろえて）");
            sb.AppendLine("根の名前：大城さん " + Child0(oshiro) + "・寺島さん " + Child0(tera));
            var bo = BoneDict(oshiro); var bt = BoneDict(tera);
            var onlyO = new List<string>(); var onlyT = new List<string>();
            foreach (var k in bo.Keys) if (!bt.ContainsKey(k)) onlyO.Add(k);
            foreach (var k in bt.Keys) if (!bo.ContainsKey(k)) onlyT.Add(k);
            sb.AppendLine("骨の数：大城さん " + bo.Count + "・寺島さん " + bt.Count);
            sb.AppendLine("大城さんだけにある骨: " + (onlyO.Count == 0 ? "なし" : string.Join(", ", onlyO.ToArray())));
            sb.AppendLine("寺島さんだけにある骨: " + (onlyT.Count == 0 ? "なし" : string.Join(", ", onlyT.ToArray())));
            float maxP = 0, maxLP = 0, maxLR = 0; string wP = "", wLP = "", wLR = "";
            foreach (var kv in bo)
            {
                Transform t2;
                if (!bt.TryGetValue(kv.Key, out t2)) continue;
                float dp = (kv.Value.position - t2.position).magnitude;
                float dlp = (kv.Value.localPosition - t2.localPosition).magnitude;
                float dlr = Quaternion.Angle(kv.Value.localRotation, t2.localRotation);
                if (dp > maxP) { maxP = dp; wP = kv.Key; }
                if (dlp > maxLP) { maxLP = dlp; wLP = kv.Key; }
                if (dlr > maxLR) { maxLR = dlr; wLR = kv.Key; }
            }
            sb.AppendLine("同じ名前の骨の位置のずれ 最大 " + F(maxP) + " m（" + wP + "）・親からの位置 最大 " + F(maxLP) + " m（" + wLP + "）・親からの向き 最大 " + F(maxLR) + "°（" + wLR + "）");
            var ao = oshiro.GetComponent<Animator>(); var at = tera.GetComponent<Animator>();
            int hm = 0, hDiff = 0;
            for (int i = 0; i < (int)HumanBodyBones.LastBone; i++)
            {
                var a = ao.GetBoneTransform((HumanBodyBones)i); var b = at.GetBoneTransform((HumanBodyBones)i);
                if (a == null && b == null) continue;
                hm++;
                if (a == null || b == null || a.name != b.name) hDiff++;
            }
            sb.AppendLine("Humanoid の割り当て：" + hm + " 本・大城さんと骨の名前が違う割り当て " + hDiff + " 本");

            sb.AppendLine();
            sb.AppendLine("== 部品（SkinnedMeshRenderer）");
            foreach (var go in new[] { oshiro, tera })
                foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    sb.AppendLine("  " + smr.name + " 表示=" + smr.gameObject.activeSelf + "/" + smr.enabled + " 頂点=" + smr.sharedMesh.vertexCount + " 三角形=" + (smr.sharedMesh.triangles.Length / 3) + " 材質=" + smr.sharedMaterial.name + " " + Hex(smr.sharedMaterial.color) + " 骨=" + smr.bones.Length);

            sb.AppendLine();
            sb.AppendLine("== 寸法（作った時の姿勢・前 +z・右 −x は体の左。腕を除く＝上腕より先の骨に重みの一番大きい頂点を除く）");
            Measure(sb, "大城さん", oshiro, "Nurse_");
            Measure(sb, "寺島さん", tera, "Terashima_");

            // 並べた静止画（口は flat だけを出す）
            foreach (var go in new[] { oshiro, tera })
            {
                string pre = go == oshiro ? "Nurse_Mouth_" : "Terashima_Mouth_";
                foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    if (smr.name.StartsWith(pre)) smr.gameObject.SetActive(smr.name == pre + "flat");
            }
            oshiro.transform.position = new Vector3(-0.45f, 0, 0);
            tera.transform.position = new Vector3(0.45f, 0, 0);
            Shot(outDir + "/terashima231_front.png", new Vector3(0, 1.0f, 3.6f), new Vector3(0, 0.88f, 0), 32);
            oshiro.transform.SetPositionAndRotation(new Vector3(0, 0, -0.45f), Quaternion.Euler(0, 90, 0));
            tera.transform.SetPositionAndRotation(new Vector3(0, 0, 0.45f), Quaternion.Euler(0, 90, 0));
            Shot(outDir + "/terashima231_side.png", new Vector3(3.6f, 1.0f, 0), new Vector3(0, 0.88f, 0), 32);
            oshiro.transform.SetPositionAndRotation(new Vector3(-0.3f, 0, 0), Quaternion.identity);
            tera.transform.SetPositionAndRotation(new Vector3(0.3f, 0, 0), Quaternion.identity);
            Shot(outDir + "/terashima231_face.png", new Vector3(0, 1.55f, 1.4f), new Vector3(0, 1.52f, 0), 22);
            UnityEngine.Object.DestroyImmediate(oshiro);
            UnityEngine.Object.DestroyImmediate(tera);
        }

        static string Child0(GameObject go)
        {
            var l = new List<string>();
            foreach (Transform c in go.transform) l.Add(c.name);
            return string.Join("/", l.ToArray());
        }

        static Dictionary<string, Transform> BoneDict(GameObject go)
        {
            var d = new Dictionary<string, Transform>();
            foreach (var t in go.GetComponentsInChildren<Transform>(true))
                if (t != go.transform && t.GetComponent<Renderer>() == null && !d.ContainsKey(t.name)) d[t.name] = t;
            return d;
        }

        static void Measure(StringBuilder sb, string who, GameObject go, string pre)
        {
            var an = go.GetComponent<Animator>();
            var arm = new HashSet<Transform>();
            foreach (var hb in new[] { HumanBodyBones.LeftUpperArm, HumanBodyBones.RightUpperArm })
            {
                var t = an.GetBoneTransform(hb);
                if (t != null) foreach (var c in t.GetComponentsInChildren<Transform>(true)) arm.Add(c);
            }
            Vector3 mn = Vector3.one * 1e9f, mx = -Vector3.one * 1e9f, tmn = mn, tmx = mx;
            Vector3 cmn = mn, cmx = mx;    // 胸の高さ（1.0〜1.45 m）の胴
            var mesh = new Mesh();
            foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                if (!smr.gameObject.activeSelf) continue;
                if (smr.name.StartsWith(pre + "Mouth_")) continue;
                smr.BakeMesh(mesh, true);
                var vs = mesh.vertices; var bw = smr.sharedMesh.boneWeights;
                for (int i = 0; i < vs.Length; i++)
                {
                    Vector3 w = smr.transform.TransformPoint(vs[i]);
                    mn = Vector3.Min(mn, w); mx = Vector3.Max(mx, w);
                    bool isArm = bw.Length > i && arm.Contains(smr.bones[bw[i].boneIndex0]);
                    if (isArm) continue;
                    tmn = Vector3.Min(tmn, w); tmx = Vector3.Max(tmx, w);
                    if (w.y > 1.0f && w.y < 1.45f) { cmn = Vector3.Min(cmn, w); cmx = Vector3.Max(cmx, w); }
                }
            }
            sb.AppendLine(who + "：全体 x " + F(mn.x) + "〜" + F(mx.x) + "（幅 " + F(mx.x - mn.x) + "）・y " + F(mn.y) + "〜" + F(mx.y) + "・z " + F(mn.z) + "〜" + F(mx.z) + "（奥行 " + F(mx.z - mn.z) + "）");
            sb.AppendLine(who + "：腕を除く x " + F(tmn.x) + "〜" + F(tmx.x) + "（幅 " + F(tmx.x - tmn.x) + "）・z " + F(tmn.z) + "〜" + F(tmx.z) + "（奥行 " + F(tmx.z - tmn.z) + "）");
            sb.AppendLine(who + "：胸の高さ 1.00〜1.45 m の胴 x " + F(cmn.x) + "〜" + F(cmx.x) + "・z " + F(cmn.z) + "〜" + F(cmx.z) + "（奥行 " + F(cmx.z - cmn.z) + "）");
            foreach (var n in new[] { HumanBodyBones.Hips, HumanBodyBones.Head, HumanBodyBones.LeftUpperArm, HumanBodyBones.LeftHand, HumanBodyBones.LeftFoot })
            {
                var t = an.GetBoneTransform(n);
                sb.AppendLine("  " + who + " 骨 " + n + " " + (t == null ? "なし" : V(t.position)));
            }
        }

        static void Shot(string path, Vector3 pos, Vector3 look, float fov)
        {
            var camGo = new GameObject("Cam231");
            var cam = camGo.AddComponent<Camera>();
            cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.4f, 0.38f, 0.36f);
            cam.fieldOfView = fov; cam.nearClipPlane = 0.05f;
            camGo.transform.position = pos; camGo.transform.LookAt(look);
            var lg = new GameObject("Light231"); var l = lg.AddComponent<Light>(); l.type = LightType.Directional; l.intensity = 1.1f;
            lg.transform.rotation = Quaternion.Euler(40, -30 + Quaternion.LookRotation(look - pos).eulerAngles.y, 0);
            RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.46f, 0.47f, 0.5f);
            int W = 1280, H = 960;
            var rt = new RenderTexture(W, H, 24) { antiAliasing = 4 };
            cam.targetTexture = rt; cam.Render();
            RenderTexture.active = rt;
            var tex = new Texture2D(W, H, TextureFormat.RGB24, false);
            tex.ReadPixels(new Rect(0, 0, W, H), 0, 0); tex.Apply();
            File.WriteAllBytes(path, tex.EncodeToPNG());
            RenderTexture.active = null; cam.targetTexture = null;
            UnityEngine.Object.DestroyImmediate(rt); UnityEngine.Object.DestroyImmediate(tex);
            UnityEngine.Object.DestroyImmediate(camGo); UnityEngine.Object.DestroyImmediate(lg);
        }

        static void Align(Dictionary<string, Transform> b, string a, string c, Vector3 to)
        {
            Vector3 d = b[c].position - b[a].position;
            b[a].rotation = Quaternion.FromToRotation(d.normalized, to) * b[a].rotation;
        }
    }
}
```

#### tools/geo231.py（依頼231）

```python
"""依頼231：止まった所の置き方と、両横に残る幅・寄せて通る所の幅を数える（廊下の中心から。m）。
値の出どころ：廊下＝closeup229_script.json（手すりの内の面 ±0.84・壁 ±0.90）、ハコブくんの幅と決まり＝229 の frames229.csv と robot_rule、
車いすの幅＝228 の報告（後ろの車輪の外 0.653）、寺島さん・大城さんの寸法＝Unity で測った terashima231.txt。
使い方: python3 geo231.py <出力フォルダ>"""
import sys, os, json
from PIL import Image, ImageDraw, ImageFont
out = sys.argv[1] if len(sys.argv) > 1 else '.'
RAIL = 0.84; WALL = 0.90
ROBOT_HALF = 0.84 - 0.1905 - 0.33          # 229：x −0.33 で手すりと 0.1905 → 半分の幅 0.3195
RAIL_CLEAR = 0.053; GAP = 0.15             # 229 の決まり（手すりと 0.053・人や車いすと 0.15 より狭いなら止まる）
NEED = RAIL_CLEAR + 2 * ROBOT_HALF + GAP   # 手すりの側を通る時に要る幅
CHAIR_HALF = 0.653 / 2
T_BACK, T_FRONT = 0.1399, 0.1499           # 寺島さん 奥行（作った時の姿勢・前 +0.1499・後ろ −0.1399）
T_HALF_W = 0.2381                          # 寺島さん 腕を含む幅の半分
O_HALF_W = 0.2381; O_DEPTH_HALF = 0.157    # 大城さん
WC_AHEAD = 0.594                           # 車いすの根は大城さんの根の前 0.594（228）
# 止まった所（提案ではなく、依頼の置き方どおりに置いた時の値）
chair_x = 0.0
oshiro_x = 0.0
tera_x = -0.55                             # 寺島さんの根（+x を向く）。大城さんの体の −x の端 −0.238 と 0.16 m あける
L = []
def p(s): print(s); L.append(s)
p(f"ハコブくんの幅 {2*ROBOT_HALF:.3f} m（手すりの高さ）・手すりの側を通るのに要る幅 = 手すり {RAIL_CLEAR} + 幅 {2*ROBOT_HALF:.3f} + すき間 {GAP} = {NEED:.3f} m")
p("■ 止まった時（車いす x 0.00・向き 0°、大城さん x 0.00、寺島さん x %.2f で +x を向く）" % tera_x)
cl = (chair_x - CHAIR_HALF) - (-RAIL); cr = RAIL - (chair_x + CHAIR_HALF)
p(f"  車いすの所：−x 側 {cl:.3f} m・+x 側 {cr:.3f} m（どちらも {NEED:.3f} より狭い → 通れない）")
tl = (tera_x - T_BACK) - (-RAIL)
orr = RAIL - (oshiro_x + O_HALF_W)
p(f"  大城さん・寺島さんの所：−x 側（寺島さんの背中と手すり）{tl:.3f} m・+x 側（大城さんと手すり）{orr:.3f} m（どちらも狭い → 通れない）")
p(f"  寺島さんの前と大城さんの体の −x の端：{(oshiro_x - O_HALF_W) - (tera_x + T_FRONT):.3f} m")
p("■ 寺島さんが −x へ半歩 0.5 m よける")
room = (tera_x - T_BACK) - (-RAIL)
p(f"  背中から手すりまで {room:.3f} m（壁まで {(tera_x - T_BACK) + WALL:.3f} m）。0.5 m よけると背中は x {tera_x - 0.5 - T_BACK:.3f}（手すりの外 {(-RAIL) - (tera_x - 0.5 - T_BACK):.3f} m・壁の外 {(-WALL) - (tera_x - 0.5 - T_BACK):.3f} m）")
p(f"  よけたあとも手すりの内に収まるには、はじめの寺島さんの根が x ≥ {-RAIL + T_BACK + 0.5:.3f}。大城さんの体（−x の端 {oshiro_x - O_HALF_W:.3f}）とぶつからないのは x ≤ {oshiro_x - O_HALF_W - T_FRONT:.3f} → 両方を満たす所は無い")
p("■ 大城さんが車いすを +x 0.42 へ寄せた後、ハコブくんが空いた間を通る（229 の通り方）")
chair_near = 0.079                         # 229：すれ違う時の一番近い車いすの点（ハコブくん x −0.4643 の右の端 −0.1448 + 0.2238）
span = chair_near - (-RAIL)
need_t = (T_BACK + T_FRONT) + GAP + 2 * ROBOT_HALF + GAP
p(f"  車いすの所の幅（−x の手すり〜車いすの一番近い点）{span:.3f} m")
p(f"  寺島さんがこの間（−x 側）に残る時に要る幅 = 寺島さんの奥行 {T_BACK+T_FRONT:.3f} + すき間 {GAP} + ハコブくん {2*ROBOT_HALF:.3f} + すき間 {GAP} = {need_t:.3f} m → {need_t-span:.3f} m 足りない")
osh_edge = 0.42 - O_HALF_W
p(f"  大城さんの所（大城さんの体の −x の端 {osh_edge:.3f}）の幅 {osh_edge + RAIL:.3f} m → {need_t-(osh_edge+RAIL):.3f} m 足りない")
p(f"  寺島さんが手すりに背中を付けても、ハコブくんの −x の端（寄った位置 x −0.4643 で {-0.4643-ROBOT_HALF:.3f}）と寺島さんの前（{-RAIL+T_BACK+T_FRONT:.3f}）が {(-RAIL+T_BACK+T_FRONT)-(-0.4643-ROBOT_HALF):.3f} m 重なる")
open(os.path.join(out, 'geo231.txt'), 'w').write('\n'.join(L) + '\n')

# 真上の図（左が −x）。1 m = 300 px
S = 300; W = int(3.0 * S); H = int(5.2 * S)
img = Image.new('RGB', (W, H), (235, 232, 224)); d = ImageDraw.Draw(img)
try: font = ImageFont.truetype('/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc', 26)
except Exception: font = ImageFont.load_default()
X = lambda x: int(W / 2 + x * S); Z = lambda z: int(H - 0.4 * S - z * S)
def panel(z0, title, chair, osh, tera, robot, tera_ghost=None):
    d.rectangle([X(-WALL), Z(z0 + 2.0), X(WALL), Z(z0)], fill=(219, 214, 201))
    for sx in (-1, 1):
        d.line([X(sx * RAIL), Z(z0 + 2.0), X(sx * RAIL), Z(z0)], fill=(160, 120, 70), width=3)
        d.rectangle([X(sx * WALL) - (6 if sx < 0 else 0), Z(z0 + 2.0), X(sx * WALL) + (6 if sx > 0 else 0), Z(z0)], fill=(102, 110, 122))
    cz = z0 + 0.55
    d.rectangle([X(chair - CHAIR_HALF), Z(cz + 0.53), X(chair + CHAIR_HALF), Z(cz - 0.54)], outline=(30, 50, 110), width=3)
    d.text((X(chair) - 30, Z(cz) - 14), '車いす', fill=(30, 50, 110), font=font)
    oz = cz + WC_AHEAD + 0.15
    d.ellipse([X(osh - O_HALF_W), Z(oz + O_DEPTH_HALF), X(osh + O_HALF_W), Z(oz - O_DEPTH_HALF)], outline=(40, 83, 171), width=3)
    d.text((X(osh) - 26, Z(oz) - 14), '大城', fill=(40, 83, 171), font=font)
    d.ellipse([X(tera - T_BACK), Z(oz + T_HALF_W), X(tera + T_FRONT), Z(oz - T_HALF_W)], outline=(200, 40, 40), width=3)
    d.text((X(tera) - 26, Z(oz) - 14), '寺島', fill=(200, 40, 40), font=font)
    if tera_ghost is not None:
        d.ellipse([X(tera_ghost - T_BACK), Z(oz + T_HALF_W), X(tera_ghost + T_FRONT), Z(oz - T_HALF_W)], outline=(200, 40, 40), width=2)
        d.text((X(tera_ghost) - 20, Z(oz) + 75), '0.5 m よけた所', fill=(200, 40, 40), font=font)
    if robot is not None:
        rz = cz + 0.2
        d.rectangle([X(robot - ROBOT_HALF), Z(rz + 0.38), X(robot + ROBOT_HALF), Z(rz - 0.38)], outline=(20, 140, 100), width=3)
        d.text((X(robot) - 60, Z(rz) - 14), 'ハコブくん', fill=(20, 140, 100), font=font)
    d.text((X(-WALL), Z(z0 + 2.0) - 36), title, fill=(0, 0, 0), font=font)
panel(2.4, '止まった所（両横とも狭い）', chair_x, oshiro_x, tera_x, None)
panel(0.0, '寄せて通る所（229 の位置）', 0.42, 0.42, tera_x, -0.4643, tera_ghost=tera_x - 0.5)
img.save(os.path.join(out, 'geo231_top.png'))
```

#### tools/readchk217.py（依頼231）

```python
"""依頼217：読みの確かめ。漢字の文の声と、ひらがなで読みを書いた文（ごかいひがし／ごかいとう）の声を、
MFCC の DTW の距離で比べ、どちらの読みに近いかを見る（同じ声・同じ種）。
使い方: python3 readchk217.py <漢字の wav> <ひがし の wav> <とう の wav>"""
import sys, wave, numpy as np
from scipy.fft import dct
def load(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(float) / 32768; return x, w.getframerate()
def trim(x, sr):
    e = np.array([np.sqrt(np.mean(x[i:i+160]**2)) for i in range(0, len(x)-160, 160)])
    on = np.where(e > 0.01)[0]; return x[on[0]*160:(on[-1]+1)*160]
def mfcc(x, sr, n=13):
    x = np.append(x[0], x[1:] - 0.97 * x[:-1]); fl, hop = int(0.025*sr), int(0.010*sr)
    fr = np.array([x[i:i+fl] * np.hamming(fl) for i in range(0, len(x)-fl, hop)])
    P = np.abs(np.fft.rfft(fr, 512))**2 / 512
    mel = lambda f: 2595*np.log10(1+f/700); imel = lambda m: 700*(10**(m/2595)-1)
    pts = imel(np.linspace(mel(0), mel(sr/2), 28)); b = np.floor(513*pts/sr).astype(int)
    fb = np.zeros((26, 257))
    for m in range(1, 27):
        for k in range(b[m-1], b[m]): fb[m-1, k] = (k-b[m-1])/max(1, b[m]-b[m-1])
        for k in range(b[m], b[m+1]): fb[m-1, k] = (b[m+1]-k)/max(1, b[m+1]-b[m])
    E = np.log(P @ fb.T + 1e-10); c = dct(E, type=2, axis=1, norm='ortho')[:, 1:n]
    return (c - c.mean(0)) / (c.std(0) + 1e-9)
def dtw(a, b):
    D = np.full((len(a)+1, len(b)+1), np.inf); D[0, 0] = 0
    d = np.sqrt(((a[:, None, :] - b[None, :, :])**2).sum(-1))
    for i in range(1, len(a)+1):
        for j in range(1, len(b)+1):
            D[i, j] = d[i-1, j-1] + min(D[i-1, j], D[i, j-1], D[i-1, j-1])
    return D[-1, -1] / (len(a) + len(b))
k, h, t = [mfcc(trim(*load(p)), 16000) for p in sys.argv[1:4]]
print("漢字の長さ %.2f 秒・ひがし %.2f・とう %.2f" % (len(k)/100, len(h)/100, len(t)/100))
dh, dt_ = dtw(k, h), dtw(k, t); print("DTW の距離 ひがし %.3f・とう %.3f → %s に近い" % (dh, dt_, "ひがし" if dh < dt_ else "とう"))
```

#### geo/geo231.txt（依頼231）

```text
ハコブくんの幅 0.639 m（手すりの高さ）・手すりの側を通るのに要る幅 = 手すり 0.053 + 幅 0.639 + すき間 0.15 = 0.842 m
■ 止まった時（車いす x 0.00・向き 0°、大城さん x 0.00、寺島さん x -0.55 で +x を向く）
  車いすの所：−x 側 0.513 m・+x 側 0.513 m（どちらも 0.842 より狭い → 通れない）
  大城さん・寺島さんの所：−x 側（寺島さんの背中と手すり）0.150 m・+x 側（大城さんと手すり）0.602 m（どちらも狭い → 通れない）
  寺島さんの前と大城さんの体の −x の端：0.162 m
■ 寺島さんが −x へ半歩 0.5 m よける
  背中から手すりまで 0.150 m（壁まで 0.210 m）。0.5 m よけると背中は x -1.190（手すりの外 0.350 m・壁の外 0.290 m）
  よけたあとも手すりの内に収まるには、はじめの寺島さんの根が x ≥ -0.200。大城さんの体（−x の端 -0.238）とぶつからないのは x ≤ -0.388 → 両方を満たす所は無い
■ 大城さんが車いすを +x 0.42 へ寄せた後、ハコブくんが空いた間を通る（229 の通り方）
  車いすの所の幅（−x の手すり〜車いすの一番近い点）0.919 m
  寺島さんがこの間（−x 側）に残る時に要る幅 = 寺島さんの奥行 0.290 + すき間 0.15 + ハコブくん 0.639 + すき間 0.15 = 1.229 m → 0.310 m 足りない
  大城さんの所（大城さんの体の −x の端 0.182）の幅 1.022 m → 0.207 m 足りない
  寺島さんが手すりに背中を付けても、ハコブくんの −x の端（寄った位置 x −0.4643 で -0.784）と寺島さんの前（-0.550）が 0.234 m 重なる
```

### 依頼232

#### tools/Closeup232.cs（依頼232）

```csharp
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>
    /// 依頼232：230 の真上の動画の床の線（中心・+0.28・+0.42・−0.33 の線と線の端の字）を、ハコブくん・大城さん・茂さん・車いすの下に描く。Closeup230.cs を写して、写した先で変えた。
    /// 動き・カメラ・真上のコマは 230 のまま。足したのは、真上のコマごとに「体だけを白く写した型」frames/yield_top_mask/f_*.png（黒＝床・白＝体）を撮ることだけ。
    /// 型は真上のカメラを写した別のカメラ（MaskCam232）で、体の部品だけを層 LayerMask232 に移し、白の Unlit/Color で写す（影・光は写らない）。写した後に層と材料を元に戻す。
    /// make232.py が床の線の層を、この型の白い所で消してから重ねる（線は床の上・体の下に見える）。
    /// 以下は 230 の説明：
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top232.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top232_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c232Views top）・静止画なし（-c232Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup232.Run \
    ///                 -c232Out <出力フォルダ> [-c232Script closeup229_script.json] [-c232Frames on|off] [-c232Stills on|off] [-c232Views main,top] [-c232From 秒] [-c232To 秒] [-c232Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames232.csv・bones232.csv・feet232.csv・wc232.csv・check232.txt・events232.txt
    /// </summary>
    public static class Closeup232
    {
        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 LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;   // 依頼232：体の型を写す間だけ体の部品を置く層

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c232Out", "");
            if (outDir == "") throw new Exception("-c232Out がない");
            string scriptName = CloseupArgs.Get("-c232Script", "closeup229_script.json");
            bool frames = CloseupArgs.Get("-c232Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c232Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c232Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c232From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c232To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk") talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.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;

                string shotName = "yield";
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c229"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                Texture2D bandTex = ScreenTex(TexDir + "/" + C["band"].S() + ".png");
                float bandOn = C["band_on"].F(), bandOff = C["band_off"].F(), happyFrom = C["happy_from"].F(), happyTo = C["happy_to"].F();
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                var SH = C["shift"]; float shT0 = SH["t0"].F(1e9f), shT1 = SH["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c232Until", "1e9"), IC)) * fps);
                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"); }   // 依頼232：_mask は体の型
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        if (mode == "stop" && stopped && behindN >= R.passBehind) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師
                    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;
                    chair.SetPositionAndRotation(nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead), nr.rotation);
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    bool bandNow = t >= bandOn - 1e-4f && t < bandOff - 1e-4f;
                    bool happyNow = t >= happyFrom - 1e-4f && t < happyTo - 1e-4f;
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", bandTex); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy" : 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 ? "帯" : "") + (happyNow ? "目まで笑う顔" : "基本") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        float d = RobotDist(rs, lr, Mathf.Min(gap, 1.5f));
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000"));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top232_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && inRange)
                    {
                        syncProxies(); scaleMouth();
                        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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            // 依頼232：体だけの型（同じ真上のカメラ・同じ大きさ）
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", 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();
                        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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames232.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top232.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones232.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet232.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc232.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check232.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events232.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C232] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        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;
        }

        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.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] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, 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);
        }
    }
}
```

#### tools/cmp232.py（依頼232）

```python
"""依頼232：230 と 232 の動きと真上の画面の位置を全部のコマで比べる（frames・bones・wc・feet・top の数の列、check・events・top_cam）。
使い方: python3 cmp232.py <230 の out> <232 の出力>"""
import csv, json, sys
A, B = sys.argv[1:3]
def load(p): return list(csv.DictReader(open(p)))
for name in ["frames", "bones", "wc", "feet", "top"]:
    ra, rb = load(f"{A}/{name}230.csv"), load(f"{B}/{name}232.csv")
    assert len(ra) == len(rb), (name, len(ra), len(rb))
    assert list(ra[0].keys()) == list(rb[0].keys()), name
    worst = 0.0; ndiff = 0
    for a, b in zip(ra, rb):
        for k in a:
            if a[k] == b[k]: continue
            ndiff += 1
            try: worst = max(worst, abs(float(a[k]) - float(b[k])))
            except ValueError: worst = float("inf")
    print(f"{name}: {len(ra)} コマ・{len(ra[0])} 列・違うセル {ndiff}・差の最大 {worst}")
ca, cb = json.load(open(f"{A}/top230_cam.json")), json.load(open(f"{B}/top232_cam.json"))
print("top_cam:", "同じ" if ca == cb else f"違う {ca} {cb}")
for n in ["check", "events"]:
    a = open(f"{A}/{n}230.txt", encoding="utf-8").read(); b = open(f"{B}/{n}232.txt", encoding="utf-8").read()
    b = b.split("依頼232 体の型")[0] + (b.split("入れない部品")[1].split("\n", 1)[1] if "入れない部品" in b else "")
    print(f"{n}:", "同じ（依頼232 の部品の一覧を除く）" if a == b else "違う")
```

#### tools/make232.py（依頼232）

```python
"""依頼232：make230.py を写して変えた。床の目印の線（中心・+0.28・+0.42・−0.33）と線の端の字の層を、Closeup232.cs が撮った体の型
（frames/yield_top_mask：白＝ハコブくん・大城さん・茂さん・車いす）の所で消してから重ねる（線は床の上・体の下に見える）。
通った跡・印・左上の字は 230 のまま（体の上に重ねる）。重ねる順も 230 のまま（コマ → 跡 → 線 → 印 → 左上の字）。
あわせて、型を使わない 230 の重ね方のコマも作り、型の外は 1 画素も違わないこと・型の所に線が残っていないことを数え、
230 の重ね方の動画（<Unity の出力>/closeup232_as230.mp4）も作る（230 の動画と md5 が同じかを確かめるため）。
使い方: python3 make232.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ> [寄りの静止画のコマ,…]
以下は 230 の説明：
依頼230：229 の真上のコマ（Closeup230.cs が動かない真上のカメラで撮った frames/yield_top）に、床の目印・通った跡・印・左上の字を重ねて
closeup230_yield_top.mp4（音なし）と静止画 3 枚を作り、確かめ（check230_top.txt）を書く。
目印・跡は Unity のカメラで写した位置（top230.csv の画面の位置・top230_cam.json の写し方）に 2 倍の大きさで描いて縮める。
時刻は動画の秒（台本の秒 − video_from）。
使い方: python3 make230.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, VD = sys.argv[1:4]
ZOOM = dict((int(x.split(":")[0]), x.split(":")[1]) for x in sys.argv[4].split(",")) if len(sys.argv) > 4 else {}   # 依頼232：寄りの静止画のコマ:寄る物（robot｜chair｜x,y）
ZOOM_F = list(ZOOM)
os.makedirs(VD, exist_ok=True)
C = json.load(open(SC))["shots"][0]["c229"]
CAM = json.load(open(os.path.join(D, "top232_cam.json")))
FPS, W, H, S = 30, 1920, 1080, 2          # S：描く倍率（2 倍で描いて縮める）
f0, f1 = int(round(C["video_from"] * FPS)), int(round(C["video_to"] * FPS))
n = f1 - f0 + 1
vt = lambda f: (f - f0) / FPS             # 動画の秒

# ---- 決めた値（1920×1080 の画面での px）
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {
    "center": (120, 120, 120),       # 廊下の中心の線（細い実線・灰色）
    "x028": (21, 101, 192),          # 車いすの始めの線 +0.28（破線・青）
    "x042": (142, 36, 170),          # 寄せたあとの線 +0.42（破線・紫）
    "lane": (46, 173, 107),          # ハコブくんのふだんの線 −0.33（破線・ハコブくんの輪の光に近い緑）
    "chair": (239, 108, 0),          # 車いすの通った跡（実線・橙）
    "robot": (0, 105, 92),           # ハコブくんの通った跡（実線・深い青緑）
}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16

# ---- 床の点 → 画面（Unity のカメラで写した 3 点から。正射影なので一次式）
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)   # (x, z)

rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames232.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top232.csv")))}
ev = open(os.path.join(D, "events232.txt"), encoding="utf-8").read()
t_trig = float(re.search(r"([\d.]+) 秒 決まりに当たった", ev).group(1))
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_sh0, t_sh1 = C["shift"]["t0"], C["shift"]["t1"]
# 印：(どれ, 台本の秒, 字の頭)。出す時刻 = その秒のコマ
MARKS = [("chair", t_sh0, "寄せ始め"), ("chair", t_sh1, "寄せ終わり"), ("robot", t_trig, "寄り始め"), ("robot", t_stop, "止まった")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]

def font(px): return ImageFont.truetype(FONT_PATH, px * S)
FL, FM, FH = font(LINE_LABEL_PX), font(MARK_LABEL_PX), font(HUD_PX)
def sc(p): return (p[0] * S, p[1] * S)

def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy
    bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)

def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1)
    L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L
    s = 0.0
    while s < L:
        e = min(L, s + DASH * S)
        d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S)
        s += (DASH + GAP) * S

def down(layer): return layer.resize((W, H), Image.LANCZOS)

# ---- 動かない層：中心の線・目印の線と字
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x028": 0.28, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x028", "x042", "lane"):
    dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
# 字：始め +0.28（線の上）と寄せたあと +0.42（線の下）は左の端（車いすが来るのは右の端なので、入ってくる所と寄せる所を隠さない）、ハコブくんのふだん −0.33 は右の端（ハコブくんが行かない側）
text_box(d, (sc((14, line_py["x028"] - 8))), "始め +0.28", FL, COL["x028"], "lb", edge=COL["x028"])
text_box(d, (sc((14, line_py["x042"] + 8))), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, (sc((W - 14, line_py["lane"] - 8))), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st)

# ---- 印の層（時刻になったら出す）。字は車いすの印は廊下の下、ハコブくんの印は廊下の上へ引き出す
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    nrob = 0
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (0 if head == "寄せ始め" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "止まった" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        text_box(d, sc((px, ly)), f"{head} {vt(mark_f[i]):.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)

# ---- 左上の字
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]
    cx = num_ok(r["chair_x"]); g = num_ok(r["gap_m"])
    return [f"{vt(f):.1f} 秒",
            "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None else "—")]

# ---- コマを作る
tmp = tempfile.mkdtemp(prefix="m232_", dir="/tmp"); tmp230 = tempfile.mkdtemp(prefix="m232as230_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}
shown = [False] * len(MARKS); mcache = mark_layer(shown)
chk = {"trail_err_m": {"chair": 0.0, "robot": 0.0}, "mark_first": [None] * len(MARKS), "hud_bad": 0, "hud_dash": {1: 0, 2: 0}, "hud_texts": []}
stills = {}; zooms = {}; per = []
for k, f in enumerate(range(f0, f1 + 1)):
    r = top[f]
    for who, kx, ky, wx, wz in (("chair", "axle_px", "axle_py", "axle_x", "axle_z"), ("robot", "robot_px", "robot_py", "robot_x", "robot_z")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)   # 描く点（2 倍の画面の整数の点）
        bx, bz = from_px(*p)
        chk["trail_err_m"][who] = max(chk["trail_err_m"][who], math.hypot(bx - float(r[wx]), bz - float(r[wz])))
        if prev[who] is not None:
            td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2
        td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))   # 線のつなぎ目を丸く
        prev[who] = p
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True; chk["mark_first"][i] = vt(f)
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", "yield_top", f"f_{f:05d}.png")).convert("RGBA")
    mk = Image.open(os.path.join(D, "frames", "yield_top_mask", f"f_{f:05d}.png")).convert("L")   # 依頼232：体の型
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static.getchannel("A"), ImageChops.invert(mk)))   # 線の層を体の所で消す
    trail_d = down(trail)
    im = raw.copy(); im.alpha_composite(trail_d); im.alpha_composite(st_m); im.alpha_composite(mcache)
    im230 = raw.copy(); im230.alpha_composite(trail_d); im230.alpha_composite(static); im230.alpha_composite(mcache)   # 230 の重ね方
    lines = hud_lines(f)
    for i in (1, 2):
        if lines[i].endswith("—"): chk["hud_dash"][i] += 1
    if any(re.search(r"\d{5,}|nan|inf", s, re.I) for s in lines): chk["hud_bad"] += 1
    if k % 30 == 0: chk["hud_texts"].append(" / ".join(lines))
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl)
    x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    hl_d = down(hl)
    im.alpha_composite(hl_d); im230.alpha_composite(hl_d)
    out = im.convert("RGB"); out.save(os.path.join(tmp, f"v_{k:05d}.png"))
    o230 = im230.convert("RGB"); o230.save(os.path.join(tmp230, f"v_{k:05d}.png"))
    # 依頼232 の確かめ：型の外（型 0）で 230 の重ね方と違う画素・型が白い所（255）に線の層が残る画素・230 で線が体に重なっていた画素
    zero = mk.point(lambda v: 255 if v == 0 else 0); full = mk.point(lambda v: 255 if v == 255 else 0)
    dd = ImageChops.difference(out, o230).convert("L").point(lambda v: 255 if v else 0)
    n_out = ImageChops.multiply(dd, zero).histogram()[255]
    left = ImageChops.multiply(st_m.getchannel("A").point(lambda v: 255 if v else 0), full).histogram()[255]
    over = ImageChops.multiply(static.getchannel("A").point(lambda v: 255 if v else 0), full).histogram()[255]
    per.append((f, n_out, left, over))
    if f in ZOOM_F: zooms[f] = (out.copy(), o230.copy())
    for name, ff in (("s1_shift_start", mark_f[0]), ("s2_shift_end", mark_f[1]), ("s3_last", f1)):
        if f == ff: stills[name] = out.copy()
vid = os.path.join(VD, "closeup232_yield_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vid], check=True)
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp230, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", os.path.join(D, "closeup232_as230.mp4")], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for name, im in stills.items(): im.save(os.path.join(sd, name + ".png"))

# ---- 確かめ
o = []
o.append(f"コマ {n}（{f0}〜{f1}）・動画 {n / FPS:.3f} 秒")
o.append(f"写し方：画面の点 = ({ox:.4f}, {oy:.4f}) + x×({xx:.4f}, {xy:.4f}) + z×({zx:.4f}, {zy:.4f}) px（1 m = {math.hypot(zx, zy):.3f} px・1 px = {1000 / math.hypot(zx, zy):.2f} mm）")
o.append(f"写す範囲：z {z_lo:.3f}〜{z_hi:.3f}（{z_hi - z_lo:.3f} m）・x {from_px(0, 0)[0]:.3f}〜{from_px(0, H)[0]:.3f}（{from_px(0, H)[0] - from_px(0, 0)[0]:.3f} m）")
for k2, x in LINES.items():
    py = line_py[k2]; back = from_px(W / 2, py)[0]
    o.append(f"目印の線 {k2}：x {x:+.2f} → 画面の y {py:.2f} px（画面から戻した x {back:+.5f}）")
o.append(f"手すり（内側の面 x ±0.84）：画面の y {to_px(-0.84, 0)[1]:.2f}〜{to_px(0.84, 0)[1]:.2f} px（{to_px(0.84, 0)[1] - to_px(-0.84, 0)[1]:.1f} px ＝ 画面の高さの {(to_px(0.84, 0)[1] - to_px(-0.84, 0)[1]) / H * 100:.1f}%）")
o.append(f"通った跡の点と本当の位置のずれの最大：車いすの後ろの車軸の真ん中 {chk['trail_err_m']['chair'] * 100:.3f} cm・ハコブくんの根 {chk['trail_err_m']['robot'] * 100:.3f} cm")
for (who, t, head), fv in zip(MARKS, chk["mark_first"]):
    o.append(f"印 {who} {head}：台本 {t:.4f} 秒（動画 {t - C['video_from']:.3f} 秒）→ 出たコマの動画の秒 {fv:.3f}")
o.append(f"左上の字：壊れた値のコマ {chk['hud_bad']}・車いすの横の位置が「—」のコマ {chk['hud_dash'][1]}・すき間が「—」のコマ {chk['hud_dash'][2]}")
o += ["  " + s for s in chk["hud_texts"]]
# 画面の中か（2＝全部・1＝一部・0＝外）
def spans(key):
    out, cur = [], None
    for f in range(f0, f1 + 1):
        v = int(top[f][key])
        if cur is None or cur[0] != v: cur = [v, vt(f), vt(f)]; out.append(cur)
        else: cur[2] = vt(f)
    return " ／ ".join(f"{['外', '一部', '全部'][v]} {a:.3f}〜{b:.3f}" for v, a, b in out)
for key, nm in (("chair_in", "車いす"), ("robot_in", "ハコブくん"), ("nurse_in", "大城さん")):
    o.append(f"{nm}が画面の中か：{spans(key)}")
a, b = int(round((t_sh0 - 1.0) * FPS)), int(round(t_sh1 * FPS))
o.append(f"寄せ始めの 1 秒前〜寄せ終わり（動画 {vt(a):.3f}〜{vt(b):.3f}）の車いす：全部が画面の中でないコマ {sum(1 for f in range(a, b + 1) if int(top[f]['chair_in']) != 2)}")
# 依頼232：体の下の線
o.append(f"依頼232 型の外（型 0）で 230 の重ね方と違う画素：全部のコマの合計 {sum(p[1] for p in per)}・1 コマの最大 {max(p[1] for p in per)}")
o.append(f"依頼232 型が白い所（体）に線の層が残る画素：合計 {sum(p[2] for p in per)}・1 コマの最大 {max(p[2] for p in per)}")
o.append(f"依頼232 230 の重ね方で線が体に重なっていた画素（今は消えた）：線が体に重なるコマ {sum(1 for p in per if p[3] > 0)}／{len(per)}・1 コマの最大 {max(p[3] for p in per)}")
open(os.path.join(D, "per232.csv"), "w").write("frame,diff_outside_mask,line_left_on_body,line_over_body_230\n" + "".join(f"{a},{b},{c},{d}\n" for a, b, c, d in per))
# 依頼232：寄りの静止画（線が体に重なるコマ。体の型の白い所のうち 230 で線が重なっていた所のまわりを 3 倍に寄せ、上に 230・下に 232）
zd = os.path.join(VD, "stills_zoom"); os.makedirs(zd, exist_ok=True)
for f, (a, b) in sorted(zooms.items()):
    mk = Image.open(os.path.join(D, "frames", "yield_top_mask", f"f_{f:05d}.png")).convert("L").point(lambda v: 255 if v == 255 else 0)
    r = top[f]; who = ZOOM[f]
    if who == "robot": cx, cy = float(r["robot_px"]), float(r["robot_py"])
    elif who == "chair": cx, cy = float(r["axle_px"]), float(r["axle_py"])
    else: cx, cy = map(float, who.split("/"))
    cx, cy = int(round(cx)), int(round(cy)); bw, bh = 480, 270
    x0 = min(max(0, cx - bw // 2), W - bw); y0 = min(max(0, cy - bh // 2), H - bh)
    box = (x0, y0, x0 + bw, y0 + bh); zw = 1200; zh = zw * bh // bw
    pane = Image.new("RGB", (zw, zh * 2 + 60), (255, 255, 255)); pd = ImageDraw.Draw(pane)
    pane.paste(b.crop(box).resize((zw, zh), Image.NEAREST), (0, 30)); pane.paste(a.crop(box).resize((zw, zh), Image.NEAREST), (0, zh + 60))
    fz = ImageFont.truetype(FONT_PATH, 24)
    pd.text((8, 2), f"230（線が体の上）動画 {vt(f):.3f} 秒・画面 x {box[0]}〜{box[2]}・y {box[1]}〜{box[3]}", font=fz, fill=(0, 0, 0))
    pd.text((8, zh + 32), f"232（線が体の下）", font=fz, fill=(0, 0, 0))
    nm = f"z_{vt(f):06.3f}s_f{f}.png"; pane.save(os.path.join(zd, nm))
    hitc = ImageChops.multiply(static.getchannel('A').point(lambda v: 255 if v else 0), mk).crop(box).histogram()[255]
    leftc = ImageChops.multiply(ImageChops.multiply(static.getchannel("A"), ImageChops.invert(Image.open(os.path.join(D, "frames", "yield_top_mask", f"f_{f:05d}.png")).convert("L"))).point(lambda v: 255 if v else 0), mk).crop(box).histogram()[255]
    o.append(f"寄りの静止画 {nm}（{who}）：範囲 {box}・230 で線が体に重なっていた画素 {hitc}・232 で体の所に残る線の画素 {leftc}")
open(os.path.join(D, "check232_top.txt"), "w", encoding="utf-8").write("\n".join(o) + "\n")
print("\n".join(o)); print("動画", vid)
```

#### tools/run232.sh（依頼232）

```bash
#!/bin/bash
# 依頼232 使い方: run232.sh <出力フォルダ> <コマ on|off> [views] [until]
OUT="$1"; FR="${2:-off}"; VW="${3:-top}"; UNTIL="${4:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup232.Run \
   -c232Out "$OUT" -c232Frames "$FR" -c232Stills off -c232Script closeup229_script.json -c232Views "$VW" -c232Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

### 依頼233

#### tools/feas233.py（依頼233）

```python
"""依頼233：寄せて通る形があるかの計算（真上の2次元・長方形で近似）。
車いす（根から x ±0.326・前後 −0.430〜+0.640。229 の Unity で測った範囲）、大城さん（根は車いすの根の後ろ 0.594・体 幅 ±0.238・奥行 ±0.157）、
ハコブくん（根から x ±0.330・前後 −0.380〜+0.382、寄った位置 x −0.4643 で止まる。229）。
車いすは 229 の寄せ方の決まり（前へ進みながら・向き 8° まで・横の速さ 0.12 m/秒まで・寄せ終わりで向き 0°）で、廊下の真ん中 x 0.00 から寄せる。
向きは道に沿って 0 → 最大 → 0（変わる所の長さ a）。最大 8°・a を変えて、寄せ終わりまでに前へ進む長さと、ハコブくんとのすき間の最小を出す"""
import math, sys
import numpy as np
RX = -0.4643; RHX = 0.330; RF, RB = 0.382, 0.380
CX0, CX1, CF, CB = -0.326, 0.326, 0.640, 0.430
def rect_pts(cx, cz, yaw, x0, x1, f, b, n=12):
    # 前＝−z。yaw は +x へ向く角度
    s, c = math.sin(yaw), math.cos(yaw)
    pts = []
    for i in range(n + 1):
        for (lx, lu) in ((x0 + (x1 - x0) * i / n, f), (x0 + (x1 - x0) * i / n, -b), (x0, -b + (f + b) * i / n), (x1, -b + (f + b) * i / n)):
            pts.append((cx + lx * c + lu * s, cz - lu * c + lx * s))
    return pts
def dist_robot(pts, rz):
    best = 9.0
    for (x, z) in pts:
        dx = max(RX - RHX - x, 0, x - (RX + RHX)); dz = max(rz - RB - z, 0, z - (rz + RF))
        inside = dx == 0 and dz == 0
        d = -1.0 if inside else math.hypot(dx, dz)
        best = min(best, d)
    return best
def run(DX, ang_deg, a, G, ds=0.002):
    rz = 0.0; zfront = rz + RF + G           # 足のせの前の端
    root_z0 = zfront + CF
    tmax = math.tan(math.radians(ang_deg))
    # 向き θ(s)：0→ang（長さ a）・平ら（長さ p）・ang→0（長さ a）。横の動き＝∫tanθ ds = tmax の近似で解く
    # p を二分法で
    def lat(p):
        x = 0.0; s = 0.0; L = 2 * a + p
        while s < L:
            th = math.radians(ang_deg) * (min(1, s / a) if s < a else 1 if s < a + p else max(0, (L - s) / a))
            x += math.tan(th) * ds; s += ds
        return x
    lo, hi = 0.0, 20.0
    if lat(0.0) > DX:   # 平らが無くても寄りすぎ → 角度を下げる代わりに a を縮めずにそのまま（報告用に記す）
        hi = 0.0
    for _ in range(40):
        mid = 0.5 * (lo + hi)
        if lat(mid) < DX: lo = mid
        else: hi = mid
    p = hi; L = 2 * a + p
    x = 0.0; s = 0.0; gmin = 9.0; gmin_s = 0; x_at = []
    while s <= L + 1e-9:
        th = math.radians(ang_deg) * (min(1, s / a) if s < a else 1 if s < a + p else max(0, (L - s) / a))
        # 車軸は根の後ろ 0.15。根の位置（x, z）
        ax_z = root_z0 + 0.15 - s; ax_x = x
        rx_ = ax_x + 0.15 * math.sin(th); rz_ = ax_z - 0.15 * math.cos(th)
        pts = rect_pts(rx_, rz_, th, CX0, CX1, CF, CB)
        # 大城さん
        ox = rx_ - 0.594 * math.sin(th); oz = rz_ + 0.594 * math.cos(th)
        pts += rect_pts(ox, oz, th, -0.238, 0.238, 0.157, 0.157, 6)
        g = dist_robot(pts, rz)
        if g < gmin: gmin, gmin_s = g, s
        x += math.tan(th) * ds; s += ds
    return L, gmin, gmin_s
out = []
P = lambda t: (print(t), out.append(t))
P("寄せる横の長さ ΔX と、向きの最大 8° で前へ進む長さの下限（向きが一瞬で変わるとしても）= ΔX / tan 8°")
for DX, why in ((0.42, "229 と同じ x +0.42 へ"), (0.346, "寄った位置のハコブくんと 0.15 m あくのに要る最小（229：+0.42 で 0.224 m）"), (0.4805, "ふだんの位置 x −0.33 のハコブくんと 0.15 m あくのに要る最小（+0.42 で 0.0895 m）")):
    P(f"  ΔX {DX:.4f}（{why}）：{DX / math.tan(math.radians(8)):.3f} m")
P("止まった時の足のせの前の端とハコブくんの前の端のあいだ G（229 の決まりで止まると 2.30 m。できるだけ守る 2.0〜3.0 m）")
P("向きの変わる所の長さ a・前へ進む長さ L・ハコブくん（x −0.4643 で止まったまま）と車いす/大城さんのすき間の最小（負は重なる）")
for G in (2.0, 2.3, 3.0):
    for DX in (0.42, 0.346):
        for a in (0.3, 0.6, 1.0):
            L, g, gs = run(DX, 8.0, a, G)
            P(f"  G {G:.1f}・ΔX {DX:.3f}・a {a:.1f}：前へ {L:.3f} m 進む（足のせの前の端がハコブくんの前の端を {L - G:+.3f} m 越える）・すき間の最小 {g:.3f} m（前へ {gs:.2f} m の所）")
open(sys.argv[1] if len(sys.argv) > 1 else "/tmp/c233/geo/feas233.txt", "w").write("\n".join(out) + "\n")

# ---------------------------------------------------------------- 依頼233 の置き方（寺島さんは +x 側）と、寄せる所のくわしい値
P("")
P("■ 止まった所の置き方（車いす x 0.00・向き 0°・大城さん x 0.00、寺島さんは大城さんの +x 側で −x を向く。寸法は 231 の terashima231.txt）")
RAIL = 0.84; NEED = 0.053 + 0.639 + 0.15
O_HW, O_HD = 0.2381, 0.157
T_F, T_B, T_HW = 0.1499, 0.1399, 0.2381
for g in (0.10, 0.15):
    xT = O_HW + g + T_F
    P(f"  寺島さんと大城さんのすき間 {g:.2f} m に置くと：寺島さんの根 x {xT:+.3f}・背中 x {xT + T_B:+.3f}（手すりと {RAIL - xT - T_B:.3f} m）")
P(f"  車いすの所：−x 側 {(-0.326) + RAIL:.3f} m・+x 側 {RAIL - 0.326:.3f} m／大城さん・寺島さんの所：−x 側（大城さんと手すり）{RAIL - O_HW:.3f} m・+x 側（寺島さんの背中と手すり）0.162〜0.212 m")
P(f"  ハコブくんが手すりの側を通るのに要る幅 {NEED:.3f} m（231 と同じ）→ どこも狭く、通れない")
P(f"  寺島さんが後ろから追いついて横に並ぶ時（前を向いて歩く・幅 {2*T_HW:.3f} m）：大城さんの +x の端 {O_HW:.3f} と手すり {RAIL:.2f} の間 {RAIL - O_HW:.3f} m → 真ん中を歩いて両側 {(RAIL - O_HW - 2*T_HW) / 2:.3f} m ずつ")
P(f"  寺島さんの横（大城さんと同じ z）で、大城さんが寺島さんの顔を見るのに要る顔の向き：約 {math.degrees(math.atan2(O_HW + 0.15 + T_F, -0.09)) :.0f}°（228・229 の大城さんの顔の向きの最大 34°。大城さんの顔は Head の骨だけで回す作り）")

P("")
P("■ その場で寄せる形（依頼の形：車いすの前に空いている所の中で寄せ、寺島さんが下がって大城さんの寄る所を空ける）")
for G in (2.3, 3.0):
    for a in (0.0, 0.6):
        D = G - 0.15
        lat = math.tan(math.radians(8)) * max(0.0, D - a)
        P(f"  足のせとハコブくんのあいだ {G:.1f} m・前へ {D:.2f} m まで（ハコブくんの前の端と 0.15 m）・向きの変わる所 {a:.1f} m：寄せられる横の長さ {lat:.3f} m"
          f"（x +0.42 まで {0.42 - lat:.3f} m 足りない・寄った位置のハコブくんと 0.15 m あく x +0.346 まで {max(0.0, 0.346 - lat):.3f} m 足りない）")

P("")
P("■ 前へ進んでハコブくんの横まで行く形（229 の寄せ方の決まりで、当たらずに寄せられる形）で、寺島さんが動かない時の大城さんとのすき間")
def tera_gap(DX, a, G, xT, zrel):
    rz = 0.0; zfront = rz + RF + G; root_z0 = zfront + CF; oz0 = root_z0 + 0.594
    tz = oz0 + zrel
    tpts = rect_pts(xT, tz, -math.pi / 2, -T_HW, T_HW, T_F, T_B, 8)
    ds = 0.002; tmax = math.radians(8.0)
    def lat(p):
        x = 0.0; s = 0.0; L = 2 * a + p
        while s < L:
            th = tmax * (min(1, s / a) if s < a else 1 if s < a + p else max(0, (L - s) / a)); x += math.tan(th) * ds; s += ds
        return x
    lo, hi = 0.0, 20.0
    for _ in range(40):
        mid = 0.5 * (lo + hi)
        if lat(mid) < DX: lo = mid
        else: hi = mid
    p = hi; L = 2 * a + p; x = 0.0; s = 0.0; best = 9.0
    while s <= L:
        th = tmax * (min(1, s / a) if s < a else 1 if s < a + p else max(0, (L - s) / a))
        ax_z = root_z0 + 0.15 - s; rx_ = x + 0.15 * math.sin(th); rz_ = ax_z - 0.15 * math.cos(th)
        ox = rx_ - 0.594 * math.sin(th); oz = rz_ + 0.594 * math.cos(th)
        opts = rect_pts(ox, oz, th, -O_HW, O_HW, O_HD, O_HD, 6) + rect_pts(rx_, rz_, th, CX0, CX1, CF, CB)
        for (px_, pz_) in opts:
            # 寺島さんの長方形（−x を向く）の中か・距離
            lx = -(pz_ - tz); lu = -(px_ - xT)   # 寺島さんの枠：横＝z・前＝−x
            dx = max(-T_HW - lx, 0, lx - T_HW); du = max(-T_B - lu, 0, lu - T_F)
            best = min(best, -1.0 if dx == 0 and du == 0 else math.hypot(dx, du))
        x += math.tan(th) * ds; s += ds
    return best
for zrel in (0.0, -0.2):
    g = tera_gap(0.42, 0.6, 2.3, O_HW + 0.15 + T_F, zrel)
    P(f"  寺島さん x {O_HW + 0.15 + T_F:+.3f}・大城さんより前へ {abs(zrel):.1f} m：下がらなくても大城さん・車いすとのすき間の最小 {g:.3f} m（大城さんは前へ離れていく）→ 下がる距離 0 m で当たらない")
open(sys.argv[1] if len(sys.argv) > 1 else "/tmp/c233/geo/feas233.txt", "w").write("\n".join(out) + "\n")
```

#### tools/fig233.py（依頼233）

```python
"""依頼233：止まった所と、229 の寄せ方で寄せる形の真上の図（左が −x・上が +z〔車いすの来る側〕）。1 m = 260 px
使い方: python3 fig233.py <出力 png>"""
import sys, math
from PIL import Image, ImageDraw, ImageFont
S = 260; RAIL = 0.84; WALL = 0.90
W, H = int(2.4 * S) * 2 + 60, int(6.9 * S)
img = Image.new('RGB', (W, H), (235, 232, 224)); d = ImageDraw.Draw(img)
font = ImageFont.truetype('/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc', 24)
def panel(ox, title, shift):
    X = lambda x: int(ox + 1.2 * S + x * S); Z = lambda z: int(H - 0.9 * S - z * S)
    d.rectangle([X(-WALL), Z(5.6), X(WALL), Z(-0.6)], fill=(219, 214, 201))
    for sx in (-1, 1):
        d.line([X(sx * RAIL), Z(5.6), X(sx * RAIL), Z(-0.6)], fill=(160, 120, 70), width=3)
    d.text((X(-WALL), Z(5.6) - 64), title, fill=(0, 0, 0), font=font)
    def rect(cx, cz, yaw, x0, x1, f, b, col, w=3):
        s, c = math.sin(yaw), math.cos(yaw)
        P = [(x0, f), (x1, f), (x1, -b), (x0, -b)]
        d.polygon([(X(cx + lx * c + lu * s), Z(cz - lu * c + lx * s)) for lx, lu in P], outline=col, width=w)
    # ハコブくん（止まった所 x −0.4643・前の端 z 0.382）
    rect(-0.4643, 0.0, 0.0, -0.33, 0.33, 0.380, 0.382, (20, 140, 100))   # ハコブくんは +z を向く（後ろ 0.380・前 0.382）
    d.text((X(-0.46) - 50, Z(0.0) - 12), 'ハコブ', fill=(20, 140, 100), font=font)
    G = 2.3; zf = 0.382 + G; root = zf + 0.64; oz = root + 0.594
    if not shift:
        rect(0.0, root, 0.0, -0.326, 0.326, 0.64, 0.43, (30, 50, 110)); d.text((X(0) - 32, Z(root) - 12), '車いす', fill=(30, 50, 110), font=font)
        rect(0.0, oz, 0.0, -0.238, 0.238, 0.157, 0.157, (40, 83, 171)); d.text((X(0) - 22, Z(oz) - 12), '大城', fill=(40, 83, 171), font=font)
        rect(0.538, oz, -math.pi / 2, -0.238, 0.238, 0.15, 0.14, (200, 40, 40)); d.text((X(0.538) - 22, Z(oz) + 40), '寺島', fill=(200, 40, 40), font=font)
        d.line([X(-RAIL), Z(root), X(-0.326), Z(root)], fill=(200, 0, 0), width=2); d.text((X(-RAIL) + 4, Z(root) + 4), '0.514', fill=(200, 0, 0), font=font)
        d.line([X(0.326), Z(root), X(RAIL), Z(root)], fill=(200, 0, 0), width=2); d.text((X(0.36), Z(root) + 4), '0.514', fill=(200, 0, 0), font=font)
        d.line([X(-0.9), Z(zf), X(0.9), Z(zf)], fill=(120, 120, 120), width=1)
        d.text((X(-0.15), Z((zf + 0.382) / 2) - 12), f'{G:.2f} m', fill=(80, 80, 80), font=font)
        d.text((X(-WALL), Z(-0.6) + 8), '要る幅 0.842 m（どちら側も狭い）', fill=(0, 0, 0), font=font)
    else:
        # 229 の寄せ方：向き 8°・向きの変わる所 0.6 m・x 0 → +0.42
        a = 0.6; tm = math.radians(8); ds = 0.01
        def lat(p):
            x = 0; s = 0; L = 2 * a + p
            while s < L:
                th = tm * (min(1, s / a) if s < a else 1 if s < a + p else max(0, (L - s) / a)); x += math.tan(th) * ds; s += ds
            return x
        lo, hi = 0, 20
        for _ in range(30):
            m = (lo + hi) / 2
            if lat(m) < 0.42: lo = m
            else: hi = m
        p = hi; L = 2 * a + p; x = 0; s = 0; k = 0
        while s <= L + 1e-9:
            th = tm * (min(1, s / a) if s < a else 1 if s < a + p else max(0, (L - s) / a))
            az = root + 0.15 - s; rx = x + 0.15 * math.sin(th); rz = az - 0.15 * math.cos(th)
            if k % 60 == 0 or s + ds > L:
                last = s + ds > L
                col = (30, 50, 110) if last or k == 0 else (150, 160, 190)
                rect(rx, rz, -th, -0.326, 0.326, 0.64, 0.43, col, 3 if last or k == 0 else 1)
                rect(rx - 0.594 * math.sin(th), rz + 0.594 * math.cos(th), -th, -0.238, 0.238, 0.157, 0.157, (40, 83, 171) if last or k == 0 else (160, 175, 210), 3 if last or k == 0 else 1)
            x += math.tan(th) * ds; s += ds; k += 1
        rect(0.538, oz, -math.pi / 2, -0.238, 0.238, 0.15, 0.14, (200, 40, 40)); d.text((X(0.538) - 22, Z(oz) + 40), '寺島', fill=(200, 40, 40), font=font)
        d.text((X(-WALL), Z(-0.6) + 8), f'前へ {L:.2f} m 進んで x +0.42（向き 8°まで）', fill=(0, 0, 0), font=font)
        # その場で寄せられる所（前へ 2.15 m まで）
        d.line([X(-0.9), Z(0.382 + 0.15), X(0.9), Z(0.382 + 0.15)], fill=(200, 0, 0), width=2)
        d.text((X(-0.25), Z(0.382 + 0.15) + 4), 'ハコブくんの前 0.15 m', fill=(200, 0, 0), font=font)
panel(0, '止まった所（両横の幅）', False)
panel(int(2.4 * S) + 60, '229 の寄せ方で x +0.42 へ', True)
img.save(sys.argv[1])
```

#### tools/readchk.py（依頼233）

```python
"""依頼217：読みの確かめ。漢字の文の声と、ひらがなで読みを書いた文（ごかいひがし／ごかいとう）の声を、
MFCC の DTW の距離で比べ、どちらの読みに近いかを見る（同じ声・同じ種）。
使い方: python3 readchk217.py <漢字の wav> <ひがし の wav> <とう の wav>"""
import sys, wave, numpy as np
from scipy.fft import dct
def load(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(float) / 32768; return x, w.getframerate()
def trim(x, sr):
    e = np.array([np.sqrt(np.mean(x[i:i+160]**2)) for i in range(0, len(x)-160, 160)])
    on = np.where(e > 0.01)[0]; return x[on[0]*160:(on[-1]+1)*160]
def mfcc(x, sr, n=13):
    x = np.append(x[0], x[1:] - 0.97 * x[:-1]); fl, hop = int(0.025*sr), int(0.010*sr)
    fr = np.array([x[i:i+fl] * np.hamming(fl) for i in range(0, len(x)-fl, hop)])
    P = np.abs(np.fft.rfft(fr, 512))**2 / 512
    mel = lambda f: 2595*np.log10(1+f/700); imel = lambda m: 700*(10**(m/2595)-1)
    pts = imel(np.linspace(mel(0), mel(sr/2), 28)); b = np.floor(513*pts/sr).astype(int)
    fb = np.zeros((26, 257))
    for m in range(1, 27):
        for k in range(b[m-1], b[m]): fb[m-1, k] = (k-b[m-1])/max(1, b[m]-b[m-1])
        for k in range(b[m], b[m+1]): fb[m-1, k] = (b[m+1]-k)/max(1, b[m+1]-b[m])
    E = np.log(P @ fb.T + 1e-10); c = dct(E, type=2, axis=1, norm='ortho')[:, 1:n]
    return (c - c.mean(0)) / (c.std(0) + 1e-9)
def dtw(a, b):
    D = np.full((len(a)+1, len(b)+1), np.inf); D[0, 0] = 0
    d = np.sqrt(((a[:, None, :] - b[None, :, :])**2).sum(-1))
    for i in range(1, len(a)+1):
        for j in range(1, len(b)+1):
            D[i, j] = d[i-1, j-1] + min(D[i-1, j], D[i, j-1], D[i-1, j-1])
    return D[-1, -1] / (len(a) + len(b))
k, h, t = [mfcc(trim(*load(p)), 16000) for p in sys.argv[1:4]]
print("漢字の長さ %.2f 秒・ひがし %.2f・とう %.2f" % (len(k)/100, len(h)/100, len(t)/100))
dh, dt_ = dtw(k, h), dtw(k, t); print("DTW の距離 ひがし %.3f・とう %.3f → %s に近い" % (dh, dt_, "ひがし" if dh < dt_ else "とう"))
```

#### geo/feas233.txt（依頼233）

```text
寄せる横の長さ ΔX と、向きの最大 8° で前へ進む長さの下限（向きが一瞬で変わるとしても）= ΔX / tan 8°
  ΔX 0.4200（229 と同じ x +0.42 へ）：2.988 m
  ΔX 0.3460（寄った位置のハコブくんと 0.15 m あくのに要る最小（229：+0.42 で 0.224 m））：2.462 m
  ΔX 0.4805（ふだんの位置 x −0.33 のハコブくんと 0.15 m あくのに要る最小（+0.42 で 0.0895 m））：3.419 m
止まった時の足のせの前の端とハコブくんの前の端のあいだ G（229 の決まりで止まると 2.30 m。できるだけ守る 2.0〜3.0 m）
向きの変わる所の長さ a・前へ進む長さ L・ハコブくん（x −0.4643 で止まったまま）と車いす/大城さんのすき間の最小（負は重なる）
  G 2.0・ΔX 0.420・a 0.3：前へ 3.289 m 進む（足のせの前の端がハコブくんの前の端を +1.289 m 越える）・すき間の最小 0.174 m（前へ 1.94 m の所）
  G 2.0・ΔX 0.420・a 0.6：前へ 3.590 m 進む（足のせの前の端がハコブくんの前の端を +1.590 m 越える）・すき間の最小 0.153 m（前へ 2.82 m の所）
  G 2.0・ΔX 0.420・a 1.0：前へ 3.992 m 進む（足のせの前の端がハコブくんの前の端を +1.992 m 越える）・すき間の最小 0.125 m（前へ 2.30 m の所）
  G 2.0・ΔX 0.346・a 0.3：前へ 2.763 m 進む（足のせの前の端がハコブくんの前の端を +0.763 m 越える）・すき間の最小 0.154 m（前へ 2.76 m の所）
  G 2.0・ΔX 0.346・a 0.6：前へ 3.064 m 進む（足のせの前の端がハコブくんの前の端を +1.064 m 越える）・すき間の最小 0.144 m（前へ 2.77 m の所）
  G 2.0・ΔX 0.346・a 1.0：前へ 3.465 m 進む（足のせの前の端がハコブくんの前の端を +1.465 m 越える）・すき間の最小 0.120 m（前へ 2.76 m の所）
  G 2.3・ΔX 0.420・a 0.3：前へ 3.289 m 進む（足のせの前の端がハコブくんの前の端を +0.989 m 越える）・すき間の最小 0.216 m（前へ 3.04 m の所）
  G 2.3・ΔX 0.420・a 0.6：前へ 3.590 m 進む（足のせの前の端がハコブくんの前の端を +1.290 m 越える）・すき間の最小 0.195 m（前へ 3.03 m の所）
  G 2.3・ΔX 0.420・a 1.0：前へ 3.992 m 進む（足のせの前の端がハコブくんの前の端を +1.692 m 越える）・すき間の最小 0.167 m（前へ 3.04 m の所）
  G 2.3・ΔX 0.346・a 0.3：前へ 2.763 m 進む（足のせの前の端がハコブくんの前の端を +0.463 m 越える）・すき間の最小 0.154 m（前へ 2.76 m の所）
  G 2.3・ΔX 0.346・a 0.6：前へ 3.064 m 進む（足のせの前の端がハコブくんの前の端を +0.764 m 越える）・すき間の最小 0.154 m（前へ 3.06 m の所）
  G 2.3・ΔX 0.346・a 1.0：前へ 3.465 m 進む（足のせの前の端がハコブくんの前の端を +1.165 m 越える）・すき間の最小 0.144 m（前へ 3.08 m の所）
  G 3.0・ΔX 0.420・a 0.3：前へ 3.289 m 進む（足のせの前の端がハコブくんの前の端を +0.289 m 越える）・すき間の最小 0.229 m（前へ 3.29 m の所）
  G 3.0・ΔX 0.420・a 0.6：前へ 3.590 m 進む（足のせの前の端がハコブくんの前の端を +0.590 m 越える）・すき間の最小 0.228 m（前へ 3.59 m の所）
  G 3.0・ΔX 0.420・a 1.0：前へ 3.992 m 進む（足のせの前の端がハコブくんの前の端を +0.992 m 越える）・すき間の最小 0.225 m（前へ 3.79 m の所）
  G 3.0・ΔX 0.346・a 0.3：前へ 2.763 m 進む（足のせの前の端がハコブくんの前の端を -0.237 m 越える）・すき間の最小 0.284 m（前へ 2.76 m の所）
  G 3.0・ΔX 0.346・a 0.6：前へ 3.064 m 進む（足のせの前の端がハコブくんの前の端を +0.064 m 越える）・すき間の最小 0.155 m（前へ 3.06 m の所）
  G 3.0・ΔX 0.346・a 1.0：前へ 3.465 m 進む（足のせの前の端がハコブくんの前の端を +0.465 m 越える）・すき間の最小 0.154 m（前へ 3.46 m の所）

■ 止まった所の置き方（車いす x 0.00・向き 0°・大城さん x 0.00、寺島さんは大城さんの +x 側で −x を向く。寸法は 231 の terashima231.txt）
  寺島さんと大城さんのすき間 0.10 m に置くと：寺島さんの根 x +0.488・背中 x +0.628（手すりと 0.212 m）
  寺島さんと大城さんのすき間 0.15 m に置くと：寺島さんの根 x +0.538・背中 x +0.678（手すりと 0.162 m）
  車いすの所：−x 側 0.514 m・+x 側 0.514 m／大城さん・寺島さんの所：−x 側（大城さんと手すり）0.602 m・+x 側（寺島さんの背中と手すり）0.162〜0.212 m
  ハコブくんが手すりの側を通るのに要る幅 0.842 m（231 と同じ）→ どこも狭く、通れない
  寺島さんが後ろから追いついて横に並ぶ時（前を向いて歩く・幅 0.476 m）：大城さんの +x の端 0.238 と手すり 0.84 の間 0.602 m → 真ん中を歩いて両側 0.063 m ずつ
  寺島さんの横（大城さんと同じ z）で、大城さんが寺島さんの顔を見るのに要る顔の向き：約 99°（228・229 の大城さんの顔の向きの最大 34°。大城さんの顔は Head の骨だけで回す作り）

■ その場で寄せる形（依頼の形：車いすの前に空いている所の中で寄せ、寺島さんが下がって大城さんの寄る所を空ける）
  足のせとハコブくんのあいだ 2.3 m・前へ 2.15 m まで（ハコブくんの前の端と 0.15 m）・向きの変わる所 0.0 m：寄せられる横の長さ 0.302 m（x +0.42 まで 0.118 m 足りない・寄った位置のハコブくんと 0.15 m あく x +0.346 まで 0.044 m 足りない）
  足のせとハコブくんのあいだ 2.3 m・前へ 2.15 m まで（ハコブくんの前の端と 0.15 m）・向きの変わる所 0.6 m：寄せられる横の長さ 0.218 m（x +0.42 まで 0.202 m 足りない・寄った位置のハコブくんと 0.15 m あく x +0.346 まで 0.128 m 足りない）
  足のせとハコブくんのあいだ 3.0 m・前へ 2.85 m まで（ハコブくんの前の端と 0.15 m）・向きの変わる所 0.0 m：寄せられる横の長さ 0.401 m（x +0.42 まで 0.019 m 足りない・寄った位置のハコブくんと 0.15 m あく x +0.346 まで 0.000 m 足りない）
  足のせとハコブくんのあいだ 3.0 m・前へ 2.85 m まで（ハコブくんの前の端と 0.15 m）・向きの変わる所 0.6 m：寄せられる横の長さ 0.316 m（x +0.42 まで 0.104 m 足りない・寄った位置のハコブくんと 0.15 m あく x +0.346 まで 0.030 m 足りない）

■ 前へ進んでハコブくんの横まで行く形（229 の寄せ方の決まりで、当たらずに寄せられる形）で、寺島さんが動かない時の大城さんとのすき間
  寺島さん x +0.538・大城さんより前へ 0.0 m：下がらなくても大城さん・車いすとのすき間の最小 0.062 m（大城さんは前へ離れていく）→ 下がる距離 0 m で当たらない
  寺島さん x +0.538・大城さんより前へ 0.2 m：下がらなくても大城さん・車いすとのすき間の最小 0.062 m（大城さんは前へ離れていく）→ 下がる距離 0 m で当たらない
```

### 依頼234

#### tools/Closeup234.cs（依頼234）

```csharp
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>
    /// 依頼234：232 の体の型に加えて、もの（ハコブくん／車いすと茂さん／大城さん）ごとに別々に白く写した型を撮る（Closeup232.cs を写して、写した先で変えた）。
    /// frames/yield_top_obj/f_*.png は 1 枚の色の型で、赤＝ハコブくんだけ・緑＝車いすと茂さんだけ・青＝大城さんだけを写したもの（3 回別々に撮るので、ほかのものに隠された所も入る）。
    /// make234.py が、ものごとに中の穴を埋めた外形にしてから床の線を消す。真上のコマと 232 と同じ型（frames/yield_top_mask）は 232 のまま撮る。
    /// 以下は 232 の説明：
    /// 依頼232：230 の真上の動画の床の線（中心・+0.28・+0.42・−0.33 の線と線の端の字）を、ハコブくん・大城さん・茂さん・車いすの下に描く。Closeup230.cs を写して、写した先で変えた。
    /// 動き・カメラ・真上のコマは 230 のまま。足したのは、真上のコマごとに「体だけを白く写した型」frames/yield_top_mask/f_*.png（黒＝床・白＝体）を撮ることだけ。
    /// 型は真上のカメラを写した別のカメラ（MaskCam232）で、体の部品だけを層 LayerMask232 に移し、白の Unlit/Color で写す（影・光は写らない）。写した後に層と材料を元に戻す。
    /// make232.py が床の線の層を、この型の白い所で消してから重ねる（線は床の上・体の下に見える）。
    /// 以下は 230 の説明：
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top234.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top234_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c234Views top）・静止画なし（-c234Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup234.Run \
    ///                 -c234Out <出力フォルダ> [-c234Script closeup229_script.json] [-c234Frames on|off] [-c234Stills on|off] [-c234Views main,top] [-c234From 秒] [-c234To 秒] [-c234Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames234.csv・bones234.csv・feet234.csv・wc234.csv・check234.txt・events234.txt
    /// </summary>
    public static class Closeup234
    {
        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 LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;   // 依頼232：体の型を写す間だけ体の部品を置く層

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c234Out", "");
            if (outDir == "") throw new Exception("-c234Out がない");
            string scriptName = CloseupArgs.Get("-c234Script", "closeup229_script.json");
            bool frames = CloseupArgs.Get("-c234Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c234Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c234Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c234From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c234To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk") talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.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;

                string shotName = "yield";
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c229"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                Texture2D bandTex = ScreenTex(TexDir + "/" + C["band"].S() + ".png");
                float bandOn = C["band_on"].F(), bandOff = C["band_off"].F(), happyFrom = C["happy_from"].F(), happyTo = C["happy_to"].F();
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                var SH = C["shift"]; float shT0 = SH["t0"].F(1e9f), shT1 = SH["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c234Until", "1e9"), IC)) * fps);
                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"); }   // 依頼232：_mask は体の型
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        if (mode == "stop" && stopped && behindN >= R.passBehind) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師
                    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;
                    chair.SetPositionAndRotation(nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead), nr.rotation);
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    bool bandNow = t >= bandOn - 1e-4f && t < bandOff - 1e-4f;
                    bool happyNow = t >= happyFrom - 1e-4f && t < happyTo - 1e-4f;
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", bandTex); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy" : 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 ? "帯" : "") + (happyNow ? "目まで笑う顔" : "基本") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        float d = RobotDist(rs, lr, Mathf.Min(gap, 1.5f));
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000"));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top234_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && inRange)
                    {
                        syncProxies(); scaleMouth();
                        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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            // 依頼232：体だけの型（同じ真上のカメラ・同じ大きさ）
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // 依頼234：もの別の型（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん）
                            var grp = new List<Renderer>[3]; for (int g = 0; g < 3; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[Group234(rd, dir.robot, chair, mor)].Add(rd);
                            if (!log.ToString().Contains("依頼234 もの別")) { log.AppendLine("依頼234 もの別の型の部品"); string[] gn = { "赤 ハコブくん", "緑 車いすと茂さん", "青 大城さん" }; for (int g = 0; g < 3; g++) { log.Append("  " + gn[g] + " " + grp[g].Count + "："); foreach (var rd in grp[g]) log.Append(" " + rd.name); log.AppendLine(); } }
                            var obj = new Texture2D(W, H, TextureFormat.RGB24, false);
                            var px = new Color32[W * H];
                            for (int g = 0; g < 3; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < px.Length; i++) { if (g == 0) px[i].r = mp[i].r; else if (g == 1) px[i].g = mp[i].r; else px[i].b = mp[i].r; px[i].a = 255; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(px); 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();
                        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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames234.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top234.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones234.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet234.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc234.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check234.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events234.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C234] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        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;
        }

        /// <summary>依頼234：部品がどのものか（0＝ハコブくん・1＝車いすと茂さん・2＝大城さん）。茂さんの写しの部品は名前が Morita_ で始まる</summary>
        static int Group234(Renderer rd, Transform robot, Transform chair, Transform mor)
        {
            var t = rd.transform;
            if (t.IsChildOf(robot)) return 0;
            if (t.IsChildOf(chair) || t.IsChildOf(mor) || rd.name.StartsWith("Morita_")) return 1;
            return 2;
        }

        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.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] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, 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);
        }
    }
}
```

#### tools/between234.py（依頼234）

```python
"""依頼234：もの別に埋めた外形どうしで囲まれた床（もののあいだのすき間。どのものの外形にも入らない所）に線が見えるコマを数える（直しはしない・報告用）。
床の線の層は make234.py と同じ描き方（下の部分は make234.py からそのまま写した）。
使い方: python3 between234.py <Unity の出力> <台本> [閉じる処理の半径 既定 6]"""
import csv, json, math, os, re, sys
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont
sys.argv = sys.argv[:3] + ["-"] + sys.argv[3:]
FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, VD = sys.argv[1:4]; RC = int(sys.argv[4]) if len(sys.argv) > 4 else 6
C = json.load(open(SC))["shots"][0]["c229"]
CAM = json.load(open(os.path.join(D, "top234_cam.json")))
FPS, W, H, S = 30, 1920, 1080, 2          # S：描く倍率（2 倍で描いて縮める）
f0, f1 = int(round(C["video_from"] * FPS)), int(round(C["video_to"] * FPS))
n = f1 - f0 + 1
vt = lambda f: (f - f0) / FPS             # 動画の秒

# ---- 決めた値（1920×1080 の画面での px）
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {
    "center": (120, 120, 120),       # 廊下の中心の線（細い実線・灰色）
    "x028": (21, 101, 192),          # 車いすの始めの線 +0.28（破線・青）
    "x042": (142, 36, 170),          # 寄せたあとの線 +0.42（破線・紫）
    "lane": (46, 173, 107),          # ハコブくんのふだんの線 −0.33（破線・ハコブくんの輪の光に近い緑）
    "chair": (239, 108, 0),          # 車いすの通った跡（実線・橙）
    "robot": (0, 105, 92),           # ハコブくんの通った跡（実線・深い青緑）
}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16

# ---- 床の点 → 画面（Unity のカメラで写した 3 点から。正射影なので一次式）
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)   # (x, z)


def font(px): return ImageFont.truetype(FONT_PATH, px * S)
FL, FM, FH = font(LINE_LABEL_PX), font(MARK_LABEL_PX), font(HUD_PX)
def sc(p): return (p[0] * S, p[1] * S)

def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy
    bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)

def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1)
    L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L
    s = 0.0
    while s < L:
        e = min(L, s + DASH * S)
        d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S)
        s += (DASH + GAP) * S

def down(layer): return layer.resize((W, H), Image.LANCZOS)

# ---- 動かない層：中心の線・目印の線と字
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x028": 0.28, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x028", "x042", "lane"):
    dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
# 字：始め +0.28（線の上）と寄せたあと +0.42（線の下）は左の端（車いすが来るのは右の端なので、入ってくる所と寄せる所を隠さない）、ハコブくんのふだん −0.33 は右の端（ハコブくんが行かない側）
text_box(d, (sc((14, line_py["x028"] - 8))), "始め +0.28", FL, COL["x028"], "lb", edge=COL["x028"])
text_box(d, (sc((14, line_py["x042"] + 8))), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, (sc((W - 14, line_py["lane"] - 8))), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st)
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def filled_obj(soft):
    b = soft > 0
    if not b.any(): return b
    bp = cv2.copyMakeBorder(b.astype(np.uint8), PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    return ndimage.binary_fill_holes(cl | b)
SA = np.array(static.getchannel("A")) > 0
n_fr, tot, mx, mxf = 0, 0, 0, None
for f in range(f0, f1 + 1):
    ob = np.array(Image.open(f"{D}/frames/yield_top_obj/f_{f:05d}.png").convert("RGB"))
    mk = np.array(Image.open(f"{D}/frames/yield_top_mask/f_{f:05d}.png").convert("L"))
    fl = mk > 0
    for c in range(3): fl |= filled_obj(ob[:, :, c])
    n = int((ndimage.binary_fill_holes(fl) & ~fl & SA).sum())
    if n: n_fr += 1; tot += n
    if n > mx: mx, mxf = n, f
print(f"半径 {RC}：もののあいだで囲まれた床に線が見えるコマ {n_fr}／{f1 - f0 + 1}・画素の合計 {tot}・1 コマの最大 {mx}（コマ {mxf}・動画 {(mxf - f0) / 30 if mxf else 0:.3f} 秒）")
```

#### tools/cmp234.py（依頼234）

```python
"""依頼234：232 と 234 の動きと真上の画面の位置を全部のコマで比べる（frames・bones・wc・feet・top の数の列、check・events・top_cam）。
使い方: python3 cmp234.py <232 の出力> <234 の出力>"""
import csv, json, sys
A, B = sys.argv[1:3]
def load(p): return list(csv.DictReader(open(p)))
for name in ["frames", "bones", "wc", "feet", "top"]:
    ra, rb = load(f"{A}/{name}232.csv"), load(f"{B}/{name}234.csv")
    assert len(ra) == len(rb), (name, len(ra), len(rb))
    assert list(ra[0].keys()) == list(rb[0].keys()), name
    worst = 0.0; ndiff = 0
    for a, b in zip(ra, rb):
        for k in a:
            if a[k] == b[k]: continue
            ndiff += 1
            try: worst = max(worst, abs(float(a[k]) - float(b[k])))
            except ValueError: worst = float("inf")
    print(f"{name}: {len(ra)} コマ・{len(ra[0])} 列・違うセル {ndiff}・差の最大 {worst}")
ca, cb = json.load(open(f"{A}/top232_cam.json")), json.load(open(f"{B}/top234_cam.json"))
print("top_cam:", "同じ" if ca == cb else f"違う {ca} {cb}")
for n in ["check", "events"]:
    a = open(f"{A}/{n}232.txt", encoding="utf-8").read(); b = open(f"{B}/{n}234.txt", encoding="utf-8").read()
    L = b.split("\n"); i = L.index("依頼234 もの別の型の部品") if "依頼234 もの別の型の部品" in L else None
    if i is not None: L = L[:i] + L[i + 4:]
    b = "\n".join(L)
    print(f"{n}:", "同じ（依頼234 のもの別の部品の一覧を除く）" if a == b else "違う")
```

#### tools/make234.py（依頼234）

```python
"""依頼234：make232.py を写して変えた。
・もの別の型（Closeup234.cs が撮った frames/yield_top_obj：赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さんを別々に白く写したもの）を、
  ものごとに「数画素の閉じる処理（半径 RC 画素の円）→ 中の穴埋め」で中の穴とすき間を埋めた外形にし、232 の体の型と合わせた型で床の線の層を消す
  （体の部品が写っている所は 232 と同じなめらかなふち。埋めて足した所は線を全部消す）。
・重ねる順を、下から コマ（床・体）→ 床の線（体の所と埋めた所は消す）→ 通った跡 → 印と印の字 → 左上の字 にした（232 は 跡 → 線 の順）。
・あわせて 232 の重ね方のコマも作り（<Unity の出力>/closeup234_as232.mp4。232 の動画と md5 が同じかを確かめるため）、
  外形の中に線が残らないこと・232 で外形の中のすき間に線が見えていたコマ・ふくらみの最大・体の無い所で 232 と違う画素が重ねる順の所だけかを数える。
使い方: python3 make234.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ> [寄りの静止画のコマ:寄る物,…]   （閉じる処理の半径は環境変数 RC234、既定 6 画素）
以下は 232 の説明：
依頼232：make230.py を写して変えた。床の目印の線（中心・+0.28・+0.42・−0.33）と線の端の字の層を、Closeup232.cs が撮った体の型
（frames/yield_top_mask：白＝ハコブくん・大城さん・茂さん・車いす）の所で消してから重ねる（線は床の上・体の下に見える）。
通った跡・印・左上の字は 230 のまま（体の上に重ねる）。重ねる順も 230 のまま（コマ → 跡 → 線 → 印 → 左上の字）。
あわせて、型を使わない 230 の重ね方のコマも作り、型の外は 1 画素も違わないこと・型の所に線が残っていないことを数え、
230 の重ね方の動画（<Unity の出力>/closeup232_as230.mp4）も作る（230 の動画と md5 が同じかを確かめるため）。
使い方: python3 make232.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ> [寄りの静止画のコマ,…]
以下は 230 の説明：
依頼230：229 の真上のコマ（Closeup230.cs が動かない真上のカメラで撮った frames/yield_top）に、床の目印・通った跡・印・左上の字を重ねて
closeup230_yield_top.mp4（音なし）と静止画 3 枚を作り、確かめ（check230_top.txt）を書く。
目印・跡は Unity のカメラで写した位置（top230.csv の画面の位置・top230_cam.json の写し方）に 2 倍の大きさで描いて縮める。
時刻は動画の秒（台本の秒 − video_from）。
使い方: python3 make230.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, VD = sys.argv[1:4]
ZOOM = dict((int(x.split(":")[0]), x.split(":")[1]) for x in sys.argv[4].split(",")) if len(sys.argv) > 4 else {}   # 依頼232：寄りの静止画のコマ:寄る物（robot｜chair｜x,y）
ZOOM_F = list(ZOOM)
os.makedirs(VD, exist_ok=True)
C = json.load(open(SC))["shots"][0]["c229"]
CAM = json.load(open(os.path.join(D, "top234_cam.json")))
FPS, W, H, S = 30, 1920, 1080, 2          # S：描く倍率（2 倍で描いて縮める）
f0, f1 = int(round(C["video_from"] * FPS)), int(round(C["video_to"] * FPS))
n = f1 - f0 + 1
vt = lambda f: (f - f0) / FPS             # 動画の秒

# ---- 決めた値（1920×1080 の画面での px）
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {
    "center": (120, 120, 120),       # 廊下の中心の線（細い実線・灰色）
    "x028": (21, 101, 192),          # 車いすの始めの線 +0.28（破線・青）
    "x042": (142, 36, 170),          # 寄せたあとの線 +0.42（破線・紫）
    "lane": (46, 173, 107),          # ハコブくんのふだんの線 −0.33（破線・ハコブくんの輪の光に近い緑）
    "chair": (239, 108, 0),          # 車いすの通った跡（実線・橙）
    "robot": (0, 105, 92),           # ハコブくんの通った跡（実線・深い青緑）
}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16

# ---- 床の点 → 画面（Unity のカメラで写した 3 点から。正射影なので一次式）
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)   # (x, z)

rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames234.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top234.csv")))}
ev = open(os.path.join(D, "events234.txt"), encoding="utf-8").read()
t_trig = float(re.search(r"([\d.]+) 秒 決まりに当たった", ev).group(1))
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_sh0, t_sh1 = C["shift"]["t0"], C["shift"]["t1"]
# 印：(どれ, 台本の秒, 字の頭)。出す時刻 = その秒のコマ
MARKS = [("chair", t_sh0, "寄せ始め"), ("chair", t_sh1, "寄せ終わり"), ("robot", t_trig, "寄り始め"), ("robot", t_stop, "止まった")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]

def font(px): return ImageFont.truetype(FONT_PATH, px * S)
FL, FM, FH = font(LINE_LABEL_PX), font(MARK_LABEL_PX), font(HUD_PX)
def sc(p): return (p[0] * S, p[1] * S)

def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy
    bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)

def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1)
    L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L
    s = 0.0
    while s < L:
        e = min(L, s + DASH * S)
        d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S)
        s += (DASH + GAP) * S

def down(layer): return layer.resize((W, H), Image.LANCZOS)

# ---- 動かない層：中心の線・目印の線と字
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x028": 0.28, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x028", "x042", "lane"):
    dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
# 字：始め +0.28（線の上）と寄せたあと +0.42（線の下）は左の端（車いすが来るのは右の端なので、入ってくる所と寄せる所を隠さない）、ハコブくんのふだん −0.33 は右の端（ハコブくんが行かない側）
text_box(d, (sc((14, line_py["x028"] - 8))), "始め +0.28", FL, COL["x028"], "lb", edge=COL["x028"])
text_box(d, (sc((14, line_py["x042"] + 8))), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, (sc((W - 14, line_py["lane"] - 8))), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st)

# ---- 印の層（時刻になったら出す）。字は車いすの印は廊下の下、ハコブくんの印は廊下の上へ引き出す
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    nrob = 0
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (0 if head == "寄せ始め" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "止まった" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        text_box(d, sc((px, ly)), f"{head} {vt(mark_f[i]):.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)

# ---- 左上の字
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]
    cx = num_ok(r["chair_x"]); g = num_ok(r["gap_m"])
    return [f"{vt(f):.1f} 秒",
            "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None else "—")]

# ---- 依頼234：もの別の型から、中の穴とすき間を埋めた外形を作る
RC = int(os.environ.get("RC234", "6"))
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1))
PAD = RC + 24
OBJ = ["robot", "chair", "nurse"]          # 赤・緑・青
OBJ_JA = {"robot": "ハコブくん", "chair": "車いすと茂さん", "nurse": "大城さん"}
def fill_obj(soft):
    """soft：1 つのものの型（0〜255）。返す：足した所（体の部品が写っていない所で外形の中・bool）と、ふくらみ（外形のふちの足した画素の、体からの距離の最大）・足した画素の距離の最大"""
    Hh, Ww = soft.shape
    ys, xs = np.nonzero(soft)
    added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added, 0.0, 0.0, 0, 0
    y0, y1 = max(0, ys.min() - PAD), min(Hh, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(Ww, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)          # 画面の外は床として扱う
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    ad = filled & ~b.astype(bool)
    if not ad.any(): return added, 0.0, 0.0, 0, 0
    dist = ndimage.distance_transform_edt(~b.astype(bool))                                 # 体の部品の写った画素からの距離（画素）
    rim = ad & ndimage.binary_dilation(~filled, structure=np.ones((3, 3), bool))           # 外形のふちにある足した画素（＝外へふくらんだ所）
    holes = ndimage.binary_fill_holes(b.astype(bool)) & ~b.astype(bool)                     # もとから閉じた穴
    added[y0:y1, x0:x1] = ad
    return added, float(dist[rim].max()) if rim.any() else 0.0, float(dist[ad].max()), int(holes.sum()), int(ad.sum())

# ---- コマを作る
tmp = tempfile.mkdtemp(prefix="m234_", dir="/tmp"); tmp232 = tempfile.mkdtemp(prefix="m234as232_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}
shown = [False] * len(MARKS); mcache = mark_layer(shown)
chk = {"trail_err_m": {"chair": 0.0, "robot": 0.0}, "mark_first": [None] * len(MARKS), "hud_bad": 0, "hud_dash": {1: 0, 2: 0}, "hud_texts": []}
stills = {}; zooms = {}; per = []
bul = {o: [0.0, 0.0, -1] for o in OBJ}          # ふくらみの最大・足した画素の距離の最大・そのコマ
static_A = static.getchannel("A"); static_An = np.array(static_A)
for k, f in enumerate(range(f0, f1 + 1)):
    r = top[f]
    for who, kx, ky, wx, wz in (("chair", "axle_px", "axle_py", "axle_x", "axle_z"), ("robot", "robot_px", "robot_py", "robot_x", "robot_z")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)   # 描く点（2 倍の画面の整数の点）
        bx, bz = from_px(*p)
        chk["trail_err_m"][who] = max(chk["trail_err_m"][who], math.hypot(bx - float(r[wx]), bz - float(r[wz])))
        if prev[who] is not None:
            td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2
        td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))   # 線のつなぎ目を丸く
        prev[who] = p
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True; chk["mark_first"][i] = vt(f)
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", "yield_top", f"f_{f:05d}.png")).convert("RGBA")
    mk = Image.open(os.path.join(D, "frames", "yield_top_mask", f"f_{f:05d}.png")).convert("L")   # 232 と同じ体の型
    ob = np.array(Image.open(os.path.join(D, "frames", "yield_top_obj", f"f_{f:05d}.png")).convert("RGB"))   # 依頼234：もの別の型
    add_any = np.zeros((H, W), bool); nadd = {}
    for c, o in enumerate(OBJ):
        ad, bmax, dmax, nh, na = fill_obj(ob[:, :, c])
        add_any |= ad; nadd[o] = na
        if bmax > bul[o][0]: bul[o][0] = bmax; bul[o][2] = f
        bul[o][1] = max(bul[o][1], dmax)
    mkn = np.array(mk)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))      # 外形の型：体の所は 232 の型・足した所は 255
    F = Image.fromarray(Fn, "L")
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(F)))       # 234：外形の所で線を消す
    st_232 = static.copy(); st_232.putalpha(ImageChops.multiply(static_A, ImageChops.invert(mk)))  # 232：体の所だけ消す
    trail_d = down(trail)
    lines = hud_lines(f)
    for i in (1, 2):
        if lines[i].endswith("—"): chk["hud_dash"][i] += 1
    if any(re.search(r"\d{5,}|nan|inf", s, re.I) for s in lines): chk["hud_bad"] += 1
    if k % 30 == 0: chk["hud_texts"].append(" / ".join(lines))
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl)
    x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    hl_d = down(hl)
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(trail_d); im.alpha_composite(mcache); im.alpha_composite(hl_d)        # 234：床の線 → 跡 → 印 → 左上の字
    im232 = raw.copy(); im232.alpha_composite(trail_d); im232.alpha_composite(st_232); im232.alpha_composite(mcache); im232.alpha_composite(hl_d)   # 232 の重ね方
    out = im.convert("RGB"); out.save(os.path.join(tmp, f"v_{k:05d}.png"))
    o232 = im232.convert("RGB"); o232.save(os.path.join(tmp232, f"v_{k:05d}.png"))
    # 依頼234 の確かめ
    stA = np.array(st_m.getchannel("A")); s2A = np.array(st_232.getchannel("A")); trA = np.array(trail_d.getchannel("A"))
    inside = (Fn == 255)                                               # 外形の中（体の部品が全部写っている所と埋めた所）
    left = int(((stA > 0) & inside).sum())                             # 234 で外形の中に残る線の画素（0 のはず）
    rim_left = int(((stA > 0) & (Fn > 0) & (Fn < 255)).sum())          # 体のふちのなめらかな所に薄く残る線（232 と同じ扱い）
    gap232 = int(((s2A > 0) & add_any).sum())                          # 232 で、外形の中のすき間（埋めた所）に線が見えていた画素
    dif = np.any(np.array(out) != np.array(o232), axis=2)
    outside = (Fn == 0)
    order = (trA > 0) & (static_An > 0)                                # 体の無い所で跡と線が重なる所（重ねる順で色が変わる所）
    n_out = int((dif & outside).sum()); n_out_bad = int((dif & outside & ~order).sum())
    per.append((f, left, rim_left, gap232, n_out, n_out_bad, nadd["robot"], nadd["chair"], nadd["nurse"]))
    if f in ZOOM_F: zooms[f] = (out.copy(), o232.copy())
    for name, ff in (("s1_shift_start", mark_f[0]), ("s2_shift_end", mark_f[1]), ("s3_last", f1)):
        if f == ff: stills[name] = out.copy()
vid = os.path.join(VD, "closeup234_yield_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vid], check=True)
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp232, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", os.path.join(D, "closeup234_as232.mp4")], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for name, im in stills.items(): im.save(os.path.join(sd, name + ".png"))

# ---- 確かめ
o = []
o.append(f"コマ {n}（{f0}〜{f1}）・動画 {n / FPS:.3f} 秒")
o.append(f"写し方：画面の点 = ({ox:.4f}, {oy:.4f}) + x×({xx:.4f}, {xy:.4f}) + z×({zx:.4f}, {zy:.4f}) px（1 m = {math.hypot(zx, zy):.3f} px・1 px = {1000 / math.hypot(zx, zy):.2f} mm）")
o.append(f"写す範囲：z {z_lo:.3f}〜{z_hi:.3f}（{z_hi - z_lo:.3f} m）・x {from_px(0, 0)[0]:.3f}〜{from_px(0, H)[0]:.3f}（{from_px(0, H)[0] - from_px(0, 0)[0]:.3f} m）")
for k2, x in LINES.items():
    py = line_py[k2]; back = from_px(W / 2, py)[0]
    o.append(f"目印の線 {k2}：x {x:+.2f} → 画面の y {py:.2f} px（画面から戻した x {back:+.5f}）")
o.append(f"手すり（内側の面 x ±0.84）：画面の y {to_px(-0.84, 0)[1]:.2f}〜{to_px(0.84, 0)[1]:.2f} px（{to_px(0.84, 0)[1] - to_px(-0.84, 0)[1]:.1f} px ＝ 画面の高さの {(to_px(0.84, 0)[1] - to_px(-0.84, 0)[1]) / H * 100:.1f}%）")
o.append(f"通った跡の点と本当の位置のずれの最大：車いすの後ろの車軸の真ん中 {chk['trail_err_m']['chair'] * 100:.3f} cm・ハコブくんの根 {chk['trail_err_m']['robot'] * 100:.3f} cm")
for (who, t, head), fv in zip(MARKS, chk["mark_first"]):
    o.append(f"印 {who} {head}：台本 {t:.4f} 秒（動画 {t - C['video_from']:.3f} 秒）→ 出たコマの動画の秒 {fv:.3f}")
o.append(f"左上の字：壊れた値のコマ {chk['hud_bad']}・車いすの横の位置が「—」のコマ {chk['hud_dash'][1]}・すき間が「—」のコマ {chk['hud_dash'][2]}")
o += ["  " + s for s in chk["hud_texts"]]
# 画面の中か（2＝全部・1＝一部・0＝外）
def spans(key):
    out, cur = [], None
    for f in range(f0, f1 + 1):
        v = int(top[f][key])
        if cur is None or cur[0] != v: cur = [v, vt(f), vt(f)]; out.append(cur)
        else: cur[2] = vt(f)
    return " ／ ".join(f"{['外', '一部', '全部'][v]} {a:.3f}〜{b:.3f}" for v, a, b in out)
for key, nm in (("chair_in", "車いす"), ("robot_in", "ハコブくん"), ("nurse_in", "大城さん")):
    o.append(f"{nm}が画面の中か：{spans(key)}")
a, b = int(round((t_sh0 - 1.0) * FPS)), int(round(t_sh1 * FPS))
o.append(f"寄せ始めの 1 秒前〜寄せ終わり（動画 {vt(a):.3f}〜{vt(b):.3f}）の車いす：全部が画面の中でないコマ {sum(1 for f in range(a, b + 1) if int(top[f]['chair_in']) != 2)}")
# 依頼234：外形の中の線・すき間・ふくらみ・体の無い所
PXCM = 100 / math.hypot(zx, zy)
o.append(f"依頼234 閉じる処理の半径 {RC} 画素（{RC * PXCM:.2f} cm）→ 中の穴埋め。もの：赤 ハコブくん・緑 車いすと茂さん・青 大城さん")
o.append(f"依頼234 外形の中（型 255）に残る線の画素：合計 {sum(p[1] for p in per)}・1 コマの最大 {max(p[1] for p in per)}")
o.append(f"依頼234 体のふちのなめらかな所（0<型<255）に薄く残る線の画素（232 と同じ扱い）：1 コマの最大 {max(p[2] for p in per)}")
o.append(f"依頼234 232 で外形の中のすき間（埋めた所）に線が見えていたコマ：{sum(1 for p in per if p[3] > 0)}／{len(per)}（画素の合計 {sum(p[3] for p in per)}・1 コマの最大 {max(p[3] for p in per)}）")
for ob_ in OBJ:
    bm, dm, bf = bul[ob_]
    o.append(f"依頼234 ふくらみ {OBJ_JA[ob_]}：外形のふちの足した画素の体からの距離の最大 {bm:.2f} 画素（{bm * PXCM:.2f} cm・コマ {bf}）・足した画素（中の穴を含む）の体からの距離の最大 {dm:.2f} 画素（{dm * PXCM:.2f} cm）・足した画素の 1 コマの最大 {max(p[6 + OBJ.index(ob_)] for p in per)}")
o.append(f"依頼234 体の無い所（型 0）で 232 の重ね方と違う画素：合計 {sum(p[4] for p in per)}・1 コマの最大 {max(p[4] for p in per)}・そのうち跡と線が重なる所の外 {sum(p[5] for p in per)}")
open(os.path.join(D, "per234.csv"), "w").write("frame,line_left_inside,line_rim_soft,gap_line_232,diff_outside_vs232,diff_outside_not_order,added_robot,added_chair,added_nurse\n" + "".join(",".join(str(v) for v in p) + "\n" for p in per))
# 依頼234：寄りの静止画（232 と同じ範囲を 2.5 倍に寄せ、上に 232・下に 234）
zd = os.path.join(VD, "stills_zoom"); os.makedirs(zd, exist_ok=True)
for f, (a, b) in sorted(zooms.items()):
    r = top[f]; who = ZOOM[f]
    if who == "robot": cx, cy = float(r["robot_px"]), float(r["robot_py"])
    elif who == "chair": cx, cy = float(r["axle_px"]), float(r["axle_py"])
    else: cx, cy = map(float, who.split("/"))
    cx, cy = int(round(cx)), int(round(cy)); bw, bh = 480, 270
    x0 = min(max(0, cx - bw // 2), W - bw); y0 = min(max(0, cy - bh // 2), H - bh)
    box = (x0, y0, x0 + bw, y0 + bh); zw = 1200; zh = zw * bh // bw
    pane = Image.new("RGB", (zw, zh * 2 + 60), (255, 255, 255)); pd = ImageDraw.Draw(pane)
    pane.paste(b.crop(box).resize((zw, zh), Image.NEAREST), (0, 30)); pane.paste(a.crop(box).resize((zw, zh), Image.NEAREST), (0, zh + 60))
    fz = ImageFont.truetype(FONT_PATH, 24)
    pd.text((8, 2), f"232（すき間から線が見える・線が跡の上）動画 {vt(f):.3f} 秒・画面 x {box[0]}〜{box[2]}・y {box[1]}〜{box[3]}", font=fz, fill=(0, 0, 0))
    pd.text((8, zh + 32), f"234（穴を埋めた外形の所で線を消す・線が跡の下）", font=fz, fill=(0, 0, 0))
    nm = f"z_{vt(f):06.3f}s_f{f}.png"; pane.save(os.path.join(zd, nm))
    p = per[f - f0]
    o.append(f"寄りの静止画 {nm}（{who}）：範囲 {box}・このコマで 232 のすき間に見えていた線の画素 {p[3]}（画面全体）・234 で外形の中に残る線 {p[1]}")
open(os.path.join(D, "check234_top.txt"), "w", encoding="utf-8").write("\n".join(o) + "\n")
print("\n".join(o)); print("動画", vid)
```

#### tools/run234.sh（依頼234）

```bash
#!/bin/bash
# 依頼234 使い方: run234.sh <出力フォルダ> <コマ on|off> [views] [until]
OUT="$1"; FR="${2:-off}"; VW="${3:-top}"; UNTIL="${4:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup234.Run \
   -c234Out "$OUT" -c234Frames "$FR" -c234Stills off -c234Script closeup229_script.json -c234Views "$VW" -c234Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

### 依頼235

#### tools/Closeup235.cs.copy（依頼235）

```csharp
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>
    /// 依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）。場面 stop_voice（⑨-1）・stop_stuck（⑨-2）。Closeup234.cs を写して、写した先で変えた。台本は closeup235_script.json（make_script235.py）。
    /// 234 から変えたこと：
    ///   ・寺島さん（Models_terashima/NurseTerashima.prefab）を置き、2 つめの CloseupDirector で台本の場面 <場面>__tera を動かす（部品の名前 Terashima_ を Nurse_ に替えて CloseupNurse を付ける。共通の部品は変えない）
    ///   ・車いすの根の位置・向きは台本の c235.chair（毎コマ）。両手で握っている間は大城さんの根の前に固く付いた値、立ち話の間は止めた所
    ///   ・ハコブくんの決まりに足した：止まった後、前の物（車いす・茂さん・大城さん・寺島さん）が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す。
    ///     寄った位置（x −0.4643）のまま通り、物の一番後ろを通り過ぎてから x −0.33 へ戻る（依頼235 の答え 3）
    ///   ・画面：c235.screen（face・wait・deliv・pass・stuck・happy）。輪：c235.ring の wait の間は待つ色（203 と同じ作り）
    ///   ・真上のもの別の型 frames/<場面>_top_obj は RGBA（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん・アルファ＝寺島さん）
    ///   ・確かめを足した：寄せる道（向き・速さ・向きの変わる速さ・前へ／後ろへ・足のせとハコブくん・車輪の横すべり）、大城さんの体と顔の向き・握りをはなした／握り直した時刻、
    ///     ハコブくんが通る時の車いす・大城さん・寺島さんとのすき間の最小、寺島さんの当たり
    /// 以下は 234 の説明：
    /// 依頼234：232 の体の型に加えて、もの（ハコブくん／車いすと茂さん／大城さん）ごとに別々に白く写した型を撮る（Closeup232.cs を写して、写した先で変えた）。
    /// frames/yield_top_obj/f_*.png は 1 枚の色の型で、赤＝ハコブくんだけ・緑＝車いすと茂さんだけ・青＝大城さんだけを写したもの（3 回別々に撮るので、ほかのものに隠された所も入る）。
    /// make234.py が、ものごとに中の穴を埋めた外形にしてから床の線を消す。真上のコマと 232 と同じ型（frames/yield_top_mask）は 232 のまま撮る。
    /// 以下は 232 の説明：
    /// 依頼232：230 の真上の動画の床の線（中心・+0.28・+0.42・−0.33 の線と線の端の字）を、ハコブくん・大城さん・茂さん・車いすの下に描く。Closeup230.cs を写して、写した先で変えた。
    /// 動き・カメラ・真上のコマは 230 のまま。足したのは、真上のコマごとに「体だけを白く写した型」frames/yield_top_mask/f_*.png（黒＝床・白＝体）を撮ることだけ。
    /// 型は真上のカメラを写した別のカメラ（MaskCam232）で、体の部品だけを層 LayerMask232 に移し、白の Unlit/Color で写す（影・光は写らない）。写した後に層と材料を元に戻す。
    /// make232.py が床の線の層を、この型の白い所で消してから重ねる（線は床の上・体の下に見える）。
    /// 以下は 230 の説明：
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top235.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top235_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c235Views top）・静止画なし（-c235Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup235.Run \
    ///                 -c235Out <出力フォルダ> [-c235Script closeup229_script.json] [-c235Frames on|off] [-c235Stills on|off] [-c235Views main,top] [-c235From 秒] [-c235To 秒] [-c235Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames235.csv・bones235.csv・feet235.csv・wc235.csv・check235.txt・events235.txt
    /// </summary>
    public static class Closeup235
    {
        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 LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;   // 依頼232：体の型を写す間だけ体の部品を置く層

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c235Out", "");
            if (outDir == "") throw new Exception("-c235Out がない");
            string scriptName = CloseupArgs.Get("-c235Script", "closeup235_script.json");
            string shotArg = CloseupArgs.Get("-c235Shot", "stop_voice");
            bool frames = CloseupArgs.Get("-c235Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c235Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c235Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c235From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c235To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk" && kv.Key.transform.IsChildOf(dir.nurse.transform)) talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // ---- 依頼235：寺島さん（2 つめの CloseupDirector で動かす。部品の名前 Terashima_ → Nurse_）
                var teraGo = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(Closeup231Terashima.Prefab));
                teraGo.name = "Terashima235";
                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>();
                teraN.Init();
                var dir2 = new GameObject("Director235Tera").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(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var anT = teraN.Anim;
                var partsT = new List<SkinnedMeshRenderer>();
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) partsT.Add(smr);
                var proxyRootT = new GameObject("Baked235Tera").transform;
                int nProxyO = proxies.Count;
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                {
                    var g = new GameObject(smr.name + "_BakedT"); g.transform.SetParent(proxyRootT, 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));
                }
                log.AppendLine("寺島さん：部品 " + partsT.Count + "（体）・写し " + (proxies.Count - nProxyO) + "・骨の Animator " + (anT != null ? anT.isHuman.ToString() : "なし"));
                MeshFilter talkProxyT = null;
                for (int i = nProxyO; i < proxies.Count; i++) if (proxies[i].Key.name == "Nurse_Mouth_talk") talkProxyT = proxies[i].Value;
                if (talkProxyT == null) throw new Exception("寺島さんの口の部品 Nurse_Mouth_talk が無い");
                float curMouthScaleT = 1f;
                Action scaleMouthT = () =>
                {
                    if (!talkProxyT.gameObject.activeSelf || Mathf.Abs(curMouthScaleT - 1f) < 1e-4f) return;
                    var mesh = talkProxyT.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = teraN.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxyT.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 - curMouthScaleT)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.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;

                string shotName = shotArg;
                dir2.BeginShot(shotName + "__tera");
                anT.Rebind();
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c235"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                var scrTex = new Dictionary<string, Texture2D> { { "wait", ScreenTex(TexDir + "/c235_wait_band.png") }, { "deliv", ScreenTex(TexDir + "/c235_deliv_band.png") },
                                                                 { "pass", ScreenTex(TexDir + "/c235_pass_band.png") }, { "stuck", ScreenTex(TexDir + "/c235_stuck.png") } };
                var scrKeys = C["screen"]; var ringKeys = C["ring"];
                var chairKeys = C["chair"]; var gripBoth = C["grip_both"]; var teraMouth = C["tera_mouth"];
                var ringR = dir.ring.GetComponent<MeshRenderer>(); var ringOrig = ringR.sharedMaterial;
                Color rwc; ColorUtility.TryParseHtmlString(C["ring_wait_color"].S("#F2C230"), out rwc);
                var ringWait = new Material(Shader.Find("Standard")) { name = "C235_ring_wait" };
                ringWait.color = rwc; ringWait.SetFloat("_Glossiness", 0.3f); ringWait.EnableKeyword("_EMISSION"); ringWait.SetColor("_EmissionColor", rwc * 0.9f);
                ringWait.globalIlluminationFlags = MaterialGlobalIlluminationFlags.None;
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                float shT0 = C["man"]["t0"].F(1e9f), shT1 = C["man"]["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                float stillS = js["robot_rule"]["resume_still_s"].F(0.5f), stillV = js["robot_rule"]["still_mps"].F(0.005f);
                float lastMoveT = 0f, resumeGapWall = float.NaN, passedT = -1f; bool passedAll = false;
                Vector3 pvC = Vector3.zero, pvO = Vector3.zero, pvT = Vector3.zero; float pvCy = 0f, pvOy = 0f, pvTy = 0f;
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                // 依頼235
                var ncTimes = new List<string>();
                float rigidErr = 0f; int hitTS = 0, hitTO = 0, hitTC = 0; string hitTWhere = "";
                var passMin = new Dictionary<string, float> { { "車いす", float.MaxValue }, { "茂さん", float.MaxValue }, { "看護師", float.MaxValue }, { "寺島さん", float.MaxValue } };
                var passMinT = new Dictionary<string, float> { { "車いす", -1f }, { "茂さん", -1f }, { "看護師", -1f }, { "寺島さん", -1f } };
                float manYawMax = 0f, manV = 0f, manVT = -1f, manW = 0f, manWT = -1f, manFwd = 0f, manBack = 0f, footRobotMin = float.MaxValue, footRobotMinT = -1f, axZ0 = float.NaN;
                float oBodyRelMax = 0f, oBodyRelMaxT = -1f, oHeadMaxTalk = 0f, oHeadMaxTalkT = -1f, oLookTeraMin = 180f, relT = -1f, regripT = -1f; bool prevGripR = true;
                float tHeadMax = 0f, tHeadMaxT = -1f; Vector3 prevAxle = Vector3.zero; float prevCy = 0f; bool havePA = false;
                float teraZ0 = float.NaN, teraX0 = float.NaN, teraRetDist = 0f, teraRetT0 = -1f, teraRetT1 = -1f; Vector3 prevTera = Vector3.zero;
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c235Until", "1e9"), IC)) * fps);
                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"); }   // 依頼232：_mask は体の型
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    if (f > 0 && f % 150 == 0) GC.Collect();   // 依頼235：長い場面でメモリが増えないように
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        // 依頼235：止まった後、前の物が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す
                        if (mode == "stop" && stopped && t - lastMoveT >= stillS - 1e-4f && gapWall >= R.gapStop) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; resumeGapWall = gapWall;
                            log.AppendLine(string.Format(IC, "  {0:0.000} 秒 走り出す：前の物が {1:0.000} 秒動いていない・寄った位置のすき間 {2:0.000} m", t, t - lastMoveT, gapWall)); }
                        if ((mode == "resume" || mode == "cruise2") && !passedAll && rearZ - o.farZ >= 0f) { passedAll = true; passedT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 物の一番後ろを通り過ぎた → x {1:0.000} へ戻る", t, R.laneX)); }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && passedAll && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if ((mode == "resume" || mode == "cruise2") && !passedAll) StepLat(ref rx, ref ryaw, xWall, rv, R.resumeAngle, R, dt, xWall);   // 依頼235：通り過ぎるまで寄った位置のまま
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師（依頼235：寺島さんを先に。大城さんの 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;
                    {
                        // 依頼235：車いすの根は台本の c235.chair（両手で握っている間は大城さんの根の前に固く付いた値と同じ）
                        var ck = chairKeys[Mathf.Min(f, chairKeys.Count - 1)];
                        chair.SetPositionAndRotation(O + new Vector3(ck[0].F(), 0f, ck[1].F()), Quaternion.Euler(0f, ck[2].F(), 0f));
                        bool gb = gripBoth[Mathf.Min(f, gripBoth.Count - 1)].I() == 1;
                        if (gb) { float dRig = Vector3.Distance(chair.position, nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead)) + Mathf.Abs(Mathf.DeltaAngle(chair.eulerAngles.y, nr.eulerAngles.y)) * 0.01f; rigidErr = Mathf.Max(rigidErr, dRig); }
                    }
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼235：前の物が動いたか（車いす・大城さん・寺島さんの根と向き）
                    {
                        Vector3 pc = chair.position, po = nr.position, pt = teraN.transform.position; float yc = chair.eulerAngles.y, yo = nr.eulerAngles.y, yt = teraN.transform.eulerAngles.y;
                        if (f > 0)
                        {
                            float mvm = Mathf.Max(Vector3.Distance(pc, pvC), Mathf.Max(Vector3.Distance(po, pvO), Vector3.Distance(pt, pvT))) / dt;
                            float mva = Mathf.Max(Mathf.Abs(Mathf.DeltaAngle(yc, pvCy)), Mathf.Max(Mathf.Abs(Mathf.DeltaAngle(yo, pvOy)), Mathf.Abs(Mathf.DeltaAngle(yt, pvTy)))) / dt;
                            if (mvm > stillV || mva > 0.5f) lastMoveT = t;
                        }
                        pvC = pc; pvO = po; pvT = pt; pvCy = yc; pvOy = yo; pvTy = yt;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    { var ml = C["morita_mouth_lvl"]; if (f < ml.Count && ml[f].I() > 0) mMouth = "talk"; }     // 依頼235：茂さんが話す間は talk
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    string sk = "face"; for (int k = 0; k < scrKeys.Count; k++) { string v = scrKeys[k][1].S(); if (v == "happy" || (v == "face" && k > 0)) continue; if (scrKeys[k][0].F() <= t + 1e-4f) sk = v; }
                    if (resumeT >= 0f) sk = t < resumeT + 1.5f - 1e-4f ? "happy" : "face";     // 依頼235：走り出したら帯を消し、目まで笑う顔を 1.5 秒 → 基本（走り出しは Unity の中の決まりで決まる）
                    bool bandNow = scrTex.ContainsKey(sk);
                    bool happyNow = sk == "happy";
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", scrTex[sk]); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string rk = "normal"; for (int k = 0; k < ringKeys.Count; k++) { string v = ringKeys[k][1].S(); if (v == "normal" && k > 0) continue; if (ringKeys[k][0].F() <= t + 1e-4f) rk = v; }
                    if (resumeT >= 0f) rk = "normal";
                    ringR.sharedMaterial = rk == "wait" ? ringWait : ringOrig;
                    string fk = happyNow ? "happy" : 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 ? "絵" + sk : "") + (happyNow ? "目まで笑う顔" : "基本") + (rk == "wait" ? "＋輪の待つ色" : "") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    var passNow = new Dictionary<string, float> { { "車いす", float.MaxValue }, { "茂さん", float.MaxValue }, { "看護師", float.MaxValue }, { "寺島さん", float.MaxValue } };
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.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;   // 依頼235：1.5 m より遠い点は数えない（速くするため。1.5 m より近い値は同じ）
                        string cat0 = who.Substring(0, Math.Max(0, who.IndexOf(' ')));
                        float cutW = passNow.ContainsKey(cat0) ? Mathf.Min(passNow[cat0], 1.5f) : Mathf.Min(gap, 1.5f);
                        float d = RobotDist(rs, lr, Mathf.Max(cutW, Mathf.Min(gap, 1.5f)));
                        if (passNow.ContainsKey(cat0) && d < passNow[cat0]) passNow[cat0] = d;
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 依頼235：寺島さんの頂点（見る・壁/手すり・大城さん・車いす）
                    {
                        bool tsHit = false, toHit = false, tcHit = false;
                        foreach (var smr in partsT)
                        {
                            smr.BakeMesh(baked, true);
                            Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                            var vs = baked.vertices;
                            for (int i = 0; i < vs.Length; i += 2)
                            {
                                Vector3 w = m.MultiplyPoint3x4(vs[i]);
                                seeVert(w, "寺島さん " + smr.name);
                                foreach (var s2 in solids)
                                {
                                    if (w.x < s2.min.x - 0.1f || w.x > s2.max.x + 0.1f || w.z < s2.min.z - 0.1f || w.z > s2.max.z + 0.1f) continue;
                                    if (InBox(w, s2.min, s2.max)) { tsHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→" + s2.name; }
                                }
                                if (Physics.CheckSphere(w, 0.003f, 1 << LayerNurse)) { toHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→大城さん"; }
                                if (Physics.CheckSphere(w, 0.003f, 1 << LayerChair)) { tcHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→車いす"; }
                            }
                        }
                        if (tsHit) hitTS++; if (toHit) hitTO++; if (tcHit) hitTC++;
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (ncHit && ncTimes.Count < 80) ncTimes.Add(F(t, "0.000"));
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (resumeT >= 0f) foreach (var kc in new List<string>(passNow.Keys)) if (passNow[kc] < passMin[kc]) { passMin[kc] = passNow[kc]; passMinT[kc] = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    bool gbNow = gripBoth[Mathf.Min(f, gripBoth.Count - 1)].I() == 1;
                    {
                        // 依頼235：右手を握りからはなした時刻・握り直した時刻（右手の重み）
                        float wR = dir.nurse.hands[1].weight;
                        if (prevGripR && wR < 0.999f && relT < 0f) relT = t;
                        if (!prevGripR && wR >= 0.999f && regripT < 0f) regripT = t;
                        prevGripR = wR >= 0.999f;
                    }
                    for (int s = 0; s < 2; s++)
                    {
                        if (s == 1 && !gbNow) continue;     // 依頼235：右手をはなしている間は数えない
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 依頼235：寄せる道・体と顔の向き・寺島さん
                    {
                        Vector3 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        float cy = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (float.IsNaN(axZ0) && t >= shT0 - 1e-4f) axZ0 = axle.z;
                        if (t >= shT0 - 1e-4f && t <= shT1 + 0.5f)
                        {
                            manYawMax = Mathf.Max(manYawMax, Mathf.Abs(cy));
                            if (havePA) { float v1 = Vector3.Distance(axle, prevAxle) / dt, w1 = Mathf.Abs(Mathf.DeltaAngle(cy, prevCy)) / dt; if (v1 > manV) { manV = v1; manVT = t; } if (w1 > manW) { manW = w1; manWT = t; } }
                            manFwd = Mathf.Max(manFwd, axZ0 - axle.z); manBack = Mathf.Max(manBack, axle.z - axZ0);
                        }
                        prevAxle = axle; prevCy = cy; havePA = true;
                        // 足のせの前の端（車いすの頂点で一番 −z）とハコブくんの前の端
                        float fz = float.MaxValue; Matrix4x4 cw2 = chair.localToWorldMatrix; foreach (var v in chairVertsLocal) if (v.z > 0.5f) fz = Mathf.Min(fz, cw2.MultiplyPoint3x4(v).z);
                        float fr = fz - (rz + rs.maxZ + O.z);
                        if (stopped && resumeT < 0f && fr < footRobotMin) { footRobotMin = fr; footRobotMinT = t; }
                        // 大城さんの体の向き（車いすから）・顔（体から）
                        float bodyRel = Mathf.Abs(Mathf.DeltaAngle(nr.eulerAngles.y, chair.eulerAngles.y));
                        if (bodyRel > oBodyRelMax) { oBodyRelMax = bodyRel; oBodyRelMaxT = t; }
                        if (!gbNow && Mathf.Abs(dir.nurse.headYawDeg) > oHeadMaxTalk) { oHeadMaxTalk = Mathf.Abs(dir.nurse.headYawDeg); oHeadMaxTalkT = t; }
                        if (!gbNow)
                        {
                            var tEL = CloseupNurse.Find(teraN.transform, "Eye_L"); var tER = CloseupNurse.Find(teraN.transform, "Eye_R");
                            var oEL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var oER = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                            float la = Vector3.Angle(dir.nurse.HeadForward(), 0.5f * (tEL.position + tER.position) - 0.5f * (oEL.position + oER.position));
                            oLookTeraMin = Mathf.Min(oLookTeraMin, la);
                        }
                        if (Mathf.Abs(teraN.headYawDeg) > tHeadMax) { tHeadMax = Mathf.Abs(teraN.headYawDeg); tHeadMaxT = t; }
                        Vector3 tp = teraN.transform.position;
                        var tr0 = C["tera_ret"]["t"];
                        if (t >= tr0[0].F() - 1e-4f && t <= tr0[1].F() + 1e-4f)
                        {
                            if (float.IsNaN(teraX0)) { teraX0 = tp.x; teraZ0 = tp.z; teraRetT0 = t; }
                            teraRetDist = Mathf.Max(teraRetDist, new Vector2(tp.x - teraX0, tp.z - teraZ0).magnitude); teraRetT1 = t;
                        }
                        prevTera = tp;
                    }
                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000"));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top235_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    {
                        var ffk = C["ff"]; int spd = C["ff_speed"].I(4);
                        for (int k = 0; ffk != null && k < ffk.Count; k++)
                        {
                            int a0 = Mathf.RoundToInt(ffk[k][0].F() * fps), a1 = Mathf.RoundToInt(ffk[k][1].F() * fps);
                            if (f > a0 && f < a1 && (f - a0) % spd != 0) inRange = false;     // 依頼235：早回しの所は使うコマだけ撮る
                        }
                    }
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && 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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            // 依頼232：体だけの型（同じ真上のカメラ・同じ大きさ）
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform, proxyRootT, teraN.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // 依頼234：もの別の型（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん）
                            var grp = new List<Renderer>[4]; for (int g = 0; g < 4; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[(rd.transform.IsChildOf(proxyRootT) || rd.transform.IsChildOf(teraN.transform)) ? 3 : Group234(rd, dir.robot, chair, mor)].Add(rd);
                            if (!log.ToString().Contains("依頼234 もの別")) { log.AppendLine("依頼234 もの別の型の部品"); string[] gn = { "赤 ハコブくん", "緑 車いすと茂さん", "青 大城さん", "アルファ 寺島さん" }; for (int g = 0; g < 4; g++) { log.Append("  " + gn[g] + " " + grp[g].Count + "："); foreach (var rd in grp[g]) log.Append(" " + rd.name); log.AppendLine(); } }
                            var obj = new Texture2D(W, H, TextureFormat.RGBA32, false);
                            var px = new Color32[W * H];
                            for (int g = 0; g < 4; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < px.Length; i++) { if (g == 0) px[i].r = mp[i].r; else if (g == 1) px[i].g = mp[i].r; else if (g == 2) px[i].b = mp[i].r; else px[i].a = mp[i].r; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(px); 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") SetTop230(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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames235.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top235.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones235.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet235.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc235.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("■ 依頼235 の確かめ");
                tab.AppendLine(string.Format(IC, "寄せる道（{0:0.000}〜{1:0.000} 秒）\t車いすの向きの最大 {2:0.00}°・後ろの車軸の速さの最大 {3:0.0000} m/秒（{4:0.000} 秒）・向きの変わる速さの最大 {5:0.00}°/秒（{6:0.000} 秒）・前へ進んだ距離 {7:0.0000} m・後ろへ下がった距離 {8:0.0000} m（寄せ始めの車軸から）",
                                              shT0, shT1, manYawMax, manV, manVT, manW, manWT, manFwd, manBack));
                tab.AppendLine(string.Format(IC, "足のせの前の端とハコブくんの前の端（止まってから走り出すまで）\t最小 {0:0.0000} m（{1:0.000} 秒）", footRobotMin, footRobotMinT));
                tab.AppendLine(string.Format(IC, "大城さん\t体の向き（車いすから）の最大 {0:0.00}°（{1:0.000} 秒）・顔の向き（体から・片手の間）の最大 {2:0.00}°（{3:0.000} 秒）・寺島さんの目への角度の最小 {4:0.0}°・右手をはなした {5:0.000} 秒・握り直した {6:0.000} 秒・車いすが根に固い時のずれ {7:0.00000}",
                                              oBodyRelMax, oBodyRelMaxT, oHeadMaxTalk, oHeadMaxTalkT, oLookTeraMin, relT, regripT, rigidErr));
                tab.AppendLine(string.Format(IC, "寺島さん\t顔の向きの最大 {0:0.00}°（{1:0.000} 秒）・下がった距離 {2:0.0000} m（{3:0.000}〜{4:0.000} 秒）・当たったコマ 壁/手すり {5}・大城さん {6}・車いす {7}（{8}）",
                                              tHeadMax, tHeadMaxT, teraRetDist, teraRetT0, teraRetT1, hitTS, hitTO, hitTC, hitTWhere));
                tab.AppendLine(string.Format(IC, "走り出し（依頼235 の決まり）\t{0:0.000} 秒・止まってから {1:0.000} 秒・寄った位置のすき間 {2:0.000} m・物の一番後ろを通り過ぎた {3:0.000} 秒", resumeT, resumeT - stopT, resumeGapWall, passedT));
                tab.AppendLine(string.Format(IC, "ハコブくんが通る時（走り出し後）のすき間の最小\t車いす {0:0.000} m（{1:0.000} 秒）・茂さん {2:0.000} m（{3:0.000}）・大城さん {4:0.000} m（{5:0.000}）・寺島さん {6:0.000} m（{7:0.000}）",
                                              passMin["車いす"], passMinT["車いす"], passMin["茂さん"], passMinT["茂さん"], passMin["看護師"], passMinT["看護師"], passMin["寺島さん"], passMinT["寺島さん"]));
                tab.AppendLine("看護師と車いすが当たったコマの時刻\t" + string.Join("・", ncTimes.ToArray()));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check235.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events235.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C235] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        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;
        }

        /// <summary>依頼234：部品がどのものか（0＝ハコブくん・1＝車いすと茂さん・2＝大城さん）。茂さんの写しの部品は名前が Morita_ で始まる</summary>
        static int Group234(Renderer rd, Transform robot, Transform chair, Transform mor)
        {
            var t = rd.transform;
            if (t.IsChildOf(robot)) return 0;
            if (t.IsChildOf(chair) || t.IsChildOf(mor) || rd.name.StartsWith("Morita_")) return 1;
            return 2;
        }

        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.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] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, 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);
        }
    }
}
```

#### tools/an235.py（依頼235）

```python
"""依頼235：報告の表（セリフごとの時刻・カメラの切りかえ・動けない時間・早回し・画面の変わり目）を作る。
使い方: python3 an235.py <Unity の出力フォルダ> <台本> <場面>"""
import csv, json, os, re, sys
D, SC, SHOT = sys.argv[1:4]
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c235"]
vm = json.load(open(os.path.join(D, f"vmap235_{SHOT}.json")))
FPS = 30
ff = [(round(a * FPS), round(b * FPS)) for a, b in C["ff"]]; SPD = C["ff_speed"]
f0 = vm["seq_first"]
def vt(t):
    """台本の秒 → 動画の秒（早回しの所は 1/4）"""
    f = t * FPS; v = (f - f0) / FPS
    for a, b in ff:
        if f > a: v -= (min(f, b) - a) / FPS * (1 - 1 / SPD)
    return v
o = [f"■ {SHOT}"]
o.append(f"動画の長さ {vm['video_s']:.3f} 秒（{vm['n']} コマ・台本 {f0 / FPS:.3f}〜{vm['seq_last'] / FPS:.3f} 秒）")
o.append(f"止まった {vm['t_stop']:.3f} 秒（動画 {vt(vm['t_stop']):.3f}）・走り出し {vm['t_resume']:.3f}（動画 {vt(vm['t_resume']):.3f}）・動けない時間 {vm['t_resume'] - vm['t_stop']:.3f} 秒・物の一番後ろを通り過ぎた {vm['t_pass']:.3f}")
if vm["label_t"] is not None:
    o.append(f"立ち往生の字 {vm['label_t']:.3f} 秒（動画 {vt(vm['label_t']):.3f}）・動けない時間が 30 秒になった {vm['t30']:.3f} 秒・差 {abs(vm['label_t'] - vm['t30']):.3f} 秒")
for a, b in C["ff"]:
    o.append(f"早回し ×{SPD}：台本 {a:.3f}〜{b:.3f} 秒（{b - a:.3f} 秒）→ 動画 {vt(a):.3f}〜{vt(b):.3f} 秒")
o.append("セリフ\t誰\t台本の秒（声の始まり〜終わり）\t動画の秒\t声の長さ")
for k, p in sorted(C["lines"].items(), key=lambda kv: kv[1]["voice_on_s"]):
    o.append(f"{p['text']}\t{p['who']}\t{p['voice_on_s']:.3f}〜{p['voice_off_s']:.3f}\t{vt(p['voice_on_s']):.3f}〜{vt(p['voice_off_s']):.3f}\t{p['voice_len_s']:.3f}")
ls = sorted(C["lines"].values(), key=lambda p: p["voice_on_s"])
o.append("セリフの間（前の声の終わり→次の声の始まり）：" + "・".join(f"{b['text'][:6]} {b['voice_on_s'] - a['voice_off_s']:.3f}" for a, b in zip(ls, ls[1:])))
o.append("カメラ\t台本の秒\t動画の秒")
for t, c in shot["cuts"]:
    if t * FPS <= vm["seq_last"]: o.append(f"{c}\t{t:.3f}\t{max(0.0, vt(t)):.3f}")
rows = list(csv.DictReader(open(os.path.join(D, "frames235.csv"))))
prev = None
o.append("画面の変わり目（台本の秒・動画の秒）")
for r in rows:
    s = r["screen"].split("_")[0]
    if s != prev and float(r["t"]) * FPS <= vm["seq_last"]: o.append(f"  {float(r['t']):.3f}\t{max(0.0, vt(float(r['t']))):.3f}\t{s}"); prev = s
print("\n".join(o))
open(os.path.join(D, f"an235_{SHOT}.txt"), "w").write("\n".join(o) + "\n")
```

#### tools/feas235.py（依頼235）

```python
"""依頼235：止まった車いす（x 0.00・向き 0°）を、その場で向きを変えて x +0.42・向き 0° へ寄せる道があるかの計算（真上の2次元・長方形で近似）。
決まり（依頼235 の答え 1）：向き ±30° まで・速さ 0.3 m/秒・向きの変わる速さ 25°/秒・後ろの車輪は車軸の向きにだけ進む（その場で回るのは車軸の中心で）。
前へ：足のせの前の端とハコブくんの前の端のあいだ 0.6 m 以上。後ろへ：1.0 m まで（車軸の中心の z）。
寸法は 233 と同じ：車いす 車軸の中心から 横 ±0.326・前 0.790（足のせの前の端）・後ろ 0.280。大城さん 根は車軸の後ろ 0.444・幅 ±0.2381・奥行 ±0.157。
手すりの内の面 ±0.84。ハコブくん x −0.4643・幅 ±0.330・前の端は z 0（止まった所。足のせの前の端は G=2.30 m 先）。
z は前（ハコブくんの方）を − に取る。道は「その場で回る」「まっすぐ前／後ろ」をつないだもの（hybrid A*）。費用＝時間（速さの上限で）＋切りかえ 1 回 0.8 秒"""
import math, heapq, sys, json
RAIL = 0.84
CW, CF, CB = 0.326, 0.790, 0.280
OB, OW, OD = 0.444, 0.2381, 0.157
G = float(sys.argv[1]) if len(sys.argv) > 1 else 2.30
MARGIN = float(sys.argv[2]) if len(sys.argv) > 2 else 0.05     # 手すりとの余り
BACK_MAX = float(sys.argv[3]) if len(sys.argv) > 3 else 1.0
FWD_MAX = G - 0.6                                                 # 足のせが前へ出てよい長さ（z）
TH_MAX = 30.0
# 寺島さん（−x を向いて立つ・前 0.150・後ろ 0.140・幅 ±0.2381）。TZ は大城さんの根からの前後（+ は後ろ）。TX は根の x
TX = float(sys.argv[5]) if len(sys.argv) > 5 else 9.0
TZ = float(sys.argv[6]) if len(sys.argv) > 6 else 0.0
PCLR = float(sys.argv[7]) if len(sys.argv) > 7 else 0.05
TF, TB, TW = 0.1499, 0.1399, 0.2381
def tera_box(): return (TX - TF, TX + TB, OB + TZ - TW, OB + TZ + TW)
def poly_box_gap(pts, box):
    # 凸の四角（pts）と軸に沿った箱のすき間（近似：頂点と辺の点の距離・中に入れば −1）
    x0, x1, z0, z1 = box; best = 9.0
    for i in range(4):
        a, b = pts[i], pts[(i + 1) % 4]
        for k in range(9):
            px = a[0] + (b[0] - a[0]) * k / 8; pz = a[1] + (b[1] - a[1]) * k / 8
            dx = max(x0 - px, 0, px - x1); dz = max(z0 - pz, 0, pz - z1)
            best = min(best, -1.0 if dx == 0 and dz == 0 else math.hypot(dx, dz))
    # 箱の角が四角の中
    for (cx, cz) in ((x0, z0), (x0, z1), (x1, z0), (x1, z1)):
        inside = True
        for i in range(4):
            a, b = pts[i], pts[(i + 1) % 4]
            if (b[0] - a[0]) * (cz - a[1]) - (b[1] - a[1]) * (cx - a[0]) > 0: inside = False
        if inside: return -1.0
    return best
def corners(ax, az, th):
    s, c = math.sin(math.radians(th)), math.cos(math.radians(th))
    # 前＝−z、向き + は +x へ。点 (lx 横, lu 前) → 世界
    def w(lx, lu): return (ax + lx * c + lu * s, az - lu * c + lx * s)
    ch = [w(-CW, CF), w(CW, CF), w(CW, -CB), w(-CW, -CB)]
    ob = [w(-OW, -OB + OD), w(OW, -OB + OD), w(OW, -OB - OD), w(-OW, -OB - OD)]
    return ch, ob
def ok(ax, az, th):
    ch, ob = corners(ax, az, th)
    xs = [p[0] for p in ch + ob]
    if max(xs) > RAIL - MARGIN or min(xs) < -RAIL + MARGIN: return False
    fz = min(p[1] for p in ch)            # 足のせの前の端（いちばん前の点）
    if 0.0 - fz > FWD_MAX + 1e-9: return False    # z0 = 足のせの始めの前の端を 0 とする
    if az > BACK_MAX + 1e-9: return False
    if TX < 5:
        bx = tera_box()
        if min(poly_box_gap(ch, bx), poly_box_gap(ob, bx)) < PCLR: return False
    return True
def rail_gap(ax, az, th):
    ch, ob = corners(ax, az, th); xs = [p[0] for p in ch + ob]
    return min(RAIL - max(xs), RAIL + min(xs))
DTH, DS = 1.0, 0.01
V, W = 0.3, 25.0
import os; SW = float(os.environ.get("SW", "0.8"))
def key(ax, az, th): return (round(ax / 0.005), round(az / 0.01), round(th))
start = (0.0, 0.0, 0.0)
goalx = 0.42
pq = [(0.0, 0.0, 0.0, 0.0, 0.0, "", None)]
seen = {}
parent = {}
best = None
n = 0
while pq:
    cost, ax, az, th, _, last, par = heapq.heappop(pq)
    k = key(ax, az, th)
    if k in seen: continue
    seen[k] = (ax, az, th, last, par)
    n += 1
    if abs(ax - goalx) < 0.0026 and abs(th) < 0.5:
        best = k; break
    for mv in ("r+", "r-", "f", "b"):
        if mv == "r+": nax, naz, nth, dc = ax, az, th + DTH, DTH / W
        elif mv == "r-": nax, naz, nth, dc = ax, az, th - DTH, DTH / W
        else:
            sg = 1 if mv == "f" else -1
            nax = ax + sg * DS * math.sin(math.radians(th)); naz = az - sg * DS * math.cos(math.radians(th)); nth = th; dc = DS / V
        if abs(nth) > TH_MAX + 1e-9 or not ok(nax, naz, nth): continue
        # 回る途中も確かめる（1° ごとなので端だけで足りる）
        kind = "r" if mv[0] == "r" else mv
        c2 = cost + dc + (SW if (last and kind != last) else 0.0)
        nk = key(nax, naz, nth)
        if nk in seen: continue
        heapq.heappush(pq, (c2, nax, naz, nth, 0.0, kind, k))
if best is None:
    print(f"G {G} MARGIN {MARGIN} BACK {BACK_MAX}: 道なし（調べた {n}）"); sys.exit(1)
path = []
k = best
while k is not None:
    ax, az, th, last, par = seen[k]; path.append((ax, az, th, last)); k = par
path.reverse()
# 区切り
segs = []
for p in path[1:]:
    if not segs or segs[-1][0] != p[3]: segs.append([p[3], p])
    else: segs[-1].append(p)
fwd = -min(p[1] for p in path); back = max(p[1] for p in path)
fz_min = min(min(q[1] for q in corners(*p[:3])[0]) for p in path)
rg = min(rail_gap(*p[:3]) for p in path)
thmax = max(abs(p[2]) for p in path)
T = 0; prev = None
for s in segs:
    kind = s[0]; a = s[1]; b = s[-1]
    T += (len(s) - 1) * (DTH / W if kind == "r" else DS / V)
desc = []
p0 = path[0]
for s in segs:
    b = s[-1]
    desc.append(f"{ {'r':'回る','f':'前へ','b':'後ろへ'}[s[0]] }→(x {b[0]:+.3f}, z {b[1]:+.3f}, 向き {b[2]:+.0f}°)")
res = {"G": G, "margin": MARGIN, "back_max": BACK_MAX, "turns": len(segs), "time_s": round(T + 0.8 * (len(segs) - 1), 2), "fwd_axle_m": round(fwd, 3), "back_axle_m": round(back, 3),
       "footrest_to_robot_min_m": round(G + fz_min, 3), "rail_gap_min_m": round(rg, 3), "heading_max_deg": thmax, "segs": desc,
       "path": [[round(p[0], 4), round(p[1], 4), p[2], p[3]] for p in path]}
print(json.dumps({k: v for k, v in res.items() if k != "path"}, ensure_ascii=False))
if len(sys.argv) > 4: json.dump(res, open(sys.argv[4], "w"), ensure_ascii=False)
```

#### tools/make235.py（依頼235）

```python
"""依頼235：コマから動画を作る（make229.py・make234.py を写して変えた）。
(1) closeup235_<場面>.mp4：frames/<場面>/f_*.png に台本の秒の音（mix235_<場面>.wav）を重ねる。早回し（台本 c235.ff・×c235.ff_speed）の所は 4 コマに 1 枚を使い、
    音は無し（声の無い所だけを早回しにしている）、右上に「早回し ×4・実際の時間 m:ss」を出す。⑨-2 は 30 秒になった所から 3 秒、左下に「立ち往生 1件（30 秒以上動けず、人が動かした）」
(2) closeup235_<場面>_top.mp4：frames/<場面>_top に 234 の描き方で床の線・通った跡・印・左上の字を重ねる。床の線は、ものごとに穴を埋めた外形
    （閉じる処理 半径 6 画素 → 中の穴埋め）の中には描かない。もの：ハコブくん（赤）・車いすと茂さん（緑）・大城さん（青）・寺島さん（アルファ）。
    大城さんが両手で握りにのせている間（台本 c235.grip_both）は、大城さんと車いすと茂さんを 1 つのものとして埋める（依頼235）
    重ねる順：コマ → 床の線（外形の所は消す）→ 通った跡 → 印 → 左上の字。早回しの所は (1) と同じコマだけ
動画の終わり：ハコブくんが物の一番後ろを通り過ぎてから 2.5 秒（events235.txt）
使い方: python3 make235.py <Unity の出力フォルダ> <台本> <場面> <音の wav> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile, wave
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, SHOT, WAV, VD = sys.argv[1:6]
os.makedirs(VD, exist_ok=True)
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c235"]
FPS, W, H, S = 30, 1920, 1080, 2
ev = open(os.path.join(D, "events235.txt"), encoding="utf-8").read()
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_res = float(re.search(r"([\d.]+) 秒 走り出す", ev).group(1))
t_pass = float(re.search(r"([\d.]+) 秒 物の一番後ろを通り過ぎた", ev).group(1))
f0 = int(round(C["video_from"] * FPS)); f1 = min(int(round((t_pass + 2.5) * FPS)), int(round(C["video_to"] * FPS)))
SPD = C["ff_speed"]; ffseg = [(int(round(a * FPS)), int(round(b * FPS))) for a, b in C["ff"]]
def in_ff(f):
    for a, b in ffseg:
        if a < f < b: return (a, b)
    return None
seq = [f for f in range(f0, f1 + 1) if in_ff(f) is None or (f - in_ff(f)[0]) % SPD == 0]
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s)
label = C.get("stuck_label")
# 立ち往生の字は「止まってから 30 秒」のコマ（Unity の止まった時刻から）
t30 = t_stop + 30.0 if label else None

# ---------------------------------------------------------------- (1) 本番の動画
tmp = tempfile.mkdtemp(prefix="m235_", dir="/tmp")
FB, FS = font(40), font(30)
info = {"frames": len(seq), "ff_frames": sum(1 for f in seq if in_ff(f)), "label": None}
for k, f in enumerate(seq):
    src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src
    t = f / FPS
    ff = in_ff(f); lab = t30 is not None and t30 - 1e-4 <= t < t30 + 3.0 - 1e-4
    if not ff and not lab:
        os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png")); continue
    im = Image.open(src).convert("RGB"); d = ImageDraw.Draw(im)
    if ff:
        real = t - C["video_from"]; s = f"早回し ×{SPD}　実際の時間 {int(real) // 60}:{int(real) % 60:02d}"
        bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
        d.rounded_rectangle([W - w - 70, 24, W - 24, 24 + 72], radius=12, fill=(255, 255, 255))
        d.text((W - w - 47, 60), s, font=FB, fill=(25, 25, 25), anchor="lm")
    if lab:
        if info["label"] is None: info["label"] = t
        s = "立ち往生 1件（30 秒以上動けず、人が動かした）"
        bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
        d.rounded_rectangle([24, H - 24 - 80, 24 + w + 50, H - 24], radius=12, fill=(242, 194, 48))
        d.text((49, H - 24 - 40), s, font=FB, fill=(25, 25, 25), anchor="lm")
    im.save(os.path.join(tmp, f"v_{k:05d}.png"))
# 音：ふだんの所は台本の秒の音、早回しの所は無音（その長さはコマの数 / 30）
wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16)
out = []
for f in seq:
    a = int(round(f / FPS * SR)); b = a + SR // FPS
    out.append(np.zeros(SR // FPS, np.int16) if in_ff(f) else (x[a:b] if b <= len(x) else np.pad(x[a:min(b, len(x))], (0, b - min(b, len(x))))))
aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(np.concatenate(out).tobytes()); w2.close()
vid = os.path.join(VD, f"closeup235_{SHOT}.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw,
                "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30",
                "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True)
# 動画の秒 ↔ 台本の秒
vmap = {f: k / FPS for k, f in enumerate(seq)}
json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "t_stop": t_stop, "t_resume": t_res, "t_pass": t_pass,
           "label_t": info["label"], "t30": t30, "ff": C["ff"], "vmap_keys": {str(f): round(v, 4) for f, v in vmap.items() if f % 15 == 0}},
          open(os.path.join(D, f"vmap235_{SHOT}.json"), "w"), ensure_ascii=False)
print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒・早回しのコマ", info["ff_frames"], "・立ち往生の字", info["label"])

# ---------------------------------------------------------------- (2) 真上の動画
CAM = json.load(open(os.path.join(D, "top235_cam.json")))
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {"center": (120, 120, 120), "x042": (142, 36, 170), "lane": (46, 173, 107), "chair": (239, 108, 0), "robot": (0, 105, 92)}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)
rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames235.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top235.csv")))}
man = C["man"]
MARKS = [("chair", man["t0"], "寄せ始め"), ("chair", man["t1"], "寄せ終わり"), ("robot", t_stop, "止まった"), ("robot", t_res, "走り出し")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]
FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S)
def sc(p): return (p[0] * S, p[1] * S)
def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)
def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0
    while s < L:
        e = min(L, s + DASH * S); d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S); s += (DASH + GAP) * S
def down(layer): return layer.resize((W, H), Image.LANCZOS)
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x042", "lane"): dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
text_box(d, sc((14, line_py["center"] - 8)), "真ん中 0.00", FL, COL["center"], "lb", edge=COL["center"])
text_box(d, sc((14, line_py["x042"] + 8)), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, sc((W - 14, line_py["lane"] - 8)), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st); static_A = static.getchannel("A"); static_An = np.array(static_A)
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (70 if head == "寄せ終わり" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "走り出し" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        tv = vmap.get(mark_f[i]); tv = tv if tv is not None else vmap[min(vmap, key=lambda q: abs(q - mark_f[i]))]
        text_box(d, sc((px, ly)), f"{head} {tv:.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]; cx = num_ok(r["chair_x"]); cy = num_ok(r["chair_yaw"]); g = num_ok(r["gap_m"])
    s0 = f"{vmap[f]:.1f} 秒" + (f"（早回し ×{SPD}）" if in_ff(f) else "")
    return [s0, "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm・向き {cy:+.0f}°" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")]
RC = 6
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def fill_obj(soft):
    ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added
    y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    added[y0:y1, x0:x1] = filled & ~b.astype(bool)
    return added
gb = C["grip_both"]
tmpT = tempfile.mkdtemp(prefix="m235t_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown)
per = []; top_stills = {}
want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"}
k = 0
seqset = set(seq)
for f in range(0, f1 + 1):
    r = top[f]
    for who, kx, ky in (("chair", "axle_px", "axle_py"), ("robot", "robot_px", "robot_py")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)
        if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2; td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))
        prev[who] = p
    if f not in seqset: continue
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA")
    mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L"))
    ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA"))
    joined = gb[min(f, len(gb) - 1)] == 1
    groups = [ob[:, :, 0], np.maximum(ob[:, :, 1], ob[:, :, 2]), ob[:, :, 3]] if joined else [ob[:, :, 0], ob[:, :, 1], ob[:, :, 2], ob[:, :, 3]]
    add_any = np.zeros((H, W), bool)
    for g in groups: add_any |= fill_obj(g)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L"))))
    lines = hud_lines(f)
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl))
    o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1
    stA = np.array(st_m.getchannel("A"))
    per.append((f, int(joined), int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum())))
    if f in want: top_stills[want[f]] = o
vidT = os.path.join(VD, f"closeup235_{SHOT}_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png"))
open(os.path.join(D, f"per235_{SHOT}.csv"), "w").write("frame,joined,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per))
print("真上", vidT, k, "コマ・外形の中に残る線 合計", sum(p[2] for p in per), "・ひとまとめのコマ", sum(p[1] for p in per))
```

#### tools/make_script235.py（依頼235）

```python
"""依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）の台本 closeup235_script.json を作る。場面は 2 つ：stop_voice（⑨-1）・stop_stuck（⑨-2）。
寺島さんは別の場面 <名前>__tera（同じ台本の中。Closeup235.cs が 2 つめの CloseupDirector で動かす）。
make_script229.py を土台にした（廊下・色・光・看護師の値・握りの的・声の口の作り方・ハコブくんの決まり）。229 から変えたこと：
・車いすの根の位置・向きを毎コマ台本に書く（c235.chair）。両手で握っている間は大城さんの根の前に固く付いた位置（229 と同じ）、
  立ち話で大城さんが体を回す間は止めた所のまま
・寄せ方（依頼235 の答え 1）：feas235.py で出した道（その場で回る・まっすぐ前／後ろ）を、速さ 0.3 m/秒・向きの変わる速さ 25°/秒を超えない台形の速さでたどる。
  後ろの車軸の中心がその道を通る（横にすべらない）。大城さんの根と向きは車いすから出す
・立ち話の向き（答え 2）：大城さんは右手（寺島さんから遠い側）を握りからはなし、体ごと寺島さんへ回す（足は 2 歩踏み替える）。左手は左の握りのまま（的は世界に止めた握り）
使い方：python3 make_script229.py と同じ並び：<175 の台本> <出力の台本> <声の wav のフォルダ> <道の json（feas235.py の出力）> [times.json]"""
import json, math, os, sys, wave
import numpy as np

def E(k, d):
    v = os.environ.get(k)
    return type(d)(v) if v is not None else d

src, dst, wavdir, pathjs = sys.argv[1:5]
times = json.load(open(sys.argv[5])) if len(sys.argv) > 5 and os.path.exists(sys.argv[5]) else {}
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = list(S["corridor"]["origin"])
AXLE_BACK = 0.15
GRIP_Z = 0.3336; GRIP_X, GRIP_Y = 0.225, 0.910; GRIP_R = 0.0155
D_PUSH = 0.26
WC_AHEAD = GRIP_Z + D_PUSH                 # 車いすの根：大城さんの根の前（229 と同じ 0.5936）
AX_AHEAD = WC_AHEAD - AXLE_BACK            # 後ろの車軸の中心：大城さんの根の前
WC_FRONT = 0.64
ROBOT_FRONT, ROBOT_REAR = 0.382, 0.380
LANE_R = -0.33
V_C = 0.8                                  # 押す速さ（229）
STEP_T = 0.5
SPINE, CHEST = 4.0, 3.0
Z_NS = E("Z_NS", 9.714)                    # 大城さんの根が止まる z（ハコブくんが 229 と同じ z 5.8 あたりで止まるように）
NZ0 = E("NZ0", 15.0)
RZ0 = E("RZ0", -1.6)
TV0 = 1.0
GAP = E("GAP", 0.55)
O_HW, T_F, T_B = 0.2381, 0.1499, 0.1399
T_GAP = 0.15                               # 寺島さんと大城さんのすき間（233 の 0.10〜0.15 の大きいほう）
T_DZ = E("T_DZ", -0.30)                    # 寺島さんの立つ前後（大城さんの根から。− は前）：答え 2 の「手の届かない形」→ 0.3 m 前へ（turn235.py）
T_X = O_HW + T_GAP + T_F                   # 寺島さんの根の x（立ち話）0.538
T_WALK_X = 0.539                           # 追いつく時の x（大城さんの +x の端 0.238 と手すり 0.84 の真ん中）
T_V = 1.2
O_TURN = E("O_TURN", 29.0)                 # 大城さんが体を回す角度（turn235.py：寺島さん 0.3 m 前で 29°・顔は体から −29°）
T_RET = (0.65, 0.69)                       # 寺島さんが下がって立つ所（x、大城さんの止まった根からの z）。feas235.py の TX・TZ
def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)
q = lambda t: round(round(t * FPS) / FPS, 4)

# ---------------------------------------------------------------- 声（233 の audio）
LINES = {"V1": ("tera", "V1_terashima_oshirosan.wav", "大城さん"), "V2": ("nurse", "V2_oshiro_otsukare.wav", "あ、寺島さん。おつかれさま"),
         "M1": ("morita", "M1_morita_nani.wav", "何を運んでるの？"), "H1": ("robot", "H1_hakobu_otodoke.wav", "病棟へのお届け物です"),
         "H2": ("robot", "H2_hakobu_toorimasu.wav", "すみません、通ります"), "T2": ("tera", "T2_terashima_hakobukun.wav", "あ、ハコブくん"),
         "V8": ("nurse", "V8_oshiro_gomenne.wav", "あ、ごめんね")}
SR = 48000
def load_wav(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float64) / 32768.0
    assert w.getframerate() == SR and w.getnchannels() == 1, p
    return x
def voiced(x, th_db=-45.0):
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    on = np.where(20 * np.log10(e + 1e-9) > th_db)[0]
    return on[0] * hop / SR, (on[-1] + 1) * hop / SR
clips = {}
for k, (who, fn, text) in LINES.items():
    x = load_wav(os.path.join(wavdir, fn)); v0, v1 = voiced(x)
    clips[k] = {"who": who, "file": fn, "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}

RULE = {
    "about": "ハコブくんの決まり（依頼228・229 のまま）。依頼235 で足したのは resume_still_s（止まった後、前の物が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す）と、通り過ぎてから x −0.33 へ戻ること",
    "cruise_mps": 0.6, "slow_mps": 0.5, "accel_max_mps2": 0.4, "decel_max_mps2": 0.4, "jerk_max_mps3": 1.0,
    "detect_range_m": 6.0, "react_s": 0.1, "margin_m": 2.4, "gap_slow_m": 0.40, "gap_stop_m": 0.15,
    "lane_x": LANE_R, "wall_clear_m": 0.053,
    "lateral_max_mps": 0.15, "lateral_angle_deg": 15.0, "lateral_accel_mps2": 0.25, "lateral_gain": 2.0, "lateral_done_m": 0.03,
    "resume_lateral_angle_deg": 10.0, "turn_rate_dps": 30.0, "corner_half_len_m": 0.38, "corner_slack_m": 0.006,
    "pass_behind_m": 1.0, "resume_still_s": 0.5, "still_mps": 0.005,
}

# ---------------------------------------------------------------- 1. 押して来て止まる（x 0・向き 180°）
TW0, RAMP, T_DEC = 0.2, 1.0, 1.6
d_dec = V_C * T_DEC / 2
d_total = NZ0 - Z_NS
t_cr0 = TW0 + RAMP; d_ramp = V_C * RAMP / 2
t_dec0 = t_cr0 + (d_total - d_ramp - d_dec) / V_C
t_ns = t_dec0 + T_DEC
def oshiro_push_z(t):
    if t <= TW0: return NZ0
    if t <= t_cr0:
        u = (t - TW0) / RAMP; return NZ0 - V_C * RAMP * (u ** 3 - 0.5 * u ** 4)          # 速さ smooth(u)·V の積分
    if t <= t_dec0: return NZ0 - d_ramp - V_C * (t - t_cr0)
    if t <= t_ns:
        u = (t - t_dec0) / T_DEC; return NZ0 - d_ramp - V_C * (t_dec0 - t_cr0) - V_C * T_DEC * (u - (u ** 3 - 0.5 * u ** 4))
    return Z_NS
# smooth の積分：∫0^u (3s²−2s³) ds = u³ − u⁴/2（u=1 で 0.5）
assert abs(oshiro_push_z(t_ns) - Z_NS) < 1e-6

# ---------------------------------------------------------------- 2. 寺島さん：後ろから 1.2 m/秒で追いつき、横に並んで「大城さん」、止まって大城さんへ向く
t_v1 = t_dec0 - 0.4                         # 横に並んだ時（大城さんはまだ 0.8 m/秒）に「大城さん」
z_al = oshiro_push_z(t_v1)
T_TD = 2.1                                  # 寺島さんの減速（1.2 → 0・なめらか）
z_tstop = Z_NS + T_DZ
t_ts = t_v1 + T_TD
assert abs((z_al - z_tstop) - T_V * T_TD / 2) < 0.08, (z_al - z_tstop, T_V * T_TD / 2)
T_TD = (z_al - z_tstop) * 2 / T_V; t_ts = t_v1 + T_TD
TZ0 = E("TZ0", z_al + T_V * (t_v1 - 0.2))   # 0.2 秒で 1.2 m/秒（はじめから歩いている）
def tera_z(t):
    if t <= t_v1: return z_al + T_V * (t_v1 - t)
    if t <= t_ts:
        u = (t - t_v1) / T_TD; return z_al - T_V * T_TD * (u - (u ** 3 - 0.5 * u ** 4))
    return z_tstop
YAW_FACE_O = math.degrees(math.atan2(0.0 - T_X, Z_NS - z_tstop)) % 360     # 大城さんの根のほうへ（299°）
t_tturn0, t_tturn1 = t_ts - 0.5, t_ts + 0.5                                # 減速の終わりで向きを変える（2 歩）
def tera_x(t):
    return T_WALK_X + (T_X - T_WALK_X) * smooth((t - t_tturn0) / (t_tturn1 - t_tturn0))
def tera_yaw0(t):
    return 180.0 + (YAW_FACE_O - 180.0) * smooth((t - t_tturn0) / (t_tturn1 - t_tturn0))

# ---------------------------------------------------------------- 3. 大城さんが振り返る（右手をはなし、体を 29° 回す・2 歩）
t_rel0 = t_ns + 0.25; t_rel1 = t_rel0 + 0.5           # 右手の重み 1 → 0
t_oturn0 = t_ns + 0.35; t_oturn1 = t_oturn0 + 0.9     # 向き 180 → 151
on = {"V1": t_v1}
on["V2"] = max(t_oturn0 + 0.45, on["V1"] + clips["V1"]["dur"] + GAP)
T_STOP_EST = on["V2"] + clips["V2"]["dur"] + 2.5
t_stop = times.get("stop_t", T_STOP_EST)
z_rstop = times.get("robot_stop_z", 5.8); x_rstop = times.get("robot_stop_x", -0.4643)

# ---------------------------------------------------------------- 4. 寄せる道（feas235.py の道を時間に）
P = json.load(open(pathjs))
pts = P["path"]
segs = []
for p in pts[1:]:
    if not segs or segs[-1]["kind"] != p[3]: segs.append({"kind": p[3], "pts": []})
    segs[-1]["pts"].append(p)
V_MAX, W_MAX, ACC_T, PAUSE = E("V_MAX", 0.28), E("W_MAX", 23.0), 0.3, 0.15     # 上限 0.3 m/秒・25°/秒より少し下
def trap(d, vmax, ta):
    T = d / vmax + ta
    def f(t):
        if t <= 0: return 0.0
        if t >= T: return d
        if t < ta: return vmax * t * t / (2 * ta)
        if t > T - ta: return d - vmax * (T - t) ** 2 / (2 * ta)
        return vmax * (t - ta / 2)
    return T, f
start = pts[0]
man = []          # (時間の長さ, 関数 u→(ax, az, th))
cur = (start[0], start[1], start[2])
for sg in segs:
    end = sg["pts"][-1]
    if sg["kind"] == "r":
        dth = end[2] - cur[2]; T, f = trap(abs(dth), W_MAX, 0.2); c0 = cur
        man.append((T, (lambda f, c0, dth: lambda t: (c0[0], c0[1], c0[2] + math.copysign(f(t), dth)))(f, c0, dth)))
    else:
        d = math.hypot(end[0] - cur[0], end[1] - cur[1]); T, f = trap(d, V_MAX, ACC_T); c0 = cur; e0 = (end[0], end[1])
        man.append((T, (lambda f, c0, e0, d: lambda t: (c0[0] + (e0[0] - c0[0]) * f(t) / d, c0[1] + (e0[1] - c0[1]) * f(t) / d, c0[2]))(f, c0, e0, d)))
    cur = (end[0], end[1], end[2])
MAN_T = sum(T for T, _ in man) + PAUSE * (len(man) - 1)
AX0_Z = Z_NS - AX_AHEAD                    # 止まった時の車軸の z（向き 0）
def man_at(t):
    """寄せ始めから t 秒の (車軸 x, 車軸 z, 向き°)。feas の z は前＝−（車軸の止まった所から）"""
    for T, fn in man:
        if t <= T: a = fn(t); return a[0], AX0_Z + a[1], a[2]
        t -= T
        if t <= PAUSE: a = fn(T); return a[0], AX0_Z + a[1], a[2]
        t -= PAUSE
    a = man[-1][1](man[-1][0]); return a[0], AX0_Z + a[1], a[2]

# ---------------------------------------------------------------- 場面ごと
def build(variant):
    stuck = variant == "stop_stuck"
    on2 = dict(on)
    ev = {}
    # ⑩
    t_m_turn0 = t_stop + 3.0; t_m_turn1 = t_m_turn0 + 0.45
    on2["M1"] = t_stop + E("M1_AFTER", 3.5)
    on2["H1"] = on2["M1"] + clips["M1"]["dur"] + GAP
    endH1 = on2["H1"] + clips["H1"]["dur"]
    nod_t0 = endH1 + 0.25; NOD_DOWN, NOD_HOLD, NOD_BACK = 0.28, 0.10, 0.32
    m_back0 = nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK + 0.3; m_back1 = m_back0 + 0.6
    # 声をかける
    calls = [t_stop + 10.0] + ([t_stop + 20.0] if stuck else [])
    on2["H2"] = calls[0]
    if stuck: on2["H2b"] = calls[1]
    t30 = t_stop + 30.0
    if stuck:
        t_tlook0 = t30 + E("TLOOK_AFTER", 1.2); t_tlook1 = t_tlook0 + 0.4; t_tback0 = t_tlook1 + 0.35; t_tback1 = t_tback0 + 0.4
        on2["T2"] = t_tback1 + 0.05
        cue_end = on2["T2"] + clips["T2"]["dur"]
    else:
        cue_end = on2["H2"] + clips["H2"]["dur"]
    # 大城さんが気づく：顔をハコブくんへ（cue_end＋0.25）・体を戻して両手で握り直す（＋0.45 から 0.9 秒）・「あ、ごめんね」
    t_olook0 = cue_end + 0.25; t_olook1 = t_olook0 + 0.35
    t_oback0 = cue_end + 0.45; t_oback1 = t_oback0 + 0.9
    t_regrip0 = t_oback1 + 0.1; t_regrip1 = t_regrip0 + 1.0         # 体を戻し終わってから右手を上から握りへ
    on2["V8"] = cue_end + GAP
    endV8 = on2["V8"] + clips["V8"]["dur"]
    t_olookback0 = endV8 + 0.2; t_olookback1 = t_olookback0 + 0.45
    # 寺島さんが下がる（V8 の始まり＋0.3 から）：向きを変え（後ろ＝+z へ）・歩いて・手すりを背に −x を向く
    t_tr0 = on2["V8"] + 0.3
    TR_TURN1, TR_WALK, TR_TURN2 = 0.8, 1.6, 0.8
    t_tr1 = t_tr0 + TR_TURN1; t_tr2 = t_tr1 + TR_WALK; t_tr3 = t_tr2 + TR_TURN2
    # 寄せ始め：握り直しと寺島さんが下がり終わった後
    t_man0 = max(t_regrip1 + 0.2, t_tr3 + 0.1)
    t_man1 = t_man0 + MAN_T
    t_resume_est = t_man1 + 0.6
    t_resume = times.get(variant, {}).get("resume_t", t_resume_est)
    t_exit = times.get(variant, {}).get("passed_t", t_resume + 11.5) + 2.5
    DUR = q(t_exit)
    NF = int(round(DUR * FPS))
    ev.update({"t_stop": t_stop, "t30": t30 if stuck else None, "t_man0": t_man0, "t_man1": t_man1, "t_resume_used": t_resume, "t_exit_used": t_exit,
               "t_tr": [t_tr0, t_tr3], "t_oturn": [t_oturn0, t_oturn1], "t_oback": [t_oback0, t_oback1], "t_rel": [t_rel0, t_rel1], "t_regrip": [t_regrip0, t_regrip1]})

    # ---------- 大城さんの根・向き、車いすの根・向き（毎コマ）
    nurse_rows, chair_rows, grip_both = [], [], []
    for f in range(NF + 1):
        t = f * DT
        if t < t_man0:
            ax, az, th = 0.0, oshiro_push_z(t) - AX_AHEAD, 0.0
            nx_, nz_ = 0.0, oshiro_push_z(t)
            if t < t_oturn0: nyaw = 180.0
            elif t < t_oback0: nyaw = 180.0 - O_TURN * smooth((t - t_oturn0) / (t_oturn1 - t_oturn0))
            else: nyaw = 180.0 - O_TURN * (1 - smooth((t - t_oback0) / (t_oback1 - t_oback0)))
        else:
            ax, az, th = man_at(t - t_man0)
            fx, fz = math.sin(math.radians(th)), -math.cos(math.radians(th))
            nx_, nz_ = ax - fx * AX_AHEAD, az - fz * AX_AHEAD; nyaw = 180.0 - th
        # 車いすの根：車軸の前 0.15（向き th）
        fx, fz = math.sin(math.radians(th)), -math.cos(math.radians(th))
        cx, cz = ax + fx * AXLE_BACK, az + fz * AXLE_BACK
        nurse_rows.append((t, nx_, nz_, nyaw)); chair_rows.append((round(cx, 5), round(cz, 5), round(180.0 - th, 4)))
        grip_both.append(not (t_rel0 <= t < t_regrip1))
    keys_x = [[round(r[0], 4), round(r[1], 5), "lin"] for r in nurse_rows]; keys_x[0] = keys_x[0][:2]
    keys_z = [[round(r[0], 4), round(r[2], 5), "lin"] for r in nurse_rows]; keys_z[0] = keys_z[0][:2]
    keys_yaw = [[round(r[0], 4), round(r[3], 4), "lin"] for r in nurse_rows]; keys_yaw[0] = keys_yaw[0][:2]

    # ---------- 大城さんの足
    def walk_steps(t0, t1, first="R", period=STEP_T):
        st, t, foot = [], t0, first
        while t + period <= t1 + 1e-6:
            st.append([round(t, 4), round(t + period, 4), foot]); t += period; foot = "L" if foot == "R" else "R"
        return st, foot
    steps, foot = walk_steps(TW0, t_ns + 0.25)
    # 振り返る（2 歩：寺島さん側の左足から）・戻る（2 歩）
    steps += [[round(t_oturn0, 4), round(t_oturn0 + 0.45, 4), "L"], [round(t_oturn0 + 0.45, 4), round(t_oturn0 + 0.9, 4), "R"]]
    steps += [[round(t_oback0, 4), round(t_oback0 + 0.45, 4), "R"], [round(t_oback0 + 0.45, 4), round(t_oback0 + 0.9, 4), "L"]]
    # 寄せる間：根が動く／回る間は 0.45 秒ごとに交互に踏む（最後にそろえる 1 歩）
    mv = []
    prev = None
    for f in range(int(t_man0 * FPS), NF + 1):
        r = nurse_rows[f]
        if prev is not None: mv.append((r[0], math.hypot(r[1] - prev[1], r[2] - prev[2]) / DT + abs(r[3] - prev[3]) / DT * 0.01))
        prev = r
    moving = [t for t, v in mv if v > 0.004]
    if moving:
        t, ft, tend = moving[0] - 0.05, "R", moving[-1]
        while t < tend + 0.3:
            steps.append([round(t, 4), round(t + 0.45, 4), ft]); t += 0.45; ft = "L" if ft == "R" else "R"
        steps.append([round(t, 4), round(t + 0.45, 4), ft])
    steps.sort(key=lambda s: s[0])

    # ---------- 大城さんの手：右手は振り返る間はなす。左手は世界に止めた握り
    gz = WC_AHEAD - GRIP_Z
    py = GRIP_Y + GRIP_R + 0.018
    gl_world = [round(GRIP_X, 4), round(py, 4), round(Z_NS - (gz - 0.05), 4)]
    L_target = [[0, "grip_l"], [round(t_oturn0 - 0.02, 4), "grip_l_w", 0.01], [round(t_oback1, 4), "grip_l", 0.01]]
    # 右手：はなす時は握りの上へ上げてから下ろす・握り直す時は上から下ろしてのせる（握りの筒を通らない）
    R_w = [[0, 1.0], [round(t_rel0 + 0.35, 4), 1.0], [round(t_rel1 + 0.35, 4), 0.0], [round(t_regrip0, 4), 0.0], [round(t_regrip0 + 0.55, 4), 1.0]]
    R_target = [[0, "grip_r"], [round(t_rel0, 4), "grip_r_up", 0.35], [round(t_regrip0 - 0.05, 4), "grip_r_up", 0.01], [round(t_regrip0 + 0.55, 4), "grip_r", 0.4]]
    R_curl = [[0, 30.0], [round(t_rel0, 4), 30.0], [round(t_rel1, 4), 8.0], [round(t_regrip0, 4), 8.0], [round(t_regrip1, 4), 30.0]]
    spine = [[0, SPINE], [round(t_oturn0, 4), SPINE], [round(t_oturn1, 4), 2.0], [round(t_oback0, 4), 2.0], [round(t_oback1, 4), SPINE]]
    chest = [[0, CHEST], [round(t_oturn0, 4), CHEST], [round(t_oturn1, 4), 1.0], [round(t_oback0, 4), 1.0], [round(t_oback1, 4), CHEST]]
    walk = [[0, 0], [TW0, 0], [TW0 + 0.4, 1], [round(t_dec0 + 0.6, 4), 1], [round(t_ns, 4), 0]]

    # ---------- 顔の向き：寺島さんを見る（体から 30° 以内）・ハコブくんを見る
    EYE_Y = 1.50
    t_head = (t_oturn0 + 0.2, t_oturn1)
    def look_yaw(nx_, nz_, byaw, tx, tz):
        want = math.degrees(math.atan2(tx - nx_, tz - nz_)); return ((want - byaw + 180) % 360) - 180
    hy = [[0, 0.0], [round(t_head[0], 4), 0.0]]
    hn = [[0, 8.0], [round(t_head[0], 4), 8.0], [round(t_head[1], 4), 0.0]]
    o_to_t = look_yaw(0.0, Z_NS, 180.0 - O_TURN, T_X - 0.05, z_tstop)
    o_to_t = max(-30.0, min(30.0, o_to_t))
    hy.append([round(t_head[1], 4), round(o_to_t, 3)])
    # 立ち話のうなずき（聞く側）・話す（口だけ talk）
    talk_o, talk_t = [[0, 0]], [[0, 0]]
    nod_o, nod_t = [], []
    t_talk0 = on2["V2"] + clips["V2"]["dur"] + 0.6
    t_talk_end_o = cue_end + 0.1
    t_talk_end_t = on2["V8"] if not stuck else t_tlook0 - 0.1
    t, who = t_talk0, "t"
    while t < max(t_talk_end_o, t_talk_end_t) - 0.5:
        L = 2.6 if who == "t" else 2.2
        if who == "t" and t < t_talk_end_t - 0.3:
            talk_t += [[round(t, 4), 1], [round(min(t + L, t_talk_end_t - 0.1), 4), 0]]
            if t + 1.2 < t_talk_end_o: nod_o.append(t + 1.0)
        elif who == "o" and t < t_talk_end_o - 0.3:
            talk_o += [[round(t, 4), 1], [round(min(t + L, t_talk_end_o - 0.1), 4), 0]]
            if t + 1.2 < t_talk_end_t: nod_t.append(t + 1.1)
        t += L + 0.5; who = "o" if who == "t" else "t"
    for tn in nod_o:
        hn += [[round(tn, 4), 0.0], [round(tn + 0.25, 4), 7.0], [round(tn + 0.55, 4), 0.0]]
    hn.sort(key=lambda r: r[0])
    # 気づく
    o_to_r = look_yaw(0.0, Z_NS, 180.0, x_rstop, z_rstop + ROBOT_FRONT)
    hy += [[round(t_olook0, 4), round(o_to_t, 3)], [round(t_olook1, 4), round(o_to_r - (180.0 - (180.0 - O_TURN)), 3)],
           [round(t_oback0, 4), round(o_to_r - O_TURN, 3)], [round(t_oback1, 4), round(o_to_r, 3)],
           [round(t_olookback0, 4), round(o_to_r, 3)], [round(t_olookback1, 4), 0.0]]
    hn += [[round(t_olook0, 4), 0.0], [round(t_olook1, 4), 4.0], [round(t_olookback1, 4), 8.0]]
    hy.sort(key=lambda r: r[0]); hn.sort(key=lambda r: r[0])
    mouth_o = [[0, "flat"], [round(on2["V2"] - 0.2, 4), "smile"]]

    # ---------- 寺島さんの道
    t_rows = []
    zr = Z_NS + T_RET[1]; xr = T_RET[0]
    ret_yaw = 0.0                                                              # 下がる向き（+z）
    for f in range(NF + 1):
        t = f * DT
        if t < t_tr0: x, z, y = tera_x(t), tera_z(t), tera_yaw0(t)
        elif t < t_tr1: x, z, y = T_X, z_tstop, YAW_FACE_O + (((ret_yaw - YAW_FACE_O + 180) % 360) - 180) * smooth((t - t_tr0) / TR_TURN1)
        elif t < t_tr2:
            u = smooth((t - t_tr1) / TR_WALK); x, z, y = T_X, z_tstop + (zr - z_tstop) * u, ret_yaw
        else:
            u = (t - t_tr2) / TR_TURN2
            x, z, y = T_X + (xr - T_X) * smooth(2 * u - 1), zr, ret_yaw + (((270.0 - ret_yaw + 180) % 360) - 180) * smooth(u)
        t_rows.append((t, x, z, y))
    tk = lambda i: [[round(r[0], 4), round(r[i], 5), "lin"] for r in t_rows]
    tx_, tz_, ty_ = tk(1), tk(2), tk(3)
    for a in (tx_, tz_, ty_): a[0] = a[0][:2]
    t_steps = []
    tt, ft = 0.2, "R"
    while tt + 0.45 <= t_ts + 0.05:
        t_steps.append([round(tt, 4), round(tt + 0.45, 4), ft]); tt += 0.45; ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tturn1 - 0.2, 4), round(t_tturn1 + 0.25, 4), ft]]
    ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tr0, 4), round(t_tr0 + 0.4, 4), "R"], [round(t_tr0 + 0.4, 4), round(t_tr0 + 0.8, 4), "L"]]
    tt, ft = t_tr1, "R"
    while tt + 0.4 <= t_tr2 + 0.05:
        t_steps.append([round(tt, 4), round(tt + 0.4, 4), ft]); tt += 0.4; ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tr2, 4), round(t_tr2 + 0.4, 4), ft], [round(t_tr2 + 0.4, 4), round(t_tr2 + 0.8, 4), "L" if ft == "R" else "R"]]
    t_steps.sort(key=lambda s: s[0])
    t_walk = [[0, 1], [round(t_v1 + 0.6, 4), 1], [round(t_ts, 4), 0], [round(t_tr1, 4), 0], [round(t_tr1 + 0.3, 4), 0.6], [round(t_tr2 - 0.3, 4), 0.6], [round(t_tr2, 4), 0]]
    # 寺島さんの顔：大城さんの顔を見る（立ち話）。⑨-2 はハコブくんのほうへ −30°（20〜35°）向けて戻す
    def t_look_o(t):
        r = nurse_rows[min(len(nurse_rows) - 1, int(round(t * FPS)))]
        return look_yaw(T_X, z_tstop, YAW_FACE_O, r[1], r[2])
    thy = [[0, 0.0], [round(t_tturn1, 4), 0.0], [round(t_tturn1 + 0.4, 4), round(max(-30, min(30, t_look_o(t_tturn1 + 0.4))), 3)]]
    if stuck:
        base = round(max(-30, min(30, t_look_o(t_tlook0))), 3)
        thy += [[round(t_tlook0, 4), base], [round(t_tlook1, 4), round(base - E("T_LOOK", 30.0), 3)], [round(t_tback0, 4), round(base - E("T_LOOK", 30.0), 3)], [round(t_tback1, 4), base]]
    thy += [[round(t_tr0, 4), round(max(-30, min(30, t_look_o(t_tr0))), 3)], [round(t_tr0 + 0.5, 4), 0.0]]
    thn = [[0, 6.0], [round(t_ts, 4), 0.0]]
    for tn in nod_t: thn += [[round(tn, 4), 0.0], [round(tn + 0.25, 4), 7.0], [round(tn + 0.55, 4), 0.0]]
    thn.sort(key=lambda r: r[0])
    mouth_t = [[0, "flat"], [round(t_v1 - 0.3, 4), "smile"]]

    # ---------- 茂さん
    M_YAW = 25.0
    m_yaw = [[0, 0.0], [round(t_m_turn0, 4), 0.0], [round(t_m_turn1, 4), M_YAW], [round(m_back0, 4), M_YAW], [round(m_back1, 4), 0.0]]
    m_nod = [[0, 0.0], [round(nod_t0, 4), 0.0], [round(nod_t0 + NOD_DOWN, 4), 10.0], [round(nod_t0 + NOD_DOWN + NOD_HOLD, 4), 10.0], [round(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, 4), 0.0]]
    m_mouth = [[0, "flat"]]

    # ---------- 画面
    scr = [[0, "face"], [q(t_stop + 0.2), "wait"], [q(on2["H1"]), "deliv"], [q(m_back0), "wait"], [q(on2["H2"]), "pass"]]
    if stuck:
        scr += [[q(on2["H2"] + 3.0), "wait"], [q(on2["H2b"]), "pass"], [q(on2["H2b"] + 3.0), "wait"], [q(t30), "stuck"]]
    happy_from = t_resume; happy_to = happy_from + 1.5
    scr += [[q(happy_from), "happy"], [q(happy_to), "face"]]
    ring = [[0, "normal"]] + ([[q(t30), "wait"], [q(t_resume), "normal"]] if stuck else [])

    # ---------- 声の並び・口
    tracks = {w: np.zeros(int(DUR * SR) + SR) for w in ("nurse", "robot", "tera", "morita")}
    place = {}
    for k, t0 in on2.items():
        c = clips["H2" if k == "H2b" else k]
        s0 = t0 - c["v0"]; i0 = int(round(s0 * SR))
        tracks[c["who"]][i0:i0 + len(c["x"])] += c["x"]
        place[k] = {"who": c["who"], "file": c["file"], "text": c["text"], "clip_start_s": round(s0, 4), "voice_on_s": round(t0, 4), "voice_off_s": round(t0 + c["dur"], 4),
                    "voice_len_s": round(c["dur"], 4), "clip_len_s": round(c["len"], 4)}
    HOP = SR // FPS
    def frame_rms(x): return np.array([np.sqrt(np.mean(x[i * HOP:(i + 1) * HOP] ** 2)) if i * HOP < len(x) else 0 for i in range(NF)])
    def ladder(who, rest, speak):
        rms = frame_rms(tracks[who])
        ref = np.percentile(rms[rms > 0.01], 90) if (rms > 0.01).any() else 1.0
        lvl = np.convolve(rms / ref, np.ones(3) / 3, mode="same")
        target = np.where(speak, np.digitize(lvl, [0.15, 0.35, 0.65]), 0)
        for i in range(NF):
            if not speak[i]: target[i] = rest[i]
        for i in range(1, NF - 1):
            if target[i] != target[i - 1] and target[i] != target[i + 1]: target[i] = target[i - 1]
        step = np.zeros(NF, int)
        for i in range(NF):
            prev = step[i - 1] if i else rest[0]
            step[i] = prev + int(np.clip(target[i] - prev, -1, 1)) if i % 2 == 0 else prev
        return step
    def speak_mask(names):
        m = np.zeros(NF, bool)
        for k in names:
            if k in on2: m[int(math.floor(on2[k] * FPS)):int(math.ceil(place[k]["voice_off_s"] * FPS))] = True
        return m
    LADDER = ["closed", "small", "mid", "large"]
    robot_mouth = [LADDER[s] for s in ladder("robot", np.full(NF, 2), speak_mask(["H1", "H2", "H2b"]))]
    nurse_mouth = [int(s) for s in ladder("nurse", np.zeros(NF, int), speak_mask(["V2", "V8"]))]
    tera_mouth = [int(s) for s in ladder("tera", np.zeros(NF, int), speak_mask(["V1", "T2"]))]
    mor_mouth = [int(s) for s in ladder("morita", np.zeros(NF, int), speak_mask(["M1"]))]
    mix = sum(tracks.values())[: int(round(DUR * SR))]
    pk = float(np.max(np.abs(mix))); assert pk < 1.0, pk
    wav_out = os.path.join(os.path.dirname(dst), f"mix235_{variant}.wav")
    w = wave.open(wav_out, "w"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
    w.writeframes((np.clip(mix, -1, 1) * 32767).astype(np.int16).tobytes()); w.close()

    # ---------- カメラ
    zc = z_rstop + 0.7
    zf = z_rstop + ROBOT_FRONT
    CAM = {
        "main": {"pos": [-0.62, 1.72, round(zc - 6.0, 4)], "look": [0.12, 0.8, round(zc + 1.6, 4)], "fov": 38},
        "screen_close": {"follow": "robot", "pos": [x_rstop, 1.23, 1.15], "look": [x_rstop, 0.962, 0.29], "fov": 24},
        "morita_face": {"pos": [-0.42, 1.22, round(Z_NS - WC_AHEAD - 1.25, 4)], "look": [0.02, 1.12, round(Z_NS - WC_AHEAD + 0.02, 4)], "fov": 24},
        "oshiro_face": {"pos": [-0.62, 1.62, round(Z_NS - 1.75, 4)], "look": [0.05, 1.45, round(Z_NS, 4)], "fov": 22},
        "depart": {"pos": [-0.75, 1.70, round(z_rstop - 1.4, 4)], "look": [0.20, 0.75, round(z_rstop + 3.2, 4)], "fov": 46},
        "chk_grip": {"pos": [0.05, 1.55, round(Z_NS + 0.75, 4)], "look": [0.10, 0.95, round(Z_NS - 0.25, 4)], "fov": 40},
    }
    cuts = [[0, "main"], [q(t_stop - 0.1), "screen_close"], [q(t_stop + 1.6), "main"],
            [q(on2["M1"] - 0.35), "morita_face"], [q(on2["H1"] - 0.15), "screen_close"], [q(m_back0 + 0.4), "main"],
            [q(on2["H2"] - 0.15), "screen_close"], [q(on2["H2"] + clips["H2"]["dur"] + 0.15), "main"]]
    if stuck:
        cuts += [[q(on2["H2b"] - 0.15), "screen_close"], [q(on2["H2b"] + clips["H2"]["dur"] + 0.15), "main"],
                 [q(t30 - 0.1), "screen_close"], [q(t30 + 1.0), "main"]]
    cuts += [[q(t_olook0 - 0.1), "oshiro_face"], [q(endV8 + 0.35), "main"]]
    cuts.sort(key=lambda c: c[0])
    stills = [[q(t_v1 + 0.3), "main", "s01_terashima_calls"], [q(on2["V2"] + 1.0), "main", "s02_three_talk"],
              [q(t_stop + 0.1), "main", "s03_robot_stopped_main"], [q(t_stop + 0.8), "screen_close", "s04_robot_stopped_close"],
              [q(on2["M1"] + 0.6), "morita_face", "s05_morita_asks"], [q(on2["H1"] + 0.8), "screen_close", "s06_otodokechu"],
              [q(on2["H2"] + 0.8), "screen_close", "s07_toorimasu"], [q(t_man0 + 0.5 * MAN_T), "main", "s09_shift_main"],
              [q(t_man0 + 0.5 * MAN_T), "top", "s09_shift_top"], [q(t_resume + 2.5), "main", "s10_pass_main"], [q(t_oturn1 + 0.3), "chk_grip", "chk_grip_turned"],
              [q(t_man0 + 1.0), "chk_grip", "chk_grip_man"]]
    if stuck: stills += [[q(t30 + 0.5), "screen_close", "s08_toremasen"], [q(t30 + 1.5), "main", "s08_stuck_label"]]
    else: stills += [[q(on2["V8"] + 0.4), "oshiro_face", "s08_oshiro_notices"]]
    # 早回し（⑨-2：声と動きの無い所。×4）
    ff = []
    if stuck:
        ff = [[round(m_back1 + 0.6, 3), round(on2["H2"] - 0.6, 3)], [round(on2["H2"] + 3.4, 3), round(on2["H2b"] - 0.6, 3)], [round(on2["H2b"] + 3.4, 3), round(t30 - 0.6, 3)]]
        ff = [[a, b] for a, b in ff if b - a >= 1.0]
    shot = {"name": variant, "about": "⑨ 車いすが廊下の真ん中で止まる（依頼235：" + ("⑨-2 立ち往生になる" if stuck else "⑨-1 声をかけて寄せてもらう") + "）", "origin": O, "duration": DUR, "video": True,
            "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]},
            "box_events": [], "card_events": [], "presses": [], "card": False,
            "check_open": [], "check_close": [], "check_above": [], "transitions": [],
            "robot_start_z": RZ0, "swing_ramp": 0.15, "lift_pow": 0.5,
            "nurse": {"x": keys_x, "z": keys_z, "yaw": keys_yaw, "walk": walk, "spine": spine, "chest": chest,
                      "head_yaw": hy, "head_nod": hn, "mouth": mouth_o, "talk": talk_o,
                      "L_w": [[0, 1.0]], "R_w": R_w, "L_target": L_target, "R_target": R_target,
                      "L_curl": [[0, 30.0]], "R_curl": R_curl, "L_thumb": [[0, 20.0]], "R_thumb": [[0, 20.0]],
                      "L_hint": [[0, "push_l"]], "R_hint": [[0, "push_r"]], "L_hint_w": [[0, 0.5]], "R_hint_w": [[0, 0.5]]},
            "steps": steps, "look_windows": [], "cameras": CAM, "cuts": cuts, "stills": stills,
            "c235": {"wc_ahead_m": round(WC_AHEAD, 4), "video_from": TV0, "video_to": round((NF - 1) * DT, 4),
                     "chair": chair_rows, "grip_both": [1 if g else 0 for g in grip_both],
                     "screen": scr, "ring": ring, "ring_wait_color": "#F2C230", "happy": [round(happy_from, 4), round(happy_to, 4)],
                     "stuck_label": [round(t30, 4), round(t30 + 3.0, 4)] if stuck else None, "ff": ff, "ff_speed": 4,
                     "robot_mouth": robot_mouth, "nurse_mouth": nurse_mouth, "tera_mouth": tera_mouth, "morita_mouth_lvl": mor_mouth, "nurse_mouth_scale": [1.0, 1.2, 1.8, 2.4],
                     "morita": {"head_yaw": m_yaw, "head_nod": m_nod, "mouth": m_mouth, "neck_share": 0.4,
                                "blink": {"every_min_s": 3.0, "every_max_s": 5.0, "close_s": 0.15, "seed": 228}, "eye_min_scale": 0.1},
                     "lines": place, "grip": {"x": GRIP_X, "y": GRIP_Y, "z_behind_root": GRIP_Z, "r": GRIP_R},
                     "man": {"t0": round(t_man0, 4), "t1": round(t_man1, 4), "path_file": os.path.basename(pathjs), "segs": P["segs"], "v_max": V_MAX, "w_max": W_MAX},
                     "tera_ret": {"x": xr, "z": round(zr, 4), "from": [round(T_X, 4), round(z_tstop, 4)], "t": [round(t_tr0, 4), round(t_tr3, 4)]},
                     "times": {k: (round(v, 4) if isinstance(v, float) else v) for k, v in ev.items()}}}
    tshot = {"name": variant + "__tera", "about": "寺島さん（" + variant + "）", "origin": O, "duration": DUR, "video": True,
             "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]}, "box_events": [], "card_events": [], "presses": [], "card": False,
             "check_open": [], "check_close": [], "check_above": [], "transitions": [], "swing_ramp": 0.15, "lift_pow": 0.5,
             "nurse": {"x": tx_, "z": tz_, "yaw": ty_, "walk": t_walk, "spine": [[0, 2.0]], "chest": [[0, 1.0]],
                       "head_yaw": thy, "head_nod": thn, "mouth": mouth_t, "talk": talk_t, "L_w": [[0, 0.0]], "R_w": [[0, 0.0]]},
             "steps": t_steps}
    info = {"variant": variant, "duration": DUR, "t_stop": t_stop, "on": {k: round(v, 3) for k, v in on2.items()}, "man": [round(t_man0, 3), round(t_man1, 3), round(MAN_T, 3)],
            "stuck_est": round(t_resume_est - t_stop, 3), "t_tr": [round(t_tr0, 3), round(t_tr3, 3)], "ff": ff}
    return shot, tshot, info

out = {k: S[k] for k in ("fps", "width", "height", "supersample", "colors", "light", "rooms", "box", "bag", "nurse", "targets", "card", "pocket", "screen_ui", "drawer_parts", "hints", "check_stand_parts", "corridor")}
out["about"] = "依頼235：⑨ 車いすが廊下の真ん中で止まる（場面 stop_voice・stop_stuck、寺島さんは __tera）。make_script235.py が作った。廊下・色・光・看護師・画面の値は 175 の台本から写した"
out["nurse"] = dict(out["nurse"]); out["nurse"]["walk"] = dict(out["nurse"]["walk"])
out["nurse"]["walk"].update({"amp_deg": 11.0, "knee_deg": 24, "bob_m": 0.008, "lift_m": 0.05})
gz = WC_AHEAD - GRIP_Z
out["targets"] = dict(out["targets"])
py = GRIP_Y + GRIP_R + 0.018
out["targets"]["grip_l"] = {"ref": "nurse", "pos": [round(-GRIP_X, 4), round(py, 4), round(gz - 0.05, 4)], "finger_frame": "nurse", "finger": [-1.0, -0.35, 1], "palm_frame": "nurse", "palm": [0.3, -1, 0.0]}
out["targets"]["grip_r"] = {"ref": "nurse", "pos": [round(GRIP_X, 4), round(py, 4), round(gz - 0.05, 4)], "finger_frame": "nurse", "finger": [1.0, -0.35, 1], "palm_frame": "nurse", "palm": [-0.3, -1, 0.0]}
# 振り返る間の左手：止まった時（大城さんの根 x 0・z Z_NS・向き 180°）の grip_l と同じ点・同じ向きを、世界に止める
out["targets"]["grip_r_up"] = {"ref": "nurse", "pos": [round(GRIP_X + 0.03, 4), round(py + 0.15, 4), round(gz - 0.20, 4)], "finger_frame": "nurse", "finger": [1.0, -0.35, 1], "palm_frame": "nurse", "palm": [-0.3, -1, 0.0]}
out["targets"]["grip_l_w"] = {"ref": "world", "pos": [round(GRIP_X, 4), round(py, 4), round(Z_NS - (gz - 0.05), 4)], "finger_frame": "world", "finger": [1.0, -0.35, -1], "palm_frame": "world", "palm": [-0.3, -1, 0.0]}
out["hints"] = dict(out["hints"]); out["hints"]["push_l"] = [-0.40, 1.0, -0.20]; out["hints"]["push_r"] = [0.40, 1.0, -0.20]
out["robot_rule"] = RULE
shots, infos = [], []
for v in ("stop_voice", "stop_stuck"):
    a, b, i = build(v); shots += [a, b]; infos.append(i)
out["shots"] = shots
out["c235_common"] = {"z_ns": Z_NS, "t_ns": round(t_ns, 4), "t_v1": round(t_v1, 4), "nz0": NZ0, "tz0": round(TZ0, 4), "t_x": round(T_X, 4), "t_dz": T_DZ, "o_turn": O_TURN,
                      "z_tstop": round(z_tstop, 4), "t_ts": round(t_ts, 4), "yaw_face_o": round(YAW_FACE_O, 3), "man_T": round(MAN_T, 3), "t_stop_used": t_stop, "robot_stop_z_used": z_rstop}
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=0)
print(json.dumps({"common": out["c235_common"], "shots": infos}, ensure_ascii=False))
```

#### tools/run235.sh（依頼235）

```bash
#!/bin/bash
# 依頼235 使い方: run235.sh <出力フォルダ> <場面 stop_voice|stop_stuck> <コマ on|off> [静止画 on|off] [views] [until]
OUT="$1"; SH="$2"; FR="${3:-off}"; ST="${4:-off}"; VW="${5:-main,top}"; UNTIL="${6:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup235.Run \
   -c235Out "$OUT" -c235Shot "$SH" -c235Frames "$FR" -c235Stills "$ST" -c235Views "$VW" -c235Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

#### tools/run235b.sh（依頼235）

```bash
#!/bin/bash
# 依頼235 区切って撮る（Unity は 13 分ほどで止められるので 1 回を短く）: run235b.sh <出力フォルダ> <場面> <from 秒> <to 秒（1e9＝終わりまで）> [stills on|off]
OUT="$1"; SH="$2"; FROM="$3"; TO="$4"; ST="${5:-on}"
UNTIL=$(python3 -c "print($TO + 0.05 if $TO < 1e8 else 1e9)")
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup235.Run \
   -c235Out "$OUT" -c235Shot "$SH" -c235Frames on -c235Stills "$ST" -c235Views main,top -c235From "$FROM" -c235To "$TO" -c235Until "$UNTIL" -logFile "$OUT/unity_${FROM}_${TO}.log"
echo "exit $?"
```

#### tools/screen235.py（依頼235）

```python
#!/usr/bin/env python3
"""依頼235：画面の絵。帯だけの絵（228 の screen228.py と同じ描き方）を 3 つと、「通れません」（帯は黄・帯の下に⑤の困り顔）の 1 枚。
・c235_wait_band.png「お待ちしています」・c235_deliv_band.png「お届け中」・c235_pass_band.png「通ります」（帯の色はミント＝台本の screen_ui.band）
・c235_stuck.png：帯（黄 #F2C230＝⑤の輪の待つ色）「通れません」＋帯の下の黒に、⑤の困り顔（c203_recall_1ko.png の face_box_px の所）をそのままの大きさで真ん中に置く。行き先・中身・数は描かない
確かめ：同じ描き方で「お届け完了」を描くと c223_done_band.png と同じ絵になること
使い方：python3 screen235.py <台本の JSON（screen_ui）> <Textures フォルダ> <screen218.py のフォルダ>"""
import importlib.util, json, sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
js = json.load(open(sys.argv[1])); out = Path(sys.argv[2])
spec = importlib.util.spec_from_file_location("s218", str(Path(sys.argv[3]) / "screen218.py")); m = importlib.util.module_from_spec(spec)
sys.argv = sys.argv[:1]; spec.loader.exec_module(m)
S = js["screen_ui"]
def band(text, k=0.46, color=None, full=False):
    W = int(S["tex_w"]); H = int(round(W / float(S["aspect"]))); R = int(S["corner_r"] * H)
    mask = Image.new("L", (W, H), 0); ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, H - 1], radius=R, fill=255)
    bh = int(0.2 * H)
    img = Image.new("RGBA", (W, H), m.hexc(S["bg"])); d = ImageDraw.Draw(img)
    d.rectangle([0, 0, W, bh], fill=m.hexc(color or S["band"], int(S.get("band_alpha", 235))))
    d.text((W // 2, bh // 2), text, font=m.font(bh * k), fill=m.hexc(S["fg"]) if color is None else (30, 30, 30, 255), anchor="mm")
    a = img.split()[3]; img.putalpha(Image.composite(a, Image.new("L", (W, H), 0), mask))
    b = np.array(img)
    if not full: b[bh + 1:, :, :] = 0
    return b, bh
ref = np.array(Image.open(out / "c223_done_band.png").convert("RGBA"))
chk, _ = band("お届け完了")
print("確かめ：お届け完了を描くと c223_done_band と同じ", chk.shape == ref.shape and bool((chk == ref).all()))
for fn, text in (("c235_wait_band.png", "お待ちしています"), ("c235_deliv_band.png", "お届け中"), ("c235_pass_band.png", "通ります")):
    Image.fromarray(band(text)[0]).save(out / fn); print("作った絵:", fn, text)
b, bh = band("通れません", color="#F2C230", full=True)
lay = json.load(open(out / "c203_layout.json")); x0, y0, x1, y1 = lay["face_box_px"]
src = np.array(Image.open(out / "c203_recall_1ko.png").convert("RGBA"))
face = src[y0:y1, x0:x1]
H, W = b.shape[:2]; cx, cy = W // 2, bh + (H - bh) // 2
fy0, fx0 = cy - face.shape[0] // 2, cx - face.shape[1] // 2
b[fy0:fy0 + face.shape[0], fx0:fx0 + face.shape[1]] = face
Image.fromarray(b).save(out / "c235_stuck.png"); print("作った絵: c235_stuck.png 通れません（黄）＋困り顔", face.shape)
```

#### tools/turn235.py（依頼235）

```python
"""依頼235：立ち話の大城さんの向き（答え 2）。寺島さんから遠い側（右手）を握りからはなし、体ごと寺島さんへ回す。近い側（左手）は握りのまま。
顔は体から 30° 以内で寺島さんの顔を見る。寺島さんの前後の位置 tz（+ は後ろ・0.3 m まで）と、大城さんの根を動かす量（踏み替え）から、
左の肩と左の握りの距離（229 の押す形 0.428 m・腕 0.47 m＝上腕 0.25＋前腕 0.22。手のひらの的まで）を出す。座標は大城さんの止まった根から（前＝−z・+x は寺島さんの側）"""
import math
GRIP = (0.225, -0.21, 0.943)          # 左の握りの手のひらの的（229 の grip_l。大城さんの根から：x は世界の +x）
SH_W, SH_F, SH_Y = 0.15, 0.03, 1.29
O_HW, T_F = 0.2381, 0.1499
def shoulderL(rx, rz, yaw):
    s, c = math.sin(math.radians(yaw)), math.cos(math.radians(yaw))
    fwd = (s, c); left = (-c, s)
    return (rx + left[0] * SH_W + fwd[0] * SH_F, rz + left[1] * SH_W + fwd[1] * SH_F, SH_Y)
def dist(a, b): return math.dist(a, b)
print("押す形（向き 180°）の左の肩と握り", round(dist(shoulderL(0, 0, 180), GRIP), 3))
for g in (0.10, 0.15):
    xT = O_HW + g + T_F
    for tz in (0.0, -0.1, -0.2, -0.3, 0.1, 0.2, 0.3):
        best = None
        for dx in [i * 0.01 for i in range(0, 16)]:
            for dz in [i * 0.01 for i in range(-20, 21)]:
                hx, hz = dx + 0.05 * 0, dz
                # 顔（目）から寺島さんの顔へ
                yawT = math.degrees(math.atan2(xT - 0.05 - hx, tz - hz))
                for body in range(180, 60, -1):
                    if abs(((yawT - body + 180) % 360) - 180) > 30: continue
                    d = dist(shoulderL(dx, dz, body), GRIP)
                    turn = 180 - body
                    cand = (round(math.hypot(dx, dz), 3), turn, d, dx, dz, round(((yawT - body + 180) % 360) - 180, 1))
                    if d <= 0.43 and (best is None or cand[:2] < best[:2]): best = cand
                    break
        print(f"すき間 {g:.2f}・寺島さん tz {tz:+.1f}：", "無し" if best is None else
              f"根を動かす {best[0]:.3f} m（x {best[3]:+.2f}・z {best[4]:+.2f}）・体を回す {best[1]}°・左の肩と握り {best[2]:.3f} m・顔（体から）{best[5]:+.1f}°")
```

#### geo/feas235.txt（依頼235）

```text
依頼235：その場で向きを変えて寄せる道があるかの計算（tools/feas235.py。真上の2次元・長方形で近似・hybrid A*）
決まり：向き ±30° まで・速さ 0.3 m/秒・向きの変わる速さ 25°/秒・後ろの車輪は車軸の向きにだけ進む（その場で回る時は車軸の中心で）・
前へ：足のせの前の端とハコブくんの前の端のあいだ 0.6 m 以上（止まった時のあいだ G=2.30 m で計算。Unity では 2.40 m で止まった）・後ろへ：車軸の中心で 1.0 m まで
寸法：車いす 車軸の中心から 横 ±0.326・前 0.790・後ろ 0.280／大城さん 車軸の後ろ 0.444・幅 ±0.2381・奥行 ±0.157／寺島さん −x を向いて 前 0.150・後ろ 0.140・幅 ±0.2381／手すりの内の面 ±0.84
手すりとの余り（計算で決めた値）：0.05 m（0.03 m でも試した）。寺島さんとのすき間：0.05 m 以上
費用：時間（速さの上限で）＋切りかえ 1 回 SW 秒

(1) 寺島さんがいない時（寄せられるか）
  余り 0.05・後ろへ 1.0 m まで：7 区切り・11.85 秒・前へ 0・後ろへ 0.983・向き最大 28°
  余り 0.05・後ろへ 0.5：7 区切り・12.49 秒・前へ 0.473・後ろへ 0.408・足のせとハコブくん 0.973 m
  余り 0.05・後ろへ 0.3：7 区切り・12.51 秒・前へ 0.545・後ろへ 0.243
  余り 0.05・後ろへ 0：9 区切り・14.43 秒・前へ 0.846・足のせとハコブくん 0.607 m
  余り 0.03・後ろへ 1.0：5 区切り・9.04 秒／後ろへ 0.5：5 区切り・10.73 秒／後ろへ 0：7 区切り・12.26 秒
  → どれも道がある（決まりの中で寄せられる）

(2) 寺島さんが立ち話の所（大城さんの +x 側・すき間 g・大城さんの根から前後 tz）から動かない時
  g 0.10・tz 0：道なし
  g 0.15・tz 0：9 区切り・16.69 秒・前へ 0.841・足のせとハコブくん 0.604 m（前へ・後ろへを 3 回くり返す）
  g 0.10／0.15・tz +0.15：9 区切り・15.53 秒
  ※ ただし立ち話の向き（答え 2）で左手を握りにのせたまま体を寺島さんへ回すには、寺島さんが tz 0 だと体を 75° 回して根を 0.13 m 車いすの側へ動かす必要があり、
    胴が車いすの背と重なる（turn235.txt）。寺島さんを 0.3 m 前（tz −0.3）に立たせると体を 29° 回すだけで届く（答え 2 の「前後に 0.3 m まで動かして合わせる」）。
    tz −0.3 の所は車いすの +x の横（大城さんの寄る所）なので、寺島さんは下がる

(3) 寺島さんが下がった所（x +0.65・大城さんの止まった根から後ろ 0.69 m。立ち話の所 x +0.538・tz −0.3 から 0.996 m）
  SW 0.8：7 区切り・12.51 秒・前へ 0.545・後ろへ 0.243・向き最大 20°
  SW 3.0：7 区切り・12.95 秒・前へ 0.822・後ろへ 0.054・向き最大 17°・足のせとハコブくん 0.628 m（G 2.30 で）・手すり 0.051 m  ← 使った道（geo/path235.json）
    回る +12° → 前へ 0.84 m（x +0.175）→ 回る −17° → 後ろへ 0.73 m（x +0.385）→ 回る −10° → 後ろへ 0.19 m（x +0.418）→ 回る 0°
  （前へ多く進んで、後ろへは少しだけ下がる形を選んだ。寺島さんの方へ大城さんが下がる量が小さい）
```

#### geo/path235.json（依頼235）

```json
{"G": 2.3, "margin": 0.05, "back_max": 1.0, "turns": 7, "time_s": 12.95, "fwd_axle_m": 0.822, "back_axle_m": 0.054, "footrest_to_robot_min_m": 0.628, "rail_gap_min_m": 0.051, "heading_max_deg": 17.0, "segs": ["回る→(x +0.000, z +0.000, 向き +12°)", "前へ→(x +0.175, z -0.822, 向き +12°)", "回る→(x +0.175, z -0.822, 向き -17°)", "後ろへ→(x +0.385, z -0.133, 向き -17°)", "回る→(x +0.385, z -0.133, 向き -10°)", "後ろへ→(x +0.418, z +0.054, 向き -10°)", "回る→(x +0.418, z +0.054, 向き +0°)"], "path": [[0.0, 0.0, 0.0, ""], [0.0, 0.0, 1.0, "r"], [0.0, 0.0, 2.0, "r"], [0.0, 0.0, 3.0, "r"], [0.0, 0.0, 4.0, "r"], [0.0, 0.0, 5.0, "r"], [0.0, 0.0, 6.0, "r"], [0.0, 0.0, 7.0, "r"], [0.0, 0.0, 8.0, "r"], [0.0, 0.0, 9.0, "r"], [0.0, 0.0, 10.0, "r"], [0.0, 0.0, 11.0, "r"], [0.0, 0.0, 12.0, "r"], [0.0021, -0.0098, 12.0, "f"], [0.0042, -0.0196, 12.0, "f"], [0.0062, -0.0293, 12.0, "f"], [0.0083, -0.0391, 12.0, "f"], [0.0104, -0.0489, 12.0, "f"], [0.0125, -0.0587, 12.0, "f"], [0.0146, -0.0685, 12.0, "f"], [0.0166, -0.0783, 12.0, "f"], [0.0187, -0.088, 12.0, "f"], [0.0208, -0.0978, 12.0, "f"], [0.0229, -0.1076, 12.0, "f"], [0.0249, -0.1174, 12.0, "f"], [0.027, -0.1272, 12.0, "f"], [0.0291, -0.1369, 12.0, "f"], [0.0312, -0.1467, 12.0, "f"], [0.0333, -0.1565, 12.0, "f"], [0.0353, -0.1663, 12.0, "f"], [0.0374, -0.1761, 12.0, "f"], [0.0395, -0.1858, 12.0, "f"], [0.0416, -0.1956, 12.0, "f"], [0.0437, -0.2054, 12.0, "f"], [0.0457, -0.2152, 12.0, "f"], [0.0478, -0.225, 12.0, "f"], [0.0499, -0.2348, 12.0, "f"], [0.052, -0.2445, 12.0, "f"], [0.0541, -0.2543, 12.0, "f"], [0.0561, -0.2641, 12.0, "f"], [0.0582, -0.2739, 12.0, "f"], [0.0603, -0.2837, 12.0, "f"], [0.0624, -0.2934, 12.0, "f"], [0.0645, -0.3032, 12.0, "f"], [0.0665, -0.313, 12.0, "f"], [0.0686, -0.3228, 12.0, "f"], [0.0707, -0.3326, 12.0, "f"], [0.0728, -0.3424, 12.0, "f"], [0.0748, -0.3521, 12.0, "f"], [0.0769, -0.3619, 12.0, "f"], [0.079, -0.3717, 12.0, "f"], [0.0811, -0.3815, 12.0, "f"], [0.0832, -0.3913, 12.0, "f"], [0.0852, -0.401, 12.0, "f"], [0.0873, -0.4108, 12.0, "f"], [0.0894, -0.4206, 12.0, "f"], [0.0915, -0.4304, 12.0, "f"], [0.0936, -0.4402, 12.0, "f"], [0.0956, -0.4499, 12.0, "f"], [0.0977, -0.4597, 12.0, "f"], [0.0998, -0.4695, 12.0, "f"], [0.1019, -0.4793, 12.0, "f"], [0.104, -0.4891, 12.0, "f"], [0.106, -0.4989, 12.0, "f"], [0.1081, -0.5086, 12.0, "f"], [0.1102, -0.5184, 12.0, "f"], [0.1123, -0.5282, 12.0, "f"], [0.1144, -0.538, 12.0, "f"], [0.1164, -0.5478, 12.0, "f"], [0.1185, -0.5575, 12.0, "f"], [0.1206, -0.5673, 12.0, "f"], [0.1227, -0.5771, 12.0, "f"], [0.1247, -0.5869, 12.0, "f"], [0.1268, -0.5967, 12.0, "f"], [0.1289, -0.6065, 12.0, "f"], [0.131, -0.6162, 12.0, "f"], [0.1331, -0.626, 12.0, "f"], [0.1351, -0.6358, 12.0, "f"], [0.1372, -0.6456, 12.0, "f"], [0.1393, -0.6554, 12.0, "f"], [0.1414, -0.6651, 12.0, "f"], [0.1435, -0.6749, 12.0, "f"], [0.1455, -0.6847, 12.0, "f"], [0.1476, -0.6945, 12.0, "f"], [0.1497, -0.7043, 12.0, "f"], [0.1518, -0.714, 12.0, "f"], [0.1539, -0.7238, 12.0, "f"], [0.1559, -0.7336, 12.0, "f"], [0.158, -0.7434, 12.0, "f"], [0.1601, -0.7532, 12.0, "f"], [0.1622, -0.763, 12.0, "f"], [0.1643, -0.7727, 12.0, "f"], [0.1663, -0.7825, 12.0, "f"], [0.1684, -0.7923, 12.0, "f"], [0.1705, -0.8021, 12.0, "f"], [0.1726, -0.8119, 12.0, "f"], [0.1746, -0.8216, 12.0, "f"], [0.1746, -0.8216, 11.0, "r"], [0.1746, -0.8216, 10.0, "r"], [0.1746, -0.8216, 9.0, "r"], [0.1746, -0.8216, 8.0, "r"], [0.1746, -0.8216, 7.0, "r"], [0.1746, -0.8216, 6.0, "r"], [0.1746, -0.8216, 5.0, "r"], [0.1746, -0.8216, 4.0, "r"], [0.1746, -0.8216, 3.0, "r"], [0.1746, -0.8216, 2.0, "r"], [0.1746, -0.8216, 1.0, "r"], [0.1746, -0.8216, 0.0, "r"], [0.1746, -0.8216, -1.0, "r"], [0.1746, -0.8216, -2.0, "r"], [0.1746, -0.8216, -3.0, "r"], [0.1746, -0.8216, -4.0, "r"], [0.1746, -0.8216, -5.0, "r"], [0.1746, -0.8216, -6.0, "r"], [0.1746, -0.8216, -7.0, "r"], [0.1746, -0.8216, -8.0, "r"], [0.1746, -0.8216, -9.0, "r"], [0.1746, -0.8216, -10.0, "r"], [0.1746, -0.8216, -11.0, "r"], [0.1746, -0.8216, -12.0, "r"], [0.1746, -0.8216, -13.0, "r"], [0.1746, -0.8216, -14.0, "r"], [0.1746, -0.8216, -15.0, "r"], [0.1746, -0.8216, -16.0, "r"], [0.1746, -0.8216, -17.0, "r"], [0.1776, -0.8121, -17.0, "b"], [0.1805, -0.8025, -17.0, "b"], [0.1834, -0.793, -17.0, "b"], [0.1863, -0.7834, -17.0, "b"], [0.1893, -0.7738, -17.0, "b"], [0.1922, -0.7643, -17.0, "b"], [0.1951, -0.7547, -17.0, "b"], [0.198, -0.7451, -17.0, "b"], [0.201, -0.7356, -17.0, "b"], [0.2039, -0.726, -17.0, "b"], [0.2068, -0.7165, -17.0, "b"], [0.2097, -0.7069, -17.0, "b"], [0.2127, -0.6973, -17.0, "b"], [0.2156, -0.6878, -17.0, "b"], [0.2185, -0.6782, -17.0, "b"], [0.2214, -0.6686, -17.0, "b"], [0.2243, -0.6591, -17.0, "b"], [0.2273, -0.6495, -17.0, "b"], [0.2302, -0.6399, -17.0, "b"], [0.2331, -0.6304, -17.0, "b"], [0.236, -0.6208, -17.0, "b"], [0.239, -0.6113, -17.0, "b"], [0.2419, -0.6017, -17.0, "b"], [0.2448, -0.5921, -17.0, "b"], [0.2477, -0.5826, -17.0, "b"], [0.2507, -0.573, -17.0, "b"], [0.2536, -0.5634, -17.0, "b"], [0.2565, -0.5539, -17.0, "b"], [0.2594, -0.5443, -17.0, "b"], [0.2624, -0.5348, -17.0, "b"], [0.2653, -0.5252, -17.0, "b"], [0.2682, -0.5156, -17.0, "b"], [0.2711, -0.5061, -17.0, "b"], [0.2741, -0.4965, -17.0, "b"], [0.277, -0.4869, -17.0, "b"], [0.2799, -0.4774, -17.0, "b"], [0.2828, -0.4678, -17.0, "b"], [0.2857, -0.4582, -17.0, "b"], [0.2887, -0.4487, -17.0, "b"], [0.2916, -0.4391, -17.0, "b"], [0.2945, -0.4296, -17.0, "b"], [0.2974, -0.42, -17.0, "b"], [0.3004, -0.4104, -17.0, "b"], [0.3033, -0.4009, -17.0, "b"], [0.3062, -0.3913, -17.0, "b"], [0.3091, -0.3817, -17.0, "b"], [0.3121, -0.3722, -17.0, "b"], [0.315, -0.3626, -17.0, "b"], [0.3179, -0.3531, -17.0, "b"], [0.3208, -0.3435, -17.0, "b"], [0.3238, -0.3339, -17.0, "b"], [0.3267, -0.3244, -17.0, "b"], [0.3296, -0.3148, -17.0, "b"], [0.3325, -0.3052, -17.0, "b"], [0.3355, -0.2957, -17.0, "b"], [0.3384, -0.2861, -17.0, "b"], [0.3413, -0.2766, -17.0, "b"], [0.3442, -0.267, -17.0, "b"], [0.3471, -0.2574, -17.0, "b"], [0.3501, -0.2479, -17.0, "b"], [0.353, -0.2383, -17.0, "b"], [0.3559, -0.2287, -17.0, "b"], [0.3588, -0.2192, -17.0, "b"], [0.3618, -0.2096, -17.0, "b"], [0.3647, -0.2, -17.0, "b"], [0.3676, -0.1905, -17.0, "b"], [0.3705, -0.1809, -17.0, "b"], [0.3735, -0.1714, -17.0, "b"], [0.3764, -0.1618, -17.0, "b"], [0.3793, -0.1522, -17.0, "b"], [0.3822, -0.1427, -17.0, "b"], [0.3852, -0.1331, -17.0, "b"], [0.3852, -0.1331, -16.0, "r"], [0.3852, -0.1331, -15.0, "r"], [0.3852, -0.1331, -14.0, "r"], [0.3852, -0.1331, -13.0, "r"], [0.3852, -0.1331, -12.0, "r"], [0.3852, -0.1331, -11.0, "r"], [0.3852, -0.1331, -10.0, "r"], [0.3869, -0.1233, -10.0, "b"], [0.3886, -0.1134, -10.0, "b"], [0.3904, -0.1036, -10.0, "b"], [0.3921, -0.0937, -10.0, "b"], [0.3938, -0.0839, -10.0, "b"], [0.3956, -0.074, -10.0, "b"], [0.3973, -0.0642, -10.0, "b"], [0.399, -0.0543, -10.0, "b"], [0.4008, -0.0445, -10.0, "b"], [0.4025, -0.0346, -10.0, "b"], [0.4043, -0.0248, -10.0, "b"], [0.406, -0.0149, -10.0, "b"], [0.4077, -0.0051, -10.0, "b"], [0.4095, 0.0048, -10.0, "b"], [0.4112, 0.0146, -10.0, "b"], [0.4129, 0.0245, -10.0, "b"], [0.4147, 0.0343, -10.0, "b"], [0.4164, 0.0442, -10.0, "b"], [0.4181, 0.054, -10.0, "b"], [0.4181, 0.054, -9.0, "r"], [0.4181, 0.054, -8.0, "r"], [0.4181, 0.054, -7.0, "r"], [0.4181, 0.054, -6.0, "r"], [0.4181, 0.054, -5.0, "r"], [0.4181, 0.054, -4.0, "r"], [0.4181, 0.054, -3.0, "r"], [0.4181, 0.054, -2.0, "r"], [0.4181, 0.054, -1.0, "r"], [0.4181, 0.054, 0.0, "r"]]}
```

#### geo/turn235.txt（依頼235）

```text
押す形（向き 180°）の左の肩と握り 0.398
すき間 0.10・寺島さん tz +0.0： 根を動かす 0.134 m（x +0.06・z -0.12）・体を回す 78°・左の肩と握り 0.429 m・顔（体から）-29.6°
すき間 0.10・寺島さん tz -0.1： 根を動かす 0.092 m（x +0.06・z -0.07）・体を回す 56°・左の肩と握り 0.430 m・顔（体から）-29.5°
すき間 0.10・寺島さん tz -0.2： 根を動かす 0.045 m（x +0.02・z -0.04）・体を回す 40°・左の肩と握り 0.430 m・顔（体から）-29.1°
すき間 0.10・寺島さん tz -0.3： 根を動かす 0.010 m（x +0.00・z -0.01）・体を回す 27°・左の肩と握り 0.430 m・顔（体から）-29.5°
すき間 0.10・寺島さん tz +0.1： 根を動かす 0.166 m（x +0.07・z -0.15）・体を回す 95°・左の肩と握り 0.429 m・顔（体から）-29.2°
すき間 0.10・寺島さん tz +0.2： 根を動かす 0.180 m（x +0.10・z -0.15）・体を回す 106°・左の肩と握り 0.429 m・顔（体から）-30.0°
すき間 0.10・寺島さん tz +0.3： 根を動かす 0.192 m（x +0.09・z -0.17）・体を回す 114°・左の肩と握り 0.430 m・顔（体から）-29.5°
すき間 0.15・寺島さん tz +0.0： 根を動かす 0.130 m（x +0.07・z -0.11）・体を回す 75°・左の肩と握り 0.429 m・顔（体から）-29.7°
すき間 0.15・寺島さん tz -0.1： 根を動かす 0.092 m（x +0.06・z -0.07）・体を回す 56°・左の肩と握り 0.430 m・顔（体から）-30.0°
すき間 0.15・寺島さん tz -0.2： 根を動かす 0.050 m（x +0.03・z -0.04）・体を回す 41°・左の肩と握り 0.430 m・顔（体から）-29.7°
すき間 0.15・寺島さん tz -0.3： 根を動かす 0.022 m（x +0.02・z -0.01）・体を回す 29°・左の肩と握り 0.430 m・顔（体から）-29.2°
すき間 0.15・寺島さん tz +0.1： 根を動かす 0.157 m（x +0.07・z -0.14）・体を回す 90°・左の肩と握り 0.429 m・顔（体から）-29.9°
すき間 0.15・寺島さん tz +0.2： 根を動かす 0.175 m（x +0.09・z -0.15）・体を回す 102°・左の肩と握り 0.430 m・顔（体から）-29.3°
すき間 0.15・寺島さん tz +0.3： 根を動かす 0.186 m（x +0.11・z -0.15）・体を回す 110°・左の肩と握り 0.429 m・顔（体から）-30.0°
```

### 依頼236

#### tools/Closeup236.cs（依頼236）

```csharp
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>
    /// 依頼236：Closeup234.cs を写して、出力の名前（-c236*・*236.csv など）だけ変えた。撮るもの（真上のコマ・232 の体の型・もの別の型）は 234 と同じ。
    /// 大城さんと車いす（茂さんを含む）を 1 つのものとして穴を埋めるのは make236.py で行う（もの別の型の緑と青を合わせる）。
    /// 以下は 234 の説明：
    /// 依頼234：232 の体の型に加えて、もの（ハコブくん／車いすと茂さん／大城さん）ごとに別々に白く写した型を撮る（Closeup232.cs を写して、写した先で変えた）。
    /// frames/yield_top_obj/f_*.png は 1 枚の色の型で、赤＝ハコブくんだけ・緑＝車いすと茂さんだけ・青＝大城さんだけを写したもの（3 回別々に撮るので、ほかのものに隠された所も入る）。
    /// make236.py が、ものごとに中の穴を埋めた外形にしてから床の線を消す。真上のコマと 232 と同じ型（frames/yield_top_mask）は 232 のまま撮る。
    /// 以下は 232 の説明：
    /// 依頼232：230 の真上の動画の床の線（中心・+0.28・+0.42・−0.33 の線と線の端の字）を、ハコブくん・大城さん・茂さん・車いすの下に描く。Closeup230.cs を写して、写した先で変えた。
    /// 動き・カメラ・真上のコマは 230 のまま。足したのは、真上のコマごとに「体だけを白く写した型」frames/yield_top_mask/f_*.png（黒＝床・白＝体）を撮ることだけ。
    /// 型は真上のカメラを写した別のカメラ（MaskCam232）で、体の部品だけを層 LayerMask232 に移し、白の Unlit/Color で写す（影・光は写らない）。写した後に層と材料を元に戻す。
    /// make232.py が床の線の層を、この型の白い所で消してから重ねる（線は床の上・体の下に見える）。
    /// 以下は 230 の説明：
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top236.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top236_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c236Views top）・静止画なし（-c236Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup236.Run \
    ///                 -c236Out <出力フォルダ> [-c236Script closeup229_script.json] [-c236Frames on|off] [-c236Stills on|off] [-c236Views main,top] [-c236From 秒] [-c236To 秒] [-c236Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames236.csv・bones236.csv・feet236.csv・wc236.csv・check236.txt・events236.txt
    /// </summary>
    public static class Closeup236
    {
        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 LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;   // 依頼232：体の型を写す間だけ体の部品を置く層

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c236Out", "");
            if (outDir == "") throw new Exception("-c236Out がない");
            string scriptName = CloseupArgs.Get("-c236Script", "closeup229_script.json");
            bool frames = CloseupArgs.Get("-c236Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c236Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c236Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c236From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c236To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk") talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.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;

                string shotName = "yield";
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c229"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                Texture2D bandTex = ScreenTex(TexDir + "/" + C["band"].S() + ".png");
                float bandOn = C["band_on"].F(), bandOff = C["band_off"].F(), happyFrom = C["happy_from"].F(), happyTo = C["happy_to"].F();
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                var SH = C["shift"]; float shT0 = SH["t0"].F(1e9f), shT1 = SH["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c236Until", "1e9"), IC)) * fps);
                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"); }   // 依頼232：_mask は体の型
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        if (mode == "stop" && stopped && behindN >= R.passBehind) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師
                    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;
                    chair.SetPositionAndRotation(nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead), nr.rotation);
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    bool bandNow = t >= bandOn - 1e-4f && t < bandOff - 1e-4f;
                    bool happyNow = t >= happyFrom - 1e-4f && t < happyTo - 1e-4f;
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", bandTex); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string fk = happyNow ? "happy" : 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 ? "帯" : "") + (happyNow ? "目まで笑う顔" : "基本") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.z);
                        Vector3 lr = toR.MultiplyPoint3x4(w);
                        float d = RobotDist(rs, lr, Mathf.Min(gap, 1.5f));
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    for (int s = 0; s < 2; s++)
                    {
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000"));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top236_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && inRange)
                    {
                        syncProxies(); scaleMouth();
                        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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            // 依頼232：体だけの型（同じ真上のカメラ・同じ大きさ）
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // 依頼234：もの別の型（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん）
                            var grp = new List<Renderer>[3]; for (int g = 0; g < 3; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[Group236(rd, dir.robot, chair, mor)].Add(rd);
                            if (!log.ToString().Contains("依頼234 もの別")) { log.AppendLine("依頼234 もの別の型の部品"); string[] gn = { "赤 ハコブくん", "緑 車いすと茂さん", "青 大城さん" }; for (int g = 0; g < 3; g++) { log.Append("  " + gn[g] + " " + grp[g].Count + "："); foreach (var rd in grp[g]) log.Append(" " + rd.name); log.AppendLine(); } }
                            var obj = new Texture2D(W, H, TextureFormat.RGB24, false);
                            var px = new Color32[W * H];
                            for (int g = 0; g < 3; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < px.Length; i++) { if (g == 0) px[i].r = mp[i].r; else if (g == 1) px[i].g = mp[i].r; else px[i].b = mp[i].r; px[i].a = 255; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(px); 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();
                        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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames236.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top236.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones236.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet236.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc236.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check236.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events236.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C236] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        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;
        }

        /// <summary>依頼234：部品がどのものか（0＝ハコブくん・1＝車いすと茂さん・2＝大城さん）。茂さんの写しの部品は名前が Morita_ で始まる</summary>
        static int Group236(Renderer rd, Transform robot, Transform chair, Transform mor)
        {
            var t = rd.transform;
            if (t.IsChildOf(robot)) return 0;
            if (t.IsChildOf(chair) || t.IsChildOf(mor) || rd.name.StartsWith("Morita_")) return 1;
            return 2;
        }

        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.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] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, 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);
        }
    }
}
```

#### tools/make236.py（依頼236）

```python
"""依頼236：make234.py を写して変えた。
・大城さんが握りに手をのせているコマ（frames236.csv の palm_grip_l_m・palm_grip_r_m が両方とも握った形の値 GRIP_D から 1 mm 以内）では、
  もの別の型の緑（車いすと茂さん）と青（大城さん）を合わせて 1 つのものとして「閉じる処理 → 中の穴埋め」をする（ハコブくんは別のまま）。
  手が離れているコマは 234 と同じくものごとに埋める。閉じる処理の半径は 6 画素（3.2 cm）のまま。描き方・重ねる順は 234 のまま。
・あわせて 234 の重ね方のコマも作り（<Unity の出力>/closeup236_as234.mp4。234 の動画と md5 が同じかを確かめるため）、
  外形の中に線が残らないこと・もののあいだで囲まれた床に見える線（234 は 400／770 コマ）・ふくらみ・体の無い所で 234 と違う画素を数える。
使い方: python3 make236.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ> [寄りの静止画のコマ:寄る物,…]
以下は 234 の説明：
依頼234：make232.py を写して変えた。
・もの別の型（Closeup234.cs が撮った frames/yield_top_obj：赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さんを別々に白く写したもの）を、
  ものごとに「数画素の閉じる処理（半径 RC 画素の円）→ 中の穴埋め」で中の穴とすき間を埋めた外形にし、232 の体の型と合わせた型で床の線の層を消す
  （体の部品が写っている所は 232 と同じなめらかなふち。埋めて足した所は線を全部消す）。
・重ねる順を、下から コマ（床・体）→ 床の線（体の所と埋めた所は消す）→ 通った跡 → 印と印の字 → 左上の字 にした（232 は 跡 → 線 の順）。
・あわせて 232 の重ね方のコマも作り（<Unity の出力>/closeup234_as232.mp4。232 の動画と md5 が同じかを確かめるため）、
  外形の中に線が残らないこと・232 で外形の中のすき間に線が見えていたコマ・ふくらみの最大・体の無い所で 232 と違う画素が重ねる順の所だけかを数える。
使い方: python3 make234.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ> [寄りの静止画のコマ:寄る物,…]   （閉じる処理の半径は環境変数 RC234、既定 6 画素）
以下は 232 の説明：
依頼232：make230.py を写して変えた。床の目印の線（中心・+0.28・+0.42・−0.33）と線の端の字の層を、Closeup232.cs が撮った体の型
（frames/yield_top_mask：白＝ハコブくん・大城さん・茂さん・車いす）の所で消してから重ねる（線は床の上・体の下に見える）。
通った跡・印・左上の字は 230 のまま（体の上に重ねる）。重ねる順も 230 のまま（コマ → 跡 → 線 → 印 → 左上の字）。
あわせて、型を使わない 230 の重ね方のコマも作り、型の外は 1 画素も違わないこと・型の所に線が残っていないことを数え、
230 の重ね方の動画（<Unity の出力>/closeup232_as230.mp4）も作る（230 の動画と md5 が同じかを確かめるため）。
使い方: python3 make232.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ> [寄りの静止画のコマ,…]
以下は 230 の説明：
依頼230：229 の真上のコマ（Closeup230.cs が動かない真上のカメラで撮った frames/yield_top）に、床の目印・通った跡・印・左上の字を重ねて
closeup230_yield_top.mp4（音なし）と静止画 3 枚を作り、確かめ（check230_top.txt）を書く。
目印・跡は Unity のカメラで写した位置（top230.csv の画面の位置・top230_cam.json の写し方）に 2 倍の大きさで描いて縮める。
時刻は動画の秒（台本の秒 − video_from）。
使い方: python3 make230.py <Unity の出力フォルダ> <台本> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, VD = sys.argv[1:4]
ZOOM = dict((int(x.split(":")[0]), x.split(":")[1]) for x in sys.argv[4].split(",")) if len(sys.argv) > 4 else {}   # 依頼232：寄りの静止画のコマ:寄る物（robot｜chair｜x,y）
ZOOM_F = list(ZOOM)
os.makedirs(VD, exist_ok=True)
C = json.load(open(SC))["shots"][0]["c229"]
CAM = json.load(open(os.path.join(D, "top236_cam.json")))
FPS, W, H, S = 30, 1920, 1080, 2          # S：描く倍率（2 倍で描いて縮める）
f0, f1 = int(round(C["video_from"] * FPS)), int(round(C["video_to"] * FPS))
n = f1 - f0 + 1
vt = lambda f: (f - f0) / FPS             # 動画の秒

# ---- 決めた値（1920×1080 の画面での px）
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {
    "center": (120, 120, 120),       # 廊下の中心の線（細い実線・灰色）
    "x028": (21, 101, 192),          # 車いすの始めの線 +0.28（破線・青）
    "x042": (142, 36, 170),          # 寄せたあとの線 +0.42（破線・紫）
    "lane": (46, 173, 107),          # ハコブくんのふだんの線 −0.33（破線・ハコブくんの輪の光に近い緑）
    "chair": (239, 108, 0),          # 車いすの通った跡（実線・橙）
    "robot": (0, 105, 92),           # ハコブくんの通った跡（実線・深い青緑）
}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16

# ---- 床の点 → 画面（Unity のカメラで写した 3 点から。正射影なので一次式）
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)   # (x, z)

rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames236.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top236.csv")))}
ev = open(os.path.join(D, "events236.txt"), encoding="utf-8").read()
t_trig = float(re.search(r"([\d.]+) 秒 決まりに当たった", ev).group(1))
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_sh0, t_sh1 = C["shift"]["t0"], C["shift"]["t1"]
# 印：(どれ, 台本の秒, 字の頭)。出す時刻 = その秒のコマ
MARKS = [("chair", t_sh0, "寄せ始め"), ("chair", t_sh1, "寄せ終わり"), ("robot", t_trig, "寄り始め"), ("robot", t_stop, "止まった")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]

def font(px): return ImageFont.truetype(FONT_PATH, px * S)
FL, FM, FH = font(LINE_LABEL_PX), font(MARK_LABEL_PX), font(HUD_PX)
def sc(p): return (p[0] * S, p[1] * S)

def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy
    bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)

def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1)
    L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L
    s = 0.0
    while s < L:
        e = min(L, s + DASH * S)
        d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S)
        s += (DASH + GAP) * S

def down(layer): return layer.resize((W, H), Image.LANCZOS)

# ---- 動かない層：中心の線・目印の線と字
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x028": 0.28, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x028", "x042", "lane"):
    dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
# 字：始め +0.28（線の上）と寄せたあと +0.42（線の下）は左の端（車いすが来るのは右の端なので、入ってくる所と寄せる所を隠さない）、ハコブくんのふだん −0.33 は右の端（ハコブくんが行かない側）
text_box(d, (sc((14, line_py["x028"] - 8))), "始め +0.28", FL, COL["x028"], "lb", edge=COL["x028"])
text_box(d, (sc((14, line_py["x042"] + 8))), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, (sc((W - 14, line_py["lane"] - 8))), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st)

# ---- 印の層（時刻になったら出す）。字は車いすの印は廊下の下、ハコブくんの印は廊下の上へ引き出す
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    nrob = 0
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (0 if head == "寄せ始め" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "止まった" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        text_box(d, sc((px, ly)), f"{head} {vt(mark_f[i]):.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)

# ---- 左上の字
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]
    cx = num_ok(r["chair_x"]); g = num_ok(r["gap_m"])
    return [f"{vt(f):.1f} 秒",
            "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None else "—")]


# ---- 依頼234：もの別の型から、中の穴とすき間を埋めた外形を作る（依頼236：大城さんが握りに手をのせている間は、車いすと茂さん＋大城さんを 1 つのものにする）
RC = int(os.environ.get("RC236", "6"))
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1))
PAD = RC + 24
OBJ = ["robot", "chair", "nurse"]          # 赤・緑・青
OBJ_JA = {"robot": "ハコブくん", "chair": "車いすと茂さん", "nurse": "大城さん", "group": "大城さんと車いす（茂さんを含む）"}
GRIP_D, GRIP_TOL = 0.0212, 0.001           # 依頼236：握った形の手のひらと握りの距離（228 の握り方の値）と、そこからの許し
def fill_obj(soft):
    """soft：1 つのものの型（0〜255）。返す：足した所（体の部品が写っていない所で外形の中・bool）と、ふくらみ（外形のふちの足した画素の、体からの距離の最大）・足した画素の距離の最大"""
    Hh, Ww = soft.shape
    ys, xs = np.nonzero(soft)
    added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added, 0.0, 0.0, 0, 0
    y0, y1 = max(0, ys.min() - PAD), min(Hh, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(Ww, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)          # 画面の外は床として扱う
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    ad = filled & ~b.astype(bool)
    if not ad.any(): return added, 0.0, 0.0, 0, 0
    dist = ndimage.distance_transform_edt(~b.astype(bool))                                 # 体の部品の写った画素からの距離（画素）
    rim = ad & ndimage.binary_dilation(~filled, structure=np.ones((3, 3), bool))           # 外形のふちにある足した画素（＝外へふくらんだ所）
    holes = ndimage.binary_fill_holes(b.astype(bool)) & ~b.astype(bool)                     # もとから閉じた穴
    added[y0:y1, x0:x1] = ad
    return added, float(dist[rim].max()) if rim.any() else 0.0, float(dist[ad].max()), int(holes.sum()), int(ad.sum())
def between(outl, SA):
    """外形どうしで囲まれた床（どの外形にも入らない所）に見える線の画素（between234.py と同じ数え方）"""
    return int((ndimage.binary_fill_holes(outl) & ~outl & SA).sum())

# ---- コマを作る
tmp = tempfile.mkdtemp(prefix="m236_", dir="/tmp"); tmp234 = tempfile.mkdtemp(prefix="m236as234_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}
shown = [False] * len(MARKS); mcache = mark_layer(shown)
chk = {"trail_err_m": {"chair": 0.0, "robot": 0.0}, "mark_first": [None] * len(MARKS), "hud_bad": 0, "hud_dash": {1: 0, 2: 0}, "hud_texts": []}
stills = {}; zooms = {}; per = []
bul = {o: [0.0, 0.0, -1] for o in OBJ + ["group"]}          # ふくらみの最大・足した画素の距離の最大・そのコマ
newd = {"rim": [0.0, -1], "to_chair": 0.0, "to_nurse": 0.0, "n_max": [0, -1]}   # 依頼236：1 つにして新しく足した所の、体からの距離
grip_frames = []
static_A = static.getchannel("A"); static_An = np.array(static_A); SA = static_An > 0
for k, f in enumerate(range(f0, f1 + 1)):
    r = top[f]
    for who, kx, ky, wx, wz in (("chair", "axle_px", "axle_py", "axle_x", "axle_z"), ("robot", "robot_px", "robot_py", "robot_x", "robot_z")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)   # 描く点（2 倍の画面の整数の点）
        bx, bz = from_px(*p)
        chk["trail_err_m"][who] = max(chk["trail_err_m"][who], math.hypot(bx - float(r[wx]), bz - float(r[wz])))
        if prev[who] is not None:
            td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2
        td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))   # 線のつなぎ目を丸く
        prev[who] = p
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True; chk["mark_first"][i] = vt(f)
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", "yield_top", f"f_{f:05d}.png")).convert("RGBA")
    mk = Image.open(os.path.join(D, "frames", "yield_top_mask", f"f_{f:05d}.png")).convert("L")   # 232 と同じ体の型
    ob = np.array(Image.open(os.path.join(D, "frames", "yield_top_obj", f"f_{f:05d}.png")).convert("RGB"))   # 依頼234：もの別の型
    mkn = np.array(mk)
    # 234 の埋め方（ものごと）
    add234 = np.zeros((H, W), bool); nadd = {}; outl234 = mkn > 0
    for c, o in enumerate(OBJ):
        ad, bmax, dmax, nh, na = fill_obj(ob[:, :, c])
        add234 |= ad; nadd[o] = na
        outl234 |= ad | (ob[:, :, c] > 0)
        if bmax > bul[o][0]: bul[o][0] = bmax; bul[o][2] = f
        bul[o][1] = max(bul[o][1], dmax)
    # 依頼236：握りに手をのせている間は 緑＋青 を 1 つのものにする
    fr = rows[f]
    grip = abs(float(fr["palm_grip_l_m"]) - GRIP_D) <= GRIP_TOL and abs(float(fr["palm_grip_r_m"]) - GRIP_D) <= GRIP_TOL
    if grip:
        grip_frames.append(f)
        gb = np.maximum(ob[:, :, 1], ob[:, :, 2])
        adg, bmax, dmax, nh, nag = fill_obj(gb)
        if bmax > bul["group"][0]: bul["group"][0] = bmax; bul["group"][2] = f
        bul["group"][1] = max(bul["group"][1], dmax)
        adr = fill_obj(ob[:, :, 0])[0]
        add_any = adr | adg | add234                                      # 234 の足した所も残す（236 の外形 ⊇ 234 の外形）
        nadd["group"] = nag
        # 1 つにして新しく足した所（234 の足した所の外・体の部品の外）
        new = adg & ~add234 & ~(gb > 0)
        if new.any():
            dg = ndimage.distance_transform_edt(ob[:, :, 1] == 0); dn = ndimage.distance_transform_edt(ob[:, :, 2] == 0); db = np.minimum(dg, dn)
            outl_g = adg | (gb > 0)
            rim = new & ndimage.binary_dilation(~outl_g, structure=np.ones((3, 3), bool))
            if rim.any() and db[rim].max() > newd["rim"][0]: newd["rim"] = [float(db[rim].max()), f]
            newd["to_chair"] = max(newd["to_chair"], float(dg[new].max())); newd["to_nurse"] = max(newd["to_nurse"], float(dn[new].max()))
        nnew = int(new.sum())
        if nnew > newd["n_max"][0]: newd["n_max"] = [nnew, f]
    else:
        add_any = add234; nnew = 0; nadd["group"] = 0
    outl236 = (mkn > 0) | add_any | (ob.max(axis=2) > 0)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))      # 外形の型：体の所は 232 の型・足した所は 255
    F234n = np.maximum(mkn, np.where(add234, 255, 0).astype(np.uint8))     # 234 の外形の型
    F = Image.fromarray(Fn, "L"); F234 = Image.fromarray(F234n, "L")
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(F)))         # 236：外形の所で線を消す
    st_234 = static.copy(); st_234.putalpha(ImageChops.multiply(static_A, ImageChops.invert(F234)))  # 234 の重ね方
    trail_d = down(trail)
    lines = hud_lines(f)
    for i in (1, 2):
        if lines[i].endswith("—"): chk["hud_dash"][i] += 1
    if any(re.search(r"\d{5,}|nan|inf", s, re.I) for s in lines): chk["hud_bad"] += 1
    if k % 30 == 0: chk["hud_texts"].append(" / ".join(lines))
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl)
    x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    hl_d = down(hl)
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(trail_d); im.alpha_composite(mcache); im.alpha_composite(hl_d)            # 234 と同じ順：床の線 → 跡 → 印 → 左上の字
    im234 = raw.copy(); im234.alpha_composite(st_234); im234.alpha_composite(trail_d); im234.alpha_composite(mcache); im234.alpha_composite(hl_d)
    out = im.convert("RGB"); out.save(os.path.join(tmp, f"v_{k:05d}.png"))
    o234 = im234.convert("RGB"); o234.save(os.path.join(tmp234, f"v_{k:05d}.png"))
    # 依頼236 の確かめ
    stA = np.array(st_m.getchannel("A")); s4A = np.array(st_234.getchannel("A"))
    grp_in = np.zeros((H, W), bool)
    if grip: grp_in = ((ob[:, :, 1] > 0) | (ob[:, :, 2] > 0) | adg) & (Fn == 255)        # 大城さんと車いすをまとめた外形の中（型 255）
    left = int(((stA > 0) & (Fn == 255)).sum())                        # 外形の中（全部のもの）に残る線の画素
    left_grp = int(((stA > 0) & grp_in).sum())                         # 大城さんと車いすをまとめた外形の中に残る線の画素
    rim_left = int(((stA > 0) & (Fn > 0) & (Fn < 255)).sum())          # 体のふちのなめらかな所に薄く残る線（232・234 と同じ扱い）
    btw234 = between(outl234, SA); btw236 = between(outl236, SA)       # もののあいだで囲まれた床に見える線（234 の数え方）
    vis234_new = int(((s4A > 0) & add_any & ~add234).sum())            # 234 で、236 が新しく埋めた所に見えていた線
    dif = np.any(np.array(out) != np.array(o234), axis=2)
    n_out = int((dif & (Fn == 0)).sum())                               # 体の無い所（236 の型 0）で 234 と違う画素
    n_out234 = int((dif & (F234n == 0) & ~add_any).sum())              # 234 の型 0 で、236 が埋めた所の外で違う画素
    more = int((stA > s4A).sum())                                      # 236 の方が 234 より線が濃い画素（0 のはず）
    per.append((f, int(grip), left, left_grp, rim_left, btw234, btw236, vis234_new, n_out, n_out234, int(dif.sum()), more, nnew, nadd["robot"], nadd["chair"], nadd["nurse"], nadd["group"]))
    if f in ZOOM_F: zooms[f] = (out.copy(), o234.copy())
    for name, ff in (("s1_shift_start", mark_f[0]), ("s2_shift_end", mark_f[1]), ("s3_last", f1)):
        if f == ff: stills[name] = out.copy()
vid = os.path.join(VD, "closeup236_yield_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vid], check=True)
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp234, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", os.path.join(D, "closeup236_as234.mp4")], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for name, im in stills.items(): im.save(os.path.join(sd, name + ".png"))

# ---- 確かめ
o = []
o.append(f"コマ {n}（{f0}〜{f1}）・動画 {n / FPS:.3f} 秒")
o.append(f"写し方：画面の点 = ({ox:.4f}, {oy:.4f}) + x×({xx:.4f}, {xy:.4f}) + z×({zx:.4f}, {zy:.4f}) px（1 m = {math.hypot(zx, zy):.3f} px・1 px = {1000 / math.hypot(zx, zy):.2f} mm）")
for (who, t, head), fv in zip(MARKS, chk["mark_first"]):
    o.append(f"印 {who} {head}：台本 {t:.4f} 秒（動画 {t - C['video_from']:.3f} 秒）→ 出たコマの動画の秒 {fv:.3f}")
o.append(f"左上の字：壊れた値のコマ {chk['hud_bad']}・車いすの横の位置が「—」のコマ {chk['hud_dash'][1]}・すき間が「—」のコマ {chk['hud_dash'][2]}")
PXCM = 100 / math.hypot(zx, zy)
gl = [float(rows[f]["palm_grip_l_m"]) for f in range(f0, f1 + 1)]; gr = [float(rows[f]["palm_grip_r_m"]) for f in range(f0, f1 + 1)]
o.append(f"依頼236 握りに手をのせているコマ（両手の手のひらと握りの距離が {GRIP_D} m から {GRIP_TOL * 1000:.0f} mm 以内）：{len(grip_frames)}／{n}（左 {min(gl):.4f}〜{max(gl):.4f} m・右 {min(gr):.4f}〜{max(gr):.4f} m）")
o.append(f"依頼236 閉じる処理の半径 {RC} 画素（{RC * PXCM:.2f} cm）→ 中の穴埋め。もの：赤 ハコブくん・緑＋青 大城さんと車いす（茂さんを含む。握っている間）")
o.append(f"依頼236 大城さんと車いすをまとめた外形の中（型 255）に残る線の画素：合計 {sum(p[3] for p in per)}・1 コマの最大 {max(p[3] for p in per)}")
o.append(f"依頼236 外形の中（全部のもの・型 255）に残る線の画素：合計 {sum(p[2] for p in per)}・1 コマの最大 {max(p[2] for p in per)}")
mb4 = max(per, key=lambda p: p[5]); mb6 = max(per, key=lambda p: p[6])
o.append(f"依頼236 もののあいだで囲まれた床に見える線：234 の埋め方 {sum(1 for p in per if p[5] > 0)}／{n} コマ（合計 {sum(p[5] for p in per)}・1 コマの最大 {mb4[5]}・動画 {vt(mb4[0]):.3f} 秒）→ 236 {sum(1 for p in per if p[6] > 0)}／{n} コマ（合計 {sum(p[6] for p in per)}・1 コマの最大 {mb6[6]}）")
o.append(f"依頼236 234 の動画で、236 が新しく埋めた所に見えていた線：{sum(1 for p in per if p[7] > 0)}／{n} コマ（合計 {sum(p[7] for p in per)}・1 コマの最大 {max(p[7] for p in per)}）")
o.append(f"依頼236 体のふちのなめらかな所（0<型<255）に薄く残る線の画素（232・234 と同じ扱い）：1 コマの最大 {max(p[4] for p in per)}")
for ob_ in OBJ + ["group"]:
    bm, dm, bf = bul[ob_]
    which = "234 の埋め方" if ob_ != "group" else "236 の 1 つにした埋め方"
    o.append(f"依頼236 ふくらみ {OBJ_JA[ob_]}（{which}）：外形のふちの足した画素の体からの距離の最大 {bm:.2f} 画素（{bm * PXCM:.2f} cm・コマ {bf}）・足した画素（中の穴を含む）の体からの距離の最大 {dm:.2f} 画素（{dm * PXCM:.2f} cm）")
o.append(f"依頼236 1 つにして新しく足した所：1 コマの最大 {newd['n_max'][0]} 画素（コマ {newd['n_max'][1]}）・そのうち外形のふちにある画素の体からの距離の最大 {newd['rim'][0]:.2f} 画素（{newd['rim'][0] * PXCM:.2f} cm・コマ {newd['rim'][1]}）・車いすと茂さんからの距離の最大 {newd['to_chair']:.2f} 画素（{newd['to_chair'] * PXCM:.2f} cm）・大城さんからの距離の最大 {newd['to_nurse']:.2f} 画素（{newd['to_nurse'] * PXCM:.2f} cm）")
o.append(f"依頼236 体の無い所（236 の型 0）で 234 の重ね方と違う画素：合計 {sum(p[8] for p in per)}・1 コマの最大 {max(p[8] for p in per)}")
o.append(f"依頼236 234 の型 0 で 236 が埋めた所の外の、234 と違う画素：合計 {sum(p[9] for p in per)}・画面全体で違う画素の合計 {sum(p[10] for p in per)}（違うコマ {sum(1 for p in per if p[10] > 0)}）")
o.append(f"依頼236 236 の方が 234 より床の線が濃い画素：合計 {sum(p[11] for p in per)}・1 コマの最大 {max(p[11] for p in per)}")
open(os.path.join(D, "per236.csv"), "w").write("frame,grip,line_left_inside_all,line_left_inside_group,line_rim_soft,between_line_234,between_line_236,line_234_in_new_fill,diff_outside_vs234,diff_outside234_not_newfill,diff_all,line_more_than_234,new_added,added_robot,added_chair,added_nurse,added_group\n" + "".join(",".join(str(v) for v in p) + "\n" for p in per))
# 寄りの静止画（234 と同じ範囲を 2.5 倍に寄せ、上に 234・下に 236）
zd = os.path.join(VD, "stills_zoom"); os.makedirs(zd, exist_ok=True)
for f, (a, b) in sorted(zooms.items()):
    r = top[f]; who = ZOOM[f]
    if who == "robot": cx, cy = float(r["robot_px"]), float(r["robot_py"])
    elif who == "chair": cx, cy = float(r["axle_px"]), float(r["axle_py"])
    else: cx, cy = map(float, who.split("/"))
    cx, cy = int(round(cx)), int(round(cy)); bw, bh = 480, 270
    x0 = min(max(0, cx - bw // 2), W - bw); y0 = min(max(0, cy - bh // 2), H - bh)
    box = (x0, y0, x0 + bw, y0 + bh); zw = 1200; zh = zw * bh // bw
    pane = Image.new("RGB", (zw, zh * 2 + 60), (255, 255, 255)); pd = ImageDraw.Draw(pane)
    pane.paste(b.crop(box).resize((zw, zh), Image.NEAREST), (0, 30)); pane.paste(a.crop(box).resize((zw, zh), Image.NEAREST), (0, zh + 60))
    fz = ImageFont.truetype(FONT_PATH, 24)
    pd.text((8, 2), f"234（ものごとに埋める）動画 {vt(f):.3f} 秒・画面 x {box[0]}〜{box[2]}・y {box[1]}〜{box[3]}", font=fz, fill=(0, 0, 0))
    pd.text((8, zh + 32), f"236（大城さんと車いすを 1 つのものとして埋める）", font=fz, fill=(0, 0, 0))
    nm = f"z_{vt(f):06.3f}s_f{f}.png"; pane.save(os.path.join(zd, nm))
    p = per[f - f0]
    o.append(f"寄りの静止画 {nm}（{who}）：範囲 {box}・このコマで 234 のもののあいだに見えていた線 {p[5]}（画面全体）・236 で {p[6]}・まとめた外形の中に残る線 {p[3]}")
open(os.path.join(D, "check236_top.txt"), "w", encoding="utf-8").write("\n".join(o) + "\n")
print("\n".join(o)); print("動画", vid)
```

#### tools/run236.sh（依頼236）

```bash
#!/bin/bash
# 依頼236 使い方: run236.sh <出力フォルダ> <コマ on|off> [views] [until]
OUT="$1"; FR="${2:-off}"; VW="${3:-top}"; UNTIL="${4:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup236.Run \
   -c236Out "$OUT" -c236Frames "$FR" -c236Stills off -c236Script closeup229_script.json -c236Views "$VW" -c236Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

### 依頼237

#### tools/Closeup237.cs.copy（依頼237）

```csharp
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>
    /// 依頼237：⑨（235）のやり取りを 2 本で分けて作り直した。Closeup235.cs を写して、写した先で変えた。台本は closeup237_script.json（make_script237.py）。場面の名前は 235 と同じ stop_voice・stop_stuck（まばたきの種が同じになる）。
    /// 235 から変えたこと：
    ///   ・画面の stuck：帯（黄）「通れません」だけの絵 c237_stuck_band.png を重ね、顔の板は困り顔 face237_trouble（ふだんの大きさ。ほかの帯の時と同じ顔の板）
    ///   ・画面は台本の c237.screen の時刻のとおり（happy・face も台本から）。235 の「走り出したら目まで笑う顔 1.5 秒」はやめた（走り出しの時刻は 1 回目の Unity の値を台本に入れる）
    ///   ・目まで笑う顔は 224 と同じ（face224_happy_<口>。ハコブくんが話す間も口が動く）
    ///   ・ハコブくんが車いすの横にいる間（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）の時刻を events237.txt と check237.txt に書く
    /// 以下は 235 の説明：
    /// 依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）。場面 stop_voice（⑨-1）・stop_stuck（⑨-2）。Closeup234.cs を写して、写した先で変えた。台本は closeup237_script.json（make_script235.py）。
    /// 234 から変えたこと：
    ///   ・寺島さん（Models_terashima/NurseTerashima.prefab）を置き、2 つめの CloseupDirector で台本の場面 <場面>__tera を動かす（部品の名前 Terashima_ を Nurse_ に替えて CloseupNurse を付ける。共通の部品は変えない）
    ///   ・車いすの根の位置・向きは台本の c235.chair（毎コマ）。両手で握っている間は大城さんの根の前に固く付いた値、立ち話の間は止めた所
    ///   ・ハコブくんの決まりに足した：止まった後、前の物（車いす・茂さん・大城さん・寺島さん）が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す。
    ///     寄った位置（x −0.4643）のまま通り、物の一番後ろを通り過ぎてから x −0.33 へ戻る（依頼235 の答え 3）
    ///   ・画面：c235.screen（face・wait・deliv・pass・stuck・happy）。輪：c235.ring の wait の間は待つ色（203 と同じ作り）
    ///   ・真上のもの別の型 frames/<場面>_top_obj は RGBA（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん・アルファ＝寺島さん）
    ///   ・確かめを足した：寄せる道（向き・速さ・向きの変わる速さ・前へ／後ろへ・足のせとハコブくん・車輪の横すべり）、大城さんの体と顔の向き・握りをはなした／握り直した時刻、
    ///     ハコブくんが通る時の車いす・大城さん・寺島さんとのすき間の最小、寺島さんの当たり
    /// 以下は 234 の説明：
    /// 依頼234：232 の体の型に加えて、もの（ハコブくん／車いすと茂さん／大城さん）ごとに別々に白く写した型を撮る（Closeup232.cs を写して、写した先で変えた）。
    /// frames/yield_top_obj/f_*.png は 1 枚の色の型で、赤＝ハコブくんだけ・緑＝車いすと茂さんだけ・青＝大城さんだけを写したもの（3 回別々に撮るので、ほかのものに隠された所も入る）。
    /// make234.py が、ものごとに中の穴を埋めた外形にしてから床の線を消す。真上のコマと 232 と同じ型（frames/yield_top_mask）は 232 のまま撮る。
    /// 以下は 232 の説明：
    /// 依頼232：230 の真上の動画の床の線（中心・+0.28・+0.42・−0.33 の線と線の端の字）を、ハコブくん・大城さん・茂さん・車いすの下に描く。Closeup230.cs を写して、写した先で変えた。
    /// 動き・カメラ・真上のコマは 230 のまま。足したのは、真上のコマごとに「体だけを白く写した型」frames/yield_top_mask/f_*.png（黒＝床・白＝体）を撮ることだけ。
    /// 型は真上のカメラを写した別のカメラ（MaskCam232）で、体の部品だけを層 LayerMask232 に移し、白の Unlit/Color で写す（影・光は写らない）。写した後に層と材料を元に戻す。
    /// make232.py が床の線の層を、この型の白い所で消してから重ねる（線は床の上・体の下に見える）。
    /// 以下は 230 の説明：
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top237.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top237_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c237Views top）・静止画なし（-c237Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup237.Run \
    ///                 -c237Out <出力フォルダ> [-c237Script closeup229_script.json] [-c237Frames on|off] [-c237Stills on|off] [-c237Views main,top] [-c237From 秒] [-c237To 秒] [-c237Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames237.csv・bones237.csv・feet237.csv・wc237.csv・check237.txt・events237.txt
    /// </summary>
    public static class Closeup237
    {
        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 LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;   // 依頼232：体の型を写す間だけ体の部品を置く層

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c237Out", "");
            if (outDir == "") throw new Exception("-c237Out がない");
            string scriptName = CloseupArgs.Get("-c237Script", "closeup237_script.json");
            string shotArg = CloseupArgs.Get("-c237Shot", "stop_voice");
            bool frames = CloseupArgs.Get("-c237Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c237Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c237Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c237From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c237To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk" && kv.Key.transform.IsChildOf(dir.nurse.transform)) talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // ---- 依頼235：寺島さん（2 つめの CloseupDirector で動かす。部品の名前 Terashima_ → Nurse_）
                var teraGo = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(Closeup231Terashima.Prefab));
                teraGo.name = "Terashima235";
                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>();
                teraN.Init();
                var dir2 = new GameObject("Director235Tera").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(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var anT = teraN.Anim;
                var partsT = new List<SkinnedMeshRenderer>();
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) partsT.Add(smr);
                var proxyRootT = new GameObject("Baked235Tera").transform;
                int nProxyO = proxies.Count;
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                {
                    var g = new GameObject(smr.name + "_BakedT"); g.transform.SetParent(proxyRootT, 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));
                }
                log.AppendLine("寺島さん：部品 " + partsT.Count + "（体）・写し " + (proxies.Count - nProxyO) + "・骨の Animator " + (anT != null ? anT.isHuman.ToString() : "なし"));
                MeshFilter talkProxyT = null;
                for (int i = nProxyO; i < proxies.Count; i++) if (proxies[i].Key.name == "Nurse_Mouth_talk") talkProxyT = proxies[i].Value;
                if (talkProxyT == null) throw new Exception("寺島さんの口の部品 Nurse_Mouth_talk が無い");
                float curMouthScaleT = 1f;
                Action scaleMouthT = () =>
                {
                    if (!talkProxyT.gameObject.activeSelf || Mathf.Abs(curMouthScaleT - 1f) < 1e-4f) return;
                    var mesh = talkProxyT.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = teraN.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxyT.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 - curMouthScaleT)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.png");
                }
                // 依頼237：目まで笑う顔は 224 と同じ（口の段階ごと）・困り顔（ふだんの大きさ）
                faceAlb["happy_closed"] = faceAlb["happy"]; faceEmi["happy_closed"] = faceEmi["happy"];     // 224 と同じ：閉じた口は face218_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", "");
                }
                faceAlb["trouble"] = PrepTex(TexDir + "/face237_trouble_albedo.png", ""); faceEmi["trouble"] = PrepTex(TexDir + "/face237_trouble_emission.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;

                string shotName = shotArg;
                dir2.BeginShot(shotName + "__tera");
                anT.Rebind();
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c237"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                var scrTex = new Dictionary<string, Texture2D> { { "wait", ScreenTex(TexDir + "/c235_wait_band.png") }, { "deliv", ScreenTex(TexDir + "/c235_deliv_band.png") },
                                                                 { "pass", ScreenTex(TexDir + "/c235_pass_band.png") }, { "stuck", ScreenTex(TexDir + "/c237_stuck_band.png") } };   // 依頼237：帯だけ
                var scrKeys = C["screen"]; var ringKeys = C["ring"];
                var chairKeys = C["chair"]; var gripBoth = C["grip_both"]; var teraMouth = C["tera_mouth"];
                var ringR = dir.ring.GetComponent<MeshRenderer>(); var ringOrig = ringR.sharedMaterial;
                Color rwc; ColorUtility.TryParseHtmlString(C["ring_wait_color"].S("#F2C230"), out rwc);
                var ringWait = new Material(Shader.Find("Standard")) { name = "C235_ring_wait" };
                ringWait.color = rwc; ringWait.SetFloat("_Glossiness", 0.3f); ringWait.EnableKeyword("_EMISSION"); ringWait.SetColor("_EmissionColor", rwc * 0.9f);
                ringWait.globalIlluminationFlags = MaterialGlobalIlluminationFlags.None;
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                float shT0 = C["man"]["t0"].F(1e9f), shT1 = C["man"]["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                float stillS = js["robot_rule"]["resume_still_s"].F(0.5f), stillV = js["robot_rule"]["still_mps"].F(0.005f);
                float lastMoveT = 0f, resumeGapWall = float.NaN, passedT = -1f; bool passedAll = false;
                Vector3 pvC = Vector3.zero, pvO = Vector3.zero, pvT = Vector3.zero; float pvCy = 0f, pvOy = 0f, pvTy = 0f;
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                // 依頼235
                var ncTimes = new List<string>();
                float rigidErr = 0f; int hitTS = 0, hitTO = 0, hitTC = 0; string hitTWhere = "";
                var passMin = new Dictionary<string, float> { { "車いす", float.MaxValue }, { "茂さん", float.MaxValue }, { "看護師", float.MaxValue }, { "寺島さん", float.MaxValue } };
                var passMinT = new Dictionary<string, float> { { "車いす", -1f }, { "茂さん", -1f }, { "看護師", -1f }, { "寺島さん", -1f } };
                float manYawMax = 0f, manV = 0f, manVT = -1f, manW = 0f, manWT = -1f, manFwd = 0f, manBack = 0f, footRobotMin = float.MaxValue, footRobotMinT = -1f, axZ0 = float.NaN;
                float oBodyRelMax = 0f, oBodyRelMaxT = -1f, oHeadMaxTalk = 0f, oHeadMaxTalkT = -1f, oLookTeraMin = 180f, relT = -1f, regripT = -1f; bool prevGripR = true;
                float tHeadMax = 0f, tHeadMaxT = -1f; Vector3 prevAxle = Vector3.zero; float prevCy = 0f; bool havePA = false;
                float teraZ0 = float.NaN, teraX0 = float.NaN, teraRetDist = 0f, teraRetT0 = -1f, teraRetT1 = -1f; Vector3 prevTera = Vector3.zero;
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float besideT0 = -1f, besideT1 = -1f;   // 依頼237
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c237Until", "1e9"), IC)) * fps);
                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"); }   // 依頼232：_mask は体の型
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw,m_to_robot_deg,foot_front_m,behind_oshiro_m\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    if (f > 0 && f % 150 == 0) GC.Collect();   // 依頼235：長い場面でメモリが増えないように
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        // 依頼235：止まった後、前の物が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す
                        if (mode == "stop" && stopped && t - lastMoveT >= stillS - 1e-4f && gapWall >= R.gapStop) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; resumeGapWall = gapWall;
                            log.AppendLine(string.Format(IC, "  {0:0.000} 秒 走り出す：前の物が {1:0.000} 秒動いていない・寄った位置のすき間 {2:0.000} m", t, t - lastMoveT, gapWall)); }
                        if ((mode == "resume" || mode == "cruise2") && !passedAll && rearZ - o.farZ >= 0f) { passedAll = true; passedT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 物の一番後ろを通り過ぎた → x {1:0.000} へ戻る", t, R.laneX)); }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && passedAll && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if ((mode == "resume" || mode == "cruise2") && !passedAll) StepLat(ref rx, ref ryaw, xWall, rv, R.resumeAngle, R, dt, xWall);   // 依頼235：通り過ぎるまで寄った位置のまま
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師（依頼235：寺島さんを先に。大城さんの 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;
                    {
                        // 依頼235：車いすの根は台本の c235.chair（両手で握っている間は大城さんの根の前に固く付いた値と同じ）
                        var ck = chairKeys[Mathf.Min(f, chairKeys.Count - 1)];
                        chair.SetPositionAndRotation(O + new Vector3(ck[0].F(), 0f, ck[1].F()), Quaternion.Euler(0f, ck[2].F(), 0f));
                        bool gb = gripBoth[Mathf.Min(f, gripBoth.Count - 1)].I() == 1;
                        if (gb) { float dRig = Vector3.Distance(chair.position, nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead)) + Mathf.Abs(Mathf.DeltaAngle(chair.eulerAngles.y, nr.eulerAngles.y)) * 0.01f; rigidErr = Mathf.Max(rigidErr, dRig); }
                    }
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼235：前の物が動いたか（車いす・大城さん・寺島さんの根と向き）
                    {
                        Vector3 pc = chair.position, po = nr.position, pt = teraN.transform.position; float yc = chair.eulerAngles.y, yo = nr.eulerAngles.y, yt = teraN.transform.eulerAngles.y;
                        if (f > 0)
                        {
                            float mvm = Mathf.Max(Vector3.Distance(pc, pvC), Mathf.Max(Vector3.Distance(po, pvO), Vector3.Distance(pt, pvT))) / dt;
                            float mva = Mathf.Max(Mathf.Abs(Mathf.DeltaAngle(yc, pvCy)), Mathf.Max(Mathf.Abs(Mathf.DeltaAngle(yo, pvOy)), Mathf.Abs(Mathf.DeltaAngle(yt, pvTy)))) / dt;
                            if (mvm > stillV || mva > 0.5f) lastMoveT = t;
                        }
                        pvC = pc; pvO = po; pvT = pt; pvCy = yc; pvOy = yo; pvTy = yt;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    { var ml = C["morita_mouth_lvl"]; if (f < ml.Count && ml[f].I() > 0) mMouth = "talk"; }     // 依頼235：茂さんが話す間は talk
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    // 依頼237：画面は台本の時刻のとおり（235 の走り出しの目まで笑う顔はやめた）
                    string sk = "face"; for (int k = 0; k < scrKeys.Count; k++) if (scrKeys[k][0].F() <= t + 1e-4f) sk = scrKeys[k][1].S();
                    bool bandNow = scrTex.ContainsKey(sk);
                    bool happyNow = sk == "happy";
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", scrTex[sk]); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string rk = "normal"; for (int k = 0; k < ringKeys.Count; k++) { string v = ringKeys[k][1].S(); if (v == "normal" && k > 0) continue; if (ringKeys[k][0].F() <= t + 1e-4f) rk = v; }
                    if (resumeT >= 0f) rk = "normal";
                    ringR.sharedMaterial = rk == "wait" ? ringWait : ringOrig;
                    string fk = happyNow ? "happy_" + rmo : sk == "stuck" ? "trouble" : rmo != "mid" ? rmo : "";     // 依頼237：224 の目まで笑う顔・通れませんは困り顔
                    { var mpf = new MaterialPropertyBlock(); if (fk != "") { mpf.SetTexture("_MainTex", faceAlb[fk]); mpf.SetTexture("_EmissionMap", faceEmi[fk]); } faceR.SetPropertyBlock(mpf); }
                    string scrNow = (bandNow ? "絵" + sk : "") + (happyNow ? "目まで笑う顔" : sk == "stuck" ? "困り顔" : "基本") + (rk == "wait" ? "＋輪の待つ色" : "") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    var passNow = new Dictionary<string, float> { { "車いす", float.MaxValue }, { "茂さん", float.MaxValue }, { "看護師", float.MaxValue }, { "寺島さん", float.MaxValue } };
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.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;   // 依頼235：1.5 m より遠い点は数えない（速くするため。1.5 m より近い値は同じ）
                        string cat0 = who.Substring(0, Math.Max(0, who.IndexOf(' ')));
                        float cutW = passNow.ContainsKey(cat0) ? Mathf.Min(passNow[cat0], 1.5f) : Mathf.Min(gap, 1.5f);
                        float d = RobotDist(rs, lr, Mathf.Max(cutW, Mathf.Min(gap, 1.5f)));
                        if (passNow.ContainsKey(cat0) && d < passNow[cat0]) passNow[cat0] = d;
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 依頼235：寺島さんの頂点（見る・壁/手すり・大城さん・車いす）
                    {
                        bool tsHit = false, toHit = false, tcHit = false;
                        foreach (var smr in partsT)
                        {
                            smr.BakeMesh(baked, true);
                            Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                            var vs = baked.vertices;
                            for (int i = 0; i < vs.Length; i += 2)
                            {
                                Vector3 w = m.MultiplyPoint3x4(vs[i]);
                                seeVert(w, "寺島さん " + smr.name);
                                foreach (var s2 in solids)
                                {
                                    if (w.x < s2.min.x - 0.1f || w.x > s2.max.x + 0.1f || w.z < s2.min.z - 0.1f || w.z > s2.max.z + 0.1f) continue;
                                    if (InBox(w, s2.min, s2.max)) { tsHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→" + s2.name; }
                                }
                                if (Physics.CheckSphere(w, 0.003f, 1 << LayerNurse)) { toHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→大城さん"; }
                                if (Physics.CheckSphere(w, 0.003f, 1 << LayerChair)) { tcHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→車いす"; }
                            }
                        }
                        if (tsHit) hitTS++; if (toHit) hitTO++; if (tcHit) hitTC++;
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (ncHit && ncTimes.Count < 80) ncTimes.Add(F(t, "0.000"));
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (resumeT >= 0f) foreach (var kc in new List<string>(passNow.Keys)) if (passNow[kc] < passMin[kc]) { passMin[kc] = passNow[kc]; passMinT[kc] = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    bool gbNow = gripBoth[Mathf.Min(f, gripBoth.Count - 1)].I() == 1;
                    {
                        // 依頼235：右手を握りからはなした時刻・握り直した時刻（右手の重み）
                        float wR = dir.nurse.hands[1].weight;
                        if (prevGripR && wR < 0.999f && relT < 0f) relT = t;
                        if (!prevGripR && wR >= 0.999f && regripT < 0f) regripT = t;
                        prevGripR = wR >= 0.999f;
                    }
                    for (int s = 0; s < 2; s++)
                    {
                        if (s == 1 && !gbNow) continue;     // 依頼235：右手をはなしている間は数えない
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 依頼235：寄せる道・体と顔の向き・寺島さん
                    float frNow = float.NaN;
                    {
                        Vector3 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        float cy = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (float.IsNaN(axZ0) && t >= shT0 - 1e-4f) axZ0 = axle.z;
                        if (t >= shT0 - 1e-4f && t <= shT1 + 0.5f)
                        {
                            manYawMax = Mathf.Max(manYawMax, Mathf.Abs(cy));
                            if (havePA) { float v1 = Vector3.Distance(axle, prevAxle) / dt, w1 = Mathf.Abs(Mathf.DeltaAngle(cy, prevCy)) / dt; if (v1 > manV) { manV = v1; manVT = t; } if (w1 > manW) { manW = w1; manWT = t; } }
                            manFwd = Mathf.Max(manFwd, axZ0 - axle.z); manBack = Mathf.Max(manBack, axle.z - axZ0);
                        }
                        prevAxle = axle; prevCy = cy; havePA = true;
                        // 足のせの前の端（車いすの頂点で一番 −z）とハコブくんの前の端
                        float fz = float.MaxValue; Matrix4x4 cw2 = chair.localToWorldMatrix; foreach (var v in chairVertsLocal) if (v.z > 0.5f) fz = Mathf.Min(fz, cw2.MultiplyPoint3x4(v).z);
                        float fr = fz - (rz + rs.maxZ + O.z); frNow = fr;
                        if (stopped && resumeT < 0f && fr < footRobotMin) { footRobotMin = fr; footRobotMinT = t; }
                        // 依頼237：ハコブくんが車いすの横にいる間（走り出した後、前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）
                        if (resumeT >= 0f && besideT0 < 0f && fr <= 0f) { besideT0 = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんの前の端が足のせの前の端を過ぎた（横にいる間の始まり）", t)); }
                        if (besideT0 >= 0f && besideT1 < 0f && (rz + rs.minZ) - ob.nurseFarZ >= 0f) { besideT1 = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんの後ろの端が大城さんの後ろの端を過ぎた（横にいる間の終わり）", t)); }
                        // 大城さんの体の向き（車いすから）・顔（体から）
                        float bodyRel = Mathf.Abs(Mathf.DeltaAngle(nr.eulerAngles.y, chair.eulerAngles.y));
                        if (bodyRel > oBodyRelMax) { oBodyRelMax = bodyRel; oBodyRelMaxT = t; }
                        if (!gbNow && Mathf.Abs(dir.nurse.headYawDeg) > oHeadMaxTalk) { oHeadMaxTalk = Mathf.Abs(dir.nurse.headYawDeg); oHeadMaxTalkT = t; }
                        if (!gbNow)
                        {
                            var tEL = CloseupNurse.Find(teraN.transform, "Eye_L"); var tER = CloseupNurse.Find(teraN.transform, "Eye_R");
                            var oEL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var oER = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                            float la = Vector3.Angle(dir.nurse.HeadForward(), 0.5f * (tEL.position + tER.position) - 0.5f * (oEL.position + oER.position));
                            oLookTeraMin = Mathf.Min(oLookTeraMin, la);
                        }
                        if (Mathf.Abs(teraN.headYawDeg) > tHeadMax) { tHeadMax = Mathf.Abs(teraN.headYawDeg); tHeadMaxT = t; }
                        Vector3 tp = teraN.transform.position;
                        var tr0 = C["tera_ret"]["t"];
                        if (t >= tr0[0].F() - 1e-4f && t <= tr0[1].F() + 1e-4f)
                        {
                            if (float.IsNaN(teraX0)) { teraX0 = tp.x; teraZ0 = tp.z; teraRetT0 = t; }
                            teraRetDist = Mathf.Max(teraRetDist, new Vector2(tp.x - teraX0, tp.z - teraZ0).magnitude); teraRetT1 = t;
                        }
                        prevTera = tp;
                    }
                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    Vector3 mToR = Quaternion.Inverse(chair.rotation) * (scr - mEye); float mToRobot = Mathf.Atan2(mToR.x, mToR.z) * Mathf.Rad2Deg;   // 依頼237：茂さんの目からハコブくんの画面へ（車いすから見た向き・+ はハコブくんの側）
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000") + "," + F(mToRobot, "0.00") + "," + F(frNow) + "," + F((rz + rs.minZ) - ob.nurseFarZ));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top237_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    {
                        var ffk = C["ff"]; int spd = C["ff_speed"].I(4);
                        for (int k = 0; ffk != null && k < ffk.Count; k++)
                        {
                            int a0 = Mathf.RoundToInt(ffk[k][0].F() * fps), a1 = Mathf.RoundToInt(ffk[k][1].F() * fps);
                            if (f > a0 && f < a1 && (f - a0) % spd != 0) inRange = false;     // 依頼235：早回しの所は使うコマだけ撮る
                        }
                    }
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && 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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            // 依頼232：体だけの型（同じ真上のカメラ・同じ大きさ）
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform, proxyRootT, teraN.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // 依頼234：もの別の型（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん）
                            var grp = new List<Renderer>[4]; for (int g = 0; g < 4; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[(rd.transform.IsChildOf(proxyRootT) || rd.transform.IsChildOf(teraN.transform)) ? 3 : Group234(rd, dir.robot, chair, mor)].Add(rd);
                            if (!log.ToString().Contains("依頼234 もの別")) { log.AppendLine("依頼234 もの別の型の部品"); string[] gn = { "赤 ハコブくん", "緑 車いすと茂さん", "青 大城さん", "アルファ 寺島さん" }; for (int g = 0; g < 4; g++) { log.Append("  " + gn[g] + " " + grp[g].Count + "："); foreach (var rd in grp[g]) log.Append(" " + rd.name); log.AppendLine(); } }
                            var obj = new Texture2D(W, H, TextureFormat.RGBA32, false);
                            var px = new Color32[W * H];
                            for (int g = 0; g < 4; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < px.Length; i++) { if (g == 0) px[i].r = mp[i].r; else if (g == 1) px[i].g = mp[i].r; else if (g == 2) px[i].b = mp[i].r; else px[i].a = mp[i].r; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(px); 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") SetTop230(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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames237.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top237.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones237.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet237.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc237.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("■ 依頼235 の確かめ");
                tab.AppendLine(string.Format(IC, "寄せる道（{0:0.000}〜{1:0.000} 秒）\t車いすの向きの最大 {2:0.00}°・後ろの車軸の速さの最大 {3:0.0000} m/秒（{4:0.000} 秒）・向きの変わる速さの最大 {5:0.00}°/秒（{6:0.000} 秒）・前へ進んだ距離 {7:0.0000} m・後ろへ下がった距離 {8:0.0000} m（寄せ始めの車軸から）",
                                              shT0, shT1, manYawMax, manV, manVT, manW, manWT, manFwd, manBack));
                tab.AppendLine(string.Format(IC, "足のせの前の端とハコブくんの前の端（止まってから走り出すまで）\t最小 {0:0.0000} m（{1:0.000} 秒）", footRobotMin, footRobotMinT));
                tab.AppendLine(string.Format(IC, "大城さん\t体の向き（車いすから）の最大 {0:0.00}°（{1:0.000} 秒）・顔の向き（体から・片手の間）の最大 {2:0.00}°（{3:0.000} 秒）・寺島さんの目への角度の最小 {4:0.0}°・右手をはなした {5:0.000} 秒・握り直した {6:0.000} 秒・車いすが根に固い時のずれ {7:0.00000}",
                                              oBodyRelMax, oBodyRelMaxT, oHeadMaxTalk, oHeadMaxTalkT, oLookTeraMin, relT, regripT, rigidErr));
                tab.AppendLine(string.Format(IC, "寺島さん\t顔の向きの最大 {0:0.00}°（{1:0.000} 秒）・下がった距離 {2:0.0000} m（{3:0.000}〜{4:0.000} 秒）・当たったコマ 壁/手すり {5}・大城さん {6}・車いす {7}（{8}）",
                                              tHeadMax, tHeadMaxT, teraRetDist, teraRetT0, teraRetT1, hitTS, hitTO, hitTC, hitTWhere));
                tab.AppendLine(string.Format(IC, "走り出し（依頼235 の決まり）\t{0:0.000} 秒・止まってから {1:0.000} 秒・寄った位置のすき間 {2:0.000} m・物の一番後ろを通り過ぎた {3:0.000} 秒", resumeT, resumeT - stopT, resumeGapWall, passedT));
                tab.AppendLine(string.Format(IC, "ハコブくんが通る時（走り出し後）のすき間の最小\t車いす {0:0.000} m（{1:0.000} 秒）・茂さん {2:0.000} m（{3:0.000}）・大城さん {4:0.000} m（{5:0.000}）・寺島さん {6:0.000} m（{7:0.000}）",
                                              passMin["車いす"], passMinT["車いす"], passMin["茂さん"], passMinT["茂さん"], passMin["看護師"], passMinT["看護師"], passMin["寺島さん"], passMinT["寺島さん"]));
                tab.AppendLine("■ 依頼237 の確かめ");
                tab.AppendLine(string.Format(IC, "ハコブくんが車いすの横にいる間\t{0:0.000}〜{1:0.000} 秒（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）", besideT0, besideT1));
                tab.AppendLine("看護師と車いすが当たったコマの時刻\t" + string.Join("・", ncTimes.ToArray()));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check237.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events237.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C237] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        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;
        }

        /// <summary>依頼234：部品がどのものか（0＝ハコブくん・1＝車いすと茂さん・2＝大城さん）。茂さんの写しの部品は名前が Morita_ で始まる</summary>
        static int Group234(Renderer rd, Transform robot, Transform chair, Transform mor)
        {
            var t = rd.transform;
            if (t.IsChildOf(robot)) return 0;
            if (t.IsChildOf(chair) || t.IsChildOf(mor) || rd.name.StartsWith("Morita_")) return 1;
            return 2;
        }

        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.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] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, 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);
        }
    }
}
```

#### tools/an237.py（依頼237）

```python
"""依頼237：an235.py を写して名前だけ 237 に。報告の表（セリフごとの時刻・カメラの切りかえ・動けない時間・早回し・画面の変わり目）を作る。
使い方: python3 an235.py <Unity の出力フォルダ> <台本> <場面>"""
import csv, json, os, re, sys
D, SC, SHOT = sys.argv[1:4]
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c237"]
vm = json.load(open(os.path.join(D, f"vmap237_{SHOT}.json")))
FPS = 30
ff = [(round(a * FPS), round(b * FPS)) for a, b in C["ff"]]; SPD = C["ff_speed"]
f0 = vm["seq_first"]
def vt(t):
    """台本の秒 → 動画の秒（早回しの所は 1/4）"""
    f = t * FPS; v = (f - f0) / FPS
    for a, b in ff:
        if f > a: v -= (min(f, b) - a) / FPS * (1 - 1 / SPD)
    return v
o = [f"■ {SHOT}"]
o.append(f"動画の長さ {vm['video_s']:.3f} 秒（{vm['n']} コマ・台本 {f0 / FPS:.3f}〜{vm['seq_last'] / FPS:.3f} 秒）")
o.append(f"止まった {vm['t_stop']:.3f} 秒（動画 {vt(vm['t_stop']):.3f}）・走り出し {vm['t_resume']:.3f}（動画 {vt(vm['t_resume']):.3f}）・動けない時間 {vm['t_resume'] - vm['t_stop']:.3f} 秒・物の一番後ろを通り過ぎた {vm['t_pass']:.3f}")
if vm["label_t"] is not None:
    o.append(f"立ち往生の字 {vm['label_t']:.3f} 秒（動画 {vt(vm['label_t']):.3f}）・動けない時間が 30 秒になった {vm['t30']:.3f} 秒・差 {abs(vm['label_t'] - vm['t30']):.3f} 秒")
for a, b in C["ff"]:
    o.append(f"早回し ×{SPD}：台本 {a:.3f}〜{b:.3f} 秒（{b - a:.3f} 秒）→ 動画 {vt(a):.3f}〜{vt(b):.3f} 秒")
o.append("セリフ\t誰\t台本の秒（声の始まり〜終わり）\t動画の秒\t声の長さ")
for k, p in sorted(C["lines"].items(), key=lambda kv: kv[1]["voice_on_s"]):
    o.append(f"{p['text']}\t{p['who']}\t{p['voice_on_s']:.3f}〜{p['voice_off_s']:.3f}\t{vt(p['voice_on_s']):.3f}〜{vt(p['voice_off_s']):.3f}\t{p['voice_len_s']:.3f}")
ls = sorted(C["lines"].values(), key=lambda p: p["voice_on_s"])
o.append("セリフの間（前の声の終わり→次の声の始まり）：" + "・".join(f"{b['text'][:6]} {b['voice_on_s'] - a['voice_off_s']:.3f}" for a, b in zip(ls, ls[1:])))
o.append("カメラ\t台本の秒\t動画の秒")
for t, c in shot["cuts"]:
    if t * FPS <= vm["seq_last"]: o.append(f"{c}\t{t:.3f}\t{max(0.0, vt(t)):.3f}")
rows = list(csv.DictReader(open(os.path.join(D, "frames237.csv"))))
prev = None
o.append("画面の変わり目（台本の秒・動画の秒）")
for r in rows:
    s = r["screen"].split("_")[0]
    if s != prev and float(r["t"]) * FPS <= vm["seq_last"]: o.append(f"  {float(r['t']):.3f}\t{max(0.0, vt(float(r['t']))):.3f}\t{s}"); prev = s
print("\n".join(o))
open(os.path.join(D, f"an237_{SHOT}.txt"), "w").write("\n".join(o) + "\n")
```

#### tools/batch_check.sh（依頼237）

```bash
#!/bin/bash
R=/tmp/c237/tools
for SH in stop_voice stop_stuck; do
  S=$(date +%s); $R/run237.sh /tmp/c237/out/$SH $SH closeup237_script.json off on top; echo "$SH check $(( $(date +%s)-S )) 秒"
done
```

#### tools/batch_render.sh（依頼237）

```bash
#!/bin/bash
# 依頼237：区切って撮る（1 回 12 分より短く）。使い方: batch_render.sh <場面> <from:to> [<from:to> ...]
R=/tmp/c237/tools; SH="$1"; shift
for c in "$@"; do
  F=${c%%:*}; T=${c##*:}; S=$(date +%s)
  $R/run237b.sh /tmp/c237/out/$SH $SH closeup237_script.json $F $T off
  echo "$SH $F〜$T $(( $(date +%s)-S )) 秒"
done
```

#### tools/facesize237.py（依頼237）

```python
#!/usr/bin/env python3
"""依頼237：「通れません」の顔の大きさの確かめ（223 の facesize223.py の測り方を写した）。
コマ（frames/<場面>/f_*.png）の画面の顔の目（白い縦長の 2 つのかたまり）の高さ・幅・2 つの目の中心の間・面積を測り、
寄りのカメラ（screen_close）・ハコブくんが止まったままの間で、「通れません」のコマと、ほかの帯（通ります・お待ちしています）のコマを比べる。
235 の「通れません」の静止画（顔が小さい）も同じ測り方で出す。
使い方：python3 facesize237.py <Unity の出力フォルダ> <場面> [235 の静止画 ...]"""
import sys, csv, os
import numpy as np
from PIL import Image
from scipy import ndimage
D, SHOT = sys.argv[1], sys.argv[2]
def measure(path):
    a = np.asarray(Image.open(path).convert("RGB")).astype(int)
    r, g, b = a[..., 0], a[..., 1], a[..., 2]
    white = (r > 215) & (g > 215) & (b > 215) & (np.abs(r - b) < 25)
    lab, n = ndimage.label(white)
    if n == 0: return None
    sizes = ndimage.sum(white, lab, range(1, n + 1)); objs = ndimage.find_objects(lab); cand = []
    for i, sl in enumerate(objs):
        h = sl[0].stop - sl[0].start; w = sl[1].stop - sl[1].start
        if sizes[i] <= 30 or h < 1.4 * w: continue
        y0, y1 = max(0, sl[0].start - 24), sl[0].stop + 24; x0, x1 = max(0, sl[1].start - 24), sl[1].stop + 24
        near = ndimage.binary_dilation(lab[y0:y1, x0:x1] == i + 1, iterations=12); ring = ~near
        if ring.sum() == 0 or (a[y0:y1, x0:x1].max(-1)[ring] < 80).mean() < 0.5: continue
        cand.append((sizes[i], i, sl))
    cand.sort(reverse=True)
    if len(cand) < 2: return None
    e = sorted(cand[:2], key=lambda c: c[2][1].start)
    hs = [c[2][0].stop - c[2][0].start for c in e]; ws = [c[2][1].stop - c[2][1].start for c in e]
    cx = [(c[2][1].start + c[2][1].stop) / 2 for c in e]; cy = [(c[2][0].start + c[2][0].stop) / 2 for c in e]
    return dict(eye_h=float(np.mean(hs)), eye_w=float(np.mean(ws)), eye_d=float(np.hypot(cx[1] - cx[0], cy[1] - cy[0])), area=float(e[0][0] + e[1][0]))
rows = list(csv.DictReader(open(os.path.join(D, "frames237.csv"))))
groups = {}
out = ["frame,t,screen,eye_h_px,eye_w_px,eye_dist_px,eye_area_px"]
for r in rows:
    if r["cam"] != "screen_close" or r["mode"] != "stop": continue
    sc = r["screen"].split("_")[0]
    p = os.path.join(D, "frames", SHOT, "f_%05d.png" % int(r["frame"]))
    if not os.path.exists(p): continue
    m = measure(p)
    if m is None: continue
    out.append(f"{r['frame']},{r['t']},{sc},{m['eye_h']:.1f},{m['eye_w']:.1f},{m['eye_d']:.1f},{m['area']:.0f}")
    groups.setdefault(sc, []).append(m)
open(os.path.join(D, f"facesize237_{SHOT}.csv"), "w").write("\n".join(out) + "\n")
print("■ 寄り（screen_close）・止まっている間のコマ（目の高さ・幅・目の中心の間・2 つの目の面積　画素）")
for sc, ms in groups.items():
    f = lambda k: (min(x[k] for x in ms), max(x[k] for x in ms))
    print(f"{sc}\t{len(ms)} コマ\t高さ {f('eye_h')[0]:.1f}〜{f('eye_h')[1]:.1f}・幅 {f('eye_w')[0]:.1f}〜{f('eye_w')[1]:.1f}・間 {f('eye_d')[0]:.1f}〜{f('eye_d')[1]:.1f}・面積 {f('area')[0]:.0f}〜{f('area')[1]:.0f}")
for p in sys.argv[3:]:
    m = measure(p); print("参考", os.path.basename(p), "→", {k: round(v, 1) for k, v in m.items()} if m else "目が見つからない")
```

#### tools/make237.py（依頼237）

```python
"""依頼237：make235.py を写して名前だけ 237 に（台本の c237・出力 closeup237_*）。以下は 235 の説明：
(1) closeup235_<場面>.mp4：frames/<場面>/f_*.png に台本の秒の音（mix237_<場面>.wav）を重ねる。早回し（台本 c235.ff・×c235.ff_speed）の所は 4 コマに 1 枚を使い、
    音は無し（声の無い所だけを早回しにしている）、右上に「早回し ×4・実際の時間 m:ss」を出す。⑨-2 は 30 秒になった所から 3 秒、左下に「立ち往生 1件（30 秒以上動けず、人が動かした）」
(2) closeup235_<場面>_top.mp4：frames/<場面>_top に 234 の描き方で床の線・通った跡・印・左上の字を重ねる。床の線は、ものごとに穴を埋めた外形
    （閉じる処理 半径 6 画素 → 中の穴埋め）の中には描かない。もの：ハコブくん（赤）・車いすと茂さん（緑）・大城さん（青）・寺島さん（アルファ）。
    大城さんが両手で握りにのせている間（台本 c235.grip_both）は、大城さんと車いすと茂さんを 1 つのものとして埋める（依頼235）
    重ねる順：コマ → 床の線（外形の所は消す）→ 通った跡 → 印 → 左上の字。早回しの所は (1) と同じコマだけ
動画の終わり：ハコブくんが物の一番後ろを通り過ぎてから 2.5 秒（events237.txt）
使い方: python3 make235.py <Unity の出力フォルダ> <台本> <場面> <音の wav> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile, wave
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, SHOT, WAV, VD = sys.argv[1:6]
os.makedirs(VD, exist_ok=True)
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c237"]
FPS, W, H, S = 30, 1920, 1080, 2
ev = open(os.path.join(D, "events237.txt"), encoding="utf-8").read()
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_res = float(re.search(r"([\d.]+) 秒 走り出す", ev).group(1))
t_pass = float(re.search(r"([\d.]+) 秒 物の一番後ろを通り過ぎた", ev).group(1))
f0 = int(round(C["video_from"] * FPS)); f1 = min(int(round((t_pass + 2.5) * FPS)), int(round(C["video_to"] * FPS)))
SPD = C["ff_speed"]; ffseg = [(int(round(a * FPS)), int(round(b * FPS))) for a, b in C["ff"]]
def in_ff(f):
    for a, b in ffseg:
        if a < f < b: return (a, b)
    return None
seq = [f for f in range(f0, f1 + 1) if in_ff(f) is None or (f - in_ff(f)[0]) % SPD == 0]
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s)
label = C.get("stuck_label")
# 立ち往生の字は「止まってから 30 秒」のコマ（Unity の止まった時刻から）
t30 = t_stop + 30.0 if label else None

# ---------------------------------------------------------------- (1) 本番の動画
tmp = tempfile.mkdtemp(prefix="m237_", dir="/tmp")
FB, FS = font(40), font(30)
info = {"frames": len(seq), "ff_frames": sum(1 for f in seq if in_ff(f)), "label": None}
for k, f in enumerate(seq):
    src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src
    t = f / FPS
    ff = in_ff(f); lab = t30 is not None and t30 - 1e-4 <= t < t30 + 3.0 - 1e-4
    if not ff and not lab:
        os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png")); continue
    im = Image.open(src).convert("RGB"); d = ImageDraw.Draw(im)
    if ff:
        real = t - C["video_from"]; s = f"早回し ×{SPD}　実際の時間 {int(real) // 60}:{int(real) % 60:02d}"
        bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
        d.rounded_rectangle([W - w - 70, 24, W - 24, 24 + 72], radius=12, fill=(255, 255, 255))
        d.text((W - w - 47, 60), s, font=FB, fill=(25, 25, 25), anchor="lm")
    if lab:
        if info["label"] is None: info["label"] = t
        s = "立ち往生 1件（30 秒以上動けず、人が動かした）"
        bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
        d.rounded_rectangle([24, H - 24 - 80, 24 + w + 50, H - 24], radius=12, fill=(242, 194, 48))
        d.text((49, H - 24 - 40), s, font=FB, fill=(25, 25, 25), anchor="lm")
    im.save(os.path.join(tmp, f"v_{k:05d}.png"))
# 音：ふだんの所は台本の秒の音、早回しの所は無音（その長さはコマの数 / 30）
wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16)
out = []
for f in seq:
    a = int(round(f / FPS * SR)); b = a + SR // FPS
    out.append(np.zeros(SR // FPS, np.int16) if in_ff(f) else (x[a:b] if b <= len(x) else np.pad(x[a:min(b, len(x))], (0, b - min(b, len(x))))))
aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(np.concatenate(out).tobytes()); w2.close()
vid = os.path.join(VD, f"closeup237_{SHOT}.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw,
                "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30",
                "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True)
# 動画の秒 ↔ 台本の秒
vmap = {f: k / FPS for k, f in enumerate(seq)}
json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "t_stop": t_stop, "t_resume": t_res, "t_pass": t_pass,
           "label_t": info["label"], "t30": t30, "ff": C["ff"], "vmap_keys": {str(f): round(v, 4) for f, v in vmap.items() if f % 15 == 0}},
          open(os.path.join(D, f"vmap237_{SHOT}.json"), "w"), ensure_ascii=False)
print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒・早回しのコマ", info["ff_frames"], "・立ち往生の字", info["label"])

# ---------------------------------------------------------------- (2) 真上の動画
CAM = json.load(open(os.path.join(D, "top237_cam.json")))
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {"center": (120, 120, 120), "x042": (142, 36, 170), "lane": (46, 173, 107), "chair": (239, 108, 0), "robot": (0, 105, 92)}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)
rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames237.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top237.csv")))}
man = C["man"]
MARKS = [("chair", man["t0"], "寄せ始め"), ("chair", man["t1"], "寄せ終わり"), ("robot", t_stop, "止まった"), ("robot", t_res, "走り出し")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]
FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S)
def sc(p): return (p[0] * S, p[1] * S)
def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)
def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0
    while s < L:
        e = min(L, s + DASH * S); d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S); s += (DASH + GAP) * S
def down(layer): return layer.resize((W, H), Image.LANCZOS)
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x042", "lane"): dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
text_box(d, sc((14, line_py["center"] - 8)), "真ん中 0.00", FL, COL["center"], "lb", edge=COL["center"])
text_box(d, sc((14, line_py["x042"] + 8)), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, sc((W - 14, line_py["lane"] - 8)), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st); static_A = static.getchannel("A"); static_An = np.array(static_A)
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (70 if head == "寄せ終わり" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "走り出し" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        tv = vmap.get(mark_f[i]); tv = tv if tv is not None else vmap[min(vmap, key=lambda q: abs(q - mark_f[i]))]
        text_box(d, sc((px, ly)), f"{head} {tv:.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]; cx = num_ok(r["chair_x"]); cy = num_ok(r["chair_yaw"]); g = num_ok(r["gap_m"])
    s0 = f"{vmap[f]:.1f} 秒" + (f"（早回し ×{SPD}）" if in_ff(f) else "")
    return [s0, "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm・向き {cy:+.0f}°" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")]
RC = 6
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def fill_obj(soft):
    ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added
    y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    added[y0:y1, x0:x1] = filled & ~b.astype(bool)
    return added
gb = C["grip_both"]
tmpT = tempfile.mkdtemp(prefix="m237t_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown)
per = []; top_stills = {}
want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"}
k = 0
seqset = set(seq)
for f in range(0, f1 + 1):
    r = top[f]
    for who, kx, ky in (("chair", "axle_px", "axle_py"), ("robot", "robot_px", "robot_py")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)
        if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2; td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))
        prev[who] = p
    if f not in seqset: continue
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA")
    mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L"))
    ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA"))
    joined = gb[min(f, len(gb) - 1)] == 1
    groups = [ob[:, :, 0], np.maximum(ob[:, :, 1], ob[:, :, 2]), ob[:, :, 3]] if joined else [ob[:, :, 0], ob[:, :, 1], ob[:, :, 2], ob[:, :, 3]]
    add_any = np.zeros((H, W), bool)
    for g in groups: add_any |= fill_obj(g)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L"))))
    lines = hud_lines(f)
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl))
    o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1
    stA = np.array(st_m.getchannel("A"))
    per.append((f, int(joined), int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum())))
    if f in want: top_stills[want[f]] = o
vidT = os.path.join(VD, f"closeup237_{SHOT}_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png"))
open(os.path.join(D, f"per237_{SHOT}.csv"), "w").write("frame,joined,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per))
print("真上", vidT, k, "コマ・外形の中に残る線 合計", sum(p[2] for p in per), "・ひとまとめのコマ", sum(p[1] for p in per))
```

#### tools/make_script237.py（依頼237）

```python
"""依頼237：make_script235.py を写して、写した先で変えた。235 から変えたこと：
・235 の⑩（止まって 3〜4 秒で茂さん「何を運んでるの？」→ハコブ「病棟へのお届け物です」）を 2 本とも消した
・⑨-1：止まって 10 秒のハコブ「すみません、通ります」のあと、茂さんが大城さんのほうへ顔を向けて（M_TURN_O）「おい、ロボットさんが通るって」→ 235 のとおり大城さんが気づいて寄せる。
  走り出して車いすに近づいた所で、茂さんがハコブくんのほうへ顔を向けて「何を運んでるんだい？」→ ハコブ「病棟へのお届け物です。ありがとうございます」（帯「お届け中」→「ありがとうございます」と合わせて目まで笑う顔 1.5 秒）→ 茂さんが 10° うなずき・顔を前へ
  7・8 の声は、ハコブくんが車いすの横にいる間（times.json の beside：前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）に終わるように置く
・⑨-2：20 秒の声の後 M4_AFTER 秒で茂さんがハコブくんのほうへ顔を向けて（M_YAW）「あんたも待たされてるのかい」→ ハコブ「はい、お待ちしています」→ 茂さんは顔を戻す。
  車いすの横を通る時にハコブ「ありがとうございます」＋目まで笑う顔 1.5 秒・茂さんが 10° うなずく。早回しは 10〜20 秒の間（235 のまま）と、6 のあとから 30 秒の手前まで
・走り出した時の目まで笑う顔（235）はやめ、走り出したら「基本」
・画面の stuck は帯（黄）「通れません」だけの絵 c237_stuck_band.png と、顔の板の困り顔 face237_trouble（ふだんの大きさ）
以下は 235 の説明：
依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）の台本 closeup235_script.json を作る。場面は 2 つ：stop_voice（⑨-1）・stop_stuck（⑨-2）。
寺島さんは別の場面 <名前>__tera（同じ台本の中。Closeup235.cs が 2 つめの CloseupDirector で動かす）。
make_script229.py を土台にした（廊下・色・光・看護師の値・握りの的・声の口の作り方・ハコブくんの決まり）。229 から変えたこと：
・車いすの根の位置・向きを毎コマ台本に書く（c235.chair）。両手で握っている間は大城さんの根の前に固く付いた位置（229 と同じ）、
  立ち話で大城さんが体を回す間は止めた所のまま
・寄せ方（依頼235 の答え 1）：feas235.py で出した道（その場で回る・まっすぐ前／後ろ）を、速さ 0.3 m/秒・向きの変わる速さ 25°/秒を超えない台形の速さでたどる。
  後ろの車軸の中心がその道を通る（横にすべらない）。大城さんの根と向きは車いすから出す
・立ち話の向き（答え 2）：大城さんは右手（寺島さんから遠い側）を握りからはなし、体ごと寺島さんへ回す（足は 2 歩踏み替える）。左手は左の握りのまま（的は世界に止めた握り）
使い方：python3 make_script229.py と同じ並び：<175 の台本> <出力の台本> <声の wav のフォルダ> <道の json（feas235.py の出力）> [times.json]"""
import json, math, os, sys, wave
import numpy as np

def E(k, d):
    v = os.environ.get(k)
    return type(d)(v) if v is not None else d

src, dst, wavdir, pathjs = sys.argv[1:5]
times = json.load(open(sys.argv[5])) if len(sys.argv) > 5 and os.path.exists(sys.argv[5]) else {}
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = list(S["corridor"]["origin"])
AXLE_BACK = 0.15
GRIP_Z = 0.3336; GRIP_X, GRIP_Y = 0.225, 0.910; GRIP_R = 0.0155
D_PUSH = 0.26
WC_AHEAD = GRIP_Z + D_PUSH                 # 車いすの根：大城さんの根の前（229 と同じ 0.5936）
AX_AHEAD = WC_AHEAD - AXLE_BACK            # 後ろの車軸の中心：大城さんの根の前
WC_FRONT = 0.64
ROBOT_FRONT, ROBOT_REAR = 0.382, 0.380
LANE_R = -0.33
V_C = 0.8                                  # 押す速さ（229）
STEP_T = 0.5
SPINE, CHEST = 4.0, 3.0
Z_NS = E("Z_NS", 9.714)                    # 大城さんの根が止まる z（ハコブくんが 229 と同じ z 5.8 あたりで止まるように）
NZ0 = E("NZ0", 15.0)
RZ0 = E("RZ0", -1.6)
TV0 = 1.0
GAP = E("GAP", 0.55)
O_HW, T_F, T_B = 0.2381, 0.1499, 0.1399
T_GAP = 0.15                               # 寺島さんと大城さんのすき間（233 の 0.10〜0.15 の大きいほう）
T_DZ = E("T_DZ", -0.30)                    # 寺島さんの立つ前後（大城さんの根から。− は前）：答え 2 の「手の届かない形」→ 0.3 m 前へ（turn235.py）
T_X = O_HW + T_GAP + T_F                   # 寺島さんの根の x（立ち話）0.538
T_WALK_X = 0.539                           # 追いつく時の x（大城さんの +x の端 0.238 と手すり 0.84 の真ん中）
T_V = 1.2
O_TURN = E("O_TURN", 29.0)                 # 大城さんが体を回す角度（turn235.py：寺島さん 0.3 m 前で 29°・顔は体から −29°）
T_RET = (0.65, 0.69)                       # 寺島さんが下がって立つ所（x、大城さんの止まった根からの z）。feas235.py の TX・TZ
def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)
q = lambda t: round(round(t * FPS) / FPS, 4)

# ---------------------------------------------------------------- 声（233 の audio）
LINES = {"V1": ("tera", "V1_terashima_oshirosan.wav", "大城さん"), "V2": ("nurse", "V2_oshiro_otsukare.wav", "あ、寺島さん。おつかれさま"),
         "H2": ("robot", "H2_hakobu_toorimasu.wav", "すみません、通ります"), "T2": ("tera", "T2_terashima_hakobukun.wav", "あ、ハコブくん"),
         "V8": ("nurse", "V8_oshiro_gomenne.wav", "あ、ごめんね"),
         # 依頼237 の新しい声
         "M2": ("morita", "M2_morita_tooru.wav", "おい、ロボットさんが通るって"), "M3": ("morita", "M3_morita_nanida.wav", "何を運んでるんだい？"),
         "M4": ("morita", "M4_morita_matasare.wav", "あんたも待たされてるのかい"),
         "H3": ("robot", "H3_hakobu_otodoke_arigato.wav", "病棟へのお届け物です。ありがとうございます"), "H4": ("robot", "H4_hakobu_omachi.wav", "はい、お待ちしています"),
         "H5": ("robot", "H5_hakobu_arigato.wav", "ありがとうございます")}
SR = 48000
def load_wav(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float64) / 32768.0
    assert w.getframerate() == SR and w.getnchannels() == 1, p
    return x
def voiced(x, th_db=-45.0):
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    on = np.where(20 * np.log10(e + 1e-9) > th_db)[0]
    return on[0] * hop / SR, (on[-1] + 1) * hop / SR
clips = {}
for k, (who, fn, text) in LINES.items():
    x = load_wav(os.path.join(wavdir, fn)); v0, v1 = voiced(x)
    clips[k] = {"who": who, "file": fn, "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}
def inner_gap(x, th_db=-45.0, min_s=0.3):
    """依頼237：声の中の一番長い無音（min_s 秒以上）の終わり（クリップの秒）＝ H3 の「ありがとうございます」の始まり"""
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    v = 20 * np.log10(e + 1e-9) > th_db; on = np.where(v)[0]; best = None; i = on[0]
    while i < on[-1]:
        if not v[i]:
            j = i
            while not v[j]: j += 1
            if (j - i) * hop / SR >= min_s and (best is None or j - i > best[1] - best[0]): best = (i, j)
            i = j
        i += 1
    return best[1] * hop / SR
H3_ARIGATO = inner_gap(clips["H3"]["x"]) - clips["H3"]["v0"]      # 声の始まりから「ありがとうございます」の始まりまで
GAP_Q = E("GAP_Q", 0.4)                    # 依頼237：新しいやり取りのセリフの間（235 の決まり 0.4〜0.7 の短いほう。⑨-1 の動けない時間を 30 秒未満にするため）
M_TURN_O = E("M_TURN_O", -40.0)            # ⑨-1 の 5：茂さんが後ろの大城さんのほうへ顔を向ける（30〜45°。− は +x の側＝大城さんが寺島さんのほうへ向いている側）
M_YAW = E("M_YAW", 25.0)                   # ⑨-2 の 5：ハコブくんのほうへ（20〜30°。235 の⑩と同じ 25°）
M4_AFTER = E("M4_AFTER", 2.5)              # ⑨-2 の 5：20 秒の声が終わってから（2〜4 秒）
HAPPY_S = 1.5

RULE = {
    "about": "ハコブくんの決まり（依頼228・229 のまま）。依頼235 で足したのは resume_still_s（止まった後、前の物が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す）と、通り過ぎてから x −0.33 へ戻ること",
    "cruise_mps": 0.6, "slow_mps": 0.5, "accel_max_mps2": 0.4, "decel_max_mps2": 0.4, "jerk_max_mps3": 1.0,
    "detect_range_m": 6.0, "react_s": 0.1, "margin_m": 2.4, "gap_slow_m": 0.40, "gap_stop_m": 0.15,
    "lane_x": LANE_R, "wall_clear_m": 0.053,
    "lateral_max_mps": 0.15, "lateral_angle_deg": 15.0, "lateral_accel_mps2": 0.25, "lateral_gain": 2.0, "lateral_done_m": 0.03,
    "resume_lateral_angle_deg": 10.0, "turn_rate_dps": 30.0, "corner_half_len_m": 0.38, "corner_slack_m": 0.006,
    "pass_behind_m": 1.0, "resume_still_s": 0.5, "still_mps": 0.005,
}

# ---------------------------------------------------------------- 1. 押して来て止まる（x 0・向き 180°）
TW0, RAMP, T_DEC = 0.2, 1.0, 1.6
d_dec = V_C * T_DEC / 2
d_total = NZ0 - Z_NS
t_cr0 = TW0 + RAMP; d_ramp = V_C * RAMP / 2
t_dec0 = t_cr0 + (d_total - d_ramp - d_dec) / V_C
t_ns = t_dec0 + T_DEC
def oshiro_push_z(t):
    if t <= TW0: return NZ0
    if t <= t_cr0:
        u = (t - TW0) / RAMP; return NZ0 - V_C * RAMP * (u ** 3 - 0.5 * u ** 4)          # 速さ smooth(u)·V の積分
    if t <= t_dec0: return NZ0 - d_ramp - V_C * (t - t_cr0)
    if t <= t_ns:
        u = (t - t_dec0) / T_DEC; return NZ0 - d_ramp - V_C * (t_dec0 - t_cr0) - V_C * T_DEC * (u - (u ** 3 - 0.5 * u ** 4))
    return Z_NS
# smooth の積分：∫0^u (3s²−2s³) ds = u³ − u⁴/2（u=1 で 0.5）
assert abs(oshiro_push_z(t_ns) - Z_NS) < 1e-6

# ---------------------------------------------------------------- 2. 寺島さん：後ろから 1.2 m/秒で追いつき、横に並んで「大城さん」、止まって大城さんへ向く
t_v1 = t_dec0 - 0.4                         # 横に並んだ時（大城さんはまだ 0.8 m/秒）に「大城さん」
z_al = oshiro_push_z(t_v1)
T_TD = 2.1                                  # 寺島さんの減速（1.2 → 0・なめらか）
z_tstop = Z_NS + T_DZ
t_ts = t_v1 + T_TD
assert abs((z_al - z_tstop) - T_V * T_TD / 2) < 0.08, (z_al - z_tstop, T_V * T_TD / 2)
T_TD = (z_al - z_tstop) * 2 / T_V; t_ts = t_v1 + T_TD
TZ0 = E("TZ0", z_al + T_V * (t_v1 - 0.2))   # 0.2 秒で 1.2 m/秒（はじめから歩いている）
def tera_z(t):
    if t <= t_v1: return z_al + T_V * (t_v1 - t)
    if t <= t_ts:
        u = (t - t_v1) / T_TD; return z_al - T_V * T_TD * (u - (u ** 3 - 0.5 * u ** 4))
    return z_tstop
YAW_FACE_O = math.degrees(math.atan2(0.0 - T_X, Z_NS - z_tstop)) % 360     # 大城さんの根のほうへ（299°）
t_tturn0, t_tturn1 = t_ts - 0.5, t_ts + 0.5                                # 減速の終わりで向きを変える（2 歩）
def tera_x(t):
    return T_WALK_X + (T_X - T_WALK_X) * smooth((t - t_tturn0) / (t_tturn1 - t_tturn0))
def tera_yaw0(t):
    return 180.0 + (YAW_FACE_O - 180.0) * smooth((t - t_tturn0) / (t_tturn1 - t_tturn0))

# ---------------------------------------------------------------- 3. 大城さんが振り返る（右手をはなし、体を 29° 回す・2 歩）
t_rel0 = t_ns + 0.25; t_rel1 = t_rel0 + 0.5           # 右手の重み 1 → 0
t_oturn0 = t_ns + 0.35; t_oturn1 = t_oturn0 + 0.9     # 向き 180 → 151
on = {"V1": t_v1}
on["V2"] = max(t_oturn0 + 0.45, on["V1"] + clips["V1"]["dur"] + GAP)
T_STOP_EST = on["V2"] + clips["V2"]["dur"] + 2.5
t_stop = times.get("stop_t", T_STOP_EST)
z_rstop = times.get("robot_stop_z", 5.8); x_rstop = times.get("robot_stop_x", -0.4643)

# ---------------------------------------------------------------- 4. 寄せる道（feas235.py の道を時間に）
P = json.load(open(pathjs))
pts = P["path"]
segs = []
for p in pts[1:]:
    if not segs or segs[-1]["kind"] != p[3]: segs.append({"kind": p[3], "pts": []})
    segs[-1]["pts"].append(p)
V_MAX, W_MAX, ACC_T, PAUSE = E("V_MAX", 0.28), E("W_MAX", 23.0), 0.3, 0.15     # 上限 0.3 m/秒・25°/秒より少し下
def trap(d, vmax, ta):
    T = d / vmax + ta
    def f(t):
        if t <= 0: return 0.0
        if t >= T: return d
        if t < ta: return vmax * t * t / (2 * ta)
        if t > T - ta: return d - vmax * (T - t) ** 2 / (2 * ta)
        return vmax * (t - ta / 2)
    return T, f
start = pts[0]
man = []          # (時間の長さ, 関数 u→(ax, az, th))
cur = (start[0], start[1], start[2])
for sg in segs:
    end = sg["pts"][-1]
    if sg["kind"] == "r":
        dth = end[2] - cur[2]; T, f = trap(abs(dth), W_MAX, 0.2); c0 = cur
        man.append((T, (lambda f, c0, dth: lambda t: (c0[0], c0[1], c0[2] + math.copysign(f(t), dth)))(f, c0, dth)))
    else:
        d = math.hypot(end[0] - cur[0], end[1] - cur[1]); T, f = trap(d, V_MAX, ACC_T); c0 = cur; e0 = (end[0], end[1])
        man.append((T, (lambda f, c0, e0, d: lambda t: (c0[0] + (e0[0] - c0[0]) * f(t) / d, c0[1] + (e0[1] - c0[1]) * f(t) / d, c0[2]))(f, c0, e0, d)))
    cur = (end[0], end[1], end[2])
MAN_T = sum(T for T, _ in man) + PAUSE * (len(man) - 1)
AX0_Z = Z_NS - AX_AHEAD                    # 止まった時の車軸の z（向き 0）
def man_at(t):
    """寄せ始めから t 秒の (車軸 x, 車軸 z, 向き°)。feas の z は前＝−（車軸の止まった所から）"""
    for T, fn in man:
        if t <= T: a = fn(t); return a[0], AX0_Z + a[1], a[2]
        t -= T
        if t <= PAUSE: a = fn(T); return a[0], AX0_Z + a[1], a[2]
        t -= PAUSE
    a = man[-1][1](man[-1][0]); return a[0], AX0_Z + a[1], a[2]

# ---------------------------------------------------------------- 場面ごと
def build(variant):
    stuck = variant == "stop_stuck"
    on2 = dict(on)
    ev = {}
    tv = times.get(variant, {})
    # 声をかける（235 のまま：10 秒・20 秒）
    calls = [t_stop + 10.0] + ([t_stop + 20.0] if stuck else [])
    on2["H2"] = calls[0]
    if stuck: on2["H2b"] = calls[1]
    endH2 = on2["H2"] + clips["H2"]["dur"]
    t30 = t_stop + 30.0
    NOD_DOWN, NOD_HOLD, NOD_BACK = 0.28, 0.10, 0.32
    if stuck:
        # 依頼237 ⑨-2 の 5・6：20 秒の声のあと M4_AFTER 秒で茂さん→ハコブくんが答える→茂さんは顔を戻す
        endH2b = on2["H2b"] + clips["H2"]["dur"]
        on2["M4"] = endH2b + M4_AFTER
        t_m_turn0 = on2["M4"] - 0.45; t_m_turn1 = on2["M4"]
        on2["H4"] = on2["M4"] + clips["M4"]["dur"] + GAP_Q
        endH4 = on2["H4"] + clips["H4"]["dur"]
        m_back0 = endH4 + 0.3; m_back1 = m_back0 + 0.6
        t_tlook0 = t30 + E("TLOOK_AFTER", 1.2); t_tlook1 = t_tlook0 + 0.4; t_tback0 = t_tlook1 + 0.35; t_tback1 = t_tback0 + 0.4
        on2["T2"] = t_tback1 + 0.05
        cue_end = on2["T2"] + clips["T2"]["dur"]
        on2["V8"] = cue_end + GAP
    else:
        # 依頼237 ⑨-1 の 5：茂さんが先に気づき、大城さんのほうへ顔を向けて「おい、ロボットさんが通るって」
        t_mo0 = endH2 + 0.05; t_mo1 = t_mo0 + 0.45
        on2["M2"] = endH2 + GAP_Q
        cue_end = on2["M2"] + clips["M2"]["dur"]
        on2["V8"] = cue_end + GAP_Q
    # 大城さんが気づく：顔をハコブくんへ（cue_end＋0.25）・体を戻して両手で握り直す（＋0.45 から 0.9 秒）・「あ、ごめんね」（235 のまま）
    t_olook0 = cue_end + 0.25; t_olook1 = t_olook0 + 0.35
    t_oback0 = cue_end + 0.45; t_oback1 = t_oback0 + 0.9
    t_regrip0 = t_oback1 + 0.1; t_regrip1 = t_regrip0 + 1.0         # 体を戻し終わってから右手を上から握りへ
    endV8 = on2["V8"] + clips["V8"]["dur"]
    if not stuck:
        m_ob0 = endV8 + 0.2; m_ob1 = m_ob0 + 0.6                     # 茂さんは顔を前へ戻す（大城さんが顔を戻すのと同じ時）
    t_olookback0 = endV8 + 0.2; t_olookback1 = t_olookback0 + 0.45
    # 寺島さんが下がる（V8 の始まり＋0.3 から）：向きを変え（後ろ＝+z へ）・歩いて・手すりを背に −x を向く
    t_tr0 = on2["V8"] + 0.3
    TR_TURN1, TR_WALK, TR_TURN2 = 0.8, 1.6, 0.8
    t_tr1 = t_tr0 + TR_TURN1; t_tr2 = t_tr1 + TR_WALK; t_tr3 = t_tr2 + TR_TURN2
    # 寄せ始め：握り直しと寺島さんが下がり終わった後
    t_man0 = max(t_regrip1 + 0.2, t_tr3 + 0.1)
    t_man1 = t_man0 + MAN_T
    t_resume_est = t_man1 + 0.512
    t_resume = tv.get("resume_t", t_resume_est)
    t_exit = tv.get("passed_t", t_resume + 9.833) + 2.5
    # 依頼237：ハコブくんが車いすの横にいる間（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで。1 回目の Unity の値・無ければ 235 の差）
    bs = tv.get("beside", [t_resume + 5.0, t_resume + 8.533])
    if stuck:
        # ⑨-2 の 8：横を通る時に「ありがとうございます」（横にいる間の真ん中）
        on2["H5"] = bs[0] + (bs[1] - bs[0] - clips["H5"]["dur"]) / 2
        happy_from = on2["H5"]
        endH5 = on2["H5"] + clips["H5"]["dur"]
        nod_t0 = endH5 + 0.25
    else:
        # ⑨-1 の 7・8：茂さんの声が横に来た所（bs[0]）＋0.05 で終わり、GAP_Q あけてハコブくんが答える（横にいる間に 2 つとも終わる）
        on2["M3"] = bs[0] + E("M3_END_AFTER", 0.05) - clips["M3"]["dur"]
        on2["H3"] = on2["M3"] + clips["M3"]["dur"] + GAP_Q
        happy_from = on2["H3"] + H3_ARIGATO
        endH3 = on2["H3"] + clips["H3"]["dur"]
        t_m3_0 = on2["M3"] - 0.45; t_m3_1 = on2["M3"]
        M_YAW3 = tv.get("m3_yaw", 35.0)
        nod_t0 = endH3 + 0.25
    happy_to = happy_from + HAPPY_S
    m_end0 = nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK + 0.3; m_end1 = m_end0 + 0.6
    DUR = q(t_exit)
    NF = int(round(DUR * FPS))
    ev.update({"t_stop": t_stop, "t30": t30 if stuck else None, "t_man0": t_man0, "t_man1": t_man1, "t_resume_used": t_resume, "t_exit_used": t_exit,
               "t_tr": [t_tr0, t_tr3], "t_oturn": [t_oturn0, t_oturn1], "t_oback": [t_oback0, t_oback1], "t_rel": [t_rel0, t_rel1], "t_regrip": [t_regrip0, t_regrip1]})

    # ---------- 大城さんの根・向き、車いすの根・向き（毎コマ）
    nurse_rows, chair_rows, grip_both = [], [], []
    for f in range(NF + 1):
        t = f * DT
        if t < t_man0:
            ax, az, th = 0.0, oshiro_push_z(t) - AX_AHEAD, 0.0
            nx_, nz_ = 0.0, oshiro_push_z(t)
            if t < t_oturn0: nyaw = 180.0
            elif t < t_oback0: nyaw = 180.0 - O_TURN * smooth((t - t_oturn0) / (t_oturn1 - t_oturn0))
            else: nyaw = 180.0 - O_TURN * (1 - smooth((t - t_oback0) / (t_oback1 - t_oback0)))
        else:
            ax, az, th = man_at(t - t_man0)
            fx, fz = math.sin(math.radians(th)), -math.cos(math.radians(th))
            nx_, nz_ = ax - fx * AX_AHEAD, az - fz * AX_AHEAD; nyaw = 180.0 - th
        # 車いすの根：車軸の前 0.15（向き th）
        fx, fz = math.sin(math.radians(th)), -math.cos(math.radians(th))
        cx, cz = ax + fx * AXLE_BACK, az + fz * AXLE_BACK
        nurse_rows.append((t, nx_, nz_, nyaw)); chair_rows.append((round(cx, 5), round(cz, 5), round(180.0 - th, 4)))
        grip_both.append(not (t_rel0 <= t < t_regrip1))
    keys_x = [[round(r[0], 4), round(r[1], 5), "lin"] for r in nurse_rows]; keys_x[0] = keys_x[0][:2]
    keys_z = [[round(r[0], 4), round(r[2], 5), "lin"] for r in nurse_rows]; keys_z[0] = keys_z[0][:2]
    keys_yaw = [[round(r[0], 4), round(r[3], 4), "lin"] for r in nurse_rows]; keys_yaw[0] = keys_yaw[0][:2]

    # ---------- 大城さんの足
    def walk_steps(t0, t1, first="R", period=STEP_T):
        st, t, foot = [], t0, first
        while t + period <= t1 + 1e-6:
            st.append([round(t, 4), round(t + period, 4), foot]); t += period; foot = "L" if foot == "R" else "R"
        return st, foot
    steps, foot = walk_steps(TW0, t_ns + 0.25)
    # 振り返る（2 歩：寺島さん側の左足から）・戻る（2 歩）
    steps += [[round(t_oturn0, 4), round(t_oturn0 + 0.45, 4), "L"], [round(t_oturn0 + 0.45, 4), round(t_oturn0 + 0.9, 4), "R"]]
    steps += [[round(t_oback0, 4), round(t_oback0 + 0.45, 4), "R"], [round(t_oback0 + 0.45, 4), round(t_oback0 + 0.9, 4), "L"]]
    # 寄せる間：根が動く／回る間は 0.45 秒ごとに交互に踏む（最後にそろえる 1 歩）
    mv = []
    prev = None
    for f in range(int(t_man0 * FPS), NF + 1):
        r = nurse_rows[f]
        if prev is not None: mv.append((r[0], math.hypot(r[1] - prev[1], r[2] - prev[2]) / DT + abs(r[3] - prev[3]) / DT * 0.01))
        prev = r
    moving = [t for t, v in mv if v > 0.004]
    if moving:
        t, ft, tend = moving[0] - 0.05, "R", moving[-1]
        while t < tend + 0.3:
            steps.append([round(t, 4), round(t + 0.45, 4), ft]); t += 0.45; ft = "L" if ft == "R" else "R"
        steps.append([round(t, 4), round(t + 0.45, 4), ft])
    steps.sort(key=lambda s: s[0])

    # ---------- 大城さんの手：右手は振り返る間はなす。左手は世界に止めた握り
    gz = WC_AHEAD - GRIP_Z
    py = GRIP_Y + GRIP_R + 0.018
    gl_world = [round(GRIP_X, 4), round(py, 4), round(Z_NS - (gz - 0.05), 4)]
    L_target = [[0, "grip_l"], [round(t_oturn0 - 0.02, 4), "grip_l_w", 0.01], [round(t_oback1, 4), "grip_l", 0.01]]
    # 右手：はなす時は握りの上へ上げてから下ろす・握り直す時は上から下ろしてのせる（握りの筒を通らない）
    R_w = [[0, 1.0], [round(t_rel0 + 0.35, 4), 1.0], [round(t_rel1 + 0.35, 4), 0.0], [round(t_regrip0, 4), 0.0], [round(t_regrip0 + 0.55, 4), 1.0]]
    R_target = [[0, "grip_r"], [round(t_rel0, 4), "grip_r_up", 0.35], [round(t_regrip0 - 0.05, 4), "grip_r_up", 0.01], [round(t_regrip0 + 0.55, 4), "grip_r", 0.4]]
    R_curl = [[0, 30.0], [round(t_rel0, 4), 30.0], [round(t_rel1, 4), 8.0], [round(t_regrip0, 4), 8.0], [round(t_regrip1, 4), 30.0]]
    spine = [[0, SPINE], [round(t_oturn0, 4), SPINE], [round(t_oturn1, 4), 2.0], [round(t_oback0, 4), 2.0], [round(t_oback1, 4), SPINE]]
    chest = [[0, CHEST], [round(t_oturn0, 4), CHEST], [round(t_oturn1, 4), 1.0], [round(t_oback0, 4), 1.0], [round(t_oback1, 4), CHEST]]
    walk = [[0, 0], [TW0, 0], [TW0 + 0.4, 1], [round(t_dec0 + 0.6, 4), 1], [round(t_ns, 4), 0]]

    # ---------- 顔の向き：寺島さんを見る（体から 30° 以内）・ハコブくんを見る
    EYE_Y = 1.50
    t_head = (t_oturn0 + 0.2, t_oturn1)
    def look_yaw(nx_, nz_, byaw, tx, tz):
        want = math.degrees(math.atan2(tx - nx_, tz - nz_)); return ((want - byaw + 180) % 360) - 180
    hy = [[0, 0.0], [round(t_head[0], 4), 0.0]]
    hn = [[0, 8.0], [round(t_head[0], 4), 8.0], [round(t_head[1], 4), 0.0]]
    o_to_t = look_yaw(0.0, Z_NS, 180.0 - O_TURN, T_X - 0.05, z_tstop)
    o_to_t = max(-30.0, min(30.0, o_to_t))
    hy.append([round(t_head[1], 4), round(o_to_t, 3)])
    # 立ち話のうなずき（聞く側）・話す（口だけ talk）
    talk_o, talk_t = [[0, 0]], [[0, 0]]
    nod_o, nod_t = [], []
    t_talk0 = on2["V2"] + clips["V2"]["dur"] + 0.6
    t_talk_end_o = cue_end + 0.1
    t_talk_end_t = on2["V8"] if not stuck else t_tlook0 - 0.1
    t, who = t_talk0, "t"
    while t < max(t_talk_end_o, t_talk_end_t) - 0.5:
        L = 2.6 if who == "t" else 2.2
        if who == "t" and t < t_talk_end_t - 0.3:
            talk_t += [[round(t, 4), 1], [round(min(t + L, t_talk_end_t - 0.1), 4), 0]]
            if t + 1.2 < t_talk_end_o: nod_o.append(t + 1.0)
        elif who == "o" and t < t_talk_end_o - 0.3:
            talk_o += [[round(t, 4), 1], [round(min(t + L, t_talk_end_o - 0.1), 4), 0]]
            if t + 1.2 < t_talk_end_t: nod_t.append(t + 1.1)
        t += L + 0.5; who = "o" if who == "t" else "t"
    for tn in nod_o:
        hn += [[round(tn, 4), 0.0], [round(tn + 0.25, 4), 7.0], [round(tn + 0.55, 4), 0.0]]
    hn.sort(key=lambda r: r[0])
    # 気づく
    o_to_r = look_yaw(0.0, Z_NS, 180.0, x_rstop, z_rstop + ROBOT_FRONT)
    hy += [[round(t_olook0, 4), round(o_to_t, 3)], [round(t_olook1, 4), round(o_to_r - (180.0 - (180.0 - O_TURN)), 3)],
           [round(t_oback0, 4), round(o_to_r - O_TURN, 3)], [round(t_oback1, 4), round(o_to_r, 3)],
           [round(t_olookback0, 4), round(o_to_r, 3)], [round(t_olookback1, 4), 0.0]]
    hn += [[round(t_olook0, 4), 0.0], [round(t_olook1, 4), 4.0], [round(t_olookback1, 4), 8.0]]
    hy.sort(key=lambda r: r[0]); hn.sort(key=lambda r: r[0])
    mouth_o = [[0, "flat"], [round(on2["V2"] - 0.2, 4), "smile"]]

    # ---------- 寺島さんの道
    t_rows = []
    zr = Z_NS + T_RET[1]; xr = T_RET[0]
    ret_yaw = 0.0                                                              # 下がる向き（+z）
    for f in range(NF + 1):
        t = f * DT
        if t < t_tr0: x, z, y = tera_x(t), tera_z(t), tera_yaw0(t)
        elif t < t_tr1: x, z, y = T_X, z_tstop, YAW_FACE_O + (((ret_yaw - YAW_FACE_O + 180) % 360) - 180) * smooth((t - t_tr0) / TR_TURN1)
        elif t < t_tr2:
            u = smooth((t - t_tr1) / TR_WALK); x, z, y = T_X, z_tstop + (zr - z_tstop) * u, ret_yaw
        else:
            u = (t - t_tr2) / TR_TURN2
            x, z, y = T_X + (xr - T_X) * smooth(2 * u - 1), zr, ret_yaw + (((270.0 - ret_yaw + 180) % 360) - 180) * smooth(u)
        t_rows.append((t, x, z, y))
    tk = lambda i: [[round(r[0], 4), round(r[i], 5), "lin"] for r in t_rows]
    tx_, tz_, ty_ = tk(1), tk(2), tk(3)
    for a in (tx_, tz_, ty_): a[0] = a[0][:2]
    t_steps = []
    tt, ft = 0.2, "R"
    while tt + 0.45 <= t_ts + 0.05:
        t_steps.append([round(tt, 4), round(tt + 0.45, 4), ft]); tt += 0.45; ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tturn1 - 0.2, 4), round(t_tturn1 + 0.25, 4), ft]]
    ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tr0, 4), round(t_tr0 + 0.4, 4), "R"], [round(t_tr0 + 0.4, 4), round(t_tr0 + 0.8, 4), "L"]]
    tt, ft = t_tr1, "R"
    while tt + 0.4 <= t_tr2 + 0.05:
        t_steps.append([round(tt, 4), round(tt + 0.4, 4), ft]); tt += 0.4; ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tr2, 4), round(t_tr2 + 0.4, 4), ft], [round(t_tr2 + 0.4, 4), round(t_tr2 + 0.8, 4), "L" if ft == "R" else "R"]]
    t_steps.sort(key=lambda s: s[0])
    t_walk = [[0, 1], [round(t_v1 + 0.6, 4), 1], [round(t_ts, 4), 0], [round(t_tr1, 4), 0], [round(t_tr1 + 0.3, 4), 0.6], [round(t_tr2 - 0.3, 4), 0.6], [round(t_tr2, 4), 0]]
    # 寺島さんの顔：大城さんの顔を見る（立ち話）。⑨-2 はハコブくんのほうへ −30°（20〜35°）向けて戻す
    def t_look_o(t):
        r = nurse_rows[min(len(nurse_rows) - 1, int(round(t * FPS)))]
        return look_yaw(T_X, z_tstop, YAW_FACE_O, r[1], r[2])
    thy = [[0, 0.0], [round(t_tturn1, 4), 0.0], [round(t_tturn1 + 0.4, 4), round(max(-30, min(30, t_look_o(t_tturn1 + 0.4))), 3)]]
    if stuck:
        base = round(max(-30, min(30, t_look_o(t_tlook0))), 3)
        thy += [[round(t_tlook0, 4), base], [round(t_tlook1, 4), round(base - E("T_LOOK", 30.0), 3)], [round(t_tback0, 4), round(base - E("T_LOOK", 30.0), 3)], [round(t_tback1, 4), base]]
    thy += [[round(t_tr0, 4), round(max(-30, min(30, t_look_o(t_tr0))), 3)], [round(t_tr0 + 0.5, 4), 0.0]]
    thn = [[0, 6.0], [round(t_ts, 4), 0.0]]
    for tn in nod_t: thn += [[round(tn, 4), 0.0], [round(tn + 0.25, 4), 7.0], [round(tn + 0.55, 4), 0.0]]
    thn.sort(key=lambda r: r[0])
    mouth_t = [[0, "flat"], [round(t_v1 - 0.3, 4), "smile"]]

    # ---------- 茂さん
    if stuck:
        m_yaw = [[0, 0.0], [round(t_m_turn0, 4), 0.0], [round(t_m_turn1, 4), M_YAW], [round(m_back0, 4), M_YAW], [round(m_back1, 4), 0.0]]
    else:
        m_yaw = [[0, 0.0], [round(t_mo0, 4), 0.0], [round(t_mo1, 4), M_TURN_O], [round(m_ob0, 4), M_TURN_O], [round(m_ob1, 4), 0.0],
                 [round(t_m3_0, 4), 0.0], [round(t_m3_1, 4), M_YAW3], [round(m_end0, 4), M_YAW3], [round(m_end1, 4), 0.0]]
    m_nod = [[0, 0.0], [round(nod_t0, 4), 0.0], [round(nod_t0 + NOD_DOWN, 4), 10.0], [round(nod_t0 + NOD_DOWN + NOD_HOLD, 4), 10.0], [round(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, 4), 0.0]]
    m_mouth = [[0, "flat"]]

    # ---------- 画面
    scr = [[0, "face"], [q(t_stop + 0.2), "wait"], [q(on2["H2"]), "pass"]]
    if stuck:
        scr += [[q(on2["H2"] + 3.0), "wait"], [q(on2["H2b"]), "pass"], [q(on2["H2b"] + 3.0), "wait"], [q(t30), "stuck"]]
    scr += [[q(t_resume), "face"]]                                   # 依頼237：走り出したら帯を消して「基本」
    if not stuck: scr += [[q(on2["H3"]), "deliv"]]
    scr += [[q(happy_from), "happy"], [q(happy_to), "face"]]
    ring = [[0, "normal"]] + ([[q(t30), "wait"], [q(t_resume), "normal"]] if stuck else [])

    # ---------- 声の並び・口
    tracks = {w: np.zeros(int(DUR * SR) + SR) for w in ("nurse", "robot", "tera", "morita")}
    place = {}
    for k, t0 in on2.items():
        c = clips["H2" if k == "H2b" else k]
        s0 = t0 - c["v0"]; i0 = int(round(s0 * SR))
        tracks[c["who"]][i0:i0 + len(c["x"])] += c["x"]
        place[k] = {"who": c["who"], "file": c["file"], "text": c["text"], "clip_start_s": round(s0, 4), "voice_on_s": round(t0, 4), "voice_off_s": round(t0 + c["dur"], 4),
                    "voice_len_s": round(c["dur"], 4), "clip_len_s": round(c["len"], 4)}
    HOP = SR // FPS
    def frame_rms(x): return np.array([np.sqrt(np.mean(x[i * HOP:(i + 1) * HOP] ** 2)) if i * HOP < len(x) else 0 for i in range(NF)])
    def ladder(who, rest, speak):
        rms = frame_rms(tracks[who])
        ref = np.percentile(rms[rms > 0.01], 90) if (rms > 0.01).any() else 1.0
        lvl = np.convolve(rms / ref, np.ones(3) / 3, mode="same")
        target = np.where(speak, np.digitize(lvl, [0.15, 0.35, 0.65]), 0)
        for i in range(NF):
            if not speak[i]: target[i] = rest[i]
        for i in range(1, NF - 1):
            if target[i] != target[i - 1] and target[i] != target[i + 1]: target[i] = target[i - 1]
        step = np.zeros(NF, int)
        for i in range(NF):
            prev = step[i - 1] if i else rest[0]
            step[i] = prev + int(np.clip(target[i] - prev, -1, 1)) if i % 2 == 0 else prev
        return step
    def speak_mask(names):
        m = np.zeros(NF, bool)
        for k in names:
            if k in on2: m[int(math.floor(on2[k] * FPS)):int(math.ceil(place[k]["voice_off_s"] * FPS))] = True
        return m
    LADDER = ["closed", "small", "mid", "large"]
    robot_mouth = [LADDER[s] for s in ladder("robot", np.full(NF, 2), speak_mask(["H2", "H2b", "H3", "H4", "H5"]))]
    nurse_mouth = [int(s) for s in ladder("nurse", np.zeros(NF, int), speak_mask(["V2", "V8"]))]
    tera_mouth = [int(s) for s in ladder("tera", np.zeros(NF, int), speak_mask(["V1", "T2"]))]
    mor_mouth = [int(s) for s in ladder("morita", np.zeros(NF, int), speak_mask(["M2", "M3", "M4"]))]
    mix = sum(tracks.values())[: int(round(DUR * SR))]
    pk = float(np.max(np.abs(mix))); assert pk < 1.0, pk
    wav_out = os.path.join(os.path.dirname(dst), f"mix237_{variant}.wav")
    w = wave.open(wav_out, "w"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
    w.writeframes((np.clip(mix, -1, 1) * 32767).astype(np.int16).tobytes()); w.close()

    # ---------- カメラ
    zc = z_rstop + 0.7
    zf = z_rstop + ROBOT_FRONT
    CAM = {
        "main": {"pos": [-0.62, 1.72, round(zc - 6.0, 4)], "look": [0.12, 0.8, round(zc + 1.6, 4)], "fov": 38},
        "screen_close": {"follow": "robot", "pos": [x_rstop, 1.23, 1.15], "look": [x_rstop, 0.962, 0.29], "fov": 24},
        "morita_face": {"pos": [-0.42, 1.22, round(Z_NS - WC_AHEAD - 1.25, 4)], "look": [0.02, 1.12, round(Z_NS - WC_AHEAD + 0.02, 4)], "fov": 24},
        "oshiro_face": {"pos": [-0.62, 1.62, round(Z_NS - 1.75, 4)], "look": [0.05, 1.45, round(Z_NS, 4)], "fov": 22},
        "depart": {"pos": [-0.75, 1.70, round(z_rstop - 1.4, 4)], "look": [0.20, 0.75, round(z_rstop + 3.2, 4)], "fov": 46},
        "chk_grip": {"pos": [0.05, 1.55, round(Z_NS + 0.75, 4)], "look": [0.10, 0.95, round(Z_NS - 0.25, 4)], "fov": 40},
    }
    # 依頼237：235 の⑩の切りかえ（茂さんの顔→画面→本番）を、新しいやり取りに使う（茂さんが話す時は茂さんの顔・ハコブくんが答える時は画面）
    cuts = [[0, "main"], [q(t_stop - 0.1), "screen_close"], [q(t_stop + 1.6), "main"],
            [q(on2["H2"] - 0.15), "screen_close"]]
    if stuck:
        cuts += [[q(endH2 + 0.15), "main"], [q(on2["H2b"] - 0.15), "screen_close"], [q(on2["H2b"] + clips["H2"]["dur"] + 0.15), "main"],
                 [q(on2["M4"] - 0.35), "morita_face"], [q(on2["H4"] - 0.15), "screen_close"], [q(endH4 + 0.4), "main"],
                 [q(t30 - 0.1), "screen_close"], [q(t30 + 1.0), "main"]]
    else:
        cuts += [[q(endH2 + 0.15), "morita_face"]]
    cuts += [[q(t_olook0 - 0.1), "oshiro_face"], [q(endV8 + 0.35), "main"]]
    # 依頼237：通る時にハコブくんが話す所も、235 と同じくハコブくんが話す時は画面の寄り（screen_close はハコブくんに付いて動く）→ 目まで笑う顔が終わったら本番
    #（茂さんの顔のカメラはハコブくんの通る所に置いてあるので、通る間は使わない）
    cuts += [[q(on2["H5" if stuck else "H3"] - 0.15), "screen_close"], [q(happy_to + 0.15), "main"]]
    cuts.sort(key=lambda c: c[0])
    stills = [[q(t_v1 + 0.3), "main", "s01_terashima_calls"], [q(on2["V2"] + 1.0), "main", "s02_three_talk"],
              [q(t_stop + 0.1), "main", "s03_robot_stopped_main"], [q(t_stop + 0.8), "screen_close", "s04_robot_stopped_close"],
              [q(on2["H2"] + 0.8), "screen_close", "s07_toorimasu"], [q(t_man0 + 0.5 * MAN_T), "main", "s09_shift_main"],
              [q(t_man0 + 0.5 * MAN_T), "top", "s09_shift_top"], [q(t_resume + 2.5), "main", "s10_pass_main"], [q(t_oturn1 + 0.3), "chk_grip", "chk_grip_turned"],
              [q(t_man0 + 1.0), "chk_grip", "chk_grip_man"]]
    if stuck: stills += [[q(t30 + 0.5), "screen_close", "s08_toremasen"], [q(t30 + 1.5), "main", "s08_stuck_label"],
                         [q(on2["M4"] + 0.8), "morita_face", "s11_morita_matasare"], [q(happy_from + 0.5), "screen_close", "s13_arigato_happy"],
                         [q(happy_from + 0.5), "main", "s13_arigato_main"]]
    else: stills += [[q(on2["V8"] + 0.4), "oshiro_face", "s08_oshiro_notices"], [q(on2["M2"] + 1.0), "morita_face", "s11_morita_tooru"],
                     [q(on2["M3"] + 0.6), "main", "s12_morita_nanida"], [q(on2["H3"] + 0.6), "screen_close", "s13_otodokechu"],
                     [q(happy_from + 0.5), "screen_close", "s13_arigato_happy"], [q(happy_from + 0.5), "main", "s13_arigato_main"]]
    # 早回し（⑨-2：声と動きの無い所。×4）
    ff = []
    if stuck:
        # 依頼237：10〜20 秒の間（235 のまま）と、6（ハコブ「はい、お待ちしています」）のあとから 30 秒の手前まで。5・6 は 1 倍
        ff = [[round(on2["H2"] + 3.4, 3), round(on2["H2b"] - 0.6, 3)], [round(max(endH4, m_back1) + 0.6, 3), round(t30 - 0.6, 3)]]
        ff = [[a, b] for a, b in ff if b - a >= 1.0]
    shot = {"name": variant, "about": "⑨ 車いすが廊下の真ん中で止まる（依頼237：" + ("⑨-2 立ち往生になる" if stuck else "⑨-1 声をかけて通る") + "）", "origin": O, "duration": DUR, "video": True,
            "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]},
            "box_events": [], "card_events": [], "presses": [], "card": False,
            "check_open": [], "check_close": [], "check_above": [], "transitions": [],
            "robot_start_z": RZ0, "swing_ramp": 0.15, "lift_pow": 0.5,
            "nurse": {"x": keys_x, "z": keys_z, "yaw": keys_yaw, "walk": walk, "spine": spine, "chest": chest,
                      "head_yaw": hy, "head_nod": hn, "mouth": mouth_o, "talk": talk_o,
                      "L_w": [[0, 1.0]], "R_w": R_w, "L_target": L_target, "R_target": R_target,
                      "L_curl": [[0, 30.0]], "R_curl": R_curl, "L_thumb": [[0, 20.0]], "R_thumb": [[0, 20.0]],
                      "L_hint": [[0, "push_l"]], "R_hint": [[0, "push_r"]], "L_hint_w": [[0, 0.5]], "R_hint_w": [[0, 0.5]]},
            "steps": steps, "look_windows": [], "cameras": CAM, "cuts": cuts, "stills": stills,
            "c237": {"wc_ahead_m": round(WC_AHEAD, 4), "video_from": TV0, "video_to": round((NF - 1) * DT, 4),
                     "chair": chair_rows, "grip_both": [1 if g else 0 for g in grip_both],
                     "screen": scr, "ring": ring, "ring_wait_color": "#F2C230", "happy": [round(happy_from, 4), round(happy_to, 4)], "beside_used": [round(bs[0], 4), round(bs[1], 4)], "h3_arigato_s": round(H3_ARIGATO, 4),
                     "stuck_label": [round(t30, 4), round(t30 + 3.0, 4)] if stuck else None, "ff": ff, "ff_speed": 4,
                     "robot_mouth": robot_mouth, "nurse_mouth": nurse_mouth, "tera_mouth": tera_mouth, "morita_mouth_lvl": mor_mouth, "nurse_mouth_scale": [1.0, 1.2, 1.8, 2.4],
                     "morita": {"head_yaw": m_yaw, "head_nod": m_nod, "mouth": m_mouth, "neck_share": 0.4,
                                "blink": {"every_min_s": 3.0, "every_max_s": 5.0, "close_s": 0.15, "seed": 228}, "eye_min_scale": 0.1},
                     "lines": place, "grip": {"x": GRIP_X, "y": GRIP_Y, "z_behind_root": GRIP_Z, "r": GRIP_R},
                     "man": {"t0": round(t_man0, 4), "t1": round(t_man1, 4), "path_file": os.path.basename(pathjs), "segs": P["segs"], "v_max": V_MAX, "w_max": W_MAX},
                     "tera_ret": {"x": xr, "z": round(zr, 4), "from": [round(T_X, 4), round(z_tstop, 4)], "t": [round(t_tr0, 4), round(t_tr3, 4)]},
                     "times": {k: (round(v, 4) if isinstance(v, float) else v) for k, v in ev.items()}}}
    tshot = {"name": variant + "__tera", "about": "寺島さん（" + variant + "）", "origin": O, "duration": DUR, "video": True,
             "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]}, "box_events": [], "card_events": [], "presses": [], "card": False,
             "check_open": [], "check_close": [], "check_above": [], "transitions": [], "swing_ramp": 0.15, "lift_pow": 0.5,
             "nurse": {"x": tx_, "z": tz_, "yaw": ty_, "walk": t_walk, "spine": [[0, 2.0]], "chest": [[0, 1.0]],
                       "head_yaw": thy, "head_nod": thn, "mouth": mouth_t, "talk": talk_t, "L_w": [[0, 0.0]], "R_w": [[0, 0.0]]},
             "steps": t_steps}
    info = {"variant": variant, "duration": DUR, "t_stop": t_stop, "happy": [round(happy_from, 3), round(happy_to, 3)], "beside": [round(bs[0], 3), round(bs[1], 3)], "on": {k: round(v, 3) for k, v in on2.items()}, "man": [round(t_man0, 3), round(t_man1, 3), round(MAN_T, 3)],
            "stuck_est": round(t_resume_est - t_stop, 3), "t_tr": [round(t_tr0, 3), round(t_tr3, 3)], "ff": ff}
    return shot, tshot, info

out = {k: S[k] for k in ("fps", "width", "height", "supersample", "colors", "light", "rooms", "box", "bag", "nurse", "targets", "card", "pocket", "screen_ui", "drawer_parts", "hints", "check_stand_parts", "corridor")}
out["about"] = "依頼237：⑨ 車いすが廊下の真ん中で止まる（場面 stop_voice・stop_stuck、寺島さんは __tera）。make_script237.py（make_script235.py の写し）が作った。廊下・色・光・看護師・画面の値は 175 の台本から写した"
out["nurse"] = dict(out["nurse"]); out["nurse"]["walk"] = dict(out["nurse"]["walk"])
out["nurse"]["walk"].update({"amp_deg": 11.0, "knee_deg": 24, "bob_m": 0.008, "lift_m": 0.05})
gz = WC_AHEAD - GRIP_Z
out["targets"] = dict(out["targets"])
py = GRIP_Y + GRIP_R + 0.018
out["targets"]["grip_l"] = {"ref": "nurse", "pos": [round(-GRIP_X, 4), round(py, 4), round(gz - 0.05, 4)], "finger_frame": "nurse", "finger": [-1.0, -0.35, 1], "palm_frame": "nurse", "palm": [0.3, -1, 0.0]}
out["targets"]["grip_r"] = {"ref": "nurse", "pos": [round(GRIP_X, 4), round(py, 4), round(gz - 0.05, 4)], "finger_frame": "nurse", "finger": [1.0, -0.35, 1], "palm_frame": "nurse", "palm": [-0.3, -1, 0.0]}
# 振り返る間の左手：止まった時（大城さんの根 x 0・z Z_NS・向き 180°）の grip_l と同じ点・同じ向きを、世界に止める
out["targets"]["grip_r_up"] = {"ref": "nurse", "pos": [round(GRIP_X + 0.03, 4), round(py + 0.15, 4), round(gz - 0.20, 4)], "finger_frame": "nurse", "finger": [1.0, -0.35, 1], "palm_frame": "nurse", "palm": [-0.3, -1, 0.0]}
out["targets"]["grip_l_w"] = {"ref": "world", "pos": [round(GRIP_X, 4), round(py, 4), round(Z_NS - (gz - 0.05), 4)], "finger_frame": "world", "finger": [1.0, -0.35, -1], "palm_frame": "world", "palm": [-0.3, -1, 0.0]}
out["hints"] = dict(out["hints"]); out["hints"]["push_l"] = [-0.40, 1.0, -0.20]; out["hints"]["push_r"] = [0.40, 1.0, -0.20]
out["robot_rule"] = RULE
shots, infos = [], []
for v in ("stop_voice", "stop_stuck"):
    a, b, i = build(v); shots += [a, b]; infos.append(i)
out["shots"] = shots
out["c237_common"] = {"z_ns": Z_NS, "t_ns": round(t_ns, 4), "t_v1": round(t_v1, 4), "nz0": NZ0, "tz0": round(TZ0, 4), "t_x": round(T_X, 4), "t_dz": T_DZ, "o_turn": O_TURN,
                      "z_tstop": round(z_tstop, 4), "t_ts": round(t_ts, 4), "yaw_face_o": round(YAW_FACE_O, 3), "man_T": round(MAN_T, 3), "t_stop_used": t_stop, "robot_stop_z_used": z_rstop}
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=0)
print(json.dumps({"common": out["c237_common"], "shots": infos}, ensure_ascii=False))
```

#### tools/run237.sh（依頼237）

```bash
#!/bin/bash
# 依頼237 使い方: run237.sh <出力フォルダ> <場面 stop_voice|stop_stuck> <台本（絶対パス か Closeups/ の名前）> <コマ on|off> [静止画 on|off] [views] [until]
OUT="$1"; SH="$2"; SC="$3"; FR="${4:-off}"; ST="${5:-off}"; VW="${6:-main,top}"; UNTIL="${7:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup237.Run \
   -c237Out "$OUT" -c237Shot "$SH" -c237Script "$SC" -c237Frames "$FR" -c237Stills "$ST" -c237Views "$VW" -c237Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

#### tools/run237b.sh（依頼237）

```bash
#!/bin/bash
# 依頼237 区切って撮る（Unity は 13 分ほどで止められるので 1 回を短く）: run237b.sh <出力フォルダ> <場面> <台本> <from 秒> <to 秒（1e9＝終わりまで）> [stills on|off]
OUT="$1"; SH="$2"; SC="$3"; FROM="$4"; TO="$5"; ST="${6:-on}"
UNTIL=$(python3 -c "print($TO + 0.05 if $TO < 1e8 else 1e9)")
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup237.Run \
   -c237Out "$OUT" -c237Shot "$SH" -c237Script "$SC" -c237Frames on -c237Stills "$ST" -c237Views main,top -c237From "$FROM" -c237To "$TO" -c237Until "$UNTIL" -logFile "$OUT/unity_${FROM}_${TO}.log"
echo "exit $?"
```

#### tools/screen237.py（依頼237）

```python
#!/usr/bin/env python3
"""依頼237：「通れません」の画面の絵（screen235.py を写して変えた）。
・c237_stuck_band.png：帯（黄 #F2C230）「通れません」だけ（帯の下は透明＝顔の板のふだんの大きさの顔が見える。228・235 の帯だけの絵と同じ描き方）
・face237_trouble_{albedo,emission}.png：顔の板の絵（ふだんの大きさ）を、235 の困り顔（hakobu.py の表情集 trouble＝目 open・困り眉・口 frown）にしたもの。
  screen218.py の faces() と同じ作り：もとの顔の絵 hakobu_albedo/emission の口を消して frown の口（face175 と同じ写し方）を描き、
  目（もとの絵の open の目）の上に hakobu.py の困り眉を、目の箱の幅の比（happy の目と同じ写し方）で描く（光は happy と同じ付け方）
確かめ：同じ描き方で「お届け完了」を描くと c223_done_band.png と同じになること・「通れません」の帯は c235_stuck.png の帯の行と同じ画素になること
使い方：python3 screen237.py <台本の JSON（screen_ui）> <Textures フォルダ> <screen218.py のフォルダ> <hakobu.py のフォルダ> <hakobu_albedo.png のフォルダ> <出力フォルダ>"""
import importlib.util, json, sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
js = json.load(open(sys.argv[1])); tex = Path(sys.argv[2]); s218dir, hkdir, hdir, out = sys.argv[3], sys.argv[4], sys.argv[5], Path(sys.argv[6])
spec = importlib.util.spec_from_file_location("s218", str(Path(s218dir) / "screen218.py")); m = importlib.util.module_from_spec(spec)
argv0 = sys.argv; sys.argv = sys.argv[:1]; spec.loader.exec_module(m); sys.argv = argv0
S = js["screen_ui"]
def band(text, k=0.46, color=None, full=False):
    W = int(S["tex_w"]); H = int(round(W / float(S["aspect"]))); R = int(S["corner_r"] * H)
    mask = Image.new("L", (W, H), 0); ImageDraw.Draw(mask).rounded_rectangle([0, 0, W - 1, H - 1], radius=R, fill=255)
    bh = int(0.2 * H)
    img = Image.new("RGBA", (W, H), m.hexc(S["bg"])); d = ImageDraw.Draw(img)
    d.rectangle([0, 0, W, bh], fill=m.hexc(color or S["band"], int(S.get("band_alpha", 235))))
    d.text((W // 2, bh // 2), text, font=m.font(bh * k), fill=m.hexc(S["fg"]) if color is None else (30, 30, 30, 255), anchor="mm")
    a = img.split()[3]; img.putalpha(Image.composite(a, Image.new("L", (W, H), 0), mask))
    b = np.array(img)
    if not full: b[bh + 1:, :, :] = 0
    return b, bh
ref = np.array(Image.open(tex / "c223_done_band.png").convert("RGBA"))
chk, _ = band("お届け完了")
print("確かめ：お届け完了を描くと c223_done_band と同じ", chk.shape == ref.shape and bool((chk == ref).all()))
b, bh = band("通れません", color="#F2C230")
old = np.array(Image.open(tex / "c235_stuck.png").convert("RGBA"))
print("確かめ：帯の行（0〜%d）が c235_stuck.png と同じ" % bh, bool((b[:bh + 1] == old[:bh + 1]).all()), "・帯の下は透明", int(b[bh + 1:, :, 3].max()) == 0)
Image.fromarray(b).save(out / "c237_stuck_band.png"); print("作った絵: c237_stuck_band.png 通れません（黄・帯だけ）")

# ---------------- 顔の板の困り顔
spec = importlib.util.spec_from_file_location("hk237", str(Path(hkdir) / "hakobu.py")); hk = importlib.util.module_from_spec(spec); spec.loader.exec_module(hk)
ex = hk.EXPR["trouble"]; print("表情集 trouble:", ex)
SSF = m.SSF
def brow_tex_mask():
    """hakobu.py の brow_mask("trouble")（画面での向き：外側 (x0−1, y0−6) → 内側 (x1+2, y0−13)・太さ 3.5）を、
    もとの顔の絵の目の箱へ写す。倍率は目の幅の比（happy_eye_mask と同じ）、内側＝顔の真ん中の側"""
    big = Image.new("L", (1024 * SSF, 1024 * SSF), 0); d = ImageDraw.Draw(big)
    bx = hk.V_EYE_LEFT; hw = bx[2] - bx[0]; ey0 = bx[1] + hk.EYE_SHIFT
    cxm = (m.EYES[0][1] + m.EYES[1][0]) / 2
    for x0, x1, y0, y1 in m.EYES:
        s = (x1 - x0) / hw
        left = x1 < cxm                                   # 画面の左の目（内側は x1 の側）
        if left: outer, inner = (x0 - 1 * s, y0 - 6 * s), (x1 + 2 * s, y0 - 13 * s)
        else: outer, inner = (x1 + 1 * s, y0 - 6 * s), (x0 - 2 * s, y0 - 13 * s)
        r = 3.5 * s * SSF / 2
        for t in np.linspace(0, 1, 600):
            x = outer[0] + (inner[0] - outer[0]) * t; y = outer[1] + (inner[1] - outer[1]) * t
            d.ellipse([x * SSF - r, y * SSF - r, x * SSF + r, y * SSF + r], fill=255)
    return np.array(big.resize((1024, 1024), Image.LANCZOS)).astype(float) / 255.0
e = brow_tex_mask()
halo = np.array(Image.fromarray((e * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(5.0))).astype(float) / 255.0
for name in ("albedo", "emission"):
    bgc, blue, white = m.COLS[name]
    a0 = np.array(Image.open(f"{hdir}/hakobu_{name}.png").convert("RGB")).astype(float)
    o = a0.copy(); o[333:415, 186:326] = bgc                         # 口を消す（face175.py・screen218.py と同じ範囲）
    mm = m.mouth_tex_mask(hk, ex["rest"])[..., None]; o = o * (1 - mm) + np.array(blue, float) * mm    # frown の口
    hcol = np.array((150, 160, 172) if name == "albedo" else (90, 92, 96), float)
    o = o * (1 - halo[..., None] * 0.55) + hcol * halo[..., None] * 0.55
    o = o * (1 - e[..., None]) + np.array(white, float) * e[..., None]
    Image.fromarray(np.clip(o + 0.5, 0, 255).astype(np.uint8)).save(out / f"face237_trouble_{name}.png")
# 確かめ：目の所（もとの目の箱）は もとの絵のまま＝目の大きさはふだんと同じ
a0 = np.array(Image.open(f"{hdir}/hakobu_albedo.png").convert("RGB")); a1 = np.array(Image.open(out / "face237_trouble_albedo.png").convert("RGB"))
for x0, x1, y0, y1 in m.EYES:
    print("確かめ：目の箱", (x0, x1, y0, y1), "の画素がもとの絵と同じ", bool((a0[y0:y1 + 1, x0:x1 + 1] == a1[y0:y1 + 1, x0:x1 + 1]).all()))
ys, xs = np.nonzero(e > 0.5); print("眉の範囲 x %d〜%d・y %d〜%d" % (xs.min(), xs.max(), ys.min(), ys.max()))
print("作った絵: face237_trouble_{albedo,emission}.png")
```

#### geo/path235.json（依頼237）

```json
{"G": 2.3, "margin": 0.05, "back_max": 1.0, "turns": 7, "time_s": 12.95, "fwd_axle_m": 0.822, "back_axle_m": 0.054, "footrest_to_robot_min_m": 0.628, "rail_gap_min_m": 0.051, "heading_max_deg": 17.0, "segs": ["回る→(x +0.000, z +0.000, 向き +12°)", "前へ→(x +0.175, z -0.822, 向き +12°)", "回る→(x +0.175, z -0.822, 向き -17°)", "後ろへ→(x +0.385, z -0.133, 向き -17°)", "回る→(x +0.385, z -0.133, 向き -10°)", "後ろへ→(x +0.418, z +0.054, 向き -10°)", "回る→(x +0.418, z +0.054, 向き +0°)"], "path": [[0.0, 0.0, 0.0, ""], [0.0, 0.0, 1.0, "r"], [0.0, 0.0, 2.0, "r"], [0.0, 0.0, 3.0, "r"], [0.0, 0.0, 4.0, "r"], [0.0, 0.0, 5.0, "r"], [0.0, 0.0, 6.0, "r"], [0.0, 0.0, 7.0, "r"], [0.0, 0.0, 8.0, "r"], [0.0, 0.0, 9.0, "r"], [0.0, 0.0, 10.0, "r"], [0.0, 0.0, 11.0, "r"], [0.0, 0.0, 12.0, "r"], [0.0021, -0.0098, 12.0, "f"], [0.0042, -0.0196, 12.0, "f"], [0.0062, -0.0293, 12.0, "f"], [0.0083, -0.0391, 12.0, "f"], [0.0104, -0.0489, 12.0, "f"], [0.0125, -0.0587, 12.0, "f"], [0.0146, -0.0685, 12.0, "f"], [0.0166, -0.0783, 12.0, "f"], [0.0187, -0.088, 12.0, "f"], [0.0208, -0.0978, 12.0, "f"], [0.0229, -0.1076, 12.0, "f"], [0.0249, -0.1174, 12.0, "f"], [0.027, -0.1272, 12.0, "f"], [0.0291, -0.1369, 12.0, "f"], [0.0312, -0.1467, 12.0, "f"], [0.0333, -0.1565, 12.0, "f"], [0.0353, -0.1663, 12.0, "f"], [0.0374, -0.1761, 12.0, "f"], [0.0395, -0.1858, 12.0, "f"], [0.0416, -0.1956, 12.0, "f"], [0.0437, -0.2054, 12.0, "f"], [0.0457, -0.2152, 12.0, "f"], [0.0478, -0.225, 12.0, "f"], [0.0499, -0.2348, 12.0, "f"], [0.052, -0.2445, 12.0, "f"], [0.0541, -0.2543, 12.0, "f"], [0.0561, -0.2641, 12.0, "f"], [0.0582, -0.2739, 12.0, "f"], [0.0603, -0.2837, 12.0, "f"], [0.0624, -0.2934, 12.0, "f"], [0.0645, -0.3032, 12.0, "f"], [0.0665, -0.313, 12.0, "f"], [0.0686, -0.3228, 12.0, "f"], [0.0707, -0.3326, 12.0, "f"], [0.0728, -0.3424, 12.0, "f"], [0.0748, -0.3521, 12.0, "f"], [0.0769, -0.3619, 12.0, "f"], [0.079, -0.3717, 12.0, "f"], [0.0811, -0.3815, 12.0, "f"], [0.0832, -0.3913, 12.0, "f"], [0.0852, -0.401, 12.0, "f"], [0.0873, -0.4108, 12.0, "f"], [0.0894, -0.4206, 12.0, "f"], [0.0915, -0.4304, 12.0, "f"], [0.0936, -0.4402, 12.0, "f"], [0.0956, -0.4499, 12.0, "f"], [0.0977, -0.4597, 12.0, "f"], [0.0998, -0.4695, 12.0, "f"], [0.1019, -0.4793, 12.0, "f"], [0.104, -0.4891, 12.0, "f"], [0.106, -0.4989, 12.0, "f"], [0.1081, -0.5086, 12.0, "f"], [0.1102, -0.5184, 12.0, "f"], [0.1123, -0.5282, 12.0, "f"], [0.1144, -0.538, 12.0, "f"], [0.1164, -0.5478, 12.0, "f"], [0.1185, -0.5575, 12.0, "f"], [0.1206, -0.5673, 12.0, "f"], [0.1227, -0.5771, 12.0, "f"], [0.1247, -0.5869, 12.0, "f"], [0.1268, -0.5967, 12.0, "f"], [0.1289, -0.6065, 12.0, "f"], [0.131, -0.6162, 12.0, "f"], [0.1331, -0.626, 12.0, "f"], [0.1351, -0.6358, 12.0, "f"], [0.1372, -0.6456, 12.0, "f"], [0.1393, -0.6554, 12.0, "f"], [0.1414, -0.6651, 12.0, "f"], [0.1435, -0.6749, 12.0, "f"], [0.1455, -0.6847, 12.0, "f"], [0.1476, -0.6945, 12.0, "f"], [0.1497, -0.7043, 12.0, "f"], [0.1518, -0.714, 12.0, "f"], [0.1539, -0.7238, 12.0, "f"], [0.1559, -0.7336, 12.0, "f"], [0.158, -0.7434, 12.0, "f"], [0.1601, -0.7532, 12.0, "f"], [0.1622, -0.763, 12.0, "f"], [0.1643, -0.7727, 12.0, "f"], [0.1663, -0.7825, 12.0, "f"], [0.1684, -0.7923, 12.0, "f"], [0.1705, -0.8021, 12.0, "f"], [0.1726, -0.8119, 12.0, "f"], [0.1746, -0.8216, 12.0, "f"], [0.1746, -0.8216, 11.0, "r"], [0.1746, -0.8216, 10.0, "r"], [0.1746, -0.8216, 9.0, "r"], [0.1746, -0.8216, 8.0, "r"], [0.1746, -0.8216, 7.0, "r"], [0.1746, -0.8216, 6.0, "r"], [0.1746, -0.8216, 5.0, "r"], [0.1746, -0.8216, 4.0, "r"], [0.1746, -0.8216, 3.0, "r"], [0.1746, -0.8216, 2.0, "r"], [0.1746, -0.8216, 1.0, "r"], [0.1746, -0.8216, 0.0, "r"], [0.1746, -0.8216, -1.0, "r"], [0.1746, -0.8216, -2.0, "r"], [0.1746, -0.8216, -3.0, "r"], [0.1746, -0.8216, -4.0, "r"], [0.1746, -0.8216, -5.0, "r"], [0.1746, -0.8216, -6.0, "r"], [0.1746, -0.8216, -7.0, "r"], [0.1746, -0.8216, -8.0, "r"], [0.1746, -0.8216, -9.0, "r"], [0.1746, -0.8216, -10.0, "r"], [0.1746, -0.8216, -11.0, "r"], [0.1746, -0.8216, -12.0, "r"], [0.1746, -0.8216, -13.0, "r"], [0.1746, -0.8216, -14.0, "r"], [0.1746, -0.8216, -15.0, "r"], [0.1746, -0.8216, -16.0, "r"], [0.1746, -0.8216, -17.0, "r"], [0.1776, -0.8121, -17.0, "b"], [0.1805, -0.8025, -17.0, "b"], [0.1834, -0.793, -17.0, "b"], [0.1863, -0.7834, -17.0, "b"], [0.1893, -0.7738, -17.0, "b"], [0.1922, -0.7643, -17.0, "b"], [0.1951, -0.7547, -17.0, "b"], [0.198, -0.7451, -17.0, "b"], [0.201, -0.7356, -17.0, "b"], [0.2039, -0.726, -17.0, "b"], [0.2068, -0.7165, -17.0, "b"], [0.2097, -0.7069, -17.0, "b"], [0.2127, -0.6973, -17.0, "b"], [0.2156, -0.6878, -17.0, "b"], [0.2185, -0.6782, -17.0, "b"], [0.2214, -0.6686, -17.0, "b"], [0.2243, -0.6591, -17.0, "b"], [0.2273, -0.6495, -17.0, "b"], [0.2302, -0.6399, -17.0, "b"], [0.2331, -0.6304, -17.0, "b"], [0.236, -0.6208, -17.0, "b"], [0.239, -0.6113, -17.0, "b"], [0.2419, -0.6017, -17.0, "b"], [0.2448, -0.5921, -17.0, "b"], [0.2477, -0.5826, -17.0, "b"], [0.2507, -0.573, -17.0, "b"], [0.2536, -0.5634, -17.0, "b"], [0.2565, -0.5539, -17.0, "b"], [0.2594, -0.5443, -17.0, "b"], [0.2624, -0.5348, -17.0, "b"], [0.2653, -0.5252, -17.0, "b"], [0.2682, -0.5156, -17.0, "b"], [0.2711, -0.5061, -17.0, "b"], [0.2741, -0.4965, -17.0, "b"], [0.277, -0.4869, -17.0, "b"], [0.2799, -0.4774, -17.0, "b"], [0.2828, -0.4678, -17.0, "b"], [0.2857, -0.4582, -17.0, "b"], [0.2887, -0.4487, -17.0, "b"], [0.2916, -0.4391, -17.0, "b"], [0.2945, -0.4296, -17.0, "b"], [0.2974, -0.42, -17.0, "b"], [0.3004, -0.4104, -17.0, "b"], [0.3033, -0.4009, -17.0, "b"], [0.3062, -0.3913, -17.0, "b"], [0.3091, -0.3817, -17.0, "b"], [0.3121, -0.3722, -17.0, "b"], [0.315, -0.3626, -17.0, "b"], [0.3179, -0.3531, -17.0, "b"], [0.3208, -0.3435, -17.0, "b"], [0.3238, -0.3339, -17.0, "b"], [0.3267, -0.3244, -17.0, "b"], [0.3296, -0.3148, -17.0, "b"], [0.3325, -0.3052, -17.0, "b"], [0.3355, -0.2957, -17.0, "b"], [0.3384, -0.2861, -17.0, "b"], [0.3413, -0.2766, -17.0, "b"], [0.3442, -0.267, -17.0, "b"], [0.3471, -0.2574, -17.0, "b"], [0.3501, -0.2479, -17.0, "b"], [0.353, -0.2383, -17.0, "b"], [0.3559, -0.2287, -17.0, "b"], [0.3588, -0.2192, -17.0, "b"], [0.3618, -0.2096, -17.0, "b"], [0.3647, -0.2, -17.0, "b"], [0.3676, -0.1905, -17.0, "b"], [0.3705, -0.1809, -17.0, "b"], [0.3735, -0.1714, -17.0, "b"], [0.3764, -0.1618, -17.0, "b"], [0.3793, -0.1522, -17.0, "b"], [0.3822, -0.1427, -17.0, "b"], [0.3852, -0.1331, -17.0, "b"], [0.3852, -0.1331, -16.0, "r"], [0.3852, -0.1331, -15.0, "r"], [0.3852, -0.1331, -14.0, "r"], [0.3852, -0.1331, -13.0, "r"], [0.3852, -0.1331, -12.0, "r"], [0.3852, -0.1331, -11.0, "r"], [0.3852, -0.1331, -10.0, "r"], [0.3869, -0.1233, -10.0, "b"], [0.3886, -0.1134, -10.0, "b"], [0.3904, -0.1036, -10.0, "b"], [0.3921, -0.0937, -10.0, "b"], [0.3938, -0.0839, -10.0, "b"], [0.3956, -0.074, -10.0, "b"], [0.3973, -0.0642, -10.0, "b"], [0.399, -0.0543, -10.0, "b"], [0.4008, -0.0445, -10.0, "b"], [0.4025, -0.0346, -10.0, "b"], [0.4043, -0.0248, -10.0, "b"], [0.406, -0.0149, -10.0, "b"], [0.4077, -0.0051, -10.0, "b"], [0.4095, 0.0048, -10.0, "b"], [0.4112, 0.0146, -10.0, "b"], [0.4129, 0.0245, -10.0, "b"], [0.4147, 0.0343, -10.0, "b"], [0.4164, 0.0442, -10.0, "b"], [0.4181, 0.054, -10.0, "b"], [0.4181, 0.054, -9.0, "r"], [0.4181, 0.054, -8.0, "r"], [0.4181, 0.054, -7.0, "r"], [0.4181, 0.054, -6.0, "r"], [0.4181, 0.054, -5.0, "r"], [0.4181, 0.054, -4.0, "r"], [0.4181, 0.054, -3.0, "r"], [0.4181, 0.054, -2.0, "r"], [0.4181, 0.054, -1.0, "r"], [0.4181, 0.054, 0.0, "r"]]}
```

### 依頼238

#### tools/Closeup238.cs.copy（依頼238）

```csharp
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>
    /// 依頼238：Closeup237.cs を写して、名前だけ 238 に（Closeup238・-c238*・台本の c238・出力 *238.*）。動きの作りは 237 のまま。
    ///   台本 closeup238_script.json（make_script238.py）は ⑨-1（stop_voice）だけ：茂さんのセリフ「大城さん、ロボットさんが通るって」・声をかけるのを止まって 5 秒に
    /// 依頼237：⑨（235）のやり取りを 2 本で分けて作り直した。Closeup235.cs を写して、写した先で変えた。台本は closeup237_script.json（make_script237.py）。場面の名前は 235 と同じ stop_voice・stop_stuck（まばたきの種が同じになる）。
    /// 235 から変えたこと：
    ///   ・画面の stuck：帯（黄）「通れません」だけの絵 c237_stuck_band.png を重ね、顔の板は困り顔 face237_trouble（ふだんの大きさ。ほかの帯の時と同じ顔の板）
    ///   ・画面は台本の c238.screen の時刻のとおり（happy・face も台本から）。235 の「走り出したら目まで笑う顔 1.5 秒」はやめた（走り出しの時刻は 1 回目の Unity の値を台本に入れる）
    ///   ・目まで笑う顔は 224 と同じ（face224_happy_<口>。ハコブくんが話す間も口が動く）
    ///   ・ハコブくんが車いすの横にいる間（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）の時刻を events238.txt と check238.txt に書く
    /// 以下は 235 の説明：
    /// 依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）。場面 stop_voice（⑨-1）・stop_stuck（⑨-2）。Closeup234.cs を写して、写した先で変えた。台本は closeup238_script.json（make_script235.py）。
    /// 234 から変えたこと：
    ///   ・寺島さん（Models_terashima/NurseTerashima.prefab）を置き、2 つめの CloseupDirector で台本の場面 <場面>__tera を動かす（部品の名前 Terashima_ を Nurse_ に替えて CloseupNurse を付ける。共通の部品は変えない）
    ///   ・車いすの根の位置・向きは台本の c235.chair（毎コマ）。両手で握っている間は大城さんの根の前に固く付いた値、立ち話の間は止めた所
    ///   ・ハコブくんの決まりに足した：止まった後、前の物（車いす・茂さん・大城さん・寺島さん）が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す。
    ///     寄った位置（x −0.4643）のまま通り、物の一番後ろを通り過ぎてから x −0.33 へ戻る（依頼235 の答え 3）
    ///   ・画面：c235.screen（face・wait・deliv・pass・stuck・happy）。輪：c235.ring の wait の間は待つ色（203 と同じ作り）
    ///   ・真上のもの別の型 frames/<場面>_top_obj は RGBA（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん・アルファ＝寺島さん）
    ///   ・確かめを足した：寄せる道（向き・速さ・向きの変わる速さ・前へ／後ろへ・足のせとハコブくん・車輪の横すべり）、大城さんの体と顔の向き・握りをはなした／握り直した時刻、
    ///     ハコブくんが通る時の車いす・大城さん・寺島さんとのすき間の最小、寺島さんの当たり
    /// 以下は 234 の説明：
    /// 依頼234：232 の体の型に加えて、もの（ハコブくん／車いすと茂さん／大城さん）ごとに別々に白く写した型を撮る（Closeup232.cs を写して、写した先で変えた）。
    /// frames/yield_top_obj/f_*.png は 1 枚の色の型で、赤＝ハコブくんだけ・緑＝車いすと茂さんだけ・青＝大城さんだけを写したもの（3 回別々に撮るので、ほかのものに隠された所も入る）。
    /// make234.py が、ものごとに中の穴を埋めた外形にしてから床の線を消す。真上のコマと 232 と同じ型（frames/yield_top_mask）は 232 のまま撮る。
    /// 以下は 232 の説明：
    /// 依頼232：230 の真上の動画の床の線（中心・+0.28・+0.42・−0.33 の線と線の端の字）を、ハコブくん・大城さん・茂さん・車いすの下に描く。Closeup230.cs を写して、写した先で変えた。
    /// 動き・カメラ・真上のコマは 230 のまま。足したのは、真上のコマごとに「体だけを白く写した型」frames/yield_top_mask/f_*.png（黒＝床・白＝体）を撮ることだけ。
    /// 型は真上のカメラを写した別のカメラ（MaskCam232）で、体の部品だけを層 LayerMask232 に移し、白の Unlit/Color で写す（影・光は写らない）。写した後に層と材料を元に戻す。
    /// make232.py が床の線の層を、この型の白い所で消してから重ねる（線は床の上・体の下に見える）。
    /// 以下は 230 の説明：
    /// 依頼230：229 の真上の動画を、車いすがどこにいてどう動いたか分かる形に撮り直す。Closeup229.cs を写して、写した先で変えた。
    /// 台本は 229 の closeup229_script.json をそのまま読む（動き・時刻・セリフは 229 のまま）。変えたのは次だけ：
    ///   ・真上のカメラ：closeup230_top.json の動かない真上のカメラ（正射影・廊下の長い向きが画面の横）。他のカメラは 229 のまま（正射影を戻す）
    ///   ・コマごとに top238.csv を出す：車いすの後ろの車軸の真ん中（左右の後ろの車輪の中心の真ん中）・ハコブくんの根の、廊下の原点からの x・z と真上の画面の位置（ピクセル）、
    ///     車いす（頂点）・ハコブくん（外形の四隅）・大城さん（骨）が真上の画面の中か（2＝全部・1＝一部・0＝外）
    ///   ・top238_cam.json：真上のカメラの値と、床の点（x・z）から画面の位置への写し方（Unity のカメラで 3 点を写した値）
    ///   ・既定は真上だけ撮る（-c238Views top）・静止画なし（-c238Stills off）。目印・跡・字は make230.py で重ねる
    /// 以下は 229 の説明：
    /// 依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが x +0.42 へ寄せる。
    /// 228 の Closeup228.cs を写して、写した先で変えた。228 から変えたのは次だけ（車いすを寄せる道・大城さんの根と向きは台本 closeup229_script.json の nurse.x・z・yaw。
    /// 車いすは 228 と同じく大城さんの根の前に固く付けて動かすので、向きも大城さんと一緒に変わる。前の車輪は 228 の引っぱりの形のまま）：
    ///   ・茂さん・車いすの読み込みの設定は確かめるだけ（Models/ に書かない。228 の Closeup228Morita.Import は呼ばない。違えば止める）
    ///   ・カメラの follow "nurse_xz"：pos・look を大城さんの根の位置と向きから（確かめの静止画用）
    ///   ・確かめを足した：車いすの横の位置・向き、寄せる間（c229.shift.t0〜t1）の手と握り・車輪の横すべり・前の車輪の向き・足のすべり、
    ///     車いすの前の端がハコブくんの前の端と並んだ時刻、寄せ始める前のすき間の最小、車いすの横の速さ（根・足のせの前の端）
    /// 以下は 228 の説明：
    /// 依頼228：要所の場面 ⑧「車いすに道を譲る」（場面 yield・声あり）。217 の Closeup217.cs（175 の CloseupCorridor.cs の写し）を写して、写した先で変えた。
    /// 廊下（台本の rooms の「廊下…」）・看護師の歩き・顔の向き・口・確かめの作りは 217 のまま。足したもの：
    ///   ・車いす（Models/Morita/wheelchair.fbx）を看護師の根の前 c228.wc_ahead_m に固く付けて動かす。後ろの車輪は進んだ長さ ÷ 0.28 m、
    ///     前の車輪は支柱が引っぱる形（後ろへ付いていく）で向きを変え、進んだ長さ ÷ 0.075 m だけ回す
    ///   ・森田茂さん（morita_shigeru.fbx・Generic）は車いすの子。顔の向き・うなずき（Neck と Head の骨）・口（Morita_Mouth_*）・まばたき（Eye_L/R）
    ///   ・ハコブくんの決まり（robot_rule）：前から来る物（車いす・茂さん・看護師）が「自分が止まるまでに縮まる距離＋余り margin_m」を切ったら、
    ///     ふだんの横の位置ですれ違う時のすき間（予想）が gap_stop_m より狭ければ「止まる」（slow_mps に落としながら左の手すり側へ寄り、残りが lateral_done_m を切ったら止まり始める。止まるまで寄り続ける）、
    ///     gap_slow_m より狭ければ「寄る」。止まった後、看護師の体が自分の後ろの端から pass_behind_m 以上離れたら、ふだんの横の位置へ戻りながら走り出す
    ///   ・画面：顔の板はふだん「基本」。c228.band_on〜band_off は帯だけの絵（Textures/c228_yield_band.png）を重ねる（顔は顔の板のふだんの大きさ。219・223 と同じ）。
    ///     話す口は顔の板の絵 face218_<口>（mid はもとの絵）。c228.happy_from〜happy_to は目まで笑う顔 face218_happy（224 と同じ）
    /// 場面（Closeup_Handover.unity）は保存しない。台本の場面の値は "c229"（228 の "c228" と同じ中身＋shift）
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup238.Run \
    ///                 -c238Out <出力フォルダ> [-c238Script closeup229_script.json] [-c238Frames on|off] [-c238Stills on|off] [-c238Views main,top] [-c238From 秒] [-c238To 秒] [-c238Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames238.csv・bones238.csv・feet238.csv・wc238.csv・check238.txt・events238.txt
    /// </summary>
    public static class Closeup238
    {
        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 LayerChair = 30, LayerNurse = 31;
        const int LayerMask232 = 29;   // 依頼232：体の型を写す間だけ体の部品を置く層

        // ---------------------------------------------------------------- ハコブくんの形（217 と同じ）
        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; }

        // ---------------------------------------------------------------- 前から来る物（車いす・茂さん・看護師）の見え方
        class Obs
        {
            public float t;
            public float nearRel;      // 物の頂点の x から、同じ高さのハコブくんの右の幅を引いた値の一番小さい所（ハコブくんの根の x を引けば横のすき間）
            public float nearZ;        // 一番前（−z の側）の z（足のせの前の端）
            public float nurseFarZ;    // 看護師の体の一番後ろ（+z の側）の z
            public float farZ;         // 物の一番後ろの z
        }

        class Rule
        {
            public float cruise, slow, accel, decel, jerk, detectRange, react, margin, gapSlow, gapStop;
            public float laneX, wallClear, latMax, latAngle, latAccel, kx, latDone, resumeAngle, passBehind, turnRate, halfLen, slack;
        }
        static Rule ReadRule(JsonValue j)
        {
            return new Rule
            {
                cruise = j["cruise_mps"].F(0.6f), slow = j["slow_mps"].F(0.3f), accel = j["accel_max_mps2"].F(0.4f), decel = j["decel_max_mps2"].F(0.4f), jerk = j["jerk_max_mps3"].F(1f),
                detectRange = j["detect_range_m"].F(6f), react = j["react_s"].F(0.1f), margin = j["margin_m"].F(2.4f), gapSlow = j["gap_slow_m"].F(0.4f), gapStop = j["gap_stop_m"].F(0.15f),
                laneX = j["lane_x"].F(-0.33f), wallClear = j["wall_clear_m"].F(0.053f), latMax = j["lateral_max_mps"].F(0.12f), latAngle = j["lateral_angle_deg"].F(15f),
                latAccel = j["lateral_accel_mps2"].F(0.25f), kx = j["lateral_gain"].F(2f), latDone = j["lateral_done_m"].F(0.005f), resumeAngle = j["resume_lateral_angle_deg"].F(10f),
                passBehind = j["pass_behind_m"].F(1f), turnRate = j["turn_rate_dps"].F(30f), halfLen = j["corner_half_len_m"].F(0.38f), slack = j["corner_slack_m"].F(0.004f),
            };
        }

        /// <summary>速さ：加速度は accel／decel まで・加加速度は jerk まで（217 と同じ）</summary>
        static void StepSpeed(ref float rv, ref float ra, float vT, Rule R, float dt)
        {
            float dvT = vT - rv;
            float aD = Mathf.Abs(dvT) < 1e-6f ? 0f : Mathf.Sign(dvT) * Mathf.Min(dvT > 0f ? R.accel : R.decel, Mathf.Sqrt(2f * R.jerk * Mathf.Abs(dvT)));
            ra = Mathf.MoveTowards(ra, aD, R.jerk * dt);
            float rvNew = rv + ra * dt;
            if (Mathf.Abs(dvT) > 1e-6f && (Mathf.Sign(vT - rvNew) != Mathf.Sign(dvT) || Mathf.Abs(vT - rvNew) < 0.001f)) { rvNew = vT; ra = 0f; }
            rv = Mathf.Max(0f, rvNew);
        }
        /// <summary>横：向き th（度）を持って進む（横の速さ＝速さ×tan(向き)）。向きは ang まで・変わる速さは turn_rate まで、
        /// 手すりの側の角が手すりへ振れないように、寄った位置 xWall からの余り（＋slack）で決まる角度 asin(余り／half_len) まで。
        /// 向きの目標は、横の目標 xT へ着く所で止まれる横の速さ（√(2·横の加速度·残り)・残り×gain・latMax まで）から</summary>
        static void StepLat(ref float rx, ref float th, float xT, float rv, float ang, Rule R, float dt, float xWall)
        {
            if (rv <= 1e-4f) return;     // 止まっている間は向きも変えない（その場で回らない）
            float dx = xT - rx;
            float vdes = Mathf.Sign(dx) * Mathf.Min(Mathf.Min(Mathf.Abs(dx) * R.kx, Mathf.Sqrt(2f * R.latAccel * Mathf.Abs(dx))), R.latMax);
            float thd = rv > 1e-4f ? Mathf.Atan2(vdes, rv) * Mathf.Rad2Deg : 0f;
            float clear = Mathf.Asin(Mathf.Clamp01((rx - xWall + R.slack) / R.halfLen)) * Mathf.Rad2Deg;
            float lim = Mathf.Min(ang, clear);
            thd = Mathf.Clamp(thd, -lim, lim);
            th = Mathf.MoveTowards(th, thd, R.turnRate * dt);
            th = Mathf.Clamp(th, -Mathf.Max(lim, 0f), Mathf.Max(lim, 0f));
            rx += rv * Mathf.Tan(th * Mathf.Deg2Rad) * dt;
        }
        /// <summary>止まるまでの見込み：今から「寄って止まる」をしたら、止まるまでの時間と進む長さ（自分の決まりで先を計算）</summary>
        static void PlanStop(float rv, float ra, float rx, float th, float xWall, Rule R, float dt, out float tm, out float dm)
        {
            tm = 0f; dm = 0f; bool latDone = false;
            for (int i = 0; i < 3000; i++)
            {
                float vT = latDone ? 0f : R.slow;
                StepSpeed(ref rv, ref ra, vT, R, dt);
                StepLat(ref rx, ref th, xWall, rv, R.latAngle, R, dt, xWall);
                if (!latDone && Mathf.Abs(xWall - rx) < R.latDone) latDone = true;
                tm += dt; dm += rv * dt;
                if (latDone && rv <= 0f) return;
            }
        }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c238Out", "");
            if (outDir == "") throw new Exception("-c238Out がない");
            string scriptName = CloseupArgs.Get("-c238Script", "closeup238_script.json");
            string shotArg = CloseupArgs.Get("-c238Shot", "stop_voice");
            bool frames = CloseupArgs.Get("-c238Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c238Stills", "off") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c238Views", "top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c238From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c238To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                CheckImport(log);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                dir.LoadScript(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var js = dir.script;
                string topErr; var topJs = JsonValue.Parse(File.ReadAllText(Root + "/closeup230_top.json"), out topErr); if (topJs == null) throw new Exception("closeup230_top.json: " + topErr);   // 依頼230：動かない真上のカメラ
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor230").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C230_" + 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 + " 個）");

                // ---- 看護師：描くのは焼いた形（217 と同じ）
                var parts = new List<SkinnedMeshRenderer>();
                foreach (var smr in dir.nurse.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) parts.Add(smr);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                var proxyRoot = new GameObject("Baked229").transform;
                Action<SkinnedMeshRenderer> addProxy = smr =>
                {
                    var g = new GameObject(smr.name + "_Baked");
                    g.transform.SetParent(proxyRoot, 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);
                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 partCat = new List<string[]>();
                var an = dir.nurse.Anim;
                var boneMap = new Dictionary<Transform, HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) { var tb = an.GetBoneTransform((HumanBodyBones)i); if (tb != null) boneMap[tb] = (HumanBodyBones)i; }
                foreach (var smr in 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) : "";
                    partCat.Add(cat);
                }
                var bonesList = new List<HumanBodyBones>();
                for (int i = 0; i < (int)HumanBodyBones.LastBone; i++) if (an.GetBoneTransform((HumanBodyBones)i) != null) bonesList.Add((HumanBodyBones)i);

                // 看護師の口（217・218 と同じ：talk を上の端を止めて縦に curMouthScale 倍）
                MeshFilter talkProxy = null;
                foreach (var kv in proxies) if (kv.Key.name == "Nurse_Mouth_talk" && kv.Key.transform.IsChildOf(dir.nurse.transform)) talkProxy = kv.Value;
                if (talkProxy == null) throw new Exception("看護師の口の部品 Nurse_Mouth_talk が無い");
                float curMouthScale = 1f;
                Action scaleMouth = () =>
                {
                    if (!talkProxy.gameObject.activeSelf || Mathf.Abs(curMouthScale - 1f) < 1e-4f) return;
                    var mesh = talkProxy.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = dir.nurse.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxy.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 - curMouthScale)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // ---- 依頼228：車いすと茂さん
                var chair = Closeup228Morita.Spawn(Closeup228Morita.ChairFbx, "Wheelchair229").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita229").transform;
                mor.SetParent(chair, false); mor.localPosition = Vector3.zero; mor.localRotation = Quaternion.identity;
                Func<string, Transform> CF = n => { var t0 = CloseupNurse.Find(chair, n); if (t0 == null) throw new Exception("車いす・茂さんの部品が無い: " + n); return t0; };
                Transform wheelL = CF("Wheel_L"), wheelR = CF("Wheel_R"), casL = CF("Caster_L"), casR = CF("Caster_R"), cwL = CF("CasterWheel_L"), cwR = CF("CasterWheel_R");
                Transform mNeck = CF("Neck"), mHead = CF("Head"), mEyeL = CF("Eye_L"), mEyeR = CF("Eye_R");
                var mMouths = new Dictionary<string, GameObject>();
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) mMouths[r.name.Substring("Morita_Mouth_".Length)] = r.gameObject;
                // 車いすの根にそろえた時の、回す部品の向き（根から）
                chair.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
                Quaternion wlRest = wheelL.localRotation, wrRest = wheelR.localRotation, clRest = casL.localRotation, crRest = casR.localRotation, cwlRest = cwL.localRotation, cwrRest = cwR.localRotation;
                Vector3 axWL = wheelL.parent.InverseTransformDirection(Vector3.right), axWR = wheelR.parent.InverseTransformDirection(Vector3.right);
                Vector3 axCL = casL.parent.InverseTransformDirection(Vector3.up), axCR = casR.parent.InverseTransformDirection(Vector3.up);
                Vector3 axCWL = cwL.parent.InverseTransformDirection(Vector3.right), axCWR = cwR.parent.InverseTransformDirection(Vector3.right);
                Vector3 hubL0 = wheelL.position, hubR0 = wheelR.position, stemL0 = casL.position, stemR0 = casR.position, cAxL0 = cwL.position, cAxR0 = cwR.position;
                Quaternion neckRest = mNeck.rotation, headRest = mHead.rotation;
                Vector3 eyeSL = mEyeL.localScale, eyeSR = mEyeR.localScale;
                // 当たりを数える形（車いすの部品ごとに MeshCollider）
                var chairMF = new List<MeshFilter>(chair.GetComponentsInChildren<MeshFilter>(true));
                var chairCol = new Dictionary<Collider, string>();
                foreach (var mf in chairMF)
                {
                    var mc = mf.gameObject.AddComponent<MeshCollider>(); mc.sharedMesh = mf.sharedMesh; mf.gameObject.layer = LayerChair; chairCol[mc] = mf.name;
                }
                // 車いすの頂点（根から）・タイヤの頂点
                var chairVertsLocal = new List<Vector3>(); var chairVertsPart = new List<string>();
                foreach (var mf in chairMF) foreach (var v in mf.sharedMesh.vertices) { chairVertsLocal.Add(mf.transform.TransformPoint(v)); chairVertsPart.Add(mf.name); }
                float tireBot0 = float.MaxValue, cTireBot0 = float.MaxValue;
                foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tireBot0 = Mathf.Min(tireBot0, wheelL.TransformPoint(v).y);
                foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) cTireBot0 = Mathf.Min(cTireBot0, cwL.TransformPoint(v).y);
                var chairMin = Vector3.one * 9f; var chairMax = -Vector3.one * 9f;
                foreach (var p in chairVertsLocal) { chairMin = Vector3.Min(chairMin, p); chairMax = Vector3.Max(chairMax, p); }
                log.AppendLine(string.Format(IC, "車いす：頂点 {0}・範囲 {1}〜{2}・後ろの車輪の下 {3:0.0000}・前の車輪の下 {4:0.0000}", chairVertsLocal.Count, chairMin.ToString("0.000"), chairMax.ToString("0.000"), tireBot0, cTireBot0));
                // 茂さん（焼いた形）
                var morParts = new List<SkinnedMeshRenderer>(mor.GetComponentsInChildren<SkinnedMeshRenderer>(true));
                foreach (var smr in morParts) addProxy(smr);
                // 茂さんと車いす：座った形の確かめ（はじめに 1 回。体は根に固いので、顔を動かす骨のほかは動かない）
                var bakedM = new Mesh();
                Physics.SyncTransforms();
                {
                    int touch = 0, inside = 0; float slipMin = float.MaxValue, seatMin = float.MaxValue; var sbM = new StringBuilder();
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy || smr.name.StartsWith("Morita_Mouth_")) continue;
                        smr.BakeMesh(bakedM, true);
                        var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        int tp = 0;
                        foreach (var v in bakedM.vertices)
                        {
                            var w = m.MultiplyPoint3x4(v);
                            if (Physics.CheckSphere(w, 0.001f, 1 << LayerChair)) { touch++; tp++; }
                            if (smr.name == "Morita_Slippers" && w.z > 0.42f && w.z < 0.64f) slipMin = Mathf.Min(slipMin, w.y);
                            if (smr.name == "Morita_Pants" && Mathf.Abs(w.x) < 0.2f && w.z > -0.19f && w.z < 0.23f && w.y < 0.6f) seatMin = Mathf.Min(seatMin, w.y);
                        }
                        if (tp > 0) sbM.Append(" " + smr.name + " " + tp);
                    }
                    log.AppendLine(string.Format(IC, "茂さんと車いす（はじめ）：車いすの面から 1 mm 以内の頂点 {0}（{1}）・足のせの上のスリッパの一番下 {2:0.0000} m（足のせの上の面 0.075）・クッションの上のズボンの一番下 {3:0.0000} m（クッションの上の面 0.485）",
                                                   touch, sbM.ToString().Trim(), slipMin, seatMin));
                    tab.AppendLine(string.Format(IC, "茂さんと車いす\t車いすの面から 1 mm 以内の頂点 {0}（{1}）・スリッパの一番下 {2:0.0000} m（足のせ 0.075）・ズボンの一番下 {3:0.0000} m（クッション 0.485）", touch, sbM.ToString().Trim(), slipMin, seatMin));
                }
                // ---- 依頼235：寺島さん（2 つめの CloseupDirector で動かす。部品の名前 Terashima_ → Nurse_）
                var teraGo = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath<GameObject>(Closeup231Terashima.Prefab));
                teraGo.name = "Terashima235";
                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>();
                teraN.Init();
                var dir2 = new GameObject("Director235Tera").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(File.ReadAllText(Path.IsPathRooted(scriptName) ? scriptName : Root + "/" + scriptName));
                var anT = teraN.Anim;
                var partsT = new List<SkinnedMeshRenderer>();
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                    foreach (var n in new[] { "Nurse_Skin", "Nurse_Top", "Nurse_Sleeves", "Nurse_Pants", "Nurse_Shoes", "Nurse_Hair" })
                        if (smr.name == n) partsT.Add(smr);
                var proxyRootT = new GameObject("Baked235Tera").transform;
                int nProxyO = proxies.Count;
                foreach (var smr in teraN.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                {
                    var g = new GameObject(smr.name + "_BakedT"); g.transform.SetParent(proxyRootT, 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));
                }
                log.AppendLine("寺島さん：部品 " + partsT.Count + "（体）・写し " + (proxies.Count - nProxyO) + "・骨の Animator " + (anT != null ? anT.isHuman.ToString() : "なし"));
                MeshFilter talkProxyT = null;
                for (int i = nProxyO; i < proxies.Count; i++) if (proxies[i].Key.name == "Nurse_Mouth_talk") talkProxyT = proxies[i].Value;
                if (talkProxyT == null) throw new Exception("寺島さんの口の部品 Nurse_Mouth_talk が無い");
                float curMouthScaleT = 1f;
                Action scaleMouthT = () =>
                {
                    if (!talkProxyT.gameObject.activeSelf || Mathf.Abs(curMouthScaleT - 1f) < 1e-4f) return;
                    var mesh = talkProxyT.sharedMesh; var vs = mesh.vertices;
                    Vector3 fw = teraN.HeadForward().normalized;
                    Vector3 upW = Vector3.ProjectOnPlane(Vector3.up, fw).normalized;
                    Vector3 u = Quaternion.Inverse(talkProxyT.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 - curMouthScaleT)); }
                    mesh.vertices = vs; mesh.RecalculateBounds();
                };

                // 看護師の体の当たり（焼いた形の MeshCollider）
                var nurseColGo = new GameObject("NurseCol230"); nurseColGo.layer = LayerNurse;
                var nurseCols = new List<KeyValuePair<SkinnedMeshRenderer, MeshCollider>>();
                foreach (var smr in parts)
                {
                    var g = new GameObject(smr.name + "_Col"); g.layer = LayerNurse; g.transform.SetParent(nurseColGo.transform, false);
                    var mc = g.AddComponent<MeshCollider>(); mc.sharedMesh = new Mesh();
                    nurseCols.Add(new KeyValuePair<SkinnedMeshRenderer, MeshCollider>(smr, mc));
                }

                // ---- 画面の絵
                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", CloseupImport.HakobuDir + "/hakobu_albedo.png");
                    faceEmi[fk] = PrepTex(TexDir + "/face218_" + fk + "_emission.png", CloseupImport.HakobuDir + "/hakobu_emission.png");
                }
                // 依頼237：目まで笑う顔は 224 と同じ（口の段階ごと）・困り顔（ふだんの大きさ）
                faceAlb["happy_closed"] = faceAlb["happy"]; faceEmi["happy_closed"] = faceEmi["happy"];     // 224 と同じ：閉じた口は face218_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", "");
                }
                faceAlb["trouble"] = PrepTex(TexDir + "/face237_trouble_albedo.png", ""); faceEmi["trouble"] = PrepTex(TexDir + "/face237_trouble_emission.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;

                string shotName = shotArg;
                dir2.BeginShot(shotName + "__tera");
                anT.Rebind();
                dir.BeginShot(shotName);
                an.Rebind();
                var shot = dir.shot;
                var C = shot["c238"];
                Vector3 O = CloseupDirector.V3(shot["origin"]);
                var R = ReadRule(js["robot_rule"]);
                float wcAhead = C["wc_ahead_m"].F();
                var scrTex = new Dictionary<string, Texture2D> { { "wait", ScreenTex(TexDir + "/c235_wait_band.png") }, { "deliv", ScreenTex(TexDir + "/c235_deliv_band.png") },
                                                                 { "pass", ScreenTex(TexDir + "/c235_pass_band.png") }, { "stuck", ScreenTex(TexDir + "/c237_stuck_band.png") } };   // 依頼237：帯だけ
                var scrKeys = C["screen"]; var ringKeys = C["ring"];
                var chairKeys = C["chair"]; var gripBoth = C["grip_both"]; var teraMouth = C["tera_mouth"];
                var ringR = dir.ring.GetComponent<MeshRenderer>(); var ringOrig = ringR.sharedMaterial;
                Color rwc; ColorUtility.TryParseHtmlString(C["ring_wait_color"].S("#F2C230"), out rwc);
                var ringWait = new Material(Shader.Find("Standard")) { name = "C235_ring_wait" };
                ringWait.color = rwc; ringWait.SetFloat("_Glossiness", 0.3f); ringWait.EnableKeyword("_EMISSION"); ringWait.SetColor("_EmissionColor", rwc * 0.9f);
                ringWait.globalIlluminationFlags = MaterialGlobalIlluminationFlags.None;
                var robotMouth = C["robot_mouth"]; var nurseMouth = C["nurse_mouth"]; var nmScale = C["nurse_mouth_scale"];
                var MC = C["morita"]; float neckShare = MC["neck_share"].F(0.4f), eyeMin = MC["eye_min_scale"].F(0.1f);
                var mTr = new Dictionary<string, JsonValue> { { "yaw", MC["head_yaw"] }, { "nod", MC["head_nod"] }, { "mouth", MC["mouth"] } };
                // 茂さんのまばたき（大城さんと同じ決め方。種は台本の値と場面の名前から）
                var mBlinks = new List<double>();
                {
                    var B = MC["blink"]; int hseed = B["seed"].I(228); foreach (char ch in shotName) hseed = hseed * 31 + ch;
                    var rng = new System.Random(hseed); float a = B["every_min_s"].F(3f), b = B["every_max_s"].F(5f);
                    double tb = a * 0.5 + rng.NextDouble() * (b - a) * 0.5;
                    while (tb < dir.duration + 1) { mBlinks.Add(tb); tb += a + rng.NextDouble() * (b - a); }
                }
                float mBlinkS = MC["blink"]["close_s"].F(0.15f);
                int vFrom = Mathf.RoundToInt(C["video_from"].F() * fps), vTo = Mathf.RoundToInt(C["video_to"].F() * fps);
                float shT0 = C["man"]["t0"].F(1e9f), shT1 = C["man"]["t1"].F(-1f);
                var grip = C["grip"]; float gripX = grip["x"].F(), gripY = grip["y"].F(), gripZ = grip["z_behind_root"].F(), gripR = grip["r"].F();

                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 bandMaxX = new float[rs.hulls.Count];
                for (int b = 0; b < rs.hulls.Count; b++) { bandMaxX[b] = rs.maxX; if (rs.hulls[b] != null) { float mx = float.MinValue; foreach (var qv in rs.hulls[b]) mx = Mathf.Max(mx, qv.x); bandMaxX[b] = mx; } }
                float xWall = float.MinValue;
                for (int b = 0; b < rs.hulls.Count; b++)
                {
                    if (rs.hulls[b] == null) continue;
                    float y0 = b * rs.band, y1 = y0 + rs.band, face = float.MinValue;
                    foreach (var s in solids) { float lx = s.max.x - O.x; if (lx > 0f || s.max.y < y0 || s.min.y > y1) continue; face = Mathf.Max(face, lx); }
                    if (face == float.MinValue) continue;
                    float hmin = float.MaxValue; foreach (var qv in rs.hulls[b]) hmin = Mathf.Min(hmin, qv.x);
                    xWall = Mathf.Max(xWall, face + R.wallClear - hmin);
                }
                log.AppendLine(string.Format(IC, "ハコブくんのふだんの横の位置 x={0:0.000}・寄った時 x={1:0.000}（左の箱と {2:0.000} m）", R.laneX, xWall, R.wallClear));

                // ---- 状態
                float rz = shot["robot_start_z"].F(0f), rx = R.laneX, rv = R.cruise, ra = 0f, ryaw = 0f, vxr = 0f;
                string mode = "cruise", prevMode = "cruise";
                bool latDone = false, seen = false;
                float seenT = -1f, seenGap = float.NaN, trigT = -1f, trigGap = float.NaN, trigNeed = float.NaN, trigGapLane = float.NaN, trigGapWall = float.NaN, trigTm = float.NaN, trigDm = float.NaN;
                float latDoneT = -1f, stopT = -1f, decelT = -1f, resumeT = -1f, behindAtResume = float.NaN, nurseBehindAtResume = float.NaN, exitT = -1f, stopFrontGap = float.NaN;
                var obs = new List<Obs>();
                float stillS = js["robot_rule"]["resume_still_s"].F(0.5f), stillV = js["robot_rule"]["still_mps"].F(0.005f);
                float lastMoveT = 0f, resumeGapWall = float.NaN, passedT = -1f; bool passedAll = false;
                Vector3 pvC = Vector3.zero, pvO = Vector3.zero, pvT = Vector3.zero; float pvCy = 0f, pvOy = 0f, pvTy = 0f;
                int nReact = Mathf.RoundToInt(R.react * fps);

                // 確かめ
                float gapMin = float.MaxValue, gapMinT = -1f; string gapMinWhere = "";
                float gapPassMin = float.MaxValue, gapPassMinT = -1f;
                int hitRG = 0, hitCS = 0, hitRS = 0, hitNC = 0, hitHandGrip = 0, hitNS = 0; string hitCSWhere = "", hitRSWhere = "", hitNCWhere = "", hitNSWhere = "";
                float chairSolidMin = float.MaxValue, chairRailMin = float.MaxValue, robotRailMin = float.MaxValue, robotRailMinStop = float.MaxValue, nurseSolidMin = float.MaxValue, nurseChairMin = float.MaxValue;
                float vMin = float.MaxValue, vMax = float.MinValue, aMax = 0f, aMin = 0f, xMinR = float.MaxValue, xMaxR = float.MinValue, yawMaxR = 0f;
                float stopMove = 0f; Vector3 stopPos = Vector3.zero; float stopYaw = 0f; bool stopped = false; int stopFrames = 0;
                float palmGripMax = 0f, palmGripMaxT = -1f, palmGripMin = float.MaxValue, palmTargetErrMax = 0f, palmTargetErrT = -1f;
                float jumpR = 0f, jumpRT = 0f, jumpW = 0f, jumpWT = 0f; string jumpRB = "", jumpWB = "";
                // 依頼235
                var ncTimes = new List<string>();
                float rigidErr = 0f; int hitTS = 0, hitTO = 0, hitTC = 0; string hitTWhere = "";
                var passMin = new Dictionary<string, float> { { "車いす", float.MaxValue }, { "茂さん", float.MaxValue }, { "看護師", float.MaxValue }, { "寺島さん", float.MaxValue } };
                var passMinT = new Dictionary<string, float> { { "車いす", -1f }, { "茂さん", -1f }, { "看護師", -1f }, { "寺島さん", -1f } };
                float manYawMax = 0f, manV = 0f, manVT = -1f, manW = 0f, manWT = -1f, manFwd = 0f, manBack = 0f, footRobotMin = float.MaxValue, footRobotMinT = -1f, axZ0 = float.NaN;
                float oBodyRelMax = 0f, oBodyRelMaxT = -1f, oHeadMaxTalk = 0f, oHeadMaxTalkT = -1f, oLookTeraMin = 180f, relT = -1f, regripT = -1f; bool prevGripR = true;
                float tHeadMax = 0f, tHeadMaxT = -1f; Vector3 prevAxle = Vector3.zero; float prevCy = 0f; bool havePA = false;
                float teraZ0 = float.NaN, teraX0 = float.NaN, teraRetDist = 0f, teraRetT0 = -1f, teraRetT1 = -1f; Vector3 prevTera = Vector3.zero;
                float mJump = 0f, mJumpT = 0f; string mJumpB = "";
                float besideT0 = -1f, besideT1 = -1f;   // 依頼237
                float wheelSlipMax = 0f, casterSlipMax = 0f, tireYMin = float.MaxValue, tireYMax = float.MinValue, cTireYMin = float.MaxValue, cTireYMax = float.MinValue, chairYErr = 0f;
                float wheelAngL = 0f, wheelAngR = 0f, cwAngL = 0f, cwAngR = 0f, casYawL = 0f, casYawR = 0f, casYawMax = 0f;
                Vector3 prevHubL = Vector3.zero, prevHubR = Vector3.zero, prevChair = Vector3.zero, prevChairRight = Vector3.right; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                // 依頼229：寄せる所の確かめ
                float shPalmErr = 0f, shPalmGripMin = float.MaxValue, shPalmGripMax = 0f, shWheelSlip = 0f, shCasterSlip = 0f, shCasYaw = 0f, shSlide = 0f, casYawMaxT = -1f;
                float chairLatV = 0f, chairLatVT = -1f, frontLatV = 0f, frontLatVT = -1f, chairYawMax = 0f, chairYawMaxT = -1f, gapPreShift = float.MaxValue, gapPreShiftT = -1f;
                float alignT = -1f, alignChairX = float.NaN, alignGap = float.NaN; float prevChairX = float.NaN, prevFrontX = float.NaN;
                float chairX0 = float.NaN, chairXsh0 = float.NaN, chairXsh1 = float.NaN, chairXpassMin = float.MaxValue, chairXpassMax = float.MinValue;
                float lookSum = 0f; int lookN = 0; float lookWorst = 0f, lookWorstT = -1f;
                float mYawMax = 0f, mNodMax = 0f, mLookBest = 180f, mLookBestT = -1f; float mLookAtMaxYaw = float.NaN;
                string prevScr = ""; var scrChanges = new List<string>();
                var prevBones = new Vector3[bonesList.Count]; Vector3 prevRoot = Vector3.zero; bool havePrev = false;
                var mBoneNames = new[] { "Neck", "Head", "Eye_L", "Eye_R", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "Hips" };
                var mBones = new Transform[mBoneNames.Length]; for (int i = 0; i < mBones.Length; i++) mBones[i] = CF(mBoneNames[i]);
                var mPrevLocal = new Vector3[mBones.Length]; bool mHavePrev = false;
                SkinnedMeshRenderer shoeSmr = null; foreach (var smr in parts) if (smr.name == "Nurse_Shoes") shoeSmr = smr;
                var shoeMesh = new Mesh();
                Vector3[] shoePrev = null; float[] shoeAcc = null; bool[] shoeOn = null; bool prevInWalk = false;
                float slideMax = 0f, slideMaxT = 0f, sinkMax = 0f, sinkMaxT = 0f, floatMax = 0f, floatMaxT = 0f; int walkFrames = 0;
                var nurseWheelMin = float.MaxValue; string nurseWheelWhere = ""; float handGripMin = float.MaxValue; string handGripWhere = "";

                int nFrames = Mathf.RoundToInt(Mathf.Min(dir.duration, float.Parse(CloseupArgs.Get("-c238Until", "1e9"), IC)) * fps);
                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"); }   // 依頼232：_mask は体の型
                var csv = new StringBuilder("frame,t,cam,robot_x,robot_z,robot_yaw,robot_v,robot_a,robot_vx,mode,screen,nurse_z,nurse_v,chair_z,front_gap_m,gap_m,gap_lane_pred_m,need_m,behind_nurse_m,rail_gap_m,chair_rail_gap_m,nurse_chair_m,palm_grip_l_m,palm_grip_r_m,head_yaw,head_nod,nurse_mouth,look_deg,m_yaw,m_nod,m_mouth,m_blink,m_look_deg,robot_in_depart,chair_x,chair_yaw,nurse_x,nurse_yaw,m_to_robot_deg,foot_front_m,behind_oshiro_m\n");
                var topCsv = new StringBuilder("frame,t,axle_x,axle_z,axle_px,axle_py,robot_x,robot_z,robot_px,robot_py,chair_in,robot_in,nurse_in\n");   // 依頼230
                var bonesCsv = new StringBuilder("frame,t"); foreach (var hb in bonesList) bonesCsv.Append("," + hb + "_x," + hb + "_y," + hb + "_z"); bonesCsv.AppendLine();
                var feetCsv = new StringBuilder("frame,t,step,lshoe_min_y,rshoe_min_y,shoe_slide\n");
                var wcCsv = new StringBuilder("frame,t,chair_x,chair_z,chair_yaw,dist_l,dist_r,wheel_l_deg,wheel_r_deg,caster_l_yaw,caster_r_yaw,caster_wheel_l_deg,caster_wheel_r_deg,tire_min_y,caster_tire_min_y,wheel_slip_m,caster_slip_m\n");
                var baked = new Mesh();
                var stills = shot["stills"];
                var depCam = shot["cameras"]["depart"];

                for (int f = 0; f < nFrames; f++)
                {
                    float t = f * dt;
                    if (f > 0 && f % 150 == 0) GC.Collect();   // 依頼235：長い場面でメモリが増えないように
                    // ---------- ハコブくん：決まり（react_s 前までに見た物）
                    Obs o = null, oLong = null;
                    int oi = obs.Count - 1 - nReact;
                    if (oi >= 0) { o = obs[oi]; if (oi - 15 >= 0) oLong = obs[oi - 15]; }
                    float frontZ = rz + rs.maxZ, rearZ = rz + rs.minZ;
                    float frontGap = float.NaN, gapLane = float.NaN, gapWall = float.NaN, need = float.NaN, behindN = float.NaN;
                    bool ahead = false;
                    if (o != null)
                    {
                        frontGap = o.nearZ - frontZ;
                        behindN = rearZ - o.nurseFarZ;
                        ahead = frontGap < R.detectRange && o.farZ > rearZ;
                        gapLane = o.nearRel - R.laneX; gapWall = o.nearRel - xWall;
                        if (ahead && !seen) { seen = true; seenT = t; seenGap = frontGap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 前から来る物を見つけた（見た時刻 {1:0.000}・前の端とのあいだ {2:0.000} m）", t, o.t, frontGap)); }
                        if (mode == "cruise" && ahead)
                        {
                            float vOther = oLong != null ? Mathf.Max(0f, -(o.nearZ - oLong.nearZ) / (o.t - oLong.t)) : 0f;
                            float tm, dm; PlanStop(rv, ra, rx, ryaw, xWall, R, dt, out tm, out dm);
                            need = dm + vOther * tm + R.margin;
                            if (frontGap < need && gapLane < R.gapSlow)
                            {
                                mode = gapLane < R.gapStop || gapWall < R.gapStop ? "stop" : "yield";
                                trigT = t; trigGap = frontGap; trigNeed = need; trigGapLane = gapLane; trigGapWall = gapWall; trigTm = tm; trigDm = dm;
                                log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まりに当たった：前の端とのあいだ {1:0.000} m ＜ 止まるまでに縮まる距離 {2:0.000}（自分 {3:0.000} m・{4:0.000} 秒・相手 {5:0.000} m/秒）＋余り {6:0.000} ＝ {7:0.000} m／ふだんの位置のすき間 {8:0.000} m・寄った位置のすき間 {9:0.000} m → {10}",
                                                               t, frontGap, need - R.margin, dm, tm, vOther, R.margin, need, gapLane, gapWall, mode));
                            }
                        }
                        // 依頼235：止まった後、前の物が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す
                        if (mode == "stop" && stopped && t - lastMoveT >= stillS - 1e-4f && gapWall >= R.gapStop) { mode = "resume"; resumeT = t; nurseBehindAtResume = behindN; behindAtResume = rearZ - o.farZ; resumeGapWall = gapWall;
                            log.AppendLine(string.Format(IC, "  {0:0.000} 秒 走り出す：前の物が {1:0.000} 秒動いていない・寄った位置のすき間 {2:0.000} m", t, t - lastMoveT, gapWall)); }
                        if ((mode == "resume" || mode == "cruise2") && !passedAll && rearZ - o.farZ >= 0f) { passedAll = true; passedT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 物の一番後ろを通り過ぎた → x {1:0.000} へ戻る", t, R.laneX)); }
                    }
                    if (mode == "stop" && !latDone && Mathf.Abs(xWall - rx) < R.latDone) { latDone = true; latDoneT = t; }
                    if (mode == "resume" && passedAll && rv >= R.cruise - 1e-4f && Mathf.Abs(rx - R.laneX) < 0.002f) mode = "cruise2";
                    if (mode != prevMode) log.AppendLine(string.Format(IC, "  {0:0.000} 秒 決まり {1} → {2}（見た時刻 {3:0.000}・前の端とのあいだ {4:0.000} m・看護師の体が後ろの端から {5:0.000} m）", t, prevMode, mode, o != null ? o.t : -1f, frontGap, behindN));
                    prevMode = mode;
                    float vT = mode == "cruise" || mode == "cruise2" || mode == "resume" ? R.cruise : mode == "yield" ? R.slow : latDone ? 0f : R.slow;
                    StepSpeed(ref rv, ref ra, vT, R, dt);
                    if (f > 0 && rv < R.cruise - 1e-4f && decelT < 0f) decelT = t - dt;
                    float rx0 = rx;
                    if (mode == "stop" || mode == "yield") StepLat(ref rx, ref ryaw, xWall, rv, R.latAngle, R, dt, xWall);
                    else if ((mode == "resume" || mode == "cruise2") && !passedAll) StepLat(ref rx, ref ryaw, xWall, rv, R.resumeAngle, R, dt, xWall);   // 依頼235：通り過ぎるまで寄った位置のまま
                    else if (mode == "resume" || mode == "cruise2") StepLat(ref rx, ref ryaw, R.laneX, rv, R.resumeAngle, R, dt, xWall);
                    vxr = (rx - rx0) / dt;
                    rz += rv * dt;

                    // ---------- 看護師（依頼235：寺島さんを先に。大城さんの 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;
                    {
                        // 依頼235：車いすの根は台本の c235.chair（両手で握っている間は大城さんの根の前に固く付いた値と同じ）
                        var ck = chairKeys[Mathf.Min(f, chairKeys.Count - 1)];
                        chair.SetPositionAndRotation(O + new Vector3(ck[0].F(), 0f, ck[1].F()), Quaternion.Euler(0f, ck[2].F(), 0f));
                        bool gb = gripBoth[Mathf.Min(f, gripBoth.Count - 1)].I() == 1;
                        if (gb) { float dRig = Vector3.Distance(chair.position, nr.position + nr.rotation * new Vector3(0f, 0f, wcAhead)) + Mathf.Abs(Mathf.DeltaAngle(chair.eulerAngles.y, nr.eulerAngles.y)) * 0.01f; rigidErr = Mathf.Max(rigidErr, dRig); }
                    }
                    chairYErr = Mathf.Max(chairYErr, Mathf.Abs(chair.position.y));
                    {
                        // 後ろの車輪：車軸が進んだ長さ（車いすの前の向き）÷ 半径
                        Vector3 hubL = chair.TransformPoint(hubL0), hubR = chair.TransformPoint(hubR0);
                        float dL = 0f, dR = 0f;
                        if (haveChairPrev) { dL = Vector3.Dot(hubL - prevHubL, chair.forward); dR = Vector3.Dot(hubR - prevHubR, chair.forward); }
                        wheelAngL += dL / 0.28f * Mathf.Rad2Deg; wheelAngR += dR / 0.28f * Mathf.Rad2Deg;
                        wheelL.localRotation = Quaternion.AngleAxis(wheelAngL, axWL) * wlRest; wheelR.localRotation = Quaternion.AngleAxis(wheelAngR, axWR) * wrRest;
                        if (haveChairPrev) { Vector3 rgt = (chair.right + prevChairRight).normalized;   // 依頼229：向きが変わるので、コマの前後の向きの間（真ん中）の横で数える
                            float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, rgt)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, rgt))); wheelSlipMax = Mathf.Max(wheelSlipMax, side); if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shWheelSlip = Mathf.Max(shWheelSlip, side); }
                        prevHubL = hubL; prevHubR = hubR;
                        // 前の車輪：支柱に引っぱられて後ろへ付いていく（車軸＝支柱から引っぱる向きの後ろ trail の所）
                        Vector3 stL = chair.TransformPoint(stemL0), stR = chair.TransformPoint(stemR0);
                        float trail = new Vector2(cAxL0.x - stemL0.x, cAxL0.z - stemL0.z).magnitude;
                        if (!haveChairPrev) { cAxL = chair.TransformPoint(new Vector3(cAxL0.x, 0f, cAxL0.z)); cAxR = chair.TransformPoint(new Vector3(cAxR0.x, 0f, cAxR0.z)); }
                        float cdL = 0f, cdR = 0f;
                        for (int s = 0; s < 2; s++)
                        {
                            Vector3 st = s == 0 ? stL : stR; Vector3 ax = s == 0 ? cAxL : cAxR;
                            Vector3 d = new Vector3(ax.x - st.x, 0f, ax.z - st.z);
                            Vector3 axN = new Vector3(st.x, 0f, st.z) + (d.sqrMagnitude > 1e-12f ? d.normalized : -chair.forward) * trail;
                            Vector3 move = axN - ax; move.y = 0f;
                            Vector3 rollDir = Vector3.Cross(Vector3.up, (axN - new Vector3(st.x, 0f, st.z)).normalized) * -1f;   // 車輪の向き（支柱から車軸の逆＝進む向き）
                            Vector3 fwdW = -(axN - new Vector3(st.x, 0f, st.z)).normalized;
                            float roll = Vector3.Dot(move, fwdW);
                            float slip = Vector3.Dot(move, Vector3.Cross(Vector3.up, fwdW));
                            casterSlipMax = Mathf.Max(casterSlipMax, Mathf.Abs(slip));
                            float yawW = Mathf.Atan2(fwdW.x, fwdW.z) * Mathf.Rad2Deg;
                            float yawRel = Mathf.DeltaAngle(chair.eulerAngles.y, yawW);
                            if (s == 0) { cAxL = axN; cdL = roll; casYawL = yawRel; } else { cAxR = axN; cdR = roll; casYawR = yawRel; }
                            if (Mathf.Abs(yawRel) > casYawMax) { casYawMax = Mathf.Abs(yawRel); casYawMaxT = t; }
                            if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shCasYaw = Mathf.Max(shCasYaw, Mathf.Abs(yawRel)); shCasterSlip = Mathf.Max(shCasterSlip, Mathf.Abs(slip)); }
                            if (rollDir.sqrMagnitude < 0f) roll = 0f;
                        }
                        casL.localRotation = Quaternion.AngleAxis(casYawL, axCL) * clRest; casR.localRotation = Quaternion.AngleAxis(casYawR, axCR) * crRest;
                        cwAngL += cdL / 0.075f * Mathf.Rad2Deg; cwAngR += cdR / 0.075f * Mathf.Rad2Deg;
                        cwL.localRotation = Quaternion.AngleAxis(cwAngL, axCWL) * cwlRest; cwR.localRotation = Quaternion.AngleAxis(cwAngR, axCWR) * cwrRest;
                        float tmn = float.MaxValue, ctmn = float.MaxValue;
                        foreach (var v in wheelL.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelL.TransformPoint(v).y);
                        foreach (var v in wheelR.GetComponent<MeshFilter>().sharedMesh.vertices) tmn = Mathf.Min(tmn, wheelR.TransformPoint(v).y);
                        foreach (var v in cwL.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwL.TransformPoint(v).y);
                        foreach (var v in cwR.GetComponent<MeshFilter>().sharedMesh.vertices) ctmn = Mathf.Min(ctmn, cwR.TransformPoint(v).y);
                        tireYMin = Mathf.Min(tireYMin, tmn); tireYMax = Mathf.Max(tireYMax, tmn); cTireYMin = Mathf.Min(cTireYMin, ctmn); cTireYMax = Mathf.Max(cTireYMax, ctmn);
                        wcCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(chair.position.x - O.x) + "," + F(chair.position.z - O.z) + "," + F(chair.eulerAngles.y, "0.000") + "," + F(dL, "0.00000") + "," + F(dR, "0.00000") + "," +
                                         F(wheelAngL, "0.000") + "," + F(wheelAngR, "0.000") + "," + F(casYawL, "0.000") + "," + F(casYawR, "0.000") + "," + F(cwAngL, "0.000") + "," + F(cwAngR, "0.000") + "," + F(tmn, "0.00000") + "," + F(ctmn, "0.00000") + "," +
                                         F(wheelSlipMax, "0.00000") + "," + F(casterSlipMax, "0.00000"));
                        prevChair = chair.position; prevChairRight = chair.right; haveChairPrev = true;
                    }
                    // ---------- 依頼235：前の物が動いたか（車いす・大城さん・寺島さんの根と向き）
                    {
                        Vector3 pc = chair.position, po = nr.position, pt = teraN.transform.position; float yc = chair.eulerAngles.y, yo = nr.eulerAngles.y, yt = teraN.transform.eulerAngles.y;
                        if (f > 0)
                        {
                            float mvm = Mathf.Max(Vector3.Distance(pc, pvC), Mathf.Max(Vector3.Distance(po, pvO), Vector3.Distance(pt, pvT))) / dt;
                            float mva = Mathf.Max(Mathf.Abs(Mathf.DeltaAngle(yc, pvCy)), Mathf.Max(Mathf.Abs(Mathf.DeltaAngle(yo, pvOy)), Mathf.Abs(Mathf.DeltaAngle(yt, pvTy)))) / dt;
                            if (mvm > stillV || mva > 0.5f) lastMoveT = t;
                        }
                        pvC = pc; pvO = po; pvT = pt; pvCy = yc; pvOy = yo; pvTy = yt;
                    }
                    // ---------- 依頼229：車いすの横の位置・向き・横の速さ（根と足のせの前の端）
                    {
                        float cx = chair.position.x - O.x, fx = chair.TransformPoint(new Vector3(0f, 0f, 0.64f)).x - O.x, cyaw = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (f == 0) chairX0 = cx;
                        if (Mathf.Abs(t - shT0) < 0.5f * dt) chairXsh0 = cx;
                        if (Mathf.Abs(t - shT1) < 0.5f * dt) chairXsh1 = cx;
                        if (!float.IsNaN(prevChairX)) { float v1 = Mathf.Abs(cx - prevChairX) / dt, v2 = Mathf.Abs(fx - prevFrontX) / dt; if (v1 > chairLatV) { chairLatV = v1; chairLatVT = t; } if (v2 > frontLatV) { frontLatV = v2; frontLatVT = t; } }
                        if (Mathf.Abs(cyaw) > chairYawMax) { chairYawMax = Mathf.Abs(cyaw); chairYawMaxT = t; }
                        prevChairX = cx; prevFrontX = fx;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    float mYaw = CloseupDirector.Num(mTr, "yaw", t, 0f), mNod = CloseupDirector.Num(mTr, "nod", t, 0f);
                    string mMouth = CloseupDirector.Str(mTr, "mouth", t, "flat");
                    { var ml = C["morita_mouth_lvl"]; if (f < ml.Count && ml[f].I() > 0) mMouth = "talk"; }     // 依頼235：茂さんが話す間は talk
                    mYawMax = Mathf.Max(mYawMax, Mathf.Abs(mYaw)); mNodMax = Mathf.Max(mNodMax, mNod);
                    Quaternion qNeck = Quaternion.AngleAxis(neckShare * mYaw, Vector3.up) * Quaternion.AngleAxis(neckShare * mNod, Vector3.right);
                    Quaternion qHead = Quaternion.AngleAxis(mYaw, Vector3.up) * Quaternion.AngleAxis(mNod, Vector3.right);
                    mNeck.rotation = chair.rotation * qNeck * neckRest;
                    mHead.rotation = chair.rotation * qHead * headRest;
                    foreach (var kv in mMouths) kv.Value.SetActive(kv.Key == mMouth);
                    float mbl = 0f;
                    for (int i = 0; i < mBlinks.Count; i++) { double u = (t - mBlinks[i]) / mBlinkS; if (u >= 0 && u <= 1) mbl = (float)(1.0 - Math.Abs(u * 2 - 1)); }
                    float es = Mathf.Lerp(1f, eyeMin, mbl);
                    mEyeL.localScale = new Vector3(eyeSL.x, eyeSL.y, eyeSL.z * es); mEyeR.localScale = new Vector3(eyeSR.x, eyeSR.y, eyeSR.z * es);

                    // ---------- 画面
                    string rmo = f < robotMouth.Count ? robotMouth[f].S() : "mid";
                    // 依頼237：画面は台本の時刻のとおり（235 の走り出しの目まで笑う顔はやめた）
                    string sk = "face"; for (int k = 0; k < scrKeys.Count; k++) if (scrKeys[k][0].F() <= t + 1e-4f) sk = scrKeys[k][1].S();
                    bool bandNow = scrTex.ContainsKey(sk);
                    bool happyNow = sk == "happy";
                    dir.screenOverlay.gameObject.SetActive(bandNow);
                    if (bandNow) { var mpo = new MaterialPropertyBlock(); mpo.SetTexture("_MainTex", scrTex[sk]); dir.screenOverlay.SetPropertyBlock(mpo); }
                    string rk = "normal"; for (int k = 0; k < ringKeys.Count; k++) { string v = ringKeys[k][1].S(); if (v == "normal" && k > 0) continue; if (ringKeys[k][0].F() <= t + 1e-4f) rk = v; }
                    if (resumeT >= 0f) rk = "normal";
                    ringR.sharedMaterial = rk == "wait" ? ringWait : ringOrig;
                    string fk = happyNow ? "happy_" + rmo : sk == "stuck" ? "trouble" : rmo != "mid" ? rmo : "";     // 依頼237：224 の目まで笑う顔・通れませんは困り顔
                    { var mpf = new MaterialPropertyBlock(); if (fk != "") { mpf.SetTexture("_MainTex", faceAlb[fk]); mpf.SetTexture("_EmissionMap", faceEmi[fk]); } faceR.SetPropertyBlock(mpf); }
                    string scrNow = (bandNow ? "絵" + sk : "") + (happyNow ? "目まで笑う顔" : sk == "stuck" ? "困り顔" : "基本") + (rk == "wait" ? "＋輪の待つ色" : "") + "_" + rmo;
                    if (scrNow.Split('_')[0] != prevScr.Split('_')[0]) scrChanges.Add(F(t, "0.000") + "\t" + (prevScr == "" ? "-" : prevScr.Split('_')[0]) + " → " + scrNow.Split('_')[0]);
                    prevScr = scrNow;
                    Physics.SyncTransforms();

                    // ---------- 看護師の体を焼く（見る・確かめる）
                    var ob = new Obs { t = t, nearZ = float.MaxValue, farZ = float.MinValue, nurseFarZ = float.MinValue, nearRel = float.MaxValue };
                    float gap = float.MaxValue; string gapWhere = "";
                    var passNow = new Dictionary<string, float> { { "車いす", float.MaxValue }, { "茂さん", float.MaxValue }, { "看護師", float.MaxValue }, { "寺島さん", float.MaxValue } };
                    Matrix4x4 toR = dir.robot.worldToLocalMatrix;
                    Matrix4x4 toC = chair.worldToLocalMatrix;
                    float nurseChairNow = float.MaxValue;
                    Action<Vector3, string> seeVert = (w, who) =>
                    {
                        Vector3 lc = w - O;
                        if (w.y <= rs.top + 0.1f) ob.nearRel = Mathf.Min(ob.nearRel, lc.x - bandMaxX[Mathf.Clamp(Mathf.FloorToInt(w.y / rs.band), 0, bandMaxX.Length - 1)]);
                        ob.nearZ = Mathf.Min(ob.nearZ, lc.z); ob.farZ = Mathf.Max(ob.farZ, lc.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;   // 依頼235：1.5 m より遠い点は数えない（速くするため。1.5 m より近い値は同じ）
                        string cat0 = who.Substring(0, Math.Max(0, who.IndexOf(' ')));
                        float cutW = passNow.ContainsKey(cat0) ? Mathf.Min(passNow[cat0], 1.5f) : Mathf.Min(gap, 1.5f);
                        float d = RobotDist(rs, lr, Mathf.Max(cutW, Mathf.Min(gap, 1.5f)));
                        if (passNow.ContainsKey(cat0) && d < passNow[cat0]) passNow[cat0] = d;
                        if (d < gap) { gap = d; gapWhere = who; }
                    };
                    int pi = -1; bool ncHit = false, hgHit = false, nsHit = false;
                    for (int ci = 0; ci < nurseCols.Count; ci++)
                    {
                        var smr = nurseCols[ci].Key;
                        var cm = nurseCols[ci].Value.sharedMesh;
                        smr.BakeMesh(cm, true);
                        nurseCols[ci].Value.sharedMesh = null; nurseCols[ci].Value.sharedMesh = cm;
                        nurseCols[ci].Value.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                    }
                    Physics.SyncTransforms();
                    foreach (var smr in parts)
                    {
                        pi++;
                        smr.BakeMesh(baked, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = baked.vertices; var cat = partCat[pi];
                        for (int i = 0; i < vs.Length; i++)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            ob.nurseFarZ = Mathf.Max(ob.nurseFarZ, w.z - O.z);
                            seeVert(w, "看護師 " + 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;
                                if (InBox(w, s.min, s.max)) { nsHit = true; if (hitNSWhere == "") hitNSWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + s.name; }
                                nurseSolidMin = Mathf.Min(nurseSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                            // 看護師と車いす：車いすの近くの頂点だけ
                            Vector3 lcw = toC.MultiplyPoint3x4(w);
                            if (lcw.x < chairMin.x - 0.05f || lcw.x > chairMax.x + 0.05f || lcw.z < chairMin.z - 0.05f || lcw.z > chairMax.z + 0.05f || lcw.y > chairMax.y + 0.05f) continue;
                            bool hand = cat[i] != "";
                            if (hand)
                            {
                                // 手：握りの筒（中心の線から gripR）に入らない。握りのほかの車いすの面にも入らない
                                float ax = Mathf.Abs(lcw.x) - gripX, ay = lcw.y - gripY;
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f) { float dg = Mathf.Sqrt(ax * ax + ay * ay) - gripR; if (dg < handGripMin) { handGripMin = dg; handGripWhere = F(t, "0.000") + " 秒 " + cat[i] + " " + lcw.ToString("0.000"); } }
                                if (Mathf.Abs(lcw.z + gripZ) < 0.045f && Mathf.Sqrt(ax * ax + ay * ay) < gripR - 0.001f) { hgHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→握りの中"; }
                                foreach (var col in Physics.OverlapSphere(w, 0.001f, 1 << LayerChair))
                                    if (chairCol[col] != "WC_Parts") { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + cat[i] + "→" + chairCol[col]; }
                            }
                            else
                            {
                                var cols = Physics.OverlapSphere(w, 0.003f, 1 << LayerChair);
                                if (cols.Length > 0) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 " + smr.name + "→" + chairCol[cols[0]] + " 車いすから " + lcw.ToString("0.000"); }
                                // 一番近い車いすの頂点（参考）
                                if (lcw.y < 0.6f)
                                    for (int k = 0; k < chairVertsLocal.Count; k += 3)
                                    {
                                        float dd = (chairVertsLocal[k] - lcw).sqrMagnitude;
                                        if (dd < nurseChairNow * nurseChairNow) { nurseChairNow = Mathf.Sqrt(dd); if (nurseChairNow < nurseWheelMin) { nurseWheelMin = nurseChairNow; nurseWheelWhere = F(t, "0.000") + " 秒 " + smr.name + "と" + chairVertsPart[k]; } }
                                    }
                            }
                        }
                    }
                    // 依頼235：寺島さんの頂点（見る・壁/手すり・大城さん・車いす）
                    {
                        bool tsHit = false, toHit = false, tcHit = false;
                        foreach (var smr in partsT)
                        {
                            smr.BakeMesh(baked, true);
                            Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                            var vs = baked.vertices;
                            for (int i = 0; i < vs.Length; i += 2)
                            {
                                Vector3 w = m.MultiplyPoint3x4(vs[i]);
                                seeVert(w, "寺島さん " + smr.name);
                                foreach (var s2 in solids)
                                {
                                    if (w.x < s2.min.x - 0.1f || w.x > s2.max.x + 0.1f || w.z < s2.min.z - 0.1f || w.z > s2.max.z + 0.1f) continue;
                                    if (InBox(w, s2.min, s2.max)) { tsHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→" + s2.name; }
                                }
                                if (Physics.CheckSphere(w, 0.003f, 1 << LayerNurse)) { toHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→大城さん"; }
                                if (Physics.CheckSphere(w, 0.003f, 1 << LayerChair)) { tcHit = true; if (hitTWhere == "") hitTWhere = F(t, "0.000") + " 秒 寺島さん " + smr.name + "→車いす"; }
                            }
                        }
                        if (tsHit) hitTS++; if (toHit) hitTO++; if (tcHit) hitTC++;
                    }
                    // 車いすの頂点が看護師の体に入らない（足・すねと転倒防止のバー・後ろの車輪）
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 lp = chairVertsLocal[k];
                            if (lp.z > -0.1f) continue;                      // 看護師に近い後ろの半分だけ
                            Vector3 w = cw.MultiplyPoint3x4(lp);
                            if (chairVertsPart[k] == "WC_Parts" && lp.y > 0.85f) continue;   // 握り（手でにぎる）
                            if (Physics.CheckSphere(w, 0.002f, 1 << LayerNurse)) { ncHit = true; if (hitNCWhere == "") hitNCWhere = F(t, "0.000") + " 秒 車いす " + chairVertsPart[k] + " が看護師の体に"; }
                        }
                    }
                    nurseChairMin = Mathf.Min(nurseChairMin, nurseChairNow);
                    // 車いすの頂点（見る・壁・ハコブくん）
                    bool csHit = false; float chairRailNow = float.MaxValue;
                    {
                        Matrix4x4 cw = chair.localToWorldMatrix;
                        for (int k = 0; k < chairVertsLocal.Count; k++)
                        {
                            Vector3 w = cw.MultiplyPoint3x4(chairVertsLocal[k]);
                            seeVert(w, "車いす " + chairVertsPart[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)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 " + chairVertsPart[k] + "→" + s.name; }
                                float dd = PointBoxDist(w, s.min, s.max);
                                chairSolidMin = Mathf.Min(chairSolidMin, dd);
                                if (s.rail) chairRailNow = Mathf.Min(chairRailNow, dd);
                            }
                        }
                    }
                    chairRailMin = Mathf.Min(chairRailMin, chairRailNow);
                    // 茂さんの頂点（見る・壁・ハコブくん）
                    foreach (var smr in morParts)
                    {
                        if (!smr.gameObject.activeInHierarchy) continue;
                        smr.BakeMesh(bakedM, true);
                        Matrix4x4 m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                        var vs = bakedM.vertices;
                        for (int i = 0; i < vs.Length; i += 2)
                        {
                            Vector3 w = m.MultiplyPoint3x4(vs[i]);
                            seeVert(w, "茂さん " + smr.name);
                            foreach (var s in solids)
                            {
                                if (w.x < s.min.x - 0.1f || w.x > s.max.x + 0.1f || w.z < s.min.z - 0.1f || w.z > s.max.z + 0.1f) continue;
                                if (InBox(w, s.min, s.max)) { csHit = true; if (hitCSWhere == "") hitCSWhere = F(t, "0.000") + " 秒 茂さん " + smr.name + "→" + s.name; }
                                chairSolidMin = Mathf.Min(chairSolidMin, PointBoxDist(w, s.min, s.max));
                            }
                        }
                    }
                    obs.Add(ob);
                    if (gap <= 0f) hitRG++;
                    if (ncHit && ncTimes.Count < 80) ncTimes.Add(F(t, "0.000"));
                    if (csHit) hitCS++; if (ncHit) hitNC++; if (hgHit) hitHandGrip++; if (nsHit) hitNS++;
                    if (gap < gapMin) { gapMin = gap; gapMinT = t; gapMinWhere = gapWhere; }
                    bool overlapZ = ob.nearZ <= rz + rs.maxZ && ob.farZ >= rz + rs.minZ;
                    if (overlapZ && gap < gapPassMin) { gapPassMin = gap; gapPassMinT = t; }
                    if (resumeT >= 0f) foreach (var kc in new List<string>(passNow.Keys)) if (passNow[kc] < passMin[kc]) { passMin[kc] = passNow[kc]; passMinT[kc] = t; }
                    if (t < shT0 - 1e-4f && gap < gapPreShift) { gapPreShift = gap; gapPreShiftT = t; }
                    if (alignT < 0f && ob.nearZ <= rz + rs.maxZ) { alignT = t; alignChairX = chair.position.x - O.x; alignGap = gap; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 車いすの前の端がハコブくんの前の端と並んだ（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）", t, alignChairX, gap)); }
                    if (overlapZ) { float cxp = chair.position.x - O.x; chairXpassMin = Mathf.Min(chairXpassMin, cxp); chairXpassMax = Mathf.Max(chairXpassMax, cxp); }

                    // ハコブくんと箱（壁・手すり・扉）
                    bool rsHit = false; float railGapNow = float.MaxValue;
                    Matrix4x4 toW = dir.robot.localToWorldMatrix;
                    foreach (var v in rs.verts)
                    {
                        Vector3 w = toW.MultiplyPoint3x4(v);
                        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 (hitRSWhere == "") hitRSWhere = F(t, "0.000") + " 秒 →" + s.name; }
                            if (s.rail) railGapNow = Mathf.Min(railGapNow, PointBoxDist(w, s.min, s.max));
                        }
                    }
                    if (rsHit) hitRS++;
                    robotRailMin = Mathf.Min(robotRailMin, railGapNow);
                    if (f > 0) { vMin = Mathf.Min(vMin, rv); vMax = Mathf.Max(vMax, rv); aMax = Mathf.Max(aMax, ra); aMin = Mathf.Min(aMin, ra); }
                    xMinR = Mathf.Min(xMinR, rx); xMaxR = Mathf.Max(xMaxR, rx); yawMaxR = Mathf.Max(yawMaxR, Mathf.Abs(ryaw));
                    if (rv == 0f && mode == "stop")
                    {
                        if (!stopped) { stopped = true; stopT = t; stopPos = dir.robot.position; stopYaw = ryaw; stopFrontGap = ob.nearZ - (rz + rs.maxZ); log.AppendLine(string.Format(IC, "  {0:0.000} 秒 止まった（x {1:0.0000}・z {2:0.0000}・向き {3:0.000}°・足のせの前の端とのあいだ {4:0.000} m）", t, rx, rz, ryaw, stopFrontGap)); }
                        stopMove = Mathf.Max(stopMove, Vector3.Distance(dir.robot.position, stopPos) + Mathf.Abs(Mathf.DeltaAngle(ryaw, stopYaw)) * 0.01f);
                        robotRailMinStop = Mathf.Min(robotRailMinStop, railGapNow); stopFrames++;
                    }

                    // 手と握り
                    float pgL = float.NaN, pgR = float.NaN;
                    bool gbNow = gripBoth[Mathf.Min(f, gripBoth.Count - 1)].I() == 1;
                    {
                        // 依頼235：右手を握りからはなした時刻・握り直した時刻（右手の重み）
                        float wR = dir.nurse.hands[1].weight;
                        if (prevGripR && wR < 0.999f && relT < 0f) relT = t;
                        if (!prevGripR && wR >= 0.999f && regripT < 0f) regripT = t;
                        prevGripR = wR >= 0.999f;
                    }
                    for (int s = 0; s < 2; s++)
                    {
                        if (s == 1 && !gbNow) continue;     // 依頼235：右手をはなしている間は数えない
                        Vector3 pc = toC.MultiplyPoint3x4(dir.nurse.PalmCenter(s));
                        float ax = pc.x - (s == 0 ? -gripX : gripX), ay = pc.y - gripY, az = Mathf.Max(0f, Mathf.Abs(pc.z + gripZ) - 0.035f);
                        float d = Mathf.Sqrt(ax * ax + ay * ay + az * az) - gripR;
                        if (s == 0) pgL = d; else pgR = d;
                        if (d > palmGripMax) { palmGripMax = d; palmGripMaxT = t; }
                        palmGripMin = Mathf.Min(palmGripMin, d);
                        var h = dir.nurse.hands[s];
                        float te = Vector3.Distance(dir.nurse.PalmCenter(s), h.palmTarget);
                        if (te > palmTargetErrMax) { palmTargetErrMax = te; palmTargetErrT = t; }
                        if (t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) { shPalmErr = Mathf.Max(shPalmErr, te); shPalmGripMin = Mathf.Min(shPalmGripMin, d); shPalmGripMax = Mathf.Max(shPalmGripMax, d); }
                    }

                    // 依頼235：寄せる道・体と顔の向き・寺島さん
                    float frNow = float.NaN;
                    {
                        Vector3 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        float cy = Mathf.DeltaAngle(180f, chair.eulerAngles.y);
                        if (float.IsNaN(axZ0) && t >= shT0 - 1e-4f) axZ0 = axle.z;
                        if (t >= shT0 - 1e-4f && t <= shT1 + 0.5f)
                        {
                            manYawMax = Mathf.Max(manYawMax, Mathf.Abs(cy));
                            if (havePA) { float v1 = Vector3.Distance(axle, prevAxle) / dt, w1 = Mathf.Abs(Mathf.DeltaAngle(cy, prevCy)) / dt; if (v1 > manV) { manV = v1; manVT = t; } if (w1 > manW) { manW = w1; manWT = t; } }
                            manFwd = Mathf.Max(manFwd, axZ0 - axle.z); manBack = Mathf.Max(manBack, axle.z - axZ0);
                        }
                        prevAxle = axle; prevCy = cy; havePA = true;
                        // 足のせの前の端（車いすの頂点で一番 −z）とハコブくんの前の端
                        float fz = float.MaxValue; Matrix4x4 cw2 = chair.localToWorldMatrix; foreach (var v in chairVertsLocal) if (v.z > 0.5f) fz = Mathf.Min(fz, cw2.MultiplyPoint3x4(v).z);
                        float fr = fz - (rz + rs.maxZ + O.z); frNow = fr;
                        if (stopped && resumeT < 0f && fr < footRobotMin) { footRobotMin = fr; footRobotMinT = t; }
                        // 依頼237：ハコブくんが車いすの横にいる間（走り出した後、前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）
                        if (resumeT >= 0f && besideT0 < 0f && fr <= 0f) { besideT0 = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんの前の端が足のせの前の端を過ぎた（横にいる間の始まり）", t)); }
                        if (besideT0 >= 0f && besideT1 < 0f && (rz + rs.minZ) - ob.nurseFarZ >= 0f) { besideT1 = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんの後ろの端が大城さんの後ろの端を過ぎた（横にいる間の終わり）", t)); }
                        // 大城さんの体の向き（車いすから）・顔（体から）
                        float bodyRel = Mathf.Abs(Mathf.DeltaAngle(nr.eulerAngles.y, chair.eulerAngles.y));
                        if (bodyRel > oBodyRelMax) { oBodyRelMax = bodyRel; oBodyRelMaxT = t; }
                        if (!gbNow && Mathf.Abs(dir.nurse.headYawDeg) > oHeadMaxTalk) { oHeadMaxTalk = Mathf.Abs(dir.nurse.headYawDeg); oHeadMaxTalkT = t; }
                        if (!gbNow)
                        {
                            var tEL = CloseupNurse.Find(teraN.transform, "Eye_L"); var tER = CloseupNurse.Find(teraN.transform, "Eye_R");
                            var oEL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var oER = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                            float la = Vector3.Angle(dir.nurse.HeadForward(), 0.5f * (tEL.position + tER.position) - 0.5f * (oEL.position + oER.position));
                            oLookTeraMin = Mathf.Min(oLookTeraMin, la);
                        }
                        if (Mathf.Abs(teraN.headYawDeg) > tHeadMax) { tHeadMax = Mathf.Abs(teraN.headYawDeg); tHeadMaxT = t; }
                        Vector3 tp = teraN.transform.position;
                        var tr0 = C["tera_ret"]["t"];
                        if (t >= tr0[0].F() - 1e-4f && t <= tr0[1].F() + 1e-4f)
                        {
                            if (float.IsNaN(teraX0)) { teraX0 = tp.x; teraZ0 = tp.z; teraRetT0 = t; }
                            teraRetDist = Mathf.Max(teraRetDist, new Vector2(tp.x - teraX0, tp.z - teraZ0).magnitude); teraRetT1 = t;
                        }
                        prevTera = tp;
                    }
                    // 目線：大城さんの顔の向きとハコブくんの画面
                    Vector3 scr = dir.ScreenWorld(0f, 0f, 0f);
                    var eyeL = CloseupNurse.Find(dir.nurse.transform, "Eye_L"); var eyeR = CloseupNurse.Find(dir.nurse.transform, "Eye_R");
                    Vector3 headPos = 0.5f * (eyeL.position + eyeR.position);
                    float lookNow = Vector3.Angle(dir.nurse.HeadForward(), scr - headPos);
                    var lw = shot["look_windows"];
                    for (int k = 0; k < lw.Count; k++) if (t >= lw[k][0].F() - 1e-4f && t <= lw[k][1].F() + 1e-4f) { lookSum += lookNow; lookN++; if (lookNow > lookWorst) { lookWorst = lookNow; lookWorstT = t; } }
                    // 茂さんの顔の向き（Head の骨の前）とハコブくんの画面
                    Vector3 mEye = 0.5f * (mEyeL.position + mEyeR.position);
                    Vector3 mFwd = chair.rotation * (qHead * Vector3.forward);
                    float mLook = Vector3.Angle(mFwd, scr - mEye);
                    Vector3 mToR = Quaternion.Inverse(chair.rotation) * (scr - mEye); float mToRobot = Mathf.Atan2(mToR.x, mToR.z) * Mathf.Rad2Deg;   // 依頼237：茂さんの目からハコブくんの画面へ（車いすから見た向き・+ はハコブくんの側）
                    if (Mathf.Abs(mYaw) > 0.9f * mYawMax && mYawMax > 1f && mLook < mLookBest) { mLookBest = mLook; mLookBestT = t; }

                    // 骨：1 コマの動き（根の動きを除いた）
                    Vector3 rootNow = dir.nurse.transform.position;
                    bonesCsv.Append(f + "," + F(t, "0.000"));
                    for (int b = 0; b < bonesList.Count; b++)
                    {
                        Vector3 p = an.GetBoneTransform(bonesList[b]).position;
                        bonesCsv.Append("," + F(p.x, "0.00000") + "," + F(p.y, "0.00000") + "," + F(p.z, "0.00000"));
                        if (havePrev)
                        {
                            float dw = Vector3.Distance(p, prevBones[b]);
                            float drl = ((p - prevBones[b]) - (rootNow - prevRoot)).magnitude;
                            if (dw > jumpW) { jumpW = dw; jumpWT = t; jumpWB = bonesList[b].ToString(); }
                            if (drl > jumpR) { jumpR = drl; jumpRT = t; jumpRB = bonesList[b].ToString(); }
                        }
                        prevBones[b] = p;
                    }
                    bonesCsv.AppendLine();
                    prevRoot = rootNow; havePrev = true;
                    for (int b = 0; b < mBones.Length; b++)
                    {
                        Vector3 lp = chair.InverseTransformPoint(mBones[b].position);
                        if (mHavePrev) { float d = Vector3.Distance(lp, mPrevLocal[b]); if (d > mJump) { mJump = d; mJumpT = t; mJumpB = mBoneNames[b]; } }
                        mPrevLocal[b] = lp;
                    }
                    mHavePrev = true;

                    // 足（217 と同じ）
                    {
                        bool inWalk = dir.InStep(t);
                        float lMin = float.MaxValue, rMin = float.MaxValue;
                        shoeSmr.BakeMesh(shoeMesh, true);
                        Matrix4x4 sm = Matrix4x4.TRS(shoeSmr.transform.position, shoeSmr.transform.rotation, Vector3.one);
                        Vector3 lfp = an.GetBoneTransform(HumanBodyBones.LeftFoot).position, rfp = an.GetBoneTransform(HumanBodyBones.RightFoot).position;
                        var sv = shoeMesh.vertices;
                        if (shoePrev == null || shoePrev.Length != sv.Length) { shoePrev = new Vector3[sv.Length]; shoeAcc = new float[sv.Length]; shoeOn = new bool[sv.Length]; }
                        bool winChange = inWalk != prevInWalk; 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 && (!shoeOn[i] || winChange)) shoePrev[i] = w;
                            shoeAcc[i] = on ? new Vector2(w.x - shoePrev[i].x, w.z - shoePrev[i].z).magnitude : 0f;
                            shoeOn[i] = on;
                            slideNow = Mathf.Max(slideNow, shoeAcc[i]);
                        }
                        if (inWalk && t >= shT0 - 1e-4f && t <= shT1 + 1e-4f) shSlide = Mathf.Max(shSlide, slideNow);
                        if (inWalk)
                        {
                            walkFrames++;
                            if (slideNow > slideMax) { slideMax = slideNow; slideMaxT = t; }
                            float low = Mathf.Min(lMin, rMin);
                            if (-low > sinkMax) { sinkMax = -low; sinkMaxT = t; }
                            if (low > floatMax) { floatMax = low; floatMaxT = t; }
                        }
                        feetCsv.AppendLine(f + "," + F(t, "0.000") + "," + (inWalk ? 1 : 0) + "," + F(lMin) + "," + F(rMin) + "," + F(slideNow));
                    }

                    // 走り出した後：ハコブくんが depart のカメラの画面の外へ出たか
                    int robotIn = -1;
                    if (resumeT >= 0f && depCam != null && !depCam.IsNull)
                    {
                        SetCam(dir.cam, depCam, O, dir);
                        robotIn = 0;
                        foreach (var r in dir.robot.GetComponentsInChildren<Renderer>())
                        {
                            if (!r.gameObject.activeInHierarchy) continue;
                            var bb = r.bounds;
                            for (int c8 = 0; c8 < 8 && robotIn == 0; c8++)
                            {
                                Vector3 p = new Vector3((c8 & 1) == 0 ? bb.min.x : bb.max.x, (c8 & 2) == 0 ? bb.min.y : bb.max.y, (c8 & 4) == 0 ? bb.min.z : bb.max.z);
                                Vector3 vp = dir.cam.WorldToViewportPoint(p);
                                if (vp.z > 0f && vp.x > 0f && vp.x < 1f && vp.y > 0f && vp.y < 1f) robotIn = 1;
                            }
                        }
                        if (robotIn == 0 && exitT < 0f && t > resumeT + 0.5f) { exitT = t; log.AppendLine(string.Format(IC, "  {0:0.000} 秒 ハコブくんが depart のカメラの画面の外へ出た", t)); }
                    }

                    string camName = CutAt(shot, t);
                    float nrv = 0f; { var kz = shot["nurse"]["z"]; nrv = -(CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t + dt * 0.5f, 0f) - CloseupDirector.Num(new Dictionary<string, JsonValue> { { "z", kz } }, "z", t - dt * 0.5f, 0f)) / dt; }
                    csv.AppendLine(f + "," + F(t, "0.000") + "," + camName + "," + F(rx) + "," + F(rz) + "," + F(ryaw, "0.000") + "," + F(rv) + "," + F(ra) + "," + F(vxr) + "," + mode + "," + scrNow + "," +
                                   F(nr.position.z - O.z) + "," + F(nrv) + "," + F(chair.position.z - O.z) + "," + F(ob.nearZ - (rz + rs.maxZ)) + "," + F(gap) + "," + (float.IsNaN(gapLane) ? "" : F(gapLane)) + "," + (float.IsNaN(need) ? "" : F(need)) + "," +
                                   F(rearZ - ob.nurseFarZ) + "," + F(railGapNow) + "," + F(chairRailNow) + "," + (nurseChairNow < float.MaxValue ? F(nurseChairNow) : "") + "," + F(pgL) + "," + F(pgR) + "," +
                                   F(dir.nurse.headYawDeg, "0.000") + "," + F(dir.nurse.headNodDeg, "0.000") + "," + nml + "," + F(lookNow, "0.00") + "," + F(mYaw, "0.00") + "," + F(mNod, "0.00") + "," + mMouth + "," + F(mbl, "0.00") + "," + F(mLook, "0.00") + "," + robotIn + "," +
                                   F(chair.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, chair.eulerAngles.y), "0.000") + "," + F(nr.position.x - O.x) + "," + F(Mathf.DeltaAngle(180f, nr.eulerAngles.y), "0.000") + "," + F(mToRobot, "0.00") + "," + F(frNow) + "," + F((rz + rs.minZ) - ob.nurseFarZ));

                    // ---------- 依頼230：真上の画面の位置（車いすの後ろの車軸の真ん中・ハコブくんの根）と、画面の中か
                    {
                        SetTop230(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 axle = chair.TransformPoint((hubL0 + hubR0) * 0.5f); axle.y = 0f;
                        Vector3 rRoot = dir.robot.position; rRoot.y = 0f;
                        Vector2 pa = px(axle), pr = px(rRoot);
                        int cIn = 0, cAll = 0; foreach (var v in chairVertsLocal) { cAll++; if (inV(chair.TransformPoint(v))) cIn++; }
                        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++;
                        int nIn = 0; foreach (var hb in bonesList) if (inV(an.GetBoneTransform(hb).position)) nIn++;
                        topCsv.AppendLine(f + "," + F(t, "0.000") + "," + F(axle.x - O.x, "0.00000") + "," + F(axle.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") + "," +
                                          (cIn == cAll ? 2 : cIn > 0 ? 1 : 0) + "," + (rIn == 4 ? 2 : rIn > 0 ? 1 : 0) + "," + (nIn == bonesList.Count ? 2 : nIn > 0 ? 1 : 0));
                        if (f == 0)
                        {
                            // 床の点から画面の位置への写し方（正射影なので 3 点で決まる）
                            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(string.Format(IC, "  \"chair_axle_local\": [{0:0.00000}, {1:0.00000}, {2:0.00000}]", ((hubL0 + hubR0) * 0.5f).x, ((hubL0 + hubR0) * 0.5f).y, ((hubL0 + hubR0) * 0.5f).z));
                            cj.AppendLine("}");
                            File.WriteAllText(Path.Combine(outDir, "top238_cam.json"), cj.ToString(), new UTF8Encoding(false));
                        }
                    }

                    // ---------- 撮る
                    bool inRange = t >= fromT - 1e-4f && t <= toT + 1e-4f;
                    {
                        var ffk = C["ff"]; int spd = C["ff_speed"].I(4);
                        for (int k = 0; ffk != null && k < ffk.Count; k++)
                        {
                            int a0 = Mathf.RoundToInt(ffk[k][0].F() * fps), a1 = Mathf.RoundToInt(ffk[k][1].F() * fps);
                            if (f > a0 && f < a1 && (f - a0) % spd != 0) inRange = false;     // 依頼235：早回しの所は使うコマだけ撮る
                        }
                    }
                    if ((vMain || vTop) && f >= vFrom && f <= vTo && 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) { SetTop230(dir.cam, topJs, O); SavePng(Shoot(dir.cam, W, H, SS), Path.Combine(fdirT, string.Format("f_{0:00000}.png", f))); }
                        if (vTop)
                        {
                            // 依頼232：体だけの型（同じ真上のカメラ・同じ大きさ）
                            var body = BodyRenderers(new[] { dir.robot, chair, mor, proxyRoot, dir.nurse.transform, proxyRootT, teraN.transform });
                            if (!log.ToString().Contains("依頼232 体の型")) LogRenderers232(body, log);
                            SavePng(ShootMask(dir.cam, body, W, H, SS), Path.Combine(fdirT + "_mask", string.Format("f_{0:00000}.png", f)));
                            // 依頼234：もの別の型（赤＝ハコブくん・緑＝車いすと茂さん・青＝大城さん）
                            var grp = new List<Renderer>[4]; for (int g = 0; g < 4; g++) grp[g] = new List<Renderer>();
                            foreach (var rd in body) grp[(rd.transform.IsChildOf(proxyRootT) || rd.transform.IsChildOf(teraN.transform)) ? 3 : Group234(rd, dir.robot, chair, mor)].Add(rd);
                            if (!log.ToString().Contains("依頼234 もの別")) { log.AppendLine("依頼234 もの別の型の部品"); string[] gn = { "赤 ハコブくん", "緑 車いすと茂さん", "青 大城さん", "アルファ 寺島さん" }; for (int g = 0; g < 4; g++) { log.Append("  " + gn[g] + " " + grp[g].Count + "："); foreach (var rd in grp[g]) log.Append(" " + rd.name); log.AppendLine(); } }
                            var obj = new Texture2D(W, H, TextureFormat.RGBA32, false);
                            var px = new Color32[W * H];
                            for (int g = 0; g < 4; g++)
                            {
                                var m = ShootMask(dir.cam, grp[g], W, H, SS); var mp = m.GetPixels32();
                                for (int i = 0; i < px.Length; i++) { if (g == 0) px[i].r = mp[i].r; else if (g == 1) px[i].g = mp[i].r; else if (g == 2) px[i].b = mp[i].r; else px[i].a = mp[i].r; }
                                UnityEngine.Object.DestroyImmediate(m);
                            }
                            obj.SetPixels32(px); 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") SetTop230(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, sn + ".png"));
                    }
                }
                File.WriteAllText(Path.Combine(outDir, "frames238.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "top238.csv"), topCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones238.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet238.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc238.csv"), wcCsv.ToString(), new UTF8Encoding(false));

                tab.AppendLine("■ " + shotName);
                tab.AppendLine(string.Format(IC, "見つけた\t{0:0.000} 秒（前の端とのあいだ {1:0.000} m）", seenT, seenGap));
                tab.AppendLine(string.Format(IC, "決まりに当たった\t{0:0.000} 秒・前の端とのあいだ {1:0.000} m ＜ {2:0.000} m（自分が止まるまで {3:0.000} m・{4:0.000} 秒＋相手の進む分＋余り {5:0.000}）・ふだんの位置のすき間の予想 {6:0.000} m・寄った位置 {7:0.000} m → {8}",
                                              trigT, trigGap, trigNeed, trigDm, trigTm, R.margin, trigGapLane, trigGapWall, trigT >= 0f ? "止まる" : "-"));
                tab.AppendLine(string.Format(IC, "減速の始まり・寄り終わり・止まった\t{0:0.000}・{1:0.000}・{2:0.000} 秒（止まった時の足のせの前の端とのあいだ {3:0.000} m・位置 x {4:0.0000} z {5:0.0000}・向き {6:0.000}°）",
                                              decelT, latDoneT, stopT, stopFrontGap, stopPos.x - O.x, stopPos.z - O.z, stopYaw));
                tab.AppendLine(string.Format(IC, "走り出し\t{0:0.000} 秒（看護師の体とハコブくんの後ろの端 {1:0.000} m・物全体 {2:0.000} m）・画面の外 {3:0.000} 秒", resumeT, nurseBehindAtResume, behindAtResume, exitT));
                tab.AppendLine(string.Format(IC, "止まっている間の動き\t{0:0.0000} m（{1} コマ）", stopMove, stopFrames));
                tab.AppendLine(string.Format(IC, "ハコブくんの速さ\t{0:0.0000}〜{1:0.0000} m/秒・加速度 {2:0.000}〜{3:0.000} m/秒²・横の位置 {4:0.000}〜{5:0.000} m・向きの最大 {6:0.00}°", vMin, vMax, aMin, aMax, xMinR, xMaxR, yawMaxR));
                tab.AppendLine(string.Format(IC, "当たったコマ\tハコブくんと（車いす・茂さん・看護師）{0}・車いす/茂さんと壁/手すり/扉 {1}（{2}）・ハコブくんと壁/手すり/扉 {3}（{4}）・看護師と車いす {5}・手が握りの中 {6}（{7}）・看護師と壁/手すり/扉 {8}（{9}）",
                                              hitRG, hitCS, hitCSWhere, hitRS, hitRSWhere, hitNC, hitHandGrip, hitNCWhere, hitNS, hitNSWhere));
                tab.AppendLine(string.Format(IC, "ハコブくんと物の一番近い距離\t{0:0.000} m（{1:0.000} 秒・{2}）・前後が重なる間（すれ違う時）の最小 {3:0.000} m（{4:0.000} 秒）", gapMin, gapMinT, gapMinWhere, gapPassMin, gapPassMinT));
                tab.AppendLine(string.Format(IC, "手すりとのすき間\tハコブくん 最小 {0:0.000} m・止まっている間 {1}・車いす/茂さん 最小 {2:0.000} m（手すり）・{3:0.000} m（壁/扉を含む）・看護師 {4:0.000} m",
                                              robotRailMin, robotRailMinStop < float.MaxValue ? F(robotRailMinStop, "0.000") + " m" : "-", chairRailMin, chairSolidMin, nurseSolidMin));
                tab.AppendLine(string.Format(IC, "看護師と車いすの頂点の一番近い所（手を除く・高さ 0.6 m より下・参考）\t{0:0.0000} m（{1}）", nurseWheelMin, nurseWheelWhere));
                tab.AppendLine(string.Format(IC, "手と握り\t手のひらの中心と握りの面の距離 {0:0.0000}〜{1:0.0000} m（最大 {2:0.000} 秒）・手のひらの的とのずれの最大 {3:0.0000} m（{4:0.000} 秒）", palmGripMin, palmGripMax, palmGripMaxT, palmTargetErrMax, palmTargetErrT));
                tab.AppendLine(string.Format(IC, "手の頂点と握りの面\t一番近い {0:0.0000} m（負は中・{1}）", handGripMin, handGripWhere));
                tab.AppendLine(string.Format(IC, "車いす\t根の高さのずれ {0:0.00000} m・後ろの車輪の下 {1:0.00000}〜{2:0.00000} m・前の車輪の下 {3:0.00000}〜{4:0.00000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°",
                                              chairYErr, tireYMin, tireYMax, cTireYMin, cTireYMax, wheelSlipMax, casterSlipMax, casYawMax));
                tab.AppendLine(string.Format(IC, "足（看護師）\t歩く所 {0} コマ・すべり最大 {1:0.00} cm（{2:0.000} 秒）・沈み {3:0.00} cm（{4:0.000}）・両足とも浮いた {5:0.00} cm（{6:0.000}）", walkFrames, slideMax * 100f, slideMaxT, sinkMax * 100f, sinkMaxT, floatMax * 100f, floatMaxT));
                tab.AppendLine(string.Format(IC, "1 コマの骨の動き\t看護師 根の動きを除いた最大 {0:0.00} cm（{1}・{2:0.000} 秒）・世界の最大（参考）{3:0.00} cm（{4}・{5:0.000} 秒）・茂さん（車いすから）{6:0.00} cm（{7}・{8:0.000} 秒）",
                                              jumpR * 100f, jumpRB, jumpRT, jumpW * 100f, jumpWB, jumpWT, mJump * 100f, mJumpB, mJumpT));
                tab.AppendLine(string.Format(IC, "目線\t大城さん：見る間の顔の向きと画面への向きの角度 平均 {0:0.00}°・一番大きい {1:0.00}°（{2:0.000} 秒）・{3} コマ／茂さん：顔の向き 最大 {4:0.0}°・うなずき {5:0.0}°・向けている間の画面への角度の最小 {6:0.0}°（{7:0.000} 秒）",
                                              lookN > 0 ? lookSum / lookN : 0f, lookWorst, lookWorstT, lookN, mYawMax, mNodMax, mLookBest, mLookBestT));
                tab.AppendLine(string.Format(IC, "車いすの横の位置（根）\t始め x {0:0.0000}・寄せ始め（{1:0.000} 秒）x {2:0.0000}・寄せ終わり（{3:0.000} 秒）x {4:0.0000}・すれ違う間 x {5:0.0000}〜{6:0.0000}",
                                              chairX0, shT0, chairXsh0, shT1, chairXsh1, chairXpassMin, chairXpassMax));
                tab.AppendLine(string.Format(IC, "車いすの向き・横の速さ\t向きの最大 {0:0.000}°（{1:0.000} 秒）・横の速さの最大 根 {2:0.0000} m/秒（{3:0.000}）・足のせの前の端 {4:0.0000} m/秒（{5:0.000}）",
                                              chairYawMax, chairYawMaxT, chairLatV, chairLatVT, frontLatV, frontLatVT));
                tab.AppendLine(string.Format(IC, "前の端が並んだ\t{0:0.000} 秒（車いすの根 x {1:0.0000}・すき間 {2:0.000} m）・寄せ終わりとの差 {3:0.000} 秒", alignT, alignChairX, alignGap, alignT - shT1));
                tab.AppendLine(gapPreShift < 1.5f ? string.Format(IC, "寄せ始める前のすき間の最小\t{0:0.000} m（{1:0.000} 秒）", gapPreShift, gapPreShiftT) : "寄せ始める前のすき間の最小\t1.5 m より遠い");
                tab.AppendLine(string.Format(IC, "寄せる間（{0:0.000}〜{1:0.000} 秒）\t手のひらの的とのずれ最大 {2:0.0000} m・手のひらの中心と握りの面 {3:0.0000}〜{4:0.0000} m・後ろの車輪の横すべり {5:0.00000} m/コマ・前の車輪の横すべり {6:0.00000} m/コマ・前の車輪の向きの最大 {7:0.00}°・足のすべり最大 {8:0.00} cm",
                                              shT0, shT1, shPalmErr, shPalmGripMin, shPalmGripMax, shWheelSlip, shCasterSlip, shCasYaw, shSlide * 100f));
                tab.AppendLine(string.Format(IC, "前の車輪の向きの最大（全体）\t{0:0.00}°（{1:0.000} 秒）", casYawMax, casYawMaxT));
                tab.AppendLine("■ 依頼235 の確かめ");
                tab.AppendLine(string.Format(IC, "寄せる道（{0:0.000}〜{1:0.000} 秒）\t車いすの向きの最大 {2:0.00}°・後ろの車軸の速さの最大 {3:0.0000} m/秒（{4:0.000} 秒）・向きの変わる速さの最大 {5:0.00}°/秒（{6:0.000} 秒）・前へ進んだ距離 {7:0.0000} m・後ろへ下がった距離 {8:0.0000} m（寄せ始めの車軸から）",
                                              shT0, shT1, manYawMax, manV, manVT, manW, manWT, manFwd, manBack));
                tab.AppendLine(string.Format(IC, "足のせの前の端とハコブくんの前の端（止まってから走り出すまで）\t最小 {0:0.0000} m（{1:0.000} 秒）", footRobotMin, footRobotMinT));
                tab.AppendLine(string.Format(IC, "大城さん\t体の向き（車いすから）の最大 {0:0.00}°（{1:0.000} 秒）・顔の向き（体から・片手の間）の最大 {2:0.00}°（{3:0.000} 秒）・寺島さんの目への角度の最小 {4:0.0}°・右手をはなした {5:0.000} 秒・握り直した {6:0.000} 秒・車いすが根に固い時のずれ {7:0.00000}",
                                              oBodyRelMax, oBodyRelMaxT, oHeadMaxTalk, oHeadMaxTalkT, oLookTeraMin, relT, regripT, rigidErr));
                tab.AppendLine(string.Format(IC, "寺島さん\t顔の向きの最大 {0:0.00}°（{1:0.000} 秒）・下がった距離 {2:0.0000} m（{3:0.000}〜{4:0.000} 秒）・当たったコマ 壁/手すり {5}・大城さん {6}・車いす {7}（{8}）",
                                              tHeadMax, tHeadMaxT, teraRetDist, teraRetT0, teraRetT1, hitTS, hitTO, hitTC, hitTWhere));
                tab.AppendLine(string.Format(IC, "走り出し（依頼235 の決まり）\t{0:0.000} 秒・止まってから {1:0.000} 秒・寄った位置のすき間 {2:0.000} m・物の一番後ろを通り過ぎた {3:0.000} 秒", resumeT, resumeT - stopT, resumeGapWall, passedT));
                tab.AppendLine(string.Format(IC, "ハコブくんが通る時（走り出し後）のすき間の最小\t車いす {0:0.000} m（{1:0.000} 秒）・茂さん {2:0.000} m（{3:0.000}）・大城さん {4:0.000} m（{5:0.000}）・寺島さん {6:0.000} m（{7:0.000}）",
                                              passMin["車いす"], passMinT["車いす"], passMin["茂さん"], passMinT["茂さん"], passMin["看護師"], passMinT["看護師"], passMin["寺島さん"], passMinT["寺島さん"]));
                tab.AppendLine("■ 依頼237 の確かめ");
                tab.AppendLine(string.Format(IC, "ハコブくんが車いすの横にいる間\t{0:0.000}〜{1:0.000} 秒（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）", besideT0, besideT1));
                tab.AppendLine("看護師と車いすが当たったコマの時刻\t" + string.Join("・", ncTimes.ToArray()));
                tab.AppendLine("茂さんのまばたき\t" + string.Join("・", mBlinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("大城さんのまばたき\t" + string.Join("・", dir.Blinks.ConvertAll(x => x.ToString("0.000", IC)).ToArray()));
                tab.AppendLine("画面の変わり目\t" + string.Join("／", scrChanges.ToArray()));
                foreach (var e in dir.events) log.AppendLine("  " + e);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                log.AppendLine("エラー: " + e);
            }
            File.WriteAllText(Path.Combine(outDir, "check238.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events238.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C238] done\n" + log + "\n" + tab);
        }

        /// <summary>依頼229：茂さん・車いすの読み込みの設定が 228 のままかを確かめるだけ（Models/ に書かない）。違えば止める</summary>
        static void CheckImport(StringBuilder sb)
        {
            foreach (var p in new[] { Closeup228Morita.MoritaFbx, Closeup228Morita.ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == Closeup228Morita.MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool ok = mi.animationType == at && mi.isReadable && !mi.importAnimation && mi.materialImportMode == ModelImporterMaterialImportMode.ImportStandard
                          && (!morita || mi.avatarSetup == ModelImporterAvatarSetup.NoAvatar) && mi.GetExternalObjectMap().Count > 0;
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・228 の設定のまま " + (ok ? "はい" : "いいえ"));
                if (!ok) throw new Exception("読み込みの設定が 228 と違う（Models/ は変えない決まりなので止める）: " + p);
            }
        }

        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, string like)
        {
            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" なら z をハコブくんの z から、"nurse" なら看護師の根の z から</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();   // 依頼230：真上のカメラ（正射影・横縦比を決めた）の後でも 229 のまま
            Vector3 add = Vector3.zero;
            string fo = C["follow"].S("");
            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);
            if (fo == "nurse_xz")
            {
                // 依頼229：大城さんの根の位置と向きから（向き 180°の時の置き方を、根の向きの分だけ回す）
                Transform nt = dir.nurse.transform;
                Quaternion q = Quaternion.Euler(0f, nt.eulerAngles.y - 180f, 0f);
                Vector3 np = new Vector3(nt.position.x, 0f, nt.position.z);
                cam.transform.position = np + q * CloseupDirector.V3(C["pos"]);
                cam.transform.rotation = Quaternion.LookRotation((np + q * CloseupDirector.V3(C["look"])) - cam.transform.position, Vector3.up);
                cam.fieldOfView = C["fov"].F(40f);
                return;
            }
            cam.transform.position = O + add + CloseupDirector.V3(C["pos"]);
            Vector3 up = C.Has("up") ? CloseupDirector.V3(C["up"]) : Vector3.up;
            cam.transform.rotation = Quaternion.LookRotation((O + add + CloseupDirector.V3(C["look"])) - cam.transform.position, up);
            cam.fieldOfView = C["fov"].F(40f);
        }

        /// <summary>依頼230：動かない真上のカメラ（正射影）。center_x・center_z（廊下の原点から）・height（床から）・ortho_size（画面の高さの半分 m）。画面の上が −x・右が +z</summary>
        static void SetTop230(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 maskCam232; static Material white232;

        /// <summary>依頼232：写る体の部品（ハコブくん・車いす・茂さん・大城さんと、写しの部品）。その時に写る物だけ</summary>
        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;
        }

        /// <summary>依頼234：部品がどのものか（0＝ハコブくん・1＝車いすと茂さん・2＝大城さん）。茂さんの写しの部品は名前が Morita_ で始まる</summary>
        static int Group234(Renderer rd, Transform robot, Transform chair, Transform mor)
        {
            var t = rd.transform;
            if (t.IsChildOf(robot)) return 0;
            if (t.IsChildOf(chair) || t.IsChildOf(mor) || rd.name.StartsWith("Morita_")) return 1;
            return 2;
        }

        /// <summary>依頼232：体に数えた部品と、数えなかった部品（廊下など）を書く</summary>
        static void LogRenderers232(List<Renderer> body, StringBuilder log)
        {
            log.AppendLine("依頼232 体の型に入れた部品 " + body.Count + "：");
            foreach (var r in body) log.AppendLine(string.Format(IC, "  体 {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
            int n = 0;
            foreach (var r in UnityEngine.Object.FindObjectsOfType<Renderer>())
            {
                if (!r.enabled || !r.gameObject.activeInHierarchy || body.Contains(r)) continue;
                n++; if (n <= 60) log.AppendLine(string.Format(IC, "  入れない {0}（層 {1}・高さ {2:0.000}〜{3:0.000} m）", r.name, r.gameObject.layer, r.bounds.min.y, r.bounds.max.y));
                if (r.gameObject.layer == LayerMask232) throw new Exception("層 " + LayerMask232 + " を使っている部品がある：" + r.name);
            }
            log.AppendLine("  入れない部品 " + n);
        }

        /// <summary>依頼232：体だけを白く写した型（黒＝床など・白＝体）。真上のカメラ（cam）を写した別のカメラで撮る。cam と部品は元のまま残す</summary>
        static Texture2D ShootMask(Camera cam, List<Renderer> body, int W, int H, int SS)
        {
            if (maskCam232 == null)
            {
                var g = new GameObject("MaskCam232"); maskCam232 = g.AddComponent<Camera>(); maskCam232.enabled = false;
                white232 = new Material(Shader.Find("Unlit/Color")) { name = "Mask232" }; white232.color = Color.white;
            }
            maskCam232.CopyFrom(cam);
            maskCam232.cullingMask = 1 << LayerMask232;
            maskCam232.clearFlags = CameraClearFlags.SolidColor; maskCam232.backgroundColor = Color.black;
            maskCam232.allowHDR = false; maskCam232.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] = white232;
                body[i].sharedMaterials = w;
            }
            try { return Shoot(maskCam232, 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);
        }
    }
}
```

#### tools/an238.py（依頼238）

```python
"""依頼238：an237.py を写して名前だけ 238 に。依頼237：an235.py を写して名前だけ 237 に。報告の表（セリフごとの時刻・カメラの切りかえ・動けない時間・早回し・画面の変わり目）を作る。
使い方: python3 an235.py <Unity の出力フォルダ> <台本> <場面>"""
import csv, json, os, re, sys
D, SC, SHOT = sys.argv[1:4]
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c238"]
vm = json.load(open(os.path.join(D, f"vmap238_{SHOT}.json")))
FPS = 30
ff = [(round(a * FPS), round(b * FPS)) for a, b in C["ff"]]; SPD = C["ff_speed"]
f0 = vm["seq_first"]
def vt(t):
    """台本の秒 → 動画の秒（早回しの所は 1/4）"""
    f = t * FPS; v = (f - f0) / FPS
    for a, b in ff:
        if f > a: v -= (min(f, b) - a) / FPS * (1 - 1 / SPD)
    return v
o = [f"■ {SHOT}"]
o.append(f"動画の長さ {vm['video_s']:.3f} 秒（{vm['n']} コマ・台本 {f0 / FPS:.3f}〜{vm['seq_last'] / FPS:.3f} 秒）")
o.append(f"止まった {vm['t_stop']:.3f} 秒（動画 {vt(vm['t_stop']):.3f}）・走り出し {vm['t_resume']:.3f}（動画 {vt(vm['t_resume']):.3f}）・動けない時間 {vm['t_resume'] - vm['t_stop']:.3f} 秒・物の一番後ろを通り過ぎた {vm['t_pass']:.3f}")
if vm["label_t"] is not None:
    o.append(f"立ち往生の字 {vm['label_t']:.3f} 秒（動画 {vt(vm['label_t']):.3f}）・動けない時間が 30 秒になった {vm['t30']:.3f} 秒・差 {abs(vm['label_t'] - vm['t30']):.3f} 秒")
for a, b in C["ff"]:
    o.append(f"早回し ×{SPD}：台本 {a:.3f}〜{b:.3f} 秒（{b - a:.3f} 秒）→ 動画 {vt(a):.3f}〜{vt(b):.3f} 秒")
o.append("セリフ\t誰\t台本の秒（声の始まり〜終わり）\t動画の秒\t声の長さ")
for k, p in sorted(C["lines"].items(), key=lambda kv: kv[1]["voice_on_s"]):
    o.append(f"{p['text']}\t{p['who']}\t{p['voice_on_s']:.3f}〜{p['voice_off_s']:.3f}\t{vt(p['voice_on_s']):.3f}〜{vt(p['voice_off_s']):.3f}\t{p['voice_len_s']:.3f}")
ls = sorted(C["lines"].values(), key=lambda p: p["voice_on_s"])
o.append("セリフの間（前の声の終わり→次の声の始まり）：" + "・".join(f"{b['text'][:6]} {b['voice_on_s'] - a['voice_off_s']:.3f}" for a, b in zip(ls, ls[1:])))
o.append("カメラ\t台本の秒\t動画の秒")
for t, c in shot["cuts"]:
    if t * FPS <= vm["seq_last"]: o.append(f"{c}\t{t:.3f}\t{max(0.0, vt(t)):.3f}")
rows = list(csv.DictReader(open(os.path.join(D, "frames238.csv"))))
prev = None
o.append("画面の変わり目（台本の秒・動画の秒）")
for r in rows:
    s = r["screen"].split("_")[0]
    if s != prev and float(r["t"]) * FPS <= vm["seq_last"]: o.append(f"  {float(r['t']):.3f}\t{max(0.0, vt(float(r['t']))):.3f}\t{s}"); prev = s
print("\n".join(o))
open(os.path.join(D, f"an238_{SHOT}.txt"), "w").write("\n".join(o) + "\n")
```

#### tools/batch_check.sh（依頼238）

```bash
#!/bin/bash
R=/tmp/c238/tools
for SH in stop_voice stop_stuck; do
  S=$(date +%s); $R/run238.sh /tmp/c238/out/$SH $SH closeup238_script.json off on top; echo "$SH check $(( $(date +%s)-S )) 秒"
done
```

#### tools/batch_render.sh（依頼238）

```bash
#!/bin/bash
# 依頼238（237 の写し）：区切って撮る（1 回 12 分より短く）。使い方: batch_render.sh <場面> <from:to> [<from:to> ...]
R=/tmp/c238/tools; SH="$1"; shift
for c in "$@"; do
  F=${c%%:*}; T=${c##*:}; S=$(date +%s)
  $R/run238b.sh /tmp/c238/out/$SH $SH closeup238_script.json $F $T off
  echo "$SH $F〜$T $(( $(date +%s)-S )) 秒"
done
```

#### tools/make238.py（依頼238）

```python
"""依頼238：make237.py を写して名前だけ 238 に（台本の c238・出力 closeup238_*・events238.txt など）。依頼237：make235.py を写して名前だけ 237 に。以下は 235 の説明：
(1) closeup235_<場面>.mp4：frames/<場面>/f_*.png に台本の秒の音（mix238_<場面>.wav）を重ねる。早回し（台本 c235.ff・×c235.ff_speed）の所は 4 コマに 1 枚を使い、
    音は無し（声の無い所だけを早回しにしている）、右上に「早回し ×4・実際の時間 m:ss」を出す。⑨-2 は 30 秒になった所から 3 秒、左下に「立ち往生 1件（30 秒以上動けず、人が動かした）」
(2) closeup235_<場面>_top.mp4：frames/<場面>_top に 234 の描き方で床の線・通った跡・印・左上の字を重ねる。床の線は、ものごとに穴を埋めた外形
    （閉じる処理 半径 6 画素 → 中の穴埋め）の中には描かない。もの：ハコブくん（赤）・車いすと茂さん（緑）・大城さん（青）・寺島さん（アルファ）。
    大城さんが両手で握りにのせている間（台本 c235.grip_both）は、大城さんと車いすと茂さんを 1 つのものとして埋める（依頼235）
    重ねる順：コマ → 床の線（外形の所は消す）→ 通った跡 → 印 → 左上の字。早回しの所は (1) と同じコマだけ
動画の終わり：ハコブくんが物の一番後ろを通り過ぎてから 2.5 秒（events238.txt）
使い方: python3 make235.py <Unity の出力フォルダ> <台本> <場面> <音の wav> <動画を置くフォルダ>"""
import csv, json, math, os, re, subprocess, sys, tempfile, wave
import numpy as np, cv2
from scipy import ndimage
from PIL import Image, ImageChops, ImageDraw, ImageFont

FF = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
D, SC, SHOT, WAV, VD = sys.argv[1:6]
os.makedirs(VD, exist_ok=True)
SJ = json.load(open(SC)); shot = [s for s in SJ["shots"] if s["name"] == SHOT][0]; C = shot["c238"]
FPS, W, H, S = 30, 1920, 1080, 2
ev = open(os.path.join(D, "events238.txt"), encoding="utf-8").read()
t_stop = float(re.search(r"([\d.]+) 秒 止まった（", ev).group(1))
t_res = float(re.search(r"([\d.]+) 秒 走り出す", ev).group(1))
t_pass = float(re.search(r"([\d.]+) 秒 物の一番後ろを通り過ぎた", ev).group(1))
f0 = int(round(C["video_from"] * FPS)); f1 = min(int(round((t_pass + 2.5) * FPS)), int(round(C["video_to"] * FPS)))
SPD = C["ff_speed"]; ffseg = [(int(round(a * FPS)), int(round(b * FPS))) for a, b in C["ff"]]
def in_ff(f):
    for a, b in ffseg:
        if a < f < b: return (a, b)
    return None
seq = [f for f in range(f0, f1 + 1) if in_ff(f) is None or (f - in_ff(f)[0]) % SPD == 0]
FONT_PATH = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
def font(px, s=1): return ImageFont.truetype(FONT_PATH, px * s)
label = C.get("stuck_label")
# 立ち往生の字は「止まってから 30 秒」のコマ（Unity の止まった時刻から）
t30 = t_stop + 30.0 if label else None

# ---------------------------------------------------------------- (1) 本番の動画
tmp = tempfile.mkdtemp(prefix="m238_", dir="/tmp")
FB, FS = font(40), font(30)
info = {"frames": len(seq), "ff_frames": sum(1 for f in seq if in_ff(f)), "label": None}
for k, f in enumerate(seq):
    src = os.path.join(D, "frames", SHOT, f"f_{f:05d}.png"); assert os.path.exists(src), src
    t = f / FPS
    ff = in_ff(f); lab = t30 is not None and t30 - 1e-4 <= t < t30 + 3.0 - 1e-4
    if not ff and not lab:
        os.symlink(os.path.abspath(src), os.path.join(tmp, f"v_{k:05d}.png")); continue
    im = Image.open(src).convert("RGB"); d = ImageDraw.Draw(im)
    if ff:
        real = t - C["video_from"]; s = f"早回し ×{SPD}　実際の時間 {int(real) // 60}:{int(real) % 60:02d}"
        bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
        d.rounded_rectangle([W - w - 70, 24, W - 24, 24 + 72], radius=12, fill=(255, 255, 255))
        d.text((W - w - 47, 60), s, font=FB, fill=(25, 25, 25), anchor="lm")
    if lab:
        if info["label"] is None: info["label"] = t
        s = "立ち往生 1件（30 秒以上動けず、人が動かした）"
        bb = d.textbbox((0, 0), s, font=FB); w = bb[2] - bb[0]
        d.rounded_rectangle([24, H - 24 - 80, 24 + w + 50, H - 24], radius=12, fill=(242, 194, 48))
        d.text((49, H - 24 - 40), s, font=FB, fill=(25, 25, 25), anchor="lm")
    im.save(os.path.join(tmp, f"v_{k:05d}.png"))
# 音：ふだんの所は台本の秒の音、早回しの所は無音（その長さはコマの数 / 30）
wr = wave.open(WAV); SR = wr.getframerate(); x = np.frombuffer(wr.readframes(wr.getnframes()), np.int16)
out = []
for f in seq:
    a = int(round(f / FPS * SR)); b = a + SR // FPS
    out.append(np.zeros(SR // FPS, np.int16) if in_ff(f) else (x[a:b] if b <= len(x) else np.pad(x[a:min(b, len(x))], (0, b - min(b, len(x))))))
aw = os.path.join(tmp, "a.wav"); w2 = wave.open(aw, "w"); w2.setnchannels(1); w2.setsampwidth(2); w2.setframerate(SR); w2.writeframes(np.concatenate(out).tobytes()); w2.close()
vid = os.path.join(VD, f"closeup238_{SHOT}.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmp, "v_%05d.png"), "-i", aw,
                "-map", "0:v", "-map", "1:a", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30",
                "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", "-shortest", vid], check=True)
# 動画の秒 ↔ 台本の秒
vmap = {f: k / FPS for k, f in enumerate(seq)}
json.dump({"seq_first": seq[0], "seq_last": seq[-1], "n": len(seq), "video_s": len(seq) / FPS, "t_stop": t_stop, "t_resume": t_res, "t_pass": t_pass,
           "label_t": info["label"], "t30": t30, "ff": C["ff"], "vmap_keys": {str(f): round(v, 4) for f, v in vmap.items() if f % 15 == 0}},
          open(os.path.join(D, f"vmap238_{SHOT}.json"), "w"), ensure_ascii=False)
print("動画", vid, len(seq), "コマ", len(seq) / FPS, "秒・早回しのコマ", info["ff_frames"], "・立ち往生の字", info["label"])

# ---------------------------------------------------------------- (2) 真上の動画
CAM = json.load(open(os.path.join(D, "top238_cam.json")))
HUD_PX, LINE_LABEL_PX, MARK_LABEL_PX = 70, 36, 40
COL = {"center": (120, 120, 120), "x042": (142, 36, 170), "lane": (46, 173, 107), "chair": (239, 108, 0), "robot": (0, 105, 92)}
LW = {"center": 3, "dash": 5, "trail": 10, "mark_r": 13, "mark_edge": 3, "leader": 3}
DASH, GAP = 28, 16
ox, oy = CAM["px_origin"]; xx, xy = CAM["px_per_x"]; zx, zy = CAM["px_per_z"]
def to_px(x, z): return (ox + xx * x + zx * z, oy + xy * x + zy * z)
def from_px(px, py):
    det = xx * zy - zx * xy; dx, dy = px - ox, py - oy
    return ((dx * zy - zx * dy) / det, (xx * dy - dx * xy) / det)
rows = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "frames238.csv")))}
top = {int(r["frame"]): r for r in csv.DictReader(open(os.path.join(D, "top238.csv")))}
man = C["man"]
MARKS = [("chair", man["t0"], "寄せ始め"), ("chair", man["t1"], "寄せ終わり"), ("robot", t_stop, "止まった"), ("robot", t_res, "走り出し")]
mark_f = [int(round(t * FPS)) for _, t, _ in MARKS]
FL, FM, FH = font(LINE_LABEL_PX, S), font(MARK_LABEL_PX, S), font(HUD_PX, S)
def sc(p): return (p[0] * S, p[1] * S)
def text_box(d, xy, s, f, fg, anchor, pad=8, bg=(255, 255, 255, 235), edge=None):
    x, y = xy; bb = d.textbbox((x, y), s, font=f, anchor=anchor)
    d.rounded_rectangle([bb[0] - pad * S, bb[1] - pad * S, bb[2] + pad * S, bb[3] + pad * S], radius=6 * S, fill=bg, outline=edge, width=2 * S if edge else 0)
    d.text((x, y), s, font=f, fill=fg, anchor=anchor)
def dashed(d, p0, p1, col, w):
    (x0, y0), (x1, y1) = sc(p0), sc(p1); L = math.hypot(x1 - x0, y1 - y0); ux, uy = (x1 - x0) / L, (y1 - y0) / L; s = 0.0
    while s < L:
        e = min(L, s + DASH * S); d.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=col, width=w * S); s += (DASH + GAP) * S
def down(layer): return layer.resize((W, H), Image.LANCZOS)
z_lo, z_hi = from_px(0, 0)[1], from_px(W, 0)[1]
LINES = {"center": 0.0, "x042": 0.42, "lane": -0.33}
line_py = {k: to_px(x, z_lo)[1] for k, x in LINES.items()}
st = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(st)
d.line([sc(to_px(0.0, z_lo)), sc(to_px(0.0, z_hi))], fill=COL["center"] + (255,), width=LW["center"] * S)
for k in ("x042", "lane"): dashed(d, to_px(LINES[k], z_lo), to_px(LINES[k], z_hi), COL[k] + (255,), LW["dash"])
text_box(d, sc((14, line_py["center"] - 8)), "真ん中 0.00", FL, COL["center"], "lb", edge=COL["center"])
text_box(d, sc((14, line_py["x042"] + 8)), "寄せたあと +0.42", FL, COL["x042"], "lt", edge=COL["x042"])
text_box(d, sc((W - 14, line_py["lane"] - 8)), "ハコブくんのふだん −0.33", FL, COL["lane"], "rb", edge=COL["lane"])
static = down(st); static_A = static.getchannel("A"); static_An = np.array(static_A)
rail_lo_py = to_px(0.875, 0)[1]; rail_hi_py = to_px(-0.875, 0)[1]
def mark_layer(shown):
    L = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); d = ImageDraw.Draw(L)
    for i, (who, t, head) in enumerate(MARKS):
        if not shown[i]: continue
        r = top[mark_f[i]]
        px, py = (float(r["axle_px"]), float(r["axle_py"])) if who == "chair" else (float(r["robot_px"]), float(r["robot_py"]))
        if who == "chair": ly = rail_lo_py + 40 + (70 if head == "寄せ終わり" else 0); anchor = "mt"
        else: ly = rail_hi_py - 40 - (60 if head == "走り出し" else 0); anchor = "mb"
        d.line([sc((px, py)), sc((px, ly))], fill=COL[who] + (255,), width=LW["leader"] * S)
        R = LW["mark_r"] * S; e = LW["mark_edge"] * S
        d.ellipse([px * S - R - e, py * S - R - e, px * S + R + e, py * S + R + e], fill=(255, 255, 255, 255))
        d.ellipse([px * S - R, py * S - R, px * S + R, py * S + R], fill=COL[who] + (255,))
        tv = vmap.get(mark_f[i]); tv = tv if tv is not None else vmap[min(vmap, key=lambda q: abs(q - mark_f[i]))]
        text_box(d, sc((px, ly)), f"{head} {tv:.1f}秒", FM, COL[who], anchor, edge=COL[who])
    return down(L)
def num_ok(s):
    try: v = float(s)
    except ValueError: return None
    return v if math.isfinite(v) and abs(v) < 1e6 else None
def hud_lines(f):
    r = rows[f]; cx = num_ok(r["chair_x"]); cy = num_ok(r["chair_yaw"]); g = num_ok(r["gap_m"])
    s0 = f"{vmap[f]:.1f} 秒" + (f"（早回し ×{SPD}）" if in_ff(f) else "")
    return [s0, "車いすの横の位置 " + (f"x {cx * 100:+.1f} cm・向き {cy:+.0f}°" if cx is not None else "—"),
            "ハコブくんと車いす・人のすき間 " + (f"{g:.2f} m" if g is not None and g < 1.5 else "1.5 m より遠い")]
RC = 6
KER = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * RC + 1, 2 * RC + 1)); PAD = RC + 24
def fill_obj(soft):
    ys, xs = np.nonzero(soft); added = np.zeros(soft.shape, bool)
    if len(xs) == 0: return added
    y0, y1 = max(0, ys.min() - PAD), min(H, ys.max() + PAD + 1); x0, x1 = max(0, xs.min() - PAD), min(W, xs.max() + PAD + 1)
    b = (soft[y0:y1, x0:x1] > 0).astype(np.uint8)
    bp = cv2.copyMakeBorder(b, PAD, PAD, PAD, PAD, cv2.BORDER_CONSTANT, value=0)
    cl = cv2.morphologyEx(bp, cv2.MORPH_CLOSE, KER, borderType=cv2.BORDER_CONSTANT, borderValue=0)[PAD:-PAD, PAD:-PAD].astype(bool)
    filled = ndimage.binary_fill_holes(cl | b.astype(bool))
    added[y0:y1, x0:x1] = filled & ~b.astype(bool)
    return added
gb = C["grip_both"]
tmpT = tempfile.mkdtemp(prefix="m238t_", dir="/tmp")
trail = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); td = ImageDraw.Draw(trail)
prev = {"chair": None, "robot": None}; shown = [False] * len(MARKS); mcache = mark_layer(shown)
per = []; top_stills = {}
want = {int(round(s[0] * FPS)): s[2] for s in shot["stills"] if s[1] == "top"}
k = 0
seqset = set(seq)
for f in range(0, f1 + 1):
    r = top[f]
    for who, kx, ky in (("chair", "axle_px", "axle_py"), ("robot", "robot_px", "robot_py")):
        p = (round(float(r[kx]) * S) / S, round(float(r[ky]) * S) / S)
        if prev[who] is not None: td.line([sc(prev[who]), sc(p)], fill=COL[who] + (255,), width=LW["trail"] * S)
        R = LW["trail"] * S / 2; td.ellipse([p[0] * S - R, p[1] * S - R, p[0] * S + R, p[1] * S + R], fill=COL[who] + (255,))
        prev[who] = p
    if f not in seqset: continue
    changed = False
    for i in range(len(MARKS)):
        if not shown[i] and f >= mark_f[i]: shown[i] = True; changed = True
    if changed: mcache = mark_layer(shown)
    raw = Image.open(os.path.join(D, "frames", SHOT + "_top", f"f_{f:05d}.png")).convert("RGBA")
    mkn = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_mask", f"f_{f:05d}.png")).convert("L"))
    ob = np.array(Image.open(os.path.join(D, "frames", SHOT + "_top_obj", f"f_{f:05d}.png")).convert("RGBA"))
    joined = gb[min(f, len(gb) - 1)] == 1
    groups = [ob[:, :, 0], np.maximum(ob[:, :, 1], ob[:, :, 2]), ob[:, :, 3]] if joined else [ob[:, :, 0], ob[:, :, 1], ob[:, :, 2], ob[:, :, 3]]
    add_any = np.zeros((H, W), bool)
    for g in groups: add_any |= fill_obj(g)
    Fn = np.maximum(mkn, np.where(add_any, 255, 0).astype(np.uint8))
    st_m = static.copy(); st_m.putalpha(ImageChops.multiply(static_A, ImageChops.invert(Image.fromarray(Fn, "L"))))
    lines = hud_lines(f)
    hl = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0)); hd = ImageDraw.Draw(hl); x0, y0, lh = 30, 22, 88
    wmax = max(hd.textbbox((0, 0), s, font=FH)[2] for s in lines) / S
    hd.rounded_rectangle([x0 * S - 8 * S, y0 * S - 6 * S, (x0 + wmax + 28) * S, (y0 + lh * 3 + 6) * S], radius=10 * S, fill=(255, 255, 255, 235))
    for i, s in enumerate(lines): hd.text(((x0 + 10) * S, (y0 + i * lh) * S), s, font=FH, fill=(25, 25, 25))
    im = raw.copy(); im.alpha_composite(st_m); im.alpha_composite(down(trail)); im.alpha_composite(mcache); im.alpha_composite(down(hl))
    o = im.convert("RGB"); o.save(os.path.join(tmpT, f"v_{k:05d}.png")); k += 1
    stA = np.array(st_m.getchannel("A"))
    per.append((f, int(joined), int(((stA > 0) & (Fn == 255)).sum()), int(add_any.sum())))
    if f in want: top_stills[want[f]] = o
vidT = os.path.join(VD, f"closeup238_{SHOT}_top.mp4")
subprocess.run([FF, "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(tmpT, "v_%05d.png"), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-r", "30", vidT], check=True)
sd = os.path.join(VD, "stills"); os.makedirs(sd, exist_ok=True)
for nm, im in top_stills.items(): im.save(os.path.join(sd, f"{SHOT}_{nm}.png"))
open(os.path.join(D, f"per238_{SHOT}.csv"), "w").write("frame,joined,line_left_inside,added\n" + "".join(",".join(map(str, p)) + "\n" for p in per))
print("真上", vidT, k, "コマ・外形の中に残る線 合計", sum(p[2] for p in per), "・ひとまとめのコマ", sum(p[1] for p in per))
```

#### tools/make_script238.py（依頼238）

```python
"""依頼238：make_script237.py を写して、写した先で変えた。237 から変えたこと（⑨-1 stop_voice だけを作る。⑨-2 は 237 のまま使う）：
・茂さんの 5 のセリフを「大城さん、ロボットさんが通るって」に替えた（声 M2_morita_oshirosan_tooru.wav。顔を向ける向き・角度は 237 のまま）
・ハコブくんが「すみません、通ります」と声をかけるのを、止まって 10 秒 → 5 秒に（CALL1）。そのあとの流れは 237 のまま、時刻だけ前へずれる
・名前を 238 に（台本の c238・mix238_*）
依頼237：make_script235.py を写して、写した先で変えた。235 から変えたこと：
・235 の⑩（止まって 3〜4 秒で茂さん「何を運んでるの？」→ハコブ「病棟へのお届け物です」）を 2 本とも消した
・⑨-1：止まって 10 秒のハコブ「すみません、通ります」のあと、茂さんが大城さんのほうへ顔を向けて（M_TURN_O）「おい、ロボットさんが通るって」→ 235 のとおり大城さんが気づいて寄せる。
  走り出して車いすに近づいた所で、茂さんがハコブくんのほうへ顔を向けて「何を運んでるんだい？」→ ハコブ「病棟へのお届け物です。ありがとうございます」（帯「お届け中」→「ありがとうございます」と合わせて目まで笑う顔 1.5 秒）→ 茂さんが 10° うなずき・顔を前へ
  7・8 の声は、ハコブくんが車いすの横にいる間（times.json の beside：前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで）に終わるように置く
・⑨-2：20 秒の声の後 M4_AFTER 秒で茂さんがハコブくんのほうへ顔を向けて（M_YAW）「あんたも待たされてるのかい」→ ハコブ「はい、お待ちしています」→ 茂さんは顔を戻す。
  車いすの横を通る時にハコブ「ありがとうございます」＋目まで笑う顔 1.5 秒・茂さんが 10° うなずく。早回しは 10〜20 秒の間（235 のまま）と、6 のあとから 30 秒の手前まで
・走り出した時の目まで笑う顔（235）はやめ、走り出したら「基本」
・画面の stuck は帯（黄）「通れません」だけの絵 c237_stuck_band.png と、顔の板の困り顔 face237_trouble（ふだんの大きさ）
以下は 235 の説明：
依頼235：⑨「車いすが廊下の真ん中で止まる」（⑩入り）の台本 closeup235_script.json を作る。場面は 2 つ：stop_voice（⑨-1）・stop_stuck（⑨-2）。
寺島さんは別の場面 <名前>__tera（同じ台本の中。Closeup235.cs が 2 つめの CloseupDirector で動かす）。
make_script229.py を土台にした（廊下・色・光・看護師の値・握りの的・声の口の作り方・ハコブくんの決まり）。229 から変えたこと：
・車いすの根の位置・向きを毎コマ台本に書く（c235.chair）。両手で握っている間は大城さんの根の前に固く付いた位置（229 と同じ）、
  立ち話で大城さんが体を回す間は止めた所のまま
・寄せ方（依頼235 の答え 1）：feas235.py で出した道（その場で回る・まっすぐ前／後ろ）を、速さ 0.3 m/秒・向きの変わる速さ 25°/秒を超えない台形の速さでたどる。
  後ろの車軸の中心がその道を通る（横にすべらない）。大城さんの根と向きは車いすから出す
・立ち話の向き（答え 2）：大城さんは右手（寺島さんから遠い側）を握りからはなし、体ごと寺島さんへ回す（足は 2 歩踏み替える）。左手は左の握りのまま（的は世界に止めた握り）
使い方：python3 make_script229.py と同じ並び：<175 の台本> <出力の台本> <声の wav のフォルダ> <道の json（feas235.py の出力）> [times.json]"""
import json, math, os, sys, wave
import numpy as np

def E(k, d):
    v = os.environ.get(k)
    return type(d)(v) if v is not None else d

src, dst, wavdir, pathjs = sys.argv[1:5]
times = json.load(open(sys.argv[5])) if len(sys.argv) > 5 and os.path.exists(sys.argv[5]) else {}
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = list(S["corridor"]["origin"])
AXLE_BACK = 0.15
GRIP_Z = 0.3336; GRIP_X, GRIP_Y = 0.225, 0.910; GRIP_R = 0.0155
D_PUSH = 0.26
WC_AHEAD = GRIP_Z + D_PUSH                 # 車いすの根：大城さんの根の前（229 と同じ 0.5936）
AX_AHEAD = WC_AHEAD - AXLE_BACK            # 後ろの車軸の中心：大城さんの根の前
WC_FRONT = 0.64
ROBOT_FRONT, ROBOT_REAR = 0.382, 0.380
LANE_R = -0.33
V_C = 0.8                                  # 押す速さ（229）
STEP_T = 0.5
SPINE, CHEST = 4.0, 3.0
Z_NS = E("Z_NS", 9.714)                    # 大城さんの根が止まる z（ハコブくんが 229 と同じ z 5.8 あたりで止まるように）
NZ0 = E("NZ0", 15.0)
RZ0 = E("RZ0", -1.6)
TV0 = 1.0
GAP = E("GAP", 0.55)
O_HW, T_F, T_B = 0.2381, 0.1499, 0.1399
T_GAP = 0.15                               # 寺島さんと大城さんのすき間（233 の 0.10〜0.15 の大きいほう）
T_DZ = E("T_DZ", -0.30)                    # 寺島さんの立つ前後（大城さんの根から。− は前）：答え 2 の「手の届かない形」→ 0.3 m 前へ（turn235.py）
T_X = O_HW + T_GAP + T_F                   # 寺島さんの根の x（立ち話）0.538
T_WALK_X = 0.539                           # 追いつく時の x（大城さんの +x の端 0.238 と手すり 0.84 の真ん中）
T_V = 1.2
O_TURN = E("O_TURN", 29.0)                 # 大城さんが体を回す角度（turn235.py：寺島さん 0.3 m 前で 29°・顔は体から −29°）
T_RET = (0.65, 0.69)                       # 寺島さんが下がって立つ所（x、大城さんの止まった根からの z）。feas235.py の TX・TZ
def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)
q = lambda t: round(round(t * FPS) / FPS, 4)

# ---------------------------------------------------------------- 声（233 の audio）
LINES = {"V1": ("tera", "V1_terashima_oshirosan.wav", "大城さん"), "V2": ("nurse", "V2_oshiro_otsukare.wav", "あ、寺島さん。おつかれさま"),
         "H2": ("robot", "H2_hakobu_toorimasu.wav", "すみません、通ります"), "T2": ("tera", "T2_terashima_hakobukun.wav", "あ、ハコブくん"),
         "V8": ("nurse", "V8_oshiro_gomenne.wav", "あ、ごめんね"),
         # 依頼237 の新しい声（M2 は依頼238 で「大城さん、ロボットさんが通るって」に替えた）
         "M2": ("morita", "M2_morita_oshirosan_tooru.wav", "大城さん、ロボットさんが通るって"), "M3": ("morita", "M3_morita_nanida.wav", "何を運んでるんだい？"),
         "M4": ("morita", "M4_morita_matasare.wav", "あんたも待たされてるのかい"),
         "H3": ("robot", "H3_hakobu_otodoke_arigato.wav", "病棟へのお届け物です。ありがとうございます"), "H4": ("robot", "H4_hakobu_omachi.wav", "はい、お待ちしています"),
         "H5": ("robot", "H5_hakobu_arigato.wav", "ありがとうございます")}
SR = 48000
def load_wav(p):
    w = wave.open(p); x = np.frombuffer(w.readframes(w.getnframes()), np.int16).astype(np.float64) / 32768.0
    assert w.getframerate() == SR and w.getnchannels() == 1, p
    return x
def voiced(x, th_db=-45.0):
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    on = np.where(20 * np.log10(e + 1e-9) > th_db)[0]
    return on[0] * hop / SR, (on[-1] + 1) * hop / SR
clips = {}
for k, (who, fn, text) in LINES.items():
    x = load_wav(os.path.join(wavdir, fn)); v0, v1 = voiced(x)
    clips[k] = {"who": who, "file": fn, "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}
def inner_gap(x, th_db=-45.0, min_s=0.3):
    """依頼237：声の中の一番長い無音（min_s 秒以上）の終わり（クリップの秒）＝ H3 の「ありがとうございます」の始まり"""
    hop = 480
    e = np.array([np.sqrt(np.mean(x[i:i + hop] ** 2)) for i in range(0, len(x) - hop, hop)])
    v = 20 * np.log10(e + 1e-9) > th_db; on = np.where(v)[0]; best = None; i = on[0]
    while i < on[-1]:
        if not v[i]:
            j = i
            while not v[j]: j += 1
            if (j - i) * hop / SR >= min_s and (best is None or j - i > best[1] - best[0]): best = (i, j)
            i = j
        i += 1
    return best[1] * hop / SR
H3_ARIGATO = inner_gap(clips["H3"]["x"]) - clips["H3"]["v0"]      # 声の始まりから「ありがとうございます」の始まりまで
GAP_Q = E("GAP_Q", 0.4)                    # 依頼237：新しいやり取りのセリフの間（235 の決まり 0.4〜0.7 の短いほう。⑨-1 の動けない時間を 30 秒未満にするため）
M_TURN_O = E("M_TURN_O", -40.0)            # ⑨-1 の 5：茂さんが後ろの大城さんのほうへ顔を向ける（30〜45°。− は +x の側＝大城さんが寺島さんのほうへ向いている側）
M_YAW = E("M_YAW", 25.0)                   # ⑨-2 の 5：ハコブくんのほうへ（20〜30°。235 の⑩と同じ 25°）
M4_AFTER = E("M4_AFTER", 2.5)              # ⑨-2 の 5：20 秒の声が終わってから（2〜4 秒）
HAPPY_S = 1.5
CALL1 = E("CALL1", 5.0)                    # 依頼238：⑨-1 の 4「すみません、通ります」は止まって 5 秒（237 は 10 秒）

RULE = {
    "about": "ハコブくんの決まり（依頼228・229 のまま）。依頼235 で足したのは resume_still_s（止まった後、前の物が resume_still_s 秒動かず、寄った位置で gap_stop_m 以上あけて通れる時に走り出す）と、通り過ぎてから x −0.33 へ戻ること",
    "cruise_mps": 0.6, "slow_mps": 0.5, "accel_max_mps2": 0.4, "decel_max_mps2": 0.4, "jerk_max_mps3": 1.0,
    "detect_range_m": 6.0, "react_s": 0.1, "margin_m": 2.4, "gap_slow_m": 0.40, "gap_stop_m": 0.15,
    "lane_x": LANE_R, "wall_clear_m": 0.053,
    "lateral_max_mps": 0.15, "lateral_angle_deg": 15.0, "lateral_accel_mps2": 0.25, "lateral_gain": 2.0, "lateral_done_m": 0.03,
    "resume_lateral_angle_deg": 10.0, "turn_rate_dps": 30.0, "corner_half_len_m": 0.38, "corner_slack_m": 0.006,
    "pass_behind_m": 1.0, "resume_still_s": 0.5, "still_mps": 0.005,
}

# ---------------------------------------------------------------- 1. 押して来て止まる（x 0・向き 180°）
TW0, RAMP, T_DEC = 0.2, 1.0, 1.6
d_dec = V_C * T_DEC / 2
d_total = NZ0 - Z_NS
t_cr0 = TW0 + RAMP; d_ramp = V_C * RAMP / 2
t_dec0 = t_cr0 + (d_total - d_ramp - d_dec) / V_C
t_ns = t_dec0 + T_DEC
def oshiro_push_z(t):
    if t <= TW0: return NZ0
    if t <= t_cr0:
        u = (t - TW0) / RAMP; return NZ0 - V_C * RAMP * (u ** 3 - 0.5 * u ** 4)          # 速さ smooth(u)·V の積分
    if t <= t_dec0: return NZ0 - d_ramp - V_C * (t - t_cr0)
    if t <= t_ns:
        u = (t - t_dec0) / T_DEC; return NZ0 - d_ramp - V_C * (t_dec0 - t_cr0) - V_C * T_DEC * (u - (u ** 3 - 0.5 * u ** 4))
    return Z_NS
# smooth の積分：∫0^u (3s²−2s³) ds = u³ − u⁴/2（u=1 で 0.5）
assert abs(oshiro_push_z(t_ns) - Z_NS) < 1e-6

# ---------------------------------------------------------------- 2. 寺島さん：後ろから 1.2 m/秒で追いつき、横に並んで「大城さん」、止まって大城さんへ向く
t_v1 = t_dec0 - 0.4                         # 横に並んだ時（大城さんはまだ 0.8 m/秒）に「大城さん」
z_al = oshiro_push_z(t_v1)
T_TD = 2.1                                  # 寺島さんの減速（1.2 → 0・なめらか）
z_tstop = Z_NS + T_DZ
t_ts = t_v1 + T_TD
assert abs((z_al - z_tstop) - T_V * T_TD / 2) < 0.08, (z_al - z_tstop, T_V * T_TD / 2)
T_TD = (z_al - z_tstop) * 2 / T_V; t_ts = t_v1 + T_TD
TZ0 = E("TZ0", z_al + T_V * (t_v1 - 0.2))   # 0.2 秒で 1.2 m/秒（はじめから歩いている）
def tera_z(t):
    if t <= t_v1: return z_al + T_V * (t_v1 - t)
    if t <= t_ts:
        u = (t - t_v1) / T_TD; return z_al - T_V * T_TD * (u - (u ** 3 - 0.5 * u ** 4))
    return z_tstop
YAW_FACE_O = math.degrees(math.atan2(0.0 - T_X, Z_NS - z_tstop)) % 360     # 大城さんの根のほうへ（299°）
t_tturn0, t_tturn1 = t_ts - 0.5, t_ts + 0.5                                # 減速の終わりで向きを変える（2 歩）
def tera_x(t):
    return T_WALK_X + (T_X - T_WALK_X) * smooth((t - t_tturn0) / (t_tturn1 - t_tturn0))
def tera_yaw0(t):
    return 180.0 + (YAW_FACE_O - 180.0) * smooth((t - t_tturn0) / (t_tturn1 - t_tturn0))

# ---------------------------------------------------------------- 3. 大城さんが振り返る（右手をはなし、体を 29° 回す・2 歩）
t_rel0 = t_ns + 0.25; t_rel1 = t_rel0 + 0.5           # 右手の重み 1 → 0
t_oturn0 = t_ns + 0.35; t_oturn1 = t_oturn0 + 0.9     # 向き 180 → 151
on = {"V1": t_v1}
on["V2"] = max(t_oturn0 + 0.45, on["V1"] + clips["V1"]["dur"] + GAP)
T_STOP_EST = on["V2"] + clips["V2"]["dur"] + 2.5
t_stop = times.get("stop_t", T_STOP_EST)
z_rstop = times.get("robot_stop_z", 5.8); x_rstop = times.get("robot_stop_x", -0.4643)

# ---------------------------------------------------------------- 4. 寄せる道（feas235.py の道を時間に）
P = json.load(open(pathjs))
pts = P["path"]
segs = []
for p in pts[1:]:
    if not segs or segs[-1]["kind"] != p[3]: segs.append({"kind": p[3], "pts": []})
    segs[-1]["pts"].append(p)
V_MAX, W_MAX, ACC_T, PAUSE = E("V_MAX", 0.28), E("W_MAX", 23.0), 0.3, 0.15     # 上限 0.3 m/秒・25°/秒より少し下
def trap(d, vmax, ta):
    T = d / vmax + ta
    def f(t):
        if t <= 0: return 0.0
        if t >= T: return d
        if t < ta: return vmax * t * t / (2 * ta)
        if t > T - ta: return d - vmax * (T - t) ** 2 / (2 * ta)
        return vmax * (t - ta / 2)
    return T, f
start = pts[0]
man = []          # (時間の長さ, 関数 u→(ax, az, th))
cur = (start[0], start[1], start[2])
for sg in segs:
    end = sg["pts"][-1]
    if sg["kind"] == "r":
        dth = end[2] - cur[2]; T, f = trap(abs(dth), W_MAX, 0.2); c0 = cur
        man.append((T, (lambda f, c0, dth: lambda t: (c0[0], c0[1], c0[2] + math.copysign(f(t), dth)))(f, c0, dth)))
    else:
        d = math.hypot(end[0] - cur[0], end[1] - cur[1]); T, f = trap(d, V_MAX, ACC_T); c0 = cur; e0 = (end[0], end[1])
        man.append((T, (lambda f, c0, e0, d: lambda t: (c0[0] + (e0[0] - c0[0]) * f(t) / d, c0[1] + (e0[1] - c0[1]) * f(t) / d, c0[2]))(f, c0, e0, d)))
    cur = (end[0], end[1], end[2])
MAN_T = sum(T for T, _ in man) + PAUSE * (len(man) - 1)
AX0_Z = Z_NS - AX_AHEAD                    # 止まった時の車軸の z（向き 0）
def man_at(t):
    """寄せ始めから t 秒の (車軸 x, 車軸 z, 向き°)。feas の z は前＝−（車軸の止まった所から）"""
    for T, fn in man:
        if t <= T: a = fn(t); return a[0], AX0_Z + a[1], a[2]
        t -= T
        if t <= PAUSE: a = fn(T); return a[0], AX0_Z + a[1], a[2]
        t -= PAUSE
    a = man[-1][1](man[-1][0]); return a[0], AX0_Z + a[1], a[2]

# ---------------------------------------------------------------- 場面ごと
def build(variant):
    stuck = variant == "stop_stuck"
    on2 = dict(on)
    ev = {}
    tv = times.get(variant, {})
    # 声をかける（235 のまま：10 秒・20 秒）
    calls = ([t_stop + 10.0, t_stop + 20.0] if stuck else [t_stop + CALL1])   # 依頼238：⑨-1 は CALL1 秒
    on2["H2"] = calls[0]
    if stuck: on2["H2b"] = calls[1]
    endH2 = on2["H2"] + clips["H2"]["dur"]
    t30 = t_stop + 30.0
    NOD_DOWN, NOD_HOLD, NOD_BACK = 0.28, 0.10, 0.32
    if stuck:
        # 依頼237 ⑨-2 の 5・6：20 秒の声のあと M4_AFTER 秒で茂さん→ハコブくんが答える→茂さんは顔を戻す
        endH2b = on2["H2b"] + clips["H2"]["dur"]
        on2["M4"] = endH2b + M4_AFTER
        t_m_turn0 = on2["M4"] - 0.45; t_m_turn1 = on2["M4"]
        on2["H4"] = on2["M4"] + clips["M4"]["dur"] + GAP_Q
        endH4 = on2["H4"] + clips["H4"]["dur"]
        m_back0 = endH4 + 0.3; m_back1 = m_back0 + 0.6
        t_tlook0 = t30 + E("TLOOK_AFTER", 1.2); t_tlook1 = t_tlook0 + 0.4; t_tback0 = t_tlook1 + 0.35; t_tback1 = t_tback0 + 0.4
        on2["T2"] = t_tback1 + 0.05
        cue_end = on2["T2"] + clips["T2"]["dur"]
        on2["V8"] = cue_end + GAP
    else:
        # 依頼237 ⑨-1 の 5：茂さんが先に気づき、大城さんのほうへ顔を向けて「大城さん、ロボットさんが通るって」（依頼238 でセリフを替えた）
        t_mo0 = endH2 + 0.05; t_mo1 = t_mo0 + 0.45
        on2["M2"] = endH2 + GAP_Q
        cue_end = on2["M2"] + clips["M2"]["dur"]
        on2["V8"] = cue_end + GAP_Q
    # 大城さんが気づく：顔をハコブくんへ（cue_end＋0.25）・体を戻して両手で握り直す（＋0.45 から 0.9 秒）・「あ、ごめんね」（235 のまま）
    t_olook0 = cue_end + 0.25; t_olook1 = t_olook0 + 0.35
    t_oback0 = cue_end + 0.45; t_oback1 = t_oback0 + 0.9
    t_regrip0 = t_oback1 + 0.1; t_regrip1 = t_regrip0 + 1.0         # 体を戻し終わってから右手を上から握りへ
    endV8 = on2["V8"] + clips["V8"]["dur"]
    if not stuck:
        m_ob0 = endV8 + 0.2; m_ob1 = m_ob0 + 0.6                     # 茂さんは顔を前へ戻す（大城さんが顔を戻すのと同じ時）
    t_olookback0 = endV8 + 0.2; t_olookback1 = t_olookback0 + 0.45
    # 寺島さんが下がる（V8 の始まり＋0.3 から）：向きを変え（後ろ＝+z へ）・歩いて・手すりを背に −x を向く
    t_tr0 = on2["V8"] + 0.3
    TR_TURN1, TR_WALK, TR_TURN2 = 0.8, 1.6, 0.8
    t_tr1 = t_tr0 + TR_TURN1; t_tr2 = t_tr1 + TR_WALK; t_tr3 = t_tr2 + TR_TURN2
    # 寄せ始め：握り直しと寺島さんが下がり終わった後
    t_man0 = max(t_regrip1 + 0.2, t_tr3 + 0.1)
    t_man1 = t_man0 + MAN_T
    t_resume_est = t_man1 + 0.512
    t_resume = tv.get("resume_t", t_resume_est)
    t_exit = tv.get("passed_t", t_resume + 9.833) + 2.5
    # 依頼237：ハコブくんが車いすの横にいる間（前の端が足のせの前の端を過ぎてから、後ろの端が大城さんの後ろの端を過ぎるまで。1 回目の Unity の値・無ければ 235 の差）
    bs = tv.get("beside", [t_resume + 5.0, t_resume + 8.533])
    if stuck:
        # ⑨-2 の 8：横を通る時に「ありがとうございます」（横にいる間の真ん中）
        on2["H5"] = bs[0] + (bs[1] - bs[0] - clips["H5"]["dur"]) / 2
        happy_from = on2["H5"]
        endH5 = on2["H5"] + clips["H5"]["dur"]
        nod_t0 = endH5 + 0.25
    else:
        # ⑨-1 の 7・8：茂さんの声が横に来た所（bs[0]）＋0.05 で終わり、GAP_Q あけてハコブくんが答える（横にいる間に 2 つとも終わる）
        on2["M3"] = bs[0] + E("M3_END_AFTER", 0.05) - clips["M3"]["dur"]
        on2["H3"] = on2["M3"] + clips["M3"]["dur"] + GAP_Q
        happy_from = on2["H3"] + H3_ARIGATO
        endH3 = on2["H3"] + clips["H3"]["dur"]
        t_m3_0 = on2["M3"] - 0.45; t_m3_1 = on2["M3"]
        M_YAW3 = tv.get("m3_yaw", 35.0)
        nod_t0 = endH3 + 0.25
    happy_to = happy_from + HAPPY_S
    m_end0 = nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK + 0.3; m_end1 = m_end0 + 0.6
    DUR = q(t_exit)
    NF = int(round(DUR * FPS))
    ev.update({"t_stop": t_stop, "t30": t30 if stuck else None, "t_man0": t_man0, "t_man1": t_man1, "t_resume_used": t_resume, "t_exit_used": t_exit,
               "t_tr": [t_tr0, t_tr3], "t_oturn": [t_oturn0, t_oturn1], "t_oback": [t_oback0, t_oback1], "t_rel": [t_rel0, t_rel1], "t_regrip": [t_regrip0, t_regrip1]})

    # ---------- 大城さんの根・向き、車いすの根・向き（毎コマ）
    nurse_rows, chair_rows, grip_both = [], [], []
    for f in range(NF + 1):
        t = f * DT
        if t < t_man0:
            ax, az, th = 0.0, oshiro_push_z(t) - AX_AHEAD, 0.0
            nx_, nz_ = 0.0, oshiro_push_z(t)
            if t < t_oturn0: nyaw = 180.0
            elif t < t_oback0: nyaw = 180.0 - O_TURN * smooth((t - t_oturn0) / (t_oturn1 - t_oturn0))
            else: nyaw = 180.0 - O_TURN * (1 - smooth((t - t_oback0) / (t_oback1 - t_oback0)))
        else:
            ax, az, th = man_at(t - t_man0)
            fx, fz = math.sin(math.radians(th)), -math.cos(math.radians(th))
            nx_, nz_ = ax - fx * AX_AHEAD, az - fz * AX_AHEAD; nyaw = 180.0 - th
        # 車いすの根：車軸の前 0.15（向き th）
        fx, fz = math.sin(math.radians(th)), -math.cos(math.radians(th))
        cx, cz = ax + fx * AXLE_BACK, az + fz * AXLE_BACK
        nurse_rows.append((t, nx_, nz_, nyaw)); chair_rows.append((round(cx, 5), round(cz, 5), round(180.0 - th, 4)))
        grip_both.append(not (t_rel0 <= t < t_regrip1))
    keys_x = [[round(r[0], 4), round(r[1], 5), "lin"] for r in nurse_rows]; keys_x[0] = keys_x[0][:2]
    keys_z = [[round(r[0], 4), round(r[2], 5), "lin"] for r in nurse_rows]; keys_z[0] = keys_z[0][:2]
    keys_yaw = [[round(r[0], 4), round(r[3], 4), "lin"] for r in nurse_rows]; keys_yaw[0] = keys_yaw[0][:2]

    # ---------- 大城さんの足
    def walk_steps(t0, t1, first="R", period=STEP_T):
        st, t, foot = [], t0, first
        while t + period <= t1 + 1e-6:
            st.append([round(t, 4), round(t + period, 4), foot]); t += period; foot = "L" if foot == "R" else "R"
        return st, foot
    steps, foot = walk_steps(TW0, t_ns + 0.25)
    # 振り返る（2 歩：寺島さん側の左足から）・戻る（2 歩）
    steps += [[round(t_oturn0, 4), round(t_oturn0 + 0.45, 4), "L"], [round(t_oturn0 + 0.45, 4), round(t_oturn0 + 0.9, 4), "R"]]
    steps += [[round(t_oback0, 4), round(t_oback0 + 0.45, 4), "R"], [round(t_oback0 + 0.45, 4), round(t_oback0 + 0.9, 4), "L"]]
    # 寄せる間：根が動く／回る間は 0.45 秒ごとに交互に踏む（最後にそろえる 1 歩）
    mv = []
    prev = None
    for f in range(int(t_man0 * FPS), NF + 1):
        r = nurse_rows[f]
        if prev is not None: mv.append((r[0], math.hypot(r[1] - prev[1], r[2] - prev[2]) / DT + abs(r[3] - prev[3]) / DT * 0.01))
        prev = r
    moving = [t for t, v in mv if v > 0.004]
    if moving:
        t, ft, tend = moving[0] - 0.05, "R", moving[-1]
        while t < tend + 0.3:
            steps.append([round(t, 4), round(t + 0.45, 4), ft]); t += 0.45; ft = "L" if ft == "R" else "R"
        steps.append([round(t, 4), round(t + 0.45, 4), ft])
    steps.sort(key=lambda s: s[0])

    # ---------- 大城さんの手：右手は振り返る間はなす。左手は世界に止めた握り
    gz = WC_AHEAD - GRIP_Z
    py = GRIP_Y + GRIP_R + 0.018
    gl_world = [round(GRIP_X, 4), round(py, 4), round(Z_NS - (gz - 0.05), 4)]
    L_target = [[0, "grip_l"], [round(t_oturn0 - 0.02, 4), "grip_l_w", 0.01], [round(t_oback1, 4), "grip_l", 0.01]]
    # 右手：はなす時は握りの上へ上げてから下ろす・握り直す時は上から下ろしてのせる（握りの筒を通らない）
    R_w = [[0, 1.0], [round(t_rel0 + 0.35, 4), 1.0], [round(t_rel1 + 0.35, 4), 0.0], [round(t_regrip0, 4), 0.0], [round(t_regrip0 + 0.55, 4), 1.0]]
    R_target = [[0, "grip_r"], [round(t_rel0, 4), "grip_r_up", 0.35], [round(t_regrip0 - 0.05, 4), "grip_r_up", 0.01], [round(t_regrip0 + 0.55, 4), "grip_r", 0.4]]
    R_curl = [[0, 30.0], [round(t_rel0, 4), 30.0], [round(t_rel1, 4), 8.0], [round(t_regrip0, 4), 8.0], [round(t_regrip1, 4), 30.0]]
    spine = [[0, SPINE], [round(t_oturn0, 4), SPINE], [round(t_oturn1, 4), 2.0], [round(t_oback0, 4), 2.0], [round(t_oback1, 4), SPINE]]
    chest = [[0, CHEST], [round(t_oturn0, 4), CHEST], [round(t_oturn1, 4), 1.0], [round(t_oback0, 4), 1.0], [round(t_oback1, 4), CHEST]]
    walk = [[0, 0], [TW0, 0], [TW0 + 0.4, 1], [round(t_dec0 + 0.6, 4), 1], [round(t_ns, 4), 0]]

    # ---------- 顔の向き：寺島さんを見る（体から 30° 以内）・ハコブくんを見る
    EYE_Y = 1.50
    t_head = (t_oturn0 + 0.2, t_oturn1)
    def look_yaw(nx_, nz_, byaw, tx, tz):
        want = math.degrees(math.atan2(tx - nx_, tz - nz_)); return ((want - byaw + 180) % 360) - 180
    hy = [[0, 0.0], [round(t_head[0], 4), 0.0]]
    hn = [[0, 8.0], [round(t_head[0], 4), 8.0], [round(t_head[1], 4), 0.0]]
    o_to_t = look_yaw(0.0, Z_NS, 180.0 - O_TURN, T_X - 0.05, z_tstop)
    o_to_t = max(-30.0, min(30.0, o_to_t))
    hy.append([round(t_head[1], 4), round(o_to_t, 3)])
    # 立ち話のうなずき（聞く側）・話す（口だけ talk）
    talk_o, talk_t = [[0, 0]], [[0, 0]]
    nod_o, nod_t = [], []
    t_talk0 = on2["V2"] + clips["V2"]["dur"] + 0.6
    t_talk_end_o = cue_end + 0.1
    t_talk_end_t = on2["V8"] if not stuck else t_tlook0 - 0.1
    t, who = t_talk0, "t"
    while t < max(t_talk_end_o, t_talk_end_t) - 0.5:
        L = 2.6 if who == "t" else 2.2
        if who == "t" and t < t_talk_end_t - 0.3:
            talk_t += [[round(t, 4), 1], [round(min(t + L, t_talk_end_t - 0.1), 4), 0]]
            if t + 1.2 < t_talk_end_o: nod_o.append(t + 1.0)
        elif who == "o" and t < t_talk_end_o - 0.3:
            talk_o += [[round(t, 4), 1], [round(min(t + L, t_talk_end_o - 0.1), 4), 0]]
            if t + 1.2 < t_talk_end_t: nod_t.append(t + 1.1)
        t += L + 0.5; who = "o" if who == "t" else "t"
    for tn in nod_o:
        hn += [[round(tn, 4), 0.0], [round(tn + 0.25, 4), 7.0], [round(tn + 0.55, 4), 0.0]]
    hn.sort(key=lambda r: r[0])
    # 気づく
    o_to_r = look_yaw(0.0, Z_NS, 180.0, x_rstop, z_rstop + ROBOT_FRONT)
    hy += [[round(t_olook0, 4), round(o_to_t, 3)], [round(t_olook1, 4), round(o_to_r - (180.0 - (180.0 - O_TURN)), 3)],
           [round(t_oback0, 4), round(o_to_r - O_TURN, 3)], [round(t_oback1, 4), round(o_to_r, 3)],
           [round(t_olookback0, 4), round(o_to_r, 3)], [round(t_olookback1, 4), 0.0]]
    hn += [[round(t_olook0, 4), 0.0], [round(t_olook1, 4), 4.0], [round(t_olookback1, 4), 8.0]]
    hy.sort(key=lambda r: r[0]); hn.sort(key=lambda r: r[0])
    mouth_o = [[0, "flat"], [round(on2["V2"] - 0.2, 4), "smile"]]

    # ---------- 寺島さんの道
    t_rows = []
    zr = Z_NS + T_RET[1]; xr = T_RET[0]
    ret_yaw = 0.0                                                              # 下がる向き（+z）
    for f in range(NF + 1):
        t = f * DT
        if t < t_tr0: x, z, y = tera_x(t), tera_z(t), tera_yaw0(t)
        elif t < t_tr1: x, z, y = T_X, z_tstop, YAW_FACE_O + (((ret_yaw - YAW_FACE_O + 180) % 360) - 180) * smooth((t - t_tr0) / TR_TURN1)
        elif t < t_tr2:
            u = smooth((t - t_tr1) / TR_WALK); x, z, y = T_X, z_tstop + (zr - z_tstop) * u, ret_yaw
        else:
            u = (t - t_tr2) / TR_TURN2
            x, z, y = T_X + (xr - T_X) * smooth(2 * u - 1), zr, ret_yaw + (((270.0 - ret_yaw + 180) % 360) - 180) * smooth(u)
        t_rows.append((t, x, z, y))
    tk = lambda i: [[round(r[0], 4), round(r[i], 5), "lin"] for r in t_rows]
    tx_, tz_, ty_ = tk(1), tk(2), tk(3)
    for a in (tx_, tz_, ty_): a[0] = a[0][:2]
    t_steps = []
    tt, ft = 0.2, "R"
    while tt + 0.45 <= t_ts + 0.05:
        t_steps.append([round(tt, 4), round(tt + 0.45, 4), ft]); tt += 0.45; ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tturn1 - 0.2, 4), round(t_tturn1 + 0.25, 4), ft]]
    ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tr0, 4), round(t_tr0 + 0.4, 4), "R"], [round(t_tr0 + 0.4, 4), round(t_tr0 + 0.8, 4), "L"]]
    tt, ft = t_tr1, "R"
    while tt + 0.4 <= t_tr2 + 0.05:
        t_steps.append([round(tt, 4), round(tt + 0.4, 4), ft]); tt += 0.4; ft = "L" if ft == "R" else "R"
    t_steps += [[round(t_tr2, 4), round(t_tr2 + 0.4, 4), ft], [round(t_tr2 + 0.4, 4), round(t_tr2 + 0.8, 4), "L" if ft == "R" else "R"]]
    t_steps.sort(key=lambda s: s[0])
    t_walk = [[0, 1], [round(t_v1 + 0.6, 4), 1], [round(t_ts, 4), 0], [round(t_tr1, 4), 0], [round(t_tr1 + 0.3, 4), 0.6], [round(t_tr2 - 0.3, 4), 0.6], [round(t_tr2, 4), 0]]
    # 寺島さんの顔：大城さんの顔を見る（立ち話）。⑨-2 はハコブくんのほうへ −30°（20〜35°）向けて戻す
    def t_look_o(t):
        r = nurse_rows[min(len(nurse_rows) - 1, int(round(t * FPS)))]
        return look_yaw(T_X, z_tstop, YAW_FACE_O, r[1], r[2])
    thy = [[0, 0.0], [round(t_tturn1, 4), 0.0], [round(t_tturn1 + 0.4, 4), round(max(-30, min(30, t_look_o(t_tturn1 + 0.4))), 3)]]
    if stuck:
        base = round(max(-30, min(30, t_look_o(t_tlook0))), 3)
        thy += [[round(t_tlook0, 4), base], [round(t_tlook1, 4), round(base - E("T_LOOK", 30.0), 3)], [round(t_tback0, 4), round(base - E("T_LOOK", 30.0), 3)], [round(t_tback1, 4), base]]
    thy += [[round(t_tr0, 4), round(max(-30, min(30, t_look_o(t_tr0))), 3)], [round(t_tr0 + 0.5, 4), 0.0]]
    thn = [[0, 6.0], [round(t_ts, 4), 0.0]]
    for tn in nod_t: thn += [[round(tn, 4), 0.0], [round(tn + 0.25, 4), 7.0], [round(tn + 0.55, 4), 0.0]]
    thn.sort(key=lambda r: r[0])
    mouth_t = [[0, "flat"], [round(t_v1 - 0.3, 4), "smile"]]

    # ---------- 茂さん
    if stuck:
        m_yaw = [[0, 0.0], [round(t_m_turn0, 4), 0.0], [round(t_m_turn1, 4), M_YAW], [round(m_back0, 4), M_YAW], [round(m_back1, 4), 0.0]]
    else:
        m_yaw = [[0, 0.0], [round(t_mo0, 4), 0.0], [round(t_mo1, 4), M_TURN_O], [round(m_ob0, 4), M_TURN_O], [round(m_ob1, 4), 0.0],
                 [round(t_m3_0, 4), 0.0], [round(t_m3_1, 4), M_YAW3], [round(m_end0, 4), M_YAW3], [round(m_end1, 4), 0.0]]
    m_nod = [[0, 0.0], [round(nod_t0, 4), 0.0], [round(nod_t0 + NOD_DOWN, 4), 10.0], [round(nod_t0 + NOD_DOWN + NOD_HOLD, 4), 10.0], [round(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, 4), 0.0]]
    m_mouth = [[0, "flat"]]

    # ---------- 画面
    scr = [[0, "face"], [q(t_stop + 0.2), "wait"], [q(on2["H2"]), "pass"]]
    if stuck:
        scr += [[q(on2["H2"] + 3.0), "wait"], [q(on2["H2b"]), "pass"], [q(on2["H2b"] + 3.0), "wait"], [q(t30), "stuck"]]
    scr += [[q(t_resume), "face"]]                                   # 依頼237：走り出したら帯を消して「基本」
    if not stuck: scr += [[q(on2["H3"]), "deliv"]]
    scr += [[q(happy_from), "happy"], [q(happy_to), "face"]]
    ring = [[0, "normal"]] + ([[q(t30), "wait"], [q(t_resume), "normal"]] if stuck else [])

    # ---------- 声の並び・口
    tracks = {w: np.zeros(int(DUR * SR) + SR) for w in ("nurse", "robot", "tera", "morita")}
    place = {}
    for k, t0 in on2.items():
        c = clips["H2" if k == "H2b" else k]
        s0 = t0 - c["v0"]; i0 = int(round(s0 * SR))
        tracks[c["who"]][i0:i0 + len(c["x"])] += c["x"]
        place[k] = {"who": c["who"], "file": c["file"], "text": c["text"], "clip_start_s": round(s0, 4), "voice_on_s": round(t0, 4), "voice_off_s": round(t0 + c["dur"], 4),
                    "voice_len_s": round(c["dur"], 4), "clip_len_s": round(c["len"], 4)}
    HOP = SR // FPS
    def frame_rms(x): return np.array([np.sqrt(np.mean(x[i * HOP:(i + 1) * HOP] ** 2)) if i * HOP < len(x) else 0 for i in range(NF)])
    def ladder(who, rest, speak):
        rms = frame_rms(tracks[who])
        ref = np.percentile(rms[rms > 0.01], 90) if (rms > 0.01).any() else 1.0
        lvl = np.convolve(rms / ref, np.ones(3) / 3, mode="same")
        target = np.where(speak, np.digitize(lvl, [0.15, 0.35, 0.65]), 0)
        for i in range(NF):
            if not speak[i]: target[i] = rest[i]
        for i in range(1, NF - 1):
            if target[i] != target[i - 1] and target[i] != target[i + 1]: target[i] = target[i - 1]
        step = np.zeros(NF, int)
        for i in range(NF):
            prev = step[i - 1] if i else rest[0]
            step[i] = prev + int(np.clip(target[i] - prev, -1, 1)) if i % 2 == 0 else prev
        return step
    def speak_mask(names):
        m = np.zeros(NF, bool)
        for k in names:
            if k in on2: m[int(math.floor(on2[k] * FPS)):int(math.ceil(place[k]["voice_off_s"] * FPS))] = True
        return m
    LADDER = ["closed", "small", "mid", "large"]
    robot_mouth = [LADDER[s] for s in ladder("robot", np.full(NF, 2), speak_mask(["H2", "H2b", "H3", "H4", "H5"]))]
    nurse_mouth = [int(s) for s in ladder("nurse", np.zeros(NF, int), speak_mask(["V2", "V8"]))]
    tera_mouth = [int(s) for s in ladder("tera", np.zeros(NF, int), speak_mask(["V1", "T2"]))]
    mor_mouth = [int(s) for s in ladder("morita", np.zeros(NF, int), speak_mask(["M2", "M3", "M4"]))]
    mix = sum(tracks.values())[: int(round(DUR * SR))]
    pk = float(np.max(np.abs(mix))); assert pk < 1.0, pk
    wav_out = os.path.join(os.path.dirname(dst), f"mix238_{variant}.wav")
    w = wave.open(wav_out, "w"); w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
    w.writeframes((np.clip(mix, -1, 1) * 32767).astype(np.int16).tobytes()); w.close()

    # ---------- カメラ
    zc = z_rstop + 0.7
    zf = z_rstop + ROBOT_FRONT
    CAM = {
        "main": {"pos": [-0.62, 1.72, round(zc - 6.0, 4)], "look": [0.12, 0.8, round(zc + 1.6, 4)], "fov": 38},
        "screen_close": {"follow": "robot", "pos": [x_rstop, 1.23, 1.15], "look": [x_rstop, 0.962, 0.29], "fov": 24},
        "morita_face": {"pos": [-0.42, 1.22, round(Z_NS - WC_AHEAD - 1.25, 4)], "look": [0.02, 1.12, round(Z_NS - WC_AHEAD + 0.02, 4)], "fov": 24},
        "oshiro_face": {"pos": [-0.62, 1.62, round(Z_NS - 1.75, 4)], "look": [0.05, 1.45, round(Z_NS, 4)], "fov": 22},
        "depart": {"pos": [-0.75, 1.70, round(z_rstop - 1.4, 4)], "look": [0.20, 0.75, round(z_rstop + 3.2, 4)], "fov": 46},
        "chk_grip": {"pos": [0.05, 1.55, round(Z_NS + 0.75, 4)], "look": [0.10, 0.95, round(Z_NS - 0.25, 4)], "fov": 40},
    }
    # 依頼237：235 の⑩の切りかえ（茂さんの顔→画面→本番）を、新しいやり取りに使う（茂さんが話す時は茂さんの顔・ハコブくんが答える時は画面）
    cuts = [[0, "main"], [q(t_stop - 0.1), "screen_close"], [q(t_stop + 1.6), "main"],
            [q(on2["H2"] - 0.15), "screen_close"]]
    if stuck:
        cuts += [[q(endH2 + 0.15), "main"], [q(on2["H2b"] - 0.15), "screen_close"], [q(on2["H2b"] + clips["H2"]["dur"] + 0.15), "main"],
                 [q(on2["M4"] - 0.35), "morita_face"], [q(on2["H4"] - 0.15), "screen_close"], [q(endH4 + 0.4), "main"],
                 [q(t30 - 0.1), "screen_close"], [q(t30 + 1.0), "main"]]
    else:
        cuts += [[q(endH2 + 0.15), "morita_face"]]
    cuts += [[q(t_olook0 - 0.1), "oshiro_face"], [q(endV8 + 0.35), "main"]]
    # 依頼237：通る時にハコブくんが話す所も、235 と同じくハコブくんが話す時は画面の寄り（screen_close はハコブくんに付いて動く）→ 目まで笑う顔が終わったら本番
    #（茂さんの顔のカメラはハコブくんの通る所に置いてあるので、通る間は使わない）
    cuts += [[q(on2["H5" if stuck else "H3"] - 0.15), "screen_close"], [q(happy_to + 0.15), "main"]]
    cuts.sort(key=lambda c: c[0])
    stills = [[q(t_v1 + 0.3), "main", "s01_terashima_calls"], [q(on2["V2"] + 1.0), "main", "s02_three_talk"],
              [q(t_stop + 0.1), "main", "s03_robot_stopped_main"], [q(t_stop + 0.8), "screen_close", "s04_robot_stopped_close"],
              [q(on2["H2"] + 0.8), "screen_close", "s07_toorimasu"], [q(t_man0 + 0.5 * MAN_T), "main", "s09_shift_main"],
              [q(t_man0 + 0.5 * MAN_T), "top", "s09_shift_top"], [q(t_resume + 2.5), "main", "s10_pass_main"], [q(t_oturn1 + 0.3), "chk_grip", "chk_grip_turned"],
              [q(t_man0 + 1.0), "chk_grip", "chk_grip_man"]]
    if stuck: stills += [[q(t30 + 0.5), "screen_close", "s08_toremasen"], [q(t30 + 1.5), "main", "s08_stuck_label"],
                         [q(on2["M4"] + 0.8), "morita_face", "s11_morita_matasare"], [q(happy_from + 0.5), "screen_close", "s13_arigato_happy"],
                         [q(happy_from + 0.5), "main", "s13_arigato_main"]]
    else: stills += [[q(on2["V8"] + 0.4), "oshiro_face", "s08_oshiro_notices"], [q(on2["M2"] + 1.0), "morita_face", "s11_morita_tooru"],
                     [q(on2["M3"] + 0.6), "main", "s12_morita_nanida"], [q(on2["H3"] + 0.6), "screen_close", "s13_otodokechu"],
                     [q(happy_from + 0.5), "screen_close", "s13_arigato_happy"], [q(happy_from + 0.5), "main", "s13_arigato_main"]]
    # 早回し（⑨-2：声と動きの無い所。×4）
    ff = []
    if stuck:
        # 依頼237：10〜20 秒の間（235 のまま）と、6（ハコブ「はい、お待ちしています」）のあとから 30 秒の手前まで。5・6 は 1 倍
        ff = [[round(on2["H2"] + 3.4, 3), round(on2["H2b"] - 0.6, 3)], [round(max(endH4, m_back1) + 0.6, 3), round(t30 - 0.6, 3)]]
        ff = [[a, b] for a, b in ff if b - a >= 1.0]
    shot = {"name": variant, "about": "⑨ 車いすが廊下の真ん中で止まる（依頼238：" + ("⑨-2 立ち往生になる" if stuck else "⑨-1 声をかけて通る") + "）", "origin": O, "duration": DUR, "video": True,
            "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]},
            "box_events": [], "card_events": [], "presses": [], "card": False,
            "check_open": [], "check_close": [], "check_above": [], "transitions": [],
            "robot_start_z": RZ0, "swing_ramp": 0.15, "lift_pow": 0.5,
            "nurse": {"x": keys_x, "z": keys_z, "yaw": keys_yaw, "walk": walk, "spine": spine, "chest": chest,
                      "head_yaw": hy, "head_nod": hn, "mouth": mouth_o, "talk": talk_o,
                      "L_w": [[0, 1.0]], "R_w": R_w, "L_target": L_target, "R_target": R_target,
                      "L_curl": [[0, 30.0]], "R_curl": R_curl, "L_thumb": [[0, 20.0]], "R_thumb": [[0, 20.0]],
                      "L_hint": [[0, "push_l"]], "R_hint": [[0, "push_r"]], "L_hint_w": [[0, 0.5]], "R_hint_w": [[0, 0.5]]},
            "steps": steps, "look_windows": [], "cameras": CAM, "cuts": cuts, "stills": stills,
            "c238": {"wc_ahead_m": round(WC_AHEAD, 4), "video_from": TV0, "video_to": round((NF - 1) * DT, 4),
                     "chair": chair_rows, "grip_both": [1 if g else 0 for g in grip_both],
                     "screen": scr, "ring": ring, "ring_wait_color": "#F2C230", "happy": [round(happy_from, 4), round(happy_to, 4)], "beside_used": [round(bs[0], 4), round(bs[1], 4)], "h3_arigato_s": round(H3_ARIGATO, 4),
                     "stuck_label": [round(t30, 4), round(t30 + 3.0, 4)] if stuck else None, "ff": ff, "ff_speed": 4,
                     "robot_mouth": robot_mouth, "nurse_mouth": nurse_mouth, "tera_mouth": tera_mouth, "morita_mouth_lvl": mor_mouth, "nurse_mouth_scale": [1.0, 1.2, 1.8, 2.4],
                     "morita": {"head_yaw": m_yaw, "head_nod": m_nod, "mouth": m_mouth, "neck_share": 0.4,
                                "blink": {"every_min_s": 3.0, "every_max_s": 5.0, "close_s": 0.15, "seed": 228}, "eye_min_scale": 0.1},
                     "lines": place, "grip": {"x": GRIP_X, "y": GRIP_Y, "z_behind_root": GRIP_Z, "r": GRIP_R},
                     "man": {"t0": round(t_man0, 4), "t1": round(t_man1, 4), "path_file": os.path.basename(pathjs), "segs": P["segs"], "v_max": V_MAX, "w_max": W_MAX},
                     "tera_ret": {"x": xr, "z": round(zr, 4), "from": [round(T_X, 4), round(z_tstop, 4)], "t": [round(t_tr0, 4), round(t_tr3, 4)]},
                     "times": {k: (round(v, 4) if isinstance(v, float) else v) for k, v in ev.items()}}}
    tshot = {"name": variant + "__tera", "about": "寺島さん（" + variant + "）", "origin": O, "duration": DUR, "video": True,
             "box_start": {"on": "hidden"}, "robot": {"screen": [[0, "face"]]}, "box_events": [], "card_events": [], "presses": [], "card": False,
             "check_open": [], "check_close": [], "check_above": [], "transitions": [], "swing_ramp": 0.15, "lift_pow": 0.5,
             "nurse": {"x": tx_, "z": tz_, "yaw": ty_, "walk": t_walk, "spine": [[0, 2.0]], "chest": [[0, 1.0]],
                       "head_yaw": thy, "head_nod": thn, "mouth": mouth_t, "talk": talk_t, "L_w": [[0, 0.0]], "R_w": [[0, 0.0]]},
             "steps": t_steps}
    info = {"variant": variant, "duration": DUR, "t_stop": t_stop, "happy": [round(happy_from, 3), round(happy_to, 3)], "beside": [round(bs[0], 3), round(bs[1], 3)], "on": {k: round(v, 3) for k, v in on2.items()}, "man": [round(t_man0, 3), round(t_man1, 3), round(MAN_T, 3)],
            "stuck_est": round(t_resume_est - t_stop, 3), "t_tr": [round(t_tr0, 3), round(t_tr3, 3)], "ff": ff}
    return shot, tshot, info

out = {k: S[k] for k in ("fps", "width", "height", "supersample", "colors", "light", "rooms", "box", "bag", "nurse", "targets", "card", "pocket", "screen_ui", "drawer_parts", "hints", "check_stand_parts", "corridor")}
out["about"] = "依頼238：⑨-1 声をかけて通る（場面 stop_voice、寺島さんは __tera）。make_script238.py（make_script237.py の写し）が作った。廊下・色・光・看護師・画面の値は 175 の台本から写した"
out["nurse"] = dict(out["nurse"]); out["nurse"]["walk"] = dict(out["nurse"]["walk"])
out["nurse"]["walk"].update({"amp_deg": 11.0, "knee_deg": 24, "bob_m": 0.008, "lift_m": 0.05})
gz = WC_AHEAD - GRIP_Z
out["targets"] = dict(out["targets"])
py = GRIP_Y + GRIP_R + 0.018
out["targets"]["grip_l"] = {"ref": "nurse", "pos": [round(-GRIP_X, 4), round(py, 4), round(gz - 0.05, 4)], "finger_frame": "nurse", "finger": [-1.0, -0.35, 1], "palm_frame": "nurse", "palm": [0.3, -1, 0.0]}
out["targets"]["grip_r"] = {"ref": "nurse", "pos": [round(GRIP_X, 4), round(py, 4), round(gz - 0.05, 4)], "finger_frame": "nurse", "finger": [1.0, -0.35, 1], "palm_frame": "nurse", "palm": [-0.3, -1, 0.0]}
# 振り返る間の左手：止まった時（大城さんの根 x 0・z Z_NS・向き 180°）の grip_l と同じ点・同じ向きを、世界に止める
out["targets"]["grip_r_up"] = {"ref": "nurse", "pos": [round(GRIP_X + 0.03, 4), round(py + 0.15, 4), round(gz - 0.20, 4)], "finger_frame": "nurse", "finger": [1.0, -0.35, 1], "palm_frame": "nurse", "palm": [-0.3, -1, 0.0]}
out["targets"]["grip_l_w"] = {"ref": "world", "pos": [round(GRIP_X, 4), round(py, 4), round(Z_NS - (gz - 0.05), 4)], "finger_frame": "world", "finger": [1.0, -0.35, -1], "palm_frame": "world", "palm": [-0.3, -1, 0.0]}
out["hints"] = dict(out["hints"]); out["hints"]["push_l"] = [-0.40, 1.0, -0.20]; out["hints"]["push_r"] = [0.40, 1.0, -0.20]
out["robot_rule"] = RULE
shots, infos = [], []
for v in ("stop_voice",):                  # 依頼238：⑨-1 だけ（⑨-2 は 237 のまま使う）
    a, b, i = build(v); shots += [a, b]; infos.append(i)
out["shots"] = shots
out["c238_common"] = {"z_ns": Z_NS, "t_ns": round(t_ns, 4), "t_v1": round(t_v1, 4), "nz0": NZ0, "tz0": round(TZ0, 4), "t_x": round(T_X, 4), "t_dz": T_DZ, "o_turn": O_TURN,
                      "z_tstop": round(z_tstop, 4), "t_ts": round(t_ts, 4), "yaw_face_o": round(YAW_FACE_O, 3), "man_T": round(MAN_T, 3), "t_stop_used": t_stop, "robot_stop_z_used": z_rstop}
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=0)
print(json.dumps({"common": out["c238_common"], "shots": infos}, ensure_ascii=False))
```

#### tools/run238.sh（依頼238）

```bash
#!/bin/bash
# 依頼238（237 の写し） 使い方: run238.sh <出力フォルダ> <場面 stop_voice|stop_stuck> <台本（絶対パス か Closeups/ の名前）> <コマ on|off> [静止画 on|off] [views] [until]
OUT="$1"; SH="$2"; SC="$3"; FR="${4:-off}"; ST="${5:-off}"; VW="${6:-main,top}"; UNTIL="${7:-1e9}"
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup238.Run \
   -c238Out "$OUT" -c238Shot "$SH" -c238Script "$SC" -c238Frames "$FR" -c238Stills "$ST" -c238Views "$VW" -c238Until "$UNTIL" -logFile "$OUT/unity.log"
echo "exit $?"
```

#### tools/run238b.sh（依頼238）

```bash
#!/bin/bash
# 依頼238（237 の写し） 区切って撮る（Unity は 13 分ほどで止められるので 1 回を短く）: run238b.sh <出力フォルダ> <場面> <台本> <from 秒> <to 秒（1e9＝終わりまで）> [stills on|off]
OUT="$1"; SH="$2"; SC="$3"; FROM="$4"; TO="$5"; ST="${6:-on}"
UNTIL=$(python3 -c "print($TO + 0.05 if $TO < 1e8 else 1e9)")
U=/Applications/Unity/Hub/Editor/2022.3.62f3/Unity.app/Contents/MacOS/Unity
P=/Users/shimazueiichi/Robotics_UX/ServiceSim
mkdir -p "$OUT"
"$U" -batchmode -quit -projectPath "$P" -executeMethod ServiceSim.Closeups.EditorTools.Closeup238.Run \
   -c238Out "$OUT" -c238Shot "$SH" -c238Script "$SC" -c238Frames on -c238Stills "$ST" -c238Views main,top -c238From "$FROM" -c238To "$TO" -c238Until "$UNTIL" -logFile "$OUT/unity_${FROM}_${TO}.log"
echo "exit $?"
```

#### geo/path235.json（依頼238）

```json
{"G": 2.3, "margin": 0.05, "back_max": 1.0, "turns": 7, "time_s": 12.95, "fwd_axle_m": 0.822, "back_axle_m": 0.054, "footrest_to_robot_min_m": 0.628, "rail_gap_min_m": 0.051, "heading_max_deg": 17.0, "segs": ["回る→(x +0.000, z +0.000, 向き +12°)", "前へ→(x +0.175, z -0.822, 向き +12°)", "回る→(x +0.175, z -0.822, 向き -17°)", "後ろへ→(x +0.385, z -0.133, 向き -17°)", "回る→(x +0.385, z -0.133, 向き -10°)", "後ろへ→(x +0.418, z +0.054, 向き -10°)", "回る→(x +0.418, z +0.054, 向き +0°)"], "path": [[0.0, 0.0, 0.0, ""], [0.0, 0.0, 1.0, "r"], [0.0, 0.0, 2.0, "r"], [0.0, 0.0, 3.0, "r"], [0.0, 0.0, 4.0, "r"], [0.0, 0.0, 5.0, "r"], [0.0, 0.0, 6.0, "r"], [0.0, 0.0, 7.0, "r"], [0.0, 0.0, 8.0, "r"], [0.0, 0.0, 9.0, "r"], [0.0, 0.0, 10.0, "r"], [0.0, 0.0, 11.0, "r"], [0.0, 0.0, 12.0, "r"], [0.0021, -0.0098, 12.0, "f"], [0.0042, -0.0196, 12.0, "f"], [0.0062, -0.0293, 12.0, "f"], [0.0083, -0.0391, 12.0, "f"], [0.0104, -0.0489, 12.0, "f"], [0.0125, -0.0587, 12.0, "f"], [0.0146, -0.0685, 12.0, "f"], [0.0166, -0.0783, 12.0, "f"], [0.0187, -0.088, 12.0, "f"], [0.0208, -0.0978, 12.0, "f"], [0.0229, -0.1076, 12.0, "f"], [0.0249, -0.1174, 12.0, "f"], [0.027, -0.1272, 12.0, "f"], [0.0291, -0.1369, 12.0, "f"], [0.0312, -0.1467, 12.0, "f"], [0.0333, -0.1565, 12.0, "f"], [0.0353, -0.1663, 12.0, "f"], [0.0374, -0.1761, 12.0, "f"], [0.0395, -0.1858, 12.0, "f"], [0.0416, -0.1956, 12.0, "f"], [0.0437, -0.2054, 12.0, "f"], [0.0457, -0.2152, 12.0, "f"], [0.0478, -0.225, 12.0, "f"], [0.0499, -0.2348, 12.0, "f"], [0.052, -0.2445, 12.0, "f"], [0.0541, -0.2543, 12.0, "f"], [0.0561, -0.2641, 12.0, "f"], [0.0582, -0.2739, 12.0, "f"], [0.0603, -0.2837, 12.0, "f"], [0.0624, -0.2934, 12.0, "f"], [0.0645, -0.3032, 12.0, "f"], [0.0665, -0.313, 12.0, "f"], [0.0686, -0.3228, 12.0, "f"], [0.0707, -0.3326, 12.0, "f"], [0.0728, -0.3424, 12.0, "f"], [0.0748, -0.3521, 12.0, "f"], [0.0769, -0.3619, 12.0, "f"], [0.079, -0.3717, 12.0, "f"], [0.0811, -0.3815, 12.0, "f"], [0.0832, -0.3913, 12.0, "f"], [0.0852, -0.401, 12.0, "f"], [0.0873, -0.4108, 12.0, "f"], [0.0894, -0.4206, 12.0, "f"], [0.0915, -0.4304, 12.0, "f"], [0.0936, -0.4402, 12.0, "f"], [0.0956, -0.4499, 12.0, "f"], [0.0977, -0.4597, 12.0, "f"], [0.0998, -0.4695, 12.0, "f"], [0.1019, -0.4793, 12.0, "f"], [0.104, -0.4891, 12.0, "f"], [0.106, -0.4989, 12.0, "f"], [0.1081, -0.5086, 12.0, "f"], [0.1102, -0.5184, 12.0, "f"], [0.1123, -0.5282, 12.0, "f"], [0.1144, -0.538, 12.0, "f"], [0.1164, -0.5478, 12.0, "f"], [0.1185, -0.5575, 12.0, "f"], [0.1206, -0.5673, 12.0, "f"], [0.1227, -0.5771, 12.0, "f"], [0.1247, -0.5869, 12.0, "f"], [0.1268, -0.5967, 12.0, "f"], [0.1289, -0.6065, 12.0, "f"], [0.131, -0.6162, 12.0, "f"], [0.1331, -0.626, 12.0, "f"], [0.1351, -0.6358, 12.0, "f"], [0.1372, -0.6456, 12.0, "f"], [0.1393, -0.6554, 12.0, "f"], [0.1414, -0.6651, 12.0, "f"], [0.1435, -0.6749, 12.0, "f"], [0.1455, -0.6847, 12.0, "f"], [0.1476, -0.6945, 12.0, "f"], [0.1497, -0.7043, 12.0, "f"], [0.1518, -0.714, 12.0, "f"], [0.1539, -0.7238, 12.0, "f"], [0.1559, -0.7336, 12.0, "f"], [0.158, -0.7434, 12.0, "f"], [0.1601, -0.7532, 12.0, "f"], [0.1622, -0.763, 12.0, "f"], [0.1643, -0.7727, 12.0, "f"], [0.1663, -0.7825, 12.0, "f"], [0.1684, -0.7923, 12.0, "f"], [0.1705, -0.8021, 12.0, "f"], [0.1726, -0.8119, 12.0, "f"], [0.1746, -0.8216, 12.0, "f"], [0.1746, -0.8216, 11.0, "r"], [0.1746, -0.8216, 10.0, "r"], [0.1746, -0.8216, 9.0, "r"], [0.1746, -0.8216, 8.0, "r"], [0.1746, -0.8216, 7.0, "r"], [0.1746, -0.8216, 6.0, "r"], [0.1746, -0.8216, 5.0, "r"], [0.1746, -0.8216, 4.0, "r"], [0.1746, -0.8216, 3.0, "r"], [0.1746, -0.8216, 2.0, "r"], [0.1746, -0.8216, 1.0, "r"], [0.1746, -0.8216, 0.0, "r"], [0.1746, -0.8216, -1.0, "r"], [0.1746, -0.8216, -2.0, "r"], [0.1746, -0.8216, -3.0, "r"], [0.1746, -0.8216, -4.0, "r"], [0.1746, -0.8216, -5.0, "r"], [0.1746, -0.8216, -6.0, "r"], [0.1746, -0.8216, -7.0, "r"], [0.1746, -0.8216, -8.0, "r"], [0.1746, -0.8216, -9.0, "r"], [0.1746, -0.8216, -10.0, "r"], [0.1746, -0.8216, -11.0, "r"], [0.1746, -0.8216, -12.0, "r"], [0.1746, -0.8216, -13.0, "r"], [0.1746, -0.8216, -14.0, "r"], [0.1746, -0.8216, -15.0, "r"], [0.1746, -0.8216, -16.0, "r"], [0.1746, -0.8216, -17.0, "r"], [0.1776, -0.8121, -17.0, "b"], [0.1805, -0.8025, -17.0, "b"], [0.1834, -0.793, -17.0, "b"], [0.1863, -0.7834, -17.0, "b"], [0.1893, -0.7738, -17.0, "b"], [0.1922, -0.7643, -17.0, "b"], [0.1951, -0.7547, -17.0, "b"], [0.198, -0.7451, -17.0, "b"], [0.201, -0.7356, -17.0, "b"], [0.2039, -0.726, -17.0, "b"], [0.2068, -0.7165, -17.0, "b"], [0.2097, -0.7069, -17.0, "b"], [0.2127, -0.6973, -17.0, "b"], [0.2156, -0.6878, -17.0, "b"], [0.2185, -0.6782, -17.0, "b"], [0.2214, -0.6686, -17.0, "b"], [0.2243, -0.6591, -17.0, "b"], [0.2273, -0.6495, -17.0, "b"], [0.2302, -0.6399, -17.0, "b"], [0.2331, -0.6304, -17.0, "b"], [0.236, -0.6208, -17.0, "b"], [0.239, -0.6113, -17.0, "b"], [0.2419, -0.6017, -17.0, "b"], [0.2448, -0.5921, -17.0, "b"], [0.2477, -0.5826, -17.0, "b"], [0.2507, -0.573, -17.0, "b"], [0.2536, -0.5634, -17.0, "b"], [0.2565, -0.5539, -17.0, "b"], [0.2594, -0.5443, -17.0, "b"], [0.2624, -0.5348, -17.0, "b"], [0.2653, -0.5252, -17.0, "b"], [0.2682, -0.5156, -17.0, "b"], [0.2711, -0.5061, -17.0, "b"], [0.2741, -0.4965, -17.0, "b"], [0.277, -0.4869, -17.0, "b"], [0.2799, -0.4774, -17.0, "b"], [0.2828, -0.4678, -17.0, "b"], [0.2857, -0.4582, -17.0, "b"], [0.2887, -0.4487, -17.0, "b"], [0.2916, -0.4391, -17.0, "b"], [0.2945, -0.4296, -17.0, "b"], [0.2974, -0.42, -17.0, "b"], [0.3004, -0.4104, -17.0, "b"], [0.3033, -0.4009, -17.0, "b"], [0.3062, -0.3913, -17.0, "b"], [0.3091, -0.3817, -17.0, "b"], [0.3121, -0.3722, -17.0, "b"], [0.315, -0.3626, -17.0, "b"], [0.3179, -0.3531, -17.0, "b"], [0.3208, -0.3435, -17.0, "b"], [0.3238, -0.3339, -17.0, "b"], [0.3267, -0.3244, -17.0, "b"], [0.3296, -0.3148, -17.0, "b"], [0.3325, -0.3052, -17.0, "b"], [0.3355, -0.2957, -17.0, "b"], [0.3384, -0.2861, -17.0, "b"], [0.3413, -0.2766, -17.0, "b"], [0.3442, -0.267, -17.0, "b"], [0.3471, -0.2574, -17.0, "b"], [0.3501, -0.2479, -17.0, "b"], [0.353, -0.2383, -17.0, "b"], [0.3559, -0.2287, -17.0, "b"], [0.3588, -0.2192, -17.0, "b"], [0.3618, -0.2096, -17.0, "b"], [0.3647, -0.2, -17.0, "b"], [0.3676, -0.1905, -17.0, "b"], [0.3705, -0.1809, -17.0, "b"], [0.3735, -0.1714, -17.0, "b"], [0.3764, -0.1618, -17.0, "b"], [0.3793, -0.1522, -17.0, "b"], [0.3822, -0.1427, -17.0, "b"], [0.3852, -0.1331, -17.0, "b"], [0.3852, -0.1331, -16.0, "r"], [0.3852, -0.1331, -15.0, "r"], [0.3852, -0.1331, -14.0, "r"], [0.3852, -0.1331, -13.0, "r"], [0.3852, -0.1331, -12.0, "r"], [0.3852, -0.1331, -11.0, "r"], [0.3852, -0.1331, -10.0, "r"], [0.3869, -0.1233, -10.0, "b"], [0.3886, -0.1134, -10.0, "b"], [0.3904, -0.1036, -10.0, "b"], [0.3921, -0.0937, -10.0, "b"], [0.3938, -0.0839, -10.0, "b"], [0.3956, -0.074, -10.0, "b"], [0.3973, -0.0642, -10.0, "b"], [0.399, -0.0543, -10.0, "b"], [0.4008, -0.0445, -10.0, "b"], [0.4025, -0.0346, -10.0, "b"], [0.4043, -0.0248, -10.0, "b"], [0.406, -0.0149, -10.0, "b"], [0.4077, -0.0051, -10.0, "b"], [0.4095, 0.0048, -10.0, "b"], [0.4112, 0.0146, -10.0, "b"], [0.4129, 0.0245, -10.0, "b"], [0.4147, 0.0343, -10.0, "b"], [0.4164, 0.0442, -10.0, "b"], [0.4181, 0.054, -10.0, "b"], [0.4181, 0.054, -9.0, "r"], [0.4181, 0.054, -8.0, "r"], [0.4181, 0.054, -7.0, "r"], [0.4181, 0.054, -6.0, "r"], [0.4181, 0.054, -5.0, "r"], [0.4181, 0.054, -4.0, "r"], [0.4181, 0.054, -3.0, "r"], [0.4181, 0.054, -2.0, "r"], [0.4181, 0.054, -1.0, "r"], [0.4181, 0.054, 0.0, "r"]]}
```



## 作業ログ ― サムネイルを作るコードの差分

上は真上から見た⑨-1 の寄せる所、左下は⑨-2 の「通れません」、右下は「あんたも待たされてるのかい」と言う茂さん。上に横長の帯、下に寄り2つの並べ方を足しました。

### tools/sim_thumbs/make.py の差分

```diff
diff --git a/tools/sim_thumbs/make.py b/tools/sim_thumbs/make.py
index c5a526e..b274c3f 100644
--- a/tools/sim_thumbs/make.py
+++ b/tools/sim_thumbs/make.py
@@ -218,8 +218,25 @@ def stills_mosaic(n, big, a, b, r=.6, bg=LIGHT):
     save(c, n)
 
 
+def stills_band(n, top, a, b, r=.5, bg=LIGHT):
+    """場面の寄り（LOG526〜）：上に横長の帯1つ、下に寄り2つ。top・a・b は (素材名, fx, fy, z)。r は上の帯の高さの割合"""
+    c = canvas(bg); ht = int(H * r) - G // 2; hb = H - ht - G; wl = (W - G) // 2
+    def part(spec, w, h):
+        name, fx, fy, z = spec
+        img = np.array(Image.open(D + name + '.jpg').convert('RGB'))
+        h0, w0 = img.shape[:2]; cw = int(w0 * z); ch = int(cw * h / w)
+        if ch > h0: ch = h0; cw = int(ch * w / h)
+        sx = max(0, min(w0 - cw, int(w0 * fx - cw / 2))); sy = max(0, min(h0 - ch, int(h0 * fy - ch / 2)))
+        return cv2.resize(img[sy:sy + ch, sx:sx + cw], (w, h), interpolation=cv2.INTER_AREA if cw > w else cv2.INTER_CUBIC)
+    put(c, part(top, W, ht), 0, 0)
+    put(c, part(a, wl, hb), 0, ht + G)
+    put(c, part(b, W - wl - G, hb), wl + G, ht + G)
+    save(c, n)
+
+
 # ---- 各回（素材名, 店の範囲の中の中心 x, y, 切り出し幅の割合）
 JOBS = {
+    526: lambda n: stills_band(n, ('closeup526_shift_top', .5, .58, .78), ('closeup526_toremasen', .5, .55, .85), ('closeup526_matasare', .55, .5, .8), r=.45),  # 3Dの場面⑨車いすが廊下の真ん中で止まるを作った回（依頼230〜238）。上＝真上から、止まった車いすを看護師がその場で寄せる所（⑨-1）、左下＝30秒で画面が「通れません」（⑨-2）、右下＝「あんたも待たされてるのかい」と言う患者（⑨-2）
     523: lambda n: stills_split(n, ('closeup523_pass', .42, .52, .42), ('closeup523_nod', .72, .6, .72), r=.55),  # 3Dの場面⑧車いすに道を譲るを作った回（依頼228・229）。左＝手すりに寄って止まったハコブくんの横を、看護師が押す車いすが通る所（本番のカメラ）、右＝「ありがとう」と言う看護師と、ハコブくんへ顔を向けてうなずく患者（顔の寄り）
     515: lambda n: stills_mosaic(n, ('closeup515_fail', .42, .5, .62), ('closeup515_recall', .5, .45, .8), ('closeup515_talk', .55, .5, .8)),  # 3Dの場面⑤⑥⑦を作った回（依頼203〜222）。左の大＝⑥違うカードで画面と横の輪が赤くなった所、右上＝⑤2分たって呼び直す画面（1個）、右下＝⑦廊下で「急ぎなの」と話す看護師とハコブくん
     500: lambda n: mosaic(n, ('h180_n_blood', .35, .52, .44), ('h180_n_bdoor', .26, .42, .42), ('h180_n_cross', .23, .55, .36), right=True),  # 病院の採血の人とロボットの入口を分けた回（依頼164〜180）。左の大＝10時15分の採血の所（内科の処置室）の寄り、右上＝中待合の側に足した扉を出る採血の人、右下＝台の前で待つロボットの前を横切る採血の人（依頼180 の静止画。右のパネルと上の文字を外して切った）
```
