Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.
Python
Add PEAR live preview with shared runtime support and validation
toyxyzecd72a99203b
diff --git a/.gitignore b/.gitignoreindex 3b50af6..54a808d 100644--- a/.gitignore+++ b/.gitignore@@ -103,3 +103,6 @@ third_party/**/.git/# One versioned, verified native module; models and runtimes remain excluded.!/prebuilt/motion-correction/_motion_correction.cp310-win_amd64.pyd/tools/bin/++# Local temporary shader/kernel caches+/temp/diff --git a/AGENTS.md b/AGENTS.mdindex 09d6a74..c84777b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,7 +10,8 @@ setup from custom builds and requires actual CUDA verification before registerina manually built environment. For optional PromptHMR setup and its separate SAM2build, follow [docs/models/PROMPTHMR.md](docs/models/PROMPTHMR.md).-- This is the Windows Git/CMD distribution. Preserve the separate pinned runtimes and model-specific behavior. `install.cmd` covers ExMR/FlowHMR/GVHMR; MAMMA and PromptHMR remain optional through their separate setup commands. Do not merge their packages or assume `update.cmd` installs them.+- This is the Windows Git/CMD distribution. Preserve the separate pinned runtimes and model-specific behavior. `install.cmd` covers ExMR/FlowHMR/GVHMR and PEAR's small shared-runtime support overlay; MAMMA and PromptHMR remain optional through their separate setup commands. Do not merge their packages or assume `update.cmd` installs them.+- PEAR is a transient single-person bone preview. Selecting it must not start models or modify an offline project. Start/Stop controls the resident worker; see `docs/models/PEAR.md` for fixed bones, Reset Bones, One Euro filtering and World Position. Keep inference and capture off the GUI thread, use bounded latest-frame queues and preserve offline state on exit.- Treat local `models/`, `projects/`, `cache/`, `character_scenes/`, runtime folders, external project folders and registered model data as user-owned. Do not delete, overwrite, upload or migrate them without appropriate user authorization. Ignore rules are not backups.- Preserve inference and selected-result behavior when working on preview, contacts or export. Review the relevant code and validation records before changing numerical processing.- Follow the user's request and perform checks appropriate to the change. Do not claim an inference, import, export, GPU, playback or clean-install test that was not actually run.diff --git a/README.md b/README.mdindex 474d99e..d9afc47 100644--- a/README.md+++ b/README.md@@ -36,6 +36,7 @@ https://github.com/user-attachments/assets/4c0b290b-4a65-4287-8d22-c63c96b3d080```2. Prepare the runtimes for ExMR, FlowHMR and GVHMR with their supported add-ons,+ plus PEAR live-preview support,Blender, FFmpeg and native motion correction. AI weights and registered bodyfiles are downloaded separately in Model Manager:@@ -58,7 +59,8 @@ and recovery.### Optional model runtimes-`install.cmd` prepares ExMR, FlowHMR and GVHMR. Install the following only if+`install.cmd` prepares ExMR, FlowHMR, GVHMR and the small shared-runtime support+for [PEAR live preview](docs/models/PEAR.md). Install the following only ifyou use them, after the base installation:| Model | Separate setup command | Installation and usage |@@ -66,12 +68,16 @@ you use them, after the base installation:| MAMMA | `Setup_MAMMA.cmd` | [MAMMA guide](docs/MAMMA.md) || PromptHMR | `Setup_PromptHMR.cmd` | [PromptHMR guide](docs/models/PROMPTHMR.md) |-Both require **Visual Studio 2022 C++ Build Tools**, the Windows SDK and+MAMMA and PromptHMR require **Visual Studio 2022 C++ Build Tools**, the Windows SDK and**CUDA Toolkit 12.8** for local native builds. Close the app and review theprovider terms before setup. Then reopen it and prepare the selected model's-files in **Model Manager**. Neither optional runtime requires the other;+files in **Model Manager**. Their optional runtimes do not require each other;`install.cmd` and `update.cmd` do not install them.+PEAR reuses the base shared runtime with a small support overlay prepared by+`install.cmd` and `update.cmd`. No separate setup or compiler is required.+Model files are prepared separately.+### Install with an AI agentAfter cloning, open this repository folder in a local coding agent such as Codex.@@ -116,6 +122,7 @@ do not put passwords or account tokens in the agent chat.- Export source animation as FBX; export characters as FBX with or without meshes,or PMX character motion as VMD for MMD.- Save projects with separate results for each AI model.+- Preview one person's live body/finger bones from a webcam or video with PEAR.## How it works@@ -130,6 +137,10 @@ do not put passwords or account tokens in the agent chat.3. Review the motion, edit contacts if needed and **Apply Correction**.4. Export FBX, or import a character, retarget the motion and export it.+For **PEAR · Live**, choose a webcam or open a video, then click **Start Live+Tracking**. It provides a bone preview without recording, correction or export.+See the [PEAR guide](docs/models/PEAR.md) for its controls.+## Supported AI modelsIn our subjective tests, **PromptHMR** could improve relative placement and@@ -138,6 +149,7 @@ motion quality was lower than **ExMR**. It does not support finger tracking.| Model / original project | Body representation | Fingers | Setup and use || --- | --- | --- | --- |+| [PEAR](https://github.com/Pixel-Talk/PEAR) · live preview | SMPL-X / FLAME | Included | [PEAR guide](docs/models/PEAR.md) || [ExMR](https://github.com/twehrbein/ExMR) | SMPL-X | Included | [ExMR guide](docs/models/EXMR.md) || [FlowHMR](https://github.com/flowhmr/flowhmr) | SMPL-H | Included | [FlowHMR guide](docs/models/FLOWHMR.md) || [GVHMR](https://github.com/zju3dv/GVHMR) | SMPL-X | Optional HandFlow add-on | [GVHMR guide](docs/models/GVHMR.md) |@@ -147,8 +159,8 @@ motion quality was lower than **ExMR**. It does not support finger tracking.Requires 64-bit Windows, a compatible NVIDIA GPU/driver and OpenGL 4.3.Model files are acquired separately; some require registration and license acceptance.-**Installed models and runtimes:** approximately **67.8 GB (63.1 GiB)** for all-five models, including supported add-ons, Blender and FFmpeg. Measured without+**Installed models and runtimes:** approximately **67.8 GB (63.1 GiB)** for the+five offline models, including supported add-ons, Blender and FFmpeg. Measured withoutprojects, caches or retained downloads; shared files are counted once.| Configuration | Runtime | Models | Total |@@ -156,7 +168,11 @@ projects, caches or retained downloads; shared files are counted once.| ExMR + FlowHMR + GVHMR and supported add-ons | 12.35 GiB | 28.89 GiB | 41.23 GiB || MAMMA additional files | 6.11 GiB | 3.42 GiB | 9.54 GiB || PromptHMR additional files | 6.22 GiB | 6.13 GiB | 12.34 GiB |-| **All five** | **24.68 GiB** | **38.44 GiB** | **63.11 GiB** |+| **Five offline models** | **24.68 GiB** | **38.44 GiB** | **63.11 GiB** |+| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.84 GiB | ~2.84 GiB |++Including PEAR, the estimated combined model/runtime total is about+**65.95 GiB (70.8 GB)**, before the additional space listed below.**MAMMA and PromptHMR require separate runtime installation:** run`Setup_MAMMA.cmd` or `Setup_PromptHMR.cmd` after `install.cmd`, as describeddiff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.jsonindex 60ade52..cfca105 100644--- a/SOURCE_MANIFEST.json+++ b/SOURCE_MANIFEST.json@@ -1,6 +1,6 @@{"schema": 1,- "date": "2026-10-31",+ "date": "2026-11-01","purpose": "Public source distribution; excludes model weights and runtime binaries","version": "git-source","files": [@@ -11,13 +11,13 @@},{"path": ".gitignore",- "bytes": 1877,- "sha256": "885bad850728a9c5d36ec98f000c0b6ee345975b8f03cad5ec167cba052f4f7d"+ "bytes": 1927,+ "sha256": "8ca92bc1dfe6b6bd5ebb3188701d11598dfaa99921ee50e068c192b82e837433"},{"path": "AGENTS.md",- "bytes": 1725,- "sha256": "6c015334a19a12ed2016402e7f21337bafdb5dffd31689c159f13a44aaa5e852"+ "bytes": 2139,+ "sha256": "b365e79eb890dbd5ea081274462b2170d0226973a4ac15e1828789e3b23585a1"},{"path": "LICENSE",@@ -26,8 +26,8 @@},{"path": "README.md",- "bytes": 9175,- "sha256": "e5cf105de43e78a691c2e224e1e996596a2d4803bfd4f375b25ec2b02a9d48f8"+ "bytes": 10187,+ "sha256": "3724de7094cde62a721598faffbfe1f7e063f5f01794129581d5e5a45e92a79d"},{"path": "RGBMoCap.cmd",@@ -46,8 +46,8 @@},{"path": "THIRD_PARTY_NOTICES.md",- "bytes": 7813,- "sha256": "37d98687a35d0ff41887e6895d96665c4ccc5f49386da2beac1247693cf1a3b2"+ "bytes": 8568,+ "sha256": "fdab2c03d661bd7cefc11c180a4d3f298beaa50d2ff012848d5c7ae3997bbf89"},{"path": "app.py",@@ -96,18 +96,18 @@},{"path": "docs/AGENT_GUIDE.md",- "bytes": 29976,- "sha256": "004b31957d249f0f4d02418d05fdc8c0744860fb7a738c02b70e1fb3e758722c"+ "bytes": 38876,+ "sha256": "02a866bd8c217360d9e71887bfe1008d12f5b3bf144357b745ca87087fdea7e3"},{"path": "docs/BUILD.md",- "bytes": 10223,- "sha256": "e14bd8897b0e567cc443ebdd295f6e0290157ef986bc9a44ce46d840136d2cf6"+ "bytes": 11607,+ "sha256": "ff2c901d948748e6d477127418b6f5c227d64d509bde5d7eb7f1145e4697fa0a"},{"path": "docs/CITATIONS.md",- "bytes": 4728,- "sha256": "ec3cc48f24a300793c76f15b43b3596452c8d155a8b0fbba6435e84bc40a6be0"+ "bytes": 5656,+ "sha256": "ecc6c91a14a4dbf91677c2b0833e3744d37afc0069f46af3c64860cbce02cd4c"},{"path": "docs/MAMMA.md",@@ -121,18 +121,18 @@},{"path": "docs/PERFORMANCE.md",- "bytes": 13717,- "sha256": "607e9be394e7b8b3f9c2e818106de238a469eb71db9b519da2ba9ddc13a0cd6c"+ "bytes": 14223,+ "sha256": "55951143f07abd21f5fbe7c2f26e12278fcfaaf41334048fbedb1ad7449a42b9"},{"path": "docs/USER_GUIDE.md",- "bytes": 43482,- "sha256": "acf893a4721fb344b72069c72173d5d9c9f8a1cd496bd9e5d959c7f0ffa3256f"+ "bytes": 45953,+ "sha256": "1edebd2e80c44b5954675fe953173e351a5e3f402edab15b10173cc0439714ec"},{"path": "docs/VALIDATION.md",- "bytes": 51629,- "sha256": "6bc4706d45cdb0e767d1942722630b60e21a5d4e196eb1da0176d65168f07537"+ "bytes": 85264,+ "sha256": "030f68f98c92efc1003635bfe060ec184596bff8b885f5e77a7b5bbd9792319e"},{"path": "docs/images/exmr-interaction-contact.png",@@ -169,6 +169,11 @@"bytes": 5915,"sha256": "a43b89cde13e9168431177655c9678a37cc74219436e055066b01137276ca09e"},+ {+ "path": "docs/models/PEAR.md",+ "bytes": 11649,+ "sha256": "3ac4f37547c15e48bba444514ec4d59204e2c72bed4c5dc51dbe46a93de16554"+ },{"path": "docs/models/PROMPTHMR.md","bytes": 14194,@@ -176,8 +181,8 @@},{"path": "docs/models/README.md",- "bytes": 5314,- "sha256": "ac431b998af10dcc14f14efba897f9b7d64e955e22800123d79e14dbf1f48599"+ "bytes": 5892,+ "sha256": "07e197c0203bd6a006d809d76e500fd0f190beefc26274fc3d11a6896dce59aa"},{"path": "docs/samples/character-retargeting.jpg",@@ -284,6 +289,21 @@"bytes": 3725,"sha256": "bbea620bc10c7d922720096a2f19892f8dbaadae17a03a4a25b61691a6a5141b"},+ {+ "path": "installer/pear-assets.json",+ "bytes": 5612,+ "sha256": "63cd9ea4220325a328ae5df16d6ceda09c21aaf41ecb8bce48dd2d9cb88ace05"+ },+ {+ "path": "installer/pear-sources.json",+ "bytes": 941,+ "sha256": "ecc22855b65fa68c547f9ef9a3ae3f46966c8a5263ae22892b2544a8e32bcf0f"+ },+ {+ "path": "installer/pear_adapters.py",+ "bytes": 1743,+ "sha256": "f36fb1d7d563cbb15d8effb377470559757b92f5d5e1cbe876bf4f6f7cbf7e54"+ },{"path": "installer/prompthmr-runtime-lock.json","bytes": 85747,@@ -1271,8 +1291,8 @@},{"path": "mocap/gui.py",- "bytes": 99319,- "sha256": "7baade822f55353d9402cb72a2d978448586a52e657e2133f8f8939e65b741c1"+ "bytes": 100901,+ "sha256": "5c994e4750e8ada6d23dbf76a13e9434d29c7b1bede9ec6fd10edc9bbd76e2cc"},{"path": "mocap/gvhmr_attention.py",@@ -1391,8 +1411,8 @@},{"path": "mocap/model_guide.py",- "bytes": 7377,- "sha256": "4c2007d61fe00cc8cb4600c00776ac251b868820c9225ff137583cecd1efe6e2"+ "bytes": 9200,+ "sha256": "9d3c46b118eba16d1c514b17509513d5b508d50fc6fa5edcbb3a3c39cbbfbe76"},{"path": "mocap/model_session.py",@@ -1401,13 +1421,13 @@},{"path": "mocap/models.py",- "bytes": 30979,- "sha256": "d97a6398a1dde3577bb37f0627a8666d48412e93ef9009f3033cd4b4ddd9e1e1"+ "bytes": 31459,+ "sha256": "197eb545df73c7d4027696de69c96acea369411f87c1285e5ebeb82c436a1ca2"},{"path": "mocap/motion_tools.py",- "bytes": 10708,- "sha256": "129eb449bfedc3912abd9945339c4d1e3d6bbf79e50e434161c4a9120052a2af"+ "bytes": 11043,+ "sha256": "7c74a02b8417618385aaa349c3d04d6f506139952fd3dcc62a8fe42f735ae48f"},{"path": "mocap/multilevel_contacts.py",@@ -1429,6 +1449,96 @@"bytes": 976,"sha256": "df9985bcf6265b1369374630a48de77a8704cba20658c2d826bca5443b66ef05"},+ {+ "path": "mocap/pear/__init__.py",+ "bytes": 50,+ "sha256": "1a03adf39b6c1e6dbe0e4f8423142ef33b173d863b17b4bb0d70a39f75c82f97"+ },+ {+ "path": "mocap/pear/acceleration.py",+ "bytes": 4050,+ "sha256": "fb59a655440bd0f2faddddbb776fe1bdb1d635c961e02c08615810b874651e53"+ },+ {+ "path": "mocap/pear/bone_roll.py",+ "bytes": 6416,+ "sha256": "f3027754de5f0dd9c6d456f28570ec8a960d291f8feda87c996288f28a9eda23"+ },+ {+ "path": "mocap/pear/core.py",+ "bytes": 9245,+ "sha256": "f740a7b4c9e96cd9d84a86b7b4976ff90a19a5cc634b50a92afefbea64013930"+ },+ {+ "path": "mocap/pear/fixed_rig.py",+ "bytes": 4919,+ "sha256": "419dad6e47bf7428902ec877095b5edb69ba8ee6636d74b18bae0d8ff829915e"+ },+ {+ "path": "mocap/pear/geometry_compat.py",+ "bytes": 1974,+ "sha256": "b3ca498bc0cb9d01b9003f8354fed69c74107ef04d1c5a599cbc4db69b4c0d2e"+ },+ {+ "path": "mocap/pear/input_transform.py",+ "bytes": 1011,+ "sha256": "fd0378f1bb9face1b52a05f24f32a5dc5a2cea99311ccef3b88ebffe3757f9d5"+ },+ {+ "path": "mocap/pear/live_view.py",+ "bytes": 3998,+ "sha256": "cf7606a417d0e174a61ff65aa42c7efbd2b9cbab870948543855b774d17136c6"+ },+ {+ "path": "mocap/pear/parameter_io.py",+ "bytes": 1631,+ "sha256": "5016f8d89534dd7e0e62fa7592be662f898c2bb9b40216d4cfb4eab97eb16a05"+ },+ {+ "path": "mocap/pear/preview_bones.py",+ "bytes": 982,+ "sha256": "0c23556d900b626117e59e2a9644b4b087aab9bbca6c7fd5f2107a7f2c5fe1f8"+ },+ {+ "path": "mocap/pear/projection.py",+ "bytes": 3782,+ "sha256": "01e7cc11b58b9615e4ec2ce4ce429d57f98a0d7040fcc41937cf78be03cca6f4"+ },+ {+ "path": "mocap/pear/session.py",+ "bytes": 3216,+ "sha256": "1276c11df0d5d83115d643edae98596a0c557964608e6b7f020d87a3bf9f0eba"+ },+ {+ "path": "mocap/pear/temporal_filter.py",+ "bytes": 5059,+ "sha256": "af829508790c84edc732808dcd6dd97175a508fdd9cdbdf77c75d4af74aca08a"+ },+ {+ "path": "mocap/pear/wire.py",+ "bytes": 4666,+ "sha256": "8e0cc9cafdc374c5dcad0621357456e30f75341449c0ca6f07a9d9ba313d1f0a"+ },+ {+ "path": "mocap/pear/worker.py",+ "bytes": 12549,+ "sha256": "60f325208c2224d25b273258e2f1a4cba683625d4f16d9d31ae3c348ac761709"+ },+ {+ "path": "mocap/pear_models.py",+ "bytes": 4863,+ "sha256": "b620d9eb9333a15706daaccd343a8dac851098c4324b7da5ee8ef2c8445d1f62"+ },+ {+ "path": "mocap/pear_runtime.py",+ "bytes": 2220,+ "sha256": "fd1943cea020f15bf29b91412cb382d236f8461a44ea761d6ffedb0859dd81ed"+ },+ {+ "path": "mocap/pear_ui.py",+ "bytes": 29232,+ "sha256": "670920bf957604bb9f721dbbce8a7658d865693d77a109fb1a54e922cc70563c"+ },{"path": "mocap/people_store.py","bytes": 4171,@@ -1496,13 +1606,13 @@},{"path": "mocap/project_workspace.py",- "bytes": 3580,- "sha256": "fef3a4d21040f912636f2797206391e40ea272c76a9556297c973563cbc3559f"+ "bytes": 3604,+ "sha256": "7e9463a0c2f62025f59d29c7eefb3e01cda488613d0d8c22c3d10e8a66eead97"},{"path": "mocap/project_workspace_ui.py",- "bytes": 10000,- "sha256": "bb3c0ee2b37e47c583938c0f93d764a09bdda8340be0efb75bbb34297d92708e"+ "bytes": 10053,+ "sha256": "9763cff6b9940a69fd93f043a726f9b8384375951e4830877ce5f9507b37f8bb"},{"path": "mocap/prompthmr_manager.py",@@ -1766,8 +1876,8 @@},{"path": "mocap/timeline_editor.py",- "bytes": 14421,- "sha256": "b58f80a159b55d5352ec1a56c708b66fe45350acc3aafa319e1fbdbd1346f4c7"+ "bytes": 14529,+ "sha256": "57e36aa035cbaa21368f53d4748b8e14bef745d3c3b638f8bcea7b4a5196d35c"},{"path": "mocap/tooltips.py",@@ -1796,13 +1906,13 @@},{"path": "mocap/viewer.py",- "bytes": 9793,- "sha256": "13b3eb7e9bb32ab46a1bec6d18fd87ee7d1ab54cafd57209a1aa118d068f1381"+ "bytes": 10547,+ "sha256": "d0e0011b4580d2413f65b59d59216e5aadf0cb86a86afbccd51b7b533975bc87"},{"path": "mocap/viewport.py",- "bytes": 50029,- "sha256": "1ae0103991357d6db1cfe09a5c0ee4003d3b63b38cf2a7037ed2c10ad5430f11"+ "bytes": 52101,+ "sha256": "d34193b8f8119014ebcd2f88f6fa84a8b83e9eaa7671f8c871656c6f18c48ef7"},{"path": "mocap/worker.py",@@ -1811,13 +1921,13 @@},{"path": "mocap/worker_progress.py",- "bytes": 1847,- "sha256": "a151f9c27c9f9f2a34d8a2ec1370f69c16f1f8fbf5b8daf3e5ff3b8cf3df9f90"+ "bytes": 1952,+ "sha256": "3ffc6fba68cd26a6a733ce0f7d58b9ee0b34b33756492769cfe4dab2bf9cdbe0"},{"path": "mocap/workspace_ui.py",- "bytes": 35992,- "sha256": "36347af70ded4ec5317e563ea24c48cca8f2654516c8a83a0539e97a359c2533"+ "bytes": 36159,+ "sha256": "e31dc3e99adb6fd84bf6c36e4b6a9436b3182e550822deeba1efafd62ee3ae92"},{"path": "native_compat/LICENSE",@@ -12511,8 +12621,8 @@},{"path": "tools/check_source.py",- "bytes": 3951,- "sha256": "92397f4f48fbd4f8ce0ae8df40ae9042706d9964d2a31ef28bf5db663906435c"+ "bytes": 3971,+ "sha256": "2c65548b8abe5d4893c191a7caaea03076b17ab5f6bed26235af3143ac60106e"},{"path": "tools/configure_mamma.py",@@ -12531,8 +12641,8 @@},{"path": "tools/git_managed_install.py",- "bytes": 5606,- "sha256": "b4e5826a9dca0f91cc2d78c054782608cac4f264c1b3a8902fdf11d788ea2307"+ "bytes": 5686,+ "sha256": "e3f6cbe11315e1a6624e4d91febd2a697ebc7f9196a616b7321b4173df94bca9"},{"path": "tools/git_transaction.py",@@ -12569,6 +12679,11 @@"bytes": 14090,"sha256": "783731563bc03da8302d0a6bf2c2d433232b3d76f06a61063e56511d42fe076f"},+ {+ "path": "tools/setup_pear.py",+ "bytes": 4947,+ "sha256": "ff9be39a046f9afa0c083cd0afc175ccde0e2241ea1e6eb1b692230b262e73bc"+ },{"path": "tools/setup_prompthmr.py","bytes": 9016,diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex a707303..6a7f382 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -53,7 +53,7 @@ Other runtime packages retain their included licenses. Supporting notices includGVHMR notices. Follow the upstream publication/citation instructions, includingWehrbein and Rosenhahn (ExMR, arXiv:2610.26213; FootMR, 3DV 2026),and the original GVHMR work. [Papers and BibTeX](docs/CITATIONS.md) cover- the five supported motion models and optional refinement models.+ the supported motion models, PEAR live preview and optional refinement models.- Kimodo MotionCorrection: copyright 2026, NVIDIA Corporation & Affiliates.Local changes add explicit contact targets, bounded solving and anatomical guards.- OSNet: Kaiyang Zhou; original MIT notices and model-zoo provenance are retained.@@ -71,3 +71,15 @@ permissions are not waived by separate worker processes or separate labeling.Keep original notices and any required corresponding source/build materials whendistributing. The private development folder may contain registered models,derived caches and user projects; it is not a cleared public release package.++## Optional PEAR live support++[PEAR](https://github.com/Pixel-Talk/PEAR) source uses Apache-2.0. Setup fetches a+pinned upstream revision and preserves its license with the locally adapted+source. The connector omits unused training/render imports, uses native Torch+constructor helpers and reuses the shared runtime. PyTorch3D pure-Python utilities+retain their upstream BSD license/notices; RoMa retains its package license.+YOLOv8s/Ultralytics retain their existing AGPL/provider terms. PEAR weights,+SMPL-X 2020 and FLAME geometry retain separate provider conditions; registered+body data is neither committed nor redistributed by RGB MoCap. See the+[PEAR guide](docs/models/PEAR.md) and [PEAR paper citation](docs/CITATIONS.md#pear).diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.mdindex 5ee7b0e..4b4b560 100644--- a/docs/AGENT_GUIDE.md+++ b/docs/AGENT_GUIDE.md@@ -5,11 +5,11 @@ This guide is for agents helping users operate or modify RGB MoCap. It describes## Start and update- Windows 64-bit, compatible NVIDIA GPU/driver and OpenGL 4.3 are required for the documented inference workflow. Other systems and GPUs were not comprehensively verified; see [validation](VALIDATION.md).-- In a writable checkout, run `install.cmd` once. It sets up separate pinned profiles for ExMR, FlowHMR and GVHMR and their supported add-ons, Blender 4.5, FFmpeg and the prebuilt native motion-correction module. It does not install only the selected model's runtime or obtain AI weights/body data. Downloading and disk space are required. Models are obtained separately; optional MAMMA uses Setup_MAMMA.cmd and PromptHMR uses Setup_PromptHMR.cmd.+- In a writable checkout, run `install.cmd` once. It sets up separate pinned profiles for ExMR, FlowHMR and GVHMR and their supported add-ons, PEAR support over the shared runtime, Blender 4.5, FFmpeg and the prebuilt native motion-correction module. It does not install only the selected model's runtime or obtain AI weights/body data. Downloading and disk space are required. Models are obtained separately; optional MAMMA uses Setup_MAMMA.cmd and PromptHMR uses Setup_PromptHMR.cmd.- Run `RGBMoCap.cmd`. Keep its command window open; launch errors, processing messages and app Console output are also sent there, but long messages can be truncated and a saturated output queue can drop messages. Within the GUI, **Help > Check System** checks the system.- Close the app before `update.cmd`. The updater requires a clean tracked worktree and the `main` branch, uses `git pull --ff-only`, then verifies/repairs runtime configuration. It refuses tracked local edits. A plain `git pull` does not perform runtime repair; use `install.cmd` after dependency changes when needed. Do not discard local edits or force an update.- For setup failure, read the message, check connectivity and free space, then retry `install.cmd`. Preserve models, projects and `.setup` state. Do not repeatedly reinstall or redownload models without evidence.-- Base installation currently estimates at least 32.4 GiB free before models; ExMR/FlowHMR/GVHMR and add-ons were previously measured around 29 GiB of weights. Optional MAMMA and PromptHMR add separate runtimes and model files; see [MAMMA](MAMMA.md) and [PromptHMR](models/PROMPTHMR.md). All five model/runtime sets total about **63.11 GiB (67.8 GB)** excluding caches, projects, downloads and compiler tools, counting shared files once. See the [installed-size table](USER_GUIDE.md#installed-size); installed size and temporary setup headroom are different. Measurements are not guarantees.+- Base installation currently estimates at least 32.4 GiB free before models; ExMR/FlowHMR/GVHMR and add-ons were previously measured around 29 GiB of weights. Optional MAMMA and PromptHMR add separate runtimes and model files; see [MAMMA](MAMMA.md) and [PromptHMR](models/PROMPTHMR.md). The five offline model/runtime sets total about **63.11 GiB (67.8 GB)** excluding caches, projects, downloads and compiler tools, counting shared files once. See the [installed-size table](USER_GUIDE.md#installed-size); installed size and temporary setup headroom are different. Measurements are not guarantees.Multi-person reconstruction groups supported ExMR, FlowHMR and GVHMR phasesinto sequential, bounded worker requests. `mocap/queue_groups.py` builds the queue;@@ -64,6 +64,7 @@ are unchanged. See [validation](VALIDATION.md#exmr-public-api-and-bounded-toe-ik| GVHMR | Lower overall quality in those tests but sometimes better for unusual poses such as backflips. SMPL-X. | Fingers via optional HandFlow. HTD refines body motion; FootMR refines ankles. Both are separate from contact correction. || MAMMA | Optional multi-view SMPL-X capture from two or more synchronized fixed cameras, without a fixed camera-count maximum. Practical capacity depends on RAM/VRAM. Not part of the single-video quality ranking. | Fingers included; separate setup and locked-head body assets. VGGT or compatible manual calibration. || PromptHMR | Multiple people reconstructed jointly from one video; can improve relative placement and interactions. Overall motion quality was lower than ExMR in our subjective tests. Fixed-camera Windows path, up to eight people; placement can still be wrong. | No finger tracking; fixed neutral fingers. Setup_PromptHMR.cmd; People defaults to 2, Interaction Prompt on. |+| PEAR | Live single-person bone preview from a webcam or the video timeline; transient, with no recording/export or contact correction. | Fingers included; Start/Stop, fixed lengths/Reset Bones, One Euro filter, Rotation and default-on World Position. Shared support is installed by install.cmd. |Start with the [model guide index](models/README.md), then [ExMR](models/EXMR.md), [FlowHMR](models/FLOWHMR.md), [GVHMR](models/GVHMR.md), [MAMMA](MAMMA.md) or [PromptHMR](models/PROMPTHMR.md) for exact setup and controls. The [user guide](USER_GUIDE.md#recorded-processing-time-and-vram) includes observed timings, conditions and VRAM; these are historical measurements, not minimum specifications. FlowHMR has a 5,000-frame per-take limit and available memory may require less. MAMMA retains its 4–1,800-frame common trim and eight-person limits; there is no fixed camera-count maximum. Four-column thumbnails are a layout, not admission control. Do not change numerical precision, temporal context or model settings merely to improve a benchmark.@@ -73,7 +74,7 @@ Use **Model Manager** for the selected model and add-ons. Automatic download may| Command | Scope | Additional prerequisites || --- | --- | --- |-| `install.cmd` | Base GUI, ExMR/FlowHMR/GVHMR and supported add-ons, Blender, FFmpeg, native correction | See the base installation guide; no PromptHMR/MAMMA native build |+| `install.cmd` | Base GUI, ExMR/FlowHMR/GVHMR and supported add-ons, PEAR shared support, Blender, FFmpeg, native correction | See the base installation guide; no PromptHMR/MAMMA native build || `Setup_MAMMA.cmd` | Optional independent MAMMA runtime | VS 2022 C++ tools/Windows SDK, CUDA Toolkit 12.8, provider license review || `Setup_PromptHMR.cmd` | Optional independent PromptHMR runtime | Same build tools, separate provider license review; MAMMA/SDF not required || `update.cmd` | Source update and base runtime verification | Close the app and preserve tracked edits; it does not install the optional runtimes |@@ -268,3 +269,121 @@ The app uses separate runtime profiles to maintain compatibility, with bounded b- Installation/update: `install.cmd`, `update.cmd`, `tools/git_bootstrap.ps1`, `tools/git_managed_install.py`, `tools/git_update.py`, `installer/runtime-lock.json`. Native correction source/build instructions: [developer-build/motion-correction](../developer-build/motion-correction/README.md).Inspect [BUILD.md](BUILD.md), [VALIDATION.md](VALIDATION.md) and relevant code before edits. The developer `.venv` workflow is separate from ordinary Git/CMD installation. Run targeted checks for modified behavior; real model inference, real GPU use, Blender/MMD import and clean-install compatibility must only be reported when actually tested. This public checkout may not include private regression tests or licensed assets.++## PEAR live mode++Close the app and run `install.cmd`. The base installer also downloads+pinned source, pure-Python PyTorch3D utilities and RoMa into `runtime_pear/`,+validates CUDA kernels, and preserves the shared runtime packages. Do not install+a second Torch, upgrade global NumPy/timm/Ultralytics or compile PyTorch3D.+Import the PEAR checkpoint and original registered geometry ZIP using Model+Manager. Standard SMPL-X v1.1 and MAMMA locked-head files are incompatible with+PEAR's SMPL-X 2020/FLAME bundle. Read [PEAR](models/PEAR.md) first.+No separate PEAR setup command is required. `update.cmd` uses the same installation+flow and repairs support when its source or shared-runtime group changes; matching+verified generations are reused. Model weights/body data remain manual or Model+Manager downloads. MAMMA and PromptHMR still use their separate setup commands.++This is a transient single-person preview, not a saved offline project model.+`None` in the webcam selector uses video timeline frames; a named camera selects+the webcam input. Neither loads models until Start Live Tracking is pressed. No recording, Find person, contact correction, retargeting or+export is available. Preserve offline projects and camera views when switching.+Keep requests and output mailboxes bounded/latest-only, run native imports and+warmup before the Windows blocking stdin reader, and release only the worker+and device owned by this session. Never kill another camera application.+Registered assets and test captures must remain ignored and unpublished.++PEAR is accepted in the tool selector but rejected as a saved offline model,+including workspace active/member identities. Never create or relabel a project+as PEAR. Source/adaptation pins are in `installer/pear-sources.json`; setup retains+upstream licenses, marks changed files and writes `RGB_MOCAP_PROVENANCE.json` in+the private support generation. Its receipt hashes the support-defining source+bytes: preserve line endings and `.gitattributes`, and rerun installation for a+real adapter change instead of editing receipts. The [PEAR citation](CITATIONS.md#pear)+and [detailed guide](models/PEAR.md) distinguish upstream research from the+application's fixed-length display, filtering and position controls.++PEAR's selected-tool state and running state are separate. Selection, video open,+webcam selection, seeking and settings edits must not create a model worker while+stopped. Start Live Tracking explicitly enables loading/warmup and tracking;+the same button becomes Stop immediately, including during loading. Stop+invalidates pending output, stops playback and closes only this session's worker,+capture and GPU data off the GUI thread. Disable Start until the old worker exits;+never overlap workers or automatically restart after Stop/error/leave/reselect.+A new Start loads a fresh worker. While running, input changes reuse its model.+PEAR alone uses the pinned YOLOv8s asset (`pear_yolo`, `models/yolo/yolov8s.pt`).+Keep its size/hash-checked Model Manager download/import and trusted loader.+Do not replace the shared YOLOv8x asset used by offline models. Detector boxes+can alter pose predictions; detection success is not an accuracy measurement.+Idle acknowledgement keeps a deliberately waiting started worker from appearing+stalled. Keep RAM/VRAM monitoring and bounded mailboxes while it is running.++During PEAR video playback, present each completed image/pose pair together,+accepting monotonically newer results within the current source/seek epoch.+Never require a playing result to equal the newest outstanding request: inference+latency would discard it indefinitely. Preserve the last pair until its replacement.+Manual seeks, loops and pause invalidate old epochs; paused seeks require the exact+request. Keep the request clock separate from the actual displayed frame. The+ordinary decoder is suspended during paired presentation, including exact paused+inference, and resumes after Stop or leaving PEAR.++PEAR live mode now uses `mocap/pear/fixed_rig.py`: fixed-length physical FK pivots,+each bone's own predicted rotation and constant neutral axes. Initial calibration+and **Reset Bones** use a resident CPU EHM model once; ordinary live frames do not+skin a body mesh, regress mesh joints or evaluate animated surface-roll evidence.+Neutral knee/elbow patches and the neutral foot-width basis remain calibration+references only. Never use an animated bend plane or the child rotation to select+incoming upper-limb/foot roll. Fixed FK pivots differ from the previous skinned+landmarks; do not claim identical mesh registration or ground-truth accuracy.+The Bone Overlay checkbox changes drawing only, not inference or calibration.++Calibrate once on the first valid frame of a new input; preserve that rig across+seeks, filter changes and temporary missing detections. Reset Bones is enabled+only with a displayed pose. It pauses video at the displayed frame and sends its+pose ID, not the outstanding playback request. The worker keeps at most 32+parameter-only references (no video/mesh history) and refuses an expired reference+without silently calibrating another pose. Webcam reset also uses that displayed+pose ID. Publish a complete calibration atomically; failure retains the old rig.+Reset must preserve the model process, placement origin and viewport camera.+Frames carry a rig revision; replace bound bone geometry only on a new revision.+Clear references on input/rotation changes, and disable Reset while stopped or+pending. Registered body data are still required for calibration; this does not+remove the geometry download requirement or imply zero startup cost.+Toe terminal tips use each foot's neutral sagittal centreline, not a big-toe+surface point. Preserve terminal length and vertical pitch, native toe pivots,+predicted rotations and other bones. Recompute only this constant calibration+on initial input/Reset Bones; do not aim toes at a world axis each live frame.++PEAR's default-on **World Position** checkbox controls translation only. Off+anchors all three pelvis coordinates to the displayed position (or first valid+pose if disabled before Start). Keep pelvis/bone rotations and relative pose+unchanged. `pear_ui.py` retains one raw worker packet and translates only bounded+preview points/bounds; never mutate that packet, reset filters/rig, submit extra+inference or reload the model for this switch. Use a bounded render key to refresh+paused output immediately. Reset Bones keeps the anchor; a new input or Stop+clears it and releases the cached pose. On restores the raw estimated position,+so a position change is expected. This is pelvis locking, not foot locking.++PEAR's **One Euro Filter** and **Rotation** apply to webcam and video inputs. Rotate+pixels before detection/inference, then display the matching rotated image even+when paused. Source files are never rewritten. Smoothing is a causal adaptive+parameter filter on rotations/shape/face plus a vector-speed root filter; it changes+the live pose intentionally. Rotations use shortest geodesic interpolation with+bounded speed-dependent cutoff, not entrywise matrix averages or vertex blending.+Use actual source timestamps for skipped playback frames. Infer each requested+frame once: do not restore historical pre-roll inference on seeks, loops or gaps.+A discontinuous seek seeds the filter with its own prediction; subsequent streaming+is smoothed. Parameter filtering is batched across rotations/scalars; uniform FP32+pose/face tensors use one packed CPU transfer and one packed GPU upload. Retain the+generic dtype/device fallback, raw parameters and valid rotation matrices.+Filter Strength ranges from 1 to 100; 50 preserves the prior coefficients. Higher+values lower all adaptive cutoffs and slopes together. Strength-only changes keep+filter history, placement origin, identity, camera and resident model.+Reset temporal state on missing people, input/rotation/enable changes, reverse time or+long gaps; preserve the existing placement origin during same-source seeks.+Retain the last matched image/pose while a seek, pause or smoothing toggle computes+its replacement; clear it for a real missing-person result, error or changed input.+A smoothing-only toggle must not reopen capture, reacquire identity, reframe the+camera or reset the placement origin. It is not an offline full-sequence smoother+or a guarantee of identical live/seek history.+Keep the one resident model, latest-only controls and fixed memory bounds.diff --git a/docs/BUILD.md b/docs/BUILD.mdindex dfee5ce..83e4a7a 100644--- a/docs/BUILD.md+++ b/docs/BUILD.md@@ -183,3 +183,25 @@ preserves the old pointer. Setup stages first and checks again after relocation.Changing the optional lock/adapters invalidates this runtime only: the UI requests`Setup_MAMMA.cmd`, while other models and saved results stay available. Keepprivate benchmark scripts, logs and derived models outside the source checkout.++## PEAR support++`install.cmd` and `update.cmd` prepare PEAR support with `tools/setup_pear.py`+after committing the base shared Python/Torch runtime. The helper runs under the+installer's existing application lock; it must not acquire that lock a second time.+It prepares pinned+upstream PEAR source and pure-Python support in `runtime_pear/`, rather than+changing base dependencies. No native PyTorch3D build is used. Source URLs and+hashes are in `installer/pear-sources.json`; explicit import adaptations are in+`installer/pear_adapters.py`. Geometry imports use `installer/pear-assets.json`+for exact archive/member hashes. See [PEAR](models/PEAR.md). Models, generated+support folders, diagnostics and private regression artifacts are excluded from Git.+The active receipt binds the support/adapters to the installed shared-runtime group.+Matching verified support is retained without downloading or extracting it again;+a source/base change or damaged support stages and CUDA-verifies a new generation+before replacing the pointer. Failure leaves prior support and the install retry+marker intact. No weights or registered geometry are acquired by this step.++Changed upstream files receive an adaptation notice. Each support generation+also records pinned source URLs/hashes and the adapter hash in+`RGB_MOCAP_PROVENANCE.json`, alongside the retained provider license files.diff --git a/docs/CITATIONS.md b/docs/CITATIONS.mdindex 969b82c..01e0849 100644--- a/docs/CITATIONS.md+++ b/docs/CITATIONS.md@@ -6,6 +6,27 @@ These references do not change the separate licenses or permissions for code,model weights, body data or input footage. Supporting models retain their ownupstream acknowledgements; see [third-party notices](../THIRD_PARTY_NOTICES.md).+## PEAR++[Paper](https://doi.org/10.1145/3799902.3811096) · [Official citation](https://github.com/Pixel-Talk/PEAR/blob/8e915f8c3dfae4063d66763e6296b2b0b02eb303/README.md#-citation)++```bibtex+@inproceedings{wu2026pear,+ author = {Wu, Jiahao and Liu, Yunfei and Lin, Lijian and Zhu, Ye and Zhu, Lei and Li, Jingyi and Li, Yu},+ title = {PEAR: Pixel-aligned Expressive humAn mesh Recovery},+ booktitle = {Proceedings of the Special Interest Group on Computer Graphics and Interactive Techniques Conference Conference Papers},+ series = {SIGGRAPH '26 Conference Papers},+ year = {2026},+ pages = {46:1--46:12},+ doi = {10.1145/3799902.3811096},+ publisher = {Association for Computing Machinery}+}+```++RGB MoCap uses PEAR for live bone preview; its fixed-length display rig and+filtering are application features, not a claim to reproduce the paper's full+mesh workflow or reported throughput.+## ExMR[Paper](https://arxiv.org/abs/2610.26213) · [Official citation](https://github.com/twehrbein/ExMR/blob/main/README.md)diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.mdindex 5ffcae4..75b830c 100644--- a/docs/PERFORMANCE.md+++ b/docs/PERFORMANCE.md@@ -31,6 +31,13 @@ the app Console and CMD window.| FlowHMR | Offload SAM/VGGT transformer blocks to CPU and transfer them for inference. SAM uses one frame per batch; the saved GPU Hand Crops selection is retained. || GVHMR and add-ons | Use existing adaptive image batches and bounded processing. Preserve full-context FP32 attention; use the validated query split only when dense attention does not fit or after its supported OOM recovery. || MAMMA | Offload the VGGT camera transformer blocks. Masks, FP32 landmarks and 3D fitting keep their current settings; this is not full-MAMMA model offloading. |+| PromptHMR | Retains one-image batches and full temporal context; additional block offloading is not implemented. |++PEAR is a separate live tool: the offline Resource Mode control is hidden. Its+fixed-length bone path uses FP16 encoding/FP32 decoding, one requested frame per+prediction and bounded latest-frame presentation. It retains RAM monitoring and+a CUDA allocation budget but has no automatic offload/retry path. See the+[PEAR timings and limitations](models/PEAR.md#placement-and-performance).## Measured memory savingsdiff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex 4d5abb9..03f1893 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -107,8 +107,9 @@ have not yet been verified; compatibility reports are welcome.2. Run `install.cmd` with an internet connection. It downloads and verifiespinned Python environments, Blender 4.5.0, FFmpeg 7.1.1 and small upstreamsupport files, and installs the included prebuilt motion-correction module.- It prepares ExMR, FlowHMR and GVHMR runtimes and their supported add-ons- together, not only the currently selected model. The AI runtimes remain+ It prepares ExMR, FlowHMR and GVHMR runtimes, their supported add-ons, and+ PEAR's small shared-runtime support together, not only the selected model.+ The AI runtimes remainseparate; model weights/body data are not included. Downloads and free diskspace are needed, and the install can take time.3. Run `RGBMoCap.cmd`. Keep its console open while the GUI runs; launch errors@@ -170,7 +171,7 @@ other PCs; connection speed and storage performance affect the time.### Installed sizeThe current registered model files and active runtimes measured approximately-**67.8 GB (63.1 GiB)** with all five models and supported add-ons installed.+**67.8 GB (63.1 GiB)** with the five offline models and supported add-ons installed.Blender and FFmpeg are included. The inventory excludes projects, importedcharacters, exports, caches (including Python bytecode), retained downloadarchives, obsolete runtime generations and separately installed compiler tools.@@ -181,7 +182,11 @@ Shared model files and hardlinks are counted once.| ExMR + FlowHMR + GVHMR, including supported add-ons | 12.35 GiB | 28.89 GiB | 41.23 GiB || MAMMA additional files | 6.11 GiB | 3.42 GiB | 9.54 GiB || PromptHMR additional files | 6.22 GiB | 6.13 GiB | 12.34 GiB |-| **All five** | **24.68 GiB** | **38.44 GiB** | **63.11 GiB** |+| **Five offline models** | **24.68 GiB** | **38.44 GiB** | **63.11 GiB** |+| PEAR live preview, additional | Small support overlay; shared runtime reused | ~2.84 GiB | ~2.84 GiB |++Adding PEAR to all five offline sets gives an estimated combined total of about+**65.95 GiB (70.8 GB)**. Its original geometry ZIP needs additional download space.Totals use unrounded bytes; rounded cells may not sum exactly. These are localobservations, not universal requirements. App source files add space beyond this@@ -222,6 +227,8 @@ may be outside the installation folder.| `<install folder>\.setup\downloads\`, `.setup\uv-cache\` and `.setup\tmp\` | Downloaded wheels and temporary cache can be removed only after installation or update completes. They are reused for repair and updates; deleting them may require downloading files again. Keep the rest of `.setup`, including the private Python and installation state. || `<install folder>\.setup\mamma-downloads\` | Optional MAMMA package/source download cache. Its contents can be removed after MAMMA setup finishes; repair may need to download them again. Keep `runtime_mamma` and `.setup/mamma-runtime.json`. || `<install folder>\.setup\prompthmr-downloads\` | Optional PromptHMR package/source download cache. Remove contents only after setup finishes; repair may need to download them again. Keep `runtime_prompthmr` and `.setup/prompthmr-runtime.json`. |+| `<install folder>\.setup\pear-downloads\` | PEAR source/support archives. Contents can be removed after installation/update finishes; repair may download them again. Keep `runtime_pear` and `.setup/pear-runtime.json`. |+| `<install folder>\temp\` | Local PEAR Torch/kernel temporary cache. Contents can be removed after closing the app and its workers; the next run can recreate them. |Repeated work mainly grows project data: each model has its own result folder.Inside `exmr`, `flowhmr` or `gvhmr`, different processing ranges can add `clips`@@ -295,7 +302,7 @@ and feature-stage gains, see [resource modes and optimizations](PERFORMANCE.md).Each model has a [detailed guide](models/README.md): [ExMR](models/EXMR.md),[FlowHMR](models/FLOWHMR.md), [GVHMR](models/GVHMR.md), [MAMMA](MAMMA.md)-and [PromptHMR](models/PROMPTHMR.md).+and [PromptHMR](models/PROMPTHMR.md). For live bone preview, use [PEAR](models/PEAR.md).These cover required files, settings, defaults and workflow limitations.These quality comparisons are **subjective observations from our test videos**,@@ -311,8 +318,9 @@ opening a project restores its saved model. **Prepare Preview**, below| **GVHMR** | Lowest overall quality in our tests, but sometimes better for unusual poses such as backflips. | Optional **HandFlow**; not inferred by GVHMR itself. || **MAMMA** | Multi-view capture of human motion and interactions. Needs separate setup and overlapping synchronized views; outside the quality ranking above. | Included. || **PromptHMR** | Can improve relative placement and interactions between multiple people in one fixed-camera video. Overall motion quality was lower than ExMR in our subjective tests; contacts and depth can still be wrong. Separate setup. | No finger tracking; fixed neutral pose. |+| **PEAR** | Live single-person bone preview from a webcam or video. No motion recording, correction, retargeting or export in this mode. | Included. |-All five support contact correction, a 52-bone overlay and FBX export.+The five offline models support contact correction, a 52-bone overlay and FBX export.ExMR/FlowHMR/GVHMR use **Find person** for explicit people selection; MAMMAand PromptHMR track people during reconstruction. The viewport shows the selectedsource mesh: SMPL-X for ExMR/GVHMR/MAMMA/PromptHMR,@@ -368,6 +376,10 @@ clips and timing scopes from this historical table.| 13.8 seconds | MAMMA | 3 | 11m 52s | 6.47 | 9.11 || 14.1 seconds | PromptHMR | 1 | 3m 56s | 4.61 | 8.74 |+For PEAR's separate live-frame timings, current fixed-bone behavior and measured+VRAM, see the [PEAR performance notes](models/PEAR.md#placement-and-performance).+These are not full-clip reconstruction measurements.+For ExMR, FlowHMR and GVHMR, times cover model-processing stages, excluding shared persontracking, app contact correction and preview/export. GVHMR includes HTD, FootMRand HandFlow. FlowHMR includes camera estimation and the original SAM path;@@ -528,7 +540,7 @@ disabled in Low Memory; FlowHMR SAM also uses one-frame batches in that mode.GPU allocator budgets use ComfyUI's external-use margin: 600 MiB on Windows,or 700 MiB on GPUs larger than 15 GiB, subtracted from currently free VRAM.-All five model paths use this rule; FlowHMR/ExMR no longer subtract fixed+The five offline model paths use this rule; FlowHMR/ExMR no longer subtract fixed3/2 GiB or impose an additional 95/90% ceiling. Inference working memory ispart of the allowed budget. This is not a guarantee of free VRAM: other appsand allocations outside PyTorch can still consume it.@@ -619,3 +631,22 @@ See [Build from source](BUILD.md) for environment setup, editing and release buiOriginal RGB MoCap code/documentation uses the [MIT License](../LICENSE).Third-party code, derived modifications, weights and body data keep their ownterms; see [Third-party notices](../THIRD_PARTY_NOTICES.md).++## PEAR live preview++Run `install.cmd` with the app closed; PEAR support is included. PEAR reuses+the shared runtime and adds only pinned source/utilities; no compiler is required.+Prepare its checkpoint and registered SMPL-X 2020/FLAME bundle in Model Manager.+Select **PEAR · Live** and click **Start Live Tracking** to load the models.+**Stop** ends tracking and releases the models and webcam. With **Webcam: None**,+open a video and seek/play its timeline to infer the current frame. Alternatively,+select a connected webcam before starting. While tracking is running, input+changes reuse the loaded models. Rotation and smoothing apply to both sources.+The live view shows fixed-length body and finger bones without per-frame body+mesh calculation. **Reset Bones** recalibrates their lengths from the displayed+pose, pauses video playback and retains the loaded models and viewport camera.+**World Position** is on by default. Turn it off to hold the pelvis at its current+position, including height, while retaining pelvis rotation and joint motion.+There is no Find person, recording, correction, retargeting or animation export+in this live mode. Switching models releases the live worker and device.+See the [PEAR guide](models/PEAR.md) for setup, resources and limitations.diff --git a/docs/VALIDATION.md b/docs/VALIDATION.mdindex 7d2f195..fce74e0 100644--- a/docs/VALIDATION.md+++ b/docs/VALIDATION.md@@ -771,3 +771,513 @@ validation and leaves other model scopes unchanged. The development app alsodownloaded and verified its own copy. Test artifacts and model files remainoutside the public source manifest. This metadata-only registration does notrequire a runtime reinstall or a new checkpoint.++## PEAR live integration (2026-10-31)++The app live mode was checked on the documented Windows/RTX 5090 test PC using+the pinned shared runtime plus the small PEAR support overlay. Six fixed-crop+frames matched the earlier validated fast PEAR experiment exactly: maximum joint+and vertex difference was zero. This is equivalence to that FP16-encoder fast+path, not a claim of identity to every upstream precision/configuration.++Video timeline requests and native GPU mesh rendering were exercised. Readback+matched submitted vertex positions exactly and normals were finite. After+warmup, sampled automatic-detector frames typically took about 23–28 ms, with a+35 ms outlier; peak PyTorch+allocated VRAM was approximately 1.93 GiB. Startup varied around 18–34 seconds.+A 10 ms GUI heartbeat timer usually ran at 16 ms, with startup outliers around+0.55–0.8 seconds. These short tests do not establish universal frame rates.++DroidCam appeared by name. Camera images, a 90-degree rotation, switching back+to video and releasing the worker/device were checked. No person was visible+in that camera scene: a missing-person notice and cleared pose were verified,+not live human pose accuracy. No video or motion recording was created.++Three full worker open/close cycles settled bursts of 1,000 latest-frame requests+and exited in approximately 0.77–0.80 seconds. The supervising test process kept+218 handles and about 32 MiB RSS after each cycle; this is not a long-duration+GUI/driver leak guarantee. Twenty UI switch pairs across the five offline models+and PEAR preserved their selected offline result and camera target. Scoped model+managers and guides opened for all six tools. Existing offline inference/correction+math and pinned runtime packages were not changed or rerun for this UI integration.++Source/setup receipts, malformed live packets, bounded mailbox behavior, syntax+and public-source composition were checked. Models, user video frames and private+benchmark scripts remain outside the public source manifest.++### PEAR video playback follow-up++A continuous-playback regression was reproduced: each new request cleared the+mesh, and the exact-request test rejected almost every completed playing result.+The original seven-second test showed a pose in only 0.9% of visibility samples.+Playback now presents the completed video image and pose together, retains the+last pair while processing, and rejects results from earlier seek/source epochs.+Paused inspection still requires the exact requested frame. The ordinary video+decoder is suspended during paired display; bounded forward skips avoid repeated+codec seeks. Twenty-four decoded test frames had zero pixel differences against+individual seeks. Inference inputs, precision and model calculations are unchanged.++On the same test PC, a seven-second 30 fps source produced 195 completed pose+presentations (about 27.9 fps), with 100% pose visibility and zero image/pose frame+mismatches. Presentation intervals were 31 ms median, 52 ms p95 and 78 ms maximum;+request-to-display delay was 62 ms median, 78 ms p95 and 94 ms maximum. Peak PyTorch+allocated VRAM remained 1.93 GiB. These are short local observations, not guaranteed+rates. The preview image transfer is bounded to 1280 by 720; source pixels used+for inference and original video files are unchanged.++Additional tests covered 2x playback, manual seeking during playback, repeated+half-second loops, pause/exact seek, and deliberately slowed presentation polling.+Every presented image/pose pair matched. Loop and slow-poll outliers reached about+157 ms and 250 ms respectively; an exact seek can briefly wait for its first pose.+GUI heartbeat p95 was 16 ms, with a 188 ms maximum including startup. Observed GUI+RSS ranged roughly 522–545 MiB and settled around 534 MiB after leaving; handles+stayed around 1,495 after initial warmup. Worker shutdown took about 0.8–1.1 seconds.+These short runs do not prove long-duration leak freedom. Twenty model-switch+pairs also preserved offline state. Packet checks covered late/duplicate results,+old epochs, missing people and recovery, and paused exact-frame acceptance.++### PEAR bone appearance follow-up++PEAR now shares the offline octahedron generator and BoneRenderer, including flat+faces, joint caps and outlines. Its 52 body/finger display bones use native PEAR+landmarks; jaw/eye control bones are excluded. This does not fit an export rig or+change inference. Terminal head/toe/finger points use the pinned EHM surface-landmark+layout, checked against its registered metadata. Six cached poses retained their+input joints exactly; maximum display endpoint error was below 0.00000002 metres.+GPU readback matched the unmodified skin exactly and bone normals were finite.+Bone Overlay toggling preserved the pose. CPU frame preparation was about 0.81 ms+median / 0.88 ms p95; the bounded bone buffers occupied about 1.07 MiB. Short live+playback tests showed 24–25 completed presentations per second with uninterrupted+pose visibility and exact image/pose pairing on this PC. These observations are+not a guaranteed frame rate or a controlled renderer-only speed comparison.++### PEAR resident model lifetime++PEAR now preloads/warmups when selected, including with no input, and keeps one+model worker until the tool is left or closed. Switching inputs and Restart Live+Tracking release/reopen captures and reset tracking without rebuilding models.+Recoverable input errors retain the worker; fatal model/resource failures still+release it. Idle acknowledgements keep intentional waiting distinct from stalls,+and RAM/commit-pressure supervision remains active.++Two local lifecycle runs kept one worker PID through preload, two video sources,+six repeated video replacements, camera-open failure and recovery, playback and+tool exit. Initial preload took about 34 seconds; warm video replacement to first+pose took roughly 0.19–0.30 seconds, and input restart about 0.16 seconds. Worker+RSS was about 2,344 MiB while ready/idle and 2,513–2,519 MiB across the last repeated+video switches. Handles settled at 1,171 during those switches. Exit released the+worker in about one second. Short playback checks retained 100% pose visibility;+GUI heartbeat p95 was 16 ms, with startup maxima up to 578 ms. These short tests+do not establish long-term leak freedom. An active physical webcam stream was+not available during this follow-up; camera-open failure recovery was checked.+Packet checks also confirmed that an obsolete recoverable camera error cannot+unload models for the newly selected source. Tests/captures stay outside source.++### PEAR live limb roll++The endpoint-only preview basis was underdetermined around each shaft and could+spin near its reference-axis singularity. PEAR now uses its own-joint EHM/FK+rotations with fixed registered-neutral surface calibration, reusing the shared+front/side surface evidence. A source-relative soft correction is bounded to five+degrees, fades opposed/weak hints, and uses only a bounded past 0.10-second circular+history while streaming. This is a lightweight causal adaptation, not the offline+centred/paired iterative solver. Original inferred rotations, joints and skin are+not smoothed or refitted by this display calculation. Surface sampling and roll+run in the worker even with Bone Overlay hidden; painting uploads finished frames.+Neutral calibration is prepared once on CPU.++In a 180-frame / six-second real clip, the largest inter-frame change of **added+display roll relative to the inferred source** fell from 179.04 to 0.60 degrees;+the p95 fell from 59.49 to 0.22 degrees. These are display-error measurements, not+the total physical rotation of a limb or a claim that the underlying inference has+no jitter. Maximum display endpoint error was below 0.00000003 metres. Seek-order,+input-reset, full-body rotation covariance and independence from lower-joint roll+were checked. Twenty-six earlier sampled poses also passed the fidelity checks.+Six fixed-crop inference regressions retained exactly identical joints and vertices+to the earlier fast-path outputs. GPU mesh readback was unchanged and bone normals+were finite; a 180-frame before/after display video was rendered privately.++Worker roll calculation took about 0.56 ms median / 0.60 ms p95 on the test PC.+A short actual app playback showed about 25.6 completed presentations per second,+100% pose visibility and zero image/pose frame mismatches. Presentation intervals+were 32 ms median, 47 ms p95 and 63 ms maximum. Peak allocated VRAM remained about+1.93 GiB. GUI heartbeat p95 was 16 ms, with a 360 ms maximum including startup.+These short observations are not universal speed or long-duration leak guarantees.++### PEAR thigh neutral-roll calibration follow-up++The previous added-roll continuity checks did not establish alignment to the mesh.+Separate proximal and knee patches gave the thigh and shin different constant+neutral references. Both segments now use the same knee material patch; the arm+pair likewise shares the elbow patch. Each bone retains its own inferred rotation.+This changes display bases only, without modifying model outputs, joints or skin.++Removing shaft-direction differences by parallel transport, neutral left/right+thigh-to-shin roll disagreement fell from -39.05/+13.27 degrees to +1.77/-0.28.+In 180 continuous frames, absolute leg surface-facing residual p95 fell from 42.01+to 4.51 degrees (maximum 44.43 to 6.63). Across 26 separate sampled poses, p95 fell+from 44.13 to 5.73 degrees. These are material-proxy alignment measurements, not+ground-truth anatomical accuracy. Arm surface residual p95 also improved: 9.35 to+7.50 degrees in the continuous clip and 26.37 to 14.50 in the separate poses.++The largest inter-frame change of added display roll in the continuous clip was+0.79 degrees, versus 0.60 before; fixing static alignment is distinct from reducing+every temporal metric. Unmodified inputs, proper rotations, stateless seeks, input+reset and independence from lower-joint rotations passed. Maximum endpoint error+was below 0.00000003 metres. GPU mesh readback was identical; bone normals remained+finite in the 180-frame comparison render. A separate CPU check measured display+orientation work at 0.70 ms median / 0.94 ms p95. No model inference or additional+GPU allocation is needed for this patch mapping change. Tests and captures remain+outside the source tree.++A fresh seven-second app playback retained 100% pose visibility, zero image/pose+frame mismatches and about 25.7 completed presentations per second. Peak allocated+VRAM was 1.93 GiB; GUI heartbeat p95 was 16 ms (359 ms maximum including startup).+Presentation intervals were 32 ms median, 62 ms p95 and 93 ms maximum.+Closing released the worker in about 0.94 seconds. This short check does not test+long-term resource growth or an active physical webcam.++### PEAR foot/toe display basis follow-up++The generic shortest-arc zero-roll frame left a constant foot-width tilt when+combined with the registered ankle-to-toe pitch/yaw. Foot and toe display bases+now use the registered-neutral foot direction and body up, with consistent lateral+sign. This calibration is constant; each bone still follows its own inferred FK.+It does not move endpoints, change inference/skin, use toe rotation for incoming+ankle roll, or add frame-by-frame filtering or GPU work.++Validation used separate ankle/toe material regions (51/96 left, 53/96 right+vertices with more than 85% weight to the respective joint). A best-fit material+rotation transports the same neutral foot-width reference for comparison. In 180+continuous frames, aggregate width-direction error p95 fell from 26.29 to 3.66+degrees (maximum 28.76 to 4.52); in 26 separate poses, p95 fell from 26.70 to 3.71.+These measure the chosen neutral reference's agreement with deforming material,+not anatomical ground truth. A forefoot span alone is unsuitable for ankle-roll+validation because it also contains the toe joint's animation.++Non-foot display frames remained bit-identical to the preceding thigh-roll fix.+Endpoint error stayed below 0.00000003 metres, original arrays were unchanged,+and proper frames, seek/reset behavior, rigid rotation covariance and independent+ankle/toe rotations passed. Continuous physical foot-frame step p95 remained about+8.89 degrees (8.88 before), maximum 18.09 degrees; this is inferred motion, not+newly added roll. GPU mesh readback was exact and normals finite in a separate+180-frame comparison render. Private scripts, model data and video captures remain+outside the public source tree.++A fresh seven-second app playback showed 25.1 completed presentations per second,+100% pose visibility and zero image/pose frame mismatches. Presentation intervals+were 32 ms median, 62.3 ms p95 and 125 ms maximum; GUI heartbeat p95 was 16 ms,+maximum 359 ms including startup. Peak allocated VRAM was 1.93 GiB. Worker exit+took about 0.97 seconds. This short run is not a universal speed or leak guarantee;+no active physical webcam was tested in this follow-up.++### PEAR common input rotation and smoothing (2026-11-01)++**Smooth Motion** and **Rotation** now apply to video and webcam. Rotated input+pixels are used for detection/inference and the matching image is returned even+for a paused video seek. Source files are unchanged. Video playback uses source+timestamps across small forward skips instead of resetting its filter at each+skip. Paused seeks/loops/new epochs prime up to eight past parameter frames+(six at 30 fps), skipping geometry for hidden context frames. Obsolete context+requests are cancelled between inferences; no future frames or growing cache.++The causal adaptive rotation filter uses shortest geodesic interpolation, velocity+vectors in one coordinate frame, a 1.2 Hz base cutoff and 8 Hz upper cutoff.+Motion adaptation uses slope 0.65; shape uses 0.35 Hz / 0.02. Root translation+uses vector speed, 1.2 Hz / slope 4 and the same upper cutoff. This is an original+live adaptation of the [One Euro filter principle](https://gery.casiez.net/publications/CHI2012-casiez.pdf),+not an offline motion/contact solve. Smoothing intentionally changes the live pose.++In one 150-frame real clip, rotation-acceleration RMS changed from 109.48 to 86.65+rad/s² versus the preceding smoother (about 21% lower); root-relative joint+acceleration RMS changed from 31.15 to 25.66 m/s² (about 18% lower). Actual motion+also contributes to these measures; they are not ground-truth reconstruction+errors. The shared process compared raw, preceding and revised parameter geometry;+peak allocated VRAM was 1.93 GiB and process RSS about 2.47 GiB.++Controlled synthetic 1.5-degree rotation noise reduced stationary RMS error from+1.11 to 0.91 degrees and residual acceleration about 32%. The tradeoff is lag:+the slow-motion signal's best frame delay increased from about 67 to 100 ms;+fast-motion unshifted RMS error increased from 9.27 to 12.34 degrees. This is+stronger stabilization, not a claim of equal responsiveness or universally more+accurate motion. The checkbox disables parameter/root smoothing for raw inspection.++A real worker roundtrip verified repeated smoothed seeks were bit-identical,+unfiltered results returned identically after toggling, 90-degree image pixels+matched the rotated/resized decoded source exactly, and forward skipped playback+used zero extra context frames. Warm six-frame-context seeks took roughly 0.20–0.22+seconds; subsequent sampled playback requests roughly 0.05 seconds including pipe+polling. One resident model PID was retained; worker close took about 1.06 seconds.+Turning an upright test image sideways lost person detection; pixel rotation+support does not guarantee recognition of every input orientation. Pure checks+covered valid rotation matrices, time resets, bounded context, root coordinate+invariance and expanded arbitrary-angle rotation. Private tests and captures are+kept outside the public checkout; physical webcam capture was not retested here.++Actual app playback for seven seconds retained 100% pose visibility with zero+image/pose frame mismatches at about 25.7 completed presentations/s. Intervals were+32 ms median, 62 ms p95 and 63 ms maximum. GUI heartbeat p95 was 16 ms, maximum+359 ms including startup. Peak allocated VRAM remained 1.93 GiB, and worker exit+took about 0.89 seconds. These short observations do not prove universal FPS or+long-term leak freedom.++Eight repeated input reopens in the updated worker retained one model PID.+RSS settled near 2,577 MiB (first reopen about 2,575 MiB), with 1,160 handles+throughout. Reopens including six-frame seek context took about 0.22–0.28 seconds.+The repeated run closed its worker in about 0.95 seconds. This bounded sample+showed no sustained resource growth; it is not a long-duration leak guarantee.++### PEAR support included in base installation (2026-11-01)++`install.cmd` now prepares PEAR's small source/utility overlay after the base+runtime transaction commits. `update.cmd` reaches the same managed installation+flow. PEAR reuses the pinned shared Python/Torch packages; model weights and+registered geometry remain separate. The separate PEAR setup CMD was removed.++The support receipt binds its source/adapters and installed shared-runtime group.+A matching, intact receipt is retained without download/extraction or another CUDA+verification process. A changed base, changed support source or damaged inventory+stages and verifies a new support generation before replacing the pointer. The+installer keeps its retry marker until this succeeds; failed support preparation+does not roll back or corrupt the committed base packages or erase user data.++Eight isolated preparation checks covered initial receipt creation, idempotent+reuse without downloads, base-change invalidation, verification/download failure+preserving the old pointer, damaged-source recovery, application-lock refusal and+the integration call's ordering. A separate simulated full installer flow confirmed+the helper runs under the already-held lock after base commit, failure retains the+retry marker, retry succeeds, and model/project sentinels survive both attempts.+These use small mocked archives/processes for fault injection, not a clean-PC test.++The actual Windows `install.cmd` flow then completed on the test PC: all six base+runtime groups passed package/import verification and were retained; cached pinned+PEAR archives prepared 88 support files (about 0.87 MiB) and passed actual CUDA+transform/NMS checks. The shared-group receipt matched and the retry marker cleared.+A subsequent support preparation retained the same generation without download or+another verification process. This used an existing installation and cached+archives; it is not a clean-Windows or fresh-network installation test.+Six fixed-crop real PEAR inference cases through the newly prepared support path+matched the earlier fast-path references exactly (zero joint/vertex difference).+This checks the support path and package reuse, not webcam hardware or every pose.++### PEAR lightweight One Euro path (2026-11-01)++This revision supersedes the earlier same-day video pre-roll design. The existing+One Euro equations were not the main latency source: a smoothed seek or large+frame gap reconstructed six hidden past frames, and setting changes cleared the+last visible pair. Each request now infers exactly one frame. A seek seeds the+filter from that pose; continuous playback/webcam samples use their real time+delta. No future samples, hidden inference or history cache are used. The last+matched image/pose stays visible during replacement. A smoothing-only toggle+retains capture, person association, placement origin and camera framing.++The same filter coefficients/geodesic equations are retained. CPU parameters are+processed in two bounded batches (rotations/scalars), and the normal FP32 pose/face+path packs its tiny tensors into one transfer in each direction. A generic mixed+dtype/device fallback is retained. In 360 parameter samples, batched results+matched the preceding filter exactly, including face axis-angle conversions.+Median CPU filter time fell from 0.243 to 0.104 ms (p95 0.114 ms). On real CUDA+pose/face tensors, filtering plus transfers fell from 0.648 to 0.256 ms median+(p95 0.851 to 0.399 ms); rebuilt joints and vertices were bit-identical. This is+filter/transfer overhead, not the whole model's inference time.++Paired worker runs on one real video measured smoothed random-seek processing at+195.49 ms median before versus 58.67 ms after (response including polling about+217 versus 77 ms). Large skipped-frame requests fell from 171.12 to 57.92 ms.+Ordinary short skipped playback stayed around 30 ms; the gain is chiefly removing+hidden reconstruction, not multiplying steady-state model FPS. Isolated seeks now+show their own prediction rather than the old pre-rolled filtered pose. Sequential+filtering has identical parameters, but seek/gap histories intentionally differ.+Worker allocated VRAM remained about 1.93 GiB; end-of-run RSS was about 2,537 MiB+before and 2,532 MiB after. Single short runs are not universal performance or+long-duration leak guarantees. Tests remain private and source videos unchanged.++An actual seven-second app run toggled smoothing off and back on during playback.+Both toggles retained the displayed pose and camera state. Pose visibility stayed+100%, with zero image/pose mismatches, zero context frames and one inference per+reported frame. Observed presentation rate was about 26.9/s; intervals were 32 ms+median, 57.5 ms p95 and 156 ms maximum. The maximum includes setting changes;+continuous visibility is not a claim of perfectly uniform cadence. GUI heartbeat+p95 was 16 ms, maximum 359 ms including startup. Allocated VRAM remained 1.93 GiB,+and closing released the worker in about 0.97 seconds. Physical webcam capture+was not retested in this follow-up.++Eight input replacements retained one resident worker; RSS stayed around+2,532–2,533 MiB and handles remained 1,160. Replacement-to-pose times were about+0.125–0.141 seconds including capture reopening, with no temporal pre-roll. Repeat+seeks remained deterministic, smoothing-off results returned identically, rotated+pixels still matched the decoded source and the worker exited in about 0.97 s.+++## PEAR adjustable One Euro strength (2026-11-01)++The live checkbox is now One Euro Filter with a short tooltip. Filter Strength+ranges from 1 to 100, default 50. Higher settings lower adaptive cutoffs/slopes+for pose, face, shape and root placement; this reduces jitter and increases lag.+Strength-only edits preserve filter history and do not reload the resident model.++At default 50, 360 parameter samples still matched the previous filter exactly+(maximum difference zero). Synthetic alternating-noise and step tests confirmed+monotonic smoothing/response changes at 1/25/50/75/100, valid rotations, unchanged+input parameters and exact seek reseeding. A seven-second real-video GUI run+changed strength five times and retained pose/camera state each time: 100% pose+visibility, zero image/pose mismatches and one inference per displayed result.+Observed presentation rate was 26.4/s; pose intervals were 32 ms median, 60 ms p95+and 78 ms maximum. Allocated VRAM remained 1.93 GiB.+These short local tests are not universal FPS or long-duration stability claims.+Physical webcam capture was not retested; the same filter path serves both inputs.+Tests and source videos remain outside the public repository.+++## PEAR explicit Start / Stop (2026-11-01)++Selecting PEAR no longer loads or warms models. The right-side Start Live Tracking+button explicitly starts the worker and becomes Stop during loading and tracking.+Stop invalidates pending output, stops playback, clears the live mesh and releases+only this worker/camera. Start is disabled while shutdown finishes. Video/webcam+changes while running still reuse the model; input or filter edits while stopped+cannot start it. Guides supersede the earlier automatic-preload workflow.++A real-video GUI lifecycle test cancelled one loading worker, then completed two+Start/play/Stop cycles with fresh workers. Model selection, video open, stopped+webcam selection/settings and leave/reselect created no worker. Loading cancellation+completed in about 2.06 seconds; both ready workers exited in about 0.92 seconds.+Fresh load/warmup was about 35.8 and 36.5 seconds on the test PC. All sampled video+images matched their pose frame. The repeat lifecycle run used a minimized GUI;+the preceding visible run also verified video playback and the Stop button.+Ten packet-order/seek/missing-result regression checks passed. GUI heartbeat p95+was 16 ms, maximum 1,609 ms across setup, lifecycle and model switches; this does+not establish uniform rendering cadence or long-duration leak freedom. Physical+webcam capture was not retested. Private tests and user videos were not published.+++## PEAR YOLOv8s detector (2026-11-01)++PEAR alone now defaults to official YOLOv8s v8.3.0 (22,588,772 bytes), scoped as+`pear_yolo` in Model Manager with direct official download and SHA-256 checked+imports/loading. Offline models retain their existing YOLOv8x asset and behavior.+No runtime package, detector resolution (640), threshold (0.5), crop ratio (1.25),+PEAR precision, full mesh, filter or bone-roll calculation changed.++Separate warmed worker tests processed 26 sampled frames from two real videos+and 90 sequential smoothed frames. Both variants detected the person in all+116 requests. Frame processing median was 27.29 ms with x versus 24.80 ms with s+(about 9.1% less time); p95 was 32.24 versus 32.07 ms. Detector medians were+11.26 versus 9.03 ms. These exclude decoding, GUI transfer and drawing; they are+not guaranteed viewport FPS. Peak allocated GPU memory was 1,932 versus 1,664 MiB;+end RSS was 2,174 versus 2,144 MiB. Short runs are not leak or hardware guarantees.++Detected boxes averaged 0.972 IoU against the previous detector. Pose rotations+differed by 1.08 degrees mean, 3.89 degrees p95 and 26.50 degrees maximum over+body/hand joints. Root-relative joint differences averaged 11.2 mm; wrist/ankle+p95 was 36.6 mm, maximum 121.1 mm. These are differences, not ground-truth errors+or evidence of equal accuracy. With the same x boxes supplied to the production+s path, all 1,392 stored pose/box/camera/joint arrays were bit-identical, isolating+the changes to detection/cropping. Five model-asset checks covered scoped readiness,+verified import, rejection of a tampered replacement, preservation of the previous+model/receipt and invalidation after an installed-file change. Tests and local+source videos remain outside the public checkout.++An actual seven-second visible app run with the integrated s detector presented+189 image/pose pairs (about 27/s), retained the mesh throughout and had no sampled+frame mismatches. Pose intervals were 32 ms median, 47 ms p95 and+110 ms maximum. Allocated worker VRAM peaked around 1.64 GiB.+The worker closed in about 0.84 seconds. This is not a synchronized before/after+viewport-FPS benchmark. Webcam capture and longer-term identity stability were+not retested in this follow-up.++## PEAR fixed-length bones and forward toe tips (2026-11-01)++The live worker uses fixed-length physical FK pivots and predicted rotations.+A resident CPU EHM model calibrates anatomy on first valid input and Reset Bones;+ordinary frames do not evaluate body skinning or mesh-regressed joints. A bounded+32-entry parameter-only history supports reset from the displayed pose ID. Expired+references warn and retain the rig. Seeks/filter edits retain calibrated lengths.+There is no new video or motion archive.++Three private clip replays covered 539 frames. CPU calibration matched the+earlier GPU-based calibration within 0.00024 mm. Per-segment length variation+was below 0.00018 mm (FP32 roundoff). Invalid NaN calibration retained the old rig.+A real worker verified first-frame calibration, fixed lengths, expired-reference+rejection, exact-reference reset and new-input calibration without reloading.++In a visible five-second app test, 150 image/pose pairs matched, approximately+30/s. Presentation intervals were 31 ms median, 56 ms p95 and 78 ms maximum.+Worker processing was 21.43 ms median, 23.80 ms p95 and 160.31 ms maximum.+Six consecutive resets paused on the displayed frame, preserved the model process+and viewport camera, and updated bound geometry in 0.109–0.141 seconds. Hiding+bones or changing filter strength did not recalibrate. Stop released the worker+in about 0.94 seconds. Startup took about 34 seconds; peak allocated worker VRAM+was 1,541 MiB. GUI handles remained at 1,691 across six resets; worker working set+changed from about 2.4057 to 2.4061 GB and GUI RSS from 587.8 to 588.6 MB.+Timer intervals including startup were 16 ms median, 31 ms p95 and 344 ms maximum.+Short runs do not establish universal FPS, leak freedom or webcam/other-GPU behavior.++The subsequent toe-tip change centres each neutral terminal vector on its foot's+forward sagittal plane instead of the big-toe surface landmark. Length and vertical+pitch are retained; native pivots and predicted rotations are unchanged. Cached+three-clip replay and OpenGL rendering verify the new constant display reference.+Other models, source correction and exports are unaffected.++## PEAR World Position (2026-11-01)++The default-on World Position option retains estimated placement. Off translates+the finished preview uniformly to the currently displayed pelvis XYZ, including+height; when stopped, the first valid pose supplies the anchor. Rotations and+relative pose continue. Only the latest raw packet and one anchor are retained.+Input changes and Stop clear them; Reset Bones retains the anchor. Toggling does+not submit inference, restart models, reset filtering or recalibrate bones.++Three cached clips (539 frames) verified exactly fixed pelvis coordinates,+unchanged source arrays and bit-identical rotation/facing arrays. Relative pose+differences stayed below 0.00012 mm from FP32 translation roundoff. The translation+step took approximately 0.011 ms median, with 0.0125–0.0230 ms p95 across clips.++A visible app test covered 182 paired video/pose presentations across two-second+off/on/off phases. Both off phases had zero root range on all three axes; on+restored the unmodified worker packet. Presentation intervals were 31 ms median,+47 ms p95 and 63 ms maximum. Worker processing was 22.54 ms median, 27.00 ms p95+and 178.72 ms maximum. GUI timer intervals including loading were 16 ms median,+16 ms p95 and 343 ms maximum. Ten paused toggles retained the request/pose ID,+camera settings and bounded render keys. Reset Bones preserved the fixed anchor;+Stop released the cached packet and anchor. These are short video checks, not a+webcam benchmark or a guarantee of sustained FPS or leak freedom.++## PEAR publication review and offline regression (2026-11-01)++Verified the PEAR paper citation against the pinned official README, updated+installation/model/agent guides, current live timings, storage and cleanup+instructions, and kept offline resource modes distinct from live preview.+Setup now marks adapted upstream files and records their pinned provenance.+Saved-workspace validation rejects PEAR as an active or member offline model,+including malformed files, without rewriting them. Retired identities remain+rejected. The live selector still accepts PEAR.++All 80 existing offline tool/processing-option combinations match the preceding+published revision. Existing model paths, URLs, hashes and stage requirements+are unchanged. Twenty GUI switch pairs and all six scoped model managers passed.+Four copied workspaces covered ExMR, FlowHMR, GVHMR, MAMMA and PromptHMR cached+results: loading, seek/playback, PEAR entry/exit, camera/settings restoration and+selected export availability passed. Original project file inventories and+timestamps were unchanged. Five source FBX exports were imported into Blender+4.5 with the normal importer settings: each retained a 52-bone Hips hierarchy,+finite poses and bone-only animation curves. This check does not rerun full AI+reconstruction or retargeting for every model.++PEAR support was freshly staged from the verified cached upstream archives with+real shared-runtime CUDA checks, then reused without reconstruction or package+upgrades. Isolated installer fault injection covered download/verification+failure, damaged source, base changes, lock enforcement, preserved prior pointers,+retained retry markers and successful retry. Model import checks rejected a+tampered detector while preserving the previous registered model and receipt.+The current live app passed default/position/filter controls, paired presentation,+Reset Bones, no extra inference on paused position toggles and worker shutdown.+Five repeated fixed-frame renderer transitions and framebuffer inspection did+not reproduce persistent display corruption. A transient composite window grab+during playback is not a framebuffer-quality measurement.++Publication checks cover source syntax, local documentation links, personal-path+and credential candidates, and excluded runtime/model/project/test payloads.+Private tests and derived files remain outside the source checkout. These are+tests on the existing Windows PC, not a fresh OS, alternate GPU or new physical+webcam certification. Short playback checks do not establish long-term leak freedom.diff --git a/docs/models/PEAR.md b/docs/models/PEAR.mdnew file mode 100644index 0000000..1843e3d--- /dev/null+++ b/docs/models/PEAR.md@@ -0,0 +1,168 @@+# PEAR: live pose preview++[Original PEAR project](https://github.com/Pixel-Talk/PEAR) · [Official checkpoint](https://huggingface.co/BestWJH/PEAR_models)++[Paper and BibTeX](../CITATIONS.md#pear) · [Upstream source license](https://github.com/Pixel-Talk/PEAR/blob/8e915f8c3dfae4063d66763e6296b2b0b02eb303/LICENSE.txt)++PEAR displays fixed-length body and finger bones for one visible person, from a+webcam or the current frame of an opened video. Body mesh and face geometry are+not calculated for each live frame. It is a live preview tool. It does not use+Find person, record motion, run contact correction, retarget characters or export+animation in this integration. Use an offline reconstruction model for those tasks.++Selecting PEAR only shows its controls. Click **Start Live Tracking** to load and+warm the models, then track the selected webcam or video. The button becomes+**Stop**, including during loading. Stop ends tracking and releases the worker,+models and camera; wait for shutdown before starting again.++While tracking is started, opening another video or switching webcams replaces+only the input. Models remain loaded until Stop, leaving PEAR or app close.++## Setup++1. Close RGB MoCap and run `install.cmd` for the base app. It also downloads pinned+ PEAR source, RoMa and the required+ pure-Python PyTorch3D utilities. It checks CUDA operations and reuses the existing+ shared Python/Torch runtime without upgrading its packages. No CUDA Toolkit,+ C++ compiler, separate Torch installation or native PyTorch3D build is needed.+2. Open `RGBMoCap.cmd`, select **PEAR · Live**, and open **Model Manager**.+3. Download/import `pear_model.pt` and **PEAR Person Detection / YOLOv8s**+ (`yolov8s.pt`). Model Manager verifies the supported official files.+4. In the geometry row, use **Manual Download**. Follow the upstream Preparation+ instructions, review the SMPL-X/FLAME provider terms, and obtain the original+ `assets.zip`. Import that ZIP without editing it. Import validates its SHA-256+ and extracts only required files. The source ZIP is preserved.++PEAR requires **SMPL-X 2020 and FLAME 2020** geometry. The standard SMPL-X v1.1+used by other models and MAMMA's locked-head model cannot replace these files.+Registered geometry is not included in the repository or downloaded automatically+by setup. The PEAR source license does not replace body-data or weight licenses.++The checkpoint is approximately **2.50 GiB**. Selected geometry occupies about+**0.32 GiB** logically (about **0.27 GiB** when duplicate files can be hardlinked).+The installed support source/utilities were about **0.87 MiB** on the test PC. The original+geometry ZIP download is about **1.48 GiB** and needs separate temporary space.+PEAR also uses the official YOLOv8s detector (about 21.5 MiB), downloaded or+imported through its Model Manager. The larger YOLOv8x used by offline models+is unchanged. These are additional to the base installation, not a new runtime.++## Video and webcam controls++- **File > Open Video**: choose a video. Leave **Webcam** at **None — use video**.+ Click **Start Live Tracking**, then seek or play to process the requested frame. Requests are+ coalesced to the latest frame, so scrubbing does not create an inference queue.+ During playback, the completed video frame and its pose are displayed together.+ The header shows the displayed frame and delay; the timeline remains the playback+ request clock. Slower inference skips frames rather than hiding every late pose.+ Pause or seek for the exact selected frame. Live video images are bounded to+ 1280 × 720 for transfer. Rotation is applied before inference and this transfer+ resize; the original video file is unchanged.+- **Webcam**, above the video: select a connected device. Camera capture and PEAR+ tracking begin after **Start Live Tracking**. The displayed image and pose belong to the+ same processed frame. Old camera frames are dropped to bound latency.+- **Refresh**: rescan connected cameras. Close other apps using the device if it+ cannot open. Choose **None** to release it and return to the video.+- **Rotation**: clockwise degrees applied to video or webcam images before display+ and inference. `90` turns right; `-90` turns left. Arbitrary angles expand the+ image to avoid clipping. The source file is unchanged.+- **One Euro Filter**: applies to both webcam and video. Adaptive filtering stabilizes+ quiet poses, follows moving poses faster, and caps its response to noisy speed+ estimates. Rotations remain valid rotations; the fixed rig follows the smoothed+ pose. Root placement is also filtered. This intentionally changes the live+ pose and adds some motion-dependent lag; it is not contact correction.+ This lightweight One Euro path processes each requested frame once, using actual+ source time when frames are skipped. There is no extra inference, look-ahead or+ recording-length cache. A seek seeds the filter with that frame's prediction;+ subsequent playback is smoothed. The last matching image/pose pair stays visible+ while a replacement is computed. Turn smoothing off for unfiltered predicted+ rotations; fixed bone lengths remain. Switching it does not reload models or reframe the view.+- **Filter Strength**: 1–100, default 50 (the previous filter setting). Higher values+ reduce jitter but add delay. Applies to pose and root placement; filtered shape+ parameters are used only when bone lengths are calibrated.+ Adjusting it while playing retains filter history and the loaded model.+- **World Position**: on by default, retaining estimated pelvis movement. Off+ fixes all three position coordinates, including height, at the currently+ displayed pelvis position. If turned off before tracking, the first valid pose+ supplies that position. Pelvis rotation and joint motion continue normally.+ Switching it does not reload models, rerun inference or reset bone lengths.+ Turning it back on restores estimated position; this may move the character.+- **Start Live Tracking / Stop**: load the models and begin tracking, or stop and+ release the models and webcam. Stop also cancels model loading. Selecting a new+ input or changing settings while stopped does not start tracking.+- **Reset Bones**: recalculate bone lengths and neutral axes from the pose currently+ displayed. Video playback pauses on that frame. For a webcam, its displayed+ pose parameters are used rather than an unrelated newer camera frame. Models+ remain loaded and the viewport camera is preserved. Choose a frame where the+ person is clearly visible. If the displayed pose has expired, try again; the+ existing rig is retained. Changing input calibrates a new rig automatically.+- **Bone Overlay** uses the same octahedra, joint caps and outlines as the other+ models. Its 52 body/finger bones form a fixed-length FK rig; jaw and eye control bones+ are hidden. This is a live display, not a committed offline export skeleton.+ Each bone follows its own inferred rotation with a constant neutral calibration.+ Lengths remain fixed while playing, seeking or changing filter strength. There+ is no animated bend-plane pole or live mesh-surface roll correction.+ Original inferred twisting can remain.+ Foot and toe roll use a fixed neutral foot-plane reference and each bone's own+ inferred rotation; they do not use the toe rotation to orient the incoming foot.+ Toe tips extend along each foot's neutral forward centreline, rather than toward+ its big-toe landmark. This constant display reference preserves toe length,+ neutral pitch and predicted foot/toe rotations.++The largest detected person is selected initially and followed while visible.+There is no manual person selection in this live mode. Occlusion, leaving the+image and multiple people can cause loss or reacquisition of identity.++## Placement and performance++Pelvis movement is enabled by default through **World Position**. Turning it off+holds pelvis translation in place; it does not lock feet to the ground.+Placement uses the crop camera with an assumed fixed+full-image camera and one initial reference height. It is **not calibrated world+motion**, camera-motion tracking or foot locking. Feet may float or slide.++The fast path uses SDPA, an FP16 encoder, FP32 decoder, encoder CUDA Graphs,+fixed-length CPU FK and YOLOv8s person detection. A reusable CPU body model+calibrates neutral anatomy on the first valid frame and on Reset Bones; body+skinning is not evaluated on each subsequent frame. It detects every processed+frame at 640 pixels.+Changing the detector can change its box and therefore the inferred pose; this+is a speed tradeoff, not a claim of identical motion or equal accuracy. Model+loading and initial warmup take longer than subsequent frames. Performance depends+on the GPU, camera driver, resolution and scene; live preview can skip frames.++On the test PC (RTX 5090 32 GB, Ryzen 9 9950X, 96 GB RAM), a five-second visible+video test of the current bone path presented 150 paired frames, about 30/s.+Worker processing was 21.43 ms median and 23.80 ms p95, with a 160.31 ms maximum;+peak PyTorch allocated GPU memory was about 1.50 GiB. Initial loading took about+34 seconds. A separate warmed paired test measured 19.03 ms with mesh computation+versus 13.84 ms with fixed-length FK (27% less processing time). These measure+different scopes; neither promises webcam throughput or minimum VRAM. See+[validation and limits](../VALIDATION.md#pear-fixed-length-bones-and-forward-toe-tips-2026-11-01).+An earlier full-mesh test used about 1.93 GiB. The integration+keeps video decoding, camera capture, calibration and inference off the GUI thread, with bounded+mailboxes and no automatic video/pose recording. Available RAM and CUDA allocation+failures are reported rather than repeatedly retrying a failing worker.+The offline Resource Mode selector does not apply to PEAR. Its live worker uses+the validated fast configuration with available-memory monitoring and CUDA+allocation limits; it has no block-offload or automatic Low Memory retry.++## Files and development++`runtime_pear/` contains pinned support source/packages; `.setup/pear-runtime.json`+is the setup receipt. `models/pear/` contains checkpoint and imported geometry.+Recent worker diagnostics are in `cache/pear/sessions/`; no captured video or motion+archive is created there. Close the app before deleting support files. Rerun+`install.cmd` after support-source changes; `update.cmd` also prepares/verifies+this support. Matching verified files are reused. Preserve model files and projects.++`mocap/pear_ui.py` owns the transient GUI mode. `mocap/pear/worker.py` owns the model+and capture device. `session.py`/`wire.py` implement bounded non-pickle IPC.+`installer/pear_adapters.py` records the pinned upstream import adaptations. Keep+the base runtime read-only; do not upgrade NumPy, timm or Ultralytics globally.++Pinned source/weight revisions and hashes are recorded in `installer/pear-sources.json`+and `mocap/pear_models.py`; the geometry inventory is in `installer/pear-assets.json`.+The One Euro filter follows the [original method](https://gery.casiez.net/1euro/),+with adaptive rotation and placement filtering in the live worker. The optional+pelvis-position control also draws on the [PoseCap](https://github.com/CorridorTech/PoseCap)+workflow; RGB MoCap implements its own preview controls and fixed-position anchor.diff --git a/docs/models/README.md b/docs/models/README.mdindex 5a0114c..fe341c4 100644--- a/docs/models/README.md+++ b/docs/models/README.md@@ -11,6 +11,7 @@ saved selection. Only implemented tools appear in the list.| GVHMR | One video; SMPL-X | Optional HandFlow | [GVHMR](GVHMR.md) || MAMMA | Two or more synchronized fixed-camera videos; SMPL-X | Included | [MAMMA](../MAMMA.md) || PromptHMR | One fixed-camera video; jointly reconstructed people; SMPL-X | Not generated | [PromptHMR](PROMPTHMR.md) |+| PEAR | Live preview of one person from a webcam or video timeline | Included | [PEAR](PEAR.md) |One-video input does not mean one-person output. ExMR, FlowHMR and GVHMR canprocess checked people independently after **Find person**. Without discovery,@@ -20,6 +21,9 @@ MAMMA detects and matches people across views during reconstruction; itsPromptHMR also tracks people during reconstruction. It defaults to two peopleand Interaction Prompt on; see its guide for setup and fixed-camera limits.For manual MAMMA cameras, see the [calibration format and JSON example](../MAMMA.md#manual-cameras).+PEAR support is prepared by `install.cmd` and `update.cmd` over the shared runtime;+its weights/body data are obtained separately. It is a live preview without motion+recording, contact correction, retargeting or export.In this project's subjective tests, ExMR was generally fast with good quality;FlowHMR was slower with the best overall quality; GVHMR was less consistent@@ -32,7 +36,7 @@ MAMMA is a separate multi-view workflow rather than another single-video option.## Installation and shared workflow1. Run `install.cmd` in the app folder. It prepares ExMR, FlowHMR and GVHMR- runtimes and their supported add-ons, Blender, FFmpeg and native+ runtimes and their supported add-ons, PEAR's shared support, Blender, FFmpeg and nativemotion correction. It does **not** download AI weights or registered body data.2. For MAMMA, additionally follow [its runtime setup](../MAMMA.md#install-the-runtime).`Setup_MAMMA.cmd` is separate from the base installation and update commands.@@ -48,6 +52,10 @@ MAMMA is a separate multi-view workflow rather than another single-video option.Foot defaults on and Hand off. Edit contact timings and **Apply Correction**without rerunning AI inference. Export the displayed applied motion as FBX.+For PEAR, use **Start Live Tracking** instead of reconstruction. It displays+live bones only; offline contact, project-save, retarget and export steps do not+apply. See its guide for filtering, World Position and Reset Bones.+Model-specific settings affect reconstruction; they are separate from contactcorrection and display-only viewport controls. Original and corrected resultsare preserved. One project can hold separate results for each model. MAMMA savesdiff --git a/installer/pear-assets.json b/installer/pear-assets.jsonnew file mode 100644index 0000000..465bbde--- /dev/null+++ b/installer/pear-assets.json@@ -0,0 +1,151 @@+{+ "version": 1,+ "bundle_bytes": 1586423649,+ "bundle_sha256": "af060f27bcfe5f8583ca9700211dd3e64cb5e81b97beb30fc44940c89f3cd9e3",+ "files": [+ {+ "path": "FLAME/203_landmark_embeding.npz",+ "bytes": 12516,+ "sha256": "e90b02f86010b34767162c54ddd310067a2fda9a94d27efd3483d6eb7a6f5ba3",+ "member": "assets/FLAME/203_landmark_embeding.npz"+ },+ {+ "path": "FLAME/FLAME2020/generic_model.pkl",+ "bytes": 53023716,+ "sha256": "efcd14cc4a69f3a3d9af8ded80146b5b6b50df3bd74cf69108213b144eba725b",+ "member": "assets/FLAME/FLAME2020/generic_model.pkl"+ },+ {+ "path": "FLAME/FLAME_masks/FLAME_masks.pkl",+ "bytes": 215062,+ "sha256": "ccefbe1ac0774ff78c68caf2c627b4abc067a6555ebeb0be5d5b0812366ab492",+ "member": "assets/FLAME/FLAME_masks/FLAME_masks.pkl"+ },+ {+ "path": "FLAME/head_template.obj",+ "bytes": 563358,+ "sha256": "dd5bfbce75adb99b1963f43bca7ec3557bd4a7321f8fc515f4100599e80d99f2",+ "member": "assets/FLAME/head_template.obj"+ },+ {+ "path": "FLAME/l_eyelid.npy",+ "bytes": 120680,+ "sha256": "fa50997166c2f884fbfc577d99fe8707966763fc3d83a1870bb786df6cc9410d",+ "member": "assets/FLAME/l_eyelid.npy"+ },+ {+ "path": "FLAME/landmark_embedding.npy",+ "bytes": 31292,+ "sha256": "8095348eeafce5a02f6bd8765146307f9567a3f03b316d788a2e47336d667954",+ "member": "assets/FLAME/landmark_embedding.npy"+ },+ {+ "path": "FLAME/mediapipe_landmark_embedding.npz",+ "bytes": 4518,+ "sha256": "8863363013fc6fe3752d4318ea02a1784970200616a54b785920cdd0568816fc",+ "member": "assets/FLAME/mediapipe_landmark_embedding.npz"+ },+ {+ "path": "FLAME/r_eyelid.npy",+ "bytes": 120680,+ "sha256": "dd78776fed765be4468889dd7d5b54b4bf61c8efbb2869b5b91409ce798aad8d",+ "member": "assets/FLAME/r_eyelid.npy"+ },+ {+ "path": "FLAME/selected_lowerhead.npy",+ "bytes": 1872,+ "sha256": "53d7a5220428780af192c29f4b58b09576ec4a8bf4e7139b8997dfe5ce501721",+ "member": "assets/FLAME/selected_lowerhead.npy"+ },+ {+ "path": "SMPLX/203_landmark_embeding.npz",+ "bytes": 12516,+ "sha256": "e90b02f86010b34767162c54ddd310067a2fda9a94d27efd3483d6eb7a6f5ba3",+ "member": "assets/SMPLX/203_landmark_embeding.npz"+ },+ {+ "path": "SMPLX/flame_generic_model.pkl",+ "bytes": 53023716,+ "sha256": "efcd14cc4a69f3a3d9af8ded80146b5b6b50df3bd74cf69108213b144eba725b",+ "member": "assets/SMPLX/flame_generic_model.pkl"+ },+ {+ "path": "SMPLX/flame_l_eyelid.npy",+ "bytes": 120680,+ "sha256": "fa50997166c2f884fbfc577d99fe8707966763fc3d83a1870bb786df6cc9410d",+ "member": "assets/SMPLX/flame_l_eyelid.npy"+ },+ {+ "path": "SMPLX/flame_r_eyelid.npy",+ "bytes": 120680,+ "sha256": "dd78776fed765be4468889dd7d5b54b4bf61c8efbb2869b5b91409ce798aad8d",+ "member": "assets/SMPLX/flame_r_eyelid.npy"+ },+ {+ "path": "SMPLX/lbs_map_smplx_512.npy",+ "bytes": 57671808,+ "sha256": "78630e1cedc076412a4c9e9ecb04e5aa9ecd7b705e0da82756d727659bb8310f",+ "member": "assets/SMPLX/lbs_map_smplx_512.npy"+ },+ {+ "path": "SMPLX/MANO_SMPLX_vertex_ids.pkl",+ "bytes": 13535,+ "sha256": "e5abe70b6574de25470475091e8008314a5b90127eb48c3e63bfa0adf8c04dcf",+ "member": "assets/SMPLX/MANO_SMPLX_vertex_ids.pkl"+ },+ {+ "path": "SMPLX/mediapipe_landmark_embedding.npz",+ "bytes": 4518,+ "sha256": "8863363013fc6fe3752d4318ea02a1784970200616a54b785920cdd0568816fc",+ "member": "assets/SMPLX/mediapipe_landmark_embedding.npz"+ },+ {+ "path": "SMPLX/SMPL-X__FLAME_vertex_ids.npy",+ "bytes": 40312,+ "sha256": "7e70cdc3659aae699b9732e8dd4af49106310c69b90dc83d9f73e96dbf871e49",+ "member": "assets/SMPLX/SMPL-X__FLAME_vertex_ids.npy"+ },+ {+ "path": "SMPLX/smpl_mean_params.npz",+ "bytes": 1310,+ "sha256": "6fd6dd687800da946d0a0492383f973b92ec20f166a0b829775882868c35fcdd",+ "member": "assets/SMPLX2SMPL/body_models/smpl_mean_params.npz"+ },+ {+ "path": "SMPLX/smplx_extra_joints.yaml",+ "bytes": 1261,+ "sha256": "78ec286757646ab4a01e3fdc1ce8f79affd942b9f94efdc36ee91f914a99d753",+ "member": "assets/SMPLX/smplx_extra_joints.yaml"+ },+ {+ "path": "SMPLX/smplx_faces.npy",+ "bytes": 251024,+ "sha256": "f41bf8209273e907d94417b6a5f3f726f0bd6c156700a09650bc38648d47fe11",+ "member": "assets/SMPLX/smplx_faces.npy"+ },+ {+ "path": "SMPLX/SMPLX_NEUTRAL_2020.npz",+ "bytes": 167264530,+ "sha256": "bdf06146e27d92022fe5dadad3b9203373f6879eca8e4d8235359ee3ec6a5a74",+ "member": "assets/SMPLX/SMPLX_NEUTRAL_2020.npz"+ },+ {+ "path": "SMPLX/SMPLX_to_J14.pkl",+ "bytes": 4692193,+ "sha256": "5df844ddea85b0a400a2e8dbe63d09d19f2b1b7ec0e0e952daeae08f83d82d61",+ "member": "assets/SMPLX/SMPLX_to_J14.pkl"+ },+ {+ "path": "SMPLX/smplx_uv.obj",+ "bytes": 1221122,+ "sha256": "917d9c1922cab36e7a4d9337d25c54aba105b02c29c15391507fa854eec1dac3",+ "member": "assets/SMPLX/smplx_uv.obj"+ },+ {+ "path": "SMPLX/uv_masks/uv_mask512_with_faceid_smplx.npy",+ "bytes": 1048704,+ "sha256": "d8a94c1bee6a66573c188c6aa4cf69b1fc8f6b66aa5c2089f9ab2bfe0fbb7680",+ "member": "assets/SMPLX/uv_masks/uv_mask512_with_faceid_smplx.npy"+ }+ ]+}diff --git a/installer/pear-sources.json b/installer/pear-sources.jsonnew file mode 100644index 0000000..80ff562--- /dev/null+++ b/installer/pear-sources.json@@ -0,0 +1,22 @@+{+ "version": 1,+ "sources": {+ "pear": {+ "url": "https://codeload.github.com/Pixel-Talk/PEAR/zip/8e915f8c3dfae4063d66763e6296b2b0b02eb303",+ "bytes": 69495155,+ "sha256": "ba4769dd938ee19f41ac10b393e9f9d012a6c2863921dc688002d33bf10c7876",+ "commit": "8e915f8c3dfae4063d66763e6296b2b0b02eb303"+ },+ "pytorch3d": {+ "url": "https://codeload.github.com/facebookresearch/pytorch3d/zip/2d224e66523039dbde1d24a86ecef4f8b1dcb038",+ "bytes": 37092043,+ "sha256": "1014571249f8f94fdcd5d5be6b9d8fd7ef2d730d52a9a28e57d5600f14f1b492",+ "commit": "2d224e66523039dbde1d24a86ecef4f8b1dcb038"+ },+ "roma": {+ "url": "https://files.pythonhosted.org/packages/8f/e5/484ff091291cfb9ba82977717ca817456f9a22d519906ec9d16629036360/roma-1.6.1-py3-none-any.whl",+ "bytes": 25484,+ "sha256": "79c3a07ab94c0e784e8de2ecc878645a5cf0aff312f7b1e281ca1be7c5f0b7e8"+ }+ }+}diff --git a/installer/pear_adapters.py b/installer/pear_adapters.pynew file mode 100644index 0000000..5a622fc--- /dev/null+++ b/installer/pear_adapters.py@@ -0,0 +1,22 @@+"""Windows live adapter for pinned PEAR sources; never alter learned forwards."""+from pathlib import Path++def adapt(folder):+ folder=Path(folder)+ def change(name,old,new):+ p=folder/name;s=p.read_text(encoding='utf8')+ if old not in s:raise ValueError('Unsupported PEAR source: '+name)+ notice='# Modified by RGB MoCap: Windows live-inference imports; original PEAR license retained.\n'+ updated=s.replace(old,new)+ if not updated.startswith(notice):updated=notice+updated+ p.write_text(updated,encoding='utf8')+ change('models/pipeline/ehm_pipeline.py','import lightning as L','import torch.nn as nn')+ change('models/pipeline/ehm_pipeline.py','class Ehm_Pipeline(L.LightningModule):','class Ehm_Pipeline(nn.Module):')+ change('models/pipeline/ehm_pipeline.py','from utils.pipeline_utils import *','# Unused offline plotting helpers are not needed for live inference.')+ change('models/smplx/pose_transformer.py','from utils.graphics import overlay_attention_on_image','# Unused offline attention renderer omitted.')+ for line in ['from .smplx_layer import SMPL_Layer','from .SMPLXV2 import SMPLX','from ..modules.ehm import EHM_v2 ',+ 'from pytorch3d.transforms import matrix_to_rotation_6d, matrix_to_axis_angle, axis_angle_to_matrix, rotation_6d_to_matrix']:+ change('models/smplx/smplx_head.py',line,'# Unused import: '+line)+ for name in ['models/modules/smplx/SMPLX.py','models/modules/ehm/EHM_v2.py']:+ change(name,'from pytorch3d.structures import Meshes','from mocap.pear.geometry_compat import Meshes')+ change('models/modules/flame/FLAME.py','from pytorch3d.io import load_obj','from mocap.pear.geometry_compat import load_obj')diff --git a/mocap/gui.py b/mocap/gui.pyindex 8ee15d3..6eb0a32 100644--- a/mocap/gui.py+++ b/mocap/gui.py@@ -127,7 +127,7 @@ class ModelsDialog(QDialog):self.window = windowself.tool = MOTION_TOOLS[tool_key or window.model_choice.currentData()]from .models import STAGE_REQUIREMENTS- keys = ({key for key in STAGE_REQUIREMENTS[self.tool.key+'_assets']} if self.tool.key in ('mamma','prompthmr') else+ keys = ({key for key in STAGE_REQUIREMENTS[self.tool.key+'_assets']} if self.tool.key in ('mamma','prompthmr','pear') else{key for stage in (*self.tool.stages(refine=True, footmr=True, handflow=True),'people') for key in STAGE_REQUIREMENTS.get(stage, ())})# Keep public automatic downloads together, followed by manual-only files.# Stable sorting preserves the existing component order within each group.@@ -145,6 +145,10 @@ class ModelsDialog(QDialog):elif self.tool.key=='prompthmr':from .prompthmr_manager import runtime_panellayout.addWidget(runtime_panel(self))+ elif self.tool.key=='pear':+ from .pear_runtime import status+ note=QLabel(status()[1]+'\nPEAR support is included in install.cmd and update.cmd. Uses the existing shared runtime; no CUDA compiler is needed. Model files are prepared separately below.')+ note.setWordWrap(True);layout.addWidget(note)self.table = QTableWidget(len(self.models), 3)self.table.setHorizontalHeaderLabels(["Model", "Status", "Action"])self.table.horizontalHeader().setStretchLastSection(True)@@ -326,7 +330,7 @@ class ModelsDialog(QDialog):raise ValueError("This model is not part of the selected motion tool.")model = BY_KEY[key]name, _ = QFileDialog.getOpenFileName(picker_parent or self, 'Import ' + model.name, '',- f'Model file ({model.path.name});;All files (*)')+ ('PEAR assets (assets.zip);;All files (*)' if key=='pear_geometry' else f'Model file ({model.path.name});;All files (*)'))if name:self.start_model_jobs([('import_model', ['--model', key, '--video', name])])@@ -335,8 +339,9 @@ class ModelsDialog(QDialog):from .character_ui import CharacterWorkspacefrom .mamma_ui import MammaWorkspacefrom .prompthmr_ui import PromptHMRWorkspace+from .pear_ui import PearWorkspace-class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace,QMainWindow):+class MainWindow(PearWorkspace,PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace,QMainWindow):def __init__(self, video: Path | None = None):super().__init__()self.setWindowTitle("RGB MoCap | Motion Workspace")@@ -344,6 +349,7 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.setMinimumSize(1100, 700)self.video_path = Noneself.init_mamma()+ self.init_pear()self.project = Noneself.workspace_root=Noneself._workspace_loading=False@@ -420,6 +426,8 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorks@read_only_checksdef update_readiness(self):+ if self._pear_active:+ self.pear_sync_controls();returnif getattr(self,'_readiness_depth',0):self._readiness_pending=Truereturn@@ -500,6 +508,7 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksdialog.deleteLater()def select_model(self, *_):+ if self.pear_select_model():returntool = MOTION_TOOLS[self.model_choice.currentData()]if self.workspace_root is not None and not self._workspace_loading and tool.key!=getattr(self,'_selected_tool',None):if self.busy or self.contact_saving:@@ -559,6 +568,7 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.set_active_result(self.selected_result())def current_export(self):+ if self._pear_active:return Noneinfo=self.contact_tracks.get(base_result(self.active_result))if self.active_result.startswith('corrected_') and (self.contact_saving or (info and info.get('unsaved'))):return None# selected_export checks source, correction and target receipts itself.@@ -634,6 +644,13 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.load_video(Path(name))def load_video(self, path):+ if self._pear_active:+ self.stop_playback()+ self.pear_camera.blockSignals(True)+ self.pear_camera.setCurrentIndex(0)+ self.pear_camera.blockSignals(False)+ self.video_readable=False+ self.pear_source_changed()if self.model_choice.currentData()=='mamma':return self.load_mamma_videos([path])try:@@ -710,6 +727,9 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorks@batch_readinessdef load_project(self, project):+ if self._pear_active:+ self.pear_leave()+ self.model_choice.blockSignals(True);self.model_choice.setCurrentIndex(self.model_choice.findData(self._selected_tool));self.model_choice.blockSignals(False)from .project_workspace import is_workspaceif is_workspace(project):return self.open_workspace(project)from .project_storage import project_to_open, source_video@@ -813,6 +833,7 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksreturn Truedef seek(self, index):+ self.pear_seek(index)self.frame_number.blockSignals(True)self.frame_number.setValue(index + 1)self.frame_number.blockSignals(False)@@ -842,6 +863,8 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.clip_label.setText("Clip: no video")def present_frame(self, index):+ if self._pear_active:+ self.pear_submit();return# 3D and overlays advance only when the corresponding decoded image is ready.self.motion_view.index = indexself.motion_view.scene_time=self.source_offset+index/(self.info['fps'] if self.info else 30)@@ -866,6 +889,7 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.timer.stop()self.timer_resolution.release()self.set_playback_indicator(False)+ self.pear_playback_stopped()def set_playback_indicator(self, playing):label = "Pause" if playing else "Play"@@ -874,10 +898,12 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.play_button.setAccessibleName(label)def step_frames(self, amount):+ if self._pear_active and self.pear_camera.currentData() is not None:returnself.stop_playback()self.slider.setValue(max(0, min(self.slider.maximum(), self.slider.value() + amount)))def toggle_play(self):+ if self._pear_active and self.pear_camera.currentData() is not None:returnif self.timer.isActive():self.stop_playback()elif self.video_path and self.info and self.video_readable:@@ -1454,6 +1480,8 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksself.update_readiness()def cancel_job(self):+ self.pear_leave()+ self.pear_stop_scan()if self.character_process is not None:self.cancel_character();returnif self.current_stage=='save_project' and getattr(self,'_project_save_request',None):@@ -1741,6 +1769,8 @@ class MainWindow(PromptHMRWorkspace,MammaWorkspace,CharacterWorkspace,ModelWorksworker = self.processif worker:worker.waitForFinished(3000)+ self.pear_leave()+ self.pear_stop_scan()if self.character_process is not None:self.cancel_character();self.character_process.waitForFinished(5000)self.character_loader.close()diff --git a/mocap/model_guide.py b/mocap/model_guide.pyindex e60dfda..b4d20cf 100644--- a/mocap/model_guide.py+++ b/mocap/model_guide.py@@ -9,6 +9,7 @@ from .motion_tools import MOTION_TOOLS# MAMMA: separate 413-frame/three-view manual run (SAM 2.1, VGGT, two people).# Time includes correction/preview; memory is measured across four inference workers.BENCHMARKS = {+ 'pear': ('5s live video<br>1 person','21.43 ms/frame median<br>23.80 ms p95','1.50','—'),'gvhmr': ('7s<br>1 video', '2m 01s', '5.08', '12.47'),'flowhmr': ('7s<br>1 video', '2m 49s', '14.89', '22.19'),'exmr': ('7s<br>1 video', '1m 08s', '11.32', '19.31'),@@ -16,6 +17,7 @@ BENCHMARKS = {'prompthmr': ('14.1s<br>1 video<br>2 people', '3m 56s', '4.61', '8.74'),}PROJECT_URLS = {+ 'pear':'https://github.com/Pixel-Talk/PEAR','prompthmr': 'https://github.com/yufu-wang/PromptHMR','mamma': 'https://mamma.is.tue.mpg.de/','gvhmr': 'https://github.com/zju3dv/GVHMR',@@ -23,6 +25,7 @@ PROJECT_URLS = {'exmr': 'https://github.com/twehrbein/ExMR',}DESCRIPTIONS = {+ 'pear':'Live single-person body and finger bone preview from a webcam or the current video frame. Fixed bone lengths are calibrated once; Reset Bones recalibrates from the displayed pose without reloading models. World Position is on by default; off fixes pelvis translation while preserving rotation. Body mesh is not computed per live frame. Select a webcam above the video, or choose None for video, then click Start Live Tracking. Stop releases models and the webcam. Uses YOLOv8s person detection; detector boxes can affect the resulting pose. Rotation and One Euro Filter apply to both sources. Adjustable One Euro smoothing reduces tremors with some motion-dependent lag and no extra inference. Seeks start from the selected frame; filtering continues during playback. No Find person, recording, Motion Correction, retargeting or motion export in this live mode. Pelvis placement assumes a fixed camera, not a calibrated world. Support files are included in install.cmd and update.cmd, reusing the shared runtime without upgrading its packages or requiring a CUDA compiler. Prepare the checkpoint and registered SMPL-X 2020/FLAME geometry bundle in Model Manager. See docs/models/PEAR.md.','prompthmr': 'Reconstructs multiple people together from one video. In our subjective tests, it could give more accurate relative placement and interactions, but overall motion quality was lower than ExMR. Contacts, depth and intersections can still be wrong. Fixed cameras only in this Windows integration. People defaults to 2; 0 detects automatically, up to 8. Find person is not needed. Interaction Prompt defaults on; off follows the official default video path. Body motion uses SMPL-X. No finger tracking; untracked fingers use a fixed neutral pose. Supports the usual optional foot/hand contact correction, retargeting and FBX export. Requires Setup_PromptHMR.cmd and separate weights. Non-commercial scientific research license. See docs/models/PROMPTHMR.md.','mamma': 'Multi-view reconstruction of one or several people from two or more synchronized fixed-camera videos of the same performance. No fixed camera-count maximum; practical capacity depends on available RAM and VRAM. Detects people automatically; Find person is not needed. Uses SAM 2.1 masks, FP32 landmarks and VGGT cameras, or your compatible camera calibration. Body and finger motion, original results and contact-corrected results are preserved. Best suited to views that complement each other; occlusion and bad masks can cause errors. Slower than single-video methods. Requires the separate Setup_MAMMA.cmd runtime and registered restricted-use models. See Model Manager > Runtime Setup and docs/MAMMA.md.','gvhmr': 'Lowest overall motion quality in our tests, but sometimes better for unusual poses such as backflips. '@@ -62,11 +65,12 @@ memory covers masks, landmarks, VGGT and 3D fitting. This is not a direct speedInteraction Prompt and app correction on. Time includes tracking, native inference,post-optimization, correction and preview/bone preparation; writing public FBX files is excluded.Its peak reserved CUDA memory was 7.83 GiB. It used a different clip from the older three-model test.</p>+<p>PEAR is a live preview, not a full-clip reconstruction. Its row measures the fixed-length bone worker after warmup, excluding model startup, GUI and camera capture. Maximum processing time was 160.31 ms; the visible app presented 150 paired frames in five seconds. Startup took about 34 seconds. Peak RAM was not separately recorded for this row. See docs/models/PEAR.md for scope and limits. This is not directly comparable with offline processing times.</p><p>VRAM is peak PyTorch allocated memory, not total GPU usage. ExMR/FlowHMR/GVHMR RAM ispeak private memory; MAMMA/PromptHMR RAM is peak worker working set. The older four-modelmeasurements predate the latest Low Memory changes. These are not minimum requirements.Results vary by input and PC.</p>-<p>All supported models offer Motion Correction for foot and hand contacts. Contact correction reduces sliding;+<p>Offline reconstruction models offer Motion Correction for foot and hand contacts. Contact correction reduces sliding;it is separate from tracking fingers or refining ankle angles.</p></body></html>"""diff --git a/mocap/models.py b/mocap/models.pyindex de1101a..b10673a 100644--- a/mocap/models.py+++ b/mocap/models.py@@ -98,6 +98,8 @@ MODELS_LIST.extend([from .mamma_models import ASSETS as MAMMA_ASSETS, KEYS as MAMMA_KEYS, INSTRUCTIONS as MAMMA_INSTRUCTIONSMODELS_LIST.extend(Model(**entry) for entry in MAMMA_ASSETS)from .prompthmr_models import ASSETS as PHMR_ASSETS,KEYS as PHMR_KEYS,INSTRUCTIONS as PHMR_INSTRUCTIONS+from .pear_models import ASSETS as PEAR_ASSETS,KEYS as PEAR_KEYS,INSTRUCTIONS as PEAR_INSTRUCTIONS+MODELS_LIST.extend(Model(**entry) for entry in PEAR_ASSETS)MODELS_LIST.extend(Model(**entry) for entry in PHMR_ASSETS)BY_KEY = {model.key: model for model in MODELS_LIST}if len(BY_KEY)!=len(MODELS_LIST):raise ValueError('Duplicate model identifiers in the model registry.')@@ -116,6 +118,7 @@ MANUAL_INSTRUCTIONS = {MANUAL_INSTRUCTIONS.update(MAMMA_INSTRUCTIONS)MANUAL_INSTRUCTIONS.update(PHMR_INSTRUCTIONS)+MANUAL_INSTRUCTIONS.update(PEAR_INSTRUCTIONS)for _key in ('mano_right','smplh'):MANUAL_INSTRUCTIONS[_key] += ('\nIf the MANO website shows 502 Bad Gateway, use the Recommended download link below '@@ -220,6 +223,7 @@ def manual_instructions_html(key: str) -> str:STAGE_REQUIREMENTS = {+ 'pear_assets': PEAR_KEYS,"people": ("yolo", "person_reid"),"track": ("yolo",), "pva": ("pva",),"features": ("hmr2", "vitpose"),@@ -246,8 +250,11 @@ STAGE_REQUIREMENTS = {def ready(model: Model) -> bool:+ if model.key=='pear_geometry':+ from .pear_models import geometry_ready+ return geometry_ready()valid=model.path.is_file() and model.path.stat().st_size >= model.minimum_bytes- if valid and (model.key.startswith(('flow','hand','exmr','mamma','phmr')) or model.key in ('smplh','mano_right')):+ if valid and (model.key.startswith(('flow','hand','exmr','mamma','phmr','pear')) or model.key in ('smplh','mano_right')):import jsontry:receipt=json.loads(model.path.with_suffix(model.path.suffix+'.receipt.json').read_text(encoding='utf-8'))@@ -333,6 +340,9 @@ def download(key: str, progress=None) -> Path:def import_model_file(key: str, source: Path) -> Path:"""Worker-only validated, atomic registration; never unpickles imports."""import os, uuid+ if key=='pear_geometry':+ from .pear_models import import_bundle+ return import_bundle(source)model=BY_KEY[key]; source=Path(source).resolve()if source.stat().st_size < model.minimum_bytes:raise ValueError('The file is too small for '+model.name)diff --git a/mocap/motion_tools.py b/mocap/motion_tools.pyindex dd9f8a1..9fa97c6 100644--- a/mocap/motion_tools.py+++ b/mocap/motion_tools.py@@ -10,9 +10,10 @@ class MotionTool:reconstruction: tuple[str, ...]refinement: tuple[str, ...] = ()input_setup_only: bool = False+ live: bool = Falsedef stages(self, refine=False, footmr=False, correction=False, handflow=False):- if self.input_setup_only:+ if self.input_setup_only or self.live:return []if self.key in ('mamma','prompthmr'):return list(self.reconstruction)if self.key == 'flowhmr':@@ -22,7 +23,7 @@ class MotionTool:*(("correct",) if correction else ()), "export"]-MOTION_TOOLS = {"gvhmr": MotionTool("gvhmr", "GVHMR", ("track", "gvhmr"), ("pva", "refine")),+MOTION_TOOLS = {"pear": MotionTool("pear", "PEAR · Live", (), live=True),"gvhmr": MotionTool("gvhmr", "GVHMR", ("track", "gvhmr"), ("pva", "refine")),"flowhmr": MotionTool("flowhmr", "FlowHMR", ("track", "flow_camera", "flow_features", "flowhmr")),"exmr": MotionTool("exmr", "ExMR", ("track", "exmr_preprocess", "exmr_features", "exmr")),"mamma": MotionTool("mamma", "MAMMA", ("mamma_prepare","mamma_masks","mamma_landmarks","mamma_camera","mamma_fit","mamma_publish")),@@ -43,7 +44,13 @@ def require_supported_project(project):from pathlib import Pathpath=Path(project)/'project.json'state=json.loads(path.read_text(encoding='utf-8')) if path.exists() else {}- return require_supported_tool(state.get('pipeline',{}).get('model','gvhmr'))+ return require_offline_tool(state.get('pipeline',{}).get('model','gvhmr'))+++def require_offline_tool(model):+ tool=require_supported_tool(model)+ if tool.live:raise UnsupportedMotionTool('PEAR is a transient live preview, not a saved reconstruction model. Project files were preserved.')+ return tool# Derived results never replace either upstream prediction.RESULTS = {diff --git a/mocap/pear/__init__.py b/mocap/pear/__init__.pynew file mode 100644index 0000000..bae76ef--- /dev/null+++ b/mocap/pear/__init__.py@@ -0,0 +1 @@+"""PEAR single-person live inference support."""diff --git a/mocap/pear/acceleration.py b/mocap/pear/acceleration.pynew file mode 100644index 0000000..baf4a2c--- /dev/null+++ b/mocap/pear/acceleration.py@@ -0,0 +1,65 @@+"""Validated full-mesh live path: FP16 encoder and FP32 decoder/geometry."""+import torch,types,ast,copy+from pathlib import Path+from ..pear_runtime import engine_folder+ROOT=engine_folder().parent+PROFILES={'fast':dict(sdpa=True,precision='fp16',graph=True,geometry='full',fast_fk=True)}++def sdpa_forward(self,x):+ b,n,c=x.shape;qkv=self.qkv(x).reshape(b,n,3,self.num_heads,-1).permute(2,0,3,1,4)+ q,k,v=qkv.unbind(0)+ y=torch.nn.functional.scaled_dot_product_attention(q,k,v,dropout_p=self.attn_drop.p if self.training else 0.,scale=self.scale)+ return self.proj_drop(self.proj(y.transpose(1,2).reshape(b,n,-1)))+class Network(torch.nn.Module):+ def __init__(self,model,config):+ super().__init__();self.original=model;self.config=config;self.static=None;self.graphed=None+ if config['sdpa']:+ for block in model.backbone.blocks:block.attn.forward=types.MethodType(sdpa_forward,block.attn)+ self.dtype={'fp32':torch.float32,'fp16':torch.float16,'bf16':torch.bfloat16}[config['precision']]+ # Store encoder weights in the selected dtype, avoiding a second FP32 GPU copy.+ if self.dtype!=torch.float32:model.backbone.to(dtype=self.dtype)+ def encoder(self,x):+ if not self.config['graph']:return self.original.backbone(x)+ if self.graphed is None:+ self.static=torch.empty_like(x,device='cuda').contiguous();self.static.copy_(x)+ stream=torch.cuda.Stream();stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(3):self.original.backbone(self.static)+ torch.cuda.current_stream().wait_stream(stream)+ self.graph=torch.cuda.CUDAGraph()+ with torch.cuda.graph(self.graph):self.graphed=self.original.backbone(self.static)+ self.static.copy_(x);self.graph.replay();return self.graphed+ def forward(self,x):+ x=self.original.normalize(x)[:,:, :,32:-32].to(dtype=self.dtype).contiguous()+ feats=self.encoder(x)+ # Decoder, rotation orthonormalization, camera and body geometry stay FP32.+ return self.original.head(feats.float())++def install_cached_fk():+ """Keep identical matrix operations; remove CUDA scalar reads for static parents."""+ import importlib,weakref+ module=importlib.import_module('models.modules.flame.lbs')+ path=ROOT/'engine/models/modules/flame/lbs.py';tree=ast.parse(path.read_text(encoding='utf8'))+ fn=copy.deepcopy(next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='batch_rigid_transform'))+ cache={}+ def parent_list(parents):+ key=id(parents);entry=cache.get(key)+ if entry is None or entry[0]() is not parents or entry[1]!=parents._version:+ if len(cache)>=8:cache.clear()+ entry=(weakref.ref(parents),parents._version,parents.detach().cpu().tolist());cache[key]=entry+ return entry[2]+ class Replace(ast.NodeTransformer):+ def visit_Subscript(self,node):+ if isinstance(node.value,ast.Name) and node.value.id=='transform_chain' and isinstance(node.slice,ast.Subscript) and isinstance(node.slice.value,ast.Name) and node.slice.value.id=='parents':+ node.slice.value.id='static_parents'+ return self.generic_visit(node)+ fn=Replace().visit(fn);fn.body.insert(0,ast.parse('static_parents = _parent_list(parents)').body[0])+ scope=dict(module.__dict__);scope['_parent_list']=parent_list+ exec(compile(ast.fix_missing_locations(ast.Module(body=[fn],type_ignores=[])),'<cached static EHM FK parents>','exec'),scope)+ module.batch_rigid_transform=scope['batch_rigid_transform']++def trim_unused_geometry(ehm):+ # These constructor/training buffers are not read by EHM_v2.forward.+ for model in [ehm,ehm.smplx]:+ for name in ['laplacian_matrix','laplacian_matrix_negate_diag','head_idxs_uv_flat','head_idxs_temp']:+ if hasattr(model,name):delattr(model,name)diff --git a/mocap/pear/bone_roll.py b/mocap/pear/bone_roll.pynew file mode 100644index 0000000..b16e1f9--- /dev/null+++ b/mocap/pear/bone_roll.py@@ -0,0 +1,121 @@+"""Source-relative live display frames, independent of PEAR inference/skin."""+from collections import deque+import numpy as np+from ..bone_overlay import reference_frame+from ..source_surface import layout,endpoints+from ..surface_roll import evidence,unit,smooth++ACTIVE=np.array([1,4,2,5,16,18,17,19])+# Both segments use the same knee/elbow material frame. A separate proximal+# neutral frame bakes in skin-contour bias as a permanent thigh/upper-arm roll.+PATCH=np.repeat(np.arange(4),2)+LIMIT=np.deg2rad(5.)+JOINTS=np.r_[np.arange(22),np.arange(25,55)]+# Pinned EHM: body joints, 68 face landmarks, then named surface landmarks.+TIPS={15:123,10:124,11:135,27:128,30:129,33:130,36:131,39:133,+ 42:139,45:140,48:141,51:142,54:144}+++class SkeletonLayout:+ def __init__(self,parents):+ lookup={int(j):i for i,j in enumerate(JOINTS)}+ self.parents=np.asarray([lookup.get(int(parents[j]),-1) for j in JOINTS],dtype=np.int32)+ self.children=[np.flatnonzero(self.parents==i) for i in range(52)]++ def landmarks(self,joints):+ joints=np.asarray(joints,dtype=np.float64);p=joints[JOINTS];ends=np.zeros_like(p)+ for i,native in enumerate(JOINTS):+ if len(self.children[i]):continue+ tip=TIPS.get(int(native))+ if tip is not None and tip<len(joints):ends[i]=joints[tip]-p[i]+ else:+ parent=self.parents[i]+ ends[i]=(p[i]-p[parent])*(1.4 if native==15 else .7) if parent>=0 else [0,.1,0]+ return p,ends++ def directions(self,p,ends):+ delta=np.stack([p[c].mean(0)-p[i] if len(c) else ends[i] for i,c in enumerate(self.children)])+ short=np.linalg.norm(delta,axis=1)<=.001;delta[short]+=[0.,.1,0.]+ return delta+++def source_rotations(body,parents,camera):+ """Own-joint FK rotations used by EHM, including its neutral jaw/eyes."""+ local=np.concatenate([np.asarray(body['global_pose']).reshape(1,3,3),+ np.asarray(body['body_pose']).reshape(21,3,3),np.tile(np.eye(3),(3,1,1)),+ np.asarray(body['left_hand_pose']).reshape(15,3,3),+ np.asarray(body['right_hand_pose']).reshape(15,3,3)]).astype(np.float32)+ world=local.copy();world[0]=np.asarray(camera)[:3,:3]@local[0]+ for i in range(1,55):world[i]=world[int(parents[i])]@local[i]+ return world+++def source_basis(rest,parents,children,neutral_surface):+ delta=np.stack([rest[c].mean(0)-rest[i] if len(c) else rest[i]-rest[parents[i]] for i,c in enumerate(children)])+ short=np.linalg.norm(delta,axis=1)<=.001;delta[short]+=[0.,.1,0.]+ basis=np.asarray([reference_frame(d) for d in delta])+ patches=np.asarray(neutral_surface)[PATCH]+ front=unit(patches[:,0]-patches[:,1]);side=unit(patches[:,2]-patches[:,3])+ y=unit(delta[ACTIVE]);x=basis[ACTIVE,:,0];z=basis[ACTIVE,:,2]+ c,t,strength,_,_=evidence(y,x,z,front,side)+ theta=np.where(strength>1e-6,np.arctan2(t,c),0.)+ x=x*np.cos(theta[:,None])+np.cross(y,x)*np.sin(theta[:,None])+ basis[ACTIVE]=np.stack([x,y,unit(np.cross(x,y))],axis=-1)+ # Shortest-arc zero roll is not a foot-width reference: the registered+ # ankle-to-toe pitch/yaw can tilt it into the sole. Calibrate both outgoing+ # foot segments to the neutral foot plane, retaining their own source FK.+ up=unit(rest[3]-rest[0]);lateral=unit(rest[1]-rest[2])+ for ankle,toe in ((7,10),(8,11)):+ forward=unit(rest[toe]-rest[ankle]);width=unit(np.cross(forward,up))+ if np.dot(width,lateral)<0:width=-width+ for joint in (ankle,toe):+ y=unit(delta[joint]);x=unit(width-y*np.dot(y,width))+ basis[joint]=np.stack([x,y,unit(np.cross(x,y))],axis=-1)+ return basis+++class SurfaceRoll:+ def __init__(self):+ self.ids,self.lookup=layout('smplx');self.history=deque(maxlen=32);self.key=None;self.time=None++ def apply(self,y,x,vertices,timestamp=None,stream=None):+ z=unit(np.cross(x,y));x=unit(np.cross(y,z))+ patches=endpoints(np.asarray(vertices)[None,self.ids],self.lookup)[0][PATCH]+ front=unit(patches[:,0]-patches[:,1]);side=unit(patches[:,2]-patches[:,3])+ c,t,strength,_,_=evidence(y[ACTIVE],x[ACTIVE],z[ACTIVE],front,side)+ # Fixed neutral calibration carries the full source roll. Only the+ # additional skin-based correction has this small soft trust region.+ theta=np.where(strength>1e-6,np.arctan2(t,c),0.)+ # Opposed/ambiguous evidence fades to the source instead of flipping+ # between +/- the trust-region limit at the circular branch cut.+ angle=LIMIT*np.tanh(.25*np.sin(theta)/LIMIT)*smooth(strength,.005,.08)+ if timestamp is None:+ self.history.clear();self.time=None;self.key=None+ else:+ now=float(timestamp)+ if stream!=self.key or self.time is None or not 0<now-self.time<=.25:self.history.clear()+ self.key=stream;self.time=now+ while self.history and now-self.history[0][0]>.10:self.history.popleft()+ self.history.append((now,angle.copy()))+ values=np.asarray([v for _,v in self.history])+ angle=np.arctan2(np.sin(values).mean(0),np.cos(values).mean(0))+ x=x.copy();x[ACTIVE]=x[ACTIVE]*np.cos(angle[:,None])+np.cross(y[ACTIVE],x[ACTIVE])*np.sin(angle[:,None])+ return np.stack([x,y,unit(np.cross(x,y))],axis=-1)+++class RollFrames(SkeletonLayout):+ """Small worker-side calculation; painting only consumes finished frames."""+ def __init__(self,parents,neutral_joints,neutral_surface):+ super().__init__(parents)+ self.source_basis=source_basis(np.asarray(neutral_joints)[JOINTS],self.parents,self.children,neutral_surface)+ self.roll=SurfaceRoll()++ def reset(self):self.roll.history.clear();self.roll.key=None;self.roll.time=None++ def frames(self,joints,rotations,vertices,timestamp=None,stream=None):+ p,ends=self.landmarks(joints);y=unit(self.directions(p,ends))+ prior=np.asarray(rotations)[JOINTS]@self.source_basis+ x=prior[:,:,0]-y*np.sum(y*prior[:,:,0],axis=-1,keepdims=True)+ fallback=np.cross(y,prior[:,:,2])+ x=unit(np.where(np.linalg.norm(x,axis=-1,keepdims=True)>.01,x,fallback))+ return self.roll.apply(y,x,vertices,timestamp,stream).astype(np.float32)diff --git a/mocap/pear/core.py b/mocap/pear/core.pynew file mode 100644index 0000000..d646aa6--- /dev/null+++ b/mocap/pear/core.py@@ -0,0 +1,148 @@+from pathlib import Path+import os,sys,time,json,ast,types+from ..paths import ROOT,MODELS+from ..pear_runtime import activate+from ..pear_models import geometry_folder+ENGINE=activate()+ASSETS=geometry_folder()+os.environ.setdefault('OMP_NUM_THREADS','4');os.environ.setdefault('MKL_NUM_THREADS','4')+os.environ['YOLO_CONFIG_DIR']=str(ROOT/'cache/pear/yolo')+os.environ['TORCH_HOME']=str(ROOT/'cache/pear/torch')+os.environ['TEMP']=str(ROOT/'temp');os.environ['TMP']=str(ROOT/'temp')+(ROOT/'cache/pear/yolo').mkdir(parents=True,exist_ok=True)+(ROOT/'temp/torch/kernels').mkdir(parents=True,exist_ok=True)++import numpy as np+import inspect+if not hasattr(inspect,'getargspec'):inspect.getargspec=inspect.getfullargspec+for _name,_value in {'bool':np.bool_,'int':int,'float':float,'complex':complex,'object':object,'str':str,'unicode':str}.items():+ if _name not in np.__dict__:setattr(np,_name,_value)+import torch+import cv2+from omegaconf import OmegaConf+torch.set_num_threads(4)++def crop_functions():+ # Import ONLY official crop definitions; don't import its renderer/demo dependencies.+ source=ENGINE/'inference_images.py';tree=ast.parse(source.read_text(encoding='utf8'))+ names={'sanitize_bbox','process_bbox','rotate_2d','gen_trans_from_patch_cv','generate_patch_image'}+ mod=ast.Module([n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name in names],type_ignores=[])+ scope={'np':np,'cv2':cv2};exec(compile(mod,str(source),'exec'),scope);return scope+CROP=crop_functions()++class Pear:+ def __init__(self,mesh=True,detector='s',profile='fast',detect_every=1,progress=lambda text:None,fixed_rig=False):+ if detector not in ('s','x'):raise ValueError('Unsupported PEAR person detector')+ progress('Preparing PEAR inference modules…')+ from .acceleration import PROFILES,Network,trim_unused_geometry,install_cached_fk+ self.profile=profile;self.config=PROFILES[profile];self.geometry_mode=self.config['geometry'];self.detect_every=detect_every;self.frame_counter=0+ if self.config.get('fast_fk'):install_cached_fk()+ start=time.perf_counter();old=os.getcwd();os.chdir(ASSETS.parent)+ try:+ from models.pipeline.ehm_pipeline import Ehm_Pipeline+ cfg=OmegaConf.load(ENGINE/'configs/infer.yaml')+ progress('Constructing PEAR network…')+ self.model=Ehm_Pipeline(cfg)+ progress('Loading PEAR checkpoint on CPU…')+ state=torch.load(MODELS/'pear/pear_model.pt',map_location='cpu',weights_only=True,mmap=True)+ for key in ['backbone','head']:+ missing=getattr(self.model,key).load_state_dict(state[key],strict=True)+ del state+ if self.config['precision']!='fp32':+ self.model.backbone.to(dtype={'fp16':torch.float16,'bf16':torch.bfloat16}[self.config['precision']])+ progress('Moving PEAR network to GPU…')+ self.model=self.model.cuda().eval()+ self.ehm=None+ self.rig=None+ if mesh or fixed_rig:+ from models.modules.ehm.EHM_v2 import EHM_v2+ progress('Loading registered body geometry…')+ self.ehm=EHM_v2('assets/FLAME','assets/SMPLX').eval()+ if profile!='baseline':trim_unused_geometry(self.ehm)+ if fixed_rig:+ from .fixed_rig import FixedRig+ self.rig=FixedRig(self.ehm);self.parents=self.rig.native_parents+ self.ehm=None # Calibration stays on CPU; never evaluate skin per live frame.+ else:+ self.ehm=self.ehm.cuda()+ self.faces=self.ehm.smplx.faces_tensor.detach().cpu().numpy()+ self.parents=self.ehm.smplx.parents.detach().cpu().numpy()+ from ..source_surface import layout,endpoints+ neutral=self.ehm.smplx.v_template.detach().cpu().numpy()+ self.neutral_joints=(self.ehm.smplx.J_regressor.detach().cpu().numpy()@neutral).astype('float32')+ ids,lookup=layout('smplx')+ self.neutral_surface=endpoints(neutral[None,ids],lookup)[0].astype('float32')+ if profile!='baseline':+ self.model=Network(self.model,self.config).eval()+ torch.cuda.empty_cache()+ finally:os.chdir(old)+ progress('Loading person detector…')+ from ultralytics import YOLO+ from ultralytics.nn import tasks+ from ..storage import sha256+ from ..models import BY_KEY+ detector_spec=BY_KEY['pear_yolo' if detector=='s' else 'yolo'];path=detector_spec.path+ if sha256(path)!=detector_spec.expected_sha256:raise ValueError('Invalid official YOLO checkpoint')+ original_loader=tasks.torch_safe_load+ def trusted_loader(weight,*args,**kwargs):+ if Path(weight).resolve()!=path.resolve():return original_loader(weight,*args,**kwargs)+ return torch.load(path,map_location='cpu',weights_only=False),str(path)+ tasks.torch_safe_load=trusted_loader+ self.detector=YOLO(str(path));self.detector_kind=detector+ self.load_seconds=time.perf_counter()-start+ self.previous=None+ @torch.inference_mode()+ def run(self,bgr,box_override=None,parameter_filter=None,timestamp=None,geometry=True):+ start=time.perf_counter();rgb=cv2.cvtColor(bgr,cv2.COLOR_BGR2RGB)+ t=time.perf_counter()+ if box_override is not None:boxes=np.asarray(box_override)[None]+ elif self.previous is not None and self.frame_counter%self.detect_every:+ boxes=self.previous[None].copy()+ else:+ result=self.detector.predict(bgr,device=0,classes=[0],conf=.5,imgsz=640,verbose=False)[0]+ boxes=result.boxes.xyxy.detach().cpu().numpy()+ self.frame_counter+=1+ detection=(time.perf_counter()-t)*1000+ if not len(boxes):return None+ if self.previous is None:+ box=max(boxes,key=lambda b:(b[2]-b[0])*(b[3]-b[1]))+ else:+ # Stay with the previous person while visible; do not jump to another person.+ p=self.previous;lo=np.maximum(boxes[:,:2],p[:2]);hi=np.minimum(boxes[:,2:],p[2:])+ area=np.maximum(0,hi-lo).prod(1)+ iou=area/np.maximum(1,(boxes[:,2:]-boxes[:,:2]).prod(1)+(p[2:]-p[:2]).prod()-area)+ if iou.max()<.1:self.previous=None;return None+ box=boxes[iou.argmax()]+ self.previous=box.copy();x,y,x2,y2=box+ t=time.perf_counter()+ bbox=CROP['process_bbox'](np.array([x,y,x2-x,y2-y]),rgb.shape[1],rgb.shape[0],[256,256],ratio=1.25)+ if bbox is None:return None+ patch,_,_=CROP['generate_patch_image'](rgb,bbox,1.,0.,False,[256,256])+ inp=torch.from_numpy(patch.astype(np.float32).transpose(2,0,1).copy()).unsqueeze(0).cuda()/255+ preprocess=(time.perf_counter()-t)*1000+ a=torch.cuda.Event(enable_timing=True);b=torch.cuda.Event(enable_timing=True);c=torch.cuda.Event(enable_timing=True)+ a.record();out=self.model(inp);b.record()+ raw_body=None;raw_flame=None;filtered_body=None;filtered_flame=None+ body=out['body_param'];flame=out['flame_param']+ if parameter_filter is not None:+ from .parameter_io import filter_parameters+ raw_body,raw_flame,filtered_body,filtered_flame,body,flame=filter_parameters(body,flame,parameter_filter,timestamp)+ geom=None+ if self.ehm is not None and geometry:geom=self.ehm(body,flame,pose_type='aa')+ c.record();c.synchronize()+ packet={'body':filtered_body if filtered_body is not None else {k:v.detach().cpu().numpy() for k,v in out['body_param'].items() if torch.is_tensor(v)},+ 'flame':filtered_flame if filtered_flame is not None else {k:v.detach().cpu().numpy() for k,v in out['flame_param'].items() if torch.is_tensor(v)},+ 'camera':out['pd_cam'].detach().cpu().numpy()[0],'bbox':box,'crop_bbox':bbox.copy(),+ 'image_size':np.array([bgr.shape[1],bgr.shape[0]],dtype=np.int32),'patch':patch.astype(np.uint8)}+ packet['raw_body']=raw_body if raw_body is not None else packet['body']+ packet['raw_flame']=raw_flame if raw_flame is not None else packet['flame']+ packet['smoothing_enabled']=parameter_filter is not None+ if geom is not None:+ packet['vertices']=geom['vertices'].detach().cpu().numpy()[0]+ packet['joints']=geom['joints'].detach().cpu().numpy()[0]+ from .bone_roll import source_rotations+ packet['rotations']=source_rotations(packet['body'],self.parents,packet['camera'])+ packet['timing']={'detection_ms':detection,'preprocess_ms':preprocess,'pear_cuda_ms':a.elapsed_time(b),+ 'geometry_cuda_ms':b.elapsed_time(c),'total_ms':(time.perf_counter()-start)*1000}+ if not all(np.isfinite(v).all() for v in packet['body'].values()):raise RuntimeError('Nonfinite PEAR output')+ return packetdiff --git a/mocap/pear/fixed_rig.py b/mocap/pear/fixed_rig.pynew file mode 100644index 0000000..8fa76a0--- /dev/null+++ b/mocap/pear/fixed_rig.py@@ -0,0 +1,80 @@+"""One-shot CPU anatomy calibration, then fixed-length FK without live skinning."""+import numpy as np+from collections import OrderedDict+from .bone_roll import JOINTS,TIPS,SkeletonLayout,source_basis,unit+++def forward_toe_tips(rest,joints):+ """Centre display toe tips on each foot's sagittal plane, keeping length/pitch."""+ result=np.asarray(joints).copy();up=unit(rest[3]-rest[0])+ for ankle,toe in ((7,10),(8,11)):+ tip=TIPS[toe];offset=result[tip]-rest[toe];length=np.linalg.norm(offset)+ forward=rest[toe]-rest[ankle];forward=unit(forward-up*np.dot(forward,up))+ height=float(np.clip(np.dot(offset,up),-length,length))+ result[tip]=rest[toe]+forward*np.sqrt(max(0.,length*length-height*height))+up*height+ return result+++class CalibrationFrames:+ """Small parameter-only history for an exact displayed-frame Reset Bones."""+ def __init__(self):self.frames=OrderedDict()+ def clear(self):self.frames.clear()+ def remember(self,key,body,flame):+ self.frames[key]=tuple({k:np.asarray(v).copy() for k,v in group.items()} for group in (body,flame))+ while len(self.frames)>32:self.frames.popitem(last=False)+ def get(self,key):return self.frames.get(key)+++class FixedRig(SkeletonLayout):+ def __init__(self,calibrator):+ self.calibrator=calibrator+ self.native_parents=calibrator.smplx.parents.detach().cpu().numpy().astype('int32')+ super().__init__(self.native_parents)+ self.revision=0;self.clear()++ def clear(self):+ self.rest=None;self.tip_offsets=None;self.basis=None++ def calibrate(self,body,flame):+ """Publish a complete replacement only after validating the current pose's anatomy."""+ import torch+ from ..source_surface import layout,endpoints+ b={k:torch.from_numpy(np.asarray(v,dtype='float32').copy()) for k,v in body.items()}+ f={k:torch.from_numpy(np.asarray(v,dtype='float32').copy()) for k,v in flame.items()}+ for key in ('global_pose','body_pose','left_hand_pose','right_hand_pose'):+ b[key]=torch.eye(3).expand_as(b[key]).clone()+ with torch.inference_mode():+ neutral=self.calibrator(b,f,pose_type='aa')+ vertices=neutral['vertices']+ # Identity body rotations leave the shaped template unchanged. The+ # physical FK pivots precede EHM's optional mesh-joint replacement.+ rest=torch.einsum('jv,bvc->bjc',self.calibrator.smplx.J_regressor,vertices)+ if 'joints_offset' in b:rest=rest+b['joints_offset']+ rest=rest[0].numpy().copy();v=vertices[0].numpy();j=neutral['joints'][0].numpy().copy()+ lengths=np.linalg.norm(rest[1:]-rest[self.native_parents[1:]],axis=1)+ if rest.shape!=(55,3) or not np.isfinite(rest).all() or not np.isfinite(v).all() or np.any(lengths<1e-5) or np.any(lengths>5):+ raise ValueError('Cannot calibrate bones from this pose. Choose a clearly visible person and try Reset Bones again.')+ ids,lookup=layout('smplx');surface=endpoints(v[None,ids],lookup)[0]+ basis=source_basis(rest[JOINTS],self.parents,self.children,surface)+ j[:55]=rest;j=forward_toe_tips(rest,j)+ p,ends=self.landmarks(j);y=unit(self.directions(p,ends));x=basis[:,:,0]+ x=unit(x-y*np.sum(x*y,-1,keepdims=True));basis=np.stack([x,y,unit(np.cross(x,y))],-1).astype('float32')+ offsets={native:(j[tip]-rest[native]).astype('float32') for native,tip in TIPS.items()}+ if not np.isfinite(basis).all() or np.max(abs(basis.swapaxes(-1,-2)@basis-np.eye(3)))>1e-4:+ raise ValueError('Invalid bone calibration. Try Reset Bones on another frame.')+ self.rest=rest.astype('float32');self.tip_offsets=offsets;self.basis=basis;self.revision+=1++ def pose(self,body,camera):+ if self.rest is None:raise RuntimeError('PEAR bones have not been calibrated.')+ local=np.concatenate([np.asarray(body['global_pose']).reshape(1,3,3),np.asarray(body['body_pose']).reshape(21,3,3),+ np.tile(np.eye(3),(3,1,1)),np.asarray(body['left_hand_pose']).reshape(15,3,3),+ np.asarray(body['right_hand_pose']).reshape(15,3,3)]).astype('float32')+ rotations=local.copy();joints=np.zeros((145,3),dtype='float32');joints[:55]=self.rest+ for i in range(1,55):+ parent=int(self.native_parents[i]);rotations[i]=rotations[parent]@local[i]+ joints[i]=joints[parent]+rotations[parent]@(self.rest[i]-self.rest[parent])+ for native,tip in TIPS.items():joints[tip]=joints[native]+rotations[native]@self.tip_offsets[native]+ rotations=np.asarray(camera,dtype='float32')[:3,:3]@rotations+ facing=rotations[JOINTS]@self.basis+ bounds=joints[np.r_[JOINTS,list(TIPS.values())]]+ return bounds,joints,rotations,facingdiff --git a/mocap/pear/geometry_compat.py b/mocap/pear/geometry_compat.pynew file mode 100644index 0000000..394b61f--- /dev/null+++ b/mocap/pear/geometry_compat.py@@ -0,0 +1,36 @@+"""CPU/PyTorch-only constructor helpers, avoiding unused native rasterization.++Uniform graph Laplacian follows the documented PyTorch3D definition. OBJ reader+supports triangle/polygon indices used by the supplied FLAME template only.+These helpers do not change the PEAR network or EHM forward skinning equations.+"""+from types import SimpleNamespace+import torch+class Meshes:+ def __init__(self,verts,faces):+ if len(verts)!=1 or len(faces)!=1:raise ValueError('Single mesh constructor helper only')+ self.verts=verts[0];self.faces=faces[0]+ def laplacian_packed(self):+ f=self.faces;n=len(self.verts)+ edges=torch.cat([f[:,[0,1]],f[:,[1,2]],f[:,[2,0]]],0)+ edges=torch.unique(torch.sort(edges,1).values,dim=0)+ both=torch.cat([edges,edges.flip(1)],0).T+ deg=torch.bincount(both[0],minlength=n).float().clamp(min=1)+ idx=torch.arange(n,device=f.device)+ inds=torch.cat([both,torch.stack([idx,idx])],1)+ vals=torch.cat([1/deg[both[0]],-torch.ones(n,device=f.device)])+ return torch.sparse_coo_tensor(inds,vals,(n,n)).coalesce()+def load_obj(path,load_textures=False):+ verts=[];uv=[];faces=[];tex=[]+ for line in open(path,encoding='utf8'):+ a=line.split()+ if not a:continue+ if a[0]=='v':verts.append([float(v) for v in a[1:4]])+ elif a[0]=='vt':uv.append([float(v) for v in a[1:3]])+ elif a[0]=='f':+ poly=[v.split('/') for v in a[1:]]+ for j in range(1,len(poly)-1):+ t=[poly[0],poly[j],poly[j+1]]+ faces.append([int(v[0])-1 if int(v[0])>0 else len(verts)+int(v[0]) for v in t])+ tex.append([int(v[1])-1 if len(v)>1 and v[1] else -1 for v in t])+ return torch.tensor(verts,dtype=torch.float32),SimpleNamespace(verts_idx=torch.tensor(faces),textures_idx=torch.tensor(tex)),SimpleNamespace(verts_uvs=torch.tensor(uv,dtype=torch.float32))diff --git a/mocap/pear/input_transform.py b/mocap/pear/input_transform.pynew file mode 100644index 0000000..38ee190--- /dev/null+++ b/mocap/pear/input_transform.py@@ -0,0 +1,20 @@+"""Rotate input pixels before display, detection and pose estimation."""+import math+import cv2++def rotate_frame(frame, clockwise_degrees):+ angle=float(clockwise_degrees)+ if not math.isfinite(angle):raise ValueError('Input rotation must be finite')+ angle=angle%360+ if angle==0:return frame+ if angle==90:return cv2.rotate(frame,cv2.ROTATE_90_CLOCKWISE)+ if angle==180:return cv2.rotate(frame,cv2.ROTATE_180)+ if angle==270:return cv2.rotate(frame,cv2.ROTATE_90_COUNTERCLOCKWISE)+ h,w=frame.shape[:2]+ matrix=cv2.getRotationMatrix2D(((w-1)/2,(h-1)/2),-angle,1.)+ # Expand rather than cut off the head or feet at arbitrary angles.+ out_w=math.ceil(w*abs(matrix[0,0])+h*abs(matrix[0,1]))+ out_h=math.ceil(h*abs(matrix[0,0])+w*abs(matrix[0,1]))+ matrix[0,2]+=(out_w-w)/2;matrix[1,2]+=(out_h-h)/2+ return cv2.warpAffine(frame,matrix,(out_w,out_h),flags=cv2.INTER_LINEAR,+ borderMode=cv2.BORDER_CONSTANT,borderValue=(0,0,0))diff --git a/mocap/pear/live_view.py b/mocap/pear/live_view.pynew file mode 100644index 0000000..d663058--- /dev/null+++ b/mocap/pear/live_view.py@@ -0,0 +1,64 @@+"""Native live mesh/grid pass, independent of offline Qt overlay state."""+import numpy as np+from PySide6.QtGui import QMatrix4x4+from PySide6.QtOpenGL import QOpenGLBuffer,QOpenGLVertexArrayObject,QOpenGLShader+from ..rig_gl import RigRenderer+from ..mesh_gl import MeshRenderer+from ..bone_gl import BoneRenderer+from .preview_bones import PreviewBones++VERTEX='''#version 430 core+layout(location=0) in vec3 position;+layout(location=1) in vec3 tint;+uniform mat4 mvp;+out vec3 lineColor;+void main(){gl_Position=mvp*vec4(position,1);lineColor=tint;}'''+FRAGMENT='''#version 430 core+in vec3 lineColor;out vec4 color;+void main(){color=vec4(lineColor,1);}'''++class LiveRenderer:+ def __init__(self,view):+ self.mesh=None;self.bones=BoneRenderer();self.bone_preview=None;self.bone_key=None;self.bone_revision=None;self.gl=self.bones.gl+ self.program=MeshRenderer.program(((QOpenGLShader.Vertex,VERTEX),(QOpenGLShader.Fragment,FRAGMENT)))+ batches=[]+ for lines,color in ((view.grid_minor,(.27,.27,.27)),(view.grid_major,(.34,.34,.34)),+ (np.array([[[-10,.001,0],[10,.001,0]]]),(.60,.32,.36)),+ (np.array([[[0,.001,-10],[0,.001,10]]]),(.30,.46,.61))):+ v=np.asarray(lines,dtype='float32').reshape(-1,3);batches.append(np.column_stack([v,np.tile(color,(len(v),1))]))+ data=np.ascontiguousarray(np.concatenate(batches),dtype='float32');self.count=len(data)+ self.vao=QOpenGLVertexArrayObject();self.vao.create();self.vao.bind()+ self.buffer=QOpenGLBuffer();self.buffer.create();self.buffer.bind();self.buffer.allocate(data.tobytes(),data.nbytes)+ self.program.bind()+ for loc,offset in ((0,0),(1,12)):+ self.program.enableAttributeArray(loc);self.program.setAttributeBuffer(loc,0x1406,offset,3,24)+ self.vao.release();self.program.release()++ def paint(self,view):+ gl=self.gl;gl.glDisable(0x0C11);gl.glDisable(0x0B90);gl.glDisable(0x0BE2)+ gl.glColorMask(True,True,True,True);gl.glDepthMask(True);gl.glStencilMask(0xffffffff)+ gl.glClearColor(.2196,.2196,.2196,1.);gl.glClear(0x4000|0x100|0x400)+ if view.show_grid:+ eye,basis=view._paint_camera;matrix=np.eye(4);matrix[:3,:3]=basis*np.array([[1],[1],[-1]]);matrix[:3,3]=-matrix[:3,:3]@eye+ projection=QMatrix4x4();projection.perspective(40,view.width()/max(1,view.height()),.03,2000)+ self.program.bind();self.program.setUniformValue('mvp',projection*QMatrix4x4(*matrix.reshape(-1).tolist()))+ gl.glDisable(0x0B71);self.vao.bind();gl.glDrawArrays(0x1,0,self.count);self.vao.release();self.program.release()+ if view.live_data is None or view.live_asset is None:return+ if view.live_asset.get('render_mode')!='bones':+ if self.mesh is None:self.mesh=RigRenderer()+ self.mesh.load(view.live_asset);self.mesh.deform(view.live_data['vertices'],view.live_key)+ self.mesh.draw(*view._paint_camera,view.width(),view.height(),(.64,.79,.86))+ if view.show_bones:+ j=view.live_data['joints'];parents=view.live_parents+ revision=view.live_data.get('rig_revision',0)+ if self.bone_preview is None or revision!=self.bone_revision:+ self.bone_preview=PreviewBones(j,parents,('pear-live',revision));self.bone_key=None;self.bone_revision=revision+ if self.bone_key!=view.live_key:+ self.bone_frames=self.bone_preview.frames(j,view.live_data['bone_facing']);self.bone_key=view.live_key+ self.bones.load(self.bone_preview.asset);self.bones.deform(self.bone_frames,view.live_key)+ self.bones.draw(*view._paint_camera,view.width(),view.height())++ def close(self):+ self.bones.close()+ if self.mesh is not None:self.mesh.close()+ self.buffer.destroy();self.vao.destroy();self.program.removeAllShaders()diff --git a/mocap/pear/parameter_io.py b/mocap/pear/parameter_io.pynew file mode 100644index 0000000..625e267--- /dev/null+++ b/mocap/pear/parameter_io.py@@ -0,0 +1,32 @@+"""Coalesce tiny pose tensors into one transfer in each direction."""+import numpy as np+import torch+++def filter_parameters(body,flame,parameter_filter,timestamp):+ groups=(body,flame)+ entries=[(group,key,value) for group,values in enumerate(groups) for key,value in values.items() if torch.is_tensor(value)]+ if not entries:+ filtered=parameter_filter.update({}, {},float(timestamp))+ return {},{},*filtered,dict(body),dict(flame)+ first=entries[0][2]+ packed=all(v.dtype==torch.float32 and v.device==first.device for _,_,v in entries)+ raw=[{},{}]+ if packed:+ values=torch.cat([v.reshape(-1) for _,_,v in entries]).detach().cpu().numpy()+ offset=0+ for group,key,value in entries:+ size=value.numel();raw[group][key]=values[offset:offset+size].reshape(tuple(value.shape));offset+=size+ else:+ # Preserve the generic path if an upstream output's dtype/device differs.+ for group,key,value in entries:raw[group][key]=value.detach().cpu().numpy()+ filtered=list(parameter_filter.update(*raw,float(timestamp)))+ result=[dict(body),dict(flame)]+ if packed:+ uploaded=torch.from_numpy(np.concatenate([filtered[g][k].reshape(-1) for g,k,_ in entries])).to(first.device)+ offset=0+ for group,key,value in entries:+ size=value.numel();result[group][key]=uploaded[offset:offset+size].reshape(value.shape);offset+=size+ else:+ for group,key,value in entries:result[group][key]=torch.from_numpy(filtered[group][key]).to(value.device)+ return (*raw,*filtered,*result)diff --git a/mocap/pear/preview_bones.py b/mocap/pear/preview_bones.pynew file mode 100644index 0000000..9afe349--- /dev/null+++ b/mocap/pear/preview_bones.py@@ -0,0 +1,22 @@+"""Shared bone appearance over native PEAR landmarks; display only."""+import numpy as np+from ..bone_overlay import geometry,reference_frame+from .bone_roll import SkeletonLayout+++class PreviewBones(SkeletonLayout):+ def __init__(self,joints,parents,key=('pear-live',)):+ super().__init__(parents)+ p,ends=self.landmarks(joints)+ self.asset=geometry(p,self.parents,ends,key)+ self.bind_delta=np.asarray([s[2] for s in self.asset['segments']])+ self.bind_length=np.linalg.norm(self.bind_delta,axis=1)+ self.bind_inverse=np.asarray([reference_frame(d).T for d in self.bind_delta])++ def frames(self,joints,facing):+ p,ends=self.landmarks(joints)+ length=np.linalg.norm(self.directions(p,ends),axis=1)+ result=np.tile(np.eye(4,dtype=np.float32),(52,1,1))+ result[:,:3,:3]=([email protected]_inverse)*(length/self.bind_length)[:,None,None]+ result[:,:3,3]=p+ return resultdiff --git a/mocap/pear/projection.py b/mocap/pear/projection.pynew file mode 100644index 0000000..2cda7dd--- /dev/null+++ b/mocap/pear/projection.py@@ -0,0 +1,58 @@+"""Crop-camera -> fixed assumed full-image camera, without changing body scale.++The root's reprojection is exact for the official crop projection. The inferred+translation uses weak-perspective depth lifting and an assumed focal length;+it is NOT calibrated world trajectory or a metric camera measurement.+"""+import numpy as np++def lock_position(pose,root):+ """Translate a finished preview uniformly; never change rotations or inference."""+ root=np.asarray(root,dtype=np.float32)+ if root.shape!=(3,) or not np.isfinite(root).all():raise ValueError('Invalid fixed pelvis position')+ result=dict(pose);delta=root-pose['joints'][0]+ for name in ('joints','bounds','vertices'):+ if name in pose:result[name]=np.ascontiguousarray(pose[name]+delta,dtype=np.float32)+ result['joints'][0]=root+ return result+def processed_bbox(raw,width,height):+ x,y,x2,y2=np.asarray(raw,dtype=np.float64);w=x2-x;h=y2-y+ x1=max(0,x);y1=max(0,y);x2=min(width-1,x1+max(0,w-1));y2=min(height-1,y1+max(0,h-1))+ if not (w*h>0 and x2>x1 and y2>y1):raise ValueError('Invalid person bbox')+ w=x2-x1;h=y2-y1;cx=x1+w/2;cy=y1+h/2;side=max(w,h)*1.25+ return np.array([cx-side/2,cy-side/2,side,side],dtype=np.float32)+def full_camera(root,camera,crop,image_size,focal_factor=1.2):+ root=np.asarray(root,dtype=np.float64);camera=np.asarray(camera,dtype=np.float64)+ width,height=np.asarray(image_size,dtype=np.float64);x,y,w,h=np.asarray(crop,dtype=np.float64)+ if abs(w-h)>1e-3:raise ValueError('Expected the official square PEAR crop')+ q=camera[:3,:3]@root+camera[:3,3]+ if not np.isfinite(q).all() or q[2]<=.05:raise ValueError('Invalid crop camera depth')+ # PEAR GS_Camera: crop pixel = 128 * (1 - 24 * camera_xy / camera_z).+ uv=np.array([x+w/2,y+h/2])-12*w*q[:2]/q[2]+ focal=float(max(width,height)*focal_factor);depth=q[2]*focal/(12*w)+ placed=np.r_[(np.array([width,height])/2-uv)/focal*depth,depth]+ translation=placed-camera[:3,:3]@root+ return translation,placed,uv,focal+class Placement:+ def __init__(self):self.reset()+ def reset(self):self.origin=None;self.reset_filter()+ def reset_filter(self):self.root_filter=None;self.last_time=None;self.last_smoothing=None+ def points(self,vertices,joints,camera,crop,image_size,smoothing=False,timestamp=None,position_offset=None,strength=50.):+ t,root,uv,f=full_camera(joints[0],camera,crop,image_size)+ def basis(a):return np.ascontiguousarray(a[:,[0,2,1]]*np.array([1.,-1.,1.]),dtype=np.float32)+ v=basis(vertices@camera[:3,:3].T+t);j=basis(joints@camera[:3,:3].T+t)+ if position_offset is not None:+ v+=position_offset;j+=position_offset+ elif smoothing:+ from .temporal_filter import AdaptiveFilter,strength_scale+ if self.root_filter is None or not self.last_smoothing:self.root_filter=AdaptiveFilter(1.2,4.,vector=True)+ scale=strength_scale(strength)+ self.root_filter.min_cutoff=1.2/scale;self.root_filter.beta=4./scale;self.root_filter.max_cutoff=8./scale+ dt=float(timestamp)-self.last_time if timestamp is not None and self.last_time is not None else 0.+ filtered=self.root_filter.value.astype(np.float32) if dt==0 and self.root_filter.value is not None else self.root_filter.update(j[0],dt)+ delta=filtered-j[0];v+=delta;j+=delta+ self.last_smoothing=smoothing;self.last_time=float(timestamp) if timestamp is not None else None+ if self.origin is None:+ # One constant origin/initial ground reference. No per-frame root subtraction.+ self.origin=j[0].copy();self.origin[2]=float(v[:,2].min())+ return v-self.origin,j-self.origindiff --git a/mocap/pear/session.py b/mocap/pear/session.pynew file mode 100644index 0000000..ea0de85--- /dev/null+++ b/mocap/pear/session.py@@ -0,0 +1,61 @@+"""Pipe ownership and bounded mailboxes; no blocking work on the GUI thread."""+import subprocess,threading,json,time,os,uuid+from pathlib import Path+from ..paths import ROOT,worker_command+from .wire import receive++class Session:+ def __init__(self):+ self.lock=threading.Condition();self.latest=None;self.command=None;self.closed=False;self.topology=None+ folder=ROOT/'cache/pear/sessions';folder.mkdir(parents=True,exist_ok=True)+ # One bounded log per session; retain only the most recent eight sessions.+ for old in sorted(folder.glob('*.log'),key=lambda p:p.stat().st_mtime)[:-7]:+ try:old.unlink()+ except OSError:pass+ self.log=folder/(uuid.uuid4().hex+'.log')+ log=self.log.open('wb');env=os.environ.copy();env['PYTHONDONTWRITEBYTECODE']='1';env['PYTHONUNBUFFERED']='1'+ try:self.process=subprocess.Popen(worker_command('pear_live'),cwd=ROOT,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=log,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ finally:log.close()+ from ..processing_guard import ProcessingGuard+ self.guard=ProcessingGuard(self.process.pid)+ threading.Thread(target=self.read,daemon=True).start();threading.Thread(target=self.write,daemon=True).start()+ def read(self):+ try:+ while not self.closed:+ meta,arrays=receive(self.process.stdout)+ self.guard.output()+ with self.lock:+ if meta['type']=='topology':self.topology=(meta,arrays)+ else:self.latest=(meta,arrays)+ except Exception as exc:+ with self.lock:+ if not self.closed and not (self.latest and self.latest[0]['type']=='error'):+ self.latest=({'type':'error','text':'PEAR worker stopped. See '+str(self.log)}, {})+ finally:self.process.stdout.close()+ def write(self):+ try:+ while True:+ with self.lock:+ while not self.command and not self.closed:self.lock.wait()+ if self.closed:break+ value=self.command;self.command=None+ self.process.stdin.write((json.dumps(value,ensure_ascii=False)+'\n').encode('utf8'));self.process.stdin.flush()+ except (OSError,ValueError):pass+ finally:+ try:self.process.stdin.close()+ except OSError:pass+ def submit(self,value):+ with self.lock:self.command=value;self.lock.notify_all()+ def poll(self):+ with self.lock:+ value=self.latest;self.latest=None;top=self.topology;self.topology=None+ return top,value+ def close(self):+ with self.lock:self.closed=True;self.command=None;self.lock.notify_all()+ def reap():+ try:self.process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ self.process.terminate()+ try:self.process.wait(timeout=3)+ except subprocess.TimeoutExpired:self.process.kill();self.process.wait()+ threading.Thread(target=reap,daemon=False).start()diff --git a/mocap/pear/temporal_filter.py b/mocap/pear/temporal_filter.pynew file mode 100644index 0000000..d9ec8b6--- /dev/null+++ b/mocap/pear/temporal_filter.py@@ -0,0 +1,85 @@+"""Causal adaptive smoothing; rotation matrices remain on SO(3).++Speed-adaptive cutoff follows the 1 Euro principle (Casiez et al., CHI 2012).+Rotations use geodesic interpolation instead of averaging matrix entries.+No future frames, queues, global trajectory solve or contact constraints.+"""+import math+import numpy as np+from scipy.spatial.transform import Rotation++def alpha(cutoff,dt):return 1/(1+1/(2*math.pi*np.asarray(cutoff)*dt))++def strength_scale(strength):+ value=float(strength)+ if not math.isfinite(value):raise ValueError('Invalid smoothing strength')+ return 2**((min(100.,max(1.,value))-50.)/25.)++class AdaptiveFilter:+ def __init__(self,min_cutoff=1.2,beta=.65,rotation=False,vector=False,max_cutoff=8.):+ self.min_cutoff=min_cutoff;self.beta=beta;self.rotation=rotation+ self.vector=vector;self.max_cutoff=max_cutoff;self.reset()+ def reset(self):self.raw=None;self.value=None;self.derivative=None+ def update(self,value,dt):+ x=np.asarray(value,dtype=np.float64)+ if self.raw is None or not 0<dt<=.25 or self.raw.shape!=x.shape:+ self.raw=x.copy();self.value=x.copy()+ self.derivative=np.zeros(x.shape[:-2]+(3,)) if self.rotation else np.zeros_like(x)+ return self.value.astype(np.float32)+ if self.rotation:+ # Compare angular velocities in the same (parent) coordinate frame,+ # rather than averaging vectors expressed in changing local frames.+ delta=Rotation.from_matrix(([email protected](-1,-2)).reshape(-1,3,3)).as_rotvec().reshape(self.derivative.shape)/dt+ else:delta=(x-self.raw)/dt+ self.derivative+=alpha(1.,dt)*(delta-self.derivative)+ speed=np.linalg.norm(self.derivative,axis=-1,keepdims=True) if self.rotation or self.vector else np.abs(self.derivative)+ # Quiet poses get stronger smoothing. Cap responsiveness so noisy+ # derivative spikes cannot effectively disable filtering.+ a=alpha(np.minimum(self.max_cutoff,self.min_cutoff+self.beta*speed),dt)+ if self.rotation:+ residual=Rotation.from_matrix((self.value.swapaxes(-1,-2)@x).reshape(-1,3,3)).as_rotvec().reshape(self.derivative.shape)+ [email protected]_rotvec((a*residual).reshape(-1,3)).as_matrix().reshape(x.shape)+ else:self.value+=a*(x-self.value)+ self.raw=x.copy()+ return self.value.astype(np.float32)++class ParameterFilter:+ """One Euro state in two bounded batches: rotations and scalar parameters."""+ def __init__(self,strength=50.):self.strength=float(strength);self.reset()+ def reset(self):self.filters={};self.last_time=None;self.schema=None+ def set_strength(self,strength):+ scale=strength_scale(strength);self.strength=float(strength)+ for rotation,f in self.filters.items():+ f.min_cutoff=(1.2 if rotation else np.where(self.shape,.35,1.2))/scale+ f.beta=(.65 if rotation else np.where(self.shape,.02,.65))/scale+ f.max_cutoff=8./scale+ def update(self,body,flame,timestamp):+ dt=timestamp-self.last_time if self.last_time is not None else 0.+ entries=[]+ for prefix,values in (('body',body),('flame',flame)):+ for key in sorted(values):+ x=np.asarray(values[key]);original=x.shape+ axis_angle=prefix=='flame' and key in ('eye_pose_params','pose_params','jaw_params')+ if axis_angle:x=Rotation.from_rotvec(x.reshape(-1,3)).as_matrix()+ entries.append((prefix,key,x,original,axis_angle,x.shape[-2:]==(3,3)))+ schema=tuple((p,k,x.shape,shape,aa,rot) for p,k,x,shape,aa,rot in entries)+ if not 0<dt<=.25 or schema!=self.schema:self.filters={};dt=0.+ self.last_time=timestamp;self.schema=schema+ result={'body':{},'flame':{}}+ for rotation in (True,False):+ items=[e for e in entries if e[-1]==rotation]+ if not items:continue+ values=np.concatenate([x.reshape(-1,3,3) if rotation else x.reshape(-1) for _,_,x,_,_,_ in items])+ if rotation not in self.filters:+ if rotation:self.filters[rotation]=AdaptiveFilter(rotation=True)+ else:+ self.shape=np.concatenate([np.full(x.size,k in ('shape','shape_params','hand_scale','head_scale')) for _,k,x,_,_,_ in items])+ self.filters[rotation]=AdaptiveFilter()+ self.set_strength(self.strength)+ filtered=self.filters[rotation].update(values,dt);offset=0+ for prefix,key,x,original,axis_angle,_ in items:+ count=x.size//9 if rotation else x.size+ value=filtered[offset:offset+count].reshape(x.shape);offset+=count+ if axis_angle:value=Rotation.from_matrix(value).as_rotvec().reshape(original).astype(np.float32)+ result[prefix][key]=value+ return result['body'],result['flame']diff --git a/mocap/pear/wire.py b/mocap/pear/wire.pynew file mode 100644index 0000000..9a405e0--- /dev/null+++ b/mocap/pear/wire.py@@ -0,0 +1,79 @@+"""Bounded, non-pickle packets for the private live worker pipe."""+import io,json,struct+import numpy as np++LIMIT=16*1024**2++def send(stream,meta,**arrays):+ out=io.BytesIO()+ np.savez(out,**arrays)+ header=json.dumps(meta,ensure_ascii=False).encode('utf8')+ data=struct.pack('<I',len(header))+header+out.getvalue()+ if len(data)>LIMIT:raise ValueError('Live packet too large')+ stream.write(struct.pack('<I',len(data))+data);stream.flush()++def exact(stream,n):+ chunks=[]+ while n:+ part=stream.read(n)+ if not part:raise EOFError()+ chunks.append(part);n-=len(part)+ return b''.join(chunks)++def receive(stream):+ size=struct.unpack('<I',exact(stream,4))[0]+ if not 4<=size<=LIMIT:raise ValueError('Invalid live packet size')+ data=exact(stream,size);h=struct.unpack('<I',data[:4])[0]+ if h>65536 or h>size-4:raise ValueError('Invalid live header')+ meta=json.loads(data[4:4+h]);arrays={}+ import zipfile+ payload=io.BytesIO(data[4+h:])+ with zipfile.ZipFile(payload) as z:+ if len(z.infolist())>10 or sum(i.file_size for i in z.infolist())>LIMIT:raise ValueError('Invalid live arrays')+ payload.seek(0)+ with np.load(payload,allow_pickle=False) as z:+ for key in z.files:+ a=z[key]+ if a.dtype not in (np.dtype('uint8'),np.dtype('uint32'),np.dtype('int32'),np.dtype('float32')) or a.size>4_000_000:raise ValueError('Invalid live array')+ if a.dtype.kind=='f' and not np.isfinite(a).all():raise ValueError('Nonfinite live array')+ arrays[key]=a+ kind=meta.get('type') if isinstance(meta,dict) else None+ if kind not in ('status','topology','frame','missing','error'):raise ValueError('Unknown live packet')+ if kind=='topology':+ p=arrays['parents']+ if p.dtype!=np.int32 or p.shape!=(55,) or p[0]!=-1 or np.any(p[1:]<0) or np.any(p[1:]>=np.arange(1,55)):raise ValueError('Invalid PEAR hierarchy')+ if kind=='topology' and meta.get('render_mode')=='bones':+ if set(arrays)!={'parents'}:raise ValueError('Invalid bone topology payload')+ elif kind=='topology':+ n=int(meta['vertices']);f=arrays['faces'];o=arrays['offsets'];b=arrays['neighbors'];p=arrays['parents']+ if not 1<=n<=200000 or f.ndim!=1 or len(f)%3 or o.shape!=(n+1,) or b.ndim!=1 or p.ndim!=1 or len(p)>512:raise ValueError('Invalid live topology')+ if f.dtype!=np.uint32 or o.dtype!=np.uint32 or b.dtype!=np.uint32 or p.dtype!=np.int32:raise ValueError('Invalid topology type')+ if p.shape!=(55,) or p[0]!=-1 or np.any(p[1:]<0) or np.any(p[1:]>=np.arange(1,55)):raise ValueError('Invalid PEAR hierarchy')+ if not len(f) or f.max()>=n or (len(b) and b.max()>=n) or o[0]!=0 or int(o[-1])*2!=len(b) or np.any(o[1:]<o[:-1]):raise ValueError('Invalid topology indices')+ for key,shape in (('neutral_joints',(55,3)),('neutral_surface',(8,4,3))):+ a=arrays[key]+ if a.dtype!=np.float32 or a.shape!=shape:raise ValueError('Invalid live neutral calibration')+ if kind=='frame':+ bones=meta.get('render_mode')=='bones'+ for k,minimum,limit in (('bounds' if bones else 'vertices',22,128 if bones else 200000),('joints',55,512)):+ a=arrays[k]+ if a.dtype!=np.float32 or a.ndim!=2 or a.shape[1]!=3 or not minimum<=len(a)<=limit:raise ValueError('Invalid live pose')+ if bones and (int(meta.get('pose_id',0))<1 or int(meta.get('bone_revision',0))<1):raise ValueError('Invalid fixed-rig generation')+ r=arrays['rotations']+ if r.dtype!=np.float32 or r.shape!=(55,3,3) or np.max(abs(r.swapaxes(-1,-2)@r-np.eye(3)))>.005 or np.linalg.det(r).min()<.99:+ raise ValueError('Invalid live source rotations')+ r=arrays['bone_facing']+ if r.dtype!=np.float32 or r.shape!=(52,3,3) or np.max(abs(r.swapaxes(-1,-2)@r-np.eye(3)))>.005 or np.linalg.det(r).min()<.99:+ raise ValueError('Invalid live bone facing')+ if 'image' in arrays:+ a=arrays['image']+ if a.dtype!=np.uint8 or a.ndim!=3 or a.shape[2]!=3 or not 0<a.shape[0]<=720 or not 0<a.shape[1]<=1280:raise ValueError('Invalid camera image')+ return meta,arrays++def topology(faces,count):+ f=np.asarray(faces,dtype=np.uint32).reshape(-1,3)+ centers=f.reshape(-1)+ pairs=f[:,[[1,2],[2,0],[0,1]]].reshape(-1,2)+ order=np.argsort(centers,kind='stable')+ offsets=np.r_[0,np.cumsum(np.bincount(centers,minlength=count))].astype('uint32')+ return dict(faces=f.reshape(-1),offsets=offsets,neighbors=pairs[order].reshape(-1))diff --git a/mocap/pear/worker.py b/mocap/pear/worker.pynew file mode 100644index 0000000..a59a1ae--- /dev/null+++ b/mocap/pear/worker.py@@ -0,0 +1,192 @@+"""Latest-frame PEAR preview. No inference archives, recordings or project writes."""+import sys,threading,json,time,traceback++def main():+ pipe=sys.stdout.buffer+ sys.stdout=sys.stderr+ import faulthandler+ faulthandler.enable(file=sys.stderr)+ faulthandler.dump_traceback_later(40,repeat=True,file=sys.stderr)+ from .wire import send+ condition=threading.Condition();state={'value':None,'serial':0,'stop':False}+ def controls():+ try:+ while True:+ line=sys.stdin.buffer.readline(65537)+ if not line or len(line)>65536:break+ value=json.loads(line)+ with condition:+ if value.get('stop'):break+ state['value']=value;state['serial']+=1;condition.notify_all()+ finally:+ with condition:state['stop']=True;condition.notify_all()+ cap=None;camera=None+ def release_inputs():+ nonlocal cap,camera+ current=camera;camera=None+ try:+ if current:current.close()+ finally:+ if cap:cap.release();cap=None+ try:+ send(pipe,{'type':'status','text':'Loading PEAR models…'})+ from .core import Pear,cv2,np,torch+ from .projection import Placement+ from .temporal_filter import ParameterFilter+ from .input_transform import rotate_frame+ if not torch.cuda.is_available():raise RuntimeError('PEAR requires a compatible NVIDIA GPU.')+ from ..compute_policy import gpu_reserve+ free,total=torch.cuda.mem_get_info()+ budget=max(1024**2,free-gpu_reserve(total))+ torch.cuda.set_per_process_memory_fraction(min(1.,budget/total))+ model=Pear(mesh=False,fixed_rig=True,profile='fast',progress=lambda text:send(pipe,{'type':'status','text':text}))+ send(pipe,{'type':'status','text':'Warming up live inference…'})+ model.run(np.zeros((480,640,3),dtype=np.uint8),box_override=np.array([160,10,480,470],dtype=np.float32))+ # Detector imports its backend lazily on its first call.+ model.detector.predict(np.zeros((480,640,3),dtype=np.uint8),device=0,classes=[0],conf=.5,imgsz=640,verbose=False)+ model.previous=None;model.frame_counter=0+ faulthandler.cancel_dump_traceback_later()+ # Windows Fortran/CRT DLL initialization can contend with a blocking+ # stdin reader. Start the control reader only after native imports/load.+ threading.Thread(target=controls,daemon=True).start()+ placement=Placement();smooth=ParameterFilter()+ from .fixed_rig import CalibrationFrames+ references=CalibrationFrames();rig=model.rig;pose_id=0;reset_handled=0;reset_warning='';calibration_pose=None+ send(pipe,{'type':'topology','render_mode':'bones','load_seconds':model.load_seconds},parents=np.asarray(model.parents,dtype='int32'))+ seen=-1;source=None;last_index=None;last_options=None;last_epoch=None;last_playing=False;frame_number=0+ while True:+ with condition:+ while not state['stop'] and (state['value'] is None or (state['serial']==seen and camera is None)):+ condition.wait(.25)+ if state['stop']:break+ request=dict(state['value']);seen=state['serial']+ mode=request.get('mode','video');generation=int(request['generation'])+ options=(float(request.get('rotation',0)),bool(request.get('smoothing',True)))+ strength=float(request.get('smoothing_strength',50.))+ if strength!=smooth.strength:smooth.set_strength(strength)+ desired=(mode,request.get('camera'),request.get('path'),request.get('resolution'),request.get('restart',0))+ if desired!=source:+ release_inputs()+ model.previous=None;placement.reset();smooth.reset();rig.clear();references.clear();reset_warning='';calibration_pose=None;last_index=None;last_epoch=None;source=desired+ try:+ if mode=='camera':+ send(pipe,{'type':'status','text':'Opening camera…','generation':generation})+ camera=LatestCamera(request['camera'],request.get('resolution',720),cv2)+ elif mode=='video' and request.get('path'):+ cap=cv2.VideoCapture(request['path'])+ if not cap.isOpened():raise RuntimeError('Cannot open the selected video.')+ except Exception as exc:+ release_inputs();source=None+ send(pipe,{'type':'error','recoverable':True,'text':str(exc),'generation':generation,'request':request['request']});continue+ if mode=='idle':+ send(pipe,{'type':'status','idle':True,'text':'PEAR ready · Open a video or select a webcam.','generation':generation,'request':request['request']});continue+ if options!=last_options:+ if last_options is None or options[0]!=last_options[0]:+ model.previous=None;placement.reset();references.clear()+ else:placement.reset_filter()+ smooth.reset();last_options=options+ reset_id=int(request.get('bone_reset',0))+ if reset_id>reset_handled:+ reset_handled=reset_id;reset_warning=''+ reference=references.get(request.get('reset_pose'))+ if request.get('reset_pose') is not None:+ if reference is None:reset_warning='Reset Bones: displayed pose expired. Pause the video or try again.'+ else:+ send(pipe,{'type':'status','text':'Resetting bones from the displayed pose…','generation':generation})+ try:rig.calibrate(*reference);calibration_pose=request['reset_pose']+ except (ValueError,RuntimeError) as exc:reset_warning='Reset Bones: '+str(exc)+ if mode=='camera':+ try:item=camera.take()+ except Exception as exc:+ release_inputs();source=None+ send(pipe,{'type':'error','recoverable':True,'text':str(exc),'generation':generation,'request':request['request']});continue+ if item is None:continue+ image,timestamp=item;index=frame_number;frame_number+=1+ image=rotate_frame(image,options[0])+ started=time.perf_counter()+ elif cap:+ started=time.perf_counter();index=int(request.get('frame',0));fps=max(float(cap.get(cv2.CAP_PROP_FPS)),1.);timestamp=index/fps+ playing=bool(request.get('pair_video'))+ forward=playing and last_playing and last_index is not None and 0<(index-last_index)/fps<=.25+ continuous=forward and last_epoch==generation+ if not continuous:+ smooth.reset();placement.reset_filter()+ if not forward and index!=last_index:model.previous=None+ # One requested frame, one prediction. A seek seeds the filter+ # from that pose; it never reconstructs hidden history frames.+ if last_index is None or not last_index<index<=last_index+8:cap.set(cv2.CAP_PROP_POS_FRAMES,index)+ else:+ for _ in range(index-last_index-1):cap.grab()+ ok,image=cap.read();last_index=index;last_epoch=generation;last_playing=playing+ if not ok:+ smooth.reset();model.previous=None+ send(pipe,{'type':'missing','generation':generation,'request':request['request'],'pair_video':bool(request.get('pair_video')),'mode':'video','frame':index,'timeline_frame':request.get('timeline_frame',index),'text':'Cannot decode this video frame.'});continue+ image=rotate_frame(image,options[0])+ else:continue+ result=model.run(image,parameter_filter=smooth if options[1] else None,timestamp=timestamp)+ meta={'type':'frame' if result else 'missing','generation':generation,'request':request['request'],'frame':index,'mode':mode,+ 'pair_video':bool(request.get('pair_video')),'timeline_frame':request.get('timeline_frame',index),'requested_at':request.get('requested_at',time.monotonic()),'timestamp':timestamp,+ 'smoothing':options[1],'smoothing_strength':strength,'rotation':options[0],'context_frames':0,'inference_frames':1}+ arrays={}+ if result:+ pose_id+=1+ if rig.rest is None:+ send(pipe,{'type':'status','text':'Calibrating fixed bone lengths…','generation':generation})+ rig.calibrate(result['body'],result['flame']);calibration_pose=pose_id+ v,j,rot,facing=rig.pose(result['body'],result['camera'])+ v,j=placement.points(v,j,result['camera'],result['crop_bbox'],result['image_size'],smoothing=options[1],timestamp=timestamp,strength=strength)+ arrays.update(bounds=np.ascontiguousarray(v[:,[0,2,1]]*[1,1,-1],dtype='float32'),joints=np.ascontiguousarray(j[:,[0,2,1]]*[1,1,-1],dtype='float32'),rotations=rot,bone_facing=facing)+ references.remember(pose_id,result['body'],result['flame'])+ meta.update(render_mode='bones',pose_id=pose_id,bone_revision=rig.revision,calibration_pose=calibration_pose,+ bone_reset_handled=reset_handled,bone_reset_warning=reset_warning)+ meta['ms']=round((time.perf_counter()-started)*1000,2)+ meta['peak_vram_mib']=round(torch.cuda.max_memory_allocated()/1024**2,1)+ else:smooth.reset();model.previous=None;meta['text']='No person visible.'+ if mode in ('camera','video'):+ h,w=image.shape[:2];scale=min(1,1280/w,720/h)+ if scale<1:image=cv2.resize(image,(round(w*scale),round(h*scale)))+ arrays['image']=np.ascontiguousarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB))+ send(pipe,meta,**arrays)+ except (BrokenPipeError,EOFError):pass+ except Exception as exc:+ traceback.print_exc()+ try:send(pipe,{'type':'error','text':str(exc),'generation':locals().get('generation')})+ except (OSError,EOFError):pass+ finally:+ release_inputs()++class LatestCamera:+ def __init__(self,device,height,cv):+ self.cv=cv;self.condition=threading.Condition();self.latest=None;self.error=None;self.stop=False;self.cap=None+ self.thread=threading.Thread(target=self.run,args=(device,height),daemon=True);self.thread.start()+ def run(self,device,height):+ try:+ for backend,index in ((self.cv.CAP_MSMF,device.get('mf_index')),(self.cv.CAP_DSHOW,device.get('ds_index'))):+ if index is None:continue+ cap=None+ try:+ cap=self.cv.VideoCapture(int(index),backend)+ if cap.isOpened():+ cap.set(self.cv.CAP_PROP_FRAME_WIDTH,1280 if height==720 else 640);cap.set(self.cv.CAP_PROP_FRAME_HEIGHT,height)+ cap.set(self.cv.CAP_PROP_FPS,30)+ ok,im=cap.read()+ if ok:self.cap=cap;break+ except Exception:pass+ if cap:cap.release()+ if self.cap is None:raise RuntimeError('Cannot open this webcam. Close other camera applications and try again.')+ while not self.stop:+ with self.condition:self.latest=(im,time.monotonic());self.condition.notify_all()+ ok,im=self.cap.read()+ if not ok:raise RuntimeError('Webcam disconnected or stopped delivering frames.')+ except Exception as e:+ with self.condition:self.error=str(e);self.condition.notify_all()+ finally:+ if self.cap:self.cap.release()+ def take(self):+ with self.condition:+ if self.latest is None and not self.error:self.condition.wait(.2)+ if self.error:raise RuntimeError(self.error)+ item=self.latest;self.latest=None;return item+ def close(self):+ self.stop=True;self.thread.join(2)+ if self.thread.is_alive():raise RuntimeError('Camera did not stop; restart PEAR to release the device.')diff --git a/mocap/pear_models.py b/mocap/pear_models.pynew file mode 100644index 0000000..23c3fae--- /dev/null+++ b/mocap/pear_models.py@@ -0,0 +1,66 @@+"""Scoped PEAR assets; registered geometry is imported locally, never bundled."""+from pathlib import Path+import json,os,zipfile,uuid,shutil+from .paths import ROOT,MODELS+from .storage import sha256,atomic_json++REV='513a74e70a6b4bdecc90ac84ef989c17fe415a9e'+ASSETS=[dict(key='pear',name='Live Pose / PEAR',relative='pear/pear_model.pt',url='https://huggingface.co/BestWJH/PEAR_models',+ minimum_bytes=2685908343,download_url=f'https://huggingface.co/BestWJH/PEAR_models/resolve/{REV}/pear_model.pt',+ expected_sha256='be82dfa06e7b0608c6440058dfa0794d9b2ceee69f6e5b09bf41bb0076abeb18'),+ dict(key='pear_yolo',name='PEAR Person Detection / YOLOv8s',relative='yolo/yolov8s.pt',+ url='https://github.com/ultralytics/assets/releases/tag/v8.3.0',minimum_bytes=22588772,+ download_url='https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov8s.pt',+ expected_sha256='1f47a78bf100391c2a140b7ac73a1caae18c32779be7d310658112f7ac9aa78a'),+ dict(key='pear_geometry',name='PEAR / SMPL-X 2020 + FLAME Geometry',relative='pear/geometry.json',url='https://github.com/Pixel-Talk/PEAR#-preparation',minimum_bytes=1)]+KEYS=('pear','pear_geometry','pear_yolo')+INSTRUCTIONS={'pear':'Download pear_model.pt from the linked official checkpoint, then import it here.',+ 'pear_geometry':'1. Review and accept the SMPL-X and FLAME provider terms; register or sign in where required. PEAR needs SMPL-X 2020 and FLAME 2020, not the standard SMPL-X v1.1 or MAMMA locked-head models.\n2. Open PEAR Preparation below. Use its official Google Drive assets bundle link to obtain assets.zip.\n3. Import the original assets.zip here. The app validates its SHA-256 and extracts only the required geometry files. The source ZIP is left unchanged and is not copied into the models folder.\n4. The geometry bundle has separate provider restrictions; it is not redistributed by RGB MoCap.'}++def spec():return json.loads((ROOT/'installer/pear-assets.json').read_text(encoding='utf8'))++def geometry_folder():+ state=json.loads((MODELS/'pear/geometry.json').read_text(encoding='utf8'))+ folder=(MODELS/'pear'/state['folder']).resolve()+ if not folder.is_relative_to((MODELS/'pear').resolve()):raise ValueError('Invalid PEAR geometry path')+ expected=spec()+ if state.get('bundle_sha256')!=expected['bundle_sha256']:raise ValueError('PEAR geometry bundle changed')+ for item in expected['files']:+ p=(folder/item['path']).resolve()+ if not p.is_relative_to(folder):raise ValueError('Invalid asset path')+ st=p.stat()+ if state['files'].get(item['path'])!=[st.st_size,st.st_mtime_ns] or st.st_size!=item['bytes']:raise ValueError('PEAR geometry changed; import the bundle again')+ return folder++def geometry_ready():+ try:geometry_folder();return True+ except (OSError,ValueError,KeyError,TypeError):return False++def import_bundle(source):+ source=Path(source);expected=spec()+ if source.stat().st_size!=expected['bundle_bytes'] or sha256(source)!=expected['bundle_sha256']:raise ValueError('Select the original assets.zip linked by PEAR Preparation; the bundle hash does not match.')+ target=MODELS/'pear'/('geometry-'+uuid.uuid4().hex)/'assets';target.mkdir(parents=True)+ try:+ linked={}+ with zipfile.ZipFile(source) as z:+ names={i.filename.replace('\\','/'):i for i in z.infolist() if not i.is_dir()}+ for item in expected['files']:+ matches=[k for k in names if k==item['member']]+ if len(matches)!=1:raise ValueError('Missing or ambiguous PEAR asset: '+item['path'])+ out=(target/item['path']).resolve()+ if not out.is_relative_to(target.resolve()):raise ValueError('Unsafe asset path')+ out.parent.mkdir(parents=True,exist_ok=True)+ prior=linked.get(item['sha256'])+ if prior is not None:+ try:os.link(prior,out)+ except OSError:shutil.copy2(prior,out)+ else:+ with z.open(names[matches[0]]) as inp,out.open('wb') as stream:shutil.copyfileobj(inp,stream,1024**2)+ if out.stat().st_size!=item['bytes'] or sha256(out)!=item['sha256']:raise ValueError('Invalid PEAR geometry: '+item['path'])+ linked[item['sha256']]=out+ files={i['path']:[(target/i['path']).stat().st_size,(target/i['path']).stat().st_mtime_ns] for i in expected['files']}+ receipt=MODELS/'pear/geometry.json';atomic_json(receipt,dict(version=1,folder=target.relative_to(MODELS/'pear').as_posix(),bundle_sha256=expected['bundle_sha256'],files=files))+ return receipt+ except Exception:+ # Preserve old generations and a failed staging folder for diagnosis.+ raisediff --git a/mocap/pear_runtime.py b/mocap/pear_runtime.pynew file mode 100644index 0000000..0c30077--- /dev/null+++ b/mocap/pear_runtime.py@@ -0,0 +1,43 @@+"""A small PEAR support profile over the existing read-only shared runtime."""+from pathlib import Path+from functools import lru_cache+import hashlib,json+from .paths import ROOT++@lru_cache(maxsize=1)+def identity():+ names=['installer/pear-sources.json','installer/pear_adapters.py','tools/setup_pear.py','mocap/runtime_registry.py']+ return hashlib.sha256(b''.join((ROOT/name).read_bytes() for name in names)).hexdigest()++def base_identity():+ data=json.loads((ROOT/'SETUP_RECEIPT.json').read_text(encoding='utf8'))+ value=data['group_ids']['shared']+ if not isinstance(value,str) or not value:raise ValueError('Shared runtime receipt is unavailable')+ return value+++def configuration():+ data=json.loads((ROOT/'.setup/pear-runtime.json').read_text(encoding='utf8'))+ folder=(ROOT/data['folder']).resolve()+ if not folder.is_relative_to((ROOT/'runtime_pear').resolve()) or data.get('identity')!=identity() or data.get('base_identity')!=base_identity():raise ValueError('PEAR support profile needs installation')+ if not isinstance(data.get('files'),dict) or not {'engine/inference_images.py','packages/roma/__init__.py','packages/pytorch3d/transforms/rotation_conversions.py'}<=data['files'].keys():raise ValueError('Incomplete PEAR support inventory')+ for name,stamp in data['files'].items():+ p=(folder/name).resolve()+ if not p.is_relative_to(folder):raise ValueError('Invalid PEAR support path')+ st=p.stat()+ if [st.st_size,st.st_mtime_ns]!=stamp:raise ValueError('PEAR support files changed; rerun install.cmd')+ return folder++def engine_folder():return configuration()/'engine'++def status():+ try:configuration();return True,'PEAR support files ready · shared runtime'+ except (OSError,ValueError,KeyError,TypeError):return False,'Run install.cmd to prepare PEAR support, then prepare models in Model Manager.'++def activate():+ import sys,os+ folder=configuration()+ sys.dont_write_bytecode=True+ sys.path[:0]=[str(folder/'packages'),str(folder/'engine')]+ os.environ.setdefault('OMP_NUM_THREADS','4');os.environ.setdefault('MKL_NUM_THREADS','4')+ return folder/'engine'diff --git a/mocap/pear_ui.py b/mocap/pear_ui.pynew file mode 100644index 0000000..dd667a6--- /dev/null+++ b/mocap/pear_ui.py@@ -0,0 +1,394 @@+"""Transient live tool; offline projects and committed motion remain untouched."""+import time,subprocess,re,threading+import numpy as np+from PySide6.QtCore import Qt,QTimer+from PySide6.QtGui import QImage+from PySide6.QtWidgets import QWidget,QHBoxLayout,QVBoxLayout,QComboBox,QPushButton,QLabel,QCheckBox,QDoubleSpinBox,QMessageBox,QGroupBox,QSizePolicy++class CameraScan:+ def __init__(self):+ self.devices=None;self.cancelled=threading.Event();self.process=None+ def start(self):threading.Thread(target=self.run,daemon=True).start()+ def cancel(self):+ self.cancelled.set()+ if self.process and self.process.poll() is None:+ try:self.process.terminate()+ except OSError:pass+ def run(self):+ devices=[]+ try:+ from PySide6.QtMultimedia import QMediaDevices+ devices=[dict(name=d.description(),id=bytes(d.id()).hex(),mf_index=i) for i,d in enumerate(QMediaDevices.videoInputs())]+ except (ImportError,RuntimeError):pass+ try:+ from .paths import ROOT+ if self.cancelled.is_set():return+ self.process=subprocess.Popen([str(ROOT/'tools/bin/ffmpeg.exe'),'-hide_banner','-list_devices','true','-f','dshow','-i','dummy'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))+ if self.cancelled.is_set():self.cancel()+ _,error=self.process.communicate(timeout=8)+ names=re.findall(r'"([^"\r\n]+)" \(video\)',error.decode('utf8',errors='replace'))+ for index,name in enumerate(names):+ matches=[d for d in devices if d['name']==name and 'mf_index' in d]+ if len(matches)==1 and names.count(name)==1:matches[0]['ds_index']=index+ elif not matches:devices.append(dict(name=name,id='dshow:'+name+':'+str(index),ds_index=index))+ except (OSError,subprocess.TimeoutExpired):+ if self.process:+ self.cancel();self.process.communicate()+ finally:self.devices=devices++class PearWorkspace:+ def init_pear(self):+ self._pear_active=False;self._pear_failed=False;self.pear_session=None;self.pear_generation=0;self.pear_request=0;self._pear_last=None+ self._pear_scan_cache_at=0;self._pear_probe_at=0;self._pear_guard_at=0;self._pear_camera_state=None;self._pear_camera_scan=None;self._pear_closing=[]+ self._pear_presented_request=-1+ self._pear_ready=False+ self._pear_running=False+ self._pear_restart=0+ self._pear_source_signature=None+ self._pear_bone_reset=0;self._pear_reset_pose=None;self._pear_reset_pending=False+ self._pear_raw_pose=None;self._pear_world_anchor=None;self._pear_position_revision=0++ def build_pear_header(self,header):+ self.pear_header=QWidget();row=QHBoxLayout(self.pear_header);row.setContentsMargins(0,0,0,0)+ row.addWidget(QLabel('Webcam'))+ self.pear_camera=QComboBox();self.pear_camera.setMinimumWidth(130);self.pear_camera.setMaximumWidth(260)+ self.pear_camera.addItem('None — use video',None)+ self.pear_camera.setToolTip('Choose video or a webcam, then click Start Live Tracking. Close other camera apps first.')+ row.addWidget(self.pear_camera)+ self.pear_refresh=QPushButton('↻');self.pear_refresh.setFixedWidth(28);self.pear_refresh.setToolTip('Refresh connected webcams.')+ row.addWidget(self.pear_refresh);self.pear_refresh.clicked.connect(lambda:self.pear_scan_cameras(force=True))+ self.pear_camera.currentIndexChanged.connect(self.pear_source_changed)+ header.insertWidget(1,self.pear_header);self.pear_header.hide()+ self.pear_scan_timer=QTimer(self);self.pear_scan_timer.setInterval(100);self.pear_scan_timer.timeout.connect(self.pear_finish_scan)++ def build_pear_settings(self):+ self.pear_page=QWidget();self.pear_page.setProperty("motion_tool","pear");outer=QVBoxLayout(self.pear_page);outer.setContentsMargins(0,0,0,0);outer.setAlignment(Qt.AlignTop)+ self.pear_page.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Maximum)+ group=QGroupBox("PEAR Settings");outer.addWidget(group);layout=QVBoxLayout(group);layout.setSpacing(8);layout.setAlignment(Qt.AlignTop)+ self.pear_world_position=QCheckBox('World Position');self.pear_world_position.setChecked(True)+ self.pear_world_position.setToolTip('Move the pelvis using estimated position. Off fixes its current position, including height; rotation is unchanged.')+ layout.addWidget(self.pear_world_position);self.pear_world_position.toggled.connect(self.pear_position_changed)+ self.pear_smoothing=QCheckBox('One Euro Filter');self.pear_smoothing.setChecked(True)+ self.pear_smoothing.setToolTip('Reduce motion jitter in video and webcam input.')+ layout.addWidget(self.pear_smoothing)+ strength_row=QHBoxLayout();strength_row.addWidget(QLabel('Filter Strength'))+ self.pear_strength=QDoubleSpinBox();self.pear_strength.setRange(1,100);self.pear_strength.setDecimals(0);self.pear_strength.setValue(50);self.pear_strength.setSingleStep(5)+ self.pear_strength.setToolTip('Higher values reduce jitter but add more delay.')+ strength_row.addWidget(self.pear_strength);layout.addLayout(strength_row)+ self.pear_smoothing.toggled.connect(self.pear_strength.setEnabled)+ self.pear_strength.valueChanged.connect(self.pear_filter_changed)+ layout.addWidget(QLabel('Rotation (degrees)'))+ self.pear_rotation=QDoubleSpinBox();self.pear_rotation.setRange(-360,360);self.pear_rotation.setDecimals(1);self.pear_rotation.setSingleStep(90)+ self.pear_rotation.setToolTip('Rotate video or webcam images before display and tracking. Positive values turn clockwise; 90 turns right, −90 turns left. The original video file is unchanged.')+ layout.addWidget(self.pear_rotation)+ self.pear_resolution=QComboBox();self.pear_resolution.addItem('Webcam 1280 × 720',720);self.pear_resolution.addItem('Webcam 640 × 480',480)+ self.pear_resolution.setToolTip('Requested webcam capture size. Actual size depends on the driver. Lower resolution may reduce camera and detector cost.')+ layout.addWidget(self.pear_resolution)+ self.pear_status=QLabel('Click Start Live Tracking to begin.');self.pear_status.setWordWrap(True);layout.addWidget(self.pear_status)+ self.pear_status.setToolTip('Fixed-length body and finger bones, without per-frame body mesh calculation. Live preview only; no recording, correction, retargeting or export. Pelvis placement assumes a fixed camera.')+ self.pear_tracking_button=QPushButton('Start Live Tracking');layout.addWidget(self.pear_tracking_button);self.pear_tracking_button.clicked.connect(self.pear_toggle_tracking)+ self.pear_tracking_button.setToolTip('Start tracking, or stop and release the models and webcam.')+ self.pear_reset_button=QPushButton('Reset Bones');self.pear_reset_button.setEnabled(False);layout.addWidget(self.pear_reset_button)+ self.pear_reset_button.setToolTip('Recalculate fixed bone lengths from the displayed pose. Video playback pauses. Models stay loaded.')+ self.pear_reset_button.clicked.connect(self.pear_reset_bones)+ for signal in (self.pear_smoothing.toggled,self.pear_rotation.valueChanged,self.pear_resolution.currentIndexChanged):signal.connect(self.pear_source_changed)+ self.model_pages.addWidget(self.pear_page)+ self.pear_poll_timer=QTimer(self);self.pear_poll_timer.setInterval(16);self.pear_poll_timer.timeout.connect(self.pear_poll)++ def pear_scan_cameras(self,force=False):+ if not force and time.monotonic()-self._pear_scan_cache_at<5:return+ if self._pear_camera_scan is not None:return+ self._pear_camera_scan=CameraScan();self.pear_refresh.setEnabled(False)+ self._pear_camera_scan.start();self.pear_scan_timer.start()++ def pear_finish_scan(self):+ scan=self._pear_camera_scan+ if scan is None or scan.devices is None:return+ devices=scan.devices;self._pear_scan_cache_at=time.monotonic();self._pear_camera_scan=None;self.pear_scan_timer.stop()+ current=self.pear_camera.currentData();self.pear_camera.blockSignals(True);self.pear_camera.clear();self.pear_camera.addItem('None — use video',None)+ for device in devices:self.pear_camera.addItem(device['name'],device)+ index=next((i for i in range(1,self.pear_camera.count()) if current and self.pear_camera.itemData(i).get('id')==current.get('id')),0)+ self.pear_camera.setCurrentIndex(index);self.pear_camera.blockSignals(False);self.pear_refresh.setEnabled(True)+ if current and current!=self.pear_camera.currentData():self.pear_source_changed()++ def pear_stop_scan(self):+ self.pear_scan_timer.stop()+ if self._pear_camera_scan:self._pear_camera_scan.cancel()+ self._pear_camera_scan=None;self.pear_refresh.setEnabled(True)++ def pear_select_model(self):+ selected=self.model_choice.currentData()=='pear'+ if selected:+ if self.busy or self.contact_saving:+ self.model_choice.blockSignals(True);self.model_choice.setCurrentIndex(self.model_choice.findData(self._selected_tool));self.model_choice.blockSignals(False);return True+ if not self._pear_active:+ self.stop_playback();self.remember_workspace_model()+ self._pear_active=True;self._pear_running=False;self._pear_last=None+ m=self.motion_view+ self._pear_camera_state={k:np.copy(getattr(m,k)) if isinstance(getattr(m,k),np.ndarray) else getattr(m,k) for k in ('yaw','pitch','distance','pan','scene_center','body_height','scene_span','auto_fit')}+ self._pear_contact_edit=self.slider.contact_edit_enabled;self._pear_status_text=self.status.text();self._pear_bone_tooltip=self.bone_overlay.toolTip();self._pear_timeline_help=self.timeline_help_dialog.text()+ self._pear_observations=self.video_view.show_observations;self.video_view.show_observations=False+ m.live_active=True;m.live_data=None;m.live_asset=None;m.live_message='Open a video or select a webcam.';m.live_frame_first=True+ self.pear_scan_cameras();self.pear_poll_timer.start()+ self.pear_source_changed()+ self.pear_sync_controls();return True+ if self._pear_active:self.pear_leave()+ return False++ def pear_leave(self):+ if not self._pear_active:return+ self._pear_active=False;self.pear_poll_timer.stop();self.pear_close_session()+ self.pear_header.hide();self.timeline_panel.setEnabled(True);self.video_view.set_external_frame(None)+ self.video_view.show_observations=self._pear_observations+ self.video_overlay.show();self.status.setText(self._pear_status_text)+ self.bone_overlay.setToolTip(self._pear_bone_tooltip)+ self.timeline_help_dialog.setText(self._pear_timeline_help)+ for check in self.viewport_checks.values():check.show()+ self.slider.contact_edit_enabled=self._pear_contact_edit+ m=self.motion_view;m.live_active=False;m.live_data=None;m.live_asset=None+ for k,v in self._pear_camera_state.items():setattr(m,k,v)+ m.release_live_renderer();m.update()+ for widget in (self.people_panel,self.find_person_button,self.correction_group,self.compute_mode.parentWidget(),self.run_button,self.mesh_button,self.cancel_button,self.viewport_footer):widget.show()+ self.import_character_action.setEnabled(True);self.model_pages.setVisible(True)+ self.slider.live_preview=False;self.slider._cache_key=None;self.slider.update()++ def pear_close_session(self):+ self._pear_running=False+ self._pear_reset_pending=False;self._pear_reset_pose=None+ self._pear_raw_pose=None;self._pear_world_anchor=None+ if self.pear_session:+ self._pear_closing.append(self.pear_session);self.pear_session.close();self.pear_session=None+ self._pear_last=None+ self._pear_ready=False+ if self._pear_active:+ self.motion_view.live_data=None;self.motion_view.live_asset=None;self.motion_view.release_live_renderer()+ self.pear_update_tracking_button()++ def pear_update_tracking_button(self):+ closing=any(s.process.poll() is None for s in self._pear_closing)+ self.pear_tracking_button.setText('Stop' if self._pear_running else 'Stopping…' if closing else 'Start Live Tracking')+ self.pear_tracking_button.setEnabled(self._pear_running or not closing)+ self.pear_reset_button.setEnabled(self._pear_running and self._pear_ready and self.motion_view.live_data is not None and not self._pear_reset_pending)++ def pear_reset_bones(self):+ if not self.pear_reset_button.isEnabled():return+ meta=self.pear_last_metrics+ if self.pear_camera.currentData() is None:+ frame=int(meta['timeline_frame']);self.stop_playback();self.slider.setValue(frame);self.seek(frame)+ self._pear_bone_reset+=1;self._pear_reset_pose=meta['pose_id'];self._pear_reset_pending=True+ self._pear_last=None;self.pear_status.setText('Resetting bones from the displayed pose…')+ self.pear_update_tracking_button();self.pear_submit()++ def pear_position_changed(self,*_):+ self._pear_position_revision+=1+ current=self.motion_view.live_data+ self._pear_world_anchor=current['joints'][0].copy() if not self.pear_world_position.isChecked() and current is not None else None+ if self._pear_active and current is not None and self._pear_raw_pose is not None:+ self.pear_position_pose(self._pear_raw_pose)+ self.motion_view.live_key=('pear-position',self.pear_generation,self._pear_position_revision,self._pear_presented_request)+ self.motion_view.update()++ def pear_position_pose(self,pose):+ self._pear_raw_pose=pose+ if pose is None:self.motion_view.live_data=None;return+ if self.pear_world_position.isChecked():self.motion_view.live_data=pose;return+ if self._pear_world_anchor is None:self._pear_world_anchor=pose['joints'][0].copy()+ from .pear.projection import lock_position+ self.motion_view.live_data=lock_position(pose,self._pear_world_anchor)++ def pear_toggle_tracking(self):+ if not self._pear_active:return+ if self._pear_running:+ self._pear_running=False;self.pear_generation+=1+ self.stop_playback();self.pear_close_session()+ self.video_view.set_external_frame(None)+ self.pear_status.setText('Tracking stopped.')+ self.motion_view.live_message='Click Start Live Tracking to begin.';self.motion_view.update()+ if self.info:self.fps_label.setText(f"Source {self.info['fps']:.2f} fps")+ return+ if any(s.process.poll() is None for s in self._pear_closing):return+ from .pear_runtime import status+ from .models import missing+ ok,message=status()+ if not ok or missing('pear_assets'):+ self.pear_status.setText(message if not ok else 'Prepare missing PEAR models in Model Manager.');return+ self._pear_running=True;self._pear_failed=False;self._pear_probe_at=0+ self._pear_restart+=1;self.pear_update_tracking_button();self.pear_source_changed()++ def pear_sync_controls(self):+ from .models import missing+ from .pear_runtime import status+ ok,message=status();unavailable=missing('pear_assets')+ self.viewport_footer.show()+ for key,check in self.viewport_checks.items():check.setVisible(key=='show_grid')+ self.bone_overlay.setToolTip('Show fixed-length PEAR body and finger bones. Use Reset Bones to recalibrate their lengths from the displayed pose. Display only; no animation export in this mode.')+ self.mamma_thumbnails.hide()+ self.timeline_help_dialog.setText("PEAR live video preview\n\nOpen a video or select a webcam, then click Start Live Tracking. Stop releases the models and webcam.\n\nFor video, click or drag the frame ruler to infer the current frame. During playback, the processed video frame and its pose appear together with a small delay. Old requests are skipped. Pause or seek to inspect an exact frame.\n\nSelecting a webcam disables video timeline controls. No motion is recorded or exported in this mode.")+ self.video_overlay.hide();self.slider.contact_edit_enabled=False+ self.status.setText("PEAR live preview · Choose an input, then click Start Live Tracking.")+ self.pear_header.show();self.model_pages.setCurrentWidget(self.pear_page);self.model_pages.show()+ for widget in (self.people_panel,self.find_person_button,self.correction_group,self.compute_mode.parentWidget(),self.run_button,self.mesh_button,self.cancel_button,self.htd_refine,self.refine_description,self.footmr_refine,self.handflow_refine,self.footmr_description,self.refine_preview_note,self.analyze_button):widget.hide()+ self.models_group.setTitle('PEAR Models');self.readiness.setText('PEAR: '+('models ready' if not unavailable else str(len(unavailable))+' files missing'))+ self.readiness.setToolTip(message)+ self.export_action.setEnabled(False);self.save_project_action.setEnabled(False);self.import_character_action.setEnabled(False)+ self.slider.contacts_supported=False;self.slider.live_preview=True;self.slider._cache_key=None;self.slider.update()+ self.play_button.setEnabled(self.info is not None and self.video_readable and self.pear_camera.currentData() is None)+ if not ok or unavailable:+ self.pear_status.setText(message if not ok else 'Prepare missing PEAR models in Model Manager.')+ self.motion_view.live_message=self.pear_status.text();self.motion_view.update()+ self.model_choice.setEnabled(not self.busy and not self.contact_saving)+ self.models_button.setEnabled(not self.busy)+ if self.busy:self.pear_close_session()+ self.pear_update_tracking_button()++ def pear_source_changed(self,*_):+ if not self._pear_active:return+ self._pear_failed=False+ camera=self.pear_camera.currentData()+ path=self.video_view._source_key[0] if self.video_view._source_key and self.video_readable and camera is None else None+ signature=(camera,path,self.pear_rotation.value(),self.pear_resolution.currentData() if camera else None,self._pear_restart)+ keep_pair=signature==self._pear_source_signature and self.motion_view.live_data is not None+ self._pear_source_signature=signature+ self.pear_generation+=1;self._pear_last=None+ if not keep_pair:+ self._pear_reset_pending=False;self._pear_reset_pose=None+ self._pear_raw_pose=None;self._pear_world_anchor=None+ self.motion_view.live_data=None;self.motion_view.live_frame_first=True+ self.motion_view.live_message='Waiting for live tracking…';self.motion_view.update()+ self.timeline_panel.setEnabled(camera is None)+ self.pear_rotation.setEnabled(True);self.pear_smoothing.setEnabled(True);self.pear_resolution.setEnabled(camera is not None)+ if not self._pear_running:+ self.video_view.set_external_frame(None)+ self.pear_status.setText('Click Start Live Tracking to begin.')+ self.motion_view.live_message=self.pear_status.text();self.motion_view.update()+ self.pear_sync_controls();return+ if not keep_pair:+ if camera:+ self.stop_playback();self.video_view.set_external_frame(QImage())+ elif self.video_readable:self.video_view.set_external_frame(QImage())+ else:self.video_view.set_external_frame(None)+ self.pear_sync_controls();self.pear_submit()++ def pear_filter_changed(self,*_):+ if self._pear_active:self._pear_last=None;self.pear_submit()++ def pear_submit(self):+ if not self._pear_active or not self._pear_running or self._pear_failed or self.busy:return+ camera=self.pear_camera.currentData();view=self.video_view+ path=view._source_key[0] if view._source_key and self.video_readable else None+ playing=self.timer.isActive() and camera is None+ value=dict(generation=self.pear_generation,mode='camera' if camera else 'video' if path else 'idle',camera=camera,path=None if camera else path,frame=view.requested_index,+ timeline_frame=view.timeline_requested_index,pair_video=playing,restart=self._pear_restart,+ rotation=self.pear_rotation.value(),smoothing=self.pear_smoothing.isChecked(),smoothing_strength=self.pear_strength.value(),resolution=self.pear_resolution.currentData())+ value.update(bone_reset=self._pear_bone_reset,reset_pose=self._pear_reset_pose)+ if value==self._pear_last:return+ self._pear_source_signature=(camera,value['path'],value['rotation'],value['resolution'] if camera else None,value['restart'])+ if not self.pear_session:+ if any(s.process.poll() is None for s in self._pear_closing):+ self.pear_status.setText('Stopping previous PEAR session…');return+ if time.monotonic()-self._pear_probe_at<1:return+ self._pear_probe_at=time.monotonic()+ from .pear_runtime import status+ from .models import missing+ if not status()[0] or missing('pear_assets'):return+ from .pear.session import Session+ try:self.pear_session=Session()+ except Exception as e:+ self._pear_running=False;self.pear_update_tracking_button();self.pear_status.setText(str(e));return+ self.pear_started=time.monotonic();self._pear_failed=False;self._pear_ready=False+ self._pear_last=value.copy();self.pear_request+=1;value['request']=self.pear_request;value['requested_at']=time.monotonic()+ if path and not view.external_mode:view.set_external_frame(view.frame if view.frame is not None else QImage())+ self.pear_session.submit(value)+ if not camera and not playing:+ if self.motion_view.live_data is None:self.motion_view.live_message='Tracking current video frame…' if path else 'Open a video or select a webcam.'+ else:self.pear_status.setText('Updating current video frame…')+ self.motion_view.update()++ def pear_seek(self,index):+ if not self._pear_active or not self._pear_running or self.pear_camera.currentData() is not None:return+ # Ordinary forward playback accepts completed frames with bounded delay.+ # A scrub or loop starts a new epoch: old results must not cross it.+ if index!=self.video_view.timeline_requested_index and (not self.playback_tick or index<self.video_view.timeline_requested_index):+ self.pear_generation+=1;self._pear_last=None+ if not (self.timer.isActive() and self.video_view.external_mode):+ if self.motion_view.live_data is None:self.motion_view.live_message='Tracking current video frame…'+ else:self.pear_status.setText('Updating current video frame…')+ self.motion_view.update()++ def pear_playback_stopped(self):+ if not self._pear_active or not self._pear_running or self.pear_camera.currentData() is not None:return+ if self.info:self.fps_label.setText(f"Source {self.info['fps']:.2f} fps")+ if self.video_view.external_mode:+ self.pear_generation+=1;self._pear_last=None+ if self.motion_view.live_data is None:self.motion_view.live_message='Tracking current video frame…'+ else:self.pear_status.setText('Updating current video frame…')+ # Keep the last correctly rotated image/pose pair until the exact+ # paused request arrives. Do not briefly restore unrotated pixels.+ self.motion_view.update()++ def pear_poll(self):+ self._pear_closing=[s for s in self._pear_closing if s.process.poll() is None]+ if not self._pear_active:return+ self.pear_update_tracking_button()+ if not self._pear_running:return+ self.pear_submit()+ if not self.pear_session:return+ if time.monotonic()-self._pear_guard_at>.5:+ self._pear_guard_at=time.monotonic()+ idle=self._pear_ready and (self._pear_failed or (self.pear_camera.currentData() is None and not self.timer.isActive() and self._pear_presented_request==self.pear_request))+ if idle:self.pear_session.guard.output()+ warning=self.pear_session.guard.check()+ if warning:+ self._pear_raw_pose=None+ self.pear_status.setText(warning);self.motion_view.live_data=None;self.motion_view.live_message=warning+ self.pear_close_session();self._pear_failed=True;self.log.append('PEAR: '+warning);self.motion_view.update();return+ top,packet=self.pear_session.poll()+ if top:+ self._pear_ready=True+ meta,a=top+ self.motion_view.live_asset=dict(key='pear-live',render_mode='bones') if meta.get('render_mode')=='bones' else dict(key='pear-live',topology_key='pear-live',mode='raw',vertex_count=meta['vertices'],**{k:a[k] for k in ('faces','offsets','neighbors')})+ self.motion_view.live_parents=a['parents']+ if packet:+ meta,a=packet;kind=meta['type']+ if kind=='error':+ if meta.get('generation') is not None and meta['generation']!=self.pear_generation:+ if meta.get('recoverable'):return+ self.pear_close_session();return+ self._pear_raw_pose=None+ self.pear_status.setText(meta['text']);self.motion_view.live_data=None;self.motion_view.live_message=meta['text'];self.motion_view.update()+ if meta.get('recoverable'):+ self._pear_failed=True;self.log.append('PEAR: '+meta['text']);return+ self.log.append('PEAR: '+meta['text']);self.pear_close_session();self._pear_failed=True;return+ if kind=='status':+ if meta.get('generation',self.pear_generation)!=self.pear_generation:return+ if meta.get('idle'):self._pear_presented_request=meta['request']+ self.pear_status.setText(meta['text']);self.motion_view.live_message=meta['text'];self.motion_view.update();return+ if meta.get('generation')!=self.pear_generation:return+ if meta.get('mode')=='video':+ playing=self.timer.isActive() and self.pear_camera.currentData() is None+ if bool(meta.get('pair_video'))!=playing:return+ if playing:+ if meta.get('request',-1)<=self._pear_presented_request or ('image' not in a and kind!='missing'):return+ elif meta.get('request')!=self.pear_request:return+ self._pear_presented_request=meta.get('request',-1)+ if 'image' in a:+ im=a['image'];h,w,_=im.shape;self.video_view.set_external_frame(QImage(im.data,w,h,im.strides[0],QImage.Format_RGB888).copy())+ if meta.get('mode')=='video':self.video_view.index=meta['timeline_frame']+ if kind=='frame':a['rig_revision']=meta.get('bone_revision',0)+ self.pear_position_pose(a if kind=='frame' else None)+ self.motion_view.live_key=(self.pear_generation,meta.get('frame'),meta.get('request'),self._pear_position_revision)+ self.motion_view.live_message=meta.get('text','')+ if kind=='frame':+ if meta.get('bone_reset_handled',-1)>=self._pear_bone_reset:self._pear_reset_pending=False+ self.pear_last_metrics=meta+ ms=meta['ms'];self.pear_status.setText(meta.get('bone_reset_warning') or f'Live tracking · {ms:.0f} ms/frame · {1000/max(ms,1):.1f} inference fps')+ if meta.get('pair_video'):+ delay=max(0,(time.monotonic()-meta['requested_at'])*1000)+ self.pear_last_metrics['display_delay_ms']=delay+ self.fps_label.setText(f"Preview {meta['timeline_frame']+1} · {delay:.0f} ms delay")+ if self.motion_view.live_frame_first:self.motion_view.live_frame_first=False;self.motion_view.frame_all()+ else:self.pear_status.setText(meta.get('text','No person visible.'))+ self.pear_update_tracking_button()+ self.motion_view.update()+ elif self.pear_session and not self._pear_ready:+ self.pear_status.setText(f'Loading PEAR · {time.monotonic()-self.pear_started:.0f} s')diff --git a/mocap/project_workspace.py b/mocap/project_workspace.pyindex b33d8e2..e3d6a19 100644--- a/mocap/project_workspace.py+++ b/mocap/project_workspace.py@@ -3,7 +3,7 @@ from pathlib import Pathimport jsonimport osfrom .storage import atomic_json-from .motion_tools import require_supported_tool, require_supported_project+from .motion_tools import require_offline_tool as require_supported_tool, require_supported_projectVERSION = 2diff --git a/mocap/project_workspace_ui.py b/mocap/project_workspace_ui.pyindex b222376..9794ec6 100644--- a/mocap/project_workspace_ui.py+++ b/mocap/project_workspace_ui.py@@ -48,6 +48,7 @@ class ModelWorkspace:for key in ('yaw','pitch','distance','pan','scene_center')},'target':self.motion_view.target().tolist()})def remember_workspace_model(self):+ if getattr(self,"_pear_active",False):returnroot=self.workspace_rootif root is None:returnif self.project is not None:diff --git a/mocap/timeline_editor.py b/mocap/timeline_editor.pyindex cae99d2..cbe61de 100644--- a/mocap/timeline_editor.py+++ b/mocap/timeline_editor.py@@ -260,6 +260,7 @@ class TimelineSlider(FootLockEditor,QSlider):p.drawText(QRectF(8, y, 53, row_height), Qt.AlignVCenter, label)p.setPen(QColor("#b1b9c1" if row == 0 else "#aebeb4"))text = self.video_track_label if row == 0 else ((self.person_name or "Body animation") if self.has_motion else "No motion data")+ if row==1 and getattr(self,"live_preview",False):text="PEAR live preview — no recording"left, right = self.clip_edges() if row == 0 else (self.LEFT, self.width() - self.RIGHT)left, right = max(self.LEFT, left), min(self.width() - self.RIGHT, right)p.drawText(QRectF(left + 12, y, max(0, right - left - 24), row_height), Qt.AlignVCenter, text)diff --git a/mocap/viewer.py b/mocap/viewer.pyindex 790111f..73915f8 100644--- a/mocap/viewer.py+++ b/mocap/viewer.py@@ -24,6 +24,8 @@ class VideoView(QWidget):super().__init__()self.setMinimumSize(440, 280)cv2.setNumThreads(1) # Preview uses one decoder, not a pool for each resize.+ self.external_mode=False+ self._external_saved=Noneself.frame = Noneself.boxes = self.observed = self.keypoints = self.confidence = Noneself.index = 0@@ -175,7 +177,21 @@ class VideoView(QWidget):if image is not None:self._present(index, image)+ def set_external_frame(self,image):+ if image is None:+ if not self.external_mode:return+ self.external_mode=False+ self.frame,self.source_size=self._external_saved+ self._external_saved=None+ self.seek(self.timeline_requested_index);self.update();return+ if not self.external_mode:self._external_saved=(self.frame,self.source_size)+ self.external_mode=True+ self.frame=None if image.isNull() else image+ if self.frame is not None:self.source_size=(image.width(),image.height())+ self.update()+def _present(self, index, image):+ if self.external_mode:returnself.index, self.frame = (self.timeline_requested_index if self.timeline_fps else index), imageself.update()self.frame_presented.emit(self.index)@@ -195,6 +211,7 @@ class VideoView(QWidget):index = max(0,round((index + self.timeline_start) * self.native_fps / self.timeline_fps))if self.decoder.length:index=min(index,self.decoder.length-1)self.requested_index = index+ if self.external_mode:returnimage = self.decoder.request(index)if image is not None:self._present(index, image)diff --git a/mocap/viewport.py b/mocap/viewport.pyindex 43f49c7..7c53a75 100644--- a/mocap/viewport.py+++ b/mocap/viewport.py@@ -9,7 +9,7 @@ from pathlib import Pathimport numpy as npfrom PySide6.QtCore import Qt, QPointF, QRectF, QLineF, Signalfrom PySide6.QtGui import QColor, QFont, QPainter, QPen, QPolygonF, QRadialGradient, QSurfaceFormat-from PySide6.QtWidgets import QWidget+from PySide6.QtWidgets import QWidget,QLabelfrom PySide6.QtOpenGLWidgets import QOpenGLWidgetfrom .preview_data import mapped_array, motion_summary, close_arrayfrom .foot_contacts import FOOT_COLORS@@ -38,6 +38,10 @@ class MotionView(ViewportBase):self.setMinimumSize(350, 280)self.setMouseTracking(True)self.setFocusPolicy(Qt.StrongFocus)+ self._pear_renderer=None+ self._pear_notice=QLabel(self);self._pear_notice.setWordWrap(True);self._pear_notice.setAlignment(Qt.AlignCenter);self._pear_notice.setAttribute(Qt.WA_TransparentForMouseEvents)+ self._pear_notice.setStyleSheet("color:#dddddd; background:transparent; font-size:14px; padding:20px;");self._pear_notice.hide()+ self.live_active=False;self.live_data=None;self.live_asset=None;self.live_frame_first=True;self.live_message="";self.live_key=Noneself.joints = Noneself.rotations = Noneself.mesh_frames = self.mesh_asset = self.mesh_renderer = None@@ -294,6 +298,10 @@ class MotionView(ViewportBase):self.update()def target(self):+ if self.live_active:+ target=self.scene_center.copy()+ if self.follow and self.live_data is not None:target[[0,2]]=self.live_data["joints"][0,[0,2]]+ return target+self.pantarget = self.scene_center.copy()if self.follow and self.people_scene is not None:actors=self.scene_actors()@@ -318,6 +326,10 @@ class MotionView(ViewportBase):self.update()def frame_all(self):+ if self.live_active:+ if self.live_data is not None:+ v=self.live_data.get("bounds",self.live_data.get("vertices"));self.scene_center=(v.min(0)+v.max(0))*.5;self.body_height=float(max(1.,np.ptp(v,axis=0).max()));self.scene_span=self.body_height+ self.fit_view();return# Explicit user framing may recenter. Replacing a corrected preview or# resizing the widget must retain the existing world-space camera Y.if self.people_scene is not None and self.people_scene.summary:@@ -437,6 +449,7 @@ class MotionView(ViewportBase):self.context().aboutToBeDestroyed.connect(self.cleanup_gl)def cleanup_gl(self):+ self.release_live_renderer()self.clear_characters()self.release_scene_renderers()if self.mesh_renderer is not None:@@ -495,6 +508,15 @@ class MotionView(ViewportBase):self.paint_scene(event)def paintGL(self):+ if self.live_active:+ from .pear.live_view import LiveRenderer+ if self._pear_renderer is None:self._pear_renderer=LiveRenderer(self)+ self._paint_camera=self.camera()+ try:self._pear_renderer.paint(self)+ except Exception as e:self.live_message='PEAR preview: '+str(e)+ self._pear_notice.setGeometry(self.rect());self._pear_notice.setText(self.live_message)+ self._pear_notice.setVisible(bool(self.live_message));return+ self._pear_notice.hide()self.paint_scene(None)def foot_lock_discs(self,index,joints,activity=None,floor=None):@@ -753,6 +775,12 @@ class MotionView(ViewportBase):text=self.mesh_error or '; '.join(warnings[:2])painter.drawText(self.rect().adjusted(18,80,-95,-80),Qt.AlignTop|Qt.TextWordWrap,text)+ def release_live_renderer(self):+ self._pear_notice.hide()+ if self._pear_renderer is not None and OPENGL_VIEW and self.isValid():+ self.makeCurrent();self._pear_renderer.close();self.doneCurrent()+ self._pear_renderer=None+def paint_scene(self, event):painter = QPainter(self)self._empty_people_notice=None@@ -797,6 +825,8 @@ class MotionView(ViewportBase):line3d([-edge, self.grid_floor + .001, 0], [edge, self.grid_floor + .001, 0], "#99515b", 1.1)line3d([0, self.grid_floor + .001, -edge], [0, self.grid_floor + .001, edge], "#4c759c", 1.1)painter.setRenderHint(QPainter.Antialiasing, True)+ if self.live_active:+ painter.setPen(QColor("#dddddd"));painter.drawText(self.rect(),Qt.AlignCenter|Qt.TextWordWrap,self.live_message);painter.end();returncorrection_plane_visible=self.draw_correction_floor(painter,lines3d)self.name_labels_presented=[]bone_actors=[]diff --git a/mocap/worker_progress.py b/mocap/worker_progress.pyindex a8813b3..a2ac6d1 100644--- a/mocap/worker_progress.py+++ b/mocap/worker_progress.py@@ -12,6 +12,9 @@ def emit(kind,**value):def main():stage=sys.argv[1] if len(sys.argv)>1 else ''+ if stage=='pear_live':+ from .pear.worker import main as live_main+ return live_main()if stage in ('prompthmr_prepare','prompthmr_publish'):from .compute_policy import configure_worker_cpuconfigure_worker_cpu(stage)diff --git a/mocap/workspace_ui.py b/mocap/workspace_ui.pyindex 7e33128..04b250e 100644--- a/mocap/workspace_ui.py+++ b/mocap/workspace_ui.py@@ -135,6 +135,7 @@ def build_workspace(w):w.video_view.metadata_ready.connect(w.video_ready)w.video_view.decode_error.connect(w.video_failed)video_panel, video_header = editor("Movie Clip", w.build_people_editor(w.video_view))+ w.build_pear_header(video_header)w.fps_label = QLabel("No clip loaded")w.fps_label.setObjectName("muted")w.fps_label.setMinimumWidth(0)@@ -148,6 +149,7 @@ def build_workspace(w):w.video_view.show_observations = enabledw.video_view.update()overlay.toggled.connect(toggle_overlay)+ w.video_overlay=overlayvideo_header.addWidget(overlay)motion_panel, motion_header = editor("3D Viewport", w.motion_view)w.bone_overlay=QCheckBox('Bone Overlay')@@ -172,9 +174,11 @@ def build_workspace(w):w.viewport_footer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)viewport_footer = QHBoxLayout(w.viewport_footer)viewport_footer.setContentsMargins(9, 3, 6, 3)+ w.viewport_checks={}for label, attribute in (("Floor Grid", "show_grid"), ("Correction Floor", "show_correction_floor"), ("Motion Path", "show_trajectory"),("Lock", "show_foot_locks"), ("Name", "show_names")):check = QCheckBox(label)+ w.viewport_checks[attribute]=checkcheck.setChecked(getattr(w.motion_view, attribute))check.setToolTip(tooltip_text({'show_grid': 'Show the reference grid at height zero. Does not change ground contact.', 'show_correction_floor': 'Show the correction floor height as an orange plane. Display only.', 'show_trajectory': 'Show the path followed by the person.', 'show_foot_locks': '', 'show_names': 'Show each person\'s name above their mesh. Rename people by right-clicking the People list. Display only.'}[attribute]))if attribute=='show_names':w.name_labels=check@@ -415,6 +419,7 @@ def build_workspace(w):w.model_pages.addWidget(w.exmr_page)w.build_mamma_settings()w.build_prompthmr_settings()+ w.build_pear_settings()shared_settings=QWidget()settings = QVBoxLayout(shared_settings)settings.setContentsMargins(0, 0, 0, 0)diff --git a/tools/check_source.py b/tools/check_source.pyindex 99da6ab..bd911dd 100644--- a/tools/check_source.py+++ b/tools/check_source.py@@ -5,7 +5,7 @@ from runtime_support import cache_dependency_filesROOT=Path(__file__).resolve().parents[1]SKIP={'.git','__pycache__','.bootstrap','.runtime','.cache','.setup','.venv','.venv-flow','.venv-hand','.venv-htd','.venv-exmr','build','dist','releases','models','projects','cache','character_scenes','.build-inputs','runtime','runtime_gui','runtime_flow','runtime_hand','runtime_htd','runtime_exmr','runtime_character','runtime_mamma'}-SKIP.add('runtime_prompthmr')+SKIP.update(('runtime_prompthmr','runtime_pear'))FORBIDDEN={'.exe','.dll','.pyd','.pyc','.whl','.pt','.pth','.ckpt','.safetensors','.onnx','.npz','.npy','.pkl','.fbx','.bvh','.blend','.mp4','.vrm','.pmx','.vmd','.pmd','.vpd','.pmm','.avi','.mov','.mkv','.webm','.zip','.7z'}def main():diff --git a/tools/git_managed_install.py b/tools/git_managed_install.pyindex 5c6271a..6f9956a 100644--- a/tools/git_managed_install.py+++ b/tools/git_managed_install.py@@ -76,6 +76,8 @@ def setup():raiserecover(ROOT,engine.remove_owned)if support_stage.exists():engine.remove_owned(folder,support_stage)+ from setup_pear import prepare as prepare_pear+ prepare_pear()pending.unlink()print('Installation complete. Existing models and projects were retained.',flush=True)diff --git a/tools/setup_pear.py b/tools/setup_pear.pynew file mode 100644index 0000000..e765383--- /dev/null+++ b/tools/setup_pear.py@@ -0,0 +1,63 @@+"""Prepare PEAR source/support files without upgrading an installed runtime."""+from pathlib import Path+import sys,json,hashlib,zipfile,shutil,os,argparse,uuid,subprocess,stat+ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT))+from mocap.storage import atomic_json,sha256+from mocap.pear_runtime import identity,base_identity,configuration+from installer.pear_adapters import adapt+from tools.session_lock import app_lock++def prepare(cache=None):+ """Called under the installer lock, after committing the shared base."""+ from tools.support_components import download+ lock=json.loads((ROOT/'installer/pear-sources.json').read_text())+ if not (ROOT/'runtime/python.exe').is_file():raise RuntimeError('Run install.cmd first.')+ try:current=configuration()+ except (OSError,ValueError,KeyError,TypeError):current=None+ if current is not None:+ print('Keeping verified PEAR support over the shared runtime.',flush=True)+ return current+ base=base_identity()+ folder=ROOT/'runtime_pear'/('support-'+identity()[:20]+'-'+uuid.uuid4().hex[:8]);folder.mkdir(parents=True)+ cache=Path(cache) if cache else ROOT/'.setup/pear-downloads';cache.mkdir(parents=True,exist_ok=True)+ try:+ for name,row in lock['sources'].items():+ print('Preparing PEAR support: '+name,flush=True)+ archive=download(cache,name,dict(row,filename=name+('.whl' if name=='roma' else '.zip')))+ with zipfile.ZipFile(archive) as z:+ for info in z.infolist():+ p=Path(info.filename)+ if p.is_absolute() or '..' in p.parts or '\\' in info.filename or ':' in info.filename or stat.S_ISLNK(info.external_attr >> 16):raise ValueError('Unsafe source archive')+ if info.file_size>512*1024**2:raise ValueError('Source file too large')+ if info.is_dir() or '__pycache__' in p.parts or p.suffix in ('.pyc','.pyo'):continue+ parts=p.parts[1:]+ target=None+ if name=='pear' and parts and (parts[0] in ['models','utils','configs'] or Path(*parts).as_posix() in ['inference_images.py','LICENSE.txt']):+ target=folder/'engine'/Path(*parts)+ elif name=='pytorch3d' and parts and (tuple(parts[:2]) in (('pytorch3d','transforms'),('pytorch3d','common')) or Path(*parts).as_posix() in ['pytorch3d/__init__.py','LICENSE','LICENSE_BSD','NOTICE']):+ target=folder/'packages'/Path(*parts)+ elif name=='roma':target=folder/'packages'/p+ if target:+ target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(z.read(info))+ if name=='pear':adapt(folder/'engine')+ atomic_json(folder/'RGB_MOCAP_PROVENANCE.json',dict(sources=lock['sources'],+ adapter_sha256=sha256(ROOT/'installer/pear_adapters.py'),+ changes='Windows live-inference imports; shared runtime and pure-Python geometry constructor helpers. Original licenses retained.'))+ print('Verifying PEAR shared-runtime imports and CUDA kernels...',flush=True)+ code='import sys; sys.path[:0]='+repr([str(ROOT),str(folder/'packages'),str(folder/'engine')])+'; from mocap.runtime_registry import activate; activate('+repr(str(ROOT))+', "shared"); import torch, numpy, scipy, timm, cv2, roma; from pytorch3d.transforms import axis_angle_to_matrix; from torchvision.ops import nms; assert torch.cuda.is_available(), \"Compatible NVIDIA GPU required\"; x=torch.zeros((1,3),device=\"cuda\"); assert axis_angle_to_matrix(x).isfinite().all(); assert nms(torch.tensor([[0.,0.,1.,1.]],device=\"cuda\"),torch.ones(1,device=\"cuda\"),.5).numel()==1; print(\"PEAR CUDA verification passed\")'+ subprocess.run([str(ROOT/'runtime/python.exe'),'-I','-B','-c',code],check=True,timeout=180)+ files={p.relative_to(folder).as_posix():[p.stat().st_size,p.stat().st_mtime_ns] for p in folder.rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc','.pyo')}+ atomic_json(ROOT/'.setup/pear-runtime.json',dict(version=2,identity=identity(),base_identity=base,folder=folder.relative_to(ROOT).as_posix(),files=files))+ print('PEAR support ready. Existing runtime packages, models and projects were not changed.',flush=True)+ return folder+ except Exception:+ # Keep failed staging for diagnosis; no previous configuration is overwritten.+ print('PEAR setup failed. Existing support generations were preserved.',flush=True);raise+++def setup(cache=None):+ # Developer repair entry point; ordinary users run install.cmd/update.cmd.+ with app_lock(ROOT):return prepare(cache)++if __name__=='__main__':+ p=argparse.ArgumentParser();p.add_argument('--cache');a=p.parse_args();setup(a.cache)