diff --git a/CLAUDE.md b/CLAUDE.md index 661e320..97b30e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,6 +11,8 @@ - シェーダー本体、C#、Humanoid のアニメーション・ボーンのカーブ・Animator Controller、Expression メニュー等は読み込まない。 Generic な `.anim`(シェイプキー・表示の切り替え・オブジェクトの Transform)は、ミュートした NLA トラックの Action にする(`core/animation.py`。#209)。 値が変わらないか 0.1 秒以下で終わる、状態を切り替えるだけのクリップ(Animator のステート用)は読み込まない。 + FBX の中のテイクは、.meta の clipAnimations どおりのクリップにして同じく NLA に並べ、同じ骨格のモーションだけのモデルは + レストの違いを変換して 1 体のアーマチュアにまとめる(`blender/fbx_motion.py`。#276)。オプションは Animation(Muted / Active / None)。 ## 設計の要点(詳細は DESIGN.md) @@ -49,7 +51,7 @@ ``` unitypackage_loader/ Extension 本体(blender_manifest.toml、Blender 4.5 以降の Extension 形式) core/ bpy 非依存。単体テスト可能。bpy を import しないこと - blender/ bpy 依存(importer / options / log / prepare / model_import / session_materials / scene_placement / scene_objects / terrain / unity_meshes / animation / materials / nodes / textures / toon_group / outline) + blender/ bpy 依存(importer / options / log / prepare / model_import / session_materials / scene_placement / scene_objects / terrain / unity_meshes / animation / fbx_motion / materials / nodes / textures / toon_group / outline) operators/ File > Import、モデル選択ダイアログ、再構築、アウトライン ui/ Preferences、サイドバー "UPI" タブ tests/ unittest(bpy 不要)+ Blender 上の統合テスト+合成パッケージ生成 diff --git a/DESIGN.md b/DESIGN.md index 2299eaa..80672c8 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -314,6 +314,7 @@ Material: - マテリアル: `.mat` を解析し、**Blender で意味を持つ情報だけ**をノードに反映。 - テクスチャ: `.mat` から参照されている画像のみ展開して読み込む(オプションで全画像)。 - アニメーションクリップ: Generic な `.anim` のシェイプキー・表示の切り替え・オブジェクトの Transform を、クリップごとの Action にしてミュートした NLA トラックに並べる(§4.7.1。#209)。 +- モデルの中のモーション: FBX のテイクを、.meta の `clipAnimations` どおりのクリップにして NLA に並べる。同じ骨格のモーションだけのモデルは 1 体のアーマチュアにまとめる(§4.7.2。#276)。 ### 読み込まない - シェーダー本体(`.shader` `.cginc`)、C#(`.cs` `.dll`)、Animator Controller(`.controller`)と Humanoid の `.anim`・ボーンのカーブ(§4.7.1)、Expression/Parameter アセット、PhysBone 等の MonoBehaviour、prefab 階層(シーンを読み込む場合はモデルの配置と、その上の GameObject、ライト・カメラだけ再現する)、アイコン画像、`preview.png`。 @@ -364,8 +365,8 @@ File > Import > Unitypackage (.unitypackage) .unitypackage を 3D View に | VRM via VRM Add-on | Bool = ON | `.vrm` を VRM add-on に委譲する。add-on が無ければ glTF インポーターにフォールバックし警告で案内 | | Import bundled .blend files | Bool = OFF | 同梱 `.blend` を append する。`.blend` はドライバー式等で Python を実行し得るため既定 OFF。ON のとき UI に警告を出す。OFF なら該当モデルはスキップして警告に理由を出す | | FBX Importer | Enum: `Auto` / `New (C++)` / `Legacy (Python)` = `Auto` | `Auto` と New は `wm.fbx_import`、Legacy だけ `import_scene.fbx`。Scale(常に表示)はモデルのインポーターに渡す | -| Import Animation / Ignore Leaf Bones | Bool = OFF / ON | FBX インポーターへ渡す(アーマチュアとシェイプキーは常に読む) | -| Animation Clips | Bool = ON | パッケージの Generic な `.anim` を Action にし、ミュートした NLA トラックで並べる(§4.7.1。読み込んだ直後の見た目は変わらないので既定 ON) | +| Animation | Enum: `Muted` / `Active` / `None` = `Muted` | モデルのテイク(§4.7.2)とパッケージの `.anim`(§4.7.1)を NLA トラックにする。`Muted` はすべてミュート(読み込んだ直後の見た目は変わらない)、`Active` はオブジェクトごとに最初の 1 本だけミュートを外す(上のトラックが下を上書きするので 1 本だけ)、`None` は読まない(FBX インポーターの `use_anim` も切る)。以前の Import Animation(FBX に渡すだけ、既定 OFF)と Animation Clips(#209)を 1 つにした(#276) | +| Ignore Leaf Bones | Bool = ON | FBX インポーターへ渡す(アーマチュアとシェイプキーは常に読む) | **Materials** | 項目 | 型 / 既定値 | 説明 | @@ -656,6 +657,7 @@ unitypackage_loader/ │ ├─ terrain.py # Terrain のメッシュと塗り分けのマテリアル(SessionTerrains。#205) │ ├─ unity_meshes.py # Unity の Mesh アセットから作るメッシュ(SessionMeshes。#216) │ ├─ animation.py # クリップの Action と NLA トラック(ClipImporter。#209) +│ ├─ fbx_motion.py # モデルのテイクのクリップへの分割、モーションだけのアーマチュアのまとめ(MotionBuilder。#276) │ ├─ log.py # 捕まえて続けた例外のログ(Verbose Console Log はオペレーターが渡す) │ ├─ scene_objects.py # シーンの Empty・ライト・カメラ・複製・行列の当てはめ(計算は core/model_space.py)・非表示 │ ├─ materials.py # ノード生成 @@ -1008,7 +1010,8 @@ def resolve(model_entry, fbx_material_names, index) -> dict[str, str | None]: 1 回の読み込みは `_ImportSession`(`importer.py`)が手順を並べる: 解析(`analyze`)→ 読み込むモデルの決定 → 展開(`extract`)→ 画像の読み込み → prefab のグループごと(`import_group`)かシーンごと(`SceneImport`。`scene_placement.py`)のモデルの読み込み → -足りなかったテクスチャの補い(`fill_missed_textures`)→ アニメーションクリップ(`import_clips`。§4.7.1)。マテリアルの対応付けと組み立ては `SessionMaterials`(`session_materials.py`)、 +足りなかったテクスチャの補い(`fill_missed_textures`)→ モーションだけのアーマチュアのまとめ(`merge_motion_rigs`。§4.7.2)→ アニメーションクリップ(`import_clips`。§4.7.1)。 +モデルのテイクは、モデルを読み込むたびに `build_model` から `MotionBuilder.arrange` で NLA に並べる(§4.7.2)。マテリアルの対応付けと組み立ては `SessionMaterials`(`session_materials.py`)、 モデルファイルの読み込みは `model_import.py` にある。以前は `importer.py` 1 つ(約 1,900 行)だったのを、役割ごとに分けた(#198)。 下の擬似コードは最初の設計で、流れを示すもの。 @@ -1103,6 +1106,40 @@ def run(ctx, filepath, opts) -> Report: `clip_notes` に出す(警告にはしない)。 - Python から `NlaTrack.mute` を切り替えても依存関係は組み直されず、一度評価したトラックは切り替わらない(NLA エディターでの切り替えでは組み直される)。 統合テストはコレクションを付け外しして組み直させてから値を確かめる。 +- Animation が `Active` なら、対象ごとに最初のトラックだけミュートを外す(モデルのテイクのトラックが先にあれば、そちらが残る)。 + +### 4.7.2 モデルの中のモーション(#276) + +モーション集(32 RPG Animations)や `@` 付きの FBX(Everyday Motion Pack)は、モーションを `.anim` ではなく FBX のテイクに持つ。 +Blender の FBX インポーターはテイクごとにテイクの名前の Action を作り、最初のテイクをアクティブにする(多くは 1 フレームの T ポーズ)。 + +- **クリップの設定**(`core/meta.py` の `ModelClip`): .meta の `animations.clipAnimations` の `name` / `takeName` / `firstFrame` / + `lastFrame` / `loopTime` と、`importAnimation`(0 ならテイクを並べない)。フレームは FBX のフレームレートで、テイクの時刻と同じ数え方。 +- **NLA**(`blender/fbx_motion.py` の `MotionBuilder.arrange`): モデルを読み込むたびに、新しい Action をテイクの名前で引き + (.meta のテイク名と完全一致 → Blender の連番を外した形)、クリップごとにクリップの名前のトラックとストリップを足す。 + ストリップの範囲は firstFrame / lastFrame + 1(FBX インポーターの `anim_offset`)で、同じテイクのクリップは Action を共有する。 + スロットの対象は、スロットの識別子と読み込んだオブジェクトの FBX のノード名(`unity_fbx_node`)で引く。クリップの設定が無ければ + テイクごとに全体を 1 クリップにする。0.1 秒以下のクリップ(`STATE_CLIP_MAX_LENGTH`。T ポーズのテイク)は置かない。 + どのクリップにも使われないテイクの Action は消し、アクティブな Action は外す(読み込んだ直後の見た目をアニメーションを読まない + ときと同じにする)。Action には `unity_take` / `unity_take_model` を残す。 +- **使い回し**: シーンで同じモデルを配置ごとに読み直すときは、最初に読んだときの Action を使い、新しく作られた分は消す。 + 前の読み込みが失敗して Action が消えていたら作り直す。 +- **アーマチュアのまとめ**(`merge_motion_rigs`。Models 単位): メッシュが無く、アーマチュアが 1 体で、トラックを持つモデルを + モーションだけのモデルとし、骨格(ボーンの名前と親の組)が含まれる関係にあり、置き場所(親のワールドの行列)が同じものを + 1 体にまとめる。残すのはボーンがいちばん多く、その中で先に読んだもの。 + - スキンの無い FBX はファイルの既定の姿勢をレストにするので、レストはファイルごとに違う(32 RPG Animations では指のボーンで + 100 以上違った)。親からの相対のレストを R(元)、R'(残す側)とすると、ローカルの行列 B を B' = R'⁻¹·R·B にすれば同じ姿勢になる + (`retarget_action`)。キーの時刻ごとに求め直し、LINEAR のキーにする(フレームごとにキーがあるので見た目は変わらない)。 + - FBX のルートのボーンがアーマチュアのオブジェクトになったもの(Everyday Motion Pack の Bip001)は、オブジェクトの Transform が + ファイルの最初のフレームの値で、モーションごとに違う。オブジェクトのカーブは絶対値なのでそのまま使い、動かさないチャンネルには + 元のアーマチュアの値の一定のキーを足す。 + - 32 RPG Animations(31 体 → 1 体)と Everyday Motion Pack(244 体 → 1 体。21 秒)で、元の FBX を直接読んだときと、ボーンの + ワールドの姿勢が 1e-4 以内で一致することを確かめた。 +- **レポート**: 置いたクリップを `clips`("モデルのパス: クリップ名")に、外したクリップの数・見つからなかったテイク・まとめた + アーマチュアの数を `clip_notes` に出す。 +- FBX インポーターは、アニメーションを読むかどうかによらずシーンのフレームレートをファイルのものにする(今までと同じ)。 + フレームレートの違う FBX を続けて読むと、先に読んだ FBX のモーションの速さがずれる(未対応)。 +- ループ(`loopTime`)はまだ NLA に反映しない(ストリップは範囲の終わりで止まる)。 ### 4.8 `blender/textures.py` diff --git a/README.md b/README.md index d13cf41..a51f10d 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ A Blender Extension that imports `.unitypackage` files directly from File > Impo (including armatures and shape keys) with the material settings and textures from the Unity side applied. - Supported Blender: 4.5 or later (developed on 5.2 LTS, tested on 4.5 LTS and 5.2 LTS) -- What is imported: FBX / OBJ / glTF / VRM / Collada (Blender 4.5 only; removed in Blender 5.0) / bundled .blend files (opt-in), `.mat` files (lilToon / MToon / Poiyomi / Standard / URP / HDRP / VRChat Mobile (Quest) shaders; others on a best-effort basis using generic rules), referenced textures, and Generic animation clips (`.anim`: blend shapes, object visibility and transforms) as actions on muted NLA tracks +- What is imported: FBX / OBJ / glTF / VRM / Collada (Blender 4.5 only; removed in Blender 5.0) / bundled .blend files (opt-in), `.mat` files (lilToon / MToon / Poiyomi / Standard / URP / HDRP / VRChat Mobile (Quest) shaders; others on a best-effort basis using generic rules), referenced textures, and animation as actions on muted NLA tracks: the animation takes inside models (split into Unity's clips; motion-only FBX files with the same skeleton are merged into one armature) and Generic animation clips (`.anim`: blend shapes, object visibility and transforms) - What is not imported: shader source code, C# scripts, Humanoid animation clips, animation curves on bones, Animator Controllers, Expression menus, etc. Prefab hierarchies, lights and cameras are reproduced only when a scene is imported. - VRM: when the [VRM format](https://extensions.blender.org/add-ons/vrm/) add-on is installed, `.vrm` models are handed to it (MToon materials, humanoid rig, spring bones and expressions are reproduced by the add-on). Without it, the glTF importer is used and materials are rebuilt from the bundled `.mat` files. @@ -79,8 +79,8 @@ The options show Material Mode and Scale; everything else is folded into the Mod | (always shown) | Material Mode | `Auto` (Toon for toon-style shaders, Principled for PBR) / `Principled BSDF` / `Toon (Node Group)` / `Unlit (Emission)` / `Names Only` | | | Scale | Scale passed to the model importer | | Model | FBX Importer | Prefer the new C++ importer (`Auto`) / choose explicitly | -| | Import Animation / Ignore Leaf Bones | Passed to the FBX importer (OFF / ON by default) | -| | Animation Clips | Turn the package's Generic `.anim` clips into actions on muted NLA tracks (default ON). See [Animation clips](#animation-clips) | +| | Animation | `Muted` (default): import the models' animation takes and the package's `.anim` clips as muted NLA tracks / `Active`: the same, but unmute the first track of each object / `None`: do not import animation. See [Animation clips](#animation-clips) | +| | Ignore Leaf Bones | Passed to the FBX importer (default ON) | | | VRM via VRM Add-on | Import `.vrm` with the VRM format add-on when installed (default ON); otherwise fall back to the glTF importer and rebuild materials from `.mat` | | | Import Bundled .blend Files | Append objects from `.blend` files inside the package (default OFF). See [Security notes](#security-notes) | | Materials | Force Opaque | Ignore Unity's Cutout / Transparent settings | @@ -172,6 +172,26 @@ Textures > Extract To to `Custom Path` and choose a short folder such as `C:\upi ### Animation clips +Animation is added as **muted** NLA tracks named after each clip, so the scene looks the same right after the import. +To preview a clip, unmute its track in the NLA editor (or click its star to solo it), or select the strip and press Tab to +edit the action. With Animation set to `Active`, the first track of each object is unmuted instead (only one, because +unmuted NLA tracks override each other). + +#### Motions inside models + +Animation takes inside FBX files (for example motion packs, or `model@motion.fbx` files) are split into the clips that the +model's `.meta` defines in Unity (Model Import Settings > Animation: name, first and last frame). All clips of a take share +one action, and each strip plays its own frame range. Models without clip settings get one clip per take. Short clips +(0.1 seconds or shorter, such as a T-pose take) are skipped, and the active action that the FBX importer assigns is cleared. + +When several motion-only models (no meshes, one armature) share the same skeleton, they are merged into one armature +that has all the motions as NLA tracks (Models only). An FBX without a skin uses its default pose as the rest pose, so +the rest pose differs from file to file; the keys are converted so that each motion keeps its pose on the remaining +armature. A skeleton that lacks some bones (for example weapon bones) is merged too; the missing bones stay at rest. +When a scene places the same model many times, the actions of its takes are shared. + +#### Generic `.anim` clips + Generic animation clips (`.anim`) in the package become one action per clip. These curves are read: - Blend shape weights (`blendShape.`, 0–100 in Unity) → shape key values (0–1) @@ -180,16 +200,14 @@ Generic animation clips (`.anim`) in the package become one action per clip. The A clip does not say which model it belongs to, so the importer looks for the imported object under which the most curve paths resolve, and treats it as the object the clip is played on (all placements of the same model get the clip). -Each clip is added as a **muted** NLA track (named after the clip) on every object or shape key it animates, so the -scene looks the same right after the import. To preview a clip, unmute its track in the NLA editor (or click its star to solo it), -or select the strip and press Tab to edit the action. Keys start at the scene's start frame and use the scene's frame rate. +Each clip gets an NLA track on every object or shape key it animates. Keys start at the scene's start frame and use the scene's frame rate. Looping clips get a Cycles modifier on their F-curves. Clips that only switch a state are skipped: clips whose values never change, or that end within 0.1 seconds. Unity's Animator uses such clips as states and makes the motion with transitions (outfit toggles and expressions of VRChat avatars, the steering angle of a vehicle, and so on), so they have nothing to play back in Blender. -Not imported (the report lists how many were skipped): state clips (above), Humanoid clips (the body motion is stored as muscle curves, so the whole clip is skipped, including its other curves), +Not imported (the report lists how many were skipped): state clips (above), Humanoid clips (the body motion is stored as muscle curves, so the whole clip is skipped, including its other curves; the original motion is usually in an FBX in the package, which is imported as above), curves on bones, clips that only animate the object they are played on (no path, so the object is unknown), and curves on materials or object references. Clips whose paths match no imported object are skipped too. Animator Controllers are not read. diff --git a/README_ja.md b/README_ja.md index a37303d..26a71a7 100644 --- a/README_ja.md +++ b/README_ja.md @@ -8,7 +8,7 @@ Unity 側のマテリアル設定とテクスチャを反映した状態で配置する Extension です。 - 対応 Blender: 4.5 以降(開発は 5.2 LTS、検証は 4.5 LTS と 5.2 LTS) -- 読み込むもの: FBX / OBJ / glTF / VRM / Collada(Blender 4.5 のみ。5.0 で削除された)/ 同梱 .blend(オプトイン)、`.mat`(lilToon / MToon / Poiyomi / Standard / URP / HDRP / VRChat Mobile(Quest 向け)シェーダー、その他は一般規則で最善努力)、参照テクスチャ、Generic なアニメーションクリップ(`.anim` のシェイプキー・表示の切り替え・Transform。ミュートした NLA トラックの Action にする) +- 読み込むもの: FBX / OBJ / glTF / VRM / Collada(Blender 4.5 のみ。5.0 で削除された)/ 同梱 .blend(オプトイン)、`.mat`(lilToon / MToon / Poiyomi / Standard / URP / HDRP / VRChat Mobile(Quest 向け)シェーダー、その他は一般規則で最善努力)、参照テクスチャ、アニメーション(ミュートした NLA トラックの Action にする。モデルの中のテイクを Unity のクリップどおりに分けたもの(同じ骨格のモーションだけの FBX は 1 体のアーマチュアにまとめる)と、Generic な `.anim` のシェイプキー・表示の切り替え・Transform) - 読み込まないもの: シェーダー本体、C#、Humanoid のアニメーションクリップ、ボーンのアニメーションのカーブ、Animator Controller、Expression メニュー等。prefab の階層、ライト、カメラは、シーンを読み込むときだけ再現します - VRM: [VRM format](https://extensions.blender.org/add-ons/vrm/) add-on が入っていれば `.vrm` はそちらに委譲します(MToon マテリアル、Humanoid リグ、スプリングボーン、表情は add-on が再現)。無ければ glTF インポーターで読み、同梱の `.mat` からマテリアルを組み直します。 @@ -77,8 +77,8 @@ Settings > Pages > Source を "GitHub Actions" にしてください。 | (常に表示) | Material Mode | `Auto`(トゥーン系は Toon、PBR 系は Principled)/ `Principled BSDF` / `Toon (Node Group)` / `Unlit (Emission)` / `Names Only` | | | Scale | モデルのインポーターに渡すスケール | | Model | FBX Importer | 新 C++ インポーター優先(`Auto`)/ 明示指定 | -| | Import Animation / Ignore Leaf Bones | FBX インポーターに渡す(既定はそれぞれ OFF / ON) | -| | Animation Clips | パッケージの Generic な `.anim` を、ミュートした NLA トラックの Action にする(既定 ON)。[アニメーションクリップ](#アニメーションクリップ) を参照 | +| | Animation | `Muted`(既定): モデルのテイクとパッケージの `.anim` を、ミュートした NLA トラックにする / `Active`: 同じく読み、オブジェクトごとに最初のトラックだけミュートを外す / `None`: アニメーションを読まない。[アニメーションクリップ](#アニメーションクリップ) を参照 | +| | Ignore Leaf Bones | FBX インポーターに渡す(既定 ON) | | | VRM via VRM Add-on | `.vrm` を VRM format add-on で読む(既定 ON)。add-on が無ければ glTF インポーターで読んで `.mat` から組み直す | | | Import Bundled .blend Files | パッケージ内の `.blend` からオブジェクトを append する(既定 OFF)。[セキュリティ上の注意](#セキュリティ上の注意) を参照 | | Materials | Force Opaque | Unity の Cutout / Transparent 設定を無視する | @@ -154,6 +154,25 @@ Windows のパスの長さの上限に当たらないよう、フルパスが長 ### アニメーションクリップ +アニメーションは、クリップの名前の NLA トラックを**ミュート**で足すので、読み込んだ直後の見た目は変わりません。確かめるときは +NLA エディターでトラックのミュートを外すか、星のアイコンでソロにします。ストリップを選んで Tab で Action を編集することもできます。 +Animation を `Active` にすると、オブジェクトごとに最初の 1 本だけミュートを外します(ミュートしていないトラックは上のものが下を +上書きするので、1 本だけにしています)。 + +#### モデルの中のモーション + +FBX の中のアニメーションのテイク(モーション集や、`モデル@モーション.fbx` のファイルなど)は、Unity でモデルの `.meta` に設定した +クリップ(Model Import Settings の Animation。名前と開始・終了フレーム)に分けます。同じテイクのクリップは 1 つの Action を共有し、 +ストリップごとに自分の範囲を再生します。クリップの設定が無いモデルは、テイクごとに 1 クリップです。0.1 秒以下の短いクリップ +(T ポーズのテイクなど)は外し、FBX インポーターが付けるアクティブな Action も外します。 + +同じ骨格のモーションだけのモデル(メッシュが無く、アーマチュアが 1 体)が複数あれば、1 体のアーマチュアにまとめて、全モーションを +NLA トラックとして並べます(Models 単位)。スキンの無い FBX はファイルの既定の姿勢をレストにするので、レスト姿勢はファイルごとに +違います。残すアーマチュアでも同じ姿勢になるよう、キーを変換します。一部のボーン(武器用のボーンなど)が無い骨格もまとめます +(無いボーンはレストのまま)。シーンで同じモデルを何度も置くときは、テイクの Action を共有します。 + +#### Generic な `.anim` + パッケージの Generic なアニメーションクリップ(`.anim`)を、クリップごとに 1 つの Action にします。読むカーブは次のとおりです。 - シェイプキーの重み(`blendShape.<名前>`。Unity では 0〜100)→ シェイプキーの値(0〜1) @@ -161,16 +180,14 @@ Windows のパスの長さの上限に当たらないよう、フルパスが長 - Transform の位置・回転(クォータニオンかオイラー角)・スケール → オブジェクトの位置・回転・スケール(フレームごとに求める) クリップは対象のモデルを持たないので、カーブの階層パスがいちばん多く当てはまる読み込んだオブジェクトを、クリップを再生する -オブジェクトとみなします(同じモデルを複数置いていれば、すべてに付けます)。動かすオブジェクトとシェイプキーごとに、 -クリップの名前の NLA トラックを**ミュート**で足すので、読み込んだ直後の見た目は変わりません。確かめるときは NLA エディターで -トラックのミュートを外すか、星のアイコンでソロにします。ストリップを選んで Tab で Action を編集することもできます。 -キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップの F カーブには Cycles モディファイアーを付けます。 +オブジェクトとみなします(同じモデルを複数置いていれば、すべてに付けます)。動かすオブジェクトとシェイプキーごとに +NLA トラックを足します。キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップの F カーブには Cycles モディファイアーを付けます。 状態を切り替えるだけのクリップ(値が変わらないもの、0.1 秒以下で終わるもの)は読み込みません。Unity の Animator はこうしたクリップを ステートとして使い、動きは遷移で作ります(VRChat のアバターの衣装の切り替えや表情、車両のハンドルの角度など)。 Blender では再生しても何も動かないためです。 -読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(体の動きがマッスル値で入っているため、ほかのカーブも含めてクリップごと外します。元の FBX にモーションがあれば #276 で取り出す予定)、ボーンのカーブ、 +読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(体の動きがマッスル値で入っているため、ほかのカーブも含めてクリップごと外します。元のモーションはたいていパッケージの FBX にあり、上記のとおり読み込みます)、ボーンのカーブ、 再生するオブジェクト自身だけを動かすクリップ(パスが無く、どのオブジェクトか決められない)、マテリアルやオブジェクト参照のカーブ。 読み込んだオブジェクトにパスが当てはまらないクリップも外します。Animator Controller は読みません。 diff --git a/tests/expectations_synthetic_anim_off.json b/tests/expectations_synthetic_anim_off.json index 18bb6ec..52bc9b4 100644 --- a/tests/expectations_synthetic_anim_off.json +++ b/tests/expectations_synthetic_anim_off.json @@ -1,7 +1,7 @@ { "options": { "unit": "MODELS", - "import_clips": false + "animation": "NONE" }, "errors": 0, "clips": { diff --git a/tests/expectations_synthetic_motion.json b/tests/expectations_synthetic_motion.json new file mode 100644 index 0000000..b478962 --- /dev/null +++ b/tests/expectations_synthetic_motion.json @@ -0,0 +1,27 @@ +{ + "options": { + "unit": "MODELS" + }, + "errors": 0, + "clips": { + "count": 4, + "armatures": 2, + "take_actions": 3, + "notes_contain": [ + "skipped 1 model animation clip(s) that only switch a state", + "merged 1 motion-only armature(s)" + ], + "tracks": { + "Rig": ["Walk_Start", "Walk", "Rig|run_take"], + "CharRig": ["CharRig|wave_take"] + }, + "values": [ + { "track": "Walk_Start", "object": "Rig", "seconds": 0.2, "bone_direction": { "bone": "Spine", "vector": [0, -0.2938, 0.9559] } }, + { "track": "Walk", "object": "Rig", "seconds": 0.5, "bone_direction": { "bone": "Spine", "vector": [0, -0.7071, 0.7071] } }, + { "track": "Walk", "object": "Rig", "seconds": 1, "bone_direction": { "bone": "Spine", "vector": [0, -1, 0] } }, + { "track": "Rig|run_take", "object": "Rig", "seconds": 0, "bone_direction": { "bone": "Spine", "vector": [0, 0.4961, 0.8682] } }, + { "track": "Rig|run_take", "object": "Rig", "seconds": 1, "bone_direction": { "bone": "Spine", "vector": [0, -0.5039, 0.8638] } }, + { "track": "CharRig|wave_take", "object": "CharRig", "seconds": 1, "bone_direction": { "bone": "Spine", "vector": [0, -0.7071, 0.7071] } } + ] + } +} diff --git a/tests/expectations_synthetic_motion_active.json b/tests/expectations_synthetic_motion_active.json new file mode 100644 index 0000000..640bf15 --- /dev/null +++ b/tests/expectations_synthetic_motion_active.json @@ -0,0 +1,19 @@ +{ + "options": { + "unit": "MODELS", + "animation": "ACTIVE" + }, + "errors": 0, + "clips": { + "count": 4, + "armatures": 2, + "unmuted": { + "Rig": ["Walk_Start"], + "CharRig": ["CharRig|wave_take"] + }, + "tracks": { + "Rig": ["Walk_Start", "Walk", "Rig|run_take"], + "CharRig": ["CharRig|wave_take"] + } + } +} diff --git a/tests/expectations_synthetic_motion_none.json b/tests/expectations_synthetic_motion_none.json new file mode 100644 index 0000000..07cb38a --- /dev/null +++ b/tests/expectations_synthetic_motion_none.json @@ -0,0 +1,16 @@ +{ + "options": { + "unit": "MODELS", + "animation": "NONE" + }, + "errors": 0, + "clips": { + "count": 0, + "armatures": 3, + "take_actions": 0, + "tracks": { + "Rig": [], + "CharRig": [] + } + } +} diff --git a/tests/expectations_synthetic_motion_scene.json b/tests/expectations_synthetic_motion_scene.json new file mode 100644 index 0000000..2c4b53c --- /dev/null +++ b/tests/expectations_synthetic_motion_scene.json @@ -0,0 +1,19 @@ +{ + "options": { + "unit": "SCENES" + }, + "errors": 0, + "clips": { + "count": 1, + "take_actions": 1, + "instances": { + "CharRig": 2 + }, + "tracks": { + "CharRig": ["CharRig|wave_take"] + }, + "values": [ + { "track": "CharRig|wave_take", "object": "CharRig", "seconds": 1, "bone_direction": { "bone": "Spine", "vector": [0, -0.7071, 0.7071] } } + ] + } +} diff --git a/tests/integration_import.py b/tests/integration_import.py index 21f29ac..a770ac3 100644 --- a/tests/integration_import.py +++ b/tests/integration_import.py @@ -641,10 +641,19 @@ def _world(obj) -> Matrix: def check_clips(ctx: Context) -> None: - """パッケージの .anim から作った Action と NLA トラック(#209)。""" + """パッケージの .anim と、モデルのテイクから作った Action と NLA トラック(#209 / #276)。""" c, spec = ctx.c, ctx.exp.get("clips") if spec is None: return + if "armatures" in spec: # モーションだけのモデルをまとめた後のアーマチュアの数 + c.eq("armature count", len([o for o in bpy.data.objects if o.type == "ARMATURE"]), spec["armatures"]) + if "take_actions" in spec: # モデルのテイクから作った Action(同じモデルを何度読んでも 1 つ) + c.eq("take actions", len([a for a in bpy.data.actions if a.get("unity_take")]), spec["take_actions"]) + unmuted = spec.get("unmuted", {}) # Animation が Active のときに、ミュートを外したトラック + for name, tracks in unmuted.items(): + for obj in [o for o in bpy.data.objects if _strip_suffix(o.name) == name]: + actual = sorted(t.name for d in _clip_datablocks(obj) if d.animation_data for t in d.animation_data.nla_tracks if not t.mute) + c.eq(f"{obj.name} unmuted NLA tracks", actual, sorted(tracks)) if "count" in spec: c.eq("clip count", len(ctx.report.clips), spec["count"]) if "actions" in spec: @@ -659,7 +668,7 @@ def check_clips(ctx: Context) -> None: for obj in objects: c.eq(f"{obj.name} NLA tracks", _clip_tracks(obj), sorted(tracks)) for d in _clip_datablocks(obj): - if d.animation_data: + if d.animation_data and name not in unmuted: c.true(f"{obj.name} NLA tracks are muted", all(t.mute for t in d.animation_data.nla_tracks)) for value in spec.get("values", []): objects = [o for o in bpy.data.objects if _strip_suffix(o.name) == value["object"]] @@ -683,6 +692,14 @@ def check_clips(ctx: Context) -> None: _at_clip_time([obj, other], value["track"], value["seconds"]) distance = (_world(obj).translation - _world(other).translation).length c.close(f"{label} distance to {other.name} at {value['seconds']}s", distance, value["distance"], 1e-3) + if "bone_direction" in value: # ボーンの向き(頭から尾へのワールドの単位ベクトル) + spec_bone = value["bone_direction"] + _at_clip_time([obj], value["track"], value["seconds"]) + evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + direction = (evaluated.matrix_world.to_3x3() @ evaluated.pose.bones[spec_bone["bone"]].matrix.col[1].xyz).normalized() + error = max(abs(a - b) for a, b in zip(direction, spec_bone["vector"])) + c.true(f"{label} {spec_bone['bone']} direction at {value['seconds']}s", error < 1e-3, + f"expected {spec_bone['vector']}, got {[round(v, 4) for v in direction]}") if "rotation_delta" in value: delta = value["rotation_delta"] _at_clip_time([obj], value["track"], delta["from"]) diff --git a/tests/integration_runs.json b/tests/integration_runs.json index 57debfa..cb53ba1 100644 --- a/tests/integration_runs.json +++ b/tests/integration_runs.json @@ -8,6 +8,7 @@ { "script": "tests/make_synthetic_terrain_package.py", "blender": true, "outputs": ["synthetic_terrain.unitypackage"] }, { "script": "tests/make_synthetic_mesh_package.py", "blender": true, "outputs": ["synthetic_mesh.unitypackage"] }, { "script": "tests/make_synthetic_anim_package.py", "blender": true, "outputs": ["synthetic_anim.unitypackage"] }, + { "script": "tests/make_synthetic_motion_package.py", "blender": true, "outputs": ["synthetic_motion.unitypackage"] }, { "script": "tests/make_synthetic_nested_package.py", "blender": false, @@ -45,7 +46,11 @@ { "package": "synthetic_mesh.unitypackage", "expectations": "expectations_synthetic_mesh_models.json", "note": "FBX のマテリアルの画像が作者の PC のパスを指すモデル" }, { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim.json", "note": ".anim の Action(シェイプキー・表示の切り替え・Transform)と、読み込まないクリップの内訳" }, { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim_scene.json", "note": "シーンに 2 か所置いたモデルの両方にクリップを付ける" }, - { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim_off.json", "note": "Animation Clips を OFF にすると Action を作らない" }, + { "package": "synthetic_anim.unitypackage", "expectations": "expectations_synthetic_anim_off.json", "note": "Animation を None にすると Action を作らない" }, + { "package": "synthetic_motion.unitypackage", "expectations": "expectations_synthetic_motion.json", "note": "モデルのテイクを .meta のクリップで分け、同じ骨格のモーションだけのアーマチュアをレストを変換してまとめる" }, + { "package": "synthetic_motion.unitypackage", "expectations": "expectations_synthetic_motion_active.json", "note": "Animation が Active なら、オブジェクトごとに最初のトラックだけミュートを外す" }, + { "package": "synthetic_motion.unitypackage", "expectations": "expectations_synthetic_motion_none.json", "note": "Animation が None ならテイクを読まず、アーマチュアもまとめない" }, + { "package": "synthetic_motion.unitypackage", "expectations": "expectations_synthetic_motion_scene.json", "note": "シーンに 2 か所置いたモデルで、テイクの Action を使い回す" }, { "package": "synthetic_nested.unitypackage", "expectations": "expectations_synthetic_nested.json", "note": "入れ子のパッケージ(選ばなければ Built-in らしいもの)" }, { "package": "synthetic_nested.unitypackage", "expectations": "expectations_synthetic_nested_chosen.json", "note": "入れ子のパッケージを選んで読む" }, { "package": "synthetic_broken_model.unitypackage", "expectations": "expectations_synthetic_broken_model.json", "note": "1 つ失敗しても残りを読む" }, diff --git a/tests/make_synthetic_motion_package.py b/tests/make_synthetic_motion_package.py new file mode 100644 index 0000000..f660d4c --- /dev/null +++ b/tests/make_synthetic_motion_package.py @@ -0,0 +1,210 @@ +"""モデルの中のアニメーションのテイクを含む合成 unitypackage を生成する(Issue #276)。 + + blender -b --factory-startup --python tests/make_synthetic_motion_package.py -- <出力パス.unitypackage> + +実在アセットのデータは使わない。 + +- Motions/Walk.fbx: モーションだけ(アーマチュア Rig。ボーン Hips → Spine → Hand。末端に Hand_End)。テイクは tpose(1 フレーム)と walk_take + (30 フレームで Spine を 90° 曲げる)。.meta の clipAnimations で tpose・Walk_Start(0〜10)・Walk(0〜30、ループ)に分ける。 +- Motions/Run.fbx: モーションだけ。骨格は Walk の部分集合(Hand が無い)。書き出したときの姿勢がレストになるので、レストも Walk と違う。テイク run_take + (30 フレームで Spine を 60° 曲げる)。clipAnimations は無い(テイクがそのままクリップになる)。 +- Models/Character.fbx: アーマチュア CharRig とスキンメッシュ Body。テイク wave_take。メッシュがあるのでまとめない。 +- Scenes/Two.unity: Character.fbx を 2 か所に置く(テイクの Action を使い回す)。 + +曲げる Action はクォータニオンの成分を LINEAR でつなぐので、角度は時間に比例しない(Walk の 0.2 秒は 18° ではなく 17.086°)。 +期待値(tests/expectations_synthetic_motion*.json)のボーンの向きは、この補間で求めた値。 +""" + +from __future__ import annotations + +import math +import sys +import tempfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +import bpy # noqa: E402 + +from tests.make_synthetic_package import guid_of, write_package # noqa: E402 +from tests.unity_yaml_writer import HEADER, ROOT_TRANSFORM, instance, mod # noqa: E402 + + +def _armature(name: str, bones: list[tuple[str, tuple, tuple, str | None]]) -> bpy.types.Object: + bpy.ops.object.armature_add(location=(0, 0, 0)) + armature = bpy.context.object + armature.name = armature.data.name = name + bpy.ops.object.mode_set(mode="EDIT") + edit = armature.data.edit_bones + edit.remove(edit[0]) + for bone_name, head, tail, parent in bones: + bone = edit.new(bone_name) + bone.head, bone.tail = head, tail + if parent: + bone.parent = edit[parent] + bone.use_connect = False + bpy.ops.object.mode_set(mode="OBJECT") + return armature + + +def _bend(armature, action_name: str, bone: str, degrees: float, frames: int) -> bpy.types.Action: + """``bone`` をローカルの X まわりに 0 → ``degrees`` 曲げる Action(フレーム 1 から ``frames`` フレーム)。""" + action = bpy.data.actions.new(action_name) + armature.animation_data_create() + armature.animation_data.action = action + pose_bone = armature.pose.bones[bone] + pose_bone.rotation_mode = "QUATERNION" + for frame, angle in ((1, 0.0), (1 + frames, math.radians(degrees))): + pose_bone.rotation_quaternion = (math.cos(angle / 2), math.sin(angle / 2), 0, 0) + pose_bone.keyframe_insert("rotation_quaternion", frame=frame) + for fcurve in _fcurves(action): + for point in fcurve.keyframe_points: + point.interpolation = "LINEAR" + action.use_fake_user = True + return action + + +def _fcurves(action): + # Blender 5 でも action.fcurves は残っているが、スロット付きの Action では空を返す + return [fc for layer in action.layers for strip in layer.strips for bag in strip.channelbags for fc in bag.fcurves] + + +def _hold(armature, action_name: str, frames: int) -> bpy.types.Action: + """どこも動かさない Action(T ポーズのテイク)。""" + action = bpy.data.actions.new(action_name) + armature.animation_data.action = action + for pose_bone in armature.pose.bones: + pose_bone.rotation_mode = "QUATERNION" + pose_bone.rotation_quaternion = (1, 0, 0, 0) + for frame in (1, 1 + frames): + pose_bone.keyframe_insert("rotation_quaternion", frame=frame) + action.use_fake_user = True + return action + + +def _export(path: Path, objects) -> None: + bpy.ops.object.select_all(action="DESELECT") + for obj in objects: + obj.select_set(True) + bpy.ops.export_scene.fbx( + filepath=str(path), use_selection=True, add_leaf_bones=False, bake_anim=True, bake_anim_use_all_actions=True, + bake_anim_use_nla_strips=False, bake_anim_simplify_factor=0.0, + ) + + +def _reset() -> None: + bpy.ops.wm.read_factory_settings(use_empty=True) + bpy.context.scene.render.fps = 30 + + +# 読み込みは Ignore Leaf Bones(既定 ON)で末端のボーンを消すので、チェーンの先に末端のボーン(*_End)を置く +SPINE = [("Hips", (0, 0, 0.8), (0, 0, 1.0), None), ("Spine", (0, 0, 1.0), (0, 0, 1.4), "Hips")] + + +def export_walk(path: Path) -> None: + _reset() + rig = _armature("Rig", SPINE + [("Hand", (0, 0, 1.4), (0, 0, 1.6), "Spine"), ("Hand_End", (0, 0, 1.6), (0, 0, 1.7), "Hand")]) + rig.animation_data_create() + _hold(rig, "tpose", 1) + _bend(rig, "walk_take", "Spine", 90, 30) + rig.animation_data.action = None + _export(path, [rig]) + + +def export_run(path: Path) -> None: + _reset() + # Spine のレストを Y の向きに傾ける(Walk とレストが違う) + rig = _armature("Rig", [SPINE[0], ("Spine", (0, 0, 1.0), (0, 0.2, 1.35), "Hips"), ("Spine_End", (0, 0.2, 1.35), (0, 0.25, 1.45), "Spine")]) + rig.animation_data_create() + _bend(rig, "run_take", "Spine", 60, 30) + rig.animation_data.action = None + _export(path, [rig]) + + +def export_character(path: Path) -> None: + _reset() + rig = _armature("CharRig", SPINE + [("Spine_End", (0, 0, 1.4), (0, 0, 1.5), "Spine")]) + bpy.ops.mesh.primitive_cube_add(size=0.4, location=(0, 0, 1.2)) + body = bpy.context.object + body.name = body.data.name = "Body" + body.vertex_groups.new(name="Spine").add([v.index for v in body.data.vertices], 1.0, "REPLACE") + body.parent = rig + body.modifiers.new("Armature", "ARMATURE").object = rig + rig.animation_data_create() + _bend(rig, "wave_take", "Spine", 45, 30) + rig.animation_data.action = None + _export(path, [rig, body]) + + +def takes_of(path: Path) -> dict[str, tuple[float, float]]: + """書き出した FBX を読み直して、テイクの名前 → Unity のフレーム番号の範囲(Blender のフレーム - 1)。""" + _reset() + bpy.ops.wm.fbx_import(filepath=str(path), use_anim=True) + return {a.name: (a.frame_range[0] - 1, a.frame_range[1] - 1) for a in bpy.data.actions} + + +def motion_meta(guid: str, clips: list[tuple[str, str, float, float, bool]]) -> str: + lines = ["fileFormatVersion: 2", f"guid: {guid}", "ModelImporter:", " serializedVersion: 22200", " externalObjects: {}", + " materials:", " materialImportMode: 2", " animations:", " importAnimatedCustomProperties: 0"] + if clips: + lines.append(" clipAnimations:") + for name, take, first, last, loop in clips: + lines += [ + " - serializedVersion: 16", + f" name: {name}", + f" takeName: {take}", + f" firstFrame: {first:g}", + f" lastFrame: {last:g}", + " wrapMode: 0", + f" loopTime: {1 if loop else 0}", + ] + else: + lines.append(" clipAnimations: []") + lines += [" meshes:", " globalScale: 1", " useFileScale: 1", " importAnimation: 1", " animationType: 2"] + return "\n".join(lines) + "\n" + + +def main() -> None: + argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [] + out = Path(argv[0]) if argv else REPO_ROOT / "_local" / "unitypackages" / "synthetic_motion.unitypackage" + tmp = Path(tempfile.mkdtemp(prefix="synthetic_motion_")) + entries: dict[str, tuple[str, bytes | None, str | None]] = {} + + def add(pathname: str, asset: bytes, meta: str) -> str: + guid = guid_of(pathname) + entries[guid] = (pathname, asset, meta) + return guid + + export_walk(tmp / "walk.fbx") + export_run(tmp / "run.fbx") + export_character(tmp / "character.fbx") + walk_takes = takes_of(tmp / "walk.fbx") + print("walk takes:", walk_takes, "run takes:", takes_of(tmp / "run.fbx"), "character takes:", takes_of(tmp / "character.fbx")) + tpose = next(name for name in walk_takes if name.endswith("tpose")) + walk = next(name for name in walk_takes if name.endswith("walk_take")) + start = walk_takes[walk][0] + walk_clips = [ + ("tpose", tpose, walk_takes[tpose][0], walk_takes[tpose][1], False), + ("Walk_Start", walk, start, start + 10, False), + ("Walk", walk, start, start + 30, True), + ] + path = "Assets/Synthetic/Motions/Walk.fbx" + add(path, (tmp / "walk.fbx").read_bytes(), motion_meta(guid_of(path), walk_clips)) + path = "Assets/Synthetic/Motions/Run.fbx" + add(path, (tmp / "run.fbx").read_bytes(), motion_meta(guid_of(path), [])) + path = "Assets/Synthetic/Models/Character.fbx" + character = add(path, (tmp / "character.fbx").read_bytes(), motion_meta(guid_of(path), [])) + scene_path = "Assets/Synthetic/Scenes/Two.unity" + scene = HEADER + "".join([ + instance(100, character, 0, [mod(ROOT_TRANSFORM, character, "m_LocalPosition.x", -2)]), + instance(200, character, 0, [mod(ROOT_TRANSFORM, character, "m_LocalPosition.x", 2)]), + ]) + add(scene_path, scene.encode(), f"fileFormatVersion: 2\nguid: {guid_of(scene_path)}\nDefaultImporter:\n externalObjects: {{}}\n") + write_package(out, entries) + print(f"wrote {out}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_meta.py b/tests/test_meta.py index 743329c..01ae303 100644 --- a/tests/test_meta.py +++ b/tests/test_meta.py @@ -86,6 +86,28 @@ def test_bake_axis_conversion(self): info = ModelImporterInfo.from_meta("ModelImporter:\n meshes:\n bakeAxisConversion: 0\n") self.assertFalse(info.bake_axis_conversion) + def test_clip_animations(self): + # 32 RPG Animations の Jumps.fbx と同じ形(1 つのテイクを 2 つのクリップに分ける。#276) + text = ( + "ModelImporter:\n" + " animations:\n" + " clipAnimations:\n" + " - serializedVersion: 16\n name: tpose\n takeName: tpose\n firstFrame: 0\n lastFrame: 1\n loopTime: 0\n" + " - serializedVersion: 16\n name: Jump_Up\n takeName: human_male_jumpup\n firstFrame: 2\n lastFrame: 18\n loopTime: 1\n" + " - serializedVersion: 16\n name: Broken\n takeName: x\n firstFrame: 5\n lastFrame: 2\n" + " - serializedVersion: 16\n name: 123\n takeName: Take 001\n firstFrame: 0.5\n lastFrame: 30\n" + " importAnimation: 1\n" + ) + info = ModelImporterInfo.from_meta(text) + self.assertTrue(info.import_animation) + self.assertEqual( + [(c.name, c.take, c.first_frame, c.last_frame, c.loop) for c in info.clips], + [("tpose", "tpose", 0.0, 1.0, False), ("Jump_Up", "human_male_jumpup", 2.0, 18.0, True), ("123", "Take 001", 0.5, 30.0, False)], + ) + info = ModelImporterInfo.from_meta("ModelImporter:\n animations:\n clipAnimations: []\n importAnimation: 0\n") + self.assertFalse(info.import_animation) + self.assertEqual(info.clips, []) + def test_resolve_material(self): info = ModelImporterInfo.from_meta(MODEL_META) self.assertEqual(info.resolve_material("MatA"), "d" * 32) diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 2505f5f..18d080a 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -200,11 +200,12 @@ def slot_for(datablock: bpy.types.ID, id_type: str, label: str): def _add_track(self, datablock, action, slot, name: str) -> None: animation_data = datablock.animation_data or datablock.animation_data_create() track = animation_data.nla_tracks.new() + active = self.session.opts.animation == "ACTIVE" and not any(not t.mute for t in animation_data.nla_tracks) track.name = name - track.mute = True nla_strip = track.strips.new(name, self.frame_start, action) if nla_strip.action_slot != slot: nla_strip.action_slot = slot + track.mute = not active # 各種のカーブ ------------------------------------------------------ diff --git a/unitypackage_loader/blender/fbx_motion.py b/unitypackage_loader/blender/fbx_motion.py new file mode 100644 index 0000000..7151610 --- /dev/null +++ b/unitypackage_loader/blender/fbx_motion.py @@ -0,0 +1,434 @@ +"""モデル(FBX など)の中のアニメーションのテイクを、Unity のクリップの設定どおりに NLA に並べる(#276)。 + +Blender の FBX インポーターは、テイクごとにテイクの名前の Action を作り、最初のテイクをアクティブな Action にする。 +Unity はモデルの .meta の ``clipAnimations`` で、テイクから名前・範囲を決めてクリップを切り出す(無ければテイクごとに全体)。 +ここでは読み込んだ直後に、クリップごとに範囲を絞った NLA ストリップを、クリップの名前のトラックに置く。 + +- 同じテイクの Action を範囲違いのストリップで共有する(クリップごとに Action を複製しない)。 +- 状態を切り替えるだけの短いクリップ(T ポーズなど。``core.animation.STATE_CLIP_MAX_LENGTH`` 以下)は置かない。 +- どのクリップにも使われないテイクの Action は消す。アクティブな Action は外す(読み込んだ直後の見た目を、アニメーションを + 読まないときと同じにする)。 +- 同じモデルを何度も読む(シーンの配置ごと)ときは、最初に読んだときの Action を使い回し、新しく作られた分は消す。 +- モーションだけのモデル(メッシュが無く、アーマチュアが 1 体)が同じ骨格で並ぶとき(Models 単位)は、アーマチュアを 1 体にまとめて + 全部のトラックを載せる(``merge_motion_rigs``)。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field + +import bpy +from mathutils import Euler, Matrix, Quaternion, Vector + +from ..core.animation import STATE_CLIP_MAX_LENGTH +from ..core.meta import ModelClip, ModelImporterInfo, strip_numeric_suffix +from .model_import import FBX_NODE_PROP, MODEL_GUID_PROP, is_removed + +# Blender の FBX インポーターの anim_offset の既定値(FBX のフレーム 0 を Blender のフレーム 1 に置く) +ANIM_OFFSET = 1.0 +# Action に残す、元のテイクの名前とモデルの GUID +TAKE_PROP = "unity_take" +TAKE_MODEL_PROP = "unity_take_model" + +MODE_MUTED = "MUTED" +MODE_ACTIVE = "ACTIVE" +MODE_NONE = "NONE" + +# keyframe_points の interpolation に foreach_set で渡す LINEAR の値 +_LINEAR = bpy.types.Keyframe.bl_rna.properties["interpolation"].enum_items["LINEAR"].value + + +@dataclass +class MotionStats: + """モデルのテイクから作ったクリップの集計(レポートに書く)。""" + + clips: list[str] = field(default_factory=list) # 置いたクリップ("モデルのパス: クリップ名") + state: int = 0 # 状態を切り替えるだけで置かなかったクリップ + missing_takes: list[str] = field(default_factory=list) # .meta のクリップのテイクが見つからなかったもの + merged_rigs: int = 0 # 1 体にまとめて消したアーマチュア + + def report_lines(self): + if self.state: + yield f"skipped {self.state} model animation clip(s) that only switch a state (0.1 s or shorter, e.g. a T-pose)" + if self.missing_takes: + yield f"{len(self.missing_takes)} model animation clip(s) refer to a take that was not found in the model" + if self.merged_rigs: + yield f"merged {self.merged_rigs} motion-only armature(s) with the same skeleton into one" + + +@dataclass(frozen=True) +class _Clip: + name: str + action: bpy.types.Action + start: float # Blender のフレーム(Action の中の範囲) + end: float + + +def _slot_owner(slot, objects: list[bpy.types.Object]): + """スロットの対象(オブジェクトかシェイプキー)を、読み込んだオブジェクトから探す。""" + name = slot.identifier[2:] + if slot.target_id_type == "OBJECT": + for obj in objects: + if obj.get(FBX_NODE_PROP, obj.name) == name or obj.name == name: + return obj + return None + if slot.target_id_type == "KEY": + for obj in objects: + key = getattr(obj.data, "shape_keys", None) if obj.data is not None else None + if key is not None and key.name == name: + return key + return None + + +def _users(action: bpy.types.Action, objects: list[bpy.types.Object]) -> list[tuple[bpy.types.ID, bpy.types.ActionSlot]]: + users = [] + for slot in action.slots: + owner = _slot_owner(slot, objects) + if owner is None and len(action.slots) == 1: + # スロットの名前が付け替わっていても、アニメーションを持つオブジェクトが 1 つなら、それとみなす + animated = [o for o in objects if o.animation_data is not None and o.animation_data.action == action] + owner = animated[0] if len(animated) == 1 else None + if owner is not None: + users.append((owner, slot)) + return users + + +def _take_of(action: bpy.types.Action) -> str: + return str(action.get(TAKE_PROP) or strip_numeric_suffix(action.name)) + + +def _take_name(action_name: str, known: set[str]) -> str: + """Action の名前から元のテイクの名前を求める。.meta のテイク名と完全一致すればそのまま、無ければ Blender の連番を外す。""" + return action_name if action_name in known else strip_numeric_suffix(action_name) + + +class MotionBuilder: + """読み込みの間、モデルのテイクから NLA を作る(モデルを読み込むたびに ``arrange`` を呼ぶ)。""" + + def __init__(self, scene: bpy.types.Scene, mode: str): + self.scene = scene + self.mode = mode + self.stats = MotionStats() + # モデルの GUID → テイクの名前 → 最初に読んだときの Action(2 回目以降に使い回す) + self._actions: dict[str, dict[str, bpy.types.Action]] = {} + + def arrange(self, model_guid: str, pathname: str, info: ModelImporterInfo | None, + objects: list[bpy.types.Object], actions: list[bpy.types.Action]) -> None: + if not actions: + return + if info is not None and not info.import_animation: + # Unity でアニメーションを取り込まない設定のモデル(Unity にクリップが無い) + for obj in objects: + if obj.animation_data is not None: + obj.animation_data.action = None + bpy.data.batch_remove(actions) + return + known = {c.take for c in info.clips} if info is not None else set() + takes = {a.as_pointer(): _take_name(a.name, known) for a in actions} + cached = self._actions.get(model_guid) + if cached is not None and any(is_removed(a) for a in cached.values()): + cached = None # 前の読み込みが失敗して片付けで消えた + first_time = cached is None + if first_time: + cached = self._actions[model_guid] = {} + for action in actions: + action[TAKE_PROP] = takes[action.as_pointer()] + action[TAKE_MODEL_PROP] = model_guid + cached.setdefault(takes[action.as_pointer()], action) + # 新しい Action の (対象, スロットの識別子) を、テイクの名前ごとに控える(使い回すときは、元の Action の同じ識別子のスロットを使う) + targets: dict[str, list[tuple[bpy.types.ID, str]]] = {} + for action in actions: + targets.setdefault(takes[action.as_pointer()], []).extend((owner, slot.identifier) for owner, slot in _users(action, objects)) + for obj in objects: + key = getattr(obj.data, "shape_keys", None) if obj.data is not None else None + for owner in (obj, key): + if owner is not None and owner.animation_data is not None: + owner.animation_data.action = None + clips = self._clips(info, cached, count=first_time) + used: set[str] = set() + for clip in clips: + take = _take_of(clip.action) + for owner, identifier in targets.get(take, []): + slot = clip.action.slots.get(identifier) + if slot is None: + continue + self._add_track(owner, clip, slot) + used.add(take) + if first_time: + self.stats.clips.append(f"{pathname}: {clip.name}") + removed = [a for a in actions if not (first_time and _take_of(a) in used and cached.get(_take_of(a)) == a)] + if first_time: + # どのクリップにも使われなかったテイクは、使い回しの表からも外す + for take in [t for t in cached if t not in used]: + del cached[take] + if removed: + bpy.data.batch_remove(removed) + + def _clips(self, info: ModelImporterInfo | None, cached: dict[str, bpy.types.Action], count: bool = True) -> list[_Clip]: + """置くクリップ。``count`` なら、外したものをレポートに数える(同じモデルの 2 回目以降の読み込みでは数えない)。""" + fps = self.scene.render.fps / (self.scene.render.fps_base or 1.0) + settings: list[ModelClip] = list(info.clips) if info is not None else [] + clips: list[_Clip] = [] + if not settings: + for take, action in cached.items(): + start, end = action.frame_range + settings.append(ModelClip(take, take, start - ANIM_OFFSET, end - ANIM_OFFSET)) + for setting in settings: + action = cached.get(setting.take) + if action is None: + if count: + self.stats.missing_takes.append(setting.name) + continue + if (setting.last_frame - setting.first_frame) / max(fps, 1e-6) <= STATE_CLIP_MAX_LENGTH: + if count: + self.stats.state += 1 + continue + clips.append(_Clip(setting.name, action, setting.first_frame + ANIM_OFFSET, setting.last_frame + ANIM_OFFSET)) + return clips + + def _add_track(self, owner: bpy.types.ID, clip: _Clip, slot) -> None: + animation_data = owner.animation_data or owner.animation_data_create() + active = self.mode == MODE_ACTIVE and not any(not t.mute for t in animation_data.nla_tracks) + track = animation_data.nla_tracks.new() + track.name = clip.name + strip = track.strips.new(clip.name, int(self.scene.frame_start), clip.action) + if strip.action_slot != slot: + strip.action_slot = slot + set_strip_range(strip, clip.start, clip.end) + track.mute = not active + + +def set_strip_range(strip, start: float, end: float) -> None: + """ストリップが使う Action の範囲を変え、ストリップの長さをそれに合わせる(置く位置は変えない)。""" + begin = strip.frame_start + if start >= strip.action_frame_end: + strip.action_frame_end = end + strip.action_frame_start = start + else: + strip.action_frame_start = start + strip.action_frame_end = end + strip.frame_start = begin + strip.frame_end = begin + (end - start) * strip.scale * strip.repeat + + +# --------------------------------------------------------------------------- +# モーションだけのモデルのアーマチュアをまとめる +# --------------------------------------------------------------------------- + +# 骨格・配置が同じとみなす行列の差 +_TOLERANCE = 1e-4 + + +def _skeleton(armature: bpy.types.Object) -> tuple: + """ボーンの名前と親の組(骨格が同じかの判定に使う)。""" + return tuple(sorted((b.name, b.parent.name if b.parent else "") for b in armature.data.bones)) + + +def _close(a, b, tolerance: float = _TOLERANCE) -> bool: + return all(abs(x - y) <= tolerance for ra, rb in zip(a, b) for x, y in zip(ra, rb)) + + +def _placement(armature: bpy.types.Object) -> Matrix: + """アーマチュアを置いた場所(親のワールドの行列)。アーマチュア自身の Transform は、FBX のルートのボーンがオブジェクトになった + もの(Everyday Motion Pack の Bip001)だとファイルの最初のフレームの値で、モーションごとに違うので比べない。""" + return armature.parent.matrix_world.copy() if armature.parent else Matrix.Identity(4) + + +def _relative_rest(bone) -> Matrix: + return bone.parent.matrix_local.inverted_safe() @ bone.matrix_local if bone.parent else bone.matrix_local.copy() + + +def motion_rigs(objects: list[bpy.types.Object]) -> dict[str, bpy.types.Object]: + """モデルの GUID → モーションだけのモデルのアーマチュア(メッシュが無く、アーマチュアが 1 体で、NLA のトラックを持つもの)。""" + by_model: dict[str, list[bpy.types.Object]] = {} + for obj in objects: + guid = obj.get(MODEL_GUID_PROP) + if guid: + by_model.setdefault(str(guid), []).append(obj) + rigs = {} + for guid, members in by_model.items(): + if any(o.type not in ("ARMATURE", "EMPTY") for o in members): + continue + armatures = [o for o in members if o.type == "ARMATURE"] + if len(armatures) == 1 and armatures[0].animation_data is not None and armatures[0].animation_data.nla_tracks: + rigs[guid] = armatures[0] + return rigs + + +def merge_motion_rigs(objects: list[bpy.types.Object], model_order: list[str]) -> list[bpy.types.Object]: + """同じ骨格のモーションだけのアーマチュアを 1 体にまとめ、消すべきオブジェクトを返す。 + + 骨格(ボーンの名前と親子)と、アーマチュアのワールドの行列が同じものをまとめる。骨格は、ボーンの多いほうに少ないほうが + 含まれていればよい(武器を持たせるボーンが無いモーションなど。無いボーンはレストのまま)。残すのはボーンがいちばん多く、 + その中で先に読んだモデルのアーマチュア。スキンの無い FBX は、ファイルの既定の姿勢を + レストにするので、レスト姿勢はファイルごとに違う。そのため、残すアーマチュアのレストで同じ姿勢になるようにキーを変換した + Action を作って、トラックを写す(``retarget_action``)。消すのは、まとめたモデルの全オブジェクト(アーマチュアと、その上の Empty)。 + """ + rigs = motion_rigs(objects) + order = {guid: i for i, guid in enumerate(model_order)} + groups: list[list[tuple[str, bpy.types.Object]]] = [] + ranked = sorted(rigs.items(), key=lambda item: (-len(item[1].data.bones), order.get(item[0], len(order)))) + for guid, armature in ranked: + for group in groups: + first = group[0][1] + if set(_skeleton(armature)) <= set(_skeleton(first)) and _close(_placement(first), _placement(armature)): + group.append((guid, armature)) + break + else: + groups.append([(guid, armature)]) + removed_models: set[str] = set() + converted: dict[tuple[int, int], bpy.types.Action] = {} + for members in groups: + if len(members) < 2: + continue + keeper = members[0][1] + for guid, armature in members[1:]: + for track in armature.animation_data.nla_tracks: + for strip in track.strips: + key = (strip.action.as_pointer(), keeper.as_pointer()) + if key not in converted: + converted[key] = retarget_action(strip.action, strip.action_slot, armature, keeper) + copy_track(keeper.animation_data, track, strip, converted[key]) + removed_models.add(guid) + return [o for o in objects if str(o.get(MODEL_GUID_PROP, "")) in removed_models] + + +def copy_track(animation_data, track, strip, action: bpy.types.Action) -> None: + """``strip`` と同じ範囲・名前のトラックを ``animation_data`` に足す(Action は ``action`` に差し替える)。""" + has_active = any(not t.mute for t in animation_data.nla_tracks) + new_track = animation_data.nla_tracks.new() + new_track.name = track.name + new_strip = new_track.strips.new(strip.name, int(strip.frame_start), action) + slot = action.slots.get(strip.action_slot.identifier) if strip.action_slot is not None else None + if slot is not None and new_strip.action_slot != slot: + new_strip.action_slot = slot + set_strip_range(new_strip, strip.action_frame_start, strip.action_frame_end) + new_track.mute = track.mute or has_active + + +_BONE_PATH = re.compile(r'^pose\.bones\["((?:[^"\\]|\\.)*)"\]\.(location|rotation_quaternion|rotation_euler|scale)$') + + +def retarget_action(action: bpy.types.Action, slot, source: bpy.types.Object, target: bpy.types.Object) -> bpy.types.Action: + """``source`` のレストで作られた ``action`` を、``target`` のレストで同じ姿勢になる Action にする。 + + ボーンのローカルの行列 B(レストからの差分)は、親からの相対のレスト R と合わせて R·B が姿勢を決める。レストが R' のボーンで + 同じ姿勢にするには B' = R'⁻¹·R·B。R が R' と同じボーンのカーブはそのまま写し、違うボーンはキーの時刻ごとに求め直す + (補間は LINEAR。FBX のモーションはフレームごとにキーがあるので、見た目は変わらない)。 + + オブジェクトの Transform のカーブは絶対値なのでそのまま使う。動かさないチャンネルは ``source`` の値を一定のキーで足す + (残すアーマチュアの値のままにしない)。 + """ + corrections: dict[str, Matrix] = {} + for bone in source.data.bones: + other = target.data.bones.get(bone.name) + if other is None: + continue + correction = _relative_rest(other).inverted_safe() @ _relative_rest(bone) + if not _close(correction, Matrix.Identity(4), 1e-5): + corrections[bone.name] = correction + same_basis = _close(source.matrix_basis, target.matrix_basis, _TOLERANCE) and source.rotation_mode == target.rotation_mode + if not corrections and same_basis: + return action + new = action.copy() + new.name = action.name + for key in (TAKE_PROP, TAKE_MODEL_PROP): + if key in action: + new[key] = action[key] + for layer in new.layers: + for strip in layer.strips: + for channelbag in strip.channelbags: + _retarget_channelbag(channelbag, corrections, target) + if not same_basis and channelbag.slot.target_id_type == "OBJECT": + _hold_object_transform(channelbag, source, target) + return new + + +def _hold_object_transform(channelbag, source: bpy.types.Object, target: bpy.types.Object) -> None: + """``channelbag`` が動かさないオブジェクトの Transform のチャンネルに、``source`` の値の一定のキーを足す。""" + location, rotation, scale = source.matrix_basis.decompose() + mode = target.rotation_mode + if mode == "QUATERNION": + rotation_path, rotation_values = "rotation_quaternion", tuple(rotation) + elif mode == "AXIS_ANGLE": + axis, angle = rotation.to_axis_angle() + rotation_path, rotation_values = "rotation_axis_angle", (angle, *axis) + else: + rotation_path, rotation_values = "rotation_euler", tuple(rotation.to_euler(mode)) + existing = {(fc.data_path, fc.array_index) for fc in channelbag.fcurves} + animated = {path for path, _ in existing} + for path, values in (("location", tuple(location)), (rotation_path, rotation_values), ("scale", tuple(scale))): + if path == rotation_path and animated & {"rotation_quaternion", "rotation_euler", "rotation_axis_angle"}: + continue + for index, value in enumerate(values): + if (path, index) in existing: + continue + fcurve = channelbag.fcurves.new(path, index=index) + fcurve.keyframe_points.insert(1.0, value) + + +def _retarget_channelbag(channelbag, corrections: dict[str, Matrix], target: bpy.types.Object) -> None: + by_bone: dict[str, dict[str, dict[int, bpy.types.FCurve]]] = {} + for fcurve in channelbag.fcurves: + match = _BONE_PATH.match(fcurve.data_path) + if match and match.group(1).replace('\\"', '"') in corrections: + by_bone.setdefault(match.group(1), {}).setdefault(match.group(2), {})[fcurve.array_index] = fcurve + for escaped, channels in by_bone.items(): + name = escaped.replace('\\"', '"') + correction = corrections[name] + pose_bone = target.pose.bones.get(name) + mode = pose_bone.rotation_mode if pose_bone is not None else "QUATERNION" + times = sorted({k.co.x for curves in channels.values() for fc in curves.values() for k in fc.keyframe_points}) + if not times: + continue + + def value(prop: str, index: int, frame: float, default: float) -> float: + fcurve = channels.get(prop, {}).get(index) + return fcurve.evaluate(frame) if fcurve is not None else default + + samples = [] + previous = None + for frame in times: + location = Vector([value("location", i, frame, 0.0) for i in range(3)]) + scale = Vector([value("scale", i, frame, 1.0) for i in range(3)]) + if "rotation_quaternion" in channels: + rotation = Quaternion([value("rotation_quaternion", i, frame, 1.0 if i == 0 else 0.0) for i in range(4)]) + else: + order = mode if mode not in ("QUATERNION", "AXIS_ANGLE") else "XYZ" + rotation = Euler([value("rotation_euler", i, frame, 0.0) for i in range(3)], order).to_quaternion() + basis = correction @ Matrix.LocRotScale(location, rotation, scale) + loc, rot, sca = basis.decompose() + if previous is not None and previous.dot(rot) < 0: + rot.negate() + previous = rot + samples.append((frame, loc, rot, sca)) + for curves in channels.values(): + for fcurve in curves.values(): + channelbag.fcurves.remove(fcurve) + path = f'pose.bones["{escaped}"]' + euler_order = mode if mode not in ("QUATERNION", "AXIS_ANGLE") else None + columns = [("location", 3, lambda s, i: s[1][i]), ("scale", 3, lambda s, i: s[3][i])] + if euler_order is None: + columns.append(("rotation_quaternion", 4, lambda s, i: s[2][i])) + else: + eulers = [] + last = None + for sample in samples: + euler = sample[2].to_euler(euler_order, last) if last is not None else sample[2].to_euler(euler_order) + eulers.append(euler) + last = euler + lookup = {id(s): e for s, e in zip(samples, eulers)} + columns.append(("rotation_euler", 3, lambda s, i: lookup[id(s)][i])) + for prop, size, get in columns: + for index in range(size): + fcurve = channelbag.fcurves.new(f"{path}.{prop}", index=index) + fcurve.group = channelbag.groups.get(name) or channelbag.groups.new(name) + points = fcurve.keyframe_points + points.add(len(samples)) + flat = [] + for sample in samples: + flat += [sample[0], get(sample, index)] + points.foreach_set("co", flat) + points.foreach_set("interpolation", [_LINEAR] * len(samples)) + fcurve.update() diff --git a/unitypackage_loader/blender/importer.py b/unitypackage_loader/blender/importer.py index 3bd1cd5..125cc9f 100644 --- a/unitypackage_loader/blender/importer.py +++ b/unitypackage_loader/blender/importer.py @@ -39,6 +39,7 @@ from . import outline as outline_builder from .animation import ClipImporter from .animation import report_lines as clip_report_lines +from .fbx_motion import MODE_NONE, MotionBuilder, merge_motion_rigs from .log import record_failure, warn_skipped from .model_import import ( FBX_NODE_PROP, @@ -260,6 +261,8 @@ def __init__(self, context, filepath, opts, progress, prepared, report): # 直前の import_model で、中のオブジェクトの fileID を計算したもの(表示の上書きと削除を当てる。#172) self.last_matcher: PartMatcher | None = None self.failed_models: set[str] = set() # 読み込みに失敗したモデル(同じモデルを何度も試さない) + # モデルの中のアニメーションのテイクを NLA に並べる(#276)。アニメーションを読まないなら None + self.motions = MotionBuilder(self.scene, opts.animation) if opts.animation != MODE_NONE else None self.primitive_meshes: dict[str, bpy.types.Mesh] = {} # 組み込みメッシュの種類 → この回で作ったメッシュ(#190) self.decal_meshes: dict[tuple, bpy.types.Mesh] = {} # デカールの形 → この回で作った板(#165) self.prefab_collections: list[bpy.types.Collection] = [] # 読み込む単位 Prefabs で prefab ごとに作ったコレクション @@ -305,7 +308,11 @@ def run(self) -> None: done += 1 self.fill_missed_textures() self.materials.warn_slotless() - if self.opts.import_clips: + if self.motions is not None and not scenes: + self.merge_motion_rigs([summary.guid for group in groups for summary, _ in group.models]) + if self.motions is not None: + self.report.clips.extend(self.motions.stats.clips) + self.report.clip_notes.extend(self.motions.stats.report_lines()) self.step(0.96, "Importing animation clips") self.import_clips() hide_objects(self.context, [obj for obj in self.hidden_objects if not is_removed(obj)]) @@ -315,6 +322,22 @@ def run(self) -> None: self.collection["unity_package"] = self.package_path.name self.step(1.0, "Done") + def merge_motion_rigs(self, model_order: list[str]) -> None: + """同じ骨格のモーションだけのモデルを、1 体のアーマチュアにまとめる(Models 単位。#276)。""" + removed = merge_motion_rigs(list(self.collection.all_objects), model_order) + if not removed: + return + self.motions.stats.merged_rigs += sum(1 for o in removed if o.type == "ARMATURE") + gone = {o.name for o in removed} + self.report.objects[:] = [name for name in self.report.objects if name not in gone] + data = [o.data for o in removed if o.data is not None] + actions = {s.action for o in removed if o.animation_data for t in o.animation_data.nla_tracks for s in t.strips if s.action} + bpy.data.batch_remove(removed) + bpy.data.batch_remove([d for d in data if d.users == 0]) + # 変換した Action に置き換わり、どこからも使われなくなった元の Action + # (FBX インポーターが Action にフェイクユーザーを付けるので、それを除いて数える) + bpy.data.batch_remove([a for a in actions if a.users - int(a.use_fake_user) == 0]) + def import_clips(self) -> None: """パッケージの AnimationClip を Action にして、読み込んだオブジェクトの NLA にミュートで並べる(#209)。""" stats = ClipImporter(self, self.collection).run() @@ -593,6 +616,8 @@ def build_model( ) self.report.models.append(model.pathname) self.report.objects.extend(o.name for o in new["objects"]) + if self.motions is not None: + self.motions.arrange(model.guid, model.pathname, summary.info, new["objects"], new["actions"]) prefab_table = self.match_model_parts(model, prefab_table or {}, new["objects"], before, with_parts) self.materials.assign_materials(summary, prefab_table, new, delegated, existing_materials) diff --git a/unitypackage_loader/blender/model_import.py b/unitypackage_loader/blender/model_import.py index 9ba3389..9f696e8 100644 --- a/unitypackage_loader/blender/model_import.py +++ b/unitypackage_loader/blender/model_import.py @@ -181,7 +181,7 @@ def _import_fbx(path: Path, opts: ImportOptions, scale: float = 1.0) -> None: kwargs = dict( filepath=str(path), global_scale=opts.global_scale * scale, - use_anim=opts.use_anim, + use_anim=opts.animation != "NONE", ignore_leaf_bones=opts.ignore_leaf_bones, use_custom_normals=True, ) diff --git a/unitypackage_loader/blender/options.py b/unitypackage_loader/blender/options.py index 514ba05..b13d458 100644 --- a/unitypackage_loader/blender/options.py +++ b/unitypackage_loader/blender/options.py @@ -38,8 +38,9 @@ class ImportOptions: overwrite_extracted: bool = False max_extract_size: int = 0 # 1 回のインポートで展開する合計バイト数の上限(0 は無制限。Preferences から) fbx_importer: str = "AUTO" # AUTO / NEW / LEGACY - use_anim: bool = False - import_clips: bool = True # パッケージの .anim を Action にして NLA にミュートで並べる(#209) + # アニメーション(#276): MUTED(モデルのテイクと .anim を NLA にミュートで並べる)/ ACTIVE(オブジェクトごとに最初の 1 本だけ + # ミュートを外す)/ NONE(読まない) + animation: str = "MUTED" ignore_leaf_bones: bool = True global_scale: float = 1.0 import_blend: bool = False # 同梱 .blend を append するか(Python スクリプトを含み得るので既定 OFF) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 4e5d0c5..773e6fd 100644 --- a/unitypackage_loader/blender_manifest.toml +++ b/unitypackage_loader/blender_manifest.toml @@ -1,7 +1,7 @@ schema_version = "1.0.0" id = "unitypackage_loader" -version = "1.18.0-dev.8" +version = "1.18.0-dev.10" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/meta.py b/unitypackage_loader/core/meta.py index 4b10f87..a428c22 100644 --- a/unitypackage_loader/core/meta.py +++ b/unitypackage_loader/core/meta.py @@ -18,6 +18,7 @@ __all__ = [ "LEGACY_GLOBAL_SCALE", "MetaInfo", + "ModelClip", "ModelImporterInfo", "TextureImporterInfo", "legacy_meta", @@ -103,6 +104,26 @@ def _unit(unit_scale: float | None) -> float: return unit_scale if unit_scale and math.isfinite(unit_scale) and unit_scale > 0 else 1.0 +@dataclass(frozen=True) +class ModelClip: + """モデルの .meta の ``animations.clipAnimations`` の 1 行(Unity でモデルのテイクから切り出したクリップ。#276)。 + + ``first_frame`` / ``last_frame`` は FBX のフレームレートでのフレーム番号(テイクの時刻と同じ数え方)。 + """ + + name: str + take: str + first_frame: float + last_frame: float + loop: bool = False + + +def _frame(value: Any) -> float | None: + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + return None + return float(value) + + @dataclass class ModelImporterInfo: external_materials: dict[str, str] = field(default_factory=dict) # FBX 内マテリアル名 → .mat GUID @@ -120,6 +141,10 @@ class ModelImporterInfo: # これだけを掛ける(Japanese School Cafeteria: cm の FBX も m の FBX も 0.01 で、頂点はどちらも cm の値)。 # Unity 5 以降のモデルでは None legacy_global_scale: float | None = None + # アニメーションを取り込む設定(animations.importAnimation。無ければ取り込む)と、テイクから切り出したクリップ(#276)。 + # クリップが空なら、Unity はテイクごとに全体を 1 つのクリップにする + import_animation: bool = True + clips: list[ModelClip] = field(default_factory=list) @classmethod def from_meta(cls, meta: MetaInfo | str) -> "ModelImporterInfo": @@ -168,6 +193,24 @@ def from_meta(cls, meta: MetaInfo | str) -> "ModelImporterInfo": info.use_file_scale = bool(meshes.get("useFileScale", 1)) info.bake_axis_conversion = bool(meshes.get("bakeAxisConversion", 0)) info.import_blend_shapes = bool(meshes.get("importBlendShapes", 1)) + info.import_animation = bool(data.get("importAnimation", 1)) + animations = data.get("animations") or {} + raw_clips = animations.get("clipAnimations") if isinstance(animations, dict) else None + for item in raw_clips if isinstance(raw_clips, list) else []: + if not isinstance(item, dict): + continue + first, last = _frame(item.get("firstFrame")), _frame(item.get("lastFrame")) + take = item.get("takeName") + if first is None or last is None or last < first or take is None: + continue + name = item.get("name") + info.clips.append(ModelClip( + name=str(name) if name is not None else str(take), + take=str(take), + first_frame=first, + last_frame=last, + loop=bool(item.get("loopTime", 0)), + )) return info def import_scale(self, unit_scale: float | None) -> float: diff --git a/unitypackage_loader/operators/import_package.py b/unitypackage_loader/operators/import_package.py index 5ca3409..734deea 100644 --- a/unitypackage_loader/operators/import_package.py +++ b/unitypackage_loader/operators/import_package.py @@ -74,14 +74,15 @@ class IMPORT_SCENE_OT_unitypackage(bpy.types.Operator, ImportHelper): "Otherwise the glTF importer is used and materials are rebuilt from .mat files" ), ) - use_anim: BoolProperty(name="Import Animation", default=False) - import_clips: BoolProperty( - name="Animation Clips", - default=True, - description=( - "Turn the package's .anim files (blend shapes, object visibility and transforms) into actions, " - "added as muted NLA tracks on the objects they animate. Humanoid clips and bone curves are skipped" + animation: EnumProperty( + name="Animation", + items=( + ("MUTED", "Muted", "Import the models' animation takes (split into Unity's clips) and the package's .anim clips " + "as muted NLA tracks. The scene looks the same right after the import"), + ("ACTIVE", "Active", "Same as Muted, but unmute the first track of each object"), + ("NONE", "None", "Do not import animation"), ), + default="MUTED", ) ignore_leaf_bones: BoolProperty(name="Ignore Leaf Bones", default=True) import_blend: BoolProperty( @@ -184,8 +185,7 @@ def draw(self, context): header.label(text="Model", icon="MESH_DATA") if body: body.prop(self, "fbx_importer") - body.prop(self, "use_anim") - body.prop(self, "import_clips") + body.prop(self, "animation") body.prop(self, "ignore_leaf_bones") body.prop(self, "use_vrm_addon") body.prop(self, "import_blend")