# サービスロボット導入シミュレーション Log#51 | 搬送ロボットが車いすに道を譲る場面を3Dで

- 記録: LOG523（サービスロボット導入シミュレーション）
- 公開: 2026/11/16
- 記事のページ: https://pixelstomotors.com/record/hospital-robot-yields-to-wheelchair-in-3d
- サイト: Pixels to Motors（ADAPT DESIGN / 島津 栄一） https://pixelstomotors.com/
- 要約: 幅1.68mの病院の廊下では、搬送ロボットと車いすがどちらも幅0.65mで、ロボットがそのまま進むとすき間は9cmしか残らない。入院中の患者と車いすの3Dを作り、ロボットが道を譲る場面を Unity で見られるようにした。

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

---

手すりの間が1.68mの病院の廊下では、薬を運ぶ搬送ロボット（幅0.65m）と車いす（幅0.65m）がすれ違うとき、ロボットが手すりに寄らずにそのまま進めば、すき間は9cmしか残らない。**実物ではなく Unity の3DCGで作ったシミュレーションの場面で、搬送ロボット「ハコブくん」が車いすを見つけて減速し、手すりから5.5cmの所に寄って止まり、「お先にどうぞ」と伝えて車いすを先に通すと、すき間は22cmになった。**

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

- [サービスロボット導入シミュレーションのページ](https://pixelstomotors.com/series8#scenes) の「3Dで見る現場の場面」に、⑧車いすに道を譲る を足した。サイトのトップの3Dの場面にも同じ動画が出る。看護師とハコブくんの声つき
- 入院中の年配の患者（マンガの森田茂さん）と、病院でよく見る自走用の車いすの3Dモデルを作った。看護師の大城さんに続く2人目の人で、これからの場面で使える。作り方のコードとモデルは GitHub に置いた
- 「前から来る車いすとすれ違うとき、すき間が0.15mより狭くなりそうなら、手すりに寄って止まる」というロボットのふるまいの決まりが、数字と動画の両方で見える形になった。病院の1日のシミュレーション（丸と四角で動く版）で数えている「車いすの前を横切った」「立ち往生」が、現場ではどんな場面になるかを見せる1本になる
- 時間：モデルづくりは、作り始めてから肩口を直して見た目が決まるまで約40分（17時49分〜18時25分）。Unity への依頼は2本で、228が18時27分〜19時39分、229が19時48分〜20時17分。前のやり方と比べられる時間は測っていない

困っていたのは、病院の1日のシミュレーションで数えている問題の1件が、現場で何を意味するのかが、丸と四角の動きでは伝わりにくいことでした。「車いすの前を横切った」が1日に何回、と出ても、それがどれくらい危ないのか、ロボットはどう振る舞えばよいのかは見えません。廊下の幅と、ロボットと車いすの幅を並べると、ロボットが寄って止まらなければ通れないことが、数字ではっきりします。

| やったこと | 何を・なぜ | 結果 |
|---|---|---|
| 患者と車いすの3D | マンガの森田茂さんを、入院着で車いすに座った形のまま作った。立たない役なので、座った形で骨を入れた | 三角形 約72,700（人）と約18,400（車いす）。肩口が切れていたのを直した |
| 依頼228（⑧の1本目） | 大城さんが押す車いすと、薬を運ぶハコブくんが廊下ですれ違う | 6.0mで見つけ、手すりに寄って止まり、すき間0.224m。「必ず守る」はすべて守れた |
| 依頼229（⑧の2本目） | 車いすを14cm通路の真ん中寄りから始め、ハコブくんが寄り始めたのを見て、看護師も手すり側へ寄せる | 寄せなかったらすき間0.084mのところ、0.224m。⑧はこの版で完成 |
| サイト | /series8 とトップの3Dの場面に⑧を足した | 8本になった |

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

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

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


## 作業ログ ― 入院中の患者と車いすの3Dを、Blender で作った

⑧車いすに道を譲る は、前の回（[LOG515](https://pixelstomotors.com/record/hospital-robot-three-trouble-scenes-in-3d)）までに決めていた、3Dの場面に足す4つの最後の1本です。車いすに乗る人と押す人が要りますが、3Dの人は看護師の大城さんしかいませんでした。

### Blender は、3Dのモデルを作る無料の道具

[Blender](https://www.blender.org/) は、3Dのモデル・骨・色を作って、絵や動画に描き出せる無料の道具です。Python から動かせるので、形を手で触らずに、コードで作れます。このプロジェクトでは、ハコブくんと看護師の大城さんの3Dも Blender で作り、Unity に読み込んで動かしています（LOG496）。

| この回で使う言葉 | 意味 |
|---|---|
| FBX | 3Dのモデル・骨・色をまとめて、ほかの道具へ渡すファイルの形。Blender で書き出し、Unity で読む |
| 骨（ボーン） | 体の中に入れる棒。骨を回すと、まわりの肌や服がいっしょに動く |
| 重み | 肌や服の点が、どの骨にどれだけ付いて動くかの割合 |
| Generic と Humanoid | Unity での骨の読み方。Humanoid は人の形の決まった姿勢（T ポーズ）にそろえて読む。Generic は作ったときの姿勢のまま読み、骨を直接回す |

### 乗る人は、マンガの森田茂さんを入院着にした

だれを乗せるかは、マンガ『ハコブくん』の登場人物から選んでもらいました。外来の夫婦（茂さんが乗り、妻の久美子さんが押す）を最初の案にしましたが、エイイチが選んだのは、入院着の茂さんが乗り、看護師の大城さんが押す形でした。病棟の廊下の場面なので、入院中の患者を看護師が押すほうが合います。新しく作るのは茂さんと車いすだけになりました。

茂さんの見た目は、マンガの三面図（白髪の横分け・丸めがね）と、入院着の三面図（甚平型の上・ズボン・スリッパ）から作りました。大城さんと同じく、粘土のような簡略化した見た目です。年配に見えるように、ほうれい線と目じりのしわを、肌より少し濃い線で浅く入れました。

### 茂さんは、座った形のまま骨を入れた

ふつう、人のモデルは立った形で作り、骨を回して座らせます。茂さんは車いすから立たない役なので、はじめから座った形で作りました。立った形から座らせると、ももの付け根でズボンがつぶれたり伸びたりしやすいからです。

- ねらい：座ったときの形を、作った時点で決めてしまう
- 変わったこと：上半身は立った時の形で書き、背もたれへ7°もたれた形に回して、座面（クッションの上 0.485m）に置いた。脚・腕は、座った形の点で直接書いた
- 見込める効果：Unity では、顔の向き・うなずき・手だけを動かせばよく、座った形がくずれない。Humanoid にすると T ポーズに直されて形がくずれるので、Generic で読む（依頼228 で Generic にして、座った形がそのまま出ることを確かめた）

骨の名前は大城さんと同じ45本で、口は5つの形（flat・smile・worried・talk・surprised）を別の部品で入れ、表示を切り替えます。服や肌が骨の動きで破れないかは、首を回す・前へかがむ・右手を上げる・うなずく、の4つの姿勢を付けて描き、確かめました。

![Blender で描いた森田茂さん（入院着）と車いす。上の段は正面・横・後ろ、中の段は斜めから2つと上半身と顔の寄り、下の段は看護師の大城さんを車いすの後ろに立たせて大きさを比べた所。肩口のすき間を直す前の版](https://pixelstomotors.com/media/LOG523_01_morita_blender.jpg)

![座ったまま骨を動かして、服や肌が破れないかを確かめた4つの姿勢。左から、顔を横へ向ける・前へかがむ・右手を上げる・うなずく](https://pixelstomotors.com/media/LOG523_03_poses.jpg)

### 車いすは、回る所を別の部品にした

車いすは、病院でよく見る自走用の形にしました。幅0.65m・長さ1.07m・押し手の握りの高さ0.91m、後ろの車輪は22インチ（半径0.28m）です。Unity で押して動かすときに車輪が回るように、後ろの車輪（車軸が中心）、前の小さい車輪の向き（支柱が中心）、前の小さい車輪の回転（車軸が中心）を、それぞれ別の部品にしました。

### 肩口が横一文字に切れていたのを直した

最初の絵を見たエイイチから、入院着の肩口が切れていると指摘がありました。正面から見ると、両肩の上が横一文字に開き、中が見えていました。

原因は、えりの合わせのV字を切り抜く式でした。V字の線を、首の幅より外では端の高さのまま横へのばしていたので、肩の上まで同じ高さで切れていました。V字を首の幅（左右0.058m）の中だけで切るように1行足して直しました。

![入院着の肩口の前と後。左はエイイチが画面を切り取って送った、肩の上が横に切れて中が見えている所、右は V字を首の幅の中だけで切るように直した版](https://pixelstomotors.com/media/LOG523_02_shoulder.jpg)


## 作業ログ ― 依頼228：⑧車いすに道を譲る の1本目を作った

モデルを GitHub（`PixelstoMotors/p2m-site` の `tools/sim_people/morita_shigeru/`・commit fa920a2）に入れて、依頼箱から Claude Code に⑧を頼みました。

### 場面の流れは7つ

| 順 | 何が起きるか | セリフ |
|---|---|---|
| 1 | ハコブくんが薬を積んで、廊下を0.6m/秒で走る（左側通行） | ― |
| 2 | 向こうから、大城さんが茂さんの車いすを押して来る（0.8m/秒・左側通行） | ― |
| 3 | ハコブくんが車いすを見つけ、減速して左の手すり側へ寄り、止まる | ― |
| 4 | 止まったら、画面の帯と声で知らせる | ハコブ「お先にどうぞ」 |
| 5 | 大城さんが軽く笑って言う。茂さんはハコブくんへ顔を向けてうなずく | 大城「ありがとう」 |
| 6 | 車いすがハコブくんの横を通りすぎる（押す速さを0.65m/秒に落とす） | ― |
| 7 | 大城さんがハコブくんの後ろから1m以上離れてから、ハコブくんが走り出す | ― |

廊下は、③廊下ですれ違う（LOG503）と同じ、壁の間1.8m・手すりの間1.68mの病棟の廊下です。

### ハコブくんの決まり：0.15m より狭くなりそうなら、寄って止まる

ハコブくんは、前から来る車いすとのあいだが「止まるまでに縮まる距離＋余り2.4m」を切ったら、減速して手すり側へ寄ります。すれ違うときのすき間の予想が0.15mより狭ければ、寄って止まって待ちます。この場面では、6.0m手前で車いすを見つけ、5.76mで決まりに当たりました。そのまま進んだときのすき間の予想は0.094mで、0.15mより狭いので「寄って止まる」になりました。

| できごと | 動画の秒 | 値 |
|---|---|---|
| 見つけた | 9.533 | 車いすの足のせとのあいだ 5.995m |
| 決まりに当たり、減速して寄り始める | 9.700 | 5.762m ＜ 5.783m（止まるまでに縮まる 3.38m＋余り 2.4m） |
| 止まった | 12.533 | 足のせとのあいだ 2.299m・手すりとのすき間 0.055m |
| 「お先にどうぞ」 | 12.833〜13.663 | 声の長さ 0.830秒 |
| 「ありがとう」 | 14.213〜15.013 | 前の声との間 0.550秒 |
| すれ違うときのすき間の最小 | 18.100 | 0.224m（車いすの右の後ろの車輪とハコブくん） |
| 走り出し | 20.467 | 大城さんの体とハコブくんの後ろの端 1.020m |

![⑧車いすに道を譲る（依頼228）。左上は向こうから車いすが来る所、右上はハコブくんが手すりに寄って止まった所、左下は画面の帯「お先にどうぞ」の寄り、右下は「ありがとう」と言う大城さんと、ハコブくんへ顔を向けてうなずく茂さん](https://pixelstomotors.com/media/LOG523_05_yield228.jpg)

大城さんの手は、全部のコマで握りから離れていません（手のひらの的とのずれ0.0000m）。車いすは大城さんの前0.594mに固く付けて動かし、後ろの車輪は進んだ距離÷0.28mだけ回るので、すべって見えません。

### Unity の茂さんは、Blender の絵より暗く見えた

依頼228 では、読み込んだ茂さんと車いすを6方向から撮り、Blender の絵と並べました。形と座り方は同じでした。色は、Unity のほうが全体に暗く、肌は茶色寄り、入院着は灰色がかった青に見えます。色の値は大城さんと同じ直し方で、違いは光によるもの（Unity は病院の1日の場面と同じ光、Blender は明るい白い光と白い床）です。エイイチの判断で、このままにしました。

![左は Unity に読み込んだ茂さんと車いす（依頼228・Generic で読んだ）を6方向から撮ったもの、右は Blender で描いた絵。形と座り方は同じで、Unity のほうが光のせいで暗く見える](https://pixelstomotors.com/media/LOG523_04_unity_vs_blender.jpg)


## 作業ログ ― 依頼229：車いすを真ん中寄りから始め、看護師も寄せる形にした

依頼228 の動画を見たエイイチから、車いすはもう少しだけ通路の真ん中寄りで始まるほうがいい、と指示がありました。228 では、車いすがはじめから手すりの近く（中心から +0.42m・手すりと0.18m）を来ていたので、ハコブくんだけが道を空けているように見えました。

- ねらい：ハコブくんが道を空け、看護師も少し寄る、という譲り合いに見せる
- 変わったこと：車いすの始めの位置を、中心から +0.42m → +0.28m（14cm 真ん中寄り）にした。ハコブくんが寄り始めて0.6秒後から、大城さんが車いすを手すり側へ寄せ、3.5秒で +0.42m に戻す。寄せる間の向きは最大5.4°、横の速さは足のせの前の端で0.109m/秒（決まりは0.12m/秒まで）
- 変わったことの効果（測った値）：大城さんが寄せなかったとしたら、ハコブくんが寄って止まっても、すき間は0.084m（0.15mより狭い）。寄せて0.224m

ハコブくんの動きは、228 とまったく同じです。決まりに当たった時、車いすは +0.28m にいるので、そのまま進んだときのすき間の予想は −0.046m（重なる）でした。どちらにしても「寄って止まる」なので、止まる位置も時刻も変わりません。前の小さい車輪は、向きを変える所で最大2.41°向きを変えて付いていき、横にすべっていません。

![⑧車いすに道を譲る（依頼229）。左上は大城さんが車いすを手すり側へ寄せている所（本番のカメラ）、右上は同じ所を真上から、左下は寄せたあと、止まったハコブくんの横を車いすが通る所、右下は大城さんが離れてから走り出したハコブくん](https://pixelstomotors.com/media/LOG523_06_shift229.jpg)

寄せ終わる所は、ハコブくんの画面「お先にどうぞ」の寄りに切りかわった後になり、動画には写りません。エイイチの判断で、この版で⑧を完成にしました。


## 作業ログ ― サイトの3Dの場面に⑧を足した

依頼229 の動画を R2（`scene3d_08_yield_v1.mp4`）に入れ、`src/data/sim_scenes.json` に⑧を足しました（commit 05bfa52）。/series8 とトップは同じ部品・同じデータを読むので、両方に出ます。公開後のページで、/series8 とトップの両方に⑧の動画と「車いすに道を譲る」が出ていることを確かめました。記事を書くときに、説明の見どころの「寄って止まらなければすき間は8cm」が測った値と合っていないことに気づきました。8cm（0.084m）は、ハコブくんが寄って止まり、車いすが寄せなかったときの値です。ハコブくんがそのまま進んだときの予想は9cm（0.094m）なので、「そのまま進めばすき間は9cm」に直しました（この記事と同じ commit）。

⑦廊下で話しかけられる は、前の回の続きで「お届け完了」の画面で目まで笑う顔にした版（依頼224）が載っています。ハコブくんの「薬剤部へ戻ります」の声の終わりより少し前に、口が閉じた笑顔に替わる所が残っていましたが、エイイチの判断で、この版で確定にしました。


## 作業ログ ― 茂さんと車いすを作るコード（p2m-site の tools/sim_people/morita_shigeru/）

作ったときの版です（commit fa920a2・肩口の直しを含む）。動かし方は README.md のとおりで、Blender 5.3 を Python から使います（`pip install bpy==5.3.0 scikit-image`）。

### README.md

```markdown
# 森田茂さん（入院中の年配の患者）と車いすの3Dモデル（サービスロボット導入シミュレーション・病院の場面の人）

要所の場面 ⑧車いすに道を譲る のための人と車いす（2026-11-16）。車いすに座った茂さんを、看護師の大城さん（tools/sim_people/nurse_oshiro/）が押す。マンガの森田茂さんの三面図（ref_morita_shigeru.jpg）と、入院着の三面図（ref_gown.jpg・中村拓也さん）を元に、大城さんと同じ粘土のような簡略化した見た目で作った。

- 見た目：白髪の横分け（本人の右で分けて左へ流す）、丸めがね、浅いほうれい線と目じりのしわ。入院着は甚平型の上（左の身ごろが上・本人の右のわきで結ぶ）とズボン、スリッパ。色は薄い水色
- 大きさ：立った時の身長 1.68 m 相当。**座った形のまま作ってある**（車いすから立たない役なので、作った時の姿勢を座った形にした）
- 向き：根（骨組みの Morita_Shigeru）は床の中心。顔が Unity の +Z を向く。車いすの根（Wheelchair）と同じ位置・向きに置くと、クッションの上に座り、足が足のせ板にのる

## 作り方

1. `pip install bpy==5.3.0 scikit-image`
2. `python3 morita_build.py <出力フォルダ>`：morita_shigeru.fbx・morita_clay.blend・morita_report.json（部品ごとの三角形の数・骨の名前・頭の中心）
3. `python3 wheelchair_build.py <出力フォルダ>`：wheelchair.fbx・wheelchair.blend・wheelchair_report.json（大きさ・車輪の半径・車軸の位置・押し手の高さ）
4. 確認用の絵（GitHub に入れない。iCloud の サービスロボット導入シミュレーション/hospital/people_3d/）
   - `python3 morita_render.py <絵のフォルダ> morita_clay.blend wheelchair.blend --views front side back persp persp2 upper face feet`
   - 大城さんと並べる：`... nurse_clay.blend --nurse-y 0.72 --views withnurse`
   - `python3 morita_pose.py morita_clay.blend wheelchair.blend <絵のフォルダ>`：座ったまま動かした姿勢（顔を横へ向ける・前へかがむ・右手を上げる・うなずく）。服や肌が破れないかの確認用

形の作り方（部品ごとに「表面からの距離」を式で書き、格子で面にして三角形を減らす）と、骨の重みの付け方は大城さんと同じ。上半身は立った時の形で書いてから、背もたれへ 7° もたれた形に回して座面の上へ置いている（`T`・`Tinv_field`）。頭はまっすぐ。

## 茂さんの中身（三角形 約 72,700）

| 名前 | 中身 |
|---|---|
| Morita_Shigeru | 骨組み（大城さんと同じ 45 本の名前）。座った形で置いてある |
| Morita_Skin / Morita_SkinLegs | 頭・首・胸元・腕・手 ／ 足首と足 |
| Morita_Hair | 髪 |
| Morita_Top | 入院着の上（えり・結びひもを含む） |
| Morita_Sleeves | ひじまでの半そで（胴とつなげない。まるごと上腕の骨で動く） |
| Morita_Pants / Morita_Slippers | ズボン ／ スリッパ |
| Morita_Eyes / Morita_Brows / Morita_Lines / Morita_Glasses | 目・眉・しわ・めがね（めがねとしわは Head の骨で動く） |
| Morita_Mouth_flat（既定で表示）/ smile / worried / talk / surprised | 口。表示を切り替える |

- 骨の名前は Unity の Humanoid と同じだが、作った時の姿勢が座った形なので、Humanoid の T ポーズに直すと形がくずれる。**Unity では Generic で読み、骨をスクリプトで回して動かす**（顔の向き・うなずき・手）
- 口・まばたき・眉は大城さんと同じ仕組み（Eye_L/R を上下につぶす、Brow_L/R を回す・上げる）

## 車いすの中身（三角形 約 18,400）

幅 0.65 m・長さ 1.07 m・押し手の握りの高さ 0.91 m・後ろの車輪 22 インチ（半径 0.28 m）・前の車輪の半径 0.075 m・座る面（クッションの上）0.485 m。

| 名前 | 中身・回す中心 |
|---|---|
| Wheelchair | 根（床の中心） |
| WC_Frame / WC_Parts / WC_Seat / WC_Cushion / WC_Back | 枠（銀）・握りとひじかけと足のせ（黒）・座面と背もたれの布（紺）・クッション |
| Wheel_L / Wheel_R | 後ろの車輪とハンドリム。根は車軸。Unity の X 軸まわりに回す（進んだ距離 ÷ 0.28 m がラジアン） |
| Caster_L / Caster_R | 前の車輪の向き。根は支柱。Unity の Y 軸まわりに回す（進む向きの後ろへ車輪が付いていく） |
| CasterWheel_L / CasterWheel_R | 前の車輪の回転。Caster の子で、根は車軸（進んだ距離 ÷ 0.075 m） |

L は座った人の左（+x）。押す人の手は、握り（WC_Parts の黒い筒・左右 0.45 m 離れている）にのせる。
```

### morita_build.py

```python
"""入院中の年配の患者（森田茂さん）を、車いすに座った形のまま、形の式（距離の場）から作る。
python3 morita_build.py <out_dir> [--vox 0.0025] [部品の名前...]
前が -y、上が z、単位は m。立った時の身長 1.68 m。根（Morita_Shigeru）は床の中心で、車いす（wheelchair_build.py）の根と同じ位置に置くと座った形が合う。
服はマンガの入院着（甚平型の上・ズボン・スリッパ）。顔はマンガの森田茂さん（白髪の横分け・丸めがね）。
出力：morita_clay.blend・morita_shigeru.fbx・morita_report.json
骨は Unity の Humanoid の名前で、座った形のまま置いてある（立たせない人なので、作った時の姿勢を座った形にした）。
口は5つの形（flat・smile・worried・talk・surprised）を別の部品で入れてあり、Unity で表示を切り替える（既定は flat）。
"""
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))


# ---------- 座った姿勢の置き方 ----------
# 上半身は「立った時の形（std）」で書き、後ろへ少しもたれた形に回して座面の上へ置く。
# 頭はまっすぐ（もたれた分を首で戻す）。腕・脚は座った形の点で直接書く。
LEAN = math.radians(-7)                         # 背もたれへ 7° もたれる
STD_HIP = np.array([0.0, 0.012, 0.90])
SEAT_HIP = np.array([0.0, 0.060, 0.585])        # 座った時の腰の骨の根元（車いすのクッションの上は 0.485）
CL, SL = math.cos(LEAN), math.sin(LEAN)


def T(q):
    """std の点 → 座った形の点"""
    r = np.array(q, float) - STD_HIP
    return np.array([r[0], r[1] * CL - r[2] * SL, r[1] * SL + r[2] * CL]) + SEAT_HIP


def Tinv_field(p):
    """座った形の格子の点 → std の点（形の式を std で書くため）"""
    r = p - SEAT_HIP.reshape(3, 1)
    y = r[1] * CL + r[2] * SL
    z = -r[1] * SL + r[2] * CL
    return np.stack([r[0], y, z]) + STD_HIP.reshape(3, 1)


HC = T([0.0, 0.0, 1.512]) + np.array([0.0, -0.018, 0.0])   # 頭の中心（頭はまっすぐ・少し前へ）


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


SH = 0.168
SHOULDER = {s: T([s * SH, 0.012, 1.318]) for s in (-1, 1)}


def arm_points(side):
    """肩 → ひじ → 手首。手はひざの上（太ももの上）に置く"""
    s = 1 if side > 0 else -1
    sh = SHOULDER[s]
    el = sh + np.array([s * 0.016, -0.048, -0.244])
    wr = np.array([s * 0.128, -0.150, 0.700])
    d1 = (el - sh) / np.linalg.norm(el - sh)
    d2 = (wr - el) / np.linalg.norm(wr - el)
    return sh, el, wr, d1, d2


def hand_geo(side):
    """手のひらを下（太もも）に向けて置いた手。u＝指先の向き、n＝手のひらの向き、w＝親指のほう"""
    s = 1 if side > 0 else -1
    _, el, wr, _, d2 = arm_points(side)
    u = np.array([-s * 0.10, -0.97, -0.20])
    u /= np.linalg.norm(u)
    n = np.array([0.0, 0.0, -1.0])
    n = n - u * np.dot(n, u)
    n /= np.linalg.norm(n)
    w = np.cross(n, u) * s                      # 親指は体の内側
    if w[0] * s > 0:
        w = -w
    base = wr + u * 0.088
    fingers = {}
    for name, off, ln, r in (("Index", 0.027, 0.074, 0.0112), ("Middle", 0.009, 0.082, 0.0115),
                             ("Ring", -0.009, 0.078, 0.0112), ("Little", -0.026, 0.063, 0.0100)):
        a = base + w * off
        d_1 = u * math.cos(math.radians(16)) + n * math.sin(math.radians(16))
        b = a + d_1 * ln * 0.52
        d_2 = u * math.cos(math.radians(34)) + n * math.sin(math.radians(34))
        c = b + d_2 * ln * 0.48
        fingers[name] = (a, b, c, r)
    ta = wr + u * 0.03 + w * 0.026 + n * 0.006
    td = u * 0.60 + w * 0.70 + n * 0.30
    td /= np.linalg.norm(td)
    tb = ta + td * 0.042
    td2 = u * 0.85 + w * 0.35 + n * 0.35
    td2 /= np.linalg.norm(td2)
    tc = tb + td2 * 0.033
    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, n = g["wr"], g["u"], g["w"], g["n"]
    ds = [ellipsoid(p, (wr + u * 0.045).tolist(), (0.025, 0.025, 0.025))]
    for t in (0.02, 0.046, 0.072):
        c = wr + u * t
        ds.append(capsule(p, (c - w * 0.024).tolist(), (c + w * 0.024).tolist(), 0.0185, 0.0185))
    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.0140, 0.0125)
    out["ThumbIntermediate"] = capsule(p, tb.tolist(), tc.tolist(), 0.0125, 0.0110)
    return out


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


def leg_points(side):
    s = 1 if side > 0 else -1
    hip = np.array([s * 0.090, 0.040, 0.585])
    knee = np.array([s * 0.105, -0.395, 0.565])
    ankle = np.array([s * 0.112, -0.440, 0.165])
    ball = np.array([s * 0.112, -0.560, 0.102])
    tip = np.array([s * 0.112, -0.615, 0.098])
    return hip, knee, ankle, ball, tip


def head_solid(p):
    """年配の男の人の頭：大城さんより少し面長、ほおは細め、あごはしっかり"""
    cr = ellipsoid(p, H(0, 0, 0), (0.099, 0.108, 0.110))
    jaw = ellipsoid(p, H(0, -0.012, -0.062), (0.078, 0.080, 0.078))
    d = smin(cr, jaw, 0.03)
    cheeks = [ellipsoid(p, H(s * 0.046, -0.050, -0.050), (0.036, 0.034, 0.034)) for s in (-1, 1)]
    d = union([d] + cheeks, 0.03)
    nose = ellipsoid(p, H(0, -0.100, -0.026), (0.012, 0.013, 0.017))
    d = smin(d, nose, 0.010)
    ears = [ellipsoid(p, H(s * 0.098, 0.008, -0.018), (0.015, 0.023, 0.033)) for s in (-1, 1)]
    return union([d] + ears, 0.008)


def neck_std(q):
    return capsule(q, (0, 0.012, 1.30), (0, 0.006, 1.42), 0.044, 0.040)


def skin(p):
    q = Tinv_field(p)
    ds = [head_solid(p), neck_std(q), ellipsoid(q, (0, 0.012, 1.25), (0.11, 0.072, 0.10))]
    # 首は std で書いたので、もたれた分だけ頭とずれる。首の上を頭の下につなぐ
    ds.append(capsule(p, T([0, 0.006, 1.42]).tolist(), H(0, 0.012, -0.06), 0.041, 0.039))
    for sd in (-1, 1):
        ds.append(capsule(q, (sd * 0.045, 0.015, 1.335), (sd * 0.13, 0.015, 1.31), 0.026, 0.024))
    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.043, 0.039),
                 capsule(p, el.tolist(), wr.tolist(), 0.038, 0.030), 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)
        qq = p - sh.reshape(3, 1)
        proj = np.sum(qq * d1.reshape(3, 1), axis=0)
        radial = length(qq - d1.reshape(3, 1) * proj)
        inside = np.maximum(np.maximum(-0.12 - proj, proj - 0.17), radial - 0.07)
        d = smax(d, -inside, 0.005)
    return d


def legskin(p):
    """パンツのすそとスリッパの間の足首・足（スリッパの中も埋めておく）"""
    ds = []
    for s in (-1, 1):
        _, knee, ankle, ball, tip = leg_points(s)
        mid = ankle + (knee - ankle) * 0.12
        ds.append(capsule(p, mid.tolist(), ankle.tolist(), 0.038, 0.032))
        ds.append(capsule(p, ankle.tolist(), ball.tolist(), 0.034, 0.030))
    return union(ds, 0.02)


def hairline(p):
    x = p[0] - HC[0]
    y = p[1] - (HC[1] + 0.005)
    th = np.degrees(np.arctan2(x, -y))      # 0＝正面、＋＝本人の左
    a = np.abs(th)
    # こめかみは少し後退（額の角が上がる）、耳の前にもみあげ、耳の上は短く、後ろはえりあしまで
    z = np.interp(a, [0, 18, 34, 48, 62, 74, 82, 92, 104, 118, 140, 180],
                  [0.050, 0.052, 0.060, 0.050, 0.024, 0.004, -0.026, 0.020, 0.022, -0.010, -0.050, -0.068])
    # 本人の右で分け、左へ流す：分け目の側は額が上がり、流れた側は額に少しかかる
    front = np.clip(np.cos(np.radians(th)), 0, 1) ** 3
    z = z + front * np.interp(th, [-40, -15, 0, 20, 45], [0.010, 0.012, 0.0, -0.016, -0.004])
    return z + HC[2]


def hair(p):
    s = ellipsoid(p, H(0, 0.012, 0.004), (0.106, 0.116, 0.118))
    # 上と左前にふくらみ（右で分けて左へ流し、後ろへなでつけた量）
    puff = ellipsoid(p, H(0.022, -0.012, 0.050), (0.098, 0.106, 0.082))
    flow = ellipsoid(p, H(0.050, -0.062, 0.050), (0.060, 0.050, 0.040))
    s = union([s, puff, flow], 0.03)
    nape = ellipsoid(p, H(0, 0.050, -0.048), (0.090, 0.076, 0.058))
    s = smin(s, nape, 0.03)
    d = smax(s, hairline(p) - p[2], 0.008)
    return d


# ---------- 入院着（甚平型の上・ズボン） ----------
def torso_std(q):
    rr = 0.070
    c = np.array([0.0, 0.012, 1.080]).reshape(3, 1)
    b = np.array([0.178 - rr, 0.112 - rr, 0.300 - rr]).reshape(3, 1)
    qq = np.abs(q - c) - b
    d = length(np.maximum(qq, 0)) + np.minimum(qq.max(axis=0), 0) - rr
    ax = np.abs(q[0])
    slope = (q[2] - (1.380 - 0.22 * np.clip(ax - 0.05, 0, 0.10) - 0.20 * np.maximum(ax - 0.15, 0))) / 1.03
    d = smax(d, slope, 0.06)
    # 年配の人の、少し前に出たおなか
    belly = ellipsoid(q, (0, -0.040, 0.93), (0.150, 0.090, 0.110))
    return smin(d, belly, 0.05)


def torso_surface_y(x, z):
    """std の前の面の y（前から光線を進める）"""
    y = -0.3
    for _ in range(200):
        d = float(torso_std(np.array([[x], [y], [z]]))[0])
        if d < 1e-5:
            break
        y += max(d * 0.8, 1e-5)
    return y


# 前の合わせ：本人の左の身ごろが上（右前）。えりは左の首から、本人の右のわきの結びひもへ下りる
CROSS = (-0.012, 1.155)                          # 合わせの交わる点（x, z）
TOP_EDGE = [(0.058, 1.345), (0.030, 1.255), CROSS, (-0.060, 1.060), (-0.125, 0.950)]
UNDER_EDGE = [(-0.058, 1.345), (-0.032, 1.245), CROSS]


def edge_z(x, pts):
    xs = [p[0] for p in pts]
    zs = [p[1] for p in pts]
    if xs[0] > xs[-1]:
        xs, zs = xs[::-1], zs[::-1]
    return np.interp(x, xs, zs)


def collar_std(q):
    """えり（えりの帯）と結びひも。身ごろの表面に盛った帯"""
    ds = []
    for pts, n in ((TOP_EDGE, 14), (UNDER_EDGE, 6)):
        xs = np.linspace(pts[0][0], pts[-1][0], n)
        chain = [(x0, torso_surface_y(x0, float(edge_z(x0, pts))) + 0.002, float(edge_z(x0, pts))) for x0 in xs]
        for i in range(n - 1):
            ds.append(capsule(q, chain[i], chain[i + 1], 0.0115, 0.0115))
    # 首の後ろのえり
    for k in range(9):
        a0 = math.radians(-70 + 140 * k / 8)
        a1 = math.radians(-70 + 140 * (k + 1) / 8)
        p0 = (0.062 * math.sin(a0), 0.016 + 0.062 * math.cos(a0), 1.345 + 0.008 * math.cos(a0))
        p1 = (0.062 * math.sin(a1), 0.016 + 0.062 * math.cos(a1), 1.345 + 0.008 * math.cos(a1))
        ds.append(capsule(q, p0, p1, 0.0115, 0.0115))
    # 結びひも（本人の右のわき）：ちょう結びの輪2つと、たれる2本
    kx, kz = -0.150, 0.958
    ky = torso_surface_y(kx + 0.02, kz) + 0.004
    knot = (kx, ky, kz)
    ds.append(ellipsoid(q, knot, (0.010, 0.008, 0.009)))
    ds.append(ellipsoid(q, (kx + 0.022, ky - 0.002, kz + 0.008), (0.020, 0.006, 0.008)))
    ds.append(ellipsoid(q, (kx - 0.020, ky + 0.004, kz + 0.008), (0.018, 0.006, 0.008)))
    ds.append(capsule(q, knot, (kx + 0.010, ky - 0.004, kz - 0.050), 0.0045, 0.0045))
    ds.append(capsule(q, knot, (kx - 0.012, ky, kz - 0.044), 0.0045, 0.0045))
    return union(ds, 0.004)


def top(p):
    q = Tinv_field(p)
    outer = torso_std(q)
    d = shell(outer, 0.008)
    # すそ：座っているので、ひざの上に乗る高さで切る（後ろは座面まで）
    hem = np.interp(p[1], [-0.20, -0.05, 0.10], [0.640, 0.600, 0.505])
    d = smax(d, hem - p[2], 0.006)
    # えりぐり：首まわり＋合わせの V（上前より上で、下前より上の所を開ける）
    neck = np.sqrt(q[0] ** 2 + (q[1] - 0.016) ** 2) - 0.056
    vee = np.maximum(np.maximum(edge_z(q[0], TOP_EDGE) - q[2], edge_z(q[0], UNDER_EDGE) - q[2]), q[1] + 0.02)
    vee = np.maximum(vee, np.abs(q[0]) - 0.058)                # 合わせの V は首の幅の中だけ（外へ広げると肩口まで切れた）
    cut = smin(np.maximum(neck, 1.33 - q[2]), vee, 0.012)
    d = smax(d, -cut, 0.006)
    return smin(d, collar_std(q), 0.003)


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.24).tolist(), 0.060, 0.068)
        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.235, 0.004))
    return np.minimum(sl[0], sl[1])


def pants(p):
    ds = [ellipsoid(p, (0, 0.045, 0.590), (0.172, 0.135, 0.100))]
    for s in (-1, 1):
        hip, knee, ankle, _, _ = leg_points(s)
        ds.append(capsule(p, hip.tolist(), knee.tolist(), 0.088, 0.078))
        ds.append(capsule(p, knee.tolist(), ankle.tolist(), 0.074, 0.066))
    d = union(ds, 0.035)
    return smax(d, 0.205 - p[2], 0.004)


def slippers(p):
    ds = []
    for s in (-1, 1):
        _, _, ankle, ball, tip = leg_points(s)
        c = (ankle + ball) / 2
        sole = ellipsoid(p, (c[0], c[1] - 0.010, 0.090), (0.050, 0.140, 0.016))
        cover = ellipsoid(p, (c[0], ball[1] + 0.005, 0.110), (0.052, 0.085, 0.040))
        # 甲だけをおおう（かかとは出る）
        cover = smax(cover, p[1] - (ball[1] + 0.065), 0.01)
        ds.append(smin(sole, cover, 0.012))
    d = union(ds, 0.005)
    return smax(d, 0.074 - p[2], 0.003)


def surface_y(x, z):
    y = HC[1] - 0.25
    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.010


def eye_center(side):
    x = side * 0.039
    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.0105 / 0.0060
        ps = p.copy()
        ps[1] = (p[1] - yc) * k + yc
        pill = capsule(ps, (x, yc, z - 0.0050), (x, yc, z + 0.0050), 0.0105, 0.0105) / k
        ell = ellipsoid(p, (x, yc, z), (0.0115, 0.0060, 0.0150))
        ds.append(0.65 * pill + 0.35 * ell)
    return union(ds, 0.002)


def brow_points(side):
    xs = np.linspace(0.020, 0.060, 8)
    pts = [(side * x0, 0.0300 + 0.002 * (1 - ((x0 - 0.040) / 0.020) ** 2) - 0.004 * (x0 - 0.020) / 0.040) for x0 in xs]
    q = [(x0, surface_y(x0, HC[2] + z0) + 0.0014, HC[2] + z0) for x0, z0 in pts]
    rs = [0.0030 + 0.0006 * (1 - abs(x0 - 0.034) / 0.026) 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)


def lines(p):
    """年配らしさ：ほうれい線と目じりのしわを浅い線で（肌と同じ色で少し濃く）"""
    ds = []
    for s in (-1, 1):
        pts = []
        for t in np.linspace(0, 1, 7):
            x0 = s * (0.022 + 0.010 * t)
            z0 = HC[2] - 0.048 - 0.022 * t
            pts.append((x0, surface_y(x0, z0) + 0.0008, z0))
        for i in range(len(pts) - 1):
            ds.append(capsule(p, pts[i], pts[i + 1], 0.0011, 0.0011))
        for dz in (-0.004, 0.004):
            a0 = (s * 0.058, None, EYE_Z + dz)
            a1 = (s * 0.068, None, EYE_Z + dz * 2.2)
            q0 = (a0[0], surface_y(a0[0], a0[2]) + 0.0008, a0[2])
            q1 = (a1[0], surface_y(a1[0], a1[2]) + 0.0008, a1[2])
            ds.append(capsule(p, q0, q1, 0.0009, 0.0009))
    return union(ds, 0.001)


def glasses(p):
    """丸めがね（細い金属の縁）。つるは耳まで"""
    ds = []
    R, r = 0.0215, 0.0016
    for s in (-1, 1):
        x, yc, z = eye_center(s)
        y = yc - 0.016
        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.101, HC[1] + 0.010, HC[2] - 0.004), 0.0014, 0.0014))
        ds.append(capsule(p, (s * 0.101, HC[1] + 0.010, HC[2] - 0.004), (s * 0.098, HC[1] + 0.034, HC[2] - 0.030), 0.0014, 0.0014))
    xl, yl, zl = eye_center(1)
    xr, _, _ = eye_center(-1)
    yb = yl - 0.018
    ds.append(capsule(p, (xr + R * 0.96, yb, zl + 0.004), (0.0, yb - 0.003, zl + 0.008), 0.0014, 0.0014))
    ds.append(capsule(p, (0.0, yb - 0.003, zl + 0.008), (xl - R * 0.96, yb, zl + 0.004), 0.0014, 0.0014))
    return union(ds, 0.0008)


MOUTH_Z = HC[2] - 0.074


def mouth_line(p, half_w, curve, z0=MOUTH_Z, r=0.0018):
    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):
    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 = {   # 既定は flat（落ち着いた顔）
    "flat": lambda p: mouth_line(p, 0.014, 0.0),
    "smile": lambda p: mouth_line(p, 0.016, 0.0055),
    "worried": lambda p: mouth_line(p, 0.012, -0.004, z0=MOUTH_Z - 0.002),
    "talk": lambda p: mouth_open(p, 0.012, 0.0095),
    "surprised": lambda p: mouth_open(p, 0.0070, 0.0090, 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 = (226, 178, 142)
HAIR = (158, 156, 152)
GOWN = (150, 186, 206)
GOWN_COLLAR = (124, 162, 186)
SLIPPER = (226, 214, 192)
DARK = (44, 38, 34)
BROW = (110, 104, 98)
LIP = (150, 76, 68)
MOUTH_IN = (120, 48, 46)
FRAME = (70, 70, 74)
LINE = (206, 158, 126)

FWD = (0, -1, 0)


def bone_layout():
    """{骨の名前: (根元, 先, 親, 骨の z 軸を向ける向き)}。座った形のまま骨を置く"""
    B = {
        "Hips": (SEAT_HIP, T([0, 0.012, 0.98]), None, FWD),
        "Spine": (T([0, 0.012, 0.98]), T([0, 0.012, 1.11]), "Hips", FWD),
        "Chest": (T([0, 0.012, 1.11]), T([0, 0.012, 1.30]), "Spine", FWD),
        "Neck": (T([0, 0.012, 1.31]), np.array(H(0, 0.006, -0.10)), "Chest", FWD),
        "Head": (np.array(H(0, 0.006, -0.10)), np.array(H(0, 0.0, 0.10)), "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"] = (T([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", (0, 0, 1))
        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", (0, 0, 1))
        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(q, z0, z1):
    return np.maximum(z0 - q[2], q[2] - z1)


def regions(kind, p):
    R = {}
    q = Tinv_field(p)
    if kind == "skin":
        R["Head"] = head_solid(p)
        R["Neck"] = smin(neck_std(q), capsule(p, T([0, 0.006, 1.42]).tolist(), H(0, 0.012, -0.06), 0.041, 0.039), 0.02)
        R["Chest"] = ellipsoid(q, (0, 0.012, 1.25), (0.11, 0.072, 0.10))
        for side, L in ((1, "Left"), (-1, "Right")):
            sh, el, wr, _, _ = arm_points(side)
            R[L + "Shoulder"] = capsule(q, (side * 0.045, 0.015, 1.335), (side * 0.13, 0.015, 1.31), 0.026, 0.024)
            R[L + "UpperArm"] = capsule(p, sh.tolist(), el.tolist(), 0.043, 0.039)
            R[L + "LowerArm"] = capsule(p, el.tolist(), wr.tolist(), 0.038, 0.030)
            R[L + "Hand"] = palm(p, side)
            for k, v in finger_segs(p, side).items():
                R[L + k] = v
    elif kind == "legskin":
        for side, L in ((1, "Left"), (-1, "Right")):
            _, knee, ankle, ball, tip = leg_points(side)
            R[L + "LowerLeg"] = capsule(p, (ankle + (knee - ankle) * 0.12).tolist(), ankle.tolist(), 0.038, 0.032)
            R[L + "Foot"] = capsule(p, ankle.tolist(), ball.tolist(), 0.034, 0.030)
    elif kind == "top":
        torso = torso_std(q)
        R["Hips"] = np.maximum(torso, band(q, 0.60, 0.94))
        R["Spine"] = np.maximum(torso, band(q, 0.94, 1.10))
        R["Chest"] = np.maximum(torso, band(q, 1.10, 1.45))
        for side, L in ((1, "Left"), (-1, "Right")):
            sh, _, _, _, _ = arm_points(side)
            R[L + "Shoulder"] = capsule(p, T([side * 0.045, 0.012, 1.33]).tolist(), sh.tolist(), 0.045, 0.045)
    elif kind == "pants":
        R["Hips"] = ellipsoid(p, (0, 0.045, 0.590), (0.172, 0.135, 0.100))
        for side, L in ((1, "Left"), (-1, "Right")):
            hip, knee, ankle, _, _ = leg_points(side)
            R[L + "UpperLeg"] = capsule(p, hip.tolist(), knee.tolist(), 0.088, 0.078)
            R[L + "LowerLeg"] = capsule(p, knee.tolist(), ankle.tolist(), 0.074, 0.066)
    elif kind == "slippers":
        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)
    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("Morita_Shigeru_Rig")
    rig = bpy.data.objects.new("Morita_Shigeru", 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


bpy.ops.wm.read_factory_settings(use_empty=True)
FACE_LO = (HC[0] - 0.11, HC[1] - 0.16, HC[2] - 0.05)
FACE_HI = (HC[0] + 0.11, HC[1] - 0.04, HC[2] + 0.05)
GL_LO = (HC[0] - 0.12, HC[1] - 0.16, HC[2] - 0.05)
GL_HI = (HC[0] + 0.12, HC[1] + 0.05, HC[2] + 0.03)
MOUTH_LO = (-0.03, HC[1] - 0.14, HC[2] - 0.10)
MOUTH_HI = (0.03, HC[1] - 0.06, HC[2] - 0.05)
LINE_LO = (HC[0] - 0.08, HC[1] - 0.15, HC[2] - 0.09)
LINE_HI = (HC[0] + 0.08, HC[1] - 0.04, HC[2] + 0.01)
parts = [
    ("Skin", skin, (-0.30, -0.42, 0.62), (0.30, 0.30, HC[2] + 0.14), VOX, SKIN, 0.55, 0.12, 0.07, ("mesh", "skin")),
    ("SkinLegs", legskin, (-0.18, -0.62, 0.05), (0.18, -0.36, 0.26), VOX * 1.4, SKIN, 0.55, 0.12, 0.1, ("mesh", "legskin")),
    ("Hair", hair, (HC[0] - 0.15, HC[1] - 0.16, HC[2] - 0.10), (HC[0] + 0.15, HC[1] + 0.16, HC[2] + 0.15), VOX, HAIR, 0.55, 0, 0.06, ("whole", "Head")),
    ("Top", top, (-0.32, -0.28, 0.48), (0.32, 0.30, 1.10), VOX, GOWN, 0.85, 0, 0.03, ("mesh", "top")),
    ("Sleeves", sleeves, (-0.32, -0.12, 0.62), (0.32, 0.24, 1.08), VOX, GOWN, 0.85, 0, 0.05, ("sleeves", None)),
    ("Pants", pants, (-0.24, -0.56, 0.17), (0.24, 0.22, 0.72), VOX * 1.4, GOWN, 0.85, 0, 0.04, ("mesh", "pants")),
    ("Slippers", slippers, (-0.20, -0.66, 0.06), (0.20, -0.36, 0.17), VOX, SLIPPER, 0.7, 0, 0.06, ("mesh", "slippers")),
    ("Eyes", eyes, FACE_LO, FACE_HI, 0.0008, DARK, 0.35, 0, 0.15, ("side", "Eye_")),
    ("Brows", brows, FACE_LO, FACE_HI, 0.0008, BROW, 0.5, 0, 0.15, ("side", "Brow_")),
    ("Lines", lines, LINE_LO, LINE_HI, 0.0006, LINE, 0.6, 0, 0.3, ("whole", "Head")),
    ("Glasses", glasses, GL_LO, GL_HI, 0.0007, FRAME, 0.35, 0, 0.12, ("whole", "Head")),
]
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")))

only = [a for a in sys.argv[2:] if not a.startswith("--") and a != str(VOX)]
rig = build_armature()
tris = {}
for name, fn, lo, hi, vox, col, rough, sss, ratio, how in parts:
    if only and name not in only:
        continue
    v, f = mesh_of(fn, lo, hi, vox)
    ob = to_blender("Morita_" + 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_flat":
        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, "morita_clay.blend"))
for ob in bpy.data.objects:
    ob.hide_viewport = False
bpy.ops.export_scene.fbx(
    filepath=os.path.join(OUT, "morita_shigeru.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({"pose": "seated", "standing_height_m": 1.68, "head_center": [round(float(x), 4) for x in HC],
           "triangles": tris, "bones": list(bone_layout())},
          open(os.path.join(OUT, "morita_report.json"), "w"), ensure_ascii=False, indent=1)
print(json.dumps(tris, ensure_ascii=False))
```

### wheelchair_build.py

```python
"""病院の車いす（自走用の標準形）を作る。森田茂さん（入院中の患者）が座る。
python3 wheelchair_build.py <out_dir>
前が -y、上が z、単位は m。根（Wheelchair）は床の中心で、座っている人の根（Morita_Shigeru）と同じ位置に置けば座った形が合う。
出力：wheelchair.blend・wheelchair.fbx・wheelchair_report.json
FBX は Unity 向け（前が Unity の +Z、上が +Y）。
回る部品は根を回る中心に置いてある：
- Wheel_L / Wheel_R：後ろの大きい車輪（車軸が中心。Unity の X 軸まわりに回す）
- Caster_L / Caster_R：前の小さい車輪の向き（支柱が中心。Unity の Y 軸まわりに回す）
- CasterWheel_L / CasterWheel_R：前の小さい車輪の回転（車軸が中心。Caster の子）
"""
import json
import math
import os
import sys

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

OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)

# ---------- 寸法（m） ----------
SIDE_X = 0.225          # 横の枠の位置（座面の幅 0.42 + 枠）
SEAT_Z = 0.445          # 座面の布の上（この上にクッション 0.04）
CUSHION_TOP = 0.485     # 人が座る面
SEAT_Y0, SEAT_Y1 = -0.235, 0.205
BACK_TILT = math.radians(7)
WHEEL_R = 0.28          # 後ろの車輪（22 インチ）
AXLE = (0.150, WHEEL_R)  # (y, z)
WHEEL_X = 0.290
RIM_X = 0.318           # ハンドリム（手で回す輪）
CASTER_R = 0.075
CASTER_STEM = (-0.300, 0.255)  # 前の小さい車輪の支柱の上 (y, z)
CASTER_TRAIL = 0.035
FOOT_Z = 0.075          # 足のせ板の上
FOOT_Y0, FOOT_Y1 = -0.640, -0.420

SILVER = (196, 200, 206)
NAVY = (40, 58, 96)
CUSH = (78, 96, 128)
BLACK = (34, 34, 36)
TIRE = (52, 52, 54)


bpy.ops.wm.read_factory_settings(use_empty=True)


def mat(name, col, metal=0.0, rough=0.5):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*[(c / 255) ** 2.2 for c in col], 1)
    b.inputs["Metallic"].default_value = metal
    b.inputs["Roughness"].default_value = rough
    return m


M_SILVER = mat("WC_Frame_Mat", SILVER, 0.8, 0.35)
M_NAVY = mat("WC_Fabric_Mat", NAVY, 0.0, 0.85)
M_CUSH = mat("WC_Cushion_Mat", CUSH, 0.0, 0.9)
M_BLACK = mat("WC_Black_Mat", BLACK, 0.0, 0.6)
M_TIRE = mat("WC_Tire_Mat", TIRE, 0.0, 0.8)


def finish(ob, m, smooth=True):
    bpy.context.view_layer.objects.active = ob
    ob.select_set(True)
    if ob.type == "CURVE":
        bpy.ops.object.convert(target="MESH")
        ob = bpy.context.view_layer.objects.active
    ob.data.materials.clear()
    ob.data.materials.append(m)
    for p in ob.data.polygons:
        p.use_smooth = smooth
    ob.select_set(False)
    return ob


def tube(name, pts, r=0.011, m=M_SILVER, res=10):
    cu = bpy.data.curves.new(name, "CURVE")
    cu.dimensions = "3D"
    cu.bevel_depth = r
    cu.bevel_resolution = 2
    cu.use_fill_caps = True
    sp = cu.splines.new("POLY")
    sp.points.add(len(pts) - 1)
    for i, p in enumerate(pts):
        sp.points[i].co = (*p, 1)
    ob = bpy.data.objects.new(name, cu)
    bpy.context.scene.collection.objects.link(ob)
    return finish(ob, m)


def rounded_corner_path(pts, rad=0.04, n=5):
    """折れ線の角を丸める（パイプを曲げた形）"""
    P = [Vector(p) for p in pts]
    out = [P[0]]
    for i in range(1, len(P) - 1):
        a, b, c = P[i - 1], P[i], P[i + 1]
        u, v = (a - b).normalized(), (c - b).normalized()
        r = min(rad, (a - b).length * 0.45, (c - b).length * 0.45)
        p0, p1 = b + u * r, b + v * r
        for k in range(n + 1):
            t = k / n
            out.append((1 - t) ** 2 * p0 + 2 * (1 - t) * t * b + t * t * p1)
    out.append(P[-1])
    return [tuple(p) for p in out]


def box(name, c, size, m, bevel=0.006):
    bpy.ops.mesh.primitive_cube_add(size=1, location=c)
    ob = bpy.context.active_object
    ob.name = name
    ob.scale = size
    bpy.ops.object.transform_apply(scale=True)
    if bevel:
        md = ob.modifiers.new("b", "BEVEL")
        md.width = bevel
        md.segments = 3
        bpy.ops.object.modifier_apply(modifier="b")
    ob.select_set(False)
    return finish(ob, m)


def torus_x(name, center, R, r, m, seg=72, mseg=10):
    """x 軸に垂直な面の輪"""
    bpy.ops.mesh.primitive_torus_add(major_radius=R, minor_radius=r, major_segments=seg, minor_segments=mseg,
                                     location=center, rotation=(0, math.radians(90), 0))
    ob = bpy.context.active_object
    ob.name = name
    bpy.ops.object.transform_apply(rotation=True)
    ob.select_set(False)
    return finish(ob, m)


def cyl_x(name, center, r, depth, m, seg=32):
    bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=depth, vertices=seg, location=center,
                                        rotation=(0, math.radians(90), 0))
    ob = bpy.context.active_object
    ob.name = name
    bpy.ops.object.transform_apply(rotation=True)
    ob.select_set(False)
    return finish(ob, m)


def join(name, obs, origin):
    bpy.ops.object.select_all(action="DESELECT")
    for o in obs:
        o.select_set(True)
    bpy.context.view_layer.objects.active = obs[0]
    if len(obs) > 1:
        bpy.ops.object.join()
    ob = bpy.context.view_layer.objects.active
    ob.name = name
    ob.data.name = name
    # 根を回る中心へ
    bpy.context.scene.cursor.location = origin
    bpy.ops.object.origin_set(type="ORIGIN_CURSOR")
    ob.select_set(False)
    return ob


# ---------- 枠 ----------
frame = []
seat_rail_z = SEAT_Z - 0.012
back_top = (SEAT_Y1 + math.sin(BACK_TILT) * 0.46, 0.905)
for s in (-1, 1):
    x = s * SIDE_X
    # 座面の横の棒 → 後ろの柱 → 押す手（ハンドル）
    frame.append(tube(f"side{s}", rounded_corner_path([
        (x, SEAT_Y0, 0.250), (x, SEAT_Y0, seat_rail_z), (x, SEAT_Y1, seat_rail_z),
        (x, back_top[0], back_top[1]), (x, back_top[0] + 0.095, back_top[1] + 0.005)], 0.035)))
    # 下の棒（前の支柱の上から後ろの車軸の下へ）
    frame.append(tube(f"low{s}", rounded_corner_path([
        (x, CASTER_STEM[0], CASTER_STEM[1]), (x, SEAT_Y0, 0.250), (x, AXLE[0] + 0.02, 0.225),
        (x, SEAT_Y1 + 0.03, seat_rail_z + 0.02)], 0.03)))
    # 前の支柱の筒
    frame.append(tube(f"stem{s}", [(x, CASTER_STEM[0], CASTER_STEM[1] - 0.015), (x, CASTER_STEM[0], CASTER_STEM[1] + 0.05)], 0.016))
    frame.append(tube(f"stemarm{s}", [(x, CASTER_STEM[0], CASTER_STEM[1] + 0.03), (x, SEAT_Y0, CASTER_STEM[1] + 0.03)], 0.010))
    # ひじかけの枠
    frame.append(tube(f"arm{s}", rounded_corner_path([
        (x, -0.150, seat_rail_z), (x, -0.150, 0.672), (x, 0.170, 0.672), (x, 0.170, seat_rail_z)], 0.03)))
    # 足のせのつり下げ
    frame.append(tube(f"hang{s}", rounded_corner_path([
        (x, SEAT_Y0, seat_rail_z), (x * 0.93, FOOT_Y1 + 0.02, FOOT_Z + 0.05), (x * 0.93, FOOT_Y1 + 0.02, FOOT_Z - 0.005),
        (s * 0.045, FOOT_Y1 + 0.02, FOOT_Z - 0.005)], 0.03), 0.0105))
    # 車軸の受け
    frame.append(tube(f"axleplate{s}", [(x, AXLE[0], AXLE[1]), (s * (WHEEL_X - 0.02), AXLE[0], AXLE[1])], 0.014))
    frame.append(tube(f"axlebrace{s}", [(x, AXLE[0], AXLE[1]), (x, AXLE[0] + 0.02, 0.225)], 0.012))
    # 後ろの転倒防止のバー（足で踏む棒）
    frame.append(tube(f"tip{s}", rounded_corner_path([
        (x, AXLE[0] + 0.02, 0.225), (x, AXLE[0] + 0.20, 0.13), (x, AXLE[0] + 0.25, 0.13)], 0.03), 0.0095))
# 座面の下のバツの棒（折りたたみ）
frame.append(tube("crossA", [(-SIDE_X, -0.03, seat_rail_z), (SIDE_X, 0.08, 0.235)], 0.010))
frame.append(tube("crossB", [(SIDE_X, -0.03, seat_rail_z), (-SIDE_X, 0.08, 0.235)], 0.010))
frame_ob = join("WC_Frame", frame, (0, 0, 0))

# ---------- 黒い部品（握り・ひじかけ・足のせ・転倒防止の先） ----------
blk = []
for s in (-1, 1):
    x = s * SIDE_X
    gy0, gz = back_top[0] + 0.035, back_top[1] + 0.003
    blk.append(tube(f"grip{s}", [(x, gy0, gz), (x, gy0 + 0.075, gz + 0.004)], 0.0155, M_BLACK))
    blk.append(box(f"armpad{s}", (x, 0.005, 0.690), (0.052, 0.30, 0.036), M_BLACK, 0.012))
    blk.append(box(f"foot{s}", (s * 0.105, (FOOT_Y0 + FOOT_Y1) / 2, FOOT_Z - 0.006), (0.150, FOOT_Y1 - FOOT_Y0, 0.012), M_BLACK, 0.004))
    blk.append(tube(f"tipcap{s}", [(x, AXLE[0] + 0.235, 0.13), (x, AXLE[0] + 0.265, 0.13)], 0.013, M_BLACK))
blk_ob = join("WC_Parts", blk, (0, 0, 0))

# ---------- 布（座面・背もたれ）とクッション ----------
seat = box("seat", (0, (SEAT_Y0 + SEAT_Y1) / 2, SEAT_Z - 0.006), (2 * SIDE_X - 0.004, SEAT_Y1 - SEAT_Y0, 0.012), M_NAVY, 0.004)
seat = join("WC_Seat", [seat], (0, 0, 0))
cush = box("cushion", (0, (SEAT_Y0 + SEAT_Y1) / 2 - 0.005, (SEAT_Z + CUSHION_TOP) / 2), (2 * SIDE_X - 0.03, SEAT_Y1 - SEAT_Y0 - 0.02, CUSHION_TOP - SEAT_Z), M_CUSH, 0.016)
cush = join("WC_Cushion", [cush], (0, 0, 0))
bh = 0.36
bc = (0, SEAT_Y1 + 0.012 + math.sin(BACK_TILT) * (0.10 + bh / 2), seat_rail_z + 0.10 + bh / 2)
back = box("back", bc, (2 * SIDE_X - 0.004, 0.012, bh), M_NAVY, 0.004)
back.rotation_euler = (-BACK_TILT, 0, 0)
bpy.context.view_layer.objects.active = back
back.select_set(True)
bpy.ops.object.transform_apply(rotation=True)
back.select_set(False)
back = join("WC_Back", [back], (0, 0, 0))

# ---------- 後ろの車輪（左右）。根は車軸 ----------
wheels = {}
for s, tag in ((1, "L"), (-1, "R")):   # L＝座った人の左＝+x
    c = (s * WHEEL_X, AXLE[0], AXLE[1])
    tire = torus_x("tire", c, WHEEL_R - 0.016, 0.016, M_TIRE, 96, 12)
    rim = torus_x("rim", c, WHEEL_R - 0.033, 0.006, M_SILVER, 96, 8)
    hub = cyl_x("hub", c, 0.032, 0.05, M_SILVER)
    parts = [tire, rim, hub]
    for k in range(18):   # スポーク（左右の面から交互に）
        a = 2 * math.pi * k / 18
        off = 0.018 if k % 2 else -0.018
        p0 = (c[0] + off, c[1] + 0.03 * math.cos(a + 0.2), c[2] + 0.03 * math.sin(a + 0.2))
        p1 = (c[0], c[1] + (WHEEL_R - 0.035) * math.cos(a), c[2] + (WHEEL_R - 0.035) * math.sin(a))
        parts.append(tube("spoke", [p0, p1], 0.0016, M_SILVER))
    hr = (s * RIM_X, AXLE[0], AXLE[1])
    parts.append(torus_x("handrim", hr, WHEEL_R - 0.030, 0.0085, M_SILVER, 96, 10))
    for k in range(6):
        a = 2 * math.pi * k / 6 + 0.3
        yy, zz = (WHEEL_R - 0.033) * math.cos(a), (WHEEL_R - 0.033) * math.sin(a)
        parts.append(tube("hrlink", [(s * (WHEEL_X + 0.006), c[1] + yy, c[2] + zz), (s * (RIM_X - 0.006), c[1] + yy, c[2] + zz)], 0.0045))
    wheels[tag] = join("Wheel_" + tag, parts, c)

# ---------- 前の小さい車輪（キャスター）。向きの根は支柱、回る根は車軸 ----------
casters = {}
for s, tag in ((1, "L"), (-1, "R")):
    x = s * SIDE_X
    stem_top = (x, CASTER_STEM[0], CASTER_STEM[1])
    axle = (x, CASTER_STEM[0] + CASTER_TRAIL, CASTER_R)
    fork = [tube("forkstem", [(x, stem_top[1], stem_top[2] - 0.02), (x, stem_top[1], CASTER_R + 0.10)], 0.010)]
    for d in (-1, 1):
        fork.append(tube("fork", rounded_corner_path([
            (x, stem_top[1], CASTER_R + 0.10), (x + d * 0.024, stem_top[1], CASTER_R + 0.10),
            (x + d * 0.024, axle[1], axle[2])], 0.012), 0.006))
    fork.append(box("forktop", (x, stem_top[1] + 0.008, CASTER_R + 0.103), (0.060, 0.030, 0.012), M_SILVER, 0.003))
    casters[tag] = join("Caster_" + tag, fork, stem_top)
    w = [cyl_x("cw", axle, CASTER_R, 0.030, M_TIRE, 40), cyl_x("cwhub", axle, 0.022, 0.034, M_SILVER, 24)]
    casters["W" + tag] = join("CasterWheel_" + tag, w, axle)

# ---------- 親子と根 ----------
root = bpy.data.objects.new("Wheelchair", None)
bpy.context.scene.collection.objects.link(root)
for ob in (frame_ob, blk_ob, seat, cush, back, wheels["L"], wheels["R"], casters["L"], casters["R"]):
    ob.parent = root
for tag in ("L", "R"):
    cw = casters["W" + tag]
    mw = cw.matrix_world.copy()
    cw.parent = casters[tag]
    cw.matrix_world = mw

bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "wheelchair.blend"))
bpy.ops.export_scene.fbx(
    filepath=os.path.join(OUT, "wheelchair.fbx"), use_selection=False, object_types={"EMPTY", "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, bake_anim=False, path_mode="STRIP", embed_textures=False,
)
tris = {o.name: sum(len(p.vertices) - 2 for p in o.data.polygons) for o in bpy.data.objects if o.type == "MESH"}
tris["_total_triangles"] = sum(tris.values())
mins = Vector((9, 9, 9))
maxs = Vector((-9, -9, -9))
for o in bpy.data.objects:
    if o.type == "MESH":
        for v in o.data.vertices:
            w = o.matrix_world @ v.co
            mins = Vector(map(min, mins, w))
            maxs = Vector(map(max, maxs, w))
rep = {"triangles": tris, "size_m": {"width_x": round(maxs.x - mins.x, 3), "length_y": round(maxs.y - mins.y, 3),
       "height_z": round(maxs.z - mins.z, 3)}, "bbox_min": [round(v, 3) for v in mins], "bbox_max": [round(v, 3) for v in maxs],
       "cushion_top_z": CUSHION_TOP, "wheel_radius": WHEEL_R, "axle_yz": AXLE, "caster_radius": CASTER_R,
       "push_handle_z": round(back_top[1] + 0.005, 3)}
json.dump(rep, open(os.path.join(OUT, "wheelchair_report.json"), "w"), ensure_ascii=False, indent=1)
print(json.dumps(rep, ensure_ascii=False))
```

### morita_render.py

```python
"""森田さん（車いすに座った姿）と車いすを描く。
python3 morita_render.py <out_dir> <blend> [<blend> ...] [--views front side back persp face ...]
最初の blend を開き、残りの blend の中身を足して同じ場所に置く（車いすと人は根が同じ位置）。
"""
import os
import sys

import bpy  # noqa: I001
from mathutils import Vector

args = sys.argv[1:]
views_want = []
if "--views" in args:
    i = args.index("--views")
    views_want = args[i + 1:]
    args = args[:i]
nurse_y = None
if "--nurse-y" in args:   # 大城さん（nurse_clay.blend）を後ろに立たせて大きさを比べる
    i = args.index("--nurse-y")
    nurse_y = float(args[i + 1])
    args = args[:i] + args[i + 2:]
out, blends = args[0], args[1:]
os.makedirs(out, exist_ok=True)
bpy.ops.wm.open_mainfile(filepath=blends[0])
for b in blends[1:]:
    with bpy.data.libraries.load(b) as (src, dst):
        dst.objects = list(src.objects)
    for o in dst.objects:
        if o is not None and o.name not in bpy.context.scene.collection.objects:
            bpy.context.scene.collection.objects.link(o)
if nurse_y is not None and "Nurse_Oshiro" in bpy.data.objects:
    bpy.data.objects["Nurse_Oshiro"].location = (0, nurse_y, 0)
for o in bpy.data.objects:
    if o.type == "MESH" and o.name.startswith("Nurse_Mouth_") and o.name != "Nurse_Mouth_smile":
        o.hide_render = True
    if o.type == "MESH" and o.name.startswith("Morita_Mouth_") and o.name != "Morita_Mouth_flat":
        o.hide_render = True

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
for nm, en, sz, loc in (("K", 380, 3, (-2.2, -2.8, 3.0)), ("F", 130, 4, (2.8, -2.0, 1.4)), ("B", 90, 3, (0.5, 3.0, 2.2))):
    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, 0.7)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
    sc.collection.objects.link(o)
bpy.ops.mesh.primitive_plane_add(size=6, location=(0, 0, 0))
fl = bpy.context.active_object
m = bpy.data.materials.new("floor")
m.use_nodes = True
m.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.62, 0.70, 0.68, 1)
fl.data.materials.append(m)

C = 0.68
views = {
    "front": ((0, -6, C), (0, -0.1, C), 1.45, (720, 800)),
    "side": ((-6, -0.1, C), (0, -0.1, C), 1.45, (900, 800)),
    "back": ((0, 6, C), (0, -0.1, C), 1.45, (720, 800)),
    "persp": ((1.6, -2.4, 1.35), (0, -0.1, 0.62), None, (900, 900)),
    "persp2": ((-1.9, 1.6, 1.45), (0, -0.05, 0.62), None, (900, 900)),
    "face": ((0.30, -1.15, 1.25), (0, 0.12, 1.20), 0.36, (640, 640)),
    "upper": ((0.7, -1.9, 1.35), (0, 0.0, 0.95), None, (800, 800)),
    "shoulderL": ((0.9, -0.9, 1.25), (0.17, 0.10, 0.95), 0.45, (700, 700)),
    "shoulderR": ((-0.9, -0.9, 1.25), (-0.17, 0.10, 0.95), 0.45, (700, 700)),
    "shoulderB": ((0.6, 1.2, 1.35), (0.12, 0.12, 0.95), 0.5, (700, 700)),
    "feet": ((0.25, -1.6, 0.35), (0, -0.45, 0.20), 0.45, (700, 600)),
    "withnurse": ((-2.6, -1.6, 1.30), (0, 0.25, 0.75), None, (1000, 800)),
}
for name, (loc, tgt, ortho, res) in views.items():
    if views_want and name not in views_want:
        continue
    cam = bpy.data.cameras.new("C")
    if ortho:
        cam.type = "ORTHO"
        cam.ortho_scale = ortho
    else:
        cam.lens = 50
    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)
```

### morita_pose.py

```python
"""骨と重みを確かめる：座ったまま動く姿勢を付けて描く（服や肌が破れないかの確認用）。
python3 morita_pose.py <morita_clay.blend> <wheelchair.blend> <出力フォルダ>
姿勢：look（顔を横へ向ける）・lean（前へかがむ）・raise（右手を少し上げる）・nod（うなずく）
"""
import math
import os
import sys

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

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


def rot_world(rig, bone, axis, deg):
    pb = rig.pose.bones[bone]
    h = 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()


POSES = {
    "look": [("Neck", (0, 0, 1), 15), ("Head", (0, 0, 1), 25)],
    "lean": [("Spine", (1, 0, 0), -10), ("Chest", (1, 0, 0), -8), ("Head", (1, 0, 0), 8)],
    "raise": [("RightUpperArm", (0, 1, 0), -10), ("RightUpperArm", (1, 0, 0), -45), ("RightLowerArm", (1, 0, 0), -55)],
    "nod": [("Head", (1, 0, 0), -15)],
}
for name, steps in POSES.items():
    bpy.ops.wm.open_mainfile(filepath=src)
    with bpy.data.libraries.load(wc) as (s, d):
        d.objects = list(s.objects)
    for o in d.objects:
        bpy.context.scene.collection.objects.link(o)
    rig = bpy.data.objects["Morita_Shigeru"]
    bpy.context.view_layer.objects.active = rig
    bpy.ops.object.mode_set(mode="POSE")
    for b, ax, deg in steps:
        rot_world(rig, b, ax, deg)
    bpy.ops.object.mode_set(mode="OBJECT")
    sc = bpy.context.scene
    sc.render.engine = "CYCLES"
    sc.cycles.samples = 16
    sc.cycles.use_denoising = True
    sc.view_settings.view_transform = "Standard"
    w = bpy.data.worlds.new("W")
    sc.world = w
    w.use_nodes = True
    w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.80, 0.90, 0.89, 1)
    w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.65
    for nm, en, loc in (("K", 380, (-2.2, -2.8, 3.0)), ("F", 130, (2.8, -2.0, 1.4))):
        L = bpy.data.lights.new(nm, "AREA")
        L.energy, L.size = en, 3
        o = bpy.data.objects.new(nm, L)
        o.location = loc
        o.rotation_euler = (Vector((0, 0, 0.8)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
        sc.collection.objects.link(o)
    cam = bpy.data.cameras.new("C")
    cam.lens = 50
    co = bpy.data.objects.new("C", cam)
    co.location = (1.3, -1.9, 1.3)
    co.rotation_euler = (Vector((0, 0.0, 0.85)) - Vector(co.location)).to_track_quat("-Z", "Y").to_euler()
    sc.collection.objects.link(co)
    sc.camera = co
    for o in bpy.data.objects:
        if o.name.startswith("Morita_Mouth_") and o.name != "Morita_Mouth_flat":
            o.hide_render = True
    sc.render.resolution_x, sc.render.resolution_y = 600, 700
    sc.render.filepath = os.path.join(out, f"pose_{name}.png")
    bpy.ops.render.render(write_still=True)
    print("wrote", name)
```


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

### 依頼228 の依頼文（20261116_228_車いすに道を譲る場面を作って撮る.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 300
---
# 依頼228：⑧車いすに道を譲る を作って撮る（看護師が押す車いすに、ハコブくんが廊下で寄って止まり、先に通してから走り出す）

依頼175（③廊下ですれ違う）・218〜224（⑦話しかけられる）の依頼文と報告を読んでから始める。廊下・ハコブくん・看護師の歩き・カメラは 175 の場面、声・口・画面の帯は 219〜224 の作り方を土台にする。⑧は新しい台本 closeup228_script.json と Editor/Closeup228.cs で作る。

## エイイチと決めたこと（2026-11-15・16）
- ⑧は「車いすに道を譲る」。車いすに乗るのは**入院着の年配の患者（森田茂さん）**、押すのは**看護師の大城さん**
- 茂さんと車いすの 3D モデルは Claude が作った（GitHub `PixelstoMotors/p2m-site` の main・commit fa920a2 の `tools/sim_people/morita_shigeru/`）。**先に README.md を読む**
- 1本ずつ仕上げる。指示していない動作は足さない

## 0. モデルを入れる
- `tools/sim_people/morita_shigeru/` の `morita_shigeru.fbx` と `wheelchair.fbx` を、Assets/ServiceSim/Models/Morita/ に写す（Mac の p2m-site を pull して写す。p2m-site のほかのファイルは変えない）
- **茂さんは座った形のまま作ってある。Rig は Generic で読む**（Humanoid にして T ポーズに直すと形がくずれる）。骨はスクリプトで回す
- 車いすは、Wheel_L/R（車軸が中心）・Caster_L/R（支柱が中心）・CasterWheel_L/R（車軸が中心）を回して動かす（README の表）
- 茂さんと車いすは根を同じ位置・向きに置くと、クッションに座り足が足のせにのる。茂さんは車いすの子にして一緒に動かす
- 入れたら、茂さんと車いすを並べた静止画を 1 枚撮り、iCloud の hospital/people_3d/ の morita_wheelchair_3d_preview.png（Claude が Blender で描いた絵）と見比べて、色・形・座り方が同じかを報告に書く（違えば、何がどう違うかを書いて、そのまま続ける）

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

## 始める前に確かめること（違えば作らずに報告して終わる）
保留は Mixamo のフォルダ（Models/Animations/）だけ・Unity と回し係が動いていない・KIOXIA がマウント済み・KIOXIA に elevenlabs_api_key.txt がある（中身は表示しない・報告に書かない）・最新の check-in の番号（報告に書く）

## 1. 場所
175 の病棟の廊下（壁の間 1.8 m・手すりの間 1.68 m・長さ 14 m 以上・片側に病室の引き戸）をそのまま使う。175 の台本の rooms を写して使い、175 の出力は変えない。

幅の目安：ハコブくん 0.653 m＋車いす 0.652 m で、手すりの間 1.68 m の 8 割になる。**ハコブくんが手すりに寄って止まらないと、安全に通れない幅**であることが、この場面の見せ所。

## 2. 流れとセリフ（声は 217〜224 と同じ道具・同じ Voice ID）

| 順 | 何が起きるか | セリフ | ハコブくんの画面 |
|---|---|---|---|
| 1 | ハコブくんが薬を積んで（引き出しは閉じたまま）廊下を 0.6 m/秒で進む。左側通行 | ― | 「基本」 |
| 2 | 向こうから、大城さんが茂さんの車いすを押して来る（0.8 m/秒・左側通行）。茂さんは前を見ている | ― | 「基本」 |
| 3 | ハコブくんが車いすを見つけ（あいだが 5〜6 m の所）、減速して左の手すり側へ寄り、止まる。止まるのは、車いすの前の端（足のせ）と 2.0〜3.0 m あいている所 | ― | 「基本」→ 止まったら下の 4 |
| 4 | 止まったら、帯で知らせて声でも言う | ハコブ「お先にどうぞ」 | 帯（ミント）「お先にどうぞ」。顔は「基本」をふだんの大きさで帯の下に（219・223 の帯の出し方） |
| 5 | 大城さんがハコブくんを見て、軽く笑って言う。茂さんはハコブくんのほうへ顔を向け（20〜30°）、口を smile にして小さくうなずく（10° くらい・1 回） | 大城「ありがとう」 | 帯のまま。大城さんの「ありがとう」が終わったら、目まで笑う顔（224 と同じ）を 1.5 秒 |
| 6 | 車いすがハコブくんの横を通りすぎる。大城さんは押す速さを 0.6〜0.7 m/秒 に落として通り、通りすぎたら 0.8 m/秒 に戻す。茂さんは顔を前に戻す | ― | 「基本」（帯を消す） |
| 7 | 大城さんの体がハコブくんの後ろの端から 1.0 m 以上離れてから、ハコブくんが廊下の左寄りの通り道へ戻りながら走り出す（加速 0.5 m/秒² 以下・0.6 m/秒）。ハコブくんが画面の外へ出たら終わり | ― | 「基本」 |

- セリフの間（前の声が終わってから次の声まで）は 0.4〜0.7 秒
- 動画の長さは 25〜40 秒（全部 1 倍）

## 3. 人と車いすの動き
- **大城さんが押す**：両手を握り（WC_Parts の黒い筒。左右 0.45 m）にのせ、ひじを軽く曲げ、上体を少し前へ（5〜10°）。手は握りから離れない。歩きは 175 の手づくりの歩きを、押す速さと歩幅に合わせて使う。大城さんの足と車いすの後ろの転倒防止のバー・後ろの車輪が当たらない
- **車いす**：大城さんの手と一緒に動く。後ろの車輪は進んだ距離 ÷ 0.28 m だけ回る（すべって見えない）。前の車輪は進む向きの後ろへ付いていき、進んだ距離 ÷ 0.075 m だけ回る。車いすは床をすべらない・浮かない・沈まない
- **茂さん**：座ったまま。足は足のせから離れない。手はひざの上。動くのは 5 の顔の向き・うなずき・口だけ。まばたきは 3〜5 秒に 1 回
- **大城さんの口**：217〜224 と同じ（話す間は口を動かす）。5 の笑顔は「にっこり」の口

## 4. ハコブくんの決まり（③ と同じ考え方で、台本に値を書く）
- 前から来る車いす（または人）とのあいだが「止まるまでの距離＋余り」を切ったら、減速して左の手すり側へ寄る。すれ違うときのすき間が 0.15 m より狭くなりそうなら、止まって待つ
- 減速・加速は 0.5 m/秒² 以下でなめらかに。寄ったときの手すりとのすき間は 0.05 m 以上
- 止まっている間は動かない（0 m）
- 決まりの値と、この場面でどの線に当たって止まったかを、報告に表で書く

## 5. カメラ
- 本番：175 の廊下のカメラ（廊下の少し上・高さ 1.6〜1.8 m から斜めに見下ろす）。すれ違う所で、ハコブくんの画面と、大城さん・茂さんの顔が見える
- 寄り：4 の「お先にどうぞ」の帯（1〜2 秒）と、5 の大城さんと茂さんの顔（茂さんがうなずく所が見える向き）に切りかえる
- 1本の動画の中で切りかえる。**別に、真上から**、ハコブくんが寄って止まり、車いすが通りすぎる所の動画を 1 本撮る（すき間が分かる画）

## 6. 止める・止めないの決まり
- **必ず守る（外れたら撮らずに止める）**：当たり 0（ハコブくんと車いす・大城さん・茂さん、車いすと壁・手すり・扉、大城さんと車いす、茂さんと車いす）／大城さんの手が握りから離れない／茂さんの足が足のせから離れない・体が車いすから浮かない／止まっている間ハコブくんが動かない／走り出すのは大城さんがハコブくんの後ろの端から 1.0 m 以上離れてから／足と車輪が床をすべらない・沈まない・浮かない
- **できるだけ守る（外れても一番近い形で撮り、外れた値と理由を報告に書く）**：すれ違うときのすき間 0.15 m 以上、ハコブくんが止まる位置（2.0〜3.0 m）、減速・加速 0.5 m/秒² 以下、セリフの間、1 コマで骨が動く量 6 cm 以内、茂さんの顔の向きとうなずきの角度、目線

## 7. 撮る
- ⑧ の動画 1 本（closeup228_yield.mp4・声あり）と、真上の動画 1 本（closeup228_yield_top.mp4）
- 静止画：車いすが来る所・ハコブくんが寄って止まった所・「お先にどうぞ」（寄り）・「ありがとう」と茂さんのうなずき（寄り）・すれ違う所（本番と真上）・ハコブくんが走り出す所・茂さんと車いすを並べた静止画（0 の確かめ）
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup228/、iCloud の hospital/closeup228/ に動画と静止画を写す（md5 を確かめる）。声の mp3 は KIOXIA の出力の audio/ に置く
- check-in（Mixamo のフォルダは除く）

## 8. 報告
claude_code_reports/20261116_closeup_228.txt（KIOXIA にも写し）。セリフごとの時刻の表（動画の秒・声の長さ）、カメラの切りかえの表、ハコブくんの決まりの値と当たった線、止まった位置と手すりとのすき間、すれ違うときのすき間の最小、大城さんがハコブくんの後ろから離れた距離（走り出しの時点）、茂さんのモデルの読み方（Generic にしたか・0 の見比べの結果）、確かめの表（必ず守る・できるだけ守る）、動画の長さ、出力の場所、check-in の番号、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／一部外れて撮った／止めた」を書く。
```

### 依頼229 の依頼文（20261116_229_車いすに道を譲る場面で車いすを真ん中寄りから始める.md）

```markdown
---
作業フォルダ: /Users/shimazueiichi/Robotics_UX/ServiceSim
上限時間: 180
---
# 依頼229：⑧車いすに道を譲る（依頼228）で、車いすを通路の少し真ん中寄りから始めて撮り直す

依頼228 の報告（claude_code_reports/20261116_closeup_228.txt）を読んでから始める。228 の台本 closeup228_script.json・Editor/Closeup228.cs・Closeup228Morita.cs（cs:160）を写して closeup229_script.json・Editor/Closeup229.cs を作り、写した先で変える。**228 の台本・コード・出力には触らない。**

## エイイチの指摘（2026-11-16・228 の動画を見て）
車いすは、もう少しだけ通路の真ん中寄りで始まるほうがいい。**そこだけ直す。**

## 1. 変えること
- 車いすの始めの横の位置：x +0.42 → **x +0.28**（廊下の中心から。14 cm 真ん中へ）
- ハコブくんが減速して寄り始めたのを見て、大城さんが車いすを左（車いすの進む向きの左＝+x の手すり側）へ寄せ、x +0.42 にする。寄せ始めはハコブくんが寄り始めてから 0.5〜1.0 秒後、寄せ終わりは車いすの前の端がハコブくんの前の端と並ぶより前
- 寄せ方はなめらかに：横の速さ 0.12 m/秒まで、向きの変わり 8° まで（向きは寄せ終わりで 0° に戻す）。大城さんの体の向き・歩きは車いすと一緒に向きを変える。前の車輪は進む向きの後ろへ付いていく（228 の引っぱりの形がそのまま効くはず。向きが変わったことを報告の表に書く）
- 寄せたあとは 228 と同じ（x +0.42 で通りすぎる）

## 2. 変えないこと
ハコブくんの決まりの値・ふだんの位置・寄る所、セリフ・声・口・画面・帯、茂さんと大城さんの動き（寄せる所の体の向きのほか）、カメラの位置と切りかえの考え方、速さ（0.8 → 0.65 → 0.8 m/秒）、動画の長さの目安（25〜40 秒）。時刻はずれてよい（ずれた時刻は表に書く）。指示していない所は変えない

**触ってよいのは Assets/ServiceSim/Closeups/ の中だけ。** Models/（Morita を含む）・①〜⑧（228）の台本・コード・出力・病院の1日の場面・配膳の場面・共通の部品・Packages・実行ファイルには触らない。Mixamo の FBX は使わない・写さない・check-in しない。
**エイイチは見ていない。人に聞かないと進めない所に当たったら、その項目は止めて報告に書き、ほかは続ける。**

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

## 3. 確かめ・止める決まり
228 の「必ず守る」「できるだけ守る」と同じ。加えて：
- 寄せている間も、大城さんの手が握りから離れない・車輪が横にすべらない（前の車輪は向きを変えて付いていく）
- 寄せる前に、車いすとハコブくんが一番近づいた時のすき間（寄せなかったとしたらの予想も）を書く
- ハコブくんが「近い」の線に当たった時刻と、見つけたあいだ・止まった位置（足のせの前の端とのあいだ 2.0〜3.0 m）を 228 と並べて書く

## 4. 撮る
- ⑧ の動画 1 本（closeup229_yield.mp4・声あり）と真上の動画 1 本（closeup229_yield_top.mp4）。静止画は 228 と同じ 7 枚（s8 は不要）＋車いすを寄せている所（本番と真上）
- 出力は KIOXIA の service_sim/unity/closeup/20261116_closeup229/、iCloud の hospital/closeup229/ に動画と静止画を写す（md5 を確かめる）
- check-in（Mixamo のフォルダは除く）

## 5. 報告
claude_code_reports/20261116_closeup_229.txt（KIOXIA にも写し）。228 と同じ形の表（時刻・決まりの当たり・確かめ）を 228 と並べて書く。車いすの横の位置の動き（始め・寄せ始め・寄せ終わり・通りすぎる所）、前の車輪の向きの最大、決めてほしいこと（直し方の候補は作らない）。最後に「判定：合格／一部外れて撮った／止めた」を書く。
```


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

### 依頼228 の報告（report228.txt）

```text
依頼228：⑧ 車いすに道を譲る を作って撮る（看護師の大城さんが押す車いすに、ハコブくんが廊下で寄って止まり、先に通してから走り出す）（2026-11-16）

依頼175・217〜224 の依頼文と報告、p2m-site（fa920a2）の tools/sim_people/morita_shigeru/README.md を読んでから始めた。
廊下・ハコブくん・看護師の歩き・カメラは 175 の場面、声・口・画面の帯は 217〜224 の作り方を土台にした。
⑧ は新しい台本 closeup228_script.json と、新しいコード Editor/Closeup228.cs（217 の Closeup217.cs を写して、写した先で変えた）、Editor/Closeup228Morita.cs（茂さんと車いすの読み込み・並べた静止画）で作った。
触ったのは Assets/ServiceSim/Closeups/ の中と、新しく作った Assets/ServiceSim/Models/Morita/ だけ。①〜⑦ の台本・コード・出力、CloseupDirector.cs・CloseupNurse.cs、Models/ のほかの物、病院の1日の場面、配膳の場面、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。場面のファイル（Closeup_Handover.unity）は開いて使うだけで保存していない。
指示していない動作（おじぎ・手を振る・吹き出し・字幕・BGM）は入れていない。

結論：「必ず守る」はすべて守れた。「できるだけ守る」も、目線（大城さんの顔の向きと画面への向きのずれ 平均 8.5°）のほかは基準の中。⑧ の動画（25.667 秒・声あり）と真上の動画、静止画 8 枚を撮って、KIOXIA と iCloud に写した。

■ 始める前の確かめ（すべて合っていたので始めた）
- 保留：無し（cm status は変更なし。Mixamo のフォルダは無視の設定のまま）
- Unity と回し係：動いていない（Unity Hub と依頼箱の回し係だけ）
- KIOXIA：マウント済み
- KIOXIA に elevenlabs_api_key.txt がある（中身は見ていない。道具 tts_eleven.py が読んだ）
- 最新の check-in：cs:159（依頼224）

■ 0. モデルを入れる
- p2m-site：Mac の p2m-site（iCloud の _guide_review_20261115/p2m-site。今は guide-section の枝で作業中だった）で main を fetch し、fa920a2 が main に入っていることを確かめてから、git show で 2 つのファイルだけを取り出して写した（作業中の枝・ほかのファイルは変えていない）
  morita_shigeru.fbx md5 69c036d8d1f4eea6a4664c0e83106a2b・wheelchair.fbx md5 a162a3cf3eefd2770867f32ab2d16427（写した後も同じ）
- 読み方：茂さんは Rig＝Generic（Avatar なし）にした。Humanoid にはしていない（T ポーズに直さない）。骨（Neck・Head・Eye_L/R）は Closeup228.cs で直接回す。車いすは Rig なし
- 材質：Models/Morita/Materials/ に 21 個（茂さん 16・車いす 5）。大城さんと同じく、FBX の色（Blender の linear の値）を sRGB に直した Standard（例：肌 #C47446→#E3B38F・入院着 #4F7F9F→#97BBCF・髪 #595752→#9F9D99・車いすの布 #040A1E→#233760・枠 #8F959F→#C5C9CF）
- 置き方：車いすの FBX は根（Wheelchair）に Blender の向きを直す回転（x 270°）が入っているので、入れ物の子にして根の回転を残した。茂さんは車いすの子で、根を同じ位置・向きにした
- 口の部品は Unity では 6 つ全部が出ていたので、Morita_Mouth_flat だけを出す（README の既定）形にした
- 測った値（車いすの根から・Unity）：握りの中心 x ±0.225・高さ 0.910・後ろ 0.334 m（長さ 0.076・太さ半径 0.0155）／足のせ 高さ 0.063〜0.075・前の端 0.640 m／幅 0.653 m（後ろの車輪の外）／長さ 1.07 m／後ろの車輪の下 0.0000 m・前の車輪の下 0.0000 m
- 座った形の確かめ（はじめ）：スリッパの一番下 0.0740 m（足のせの上の面 0.075＝1.0 mm 下）・クッションの上のズボンの一番下 0.4899 m（クッション 0.485）。車いすの面から 1 mm 以内の頂点 95（スリッパ 77・足首と足 18）＝足が足のせにのっている所
- Blender の絵（hospital/people_3d/morita_wheelchair_3d_preview.png）との見比べ（stills/s8_morita_wheelchair.png に並べた）
  ・形：同じ（白髪の横分け・丸めがね・甚平型の入院着・半そで・スリッパ・車いすの枠・握り・ひじかけ・足のせ・前後の車輪・背もたれの紺の布）
  ・座り方：同じ（クッションに座り、背もたれへ少しもたれ、手はひざの上、足は足のせの上）
  ・色：違う。Unity のほうが全体に暗く、肌は桃色より茶色寄り、入院着は薄い水色より灰色がかった青、髪は銀白より濃い灰色に見える。色の値は FBX のまま（大城さんと同じ直し方）で、違いは光（Unity は病院の1日の場面と同じ光・Blender は明るい白い光と白い床）のため。直さずにそのまま続けた（決めてほしいことの 1）

■ 1. 場所
- 175 の台本の rooms（「廊下…」76 個。当たりを数える箱 63 個）をそのまま写した。壁の間 1.8 m・手すりの間 1.68 m・長さ 25 m・−x の壁に病室の引き戸 3 つ。175 の出力は変えていない
- 左側通行：ハコブくんは +z へ −x の側、車いすは −z へ +x の側
- 横の位置（廊下の中心から）：車いすの中心 x +0.42（手すりと 0.182 m）。ハコブくんのふだんの位置 x −0.33（手すりと 0.19 m）。寄った時 x −0.470（手すりと 0.053 m の決まり。止まったのは x −0.4643）
  ふだんの位置のままだと車いすとのすき間は 0.094 m（0.15 m より狭い）で、寄ると 0.234 m になる。「寄って止まらないと安全に通れない幅」になるように、この 2 つの位置を決めた（決めてほしいことの 2）

■ 2. 流れとセリフの時刻（動画の秒＝台本の秒 − 1.000）
| 順 | できごと・セリフ | 動画の秒 | 声の長さ | 前の声の終わりから |
| 1 | ハコブくん 0.6 m/秒（引き出しは閉じたまま・薬の袋は引き出しの中）。画面「基本」 | 0.000〜 | | |
| 2 | 大城さんが茂さんの車いすを押して来る 0.8 m/秒（動画の始めから） | 0.000〜 | | |
| 3 | 見つけた（足のせの前の端とのあいだ 5.995 m）／決まりに当たり減速して寄り始める（5.762 m）／寄り終わり（残り 3 cm）／止まる（2.299 m） | 9.533／9.700／11.033／12.533 | | |
| 4 | 帯（ミント）「お先にどうぞ」12.733〜。ハコブ「お先にどうぞ」 | 12.833〜13.663 | 0.830 秒 | ― |
| 5 | 大城さんがハコブくんを見る 13.613〜（笑う口 smile）。茂さんが顔を向ける 13.763〜（25°・口 smile 13.933〜）・うなずき 14.463〜（10°・1 回・0.70 秒）。大城「ありがとう」 | 14.213〜15.013 | 0.800 秒 | 0.550 秒 |
|   | 目まで笑う顔（224 と同じ face218_happy）・帯のまま | 15.013〜16.513（1.500 秒） | | |
| 6 | 帯を消して「基本」16.513。車いすが横を通る（前後が重なる 15.600〜18.867・押す速さ 0.650 m/秒）→ 0.8 m/秒へ戻す。茂さんは顔を前へ戻す（15.913〜16.513）・大城さんも前へ（15.363〜15.813） | | | |
| 7 | 大城さんの体がハコブくんの後ろの端から 1.020 m（ハコブくんが見た値）で走り出す → 左寄りの通り道（x −0.33）へ戻りながら 0.6 m/秒（24.333 に戻り終わり）→ 画面の外 | 20.467／25.633 | | |
- セリフの間：0.550 秒（0.4〜0.7 秒の中）
- 動画の長さ：25.667 秒（770 コマ・30 コマ/秒・全部 1 倍）。終わりはハコブくんが画面の外へ出た次のコマ
- 声：217〜224 と同じ道具（動画/_制作ベース/tts_eleven.py --try・モデル eleven_v4・種 7・道具の既定の設定）と同じ Voice ID（ハコブくん gWJpc8whMBqnF7Y0kc9f・大城さん PrFsT9a2iZebpuiWVeug）。2 文とも新しく作った
  読みの確かめ（217 と同じ MFCC-DTW）：「お先にどうぞ」の声と、ひらがなの「おさきにどうぞ」0.872・「おせんにどうぞ」1.434 → おさきに に近い。耳では聞いていない
  声の大きさ：1 文ずつ −20 LUFS にそろえた（−2.2 dB・−1.2 dB）。動画の音全体 −20.7 LUFS。48 kHz・AAC・2 チャンネル（同じ音）。声だけ（BGM なし）
- 口：ハコブくん（顔の板の口を hakobu.py の 4 段階で替える。開いた 12.933〜13.633＝声の始まり +0.100・終わり −0.030）。大城さん（218〜224 と同じ talk を 120/180/240%。開いた 14.267〜14.900＝+0.054・−0.113。声の区間 ±0.1 秒の外で開いたコマ 0）

■ 3. 人と車いすの動き
- 大城さん：両手を握りにのせたまま（手のひらの的は看護師の根から。車いすは看護師の根の前 0.594 m に固く付けて動かすので、握りは根から動かない）。ひじは軽く曲げ（ひじの目安 push_l/push_r）、上体を前へ 7°（spine 4°＋chest 3°）
  ・手の置き方：手のひらを握りの上に、指を外側へ向けて握りの外へ回す（指の曲げ 30°）。手の頂点と握りの面の一番近い所 +3.4 mm（筒に入らない）・手のひらの的とのずれ 0.0000 m
  ・歩き：175 の手づくりの歩き（足を床に留める IK）を、押す歩き（1 歩 0.5 秒・歩幅 0.40 m・脚の振り 11°・ひざ 24°）にして使った。速さは 0.8 → 横を通る時 0.65 → 0.8 m/秒（変える時は 0.8 秒でなめらかに）
  ・大城さんの口：歩く間は flat、ハコブくんを見る所から smile（にっこり）。決めてほしいことの 3
- 車いす：後ろの車輪は車軸が進んだ長さ ÷ 0.28 m、前の車輪は支柱に引っぱられて後ろへ付いていく形（車軸の位置を毎コマ引っぱりで出す）で向きを決め、進んだ長さ ÷ 0.075 m だけ回した。この場面はまっすぐ進むので前の車輪の向きは 0°のまま
- 茂さん：座ったまま（体は車いすの子で動かない）。手はひざの上・足は足のせの上。動かしたのは顔の向き（Neck 4 割・Head 6 割で 25°）・うなずき（10°・1 回）・口（flat → smile）・まばたき（大城さんと同じ決め方・3〜5 秒に 1 回：2.174・5.248・9.851・14.743・17.932・21.439・25.759 秒〔台本の秒〕）。smile は最後まで（決めてほしいことの 3）

■ 4. ハコブくんの決まり（台本の robot_rule。値は Closeup228.cs が読む）
| 項目 | 値 |
| ふつうの速さ | 0.6 m/秒 |
| 寄る時の速さ | 0.5 m/秒 |
| 加速・減速の上限 | 0.4 m/秒²（加加速度 1.0 m/秒³ でなめらかに） |
| 見る範囲 | 前 6.0 m 以内に来た物（車いす・茂さん・看護師の体の頂点） |
| 見てから動くまで | 0.1 秒 |
| 「近い」の線（減速して寄る・止まる） | 前の端とのあいだ ＜ 止まるまでに縮まる距離（自分の決まりで先を計算した「寄って止まる」までの自分の進む長さ＋相手の速さ×その時間）＋余り 2.4 m |
| 寄る | その時、ふだんの位置ですれ違う時のすき間の予想が 0.40 m より狭い |
| 止まって待つ | ふだんの位置ですれ違う時のすき間の予想（または寄った位置のすき間）が 0.15 m より狭い |
| 寄る所 | 左の手すり・金具・扉と 0.053 m（x −0.470） |
| 横への動き | 向きは 15°まで・向きの変わる速さ 30°/秒まで・横の速さ 0.15 m/秒まで・横の加速度 0.25 m/秒²。手すりの側の角が手すりへ振れない向きまで（寄った位置からの余り＋0.006 m ÷ 0.38 m の asin） |
| 止まり始める | 寄る所まで残り 0.03 m を切ったら（止まるまで寄り続ける） |
| 止まっている間 | 動かない・向きも変えない |
| 走り出す | 看護師の体が自分の後ろの端から 1.0 m 以上離れた。ふだんの位置へ向き 10°まで（角が手すりへ振れない向きまで）で戻る |
- この場面で当たった線
| 時刻（動画の秒） | 線 | 値 |
| 9.533 | 見る範囲 6.0 m | 前の端とのあいだ 5.995 m で見つけた |
| 9.700 | 「近い」の線 | 5.762 m ＜ 5.783 m（自分 1.089 m・2.867 秒＋相手 0.8 m/秒×2.867 秒＋余り 2.4 m） |
| 9.700 | 止まって待つ線 0.15 m | ふだんの位置のすき間の予想 0.094 m（寄った位置 0.234 m） → 「寄って止まる」 |
| 11.033 | 止まり始める線 0.03 m | 寄り終わり（残り 3 cm） |
| 12.533 | 止まった | 足のせの前の端とのあいだ 2.299 m |
| 20.467 | 走り出す線 1.0 m | 看護師の体と後ろの端 1.020 m（0.1 秒前に見た値。走り出したコマの本当の値は 1.225 m） |
- 止まった位置：x −0.4643・z 5.9094（廊下の原点から）・向き −1.83°（決めてほしいことの 4）。手すりとのすき間 0.055 m（止まっている間ずっと）・動いている間の最小 0.055 m
- すれ違う時のすき間の最小：0.224 m（動画 18.100 秒・車いすの右の後ろの車輪とハコブくん）

■ 5. カメラの切りかえ（動画の秒。位置 → 見る所は廊下の原点から）
| 動画の秒 | カメラ | 中身 |
| 0.000〜12.633 | main | 175 の本番（ハコブくんの後ろの上・高さ 1.72 m から斜めに見下ろす。(−0.62, 1.72, 0.61) → (0.12, 0.8, 7.51)・38°）。1〜3 |
| 12.633〜13.900 | screen_close | 画面の寄り 1.267 秒（217〜224 と同じ置き方）。4「お先にどうぞ」の帯と声 |
| 13.900〜15.400 | face | 大城さんと茂さんの顔（ハコブくんの前の左上から車いすのほうへ (−0.70, 1.30, 6.39) → (0.40, 1.28, 8.39)・30°）。5「ありがとう」と茂さんのうなずき |
| 15.400〜16.600 | screen_close | 目まで笑う顔（帯のまま）→ 帯を消す |
| 16.600〜21.067 | main | 6 すれ違う所（大城さん・茂さんの顔は前から見える）・7 走り出し |
| 21.067〜25.667 | depart | 走り出したハコブくんを前から ((0.62, 1.70, 8.51) → (−0.40, 0.55, 6.21)・40°)。ハコブくんが画面の外へ出たら終わり |
- 真上の動画（closeup228_yield_top.mp4）：止まる所の真上 7.6 m から 27°（画面の上が −x の壁＝ハコブくんの側）。左上にすき間・足のせまでのあいだ・ハコブくんの速さ・決まりの状態・手すりとのすき間・時刻を書いた（175 と同じ書き方）
- 本番のカメラで「ハコブくんの画面」と「大城さん・茂さんの顔」を同時に前から写すことはできない（175・218 と同じ。向き合っている）。顔は main と face、画面は screen_close で見せた（決めてほしいことの 5）

■ 6. 確かめ（台本 closeup228_script.json を Unity で全部のコマ回した出力。out/check228.txt・an228.txt・frames228.csv・wc228.csv）
必ず守る
| 項目 | 基準 | 結果 | 合否 |
| 当たったコマ：ハコブくんと車いす・大城さん・茂さん | 0 | 0（一番近い 0.224 m） | 合う |
| 当たったコマ：車いす・茂さんと壁・手すり・扉 | 0 | 0（手すりと 0.182 m・壁/扉を含め 0.146 m） | 合う |
| 当たったコマ：大城さんと車いす | 0 | 0（手を除く体の頂点が車いすの面から 3 mm 以内のコマ 0・車いすの頂点が大城さんの体の中のコマ 0・手が握りの筒に入ったコマ 0。足と転倒防止のバー・後ろの車輪：一番近い頂点どうし 0.061 m） | 合う |
| 当たったコマ：茂さんと車いす | 0 | 体は車いすに固く付いているので全部のコマで同じ。スリッパの裏が足のせの上の面に 1.0 mm 入る（作ったモデルのまま）・足首と足の 18 頂点が 1 mm 以内。座る所・背中・手は離れている | 合う（足のせにのった形。決めてほしいことの 6） |
| 当たったコマ：ハコブくん・大城さんと壁・手すり・扉 | 0 | 0・0（ハコブくん 0.055 m・大城さん 0.159 m） | 合う |
| 大城さんの手が握りから離れない | 離れない | 手のひらの的とのずれ 0.0000 m・手のひらの中心と握りの面 0.0212 m で全部のコマ同じ | 合う |
| 茂さんの足が足のせから離れない・体が浮かない | 離れない | 全部のコマで同じ（スリッパの一番下 0.0740・ズボンの一番下 0.4899） | 合う |
| 止まっている間ハコブくんが動かない | 0 m | 0.0000 m・向きも同じ（238 コマ） | 合う |
| 走り出すのは大城さんが後ろの端から 1.0 m 以上離れてから | 1.0 m 以上 | 1.020 m（見た値）・1.225 m（そのコマ） | 合う |
| 大城さんの足が床をすべらない・沈まない・浮かない | 0 cm | すべり 0.00・沈み 0.00・両足とも浮いた 0.00 cm（歩く所 794 コマ） | 合う |
| 車輪が床をすべらない・沈まない・浮かない | 0 | 後ろの車輪：回る角度＝進んだ長さ÷0.28（横すべり 0.00000 m）・車輪の下 0.00000〜0.00015 m／前の車輪：横すべり 0.00000 m・下 0.00000〜0.00023 m（回した形の頂点の丸めの差）・車いすの根の高さのずれ 0.00000 m | 合う |
できるだけ守る
| 項目 | 基準 | 結果 | 合否 |
| すれ違うときのすき間 | 0.15 m 以上 | 0.224 m | 合う |
| ハコブくんが止まる位置 | 足のせと 2.0〜3.0 m | 2.299 m | 合う |
| 減速・加速 | 0.5 m/秒² 以下 | 減速 0.400・加速 0.400（速さの差から 0.402） | 合う |
| セリフの間 | 0.4〜0.7 秒 | 0.550 秒 | 合う |
| 1 コマで骨が動く量 | 6 cm 以内 | 大城さん（根の動きを除く）3.87 cm・茂さん（車いすから）0.52 cm／世界で数えると大城さん 6.29 cm（右のつま先・歩き。参考） | 合う |
| 茂さんの顔の向き・うなずき | 20〜30°・10° くらい 1 回 | 25.0°・10.0° 1 回 | 合う |
| 目線（茂さん） | ハコブくんのほうへ | 25° を向いている間の顔の向きと画面への向き 最小 6.4°（車いすが進むと横になり 34.6° まで開く） | 合う |
| 目線（大城さん） | ハコブくんを見る | 見る間（動画 13.963〜15.363）の顔の向きと画面への向き 平均 8.47°・最大 9.16°（頭の横向き最大 34.1°） | ほぼ合う（直しの回は回していない） |
| 帯の寄り | 1〜2 秒 | 1.267 秒 | 合う |
| 動画の長さ | 25〜40 秒 | 25.667 秒 | 合う |

■ 7. 撮ったもの（1920×1080・30 コマ/秒・1 倍）
- closeup228_yield.mp4：⑧ 本番（寄りの切りかえ入り・声あり）25.667 秒・770 コマ（md5 fca1fa554433f535837d858034375e5b・3,022,053 バイト）
- closeup228_yield_top.mp4：真上（音なし）25.667 秒・770 コマ（md5 ff5cd0e3553166fb9912bd0c6ff2a611・1,487,734 バイト）
- 静止画 8 枚（stills/。動画の秒）：s1_coming_main（車いすが来る所 9.833）・s2_stopped_main（寄って止まった所 12.633）・s3_osakini_close（「お先にどうぞ」寄り 13.233）・s4_arigatou_nod_face（「ありがとう」と茂さんのうなずき 14.800）・s5_pass_main・s6_pass_top（すれ違う所 本番と真上 17.133）・s7_depart（走り出す所 21.667）・s8_morita_wheelchair（茂さんと車いすを並べた静止画と Blender の絵）
- 確かめの静止画（stills_check/）：真上（止まった所・走り出し）・目まで笑う顔・握り（3 方向）・車いすの横・茂さんの見本 6 方向（morita_*.png）

■ 出力の場所（写した後に md5 を確かめた。KIOXIA 32 ファイル・iCloud 10 ファイル、すべて同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup228/
  closeup228_yield.mp4・closeup228_yield_top.mp4・closeup228_script.json（md5 6141e40131340ba42ef9603e3c8dcba1）・stills/（8 枚）・stills_check/
  audio/：L4_hakobu.mp3・L5_oshiro.mp3（声の mp3）と 48 kHz の wav・mix228.wav（台本の秒の音。動画には 1.000 秒から使った）・lufs.txt・reading_check/（読みの確かめの声 2 つ）
  out/：check228.txt・events228.txt・an228.txt（報告の表）・frames228.csv・bones228.csv・feet228.csv・wc228.csv（車輪）・morita228.txt（読み込みの記録）・times.json・final_info.json・unity.log
  tools/：make_script228.py（175 の台本と声と times.json から台本を作る）・screen228.py（帯の絵。同じ描き方で「お届け完了」を描くと c223_done_band.png と画素まで同じ）・run228.sh・make228.py（動画）・an228.py・sim_try*.py / sim_lat.py（寄り方の試算）・Closeup228.cs と Closeup228Morita.cs の写し
  report228.txt（この報告の写し）
  （試しの走り〔握り方 A〜I・1 回めの走り〕は /tmp/c228 にあり、KIOXIA には写していない。直した順：1 回め 走り出しで向きが 0°→10° に跳び手すりと 0.019 m → 向きの変わる速さと角の線を足した／2 回め 寄り終わりが遅く足のせと 0.475 m → 残り 3 cm で止まり始める形に／指が握りの筒に 1.4 cm 入る → 手を 5 cm 後ろ・指を外へ・手のひらを 1.8 cm 上に）
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup228/（closeup228_yield.mp4・closeup228_yield_top.mp4・stills/ 8 枚）

■ check-in
- cs:160（58 件：Models/Morita/（morita_shigeru.fbx・wheelchair.fbx・Materials/ 21 個と .meta）・Closeups/closeup228_script.json・Editor/Closeup228.cs・Editor/Closeup228Morita.cs・Textures/c228_yield_band.png（と .meta）を追加）
- 保留は無し（Mixamo のフォルダは無視の設定のまま）

■ 決めてほしいこと
1. 茂さんと車いすの色が Blender の絵より暗く見える（形と座り方は同じ）。FBX の色を大城さんと同じ直し方で使い、光は病院の1日の場面のまま。このままでよいか
2. ハコブくんのふだんの横の位置 x −0.33（手すりと 0.19 m）と、車いすの通る位置 x +0.42 は今回決めた値（175 は −0.451、218〜224 は −0.270）。ふだんの位置のままだと車いすとのすき間 0.094 m、寄ると 0.234 m。この位置でよいか
3. 口：大城さんは 175〜224 では歩く間も smile だったが、5 の「軽く笑って」が見えるように歩く間は flat、ハコブくんを見る所から smile にした。茂さんも flat → smile。2 人とも smile は最後まで（戻していない）。この形でよいか
4. ハコブくんは向き −1.83°（壁のほうへ）のまま止まっている（止まり始めから止まるまで寄り続けるため。止まっている間は向きを変えない決まり）。このままでよいか
5. 本番のカメラ（175 と同じハコブくんの後ろの上）では、ハコブくんの画面は後ろ向きで見えない。画面は寄り（screen_close）で見せた。この形でよいか
6. 茂さんのスリッパの裏が足のせの上の面に 1.0 mm 入っている（作ったモデルのまま）。足のせにのっている形として「当たり」に数えなかった。この数え方でよいか
7. 「見つける 5〜6 m」：決まりの線（止まるまでに縮まる 3.38 m＋余り 2.4 m＝5.78 m）が見る範囲 6.0 m のすぐ内側なので、見つけて 0.167 秒後に寄り始めている。見つける所と寄り始める所を分けて見せるなら、どちらかの値を変えることになる。このままでよいか
8. 大城さんの目線のずれ（平均 8.5°）は直していない（217 の look の直しの回は回していない）。直すか

判定：合格
```

### 依頼229 の報告（report229.txt）

```text
依頼229：⑧ 車いすに道を譲る（依頼228）で、車いすを通路の少し真ん中寄り（x +0.28）から始め、大城さんが x +0.42 へ寄せてから通りすぎる形で撮り直した（2026-11-16）

依頼228 の報告を読んでから始めた。228 の台本を作る道具 make_script228.py が 228 の台本と md5 まで同じ物を作れることを確かめてから（DEP_DZ=2.6 で 6141e401…）、写して make_script229.py にし、写した先で車いすの道だけを変えた。
コードは Closeup228.cs を写して Editor/Closeup229.cs にした。Closeup228Morita.cs は写さず、置く所（Spawn）だけ使う。228 の読み込み（Import）は Models/ へ書くので呼ばず、設定が 228 のままかを確かめるだけにした（違えば止める作り。今回は合っていた）。
触ったのは Assets/ServiceSim/Closeups/ の中の新しい 4 ファイルだけ。228 の台本・コード・出力、Models/（Morita を含む）、①〜⑦、病院の1日の場面、配膳の場面、共通の部品、Packages、実行ファイルには触っていない。Mixamo の FBX は使っていない・写していない・check-in していない。場面のファイルは保存していない。

結論：「必ず守る」はすべて守れた。「できるだけ守る」も 228 と同じ（目線のずれ 平均 8.47°のほかは基準の中）。寄せている間も手は握りから離れず、車輪は横にすべっていない。寄せなかったとしたらすれ違いのすき間は 0.084 m（0.15 m より狭い）だったところが、寄せて 0.224 m（228 と同じ）。

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

■ 1. 変えたこと：車いすの道
- 車いすは 228 と同じく大城さんの根の前 0.594 m に固く付いて動く。229 では「後ろの車軸の真ん中（車いすの根の後ろ 0.15 m）」の道を決め、車いすの向きはその道の向き、大城さんの根と体の向きは車いすから出した（大城さんは車いすと一緒に向きを変える。歩きの足の着く所も根の向きで決まるので一緒に向きを変える）
- 車軸は向いた方へだけ進む（横にすべらない形）。道に沿って進む長さは 228 の速さのまま（0.8 → 0.65 → 0.8 m/秒）
- 寄せ方：寄せ始めから前へ 2.8 m 進むあいだに、x を 0.28 → 0.42 へ 5 次のなめらかな形（向きの変わる速さも 0 から始まり 0 で終わる）で動かす。向きは寄せ終わりで 0°
- 寄せ始め：ハコブくんが減速して寄り始めた（決まりに当たった）時刻の 0.6 秒後（0.5〜1.0 秒の中）
- 前の車輪：228 の引っぱりの形のまま。向きを変えて後ろへ付いていった（下の表）

■ 2. 車いすの横の位置の動き（車いすの根の x・廊下の中心から。動画の秒＝台本の秒 − 1.000）
| 所 | 動画の秒 | x | 向き |
| 始め | 0.000 | +0.2800 | 0° |
| ハコブくんが減速して寄り始めた | 9.700 | +0.2800 | 0° |
| 寄せ始め（その 0.600 秒後） | 10.300 | +0.2800 | 0° |
| 向きの最大 | 12.067 | （途中） | 5.355°（+x の手すり側へ） |
| main から画面の寄りへ切りかわる所 | 12.633 | +0.4014 | 4.255° |
| 寄せ終わり | 13.833 | +0.4200 | 0° |
| 車いすの前の端がハコブくんの前の端と並んだ | 15.600 | +0.4200 | 0°（寄せ終わりの 1.767 秒後） |
| 通りすぎる所（前後が重なる間 15.600〜18.867） | | +0.4200〜+0.4200 | 0° |
| 終わり | 25.667 | +0.4200 | 0° |
- 寄せる間の値（決まり：横の速さ 0.12 m/秒まで・向き 8°まで）
  向きの最大 5.355°・向きの変わる速さの最大 4.71°/秒・横の速さの最大：車軸 0.075・車いすの根 0.077（Unity で測った値 0.0766）・足のせの前の端 0.109（Unity 0.1094）・大城さんの根 0.088 m/秒
  （寄せる長さを 2.4 m にすると足のせの前の端の横の速さが 0.138 m/秒になり 0.12 を超えるので、2.8 m にした）
- 前の車輪の向きの最大：2.41°（動画 11.133 秒。228 はまっすぐなので 0°）。前の車輪の横すべり 0.00000 m/コマ

■ 3. ハコブくんの決まりの当たり（228 と並べて。動画の秒）
| できごと | 228 | 229 |
| 見つけた（前の端とのあいだ） | 9.533（5.995 m） | 9.533（5.995 m） |
| 「近い」の線に当たった | 9.700：5.762 m ＜ 5.783 m | 9.700：5.762 m ＜ 5.783 m（同じ） |
| その時のすき間の予想（ふだんの位置／寄った位置） | 0.094／0.234 m | −0.046／0.094 m（車いすが x +0.28 にいるため。どちらも 0.15 m より狭いので「寄って止まる」で 228 と同じ） |
| 寄り終わり（残り 3 cm） | 11.033 | 11.033 |
| 止まった（足のせの前の端とのあいだ） | 12.533（2.299 m） | 12.533（2.297 m。2.0〜3.0 m の中） |
| 止まった位置 | x −0.4643・z 5.9094・向き −1.83° | 同じ |
| 走り出し（看護師の体と後ろの端：見た値／そのコマ） | 20.467（1.020／1.225 m） | 20.467（1.015／1.220 m） |
| 画面の外へ出た・動画の長さ | 25.633・25.667 秒 | 25.633・25.667 秒 |
- ハコブくんの決まりの値・ふだんの位置（x −0.33）・寄る所（手すりと 0.053 m）は変えていない。ハコブくんは止まる決まりに入った後は車いすの動きで決まりを変えないので、寄せても動きは 228 と同じ
- 止まった時の足のせとのあいだが 2 mm 違うのは、車いすの道が少し曲がった分（同じ時刻で前へ進んだ長さがわずかに短い）

■ 4. すき間（寄せる前・寄せなかったとしたら）
| | 寄せた（229） | 寄せなかったとしたら（x +0.28 のまま。同じ台本で寄せる所だけ消して回した） |
| 寄せ始める前の一番近いすき間 | 1.5 m より遠い（寄せ始める時はまだ離れている） | ― |
| 前の端が並んだ時のすき間 | 0.396 m | 0.258 m |
| すれ違う時のすき間の最小 | 0.224 m（動画 17.500 秒・車いすの右の後ろの車輪） | 0.084 m（動画 18.100 秒・同じ所。0.15 m より狭い） |
| 車いす/茂さんと手すり | 0.179 m | 0.329 m |
- 228 のすれ違いのすき間の最小は 0.224 m。229 も同じ

■ 5. 流れとセリフ（228 と同じ。時刻もずれていない）
| 順 | できごと | 228 | 229 |
| 帯「お先にどうぞ」 | | 12.733〜16.513 | 同じ |
| ハコブ「お先にどうぞ」 | | 12.833〜13.663 | 同じ |
| 大城「ありがとう」（間 0.550 秒） | | 14.213〜15.013 | 同じ |
| 目まで笑う顔 | | 15.013〜16.513 | 同じ |
| 茂さん顔を向ける・うなずき | | 13.763〜・14.463〜 | 同じ（25.0°・10.0°） |
| 横を通る（押す速さ 0.650〜0.651） | | 15.600〜18.867 | 同じ |
- 声：228 の声の wav をそのまま使った（新しく作っていない）。動画の音は 228 の mix228.wav と md5 まで同じ（aaf24eb5…）
- 口：ハコブ 12.933〜13.633（+0.100・−0.030）・大城 14.267〜14.900（+0.054・−0.113）・声の外で開いたコマ 0（228 と同じ）
- カメラの切りかえ：228 と同じ（0〜12.633 main／〜13.900 screen_close／〜15.400 face／〜16.600 screen_close／〜21.067 main／〜25.667 depart）。
  寄せるのは 10.300〜13.833 で、main で見えるのは 12.633 まで（x +0.4014 まで。残りの 1.9 cm は画面の寄りの間）

■ 6. 確かめ（228 と並べて。台本 closeup229_script.json を Unity で全部のコマ回した出力）
必ず守る
| 項目 | 基準 | 228 | 229 | 合否 |
| 当たったコマ：ハコブくんと車いす・大城さん・茂さん | 0 | 0（0.224 m） | 0（0.224 m） | 合う |
| 当たったコマ：車いす・茂さんと壁・手すり・扉 | 0 | 0（手すり 0.182・壁/扉 0.146 m） | 0（手すり 0.179・壁/扉 0.145 m） | 合う |
| 当たったコマ：大城さんと車いす | 0 | 0（足と車いす 0.061 m） | 0（0.057 m・動画 10.600） | 合う |
| 当たったコマ：茂さんと車いす | 0 | 足のせに 1.0 mm（モデルのまま） | 同じ | 合う（228 と同じ数え方） |
| 当たったコマ：ハコブくん・大城さんと壁・手すり・扉 | 0 | 0・0（0.055・0.159 m） | 0・0（0.055・0.159 m） | 合う |
| 大城さんの手が握りから離れない | 離れない | ずれ 0.0000・握りの面 0.0212 m | 全体も寄せる間も ずれ 0.0000・握りの面 0.0212 m（全部のコマ同じ）・手の頂点と握りの面 +3.4 mm | 合う |
| 茂さんの足が足のせから離れない・体が浮かない | 離れない | 同じ形 | 同じ形（スリッパ 0.0740・ズボン 0.4899） | 合う |
| 止まっている間ハコブくんが動かない | 0 m | 0.0000（238 コマ） | 0.0000（238 コマ） | 合う |
| 走り出しは大城さんが後ろの端から 1.0 m 以上 | 1.0 m 以上 | 1.020／1.225 m | 1.015／1.220 m | 合う |
| 大城さんの足がすべらない・沈まない・浮かない | 0 cm | 0.00・0.00・0.00 | 0.00・0.00・0.00（寄せる間のすべり 0.00 cm） | 合う |
| 車輪がすべらない・沈まない・浮かない | 0 | 横すべり 0.00000・下 0〜0.00015／0〜0.00023 m | 後ろの車輪の横すべり 0.00001 m/コマ（0.01 mm。向きが変わるのでコマの前後の向きの間の横で数えた。数え方による丸めの差）・前の車輪 0.00000・下 0〜0.00015／0〜0.00023 m・根の高さ 0.00000 | 合う |
| 寄せている間、車輪が横にすべらない（前の車輪は向きを変えて付いていく） | | ― | 前の車輪 最大 2.41°向きを変えて付いていった・横すべり 0.00000 | 合う |
できるだけ守る
| 項目 | 基準 | 228 | 229 | 合否 |
| すれ違うときのすき間 | 0.15 m 以上 | 0.224 | 0.224 | 合う |
| 止まる位置 | 足のせと 2.0〜3.0 m | 2.299 | 2.297 | 合う |
| 減速・加速 | 0.5 m/秒² 以下 | 0.400 | 0.400 | 合う |
| セリフの間 | 0.4〜0.7 秒 | 0.550 | 0.550 | 合う |
| 1 コマで骨が動く量 | 6 cm 以内 | 3.87（世界 6.29） | 3.87（世界 6.35・参考） | 合う |
| 茂さんの顔の向き・うなずき | 20〜30°・10° 1 回 | 25.0・10.0 | 25.0・10.0 | 合う |
| 目線（茂さん） | | 最小 6.4° | 最小 6.3° | 合う |
| 目線（大城さん） | | 平均 8.47°・最大 9.16° | 平均 8.47°・最大 9.16° | ほぼ合う（228 と同じ） |
| 帯の寄り | 1〜2 秒 | 1.267 | 1.267 | 合う |
| 動画の長さ | 25〜40 秒 | 25.667 | 25.667 | 合う |
| 寄せる横の速さ・向き | 0.12 m/秒・8°まで | ― | 根 0.077・足のせの前の端 0.109 m/秒・5.355° | 合う |
| 寄せ始め | 寄り始めの 0.5〜1.0 秒後 | ― | 0.600 秒後 | 合う |
| 寄せ終わり | 前の端が並ぶより前 | ― | 1.767 秒前 | 合う |

■ 7. 撮ったもの（1920×1080・30 コマ/秒・1 倍）
- closeup229_yield.mp4：⑧ 本番（声あり）25.667 秒・770 コマ（md5 e3fdd01bcfa0fc4c6cf698d848dd12ab・3,007,642 バイト）
- closeup229_yield_top.mp4：真上（音なし。228 と同じ書き方）25.667 秒・770 コマ（md5 457703bc4f59f7600c2d77729e793195・1,531,282 バイト）
- 静止画 9 枚（stills/）：s1_coming_main・s2_stopped_main・s3_osakini_close・s4_arigatou_nod_face・s5_pass_main・s6_pass_top・s7_depart（228 と同じ時刻）、
  s8_shift_main（寄せている所・本番のカメラ・動画 12.067 秒）・s8_shift_top（寄せている所の真上・同じ時刻）
  真上の静止画は、真上の動画のカメラ（止まる所の上）では車いすが画面の右の端に足のせしか写らないので、同じ高さ 7.6 m・同じ角度 27° のまま、車いすとハコブくんの間の上（z 7.41）へずらしたカメラ top_shift で撮った（決めてほしいことの 2）
- 確かめの静止画（stills_check/）：228 と同じ 9 枚＋寄せている所の握り（chk_grip_shift・大城さんの根と向きに付いて回るカメラ）・車いすの横（chk_wc_shift）

■ 出力の場所（写した後に md5 を確かめた。34 ファイルすべて同じ）
- KIOXIA：/Volumes/KIOXIA/r2r2r-data/service_sim/unity/closeup/20261116_closeup229/
  closeup229_yield.mp4・closeup229_yield_top.mp4・closeup229_script.json（md5 66fa32da74ef07b77521d870fe1222b6）・stills/（9 枚）・stills_check/（11 枚）
  out/：check229.txt・events229.txt・an229.txt・frames229.csv（車いすの x・向き、大城さんの x・向きの列を足した）・bones229.csv・feet229.csv・wc229.csv・unity.log・times.json・final_info.json
  noshift/：寄せなかったとしたらの走り（台本と check・events）
  audio/mix229.wav・tools/（make_script229.py・make229.py・an229.py・run229.sh・Closeup229.cs の写し）・report229.txt（この報告の写し）
- iCloud：…/サービスロボット導入シミュレーション/hospital/closeup229/（動画 2 本・stills/ 9 枚）
- 試しの走り（1 回め・寄せる長さ 2.4 m の試算）は /tmp/c229 にあり、KIOXIA には写していない

■ check-in
- cs:161（4 件：Closeups/closeup229_script.json と .meta・Closeups/Editor/Closeup229.cs と .meta を追加）。保留は無し（Mixamo のフォルダは無視の設定のまま）

■ 決めてほしいこと
1. 寄せ方の値は、依頼の範囲の中でこちらで決めた（寄せ始め＝寄り始めの 0.6 秒後・前へ 2.8 m 進むあいだに 5 次のなめらかな形・向き最大 5.4°）。横の速さは「足のせの前の端」でも 0.12 m/秒を超えないように長さを決めた（車いすの根だけで数えるなら 2.4 m〔向き 6.2°〕でも入る）。この決め方と値でよいか
2. 寄せている所の真上の静止画は、真上の動画のカメラでは車いすが写らないので、同じ高さ・角度で横へずらしたカメラで撮った（動画のカメラは 228 のまま）。これでよいか
3. 寄せるのは動画 10.300〜13.833 秒で、本番のカメラ（main）で見えるのは 12.633 秒まで（x +0.401 まで）。寄せ終わりは画面の寄り（screen_close）の間になる。カメラの切りかえは変えていない。このままでよいか
4. ハコブくんが決まりに当たった時、車いすは x +0.28 にいるので「ふだんの位置のすき間の予想」は −0.046 m（228 は 0.094 m）。決まりは 228 と同じく「寄って止まる」になり、動きは 228 と同じ。止まった後、ハコブくんは車いすが寄せたことを決まりに使わない（228 の決まりのまま）。このままでよいか
5. 228 の決めてほしいこと 1〜8 は答えを受けていないので、228 のまま（色・ハコブくんの位置・口・止まる向き・画面の見せ方・足のせの 1 mm・見つける所・大城さんの目線）

判定：合格
```


## 作業ログ ― Unity の場面のコード（Claude Code が書いた版）

KIOXIA の `service_sim/unity/closeup/20261116_closeup228/tools/` と `20261116_closeup229/tools/` に置いた写しです。Unity では `Assets/ServiceSim/Closeups/Editor/` にあります（cs:160・cs:161）。

### Closeup228Morita.cs（茂さんと車いすの読み込み・並べた静止画）

```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>
    /// 依頼228：森田茂さん（Models/Morita/morita_shigeru.fbx）と車いす（wheelchair.fbx）を読む・置く・動かす。
    ///   ・茂さんは座った形のまま作ってあるので Rig は Generic（Avatar なし）。骨はスクリプトで回す
    ///   ・材質は Models/Morita/Materials/ に作り、FBX の色（Blender の linear の値）を sRGB に直す（大城さんと同じ。CloseupImport.ImportNurse）
    ///   ・茂さんは車いすの子にして、根を同じ位置・向きに置く
    /// コマンド（読み込みと並べた静止画）
    ///   Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup228Morita.Run -c228Out <出力フォルダ>
    /// </summary>
    public static class Closeup228Morita
    {
        public const string Dir = "Assets/ServiceSim/Models/Morita";
        public const string MoritaFbx = Dir + "/morita_shigeru.fbx";
        public const string ChairFbx = Dir + "/wheelchair.fbx";
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string V(Vector3 v) { return string.Format(IC, "({0:0.0000},{1:0.0000},{2:0.0000})", v.x, v.y, v.z); }
        static string Hex(Color c) { return "#" + ColorUtility.ToHtmlStringRGB(c); }

        /// <summary>読み込みの設定（設定が違う時だけ読み直す）</summary>
        public static void Import(StringBuilder sb)
        {
            if (!AssetDatabase.IsValidFolder(Dir + "/Materials")) AssetDatabase.CreateFolder(Dir, "Materials");
            foreach (var p in new[] { MoritaFbx, ChairFbx })
            {
                var mi = (ModelImporter)AssetImporter.GetAtPath(p);
                if (mi == null) throw new Exception("FBX が無い: " + p);
                bool morita = p == MoritaFbx;
                var at = morita ? ModelImporterAnimationType.Generic : ModelImporterAnimationType.None;
                bool changed = mi.animationType != at || !mi.isReadable || mi.importAnimation || mi.materialImportMode != ModelImporterMaterialImportMode.ImportStandard
                               || (morita && mi.avatarSetup != ModelImporterAvatarSetup.NoAvatar);
                if (changed)
                {
                    mi.animationType = at;
                    if (morita) mi.avatarSetup = ModelImporterAvatarSetup.NoAvatar;
                    mi.isReadable = true;            // 当たりの確かめに頂点を読む
                    mi.importAnimation = false;
                    mi.materialImportMode = ModelImporterMaterialImportMode.ImportStandard;
                    mi.SaveAndReimport();
                }
                sb.AppendLine(Path.GetFileName(p) + "：Rig " + mi.animationType + (morita ? "（Avatar " + mi.avatarSetup + "）" : "") + "・読み直し " + (changed ? "した" : "しない"));
                // 材質：FBX の色（linear）→ sRGB の Standard
                var shader = Shader.Find("Standard");
                bool remapped = false;
                foreach (var o in AssetDatabase.LoadAllAssetsAtPath(p))
                {
                    var fm = o as Material;
                    if (fm == null) continue;
                    string mp = Dir + "/Materials/" + 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;
                    float metal = fm.HasProperty("_Metallic") ? fm.GetFloat("_Metallic") : 0f;
                    nm.SetFloat("_Metallic", metal);
                    nm.SetFloat("_Glossiness", fm.name.Contains("Eyes") || fm.name.Contains("Mouth") || fm.name.Contains("Glasses") ? 0.4f : metal > 0.3f ? 0.6f : 0.2f);
                    EditorUtility.SetDirty(nm);
                    var id = new AssetImporter.SourceAssetIdentifier(typeof(Material), fm.name);
                    mi.AddRemap(id, nm); remapped = true;
                    sb.AppendLine("  材質 " + fm.name + " " + Hex(lin) + " → " + Hex(nm.color) + "・金属 " + metal.ToString("0.00", IC));
                }
                if (remapped) { mi.SaveAndReimport(); }
            }
            AssetDatabase.SaveAssets();
        }

        /// <summary>FBX を置く（プレハブをほどき、Animator は外す）。FBX の根の回転（Blender の向きを直す回転）を残すため、入れ物（name）の子にする</summary>
        public static GameObject Spawn(string fbx, string name)
        {
            var src = AssetDatabase.LoadAssetAtPath<GameObject>(fbx);
            var go = (GameObject)PrefabUtility.InstantiatePrefab(src);
            PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
            var an = go.GetComponent<Animator>(); if (an != null) UnityEngine.Object.DestroyImmediate(an);
            foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true)) smr.updateWhenOffscreen = true;
            var holder = new GameObject(name);
            Vector3 lp = go.transform.localPosition; Quaternion lr = go.transform.localRotation; Vector3 ls = go.transform.localScale;
            go.transform.SetParent(holder.transform, false);
            go.transform.localPosition = lp; go.transform.localRotation = lr; go.transform.localScale = ls;
            return holder;
        }

        public static Transform Find(Transform t, string name) { return CloseupNurse.Find(t, name); }

        // ---------------------------------------------------------------- 並べた静止画（0 の確かめ）
        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c228Out", "");
            if (outDir == "") throw new Exception("-c228Out がない");
            Directory.CreateDirectory(outDir);
            var sb = new StringBuilder();
            try
            {
                Import(sb);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                var dir = UnityEngine.Object.FindObjectOfType<CloseupDirector>();
                Vector3 O = new Vector3(80f, 0f, 0f);       // ①〜⑦ の部屋・廊下から離れた所
                var chair = Spawn(ChairFbx, "Wheelchair228");
                var mor = Spawn(MoritaFbx, "Morita228");
                chair.transform.SetPositionAndRotation(O, Quaternion.identity);
                mor.transform.SetParent(chair.transform, false);
                mor.transform.localPosition = Vector3.zero; mor.transform.localRotation = Quaternion.identity;
                foreach (var r in mor.GetComponentsInChildren<Renderer>(true)) if (r.name.StartsWith("Morita_Mouth_")) r.gameObject.SetActive(r.name == "Morita_Mouth_flat");   // 口は既定の flat だけ
                // 中身の一覧
                foreach (var go in new[] { chair, mor })
                {
                    sb.AppendLine("== " + go.name);
                    foreach (Transform c in go.GetComponentsInChildren<Transform>(true))
                    {
                        var r = c.GetComponent<Renderer>();
                        if (r == null && c.childCount == 0 && go == mor) continue;
                        string info = r != null ? " 描く 表示=" + c.gameObject.activeSelf + " 範囲 " + V(r.bounds.min - O) + "〜" + V(r.bounds.max - O) + " 材質 " + r.sharedMaterial.name : "";
                        if (go == chair || r != null) sb.AppendLine("  " + c.name + " 根から " + V(c.position - O) + " 回転 " + V(c.localEulerAngles) + " 右 " + V(c.right) + " 上 " + V(c.up) + info);
                    }
                }
                var bones = new List<string>();
                foreach (Transform c in mor.GetComponentsInChildren<Transform>(true)) if (c.GetComponent<Renderer>() == null && c != mor.transform) bones.Add(c.name);
                sb.AppendLine("茂さんの骨 " + bones.Count + " 本: " + string.Join(" ", bones.ToArray()));
                foreach (var n in new[] { "Hips", "Spine", "Chest", "Neck", "Head", "LeftHand", "RightHand", "LeftFoot", "RightFoot", "LeftToes", "Eye_L", "Eye_R", "Brow_L" })
                {
                    var t = Find(mor.transform, n);
                    sb.AppendLine("  骨 " + n + (t == null ? " なし" : " 根から " + V(t.position - O) + " fwd " + V(t.forward) + " up " + V(t.up) + " lscale " + V(t.localScale)));
                }
                // 握り（WC_Parts の黒い筒）：高さ 0.85 m より上の頂点
                var parts = Find(chair.transform, "WC_Parts").GetComponent<MeshFilter>().sharedMesh;
                var pm = Find(chair.transform, "WC_Parts");
                foreach (int s in new[] { -1, 1 })
                {
                    Vector3 mn = Vector3.one * 9, mx = -Vector3.one * 9; int n = 0;
                    foreach (var v in parts.vertices)
                    {
                        Vector3 w = pm.TransformPoint(v) - O;
                        if (w.y < 0.85f || Mathf.Sign(w.x) != s) continue;
                        mn = Vector3.Min(mn, w); mx = Vector3.Max(mx, w); n++;
                    }
                    sb.AppendLine("握り x" + (s > 0 ? "+" : "−") + "：" + V(mn) + "〜" + V(mx) + "（頂点 " + n + "）中心 " + V((mn + mx) * 0.5f));
                }
                // 足のせ：高さ 0.1 m より下の黒い頂点
                {
                    Vector3 mn = Vector3.one * 9, mx = -Vector3.one * 9;
                    foreach (var v in parts.vertices) { Vector3 w = pm.TransformPoint(v) - O; if (w.y > 0.1f || w.z < 0.2f) continue; mn = Vector3.Min(mn, w); mx = Vector3.Max(mx, w); }
                    sb.AppendLine("足のせ：" + V(mn) + "〜" + V(mx));
                }
                // 茂さんの足（スリッパ）と足のせ・お尻とクッション
                var baked = new Mesh();
                foreach (var smr in mor.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                {
                    smr.BakeMesh(baked, true);
                    var m = Matrix4x4.TRS(smr.transform.position, smr.transform.rotation, Vector3.one);
                    Vector3 mn = Vector3.one * 9, mx = -Vector3.one * 9;
                    foreach (var v in baked.vertices) { var w = m.MultiplyPoint3x4(v) - O; mn = Vector3.Min(mn, w); mx = Vector3.Max(mx, w); }
                    sb.AppendLine("  " + smr.name + " 焼いた形 " + V(mn) + "〜" + V(mx) + " 頂点 " + baked.vertexCount + " 表示 " + smr.gameObject.activeSelf);
                }
                foreach (var mf in chair.GetComponentsInChildren<MeshFilter>(true))
                {
                    Vector3 mn = Vector3.one * 9, mx = -Vector3.one * 9;
                    foreach (var v in mf.sharedMesh.vertices) { var w = mf.transform.TransformPoint(v) - O; mn = Vector3.Min(mn, w); mx = Vector3.Max(mx, w); }
                    sb.AppendLine("  " + mf.name + " 形 " + V(mn) + "〜" + V(mx) + " 頂点 " + mf.sharedMesh.vertexCount);
                }

                // 静止画：Blender の絵と同じ並び（前・横・後ろ・斜め前・斜め後ろ・上から・顔）
                dir.nurse.gameObject.SetActive(false); dir.robot.gameObject.SetActive(false); dir.bag.gameObject.SetActive(false);
                var proxies = new List<KeyValuePair<SkinnedMeshRenderer, MeshFilter>>();
                foreach (var smr in mor.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                {
                    var g = new GameObject(smr.name + "_Baked"); var mf = g.AddComponent<MeshFilter>(); mf.sharedMesh = new Mesh();
                    var mr = g.AddComponent<MeshRenderer>(); mr.sharedMaterials = smr.sharedMaterials; smr.enabled = false;
                    g.SetActive(smr.gameObject.activeInHierarchy);
                    smr.BakeMesh(mf.sharedMesh, true); mf.sharedMesh.RecalculateBounds();
                    g.transform.SetPositionAndRotation(smr.transform.position, smr.transform.rotation);
                }
                var floor = GameObject.CreatePrimitive(PrimitiveType.Plane); floor.transform.position = O; floor.transform.localScale = Vector3.one * 2f;
                var fm2 = new Material(Shader.Find("Standard")) { color = new Color(0.97f, 0.97f, 0.97f) }; fm2.SetFloat("_Glossiness", 0.1f); floor.GetComponent<Renderer>().sharedMaterial = fm2;
                var back = GameObject.CreatePrimitive(PrimitiveType.Quad); back.transform.position = O + new Vector3(0, 1.5f, -3f); back.transform.localScale = new Vector3(12, 6, 1); back.transform.rotation = Quaternion.Euler(0, 180, 0);
                var bm = new Material(Shader.Find("Unlit/Color")) { color = new Color(0.74f, 0.79f, 0.79f) }; back.GetComponent<Renderer>().sharedMaterial = bm;
                var cam = dir.cam;
                cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.74f, 0.79f, 0.79f);
                var views = new[] {
                    new { n = "front", p = new Vector3(0f, 0.75f, 3.2f), l = new Vector3(0f, 0.68f, 0f), fov = 30f },
                    new { n = "side", p = new Vector3(3.2f, 0.75f, 0.05f), l = new Vector3(0f, 0.68f, 0.05f), fov = 30f },
                    new { n = "back", p = new Vector3(0f, 0.75f, -3.2f), l = new Vector3(0f, 0.68f, 0f), fov = 30f },
                    new { n = "persp", p = new Vector3(-2.0f, 1.6f, 2.4f), l = new Vector3(0f, 0.55f, 0.05f), fov = 30f },
                    new { n = "persp2", p = new Vector3(2.0f, 1.6f, -2.4f), l = new Vector3(0f, 0.55f, 0.05f), fov = 30f },
                    new { n = "face", p = new Vector3(0.0f, 1.2f, 0.75f), l = new Vector3(0f, 1.17f, 0.0f), fov = 22f },
                };
                foreach (var v in views)
                {
                    cam.transform.position = O + v.p; cam.transform.rotation = Quaternion.LookRotation((O + v.l) - cam.transform.position); cam.fieldOfView = v.fov;
                    var big = RenderTexture.GetTemporary(1600, 1200, 24); cam.targetTexture = big; cam.Render(); cam.targetTexture = null;
                    var small = RenderTexture.GetTemporary(800, 600, 0); Graphics.Blit(big, small);
                    RenderTexture.active = small; var tex = new Texture2D(800, 600, TextureFormat.RGB24, false); tex.ReadPixels(new Rect(0, 0, 800, 600), 0, 0); tex.Apply(); RenderTexture.active = null;
                    File.WriteAllBytes(Path.Combine(outDir, "morita_" + v.n + ".png"), tex.EncodeToPNG());
                    RenderTexture.ReleaseTemporary(big); RenderTexture.ReleaseTemporary(small);
                }
            }
            catch (Exception e) { Debug.LogError(e); sb.AppendLine("エラー: " + e); }
            File.WriteAllText(Path.Combine(outDir, "morita228.txt"), sb.ToString(), new UTF8Encoding(false));
        }
    }
}
```

### make_script228.py（台本 closeup228_script.json を作る）

```python
"""依頼228：⑧「車いすに道を譲る」の台本 closeup228_script.json を作る。
175 の台本（closeup175_script.json）から、廊下の部屋・色・光・看護師の値・画面の値を写し、場面は新しい "yield" 1 つだけにする。
・大城さん：175 の手づくりの歩き（Walk・walk_steps は make_script217.py から写した）を、押す速さ（0.8 m/秒）と歩幅（周期 0.5 秒）に合わせた。
  両手は車いすの握り（WC_Parts の黒い筒・左右 0.45 m）に置く（的は看護師の根から。車いすは看護師の根に固く付いて動くので、握りは看護師の根から動かない）
・車いす：根は看護師の根の前 wc_ahead_m（Unity で看護師の根から置く）。茂さんは車いすの子
・ハコブくん：台本の robot_rule の決まりで Unity の中で動く（Closeup228.cs）。止まる時刻は times.json（1 回めの走り）から
・声：L4 ハコブ「お先にどうぞ」・L5 大城「ありがとう」。口は 217・218 と同じ作り方
使い方：python3 make_script228.py <175 の台本> <出力の台本> <声の wav のフォルダ> [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 = sys.argv[1], sys.argv[2], sys.argv[3]
times = json.load(open(sys.argv[4])) if len(sys.argv) > 4 and os.path.exists(sys.argv[4]) else {}
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = list(S["corridor"]["origin"])
LANE_C = E("LANE_C", 0.42)          # 車いすの中心の横の位置（廊下の中心から。左側通行＝+x の側）
LANE_R = E("LANE_R", -0.33)         # ハコブくんのふだんの横の位置（左寄りの通り道）
V_C = E("V_C", 0.8)                 # 押す速さ
V_PASS = E("V_PASS", 0.65)          # 横を通りすぎる時の速さ
STEP_T = E("STEP_T", 0.5)           # 1 歩の時間（押す歩き。歩幅 0.4 m）
GRIP_Z = 0.3336                     # 握りの中心：車いすの根から後ろ（Unity で測った）
GRIP_X, GRIP_Y = 0.225, 0.910
GRIP_R = 0.0155
D_PUSH = E("D_PUSH", 0.26)          # 握りの中心と看護師の根の前後の距離
WC_AHEAD = GRIP_Z + D_PUSH          # 車いすの根：看護師の根の前
WC_FRONT = 0.64                     # 足のせの前の端：車いすの根から前
ROBOT_FRONT, ROBOT_REAR = 0.382, 0.380
NURSE_BACK = 0.16                   # 看護師の体の後ろの端：根から後ろ（めやす）
RZ0 = E("RZ0", -1.6)                # ハコブくんの始めの z（中心）
NZ0 = E("NZ0", 20.1)                # 看護師の根の始めの z
TV0 = E("TV0", 1.0)                 # 動画の始まり（台本の秒）
GAP = E("GAP", 0.55)                # セリフの間
SPINE, CHEST = E("SPINE", 4.0), E("SPINE_C", 3.0)   # 上体を前へ（合わせて 7°）
END_AFTER = E("END_AFTER", 4.2)     # 走り出しから動画の終わりまで（めやす。画面の外へ出たら終わり＝times.json の exit_t があればそれ）

def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)

# ---------------------------------------------------------------- 声
LINES = [("L4", "robot", "L4_hakobu.wav", "お先にどうぞ"), ("L5", "nurse", "L5_oshiro.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 name, who, fn, text in LINES:
    x = load_wav(os.path.join(wavdir, fn)); v0, v1 = voiced(x)
    clips[name] = {"who": who, "file": fn, "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}

# ---------------------------------------------------------------- ハコブくんの決まり（Closeup228.cs と同じ値）
RULE = {
    "about": "ハコブくんの決まり（依頼228。175 の考え方：近い→減速して寄る・すき間が取れない→止まる）。値は Closeup228.cs が読む",
    "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": E("MARGIN", 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,
}

# ---------------------------------------------------------------- 大城さん・車いすの道（根の z）
t_stop = times.get("stop_t", 13.5)          # ハコブくんが止まった（1 回めの走り）
z_rstop = times.get("robot_stop_z", 5.8)    # 止まった中心の z
x_rstop = times.get("robot_stop_x", -0.47)
t_resume = times.get("resume_t", t_stop + 8.0)
t_exit = times.get("exit_t", t_resume + END_AFTER)
z_rfront, z_rrear = z_rstop + ROBOT_FRONT, z_rstop - ROBOT_REAR

TW0, RAMP = 0.2, 1.0
NT = 60.0
def build_path(slow0_z, slow1_z, T_SL=0.8):
    """速さ：0.2〜1.2 秒で 0.8 へ。足のせの前の端が slow0_z を過ぎたら 0.65 へ（T_SL 秒で）、看護師の体の後ろの端が slow1_z を過ぎたら 0.8 へ"""
    z = NZ0; out = []; v = 0.0; ph = 0; ts = None
    for f in range(int(NT * FPS) + 1):
        t = f * DT
        if t < TW0: vt = 0.0
        elif t < TW0 + RAMP: vt = V_C * smooth((t - TW0) / RAMP)
        else:
            front = z - WC_AHEAD - WC_FRONT; back = z + NURSE_BACK
            if ph == 0 and front <= slow0_z: ph = 1; ts = t
            if ph == 1 and back <= slow1_z: ph = 2; ts = t
            if ph == 0: vt = V_C
            elif ph == 1: vt = V_C + (V_PASS - V_C) * smooth((t - ts) / T_SL)
            else: vt = V_PASS + (V_C - V_PASS) * smooth((t - ts) / T_SL)
        if f > 0: z -= 0.5 * (v + vt) * DT
        v = vt
        out.append((t, z, v))
    return out
SLOW0 = z_rfront + E("SLOW_AHEAD", 1.0)
path = build_path(SLOW0, z_rrear)
def nz(t): return path[min(len(path) - 1, int(round(t * FPS)))][1]

# セリフ（声の始まり）
on = {}
on["L4"] = t_stop + E("L4_AFTER", 0.3)
on["L5"] = on["L4"] + clips["L4"]["dur"] + GAP
end = {k: on[k] + clips[k]["dur"] for k in on}
band_on = t_stop + E("BAND_AFTER", 0.2)
happy_from = end["L5"]; happy_to = happy_from + 1.5
band_off = happy_to
DUR = round(t_exit * FPS) / FPS + (0.0 if "exit_t" in times else 0.0)
NF = int(round(DUR * FPS))

keys_x = [[0, LANE_C]]; keys_yaw = [[0, 180.0]]
keys_z = [[round(t, 4), round(z, 5), "lin"] for t, z, v in path if t <= DUR + 1.0 + 1e-6]
keys_z[0] = keys_z[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
steps = walk_steps(TW0, DUR + 0.6)

# ---------------------------------------------------------------- 大城さんの目線（ハコブくんの画面へ）・口
SCREEN = (x_rstop, 0.96, z_rstop + ROBOT_FRONT - 0.01)
EYE = (0.0, E("EYE_Y", 1.50), -0.09)        # 看護師の根から（前＝−z。上体を前へ傾けた分）
BASE_NOD = E("BASE_NOD", 8.0)               # 押す時は少し下を見る
t_look0, t_look1 = on["L5"] - E("LOOK_LEAD", 0.6), on["L5"] - E("LOOK_LEAD", 0.6) + 0.35
t_back0 = end["L5"] + E("LOOK_HOLD", 0.35); t_back1 = t_back0 + 0.45
def look_w(t):
    if t < t_look0 or t > t_back1: return 0.0
    if t < t_look1: return smooth((t - t_look0) / (t_look1 - t_look0))
    if t > t_back0: return 1 - smooth((t - t_back0) / (t_back1 - t_back0))
    return 1.0
hy_keys, hn_keys = [[0, 0.0]], [[0, BASE_NOD]]
f0, f1 = int(t_look0 * FPS) - 1, int(t_back1 * FPS) + 2
for f in range(max(1, f0), f1 + 1):
    t = f * DT; w = look_w(t)
    ex, ez = LANE_C, nz(t) + EYE[2]
    dx, dz, dy = SCREEN[0] - ex, SCREEN[2] - ez, SCREEN[1] - EYE[1]
    want_yaw = math.degrees(math.atan2(dx, dz)); hy = ((want_yaw - 180.0 + 180) % 360) - 180
    pitch = math.degrees(math.atan2(-dy, math.hypot(dx, dz)))
    hy_keys.append([round(t, 4), round(w * hy, 3), "lin"])
    hn_keys.append([round(t, 4), round(BASE_NOD * (1 - w) + w * pitch, 3), "lin"])
hy_keys.append([round((f1 + 1) * DT, 4), 0.0]); hn_keys.append([round((f1 + 1) * DT, 4), BASE_NOD])
t_smile = t_look0
nurse_mouth_base = [[0, "flat"], [round(t_smile, 4), "smile"]]

# ---------------------------------------------------------------- 茂さん：顔をハコブくんへ（20〜30°）・smile・うなずき 1 回
M_YAW = E("M_YAW", 25.0); M_NOD = E("M_NOD", 10.0)
m_t0 = on["L5"] - E("M_LEAD", 0.45); m_t1 = m_t0 + 0.45
nod_t0 = on["L5"] + E("NOD_AFTER", 0.25); NOD_DOWN, NOD_HOLD, NOD_BACK = 0.28, 0.10, 0.32
m_back0 = end["L5"] + E("M_HOLD", 0.9); m_back1 = m_back0 + 0.6
m_yaw = [[0, 0.0], [round(m_t0, 4), 0.0], [round(m_t1, 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), M_NOD], [round(nod_t0 + NOD_DOWN + NOD_HOLD, 4), M_NOD], [round(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, 4), 0.0]]
m_mouth = [[0, "flat"], [round(m_t0 + 0.15, 4), "smile"]]

# ---------------------------------------------------------------- 声の並び・口（217 と同じ）
tracks = {"nurse": np.zeros(int(DUR * SR) + SR), "robot": np.zeros(int(DUR * SR) + SR)}
place = {}
for k, c in clips.items():
    s0 = on[k] - 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(on[k], 4), "voice_off_s": round(end[k], 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)])
LADDER = ["closed", "small", "mid", "large"]
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: m[int(math.floor(on[k] * FPS)):int(math.ceil(end[k] * FPS))] = True
    return m
r_step = ladder("robot", np.full(NF, 2), speak_mask(["L4"]))         # 休む口は「基本」（mid）
robot_mouth = [LADDER[s] for s in r_step]
n_step = ladder("nurse", np.zeros(NF, int), speak_mask(["L5"]))
nurse_mouth = [int(s) for s in n_step]
mix = (tracks["nurse"] + tracks["robot"])[: int(round(DUR * SR))]
audio_out = os.environ.get("AUDIO_OUT", "")
if audio_out:
    pk = np.max(np.abs(mix)); assert pk < 1.0, pk
    w = wave.open(audio_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 + E("CAM_C", 0.7)
CAM = {
    "main": {"pos": [-0.62, 1.72, round(zc - E("CAM_BACK", 6.0), 4)], "look": [0.12, 0.8, round(zc + 0.9, 4)], "fov": 38},
    "screen_close": {"follow": "robot", "pos": [x_rstop, 1.23, 1.15], "look": [x_rstop, 0.962, 0.29], "fov": 24},
    "face": {"pos": [E("FACE_X", -0.70), E("FACE_Y", 1.30), round(z_rfront + E("FACE_DZ", 0.10), 4)],
             "look": [E("FACE_LX", 0.40), E("FACE_LY", 1.28), round(z_rfront + E("FACE_LDZ", 2.1), 4)], "fov": E("FACE_FOV", 30.0)},
    "depart": {"pos": [0.62, 1.70, round(z_rstop + E("DEP_DZ", 3.6), 4)], "look": [-0.40, 0.55, round(z_rstop + 0.3, 4)], "fov": 40},
    "top": {"pos": [0.0, 7.6, round(zc - 0.3, 4)], "look": [0.0, 0.0, round(zc - 0.3, 4)], "up": [-1, 0, 0], "fov": 27},
    "chk_grip": {"follow": "nurse", "pos": [round(LANE_C - 0.62, 4), 1.22, 0.05], "look": [round(LANE_C - 0.225, 4), 0.93, -0.27], "fov": 22},
    "chk_grip_l": {"follow": "nurse", "pos": [round(LANE_C - 0.3, 4), 1.75, 0.30], "look": [round(LANE_C - 0.225, 4), 0.93, -0.30], "fov": 22},
    "chk_wc": {"follow": "nurse", "pos": [-0.75, 1.0, -1.3], "look": [LANE_C, 0.6, -0.6], "fov": 45},
}
q = lambda t: round(round(t * FPS) / FPS, 4)
CL0 = q(band_on - 0.1)
F0 = q(end["L4"] + E("FACE_IN", 0.25))
F1 = q(max(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, end["L5"]) + 0.25)
cuts = [[0, "main"], [CL0, "screen_close"], [F0, "face"], [F1, "screen_close"], [q(happy_to + 0.1), "main"], [q(t_resume + E("DEP_IN", 0.6)), "depart"]]
t_pass = times.get("pass_t", t_stop + 3.5)
t_seen = times.get("seen_t", t_stop - 3.3)
stills = [
    [q(t_seen + 0.3), "main", "s1_coming_main"],
    [q(t_stop + 0.1), "main", "s2_stopped_main"],
    [q(on["L4"] + 0.4), "screen_close", "s3_osakini_close"],
    [q(nod_t0 + NOD_DOWN + 0.05), "face", "s4_arigatou_nod_face"],
    [q(t_pass), "main", "s5_pass_main"],
    [q(t_pass), "top", "s6_pass_top"],
    [q(t_resume + 1.2), "depart", "s7_depart"],
    [q(t_stop + 0.1), "top", "chk_top_stopped"], [q(t_resume), "top", "chk_top_resume"],
    [q(happy_from + 0.5), "screen_close", "chk_screen_happy"], [q(t_seen), "chk_grip", "chk_grip"], [2.0, "chk_grip", "chk_grip_2s"], [2.0, "chk_wc", "chk_wc_2s"], [2.0, "chk_grip_l", "chk_grip_l_2s"],
    [q(nod_t0 + NOD_DOWN + 0.05), "chk_wc", "chk_wc_nod"], [q(t_seen), "chk_wc", "chk_wc_walk"],
]

shot = {"name": "yield", "about": "⑧ 車いすに道を譲る（依頼228）", "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": [[0, 0], [TW0, 0], [TW0 + 0.4, 1]],
                  "spine": [[0, SPINE]], "chest": [[0, CHEST]],
                  "head_yaw": hy_keys, "head_nod": hn_keys, "mouth": nurse_mouth_base, "talk": [[0, 0]],
                  "L_w": [[0, 1.0]], "R_w": [[0, 1.0]], "L_target": [[0, "grip_l"]], "R_target": [[0, "grip_r"]],
                  "L_curl": [[0, E("CURL", 30.0)]], "R_curl": [[0, E("CURL", 30.0)]], "L_thumb": [[0, E("THUMB", 20.0)]], "R_thumb": [[0, E("THUMB", 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": [[round(t_look1, 3), round(t_back0, 3)]],
        "cameras": CAM, "cuts": cuts, "top_camera": "top", "stills": stills,
        "c228": {"wc_ahead_m": round(WC_AHEAD, 4), "video_from": TV0, "video_to": round((NF - 1) * DT, 4),
                 "band": "c228_yield_band", "band_on": round(band_on, 4), "band_off": round(band_off, 4),
                 "happy_from": round(happy_from, 4), "happy_to": round(happy_to, 4),
                 "robot_mouth": robot_mouth, "nurse_mouth": nurse_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, "speak": {k: [round(on[k], 4), round(end[k], 4)] for k in on},
                 "grip": {"x": GRIP_X, "y": GRIP_Y, "z_behind_root": GRIP_Z, "r": GRIP_R}},
        "times": {"t_stop_used": t_stop, "z_robot_stop": z_rstop, "x_robot_stop": x_rstop, "t_resume_used": t_resume, "t_exit_used": t_exit,
                  "slow0_front_z": round(SLOW0, 4), "slow1_back_z": round(z_rrear, 4), "nurse_z0": NZ0, "robot_z0": RZ0,
                  "nurse_look": [round(t_look0, 3), round(t_back1, 3)], "morita_turn": [round(m_t0, 3), round(m_back1, 3)], "nod_t0": round(nod_t0, 4)}}

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"] = "依頼228：⑧ 車いすに道を譲る（場面 yield）。廊下（rooms）・色・光・看護師・画面の値は 175 の台本から写した（この台本の中で変える）"
out["nurse"] = dict(out["nurse"]); out["nurse"]["walk"] = dict(out["nurse"]["walk"])
out["nurse"]["walk"].update({"amp_deg": E("AMP", 11.0), "knee_deg": 24, "bob_m": 0.008, "lift_m": 0.05})
out["nurse"]["blink"] = dict(out["nurse"]["blink"])
# 握りの的（看護師の根から。手のひらを下に向けて握りの上にのせる・指は前）
gz = WC_AHEAD - GRIP_Z
out["targets"] = dict(out["targets"])
out["targets"]["grip_l"] = {"ref": "nurse", "pos": [round(-GRIP_X, 4), round(GRIP_Y + GRIP_R + E("PALM_UP", 0.018), 4), round(gz - E("GRIP_BACK", 0.05), 4)], "finger_frame": "nurse", "finger": [-E("FING_X", 1.0), -E("FING_Y", 0.35), 1], "palm_frame": "nurse", "palm": [E("PALM_X", 0.3), -1, 0.0]}
out["targets"]["grip_r"] = {"ref": "nurse", "pos": [round(GRIP_X, 4), round(GRIP_Y + GRIP_R + E("PALM_UP", 0.018), 4), round(gz - E("GRIP_BACK", 0.05), 4)], "finger_frame": "nurse", "finger": [E("FING_X", 1.0), -E("FING_Y", 0.35), 1], "palm_frame": "nurse", "palm": [-E("PALM_X", 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
out["screen228"] = {"about": "帯「お先にどうぞ」（tools/screen228.py。219・223 の帯だけの絵と同じ作り方）", "band_text": "お先にどうぞ"}
out["shots"] = [shot]
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=1)
info = dict(shot["times"]); info.update({"duration": DUR, "video_len": round(DUR - TV0, 3), "speak": shot["c228"]["speak"], "gap_L4_L5": round(on["L5"] - end["L4"], 3),
             "band": [band_on, band_off], "happy": [happy_from, happy_to], "cuts": cuts})
print(json.dumps(info, ensure_ascii=False))
```

### Closeup228.cs（⑧の1本目）

```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>
    /// 依頼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）は保存しない。
    ///
    /// コマンド  Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup228.Run \
    ///                 -c228Out <出力フォルダ> [-c228Script closeup228_script.json] [-c228Frames on|off] [-c228Stills on|off] [-c228Views main,top] [-c228From 秒] [-c228To 秒] [-c228Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames228.csv・bones228.csv・feet228.csv・wc228.csv・check228.txt・events228.txt
    /// </summary>
    public static class Closeup228
    {
        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("-c228Out", "");
            if (outDir == "") throw new Exception("-c228Out がない");
            string scriptName = CloseupArgs.Get("-c228Script", "closeup228_script.json");
            bool frames = CloseupArgs.Get("-c228Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c228Stills", "on") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c228Views", "main,top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c228From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c228To", "1e9"), IC);
            Directory.CreateDirectory(outDir);
            var log = new StringBuilder();
            var tab = new StringBuilder();
            try
            {
                Closeup228Morita.Import(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;
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

                // ---- 廊下（217 と同じ）
                var solids = new List<SolidBox>();
                var corr = new GameObject("Corridor228").transform;
                var mats = new Dictionary<string, Material>();
                foreach (var k in js["colors"].Keys)
                {
                    var m = new Material(Shader.Find("Standard")) { name = "C228_" + 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("Baked228").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, "Wheelchair228").transform;
                var mor = Closeup228Morita.Spawn(Closeup228Morita.MoritaFbx, "Morita228").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("NurseCol228"); 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["c228"];
                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 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; bool haveChairPrev = false;
                Vector3 cAxL = Vector3.zero, cAxR = Vector3.zero;   // 前の車輪の車軸（世界）
                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("-c228Until", "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\n");
                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) { float side = Mathf.Max(Mathf.Abs(Vector3.Dot(hubL - prevHubL, chair.right)), Mathf.Abs(Vector3.Dot(hubR - prevHubR, chair.right))); wheelSlipMax = Mathf.Max(wheelSlipMax, 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; }
                            casYawMax = Mathf.Max(casYawMax, Mathf.Abs(yawRel));
                            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; haveChairPrev = true;
                    }
                    // ---------- 茂さん：顔の向き・うなずき・口・まばたき
                    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; }

                    // ハコブくんと箱（壁・手すり・扉）
                    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; }
                    }

                    // 目線：大城さんの顔の向きとハコブくんの画面
                    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)
                        {
                            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);

                    // ---------- 撮る
                    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) { SetCam(dir.cam, shot["cameras"][shot["top_camera"].S()], O, dir); 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, "frames228.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones228.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet228.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc228.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("茂さんのまばたき\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, "check228.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events228.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C228] done\n" + log + "\n" + tab);
        }

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

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

        static Texture2D PrepTex(string path, 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("台本にカメラが無い");
            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);
            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);
        }

        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);
        }
    }
}
```

### make_script229.py（台本 closeup229_script.json を作る）

```python
"""依頼229：⑧「車いすに道を譲る」（228）で、車いすを x +0.28 から始め、ハコブくんが寄り始めたのを見て大城さんが +x（手すり側）へ寄せて x +0.42 にする台本 closeup229_script.json を作る。
make_script228.py（228 の台本を md5 まで同じに作れることを確かめた。DEP_DZ=2.6）を写して、写した先で変えた。228 から変えたのは次だけ：
・車いすの道：後ろの車軸の中心（車いすの根の後ろ 0.15 m）が、寄せ始め（times.json の trig_t＋SHIFT_AFTER 秒）から前へ SHIFT_LEN m 進むあいだに、
  x を LANE_C0 → LANE_C へ 5 次のなめらかな形（向きの変わりも 0 から始まり 0 で終わる）で動かす。車軸は向いた方へだけ進む（横にすべらない）。
  進む長さ（道に沿った長さ）は 228 の速さのまま。大城さんの根と向きは車いすから出す（車いすは大城さんの根の前に固く付いたまま。向き＝車いすの向き）
・大城さんの目線の計算：大城さんの根の x・向きを、上の道から
・確かめのカメラ chk_grip・chk_grip_l：寄せる前の x（LANE_C0）。静止画に寄せている所（本番・真上）を足した
  （真上の静止画は、真上のカメラ top と同じ高さ・角度で、車いすとハコブくんの間の上へずらしたカメラ top_shift。動画のカメラは 228 のまま）
以下は 228 の説明：
175 の台本（closeup175_script.json）から、廊下の部屋・色・光・看護師の値・画面の値を写し、場面は新しい "yield" 1 つだけにする。
・大城さん：175 の手づくりの歩き（Walk・walk_steps は make_script217.py から写した）を、押す速さ（0.8 m/秒）と歩幅（周期 0.5 秒）に合わせた。
  両手は車いすの握り（WC_Parts の黒い筒・左右 0.45 m）に置く（的は看護師の根から。車いすは看護師の根に固く付いて動くので、握りは看護師の根から動かない）
・車いす：根は看護師の根の前 wc_ahead_m（Unity で看護師の根から置く）。茂さんは車いすの子
・ハコブくん：台本の robot_rule の決まりで Unity の中で動く（Closeup228.cs）。止まる時刻は times.json（1 回めの走り）から
・声：L4 ハコブ「お先にどうぞ」・L5 大城「ありがとう」。口は 217・218 と同じ作り方
使い方：python3 make_script229.py <175 の台本> <出力の台本> <声の wav のフォルダ> [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 = sys.argv[1], sys.argv[2], sys.argv[3]
times = json.load(open(sys.argv[4])) if len(sys.argv) > 4 and os.path.exists(sys.argv[4]) else {}
S = json.load(open(src))
FPS = 30; DT = 1.0 / FPS
O = list(S["corridor"]["origin"])
LANE_C = E("LANE_C", 0.42)          # 車いすの中心の横の位置（寄せた後。廊下の中心から。左側通行＝+x の側）
LANE_C0 = E("LANE_C0", 0.28)        # 依頼229：車いすの始めの横の位置
SHIFT = E("SHIFT", 1)               # 依頼229：1＝寄せる・0＝寄せない（寄せなかったとしたらの予想の走り）
SHIFT_AFTER = E("SHIFT_AFTER", 0.6) # 依頼229：ハコブくんが減速して寄り始めてから寄せ始めるまで（0.5〜1.0 秒）
SHIFT_LEN = E("SHIFT_LEN", 2.8)     # 依頼229：寄せるあいだに車軸が前へ進む長さ（m）
AXLE_BACK = 0.15                    # 後ろの車軸：車いすの根から後ろ（Wheel_L/R の根から z −0.15）
LANE_R = E("LANE_R", -0.33)         # ハコブくんのふだんの横の位置（左寄りの通り道）
V_C = E("V_C", 0.8)                 # 押す速さ
V_PASS = E("V_PASS", 0.65)          # 横を通りすぎる時の速さ
STEP_T = E("STEP_T", 0.5)           # 1 歩の時間（押す歩き。歩幅 0.4 m）
GRIP_Z = 0.3336                     # 握りの中心：車いすの根から後ろ（Unity で測った）
GRIP_X, GRIP_Y = 0.225, 0.910
GRIP_R = 0.0155
D_PUSH = E("D_PUSH", 0.26)          # 握りの中心と看護師の根の前後の距離
WC_AHEAD = GRIP_Z + D_PUSH          # 車いすの根：看護師の根の前
WC_FRONT = 0.64                     # 足のせの前の端：車いすの根から前
ROBOT_FRONT, ROBOT_REAR = 0.382, 0.380
NURSE_BACK = 0.16                   # 看護師の体の後ろの端：根から後ろ（めやす）
RZ0 = E("RZ0", -1.6)                # ハコブくんの始めの z（中心）
NZ0 = E("NZ0", 20.1)                # 看護師の根の始めの z
TV0 = E("TV0", 1.0)                 # 動画の始まり（台本の秒）
GAP = E("GAP", 0.55)                # セリフの間
SPINE, CHEST = E("SPINE", 4.0), E("SPINE_C", 3.0)   # 上体を前へ（合わせて 7°）
DEP_DZ_DEF = 2.6                    # 228 で使った値（228 の台本を作った時の DEP_DZ）
END_AFTER = E("END_AFTER", 4.2)     # 走り出しから動画の終わりまで（めやす。画面の外へ出たら終わり＝times.json の exit_t があればそれ）

def smooth(u): u = min(1, max(0, u)); return u * u * (3 - 2 * u)

# ---------------------------------------------------------------- 声
LINES = [("L4", "robot", "L4_hakobu.wav", "お先にどうぞ"), ("L5", "nurse", "L5_oshiro.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 name, who, fn, text in LINES:
    x = load_wav(os.path.join(wavdir, fn)); v0, v1 = voiced(x)
    clips[name] = {"who": who, "file": fn, "text": text, "x": x, "v0": v0, "v1": v1, "dur": v1 - v0, "len": len(x) / SR}

# ---------------------------------------------------------------- ハコブくんの決まり（Closeup228.cs と同じ値）
RULE = {
    "about": "ハコブくんの決まり（依頼228 のまま。175 の考え方：近い→減速して寄る・すき間が取れない→止まる）。値は Closeup229.cs が読む",
    "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": E("MARGIN", 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,
}

# ---------------------------------------------------------------- 大城さん・車いすの道（根の z）
t_stop = times.get("stop_t", 13.5)          # ハコブくんが止まった（1 回めの走り）
z_rstop = times.get("robot_stop_z", 5.8)    # 止まった中心の z
x_rstop = times.get("robot_stop_x", -0.47)
t_resume = times.get("resume_t", t_stop + 8.0)
t_exit = times.get("exit_t", t_resume + END_AFTER)
z_rfront, z_rrear = z_rstop + ROBOT_FRONT, z_rstop - ROBOT_REAR

TW0, RAMP = 0.2, 1.0
NT = 60.0
def build_path(slow0_z, slow1_z, T_SL=0.8):
    """速さ：0.2〜1.2 秒で 0.8 へ。足のせの前の端が slow0_z を過ぎたら 0.65 へ（T_SL 秒で）、看護師の体の後ろの端が slow1_z を過ぎたら 0.8 へ"""
    z = NZ0; out = []; v = 0.0; ph = 0; ts = None
    for f in range(int(NT * FPS) + 1):
        t = f * DT
        if t < TW0: vt = 0.0
        elif t < TW0 + RAMP: vt = V_C * smooth((t - TW0) / RAMP)
        else:
            front = z - WC_AHEAD - WC_FRONT; back = z + NURSE_BACK
            if ph == 0 and front <= slow0_z: ph = 1; ts = t
            if ph == 1 and back <= slow1_z: ph = 2; ts = t
            if ph == 0: vt = V_C
            elif ph == 1: vt = V_C + (V_PASS - V_C) * smooth((t - ts) / T_SL)
            else: vt = V_PASS + (V_C - V_PASS) * smooth((t - ts) / T_SL)
        if f > 0: z -= 0.5 * (v + vt) * DT
        v = vt
        out.append((t, z, v))
    return out
SLOW0 = z_rfront + E("SLOW_AHEAD", 1.0)
path = build_path(SLOW0, z_rrear)

# ---------------------------------------------------------------- 依頼229：車いすを寄せる道（後ろの車軸の中心）
t_trig = times.get("trig_t", 10.7)          # ハコブくんが減速して寄り始めた（決まりに当たった）
t_sh0 = t_trig + SHIFT_AFTER
AX_AHEAD = WC_AHEAD - AXLE_BACK             # 車軸の中心：大城さんの根の前
def P5(u): u = min(1.0, max(0.0, u)); return u * u * u * (10 - 15 * u + 6 * u * u)
def dP5(u): return 0.0 if u <= 0 or u >= 1 else 30 * u * u * (1 - u) * (1 - u)
DX = (LANE_C - LANE_C0) if SHIFT else 0.0
s_of_t = [NZ0 - z for t, z, v in path]      # 道に沿って進んだ長さ（228 の速さのまま）
ds0 = s_of_t[int(round(t_sh0 * FPS))]       # 寄せ始めまでは まっすぐ（進んだ長さ＝前へ進んだ長さ）
# 前へ進んだ長さ d → 道に沿った長さ s の表（細かく積む）
GD = 0.0005
dd = np.arange(0.0, s_of_t[-1] + 1.0, GD)
xs = LANE_C0 + DX * np.array([P5((d - ds0) / SHIFT_LEN) for d in dd])
sl = DX / SHIFT_LEN * np.array([dP5((d - ds0) / SHIFT_LEN) for d in dd])
ss = np.concatenate([[0.0], np.cumsum(np.sqrt(1 + (0.5 * (sl[1:] + sl[:-1])) ** 2) * GD)])
def axle_at(s):
    d = float(np.interp(s, ss, dd))
    u = (d - ds0) / SHIFT_LEN
    x = LANE_C0 + DX * P5(u); k = DX / SHIFT_LEN * dP5(u)
    return d, x, math.atan(k)
nurse_xz = []                               # 毎コマ：大城さんの根 x・z・向き（度）、車軸 x・z、車いすの向き（度、+ は +x へ）
for (t, z, v), s in zip(path, s_of_t):
    d, ax, dl = axle_at(s)
    az = NZ0 - AX_AHEAD - d
    fx, fz = math.sin(dl), -math.cos(dl)
    nurse_xz.append((t, ax - fx * AX_AHEAD, az - fz * AX_AHEAD, 180.0 - math.degrees(dl), ax, az, math.degrees(dl)))
def nz(t): return nurse_xz[min(len(nurse_xz) - 1, int(round(t * FPS)))][2]
def nx(t): return nurse_xz[min(len(nurse_xz) - 1, int(round(t * FPS)))][1]
def nyaw(t): return nurse_xz[min(len(nurse_xz) - 1, int(round(t * FPS)))][3]
# 寄せる所の値（確かめ）
sh = [r for r in nurse_xz if abs(r[6]) > 1e-6]
t_sh1 = (sh[-1][0] + DT) if sh else t_sh0
def lat_speeds():
    out = {"axle": 0.0, "root": 0.0, "front": 0.0, "nurse": 0.0}
    for i in range(1, len(nurse_xz)):
        a, b = nurse_xz[i - 1], nurse_xz[i]
        for key, off in (("axle", 0.0), ("root", AXLE_BACK), ("front", AXLE_BACK + WC_FRONT)):
            xa = a[4] + math.sin(math.radians(a[6])) * off; xb = b[4] + math.sin(math.radians(b[6])) * off
            out[key] = max(out[key], abs(xb - xa) / DT)
        out["nurse"] = max(out["nurse"], abs(b[1] - a[1]) / DT)
    return out
LATV = lat_speeds()
HEAD_MAX = max(abs(r[6]) for r in nurse_xz)
TURN_RATE = max(abs(nurse_xz[i][6] - nurse_xz[i - 1][6]) / DT for i in range(1, len(nurse_xz)))

# セリフ（声の始まり）
on = {}
on["L4"] = t_stop + E("L4_AFTER", 0.3)
on["L5"] = on["L4"] + clips["L4"]["dur"] + GAP
end = {k: on[k] + clips[k]["dur"] for k in on}
band_on = t_stop + E("BAND_AFTER", 0.2)
happy_from = end["L5"]; happy_to = happy_from + 1.5
band_off = happy_to
DUR = round(t_exit * FPS) / FPS + (0.0 if "exit_t" in times else 0.0)
NF = int(round(DUR * FPS))

# 依頼229：x・向きは変わるコマだけ毎コマのキー（ほかは一定）。z は 228 と同じく毎コマ
f_a, f_b = int(round(t_sh0 * FPS)) - 1, int(round(t_sh1 * FPS)) + 1
keys_x = [[0, round(LANE_C0, 5)]]; keys_yaw = [[0, 180.0]]
if SHIFT:
    for r in nurse_xz[max(1, f_a):f_b + 1]:
        keys_x.append([round(r[0], 4), round(r[1], 5), "lin"]); keys_yaw.append([round(r[0], 4), round(r[3], 4), "lin"])
keys_z = [[round(r[0], 4), round(r[2], 5), "lin"] for r in nurse_xz if r[0] <= DUR + 1.0 + 1e-6]
keys_z[0] = keys_z[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
steps = walk_steps(TW0, DUR + 0.6)

# ---------------------------------------------------------------- 大城さんの目線（ハコブくんの画面へ）・口
SCREEN = (x_rstop, 0.96, z_rstop + ROBOT_FRONT - 0.01)
EYE = (0.0, E("EYE_Y", 1.50), -0.09)        # 看護師の根から（前＝−z。上体を前へ傾けた分）
BASE_NOD = E("BASE_NOD", 8.0)               # 押す時は少し下を見る
t_look0, t_look1 = on["L5"] - E("LOOK_LEAD", 0.6), on["L5"] - E("LOOK_LEAD", 0.6) + 0.35
t_back0 = end["L5"] + E("LOOK_HOLD", 0.35); t_back1 = t_back0 + 0.45
def look_w(t):
    if t < t_look0 or t > t_back1: return 0.0
    if t < t_look1: return smooth((t - t_look0) / (t_look1 - t_look0))
    if t > t_back0: return 1 - smooth((t - t_back0) / (t_back1 - t_back0))
    return 1.0
hy_keys, hn_keys = [[0, 0.0]], [[0, BASE_NOD]]
f0, f1 = int(t_look0 * FPS) - 1, int(t_back1 * FPS) + 2
for f in range(max(1, f0), f1 + 1):
    t = f * DT; w = look_w(t)
    by = nyaw(t); ex, ez = nx(t) + math.sin(math.radians(by)) * EYE[2] * -1, nz(t) + math.cos(math.radians(by)) * EYE[2] * -1
    dx, dz, dy = SCREEN[0] - ex, SCREEN[2] - ez, SCREEN[1] - EYE[1]
    want_yaw = math.degrees(math.atan2(dx, dz)); hy = ((want_yaw - by + 180) % 360) - 180
    pitch = math.degrees(math.atan2(-dy, math.hypot(dx, dz)))
    hy_keys.append([round(t, 4), round(w * hy, 3), "lin"])
    hn_keys.append([round(t, 4), round(BASE_NOD * (1 - w) + w * pitch, 3), "lin"])
hy_keys.append([round((f1 + 1) * DT, 4), 0.0]); hn_keys.append([round((f1 + 1) * DT, 4), BASE_NOD])
t_smile = t_look0
nurse_mouth_base = [[0, "flat"], [round(t_smile, 4), "smile"]]

# ---------------------------------------------------------------- 茂さん：顔をハコブくんへ（20〜30°）・smile・うなずき 1 回
M_YAW = E("M_YAW", 25.0); M_NOD = E("M_NOD", 10.0)
m_t0 = on["L5"] - E("M_LEAD", 0.45); m_t1 = m_t0 + 0.45
nod_t0 = on["L5"] + E("NOD_AFTER", 0.25); NOD_DOWN, NOD_HOLD, NOD_BACK = 0.28, 0.10, 0.32
m_back0 = end["L5"] + E("M_HOLD", 0.9); m_back1 = m_back0 + 0.6
m_yaw = [[0, 0.0], [round(m_t0, 4), 0.0], [round(m_t1, 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), M_NOD], [round(nod_t0 + NOD_DOWN + NOD_HOLD, 4), M_NOD], [round(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, 4), 0.0]]
m_mouth = [[0, "flat"], [round(m_t0 + 0.15, 4), "smile"]]

# ---------------------------------------------------------------- 声の並び・口（217 と同じ）
tracks = {"nurse": np.zeros(int(DUR * SR) + SR), "robot": np.zeros(int(DUR * SR) + SR)}
place = {}
for k, c in clips.items():
    s0 = on[k] - 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(on[k], 4), "voice_off_s": round(end[k], 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)])
LADDER = ["closed", "small", "mid", "large"]
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: m[int(math.floor(on[k] * FPS)):int(math.ceil(end[k] * FPS))] = True
    return m
r_step = ladder("robot", np.full(NF, 2), speak_mask(["L4"]))         # 休む口は「基本」（mid）
robot_mouth = [LADDER[s] for s in r_step]
n_step = ladder("nurse", np.zeros(NF, int), speak_mask(["L5"]))
nurse_mouth = [int(s) for s in n_step]
mix = (tracks["nurse"] + tracks["robot"])[: int(round(DUR * SR))]
audio_out = os.environ.get("AUDIO_OUT", "")
if audio_out:
    pk = np.max(np.abs(mix)); assert pk < 1.0, pk
    w = wave.open(audio_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 + E("CAM_C", 0.7)
CAM = {
    "main": {"pos": [-0.62, 1.72, round(zc - E("CAM_BACK", 6.0), 4)], "look": [0.12, 0.8, round(zc + 0.9, 4)], "fov": 38},
    "screen_close": {"follow": "robot", "pos": [x_rstop, 1.23, 1.15], "look": [x_rstop, 0.962, 0.29], "fov": 24},
    "face": {"pos": [E("FACE_X", -0.70), E("FACE_Y", 1.30), round(z_rfront + E("FACE_DZ", 0.10), 4)],
             "look": [E("FACE_LX", 0.40), E("FACE_LY", 1.28), round(z_rfront + E("FACE_LDZ", 2.1), 4)], "fov": E("FACE_FOV", 30.0)},
    "depart": {"pos": [0.62, 1.70, round(z_rstop + E("DEP_DZ", DEP_DZ_DEF), 4)], "look": [-0.40, 0.55, round(z_rstop + 0.3, 4)], "fov": 40},
    "top": {"pos": [0.0, 7.6, round(zc - 0.3, 4)], "look": [0.0, 0.0, round(zc - 0.3, 4)], "up": [-1, 0, 0], "fov": 27},
    "chk_grip": {"follow": "nurse", "pos": [round(LANE_C0 - 0.62, 4), 1.22, 0.05], "look": [round(LANE_C0 - 0.225, 4), 0.93, -0.27], "fov": 22},
    "chk_grip_l": {"follow": "nurse", "pos": [round(LANE_C0 - 0.3, 4), 1.75, 0.30], "look": [round(LANE_C0 - 0.225, 4), 0.93, -0.30], "fov": 22},
    "top_shift": {"pos": [0.0, 7.6, round(nz(0.5 * (t_sh0 + t_sh1)) - WC_AHEAD - E("TOPSH_BACK", 2.2), 4)], "look": [0.0, 0.0, round(nz(0.5 * (t_sh0 + t_sh1)) - WC_AHEAD - E("TOPSH_BACK", 2.2), 4)], "up": [-1, 0, 0], "fov": 27},
    "chk_grip_shift": {"follow": "nurse_xz", "pos": [-0.62, 1.22, 0.05], "look": [-0.225, 0.93, -0.27], "fov": 22},
    "chk_wc": {"follow": "nurse", "pos": [-0.75, 1.0, -1.3], "look": [LANE_C, 0.6, -0.6], "fov": 45},
}
q = lambda t: round(round(t * FPS) / FPS, 4)
CL0 = q(band_on - 0.1)
F0 = q(end["L4"] + E("FACE_IN", 0.25))
F1 = q(max(nod_t0 + NOD_DOWN + NOD_HOLD + NOD_BACK, end["L5"]) + 0.25)
cuts = [[0, "main"], [CL0, "screen_close"], [F0, "face"], [F1, "screen_close"], [q(happy_to + 0.1), "main"], [q(t_resume + E("DEP_IN", 0.6)), "depart"]]
t_pass = times.get("pass_t", t_stop + 3.5)
t_seen = times.get("seen_t", t_stop - 3.3)
stills = [
    [q(t_seen + 0.3), "main", "s1_coming_main"],
    [q(t_stop + 0.1), "main", "s2_stopped_main"],
    [q(on["L4"] + 0.4), "screen_close", "s3_osakini_close"],
    [q(nod_t0 + NOD_DOWN + 0.05), "face", "s4_arigatou_nod_face"],
    [q(t_pass), "main", "s5_pass_main"],
    [q(t_pass), "top", "s6_pass_top"],
    [q(t_resume + 1.2), "depart", "s7_depart"],
    [q(0.5 * (t_sh0 + t_sh1)), "main", "s8_shift_main"],
    [q(0.5 * (t_sh0 + t_sh1)), "top_shift", "s8_shift_top"],
    [q(0.5 * (t_sh0 + t_sh1)), "chk_grip_shift", "chk_grip_shift"], [q(0.5 * (t_sh0 + t_sh1)), "chk_wc", "chk_wc_shift"],
    [q(t_stop + 0.1), "top", "chk_top_stopped"], [q(t_resume), "top", "chk_top_resume"],
    [q(happy_from + 0.5), "screen_close", "chk_screen_happy"], [q(t_seen), "chk_grip", "chk_grip"], [2.0, "chk_grip", "chk_grip_2s"], [2.0, "chk_wc", "chk_wc_2s"], [2.0, "chk_grip_l", "chk_grip_l_2s"],
    [q(nod_t0 + NOD_DOWN + 0.05), "chk_wc", "chk_wc_nod"], [q(t_seen), "chk_wc", "chk_wc_walk"],
]

shot = {"name": "yield", "about": "⑧ 車いすに道を譲る（依頼229：228 で車いすを x +0.28 から始めて寄せる）", "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": [[0, 0], [TW0, 0], [TW0 + 0.4, 1]],
                  "spine": [[0, SPINE]], "chest": [[0, CHEST]],
                  "head_yaw": hy_keys, "head_nod": hn_keys, "mouth": nurse_mouth_base, "talk": [[0, 0]],
                  "L_w": [[0, 1.0]], "R_w": [[0, 1.0]], "L_target": [[0, "grip_l"]], "R_target": [[0, "grip_r"]],
                  "L_curl": [[0, E("CURL", 30.0)]], "R_curl": [[0, E("CURL", 30.0)]], "L_thumb": [[0, E("THUMB", 20.0)]], "R_thumb": [[0, E("THUMB", 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": [[round(t_look1, 3), round(t_back0, 3)]],
        "cameras": CAM, "cuts": cuts, "top_camera": "top", "stills": stills,
        "c229": {"wc_ahead_m": round(WC_AHEAD, 4), "video_from": TV0, "video_to": round((NF - 1) * DT, 4),
                 "band": "c228_yield_band", "band_on": round(band_on, 4), "band_off": round(band_off, 4),
                 "happy_from": round(happy_from, 4), "happy_to": round(happy_to, 4),
                 "robot_mouth": robot_mouth, "nurse_mouth": nurse_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, "speak": {k: [round(on[k], 4), round(end[k], 4)] for k in on},
                 "grip": {"x": GRIP_X, "y": GRIP_Y, "z_behind_root": GRIP_Z, "r": GRIP_R},
                 "shift": {"on": bool(SHIFT), "x0": LANE_C0, "x1": LANE_C if SHIFT else LANE_C0, "trig_t_used": t_trig, "t0": round(t_sh0, 4), "t1": round(t_sh1, 4),
                           "len_m": SHIFT_LEN, "axle_back_m": AXLE_BACK, "heading_max_deg": round(HEAD_MAX, 3), "turn_rate_max_dps": round(TURN_RATE, 3),
                           "lat_speed_max_mps": {k: round(v, 4) for k, v in LATV.items()}}},
        "times": {"t_stop_used": t_stop, "z_robot_stop": z_rstop, "x_robot_stop": x_rstop, "t_resume_used": t_resume, "t_exit_used": t_exit, "t_trig_used": t_trig, "shift": [round(t_sh0, 4), round(t_sh1, 4)],
                  "slow0_front_z": round(SLOW0, 4), "slow1_back_z": round(z_rrear, 4), "nurse_z0": NZ0, "robot_z0": RZ0,
                  "nurse_look": [round(t_look0, 3), round(t_back1, 3)], "morita_turn": [round(m_t0, 3), round(m_back1, 3)], "nod_t0": round(nod_t0, 4)}}

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"] = "依頼229：⑧ 車いすに道を譲る（場面 yield）。228 の台本と同じ作り（make_script229.py）で、車いすを x +0.28 から始めて +0.42 へ寄せる。廊下（rooms）・色・光・看護師・画面の値は 175 の台本から写した（この台本の中で変える）"
out["nurse"] = dict(out["nurse"]); out["nurse"]["walk"] = dict(out["nurse"]["walk"])
out["nurse"]["walk"].update({"amp_deg": E("AMP", 11.0), "knee_deg": 24, "bob_m": 0.008, "lift_m": 0.05})
out["nurse"]["blink"] = dict(out["nurse"]["blink"])
# 握りの的（看護師の根から。手のひらを下に向けて握りの上にのせる・指は前）
gz = WC_AHEAD - GRIP_Z
out["targets"] = dict(out["targets"])
out["targets"]["grip_l"] = {"ref": "nurse", "pos": [round(-GRIP_X, 4), round(GRIP_Y + GRIP_R + E("PALM_UP", 0.018), 4), round(gz - E("GRIP_BACK", 0.05), 4)], "finger_frame": "nurse", "finger": [-E("FING_X", 1.0), -E("FING_Y", 0.35), 1], "palm_frame": "nurse", "palm": [E("PALM_X", 0.3), -1, 0.0]}
out["targets"]["grip_r"] = {"ref": "nurse", "pos": [round(GRIP_X, 4), round(GRIP_Y + GRIP_R + E("PALM_UP", 0.018), 4), round(gz - E("GRIP_BACK", 0.05), 4)], "finger_frame": "nurse", "finger": [E("FING_X", 1.0), -E("FING_Y", 0.35), 1], "palm_frame": "nurse", "palm": [-E("PALM_X", 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
out["screen228"] = {"about": "帯「お先にどうぞ」（tools/screen228.py。219・223 の帯だけの絵と同じ作り方）", "band_text": "お先にどうぞ"}
out["shots"] = [shot]
json.dump(out, open(dst, "w"), ensure_ascii=False, indent=1)
info = dict(shot["times"]); info.update({"duration": DUR, "video_len": round(DUR - TV0, 3), "speak": shot["c229"]["speak"], "shift": shot["c229"]["shift"], "gap_L4_L5": round(on["L5"] - end["L4"], 3),
             "band": [band_on, band_off], "happy": [happy_from, happy_to], "cuts": cuts})
print(json.dumps(info, ensure_ascii=False))
```

### Closeup229.cs（⑧の2本目・車いすを寄せる）

```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>
    /// 依頼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.Closeup229.Run \
    ///                 -c229Out <出力フォルダ> [-c229Script closeup229_script.json] [-c229Frames on|off] [-c229Stills on|off] [-c229Views main,top] [-c229From 秒] [-c229To 秒] [-c229Until 秒（試しに途中まで）]
    /// 出すもの：frames/yield/f_*.png・frames/yield_top/f_*.png・stills/・stills_check/・frames229.csv・bones229.csv・feet229.csv・wc229.csv・check229.txt・events229.txt
    /// </summary>
    public static class Closeup229
    {
        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("-c229Out", "");
            if (outDir == "") throw new Exception("-c229Out がない");
            string scriptName = CloseupArgs.Get("-c229Script", "closeup229_script.json");
            bool frames = CloseupArgs.Get("-c229Frames", "off") == "on";
            bool stillsOn = CloseupArgs.Get("-c229Stills", "on") == "on";
            var views = new HashSet<string>(CloseupArgs.Get("-c229Views", "main,top").Split(','));
            float fromT = float.Parse(CloseupArgs.Get("-c229From", "-1"), IC), toT = float.Parse(CloseupArgs.Get("-c229To", "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;
                dir.nurse.Init();
                dir.Measure();
                dir.BuildOverlay();
                dir.MeasurePocket();

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

                    // ---------- 撮る
                    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) { SetCam(dir.cam, shot["cameras"][shot["top_camera"].S()], O, dir); 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, "frames229.csv"), csv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "bones229.csv"), bonesCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "feet229.csv"), feetCsv.ToString(), new UTF8Encoding(false));
                File.WriteAllText(Path.Combine(outDir, "wc229.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, "check229.txt"), tab.ToString(), new UTF8Encoding(false));
            File.WriteAllText(Path.Combine(outDir, "events229.txt"), log.ToString(), new UTF8Encoding(false));
            Debug.Log("[C229] 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("台本にカメラが無い");
            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);
        }

        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);
        }
    }
}
```


## 作業ログ ― サイトのデータの差分

### sim_scenes.json の差分（commit 05bfa52）

```diff
diff --git a/src/data/sim_scenes.json b/src/data/sim_scenes.json
index ff95e99..88681c0 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",
+  "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/）",
   "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": [
     {
@@ -183,6 +183,31 @@
         { "t": 36.6, "text": "「お届けが終わりました。薬剤部へ戻ります」" },
         { "t": 40.0, "text": "看護師が離れてから、ハコブくんが向きを変えて戻る" }
       ]
+    },
+    {
+      "id": "yield",
+      "group": "廊下",
+      "num": "08",
+      "name": "車いすに道を譲る",
+      "short": "手すりに寄って止まり、車いすを先に通す",
+      "poster": "/media/scene3d_08_yield_poster_v1.jpg",
+      "place": "幅1.8mの病棟の廊下（両側に手すり）",
+      "who": "看護師（車いすを押す人）・入院中の患者（車いすに乗る人）・ハコブくん（薬を載せて走っている）",
+      "situation": "薬を運ぶハコブくんの前から、看護師が患者の車いすを押して来ます。ハコブくんと車いすはどちらも幅0.65mで、並ぶと手すりの間の8割をふさぎます。ハコブくんは減速して手すりに寄って止まり、画面と声で「お先にどうぞ」と伝えます。看護師も車いすを少し手すり側へ寄せて通りすぎ、看護師が1m以上離れてから、ハコブくんが走り出します。",
+      "points": ["6m手前で見つけ、減速して手すりに寄り、車いすの2.3m手前で止まる", "寄って止まらなければすき間は8cm。ハコブくんが寄り、看護師も寄せて22cm空ける", "看護師が1m以上離れるまで、ハコブくんは動かない（0m）"],
+      "angles": [
+        { "id": "main", "label": "本番のカメラ", "src": "/media/scene3d_08_yield_v1.mp4", "sec": 25.7, "timed": true, "note": "声あり（音を出して見てください）。ハコブくんと看護師の声は AI 音声です" }
+      ],
+      "steps": [
+        { "t": 0.0, "text": "ハコブくんが薬を載せて廊下を走る。向こうから車いすが来る" },
+        { "t": 9.5, "text": "6m手前で車いすを見つけ、減速して手すりに寄る" },
+        { "t": 10.3, "text": "看護師も車いすを手すり側へ寄せる" },
+        { "t": 12.5, "text": "ハコブくんが車いすの2.3m手前で止まる" },
+        { "t": 12.8, "text": "「お先にどうぞ」" },
+        { "t": 14.2, "text": "看護師「ありがとう」。患者が顔を向けてうなずく" },
+        { "t": 15.6, "text": "車いすがハコブくんの横を通りすぎる" },
+        { "t": 20.5, "text": "看護師が1m以上離れてから、ハコブくんが走り出す" }
+      ]
     }
   ]
 }
```

### sim_scenes.json の差分（見どころの数字を直した分・この記事と同じ commit）

```diff
diff --git a/src/data/sim_scenes.json b/src/data/sim_scenes.json
index 88681c0..e3674f2 100644
--- a/src/data/sim_scenes.json
+++ b/src/data/sim_scenes.json
@@ -194,7 +194,7 @@
       "place": "幅1.8mの病棟の廊下（両側に手すり）",
       "who": "看護師（車いすを押す人）・入院中の患者（車いすに乗る人）・ハコブくん（薬を載せて走っている）",
       "situation": "薬を運ぶハコブくんの前から、看護師が患者の車いすを押して来ます。ハコブくんと車いすはどちらも幅0.65mで、並ぶと手すりの間の8割をふさぎます。ハコブくんは減速して手すりに寄って止まり、画面と声で「お先にどうぞ」と伝えます。看護師も車いすを少し手すり側へ寄せて通りすぎ、看護師が1m以上離れてから、ハコブくんが走り出します。",
-      "points": ["6m手前で見つけ、減速して手すりに寄り、車いすの2.3m手前で止まる", "寄って止まらなければすき間は8cm。ハコブくんが寄り、看護師も寄せて22cm空ける", "看護師が1m以上離れるまで、ハコブくんは動かない（0m）"],
+      "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 音声です" }
       ],
```
