From cfa964477ea8e02742f06c0d7e33ee21529b45fd Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 15:46:51 +0900 Subject: [PATCH 01/25] =?UTF-8?q?refactor:=20=E9=85=8D=E7=BD=AE=E3=81=AE?= =?UTF-8?q?=E8=A1=8C=E5=88=97=E3=81=AE=E8=A8=88=E7=AE=97=E3=82=92=20bpy=20?= =?UTF-8?q?=E3=81=AB=E4=BE=9D=E5=AD=98=E3=81=97=E3=81=AA=E3=81=84=20core/m?= =?UTF-8?q?odel=5Fspace.py=20=E3=81=AB=E7=A7=BB=E3=81=99=EF=BC=88#263?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit blender/scene_objects.py にあった、モデルの FBX の単位と軸(ModelUnits)、 軸の付け替え(axis_correction)、ノードへの上書き(_node_basis)、1 メッシュの FBX の ルートの組み立て、Renderer の位置、上書きで動いたノードの逆算、置き方の比較を、 行優先タプルの行列で計算する core/model_space.py に移した。scene_objects.py には 親をたどった行列とオブジェクトへの当てはめだけを残す。 Unity と突き合わせて決めた座標計算を単体テストで確かめられるようにするため。 mathutils.Matrix.decompose と同じ約束(鏡映は 3 成分の符号を反転)の decompose を足し、 旧実装と 5,000 通りの行列で比べて差が float32 の誤差(相対 1.7e-7)だけであることを確かめた。 Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 9 +- tests/test_model_space.py | 166 +++++++++++++++ unitypackage_loader/blender/importer.py | 6 +- unitypackage_loader/blender/scene_objects.py | 131 +++--------- .../blender/scene_placement.py | 2 +- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/model_space.py | 189 ++++++++++++++++++ 7 files changed, 398 insertions(+), 107 deletions(-) create mode 100644 tests/test_model_space.py create mode 100644 unitypackage_loader/core/model_space.py diff --git a/DESIGN.md b/DESIGN.md index b4ab922..fe57f90 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -184,19 +184,19 @@ prefab を挟んだ外側からの上書き(Prefab Variant をシーンに置 **古い形式のモデルの中への上書き**(Issue #53): Unity 2018.2 以前の形式のモデルの .meta の `fileIDToRecycleName` を `ModelImporterInfo.recycle_names` に読み、モデルの PrefabInstance の中への上書きを名前付きで配置に記録する(`core/hierarchy.py`)。fileID は「クラス ID × 100000 + 通し番号」で、ルートはふつう 100000 / 400000(`//RootNode`)。Unity 4 で取り込んだモデルは名前順などで番号を振り、`//RootNode` が 100006 / 400006 のように後ろになって 100000 が中のノードを指すことがあるので、表に `//RootNode` の行があればそれをルートにする(`hierarchy.legacy_root_ids`。表が無い・行が足りなければ 100000 / 400000)。以前は 400000 と決め打ちしていて、Japanese School Cafeteria の窓・扉・柵(複数ノードの FBX)では、配置の位置の上書きが中のノードに当たってルートが原点に残っていた。展開したモデルの階層の表にも、この古い形式のルートの番号を載せる(`Expander._model`)。prefab の中に置いたモデルのルートを、外側から「中の PrefabInstance の fileID XOR 元の fileID」で指す上書きが古い形式の番号で書かれていることがあり、新しい形式の定数だけでは当たらなかった(Destroyed Building Kit の `DBK_Big_Scene` が `DBK_Cinderblock_Building.prefab` の中の瓦礫の板 `rubble` を `m_IsActive: 0` で隠している。#244)。 -Unity 4 以前に書き出したパッケージは、`asset.meta`(YAML)の代わりに `metaData` を持つ。中身は取り込み結果(GameObject・Mesh など)とインポーターを入れたバイナリの SerializedFile(version 9)で、ヘッダーのファイルサイズの後ろにプレビューの PNG が続く。scan でモデルの `metaData` だけを読み、ModelImporter の `m_FileIDToRecycleName` を上の表と同じ形にする(`meta.legacy_meta` → `AssetEntry.legacy_meta`)。あわせて `m_GlobalScale` も読む。Unity 4 は FBX の単位(UnitScaleFactor)を見ず、頂点の値にこれだけを掛ける(Japanese School Cafeteria では cm の FBX 25 個も m の FBX 28 個も 0.01 で、頂点はどちらも cm の値。エアコンは cm 指定で頂点 80 → 0.8 m、柵は m 指定で頂点 150 → 1.5 m)。Blender の FBX インポーターは UnitScaleFactor / 100 を掛けるので、m 指定のものが 100 倍になっていた。Unity 4 のモデルは読み込みで `m_GlobalScale × 100 / UnitScaleFactor` を掛けて Unity と同じ大きさにし(`ModelImporterInfo.import_scale`)、配置の計算(`_node_basis` などの fileScale)には `m_GlobalScale` を渡す(`unity_unit_scale`)。Models / Prefabs 単位でも同じ大きさで読む。テクスチャの `metaData` は取り込んだ画像まで入っていて大きく、ノーマルマップなどの設定は今は読まない。 +Unity 4 以前に書き出したパッケージは、`asset.meta`(YAML)の代わりに `metaData` を持つ。中身は取り込み結果(GameObject・Mesh など)とインポーターを入れたバイナリの SerializedFile(version 9)で、ヘッダーのファイルサイズの後ろにプレビューの PNG が続く。scan でモデルの `metaData` だけを読み、ModelImporter の `m_FileIDToRecycleName` を上の表と同じ形にする(`meta.legacy_meta` → `AssetEntry.legacy_meta`)。あわせて `m_GlobalScale` も読む。Unity 4 は FBX の単位(UnitScaleFactor)を見ず、頂点の値にこれだけを掛ける(Japanese School Cafeteria では cm の FBX 25 個も m の FBX 28 個も 0.01 で、頂点はどちらも cm の値。エアコンは cm 指定で頂点 80 → 0.8 m、柵は m 指定で頂点 150 → 1.5 m)。Blender の FBX インポーターは UnitScaleFactor / 100 を掛けるので、m 指定のものが 100 倍になっていた。Unity 4 のモデルは読み込みで `m_GlobalScale × 100 / UnitScaleFactor` を掛けて Unity と同じ大きさにし(`ModelImporterInfo.import_scale`)、配置の計算(`model_space.node_basis` などの fileScale)には `m_GlobalScale` を渡す(`unity_unit_scale`)。Models / Prefabs 単位でも同じ大きさで読む。テクスチャの `metaData` は取り込んだ画像まで入っていて大きく、ノーマルマップなどの設定は今は読まない。 Unity 4 のシーンは、PrefabInstance(`m_IsExploded: 1`)の中身を stripped にせず、値ごとふつうの GameObject / Transform / Renderer として保存している(各ドキュメントが `m_PrefabParentObject` で元のオブジェクトを、`m_PrefabInternal` で PrefabInstance を指す)。そのまま読むと、PrefabInstance から差し込んだものと二重になる。`parse_asset` は、展開済みの PrefabInstance の中にあって元を持つドキュメントを stripped と同じく別名として扱い、配置は差し込みと上書きで作る(元を持たないもの=その PrefabInstance で足したオブジェクトは、シーンのものとして残す)。2018.2 以前でも YAML のシーンは stripped を使い、この値を持たない(手元の SbbUtutuya のパッケージで確認)。 - マテリアル(`m_Materials.Array.data[N]`、クラス 23 / 137): 配置の `renderers` に入れ、既存のスロット単位の割り当てで当てる。上書きの無いスロットは None で、.meta・名前一致の結果のまま。1 メッシュの FBX では Renderer が `//RootNode` に載るので、表のメッシュ名(クラス 43 がただ 1 つ)をオブジェクト名にする -- 位置・回転・スケール(クラス 4): `node_transforms` に成分ごとに記録し、読み込み時に当てる(`blender/scene_objects.py` の `apply_node_transforms`)。上書きは Unity のノード空間の値で、元の値はパッケージに無い。Unity 6 に室内アセットを展開し、FBX を読んだノードの値・シーンの Renderer の外形とマテリアルを書き出して Blender と突き合わせた結果、原点に読み込んだ Blender のオブジェクトの行列 N と Unity のノードの行列 L は N = C·L·A(A = diag(−f, f, f)、f は Unity の fileScale = FBX の UnitScaleFactor / 100)だった(UnitScaleFactor 100 と 1 の FBX、Blender 由来の FBX で一致)。元のノード値を L = C⁻¹·N·A⁻¹ で求め、上書きの無い成分はそのまま使い、C·L'·A をオブジェクトの `matrix_basis` にする(親は配置の Empty で、globalScale は親の逆行列)。UnitScaleFactor は `core/fbx_units.py` が FBX から読む(バイナリ、ASCII の FBX 7 / 6)。A は Y が上の FBX(Maya・Blender が書き出すもの)での形で、一般には A = f·U(U は Unity がその FBX の頂点に掛ける軸の変換。`fbx_units.unity_axis_matrix`、`ModelUnits.basis_a`)。Y が上なら U = diag(−1, 1, 1)、3ds Max の Z が上の FBX(GlobalSettings の UpAxis が 2)で、.meta の Bake Axis Conversion(`meshes.bakeAxisConversion`。`ModelImporterInfo.bake_axis_conversion`)が有効なら Y と Z の入れ替え(入れ替えだけで左手系になる)。Bake Axis Conversion が無効(既定)なら、Unity は軸の変換を頂点に焼き込まずルートの回転として持ち、シーン・prefab に保存されるルートの回転にもそれが入るので、Y が上と同じ U = diag(−1, 1, 1) で合う(Unreal 由来の Z が上の FBX を使う Shibuya で、入れ替えを当てると建物などが 90° 回っていた。1.17.0 の開発中に見つけて直した)。Blender の FBX インポーターはファイルの上の軸を +Z にする B(`blender_axis_matrix`)を掛けるが、Z が上の FBX では回転を掛けないので、読み込んだ直後に最上位のオブジェクトへ K = C·U·B⁻¹ を左から掛けて Unity と同じ向きにそろえる(`axis_correction`。Bake Axis Conversion を入れたモデルだけ。Y が上なら K は単位行列で何もしない)。Cardboard Boxes Pack(box0.FBX などがインチ・Z が上・globalScale 2.54)で、展開した prefab の箱が X 軸のまわりに 90° 倒れていた(Issue #240。Unity 6000.6.9f1 で demo シーンを開いて書き出した 1,861 個の Renderer と突き合わせ、一致が 762 → 1,861)。Renderer の GameObject を Unity の位置に置き直すとき(`apply_renderer_worlds`)は、ルートの Empty のワールドから直接置くので、親の逆行列で掛けている globalScale も掛ける(`ModelUnits.world_basis_a`。以前は掛けておらず、globalScale が 1 でないモデルで子の部品が小さく、位置が寄っていた) +- 位置・回転・スケール(クラス 4): `node_transforms` に成分ごとに記録し、読み込み時に当てる(`blender/scene_objects.py` の `apply_node_transforms`)。上書きは Unity のノード空間の値で、元の値はパッケージに無い。Unity 6 に室内アセットを展開し、FBX を読んだノードの値・シーンの Renderer の外形とマテリアルを書き出して Blender と突き合わせた結果、原点に読み込んだ Blender のオブジェクトの行列 N と Unity のノードの行列 L は N = C·L·A(A = diag(−f, f, f)、f は Unity の fileScale = FBX の UnitScaleFactor / 100)だった(UnitScaleFactor 100 と 1 の FBX、Blender 由来の FBX で一致)。元のノード値を L = C⁻¹·N·A⁻¹ で求め、上書きの無い成分はそのまま使い、C·L'·A をオブジェクトの `matrix_basis` にする(親は配置の Empty で、globalScale は親の逆行列)。UnitScaleFactor は `core/fbx_units.py` が FBX から読む(バイナリ、ASCII の FBX 7 / 6)。A は Y が上の FBX(Maya・Blender が書き出すもの)での形で、一般には A = f·U(U は Unity がその FBX の頂点に掛ける軸の変換。`fbx_units.unity_axis_matrix`、`model_space.ModelUnits.basis_a`)。Y が上なら U = diag(−1, 1, 1)、3ds Max の Z が上の FBX(GlobalSettings の UpAxis が 2)で、.meta の Bake Axis Conversion(`meshes.bakeAxisConversion`。`ModelImporterInfo.bake_axis_conversion`)が有効なら Y と Z の入れ替え(入れ替えだけで左手系になる)。Bake Axis Conversion が無効(既定)なら、Unity は軸の変換を頂点に焼き込まずルートの回転として持ち、シーン・prefab に保存されるルートの回転にもそれが入るので、Y が上と同じ U = diag(−1, 1, 1) で合う(Unreal 由来の Z が上の FBX を使う Shibuya で、入れ替えを当てると建物などが 90° 回っていた。1.17.0 の開発中に見つけて直した)。Blender の FBX インポーターはファイルの上の軸を +Z にする B(`blender_axis_matrix`)を掛けるが、Z が上の FBX では回転を掛けないので、読み込んだ直後に最上位のオブジェクトへ K = C·U·B⁻¹ を左から掛けて Unity と同じ向きにそろえる(`model_space.axis_correction`。Bake Axis Conversion を入れたモデルだけ。Y が上なら K は単位行列で何もしない)。Cardboard Boxes Pack(box0.FBX などがインチ・Z が上・globalScale 2.54)で、展開した prefab の箱が X 軸のまわりに 90° 倒れていた(Issue #240。Unity 6000.6.9f1 で demo シーンを開いて書き出した 1,861 個の Renderer と突き合わせ、一致が 762 → 1,861)。Renderer の GameObject を Unity の位置に置き直すとき(`apply_renderer_worlds`)は、ルートの Empty のワールドから直接置くので、親の逆行列で掛けている globalScale も掛ける(`ModelUnits.world_basis_a`。以前は掛けておらず、globalScale が 1 でないモデルで子の部品が小さく、位置が寄っていた) - 当てるのはモデルの最上位のオブジェクトだけ。入れ子のオブジェクトとアーマチュアで変形するものは件数を警告に出す。表に無い fileID は今までどおり数える - 室内アセットのシーンでは、FBX 由来の Renderer 120 個すべてで、Unity の外形の中心との差が 1 cm 未満、マテリアルも一致した **1 メッシュの FBX をモデルの PrefabInstance で置いた配置**(Issue #99): この形の FBX では Unity がノードを `//RootNode` に畳み、**モデルのルートの Transform の値が FBX のノードの変換 L** になる(Issue #98 と同じ事実の裏返し)。シーンの上書きは L の成分を置き換えるので、上書きしなかった成分には L の値が残る(位置と回転だけ動かした配置では、スケールは FBX のノードの値のまま)。展開した階層はルートを単位行列で作るため、そのままでは上書きの無い成分が失われ、さらに Blender のオブジェクトが持つノードの変換と二重に掛かっていた。 - `core/hierarchy.py` / `core/expander.py` / `core/placement.py`: 表から畳まれたノードの名前を求め(`collapsed_root_name`)、配置の `root_node` に入れる。ルートの Transform への上書きは、当てるのに加えて成分ごとに `node_transforms[root_node]` へ記録する(上書きの無い成分は None) -- `blender/scene_objects.py` の `apply_collapsed_root`: 原点に読み込んだオブジェクトの行列から L を逆算し、上書きを当てた M で配置の Empty を C·M·C⁻¹ に直し、オブジェクトはノードを単位行列にした C·A にする。Empty を直すので、そこに付けたシーン側の子も Unity と同じ位置になる +- `blender/scene_objects.py` の `apply_collapsed_root`(行列は `core/model_space.py` の `collapsed_root`): 原点に読み込んだオブジェクトの行列から L を逆算し、上書きを当てた M で配置の Empty を C·M·C⁻¹ に直し、オブジェクトはノードを単位行列にした C·A にする。Empty を直すので、そこに付けたシーン側の子も Unity と同じ位置になる - 期待値は Unity 6000.6.0f1 で同じ置き方(位置と回転だけ上書き)を再現した頂点のワールド座標で確かめた(合成シーンの `SlabInstance`) - 表の無いモデル(Issue #111): `.meta` の表が空だと 1 メッシュの FBX か分からないので、展開ではルートの Transform への上書きを成分ごとに`node_transforms[SOLE_NODE]` へ記録し、`root_node` を `SOLE_NODE` にしておく(ルートを上書きしていなければ記録しない)。読み込み側は、読み込んだオブジェクトが子の無い 1 つだけなら畳まれた形とみなし、そのオブジェクトの名前で `apply_collapsed_root` を当てる。オブジェクトが複数なら Unity のルートは単位行列が基準なので、展開した行列のまま置く。実例は Shibuya.unitypackage の `SM_MetroEntrance_02`(ノードの回転は Unity で euler (270, 180, 0)。シーンが回転を (270, 2.47, 0) に上書きするので、Y の 180 度は Unity では消える)で、Unity 6000.6.0f1 の batchmode で求めたワールドのバウンディングボックスと突き合わせた。合成シーンでは、`SlabInstance` と同じ FBX を表の無い `.meta` で置いた `SlabBareInstance` で確かめる - prefab で包んだ形(Issue #111): 地下鉄の入口は、FBX をルートの位置 0・回転なしで置いた prefab を、シーンがさらに上書きしている。以前は FBX を直接置いた階層の上書きしか成分付きで記録しておらず、外側の上書きが読み込み側に渡っていなかった(表のあるモデルでも同じ)。そこで畳まれうるモデルのルートの Node に `collapsed_key`(表から求めたノード名か `SOLE_NODE`)を持たせ、`_apply_modification` が位置・回転・スケールを当てるときに、どの階層の上書きでも `model_transforms[collapsed_key]` に記録する。合成シーンの `SlabBareWrapped` / `SlabWrapped` で確かめる @@ -618,6 +618,7 @@ unitypackage_loader/ │ ├─ placement.py # 展開した階層からモデルの配置を求める(placements / summarize / ModelCatalog) │ ├─ scene_import.py # シーンの読み込みの判定(隠す部品)と警告文 │ ├─ transform.py # Unity の Transform の行列と Unity → Blender の座標変換 +│ ├─ model_space.py # 置いたモデルの行列(FBX の単位と軸 ModelUnits、ノードへの上書き、Renderer の位置。#263) │ ├─ shader_source.py # パッケージ内の .shader / .shadergraph が宣言するプロパティ名(残りを外す。#118)と描画の既定(#202) │ ├─ shader_graph.py # .shadergraph のつながりから、テクスチャの UV の Tiling & Offset を読む(#193) │ ├─ decals.py # DecalProjector を投影の箱の中の板で近似する(#165) @@ -648,7 +649,7 @@ unitypackage_loader/ │ ├─ terrain.py # Terrain のメッシュと塗り分けのマテリアル(SessionTerrains。#205) │ ├─ unity_meshes.py # Unity の Mesh アセットから作るメッシュ(SessionMeshes。#216) │ ├─ log.py # 捕まえて続けた例外のログ(Verbose Console Log はオペレーターが渡す) -│ ├─ scene_objects.py # シーンの Empty・ライト・カメラ・複製・行列の補正・非表示 +│ ├─ scene_objects.py # シーンの Empty・ライト・カメラ・複製・行列の当てはめ(計算は core/model_space.py)・非表示 │ ├─ materials.py # ノード生成 │ ├─ nodes.py # ノードの組み立ての共通関数 │ ├─ toon_group.py # UnityToon ノードグループ diff --git a/tests/test_model_space.py b/tests/test_model_space.py new file mode 100644 index 0000000..f42b750 --- /dev/null +++ b/tests/test_model_space.py @@ -0,0 +1,166 @@ +import math +import unittest + +from tests import _paths # noqa: F401 +from unitypackage_loader.core.model_space import ( + ModelUnits, + axis_correction, + collapsed_root, + decompose, + file_scale, + node_basis, + offset_world, + renderer_world, + same_placement, +) +from unitypackage_loader.core.transform import ( + IDENTITY, + UNITY_TO_BLENDER, + chain, + inverse_affine, + multiply, + trs, + unity_to_blender, +) +from tests.test_transform import Y90, assert_mat, assert_vec + +Z_UP_MAX = (2, 1, 1, -1, 0, 1) # 3ds Max の Z が上の FBX +Y_UP = (1, 1, 2, 1, 0, 1) + + +class FileScaleTest(unittest.TestCase): + def test_unit_scale(self): + self.assertAlmostEqual(file_scale(100.0), 1.0) + self.assertAlmostEqual(file_scale(1.0), 0.01) + + def test_unreadable_is_one(self): + for value in (None, 0.0, -1.0, math.nan, math.inf): + self.assertAlmostEqual(file_scale(value), 0.01) + + +class ModelUnitsTest(unittest.TestCase): + def test_y_up_flips_x(self): + assert_mat(self, ModelUnits(100.0, Y_UP).basis_a(), ((-1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))) + + def test_unknown_axes_are_y_up(self): + self.assertEqual(ModelUnits(1.0).basis_a(), ModelUnits(1.0, Y_UP).basis_a()) + + def test_z_up_swaps_y_and_z(self): + assert_mat(self, ModelUnits(1.0, Z_UP_MAX).basis_a(), ((0.01, 0, 0, 0), (0, 0, 0.01, 0), (0, 0.01, 0, 0), (0, 0, 0, 1))) + + def test_world_basis_includes_global_scale(self): + units = ModelUnits(100.0, Y_UP, 2.0) + assert_mat(self, units.world_basis_a(), ((-2, 0, 0, 0), (0, 2, 0, 0), (0, 0, 2, 0), (0, 0, 0, 1))) + + def test_invalid_global_scale_is_ignored(self): + for value in (0.0, -1.0, math.nan): + self.assertEqual(ModelUnits(100.0, Y_UP, value).world_basis_a(), ModelUnits(100.0, Y_UP).basis_a()) + + +class AxisCorrectionTest(unittest.TestCase): + def test_y_up_needs_none(self): + self.assertIsNone(axis_correction(Y_UP)) + self.assertIsNone(axis_correction(None)) + + def test_z_up_is_rotation(self): + k = axis_correction(Z_UP_MAX) + self.assertIsNotNone(k) + rotation = [row[:3] for row in k[:3]] + det = ( + rotation[0][0] * (rotation[1][1] * rotation[2][2] - rotation[1][2] * rotation[2][1]) + - rotation[0][1] * (rotation[1][0] * rotation[2][2] - rotation[1][2] * rotation[2][0]) + + rotation[0][2] * (rotation[1][0] * rotation[2][1] - rotation[1][1] * rotation[2][0]) + ) + self.assertAlmostEqual(det, 1.0) + + +class DecomposeTest(unittest.TestCase): + def test_round_trip(self): + for rotation in ((0, 0, 0, 1), Y90, (0.5, 0.5, 0.5, 0.5), (0.9, 0.1, -0.3, 0.2), (0.0, 0.0, 1.0, 0.0), (1.0, 0, 0, 0)): + m = trs((1.0, -2.0, 3.0), rotation, (2.0, 0.5, 3.0)) + location, quat, scale = decompose(m) + assert_vec(self, location, (1.0, -2.0, 3.0)) + assert_vec(self, scale, (2.0, 0.5, 3.0)) + assert_mat(self, trs(location, quat, scale), m) + + def test_mirror_negates_all_scales(self): + # mathutils.Matrix.decompose と同じく、鏡映は 3 成分すべての符号を反転して回転に回す + m = trs((0.0, 0.0, 0.0), Y90, (-1.0, 2.0, 3.0)) + location, quat, scale = decompose(m) + assert_vec(self, scale, (-1.0, -2.0, -3.0)) + assert_mat(self, trs(location, quat, scale), m) + + +def _object_matrix(local, basis_a): + """原点に読み込んだオブジェクトの行列 N = C·L·A。""" + return chain((UNITY_TO_BLENDER, local, basis_a)) + + +class NodeBasisTest(unittest.TestCase): + basis_a = ModelUnits(1.0, Y_UP).basis_a() + local = trs((1.0, 2.0, 3.0), Y90, (1.0, 1.0, 1.0)) + + def test_no_override_keeps_matrix(self): + basis = _object_matrix(self.local, self.basis_a) + assert_mat(self, node_basis(basis, {}, self.basis_a), basis) + + def test_partial_override(self): + basis = _object_matrix(self.local, self.basis_a) + spec = {"position": [None, 5.0, None], "scale": [2.0, 2.0, 2.0]} + expected = _object_matrix(trs((1.0, 5.0, 3.0), Y90, (2.0, 2.0, 2.0)), self.basis_a) + assert_mat(self, node_basis(basis, spec, self.basis_a), expected) + + def test_short_or_extra_values(self): + basis = _object_matrix(self.local, self.basis_a) + spec = {"position": [7.0], "rotation": [0, 0, 0, 1, 99]} + expected = _object_matrix(trs((7.0, 2.0, 3.0), (0, 0, 0, 1), (1.0, 1.0, 1.0)), self.basis_a) + assert_mat(self, node_basis(basis, spec, self.basis_a), expected) + + def test_collapsed_root(self): + basis = _object_matrix(self.local, self.basis_a) + spec = {"position": [0.0, 0.0, 0.0]} + root, obj = collapsed_root(basis, spec, self.basis_a) + assert_mat(self, obj, multiply(UNITY_TO_BLENDER, self.basis_a)) + assert_mat(self, multiply(root, obj), node_basis(basis, spec, self.basis_a)) + # ルートの Empty は C·M·C⁻¹ の形(M = 上書きを当てたノードの行列) + assert_mat(self, root, unity_to_blender(trs((0.0, 0.0, 0.0), Y90, (1.0, 1.0, 1.0)))) + + +class PlacementTest(unittest.TestCase): + def test_renderer_world(self): + a = ModelUnits(100.0, Y_UP, 2.0).world_basis_a() + root = trs((1.0, 2.0, 3.0), (0, 0, 0, 1), (1, 1, 1)) + relative = trs((0.0, 1.0, 0.0), Y90, (1, 1, 1)) + assert_mat(self, renderer_world(root, relative, a), chain((root, UNITY_TO_BLENDER, relative, a))) + + def test_offset_world_same_root_keeps_matrix(self): + root = trs((1.0, 2.0, 3.0), Y90, (1, 1, 1)) + current = trs((4.0, 5.0, 6.0), (0, 0, 0, 1), (2, 2, 2)) + assert_mat(self, offset_world(root, root, 2.0, current), current) + + def test_offset_world_moves_by_difference(self): + root = IDENTITY + offset = trs((1.0, 0.0, 0.0), (0, 0, 0, 1), (1, 1, 1)) + current = trs((0.0, 0.0, 0.0), (0, 0, 0, 1), (1, 1, 1)) + # Unity の +X は Blender の -X + assert_vec(self, [row[3] for row in offset_world(offset, root, 1.0, current)[:3]], (-1.0, 0.0, 0.0)) + + def test_offset_world_ignores_invalid_scale(self): + root = trs((1.0, 2.0, 3.0), Y90, (1, 1, 1)) + offset = trs((2.0, 2.0, 3.0), Y90, (1, 1, 1)) + assert_mat(self, offset_world(offset, root, 0.0, IDENTITY), offset_world(offset, root, 1.0, IDENTITY)) + + def test_same_placement(self): + a = trs((216.0, 0.0, 0.0), Y90, (1, 1, 1)) + self.assertTrue(same_placement(a, trs((216.00005, 0.0, 0.0), Y90, (1, 1, 1)))) + self.assertFalse(same_placement(a, trs((216.02, 0.0, 0.0), Y90, (1, 1, 1)))) # 遠くの 2 cm を見逃さない + self.assertFalse(same_placement(a, trs((216.0, 0.0, 0.0), (0, 0, 0, 1), (1, 1, 1)))) + big = trs((0.0, 0.0, 0.0), (0, 0, 0, 1), (100, 100, 100)) + self.assertTrue(same_placement(big, trs((0.0, 0.0, 0.0), (0, 0, 0, 1), (100.005, 100, 100)))) + + def test_inverse_exists_for_basis(self): + self.assertIsNotNone(inverse_affine(ModelUnits(1.0, Z_UP_MAX, 3.0).world_basis_a())) + + +if __name__ == "__main__": + unittest.main() diff --git a/unitypackage_loader/blender/importer.py b/unitypackage_loader/blender/importer.py index 6c6bf3f..e738baf 100644 --- a/unitypackage_loader/blender/importer.py +++ b/unitypackage_loader/blender/importer.py @@ -16,6 +16,7 @@ from pathlib import Path import bpy +from mathutils import Matrix from ..core.fbx_units import read_axes from ..core.decals import Decal, decal_from_body @@ -26,6 +27,7 @@ from ..core.mapping import expected_materials, material_textures from ..core.meta import strip_numeric_suffix from ..core.model_ids import PartMatcher, fbx_node_names +from ..core.model_space import axis_correction from ..core.package import AssetEntry, PackageError, UnityPackage, default_nested_package, merge_nested_package from ..core.prefab import RendererMaterials, has_pending_renderers, resolve_model_renderers from ..core.report import ImportReport @@ -63,7 +65,7 @@ prepare_package, ) from .scene_objects import ( - arrange_collections, axis_correction, find_layer_collection, hide_objects, + arrange_collections, find_layer_collection, hide_objects, move_collection_contents, remove_parts, ) from .scene_placement import SceneImport @@ -619,7 +621,7 @@ def import_with_node_names(self, model: AssetEntry, target) -> bool: if correction is not None: for obj in target.all_objects: if obj.parent is None: - obj.matrix_basis = correction @ obj.matrix_basis + obj.matrix_basis = Matrix(correction) @ obj.matrix_basis return delegated def fbx_node_names_of(self, model: AssetEntry): diff --git a/unitypackage_loader/blender/scene_objects.py b/unitypackage_loader/blender/scene_objects.py index facedb7..8a68e0e 100644 --- a/unitypackage_loader/blender/scene_objects.py +++ b/unitypackage_loader/blender/scene_objects.py @@ -1,27 +1,34 @@ """シーンの読み込みで、Blender のオブジェクトを作り・置くための関数。 -Empty・ライト・カメラの作成、読み込んだモデルの複製、行列の補正、非表示、コレクションの移動と並べ方。 -読み込みの流れは ``importer.py``、bpy に依存しない判定は ``core/scene_import.py``。 +Empty・ライト・カメラの作成、読み込んだモデルの複製、行列の当てはめ、非表示、コレクションの移動と並べ方。 +読み込みの流れは ``importer.py``、bpy に依存しない判定は ``core/scene_import.py``、行列の計算は ``core/model_space.py``。 """ from __future__ import annotations import json -import math from dataclasses import dataclass import bpy from mathutils import Matrix, Vector from ..core.arrange import arrange_offsets -from ..core.fbx_units import blender_axis_matrix, unity_axis_matrix from ..core.hierarchy import Hierarchy from ..core.lights import BlenderCamera, BlenderLight from ..core.meta import strip_numeric_suffix +from ..core.model_space import ( + ModelUnits, + collapsed_root, + node_basis, + offset_world, + positive_scale, + renderer_world, + same_placement, +) from ..core.prefab import RendererMaterials, find_renderer from ..core.decals import Decal, decal_plane from ..core.primitives import PrimitiveMesh, build_primitive -from ..core.transform import BLENDER_TO_UNITY, UNITY_TO_BLENDER, trs, unity_to_blender +from ..core.transform import Mat4, unity_to_blender from ..core.unity_yaml import UnityRef from .model_import import node_name @@ -210,7 +217,7 @@ def attach_to_empty(objects: list[bpy.types.Object], root, scale: float) -> None if root is None: return members = set(objects) - inverse = Matrix.Scale(scale, 4) if math.isfinite(scale) and scale > 0 and scale != 1 else Matrix.Identity(4) + inverse = Matrix.Scale(scale, 4) if positive_scale(scale) not in (None, 1) else Matrix.Identity(4) for obj in objects: if obj.parent is None or obj.parent not in members: obj.parent = root @@ -244,73 +251,15 @@ def _by_object_name(table: dict, name: str): return table.get(strip_numeric_suffix(name)) -def _file_scale(unit_scale: float | None) -> float: - """Unity の fileScale(= FBX の UnitScaleFactor / 100)。読めなければ 1 として扱う。""" - return (unit_scale if unit_scale and math.isfinite(unit_scale) and unit_scale > 0 else 1.0) / 100.0 - - -@dataclass(frozen=True) -class ModelUnits: - """配置の計算に使う、モデルの FBX の単位と軸(``read_unit_scale`` / ``read_axes``。FBX 以外は空)。""" - - unit_scale: float | None = None - axes: tuple[int, ...] | None = None - global_scale: float = 1.0 # .meta の globalScale(Unity は頂点と子の位置に焼き込む) - - def basis_a(self) -> Matrix: - """Blender のオブジェクトのローカル座標(FBX のファイルの座標)→ Unity のノード空間(A = f·U)。 - - U は Unity がこの FBX に掛ける軸の変換(``fbx_units.unity_axis_matrix``)。Y が上の FBX では diag(-1, 1, 1) で、 - A = diag(-f, f, f)(#53 で確かめた形)。3ds Max の Z が上の FBX では Y と Z の入れ替え(Cardboard Boxes Pack。#240)。 - """ - f = _file_scale(self.unit_scale) - return Matrix.Diagonal((f, f, f, 1.0)) @ Matrix(unity_axis_matrix(self.axes)).to_4x4() - - def world_basis_a(self) -> Matrix: - """``basis_a`` に globalScale も掛けたもの(ルートの Empty の下で、親の逆行列を通さずにワールドで置くとき)。""" - g = self.global_scale if math.isfinite(self.global_scale) and self.global_scale > 0 else 1.0 - return Matrix.Diagonal((g, g, g, 1.0)) @ self.basis_a() - - -def axis_correction(axes: tuple[int, ...] | None) -> Matrix | None: - """Y が上でない FBX を読み込んだ直後に、最上位のオブジェクトへ左から掛けて Unity と同じ向きにする行列(K = C·U·B⁻¹)。 - - Blender の FBX インポーターはファイルの上の軸を +Z にする(B。Z が上の 3ds Max の FBX では回転を掛けない)が、Unity は - U で Y が上にする(#240)。Y が上の FBX では K が単位行列(C·diag(-1, 1, 1) = B)なので None。 - """ - if axes is None or axes[0] != 2: - return None - unity = Matrix(unity_axis_matrix(axes)).to_4x4() - blender = Matrix(blender_axis_matrix(axes)).to_4x4() - return Matrix(UNITY_TO_BLENDER) @ unity @ blender.inverted_safe() +def _mat4(matrix: Matrix) -> Mat4: + """``mathutils.Matrix`` を ``core`` の行列(行優先タプル)にする。""" + return tuple(tuple(row) for row in matrix) # type: ignore[return-value] def _units(units: ModelUnits | None) -> ModelUnits: return units if units is not None else ModelUnits() -def _node_basis(basis: Matrix, spec: dict, basis_a: Matrix) -> Matrix: - """ノードへの上書きを当てたオブジェクトの行列(C·M·A)。 - - Unity のノード空間の行列 L と、原点に読み込んだ Blender のオブジェクトの行列 N の関係は N = C·L·A - (C は Unity → Blender の基底、A は ``ModelUnits.basis_a``。Y が上の FBX では diag(-f, f, f)、f は Unity の fileScale - = FBX の UnitScaleFactor / 100)。Japanese Apartment の FBX(UnitScaleFactor 100 と 1)と Blender 由来の FBX で、 - Unity 6 が読んだノードの値と突き合わせて確かめた(Issue #53)。元のノード値を L = C⁻¹·N·A⁻¹ で求め、上書きの無い成分は - その値のまま使う。 - """ - basis_a_inverse = basis_a.inverted_safe() - location, rotation, scale = (Matrix(BLENDER_TO_UNITY) @ basis @ basis_a_inverse).decompose() - position = [location.x, location.y, location.z] - quaternion = [rotation.x, rotation.y, rotation.z, rotation.w] # Unity の並び - scaling = [scale.x, scale.y, scale.z] - for values, key in ((position, "position"), (quaternion, "rotation"), (scaling, "scale")): - for index, value in enumerate(spec.get(key, [])): - if value is not None and index < len(values): - values[index] = value - local = Matrix(trs(tuple(position), tuple(quaternion), tuple(scaling))) - return Matrix(UNITY_TO_BLENDER) @ local @ basis_a - - def _movable(obj, members: set) -> bool: """行列を直接入れ替えられるオブジェクトか(入れ子やアーマチュアで変形するものは対象外)。""" deformed = obj.type == "ARMATURE" or any(m.type == "ARMATURE" for m in getattr(obj, "modifiers", [])) @@ -321,7 +270,7 @@ def apply_node_transforms(template: SceneTemplate, objects, overrides, units: Mo """モデルの中のノードへの位置・回転・スケールの上書き(古い形式の .meta で名前を引けたもの)を当てる。 当てるのはモデルの最上位のオブジェクトだけ(入れ子やアーマチュアで変形するものは数えて飛ばす)。 - 行列の組み立ては ``_node_basis`` を参照。 + 行列の組み立ては ``core.model_space.node_basis`` を参照。 """ basis_a = _units(units).basis_a() members = set(objects) @@ -333,30 +282,28 @@ def apply_node_transforms(template: SceneTemplate, objects, overrides, units: Mo if not _movable(obj, members): skipped += 1 continue - obj.matrix_basis = _node_basis(template.basis[original], spec, basis_a) + obj.matrix_basis = Matrix(node_basis(_mat4(template.basis[original]), spec, basis_a)) return skipped def apply_collapsed_root(template: SceneTemplate, objects, root, name: str, spec: dict, units: ModelUnits | None) -> bool: """1 メッシュの FBX をモデルの PrefabInstance で置いた配置を、FBX のノードの変換ぶんも含めて置き直す(#99)。 - この形の FBX では Unity のモデルのルートの Transform の値が FBX のノードの変換 L で、シーンの上書きは - その成分を置き換える(上書きしなかった成分は L のまま)。展開した階層は単位行列を基準に組み立てているので、 - ここでルートの Empty を C·M·C⁻¹(M = L に上書きを当てた行列)に直し、オブジェクトはノードを単位行列にした - C·A にする。Empty を直すのは、そこに付けたシーンの子も Unity と同じ位置にするため。置き直せなければ False。 + 行列は ``core.model_space.collapsed_root``。Empty を直すのは、そこに付けたシーンの子も Unity と同じ位置にするため。 + 置き直せなければ False。 """ if root is None: return False basis_a = _units(units).basis_a() - neutral = Matrix(UNITY_TO_BLENDER) @ basis_a # ノードを単位行列にしたオブジェクトの行列 members = set(objects) for original, obj in zip(template.objects, objects): if _by_object_name({name: spec}, node_name(obj)) is None: continue if not _movable(obj, members): return False - root.matrix_basis = _node_basis(template.basis[original], spec, basis_a) @ neutral.inverted_safe() - obj.matrix_basis = neutral + root_matrix, object_matrix = collapsed_root(_mat4(template.basis[original]), spec, basis_a) + root.matrix_basis = Matrix(root_matrix) + obj.matrix_basis = Matrix(object_matrix) return True return False @@ -527,24 +474,12 @@ def _parent_frame(obj) -> Matrix | None: return parent_world @ obj.matrix_parent_inverse if obj.parent is not None else Matrix.Identity(4) -def _same_placement(a: Matrix, b: Matrix) -> bool: - """2 つの行列が、float の誤差を除いて同じ置き方か(列の長さに対する相対誤差と、位置の誤差)。 - - 位置は 0.1 mm に、座標の大きさに比例する float の誤差(100 万分の 1)を足した範囲で比べる。座標に比例させるだけだと、 - 原点から離れた部品の数 cm のずれを見逃す(Farm の 216 m 先の門扉で 2 cm)。 - """ - size = max(1.0, *(a.col[i].xyz.length for i in range(3))) - if any(abs(a[r][c] - b[r][c]) > 1e-4 * size for r in range(3) for c in range(3)): - return False - return all(abs(a[r][3] - b[r][3]) <= 1e-4 + 1e-6 * abs(a[r][3]) for r in range(3)) - - def apply_renderer_worlds(template: SceneTemplate, objects, root, renderers: dict, units: ModelUnits | None) -> int: """FBX を展開した配置で、Renderer の GameObject が FBX のノードと違う位置にあるオブジェクトを、Unity の位置に置き直す。 ``renderers`` は配置の Renderer(``PlacedRenderer``)。``relative`` が Unity でのルートから GameObject までの行列 R。 - 原点に読み込んだオブジェクトの行列は C·L·A(``_node_basis``)なので、ルートの Empty の行列 E の下では E·C·R·A が - Unity と同じ置き方になる。展開した Transform の値そのものを Unity 上で動かした部品(上書き前の行列も同じなので、 + 原点に読み込んだオブジェクトの行列は C·L·A(``core.model_space.node_basis``)なので、ルートの Empty の行列 E の下では + E·C·R·A(``core.model_space.renderer_world``)が Unity と同じ置き方になる。展開した Transform の値そのものを Unity 上で動かした部品(上書き前の行列も同じなので、 上書きからは分からない)と、上書きで動かした部品の両方をこれで扱う。いまの置き方と同じ(誤差の範囲)なら触らない。 オブジェクトと Renderer の対応は prefab の表と同じ照合(``find_renderer``。Blender が連番を付け替えた名前も引ける。#155)で、 @@ -559,7 +494,7 @@ def apply_renderer_worlds(template: SceneTemplate, objects, root, renderers: dic base = _world_matrix(root) if base is None: return 0 - base = base @ Matrix(UNITY_TO_BLENDER) + base = _mat4(base) table = {name: RendererMaterials(name, mesh_file_id=r.mesh_file_id) for name, r in renderers.items()} claimed: dict[str, list] = {} for original, obj in zip(template.objects, objects): @@ -570,13 +505,13 @@ def apply_renderer_worlds(template: SceneTemplate, objects, root, renderers: dic for name, found in claimed.items(): relative = renderers[name].relative if relative is not None and len(found) == 1: - targets.append((found[0], Matrix(relative))) + targets.append((found[0], relative)) skipped = 0 for obj, relative in sorted(targets, key=lambda item: _depth(item[0])): current = _world_matrix(obj) - target = base @ relative @ basis_a - if current is not None and _same_placement(current, target): + target = Matrix(renderer_world(base, relative, basis_a)) + if current is not None and same_placement(_mat4(current), _mat4(target)): continue frame = _parent_frame(obj) if current is None or frame is None: @@ -589,15 +524,12 @@ def apply_renderer_worlds(template: SceneTemplate, objects, root, renderers: dic def apply_offsets(objects, root_world, offsets, scale: float) -> int: """中のノードが上書きで動いたオブジェクトを、そのノードから逆算した位置に置く。アーマチュアで変形するものは数えて飛ばす。 - ``root_world`` は配置のルートの Unity での行列。置いた直後のオブジェクトの行列は「ルートの行列 · globalScale · - 原点に読み込んだときの行列」なので、そこから原点での行列を求め、逆算したルートの行列を掛け直す。 + ``root_world`` は配置のルートの Unity での行列。行列の組み立ては ``core.model_space.offset_world``。 行列は親をたどって計算で求める(以前はオブジェクトごとに ``view_layer.update()`` を呼んでいた。#75)。 """ targets = [o for o in objects if _by_object_name(offsets, node_name(o)) is not None] if not targets: return 0 - scale_matrix = Matrix.Scale(scale, 4) if math.isfinite(scale) and scale > 0 else Matrix.Identity(4) - to_origin = (Matrix(unity_to_blender(root_world)) @ scale_matrix).inverted_safe() worlds = {o: _world_matrix(o) for o in targets} # 動かす前にまとめて求める skipped = 0 for obj in sorted(targets, key=_depth): @@ -605,6 +537,7 @@ def apply_offsets(objects, root_world, offsets, scale: float) -> int: if worlds[obj] is None or frame is None: skipped += 1 continue - world = Matrix(unity_to_blender(_by_object_name(offsets, node_name(obj)))) @ scale_matrix @ to_origin @ worlds[obj] + offset = _by_object_name(offsets, node_name(obj)) + world = Matrix(offset_world(offset, root_world, scale, _mat4(worlds[obj]))) obj.matrix_basis = frame.inverted_safe() @ world return skipped diff --git a/unitypackage_loader/blender/scene_placement.py b/unitypackage_loader/blender/scene_placement.py index 136cb18..614b111 100644 --- a/unitypackage_loader/blender/scene_placement.py +++ b/unitypackage_loader/blender/scene_placement.py @@ -17,6 +17,7 @@ from ..core.prefab import RendererMaterials from ..core.scene_import import KIND_PREFAB, KIND_SCENE, PlacedKind, PlacementStats, parts_to_hide, scene_warnings, unused_in_placement from ..core.terrain import terrain_data_ref, terrain_local +from ..core.model_space import ModelUnits from ..core.transform import inverse_affine, multiply, unity_to_blender from ..core.unity_yaml import to_float from ..core.units import SceneSummary @@ -25,7 +26,6 @@ from .unity_meshes import make_mesh_object from .prepare import ModelSummary from .scene_objects import ( - ModelUnits, SceneTemplate, apply_collapsed_root, apply_node_transforms, diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 471e839..ca518bb 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.17.0" +version = "1.18.0-dev.1" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/model_space.py b/unitypackage_loader/core/model_space.py new file mode 100644 index 0000000..d009bc9 --- /dev/null +++ b/unitypackage_loader/core/model_space.py @@ -0,0 +1,189 @@ +"""シーン・prefab に置いたモデルの行列の計算(FBX の単位と軸、ノードへの上書き、Renderer の位置)。bpy 非依存。 + +行列は ``core/transform.py`` と同じ 4x4 の行優先タプル。Blender のオブジェクトへの当てはめ(親をたどった行列、 +アーマチュアで変形するものの除外)は ``blender/scene_objects.py`` が行う(#263 で分けた)。 + +記号: + +- C: Unity → Blender の基底(``transform.UNITY_TO_BLENDER``) +- A: Blender のオブジェクトのローカル座標(FBX のファイルの座標)→ Unity のノード空間(``ModelUnits.basis_a``) +- L: Unity のノード空間での、ノードの行列 + +原点に読み込んだ Blender のオブジェクトの行列 N と L の関係は N = C·L·A(Issue #53 で確かめた)。 +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from .fbx_units import blender_axis_matrix, unity_axis_matrix +from .transform import ( + BLENDER_TO_UNITY, + IDENTITY, + UNITY_TO_BLENDER, + Mat4, + Quat, + Vec3, + chain, + inverse_affine, + multiply, + trs, + unity_to_blender, +) + + +def _to_mat4(m3) -> Mat4: + return tuple((*(float(v) for v in m3[i]), 0.0) for i in range(3)) + ((0.0, 0.0, 0.0, 1.0),) # type: ignore[return-value] + + +def _diagonal(x: float, y: float, z: float) -> Mat4: + return ((x, 0.0, 0.0, 0.0), (0.0, y, 0.0, 0.0), (0.0, 0.0, z, 0.0), (0.0, 0.0, 0.0, 1.0)) + + +def _inverse(m: Mat4) -> Mat4: + """逆行列。特異なら単位行列(呼ぶ側の行列は、スケールが正の値に限っているので特異にならない)。""" + return inverse_affine(m) or IDENTITY + + +def file_scale(unit_scale: float | None) -> float: + """Unity の fileScale(= FBX の UnitScaleFactor / 100)。読めなければ 1 として扱う。""" + return (unit_scale if unit_scale and math.isfinite(unit_scale) and unit_scale > 0 else 1.0) / 100.0 + + +def positive_scale(scale: float) -> float | None: + """有効な倍率(有限で正)ならその値、そうでなければ None。""" + return scale if math.isfinite(scale) and scale > 0 else None + + +@dataclass(frozen=True) +class ModelUnits: + """配置の計算に使う、モデルの FBX の単位と軸(``read_unit_scale`` / ``read_axes``。FBX 以外は空)。""" + + unit_scale: float | None = None + axes: tuple[int, ...] | None = None + global_scale: float = 1.0 # .meta の globalScale(Unity は頂点と子の位置に焼き込む) + + def basis_a(self) -> Mat4: + """Blender のオブジェクトのローカル座標(FBX のファイルの座標)→ Unity のノード空間(A = f·U)。 + + U は Unity がこの FBX に掛ける軸の変換(``fbx_units.unity_axis_matrix``)。Y が上の FBX では diag(-1, 1, 1) で、 + A = diag(-f, f, f)(#53 で確かめた形)。3ds Max の Z が上の FBX では Y と Z の入れ替え(Cardboard Boxes Pack。#240)。 + """ + f = file_scale(self.unit_scale) + return multiply(_diagonal(f, f, f), _to_mat4(unity_axis_matrix(self.axes))) + + def world_basis_a(self) -> Mat4: + """``basis_a`` に globalScale も掛けたもの(ルートの Empty の下で、親の逆行列を通さずにワールドで置くとき)。""" + g = positive_scale(self.global_scale) or 1.0 + return multiply(_diagonal(g, g, g), self.basis_a()) + + +def axis_correction(axes: tuple[int, ...] | None) -> Mat4 | None: + """Y が上でない FBX を読み込んだ直後に、最上位のオブジェクトへ左から掛けて Unity と同じ向きにする行列(K = C·U·B⁻¹)。 + + Blender の FBX インポーターはファイルの上の軸を +Z にする(B。Z が上の 3ds Max の FBX では回転を掛けない)が、Unity は + U で Y が上にする(#240)。Y が上の FBX では K が単位行列(C·diag(-1, 1, 1) = B)なので None。 + """ + if axes is None or axes[0] != 2: + return None + unity = _to_mat4(unity_axis_matrix(axes)) + blender = _to_mat4(blender_axis_matrix(axes)) + return chain((UNITY_TO_BLENDER, unity, _inverse(blender))) + + +def _quat_from_rotation(r) -> Quat: + """直交行列(行優先 3x3)の回転を Unity の並びの四元数 (x, y, z, w) にする。""" + trace = r[0][0] + r[1][1] + r[2][2] + if trace > 0: + s = math.sqrt(trace + 1.0) * 2 + return ((r[2][1] - r[1][2]) / s, (r[0][2] - r[2][0]) / s, (r[1][0] - r[0][1]) / s, 0.25 * s) + if r[0][0] > r[1][1] and r[0][0] > r[2][2]: + s = math.sqrt(max(1.0 + r[0][0] - r[1][1] - r[2][2], 0.0)) * 2 or 1.0 + return (0.25 * s, (r[0][1] + r[1][0]) / s, (r[0][2] + r[2][0]) / s, (r[2][1] - r[1][2]) / s) + if r[1][1] > r[2][2]: + s = math.sqrt(max(1.0 + r[1][1] - r[0][0] - r[2][2], 0.0)) * 2 or 1.0 + return ((r[0][1] + r[1][0]) / s, 0.25 * s, (r[1][2] + r[2][1]) / s, (r[0][2] - r[2][0]) / s) + s = math.sqrt(max(1.0 + r[2][2] - r[0][0] - r[1][1], 0.0)) * 2 or 1.0 + return ((r[0][2] + r[2][0]) / s, (r[1][2] + r[2][1]) / s, 0.25 * s, (r[1][0] - r[0][1]) / s) + + +def decompose(m: Mat4) -> tuple[Vec3, Quat, Vec3]: + """位置・回転(Unity の並びの四元数)・スケールに分ける(``mathutils.Matrix.decompose`` と同じ約束)。 + + スケールは各列の長さ。行列式が負(鏡映)なら、回転とスケールの 3 成分すべての符号を反転する。 + """ + location = (m[0][3], m[1][3], m[2][3]) + columns = [[m[0][j], m[1][j], m[2][j]] for j in range(3)] + scale = [math.sqrt(sum(v * v for v in col)) for col in columns] + normalized = [[v / s for v in col] if s > 0 else [0.0, 0.0, 0.0] for col, s in zip(columns, scale)] + a, b, c = columns + det = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]) + if det < 0: + normalized = [[-v for v in col] for col in normalized] + scale = [-s for s in scale] + rotation = [[normalized[j][i] for j in range(3)] for i in range(3)] # 列から行優先に戻す + return location, _quat_from_rotation(rotation), (scale[0], scale[1], scale[2]) + + +def node_basis(basis: Mat4, spec: dict, basis_a: Mat4) -> Mat4: + """ノードへの上書き ``spec``(``position`` / ``rotation`` / ``scale`` の成分ごと。None は上書きなし)を当てた行列(C·M·A)。 + + Unity のノード空間の行列 L と、原点に読み込んだ Blender のオブジェクトの行列 N の関係は N = C·L·A + (C は Unity → Blender の基底、A は ``ModelUnits.basis_a``。Y が上の FBX では diag(-f, f, f)、f は Unity の fileScale + = FBX の UnitScaleFactor / 100)。Japanese Apartment の FBX(UnitScaleFactor 100 と 1)と Blender 由来の FBX で、 + Unity 6 が読んだノードの値と突き合わせて確かめた(Issue #53)。元のノード値を L = C⁻¹·N·A⁻¹ で求め、上書きの無い成分は + その値のまま使う。 + """ + location, rotation, scale = decompose(chain((BLENDER_TO_UNITY, basis, _inverse(basis_a)))) + values = {"position": list(location), "rotation": list(rotation), "scale": list(scale)} + for key, current in values.items(): + for index, value in enumerate(spec.get(key, [])): + if value is not None and index < len(current): + current[index] = value + local = trs(tuple(values["position"]), tuple(values["rotation"]), tuple(values["scale"])) # type: ignore[arg-type] + return chain((UNITY_TO_BLENDER, local, basis_a)) + + +def collapsed_root(basis: Mat4, spec: dict, basis_a: Mat4) -> tuple[Mat4, Mat4]: + """1 メッシュの FBX をモデルの PrefabInstance で置いた配置の、ルートの Empty とオブジェクトの行列(#99)。 + + この形の FBX では Unity のモデルのルートの Transform の値が FBX のノードの変換 L で、シーンの上書きは + その成分を置き換える(上書きしなかった成分は L のまま)。ルートの Empty は C·M·C⁻¹(M = L に上書きを当てた行列)、 + オブジェクトはノードを単位行列にした C·A にする。``basis`` は原点に読み込んだときのオブジェクトの行列。 + """ + neutral = multiply(UNITY_TO_BLENDER, basis_a) + return multiply(node_basis(basis, spec, basis_a), _inverse(neutral)), neutral + + +def renderer_world(root_world: Mat4, relative: Mat4, world_basis_a: Mat4) -> Mat4: + """FBX を展開した配置で、Renderer の GameObject に置くオブジェクトのワールド行列 E·C·R·A(#186)。 + + ``root_world`` はルートの Empty のワールド行列 E、``relative`` は Unity でのルートから GameObject までの行列 R。 + ``world_basis_a`` は ``ModelUnits.world_basis_a``(ワールドで直接置くので globalScale も含める。#240)。 + """ + return chain((root_world, UNITY_TO_BLENDER, relative, world_basis_a)) + + +def offset_world(offset: Mat4, root_world: Mat4, scale: float, current: Mat4) -> Mat4: + """中のノードが上書きで動いたオブジェクトのワールド行列。 + + 置いた直後のオブジェクトの行列 ``current`` は「ルートの行列 · globalScale · 原点に読み込んだときの行列」なので、 + そこから原点での行列を求め、ノードから逆算したルートの行列 ``offset``(Unity の行列)を掛け直す。 + """ + s = positive_scale(scale) + scale_matrix = _diagonal(s, s, s) if s is not None else IDENTITY + to_origin = _inverse(multiply(unity_to_blender(root_world), scale_matrix)) + return chain((unity_to_blender(offset), scale_matrix, to_origin, current)) + + +def same_placement(a: Mat4, b: Mat4) -> bool: + """2 つの行列が、float の誤差を除いて同じ置き方か(列の長さに対する相対誤差と、位置の誤差)。 + + 位置は 0.1 mm に、座標の大きさに比例する float の誤差(100 万分の 1)を足した範囲で比べる。座標に比例させるだけだと、 + 原点から離れた部品の数 cm のずれを見逃す(Farm の 216 m 先の門扉で 2 cm)。 + """ + size = max(1.0, *(math.sqrt(sum(a[r][i] ** 2 for r in range(3))) for i in range(3))) + if any(abs(a[r][c] - b[r][c]) > 1e-4 * size for r in range(3) for c in range(3)): + return False + return all(abs(a[r][3] - b[r][3]) <= 1e-4 + 1e-6 * abs(a[r][3]) for r in range(3)) From 28dda2f914a98febdcc68dec6a5862e3dfbe794c Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 15:47:00 +0900 Subject: [PATCH 02/25] =?UTF-8?q?refactor:=20placements()=20=E3=82=92?= =?UTF-8?q?=E6=AE=B5=E9=9A=8E=E3=81=94=E3=81=A8=E3=81=AE=E9=96=A2=E6=95=B0?= =?UTF-8?q?=E3=81=AB=E5=88=86=E3=81=91=E3=82=8B=EF=BC=88#263=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FBX のノード名(#237)、最上位のノードの扱い(#185)、メッシュの差し替え(#242)などの 分岐が積み重なって 174 行になっていた placements() を、表の準備(_PlacementTables)、 モデルの PrefabInstance の配置、Renderer の行、候補をルートとみなさない判定、 ルートのノードを単位行列にする判定(_root_node_label)、Renderer の追加に分けた。 処理の中身と順番は変えていない。 Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/placement.py | 286 +++++++++++++--------- 2 files changed, 178 insertions(+), 110 deletions(-) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index ca518bb..732fbe4 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.1" +version = "1.18.0-dev.2" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/placement.py b/unitypackage_loader/core/placement.py index 8519260..e83b547 100644 --- a/unitypackage_loader/core/placement.py +++ b/unitypackage_loader/core/placement.py @@ -261,85 +261,22 @@ def placements( Renderer から作った配置のルートがそのノード(GameObject 名か、ルートの Renderer のメッシュ参照で判定)なら、 そのノードを単位行列にする。表の有無によらない(表ではルートが ``//RootNode`` になり、ノード名として引けないため)。Issue #185。 """ - root_names = _model_names(model_guids) - models = set(root_names) - tops = {g.lower(): name for g, name in (top_nodes or {}).items() if name} - top_levels = {g.lower(): names for g, names in (top_level_nodes or {}).items() if names} - tables = {g.lower(): table for g, table in (name_tables or {}).items()} - node_names = {g: names for g, table in tables.items() if (names := node_names_in_table(table)) is not None} - # Renderer の配置で使う表。表の無い 1 ノードの FBX は、メッシュ参照の fileID → ノード名の表をその場で作る - sole = { - g.lower(): name for g, name in (sole_nodes or {}).items() - if name and not tables.get(g.lower()) and g.lower() in models - } - renderer_tables = {g: table for g, table in tables.items() if g not in sole} - for node in h.nodes.values(): - renderer = node.renderer - if renderer is not None and renderer.mesh_guid in sole and renderer.mesh_file_id: - renderer_tables.setdefault(renderer.mesh_guid, {})[renderer.mesh_file_id] = sole[renderer.mesh_guid] - for g in sole: - if g in renderer_tables: - node_names[g] = set() - # 表に無いメッシュを指す Renderer があれば、その表は一部の行しか無い(古い番号を引き継いだ表)のでノードは分からない - for node in h.nodes.values(): - renderer = node.renderer - if ( - renderer is not None and renderer.mesh_guid in node_names - and renderer.mesh_file_id and renderer.mesh_file_id not in renderer_tables[renderer.mesh_guid] - ): - del node_names[renderer.mesh_guid] + ctx = _PlacementTables.build(h, model_guids, name_tables, sole_nodes, top_nodes, top_level_nodes) worlds = world_matrices(h) active = effective_active(h) - children = h.children() # 1 回目: Renderer ごとに名前とルートの候補を決める。モデルの PrefabInstance はそのまま配置にする items: list[ModelPlacement | _RendererRow] = [] groups: dict[tuple[int, str], list[_RendererRow]] = {} for key, node in h.nodes.items(): if node.model_guid is not None: - placement = ModelPlacement(node.model_guid, key, worlds[key], active[key]) - for name, slots in node.model_materials.items(): - placement.renderers[name] = PlacedRenderer(name, list(slots), CLASS_MESH_RENDERER, True) - placement.node_transforms = copy.deepcopy(node.model_transforms) - placement.parts = {k: replace(v) for k, v in node.model_parts.items()} - _swap_model_mesh(placement, node, tables, sole_nodes or {}, models) - # 1 メッシュの FBX は、ルートの Transform が FBX のノードの変換なので、読み込み側で組み立て直す(#99) - collapsed = collapsed_root_name(tables.get(placement.model_guid, {})) - if collapsed is not None: - placement.root_node = collapsed - placement.node_transforms.setdefault(collapsed, {}) - elif node.collapsed_key == SOLE_NODE and SOLE_NODE in placement.node_transforms: - # 表の無いモデルでルートを上書きした配置。畳まれた形かは読み込み側がオブジェクトの数で決める(#111) - placement.root_node = SOLE_NODE - items.append(placement) - continue - renderer = node.renderer - if renderer is None or renderer.mesh_guid not in models: - continue - # FBX のノード名と同じ GameObject 名を優先する(複数のノードが 1 つのメッシュを共有する FBX もあるため) - names = node_names.get(renderer.mesh_guid) - table = renderer_tables.get(renderer.mesh_guid, {}) - mesh_name = table.get(renderer.mesh_file_id) - name = unity_base_name(node.name) - if not (names and name in names) and mesh_name and mesh_name != ROOT_NODE_NAME: - name = mesh_name - candidate, own = _root_candidates(h, key, renderer.mesh_guid, table, names) - item = _RendererRow(key, name, candidate, own) - groups.setdefault((candidate, renderer.mesh_guid), []).append(item) - items.append(item) - - # 候補をモデルのルートとみなさないグループ - dissolved: set[tuple[int, str]] = set() - for (candidate, guid), rows in groups.items(): - if guid not in node_names or all(own == candidate for _, _, _, own in rows): + items.append(_model_instance_placement(key, node, worlds[key], active[key], ctx)) continue - repeated = len({name for _, name, _, _ in rows}) < len(rows) - # 部品が 1 つだけのときに限る(照明の prefab にろうそくを足したような、モデルのルートに別のモデルを置いたものは分けない) - mixed = len(rows) == 1 and unity_base_name(h.nodes[candidate].name) != root_names.get(guid) and any( - _is_foreign(h.nodes[child], guid, models) for child in children.get(candidate, []) if child in h.nodes - ) - if repeated or mixed: - dissolved.add((candidate, guid)) + row = _renderer_row(h, key, node, ctx) + if row is not None: + groups.setdefault((row.candidate, node.renderer.mesh_guid), []).append(row) + items.append(row) + dissolved = _dissolved_groups(h, groups, ctx) # 2 回目: 配置を作る result: list[ModelPlacement] = [] @@ -348,53 +285,184 @@ def placements( if isinstance(item, ModelPlacement): result.append(item) continue - key, name, candidate, own = item - node = h.nodes[key] - renderer = node.renderer - guid = renderer.mesh_guid - root = own if (candidate, guid) in dissolved else candidate + guid = h.nodes[item.key].renderer.mesh_guid + root = item.own if (item.candidate, guid) in dissolved else item.candidate placement = by_root.get((root, guid)) if placement is None: placement = ModelPlacement(guid, root, worlds[root], active[root]) - names = node_names.get(guid) - if names is not None: - label = _fbx_node_name(h.nodes[root], guid, renderer_tables.get(guid, {}), names) - # FBX の中のノードをルートにした。ルートに Renderer が無くても、最初に見たのが子の Renderer でも同じ(#183) - if label is not None: - placement.node_transforms[label] = copy.deepcopy(_IDENTITY_NODE) - elif guid in top_levels and not tables.get(guid) and root == key: - # 表の無い、最上位のノードが複数ある FBX を展開した GameObject(MeshDecals.fbx の RoadDecals.002 だけを置いた - # prefab)。ルートの GameObject がその最上位のノードなら、Unity の行列がノードの変換を含むので単位行列にする(#237) - base = unity_base_name(h.nodes[root].name) - if base in top_levels[guid]: - placement.node_transforms[base] = copy.deepcopy(_IDENTITY_NODE) - # FBX を展開したルートが、Unity が畳んだ最上位のノード(#185) - top = tops.get(guid) - if top and not placement.node_transforms and _is_top_node(h.nodes[root], guid, top, renderer_tables.get(guid, {})): - placement.node_transforms[top] = copy.deepcopy(_IDENTITY_NODE) + label = _root_node_label(h, root, item.key, guid, ctx) + if label is not None: + placement.node_transforms[label] = copy.deepcopy(_IDENTITY_NODE) by_root[(root, guid)] = placement result.append(placement) - if name in placement.renderers: - placement.renderers[name].relative = None - continue # 同じモデルに同名の GameObject があれば先のものを使う(prefab の表と同じ) - # ルート自身の Renderer は置き直さない。FBX の最上位のノードを Unity がルートに畳んだもので、ルートの Transform が - # ノードの変換を含むため、オブジェクトの行列との関係が中のノードと違う(置き方は #98 / #181 / #185 で決まっている) - root_inverse = inverse_affine(placement.world) if key != root else None - placement.renderers[name] = PlacedRenderer( - name, list(renderer.materials), renderer.renderer_class, active[key] and renderer.enabled, - renderer.mesh_file_id, renderer.lod_level, - multiply(root_inverse, worlds[key]) if root_inverse is not None else None, - renderer.shadows_only, - ) - # ルートからこの Node までの、上書き前の行列の積で逆算する - inverse = inverse_affine(node.scope_matrix) - if inverse is not None and key != root: - implied = multiply(multiply(worlds[key], inverse), h.nodes[root].scope_matrix) - if not _close(implied, placement.world): - placement.offsets[name] = implied + _add_renderer(h, placement, item, worlds, active) return result +@dataclass +class _PlacementTables: + """``placements`` が使う、モデルごとの表(引数から作る)。""" + + root_names: dict[str, str | None] # モデルの GUID → ルートの名前 + models: set[str] + tables: dict[str, dict[int, str]] # .meta の表(fileID → 名前) + # Renderer の配置で使う表。表の無い 1 ノードの FBX は、メッシュ参照の fileID → ノード名の表をその場で作る + renderer_tables: dict[str, dict[int, str]] + node_names: dict[str, set[str]] # 表から分かる FBX のノード名(ノードが分からないモデルは無い) + sole_nodes: Mapping[str, str] # 引数のまま(#242 の差し替えで使う) + tops: dict[str, str] # 最上位のノードが 1 つだけのモデル → その名前(#185) + top_levels: dict[str, frozenset[str]] # 最上位のノードが複数あるモデル → その名前(#237) + + @classmethod + def build( + cls, + h: Hierarchy, + model_guids: ModelNames, + name_tables: dict[str, dict[int, str]] | None, + sole_nodes: Mapping[str, str] | None, + top_nodes: Mapping[str, str] | None, + top_level_nodes: Mapping[str, frozenset[str]] | None, + ) -> _PlacementTables: + root_names = _model_names(model_guids) + models = set(root_names) + tables = {g.lower(): table for g, table in (name_tables or {}).items()} + node_names = {g: names for g, table in tables.items() if (names := node_names_in_table(table)) is not None} + sole = { + g.lower(): name for g, name in (sole_nodes or {}).items() + if name and not tables.get(g.lower()) and g.lower() in models + } + renderer_tables = {g: table for g, table in tables.items() if g not in sole} + for node in h.nodes.values(): + renderer = node.renderer + if renderer is not None and renderer.mesh_guid in sole and renderer.mesh_file_id: + renderer_tables.setdefault(renderer.mesh_guid, {})[renderer.mesh_file_id] = sole[renderer.mesh_guid] + for g in sole: + if g in renderer_tables: + node_names[g] = set() + # 表に無いメッシュを指す Renderer があれば、その表は一部の行しか無い(古い番号を引き継いだ表)のでノードは分からない + for node in h.nodes.values(): + renderer = node.renderer + if ( + renderer is not None and renderer.mesh_guid in node_names + and renderer.mesh_file_id and renderer.mesh_file_id not in renderer_tables[renderer.mesh_guid] + ): + del node_names[renderer.mesh_guid] + return cls( + root_names=root_names, + models=models, + tables=tables, + renderer_tables=renderer_tables, + node_names=node_names, + sole_nodes=sole_nodes or {}, + tops={g.lower(): name for g, name in (top_nodes or {}).items() if name}, + top_levels={g.lower(): names for g, names in (top_level_nodes or {}).items() if names}, + ) + + +def _model_instance_placement(key: int, node: Node, world: Mat4, active: bool, ctx: _PlacementTables) -> ModelPlacement: + """モデルの PrefabInstance の配置(ルートの Node をそのまま使う)。""" + placement = ModelPlacement(node.model_guid, key, world, active) + for name, slots in node.model_materials.items(): + placement.renderers[name] = PlacedRenderer(name, list(slots), CLASS_MESH_RENDERER, True) + placement.node_transforms = copy.deepcopy(node.model_transforms) + placement.parts = {k: replace(v) for k, v in node.model_parts.items()} + _swap_model_mesh(placement, node, ctx.tables, ctx.sole_nodes, ctx.models) + # 1 メッシュの FBX は、ルートの Transform が FBX のノードの変換なので、読み込み側で組み立て直す(#99) + collapsed = collapsed_root_name(ctx.tables.get(placement.model_guid, {})) + if collapsed is not None: + placement.root_node = collapsed + placement.node_transforms.setdefault(collapsed, {}) + elif node.collapsed_key == SOLE_NODE and SOLE_NODE in placement.node_transforms: + # 表の無いモデルでルートを上書きした配置。畳まれた形かは読み込み側がオブジェクトの数で決める(#111) + placement.root_node = SOLE_NODE + return placement + + +def _renderer_row(h: Hierarchy, key: int, node: Node, ctx: _PlacementTables) -> _RendererRow | None: + """モデルのメッシュを直接指す Renderer の名前とルートの候補。そうでない Node なら None。""" + renderer = node.renderer + if renderer is None or renderer.mesh_guid not in ctx.models: + return None + # FBX のノード名と同じ GameObject 名を優先する(複数のノードが 1 つのメッシュを共有する FBX もあるため) + names = ctx.node_names.get(renderer.mesh_guid) + table = ctx.renderer_tables.get(renderer.mesh_guid, {}) + mesh_name = table.get(renderer.mesh_file_id) + name = unity_base_name(node.name) + if not (names and name in names) and mesh_name and mesh_name != ROOT_NODE_NAME: + name = mesh_name + candidate, own = _root_candidates(h, key, renderer.mesh_guid, table, names) + return _RendererRow(key, name, candidate, own) + + +def _dissolved_groups( + h: Hierarchy, groups: dict[tuple[int, str], list[_RendererRow]], ctx: _PlacementTables +) -> set[tuple[int, str]]: + """候補をモデルのルートとみなさないグループ(``placements`` の説明を参照)。""" + children = h.children() + dissolved: set[tuple[int, str]] = set() + for (candidate, guid), rows in groups.items(): + if guid not in ctx.node_names or all(row.own == candidate for row in rows): + continue + repeated = len({row.name for row in rows}) < len(rows) + # 部品が 1 つだけのときに限る(照明の prefab にろうそくを足したような、モデルのルートに別のモデルを置いたものは分けない) + mixed = len(rows) == 1 and unity_base_name(h.nodes[candidate].name) != ctx.root_names.get(guid) and any( + _is_foreign(h.nodes[child], guid, ctx.models) for child in children.get(candidate, []) if child in h.nodes + ) + if repeated or mixed: + dissolved.add((candidate, guid)) + return dissolved + + +def _root_node_label(h: Hierarchy, root: int, key: int, guid: str, ctx: _PlacementTables) -> str | None: + """Renderer から作った配置のルートが FBX の中のノードなら、そのノードの名前(単位行列にする)。 + + ``key`` は配置を作るきっかけになった Renderer の Node。 + """ + names = ctx.node_names.get(guid) + label = None + if names is not None: + # FBX の中のノードをルートにした。ルートに Renderer が無くても、最初に見たのが子の Renderer でも同じ(#183) + label = _fbx_node_name(h.nodes[root], guid, ctx.renderer_tables.get(guid, {}), names) + elif guid in ctx.top_levels and not ctx.tables.get(guid) and root == key: + # 表の無い、最上位のノードが複数ある FBX を展開した GameObject(MeshDecals.fbx の RoadDecals.002 だけを置いた + # prefab)。ルートの GameObject がその最上位のノードなら、Unity の行列がノードの変換を含むので単位行列にする(#237) + base = unity_base_name(h.nodes[root].name) + if base in ctx.top_levels[guid]: + label = base + if label is not None: + return label + # FBX を展開したルートが、Unity が畳んだ最上位のノード(#185) + top = ctx.tops.get(guid) + if top and _is_top_node(h.nodes[root], guid, top, ctx.renderer_tables.get(guid, {})): + return top + return None + + +def _add_renderer(h: Hierarchy, placement: ModelPlacement, item: _RendererRow, worlds: dict, active: dict) -> None: + """配置に Renderer を加える(同名が既にあれば先のものを使い、置き直しの行列を外す)。""" + key, name, root = item.key, item.name, placement.root + node = h.nodes[key] + renderer = node.renderer + if name in placement.renderers: + placement.renderers[name].relative = None + return # 同じモデルに同名の GameObject があれば先のものを使う(prefab の表と同じ) + # ルート自身の Renderer は置き直さない。FBX の最上位のノードを Unity がルートに畳んだもので、ルートの Transform が + # ノードの変換を含むため、オブジェクトの行列との関係が中のノードと違う(置き方は #98 / #181 / #185 で決まっている) + root_inverse = inverse_affine(placement.world) if key != root else None + placement.renderers[name] = PlacedRenderer( + name, list(renderer.materials), renderer.renderer_class, active[key] and renderer.enabled, + renderer.mesh_file_id, renderer.lod_level, + multiply(root_inverse, worlds[key]) if root_inverse is not None else None, + renderer.shadows_only, + ) + # ルートからこの Node までの、上書き前の行列の積で逆算する + inverse = inverse_affine(node.scope_matrix) + if inverse is not None and key != root: + implied = multiply(multiply(worlds[key], inverse), h.nodes[root].scope_matrix) + if not _close(implied, placement.world): + placement.offsets[name] = implied + + @dataclass class PrimitivePlacement: """モデルファイルではないメッシュを使う Renderer。Unity の組み込みメッシュ(Quad・Plane・Cube など。Issue #190)か、 From 5f785314eba47197d9180034b5ac9a2502d239ba Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 15:47:00 +0900 Subject: [PATCH 03/25] =?UTF-8?q?refactor:=20prepare=5Fpackage()=20?= =?UTF-8?q?=E3=82=92=E3=83=9E=E3=83=86=E3=83=AA=E3=82=A2=E3=83=AB=E3=83=BB?= =?UTF-8?q?=E3=83=A2=E3=83=87=E3=83=AB=E3=83=BBprefab=E3=83=BB=E3=83=91?= =?UTF-8?q?=E3=82=A4=E3=83=97=E3=83=A9=E3=82=A4=E3=83=B3=E3=81=AE=E6=AE=B5?= =?UTF-8?q?=E9=9A=8E=E3=81=AB=E5=88=86=E3=81=91=E3=82=8B=EF=BC=88#263?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 117 行の prepare_package() を、.mat の解析(_parse_materials)、モデルのまとめ (_summarize_models / _model_skip_reason)、prefab の展開と表づくり(_analyze_prefabs)、 パイプラインの判定(_decide_pipeline)、ダイアログの prefab の一覧(_summarize_prefab_list)に 分け、本体は流れだけにした。警告の順番を含めて結果は変えていない。 Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender/prepare.py | 115 +++++++++++++++------- unitypackage_loader/blender_manifest.toml | 2 +- 2 files changed, 81 insertions(+), 36 deletions(-) diff --git a/unitypackage_loader/blender/prepare.py b/unitypackage_loader/blender/prepare.py index 2943df2..7777088 100644 --- a/unitypackage_loader/blender/prepare.py +++ b/unitypackage_loader/blender/prepare.py @@ -262,6 +262,8 @@ def prepare_package( """パッケージを走査して解析する。``import_blend`` が False なら同梱 .blend は「読み込まない」扱いにする。 ``pkg`` に走査済みのパッケージを渡すと、走査し直さない(入れ子のパッケージの判定で先に走査したとき。#217)。 + 段階は、マテリアル(``_parse_materials``)→ モデル(``_summarize_models``)→ prefab(``_analyze_prefabs``)→ + パイプラインの判定(``_decide_pipeline``)。シーンの展開は ``PreparedPackage.ensure_scenes`` まで遅らせる。 """ path = Path(filepath) if pkg is None: @@ -270,9 +272,34 @@ def prepare_package( table = shader_table or default_table() warnings: list[str] = list(pkg.warnings) + list(table.warnings) + unity_mats, normalized = _parse_materials(pkg, table, warnings.append) + models = _summarize_models(pkg, unity_mats, import_blend, warnings.append) + mesh_assets = _mesh_assets(pkg) + if not models and not ((pkg.scenes() or pkg.prefabs()) and (mesh_assets or _has_terrain_data(pkg))): + raise PackageError("the package contains no model files (.fbx/.obj/.gltf/.glb/.vrm/.dae/.blend)") + + referenced = material_textures(normalized, normalized) + missing = {g for g in referenced if pkg.get(g) is None} + catalog = _catalog(models, mesh_assets) + expander, prefab_analyses = _analyze_prefabs(pkg, models, catalog, warnings.append) + pipeline = _decide_pipeline(pkg, normalized, warnings.append) + return PreparedPackage( + path, pkg, unity_mats, normalized, models, referenced, missing, + prefab_analyses=prefab_analyses, warnings=warnings, prefabs=_summarize_prefab_list(pkg, models, prefab_analyses), + scene_entries=pkg.scenes(), _expander=expander, + pipeline=pipeline.pipeline, + pipeline_source=pipeline.source, + catalog=catalog, + ) + + +def _parse_materials( + pkg: UnityPackage, table: ShaderTable, warn: Callable[[str], None] +) -> tuple[dict[str, UnityMaterial], dict[str, NormalizedMaterial]]: + """.mat(とマテリアルを入れた .asset)を読み、生データと中間表現を GUID ごとに返す。読めないものは警告して外す(#69)。""" unity_mats: dict[str, UnityMaterial] = {} normalized: dict[str, NormalizedMaterial] = {} - declared = _ShaderDeclarations(pkg, warnings.append) + declared = _ShaderDeclarations(pkg, warn) # マテリアルを .asset に入れたもの(Terrain Asset Pack の Materials/*.asset。#216)も .mat と同じに読む。 # .asset は走査でキャッシュしないので、まとめて 1 回で読む asset_materials = [ @@ -290,41 +317,52 @@ def prepare_package( umat = apply_uv_transforms(umat, declared.uv_transforms(umat.shader_guid)) norm = normalize_material(umat, table, declared.get(umat.shader_guid), declared.defaults(umat.shader_guid)) except Exception as exc: # noqa: BLE001 - その .mat だけを外して続ける(#69) - warn_skipped(warnings.append, f"could not parse {entry.pathname}", exc) + warn_skipped(warn, f"could not parse {entry.pathname}", exc) continue unity_mats[entry.guid] = umat normalized[entry.guid] = norm + return unity_mats, normalized + +def _model_skip_reason(entry: AssetEntry, import_blend: bool) -> str: + """モデルを読み込めない理由(読み込めるなら空)。""" + if entry.ext not in SUPPORTED_MODEL_EXTS: + return "model format not supported yet" + if entry.ext == ".blend" and not import_blend: + return BLEND_DISABLED_REASON + if entry.ext == ".dae" and not operator_available("wm", "collada_import"): + return COLLADA_UNAVAILABLE_REASON + return "" + + +def _summarize_models( + pkg: UnityPackage, unity_mats: dict[str, UnityMaterial], import_blend: bool, warn: Callable[[str], None] +) -> list[ModelSummary]: + """モデルごとに .meta を読み、マテリアルの対応付けの数と読み込めるかをまとめる。""" models: list[ModelSummary] = [] for entry in pkg.models(): - info = _model_info(entry, warnings.append) + info = _model_info(entry, warn) if entry.ext == ".obj" and entry.obj_groups == []: # グループの無い OBJ は、Unity では中のメッシュが "default"、Blender ではファイル名のオブジェクトになる(#214) info.recycle_names = {k: (Path(entry.pathname).stem if v == OBJ_DEFAULT_NAME else v) for k, v in info.recycle_names.items()} names = list(info.external_materials) resolution = resolve_materials(names, info, unity_mats, entry.pathname) resolved = sum(1 for r in resolution.values() if r.guid) - skip_reason = "" - if entry.ext not in SUPPORTED_MODEL_EXTS: - skip_reason = "model format not supported yet" - elif entry.ext == ".blend" and not import_blend: - skip_reason = BLEND_DISABLED_REASON - elif entry.ext == ".dae" and not operator_available("wm", "collada_import"): - skip_reason = COLLADA_UNAVAILABLE_REASON + skip_reason = _model_skip_reason(entry, import_blend) models.append(ModelSummary(entry, len(names), resolved, not skip_reason, skip_reason, info)) - mesh_assets = _mesh_assets(pkg) - if not models and not ((pkg.scenes() or pkg.prefabs()) and (mesh_assets or _has_terrain_data(pkg))): - raise PackageError("the package contains no model files (.fbx/.obj/.gltf/.glb/.vrm/.dae/.blend)") + return models - referenced = material_textures(normalized, normalized) - missing = {g for g in referenced if pkg.get(g) is None} - # prefab は Scenes 単位と同じ展開器で展開する(Prefab Variant・ネスト・上書き・削除・古い形式。#71)。 - # 展開結果はキャッシュされ、あとでシーンを展開するときにも使う - model_guids = [m.guid for m in models] - catalog = _catalog(models, mesh_assets) +def _analyze_prefabs( + pkg: UnityPackage, models: list[ModelSummary], catalog: ModelCatalog, warn: Callable[[str], None] +) -> tuple[Expander, dict[str, PrefabAnalysis]]: + """prefab を展開して、モデルへの割り当ての表を作る。展開器(キャッシュ付き)と、表のある prefab の解析を返す。 + + prefab は Scenes 単位と同じ展開器で展開する(Prefab Variant・ネスト・上書き・削除・古い形式。#71)。 + 展開結果はキャッシュされ、あとでシーンを展開するときにも使う。当たり判定にだけ使うモデルには ``collider_only`` を立てる(#166)。 + """ collider_meshes: set[str] = set() - expander = catalog.expander(_prefab_reader(pkg, warnings.append, collider_meshes)) + expander = catalog.expander(_prefab_reader(pkg, warn, collider_meshes)) used_by_prefabs: set[str] = set() # prefab の Renderer か配置が使うモデル prefab_analyses: dict[str, PrefabAnalysis] = {} for entry in pkg.prefabs(): @@ -338,10 +376,10 @@ def prepare_package( analysis.meshes = [p for p in catalog.summarize(hierarchy).primitives if p.mesh_guid] used_by_prefabs.update(p.model_guid for p in placed) except Exception as exc: # noqa: BLE001 - その prefab の割り当てだけを外して続ける(#69) - warn_skipped(warnings.append, f"could not resolve prefab {entry.pathname}", exc) + warn_skipped(warn, f"could not resolve prefab {entry.pathname}", exc) continue if hierarchy.unresolved_material_overrides: # 位置などの上書きは Models / Prefabs 単位では使わないので数えない - warnings.append( + warn( f"prefab {entry.pathname}: {hierarchy.unresolved_material_overrides} material override(s) on objects inside a model " "are not read yet; the model's own assignments are used for them" ) @@ -349,29 +387,36 @@ def prepare_package( prefab_analyses[entry.pathname] = analysis for m in models: m.collider_only = m.guid in collider_meshes and m.guid not in used_by_prefabs - unsupported = {m.guid: m.skip_reason for m in models if not m.supported} - # シェーダー表で分かったマテリアルだけを手掛かりにする。指紋で URP / HDRP と読んだ表に無いシェーダーは使わない(#116)。 - # シーン・prefab のライト・カメラに URP / HDRP の追加データがあれば、そちらを優先する(#120) + return expander, prefab_analyses + + +def _decide_pipeline(pkg: UnityPackage, normalized: dict[str, NormalizedMaterial], warn: Callable[[str], None]): + """パッケージのレンダーパイプラインを判定する(``lights.decide_pipeline`` の結果)。 + + シェーダー表で分かったマテリアルだけを手掛かりにする。指紋で URP / HDRP と読んだ表に無いシェーダーは使わない(#116)。 + シーン・prefab のライト・カメラに URP / HDRP の追加データがあれば、そちらを優先する(#120)。 + """ pipeline = decide_pipeline( (n.family for n in normalized.values() if n.shader_name), pipelines_in_assets(_asset_bytes(pkg, pkg.scenes() + pkg.prefabs())), ) if pipeline.warning: - warnings.append(pipeline.warning) + warn(pipeline.warning) + return pipeline + + +def _summarize_prefab_list( + pkg: UnityPackage, models: list[ModelSummary], prefab_analyses: dict[str, PrefabAnalysis] +) -> list[PrefabSummary]: + """選択ダイアログに出す prefab の一覧。""" + unsupported = {m.guid: m.skip_reason for m in models if not m.supported} prefab_tables = {pathname: analysis.tables for pathname, analysis in prefab_analyses.items()} prefab_meshes = { pathname: [g for p in analysis.meshes for g in p.materials if g] for pathname, analysis in prefab_analyses.items() if analysis.meshes } - prefabs = summarize_prefabs( - ((e.guid, e.pathname) for e in pkg.prefabs()), prefab_tables, model_guids, unsupported, prefab_meshes - ) - return PreparedPackage( - path, pkg, unity_mats, normalized, models, referenced, missing, - prefab_analyses=prefab_analyses, warnings=warnings, prefabs=prefabs, scene_entries=pkg.scenes(), _expander=expander, - pipeline=pipeline.pipeline, - pipeline_source=pipeline.source, - catalog=catalog, + return summarize_prefabs( + ((e.guid, e.pathname) for e in pkg.prefabs()), prefab_tables, [m.guid for m in models], unsupported, prefab_meshes ) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 732fbe4..0006fd3 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.2" +version = "1.18.0-dev.3" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" From e5c1a5b4791d7d8d8ca744318a6b74782e19cf02 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 15:47:00 +0900 Subject: [PATCH 04/25] =?UTF-8?q?refactor:=20package.py=20=E3=81=8B?= =?UTF-8?q?=E3=82=89=20FBX=E3=83=BBOBJ=20=E3=81=AE=E4=B8=AD=E8=BA=AB?= =?UTF-8?q?=E3=81=AE=E8=AA=AD=E3=81=BF=E5=8F=96=E3=82=8A=E3=81=A8=E5=85=A5?= =?UTF-8?q?=E3=82=8C=E5=AD=90=E3=81=AE=E3=83=91=E3=83=83=E3=82=B1=E3=83=BC?= =?UTF-8?q?=E3=82=B8=E3=82=92=E5=88=86=E3=81=91=E3=82=8B=EF=BC=88#263?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 走査のときにモデルの中身から覚える情報(FBX のノード名・マテリアル名、OBJ のグループ名)を core/model_contents.py に、入れ子の .unitypackage の選び方と外側のアセットとの結合(#217)を core/nested_package.py に移した。tar のメンバー名の分解は split_member として公開し、 nested_package から使う。展開の安全確認(パス・symlink・空き容量)は package.py に残す。 Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 2 + tests/test_package.py | 13 +-- unitypackage_loader/blender/importer.py | 3 +- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/model_contents.py | 52 ++++++++++ unitypackage_loader/core/nested_package.py | 64 ++++++++++++ unitypackage_loader/core/package.py | 113 ++------------------- 7 files changed, 137 insertions(+), 112 deletions(-) create mode 100644 unitypackage_loader/core/model_contents.py create mode 100644 unitypackage_loader/core/nested_package.py diff --git a/DESIGN.md b/DESIGN.md index fe57f90..cb1460a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -602,6 +602,8 @@ unitypackage_loader/ │ └─ preferences.py ├─ core/ # bpy 非依存。純 Python で単体テスト可能 │ ├─ package.py # tar 走査・索引・オンデマンド展開 +│ ├─ model_contents.py # 走査のときにモデルの中身から覚える FBX のノード名・マテリアル名、OBJ のグループ名 +│ ├─ nested_package.py # 入れ子の .unitypackage の選び方と、外側のアセットとの結合(#217) │ ├─ unity_yaml.py # Unity YAML サブセットパーサー │ ├─ unity_binary.py # バイナリ形式の SerializedFile リーダー(TypeTree 付き) │ ├─ meta.py # ModelImporter / TextureImporter の読み取り diff --git a/tests/test_package.py b/tests/test_package.py index 3f0a2fe..ff60429 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -8,6 +8,7 @@ from unittest import mock from tests import _paths +from unitypackage_loader.core import model_contents, nested_package from unitypackage_loader.core import package as package_module from unitypackage_loader.core.package import ( LONG_PATH_DIR, @@ -450,8 +451,8 @@ class ObjGroupTests(unittest.TestCase): def test_group_names(self): data = b"mtllib a.mtl\no Ignored\ng Wall_01\nusemtl m\nf 1 2 3\ng Object001\ng Wall_01\ng\n" - self.assertEqual(package_module.obj_group_names(data), ["Wall_01", "Object001"]) - self.assertEqual(package_module.obj_group_names(b"o amulet1_amulets\nusemtl a\n"), []) + self.assertEqual(model_contents.obj_group_names(data), ["Wall_01", "Object001"]) + self.assertEqual(model_contents.obj_group_names(b"o amulet1_amulets\nusemtl a\n"), []) def test_scan_records_groups(self): with tempfile.TemporaryDirectory() as tmp: @@ -521,8 +522,8 @@ def test_nested_packages_and_default(self): }) nested = pkg.nested_packages() self.assertEqual([e.name for e in nested], ["BuiltIn_Pack.unitypackage", "HDRP.unitypackage", "URP.unitypackage"]) - self.assertEqual(package_module.default_nested_package(nested).name, "BuiltIn_Pack.unitypackage") - self.assertEqual(package_module.default_nested_package(nested[1:]).name, "HDRP.unitypackage") + self.assertEqual(nested_package.default_nested_package(nested).name, "BuiltIn_Pack.unitypackage") + self.assertEqual(nested_package.default_nested_package(nested[1:]).name, "HDRP.unitypackage") def test_merge_with_outer_assets(self): with tempfile.TemporaryDirectory() as tmp: @@ -534,11 +535,11 @@ def test_merge_with_outer_assets(self): _add(tar, f"{'b' * 32}/asset", b"inner") outer = self._package(tmp, {"Assets/Pack/BIRP.unitypackage": inner_path.read_bytes(), "Assets/Pack/ReadMe.txt": b"x"}) dest = Path(tmp) / "merged.unitypackage" - self.assertIsNone(package_module.merge_nested_package(outer, inner_path, dest)) # 外側に足すものが無い + self.assertIsNone(nested_package.merge_nested_package(outer, inner_path, dest)) # 外側に足すものが無い outer = self._package(tmp, { "Assets/Pack/BIRP.unitypackage": inner_path.read_bytes(), "Assets/Pack/Mesh.asset": b"mesh", }) - merged = package_module.merge_nested_package(outer, inner_path, dest) + merged = nested_package.merge_nested_package(outer, inner_path, dest) self.assertEqual(merged, dest) pkg = UnityPackage(merged) pkg.scan() diff --git a/unitypackage_loader/blender/importer.py b/unitypackage_loader/blender/importer.py index e738baf..8c520c7 100644 --- a/unitypackage_loader/blender/importer.py +++ b/unitypackage_loader/blender/importer.py @@ -28,7 +28,8 @@ from ..core.meta import strip_numeric_suffix from ..core.model_ids import PartMatcher, fbx_node_names from ..core.model_space import axis_correction -from ..core.package import AssetEntry, PackageError, UnityPackage, default_nested_package, merge_nested_package +from ..core.nested_package import default_nested_package, merge_nested_package +from ..core.package import AssetEntry, PackageError, UnityPackage from ..core.prefab import RendererMaterials, has_pending_renderers, resolve_model_renderers from ..core.report import ImportReport from ..core.scene_import import KIND_PREFAB, KIND_SCENE, PlacedKind, parts_to_remove diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 0006fd3..3dafea2 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.3" +version = "1.18.0-dev.4" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/model_contents.py b/unitypackage_loader/core/model_contents.py new file mode 100644 index 0000000..f18ac5b --- /dev/null +++ b/unitypackage_loader/core/model_contents.py @@ -0,0 +1,52 @@ +"""走査のときに、モデルの中身から覚えておく補助情報(FBX のノード名・マテリアル名、OBJ のグループ名)。bpy 非依存。 + +``UnityPackage.scan`` が、モデルの実体を捨てる前に ``note_model_contents`` を呼んで ``AssetEntry`` に書き込む(#263 で分けた)。 +""" + +from __future__ import annotations + +import struct +from typing import TYPE_CHECKING + +from .model_ids import parse_fbx_material_names, parse_fbx_node_names, parse_fbx_top_nodes + +if TYPE_CHECKING: + from .package import AssetEntry + + +def obj_group_names(data: bytes) -> list[str]: + """OBJ のグループ(``g`` の行)の名前。Unity はグループごとにメッシュを作り、グループが無ければ ``default`` 1 つにする(#214)。""" + names: dict[str, None] = {} + for line in data.splitlines(): + if line.startswith(b"g ") or line.startswith(b"g\t"): + name = line[2:].strip().decode("utf-8", "replace") + if name: + names.setdefault(name, None) + return list(names) + + +def note_model_contents(entry: AssetEntry, data: bytes) -> None: + """FBX の中身から、ノードが 1 つだけならその名前を、最上位のノードが 1 つだけならその名前を覚える(#181 / #185)。 + + マテリアルの名前も覚える(読み込む前に、使う .mat とテクスチャを決めるため。#164)。OBJ はグループの名前を覚える(#214)。 + """ + if entry.ext == ".obj": + entry.obj_groups = obj_group_names(data) + return + if entry.ext != ".fbx": + return + try: + names = parse_fbx_node_names(data) + tops = parse_fbx_top_nodes(data) + except (ValueError, IndexError, struct.error): + return + try: + entry.fbx_materials = parse_fbx_material_names(data) if names else None + except (ValueError, IndexError, struct.error): + entry.fbx_materials = None + if names and sum(names.values()) == 1: + entry.fbx_sole_node = next(iter(names)) + if tops is not None and len(tops) == 1: + entry.fbx_top_node = tops[0] + elif tops: + entry.fbx_top_nodes = tuple(tops) diff --git a/unitypackage_loader/core/nested_package.py b/unitypackage_loader/core/nested_package.py new file mode 100644 index 0000000..f6780bf --- /dev/null +++ b/unitypackage_loader/core/nested_package.py @@ -0,0 +1,64 @@ +"""入れ子になった .unitypackage(パイプライン別の中身をパッケージのまま同梱したもの。#217)の選び方と、外側のアセットとの結合。""" + +from __future__ import annotations + +import tarfile +from pathlib import Path, PurePosixPath + +from .package import AssetEntry, PackageError, UnityPackage, split_member + + +# 入れ子のパッケージを選ばなかったときに優先する中身(Blender のマテリアルにもっとも近い Built-in のもの。#217) +_NESTED_PREFERRED = ("builtin", "built-in", "birp", "standard", "3d") + + +def default_nested_package(entries: list[AssetEntry]) -> AssetEntry: + """入れ子のパッケージのうち、選ばなかったときに読むもの(Built-in 向けらしい名前のもの、無ければ pathname 順の最初)。""" + for entry in entries: + if any(key in PurePosixPath(entry.pathname).stem.lower() for key in _NESTED_PREFERRED): + return entry + return entries[0] + + +# 外側のパッケージにあっても読み込みに使わないもの(説明書など) +_DOCUMENT_EXTS = frozenset({".txt", ".pdf", ".md", ".rtf", ".html", ".htm", ".url"}) + + +def merge_nested_package(outer: UnityPackage, inner_path: Path, dest: Path) -> Path | None: + """入れ子のパッケージ ``inner_path`` に、外側のパッケージのアセット(入れ子のパッケージと説明書を除く)を足した + パッケージを ``dest`` に書く。外側に足すものが無ければ書かずに None。 + + 中身の prefab が外側のメッシュやテクスチャを使うことがある(Conifers BOTD の BIRP / URP / HDRP の中身は prefab とマテリアルだけで、 + メッシュは外側の Sources にある。#217)。中身にある GUID は中身のものを使う。``dest`` が両方より新しければ書き直さない。 + """ + outer.scan() + extra = { + e.guid for e in outer.entries.values() + if e.has_asset and e.ext != ".unitypackage" and e.ext not in _DOCUMENT_EXTS + } + if not extra: + return None + if dest.is_file() and dest.stat().st_mtime >= max(inner_path.stat().st_mtime, outer.path.stat().st_mtime): + return dest + dest.parent.mkdir(parents=True, exist_ok=True) + partial = dest.with_name(dest.name + ".partial") + inner_guids: set[str] = set() + try: + with tarfile.open(partial, "w:gz", compresslevel=1) as out: + for source, wanted in ((inner_path, None), (outer.path, extra)): + with tarfile.open(source, "r:*") as tar: + for member in tar: + split = split_member(member.name) + if split is None or not member.isfile(): + continue + guid = split[0] + if wanted is None: + inner_guids.add(guid) + elif guid not in wanted or guid in inner_guids: + continue + out.addfile(member, tar.extractfile(member)) + partial.replace(dest) + except (tarfile.TarError, EOFError, OSError) as exc: + partial.unlink(missing_ok=True) + raise PackageError(f"cannot combine {inner_path.name} with {outer.path.name}: {exc}") from exc + return dest diff --git a/unitypackage_loader/core/package.py b/unitypackage_loader/core/package.py index 7adf29e..8bd9261 100644 --- a/unitypackage_loader/core/package.py +++ b/unitypackage_loader/core/package.py @@ -15,14 +15,13 @@ import json import os import shutil -import struct import tarfile from collections.abc import Callable, Iterable from dataclasses import dataclass, field from pathlib import Path, PurePosixPath from .meta import MetaInfo, legacy_meta -from .model_ids import parse_fbx_material_names, parse_fbx_node_names, parse_fbx_top_nodes +from .model_contents import note_model_contents __all__ = [ "AssetEntry", @@ -165,7 +164,7 @@ def _save_record(dest_root: Path, files: dict[str, object]) -> None: pass -def _split_member(name: str) -> tuple[str, str] | None: +def split_member(name: str) -> tuple[str, str] | None: """tar メンバー名を (guid, part) に分ける。想定外の形なら None。""" parts = [p for p in name.split("/") if p not in ("", ".")] if len(parts) != 2: @@ -311,48 +310,10 @@ def _open_for_write(target: Path): return os.fdopen(os.open(target, flags, 0o644), "wb") -def obj_group_names(data: bytes) -> list[str]: - """OBJ のグループ(``g`` の行)の名前。Unity はグループごとにメッシュを作り、グループが無ければ ``default`` 1 つにする(#214)。""" - names: dict[str, None] = {} - for line in data.splitlines(): - if line.startswith(b"g ") or line.startswith(b"g\t"): - name = line[2:].strip().decode("utf-8", "replace") - if name: - names.setdefault(name, None) - return list(names) - - -def _note_fbx(entry: AssetEntry, data: bytes) -> None: - """FBX の中身から、ノードが 1 つだけならその名前を、最上位のノードが 1 つだけならその名前を覚える(#181 / #185)。 - - マテリアルの名前も覚える(読み込む前に、使う .mat とテクスチャを決めるため。#164)。OBJ はグループの名前を覚える(#214)。 - """ - if entry.ext == ".obj": - entry.obj_groups = obj_group_names(data) - return - if entry.ext != ".fbx": - return - try: - names = parse_fbx_node_names(data) - tops = parse_fbx_top_nodes(data) - except (ValueError, IndexError, struct.error): - return - try: - entry.fbx_materials = parse_fbx_material_names(data) if names else None - except (ValueError, IndexError, struct.error): - entry.fbx_materials = None - if names and sum(names.values()) == 1: - entry.fbx_sole_node = next(iter(names)) - if tops is not None and len(tops) == 1: - entry.fbx_top_node = tops[0] - elif tops: - entry.fbx_top_nodes = tuple(tops) - - def _drop_cache(entry: AssetEntry) -> None: - """キャッシュしない拡張子の実体を捨てる。捨てる前に FBX のノード名だけ見ておく。""" + """キャッシュしない拡張子の実体を捨てる。捨てる前に FBX のノード名などを見ておく(``model_contents``)。""" if entry._cache is not None: - _note_fbx(entry, entry._cache) + note_model_contents(entry, entry._cache) entry._cache = None @@ -381,62 +342,6 @@ def _settle_legacy_meta(entry: AssetEntry, warnings: list[str]) -> None: warnings.append(f"ignored metaData of {entry.pathname}: {exc}") -# 入れ子のパッケージを選ばなかったときに優先する中身(Blender のマテリアルにもっとも近い Built-in のもの。#217) -_NESTED_PREFERRED = ("builtin", "built-in", "birp", "standard", "3d") - - -def default_nested_package(entries: list[AssetEntry]) -> AssetEntry: - """入れ子のパッケージのうち、選ばなかったときに読むもの(Built-in 向けらしい名前のもの、無ければ pathname 順の最初)。""" - for entry in entries: - if any(key in PurePosixPath(entry.pathname).stem.lower() for key in _NESTED_PREFERRED): - return entry - return entries[0] - - -# 外側のパッケージにあっても読み込みに使わないもの(説明書など) -_DOCUMENT_EXTS = frozenset({".txt", ".pdf", ".md", ".rtf", ".html", ".htm", ".url"}) - - -def merge_nested_package(outer: "UnityPackage", inner_path: Path, dest: Path) -> Path | None: - """入れ子のパッケージ ``inner_path`` に、外側のパッケージのアセット(入れ子のパッケージと説明書を除く)を足した - パッケージを ``dest`` に書く。外側に足すものが無ければ書かずに None。 - - 中身の prefab が外側のメッシュやテクスチャを使うことがある(Conifers BOTD の BIRP / URP / HDRP の中身は prefab とマテリアルだけで、 - メッシュは外側の Sources にある。#217)。中身にある GUID は中身のものを使う。``dest`` が両方より新しければ書き直さない。 - """ - outer._require_scan() - extra = { - e.guid for e in outer.entries.values() - if e.has_asset and e.ext != ".unitypackage" and e.ext not in _DOCUMENT_EXTS - } - if not extra: - return None - if dest.is_file() and dest.stat().st_mtime >= max(inner_path.stat().st_mtime, outer.path.stat().st_mtime): - return dest - dest.parent.mkdir(parents=True, exist_ok=True) - partial = dest.with_name(dest.name + ".partial") - inner_guids: set[str] = set() - try: - with tarfile.open(partial, "w:gz", compresslevel=1) as out: - for source, wanted in ((inner_path, None), (outer.path, extra)): - with tarfile.open(source, "r:*") as tar: - for member in tar: - split = _split_member(member.name) - if split is None or not member.isfile(): - continue - guid = split[0] - if wanted is None: - inner_guids.add(guid) - elif guid not in wanted or guid in inner_guids: - continue - out.addfile(member, tar.extractfile(member)) - partial.replace(dest) - except (tarfile.TarError, EOFError, OSError) as exc: - partial.unlink(missing_ok=True) - raise PackageError(f"cannot combine {inner_path.name} with {outer.path.name}: {exc}") from exc - return dest - - def human_size(size: float) -> str: """バイト数を「12.3 MiB」のような表記にする(警告文とダイアログで使う)。""" for unit in ("B", "KiB", "MiB", "GiB"): @@ -462,7 +367,7 @@ def scan(self, progress: ProgressFn | None = None) -> dict[str, AssetEntry]: try: with tarfile.open(self.path, "r:*") as tar: for member in tar: - split = _split_member(member.name) + split = split_member(member.name) if split is None or not member.isfile(): continue guid, part = split @@ -497,7 +402,7 @@ def scan(self, progress: ProgressFn | None = None) -> dict[str, AssetEntry]: if not known: held = entry elif member.size <= _READ_ASSET_MAX_SIZE and entry.ext in (".fbx", ".obj"): - _note_fbx(entry, tar.extractfile(member).read()) + note_model_contents(entry, tar.extractfile(member).read()) if progress is not None: progress(0.0, entry.pathname or guid) except (tarfile.TarError, EOFError, OSError) as exc: @@ -590,7 +495,7 @@ def read_asset(self, guid: str) -> bytes: try: with tarfile.open(self.path, "r:*") as tar: for member in tar: - split = _split_member(member.name) + split = split_member(member.name) if split and split[0] == entry.guid and split[1] == "asset": if member.size > limit: # 索引と食い違う場合の保険 raise PackageError(f"{target} is too large to read into memory ({member.size} bytes)") @@ -624,7 +529,7 @@ def read_assets(self, guids: Iterable[str]) -> dict[str, bytes]: try: with tarfile.open(self.path, "r:*") as tar: for member in tar: - split = _split_member(member.name) + split = split_member(member.name) if split and split[1] == "asset" and split[0] in wanted and member.size <= _read_limit(self.entries[split[0]]): result[split[0]] = tar.extractfile(member).read() wanted.discard(split[0]) @@ -699,7 +604,7 @@ def extract( done = 0 with tarfile.open(self.path, "r:*") as tar: for member in tar: - split = _split_member(member.name) + split = split_member(member.name) if not split or split[1] != "asset" or split[0] not in pending: continue target = pending.pop(split[0]) From f42db5e196b53dfaddd4fbea0565175a0b342b4c Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 18:21:06 +0900 Subject: [PATCH 05/25] =?UTF-8?q?feat:=20AnimationClip=EF=BC=88.anim?= =?UTF-8?q?=EF=BC=89=E3=81=AE=E8=A7=A3=E6=9E=90=E3=81=A8=E3=83=91=E3=82=B9?= =?UTF-8?q?=E3=81=AE=E7=85=A7=E5=90=88=E3=82=92=20core=20=E3=81=AB?= =?UTF-8?q?=E8=B6=B3=E3=81=99=EF=BC=88#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generic な .anim を Action にする準備として、bpy に依存しない部分を足す。 - core/animation.py: .anim(YAML とバイナリ)から、シェイプキー・m_IsActive・Renderer の m_Enabled・ Transform(位置・クォータニオン・オイラー角・スケール。成分ごとに分ける)のカーブを読む。 Humanoid のマッスル値のカーブは読まずに印を付け、ほかの種類は数だけ数える。 カーブの評価(エルミート、weighted のベジェ、無限大の接線は階段)、Blender のベジェのハンドル、 Unity の回転の順のオイラー角とクォータニオンの変換、Transform を焼く時刻を持つ。 - core/animation_targets.py: クリップはモデルを持たないので、パスがいちばん多く解決できるオブジェクトを ルートとみなす。スキンメッシュはアーマチュアの兄弟としても引き、ボーンはボーン名でたどる。 - core/model_space.py: node_basis を basis = left·L·right の形に一般化した local_basis を足す (FBX の中の子は A⁻¹·L·A、GameObject の Empty は C·L·C⁻¹)。 - 単体テストと、.anim のファズテストを足す。壊れた入力には ValueError 系だけを送る。 Co-Authored-By: Claude Opus 5.5 --- tests/anim_writer.py | 133 ++++ tests/test_animation.py | 305 +++++++++ tests/test_fuzz_parsers.py | 27 + unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/animation.py | 604 ++++++++++++++++++ unitypackage_loader/core/animation_targets.py | 297 +++++++++ unitypackage_loader/core/model_space.py | 22 +- 7 files changed, 1385 insertions(+), 5 deletions(-) create mode 100644 tests/anim_writer.py create mode 100644 tests/test_animation.py create mode 100644 unitypackage_loader/core/animation.py create mode 100644 unitypackage_loader/core/animation_targets.py diff --git a/tests/anim_writer.py b/tests/anim_writer.py new file mode 100644 index 0000000..cb6e970 --- /dev/null +++ b/tests/anim_writer.py @@ -0,0 +1,133 @@ +"""テスト用の AnimationClip(.anim)の Unity YAML を書く(#209)。単体テストと合成パッケージの生成で使う。 + +キーは (time, value, in_slope, out_slope) か、weighted のときは (time, value, in_slope, out_slope, weighted_mode, in_weight, out_weight)。 +ベクトルのカーブ(位置・オイラー回転・スケール・クォータニオン)の value と接線は成分のタプル。接線に ``float("inf")`` を +渡すと ``Infinity``(階段)になる。 +""" + +from __future__ import annotations + +import math + +HEADER = "%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!74 &7400000\n" + + +def _num(value: float) -> str: + if math.isinf(value): + return "Infinity" if value > 0 else "-Infinity" + return repr(float(value)) if not float(value).is_integer() else str(int(value)) + + +def _vec(values, axes: str = "xyz") -> str: + return "{" + ", ".join(f"{a}: {_num(v)}" for a, v in zip(axes, values)) + "}" + + +def _key_lines(key, axes: str | None) -> list[str]: + time, value, in_slope, out_slope, *rest = key + weighted, in_weight, out_weight = (rest + [0, None, None])[:3] + if axes is None: + fmt = _num + default_weight = 1 / 3 + else: + def fmt(v): + return _vec(v, axes) + + default_weight = (1 / 3,) * len(axes) + in_weight = default_weight if in_weight is None else in_weight + out_weight = default_weight if out_weight is None else out_weight + return [ + " - serializedVersion: 3", + f" time: {_num(time)}", + f" value: {fmt(value)}", + f" inSlope: {fmt(in_slope)}", + f" outSlope: {fmt(out_slope)}", + " tangentMode: 0", + f" weightedMode: {weighted}", + f" inWeight: {fmt(in_weight)}", + f" outWeight: {fmt(out_weight)}", + ] + + +def _curve_block(keys, axes: str | None, rotation_order: int = 4) -> list[str]: + lines = [" curve:", " serializedVersion: 2", " m_Curve:"] + for key in keys: + lines += _key_lines(key, axes) + lines += [" m_PreInfinity: 2", " m_PostInfinity: 2", f" m_RotationOrder: {rotation_order}"] + return lines + + +_VECTOR_AXES = {"m_PositionCurves": "xyz", "m_EulerCurves": "xyz", "m_ScaleCurves": "xyz", "m_RotationCurves": "xyzw"} + + +def clip_yaml( + name: str, + float_curves=(), + vector_curves: dict | None = None, + loop: bool = False, + sample_rate: float = 60, + stop_time: float = 0, + pptr: int = 0, +) -> str: + """AnimationClip の YAML。``float_curves`` は (path, attribute, classID, keys)、``vector_curves`` は + {"m_PositionCurves": [(path, keys[, rotation_order])], ...}。""" + vector_curves = vector_curves or {} + lines = [ + "AnimationClip:", + " m_ObjectHideFlags: 0", + f" m_Name: {name}", + " serializedVersion: 7", + " m_Legacy: 0", + " m_Compressed: 0", + " m_UseHighQualityCurve: 1", + ] + for field_name in ("m_RotationCurves", "m_CompressedRotationCurves", "m_EulerCurves", "m_PositionCurves", "m_ScaleCurves"): + entries = vector_curves.get(field_name, []) + if not entries: + lines.append(f" {field_name}: []") + continue + lines.append(f" {field_name}:") + for entry in entries: + path, keys = entry[0], entry[1] + order = entry[2] if len(entry) > 2 else 4 + block = _curve_block(keys, _VECTOR_AXES[field_name], order) + block[0] = " - curve:" + lines += block + lines.append(f" path: {path}") + if float_curves: + lines.append(" m_FloatCurves:") + for path, attribute, class_id, keys in float_curves: + lines.append(" - serializedVersion: 2") + lines += _curve_block(keys, None) + lines += [f" attribute: {attribute}", f" path: {path}", f" classID: {class_id}", " script: {fileID: 0}", " flags: 0"] + else: + lines.append(" m_FloatCurves: []") + if pptr: + lines.append(" m_PPtrCurves:") + for i in range(pptr): + lines += [ + " - serializedVersion: 2", + " curve:", + " - time: 0", + " value: {fileID: 2100000, guid: " + "e" * 32 + ", type: 2}", + " attribute: m_Materials.Array.data[0]", + f" path: part{i}", + " classID: 23", + " script: {fileID: 0}", + ] + else: + lines.append(" m_PPtrCurves: []") + lines += [ + f" m_SampleRate: {_num(sample_rate)}", + " m_WrapMode: 0", + " m_AnimationClipSettings:", + " serializedVersion: 2", + " m_StartTime: 0", + f" m_StopTime: {_num(stop_time)}", + f" m_LoopTime: {1 if loop else 0}", + " m_EditorCurves: []", + " m_EulerEditorCurves: []", + " m_HasGenericRootTransform: 0", + " m_HasMotionFloatCurves: 0", + " m_Events: []", + ] + return HEADER + "\n".join(lines) + "\n" diff --git a/tests/test_animation.py b/tests/test_animation.py new file mode 100644 index 0000000..36768fd --- /dev/null +++ b/tests/test_animation.py @@ -0,0 +1,305 @@ +import math +import unittest + +from tests import _paths # noqa: F401 +from tests.anim_writer import clip_yaml +from unitypackage_loader.core.animation import ( + KIND_ACTIVE, + KIND_ENABLED, + KIND_EULER, + KIND_POSITION, + KIND_ROTATION, + KIND_SCALE, + KIND_SHAPE_KEY, + AnimationParseError, + Curve, + Key, + bezier_handles, + euler_to_quaternion, + evaluate, + parse_clip, + quaternion_to_euler, + sample_times, + transform_spec, +) +from unitypackage_loader.core.animation_targets import TargetObject, TargetTree, bind_paths +from unitypackage_loader.core.model_space import local_basis, local_values, node_basis +from unitypackage_loader.core.transform import UNITY_TO_BLENDER, chain, inverse_affine, trs +from tests.test_transform import assert_mat + +INF = float("inf") + + +def _bezier(p0, p1, p2, p3, t): + u = 1 - t + return tuple(u ** 3 * a + 3 * u * u * t * b + 3 * u * t * t * c + t ** 3 * d for a, b, c, d in zip(p0, p1, p2, p3)) + + +class ParseTest(unittest.TestCase): + def test_shape_key_and_toggles(self): + text = clip_yaml( + "Smile", + float_curves=[ + ("Body", "blendShape.smile", 137, [(0, 0, 0, 0), (1, 100, 0, 0)]), + ("Body/Acc", "m_IsActive", 1, [(0, 1, INF, INF)]), + ("Body", "m_Enabled", 137, [(0, 0, INF, INF)]), + ("Body", "material._Color.r", 137, [(0, 1, 0, 0)]), + ], + loop=True, + pptr=2, + ) + clip = parse_clip(text) + self.assertEqual(clip.name, "Smile") + self.assertTrue(clip.loop) + self.assertFalse(clip.humanoid) + kinds = {(c.path, c.kind) for c in clip.curves} + self.assertEqual(kinds, {("Body", KIND_SHAPE_KEY), ("Body/Acc", KIND_ACTIVE), ("Body", KIND_ENABLED)}) + smile = next(c for c in clip.curves if c.kind == KIND_SHAPE_KEY) + self.assertEqual(smile.shape_key, "smile") + self.assertEqual(clip.other_curves, 1) + self.assertEqual(clip.pptr_curves, 2) + self.assertEqual((clip.start, clip.stop), (0.0, 1.0)) + toggle = next(c for c in clip.curves if c.kind == KIND_ACTIVE) + self.assertTrue(math.isinf(toggle.keys[0].out_slope)) + + def test_vector_curves_split_by_component(self): + text = clip_yaml( + "Door", + vector_curves={ + "m_PositionCurves": [("Door", [(0, (0, 1, 2), (0, 0, 0), (0, 0, 0)), (2, (1, 1, 2), (0, 0, 0), (0, 0, 0))])], + "m_EulerCurves": [("Door/Hinge", [(0, (0, 90, 0), (0, 0, 0), (0, 0, 0))], 0)], + "m_RotationCurves": [("Knob", [(0, (0, 0, 0, 1), (0, 0, 0, 0), (0, 0, 0, 0))])], + "m_ScaleCurves": [("Door", [(0, (1, 2, 3), (0, 0, 0), (0, 0, 0))])], + }, + stop_time=2, + ) + clip = parse_clip(text) + by = {(c.path, c.attribute): c for c in clip.curves} + self.assertEqual(by[("Door", "m_LocalPosition.y")].kind, KIND_POSITION) + self.assertEqual(by[("Door", "m_LocalPosition.x")].keys[1].value, 1.0) + self.assertEqual(by[("Door/Hinge", "localEulerAnglesRaw.y")].kind, KIND_EULER) + self.assertEqual(by[("Door/Hinge", "localEulerAnglesRaw.y")].rotation_order, 0) + self.assertEqual(by[("Knob", "m_LocalRotation.w")].kind, KIND_ROTATION) + self.assertEqual(by[("Knob", "m_LocalRotation.w")].component, 3) + self.assertEqual(by[("Door", "m_LocalScale.z")].kind, KIND_SCALE) + self.assertEqual(by[("Door", "m_LocalScale.z")].keys[0].value, 3.0) + self.assertEqual(clip.stop, 2.0) + + def test_humanoid(self): + text = clip_yaml( + "Fist", + float_curves=[ + ("", "LeftHand.Thumb.1 Stretched", 95, [(0, -1, 0, 0)]), + ("", "Left Arm Down-Up", 95, [(0, 0.3, 0, 0)]), + ("", "RootT.y", 95, [(0, 1, 0, 0)]), + ], + ) + clip = parse_clip(text) + self.assertTrue(clip.humanoid) + self.assertEqual(clip.curves, []) + + def test_humanoid_keeps_generic_curves(self): + text = clip_yaml("Mixed", float_curves=[("", "Spine Front-Back", 95, [(0, 0, 0, 0)]), ("Body", "blendShape.a", 137, [(0, 50, 0, 0)])]) + clip = parse_clip(text) + self.assertTrue(clip.humanoid) + self.assertEqual([c.kind for c in clip.curves], [KIND_SHAPE_KEY]) + + def test_animator_parameter_is_not_humanoid(self): + clip = parse_clip(clip_yaml("Param", float_curves=[("", "GestureWeight", 95, [(0, 1, 0, 0)])])) + self.assertFalse(clip.humanoid) + self.assertEqual(clip.other_curves, 1) + + def test_editor_curves_fallback(self): + text = clip_yaml("Editor").replace( + " m_EditorCurves: []", + " m_EditorCurves:\n - serializedVersion: 2\n curve:\n serializedVersion: 2\n m_Curve:\n" + " - serializedVersion: 3\n time: 0\n value: 5\n inSlope: 0\n outSlope: 0\n" + " tangentMode: 0\n weightedMode: 0\n inWeight: 0\n outWeight: 0\n" + " m_PreInfinity: 2\n m_PostInfinity: 2\n m_RotationOrder: 4\n" + " attribute: m_LocalPosition.y\n path: Lid\n classID: 4\n script: {fileID: 0}\n flags: 0", + ) + clip = parse_clip(text) + self.assertEqual([(c.path, c.kind, c.component) for c in clip.curves], [("Lid", KIND_POSITION, 1)]) + + def test_numeric_names_stay_text(self): + clip = parse_clip(clip_yaml("Blink", float_curves=[("123", "blendShape.456", 137, [(0, 1, 0, 0)])])) + self.assertEqual((clip.curves[0].path, clip.curves[0].shape_key), ("123", "456")) + + def test_not_a_clip(self): + with self.assertRaises(AnimationParseError): + parse_clip("%YAML 1.1\n--- !u!1 &1\nGameObject:\n m_Name: a\n") + with self.assertRaises(ValueError): + parse_clip(b"\x00\x01garbage") + + def test_bad_values_are_ignored(self): + text = clip_yaml("Bad", float_curves=[("A", "blendShape.x", 137, [(0, 1, 0, 0), (1, 2, 0, 0)])]) + text = text.replace("time: 1", "time: nan", 1).replace("value: 1", "value: abc", 1) + clip = parse_clip(text) + self.assertEqual([(k.time, k.value) for k in clip.curves[0].keys], [(0.0, 0.0)]) + + +class EvaluateTest(unittest.TestCase): + def test_hermite(self): + keys = [Key(0, 0, 0, 0), Key(1, 1, 0, 0)] + self.assertAlmostEqual(evaluate(keys, 0.5), 0.5) # smoothstep の中点 + self.assertAlmostEqual(evaluate(keys, 0.25), 3 * 0.0625 - 2 * 0.015625) + linear = [Key(0, 0, 1, 1), Key(2, 2, 1, 1)] + self.assertAlmostEqual(evaluate(linear, 0.7), 0.7) + + def test_outside_and_constant(self): + keys = [Key(0, 1, INF, INF), Key(1, 5, INF, INF)] + self.assertEqual(evaluate(keys, -1), 1) + self.assertEqual(evaluate(keys, 0.99), 1) + self.assertEqual(evaluate(keys, 1), 5) + self.assertEqual(evaluate(keys, 3), 5) + self.assertEqual(evaluate([], 0), 0) + + def test_weighted_matches_bezier(self): + k0 = Key(0, 0, 2, 2, 0.1, 0.1, 2) + k1 = Key(1, 1, 0, 0, 0.6, 0.6, 1) + p0, p1, p2, p3 = (0, 0), (0.1, 0.2), (0.4, 1.0), (1, 1) + for t in (0.1, 0.35, 0.8): + x, y = _bezier(p0, p1, p2, p3, t) + self.assertAlmostEqual(evaluate([k0, k1], x), y, places=6) + + def test_handles_reproduce_curve(self): + for keys in ( + [Key(0, 0, 0, 3), Key(0.5, 2, -1, -1), Key(2, 0, 4, 4)], + [Key(0, 1, 0, 0.5, 0.3, 0.2, 2), Key(1, 3, 1, 1, 0.5, 0.5, 3), Key(3, -1, 0, 0)], + ): + handles = bezier_handles(keys) + for a, b in zip(handles, handles[1:]): + for t in (0.2, 0.5, 0.9): + x, y = _bezier((a.time, a.value), a.right, b.left, (b.time, b.value), t) + self.assertAlmostEqual(evaluate(keys, x), y, places=5) + + def test_handles_constant_and_scale(self): + handles = bezier_handles([Key(0, 0, 0, INF), Key(1, 100, 0, 0), Key(1, 50, 0, 0)], scale=0.01) + self.assertEqual(len(handles), 2) # 同じ時刻のキーは後のもの + self.assertTrue(handles[0].constant) + self.assertAlmostEqual(handles[1].value, 0.5) + + def test_sample_times(self): + curve = Curve("a", "m_LocalPosition.x", 4, KIND_POSITION, [Key(0, 0), Key(0.05, 1), Key(1, 0)]) + times = sample_times([curve], 0.0, 0.1, 30) + self.assertEqual(times, sorted(times)) + self.assertIn(0.05, times) + self.assertAlmostEqual(times[-1], 0.1) + self.assertEqual(sample_times([], 0.0, 0.0, 30), [0.0]) + + +class EulerTest(unittest.TestCase): + def test_unity_default_order(self): + # Quaternion.Euler(0, 90, 0) と Quaternion.Euler(90, 0, 0) + for value, expected in (((0, 90, 0), (0, math.sqrt(0.5), 0, math.sqrt(0.5))), ((90, 0, 0), (math.sqrt(0.5), 0, 0, math.sqrt(0.5)))): + for a, b in zip(euler_to_quaternion(value), expected): + self.assertAlmostEqual(a, b) + # Z → X → Y の順に回す: q = qy·qx·qz + q = euler_to_quaternion((30, 40, 50)) + qx, qy, qz = euler_to_quaternion((30, 0, 0)), euler_to_quaternion((0, 40, 0)), euler_to_quaternion((0, 0, 50)) + m = chain((trs((0, 0, 0), qy, (1, 1, 1)), trs((0, 0, 0), qx, (1, 1, 1)), trs((0, 0, 0), qz, (1, 1, 1)))) + assert_mat(self, trs((0, 0, 0), q, (1, 1, 1)), m) + + def test_round_trip_all_orders(self): + for order in range(6): + for value in ((10, 20, 30), (-170, 80, 45), (0, -89.9, 120), (90, 90, 90)): + q = euler_to_quaternion(value, order) + back = euler_to_quaternion(quaternion_to_euler(q, order), order) + sign = 1 if sum(a * b for a, b in zip(q, back)) >= 0 else -1 + for a, b in zip(q, back): + self.assertAlmostEqual(a, sign * b, places=6) + + def test_transform_spec(self): + rest = euler_to_quaternion((0, 0, 30)) + euler = Curve("a", "localEulerAnglesRaw.y", 4, KIND_EULER, [Key(0, 0), Key(1, 90)], 1) + spec = transform_spec([euler], 1.0, rest) + expected = euler_to_quaternion((0, 90, 30)) + for a, b in zip(spec["rotation"], expected): + self.assertAlmostEqual(a, b) + self.assertEqual(spec["position"], [None, None, None]) + position = Curve("a", "m_LocalPosition.z", 4, KIND_POSITION, [Key(0, 2)], 2) + self.assertEqual(transform_spec([position], 0, rest)["position"], [None, None, 2.0]) + partial = Curve("a", "m_LocalRotation.w", 4, KIND_ROTATION, [Key(0, 0.0)], 3) + rotation = transform_spec([partial], 0, (0.0, 0.0, 0.5, 0.5))["rotation"] + self.assertAlmostEqual(sum(v * v for v in rotation), 1.0) + + +class LocalBasisTest(unittest.TestCase): + a = ((-0.01, 0, 0, 0), (0, 0.01, 0, 0), (0, 0, 0.01, 0), (0, 0, 0, 1)) + + def test_node_basis_is_local_basis(self): + basis = chain((UNITY_TO_BLENDER, trs((1, 2, 3), euler_to_quaternion((10, 20, 30)), (1, 2, 1)), self.a)) + spec = {"position": [None, 5.0, None]} + assert_mat(self, node_basis(basis, spec, self.a), local_basis(basis, spec, UNITY_TO_BLENDER, self.a)) + + def test_nested_child(self): + # FBX の中の子: 親子とも C·W·A なので、子の行列は A⁻¹·L·A + inverse = inverse_affine(self.a) + local = trs((0.5, 0, 0), euler_to_quaternion((0, 45, 0)), (1, 1, 1)) + basis = chain((inverse, local, self.a)) + position, rotation, _ = local_values(basis, inverse, self.a) + for p, q in zip(position, (0.5, 0, 0)): + self.assertAlmostEqual(p, q) + turned = local_basis(basis, {"rotation": list(euler_to_quaternion((0, 90, 0)))}, inverse, self.a) + assert_mat(self, turned, chain((inverse, trs((0.5, 0, 0), euler_to_quaternion((0, 90, 0)), (1, 1, 1)), self.a))) + + +def _tree(objects, groups=()): + return TargetTree([TargetObject(**o) for o in objects], groups) + + +class BindTest(unittest.TestCase): + AVATAR = [ + dict(key="Root", name="Avatar"), + dict(key="Armature", name="Armature", parent="Root", is_armature=True, + bones=(("Hips", None), ("Spine", "Hips"), ("Head", "Spine"))), + dict(key="Body", name="Body", parent="Armature"), + dict(key="Hat", name="Hat", parent="Armature", bone_parent="Head"), + dict(key="Tail", name="Tail.001", parent="Armature"), + ] + + def test_skinned_meshes_are_siblings_of_armature(self): + tree = _tree(self.AVATAR) + [binding] = bind_paths(tree, ["Body", "Tail", "", "Armature/Hips/Spine"]) + self.assertEqual(binding.root, "Root") + self.assertEqual(binding.targets["Body"].key, "Body") + self.assertEqual(binding.targets["Tail"].key, "Tail") # 連番を外して引く + self.assertEqual(binding.targets[""].key, "Root") + self.assertEqual((binding.targets["Armature/Hips/Spine"].key, binding.targets["Armature/Hips/Spine"].bone), ("Armature", "Spine")) + self.assertEqual(tree.resolve("Root", "Armature/Hips/Spine/Head/Hat").key, "Hat") + + def test_top_group_when_no_root_object(self): + objects = [o for o in self.AVATAR if o["key"] != "Root"] + objects = [dict(o, parent=None) if o.get("parent") == "Root" else o for o in objects] + tree = _tree(objects, [["Armature"]]) + [binding] = bind_paths(tree, ["Body", "Armature/Hips"]) + self.assertIsNone(binding.root) # アーマチュアをルートとみなさない + self.assertEqual(binding.targets["Body"].key, "Body") + + def test_root_only_or_unmatched(self): + tree = _tree(self.AVATAR) + self.assertEqual(bind_paths(tree, [""]), []) + self.assertEqual(bind_paths(tree, ["Body", "Nope", "Gone", "Missing"]), []) # 半分に満たない + + def test_instances_and_nested_duplicates(self): + objects = [ + dict(key="A", name="Bike"), dict(key="A/h", name="Handle", parent="A"), + dict(key="A/fbx", name="Collection", parent="A", is_empty=True), dict(key="A/fbx/h", name="Handle.001", parent="A/fbx"), + dict(key="B", name="Bike.001"), dict(key="B/h", name="Handle.002", parent="B"), + ] + bindings = bind_paths(_tree(objects), ["Handle"]) + self.assertEqual(sorted(b.targets["Handle"].key for b in bindings), ["A/h", "B/h"]) + + def test_empty_level_is_skipped(self): + objects = [dict(key="P", name="Pin"), dict(key="F", name="Sheets", parent="P", is_empty=True), dict(key="M", name="Pins_1", parent="F")] + [binding] = bind_paths(_tree(objects), ["Pins_1"]) + self.assertEqual(binding.targets["Pins_1"].key, "M") + + def test_unity_descendants(self): + tree = _tree(self.AVATAR) + self.assertEqual(set(tree.unity_descendants("Armature")), {"Armature", "Hat"}) + self.assertEqual(set(tree.unity_descendants("Root")), {"Root", "Armature", "Body", "Hat", "Tail"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fuzz_parsers.py b/tests/test_fuzz_parsers.py index 33df5ac..81907bf 100644 --- a/tests/test_fuzz_parsers.py +++ b/tests/test_fuzz_parsers.py @@ -35,8 +35,11 @@ from unitypackage_loader.core.terrain import read_terrain_data, read_terrain_layer, terrain_mesh from unitypackage_loader.core.unity_binary import load_documents from tests.terrain_writer import terrain_data_asset, terrain_layer_yaml +from tests.anim_writer import clip_yaml from tests.unity_mesh_writer import mesh_document from unitypackage_loader.core.unity_mesh import read_mesh +from unitypackage_loader.core.animation import bezier_handles, parse_clip, sample_times, transform_spec +from unitypackage_loader.core.animation_targets import TargetObject, TargetTree, bind_paths SEED = 20260915 ROUNDS = 80 # フィクスチャ 1 つあたりの壊し方の数 @@ -288,6 +291,30 @@ def run_terrain(data: bytes) -> None: self.fuzz("old terrain data", run_terrain, old, mutate_bytes) self.fuzz("terrain layer", read_terrain_layer, terrain_layer_yaml("Road", "c" * 32, "d" * 32), mutate_text) + def test_animation_clip(self): + # AnimationClip(#209)。読めたクリップは、カーブの評価・ハンドル・Transform の値・パスの照合まで通す + tree = TargetTree([TargetObject("r", "Root"), TargetObject("b", "Body", "r"), TargetObject("d", "Door", "r")]) + + def run_clip(data) -> None: + clip = parse_clip(data) + bind_paths(tree, clip.paths) + for curve in clip.curves: + bezier_handles(curve.keys, 0.01) + for time in sample_times(clip.curves, clip.start, clip.stop, 30)[:50]: + transform_spec(clip.curves, time, (0.0, 0.0, 0.0, 1.0)) + + inf = float("inf") + text = clip_yaml( + "Fuzz", + float_curves=[("Body", "blendShape.smile", 137, [(0, 0, 0, 0), (1, 100, 0, 0, 3, 0.2, 0.7)]), + ("Door", "m_IsActive", 1, [(0, 1, inf, inf)])], + vector_curves={"m_EulerCurves": [("Door", [(0, (0, 0, 0), (0, 0, 0), (0, 0, 0)), (1, (0, 90, 0), (0, 0, 0), (0, 0, 0))])], + "m_RotationCurves": [("Door", [(0, (0, 0, 0, 1), (0, 0, 0, 0), (0, 0, 0, 0))])]}, + pptr=1, + ) + self.fuzz("animation clip", run_clip, text, mutate_text) + self.fuzz("animation clip bytes", run_clip, text.encode("utf-8"), mutate_bytes) + def test_fbx_node_names(self): # 表の無いモデルの中への上書きの対象を決めるときに読む、FBX のノード名(#31) self.fuzz("fbx node names", parse_fbx_node_names, tmi.FbxNodeNameTests.binary(["Body", "日本語", "Part", "Part"]), mutate_bytes) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 3dafea2..31fbfe0 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.4" +version = "1.18.0-dev.5" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/animation.py b/unitypackage_loader/core/animation.py new file mode 100644 index 0000000..781af06 --- /dev/null +++ b/unitypackage_loader/core/animation.py @@ -0,0 +1,604 @@ +"""AnimationClip(.anim)を読む。bpy 非依存(#209)。 + +Generic なクリップのうち、次のカーブを ``Curve`` にそろえて返す。 + +- シェイプキー: ``SkinnedMeshRenderer`` の ``blendShape.<名前>``(値は 0〜100) +- 表示の切り替え: GameObject の ``m_IsActive``、Renderer の ``m_Enabled`` +- Transform: ``m_PositionCurves`` / ``m_RotationCurves``(クォータニオン)/ ``m_EulerCurves``(度)/ ``m_ScaleCurves``。 + 3〜4 成分のカーブは成分ごとの ``Curve`` に分ける(``attribute`` は ``m_LocalPosition.x`` などエディターのカーブと同じ名前) + +Humanoid のクリップ(Animator のマッスル値のカーブ)は ``humanoid`` を立てるだけで、カーブは返さない。 +それ以外のカーブ(マテリアルのプロパティ、オブジェクト参照の差し替えなど)は数だけ数える。 + +カーブの評価は Unity の AnimationCurve と同じく、キーの間をエルミート(weighted のキーは 3 次ベジェ)でつなぎ、 +接線が無限大の区間は前のキーの値のまま(階段)にする。 + +解析は Unity YAML でもバイナリ(Force Binary)でも ``unity_binary.load_documents`` で ``UnityDocument`` にしてから行う。 +壊れた入力には ``AnimationParseError``(``ValueError``)だけを送出する。 +""" + +from __future__ import annotations + +import math +import re +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any + +from .unity_binary import load_documents + +__all__ = [ + "AnimationParseError", + "Key", + "Curve", + "AnimationClip", + "KIND_SHAPE_KEY", + "KIND_ACTIVE", + "KIND_ENABLED", + "KIND_POSITION", + "KIND_ROTATION", + "KIND_EULER", + "KIND_SCALE", + "TRANSFORM_KINDS", + "parse_clip", + "evaluate", + "bezier_handles", + "euler_to_quaternion", + "quaternion_to_euler", + "sample_times", + "transform_spec", +] + +CLASS_ANIMATION_CLIP = 74 +CLASS_GAME_OBJECT = 1 +CLASS_TRANSFORM = 4 +CLASS_ANIMATOR = 95 +CLASS_SKINNED_MESH_RENDERER = 137 +# m_Enabled を表示の切り替えとして扱う Renderer(MeshRenderer / SkinnedMeshRenderer) +RENDERER_CLASSES = frozenset({23, 137}) + +KIND_SHAPE_KEY = "shape_key" +KIND_ACTIVE = "active" +KIND_ENABLED = "enabled" +KIND_POSITION = "position" +KIND_ROTATION = "rotation" +KIND_EULER = "euler" +KIND_SCALE = "scale" +TRANSFORM_KINDS = frozenset({KIND_POSITION, KIND_ROTATION, KIND_EULER, KIND_SCALE}) + +# 1 つのクリップで読むカーブ・キーの数の上限(壊れた・細工したファイルで止まらないように) +MAX_CURVES = 20000 +MAX_KEYS = 200000 +# クリップの長さの上限(秒)。これを超えるキーは無いものとして扱う +MAX_TIME = 86400.0 + +# Animator(classID 95)のカーブのうち、Humanoid のマッスル値・ルートの動きとみなす属性 +_HUMANOID_RE = re.compile( + r"^(Root|Motion|LeftFoot|RightFoot|LeftHand|RightHand)[TQ]\.[xyzw]$" + r"|^(Spine|Chest|UpperChest|Neck|Head|Jaw|Left|Right) " + r"|^(LeftHand|RightHand)\.(Thumb|Index|Middle|Ring|Little)\." +) + +_VECTOR_FIELDS = { + "m_PositionCurves": (KIND_POSITION, "m_LocalPosition", "xyz"), + "m_EulerCurves": (KIND_EULER, "localEulerAnglesRaw", "xyz"), + "m_ScaleCurves": (KIND_SCALE, "m_LocalScale", "xyz"), + "m_RotationCurves": (KIND_ROTATION, "m_LocalRotation", "xyzw"), +} + +# エディターのカーブ(m_EditorCurves)の Transform の属性 → 種類 +_EDITOR_TRANSFORM = { + "m_LocalPosition": KIND_POSITION, + "m_LocalScale": KIND_SCALE, + "m_LocalRotation": KIND_ROTATION, + "localEulerAnglesRaw": KIND_EULER, + "localEulerAngles": KIND_EULER, + "localEulerAnglesBaked": KIND_EULER, +} + +# Unity の RotationOrder(m_RotationOrder)。文字は「先に回す軸」から並べる(4 = ZXY が既定) +ROTATION_ORDERS = {0: "XYZ", 1: "XZY", 2: "YZX", 3: "YXZ", 4: "ZXY", 5: "ZYX"} +DEFAULT_ROTATION_ORDER = 4 + + +class AnimationParseError(ValueError): + """.anim として読めない(ValueError の派生)。""" + + +@dataclass(frozen=True) +class Key: + """AnimationCurve の 1 キー。接線は値/秒(無限大は階段)。重みは weighted のときだけ使う。""" + + time: float + value: float + in_slope: float = 0.0 + out_slope: float = 0.0 + in_weight: float = 1.0 / 3.0 + out_weight: float = 1.0 / 3.0 + weighted_mode: int = 0 # 0 = None, 1 = In, 2 = Out, 3 = Both + + @property + def weighted_in(self) -> bool: + return bool(self.weighted_mode & 1) + + @property + def weighted_out(self) -> bool: + return bool(self.weighted_mode & 2) + + +@dataclass +class Curve: + """1 つの値のカーブ。``path`` はアニメーションのルートからの階層パス(ルート自身は空文字)。""" + + path: str + attribute: str + class_id: int + kind: str + keys: list[Key] + component: int = 0 # Transform のカーブの成分(x, y, z, w の順の添字) + rotation_order: int = DEFAULT_ROTATION_ORDER # オイラー回転のカーブだけが使う + + @property + def shape_key(self) -> str | None: + """シェイプキーのカーブなら、その名前。""" + return self.attribute[len("blendShape."):] if self.kind == KIND_SHAPE_KEY else None + + +@dataclass +class AnimationClip: + name: str + sample_rate: float = 60.0 + loop: bool = False + legacy: bool = False + humanoid: bool = False + curves: list[Curve] = field(default_factory=list) + other_curves: int = 0 # 読まない種類のカーブ(マテリアルのプロパティ、Animator のパラメーターなど) + pptr_curves: int = 0 # オブジェクト参照を差し替えるカーブ(マテリアル・スプライトの差し替え) + start: float = 0.0 + stop: float = 0.0 + + @property + def paths(self) -> set[str]: + return {c.path for c in self.curves} + + +# --------------------------------------------------------------------------- +# 値の取り出し +# --------------------------------------------------------------------------- + + +def _number(value: Any, default: float = 0.0, allow_infinite: bool = False) -> float: + """数値にする。Unity YAML の ``Infinity`` / ``-Infinity`` は ``allow_infinite`` のときだけ無限大にする。""" + if isinstance(value, bool): + return float(value) + if isinstance(value, (int, float)): + number = float(value) + elif isinstance(value, str): + text = value.strip() + try: + number = float(text) + except ValueError: + return default + else: + return default + if math.isnan(number): + return default + if math.isinf(number) and not allow_infinite: + return default + return number + + +def _int(value: Any, default: int = 0) -> int: + number = _number(value, float(default)) + try: + return int(number) + except (OverflowError, ValueError): + return default + + +def _component(value: Any, index: int, default: float, allow_infinite: bool = False) -> float: + """``{x: .., y: .., z: .., w: ..}`` の index 番目の成分。""" + if isinstance(value, Mapping): + return _number(value.get("xyzw"[index]), default, allow_infinite) + return default + + +def _list(value: Any) -> list: + return value if isinstance(value, list) else [] + + +def _keys(raw_curve: Any, component: int | None) -> list[Key]: + """``curve`` の ``m_Curve`` をキーの列にする(``component`` はベクトルのカーブの成分。None ならスカラー)。""" + if not isinstance(raw_curve, Mapping): + return [] + keys: list[Key] = [] + for raw in _list(raw_curve.get("m_Curve")): + if not isinstance(raw, Mapping): + continue + time = _number(raw.get("time"), math.nan) + if not -MAX_TIME <= time <= MAX_TIME: + continue + if component is None: + value = _number(raw.get("value"), 0.0) + in_slope = _number(raw.get("inSlope"), 0.0, True) + out_slope = _number(raw.get("outSlope"), 0.0, True) + in_weight = _number(raw.get("inWeight"), 1.0 / 3.0) + out_weight = _number(raw.get("outWeight"), 1.0 / 3.0) + else: + value = _component(raw.get("value"), component, 0.0) + in_slope = _component(raw.get("inSlope"), component, 0.0, True) + out_slope = _component(raw.get("outSlope"), component, 0.0, True) + in_weight = _component(raw.get("inWeight"), component, 1.0 / 3.0) + out_weight = _component(raw.get("outWeight"), component, 1.0 / 3.0) + keys.append(Key(time, value, in_slope, out_slope, in_weight, out_weight, _int(raw.get("weightedMode")) & 3)) + if len(keys) > MAX_KEYS: + raise AnimationParseError(f"too many keys (> {MAX_KEYS})") + keys.sort(key=lambda k: k.time) + # 同じ時刻のキーが並ぶことがある(階段の表現)。評価では後のものを使うので、そのまま残す + return keys + + +def _text(value: Any) -> str: + if isinstance(value, str): + return value + if isinstance(value, (int, float)) and not isinstance(value, bool): + # 数字だけの名前は YAML のパーサーが数値にする + return str(int(value)) if float(value).is_integer() else str(value) + return "" + + +# --------------------------------------------------------------------------- +# 解析 +# --------------------------------------------------------------------------- + + +def _is_humanoid(class_id: int, path: str, attribute: str) -> bool: + return class_id == CLASS_ANIMATOR and not path and bool(_HUMANOID_RE.search(attribute)) + + +def _float_curve(raw: Mapping, clip: AnimationClip) -> Curve | None: + """``m_FloatCurves`` / ``m_EditorCurves`` の 1 本を ``Curve`` にする。読まない種類は None(数は ``clip`` に足す)。""" + path = _text(raw.get("path")) + attribute = _text(raw.get("attribute")) + class_id = _int(raw.get("classID")) + if _is_humanoid(class_id, path, attribute): + clip.humanoid = True + return None + kind = None + component = 0 + if attribute.startswith("blendShape.") and len(attribute) > len("blendShape.") and class_id == CLASS_SKINNED_MESH_RENDERER: + kind = KIND_SHAPE_KEY + elif attribute == "m_IsActive" and class_id == CLASS_GAME_OBJECT: + kind = KIND_ACTIVE + elif attribute == "m_Enabled" and class_id in RENDERER_CLASSES: + kind = KIND_ENABLED + elif class_id == CLASS_TRANSFORM and "." in attribute: + base, _, axis = attribute.rpartition(".") + if base in _EDITOR_TRANSFORM and axis in "xyzw" and len(axis) == 1: + kind = _EDITOR_TRANSFORM[base] + component = "xyzw".index(axis) + if kind != KIND_ROTATION and component == 3: + kind = None + if kind is None: + clip.other_curves += 1 + return None + curve = raw.get("curve") + keys = _keys(curve, None) + if not keys: + return None + order = _int(curve.get("m_RotationOrder"), DEFAULT_ROTATION_ORDER) if isinstance(curve, Mapping) else DEFAULT_ROTATION_ORDER + return Curve(path, attribute, class_id, kind, keys, component, order if order in ROTATION_ORDERS else DEFAULT_ROTATION_ORDER) + + +def _vector_curves(raw: Mapping, field_name: str) -> list[Curve]: + kind, base, axes = _VECTOR_FIELDS[field_name] + path = _text(raw.get("path")) + curve = raw.get("curve") + order = DEFAULT_ROTATION_ORDER + if isinstance(curve, Mapping): + order = _int(curve.get("m_RotationOrder"), DEFAULT_ROTATION_ORDER) + if order not in ROTATION_ORDERS: + order = DEFAULT_ROTATION_ORDER + result = [] + for index, axis in enumerate(axes): + keys = _keys(curve, index) + if keys: + result.append(Curve(path, f"{base}.{axis}", CLASS_TRANSFORM, kind, keys, index, order)) + return result + + +def _check_count(clip: AnimationClip) -> None: + if len(clip.curves) + clip.other_curves > MAX_CURVES: + raise AnimationParseError(f"too many curves (> {MAX_CURVES})") + + +def clip_from_body(body: Mapping[str, Any]) -> AnimationClip: + """AnimationClip のドキュメントの本体から ``AnimationClip`` を作る。""" + clip = AnimationClip(_text(body.get("m_Name"))) + rate = _number(body.get("m_SampleRate"), 60.0) + clip.sample_rate = rate if 0.0 < rate <= 1000.0 else 60.0 + clip.legacy = bool(_int(body.get("m_Legacy"))) + settings = body.get("m_AnimationClipSettings") + if isinstance(settings, Mapping): + clip.loop = bool(_int(settings.get("m_LoopTime"))) + start = _number(settings.get("m_StartTime"), 0.0) + stop = _number(settings.get("m_StopTime"), 0.0) + else: + start = stop = 0.0 + if clip.legacy: + clip.loop = _int(body.get("m_WrapMode")) == 2 # Legacy のクリップは WrapMode.Loop で繰り返す + + for field_name in _VECTOR_FIELDS: + for raw in _list(body.get(field_name)): + if isinstance(raw, Mapping): + clip.curves.extend(_vector_curves(raw, field_name)) + _check_count(clip) + runtime_transforms = any(c.kind in TRANSFORM_KINDS for c in clip.curves) + float_curves = _list(body.get("m_FloatCurves")) + # 実行時のカーブが無いもの(エディターのカーブだけを残したクリップ)は、エディターのカーブを読む + if not float_curves and not clip.curves: + float_curves = _list(body.get("m_EditorCurves")) + for raw in float_curves: + if not isinstance(raw, Mapping): + continue + curve = _float_curve(raw, clip) + if curve is not None and not (runtime_transforms and curve.kind in TRANSFORM_KINDS): + clip.curves.append(curve) + _check_count(clip) + clip.pptr_curves = len([raw for raw in _list(body.get("m_PPtrCurves")) if isinstance(raw, Mapping)]) + + times = [k.time for c in clip.curves for k in c.keys] + first = min(times) if times else 0.0 + last = max(times) if times else 0.0 + if stop > start >= 0.0 and stop <= MAX_TIME: + clip.start, clip.stop = start, stop + else: + clip.start, clip.stop = min(first, 0.0), max(last, 0.0) + return clip + + +def parse_clip(data: bytes | str) -> AnimationClip: + """.anim の中身(テキストでもバイナリでも)から最初の AnimationClip を読む。""" + try: + docs = load_documents(data) + except ValueError as exc: + raise AnimationParseError(str(exc)) from exc + for doc in docs: + if doc.class_id == CLASS_ANIMATION_CLIP or doc.type_name == "AnimationClip": + return clip_from_body(doc.body) + raise AnimationParseError("no AnimationClip in the asset") + + +# --------------------------------------------------------------------------- +# 評価と、ベジェのハンドル +# --------------------------------------------------------------------------- + + +def _segment_constant(k0: Key, k1: Key) -> bool: + return math.isinf(k0.out_slope) or math.isinf(k1.in_slope) + + +def _bezier_x(t: float, x0: float, x1: float, x2: float, x3: float) -> float: + u = 1.0 - t + return u * u * u * x0 + 3.0 * u * u * t * x1 + 3.0 * u * t * t * x2 + t * t * t * x3 + + +def _solve_bezier_t(x: float, x0: float, x1: float, x2: float, x3: float) -> float: + """x 方向が単調な 3 次ベジェで、x になるパラメーター t を二分法で求める。""" + lo, hi = 0.0, 1.0 + for _ in range(48): + mid = (lo + hi) * 0.5 + if _bezier_x(mid, x0, x1, x2, x3) < x: + lo = mid + else: + hi = mid + return (lo + hi) * 0.5 + + +def _segment_handles(k0: Key, k1: Key) -> tuple[tuple[float, float], tuple[float, float]]: + """k0 → k1 の区間の 3 次ベジェの制御点 2 つ(時刻, 値)。重みの無いキーは 1/3 の長さにする。""" + dt = k1.time - k0.time + w0 = min(max(k0.out_weight, 0.0), 1.0) if k0.weighted_out else 1.0 / 3.0 + w1 = min(max(k1.in_weight, 0.0), 1.0) if k1.weighted_in else 1.0 / 3.0 + return ( + (k0.time + w0 * dt, k0.value + k0.out_slope * w0 * dt), + (k1.time - w1 * dt, k1.value - k1.in_slope * w1 * dt), + ) + + +def evaluate(keys: Sequence[Key], time: float) -> float: + """カーブの値(キーの範囲の外は端の値)。""" + if not keys: + return 0.0 + if time <= keys[0].time: + return keys[0].value + if time >= keys[-1].time: + return keys[-1].value + lo, hi = 0, len(keys) - 1 + while hi - lo > 1: + mid = (lo + hi) // 2 + if keys[mid].time <= time: + lo = mid + else: + hi = mid + k0, k1 = keys[lo], keys[hi] + dt = k1.time - k0.time + if dt <= 0.0: + return k1.value + if _segment_constant(k0, k1): + return k0.value + if k0.weighted_out or k1.weighted_in: + (x1, y1), (x2, y2) = _segment_handles(k0, k1) + t = _solve_bezier_t(time, k0.time, x1, x2, k1.time) + return _bezier_x(t, k0.value, y1, y2, k1.value) + # エルミート + t = (time - k0.time) / dt + t2, t3 = t * t, t * t * t + h00 = 2 * t3 - 3 * t2 + 1 + h10 = t3 - 2 * t2 + t + h01 = -2 * t3 + 3 * t2 + h11 = t3 - t2 + return h00 * k0.value + h10 * dt * k0.out_slope + h01 * k1.value + h11 * dt * k1.in_slope + + +@dataclass(frozen=True) +class BezierKey: + """Blender のキーフレームにする値(時刻は秒)。``constant`` はこのキーから次のキーまで値を保つ。""" + + time: float + value: float + left: tuple[float, float] + right: tuple[float, float] + constant: bool + + +def bezier_handles(keys: Sequence[Key], scale: float = 1.0) -> list[BezierKey]: + """キーの列を、Blender のベジェのキーフレーム(ハンドルは絶対位置)にする。値は ``scale`` 倍する。 + + エルミートの区間は、接線を 1/3 の長さのハンドルにすると同じ曲線になる。weighted の区間は重みの長さにする。 + 同じ時刻に並んだキーは後のものだけを残す(Blender の F カーブは同じフレームに 2 つのキーを持てない)。 + """ + unique: list[Key] = [] + for key in keys: + if unique and key.time <= unique[-1].time: + unique[-1] = key + else: + unique.append(key) + result: list[BezierKey] = [] + for i, key in enumerate(unique): + value = key.value * scale + left = (key.time, value) + right = (key.time, value) + constant = False + if i > 0: + prev = unique[i - 1] + if not _segment_constant(prev, key): + _, (x, y) = _segment_handles(prev, key) + left = (x, y * scale) + if i + 1 < len(unique): + nxt = unique[i + 1] + if _segment_constant(key, nxt): + constant = True + else: + (x, y), _ = _segment_handles(key, nxt) + right = (x, y * scale) + result.append(BezierKey(key.time, value, left, right, constant)) + return result + + +# Transform をフレームごとに焼くときの時刻の数の上限(長すぎるクリップは間隔を広げる) +MAX_SAMPLES = 20000 + + +def sample_times(curves: Iterable[Curve], start: float, stop: float, rate: float) -> list[float]: + """Transform をフレームごとに焼くときの時刻(``rate`` 毎秒。キーの時刻も含める)。 + + 数が ``MAX_SAMPLES`` を超えるときは、間隔を広げて ``MAX_SAMPLES`` に収める(キーの時刻は数に入れない)。 + """ + rate = rate if rate > 0 else 60.0 + times = {start, stop} + span = max(stop - start, 0.0) + count = int(math.floor(span * rate + 1e-6)) + step = 1.0 / rate + if count > MAX_SAMPLES: + count = MAX_SAMPLES + step = span / count + for i in range(count + 1): + times.add(start + i * step) + keys: set[float] = set() + for curve in curves: + for key in curve.keys: + if start <= key.time <= stop: + keys.add(key.time) + if len(keys) > MAX_SAMPLES: + break + times |= keys + return sorted(t for t in times if start <= t <= stop) + + +def euler_to_quaternion(degrees: Sequence[float], order: int = DEFAULT_ROTATION_ORDER) -> tuple[float, float, float, float]: + """Unity のオイラー角(度)を Unity のクォータニオン (x, y, z, w) にする。 + + ``order`` の文字の順に軸を回す(既定の ZXY は Z → X → Y。``Quaternion.Euler`` と同じ)。 + """ + axes = ROTATION_ORDERS.get(order, "ZXY") + q = (0.0, 0.0, 0.0, 1.0) + for axis in axes: + angle = math.radians(degrees["XYZ".index(axis)]) * 0.5 + s, c = math.sin(angle), math.cos(angle) + r = (s if axis == "X" else 0.0, s if axis == "Y" else 0.0, s if axis == "Z" else 0.0, c) + q = _quat_multiply(r, q) # 後に回す軸を左から掛ける + return q + + +def _quat_multiply(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float, float]: + ax, ay, az, aw = a + bx, by, bz, bw = b + return ( + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + ) + + +def quaternion_to_euler(q: Sequence[float], order: int = DEFAULT_ROTATION_ORDER) -> tuple[float, float, float]: + """Unity のクォータニオン (x, y, z, w) を、``order`` のオイラー角(度、x, y, z の順)にする(``euler_to_quaternion`` の逆)。 + + R = R_k·R_j·R_i(i を先に回す)のとき、s を (i, j, k) が巡回なら 1、そうでなければ -1 として + θj = asin(-s·R[k][i])、θi = atan2(s·R[k][j], R[k][k])、θk = atan2(s·R[j][i], R[i][i])。 + """ + x, y, z, w = q + norm = math.sqrt(x * x + y * y + z * z + w * w) or 1.0 + x, y, z, w = x / norm, y / norm, z / norm, w / norm + m = ( + (1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)), + (2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)), + (2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)), + ) + axes = ROTATION_ORDERS.get(order, "ZXY") + i, j, k = ("XYZ".index(a) for a in axes) + s = 1.0 if (j - i) % 3 == 1 else -1.0 + angles = [0.0, 0.0, 0.0] + sin_j = max(-1.0, min(1.0, -s * m[k][i])) + angles[j] = math.asin(sin_j) + if abs(sin_j) < 1.0 - 1e-9: + angles[i] = math.atan2(s * m[k][j], m[k][k]) + angles[k] = math.atan2(s * m[j][i], m[i][i]) + else: + # ジンバルロック: θk を 0 にして θi に寄せる + angles[i] = math.atan2(-s * m[j][k], m[j][j]) + return (math.degrees(angles[0]), math.degrees(angles[1]), math.degrees(angles[2])) + + +def transform_spec(curves: Iterable[Curve], time: float, rest_rotation: Sequence[float]) -> dict[str, list[float | None]]: + """1 つの Transform のカーブの、``time`` での値を ``model_space.local_basis`` の ``spec`` の形にする。 + + オイラー回転のカーブはクォータニオンにする(アニメーションしていない成分は、元の回転をオイラー角にした値)。 + クォータニオンの一部の成分だけのカーブは、残りを元の回転で埋めてから正規化する。 + """ + position: list[float | None] = [None, None, None] + scale: list[float | None] = [None, None, None] + rotation: list[float | None] = [None, None, None, None] + euler: list[float | None] = [None, None, None] + order = DEFAULT_ROTATION_ORDER + for curve in curves: + value = evaluate(curve.keys, time) + if curve.kind == KIND_POSITION and curve.component < 3: + position[curve.component] = value + elif curve.kind == KIND_SCALE and curve.component < 3: + scale[curve.component] = value + elif curve.kind == KIND_ROTATION and curve.component < 4: + rotation[curve.component] = value + elif curve.kind == KIND_EULER and curve.component < 3: + euler[curve.component] = value + order = curve.rotation_order + if any(v is not None for v in euler): + rest = quaternion_to_euler(rest_rotation, order) + filled = [rest[i] if v is None else v for i, v in enumerate(euler)] + rotation = list(euler_to_quaternion(filled, order)) + elif any(v is not None for v in rotation): + filled = [float(rest_rotation[i]) if v is None else v for i, v in enumerate(rotation)] + norm = math.sqrt(sum(v * v for v in filled)) + rotation = [v / norm for v in filled] if norm > 1e-12 else [float(v) for v in rest_rotation] + return {"position": position, "rotation": rotation, "scale": scale} diff --git a/unitypackage_loader/core/animation_targets.py b/unitypackage_loader/core/animation_targets.py new file mode 100644 index 0000000..358f889 --- /dev/null +++ b/unitypackage_loader/core/animation_targets.py @@ -0,0 +1,297 @@ +"""AnimationClip のカーブの階層パスを、読み込んだオブジェクト(とボーン)に結び付ける。bpy 非依存(#209)。 + +クリップは対象のモデルを持たない(Animator を付けた GameObject からの相対パスだけを持つ)。読み込んだ階層の中で +パスがいちばん多く解決できるオブジェクトを、そのクリップのルート(Animator の GameObject)とみなす。 +同じモデルを複数置いたシーンでは、同じだけ解決できるルートがすべて対象になる。 + +Unity と Blender の階層の違いは次のように吸収する。 + +- 名前は完全一致を先に、なければ連番(``.001``)を外した形が 1 つだけのものを使う。 +- Blender の FBX インポーターはスキンメッシュをアーマチュアの子にするが、Unity ではアーマチュアの GameObject と兄弟。 + アーマチュアのオブジェクトの子(ボーンの子でないもの)は、アーマチュアの親の子としても引けるようにする。 +- アーマチュアの下はボーンの名前でたどる(ボーンを対象にしたカーブは #270 まで読み込まない)。 +- 読み込み側が足した Empty(FBX のルートなど)で一致しなければ、Empty の子を 1 段だけ探す。 +""" + +from __future__ import annotations + +from collections.abc import Hashable, Iterable, Sequence +from dataclasses import dataclass, field + +from .meta import strip_numeric_suffix + +__all__ = ["TargetObject", "TargetTree", "Resolved", "Binding", "bind_paths"] + +# 対象が決まったとみなす、解決できたパスの割合(ルート自身を指す空のパスは数えない) +MIN_MATCH_RATIO = 0.5 + + +@dataclass(frozen=True) +class TargetObject: + """読み込んだオブジェクト 1 つ。``name`` は Unity の名前と照合する名前(FBX のノード名)。""" + + key: Hashable + name: str + parent: Hashable | None = None + is_armature: bool = False + is_empty: bool = False + bone_parent: str | None = None # ボーンの子なら、そのボーンの名前 + bones: tuple[tuple[str, str | None], ...] = () # アーマチュアなら (ボーン名, 親のボーン名) + + +@dataclass(frozen=True) +class Resolved: + """パスの行き先。``bone`` があればアーマチュア ``key`` のボーン。""" + + key: Hashable + bone: str | None = None + + +@dataclass +class Binding: + """クリップのルートと、解決できたパス → 行き先。""" + + root: Hashable | None # None は「最上位のオブジェクトの集まり」をルートとみなしたもの + targets: dict[str, Resolved] = field(default_factory=dict) + unresolved: set[str] = field(default_factory=set) + + +class _Lookup: + """名前 → 候補(完全一致 → 連番を外した形が 1 つだけ)。""" + + def __init__(self): + self.exact: dict[str, list] = {} + self.base: dict[str, list] = {} + + def add(self, name: str, item) -> None: + self.exact.setdefault(name, []).append(item) + self.base.setdefault(strip_numeric_suffix(name), []).append(item) + + def get(self, name: str): + found = self.exact.get(name) + if found: + return found[0] + found = self.base.get(strip_numeric_suffix(name), []) + return found[0] if len(found) == 1 else None + + +class TargetTree: + """Unity の親子関係に直した、オブジェクトとボーンの木。""" + + def __init__(self, objects: Sequence[TargetObject], top_groups: Iterable[Sequence[Hashable]] = ()): + self.objects = {o.key: o for o in objects} + self._children: dict[Hashable | None, _Lookup] = {} + self._empty_children: dict[Hashable | None, list[Hashable]] = {} + self._bone_children: dict[tuple[Hashable, str | None], _Lookup] = {} + self._bone_objects: dict[tuple[Hashable, str], list[Hashable]] = {} + self._unity_children: dict[Hashable, list[Hashable]] = {} + for o in objects: + if o.is_armature: + for bone, parent in o.bones: + self._bone_children.setdefault((o.key, parent), _Lookup()).add(bone, bone) + for o in objects: + parent = o.parent if o.parent in self.objects else None + if parent is None: + continue + owner = self.objects[parent] + if owner.is_armature and o.bone_parent: + self._bone_objects.setdefault((parent, o.bone_parent), []).append(o.key) + continue + if owner.is_armature: + # スキンメッシュ: Unity ではアーマチュアと兄弟(アーマチュアの子としても引けるようにはしておく) + self._link(parent, o, unity=False) + above = owner.parent if owner.parent in self.objects else None + if above is not None: + self._link(above, o) + else: + self._link(parent, o) + self.groups: dict[int, list[Hashable]] = {} + for index, group in enumerate(top_groups): + keys = [k for k in group if k in self.objects] + if keys: + self.groups[index] = keys + self._group_lookup: dict[int, _Lookup] = {} + for index, keys in self.groups.items(): + lookup = _Lookup() + for k in keys: + lookup.add(self.objects[k].name, k) + owner = self.objects[k] + if owner.is_armature: + for child_key, child in self.objects.items(): + if child.parent == k and not child.bone_parent: + lookup.add(child.name, child_key) + self._group_lookup[index] = lookup + + def _link(self, parent: Hashable, o: TargetObject, unity: bool = True) -> None: + self._children.setdefault(parent, _Lookup()).add(o.name, o.key) + if o.is_empty: + self._empty_children.setdefault(parent, []).append(o.key) + if unity: + self._unity_children.setdefault(parent, []).append(o.key) + + # 解決 ----------------------------------------------------------------- + + def _child(self, current: Resolved, name: str) -> Resolved | None: + if current.bone is not None: + bone = self._bone_children.get((current.key, current.bone)) + found = bone.get(name) if bone else None + if found is not None: + return Resolved(current.key, found) + for key in self._bone_objects.get((current.key, current.bone), []): + if self.objects[key].name == name or strip_numeric_suffix(self.objects[key].name) == strip_numeric_suffix(name): + return Resolved(key) + return None + lookup = self._children.get(current.key) + found = lookup.get(name) if lookup else None + if found is not None: + return Resolved(found) + owner = self.objects.get(current.key) + if owner is not None and owner.is_armature: + roots = self._bone_children.get((current.key, None)) + bone = roots.get(name) if roots else None + if bone is not None: + return Resolved(current.key, bone) + for key in self._empty_children.get(current.key, []): + lookup = self._children.get(key) + found = lookup.get(name) if lookup else None + if found is not None: + return Resolved(found) + return None + + def resolve(self, root: Hashable | None, path: str, group: int | None = None) -> Resolved | None: + """``root`` からのパスの行き先(``root`` が None なら ``group`` 番目の最上位の集まりから)。""" + parts = [p for p in path.split("/")] if path else [] + if root is None: + if not parts or group is None or group not in self._group_lookup: + return None + found = self._group_lookup[group].get(parts[0]) + if found is None: + return None + current = Resolved(found) + parts = parts[1:] + else: + current = Resolved(root) + for part in parts: + nxt = self._child(current, part) + if nxt is None: + return None + current = nxt + return current + + def unity_descendants(self, key: Hashable) -> list[Hashable]: + """Unity の階層での子孫のオブジェクト(自身を含む。GameObject を非アクティブにしたときに隠れるもの)。""" + result: list[Hashable] = [] + stack = [key] + seen: set[Hashable] = set() + while stack: + current = stack.pop() + if current in seen: + continue + seen.add(current) + result.append(current) + stack.extend(self._unity_children.get(current, [])) + owner = self.objects.get(current) + if owner is not None and owner.is_armature: + # ボーンの子のオブジェクトはアーマチュアの下にある + stack.extend(k for (arm, _), keys in self._bone_objects.items() if arm == current for k in keys) + return result + + # 候補 ----------------------------------------------------------------- + + def candidates(self, first_names: set[str]) -> list[Hashable]: + """パスの先頭の名前を子に持つオブジェクト(ルートの候補)。""" + bases = {strip_numeric_suffix(n) for n in first_names} + found = [] + for parent, lookup in self._children.items(): + if any(n in lookup.exact for n in first_names) or any(b in lookup.base for b in bases): + found.append(parent) + for key, o in self.objects.items(): + if o.is_armature and key not in found: + roots = self._bone_children.get((key, None)) + if roots and (any(n in roots.exact for n in first_names) or any(b in roots.base for b in bases)): + found.append(key) + for key, empties in self._empty_children.items(): + if key in found: + continue + for empty in empties: + lookup = self._children.get(empty) + if lookup and (any(n in lookup.exact for n in first_names) or any(b in lookup.base for b in bases)): + found.append(key) + break + return found + + def ancestors(self, key: Hashable) -> set[Hashable]: + """オブジェクトの祖先(自身を含まない)。""" + result: set[Hashable] = set() + current = self.objects.get(key) + while current is not None and current.parent in self.objects and current.parent not in result: + result.add(current.parent) + current = self.objects[current.parent] + return result + + def depth(self, key: Hashable) -> int: + depth = 0 + seen: set[Hashable] = set() + current = self.objects.get(key) + while current is not None and current.parent in self.objects and current.key not in seen: + seen.add(current.key) + depth += 1 + current = self.objects[current.parent] + return depth + + +def bind_paths(tree: TargetTree, paths: Iterable[str]) -> list[Binding]: + """パスをいちばん多く解決できるルートと、その解決結果(同じだけ解決できるルートはすべて)。 + + 空のパス(ルート自身)だけのクリップは、どのオブジェクトのものか決められないので結び付けない。 + 同じオブジェクトに解決する候補(アーマチュアとその親など)は、階層の上のほうを残す。 + """ + paths = sorted(set(paths)) + named = [p for p in paths if p] + if not named: + return [] + firsts = {p.split("/")[0] for p in named} + scored: list[tuple[int, Binding]] = [] + roots: list[tuple[Hashable | None, int | None]] = [(key, None) for key in tree.candidates(firsts)] + roots += [(None, index) for index in tree.groups] + for root, group in roots: + binding = Binding(root) + for path in paths: + if not path: + if root is not None: + binding.targets[path] = Resolved(root) + continue + found = tree.resolve(root, path, group) + if found is None: + binding.unresolved.add(path) + else: + binding.targets[path] = found + count = sum(1 for p in binding.targets if p) + if count: + scored.append((count, binding)) + if not scored: + return [] + best = max(count for count, _ in scored) + if best < MIN_MATCH_RATIO * len(named): + return [] + chosen: dict[frozenset, Binding] = {} + for count, binding in scored: + if count != best: + continue + identity = frozenset((p, r) for p, r in binding.targets.items() if p) + kept = chosen.get(identity) + if kept is None or _higher(tree, binding, kept): + chosen[identity] = binding + # ルートの子孫を別のルートとみなしたものは外す(prefab の GameObject と、その下に置いた FBX の同じ名前のノード)。 + # 最上位の集まり(root が None)は祖先として扱わない(シーンに置いた複数の配置を残すため) + roots = {b.root for b in chosen.values() if b.root is not None} + return [b for b in chosen.values() if b.root is None or not (tree.ancestors(b.root) & roots)] + + +def _higher(tree: TargetTree, a: Binding, b: Binding) -> bool: + """a のルートが b より階層の上か(最上位の集まりがいちばん上)。""" + if b.root is None: + return False + if a.root is None: + return True + return tree.depth(a.root) < tree.depth(b.root) diff --git a/unitypackage_loader/core/model_space.py b/unitypackage_loader/core/model_space.py index d009bc9..698ead1 100644 --- a/unitypackage_loader/core/model_space.py +++ b/unitypackage_loader/core/model_space.py @@ -19,7 +19,6 @@ from .fbx_units import blender_axis_matrix, unity_axis_matrix from .transform import ( - BLENDER_TO_UNITY, IDENTITY, UNITY_TO_BLENDER, Mat4, @@ -135,14 +134,29 @@ def node_basis(basis: Mat4, spec: dict, basis_a: Mat4) -> Mat4: Unity 6 が読んだノードの値と突き合わせて確かめた(Issue #53)。元のノード値を L = C⁻¹·N·A⁻¹ で求め、上書きの無い成分は その値のまま使う。 """ - location, rotation, scale = decompose(chain((BLENDER_TO_UNITY, basis, _inverse(basis_a)))) - values = {"position": list(location), "rotation": list(rotation), "scale": list(scale)} + return local_basis(basis, spec, UNITY_TO_BLENDER, basis_a) + + +def local_values(basis: Mat4, left: Mat4, right: Mat4) -> tuple[list[float], list[float], list[float]]: + """行列 basis = left·L·right の、Unity のローカルの値 L(位置, 回転のクォータニオン, スケール)。""" + location, rotation, scale = decompose(chain((_inverse(left), basis, _inverse(right)))) + return list(location), list(rotation), list(scale) + + +def local_basis(basis: Mat4, spec: dict, left: Mat4, right: Mat4) -> Mat4: + """basis = left·L·right の L の成分を ``spec`` で置き換えた行列(``node_basis`` は left = C、right = A)。 + + FBX の中で親が FBX のノードのオブジェクトは left = A⁻¹、right = A(親子とも C·W·A の形のため)。 + シーンの GameObject の Empty は left = C、right = C⁻¹(#209 のアニメーションで使う)。 + """ + location, rotation, scale = local_values(basis, left, right) + values = {"position": location, "rotation": rotation, "scale": scale} for key, current in values.items(): for index, value in enumerate(spec.get(key, [])): if value is not None and index < len(current): current[index] = value local = trs(tuple(values["position"]), tuple(values["rotation"]), tuple(values["scale"])) # type: ignore[arg-type] - return chain((UNITY_TO_BLENDER, local, basis_a)) + return chain((left, local, right)) def collapsed_root(basis: Mat4, spec: dict, basis_a: Mat4) -> tuple[Mat4, Mat4]: From 5f9d1122e51e431135f2ff6247b899e36ab00a82 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 18:21:26 +0900 Subject: [PATCH 06/25] =?UTF-8?q?feat:=20=E3=83=91=E3=83=83=E3=82=B1?= =?UTF-8?q?=E3=83=BC=E3=82=B8=E3=81=AE=20.anim=20=E3=82=92=20Action=20?= =?UTF-8?q?=E3=81=AB=E3=81=97=E3=81=A6=20NLA=20=E3=81=AB=E3=83=9F=E3=83=A5?= =?UTF-8?q?=E3=83=BC=E3=83=88=E3=81=A7=E4=B8=A6=E3=81=B9=E3=82=8B=EF=BC=88?= =?UTF-8?q?#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit アバターの表情・衣装の切り替えや、環境アセットの扉・ライトの切り替えなどの Generic なクリップを、 読み込んだオブジェクトの Action にする。オプション Animation Clips(既定 ON)。NLA トラックはミュートで足すので、 読み込んだ直後の見た目は変わらない。 - クリップごとに Action を 1 つ作り、対象(オブジェクト・シェイプキー)ごとにスロットを作る。 - シェイプキーと表示の切り替えはキーと接線をそのままベジェ(階段は CONSTANT)にする。 GameObject の非アクティブは Unity の階層での子孫にも当てる。 - Transform はフレームごとに Unity のローカルの値から行列を求めてキーにする。FBX のノードは元のモデルの単位と軸で 変換するので、読み込んだオブジェクトに元のモデルの GUID(unity_model_guid)を残す。 モデルの単位と軸の計算は scene_placement.model_units に出して共有する。 - Humanoid のクリップ、ボーンのカーブ(#270)、ルート自身だけを動かすクリップは読み込まず、内訳をレポートに出す。 - .anim は走査のときにメモリへ載せる(.mat と同じく小さいので、読み直しの走査をしない)。 Yumeka 1.0.4 の Generic な 54 クリップ(Humanoid 10 を除く全部)、Super Cub の 20 クリップを読み込めることを確かめた。 Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender/animation.py | 361 ++++++++++++++++++ unitypackage_loader/blender/importer.py | 13 + unitypackage_loader/blender/model_import.py | 2 + unitypackage_loader/blender/options.py | 1 + .../blender/scene_placement.py | 21 +- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/package.py | 4 +- unitypackage_loader/core/report.py | 8 + .../operators/import_package.py | 9 + unitypackage_loader/ui/panel_report.py | 2 + 10 files changed, 411 insertions(+), 12 deletions(-) create mode 100644 unitypackage_loader/blender/animation.py diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py new file mode 100644 index 0000000..1984607 --- /dev/null +++ b/unitypackage_loader/blender/animation.py @@ -0,0 +1,361 @@ +"""パッケージの AnimationClip(.anim)を Action にして、読み込んだオブジェクトの NLA にミュートで並べる(#209)。 + +クリップの解析とパスの照合は ``core/animation.py`` と ``core/animation_targets.py``。ここでは次を行う。 + +- クリップごとに Action を 1 つ作り、対象(オブジェクト・シェイプキー)ごとにスロットを作る。 +- シェイプキーの値(Unity の 0〜100 → 0〜1)と表示の切り替え(``hide_viewport`` / ``hide_render``)は、キーと接線を + そのままベジェ(階段は CONSTANT)にする。GameObject の非アクティブは、Unity の階層での子孫にも当てる。 +- Transform は Unity のローカルの値をフレームごとに求め、オブジェクトの行列にしてから位置・回転・スケールのキーにする + (行列の対応は ``core/model_space.local_basis``)。ボーンを対象にしたカーブは読み込まない(#270)。 +- 対象ごとに、クリップの名前の NLA トラックをミュートで足す。読み込んだ直後の見た目は変わらない。 +""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass, field + +import bpy +from mathutils import Matrix + +from ..core.animation import ( + KIND_ACTIVE, + KIND_ENABLED, + KIND_SHAPE_KEY, + TRANSFORM_KINDS, + AnimationClip, + Curve, + bezier_handles, + parse_clip, + sample_times, + transform_spec, +) +from ..core.animation_targets import Binding, TargetObject, TargetTree, bind_paths +from ..core.model_space import ModelUnits, local_basis, local_values +from ..core.transform import IDENTITY, UNITY_TO_BLENDER, Mat4, inverse_affine +from .log import warn_skipped +from .model_import import FBX_NODE_PROP, MODEL_GUID_PROP, node_name + +CLIP_GUID_PROP = "unity_clip_guid" +# GameObject の行列に、向きや形を足して置いたオブジェクト(Transform のカーブを当てない) +_ADDED_SHAPE_PROPS = ("unity_terrain", "unity_decal", "unity_light", "unity_camera") +CLIP_PATH_PROP = "unity_clip_path" + + +@dataclass +class ClipStats: + """クリップの読み込みの集計(レポートに書く)。""" + + loaded: list[str] = field(default_factory=list) # 読み込んだクリップの pathname + humanoid: list[str] = field(default_factory=list) # Humanoid だけのクリップ(読み込まない) + humanoid_partial: list[str] = field(default_factory=list) # Humanoid のクリップのうち、マッスル値以外のカーブだけ読んだもの + root_only: list[str] = field(default_factory=list) # ルート自身だけを動かすクリップ(どのオブジェクトのものか決められない) + unbound: list[str] = field(default_factory=list) # 対象のオブジェクトが見つからなかったクリップ + empty: list[str] = field(default_factory=list) # 読み込める種類のカーブが無いクリップ + bone_only: list[str] = field(default_factory=list) # ボーンだけを動かすクリップ(#270 まで読み込まない) + bone_curves: int = 0 # ボーンを対象にしたカーブ(#270 まで読み込まない) + missing: int = 0 # 対象が見つからなかったカーブ(シェイプキーが無い、など) + transform_skipped: int = 0 # 行列の対応が分からないオブジェクトの Transform のカーブ + + +def _mat4(m: Matrix) -> Mat4: + return tuple(tuple(float(m[r][c]) for c in range(4)) for r in range(4)) # type: ignore[return-value] + + +def _target_tree(collection: bpy.types.Collection) -> TargetTree: + objects = list(collection.all_objects) + members = set(objects) + targets = [] + for obj in objects: + parent = obj.parent if obj.parent in members else None + bones: tuple = () + if obj.type == "ARMATURE": + bones = tuple((b.name, b.parent.name if b.parent else None) for b in obj.data.bones) + bone_parent = obj.parent_bone if parent is not None and obj.parent_type == "BONE" and obj.parent_bone else None + targets.append(TargetObject(obj, node_name(obj), parent, obj.type == "ARMATURE", obj.type == "EMPTY", bone_parent, bones)) + groups = [] + for coll in [collection, *collection.children_recursive]: + top = [o for o in coll.objects if o.parent is None or o.parent not in members] + if top: + groups.append(top) + return TargetTree(targets, groups) + + +class ClipImporter: + """1 回のインポートのクリップの読み込み。""" + + def __init__(self, session, collection: bpy.types.Collection): + self.session = session + self.pkg = session.pkg + self.report = session.report + self.collection = collection + self.scene = session.scene + render = self.scene.render + self.fps = render.fps / (render.fps_base or 1.0) + self.frame_start = self.scene.frame_start + self.stats = ClipStats() + self._units: dict[str, ModelUnits | None] = {} + self._tree: TargetTree | None = None + + # ------------------------------------------------------------------ + + def run(self) -> ClipStats: + entries = sorted((e for e in self.pkg.entries.values() if e.ext == ".anim" and e.has_asset), key=lambda e: e.pathname) + if not entries: + return self.stats + for entry in entries: + try: + clip = parse_clip(self.pkg.read_asset(entry.guid)) + except Exception as exc: # noqa: BLE001 - そのクリップだけを外して続ける + warn_skipped(self.report.warn, f"could not read animation clip {entry.pathname}", exc) + continue + if not clip.curves: + (self.stats.humanoid if clip.humanoid else self.stats.empty).append(entry.pathname) + continue + if clip.paths == {""}: + self.stats.root_only.append(entry.pathname) + continue + if self._tree is None: + self._tree = _target_tree(self.collection) + bindings = bind_paths(self._tree, clip.paths) + if not bindings: + self.stats.unbound.append(entry.pathname) + continue + try: + result = self.build(entry, clip, bindings) + if result == "loaded": + self.stats.loaded.append(entry.pathname) + if clip.humanoid: + self.stats.humanoid_partial.append(entry.pathname) + elif result == "bones": + self.stats.bone_only.append(entry.pathname) + else: + self.stats.unbound.append(entry.pathname) + except Exception as exc: # noqa: BLE001 - そのクリップだけを外して続ける + warn_skipped(self.report.warn, f"could not import animation clip {entry.pathname}", exc) + return self.stats + + # ------------------------------------------------------------------ + + def build(self, entry, clip: AnimationClip, bindings: list[Binding]) -> str: + """クリップの Action を作って NLA に並べる。"loaded"、ボーンだけなら "bones"、何も当てられなければ "none"。""" + action = bpy.data.actions.new(clip.name or entry.name) + action[CLIP_GUID_PROP] = entry.guid + action[CLIP_PATH_PROP] = entry.pathname + action.use_frame_range = True + action.frame_start = 0.0 + action.frame_end = max((clip.stop - clip.start) * self.fps, 1.0) + action.use_cyclic = clip.loop + strip = action.layers.new("Layer").strips.new(type="KEYFRAME") + users: dict[bpy.types.ID, bpy.types.ActionSlot] = {} + + def slot_for(datablock: bpy.types.ID, id_type: str, label: str): + slot = users.get(datablock) + if slot is None: + slot = action.slots.new(id_type=id_type, name=label[:60] or id_type) + users[datablock] = slot + return slot + + by_path: dict[str, list[Curve]] = {} + for curve in clip.curves: + by_path.setdefault(curve.path, []).append(curve) + tree = self._tree + bones = 0 + for binding in bindings: + for path, curves in by_path.items(): + target = binding.targets.get(path) + if target is None: + self.stats.missing += len(curves) + continue + if target.bone is not None: + bones += len(curves) + continue + obj = target.key + for curve in curves: + if curve.kind == KIND_SHAPE_KEY: + self._shape_key(strip, slot_for, obj, curve, clip) + for kind in (KIND_ACTIVE, KIND_ENABLED): + toggles = [c for c in curves if c.kind == kind] + if toggles: + hidden = tree.unity_descendants(obj) if kind == KIND_ACTIVE else [obj] + for member in hidden: + self._toggle(strip, slot_for, member, toggles[-1], clip) + transforms = [c for c in curves if c.kind in TRANSFORM_KINDS] + if transforms: + self._transform(strip, slot_for, obj, transforms, clip) + self.stats.bone_curves += bones + if not users: + bpy.data.actions.remove(action) + return "bones" if bones else "none" + for datablock, slot in users.items(): + self._add_track(datablock, action, slot, clip.name or entry.name) + return "loaded" + + 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() + 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 + + # 各種のカーブ ------------------------------------------------------ + + def _frame(self, time: float, clip: AnimationClip) -> float: + return (time - clip.start) * self.fps + + def _write_keys(self, channelbag, data_path: str, index: int, curve: Curve, clip: AnimationClip, scale: float = 1.0, + constant: bool = False, transform=None) -> None: + if channelbag.fcurves.find(data_path, index=index) is not None: + return # 同じ対象に別のカーブで書いた(GameObject の非アクティブと Renderer の無効など) + fcurve = channelbag.fcurves.new(data_path, index=index) + keys = bezier_handles(curve.keys, scale) + fcurve.keyframe_points.add(len(keys)) + for point, key in zip(fcurve.keyframe_points, keys): + value = transform(key.value) if transform else key.value + point.co = (self._frame(key.time, clip), value) + if constant or key.constant: + point.interpolation = "CONSTANT" + else: + point.interpolation = "BEZIER" + point.handle_left_type = "FREE" + point.handle_right_type = "FREE" + point.handle_left = (self._frame(key.left[0], clip), key.left[1]) + point.handle_right = (self._frame(key.right[0], clip), key.right[1]) + if clip.loop: + fcurve.modifiers.new("CYCLES") + fcurve.update() + + def _shape_key(self, strip, slot_for, obj, curve: Curve, clip: AnimationClip) -> None: + name = curve.shape_key + shape_keys = obj.data.shape_keys if obj.type == "MESH" and obj.data is not None else None + if shape_keys is None or name not in shape_keys.key_blocks: + self.stats.missing += 1 + return + block = shape_keys.key_blocks[name] + # Unity の重みは 100 を超えられる。Blender の値は slider_max までなので広げる + peak = max((k.value for k in curve.keys), default=0.0) / 100.0 + if peak > block.slider_max: + block.slider_max = min(peak, 10.0) + slot = slot_for(shape_keys, "KEY", f"{node_name(obj)} Key") + bag = strip.channelbag(slot, ensure=True) + self._write_keys(bag, f'key_blocks["{_escape(name)}"].value', 0, curve, clip, scale=0.01) + + def _toggle(self, strip, slot_for, obj, curve: Curve, clip: AnimationClip) -> None: + slot = slot_for(obj, "OBJECT", node_name(obj)) + bag = strip.channelbag(slot, ensure=True) + for data_path in ("hide_viewport", "hide_render"): + self._write_keys(bag, data_path, 0, curve, clip, constant=True, transform=lambda v: 0.0 if v >= 0.5 else 1.0) + + def _transform(self, strip, slot_for, obj, curves: list[Curve], clip: AnimationClip) -> None: + sides = self._basis_sides(obj) + if sides is None: + self.stats.transform_skipped += len(curves) + return + left, right = sides + slot = slot_for(obj, "OBJECT", node_name(obj)) + bag = strip.channelbag(slot, ensure=True) + rest = _mat4(obj.matrix_basis) + _, rest_rotation, _ = local_values(rest, left, right) + mode = obj.rotation_mode + times = sample_times(curves, clip.start, clip.stop, self.fps) + has = {c.kind for c in curves} + rows: list[tuple[float, Matrix]] = [] + for time in times: + spec = transform_spec(curves, time, rest_rotation) + rows.append((self._frame(time, clip), Matrix(local_basis(rest, spec, left, right)))) + channels: dict[tuple[str, int], list[tuple[float, float]]] = {} + previous = obj.rotation_euler.copy() if mode not in ("QUATERNION", "AXIS_ANGLE") else None + for frame, matrix in rows: + location, rotation, scale = matrix.decompose() + if "position" in has: + for i in range(3): + channels.setdefault(("location", i), []).append((frame, location[i])) + if has & {"rotation", "euler"}: + if mode == "QUATERNION": + for i in range(4): + channels.setdefault(("rotation_quaternion", i), []).append((frame, rotation[i])) + elif mode == "AXIS_ANGLE": + axis, angle = rotation.to_axis_angle() + for i, value in enumerate((angle, *axis)): + channels.setdefault(("rotation_axis_angle", i), []).append((frame, value)) + else: + euler = rotation.to_euler(mode, previous) if previous is not None else rotation.to_euler(mode) + previous = euler + for i in range(3): + channels.setdefault(("rotation_euler", i), []).append((frame, euler[i])) + if "scale" in has: + for i in range(3): + channels.setdefault(("scale", i), []).append((frame, scale[i])) + for (data_path, index), points in channels.items(): + if bag.fcurves.find(data_path, index=index) is not None: + continue + fcurve = bag.fcurves.new(data_path, index=index) + fcurve.keyframe_points.add(len(points)) + for point, (frame, value) in zip(fcurve.keyframe_points, points): + point.co = (frame, value) + point.interpolation = "LINEAR" + if clip.loop: + fcurve.modifiers.new("CYCLES") + fcurve.update() + + def _basis_sides(self, obj) -> tuple[Mat4, Mat4] | None: + """オブジェクトの行列 basis = left·L·right の (left, right)。分からなければ None。 + + - FBX のノードで、親も同じモデルの FBX のノード(アーマチュアを除く): left = A⁻¹、right = A + - FBX のノードで、親がそれ以外: left = C、right = A(``model_space.node_basis`` と同じ) + - シーン・prefab の GameObject のオブジェクト(Empty、Unity の Mesh・組み込みメッシュ): left = C、right = C⁻¹ + (親の GameObject の Empty の下に C·L·C⁻¹ で置いている。ライト・カメラ・Terrain・デカールは向きや形を足しているので除く) + """ + parent = obj.parent + if obj.get(FBX_NODE_PROP) is not None and obj.get(MODEL_GUID_PROP): + units = self._model_units(str(obj[MODEL_GUID_PROP])) + if units is None: + return None + a = units.basis_a() + if parent is not None and parent.get(MODEL_GUID_PROP) == obj[MODEL_GUID_PROP] and parent.get(FBX_NODE_PROP) is not None: + if parent.type == "ARMATURE" or obj.parent_type != "OBJECT": + return None # スキンメッシュ・ボーンの子は、Unity と親子が違う + inverse = inverse_affine(a) + return (inverse, a) if inverse is not None else None + return UNITY_TO_BLENDER, a + if obj.get("unity_game_object") is not None and obj.get(MODEL_GUID_PROP) is None and obj.type in ("EMPTY", "MESH"): + if any(key in obj for key in _ADDED_SHAPE_PROPS): + return None + inverse = inverse_affine(UNITY_TO_BLENDER) + return UNITY_TO_BLENDER, inverse or IDENTITY + return None + + def _model_units(self, guid: str) -> ModelUnits | None: + if guid not in self._units: + from .scene_placement import model_units + + summary = self.session.model_by_guid.get(guid) + path = self.session.paths.get(guid) + self._units[guid] = model_units(summary, path) if summary is not None and path is not None else None + return self._units[guid] + + +def _escape(name: str) -> str: + return name.replace("\\", "\\\\").replace('"', '\\"') + + +def report_lines(stats: ClipStats) -> Iterable[str]: + """レポートの警告に足す行(読み込まなかったものの内訳)。""" + if stats.humanoid: + yield f"skipped {len(stats.humanoid)} Humanoid animation clip(s) (muscle curves are not supported)" + if stats.humanoid_partial: + yield f"imported only the non-muscle curves of {len(stats.humanoid_partial)} Humanoid animation clip(s)" + if stats.root_only: + yield f"skipped {len(stats.root_only)} animation clip(s) that only animate the object they are played on (target unknown)" + if stats.bone_only: + yield f"skipped {len(stats.bone_only)} animation clip(s) that only animate bones (not supported yet)" + if stats.bone_curves: + yield f"skipped {stats.bone_curves} animation curve(s) targeting bones (not supported yet)" + if stats.missing: + yield f"{stats.missing} animation curve(s) had no matching shape key or object" + if stats.unbound: + yield f"{len(stats.unbound)} animation clip(s) did not match any imported object" + if stats.transform_skipped: + yield f"skipped {stats.transform_skipped} Transform curve(s) on objects whose Unity transform could not be determined" diff --git a/unitypackage_loader/blender/importer.py b/unitypackage_loader/blender/importer.py index 8c520c7..3bd1cd5 100644 --- a/unitypackage_loader/blender/importer.py +++ b/unitypackage_loader/blender/importer.py @@ -37,9 +37,12 @@ from ..core.unity_binary import load_documents from ..core.units import UNIT_PREFABS, UNIT_SCENES, PrefabSummary, SceneSummary from . import outline as outline_builder +from .animation import ClipImporter +from .animation import report_lines as clip_report_lines from .log import record_failure, warn_skipped from .model_import import ( FBX_NODE_PROP, + MODEL_GUID_PROP, adopt_into_collection, delegate_to_vrm_addon, import_model_file, @@ -302,6 +305,9 @@ def run(self) -> None: done += 1 self.fill_missed_textures() self.materials.warn_slotless() + if self.opts.import_clips: + 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)]) if self.opts.arrange == "SIDE_BY_SIDE" and len(self.prefab_collections) > 1: arrange_collections(self.context, self.prefab_collections) @@ -309,6 +315,12 @@ def run(self) -> None: self.collection["unity_package"] = self.package_path.name self.step(1.0, "Done") + def import_clips(self) -> None: + """パッケージの AnimationClip を Action にして、読み込んだオブジェクトの NLA にミュートで並べる(#209)。""" + stats = ClipImporter(self, self.collection).run() + self.report.clips.extend(stats.loaded) + self.report.clip_notes.extend(clip_report_lines(stats)) + def analyze(self) -> None: """パッケージを解析し(ダイアログで解析済みなら使う)、解析中の警告と読み込めないモデルをレポートに写す。""" if self.prepared is None: @@ -564,6 +576,7 @@ def build_model( new = new_since(before) adopt_into_collection(new, self.scene, target) for obj in new["objects"]: + obj[MODEL_GUID_PROP] = model.guid if obj.type == "ARMATURE": # メッシュを覆って見づらいので、オブジェクトの表示を線にする(Object > Viewport Display > Display As。#260)。 # ボーンの形(Data の Display As)は変えない diff --git a/unitypackage_loader/blender/model_import.py b/unitypackage_loader/blender/model_import.py index 4ff41b8..9ba3389 100644 --- a/unitypackage_loader/blender/model_import.py +++ b/unitypackage_loader/blender/model_import.py @@ -51,6 +51,8 @@ def remove_created(before: dict[str, set[str]]) -> None: # 同じ名前のオブジェクトがあると、Blender は新しいほうの名前を付け替える。ノード名がもともと Blender の連番の形 # (Plane.010 など)だと、連番を外しても元の名前に戻せないので、読み込んだときの名前をここに残し、Unity のデータとの照合に使う FBX_NODE_PROP = "unity_fbx_node" +# 読み込んだオブジェクトの元のモデルの GUID。クリップの Transform を当てるときに、モデルの単位と軸を引く(#209) +MODEL_GUID_PROP = "unity_model_guid" def node_name(obj: bpy.types.Object) -> str: diff --git a/unitypackage_loader/blender/options.py b/unitypackage_loader/blender/options.py index 755aacc..514ba05 100644 --- a/unitypackage_loader/blender/options.py +++ b/unitypackage_loader/blender/options.py @@ -39,6 +39,7 @@ class ImportOptions: 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) ignore_leaf_bones: bool = True global_scale: float = 1.0 import_blend: bool = False # 同梱 .blend を append するか(Python スクリプトを含み得るので既定 OFF) diff --git a/unitypackage_loader/blender/scene_placement.py b/unitypackage_loader/blender/scene_placement.py index 614b111..b89983f 100644 --- a/unitypackage_loader/blender/scene_placement.py +++ b/unitypackage_loader/blender/scene_placement.py @@ -48,6 +48,17 @@ from .importer import _ImportSession + +def model_units(summary: ModelSummary, path) -> ModelUnits | None: + """モデルの FBX の単位と軸(配置の計算の fileScale と軸の変換に使う。#53 / #240)。FBX 以外は None。""" + if summary.entry.ext != ".fbx": + return None + # Unity 4 のモデルは読み込みで Unity と同じ大きさにしてあるので、fileScale を m_GlobalScale にする(#233) + unit = summary.info.unity_unit_scale(read_unit_scale(path)) + # 軸の変換を考えるのは Bake Axis Conversion を入れたモデルだけ(入れていなければ Y が上と同じに扱って合う。#240) + axes = read_axes(path) if summary.info.bake_axis_conversion else None + return ModelUnits(unit, axes, summary.info.global_scale) + class SceneImport: """シーン 1 つの読み込み(``_ImportSession.import_scene``)。 @@ -129,15 +140,7 @@ def link(self, obj: bpy.types.Object, parent, local: Matrix, visible: bool) -> N def unit_scale(self, summary: ModelSummary) -> ModelUnits | None: """モデルの FBX の単位と軸(配置の計算の fileScale と軸の変換に使う。#53 / #240)。FBX 以外は None。""" if summary.guid not in self.unit_scales: - path = self.session.paths[summary.guid] - if summary.entry.ext == ".fbx": - # Unity 4 のモデルは読み込みで Unity と同じ大きさにしてあるので、fileScale を m_GlobalScale にする(#233) - unit = summary.info.unity_unit_scale(read_unit_scale(path)) - # 軸の変換を考えるのは Bake Axis Conversion を入れたモデルだけ(入れていなければ Y が上と同じに扱って合う。#240) - axes = read_axes(path) if summary.info.bake_axis_conversion else None - self.unit_scales[summary.guid] = ModelUnits(unit, axes, summary.info.global_scale) - else: - self.unit_scales[summary.guid] = None + self.unit_scales[summary.guid] = model_units(summary, self.session.paths[summary.guid]) return self.unit_scales[summary.guid] # --- モデルの配置 --- diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 31fbfe0..2e416ff 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.5" +version = "1.18.0-dev.6" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/package.py b/unitypackage_loader/core/package.py index 8bd9261..d9ddee0 100644 --- a/unitypackage_loader/core/package.py +++ b/unitypackage_loader/core/package.py @@ -47,8 +47,8 @@ # 同じ GUID の ``pathname`` で拡張子が分かった時点で残すか捨てるかを決める(保持するのは常に 1 件。#75)。 # ``pathname`` が続けて来ないパッケージでは、保持したものを ``_CACHE_MAX_SIZE`` 以下に限って残す(超えたものは read_asset で再走査) # シェーダーは宣言の読み取り用(#118)、サブグラフは UV の Tiling & Offset をたどるため(#193)、 -# .terrainlayer は Terrain のレイヤーのテクスチャを展開の前に知るため(#205) -_CACHE_EXTS = frozenset({".mat", ".prefab", ".unity", ".shader", ".shadergraph", ".shadersubgraph", ".terrainlayer"}) +# .terrainlayer は Terrain のレイヤーのテクスチャを展開の前に知るため(#205)、.anim はクリップを Action にするため(#209) +_CACHE_EXTS = frozenset({".mat", ".prefab", ".unity", ".shader", ".shadergraph", ".shadersubgraph", ".terrainlayer", ".anim"}) _CACHE_MAX_SIZE = 2 << 20 # 2 MiB # メモリへ丸ごと読むメンバーの上限。tar ヘッダーのサイズで判定するので、gzip / sparse で # 小さく見せた巨大メンバーでも展開前に弾ける。超えたものは警告して無視する diff --git a/unitypackage_loader/core/report.py b/unitypackage_loader/core/report.py index d4ae9ad..a1bf3dd 100644 --- a/unitypackage_loader/core/report.py +++ b/unitypackage_loader/core/report.py @@ -58,6 +58,8 @@ class ImportReport: cameras: int = 0 # シーンから作ったカメラ decals: int = 0 # シーンの DecalProjector から作った板(#165) terrains: int = 0 # シーンの Terrain から作ったメッシュ(#205) + clips: list[str] = field(default_factory=list) # Action にした AnimationClip の pathname(#209) + clip_notes: list[str] = field(default_factory=list) # 読み込まなかったクリップ・カーブの内訳(Humanoid など。#209) exposures: list[str] = field(default_factory=list) # HDRP の Volume の露出をライトに反映したシーンごとの内容(#130) warnings: list[str] = field(default_factory=list) errors: list[str] = field(default_factory=list) @@ -94,6 +96,8 @@ def summary(self) -> str: parts.append(f"{self.decals} decals") if self.terrains: parts.append(f"{self.terrains} terrains") + if self.clips: + parts.append(f"{len(self.clips)} animation clips") text = ", ".join(parts) problems = [f"{len(self.errors)} error(s)"] if self.errors else [] if self.warnings: @@ -131,6 +135,10 @@ def as_text(self) -> str: lines.append(f" decals: {self.decals}") if self.terrains: lines.append(f" terrains: {self.terrains}") + if self.clips or self.clip_notes: + lines.append(f" animation clips ({len(self.clips)}):") + lines += [f" - {c}" for c in self.clips] + lines += [f" * {n}" for n in self.clip_notes] if self.exposures: lines.append(f" exposure ({len(self.exposures)}):") lines += [f" - {e}" for e in self.exposures] diff --git a/unitypackage_loader/operators/import_package.py b/unitypackage_loader/operators/import_package.py index 6c2c537..5ca3409 100644 --- a/unitypackage_loader/operators/import_package.py +++ b/unitypackage_loader/operators/import_package.py @@ -75,6 +75,14 @@ class IMPORT_SCENE_OT_unitypackage(bpy.types.Operator, ImportHelper): ), ) 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" + ), + ) ignore_leaf_bones: BoolProperty(name="Ignore Leaf Bones", default=True) import_blend: BoolProperty( name="Import Bundled .blend Files", @@ -177,6 +185,7 @@ def draw(self, context): if body: body.prop(self, "fbx_importer") body.prop(self, "use_anim") + body.prop(self, "import_clips") body.prop(self, "ignore_leaf_bones") body.prop(self, "use_vrm_addon") body.prop(self, "import_blend") diff --git a/unitypackage_loader/ui/panel_report.py b/unitypackage_loader/ui/panel_report.py index 4f3dbe3..04c27f9 100644 --- a/unitypackage_loader/ui/panel_report.py +++ b/unitypackage_loader/ui/panel_report.py @@ -68,6 +68,8 @@ def draw(self, context): col.label(text=f"Decals: {report.decals}") if report.terrains: col.label(text=f"Terrains: {report.terrains}") + if report.clips: + col.label(text=f"Animation clips: {len(report.clips)}") if report.prefabs: col.label(text=f"Prefabs: {len(report.prefabs)}") if report.models: From 6078dfdfde6d750d7cf5c21927c30a0182f35141 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 18:21:26 +0900 Subject: [PATCH 07/25] =?UTF-8?q?test:=20.anim=20=E3=82=92=E5=90=AB?= =?UTF-8?q?=E3=82=80=E5=90=88=E6=88=90=E3=83=91=E3=83=83=E3=82=B1=E3=83=BC?= =?UTF-8?q?=E3=82=B8=E3=81=A8=E6=9C=9F=E5=BE=85=E5=80=A4=E3=82=92=E8=B6=B3?= =?UTF-8?q?=E3=81=99=EF=BC=88#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 合成パッケージ synthetic_anim は、シェイプキー・表示の切り替え・Transform(最上位のノードと FBX の中の子)・ ボーン・Humanoid・ルートだけ・当てはまらないパスのクリップを持つ。Models 単位、シーンに 2 か所置いたもの、 Animation Clips を OFF にしたものの 3 通りで確かめる。 統合テストに clips の確認を足す。NLA トラックのミュートを Python から切り替えても依存関係が組み直されず 評価されないので(NLA エディターの操作では組み直される)、コレクションを付け外ししてから値を読む。 扉の回転は Unity の Y まわりの +90° が Blender の Z まわりの -90°、取っ手の位置は Blender 由来の FBX (Unity ではスケール 100)での Unity の距離になることを確かめる。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_anim.json | 36 +++++ tests/expectations_synthetic_anim_off.json | 15 ++ tests/expectations_synthetic_anim_scene.json | 76 +++++++++++ tests/integration_import.py | 95 ++++++++++++- tests/integration_runs.json | 4 + tests/make_synthetic_anim_package.py | 136 +++++++++++++++++++ 6 files changed, 361 insertions(+), 1 deletion(-) create mode 100644 tests/expectations_synthetic_anim.json create mode 100644 tests/expectations_synthetic_anim_off.json create mode 100644 tests/expectations_synthetic_anim_scene.json create mode 100644 tests/make_synthetic_anim_package.py diff --git a/tests/expectations_synthetic_anim.json b/tests/expectations_synthetic_anim.json new file mode 100644 index 0000000..aad115d --- /dev/null +++ b/tests/expectations_synthetic_anim.json @@ -0,0 +1,36 @@ +{ + "options": { + "unit": "MODELS" + }, + "errors": 0, + "objects": { + "count": 6 + }, + "clips": { + "count": 4, + "actions": ["DoorOpen", "HatOff", "Smile", "Wave"], + "notes_contain": [ + "skipped 1 Humanoid animation clip", + "skipped 1 animation clip(s) that only animate the object", + "skipped 4 animation curve(s) targeting bones", + "1 animation clip(s) did not match" + ], + "tracks": { + "Face": ["Smile"], + "Hat": ["HatOff"], + "Door": ["DoorOpen"], + "Knob": ["DoorOpen"], + "Body": ["Wave"], + "Armature": [] + }, + "values": [ + { "track": "Smile", "object": "Face", "seconds": 0, "shape_key": "smile", "value": 0.0 }, + { "track": "Smile", "object": "Face", "seconds": 0.5, "shape_key": "smile", "value": 0.5 }, + { "track": "Smile", "object": "Face", "seconds": 1, "shape_key": "smile", "value": 1.0 }, + { "track": "HatOff", "object": "Hat", "seconds": 0, "hidden": true }, + { "track": "Wave", "object": "Body", "seconds": 0, "hidden": true }, + { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 1, "axis": [0, 0, 1], "degrees": -90 } }, + { "track": "DoorOpen", "object": "Knob", "seconds": 0, "distance_to": "Door", "distance": 111.8034 } + ] + } +} diff --git a/tests/expectations_synthetic_anim_off.json b/tests/expectations_synthetic_anim_off.json new file mode 100644 index 0000000..18bb6ec --- /dev/null +++ b/tests/expectations_synthetic_anim_off.json @@ -0,0 +1,15 @@ +{ + "options": { + "unit": "MODELS", + "import_clips": false + }, + "errors": 0, + "clips": { + "count": 0, + "actions": [], + "tracks": { + "Face": [], + "Door": [] + } + } +} diff --git a/tests/expectations_synthetic_anim_scene.json b/tests/expectations_synthetic_anim_scene.json new file mode 100644 index 0000000..469bbdf --- /dev/null +++ b/tests/expectations_synthetic_anim_scene.json @@ -0,0 +1,76 @@ +{ + "options": { + "unit": "SCENES" + }, + "errors": 0, + "scenes": { + "count": 1 + }, + "clips": { + "count": 4, + "actions": [ + "DoorOpen", + "HatOff", + "Smile", + "Wave" + ], + "instances": { + "Face": 2, + "Door": 2, + "Knob": 2 + }, + "tracks": { + "Face": [ + "Smile" + ], + "Hat": [ + "HatOff" + ], + "Door": [ + "DoorOpen" + ], + "Knob": [ + "DoorOpen" + ], + "Body": [ + "Wave" + ] + }, + "values": [ + { + "track": "Smile", + "object": "Face", + "seconds": 0.5, + "shape_key": "smile", + "value": 0.5 + }, + { + "track": "HatOff", + "object": "Hat", + "seconds": 0, + "hidden": true + }, + { + "track": "DoorOpen", + "object": "Door", + "rotation_delta": { + "from": 0, + "to": 1, + "axis": [ + 0, + 0, + 1 + ], + "degrees": -90 + } + }, + { + "track": "DoorOpen", + "object": "Knob", + "seconds": 0, + "distance_to": "Door", + "distance": 111.8034 + } + ] + } +} diff --git a/tests/integration_import.py b/tests/integration_import.py index db895b1..21f29ac 100644 --- a/tests/integration_import.py +++ b/tests/integration_import.py @@ -15,6 +15,7 @@ from __future__ import annotations import json +import math import sys import tempfile import traceback @@ -23,7 +24,7 @@ from pathlib import Path import bpy -from mathutils import Vector +from mathutils import Matrix, Vector REPO_ROOT = Path(__file__).resolve().parent.parent if str(REPO_ROOT) not in sys.path: @@ -604,6 +605,97 @@ def check_shape_keys(ctx: Context) -> None: c.eq(f"{obj_name}.shape_keys", actual, count) +def _clip_datablocks(obj) -> list: + """オブジェクトと、そのシェイプキー(クリップの NLA トラックを持つもの)。""" + result = [obj] + if obj.type == "MESH" and obj.data is not None and obj.data.shape_keys is not None: + result.append(obj.data.shape_keys) + return result + + +def _clip_tracks(obj) -> list[str]: + return sorted(t.name for d in _clip_datablocks(obj) if d.animation_data for t in d.animation_data.nla_tracks) + + +def _at_clip_time(objects, track: str, seconds: float): + """``objects`` の ``track`` の NLA トラックだけを有効にして ``seconds`` 秒のフレームにする(戻すときは同じ関数を None で呼ぶ)。""" + scene = bpy.context.scene + fps = scene.render.fps / scene.render.fps_base + for obj in objects: + for d in _clip_datablocks(obj): + if d.animation_data: + for t in d.animation_data.nla_tracks: + t.mute = t.name != track if seconds is not None else True + # Python からミュートを切り替えても依存関係は組み直されず、評価済みのトラックは切り替わらない(NLA エディターの操作では + # 組み直される)。コレクションを付け外しして組み直させる + temp = bpy.data.collections.new("_clip_check") + scene.collection.children.link(temp) + scene.collection.children.unlink(temp) + bpy.data.collections.remove(temp) + scene.frame_set(scene.frame_start + round((seconds or 0) * fps)) + bpy.context.view_layer.update() + + +def _world(obj) -> Matrix: + return obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).matrix_world.copy() + + +def check_clips(ctx: Context) -> None: + """パッケージの .anim から作った Action と NLA トラック(#209)。""" + c, spec = ctx.c, ctx.exp.get("clips") + if spec is None: + return + if "count" in spec: + c.eq("clip count", len(ctx.report.clips), spec["count"]) + if "actions" in spec: + c.eq("actions", sorted(a.name for a in bpy.data.actions if a.get("unity_clip_guid")), sorted(spec["actions"])) + for text in spec.get("notes_contain", []): + c.true(f"clip note contains {text!r}", any(text in n for n in ctx.report.clip_notes), f"notes: {ctx.report.clip_notes}") + for name, count in spec.get("instances", {}).items(): # 同じ名前のオブジェクトの数(シーンに同じモデルを複数置いたとき) + c.eq(f"objects named {name}", len([o for o in bpy.data.objects if _strip_suffix(o.name) == name]), count) + for name, tracks in spec.get("tracks", {}).items(): + objects = [o for o in bpy.data.objects if _strip_suffix(o.name) == name] + c.true(f"objects named {name} exist", bool(objects)) + 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: + 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"]] + if not objects: + c.true(f"object {value['object']} exists", False) + continue + label = f"{value['track']} {value['object']}" + for obj in objects: + if "shape_key" in value: + _at_clip_time([obj], value["track"], value["seconds"]) + key = obj.data.shape_keys.evaluated_get(bpy.context.evaluated_depsgraph_get()) + actual = key.key_blocks[value["shape_key"]].value + c.close(f"{label} {value['shape_key']} at {value['seconds']}s", actual, value["value"], 1e-3) + if "hidden" in value: + _at_clip_time([obj], value["track"], value["seconds"]) + evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + c.eq(f"{label} hidden at {value['seconds']}s", (evaluated.hide_viewport, evaluated.hide_render), (value["hidden"],) * 2) + if "distance_to" in value: + other = min((o for o in bpy.data.objects if _strip_suffix(o.name) == value["distance_to"]), + key=lambda o: (o.matrix_world.translation - obj.matrix_world.translation).length) + _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 "rotation_delta" in value: + delta = value["rotation_delta"] + _at_clip_time([obj], value["track"], delta["from"]) + before = _world(obj).to_3x3().normalized() + _at_clip_time([obj], value["track"], delta["to"]) + after = _world(obj).to_3x3().normalized() + expected = Matrix.Rotation(math.radians(delta["degrees"]), 3, delta["axis"]) + error = max(abs(a - b) for row_a, row_b in zip(after @ before.inverted(), expected) for a, b in zip(row_a, row_b)) + c.true(f"{label} world rotation from {delta['from']}s to {delta['to']}s", error < 1e-3, + f"expected {delta['degrees']} deg about {delta['axis']}, got {[[round(v, 3) for v in r] for r in after @ before.inverted()]}") + _at_clip_time(list(bpy.data.objects), "", None) + + # 読み込みの後に、この順で確かめる。``steps`` の手順の ``checks`` も同じ表で確かめる(片付けの確認を除く) CHECKS: list[Callable[[Context], None]] = [ check_objects, @@ -624,6 +716,7 @@ def check_shape_keys(ctx: Context) -> None: check_scene_settings, check_shared_meshes, check_shape_keys, + check_clips, ] diff --git a/tests/integration_runs.json b/tests/integration_runs.json index 7da296f..57debfa 100644 --- a/tests/integration_runs.json +++ b/tests/integration_runs.json @@ -7,6 +7,7 @@ { "script": "tests/make_synthetic_toon_package.py", "blender": true, "outputs": ["synthetic_toon.unitypackage"] }, { "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_nested_package.py", "blender": false, @@ -42,6 +43,9 @@ { "package": "synthetic_mesh.unitypackage", "expectations": "expectations_synthetic_mesh.json", "note": "Unity の Mesh(.asset と prefab に埋め込んだもの)と .asset のマテリアルを使うシーン" }, { "package": "synthetic_mesh.unitypackage", "expectations": "expectations_synthetic_mesh_prefabs.json", "note": "Unity の Mesh だけを使う prefab" }, { "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_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_anim_package.py b/tests/make_synthetic_anim_package.py new file mode 100644 index 0000000..727fa20 --- /dev/null +++ b/tests/make_synthetic_anim_package.py @@ -0,0 +1,136 @@ +"""AnimationClip(.anim)を含む合成 unitypackage を生成する(Issue #209)。 + + blender -b --factory-startup --python tests/make_synthetic_anim_package.py -- <出力パス.unitypackage> + +実在アセットのデータは使わない。 + +- Models/Rig.fbx: 最上位のノード Face(シェイプキー smile を持つ板)・Hat・Door(子に Knob)・Armature(ボーン Hips → Spine。 + スキンメッシュ Body はアーマチュアの子として書き出す。Unity では Armature と兄弟)。 +- Animations/ + - Smile.anim: Face の blendShape.smile を 0 → 100(1 秒、接線 0)。 + - HatOff.anim: Hat の m_IsActive を 0(階段)。 + - DoorOpen.anim: Door のオイラー回転を (0, 0, 0) → (0, 90, 0)(1 秒)、Door/Knob の位置を (0.5, 1, 0)。ループする。 + - Wave.anim: ボーン Armature/Hips/Spine の回転(読み込まない。#270)と、Body の m_Enabled を 0。 + - Gesture.anim: Humanoid のマッスル値だけ(読み込まない)。 + - Spin.anim: ルート自身(空のパス)の回転だけ(どのオブジェクトのものか決められない)。 + - Elsewhere.anim: どこにも無いパス。 +- Scenes/Two.unity: Rig.fbx を X に -2 と 2 の 2 か所に置く(同じクリップが両方に付く)。 +""" + +from __future__ import annotations + +import sys +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 tempfile # noqa: E402 + +import bpy # noqa: E402 + +from tests.anim_writer import clip_yaml # noqa: E402 +from tests.make_synthetic_package import guid_of, model_meta, write_package # noqa: E402 +from tests.unity_yaml_writer import HEADER, ROOT_TRANSFORM, instance, mod # noqa: E402 + +INF = float("inf") +ZERO3 = (0, 0, 0) +ZERO4 = (0, 0, 0, 0) + + +def export_rig_fbx(path: Path) -> None: + bpy.ops.wm.read_factory_settings(use_empty=True) + # 表情のシェイプキーを持つ板 + bpy.ops.mesh.primitive_plane_add(size=0.5, location=(0, 0, 1.6)) + face = bpy.context.object + face.name = face.data.name = "Face" + face.shape_key_add(name="Basis") + smile = face.shape_key_add(name="smile") + for point in smile.data: + point.co.z += 0.1 + bpy.ops.mesh.primitive_cube_add(size=0.2, location=(0, 0, 1.9)) + hat = bpy.context.object + hat.name = hat.data.name = "Hat" + # 扉と、その子の取っ手 + bpy.ops.mesh.primitive_cube_add(size=1.0, location=(1.5, 0, 0.5)) + door = bpy.context.object + door.name = door.data.name = "Door" + bpy.ops.mesh.primitive_cube_add(size=0.1, location=(1.9, -0.5, 0.5)) + knob = bpy.context.object + knob.name = knob.data.name = "Knob" + knob.parent = door + knob.matrix_parent_inverse = door.matrix_world.inverted() + # アーマチュアとスキンメッシュ + bpy.ops.object.armature_add(location=(0, 0, 0)) + armature = bpy.context.object + armature.name = armature.data.name = "Armature" + bpy.ops.object.mode_set(mode="EDIT") + bones = armature.data.edit_bones + hips = bones[0] + hips.name = "Hips" + hips.head, hips.tail = (0, 0, 0.8), (0, 0, 1.0) + spine = bones.new("Spine") + spine.head, spine.tail, spine.parent = (0, 0, 1.0), (0, 0, 1.3), hips + bpy.ops.object.mode_set(mode="OBJECT") + bpy.ops.mesh.primitive_cube_add(size=0.4, location=(0, 0, 1.0)) + body = bpy.context.object + body.name = body.data.name = "Body" + group = body.vertex_groups.new(name="Spine") + group.add([v.index for v in body.data.vertices], 1.0, "REPLACE") + body.parent = armature + body.modifiers.new("Armature", "ARMATURE").object = armature + bpy.ops.export_scene.fbx(filepath=str(path), use_selection=False, add_leaf_bones=False) + + +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_anim.unitypackage" + entries: dict[str, tuple[str, bytes | None, str | None]] = {} + + def add(pathname: str, asset: bytes | None, meta: str | None) -> str: + guid = guid_of(pathname) + entries[guid] = (pathname, asset, meta) + return guid + + def clip(name: str, text: str) -> None: + path = f"Assets/Synthetic/Animations/{name}.anim" + add(path, text.encode(), f"fileFormatVersion: 2\nguid: {guid_of(path)}\nNativeFormatImporter:\n mainObjectFileID: 7400000\n") + + tmp = Path(tempfile.mkdtemp(prefix="synthetic_anim_")) + export_rig_fbx(tmp / "rig.fbx") + rig_path = "Assets/Synthetic/Models/Rig.fbx" + rig = add(rig_path, (tmp / "rig.fbx").read_bytes(), model_meta(guid_of(rig_path), {})) + + clip("Smile", clip_yaml("Smile", float_curves=[("Face", "blendShape.smile", 137, [(0, 0, 0, 0), (1, 100, 0, 0)])], stop_time=1)) + clip("HatOff", clip_yaml("HatOff", float_curves=[("Hat", "m_IsActive", 1, [(0, 0, INF, INF)])])) + clip("DoorOpen", clip_yaml( + "DoorOpen", + vector_curves={ + "m_EulerCurves": [("Door", [(0, ZERO3, ZERO3, ZERO3), (1, (0, 90, 0), ZERO3, ZERO3)])], + "m_PositionCurves": [("Door/Knob", [(0, (0.5, 1, 0), ZERO3, ZERO3)])], + }, + loop=True, + stop_time=1, + )) + clip("Wave", clip_yaml( + "Wave", + float_curves=[("Body", "m_Enabled", 137, [(0, 0, INF, INF)])], + vector_curves={"m_RotationCurves": [("Armature/Hips/Spine", [(0, (0, 0, 0, 1), ZERO4, ZERO4), (1, (0, 0.38268343, 0, 0.9238795), ZERO4, ZERO4)])]}, + stop_time=1, + )) + clip("Gesture", clip_yaml("Gesture", float_curves=[("", "LeftHand.Index.1 Stretched", 95, [(0, -1, 0, 0)]), ("", "RootT.y", 95, [(0, 1, 0, 0)])])) + clip("Spin", clip_yaml("Spin", vector_curves={"m_EulerCurves": [("", [(0, ZERO3, ZERO3, ZERO3), (2, (0, 360, 0), ZERO3, ZERO3)])]}, loop=True, stop_time=2)) + clip("Elsewhere", clip_yaml("Elsewhere", float_curves=[("Nothing/Here", "m_IsActive", 1, [(0, 0, INF, INF)])])) + + scene_path = "Assets/Synthetic/Scenes/Two.unity" + scene = HEADER + "".join([ + instance(100, rig, 0, [mod(ROOT_TRANSFORM, rig, "m_LocalPosition.x", -2)]), + instance(200, rig, 0, [mod(ROOT_TRANSFORM, rig, "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) + + +if __name__ == "__main__": + main() From a80293ea2350cb55b926005d99e47792d90f8837 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Mon, 23 Nov 2026 18:21:26 +0900 Subject: [PATCH 08/25] =?UTF-8?q?docs:=20=E3=82=A2=E3=83=8B=E3=83=A1?= =?UTF-8?q?=E3=83=BC=E3=82=B7=E3=83=A7=E3=83=B3=E3=82=AF=E3=83=AA=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=81=AE=E8=AA=AD=E3=81=BF=E8=BE=BC=E3=81=BF=E3=82=92?= =?UTF-8?q?=20README=E3=83=BBDESIGN.md=E3=83=BBCLAUDE.md=20=E3=81=AB?= =?UTF-8?q?=E6=9B=B8=E3=81=8F=EF=BC=88#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 読み込むもの・読み込まないものの記述と、オプション Animation Clips、対象の決め方・行列の対応・NLA の扱いを足す。 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +++-- DESIGN.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++++--- README.md | 24 ++++++++++++++++++++++-- README_ja.md | 23 +++++++++++++++++++++-- 4 files changed, 96 insertions(+), 9 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 519c0a7..b23eede 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,8 @@ - メッシュ(アーマチュア・シェイプキー込み)に、Unity 側のマテリアル設定とテクスチャを反映した状態で読み込む。 - Unity と Blender のマテリアルは 1:1 に対応しないので「参考にできる値だけ」を反映し、残りはカスタムプロパティに保存する。 -- シェーダー本体、C#、アニメーション、prefab 階層、Expression メニュー等は読み込まない。 +- シェーダー本体、C#、Humanoid のアニメーション・ボーンのカーブ・Animator Controller、Expression メニュー等は読み込まない。 + Generic な `.anim`(シェイプキー・表示の切り替え・オブジェクトの Transform)は、ミュートした NLA トラックの Action にする(`core/animation.py`。#209)。 ## 設計の要点(詳細は DESIGN.md) @@ -47,7 +48,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 / materials / nodes / textures / toon_group / outline) + blender/ bpy 依存(importer / options / log / prepare / model_import / session_materials / scene_placement / scene_objects / terrain / unity_meshes / animation / 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 cb1460a..47215cf 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -32,7 +32,7 @@ Blender から `.unitypackage` を直接読み込み、メッシュ(アーマ | FBX | 1 | Blender から書き出されたもの。テクスチャは **埋め込まれていない** | | .mat | 数個 | 全て **lilToon** 系シェーダー | | PNG | 数十枚 | メイン / ノーマル / MatCap / マスク。加えて Expression メニュー用アイコン(無関係) | -| .prefab / .controller / .anim / .asset | 多数 | 全て対象外 | +| .prefab / .controller / .anim / .asset | 多数 | 当初は全て対象外(prefab は後に配置を、Generic な .anim は #209 で Action を読むようにした) | ### 0.3 「どのメッシュにどのマテリアルが付くか」の情報源 @@ -313,9 +313,10 @@ Material: - メッシュ・アーマチュア・シェイプキー・UV・頂点カラー(FBX インポーターの能力の範囲)。 - マテリアル: `.mat` を解析し、**Blender で意味を持つ情報だけ**をノードに反映。 - テクスチャ: `.mat` から参照されている画像のみ展開して読み込む(オプションで全画像)。 +- アニメーションクリップ: Generic な `.anim` のシェイプキー・表示の切り替え・オブジェクトの Transform を、クリップごとの Action にしてミュートした NLA トラックに並べる(§4.7.1。#209)。 ### 読み込まない -- シェーダー本体(`.shader` `.cginc`)、C#(`.cs` `.dll`)、アニメーション(`.anim` `.controller`)、Expression/Parameter アセット、PhysBone 等の MonoBehaviour、prefab 階層(シーンを読み込む場合はモデルの配置と、その上の GameObject、ライト・カメラだけ再現する)、アイコン画像、`preview.png`。 +- シェーダー本体(`.shader` `.cginc`)、C#(`.cs` `.dll`)、Animator Controller(`.controller`)と Humanoid の `.anim`・ボーンのカーブ(§4.7.1)、Expression/Parameter アセット、PhysBone 等の MonoBehaviour、prefab 階層(シーンを読み込む場合はモデルの配置と、その上の GameObject、ライト・カメラだけ再現する)、アイコン画像、`preview.png`。 ### マテリアルの対応方針 Unity と 1:1 は不可能なので、**「Unity マテリアル → シェーダー非依存の中間表現(NormalizedMaterial)→ Blender ノード」** の 2 段変換にし、シェーダーごとの差は「プロファイル」に閉じ込める(§4.5)。 @@ -364,6 +365,7 @@ File > Import > Unitypackage (.unitypackage) .unitypackage を 3D View に | 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) | **Materials** | 項目 | 型 / 既定値 | 説明 | @@ -561,6 +563,7 @@ Base × Shadow Color と Base を係数で混ぜ、Shadow Strength で元に戻 - Objects / Materials / Textures の一覧 - 未解決マテリアル(.mat が見つからない)、パッケージに無いテクスチャ GUID、非対応シェーダー、読めない画像(統合した画像の無い PSD など) - 「Open extract folder」「Copy log」ボタン +- アニメーションクリップを Action にしたら、その数を要約と N パネルに出し、読まなかったクリップ・カーブの内訳はコンソール(`as_text`)に出す(§4.7.1) - 警告はインポートを止めず、可能なところまで進めて記録する。 ### 3.5 アドオン Preferences @@ -621,6 +624,8 @@ unitypackage_loader/ │ ├─ scene_import.py # シーンの読み込みの判定(隠す部品)と警告文 │ ├─ transform.py # Unity の Transform の行列と Unity → Blender の座標変換 │ ├─ model_space.py # 置いたモデルの行列(FBX の単位と軸 ModelUnits、ノードへの上書き、Renderer の位置。#263) +│ ├─ animation.py # AnimationClip(.anim)の読み取り、カーブの評価・ベジェのハンドル、オイラー角(#209) +│ ├─ animation_targets.py # クリップの階層パスを、読み込んだオブジェクトとボーンに結び付ける(#209) │ ├─ shader_source.py # パッケージ内の .shader / .shadergraph が宣言するプロパティ名(残りを外す。#118)と描画の既定(#202) │ ├─ shader_graph.py # .shadergraph のつながりから、テクスチャの UV の Tiling & Offset を読む(#193) │ ├─ decals.py # DecalProjector を投影の箱の中の板で近似する(#165) @@ -650,6 +655,7 @@ unitypackage_loader/ │ ├─ scene_placement.py # シーン 1 つの配置(SceneImport。モデル・組み込みメッシュ・Terrain・デカール・ライト・カメラ) │ ├─ terrain.py # Terrain のメッシュと塗り分けのマテリアル(SessionTerrains。#205) │ ├─ unity_meshes.py # Unity の Mesh アセットから作るメッシュ(SessionMeshes。#216) +│ ├─ animation.py # クリップの Action と NLA トラック(ClipImporter。#209) │ ├─ log.py # 捕まえて続けた例外のログ(Verbose Console Log はオペレーターが渡す) │ ├─ scene_objects.py # シーンの Empty・ライト・カメラ・複製・行列の当てはめ(計算は core/model_space.py)・非表示 │ ├─ materials.py # ノード生成 @@ -660,6 +666,7 @@ unitypackage_loader/ └─ tests/ ├─ test_*.py # unittest(bpy 不要) ├─ unity_yaml_writer.py # テストと合成パッケージの生成で使う、Unity の YAML を組み立てる関数 + ├─ anim_writer.py # 同じく AnimationClip(.anim)の YAML を組み立てる関数 ├─ make_synthetic_*.py # 合成パッケージの生成(Blender で実行) ├─ integration_import.py # blender -b --python で実行し、期待値 JSON と照合する ├─ integration_runs.json # 合成パッケージの生成スクリプトと、どのパッケージをどの期待値で回すかの一覧 @@ -1001,7 +1008,7 @@ 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`)。マテリアルの対応付けと組み立ては `SessionMaterials`(`session_materials.py`)、 +足りなかったテクスチャの補い(`fill_missed_textures`)→ アニメーションクリップ(`import_clips`。§4.7.1)。マテリアルの対応付けと組み立ては `SessionMaterials`(`session_materials.py`)、 モデルファイルの読み込みは `model_import.py` にある。以前は `importer.py` 1 つ(約 1,900 行)だったのを、役割ごとに分けた(#198)。 下の擬似コードは最初の設計で、流れを示すもの。 @@ -1051,6 +1058,46 @@ def run(ctx, filepath, opts) -> Report: `bpy.ops` のサブモジュールの `hasattr` はどんな名前でも True になり、C で定義されたオペレーターは `bpy.types` にも現れないので、オペレーターの有無はこの 2 つでは判定できない。 - Blender 4.x の `bpy.data.materials.new()` はノードツリーを持たない(5.0 以降は持つ)。こちらで作るマテリアル(スロット分割・アウトライン)は、組み立ての前に `use_nodes` を立てる。 +### 4.7.1 アニメーションクリップ(#209) + +パッケージの `.anim`(AnimationClip)を、読み込んだオブジェクトの Action にする。Animator Controller は読まない。 + +- **解析**(`core/animation.py`): `parse_clip` は YAML でもバイナリ(Force Binary)でも `load_documents` で読み、`m_PositionCurves` / + `m_RotationCurves` / `m_EulerCurves` / `m_ScaleCurves`(成分ごとの `Curve` に分ける)と `m_FloatCurves` のうち、シェイプキー + (classID 137 の `blendShape.*`)、GameObject の `m_IsActive`、Renderer の `m_Enabled` を返す。実行時のカーブが無いクリップは + `m_EditorCurves` を読む。Animator(classID 95)のパスの無いカーブで、マッスル値やルートの動き(`RootT.x`、`Left Arm Down-Up`、 + `LeftHand.Thumb.1 Stretched` など)の名前のものがあれば Humanoid とし、そのカーブは読まない(ほかのカーブは読む)。 + マテリアルのプロパティ・Animator のパラメーター・オブジェクト参照のカーブは数だけ数える。壊れた入力には `AnimationParseError`(ValueError)だけを送る。 +- **評価**: キーの間はエルミート(weighted のキーは重みの長さのハンドルの 3 次ベジェ)、接線が無限大の区間は前のキーの値のまま。 + `bezier_handles` はエルミートの接線を 1/3 の長さのハンドルにして Blender のベジェにする(同じ曲線になる)。 + オイラー角は Unity の `m_RotationOrder`(既定 4 = ZXY。Z → X → Y の順に回す。`Quaternion.Euler` と同じ)でクォータニオンにする。 +- **対象の決め方**(`core/animation_targets.py`): クリップは Animator を付けた GameObject からの相対パスしか持たないので、読み込んだ階層 + (パッケージのコレクションの全オブジェクト)で、パスがいちばん多く解決できるオブジェクトをルートとみなす。Models 単位のように + ルートのオブジェクトが無いときは、コレクションごとの最上位のオブジェクトの集まりをルートの候補にする。解決できたパスが半分に満たなければ付けない。 + 同じだけ解決できるルートはすべて対象にする(シーンに同じモデルを複数置いたとき)。ただし別のルートの子孫は外す(prefab の GameObject と、その下に置いた + FBX の同じ名前のノードを、両方動かさない。Super Cub の prefab で見つけた)。名前は完全一致 → 連番を外した形が 1 つだけの順で引き、 + Blender の FBX インポーターがアーマチュアの子にしたスキンメッシュは、Unity と同じくアーマチュアの親の子としても引く。アーマチュアの下はボーン名でたどる。 + 読み込み側が足した Empty(FBX のルートなど)で一致しなければ、Empty の子を 1 段だけ探す。空のパス(ルート自身)だけのクリップは、 + どのオブジェクトのものか決められないので付けない(Medieval Village の風車など。Animator Controller から引けば決められるが、今は読まない)。 +- **Action と NLA**(`blender/animation.py`): クリップごとに Action を 1 つ作り(`unity_clip_guid` / `unity_clip_path`)、対象のデータブロック + (オブジェクトかシェイプキーの Key)ごとにスロットを作る(Blender 4.4 以降のスロット付き Action)。対象ごとにクリップの名前の NLA トラックを + ミュートで足すので、読み込んだ直後の見た目は変わらない。キーはクリップの開始からの秒 × シーンのフレームレートで、ストリップはシーンの開始フレームに置く。 + ループするクリップ(`m_LoopTime`)の F カーブには Cycles モディファイアーを付ける。 + - シェイプキー: 値を 1/100 にしてキーと接線をそのままベジェにする。100 を超える重みは `slider_max` を広げる。 + - 表示: `hide_viewport` / `hide_render` を階段(CONSTANT)で、値が 0.5 未満なら隠す。`m_IsActive` は Unity の階層での子孫にも当てる + (スキンメッシュはアーマチュアの子孫にしない)。 + - Transform: 時刻ごと(フレームごとと、キーの時刻)に Unity のローカルの値を求め、`core/model_space.local_basis` でオブジェクトの行列にして、 + 位置・回転(オブジェクトの回転モード。オイラー角は前のフレームに近い値)・スケールの LINEAR のキーにする。行列の対応 basis = left·L·right は、 + FBX の最上位のノード(親が配置の Empty か無し)が C·L·A(`node_basis` と同じ)、親も同じモデルの FBX のノードなら A⁻¹·L·A(親子とも C·W·A のため)、 + シーン・prefab の GameObject の Empty と Unity の Mesh・組み込みメッシュのオブジェクトが C·L·C⁻¹。A はモデルの `ModelUnits.basis_a` で、 + オブジェクトに残した元のモデルの GUID(`unity_model_guid`)から引く。スキンメッシュ・ボーンの子・ライト・カメラ・Terrain・デカールは + Unity と親子や形が違うので当てずに数える。アニメーションしない成分は元の値(オイラー角は元の回転を同じ順のオイラー角にした値)を使う。 + - ボーンのカーブは読み込まない(#270。FBX インポーターがボーンの軸を付け替えるので、レスト姿勢の差の補正が要る)。 +- **レポート**: 読み込んだクリップの数を要約に、読まなかったものの内訳(Humanoid、ボーンだけ、ルートだけ、当てはまらない、対象が無いカーブ)を + `clip_notes` に出す(警告にはしない)。 +- Python から `NlaTrack.mute` を切り替えても依存関係は組み直されず、一度評価したトラックは切り替わらない(NLA エディターでの切り替えでは組み直される)。 + 統合テストはコレクションを付け外しして組み直させてから値を確かめる。 + ### 4.8 `blender/textures.py` - `bpy.data.images.load(path, check_existing=True)`。 diff --git a/README.md b/README.md index 09819ed..a0712e9 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ 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), and referenced textures -- What is not imported: shader source code, C# scripts, animations, Expression menus, etc. Prefab hierarchies, lights and cameras are reproduced only when a scene is imported. +- 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 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. ## Installation @@ -78,6 +78,7 @@ The options show Material Mode and Scale; everything else is folded into the Mod | | 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) | | | 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 | @@ -167,6 +168,25 @@ To stay within the Windows path length limit, files whose full path would be too `_long/` in the destination. If the destination folder itself is too long, the import stops with an error; in that case set Textures > Extract To to `Custom Path` and choose a short folder such as `C:\upi`. +### Animation 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) +- GameObject active state (`m_IsActive`) and Renderer `m_Enabled` → `hide_viewport` / `hide_render` (deactivating a GameObject also hides its children) +- Transform position, rotation (quaternion or Euler) and scale → the object's location, rotation and scale, sampled every frame + +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. +Looping clips get a Cycles modifier on their F-curves. + +Not imported (the report lists how many were skipped): Humanoid clips (muscle curves; only their other curves are read), +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. + ### Security notes - **Bundled .blend files are not imported by default.** A `.blend` can carry Python code (driver expressions, diff --git a/README_ja.md b/README_ja.md index e5c6e2f..eee9951 100644 --- a/README_ja.md +++ b/README_ja.md @@ -6,8 +6,8 @@ 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 向け)シェーダー、その他は一般規則で最善努力)、参照テクスチャ -- 読み込まないもの: シェーダー本体、C#、アニメーション、Expression メニュー等。prefab の階層、ライト、カメラは、シーンを読み込むときだけ再現します +- 読み込むもの: 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 にする) +- 読み込まないもの: シェーダー本体、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` からマテリアルを組み直します。 ## インストール @@ -76,6 +76,7 @@ Settings > Pages > Source を "GitHub Actions" にしてください。 | | Scale | モデルのインポーターに渡すスケール | | Model | FBX Importer | 新 C++ インポーター優先(`Auto`)/ 明示指定 | | | Import Animation / Ignore Leaf Bones | FBX インポーターに渡す(既定はそれぞれ OFF / ON) | +| | Animation Clips | パッケージの Generic な `.anim` を、ミュートした NLA トラックの Action にする(既定 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 設定を無視する | @@ -149,6 +150,24 @@ prefab のルートをその Collection の原点に置きます。 Windows のパスの長さの上限に当たらないよう、フルパスが長くなるファイルは展開先の `_long/` の下の短いフォルダに置きます。 展開先のフォルダ自体が長すぎるとエラーになるので、その場合は Textures の Extract To を `Custom Path` にして `C:\upi` のような短いフォルダを選んでください。 +### アニメーションクリップ + +パッケージの Generic なアニメーションクリップ(`.anim`)を、クリップごとに 1 つの Action にします。読むカーブは次のとおりです。 + +- シェイプキーの重み(`blendShape.<名前>`。Unity では 0〜100)→ シェイプキーの値(0〜1) +- GameObject のアクティブ(`m_IsActive`)と Renderer の `m_Enabled` → `hide_viewport` / `hide_render`(GameObject を非アクティブにすると子も隠れる) +- Transform の位置・回転(クォータニオンかオイラー角)・スケール → オブジェクトの位置・回転・スケール(フレームごとに求める) + +クリップは対象のモデルを持たないので、カーブの階層パスがいちばん多く当てはまる読み込んだオブジェクトを、クリップを再生する +オブジェクトとみなします(同じモデルを複数置いていれば、すべてに付けます)。動かすオブジェクトとシェイプキーごとに、 +クリップの名前の NLA トラックを**ミュート**で足すので、読み込んだ直後の見た目は変わりません。確かめるときは NLA エディターで +トラックのミュートを外すか、星のアイコンでソロにします。ストリップを選んで Tab で Action を編集することもできます。 +キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップの F カーブには Cycles モディファイアーを付けます。 + +読み込まないもの(件数はレポートに出ます): Humanoid のクリップ(マッスル値。ほかのカーブは読みます)、ボーンのカーブ、 +再生するオブジェクト自身だけを動かすクリップ(パスが無く、どのオブジェクトか決められない)、マテリアルやオブジェクト参照のカーブ。 +読み込んだオブジェクトにパスが当てはまらないクリップも外します。Animator Controller は読みません。 + ### セキュリティ上の注意 - **同梱 .blend は既定では読み込みません。** `.blend` には Python コード(ドライバー式、登録済みテキストブロック)を From 10f4704c658a5739518eddf933761ec7ef9011c5 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 00:24:24 +0900 Subject: [PATCH 09/25] =?UTF-8?q?feat:=20=E7=8A=B6=E6=85=8B=E3=82=92?= =?UTF-8?q?=E5=88=87=E3=82=8A=E6=9B=BF=E3=81=88=E3=82=8B=E3=81=A0=E3=81=91?= =?UTF-8?q?=E3=81=AE=E3=82=A2=E3=83=8B=E3=83=A1=E3=83=BC=E3=82=B7=E3=83=A7?= =?UTF-8?q?=E3=83=B3=E3=82=AF=E3=83=AA=E3=83=83=E3=83=97=E3=82=92=E8=AA=AD?= =?UTF-8?q?=E3=81=BF=E8=BE=BC=E3=81=BE=E3=81=AA=E3=81=84=EF=BC=88#209?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 値が変わらないか、0.1 秒以下で終わるクリップを外す。Animator のステートで使う前提のクリップで、 動きは遷移が作るため、Blender で再生しても意味が無い。Super Cub の 20 個(ハンドルの角度・ウインカーなど。1/12 秒)と Yumeka の 53 個(衣装の切り替え・表情)がこれにあたる。外した数はレポートに出す。読み込むオプションは設けない。 値が同じキーでも、間の接線が 0 か無限大でなければ途中で膨らむので、変わるカーブとして扱う。 合成パッケージは、状態のクリップ DoorAjar・Blink を足し、HatOff・Elsewhere を値の変わるクリップにした。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_anim.json | 4 +- tests/expectations_synthetic_anim_scene.json | 2 +- tests/make_synthetic_anim_package.py | 12 ++++-- tests/test_animation.py | 28 ++++++++++++++ unitypackage_loader/blender/animation.py | 7 ++++ unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/animation.py | 40 ++++++++++++++++++++ 7 files changed, 88 insertions(+), 7 deletions(-) diff --git a/tests/expectations_synthetic_anim.json b/tests/expectations_synthetic_anim.json index aad115d..7e3c6ce 100644 --- a/tests/expectations_synthetic_anim.json +++ b/tests/expectations_synthetic_anim.json @@ -10,6 +10,7 @@ "count": 4, "actions": ["DoorOpen", "HatOff", "Smile", "Wave"], "notes_contain": [ + "skipped 2 animation clip(s) that only switch a state", "skipped 1 Humanoid animation clip", "skipped 1 animation clip(s) that only animate the object", "skipped 4 animation curve(s) targeting bones", @@ -27,7 +28,8 @@ { "track": "Smile", "object": "Face", "seconds": 0, "shape_key": "smile", "value": 0.0 }, { "track": "Smile", "object": "Face", "seconds": 0.5, "shape_key": "smile", "value": 0.5 }, { "track": "Smile", "object": "Face", "seconds": 1, "shape_key": "smile", "value": 1.0 }, - { "track": "HatOff", "object": "Hat", "seconds": 0, "hidden": true }, + { "track": "HatOff", "object": "Hat", "seconds": 0, "hidden": false }, + { "track": "HatOff", "object": "Hat", "seconds": 0.75, "hidden": true }, { "track": "Wave", "object": "Body", "seconds": 0, "hidden": true }, { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 1, "axis": [0, 0, 1], "degrees": -90 } }, { "track": "DoorOpen", "object": "Knob", "seconds": 0, "distance_to": "Door", "distance": 111.8034 } diff --git a/tests/expectations_synthetic_anim_scene.json b/tests/expectations_synthetic_anim_scene.json index 469bbdf..b963d1a 100644 --- a/tests/expectations_synthetic_anim_scene.json +++ b/tests/expectations_synthetic_anim_scene.json @@ -47,7 +47,7 @@ { "track": "HatOff", "object": "Hat", - "seconds": 0, + "seconds": 0.75, "hidden": true }, { diff --git a/tests/make_synthetic_anim_package.py b/tests/make_synthetic_anim_package.py index 727fa20..d2ac179 100644 --- a/tests/make_synthetic_anim_package.py +++ b/tests/make_synthetic_anim_package.py @@ -8,12 +8,14 @@ スキンメッシュ Body はアーマチュアの子として書き出す。Unity では Armature と兄弟)。 - Animations/ - Smile.anim: Face の blendShape.smile を 0 → 100(1 秒、接線 0)。 - - HatOff.anim: Hat の m_IsActive を 0(階段)。 + - HatOff.anim: Hat の m_IsActive を 0.5 秒で 1 → 0(階段。1 秒)。 - DoorOpen.anim: Door のオイラー回転を (0, 0, 0) → (0, 90, 0)(1 秒)、Door/Knob の位置を (0.5, 1, 0)。ループする。 - Wave.anim: ボーン Armature/Hips/Spine の回転(読み込まない。#270)と、Body の m_Enabled を 0。 - Gesture.anim: Humanoid のマッスル値だけ(読み込まない)。 - Spin.anim: ルート自身(空のパス)の回転だけ(どのオブジェクトのものか決められない)。 - - Elsewhere.anim: どこにも無いパス。 + - Elsewhere.anim: どこにも無いパス(1 秒で値が変わる)。 + - DoorAjar.anim / Blink.anim: 状態を切り替えるだけのクリップ(読み込まない)。DoorAjar は Door の回転を (0, 45, 0) に置くだけ、 + Blink は smile を 1/12 秒で 0 → 100。 - Scenes/Two.unity: Rig.fbx を X に -2 と 2 の 2 か所に置く(同じクリップが両方に付く)。 """ @@ -103,7 +105,7 @@ def clip(name: str, text: str) -> None: rig = add(rig_path, (tmp / "rig.fbx").read_bytes(), model_meta(guid_of(rig_path), {})) clip("Smile", clip_yaml("Smile", float_curves=[("Face", "blendShape.smile", 137, [(0, 0, 0, 0), (1, 100, 0, 0)])], stop_time=1)) - clip("HatOff", clip_yaml("HatOff", float_curves=[("Hat", "m_IsActive", 1, [(0, 0, INF, INF)])])) + clip("HatOff", clip_yaml("HatOff", float_curves=[("Hat", "m_IsActive", 1, [(0, 1, INF, INF), (0.5, 0, INF, INF), (1, 0, INF, INF)])], stop_time=1)) clip("DoorOpen", clip_yaml( "DoorOpen", vector_curves={ @@ -121,7 +123,9 @@ def clip(name: str, text: str) -> None: )) clip("Gesture", clip_yaml("Gesture", float_curves=[("", "LeftHand.Index.1 Stretched", 95, [(0, -1, 0, 0)]), ("", "RootT.y", 95, [(0, 1, 0, 0)])])) clip("Spin", clip_yaml("Spin", vector_curves={"m_EulerCurves": [("", [(0, ZERO3, ZERO3, ZERO3), (2, (0, 360, 0), ZERO3, ZERO3)])]}, loop=True, stop_time=2)) - clip("Elsewhere", clip_yaml("Elsewhere", float_curves=[("Nothing/Here", "m_IsActive", 1, [(0, 0, INF, INF)])])) + clip("Elsewhere", clip_yaml("Elsewhere", float_curves=[("Nothing/Here", "m_IsActive", 1, [(0, 1, INF, INF), (1, 0, INF, INF)])], stop_time=1)) + clip("DoorAjar", clip_yaml("DoorAjar", vector_curves={"m_EulerCurves": [("Door", [(0, (0, 45, 0), ZERO3, ZERO3), (1 / 12, (0, 45, 0), ZERO3, ZERO3)])]}, stop_time=1 / 12)) + clip("Blink", clip_yaml("Blink", float_curves=[("Face", "blendShape.smile", 137, [(0, 0, 0, 0), (1 / 12, 100, 0, 0)])], stop_time=1 / 12)) scene_path = "Assets/Synthetic/Scenes/Two.unity" scene = HEADER + "".join([ diff --git a/tests/test_animation.py b/tests/test_animation.py index 36768fd..1e9b6f0 100644 --- a/tests/test_animation.py +++ b/tests/test_animation.py @@ -17,6 +17,7 @@ bezier_handles, euler_to_quaternion, evaluate, + is_state_clip, parse_clip, quaternion_to_euler, sample_times, @@ -138,6 +139,33 @@ def test_bad_values_are_ignored(self): self.assertEqual([(k.time, k.value) for k in clip.curves[0].keys], [(0.0, 0.0)]) +class StateClipTest(unittest.TestCase): + """Animator のステート用の、状態を切り替えるだけのクリップ(読み込まない)。""" + + def _clip(self, keys, attribute="blendShape.a"): + return parse_clip(clip_yaml("C", float_curves=[("Body", attribute, 137, keys)], stop_time=1)) + + def test_single_key_and_constant_values(self): + self.assertTrue(is_state_clip(self._clip([(0, 50, 0, 0)]))) + self.assertTrue(is_state_clip(self._clip([(0, 50, 0, 0), (1, 50, 0, 0)]))) + self.assertTrue(is_state_clip(self._clip([(0, 1, INF, INF), (2, 1, INF, INF)], "m_Enabled"))) + + def test_short_clip_is_state_even_if_values_change(self): + # 1/12 秒で 0 → 15°(車両のペダルの角度など) + clip = parse_clip(clip_yaml("Pedal", vector_curves={"m_EulerCurves": [("Pedal", [(0, (0, 0, 0), (0, 0, 0), (0, 0, 0)), (1 / 12, (15, 0, 0), (0, 0, 0), (0, 0, 0))])]})) + self.assertTrue(is_state_clip(clip)) + self.assertTrue(is_state_clip(self._clip([(0, 0, 0, 0), (0.1, 100, 0, 0)]))) + + def test_motion(self): + self.assertFalse(is_state_clip(self._clip([(0, 0, 0, 0), (1, 100, 0, 0)]))) + self.assertFalse(is_state_clip(self._clip([(0, 1, INF, INF), (0.5, 0, INF, INF)], "m_Enabled"))) + # 値は同じでも、接線があれば途中で膨らむ + self.assertFalse(is_state_clip(self._clip([(0, 0, 0, 100), (1, 0, 0, 0)]))) + + def test_no_curves(self): + self.assertFalse(is_state_clip(parse_clip(clip_yaml("Empty")))) + + class EvaluateTest(unittest.TestCase): def test_hermite(self): keys = [Key(0, 0, 0, 0), Key(1, 1, 0, 0)] diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 1984607..991c3a9 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -26,6 +26,7 @@ AnimationClip, Curve, bezier_handles, + is_state_clip, parse_clip, sample_times, transform_spec, @@ -47,6 +48,7 @@ class ClipStats: """クリップの読み込みの集計(レポートに書く)。""" loaded: list[str] = field(default_factory=list) # 読み込んだクリップの pathname + state: list[str] = field(default_factory=list) # 状態を切り替えるだけのクリップ(読み込まない) humanoid: list[str] = field(default_factory=list) # Humanoid だけのクリップ(読み込まない) humanoid_partial: list[str] = field(default_factory=list) # Humanoid のクリップのうち、マッスル値以外のカーブだけ読んだもの root_only: list[str] = field(default_factory=list) # ルート自身だけを動かすクリップ(どのオブジェクトのものか決められない) @@ -112,6 +114,9 @@ def run(self) -> ClipStats: if not clip.curves: (self.stats.humanoid if clip.humanoid else self.stats.empty).append(entry.pathname) continue + if is_state_clip(clip): + self.stats.state.append(entry.pathname) + continue if clip.paths == {""}: self.stats.root_only.append(entry.pathname) continue @@ -343,6 +348,8 @@ def _escape(name: str) -> str: def report_lines(stats: ClipStats) -> Iterable[str]: """レポートの警告に足す行(読み込まなかったものの内訳)。""" + if stats.state: + yield f"skipped {len(stats.state)} animation clip(s) that only switch a state (constant values or 0.1 s or shorter)" if stats.humanoid: yield f"skipped {len(stats.humanoid)} Humanoid animation clip(s) (muscle curves are not supported)" if stats.humanoid_partial: diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 2e416ff..4d5fbac 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.6" +version = "1.18.0-dev.7" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/animation.py b/unitypackage_loader/core/animation.py index 781af06..2311a20 100644 --- a/unitypackage_loader/core/animation.py +++ b/unitypackage_loader/core/animation.py @@ -13,6 +13,10 @@ カーブの評価は Unity の AnimationCurve と同じく、キーの間をエルミート(weighted のキーは 3 次ベジェ)でつなぎ、 接線が無限大の区間は前のキーの値のまま(階段)にする。 +Animator のステートで使う前提の「状態を切り替えるだけ」のクリップ(値が一定か、0.1 秒以下で終わるもの。 +VRChat のアバターの衣装の切り替えや表情、車両のハンドルの角度など)は、Blender で再生しても意味が無いので +``is_state_clip`` で見分けて読み込まない。 + 解析は Unity YAML でもバイナリ(Force Binary)でも ``unity_binary.load_documents`` で ``UnityDocument`` にしてから行う。 壊れた入力には ``AnimationParseError``(``ValueError``)だけを送出する。 """ @@ -41,6 +45,7 @@ "KIND_SCALE", "TRANSFORM_KINDS", "parse_clip", + "is_state_clip", "evaluate", "bezier_handles", "euler_to_quaternion", @@ -369,6 +374,41 @@ def parse_clip(data: bytes | str) -> AnimationClip: raise AnimationParseError("no AnimationClip in the asset") +# --------------------------------------------------------------------------- +# 状態を切り替えるだけのクリップ +# --------------------------------------------------------------------------- + +# これ以下の長さで終わるクリップは、動きではなく状態(Unity の 60fps で 6 フレーム。よくある 1/12 秒・0.1 秒を含む) +STATE_CLIP_MAX_LENGTH = 0.1 + 1e-6 + + +def _flat_slope(slope: float) -> bool: + return slope == 0.0 or math.isinf(slope) + + +def _curve_constant(keys: Sequence[Key]) -> bool: + """値が時間で変わらないカーブ。キーの値がすべて同じで、キーの間の接線が 0 か無限大(階段)のもの。""" + if len(keys) <= 1: + return True + first = keys[0].value + if any(k.value != first for k in keys): + return False + return all(_flat_slope(k0.out_slope) and _flat_slope(k1.in_slope) for k0, k1 in zip(keys, keys[1:])) + + +def is_state_clip(clip: AnimationClip) -> bool: + """Animator のステートで使う前提の、状態を切り替えるだけのクリップか。 + + どのカーブも値が変わらないか、キーのある範囲が ``STATE_CLIP_MAX_LENGTH`` 以下のもの。カーブが無いクリップは False。 + """ + if not clip.curves: + return False + if all(_curve_constant(c.keys) for c in clip.curves): + return True + times = [k.time for c in clip.curves for k in c.keys] + return max(times) - min(times) <= STATE_CLIP_MAX_LENGTH + + # --------------------------------------------------------------------------- # 評価と、ベジェのハンドル # --------------------------------------------------------------------------- From 4d45cec12fce1f5751b1b6a8ba45e6055d9577ff Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 00:24:24 +0900 Subject: [PATCH 10/25] =?UTF-8?q?docs:=20=E7=8A=B6=E6=85=8B=E3=82=92?= =?UTF-8?q?=E5=88=87=E3=82=8A=E6=9B=BF=E3=81=88=E3=82=8B=E3=81=A0=E3=81=91?= =?UTF-8?q?=E3=81=AE=E3=82=AF=E3=83=AA=E3=83=83=E3=83=97=E3=82=92=E8=AA=AD?= =?UTF-8?q?=E3=81=BF=E8=BE=BC=E3=81=BE=E3=81=AA=E3=81=84=E3=81=93=E3=81=A8?= =?UTF-8?q?=E3=82=92=E6=9B=B8=E3=81=8F=EF=BC=88#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + DESIGN.md | 6 +++++- README.md | 6 +++++- README_ja.md | 6 +++++- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b23eede..661e320 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,6 +10,7 @@ - Unity と Blender のマテリアルは 1:1 に対応しないので「参考にできる値だけ」を反映し、残りはカスタムプロパティに保存する。 - シェーダー本体、C#、Humanoid のアニメーション・ボーンのカーブ・Animator Controller、Expression メニュー等は読み込まない。 Generic な `.anim`(シェイプキー・表示の切り替え・オブジェクトの Transform)は、ミュートした NLA トラックの Action にする(`core/animation.py`。#209)。 + 値が変わらないか 0.1 秒以下で終わる、状態を切り替えるだけのクリップ(Animator のステート用)は読み込まない。 ## 設計の要点(詳細は DESIGN.md) diff --git a/DESIGN.md b/DESIGN.md index 47215cf..9eef48f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1071,6 +1071,10 @@ def run(ctx, filepath, opts) -> Report: - **評価**: キーの間はエルミート(weighted のキーは重みの長さのハンドルの 3 次ベジェ)、接線が無限大の区間は前のキーの値のまま。 `bezier_handles` はエルミートの接線を 1/3 の長さのハンドルにして Blender のベジェにする(同じ曲線になる)。 オイラー角は Unity の `m_RotationOrder`(既定 4 = ZXY。Z → X → Y の順に回す。`Quaternion.Euler` と同じ)でクォータニオンにする。 +- **状態のクリップ**: `is_state_clip` は、どのカーブも値が変わらない(キーの値が同じで、キーの間の接線が 0 か無限大)か、 + キーのある範囲が 0.1 秒以下のクリップを、状態を切り替えるだけのものとして外す。Animator のステートで使う前提のクリップで、動きは遷移が作るため + Blender では再生しても意味が無い。手元では Yumeka の 54 個のうち 53 個(衣装の切り替え・表情)と、Super Cub の 20 個すべて(ハンドルの角度、 + ウインカーの点灯など。1/12 秒)がこれにあたった。読み込むオプションは設けない(ユーザーの判断)。 - **対象の決め方**(`core/animation_targets.py`): クリップは Animator を付けた GameObject からの相対パスしか持たないので、読み込んだ階層 (パッケージのコレクションの全オブジェクト)で、パスがいちばん多く解決できるオブジェクトをルートとみなす。Models 単位のように ルートのオブジェクトが無いときは、コレクションごとの最上位のオブジェクトの集まりをルートの候補にする。解決できたパスが半分に満たなければ付けない。 @@ -1093,7 +1097,7 @@ def run(ctx, filepath, opts) -> Report: オブジェクトに残した元のモデルの GUID(`unity_model_guid`)から引く。スキンメッシュ・ボーンの子・ライト・カメラ・Terrain・デカールは Unity と親子や形が違うので当てずに数える。アニメーションしない成分は元の値(オイラー角は元の回転を同じ順のオイラー角にした値)を使う。 - ボーンのカーブは読み込まない(#270。FBX インポーターがボーンの軸を付け替えるので、レスト姿勢の差の補正が要る)。 -- **レポート**: 読み込んだクリップの数を要約に、読まなかったものの内訳(Humanoid、ボーンだけ、ルートだけ、当てはまらない、対象が無いカーブ)を +- **レポート**: 読み込んだクリップの数を要約に、読まなかったものの内訳(状態のクリップ、Humanoid、ボーンだけ、ルートだけ、当てはまらない、対象が無いカーブ)を `clip_notes` に出す(警告にはしない)。 - Python から `NlaTrack.mute` を切り替えても依存関係は組み直されず、一度評価したトラックは切り替わらない(NLA エディターでの切り替えでは組み直される)。 統合テストはコレクションを付け外しして組み直させてから値を確かめる。 diff --git a/README.md b/README.md index a0712e9..40d4391 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,11 @@ scene looks the same right after the import. To preview a clip, unmute its track 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. Looping clips get a Cycles modifier on their F-curves. -Not imported (the report lists how many were skipped): Humanoid clips (muscle curves; only their other curves are read), +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 (muscle curves; only their other curves are read), 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 eee9951..6fdb369 100644 --- a/README_ja.md +++ b/README_ja.md @@ -164,7 +164,11 @@ Windows のパスの長さの上限に当たらないよう、フルパスが長 トラックのミュートを外すか、星のアイコンでソロにします。ストリップを選んで Tab で Action を編集することもできます。 キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップの F カーブには Cycles モディファイアーを付けます。 -読み込まないもの(件数はレポートに出ます): Humanoid のクリップ(マッスル値。ほかのカーブは読みます)、ボーンのカーブ、 +状態を切り替えるだけのクリップ(値が変わらないもの、0.1 秒以下で終わるもの)は読み込みません。Unity の Animator はこうしたクリップを +ステートとして使い、動きは遷移で作ります(VRChat のアバターの衣装の切り替えや表情、車両のハンドルの角度など)。 +Blender では再生しても何も動かないためです。 + +読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(マッスル値。ほかのカーブは読みます)、ボーンのカーブ、 再生するオブジェクト自身だけを動かすクリップ(パスが無く、どのオブジェクトか決められない)、マテリアルやオブジェクト参照のカーブ。 読み込んだオブジェクトにパスが当てはまらないクリップも外します。Animator Controller は読みません。 From 5111e3dd44143c708dd50ef0fd8ae506922ba5e3 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 00:49:59 +0900 Subject: [PATCH 11/25] =?UTF-8?q?feat:=20Humanoid=20=E3=81=AE=E3=82=A2?= =?UTF-8?q?=E3=83=8B=E3=83=A1=E3=83=BC=E3=82=B7=E3=83=A7=E3=83=B3=E3=82=AF?= =?UTF-8?q?=E3=83=AA=E3=83=83=E3=83=97=E3=81=AF=E3=82=AF=E3=83=AA=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=81=94=E3=81=A8=E8=AA=AD=E3=81=BF=E8=BE=BC=E3=81=BE?= =?UTF-8?q?=E3=81=AA=E3=81=84=EF=BC=88#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit これまでは Humanoid のクリップでも、マッスル値以外のカーブは読んでいた。しかし体の動きはマッスル値にあり、残りは 補助のボーン(ひねりのボーンなど)の、キーが 1〜2 個の動かないカーブだけだった。Everyday Motion Pack では、 それだけを読んだ動かないトラックが 141 クリップ分並び、状態のクリップと見分けがつかなかった。 元のモーションは `@` 付きの FBX のテイクにあるので、FBX から取り出す方(#276)で扱う。 合成パッケージに、マッスル値とシェイプキーを持つ Humanoid のクリップ Fist を足し、付かないことを確かめる。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_anim.json | 2 +- tests/make_synthetic_anim_package.py | 2 ++ unitypackage_loader/blender/animation.py | 13 ++++++------- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/animation.py | 3 ++- 5 files changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/expectations_synthetic_anim.json b/tests/expectations_synthetic_anim.json index 7e3c6ce..acd68f0 100644 --- a/tests/expectations_synthetic_anim.json +++ b/tests/expectations_synthetic_anim.json @@ -11,7 +11,7 @@ "actions": ["DoorOpen", "HatOff", "Smile", "Wave"], "notes_contain": [ "skipped 2 animation clip(s) that only switch a state", - "skipped 1 Humanoid animation clip", + "skipped 2 Humanoid animation clip", "skipped 1 animation clip(s) that only animate the object", "skipped 4 animation curve(s) targeting bones", "1 animation clip(s) did not match" diff --git a/tests/make_synthetic_anim_package.py b/tests/make_synthetic_anim_package.py index d2ac179..7bb0ed7 100644 --- a/tests/make_synthetic_anim_package.py +++ b/tests/make_synthetic_anim_package.py @@ -12,6 +12,7 @@ - DoorOpen.anim: Door のオイラー回転を (0, 0, 0) → (0, 90, 0)(1 秒)、Door/Knob の位置を (0.5, 1, 0)。ループする。 - Wave.anim: ボーン Armature/Hips/Spine の回転(読み込まない。#270)と、Body の m_Enabled を 0。 - Gesture.anim: Humanoid のマッスル値だけ(読み込まない)。 + - Fist.anim: Humanoid のマッスル値と、Face のシェイプキー(値が変わる)。Humanoid なのでクリップごと読み込まない。 - Spin.anim: ルート自身(空のパス)の回転だけ(どのオブジェクトのものか決められない)。 - Elsewhere.anim: どこにも無いパス(1 秒で値が変わる)。 - DoorAjar.anim / Blink.anim: 状態を切り替えるだけのクリップ(読み込まない)。DoorAjar は Door の回転を (0, 45, 0) に置くだけ、 @@ -122,6 +123,7 @@ def clip(name: str, text: str) -> None: stop_time=1, )) clip("Gesture", clip_yaml("Gesture", float_curves=[("", "LeftHand.Index.1 Stretched", 95, [(0, -1, 0, 0)]), ("", "RootT.y", 95, [(0, 1, 0, 0)])])) + clip("Fist", clip_yaml("Fist", float_curves=[("", "Left Arm Down-Up", 95, [(0, 0, 0, 0), (1, 1, 0, 0)]), ("Face", "blendShape.smile", 137, [(0, 0, 0, 0), (1, 100, 0, 0)])], stop_time=1)) clip("Spin", clip_yaml("Spin", vector_curves={"m_EulerCurves": [("", [(0, ZERO3, ZERO3, ZERO3), (2, (0, 360, 0), ZERO3, ZERO3)])]}, loop=True, stop_time=2)) clip("Elsewhere", clip_yaml("Elsewhere", float_curves=[("Nothing/Here", "m_IsActive", 1, [(0, 1, INF, INF), (1, 0, INF, INF)])], stop_time=1)) clip("DoorAjar", clip_yaml("DoorAjar", vector_curves={"m_EulerCurves": [("Door", [(0, (0, 45, 0), ZERO3, ZERO3), (1 / 12, (0, 45, 0), ZERO3, ZERO3)])]}, stop_time=1 / 12)) diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 991c3a9..2505f5f 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -49,8 +49,7 @@ class ClipStats: loaded: list[str] = field(default_factory=list) # 読み込んだクリップの pathname state: list[str] = field(default_factory=list) # 状態を切り替えるだけのクリップ(読み込まない) - humanoid: list[str] = field(default_factory=list) # Humanoid だけのクリップ(読み込まない) - humanoid_partial: list[str] = field(default_factory=list) # Humanoid のクリップのうち、マッスル値以外のカーブだけ読んだもの + humanoid: list[str] = field(default_factory=list) # Humanoid のクリップ(マッスル値以外のカーブがあっても読み込まない) root_only: list[str] = field(default_factory=list) # ルート自身だけを動かすクリップ(どのオブジェクトのものか決められない) unbound: list[str] = field(default_factory=list) # 対象のオブジェクトが見つからなかったクリップ empty: list[str] = field(default_factory=list) # 読み込める種類のカーブが無いクリップ @@ -111,8 +110,12 @@ def run(self) -> ClipStats: except Exception as exc: # noqa: BLE001 - そのクリップだけを外して続ける warn_skipped(self.report.warn, f"could not read animation clip {entry.pathname}", exc) continue + if clip.humanoid: + # 体の動きはマッスル値にあり、残りのカーブ(補助のボーンなど)だけでは使い道が無い + self.stats.humanoid.append(entry.pathname) + continue if not clip.curves: - (self.stats.humanoid if clip.humanoid else self.stats.empty).append(entry.pathname) + self.stats.empty.append(entry.pathname) continue if is_state_clip(clip): self.stats.state.append(entry.pathname) @@ -130,8 +133,6 @@ def run(self) -> ClipStats: result = self.build(entry, clip, bindings) if result == "loaded": self.stats.loaded.append(entry.pathname) - if clip.humanoid: - self.stats.humanoid_partial.append(entry.pathname) elif result == "bones": self.stats.bone_only.append(entry.pathname) else: @@ -352,8 +353,6 @@ def report_lines(stats: ClipStats) -> Iterable[str]: yield f"skipped {len(stats.state)} animation clip(s) that only switch a state (constant values or 0.1 s or shorter)" if stats.humanoid: yield f"skipped {len(stats.humanoid)} Humanoid animation clip(s) (muscle curves are not supported)" - if stats.humanoid_partial: - yield f"imported only the non-muscle curves of {len(stats.humanoid_partial)} Humanoid animation clip(s)" if stats.root_only: yield f"skipped {len(stats.root_only)} animation clip(s) that only animate the object they are played on (target unknown)" if stats.bone_only: diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 4d5fbac..4e5d0c5 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.7" +version = "1.18.0-dev.8" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/animation.py b/unitypackage_loader/core/animation.py index 2311a20..7e024aa 100644 --- a/unitypackage_loader/core/animation.py +++ b/unitypackage_loader/core/animation.py @@ -7,7 +7,8 @@ - Transform: ``m_PositionCurves`` / ``m_RotationCurves``(クォータニオン)/ ``m_EulerCurves``(度)/ ``m_ScaleCurves``。 3〜4 成分のカーブは成分ごとの ``Curve`` に分ける(``attribute`` は ``m_LocalPosition.x`` などエディターのカーブと同じ名前) -Humanoid のクリップ(Animator のマッスル値のカーブ)は ``humanoid`` を立てるだけで、カーブは返さない。 +Humanoid のクリップ(Animator のマッスル値のカーブ)は ``humanoid`` を立て、マッスル値のカーブは返さない +(ほかのカーブは返すが、読み込む側はクリップごと外す)。 それ以外のカーブ(マテリアルのプロパティ、オブジェクト参照の差し替えなど)は数だけ数える。 カーブの評価は Unity の AnimationCurve と同じく、キーの間をエルミート(weighted のキーは 3 次ベジェ)でつなぎ、 From 57b94b8590d351bdb7db94804fe7a0f5b892329e Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 00:49:59 +0900 Subject: [PATCH 12/25] =?UTF-8?q?docs:=20Humanoid=20=E3=81=AE=E3=82=AF?= =?UTF-8?q?=E3=83=AA=E3=83=83=E3=83=97=E3=82=92=E3=82=AF=E3=83=AA=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=81=94=E3=81=A8=E5=A4=96=E3=81=99=E3=81=93=E3=81=A8?= =?UTF-8?q?=E3=82=92=E6=9B=B8=E3=81=8F=EF=BC=88#209=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 4 +++- README.md | 2 +- README_ja.md | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 9eef48f..2299eaa 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1066,7 +1066,9 @@ def run(ctx, filepath, opts) -> Report: `m_RotationCurves` / `m_EulerCurves` / `m_ScaleCurves`(成分ごとの `Curve` に分ける)と `m_FloatCurves` のうち、シェイプキー (classID 137 の `blendShape.*`)、GameObject の `m_IsActive`、Renderer の `m_Enabled` を返す。実行時のカーブが無いクリップは `m_EditorCurves` を読む。Animator(classID 95)のパスの無いカーブで、マッスル値やルートの動き(`RootT.x`、`Left Arm Down-Up`、 - `LeftHand.Thumb.1 Stretched` など)の名前のものがあれば Humanoid とし、そのカーブは読まない(ほかのカーブは読む)。 + `LeftHand.Thumb.1 Stretched` など)の名前のものがあれば Humanoid とし、マッスル値のカーブは返さない。ほかのカーブは返すが、`ClipImporter` はクリップごと外す + (体の動きはマッスル値にあり、残りは補助のボーン(ひねりのボーンなど)の動かないカーブだけで使い道が無い。Everyday Motion Pack で、 + それだけを読んで動かないトラックが並んでいた。元のモーションは `@` 付きの FBX のテイクにあり、#276 で扱う)。 マテリアルのプロパティ・Animator のパラメーター・オブジェクト参照のカーブは数だけ数える。壊れた入力には `AnimationParseError`(ValueError)だけを送る。 - **評価**: キーの間はエルミート(weighted のキーは重みの長さのハンドルの 3 次ベジェ)、接線が無限大の区間は前のキーの値のまま。 `bezier_handles` はエルミートの接線を 1/3 の長さのハンドルにして Blender のベジェにする(同じ曲線になる)。 diff --git a/README.md b/README.md index 40d4391..af83ceb 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ Clips that only switch a state are skipped: clips whose values never change, or 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 (muscle curves; only their other curves are read), +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), 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 6fdb369..5c57581 100644 --- a/README_ja.md +++ b/README_ja.md @@ -168,7 +168,7 @@ Windows のパスの長さの上限に当たらないよう、フルパスが長 ステートとして使い、動きは遷移で作ります(VRChat のアバターの衣装の切り替えや表情、車両のハンドルの角度など)。 Blender では再生しても何も動かないためです。 -読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(マッスル値。ほかのカーブは読みます)、ボーンのカーブ、 +読み込まないもの(件数はレポートに出ます): 状態を切り替えるだけのクリップ(上記)、Humanoid のクリップ(体の動きがマッスル値で入っているため、ほかのカーブも含めてクリップごと外します。元の FBX にモーションがあれば #276 で取り出す予定)、ボーンのカーブ、 再生するオブジェクト自身だけを動かすクリップ(パスが無く、どのオブジェクトか決められない)、マテリアルやオブジェクト参照のカーブ。 読み込んだオブジェクトにパスが当てはまらないクリップも外します。Animator Controller は読みません。 From 7213813eb5de7ced6da1b0b2e544ff56d6502e28 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 01:56:12 +0900 Subject: [PATCH 13/25] =?UTF-8?q?feat:=20=E3=83=A2=E3=83=87=E3=83=AB?= =?UTF-8?q?=E3=81=AE=20.meta=20=E3=81=8B=E3=82=89=E3=82=A2=E3=83=8B?= =?UTF-8?q?=E3=83=A1=E3=83=BC=E3=82=B7=E3=83=A7=E3=83=B3=E3=81=AE=E3=82=AF?= =?UTF-8?q?=E3=83=AA=E3=83=83=E3=83=97=E3=81=AE=E8=A8=AD=E5=AE=9A=E3=82=92?= =?UTF-8?q?=E8=AA=AD=E3=82=80=EF=BC=88#276=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit animations.clipAnimations の name / takeName / firstFrame / lastFrame / loopTime を ModelClip にし、 importAnimation とあわせて ModelImporterInfo に持たせる。Unity がモデルのテイクから切り出すクリップを、 Blender でも同じ名前・範囲で NLA に並べるのに使う。範囲が逆転しているものなど、読めない行は外す。 Co-Authored-By: Claude Opus 5.5 --- tests/test_meta.py | 22 ++++++++++++ unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/meta.py | 43 +++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) 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_manifest.toml b/unitypackage_loader/blender_manifest.toml index 4e5d0c5..0d9ece5 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.9" 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: From 371ed3b7cc821f26ea65c7d2330cc6268e49c1e0 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 01:56:12 +0900 Subject: [PATCH 14/25] =?UTF-8?q?feat:=20FBX=20=E3=81=AE=E3=83=86=E3=82=A4?= =?UTF-8?q?=E3=82=AF=E3=82=92=20Unity=20=E3=81=AE=E3=82=AF=E3=83=AA?= =?UTF-8?q?=E3=83=83=E3=83=97=E3=81=A9=E3=81=8A=E3=82=8A=E3=81=AB=20NLA=20?= =?UTF-8?q?=E3=81=AB=E4=B8=A6=E3=81=B9=E3=80=81=E3=83=A2=E3=83=BC=E3=82=B7?= =?UTF-8?q?=E3=83=A7=E3=83=B3=E3=81=A0=E3=81=91=E3=81=AE=E3=82=A2=E3=83=BC?= =?UTF-8?q?=E3=83=9E=E3=83=81=E3=83=A5=E3=82=A2=E3=82=92=E3=81=BE=E3=81=A8?= =?UTF-8?q?=E3=82=81=E3=82=8B=EF=BC=88#276=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit モーション集(32 RPG Animations)や @ 付きの FBX(Everyday Motion Pack)のモーションを使えるようにする。 - テイクの Action を .meta のクリップごとに範囲を絞ったストリップにし、クリップの名前のトラックに置く。 同じテイクのクリップは Action を共有する。0.1 秒以下のクリップ(T ポーズのテイク)は置かず、 使われないテイクの Action は消し、FBX インポーターが付けるアクティブな Action は外す。 - シーンで同じモデルを配置ごとに読み直すときは、最初の Action を使い回す。 - Models 単位で、同じ骨格(含まれる関係でもよい)のモーションだけのモデルを 1 体のアーマチュアにまとめる。 スキンの無い FBX はファイルごとにレストが違うので、B' = R'⁻¹·R·B でキーを変換する。 ルートのボーンがオブジェクトになった FBX は、動かさないオブジェクトの Transform を一定のキーで補う。 32 RPG Animations(31 体 → 1 体)と Everyday Motion Pack(244 体 → 1 体)で、元の FBX とボーンの姿勢が 1e-4 以内で一致することを確かめた。 - オプションの Import Animation(FBX に渡すだけ、既定 OFF)と Animation Clips(#209)を、 Animation(Muted(既定)/ Active / None)にまとめる。Active はオブジェクトごとに最初の 1 本だけミュートを外す。 Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender/animation.py | 3 +- unitypackage_loader/blender/fbx_motion.py | 434 ++++++++++++++++++ unitypackage_loader/blender/importer.py | 27 +- unitypackage_loader/blender/model_import.py | 2 +- unitypackage_loader/blender/options.py | 5 +- unitypackage_loader/blender_manifest.toml | 2 +- .../operators/import_package.py | 18 +- 7 files changed, 476 insertions(+), 15 deletions(-) create mode 100644 unitypackage_loader/blender/fbx_motion.py 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 0d9ece5..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.9" +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/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") From 9de3dd11d1fa7ec43d4a330b47a3ad46dcd83a1f Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 01:56:12 +0900 Subject: [PATCH 15/25] =?UTF-8?q?test:=20=E3=83=A2=E3=83=87=E3=83=AB?= =?UTF-8?q?=E3=81=AE=E3=83=86=E3=82=A4=E3=82=AF=E3=82=92=E5=90=AB=E3=82=80?= =?UTF-8?q?=E5=90=88=E6=88=90=E3=83=91=E3=83=83=E3=82=B1=E3=83=BC=E3=82=B8?= =?UTF-8?q?=E3=81=A8=E6=9C=9F=E5=BE=85=E5=80=A4=E3=82=92=E8=B6=B3=E3=81=99?= =?UTF-8?q?=EF=BC=88#276=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Walk.fbx(テイクを .meta で 2 クリップに分ける。T ポーズのテイクを含む)、Run.fbx(骨格が部分集合で、レストが違う)、 Character.fbx(メッシュ付きでまとめない。シーンに 2 か所置く)で、Muted / Active / None / シーンの 4 通りを確かめる。 統合テストに、ボーンの向き・ミュートを外したトラック・アーマチュアとテイクの Action の数の確認を足した。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_anim_off.json | 2 +- tests/expectations_synthetic_motion.json | 27 +++ .../expectations_synthetic_motion_active.json | 19 ++ tests/expectations_synthetic_motion_none.json | 16 ++ .../expectations_synthetic_motion_scene.json | 19 ++ tests/integration_import.py | 21 +- tests/integration_runs.json | 7 +- tests/make_synthetic_motion_package.py | 210 ++++++++++++++++++ 8 files changed, 317 insertions(+), 4 deletions(-) create mode 100644 tests/expectations_synthetic_motion.json create mode 100644 tests/expectations_synthetic_motion_active.json create mode 100644 tests/expectations_synthetic_motion_none.json create mode 100644 tests/expectations_synthetic_motion_scene.json create mode 100644 tests/make_synthetic_motion_package.py 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() From 837ea46063316493f5924c4ca018e2835e6b8122 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 01:56:12 +0900 Subject: [PATCH 16/25] =?UTF-8?q?docs:=20=E3=83=A2=E3=83=87=E3=83=AB?= =?UTF-8?q?=E3=81=AE=E4=B8=AD=E3=81=AE=E3=83=A2=E3=83=BC=E3=82=B7=E3=83=A7?= =?UTF-8?q?=E3=83=B3=E3=81=A8=20Animation=20=E3=81=AE=E3=82=AA=E3=83=97?= =?UTF-8?q?=E3=82=B7=E3=83=A7=E3=83=B3=E3=82=92=E6=9B=B8=E3=81=8F=EF=BC=88?= =?UTF-8?q?#276=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +++- DESIGN.md | 43 ++++++++++++++++++++++++++++++++++++++++--- README.md | 32 +++++++++++++++++++++++++------- README_ja.md | 33 +++++++++++++++++++++++++-------- 4 files changed, 93 insertions(+), 19 deletions(-) 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 は読みません。 From 566588d63f4b88367fba2e1b95a1b1538a7bf5ff Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 02:14:35 +0900 Subject: [PATCH 17/25] =?UTF-8?q?feat:=20=E3=83=AB=E3=83=BC=E3=83=97?= =?UTF-8?q?=E3=81=99=E3=82=8B=E3=82=AF=E3=83=AA=E3=83=83=E3=83=97=E3=81=AE?= =?UTF-8?q?=E3=82=B9=E3=83=88=E3=83=AA=E3=83=83=E3=83=97=E3=82=92=E3=82=B7?= =?UTF-8?q?=E3=83=BC=E3=83=B3=E3=81=AE=E7=B5=82=E3=82=8F=E3=82=8A=E3=81=BE?= =?UTF-8?q?=E3=81=A7=E7=B9=B0=E3=82=8A=E8=BF=94=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unity の Loop Time のクリップ(.anim の m_LoopTime と、モデルの .meta の loopTime)は、NLA のストリップの 繰り返し(repeat)をシーンのフレーム範囲の終わりまでにする。NLA はストリップの範囲の外を評価しないので、 .anim の Action に付けていた Cycles モディファイアーだけでは、実際にはループしていなかった。 まとめたアーマチュアにトラックを写すときも回数を引き継ぐ。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_anim.json | 3 ++- tests/expectations_synthetic_anim_scene.json | 4 ++-- tests/expectations_synthetic_motion.json | 3 ++- unitypackage_loader/blender/animation.py | 3 +++ unitypackage_loader/blender/fbx_motion.py | 19 ++++++++++++++++++- unitypackage_loader/blender_manifest.toml | 2 +- 6 files changed, 28 insertions(+), 6 deletions(-) diff --git a/tests/expectations_synthetic_anim.json b/tests/expectations_synthetic_anim.json index acd68f0..26ff6d6 100644 --- a/tests/expectations_synthetic_anim.json +++ b/tests/expectations_synthetic_anim.json @@ -31,7 +31,8 @@ { "track": "HatOff", "object": "Hat", "seconds": 0, "hidden": false }, { "track": "HatOff", "object": "Hat", "seconds": 0.75, "hidden": true }, { "track": "Wave", "object": "Body", "seconds": 0, "hidden": true }, - { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 1, "axis": [0, 0, 1], "degrees": -90 } }, + { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 0.5, "axis": [0, 0, 1], "degrees": -45 } }, + { "track": "DoorOpen", "object": "Door", "rotation_delta": { "from": 0, "to": 1.5, "axis": [0, 0, 1], "degrees": -45 } }, { "track": "DoorOpen", "object": "Knob", "seconds": 0, "distance_to": "Door", "distance": 111.8034 } ] } diff --git a/tests/expectations_synthetic_anim_scene.json b/tests/expectations_synthetic_anim_scene.json index b963d1a..ae7a307 100644 --- a/tests/expectations_synthetic_anim_scene.json +++ b/tests/expectations_synthetic_anim_scene.json @@ -55,13 +55,13 @@ "object": "Door", "rotation_delta": { "from": 0, - "to": 1, + "to": 0.5, "axis": [ 0, 0, 1 ], - "degrees": -90 + "degrees": -45 } }, { diff --git a/tests/expectations_synthetic_motion.json b/tests/expectations_synthetic_motion.json index b478962..d4994ea 100644 --- a/tests/expectations_synthetic_motion.json +++ b/tests/expectations_synthetic_motion.json @@ -18,7 +18,8 @@ "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": "Walk", "object": "Rig", "seconds": 1.5, "bone_direction": { "bone": "Spine", "vector": [0, -0.7071, 0.7071] } }, + { "track": "Rig|run_take", "object": "Rig", "seconds": 1.5, "bone_direction": { "bone": "Spine", "vector": [0, -0.5039, 0.8638] } }, { "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/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 18d080a..53fd656 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -34,6 +34,7 @@ from ..core.animation_targets import Binding, TargetObject, TargetTree, bind_paths from ..core.model_space import ModelUnits, local_basis, local_values from ..core.transform import IDENTITY, UNITY_TO_BLENDER, Mat4, inverse_affine +from .fbx_motion import loop_strip from .log import warn_skipped from .model_import import FBX_NODE_PROP, MODEL_GUID_PROP, node_name @@ -205,6 +206,8 @@ def _add_track(self, datablock, action, slot, name: str) -> None: nla_strip = track.strips.new(name, self.frame_start, action) if nla_strip.action_slot != slot: nla_strip.action_slot = slot + if action.use_cyclic: + loop_strip(nla_strip, self.scene) track.mute = not active # 各種のカーブ ------------------------------------------------------ diff --git a/unitypackage_loader/blender/fbx_motion.py b/unitypackage_loader/blender/fbx_motion.py index 7151610..074c9cd 100644 --- a/unitypackage_loader/blender/fbx_motion.py +++ b/unitypackage_loader/blender/fbx_motion.py @@ -15,6 +15,7 @@ from __future__ import annotations +import math import re from dataclasses import dataclass, field @@ -63,6 +64,7 @@ class _Clip: action: bpy.types.Action start: float # Blender のフレーム(Action の中の範囲) end: float + loop: bool = False def _slot_owner(slot, objects: list[bpy.types.Object]): @@ -184,7 +186,7 @@ def _clips(self, info: ModelImporterInfo | None, cached: dict[str, bpy.types.Act if count: self.stats.state += 1 continue - clips.append(_Clip(setting.name, action, setting.first_frame + ANIM_OFFSET, setting.last_frame + ANIM_OFFSET)) + clips.append(_Clip(setting.name, action, setting.first_frame + ANIM_OFFSET, setting.last_frame + ANIM_OFFSET, setting.loop)) return clips def _add_track(self, owner: bpy.types.ID, clip: _Clip, slot) -> None: @@ -196,9 +198,23 @@ def _add_track(self, owner: bpy.types.ID, clip: _Clip, slot) -> None: if strip.action_slot != slot: strip.action_slot = slot set_strip_range(strip, clip.start, clip.end) + if clip.loop: + loop_strip(strip, self.scene) track.mute = not active +def loop_strip(strip, scene: bpy.types.Scene) -> None: + """ループするクリップ(Unity の Loop Time)のストリップを、シーンのフレーム範囲の終わりまで繰り返す。 + + NLA はストリップの範囲の外を評価しない(Action の Cycles モディファイアーは範囲の中でしか働かない)ので、繰り返しの回数で表す。 + """ + length = strip.action_frame_end - strip.action_frame_start + if length <= 0: + return + span = scene.frame_end - strip.frame_start + 1 + strip.repeat = float(max(1, math.ceil(span / length))) + + def set_strip_range(strip, start: float, end: float) -> None: """ストリップが使う Action の範囲を変え、ストリップの長さをそれに合わせる(置く位置は変えない)。""" begin = strip.frame_start @@ -304,6 +320,7 @@ def copy_track(animation_data, track, strip, action: bpy.types.Action) -> 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_strip.repeat = strip.repeat new_track.mute = track.mute or has_active diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 773e6fd..92f5289 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.10" +version = "1.18.0-dev.11" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" From 889088d865aad4a69f17c0f00e45369f004e506f Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 02:14:35 +0900 Subject: [PATCH 18/25] =?UTF-8?q?docs:=20=E3=83=AB=E3=83=BC=E3=83=97?= =?UTF-8?q?=E3=81=99=E3=82=8B=E3=82=AF=E3=83=AA=E3=83=83=E3=83=97=E3=81=AE?= =?UTF-8?q?=E6=89=B1=E3=81=84=E3=82=92=E6=9B=B8=E3=81=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 5 +++-- README.md | 5 +++-- README_ja.md | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 80672c8..02fc04d 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1091,7 +1091,8 @@ def run(ctx, filepath, opts) -> Report: - **Action と NLA**(`blender/animation.py`): クリップごとに Action を 1 つ作り(`unity_clip_guid` / `unity_clip_path`)、対象のデータブロック (オブジェクトかシェイプキーの Key)ごとにスロットを作る(Blender 4.4 以降のスロット付き Action)。対象ごとにクリップの名前の NLA トラックを ミュートで足すので、読み込んだ直後の見た目は変わらない。キーはクリップの開始からの秒 × シーンのフレームレートで、ストリップはシーンの開始フレームに置く。 - ループするクリップ(`m_LoopTime`)の F カーブには Cycles モディファイアーを付ける。 + ループするクリップ(`m_LoopTime`)は、ストリップの繰り返し(`repeat`)をシーンのフレーム範囲の終わりまでにする(`fbx_motion.loop_strip`)。 + NLA はストリップの範囲の外を評価しないので、F カーブの Cycles モディファイアー(これも付ける。Action を直接再生するとき用)だけではループしない。 - シェイプキー: 値を 1/100 にしてキーと接線をそのままベジェにする。100 を超える重みは `slider_max` を広げる。 - 表示: `hide_viewport` / `hide_render` を階段(CONSTANT)で、値が 0.5 未満なら隠す。`m_IsActive` は Unity の階層での子孫にも当てる (スキンメッシュはアーマチュアの子孫にしない)。 @@ -1139,7 +1140,7 @@ Blender の FBX インポーターはテイクごとにテイクの名前の Act アーマチュアの数を `clip_notes` に出す。 - FBX インポーターは、アニメーションを読むかどうかによらずシーンのフレームレートをファイルのものにする(今までと同じ)。 フレームレートの違う FBX を続けて読むと、先に読んだ FBX のモーションの速さがずれる(未対応)。 -- ループ(`loopTime`)はまだ NLA に反映しない(ストリップは範囲の終わりで止まる)。 +- ループ(`loopTime`)は、`.anim` と同じくストリップの繰り返しにする(`loop_strip`。まとめたアーマチュアに写すときも回数を引き継ぐ)。 ### 4.8 `blender/textures.py` diff --git a/README.md b/README.md index a51f10d..3ebb721 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,8 @@ When several motion-only models (no meshes, one armature) share the same skeleto 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. +When a scene places the same model many times, the actions of its takes are shared. Looping clips (Loop Time in Unity) +repeat their strip until the end of the scene's frame range. #### Generic `.anim` clips @@ -201,7 +202,7 @@ 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 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. +Looping clips (Loop Time in Unity) repeat their strip until the end of the scene's frame range. 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, diff --git a/README_ja.md b/README_ja.md index 26a71a7..9143f2c 100644 --- a/README_ja.md +++ b/README_ja.md @@ -169,7 +169,8 @@ FBX の中のアニメーションのテイク(モーション集や、`モデ 同じ骨格のモーションだけのモデル(メッシュが無く、アーマチュアが 1 体)が複数あれば、1 体のアーマチュアにまとめて、全モーションを NLA トラックとして並べます(Models 単位)。スキンの無い FBX はファイルの既定の姿勢をレストにするので、レスト姿勢はファイルごとに 違います。残すアーマチュアでも同じ姿勢になるよう、キーを変換します。一部のボーン(武器用のボーンなど)が無い骨格もまとめます -(無いボーンはレストのまま)。シーンで同じモデルを何度も置くときは、テイクの Action を共有します。 +(無いボーンはレストのまま)。シーンで同じモデルを何度も置くときは、テイクの Action を共有します。ループするクリップ(Unity の Loop Time)は、 +シーンのフレーム範囲の終わりまでストリップを繰り返します。 #### Generic な `.anim` @@ -181,7 +182,7 @@ NLA トラックとして並べます(Models 単位)。スキンの無い FB クリップは対象のモデルを持たないので、カーブの階層パスがいちばん多く当てはまる読み込んだオブジェクトを、クリップを再生する オブジェクトとみなします(同じモデルを複数置いていれば、すべてに付けます)。動かすオブジェクトとシェイプキーごとに -NLA トラックを足します。キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップの F カーブには Cycles モディファイアーを付けます。 +NLA トラックを足します。キーはシーンの開始フレームから、シーンのフレームレートで並べます。ループするクリップ(Unity の Loop Time)は、シーンのフレーム範囲の終わりまでストリップを繰り返します。 状態を切り替えるだけのクリップ(値が変わらないもの、0.1 秒以下で終わるもの)は読み込みません。Unity の Animator はこうしたクリップを ステートとして使い、動きは遷移で作ります(VRChat のアバターの衣装の切り替えや表情、車両のハンドルの角度など)。 From dd1944e41be1af301f4d7c02c30214e744c62af5 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 02:34:15 +0900 Subject: [PATCH 19/25] =?UTF-8?q?fix:=20=E3=83=AB=E3=83=BC=E3=83=88?= =?UTF-8?q?=E3=81=AE=E3=83=8E=E3=83=BC=E3=83=89=E3=81=8C=E6=B1=BA=E3=81=BE?= =?UTF-8?q?=E3=82=89=E3=81=AA=E3=81=84=E9=85=8D=E7=BD=AE=E3=81=A7=E3=80=81?= =?UTF-8?q?=E3=83=AB=E3=83=BC=E3=83=88=E8=87=AA=E8=BA=AB=E3=81=AE=E3=83=A1?= =?UTF-8?q?=E3=83=83=E3=82=B7=E3=83=A5=E3=82=92=20GameObject=20=E3=81=AE?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE=E3=81=AB=E7=BD=AE=E3=81=8F=EF=BC=88#272?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GameObject の MeshFilter が、新しい形式(名前の表が無い)の複数ノードの FBX のメッシュを 1 つ直接指し、GameObject 名も ノード名と違うとき、どのノードかが決まらず、メッシュのオブジェクトが FBX の中でのノードの変換の分ずれていた。 Unity は MeshFilter が指すメッシュを GameObject の Transform で描くので、この場合はルート自身の Renderer にも 単位行列の relative を渡し、apply_renderer_worlds で GameObject の位置に置き直す。 Office Assets の Showcase で、Cork Board の紙とピンのほか、本・段ボール箱・PC 本体・飾り棚の小物(計 46 オブジェクト。 0.2〜1.4 m ずれていた)が GameObject の位置に合った。Cardboard Boxes、NewGen、Destroyed Building Kit、Synty Starter、 Japanese Apartment、Cafeteria、Yumeka の配置は変わらない(全オブジェクトの行列が一致)。 Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender_manifest.toml | 2 +- unitypackage_loader/core/placement.py | 26 +++++++++++++++++------ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index 773e6fd..b0ce091 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.10" +version = "1.18.0-dev.12" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" diff --git a/unitypackage_loader/core/placement.py b/unitypackage_loader/core/placement.py index e83b547..7b6ec61 100644 --- a/unitypackage_loader/core/placement.py +++ b/unitypackage_loader/core/placement.py @@ -40,7 +40,7 @@ ) from .primitives import builtin_mesh_kind from .terrain import terrain_data_ref -from .transform import Mat4, inverse_affine, multiply +from .transform import IDENTITY, Mat4, inverse_affine, multiply from .unity_ids import mesh_file_id @@ -281,6 +281,7 @@ def placements( # 2 回目: 配置を作る result: list[ModelPlacement] = [] by_root: dict[tuple[int, str], ModelPlacement] = {} + unlabeled: set[tuple[int, str]] = set() # ルートがどの FBX のノードか決まらなかった配置 for item in items: if isinstance(item, ModelPlacement): result.append(item) @@ -293,9 +294,11 @@ def placements( label = _root_node_label(h, root, item.key, guid, ctx) if label is not None: placement.node_transforms[label] = copy.deepcopy(_IDENTITY_NODE) + else: + unlabeled.add((root, guid)) by_root[(root, guid)] = placement result.append(placement) - _add_renderer(h, placement, item, worlds, active) + _add_renderer(h, placement, item, worlds, active, (root, guid) in unlabeled) return result @@ -438,8 +441,12 @@ def _root_node_label(h: Hierarchy, root: int, key: int, guid: str, ctx: _Placeme return None -def _add_renderer(h: Hierarchy, placement: ModelPlacement, item: _RendererRow, worlds: dict, active: dict) -> None: - """配置に Renderer を加える(同名が既にあれば先のものを使い、置き直しの行列を外す)。""" +def _add_renderer(h: Hierarchy, placement: ModelPlacement, item: _RendererRow, worlds: dict, active: dict, + unlabeled_root: bool = False) -> None: + """配置に Renderer を加える(同名が既にあれば先のものを使い、置き直しの行列を外す)。 + + ``unlabeled_root`` は、ルートがどの FBX のノードか決まらなかった配置(``_root_node_label`` が None)。 + """ key, name, root = item.key, item.name, placement.root node = h.nodes[key] renderer = node.renderer @@ -448,12 +455,17 @@ def _add_renderer(h: Hierarchy, placement: ModelPlacement, item: _RendererRow, w return # 同じモデルに同名の GameObject があれば先のものを使う(prefab の表と同じ) # ルート自身の Renderer は置き直さない。FBX の最上位のノードを Unity がルートに畳んだもので、ルートの Transform が # ノードの変換を含むため、オブジェクトの行列との関係が中のノードと違う(置き方は #98 / #181 / #185 で決まっている) + # ただし、ルートがどの FBX のノードか決まらないとき(新しい形式の .meta で名前の表が無く、GameObject 名もノード名と違う。 + # Office Assets の Cork Board の紙とピン)は、FBX のノードの変換を消せないので、ルートの位置(単位行列)に置き直す。 + # Unity は MeshFilter が指すメッシュを、その GameObject の Transform で描く(#272) root_inverse = inverse_affine(placement.world) if key != root else None + if root_inverse is not None: + relative = multiply(root_inverse, worlds[key]) + else: + relative = IDENTITY if unlabeled_root else None placement.renderers[name] = PlacedRenderer( name, list(renderer.materials), renderer.renderer_class, active[key] and renderer.enabled, - renderer.mesh_file_id, renderer.lod_level, - multiply(root_inverse, worlds[key]) if root_inverse is not None else None, - renderer.shadows_only, + renderer.mesh_file_id, renderer.lod_level, relative, renderer.shadows_only, ) # ルートからこの Node までの、上書き前の行列の積で逆算する inverse = inverse_affine(node.scope_matrix) From f5b072ded59542f36cf5c1dde428d678f9ac52eb Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 02:34:15 +0900 Subject: [PATCH 20/25] =?UTF-8?q?test:=20=E5=90=8D=E5=89=8D=E3=82=92?= =?UTF-8?q?=E5=A4=89=E3=81=88=E3=81=9F=20GameObject=20=E3=81=8C=E3=80=81?= =?UTF-8?q?=E8=A1=A8=E3=81=AE=E7=84=A1=E3=81=84=20FBX=20=E3=81=AE=E5=8E=9F?= =?UTF-8?q?=E7=82=B9=E3=81=8B=E3=82=89=E9=9B=A2=E3=82=8C=E3=81=9F=E3=83=8E?= =?UTF-8?q?=E3=83=BC=E3=83=89=E3=82=92=E6=8C=87=E3=81=99=E3=82=B1=E3=83=BC?= =?UTF-8?q?=E3=82=B9=E3=82=92=E8=B6=B3=E3=81=99=EF=BC=88#272=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 合成シーンに Rod Renamed(Rings.fbx の x = 2 にある Rod.001 を指す)を置き、GameObject の位置に置かれることを見る。 修正前は、大きさが 100 倍で位置もずれ、このテストが落ちることを確かめた。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_scene.json | 15 ++++++++++++++- .../expectations_synthetic_scene_keep_unused.json | 2 +- tests/make_synthetic_scene_package.py | 5 +++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/expectations_synthetic_scene.json b/tests/expectations_synthetic_scene.json index 5013346..b9c44b3 100644 --- a/tests/expectations_synthetic_scene.json +++ b/tests/expectations_synthetic_scene.json @@ -442,6 +442,19 @@ "top": "Ring Renamed", "object": "Rod", "absent": true + }, + { + "top": "Rod Renamed", + "object": "Rod", + "bbox": [19.995, -3.005, -0.005, 20.005, -2.995, 0.005], + "mat_files": [ + "ProbeMat.mat" + ] + }, + { + "top": "Rod Renamed", + "object": "Ring", + "absent": true } ], "shared_meshes": [ @@ -603,7 +616,7 @@ ], "warnings_contain": [ "Booth.fbx: 1 material override(s) on objects inside the model could not be matched", - "scene Assets/Synthetic/Scenes/Probe.unity: 5 object(s) from model files are not used by the Unity prefabs or scene and were not imported", + "scene Assets/Synthetic/Scenes/Probe.unity: 6 object(s) from model files are not used by the Unity prefabs or scene and were not imported", "scene Assets/Synthetic/Scenes/Probe.unity: 1 visibility override(s) or removal(s) on objects inside a model could not be matched", "scene Assets/Synthetic/Scenes/Probe.unity: 1 decal projector(s) were skipped" ], diff --git a/tests/expectations_synthetic_scene_keep_unused.json b/tests/expectations_synthetic_scene_keep_unused.json index f2d1e27..781bd08 100644 --- a/tests/expectations_synthetic_scene_keep_unused.json +++ b/tests/expectations_synthetic_scene_keep_unused.json @@ -38,7 +38,7 @@ } ], "warnings_contain": [ - "scene Assets/Synthetic/Scenes/Probe.unity: 5 object(s) from model files are not used by the Unity prefabs or scene and were hidden", + "scene Assets/Synthetic/Scenes/Probe.unity: 6 object(s) from model files are not used by the Unity prefabs or scene and were hidden", "scene Assets/Synthetic/Scenes/Legacy.unity: 4 object(s) from model files are not used by the Unity prefabs or scene and were hidden" ], "warnings_exclude": [ diff --git a/tests/make_synthetic_scene_package.py b/tests/make_synthetic_scene_package.py index 5cc66a3..a75ae7a 100644 --- a/tests/make_synthetic_scene_package.py +++ b/tests/make_synthetic_scene_package.py @@ -710,6 +710,11 @@ def mesh_collider(file_id, go, model_guid, name): game_object(6100, "Ring Renamed"), transform(6101, 6100, pos=(-20, 0, 0)), mesh_renderer(6102, 6103, 6100, rings_model, mats["ProbeRed"], mesh_file_id("Ring.001")), + # 同じく Rod.001(FBX の中で x = 2 にある)を名前を変えた GameObject で置く。Unity はメッシュを GameObject の + # Transform で描くので、FBX の中のノードの位置の分ずらさない(#272。Office Assets の Cork Board の紙とピン) + game_object(6200, "Rod Renamed"), + transform(6201, 6200, pos=(-20, 0, 3)), + mesh_renderer(6202, 6203, 6200, rings_model, mats["ProbeMat"], mesh_file_id("Rod.001")), game_object(6000, "Hidden", active=0), transform(6001, 6000, pos=(6, 0, 0)), instance(6002, model, 6001, []), From 97cff93e56b797a34aef9a290216253cdbf538de Mon Sep 17 00:00:00 2001 From: utagestudio Date: Thu, 26 Nov 2026 02:34:15 +0900 Subject: [PATCH 21/25] =?UTF-8?q?docs:=20=E3=83=AB=E3=83=BC=E3=83=88?= =?UTF-8?q?=E3=81=AE=E3=83=8E=E3=83=BC=E3=83=89=E3=81=8C=E6=B1=BA=E3=81=BE?= =?UTF-8?q?=E3=82=89=E3=81=AA=E3=81=84=E9=85=8D=E7=BD=AE=E3=81=AE=E7=BD=AE?= =?UTF-8?q?=E3=81=8D=E7=9B=B4=E3=81=97=E3=82=92=20DESIGN.md=20=E3=81=AB?= =?UTF-8?q?=E6=9B=B8=E3=81=8F=EF=BC=88#272=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index 80672c8..0f656cc 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -84,6 +84,12 @@ Blender から `.unitypackage` を直接読み込み、メッシュ(アーマ ルートの Empty の行列 E の下で E·C·R·A(下記の N = C·L·A と同じ関係)を求め、いまの置き方と違うオブジェクトだけを置き直す。上書きで動いた部品もこれで扱うので、 FBX のモデルでは `offsets` を使わない(FBX 以外のモデルは今までどおり `offsets`)。オブジェクトと Renderer の対応は prefab の表と同じ `prefab.find_renderer` (Blender が付け替えた連番も引ける。#155)で、1 つの Renderer に複数のオブジェクトが当たるときと、同じ配置に同名の Renderer があるときは置き直さない。 + - ルート自身の Renderer は、ふつう R を持たない(Unity が FBX の最上位のノードをルートに畳んだ形で、ノードを単位行列にして扱う。#98 / #181 / #185)。 + ただし、ルートがどの FBX のノードか決まらないとき(`_root_node_label` が None。新しい形式の .meta で名前の表が無く、GameObject 名もノード名と違う)は、 + ノードの変換を消せずにその分ずれるので、R を単位行列にして GameObject の位置に置き直す(Unity は MeshFilter が指すメッシュを GameObject の Transform で描く。#272)。 + Office Assets の Showcase で、Cork Board の紙とピンのほか、本・段ボール箱・PC 本体・飾り棚の小物(計 46 オブジェクト。FBX の中で横に並べて作ったものが、 + その並びの分 0.2〜1.4 m ずれていた)が GameObject の位置に合った。Cardboard Boxes、NewGen、Destroyed Building Kit、Synty Starter、Japanese Apartment、 + Cafeteria、Yumeka は変わらない。 ルートの GameObject 自身の Renderer は対象にしない(Unity がノードをルートに畳んだもので、ルートの Transform がノードの変換を含み、A の関係が成り立たない。 Train Station の `ts_corebldg` や Starter の `SM_Generic_CloudRing_01` で、スケールが 100 倍違っていた)。位置の比較は 0.1 mm + 座標の 100 万分の 1 の範囲で、 座標に比例させるだけだと原点から遠い部品の数 cm のずれを見逃す(Farm の 216 m 先の門扉)。 @@ -1176,7 +1182,7 @@ Blender の FBX インポーターはテイクごとにテイクの名前の Act - `tests/test_fbx_units.py`: FBX の UnitScaleFactor(バイナリの数値の型、FBX 6 の文字列属性の数、ASCII の FBX 7 / 6、壊れた値)。古い形式のモデルの中への上書きは、`tests/test_meta.py`(fileIDToRecycleName)、`tests/test_hierarchy.py`(名前付きの記録)、シーン用の合成パッケージの `Legacy.unity`(統合テスト)で確かめる。表の無いモデルの中への上書きは、`tests/test_model_ids.py`(fileID の計算を Unity の表の値と比べる、オブジェクトとの突き合わせ、FBX のノード名の読み取り)、`tests/test_prefab.py`(記録、付け替え、prefab を挟んだ上書き)と、シーン用の合成パッケージの `Kiosk.prefab`(ルートに付く Renderer)/ `Booth.prefab`(2 つのメッシュを両方の世代の fileID で指し、モデルに無い対象は当てずに警告する)/ `Stall.prefab`(表示の上書きと削除。シーンが prefab の上から表示し直し・削除する)で確かめる(統合テストの `warnings_contain` / `warnings_exclude` と、オブジェクトの `hidden` / `absent`)。表示の上書きと削除の記録は `tests/test_hierarchy.py`、オブジェクトへの当て方は `tests/test_model_ids.py` で確かめる。 - `tests/test_lights.py`: ライトの強さの換算が、Unity(Built-in / URP)と Blender で測った画素値を再現すること(Built-in の点光源は d/R が 0.2〜1 で 1.4 倍以内)、スポットの角度、色の線形化と色温度、カメラの画角・Physical Camera・平行投影、ライト・カメラの向き(Unity の真下向きが Blender の真下向きになる)。 - `tests/test_transform.py` / `tests/test_hierarchy.py`: 行列計算と座標変換、階層の展開(stripped の対応表、上書き、削除、非アクティブ、循環・自己参照)。配置の数値は Unity 6 で作った調査用シーンに合わせ、Unity が書き出した頂点のワールド座標を再現できることを確かめる。 -- 読み込む単位 Scenes は、`tests/make_synthetic_scene_package.py` の合成パッケージ(同じ形の FBX と、Unity の保存形式に合わせて手書きした prefab・シーン)を `tests/expectations_synthetic_scene.json` で確認する。配置した各メッシュの突起の頂点の座標(Unity が書き出した値)、非表示、マテリアルの差し替え、メッシュの共有を見る。古い形式のシーンには、FBX から切り離した部品を部屋の下に 2 つ複製して置き、それぞれの位置に置かれることも見る(Issue #60)。ノードが原点から離れた 1 メッシュの FBX(`Slab.fbx`)のメッシュを直接指す prefab も置き、ノードの変換が掛からないことを見る(Issue #98。期待値は Unity で同じ置き方をしたときの頂点のワールド座標)。FBX を展開したあと Spike と Group の Transform の値そのものを動かした prefab(`Moved`)も置き、Unity の位置に置き直されることを見る(Issue #186。期待値は、Unity で確かめた B の頂点から Unity の行列で求めたもの)。 +- 読み込む単位 Scenes は、`tests/make_synthetic_scene_package.py` の合成パッケージ(同じ形の FBX と、Unity の保存形式に合わせて手書きした prefab・シーン)を `tests/expectations_synthetic_scene.json` で確認する。配置した各メッシュの突起の頂点の座標(Unity が書き出した値)、非表示、マテリアルの差し替え、メッシュの共有を見る。古い形式のシーンには、FBX から切り離した部品を部屋の下に 2 つ複製して置き、それぞれの位置に置かれることも見る(Issue #60)。ノードが原点から離れた 1 メッシュの FBX(`Slab.fbx`)のメッシュを直接指す prefab も置き、ノードの変換が掛からないことを見る(Issue #98。期待値は Unity で同じ置き方をしたときの頂点のワールド座標)。FBX を展開したあと Spike と Group の Transform の値そのものを動かした prefab(`Moved`)も置き、Unity の位置に置き直されることを見る(Issue #186。期待値は、Unity で確かめた B の頂点から Unity の行列で求めたもの)。表の無い FBX(`Rings.fbx`)の、原点から離れたノード Rod.001 を名前を変えた GameObject(`Rod Renamed`)で指し、GameObject の位置に置かれることも見る(Issue #272)。 - URP Lit は、`tests/make_synthetic_urp_package.py` の合成パッケージを `tests/expectations_synthetic_urp.json` で確認する(Issue #116)。URP Lit の GUID のマテリアルがあるとパッケージ全体のライトが URP の単位になるので、Built-in のシーン用とは分けてある。どの .mat にも Standard から変換したときの値(別の画像を指す `_MainTex`、黒い `_Color`、`_Mode`、`_Glossiness`)を残し、それらを読まないこと、Metallic マップ・ノーマルマップ・両面・アルファクリップ・半透明の Additive・URP Unlit・表に無い URP Lit 派生のシェーダーの発光、シーンの平行光源と点光源が URP の換算になることを見る。Specular ワークフロー・Simple Lit・Baked Lit は、Principled の IOR・Specular Tint・Metallic・Roughness の値まで見る(Issue #117)。単体テストは `tests/test_profiles_urp.py`。 同じスクリプトが出す `synthetic_urp_standard`(マテリアルのシェーダーだけを Built-in の Standard にしたもの)を `tests/expectations_synthetic_urp_standard.json` で確かめ、ライトの追加データから URP として換算し、食い違いを警告することを見る(Issue #120)。 - HDRP は、`tests/make_synthetic_hdrp_package.py` の合成パッケージを `tests/expectations_synthetic_hdrp.json` で確認する(Issue #119。ライトの単位が HDRP になるので別のパッケージにしてある)。どの .mat にも互換用の `_Color`(黒)/ `_MainTex` と Standard の `_Mode` / `_Glossiness` を残し、マスクマップと Remap(Principled の Metallic と Roughness がつながり、倍率とオフセットが入ること)、ノーマルマップ、両面、Specular Color、半透明、HDRP/Unlit、LayeredLit のレイヤー 0、シーンの平行光源(lux)・点光源(candela)・面光源(nits。#129)の換算と、グローバルな Volume の固定露出の分をライトに掛け、Blender の露出は変えないこと(優先度の高いローカルな Volume は使わない。#130)を見る。単体テストは `tests/test_profiles_hdrp.py`。 - 読み込む単位 Prefabs は、合成パッケージの `tests/expectations_synthetic_prefabs.json`(並べる)と `tests/expectations_synthetic_prefabs_stack.json`(原点に重ねる)で、prefab ごとのコレクションの中身・元の .mat・外形の重なりを統合テストで確認する。prefab で表示されていない部品を隠すことは、シーン用の合成パッケージの `StallUnpacked.prefab` / `StallSpare.prefab`(`tests/expectations_synthetic_scene_prefabs*.json`)で確かめる。 From 232314e8d3c9c7b73f991fcc5c01036cbed9d3c9 Mon Sep 17 00:00:00 2001 From: utagestudio Date: Fri, 27 Nov 2026 00:59:15 +0900 Subject: [PATCH 22/25] =?UTF-8?q?refactor:=20NLA=20=E3=81=AE=E5=85=B1?= =?UTF-8?q?=E9=80=9A=E5=87=A6=E7=90=86=E3=82=92=20nla.py=20=E3=81=AB?= =?UTF-8?q?=E3=80=81=E3=82=A2=E3=83=BC=E3=83=9E=E3=83=81=E3=83=A5=E3=82=A2?= =?UTF-8?q?=E3=81=AE=E3=81=BE=E3=81=A8=E3=82=81=E3=82=92=20rig=5Fmerge.py?= =?UTF-8?q?=20=E3=81=AB=E5=88=86=E3=81=91=E3=82=8B=EF=BC=88#281=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - .anim(animation.py)とモデルのテイク(fbx_motion.py)に同じ形であった _add_track を nla.add_track の 1 つにした。 loop_strip・set_strip_range・copy_track と Animation のオプションの値(MODE_*)も nla.py に移し、 .anim の側が fbx_motion を import しなくて済むようにした。 - fbx_motion.py の後半(motion_rigs・merge_motion_rigs・retarget_action など)を rig_merge.py に分けた。 fbx_motion.py はテイクをクリップに分けて並べる処理だけになった。 あわせて直した不具合: .anim の側の _add_track は、トラックを足してから「ミュートでないトラックがあるか」を見ていた。 新しいトラックはミュートされていない状態で作られるので自分自身が数に入り、Animation を Active にしても .anim の トラックのミュートが外れていなかった。nla.add_track は足す前に数える(FBX の側と同じ順)。 Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender/animation.py | 20 +- unitypackage_loader/blender/fbx_motion.py | 280 +--------------------- unitypackage_loader/blender/importer.py | 4 +- unitypackage_loader/blender/nla.py | 82 +++++++ unitypackage_loader/blender/rig_merge.py | 225 +++++++++++++++++ unitypackage_loader/blender_manifest.toml | 2 +- 6 files changed, 321 insertions(+), 292 deletions(-) create mode 100644 unitypackage_loader/blender/nla.py create mode 100644 unitypackage_loader/blender/rig_merge.py diff --git a/unitypackage_loader/blender/animation.py b/unitypackage_loader/blender/animation.py index 53fd656..9b745c8 100644 --- a/unitypackage_loader/blender/animation.py +++ b/unitypackage_loader/blender/animation.py @@ -7,7 +7,7 @@ そのままベジェ(階段は CONSTANT)にする。GameObject の非アクティブは、Unity の階層での子孫にも当てる。 - Transform は Unity のローカルの値をフレームごとに求め、オブジェクトの行列にしてから位置・回転・スケールのキーにする (行列の対応は ``core/model_space.local_basis``)。ボーンを対象にしたカーブは読み込まない(#270)。 -- 対象ごとに、クリップの名前の NLA トラックをミュートで足す。読み込んだ直後の見た目は変わらない。 +- 対象ごとに、クリップの名前の NLA トラックを足す(``nla.add_track``)。既定はミュートで、読み込んだ直後の見た目は変わらない。 """ from __future__ import annotations @@ -34,9 +34,9 @@ from ..core.animation_targets import Binding, TargetObject, TargetTree, bind_paths from ..core.model_space import ModelUnits, local_basis, local_values from ..core.transform import IDENTITY, UNITY_TO_BLENDER, Mat4, inverse_affine -from .fbx_motion import loop_strip from .log import warn_skipped from .model_import import FBX_NODE_PROP, MODEL_GUID_PROP, node_name +from .nla import MODE_ACTIVE, add_track CLIP_GUID_PROP = "unity_clip_guid" # GameObject の行列に、向きや形を足して置いたオブジェクト(Transform のカーブを当てない) @@ -94,7 +94,6 @@ def __init__(self, session, collection: bpy.types.Collection): self.scene = session.scene render = self.scene.render self.fps = render.fps / (render.fps_base or 1.0) - self.frame_start = self.scene.frame_start self.stats = ClipStats() self._units: dict[str, ModelUnits | None] = {} self._tree: TargetTree | None = None @@ -195,21 +194,10 @@ def slot_for(datablock: bpy.types.ID, id_type: str, label: str): bpy.data.actions.remove(action) return "bones" if bones else "none" for datablock, slot in users.items(): - self._add_track(datablock, action, slot, clip.name or entry.name) + add_track(datablock, clip.name or entry.name, action, slot, self.scene, + active=self.session.opts.animation == MODE_ACTIVE, loop=action.use_cyclic) return "loaded" - 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 - nla_strip = track.strips.new(name, self.frame_start, action) - if nla_strip.action_slot != slot: - nla_strip.action_slot = slot - if action.use_cyclic: - loop_strip(nla_strip, self.scene) - track.mute = not active - # 各種のカーブ ------------------------------------------------------ def _frame(self, time: float, clip: AnimationClip) -> float: diff --git a/unitypackage_loader/blender/fbx_motion.py b/unitypackage_loader/blender/fbx_motion.py index 074c9cd..120807d 100644 --- a/unitypackage_loader/blender/fbx_motion.py +++ b/unitypackage_loader/blender/fbx_motion.py @@ -9,22 +9,20 @@ - どのクリップにも使われないテイクの Action は消す。アクティブな Action は外す(読み込んだ直後の見た目を、アニメーションを 読まないときと同じにする)。 - 同じモデルを何度も読む(シーンの配置ごと)ときは、最初に読んだときの Action を使い回し、新しく作られた分は消す。 -- モーションだけのモデル(メッシュが無く、アーマチュアが 1 体)が同じ骨格で並ぶとき(Models 単位)は、アーマチュアを 1 体にまとめて - 全部のトラックを載せる(``merge_motion_rigs``)。 +- トラックの置き方(Active のときのミュート、ループ)は ``nla.py``。モーションだけのモデルのアーマチュアを 1 体にまとめるのは + ``rig_merge.py``。 """ from __future__ import annotations -import math -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 +from .model_import import FBX_NODE_PROP, is_removed +from .nla import MODE_ACTIVE, add_track # Blender の FBX インポーターの anim_offset の既定値(FBX のフレーム 0 を Blender のフレーム 1 に置く) ANIM_OFFSET = 1.0 @@ -32,12 +30,6 @@ 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 @@ -155,7 +147,8 @@ def arrange(self, model_guid: str, pathname: str, info: ModelImporterInfo | None slot = clip.action.slots.get(identifier) if slot is None: continue - self._add_track(owner, clip, slot) + add_track(owner, clip.name, clip.action, slot, self.scene, active=self.mode == MODE_ACTIVE, + frame_range=(clip.start, clip.end), loop=clip.loop) used.add(take) if first_time: self.stats.clips.append(f"{pathname}: {clip.name}") @@ -188,264 +181,3 @@ def _clips(self, info: ModelImporterInfo | None, cached: dict[str, bpy.types.Act continue clips.append(_Clip(setting.name, action, setting.first_frame + ANIM_OFFSET, setting.last_frame + ANIM_OFFSET, setting.loop)) 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) - if clip.loop: - loop_strip(strip, self.scene) - track.mute = not active - - -def loop_strip(strip, scene: bpy.types.Scene) -> None: - """ループするクリップ(Unity の Loop Time)のストリップを、シーンのフレーム範囲の終わりまで繰り返す。 - - NLA はストリップの範囲の外を評価しない(Action の Cycles モディファイアーは範囲の中でしか働かない)ので、繰り返しの回数で表す。 - """ - length = strip.action_frame_end - strip.action_frame_start - if length <= 0: - return - span = scene.frame_end - strip.frame_start + 1 - strip.repeat = float(max(1, math.ceil(span / length))) - - -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_strip.repeat = strip.repeat - 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 125cc9f..5a076bb 100644 --- a/unitypackage_loader/blender/importer.py +++ b/unitypackage_loader/blender/importer.py @@ -39,7 +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 .fbx_motion import MotionBuilder from .log import record_failure, warn_skipped from .model_import import ( FBX_NODE_PROP, @@ -59,6 +59,7 @@ snapshot, vrm_addon_available, ) +from .nla import MODE_NONE from .options import ImportOptions from .prepare import ( BLEND_DISABLED_REASON, @@ -69,6 +70,7 @@ build_shader_table, prepare_package, ) +from .rig_merge import merge_motion_rigs from .scene_objects import ( arrange_collections, find_layer_collection, hide_objects, move_collection_contents, remove_parts, diff --git a/unitypackage_loader/blender/nla.py b/unitypackage_loader/blender/nla.py new file mode 100644 index 0000000..3ce0753 --- /dev/null +++ b/unitypackage_loader/blender/nla.py @@ -0,0 +1,82 @@ +"""読み込んだクリップを NLA のトラックに置く共通の処理(.anim は ``animation.py``、モデルのテイクは ``fbx_motion.py``)。 + +- クリップごとに、クリップの名前のトラックを 1 本足し、ストリップを 1 つ置く。 +- Animation のオプション(Muted / Active / None)が Active なら、対象ごとに最初の 1 本だけミュートを外す。残りはミュート。 +- ループするクリップ(Unity の Loop Time)は、ストリップの繰り返しでシーンのフレーム範囲の終わりまで伸ばす。 +""" + +from __future__ import annotations + +import math + +import bpy + +# Animation のオプションの値(``ImportOptions.animation``) +MODE_MUTED = "MUTED" +MODE_ACTIVE = "ACTIVE" +MODE_NONE = "NONE" + + +def add_track(owner: bpy.types.ID, name: str, action: bpy.types.Action, slot, scene: bpy.types.Scene, *, + active: bool, frame_range: tuple[float, float] | None = None, loop: bool = False) -> bpy.types.NlaStrip: + """``owner`` に ``name`` のトラックを足し、シーンの最初のフレームに ``action`` のストリップを置く。 + + ``active`` は Animation が Active かどうか。そのときでも、ミュートを外すのは ``owner`` の最初のトラックだけ。 + ``frame_range`` は使う Action の範囲(無ければ Action 全体)。``loop`` ならシーンの終わりまで繰り返す。 + """ + animation_data = owner.animation_data or owner.animation_data_create() + # 新しいトラックはミュートされていない状態で作られるので、足す前に数える + unmute = active and not any(not t.mute for t in animation_data.nla_tracks) + track = animation_data.nla_tracks.new() + track.name = name + strip = track.strips.new(name, int(scene.frame_start), action) + if slot is not None and strip.action_slot != slot: + strip.action_slot = slot + if frame_range is not None: + set_strip_range(strip, *frame_range) + if loop: + loop_strip(strip, scene) + track.mute = not unmute + return strip + + +def copy_track(animation_data, track, strip, action: bpy.types.Action) -> None: + """``strip`` と同じ範囲・名前・繰り返しのトラックを ``animation_data`` に足す(Action は ``action`` に差し替える)。 + + 元のトラックがミュートでなくても、``animation_data`` にミュートでないトラックがすでにあればミュートにする。 + """ + 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_strip.repeat = strip.repeat + new_track.mute = track.mute or has_active + + +def loop_strip(strip, scene: bpy.types.Scene) -> None: + """ループするクリップ(Unity の Loop Time)のストリップを、シーンのフレーム範囲の終わりまで繰り返す。 + + NLA はストリップの範囲の外を評価しない(Action の Cycles モディファイアーは範囲の中でしか働かない)ので、繰り返しの回数で表す。 + """ + length = strip.action_frame_end - strip.action_frame_start + if length <= 0: + return + span = scene.frame_end - strip.frame_start + 1 + strip.repeat = float(max(1, math.ceil(span / length))) + + +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 diff --git a/unitypackage_loader/blender/rig_merge.py b/unitypackage_loader/blender/rig_merge.py new file mode 100644 index 0000000..e7751bc --- /dev/null +++ b/unitypackage_loader/blender/rig_merge.py @@ -0,0 +1,225 @@ +"""モーションだけのモデルのアーマチュアを、同じ骨格のものどうしで 1 体にまとめる(#276。Models 単位)。 + +モーション集のパッケージは、モーションごとに FBX が分かれていて、読み込むとアーマチュアがモーションの数だけ並ぶ。 +メッシュが無く、アーマチュアが 1 体で、NLA のトラックを持つモデルを、骨格と置き場所が同じものどうしでまとめ、 +全部のトラックを 1 体に載せる。スキンの無い FBX はファイルの既定の姿勢をレストにするので、レストの違いはキーを変換して吸収する。 +""" + +from __future__ import annotations + +import re + +import bpy +from mathutils import Euler, Matrix, Quaternion, Vector + +from .fbx_motion import TAKE_MODEL_PROP, TAKE_PROP +from .model_import import MODEL_GUID_PROP +from .nla import copy_track + +# keyframe_points の interpolation に foreach_set で渡す LINEAR の値 +_LINEAR = bpy.types.Keyframe.bl_rna.properties["interpolation"].enum_items["LINEAR"].value + + +# 骨格・配置が同じとみなす行列の差 +_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] + + +_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_manifest.toml b/unitypackage_loader/blender_manifest.toml index c6d1550..b3cc4ab 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.13" +version = "1.18.0-dev.14" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio" From 88856242253c84928f9426b5f1127aed846a66be Mon Sep 17 00:00:00 2001 From: utagestudio Date: Fri, 27 Nov 2026 00:59:15 +0900 Subject: [PATCH 23/25] =?UTF-8?q?test:=20Animation=20=E3=81=8C=20Active=20?= =?UTF-8?q?=E3=81=AE=E3=81=A8=E3=81=8D=20.anim=20=E3=81=AE=E3=83=88?= =?UTF-8?q?=E3=83=A9=E3=83=83=E3=82=AF=E3=81=AE=E3=83=9F=E3=83=A5=E3=83=BC?= =?UTF-8?q?=E3=83=88=E3=81=8C=E5=A4=96=E3=82=8C=E3=82=8B=E3=81=93=E3=81=A8?= =?UTF-8?q?=E3=82=92=E7=A2=BA=E3=81=8B=E3=82=81=E3=82=8B=EF=BC=88#281?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit expectations_synthetic_anim_active.json を足した。リファクタ前のコードでは、5 つの対象のすべてで ミュートが外れておらず、このテストが落ちることを確かめた。 Co-Authored-By: Claude Opus 5.5 --- tests/expectations_synthetic_anim_active.json | 24 +++++++++++++++++++ tests/integration_runs.json | 1 + 2 files changed, 25 insertions(+) create mode 100644 tests/expectations_synthetic_anim_active.json diff --git a/tests/expectations_synthetic_anim_active.json b/tests/expectations_synthetic_anim_active.json new file mode 100644 index 0000000..43c2715 --- /dev/null +++ b/tests/expectations_synthetic_anim_active.json @@ -0,0 +1,24 @@ +{ + "options": { + "unit": "MODELS", + "animation": "ACTIVE" + }, + "errors": 0, + "clips": { + "count": 4, + "unmuted": { + "Face": ["Smile"], + "Hat": ["HatOff"], + "Door": ["DoorOpen"], + "Knob": ["DoorOpen"], + "Body": ["Wave"] + }, + "tracks": { + "Face": ["Smile"], + "Hat": ["HatOff"], + "Door": ["DoorOpen"], + "Knob": ["DoorOpen"], + "Body": ["Wave"] + } + } +} diff --git a/tests/integration_runs.json b/tests/integration_runs.json index cb53ba1..f4251f7 100644 --- a/tests/integration_runs.json +++ b/tests/integration_runs.json @@ -46,6 +46,7 @@ { "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_active.json", "note": "Animation が Active なら、.anim のトラックもオブジェクトごとに最初の 1 本だけミュートを外す" }, { "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 なら、オブジェクトごとに最初のトラックだけミュートを外す" }, From 95f5b28f57ab6cdd35fe25f0559fa099b2a4876e Mon Sep 17 00:00:00 2001 From: utagestudio Date: Fri, 27 Nov 2026 00:59:15 +0900 Subject: [PATCH 24/25] =?UTF-8?q?docs:=20nla.py=20=E3=81=A8=20rig=5Fmerge.?= =?UTF-8?q?py=20=E3=82=92=20DESIGN.md=20=E3=81=A8=20CLAUDE.md=20=E3=81=AB?= =?UTF-8?q?=E6=9B=B8=E3=81=8F=EF=BC=88#281=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 ++-- DESIGN.md | 12 +++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 97b30e2..c85d532 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ 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)。 + レストの違いを変換して 1 体のアーマチュアにまとめる(`blender/fbx_motion.py` と `rig_merge.py`。NLA への置き方は両方で `nla.py`。#276)。オプションは Animation(Muted / Active / None)。 ## 設計の要点(詳細は DESIGN.md) @@ -51,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 / fbx_motion / 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 / rig_merge / nla / 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 8d86882..203e7ab 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -663,7 +663,9 @@ 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) +│ ├─ fbx_motion.py # モデルのテイクのクリップへの分割(MotionBuilder。#276) +│ ├─ rig_merge.py # モーションだけのアーマチュアのまとめとレストの違いの変換(merge_motion_rigs。#276) +│ ├─ nla.py # クリップを NLA のトラックに置く共通処理(Active のときのミュート・ループ。#281) │ ├─ log.py # 捕まえて続けた例外のログ(Verbose Console Log はオペレーターが渡す) │ ├─ scene_objects.py # シーンの Empty・ライト・カメラ・複製・行列の当てはめ(計算は core/model_space.py)・非表示 │ ├─ materials.py # ノード生成 @@ -1096,8 +1098,8 @@ def run(ctx, filepath, opts) -> Report: どのオブジェクトのものか決められないので付けない(Medieval Village の風車など。Animator Controller から引けば決められるが、今は読まない)。 - **Action と NLA**(`blender/animation.py`): クリップごとに Action を 1 つ作り(`unity_clip_guid` / `unity_clip_path`)、対象のデータブロック (オブジェクトかシェイプキーの Key)ごとにスロットを作る(Blender 4.4 以降のスロット付き Action)。対象ごとにクリップの名前の NLA トラックを - ミュートで足すので、読み込んだ直後の見た目は変わらない。キーはクリップの開始からの秒 × シーンのフレームレートで、ストリップはシーンの開始フレームに置く。 - ループするクリップ(`m_LoopTime`)は、ストリップの繰り返し(`repeat`)をシーンのフレーム範囲の終わりまでにする(`fbx_motion.loop_strip`)。 + ミュートで足すので(`nla.add_track`。モデルのテイクと共通)、読み込んだ直後の見た目は変わらない。キーはクリップの開始からの秒 × シーンのフレームレートで、ストリップはシーンの開始フレームに置く。 + ループするクリップ(`m_LoopTime`)は、ストリップの繰り返し(`repeat`)をシーンのフレーム範囲の終わりまでにする(`nla.loop_strip`)。 NLA はストリップの範囲の外を評価しないので、F カーブの Cycles モディファイアー(これも付ける。Action を直接再生するとき用)だけではループしない。 - シェイプキー: 値を 1/100 にしてキーと接線をそのままベジェにする。100 を超える重みは `slider_max` を広げる。 - 表示: `hide_viewport` / `hide_render` を階段(CONSTANT)で、値が 0.5 未満なら隠す。`m_IsActive` は Unity の階層での子孫にも当てる @@ -1131,7 +1133,7 @@ Blender の FBX インポーターはテイクごとにテイクの名前の Act ときと同じにする)。Action には `unity_take` / `unity_take_model` を残す。 - **使い回し**: シーンで同じモデルを配置ごとに読み直すときは、最初に読んだときの Action を使い、新しく作られた分は消す。 前の読み込みが失敗して Action が消えていたら作り直す。 -- **アーマチュアのまとめ**(`merge_motion_rigs`。Models 単位): メッシュが無く、アーマチュアが 1 体で、トラックを持つモデルを +- **アーマチュアのまとめ**(`blender/rig_merge.py` の `merge_motion_rigs`。Models 単位): メッシュが無く、アーマチュアが 1 体で、トラックを持つモデルを モーションだけのモデルとし、骨格(ボーンの名前と親の組)が含まれる関係にあり、置き場所(親のワールドの行列)が同じものを 1 体にまとめる。残すのはボーンがいちばん多く、その中で先に読んだもの。 - スキンの無い FBX はファイルの既定の姿勢をレストにするので、レストはファイルごとに違う(32 RPG Animations では指のボーンで @@ -1146,7 +1148,7 @@ Blender の FBX インポーターはテイクごとにテイクの名前の Act アーマチュアの数を `clip_notes` に出す。 - FBX インポーターは、アニメーションを読むかどうかによらずシーンのフレームレートをファイルのものにする(今までと同じ)。 フレームレートの違う FBX を続けて読むと、先に読んだ FBX のモーションの速さがずれる(未対応)。 -- ループ(`loopTime`)は、`.anim` と同じくストリップの繰り返しにする(`loop_strip`。まとめたアーマチュアに写すときも回数を引き継ぐ)。 +- ループ(`loopTime`)は、`.anim` と同じくストリップの繰り返しにする(`nla.loop_strip`。まとめたアーマチュアに写すときも回数を引き継ぐ。`nla.copy_track`)。 ### 4.8 `blender/textures.py` From 3d8df50072093f1713cdd9afb40a889c8935603a Mon Sep 17 00:00:00 2001 From: utagestudio Date: Fri, 27 Nov 2026 01:06:49 +0900 Subject: [PATCH 25/25] =?UTF-8?q?chore:=20=E3=83=90=E3=83=BC=E3=82=B8?= =?UTF-8?q?=E3=83=A7=E3=83=B3=E3=82=92=201.18.0=20=E3=81=AB=E3=81=99?= =?UTF-8?q?=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- unitypackage_loader/blender_manifest.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unitypackage_loader/blender_manifest.toml b/unitypackage_loader/blender_manifest.toml index b3cc4ab..0c1dc3e 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.14" +version = "1.18.0" name = "Unitypackage Importer" tagline = "Import meshes, materials and textures from .unitypackage files" maintainer = "utagestudio"