motionmirror 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MotionMirror contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: motionmirror
3
+ Version: 0.1.0
4
+ Summary: Webcam motion capture driving a built-in 3D mannequin in real time - self-contained Python, no Blender or game engine required
5
+ Author: MotionMirror contributors
6
+ License: MIT
7
+ Keywords: motion capture,mocap,webcam,pose estimation,mediapipe,3d,animation,bvh,vtuber,retargeting
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: End Users/Desktop
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
19
+ Classifier: Topic :: Multimedia :: Video :: Capture
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: numpy>=1.23
24
+ Requires-Dist: opencv-python>=4.8
25
+ Requires-Dist: trimesh>=3.20
26
+ Requires-Dist: pyrender>=0.1.45
27
+ Requires-Dist: PyOpenGL>=3.1.6
28
+ Requires-Dist: pyglet<2.0,>=1.4.10
29
+ Requires-Dist: mediapipe>=0.10.14
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # MotionMirror
35
+
36
+ **Capture your movement with a webcam and drive a 3D mannequin in real time —
37
+ one Python package, no Blender, no Unity, no game engine, no asset files.**
38
+
39
+ ```
40
+ Webcam (OpenCV) → MediaPipe pose + face tracking → One Euro smoothing
41
+ → Retargeting onto a fixed-length rig → pyrender 3D window (this package)
42
+ → optional BVH recording for Blender / Unity / Unreal
43
+ ```
44
+
45
+ The whole pipeline lives inside this package: camera capture, tracking,
46
+ smoothing, skeleton retargeting, real-time 3D rendering of a procedural
47
+ mannequin (with animated eyes, brows and mouth), and BVH export.
48
+
49
+ | Feature | What it does |
50
+ |---|---|
51
+ | **Body tracking** | 33 body landmarks (MediaPipe Pose) drive all 17 joints: torso, head, both arms, forearms, hands, legs, feet |
52
+ | **Face tracking** | 52 ARKit blendshapes (MediaPipe FaceLandmarker) blink the eyes, raise the brows, open and smile the mouth |
53
+ | **Built-in mannequin** | Procedural humanoid (1.73 m) rendered in a pyrender window — zero asset files |
54
+ | **One Euro filter** | Adaptive smoothing: steady when you are still, responsive when you move fast (`--smooth`, `--beta`) |
55
+ | **Floor + lighting** | Ground grid, floor plane and three-point lighting built in |
56
+ | **Camera preview** | Side-by-side OpenCV window showing what the camera sees (disable with `--no-preview`) |
57
+ | **BVH recording** | `--bvh session.bvh` records standard motion-capture files you can import into Blender, Unity or Unreal |
58
+ | **Demo mode** | A synthetic performer so you can try everything without a camera or even mediapipe working |
59
+
60
+ ---
61
+
62
+ ## Requirements
63
+
64
+ - **Windows 10 / 11** (also works on Linux/macOS), **64-bit**
65
+ - **Python 3.9 – 3.13**, 64-bit — check with `py -0p` or `python --version`.
66
+ 64-bit is required by MediaPipe.
67
+ - A webcam (only needed for `run`; `demo` works without one)
68
+ - About 1.5 GB of disk for the dependencies
69
+ - On the very first `run`, two MediaPipe model files (~10 MB total) are
70
+ downloaded automatically into `C:\Users\<you>\.motionmirror\models`
71
+
72
+ ## Install (from the zip)
73
+
74
+ ```bat
75
+ :: unzip motionmirror.zip somewhere, then:
76
+ cd motionmirror
77
+
78
+ :: create an isolated environment
79
+ py -3.11 -m venv .venv
80
+ .venv\Scripts\activate
81
+
82
+ :: install MotionMirror + all dependencies
83
+ pip install -e .
84
+
85
+ :: check it
86
+ motionmirror --help
87
+ ```
88
+
89
+ ## Quick start (no camera needed)
90
+
91
+ ```bat
92
+ motionmirror demo
93
+ ```
94
+
95
+ A 3D window opens with a mannequin waving its arms, squatting, turning its
96
+ head and blinking — proof that tracking, retargeting and rendering all work
97
+ on your machine. The camera preview window shows the synthetic feed that is
98
+ being tracked.
99
+
100
+ ## Live capture
101
+
102
+ ```bat
103
+ motionmirror run
104
+ ```
105
+
106
+ Stand 1.5–3 m from the camera, keep your whole upper body in frame and move.
107
+ Orientation calibrates itself automatically on the first detected frame
108
+ (head up, facing the camera), so no manual axis configuration is needed.
109
+
110
+ **Recording BVH while you move:**
111
+
112
+ ```bat
113
+ motionmirror run --bvh my_motion.bvh
114
+ ```
115
+
116
+ **Everything without the 3D window** (e.g. headless recording on a server):
117
+
118
+ ```bat
119
+ motionmirror run --bvh take1.bvh --headless --frames 900
120
+ ```
121
+
122
+ ## Command reference
123
+
124
+ | Option | Applies to | Meaning |
125
+ |---|---|---|
126
+ | `--camera N` | `run` | camera index if you have several (default `0`) |
127
+ | `--width / --height` | `run` | capture resolution (default 1280×720) |
128
+ | `--pose-model lite\|full\|heavy` | `run` | MediaPipe model size; `lite` is fastest |
129
+ | `--no-mirror` | both | disable mirror view — the avatar moves *like you* instead of *like your reflection* |
130
+ | `--bvh FILE` | both | record the session to a BVH file |
131
+ | `--frames N` | both | stop automatically after N frames |
132
+ | `--headless` | both | no 3D window at all (recording/CI only) |
133
+ | `--no-preview` | both | hide the camera preview window |
134
+ | `--smooth X` | both | One Euro *min cutoff*: lower = smoother, higher = snappier (default 1.4) |
135
+ | `--beta X` | both | One Euro *beta*: higher = more responsive to fast motion (default 0.06) |
136
+ | `--fps N` | `demo` | demo frame rate |
137
+
138
+ **Stop the session:** close the 3D window, press `q`/`Esc` in the camera
139
+ preview, or `Ctrl+C` in the terminal. The BVH file is written when the
140
+ session ends.
141
+
142
+ ## Using the BVH in Blender
143
+
144
+ 1. `File → Import → Motion Capture (.bvh)`
145
+ 2. Leave *Scale* at 1.0 — MotionMirror writes metres and a Y-up, Z-forward
146
+ rest pose, which Blender's importer understands.
147
+ 3. The BVH contains the **17 body joints** (hips → spine → chest → neck →
148
+ head, both arms, both legs, with end sites for head top, fingertips and
149
+ toes) at your session's frame rate. Face expressions are not stored in
150
+ BVH (the format has no blendshape standard) — the mannequin's face is
151
+ live-preview only.
152
+ 4. The BVH is always **anatomical**: your left arm is recorded as the left
153
+ arm, regardless of the mirror setting.
154
+
155
+ ## How it works
156
+
157
+ - **Tracking** — MediaPipe *Tasks* API: `PoseLandmarker` (33 world landmarks
158
+ in metres) + `FaceLandmarker` (478 landmarks, 52 ARKit blendshapes) both
159
+ run in VIDEO mode on every frame.
160
+ - **Auto-calibration** — MediaPipe's world-landmark axis convention is
161
+ officially undocumented (mediapipe issue #3370). On the first valid frame
162
+ MotionMirror picks the correct proper rotation out of the four candidates
163
+ (one that puts the head above the hips and the nose in front of the
164
+ chest), so any upstream convention just works.
165
+ - **Retargeting** — every joint is placed at its parent plus the measured
166
+ landmark direction scaled by the **rest bone length** (directed segments),
167
+ so the skeleton never stretches and follows you closely. Bone rotations
168
+ are derived from those segments; the hips/head use a two-axis TRIAD solve
169
+ (shoulder/ear line constrains roll).
170
+ - **Smoothing** — a One Euro filter per coordinate channel and per face
171
+ parameter, with timestamps taken from the actual source frame rate.
172
+ - **BVH** — standard Biovision hierarchy with channels
173
+ `Zrotation Xrotation Yrotation` (composite matrix `R = Rz·Rx·Ry` per the
174
+ BVH specification); the included `BVHReader` verifies the export by FK
175
+ round-trip in the test-suite.
176
+
177
+ ## Performance tips
178
+
179
+ - Use `--pose-model lite` (default) and a smaller capture window:
180
+ `run --width 640 --height 480` roughly doubles the frame rate.
181
+ - Face tracking adds ~2–3 ms per frame. It cannot currently be turned off
182
+ (the mannequin face is part of the scene).
183
+ - Any GPU made in the last decade handles the 3D window; the mannequin is
184
+ ~40 small meshes, trivial to render.
185
+
186
+ ## Troubleshooting
187
+
188
+ | Problem | Fix |
189
+ |---|---|
190
+ | `Cannot open camera N` | Close other apps using the camera (Teams/Zoom/OBS). Check *Settings → Privacy & security → Camera → Let desktop apps access your camera*. Try `--camera 1`. |
191
+ | `pip install mediapipe` fails | You are probably on 32-bit Python or >3.13. Install 64-bit Python 3.10–3.13 from python.org. |
192
+ | `pip` complains about `pyglet` | MotionMirror pins `pyglet<2` because pyrender needs the 1.x API. If a conflict remains, `pip install "pyglet==1.5.27"`. |
193
+ | 3D window is black or crashes | Update your graphics driver (Intel/NVIDIA/AMD). On old laptops, try `run --no-preview` or a lower capture resolution. |
194
+ | Model download fails (offline) | Download manually from the URLs in `motionmirror/tracking.py` (`POSE_MODEL_URLS`, `FACE_MODEL_URL`) and place the files in `C:\Users\<you>\.motionmirror\models\`. |
195
+ | Avatar is too jittery | Lower `--smooth` (e.g. 1.0) and `--beta` (e.g. 0.03). Too *laggy* instead? Raise them (1.8 / 0.1). |
196
+ | Feet sink or slide | Normal for monocular webcam mocap — there is no true 3D depth. The ground clamp keeps feet above the floor, but skating can occur. |
197
+ | Low FPS | Close the preview (`--no-preview`), use `lite` model, lower resolution, and keep your whole body visible (failed detections cost the most). |
198
+
199
+ ## Development
200
+
201
+ ```bat
202
+ pip install -e .[dev]
203
+ pytest tests -v
204
+ ```
205
+
206
+ The test-suite is fully headless (no camera, no GL window, no model
207
+ downloads): it exercises the synthetic demo source, retargeting sanity,
208
+ fixed bone lengths, BVH FK round-trip, the headless pipeline and the CLI.
209
+
210
+ ## Known limitations
211
+
212
+ - One webcam = approximate depth. Leg movements are tracked, but depth
213
+ (stepping toward the camera) is weakly estimated by MediaPipe.
214
+ - Crossing your arms or leaving the frame confuses the estimator; the last
215
+ good pose is held until detection recovers.
216
+ - BVH stores body motion only; face expressions are preview-only.
217
+ - Root translation is kept in full, so walking *toward* the camera moves the
218
+ avatar in world space (it does not treadmill in place).
219
+
220
+ ## License
221
+
222
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,189 @@
1
+ # MotionMirror
2
+
3
+ **Capture your movement with a webcam and drive a 3D mannequin in real time —
4
+ one Python package, no Blender, no Unity, no game engine, no asset files.**
5
+
6
+ ```
7
+ Webcam (OpenCV) → MediaPipe pose + face tracking → One Euro smoothing
8
+ → Retargeting onto a fixed-length rig → pyrender 3D window (this package)
9
+ → optional BVH recording for Blender / Unity / Unreal
10
+ ```
11
+
12
+ The whole pipeline lives inside this package: camera capture, tracking,
13
+ smoothing, skeleton retargeting, real-time 3D rendering of a procedural
14
+ mannequin (with animated eyes, brows and mouth), and BVH export.
15
+
16
+ | Feature | What it does |
17
+ |---|---|
18
+ | **Body tracking** | 33 body landmarks (MediaPipe Pose) drive all 17 joints: torso, head, both arms, forearms, hands, legs, feet |
19
+ | **Face tracking** | 52 ARKit blendshapes (MediaPipe FaceLandmarker) blink the eyes, raise the brows, open and smile the mouth |
20
+ | **Built-in mannequin** | Procedural humanoid (1.73 m) rendered in a pyrender window — zero asset files |
21
+ | **One Euro filter** | Adaptive smoothing: steady when you are still, responsive when you move fast (`--smooth`, `--beta`) |
22
+ | **Floor + lighting** | Ground grid, floor plane and three-point lighting built in |
23
+ | **Camera preview** | Side-by-side OpenCV window showing what the camera sees (disable with `--no-preview`) |
24
+ | **BVH recording** | `--bvh session.bvh` records standard motion-capture files you can import into Blender, Unity or Unreal |
25
+ | **Demo mode** | A synthetic performer so you can try everything without a camera or even mediapipe working |
26
+
27
+ ---
28
+
29
+ ## Requirements
30
+
31
+ - **Windows 10 / 11** (also works on Linux/macOS), **64-bit**
32
+ - **Python 3.9 – 3.13**, 64-bit — check with `py -0p` or `python --version`.
33
+ 64-bit is required by MediaPipe.
34
+ - A webcam (only needed for `run`; `demo` works without one)
35
+ - About 1.5 GB of disk for the dependencies
36
+ - On the very first `run`, two MediaPipe model files (~10 MB total) are
37
+ downloaded automatically into `C:\Users\<you>\.motionmirror\models`
38
+
39
+ ## Install (from the zip)
40
+
41
+ ```bat
42
+ :: unzip motionmirror.zip somewhere, then:
43
+ cd motionmirror
44
+
45
+ :: create an isolated environment
46
+ py -3.11 -m venv .venv
47
+ .venv\Scripts\activate
48
+
49
+ :: install MotionMirror + all dependencies
50
+ pip install -e .
51
+
52
+ :: check it
53
+ motionmirror --help
54
+ ```
55
+
56
+ ## Quick start (no camera needed)
57
+
58
+ ```bat
59
+ motionmirror demo
60
+ ```
61
+
62
+ A 3D window opens with a mannequin waving its arms, squatting, turning its
63
+ head and blinking — proof that tracking, retargeting and rendering all work
64
+ on your machine. The camera preview window shows the synthetic feed that is
65
+ being tracked.
66
+
67
+ ## Live capture
68
+
69
+ ```bat
70
+ motionmirror run
71
+ ```
72
+
73
+ Stand 1.5–3 m from the camera, keep your whole upper body in frame and move.
74
+ Orientation calibrates itself automatically on the first detected frame
75
+ (head up, facing the camera), so no manual axis configuration is needed.
76
+
77
+ **Recording BVH while you move:**
78
+
79
+ ```bat
80
+ motionmirror run --bvh my_motion.bvh
81
+ ```
82
+
83
+ **Everything without the 3D window** (e.g. headless recording on a server):
84
+
85
+ ```bat
86
+ motionmirror run --bvh take1.bvh --headless --frames 900
87
+ ```
88
+
89
+ ## Command reference
90
+
91
+ | Option | Applies to | Meaning |
92
+ |---|---|---|
93
+ | `--camera N` | `run` | camera index if you have several (default `0`) |
94
+ | `--width / --height` | `run` | capture resolution (default 1280×720) |
95
+ | `--pose-model lite\|full\|heavy` | `run` | MediaPipe model size; `lite` is fastest |
96
+ | `--no-mirror` | both | disable mirror view — the avatar moves *like you* instead of *like your reflection* |
97
+ | `--bvh FILE` | both | record the session to a BVH file |
98
+ | `--frames N` | both | stop automatically after N frames |
99
+ | `--headless` | both | no 3D window at all (recording/CI only) |
100
+ | `--no-preview` | both | hide the camera preview window |
101
+ | `--smooth X` | both | One Euro *min cutoff*: lower = smoother, higher = snappier (default 1.4) |
102
+ | `--beta X` | both | One Euro *beta*: higher = more responsive to fast motion (default 0.06) |
103
+ | `--fps N` | `demo` | demo frame rate |
104
+
105
+ **Stop the session:** close the 3D window, press `q`/`Esc` in the camera
106
+ preview, or `Ctrl+C` in the terminal. The BVH file is written when the
107
+ session ends.
108
+
109
+ ## Using the BVH in Blender
110
+
111
+ 1. `File → Import → Motion Capture (.bvh)`
112
+ 2. Leave *Scale* at 1.0 — MotionMirror writes metres and a Y-up, Z-forward
113
+ rest pose, which Blender's importer understands.
114
+ 3. The BVH contains the **17 body joints** (hips → spine → chest → neck →
115
+ head, both arms, both legs, with end sites for head top, fingertips and
116
+ toes) at your session's frame rate. Face expressions are not stored in
117
+ BVH (the format has no blendshape standard) — the mannequin's face is
118
+ live-preview only.
119
+ 4. The BVH is always **anatomical**: your left arm is recorded as the left
120
+ arm, regardless of the mirror setting.
121
+
122
+ ## How it works
123
+
124
+ - **Tracking** — MediaPipe *Tasks* API: `PoseLandmarker` (33 world landmarks
125
+ in metres) + `FaceLandmarker` (478 landmarks, 52 ARKit blendshapes) both
126
+ run in VIDEO mode on every frame.
127
+ - **Auto-calibration** — MediaPipe's world-landmark axis convention is
128
+ officially undocumented (mediapipe issue #3370). On the first valid frame
129
+ MotionMirror picks the correct proper rotation out of the four candidates
130
+ (one that puts the head above the hips and the nose in front of the
131
+ chest), so any upstream convention just works.
132
+ - **Retargeting** — every joint is placed at its parent plus the measured
133
+ landmark direction scaled by the **rest bone length** (directed segments),
134
+ so the skeleton never stretches and follows you closely. Bone rotations
135
+ are derived from those segments; the hips/head use a two-axis TRIAD solve
136
+ (shoulder/ear line constrains roll).
137
+ - **Smoothing** — a One Euro filter per coordinate channel and per face
138
+ parameter, with timestamps taken from the actual source frame rate.
139
+ - **BVH** — standard Biovision hierarchy with channels
140
+ `Zrotation Xrotation Yrotation` (composite matrix `R = Rz·Rx·Ry` per the
141
+ BVH specification); the included `BVHReader` verifies the export by FK
142
+ round-trip in the test-suite.
143
+
144
+ ## Performance tips
145
+
146
+ - Use `--pose-model lite` (default) and a smaller capture window:
147
+ `run --width 640 --height 480` roughly doubles the frame rate.
148
+ - Face tracking adds ~2–3 ms per frame. It cannot currently be turned off
149
+ (the mannequin face is part of the scene).
150
+ - Any GPU made in the last decade handles the 3D window; the mannequin is
151
+ ~40 small meshes, trivial to render.
152
+
153
+ ## Troubleshooting
154
+
155
+ | Problem | Fix |
156
+ |---|---|
157
+ | `Cannot open camera N` | Close other apps using the camera (Teams/Zoom/OBS). Check *Settings → Privacy & security → Camera → Let desktop apps access your camera*. Try `--camera 1`. |
158
+ | `pip install mediapipe` fails | You are probably on 32-bit Python or >3.13. Install 64-bit Python 3.10–3.13 from python.org. |
159
+ | `pip` complains about `pyglet` | MotionMirror pins `pyglet<2` because pyrender needs the 1.x API. If a conflict remains, `pip install "pyglet==1.5.27"`. |
160
+ | 3D window is black or crashes | Update your graphics driver (Intel/NVIDIA/AMD). On old laptops, try `run --no-preview` or a lower capture resolution. |
161
+ | Model download fails (offline) | Download manually from the URLs in `motionmirror/tracking.py` (`POSE_MODEL_URLS`, `FACE_MODEL_URL`) and place the files in `C:\Users\<you>\.motionmirror\models\`. |
162
+ | Avatar is too jittery | Lower `--smooth` (e.g. 1.0) and `--beta` (e.g. 0.03). Too *laggy* instead? Raise them (1.8 / 0.1). |
163
+ | Feet sink or slide | Normal for monocular webcam mocap — there is no true 3D depth. The ground clamp keeps feet above the floor, but skating can occur. |
164
+ | Low FPS | Close the preview (`--no-preview`), use `lite` model, lower resolution, and keep your whole body visible (failed detections cost the most). |
165
+
166
+ ## Development
167
+
168
+ ```bat
169
+ pip install -e .[dev]
170
+ pytest tests -v
171
+ ```
172
+
173
+ The test-suite is fully headless (no camera, no GL window, no model
174
+ downloads): it exercises the synthetic demo source, retargeting sanity,
175
+ fixed bone lengths, BVH FK round-trip, the headless pipeline and the CLI.
176
+
177
+ ## Known limitations
178
+
179
+ - One webcam = approximate depth. Leg movements are tracked, but depth
180
+ (stepping toward the camera) is weakly estimated by MediaPipe.
181
+ - Crossing your arms or leaving the frame confuses the estimator; the last
182
+ good pose is held until detection recovers.
183
+ - BVH stores body motion only; face expressions are preview-only.
184
+ - Root translation is kept in full, so walking *toward* the camera moves the
185
+ avatar in world space (it does not treadmill in place).
186
+
187
+ ## License
188
+
189
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,28 @@
1
+ """MotionMirror: webcam motion capture applied to a built-in 3D mannequin.
2
+
3
+ The whole pipeline lives in this package - camera capture, MediaPipe pose and
4
+ face tracking, smoothing, retargeting, real-time 3D rendering and BVH export.
5
+ No Blender, no game engine, no external assets.
6
+
7
+ Quick start::
8
+
9
+ motionmirror demo # synthetic performer, no camera needed
10
+ motionmirror run # track yourself with the webcam
11
+ motionmirror run --bvh me.bvh # ...and record it for Blender
12
+ """
13
+ from __future__ import annotations
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ from .bvh import BVHReader, BVHWriter
18
+ from .pipeline import Driver
19
+ from .retarget import Pose, Retargeter, local_rotations
20
+ from .skeleton import Skeleton
21
+ from .smoothing import LandmarkSmoother, OneEuroFilter, ParamSmoother
22
+ from .tracking import DemoSource, Frame, WebcamSource, ensure_model
23
+
24
+ __all__ = [
25
+ "BVHReader", "BVHWriter", "Driver", "Pose", "Retargeter", "Skeleton",
26
+ "LandmarkSmoother", "OneEuroFilter", "ParamSmoother", "DemoSource",
27
+ "Frame", "WebcamSource", "ensure_model", "local_rotations", "__version__",
28
+ ]
@@ -0,0 +1,6 @@
1
+ """``python -m motionmirror`` entry point."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
@@ -0,0 +1,216 @@
1
+ """Biovision Hierarchy (BVH) motion-capture writer + minimal reader.
2
+
3
+ Channel order used everywhere: ``Zrotation Xrotation Yrotation`` which, per
4
+ the BVH specification, composes to the matrix product ``R = Rz @ Rx @ Ry``
5
+ (angles in degrees; column-vector convention). The included
6
+ :class:`BVHReader` performs FK with exactly this convention, so the writer is
7
+ verified end-to-end by the test-suite.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Dict, List, Optional, Tuple
13
+
14
+ import numpy as np
15
+
16
+ from .mathutils import euler_zxy_from_quat, matrix_from_euler_zxy
17
+ from .skeleton import Skeleton
18
+
19
+
20
+ class BVHWriter:
21
+ """Records a MotionMirror session as a standard BVH file.
22
+
23
+ Buffers frames in memory and writes the complete file on :meth:`close`
24
+ (frame count is only known then).
25
+ """
26
+
27
+ def __init__(self, path, skeleton: Skeleton, fps: float = 30.0):
28
+ self.skel = skeleton
29
+ self.fps = float(fps)
30
+ self.path = Path(path)
31
+ self._frames: List[str] = []
32
+ self.joint_order: List[str] = []
33
+ self._children: Dict[str, List[str]] = {n: [] for n in skeleton.names}
34
+ for n in skeleton.names:
35
+ p = skeleton.parent_idx[skeleton.index[n]]
36
+ if p is not None:
37
+ self._children[skeleton.names[p]].append(n)
38
+ self._dfs("hips")
39
+ self._header = self._build_header()
40
+
41
+ def _dfs(self, name: str) -> None:
42
+ self.joint_order.append(name)
43
+ for c in self._children[name]:
44
+ self._dfs(c)
45
+
46
+ def _block(self, name: str, indent: str) -> List[str]:
47
+ skel = self.skel
48
+ i = skel.index[name]
49
+ lines = []
50
+ if skel.parent_idx[i] is None:
51
+ off = skel.rest_positions[i]
52
+ lines.append(f"{indent}ROOT {name}")
53
+ lines.append(f"{indent}{{")
54
+ lines.append(f"{indent} OFFSET {off[0]:.6f} {off[1]:.6f} {off[2]:.6f}")
55
+ lines.append(f"{indent} CHANNELS 6 Xposition Yposition Zposition "
56
+ "Zrotation Xrotation Yrotation")
57
+ else:
58
+ off = skel.offsets[i]
59
+ lines.append(f"{indent}JOINT {name}")
60
+ lines.append(f"{indent}{{")
61
+ lines.append(f"{indent} OFFSET {off[0]:.6f} {off[1]:.6f} {off[2]:.6f}")
62
+ lines.append(f"{indent} CHANNELS 3 Zrotation Xrotation Yrotation")
63
+ for c in self._children[name]:
64
+ lines.extend(self._block(c, indent + " "))
65
+ tip = skel.tip_by_parent.get(name)
66
+ if tip is not None and not self._children[name]:
67
+ o = skel.tip_offsets[tip]
68
+ lines.append(f"{indent} End Site")
69
+ lines.append(f"{indent} {{")
70
+ lines.append(f"{indent} OFFSET {o[0]:.6f} {o[1]:.6f} {o[2]:.6f}")
71
+ lines.append(f"{indent} }}")
72
+ lines.append(f"{indent}}}")
73
+ return lines
74
+
75
+ def _build_header(self) -> str:
76
+ return "\n".join(self._block("hips", ""))
77
+
78
+ def write_frame(self, root_pos: np.ndarray, local_quats: Dict[str, np.ndarray]) -> None:
79
+ vals = [f"{root_pos[0]:.6f}", f"{root_pos[1]:.6f}", f"{root_pos[2]:.6f}"]
80
+ for name in self.joint_order:
81
+ z, x, y = euler_zxy_from_quat(local_quats.get(name))
82
+ deg = np.degrees
83
+ vals += [f"{deg(z):.6f}", f"{deg(x):.6f}", f"{deg(y):.6f}"]
84
+ self._frames.append(" ".join(vals))
85
+
86
+ @property
87
+ def frame_count(self) -> int:
88
+ return len(self._frames)
89
+
90
+ def close(self) -> None:
91
+ if self.path.parent and str(self.path.parent):
92
+ self.path.parent.mkdir(parents=True, exist_ok=True)
93
+ with open(self.path, "w", encoding="utf-8") as f:
94
+ f.write("HIERARCHY\n")
95
+ f.write(self._header + "\n")
96
+ f.write("MOTION\n")
97
+ f.write(f"Frames: {len(self._frames)}\n")
98
+ f.write(f"Frame Time: {1.0 / self.fps:.6f}\n")
99
+ f.write("\n".join(self._frames) + "\n")
100
+
101
+ def __enter__(self):
102
+ return self
103
+
104
+ def __exit__(self, *exc):
105
+ self.close()
106
+
107
+
108
+ class BVHReader:
109
+ """Minimal BVH parser with forward kinematics (for round-trip checks and
110
+ playback). Supports the channel set written by :class:`BVHWriter`."""
111
+
112
+ def __init__(self, path):
113
+ text = Path(path).read_text(encoding="utf-8")
114
+ self.joints: List[str] = []
115
+ self.parents: List[Optional[int]] = []
116
+ self.offsets: List[np.ndarray] = []
117
+ self.channels: List[List[str]] = []
118
+ self._frames: List[np.ndarray] = []
119
+ self.fps: float = 30.0
120
+ self.num_frames: int = 0
121
+ self._skip_offset = False
122
+ lines = text.splitlines()
123
+ self._parse_hierarchy(text[:text.index("MOTION")].split())
124
+ self._parse_motion(lines)
125
+
126
+ def _parse_hierarchy(self, tk: List[str]) -> None:
127
+ i, stack = 0, []
128
+ cur = -1
129
+ while i < len(tk):
130
+ t = tk[i]
131
+ if t in ("ROOT", "JOINT"):
132
+ self.joints.append(tk[i + 1])
133
+ self.parents.append(cur if cur >= 0 else None)
134
+ self.offsets.append(np.zeros(3))
135
+ self.channels.append([])
136
+ cur = len(self.joints) - 1
137
+ i += 2
138
+ elif t == "End":
139
+ self._skip_offset = True # End Site offsets are not joints
140
+ i += 2 # skip "End Site", let its "{" balance the "}"
141
+ elif t == "OFFSET":
142
+ if self._skip_offset:
143
+ self._skip_offset = False
144
+ else:
145
+ self.offsets[cur] = np.array(
146
+ [float(tk[i + 1]), float(tk[i + 2]), float(tk[i + 3])])
147
+ i += 4
148
+ elif t == "CHANNELS":
149
+ n = int(tk[i + 1])
150
+ self.channels[cur] = tk[i + 2:i + 2 + n]
151
+ i += 2 + n
152
+ elif t == "{":
153
+ stack.append(cur)
154
+ i += 1
155
+ elif t == "}":
156
+ stack.pop()
157
+ cur = stack[-1] if stack else -1
158
+ i += 1
159
+ else:
160
+ i += 1
161
+
162
+ def _parse_motion(self, lines: List[str]) -> None:
163
+ in_motion = False
164
+ for line in lines:
165
+ stripped = line.strip()
166
+ if not in_motion:
167
+ if stripped == "MOTION":
168
+ in_motion = True
169
+ continue
170
+ if not stripped:
171
+ continue
172
+ parts = stripped.split()
173
+ if parts[0] == "Frames:":
174
+ self.num_frames = int(parts[1])
175
+ elif parts[0] == "Frame":
176
+ self.fps = 1.0 / float(parts[2])
177
+ else:
178
+ self._frames.append(np.array([float(x) for x in parts]))
179
+
180
+ def fk_positions(self, frame_index: int) -> Dict[str, np.ndarray]:
181
+ """World joint positions for one motion frame."""
182
+ row = self._frames[frame_index]
183
+ out: Dict[str, np.ndarray] = {}
184
+ rots: List[np.ndarray] = []
185
+ pos: List[np.ndarray] = []
186
+ for j, name in enumerate(self.joints):
187
+ off = self.offsets[j]
188
+ ch = self.channels[j]
189
+ vals = {}
190
+ k = 0
191
+ for jn in range(j):
192
+ k += len(self.channels[jn])
193
+ for c in ch:
194
+ vals[c] = row[k]
195
+ k += 1
196
+ p = self.parents[j]
197
+ if p is None:
198
+ t = np.array([vals.get("Xposition", 0.0),
199
+ vals.get("Yposition", 0.0),
200
+ vals.get("Zposition", 0.0)])
201
+ R = self._rot(vals)
202
+ pos.append(t)
203
+ else:
204
+ R = rots[p] @ self._rot(vals)
205
+ pos.append(pos[p] + rots[p] @ off)
206
+ rots.append(R)
207
+ out[name] = pos[j]
208
+ return out
209
+
210
+ @staticmethod
211
+ def _rot(ch_vals: Dict[str, float]) -> np.ndarray:
212
+ return matrix_from_euler_zxy(
213
+ np.radians(ch_vals.get("Zrotation", 0.0)),
214
+ np.radians(ch_vals.get("Xrotation", 0.0)),
215
+ np.radians(ch_vals.get("Yrotation", 0.0)),
216
+ )