From 710c4f23e52c9758848792795c0ec558c10bc6c1 Mon Sep 17 00:00:00 2001 From: kinect-bot Date: Fri, 27 Nov 2026 03:05:51 -0500 Subject: [PATCH] feat(release): wave 1 landed - tuning/calibration, model+ORT distribution, licensing, 2P experiment+probe --- LICENSE | 22 +- ThirdPartyNotices.txt | 271 +++++++++++++++ core/calibration/calibration.cpp | 136 +------- core/calibration/calibration.h | 322 +++++++++++++++++- docs/game-internals.md | 24 +- fallback/windows-nui/src/sensor.cpp | 208 ++++++++++- tests/test_calibration.cpp | 205 +++++++++++ tracker-native/MANIFEST.sha256 | 5 + tracker-native/README.md | 41 ++- tracker-native/build.sh | 25 +- tracker-native/scripts/fetch_models.sh | 92 +++++ tracker-native/scripts/fetch_ort.sh | 77 ++++- tracker-native/scripts/setup_models.sh | 5 + tracker-native/src/two_person_probe.cpp | 123 +++++++ tracker-native/src/win_main.cpp | 129 ++++++- tracker-native/testdata/two_person_sequence.h | 55 +++ 16 files changed, 1557 insertions(+), 183 deletions(-) create mode 100644 ThirdPartyNotices.txt create mode 100644 tracker-native/MANIFEST.sha256 mode change 100755 => 100644 tracker-native/build.sh create mode 100755 tracker-native/scripts/fetch_models.sh create mode 100644 tracker-native/src/two_person_probe.cpp create mode 100644 tracker-native/testdata/two_person_sequence.h diff --git a/LICENSE b/LICENSE index 5c97586..6b6cbae 100644 --- a/LICENSE +++ b/LICENSE @@ -22,5 +22,23 @@ Third-party components (NOT included) No warranty. Windows driver components require personal-use test-signing and are not WHQL-signed or distributed as production-ready. -A formal open-source license for the project's own code may be chosen later; until then -all rights are reserved to the authors for the project's own source. +Personal-use grant +------------------ +This is not an open-source project. The authors deliberately keep the project's own +source under a personal-use grant, consistent with the clean-room discipline above. No +formal open-source license is being chosen, and none is implied. + +You may: +- Use, build, and run this software for your own personal, non-commercial purposes. +- Modify it for your own personal use. +- Share your personal modifications privately with other individuals who have the same + personal-use rights, provided this notice travels with the source unchanged. + +You may not, without the authors' prior written permission: +- Sell, rent, sublicense, or otherwise commercialize this software or any derivative. +- Redistribute it publicly (for example, in an app store, a paid bundle, or a product). +- Remove or alter this notice or the clean-room and third-party statements above. + +All rights not expressly granted here are reserved to the authors. These terms cover +only the project's own source; third-party components keep their own licenses, listed in +ThirdPartyNotices.txt. diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt new file mode 100644 index 0000000..2b3a3d3 --- /dev/null +++ b/ThirdPartyNotices.txt @@ -0,0 +1,271 @@ +Third-Party Notices +=================== + +This project's own source is covered by LICENSE (personal-use grant). The runnable +bundle ships a small number of third-party binaries, each under its own license. Those +licenses are reproduced below and govern the corresponding files, not this project's own +code. + +Components bundled with the runtime +----------------------------------- + +1. ONNX Runtime + Copyright (c) Microsoft Corporation. + License: MIT (full text below). + Used as: the prebuilt ONNX Runtime library the native tracker links against to run + pose inference. + +2. MediaPipe BlazePose models + Copyright 2020 The MediaPipe Authors. + License: Apache License, Version 2.0 (full text below). + Used as: the bundled pose-estimation model weights (BlazePose / MediaPipe Pose), + converted to ONNX, that drive the webcam-to-skeleton tracking. + Model attribution: these are the MediaPipe Pose (BlazePose) models published by + Google. See the MediaPipe Pose model card for the training data, intended use, and + limitations: https://github.com/google-ai-edge/mediapipe/blob/master/docs/solutions/models.md + The models are used as published; no retraining or modification of the weights is + claimed. + +Components NOT bundled +---------------------- + +- Microsoft Kinect for Windows SDK 1.8 headers (NuiApi.h and related): used as + interface facts only (ABI shapes, descriptors, and declarations), the way any program + that links an API uses its headers. No Kinect SDK or runtime binary is included in this + bundle. Obtain the SDK from Microsoft's official site if you need it. + +- DanceEvolution Arcade (DEA) and spice2x: user-supplied. Neither the game, its assets, + nor the spice2x loader is included in or redistributed by this project. You must supply + your own copies. + + +================================================================================ +MIT License (ONNX Runtime) +================================================================================ + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +================================================================================ +Apache License, Version 2.0 (MediaPipe BlazePose models) +================================================================================ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, excluding + those notices that do not pertain to any part of the Derivative + Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and do + not modify the License. You may add Your own attribution notices + within Derivative Works that You distribute, alongside or as an + addendum to the NOTICE text from the Work, provided that such + additional attribution notices cannot be construed as modifying + the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/core/calibration/calibration.cpp b/core/calibration/calibration.cpp index 140f01f..964d9a9 100644 --- a/core/calibration/calibration.cpp +++ b/core/calibration/calibration.cpp @@ -1,133 +1,5 @@ +// The calibration logic is header-only (see calibration.h) so the Windows shim +// and tracker can share it without linking this translation unit. This file +// remains in the libnui_core target so the core library keeps a stable object +// for the calibration module. #include "calibration/calibration.h" - -#include -#include -#include -#include - -namespace nui::calibration { -namespace { - -constexpr float kProjectionScale = 3.501e-3f; -constexpr float kMinZ = 0.8f; -constexpr float kMaxZ = 4.0f; - -bool finite(float value) { - return std::isfinite(value); -} - -} // namespace - -bool confirm_mirror_raise_right_arm( - const RaiseRightArmObservation& observation, - bool& mirror, - std::string& error) { - const bool right_raised = - observation.right_wrist_v < observation.right_shoulder_v; - const bool left_lowered = - observation.left_wrist_v >= observation.left_shoulder_v; - if (!observation.person_detected || !right_raised || !left_lowered) { - error = "mirror confirmation requires only the right arm raised"; - return false; - } - mirror = observation.right_wrist_u < observation.right_shoulder_u; - error.clear(); - return true; -} - -bool calibrate_tpose( - const TposeObservation& observation, - CalibrationConfig& output, - std::string& error) { - if (!observation.person_detected) { - error = "T-pose calibration requires one detected person"; - return false; - } - if (!finite(observation.root_depth_meters) || - !finite(observation.normalized_shoulder_width) || - observation.normalized_shoulder_width <= 0.0f) { - error = "T-pose calibration observation is invalid"; - return false; - } - - CalibrationConfig candidate{}; - candidate.mapping.z0_meters = - std::clamp(observation.root_depth_meters, kMinZ, kMaxZ); - candidate.mapping.depth_gain = 1.0f; - candidate.mapping.mirror = observation.mirror; - candidate.player_scale = kTargetShoulderWidthMeters / - (observation.normalized_shoulder_width * 320.0f * - kProjectionScale * candidate.mapping.z0_meters); - candidate.floor_plane = observation.floor_plane; - for (const float value : candidate.floor_plane) { - if (!finite(value)) { - error = "T-pose floor plane is invalid"; - return false; - } - } - output = candidate; - error.clear(); - return true; -} - -bool save_config( - const CalibrationConfig& config, - const std::string& path, - std::string& error) { - std::ofstream file(path, std::ios::trunc); - if (!file) { - error = "could not open calibration config for writing"; - return false; - } - file << std::setprecision(9) - << "depth_width " << config.mapping.depth_width << '\n' - << "depth_height " << config.mapping.depth_height << '\n' - << "z0_meters " << config.mapping.z0_meters << '\n' - << "depth_gain " << config.mapping.depth_gain << '\n' - << "mirror " << config.mapping.mirror << '\n' - << "player_scale " << config.player_scale << '\n' - << "smoothing " << config.smoothing.smoothing << ' ' - << config.smoothing.correction << ' ' << config.smoothing.prediction - << ' ' << config.smoothing.jitter_radius << ' ' - << config.smoothing.max_deviation_radius << '\n' - << "floor_plane " << config.floor_plane[0] << ' ' - << config.floor_plane[1] << ' ' << config.floor_plane[2] << ' ' - << config.floor_plane[3] << '\n'; - if (!file) { - error = "could not write calibration config"; - return false; - } - error.clear(); - return true; -} - -bool load_config( - const std::string& path, - CalibrationConfig& output, - std::string& error) { - std::ifstream file(path); - CalibrationConfig candidate{}; - std::string key; - if (!file || - !(file >> key >> candidate.mapping.depth_width) || key != "depth_width" || - !(file >> key >> candidate.mapping.depth_height) || key != "depth_height" || - !(file >> key >> candidate.mapping.z0_meters) || key != "z0_meters" || - !(file >> key >> candidate.mapping.depth_gain) || key != "depth_gain" || - !(file >> key >> candidate.mapping.mirror) || key != "mirror" || - !(file >> key >> candidate.player_scale) || key != "player_scale" || - !(file >> key >> candidate.smoothing.smoothing >> - candidate.smoothing.correction >> candidate.smoothing.prediction >> - candidate.smoothing.jitter_radius >> - candidate.smoothing.max_deviation_radius) || key != "smoothing" || - !(file >> key >> candidate.floor_plane[0] >> candidate.floor_plane[1] >> - candidate.floor_plane[2] >> candidate.floor_plane[3]) || - key != "floor_plane") { - error = "could not parse calibration config"; - return false; - } - output = candidate; - error.clear(); - return true; -} - -} // namespace nui::calibration diff --git a/core/calibration/calibration.h b/core/calibration/calibration.h index c53e3e8..25382e8 100644 --- a/core/calibration/calibration.h +++ b/core/calibration/calibration.h @@ -1,13 +1,50 @@ #ifndef NUI_CORE_CALIBRATION_H #define NUI_CORE_CALIBRATION_H +#include #include +#include +#include +#include +#include #include +#include #include "mapping/mapping.h" +// The calibration module is header-only on purpose: the camera-agnostic cursor +// gains it resolves are consumed by three separate binaries that do NOT share a +// link unit - the OS-agnostic core test suite (Linux), the Windows NUI shim +// (`Kinect10.dll`), and the native Windows tracker. Keeping the logic inline +// here lets all three use the identical path/gain/derivation code by including +// this header, without adding `calibration.cpp` to each build. + namespace nui::calibration { +// --- Camera-agnostic cursor arm-reach gains ------------------------------- +// +// The shim amplifies each arm outward from its shoulder so MediaPipe's +// compressed hand-relative reach spans the game's menu cursor range the way a +// real Kinect v1 does. These gains used to be hardcoded (3.2 / 2.6), tuned to +// one webcam/FOV; they are now resolvable (env > config file > default) and +// derivable per camera from a raised-arm hold. +constexpr float kDefaultArmGainX = 3.2f; +constexpr float kDefaultArmGainY = 2.6f; +constexpr float kArmGainMin = 1.0f; +constexpr float kArmGainMax = 6.0f; + +// Target full-extension reach of HAND_R relative to the pivot shoulder, in +// post-L/R-swap post-mirror skeleton space (metres). Taken from real Kinect v1 +// recordings, docs/game-internals.md section 3 (HAND_R - SHOULDER_CENTER x in +// [-0.35, +0.86], y reaching ~+0.5 above the shoulder). +constexpr float kTargetArmReachX = 0.86f; +constexpr float kTargetArmReachY = 0.5f; + +struct ArmGains { + float x = kDefaultArmGainX; + float y = kDefaultArmGainY; +}; + struct TposeObservation { bool person_detected = false; float root_depth_meters = 2.5f; @@ -24,6 +61,12 @@ struct RaiseRightArmObservation { float right_wrist_v = 0.0f; float left_shoulder_v = 0.0f; float left_wrist_v = 0.0f; + // HAND_R relative to the amplification-pivot shoulder in post-L/R-swap, + // post-mirror skeleton space (metres) - exactly the excursion the shim's arm + // amplification scales. Populated during a cursor-reach calibration hold; + // zero on the mirror-confirm observations that do not measure reach. + float measured_reach_x = 0.0f; + float measured_reach_y = 0.0f; }; struct CalibrationConfig { @@ -31,33 +74,296 @@ struct CalibrationConfig { mapping::SmoothingParameters smoothing{}; float player_scale = 1.0f; std::array floor_plane{0.0f, 1.0f, 0.0f, 0.0f}; + float arm_gain_x = kDefaultArmGainX; + float arm_gain_y = kDefaultArmGainY; }; constexpr float kTargetShoulderWidthMeters = 0.40f; +namespace detail { + +inline bool finite_value(float value) { return std::isfinite(value); } + +// Strict full-token float parse for a gain field (env var or config token). +// Returns false (leaving `out` untouched) for an empty value, or one whose +// non-whitespace content is not entirely a finite float - so "2junk" is +// REJECTED rather than silently read as 2.0, and a garbled value falls through +// to the next source (config, then built-in default) instead of corrupting the +// gain. +inline bool parse_strict_float(const char* text, float& out) { + if (text == nullptr || *text == '\0') { + return false; + } + char* end = nullptr; + const double value = std::strtod(text, &end); + if (end == text) { + return false; + } + while (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n') { + ++end; + } + if (*end != '\0' || !std::isfinite(value)) { + return false; + } + out = static_cast(value); + return true; +} + +} // namespace detail + +// Canonical calibration config path shared by the tracker (writer) and the shim +// (reader): the KINECT_SHIM_CONFIG override when set, else +// `\VirtualKinect\calibration.cfg`. Pure - it takes the +// already-read environment strings so the identical path logic runs in both +// Windows binaries and is unit-testable off-Windows. A nullptr/empty argument +// means that variable is unset. +inline std::string calibration_config_path(const char* env_override, + const char* local_app_data) { + if (env_override != nullptr && *env_override != '\0') { + return std::string(env_override); + } + if (local_app_data != nullptr && *local_app_data != '\0') { + return std::string(local_app_data) + "\\VirtualKinect\\calibration.cfg"; + } + return std::string("VirtualKinect\\calibration.cfg"); +} + +// Resolve the arm-reach gains with precedence +// env override (KINECT_SHIM_ARM_GAIN_X/_Y) > config-file value > built-in +// default (3.2 / 2.6). +// `base` supplies the file-or-default gains per axis; `env_x`/`env_y` are the +// raw environment strings (nullptr/empty = unset, unparseable = ignored). +inline ArmGains resolve_arm_gains(const ArmGains& base, + const char* env_x = nullptr, + const char* env_y = nullptr) { + ArmGains gains = base; + float parsed = 0.0f; + if (detail::parse_strict_float(env_x, parsed)) { + gains.x = parsed; + } + if (detail::parse_strict_float(env_y, parsed)) { + gains.y = parsed; + } + return gains; +} + +// Convenience overload: take the file-or-default gains from a loaded config. A +// default-constructed CalibrationConfig (the fallback when no config file loads) +// already holds the built-in default, so a missing/malformed config resolves to +// 3.2 / 2.6 unless an env override is present. +inline ArmGains resolve_arm_gains(const CalibrationConfig& config, + const char* env_x = nullptr, + const char* env_y = nullptr) { + return resolve_arm_gains(ArmGains{config.arm_gain_x, config.arm_gain_y}, env_x, + env_y); +} + +// The arm-reach amplification the shim's BuildSkeletonFrame applies: push each +// hand/elbow/wrist outward from its shoulder by the per-axis gain so MediaPipe's +// compressed reach spans the game's cursor range like a real Kinect. Templated +// on the position vector type so the production shim (NUI Vector4) and the host +// mechanism test (contract Vector4) run the IDENTICAL code - the single shipping +// definition of this transform. Only the six arm joints move; the hip, spine, +// head and the separate center-of-mass position are left untouched. +template +inline void apply_arm_amplification(Vec* positions, const ArmGains& gains) { + const auto amplify = [&](int joint, int shoulder) { + positions[joint].x = positions[shoulder].x + + (positions[joint].x - positions[shoulder].x) * gains.x; + positions[joint].y = positions[shoulder].y + + (positions[joint].y - positions[shoulder].y) * gains.y; + }; + amplify(9, 8); // ELBOW_RIGHT from SHOULDER_RIGHT + amplify(10, 8); // WRIST_RIGHT + amplify(11, 8); // HAND_RIGHT + amplify(5, 4); // ELBOW_LEFT from SHOULDER_LEFT + amplify(6, 4); // WRIST_LEFT + amplify(7, 4); // HAND_LEFT +} + +// Derive camera-agnostic arm-reach gains from a raised/extended-right-arm hold. +// Each observation's measured_reach_{x,y} is HAND_R relative to the +// amplification-pivot shoulder in post-L/R-swap post-mirror skeleton space +// (metres). The gain per axis is target_reach / |mean measured_reach|, clamped +// to [kArmGainMin, kArmGainMax], averaged over the hold. Returns false (leaving +// `gains` unchanged) when no detected frame with a usable reach was observed. +inline bool derive_arm_gains(const std::vector& hold, + ArmGains& gains, + std::string& error) { + double sum_x = 0.0; + double sum_y = 0.0; + int count = 0; + for (const RaiseRightArmObservation& observation : hold) { + if (!observation.person_detected) { + continue; + } + if (!detail::finite_value(observation.measured_reach_x) || + !detail::finite_value(observation.measured_reach_y)) { + continue; + } + sum_x += std::fabs(observation.measured_reach_x); + sum_y += std::fabs(observation.measured_reach_y); + ++count; + } + if (count == 0) { + error = "arm-gain calibration requires a detected raised-arm hold"; + return false; + } + const float mean_x = static_cast(sum_x / count); + const float mean_y = static_cast(sum_y / count); + constexpr float kMinMeasuredReach = 1e-3f; + if (mean_x < kMinMeasuredReach || mean_y < kMinMeasuredReach) { + error = "arm-gain calibration reach too small - extend the arm fully"; + return false; + } + gains.x = std::clamp(kTargetArmReachX / mean_x, kArmGainMin, kArmGainMax); + gains.y = std::clamp(kTargetArmReachY / mean_y, kArmGainMin, kArmGainMax); + error.clear(); + return true; +} + // Mirror-confirm step: the subject raises only the anatomical right arm. A // raw camera image places that arm on image-left, requiring the global mirror. -bool confirm_mirror_raise_right_arm( +inline bool confirm_mirror_raise_right_arm( const RaiseRightArmObservation& observation, bool& mirror, - std::string& error); + std::string& error) { + const bool right_raised = + observation.right_wrist_v < observation.right_shoulder_v; + const bool left_lowered = + observation.left_wrist_v >= observation.left_shoulder_v; + if (!observation.person_detected || !right_raised || !left_lowered) { + error = "mirror confirmation requires only the right arm raised"; + return false; + } + mirror = observation.right_wrist_u < observation.right_shoulder_u; + error.clear(); + return true; +} // Produces the one-time T-pose calibration. The shoulder span establishes the // player-space scale and Z0 preserves the observed root placement. -bool calibrate_tpose( +inline bool calibrate_tpose( const TposeObservation& observation, CalibrationConfig& output, - std::string& error); + std::string& error) { + constexpr float kProjectionScale = 3.501e-3f; + constexpr float kMinZ = 0.8f; + constexpr float kMaxZ = 4.0f; + if (!observation.person_detected) { + error = "T-pose calibration requires one detected person"; + return false; + } + if (!detail::finite_value(observation.root_depth_meters) || + !detail::finite_value(observation.normalized_shoulder_width) || + observation.normalized_shoulder_width <= 0.0f) { + error = "T-pose calibration observation is invalid"; + return false; + } -bool save_config( + CalibrationConfig candidate{}; + candidate.mapping.z0_meters = + std::clamp(observation.root_depth_meters, kMinZ, kMaxZ); + candidate.mapping.depth_gain = 1.0f; + candidate.mapping.mirror = observation.mirror; + candidate.player_scale = kTargetShoulderWidthMeters / + (observation.normalized_shoulder_width * 320.0f * + kProjectionScale * candidate.mapping.z0_meters); + candidate.floor_plane = observation.floor_plane; + for (const float value : candidate.floor_plane) { + if (!detail::finite_value(value)) { + error = "T-pose floor plane is invalid"; + return false; + } + } + output = candidate; + error.clear(); + return true; +} + +inline bool save_config( const CalibrationConfig& config, const std::string& path, - std::string& error); + std::string& error) { + std::ofstream file(path, std::ios::trunc); + if (!file) { + error = "could not open calibration config for writing"; + return false; + } + file << std::setprecision(9) + << "depth_width " << config.mapping.depth_width << '\n' + << "depth_height " << config.mapping.depth_height << '\n' + << "z0_meters " << config.mapping.z0_meters << '\n' + << "depth_gain " << config.mapping.depth_gain << '\n' + << "mirror " << config.mapping.mirror << '\n' + << "player_scale " << config.player_scale << '\n' + << "smoothing " << config.smoothing.smoothing << ' ' + << config.smoothing.correction << ' ' << config.smoothing.prediction + << ' ' << config.smoothing.jitter_radius << ' ' + << config.smoothing.max_deviation_radius << '\n' + << "floor_plane " << config.floor_plane[0] << ' ' + << config.floor_plane[1] << ' ' << config.floor_plane[2] << ' ' + << config.floor_plane[3] << '\n' + << "arm_gain_x " << config.arm_gain_x << '\n' + << "arm_gain_y " << config.arm_gain_y << '\n'; + if (!file) { + error = "could not write calibration config"; + return false; + } + error.clear(); + return true; +} -bool load_config( +inline bool load_config( const std::string& path, CalibrationConfig& output, - std::string& error); + std::string& error) { + std::ifstream file(path); + CalibrationConfig candidate{}; + std::string key; + if (!file || + !(file >> key >> candidate.mapping.depth_width) || key != "depth_width" || + !(file >> key >> candidate.mapping.depth_height) || key != "depth_height" || + !(file >> key >> candidate.mapping.z0_meters) || key != "z0_meters" || + !(file >> key >> candidate.mapping.depth_gain) || key != "depth_gain" || + !(file >> key >> candidate.mapping.mirror) || key != "mirror" || + !(file >> key >> candidate.player_scale) || key != "player_scale" || + !(file >> key >> candidate.smoothing.smoothing >> + candidate.smoothing.correction >> candidate.smoothing.prediction >> + candidate.smoothing.jitter_radius >> + candidate.smoothing.max_deviation_radius) || key != "smoothing" || + !(file >> key >> candidate.floor_plane[0] >> candidate.floor_plane[1] >> + candidate.floor_plane[2] >> candidate.floor_plane[3]) || + key != "floor_plane") { + error = "could not parse calibration config"; + return false; + } + // arm_gain_{x,y} are an optional trailing pair: older configs predate them, + // so a missing key leaves the built-in default, and a malformed value is + // ignored rather than failing the whole load. + std::string extra; + while (file >> extra) { + if (extra != "arm_gain_x" && extra != "arm_gain_y") { + continue; + } + std::string token; + if (!(file >> token)) { + break; + } + float parsed = 0.0f; + if (!detail::parse_strict_float(token.c_str(), parsed)) { + continue; + } + if (extra == "arm_gain_x") { + candidate.arm_gain_x = parsed; + } else { + candidate.arm_gain_y = parsed; + } + } + output = candidate; + error.clear(); + return true; +} } // namespace nui::calibration diff --git a/docs/game-internals.md b/docs/game-internals.md index 90292c0..d4e877d 100644 --- a/docs/game-internals.md +++ b/docs/game-internals.md @@ -90,10 +90,26 @@ This one is *not* in any DLL — it lives in the game's Flash runtime: `NuiSkeletonSetTrackedSkeletons([id0, id1])`, and NUI's 6 skeleton slots. - **The emulator does not** (yet): it's single‑person end‑to‑end — the contract carries one `SkeletonFrame`, the shim fills only `SkeletonData[0]`, and the - tracker runs single‑person BlazePose (verified: it returns exactly one pose on - a 2‑person image). Enabling 2P needs: a multi‑person pose stage, a 2‑skeleton - contract, and the shim filling `SkeletonData[0]`+`[1]` with distinct - `dwTrackingID`s. + tracker runs single‑person BlazePose. `tracker-native/build/two_person_probe` + is the reproducible Linux evidence: it composes a 24-frame two-person + prominence sequence from the committed `testdata/sample_rgb.bin`, drives the + shipping `PoseEstimator::acquire`/`run` policy, and prints the selected + nose/hip x-region every frame. The 2026-11-27 run emitted exactly one tracked + skeleton in all 24 frames; the ROI held A while B overtook it, then switched + to B at frame 14, and back to A at frame 22 (two identity switches, no loss). +- **Experimental CUR2 probe (off by default):** setting `KINECT_SHIM_2P=1` + makes `BuildSkeletonFrame` copy slot 0 to `SkeletonData[1]`, offset it + horizontally, and assign a distinct tracking ID. It is deliberately not a + claim of real 2P (both slots are the same pose and depth player mask). With + the variable unset or not exactly `1`, slot 1 remains `NOT_TRACKED`; slot 0's + hip and `Position` remain byte-identical. The env read + decision + fill live + in one shared `PopulateSecondSkeletonFromEnv` that both the production + `BuildSkeletonFrame` and the `two_person_shim_probe` host unit call, so the + probe asserts the real shipping gate (unset/`0`/empty/`2` -> off, `1` -> on, + on->off transition, slot-0 bytes unchanged) over the real environment + variable. This only permits an in-game check + whether DEA lights `CUR2`. Real 2P still needs a multi-person pose stage and + a two-skeleton tracker contract. ## 5. Debug tooling: in‑process game introspection diff --git a/fallback/windows-nui/src/sensor.cpp b/fallback/windows-nui/src/sensor.cpp index a2ac20a..1b11cb0 100644 --- a/fallback/windows-nui/src/sensor.cpp +++ b/fallback/windows-nui/src/sensor.cpp @@ -1,3 +1,134 @@ +#include +#include + +// Single shared definition of the experimental CUR2 two-player probe gate. +// Reads the REAL KINECT_SHIM_2P environment variable and, only when it is +// exactly "1", duplicates the tracked slot-0 skeleton into SkeletonData[1] with +// a distinct tracking id, a user index of 1, and a horizontal offset. It writes +// ONLY slot 1, so slot 0's hip/Position bytes are never touched. Templated on +// the frame type so the production NUI_SKELETON_FRAME and the host-test mock +// exercise the SAME shipping code path (same env read, same fill). Returns true +// only when slot 1 was populated; unset/"0"/empty/anything-but-"1" leaves the +// frame as the caller initialised it (slot 1 NOT_TRACKED). +template +bool PopulateSecondSkeletonFromEnv(SkeletonFrame& frame) { + const char* value = std::getenv("KINECT_SHIM_2P"); + if (value == nullptr || std::strcmp(value, "1") != 0) return false; + auto& first = frame.SkeletonData[0]; + auto& second = frame.SkeletonData[1]; + second = first; + second.dwTrackingID = first.dwTrackingID == 1u ? 2u : 1u; + second.dwUserIndex = 1; + const float offset = first.Position.x > 0.0f ? -0.6f : 0.6f; + second.Position.x += offset; + for (auto& position : second.SkeletonPositions) position.x += offset; + return true; +} + +#ifdef NUI_SHIM_2P_HOST_TEST +#include +#include + +struct HostVector4 { float x, y, z, w; }; +struct HostSkeletonData { + unsigned dwTrackingID; + unsigned dwUserIndex; + int eTrackingState; + HostVector4 Position; + std::array SkeletonPositions; +}; +struct HostSkeletonFrame { + std::array SkeletonData; +}; + +// Reproduce production BuildSkeletonFrame's pre-2P state for every frame: reset +// all six slots to NOT_TRACKED, then fill slot 0 as the single tracked skeleton. +// The 2P decision is NOT reimplemented here - it is delegated to the shared +// PopulateSecondSkeletonFromEnv that production also calls. +static void InitFrameWithSlot0(HostSkeletonFrame& frame) { + for (auto& slot : frame.SkeletonData) { + slot = HostSkeletonData{}; + slot.eTrackingState = 0; + slot.dwTrackingID = 0; + } + HostSkeletonData& s0 = frame.SkeletonData[0]; + s0.dwTrackingID = 17; + s0.dwUserIndex = 0; + s0.eTrackingState = 2; + s0.Position = {0.1f, -0.2f, 2.5f, 1.0f}; + for (auto& joint : s0.SkeletonPositions) joint = {0.2f, 0.3f, 2.5f, 1.0f}; +} + +int main() { + HostSkeletonFrame reference{}; + InitFrameWithSlot0(reference); + const HostSkeletonData slot0_pristine = reference.SkeletonData[0]; + + struct Case { const char* name; const char* value; bool expect_on; }; + const Case cases[] = { + {"unset", nullptr, false}, + {"one", "1", true}, + {"zero", "0", false}, + {"empty", "", false}, + {"other", "2", false}, + }; + + bool all_ok = true; + for (const Case& c : cases) { + if (c.value == nullptr) unsetenv("KINECT_SHIM_2P"); + else setenv("KINECT_SHIM_2P", c.value, 1); + + HostSkeletonFrame frame{}; + InitFrameWithSlot0(frame); + const bool populated = PopulateSecondSkeletonFromEnv(frame); + const HostSkeletonData& s1 = frame.SkeletonData[1]; + + bool slot1_ok; + if (c.expect_on) { + slot1_ok = populated && s1.eTrackingState == 2 && + s1.dwTrackingID != frame.SkeletonData[0].dwTrackingID && + s1.dwUserIndex == 1 && + s1.Position.x == slot0_pristine.Position.x - 0.6f; + } else { + slot1_ok = !populated && s1.eTrackingState == 0 && s1.dwTrackingID == 0; + } + const bool slot0_ok = + std::memcmp(&slot0_pristine, &frame.SkeletonData[0], + sizeof(slot0_pristine)) == 0; + all_ok = all_ok && slot1_ok && slot0_ok; + std::printf("env=%-5s expect_%-3s slot1=%s slot0_bytes_unchanged=%s\n", + c.value == nullptr ? "unset" + : (c.value[0] == '\0' ? "''" : c.value), + c.expect_on ? "on" : "off", slot1_ok ? "PASS" : "FAIL", + slot0_ok ? "PASS" : "FAIL"); + } + + // ON -> OFF transition across consecutive frames: frame N has the probe on, + // frame N+1 (producer re-inits the frame) has it off and must clear slot 1. + setenv("KINECT_SHIM_2P", "1", 1); + HostSkeletonFrame transition{}; + InitFrameWithSlot0(transition); + PopulateSecondSkeletonFromEnv(transition); + const bool on_state = transition.SkeletonData[1].eTrackingState == 2 && + transition.SkeletonData[1].dwTrackingID != 0; + unsetenv("KINECT_SHIM_2P"); + InitFrameWithSlot0(transition); // next frame's per-frame reset + PopulateSecondSkeletonFromEnv(transition); + const bool off_state = transition.SkeletonData[1].eTrackingState == 0 && + transition.SkeletonData[1].dwTrackingID == 0; + const bool transition_ok = on_state && off_state; + const bool transition_slot0_ok = + std::memcmp(&slot0_pristine, &transition.SkeletonData[0], + sizeof(slot0_pristine)) == 0; + all_ok = all_ok && transition_ok && transition_slot0_ok; + std::printf("transition on->off=%s slot0_bytes_unchanged=%s\n", + transition_ok ? "PASS" : "FAIL", + transition_slot0_ok ? "PASS" : "FAIL"); + + std::printf("ALL %s\n", all_ok ? "PASS" : "FAIL"); + return all_ok ? 0 : 1; +} +#else #include "sensor.h" #include @@ -9,6 +140,8 @@ #include #include +#include "calibration/calibration.h" + namespace nui_shim { namespace { @@ -19,6 +152,53 @@ VirtualKinectSensor* g_sensor = nullptr; CRITICAL_SECTION g_sensor_lock; INIT_ONCE g_sensor_lock_once = INIT_ONCE_STATIC_INIT; +// Camera-agnostic cursor arm-reach gains, resolved once at NuiInitialize +// (env KINECT_SHIM_ARM_GAIN_X/_Y > config file > built-in 3.2/2.6) and read by +// BuildSkeletonFrame on the producer thread. Set before the producer thread +// starts, so no synchronisation is needed. +float g_arm_gain_x = ::nui::calibration::kDefaultArmGainX; +float g_arm_gain_y = ::nui::calibration::kDefaultArmGainY; + +// Read a wide environment variable as a UTF-8 narrow string (empty = unset). +std::string EnvUtf8(const wchar_t* name) { + wchar_t buffer[1024]; + const DWORD n = GetEnvironmentVariableW(name, buffer, 1024); + if (n == 0 || n >= 1024) { + return std::string(); + } + const int len = WideCharToMultiByte(CP_UTF8, 0, buffer, static_cast(n), + nullptr, 0, nullptr, nullptr); + std::string out(static_cast(len), '\0'); + WideCharToMultiByte(CP_UTF8, 0, buffer, static_cast(n), out.data(), len, + nullptr, nullptr); + return out; +} + +// Resolve the arm-reach gains from the shared calibration config + environment, +// matching the path the native tracker writes (calibration_config_path). +void ResolveArmGains() { + namespace cal = ::nui::calibration; + const std::string override_path = EnvUtf8(L"KINECT_SHIM_CONFIG"); + const std::string local_app_data = EnvUtf8(L"LOCALAPPDATA"); + const std::string config_path = cal::calibration_config_path( + override_path.empty() ? nullptr : override_path.c_str(), + local_app_data.empty() ? nullptr : local_app_data.c_str()); + cal::CalibrationConfig config; + std::string error; + const bool loaded = cal::load_config(config_path, config, error); + const std::string env_x = EnvUtf8(L"KINECT_SHIM_ARM_GAIN_X"); + const std::string env_y = EnvUtf8(L"KINECT_SHIM_ARM_GAIN_Y"); + const cal::ArmGains gains = cal::resolve_arm_gains( + config, env_x.empty() ? nullptr : env_x.c_str(), + env_y.empty() ? nullptr : env_y.c_str()); + g_arm_gain_x = gains.x; + g_arm_gain_y = gains.y; + ShimLog("arm-gain resolve: path='%s' config=%d env=(%s,%s) gains=(%.3f,%.3f)", + config_path.c_str(), loaded ? 1 : 0, + env_x.empty() ? "-" : env_x.c_str(), + env_y.empty() ? "-" : env_y.c_str(), g_arm_gain_x, g_arm_gain_y); +} + // Set true (and rebuild) to re-enable the in-process reverse-engineering // instrumentation: DumpGameDisplayState() below plus the per-frame "handcur:" // hand/cursor log in BuildSkeletonFrame. These read the game's own live memory @@ -310,6 +490,7 @@ HRESULT VirtualKinectSensor::Initialize(DWORD dwFlags) { return E_NUI_ALREADY_INITIALIZED; } init_flags_ = dwFlags; + ResolveArmGains(); std::wstring name = MappingName(); bool opened = source_.open(name.c_str()); DWORD err = opened ? 0u : GetLastError(); @@ -758,19 +939,17 @@ void VirtualKinectSensor::BuildSkeletonFrame(const SourceFrame& src) { joint.position.z, joint.position.w}; data.eSkeletonPositionTrackingState[j] = NUI_SKELETON_POSITION_TRACKED; } - const float kArmGainX = 3.2f, kArmGainY = 2.6f; - auto amp_arm = [&](int j, int shoulder) { - auto& p = data.SkeletonPositions[j]; - const auto& s = data.SkeletonPositions[shoulder]; - p.x = s.x + (p.x - s.x) * kArmGainX; - p.y = s.y + (p.y - s.y) * kArmGainY; - }; - amp_arm(9, 8); - amp_arm(10, 8); - amp_arm(11, 8); // right arm from SHOULDER_RIGHT - amp_arm(5, 4); - amp_arm(6, 4); - amp_arm(7, 4); // left arm from SHOULDER_LEFT + ::nui::calibration::apply_arm_amplification( + data.SkeletonPositions, + ::nui::calibration::ArmGains{g_arm_gain_x, g_arm_gain_y}); + + // EXPERIMENT ONLY: duplicate the one tracked person to exercise DEA's CUR2. + // Explicit opt-in on each frame; unset, "0", or any other value stays OFF. + // This is not real two-person tracking or a second depth player mask. The + // decision+fill (and the KINECT_SHIM_2P read) live in the shared, host- + // tested PopulateSecondSkeletonFromEnv above so the probe exercises this + // exact code path. It writes only SkeletonData[1]; slot 0 stays untouched. + PopulateSecondSkeletonFromEnv(frame); } static unsigned build_calls = 0; @@ -1009,3 +1188,6 @@ void DestroyGlobalSensor() { } } + +#endif // NUI_SHIM_2P_HOST_TEST + diff --git a/tests/test_calibration.cpp b/tests/test_calibration.cpp index b73a674..462ca9c 100644 --- a/tests/test_calibration.cpp +++ b/tests/test_calibration.cpp @@ -1,6 +1,11 @@ #include +#include #include +#include +#include +#include +#include #include "calibration/calibration.h" @@ -88,3 +93,203 @@ TEST(calibration, NoPersonReturnsErrorWithoutWritingConfig) { EXPECT_FALSE(error.empty()); EXPECT_FLOAT_EQ(config.mapping.z0_meters, 1.75f); } + +TEST(calibration, DeriveArmGainsAveragesHoldAndScalesToTargetReach) { + std::vector hold; + for (int i = 0; i < 16; ++i) { + nui::calibration::RaiseRightArmObservation o{}; + o.person_detected = true; + o.measured_reach_x = 0.5f; + o.measured_reach_y = 0.3f; + hold.push_back(o); + } + nui::calibration::ArmGains gains{}; + std::string error; + ASSERT_TRUE(nui::calibration::derive_arm_gains(hold, gains, error)); + EXPECT_NEAR(gains.x, nui::calibration::kTargetArmReachX / 0.5f, 1e-5f); + EXPECT_NEAR(gains.y, nui::calibration::kTargetArmReachY / 0.3f, 1e-5f); +} + +TEST(calibration, DeriveArmGainsClampsToRangeAndRejectsBadHolds) { + nui::calibration::ArmGains gains{}; + std::string error; + + std::vector empty; + EXPECT_FALSE(nui::calibration::derive_arm_gains(empty, gains, error)); + EXPECT_FALSE(error.empty()); + + nui::calibration::RaiseRightArmObservation degenerate{}; + degenerate.person_detected = true; + EXPECT_FALSE(nui::calibration::derive_arm_gains({degenerate}, gains, error)); + + nui::calibration::RaiseRightArmObservation over{}; + over.person_detected = true; + over.measured_reach_x = 2.0f; + over.measured_reach_y = 2.0f; + ASSERT_TRUE(nui::calibration::derive_arm_gains({over}, gains, error)); + EXPECT_FLOAT_EQ(gains.x, nui::calibration::kArmGainMin); + EXPECT_FLOAT_EQ(gains.y, nui::calibration::kArmGainMin); +} + +TEST(calibration, ResolveArmGainsPrecedenceEnvThenConfigThenDefault) { + nui::calibration::CalibrationConfig config{}; + EXPECT_FLOAT_EQ(nui::calibration::resolve_arm_gains(config).x, + nui::calibration::kDefaultArmGainX); + EXPECT_FLOAT_EQ(nui::calibration::resolve_arm_gains(config).y, + nui::calibration::kDefaultArmGainY); + + config.arm_gain_x = 2.0f; + config.arm_gain_y = 1.5f; + const nui::calibration::ArmGains from_config = + nui::calibration::resolve_arm_gains(config, nullptr, ""); + EXPECT_FLOAT_EQ(from_config.x, 2.0f); + EXPECT_FLOAT_EQ(from_config.y, 1.5f); + + const nui::calibration::ArmGains from_env = + nui::calibration::resolve_arm_gains(config, "5.0", "4.25"); + EXPECT_FLOAT_EQ(from_env.x, 5.0f); + EXPECT_FLOAT_EQ(from_env.y, 4.25f); +} + +TEST(calibration, ResolveArmGainsIgnoresMalformedEnv) { + nui::calibration::CalibrationConfig config{}; + config.arm_gain_x = 3.0f; + config.arm_gain_y = 2.0f; + const nui::calibration::ArmGains gains = + nui::calibration::resolve_arm_gains(config, "abc", "3xyz"); + EXPECT_FLOAT_EQ(gains.x, 3.0f); + EXPECT_FLOAT_EQ(gains.y, 2.0f); +} + +TEST(calibration, CalibrationConfigPathPrefersOverrideThenLocalAppData) { + EXPECT_EQ(nui::calibration::calibration_config_path( + "C:\\custom\\k.cfg", "C:\\Users\\a\\AppData\\Local"), + "C:\\custom\\k.cfg"); + EXPECT_EQ(nui::calibration::calibration_config_path( + nullptr, "C:\\Users\\a\\AppData\\Local"), + "C:\\Users\\a\\AppData\\Local\\VirtualKinect\\calibration.cfg"); + EXPECT_EQ(nui::calibration::calibration_config_path("", ""), + "VirtualKinect\\calibration.cfg"); +} + +TEST(calibration, MalformedOrEmptyConfigResolvesToDefaultWithoutCrash) { + std::string error; + const std::string malformed = "/tmp/kinect_armgain_malformed.cfg"; + { + std::ofstream f(malformed); + f << "garbage not a config\n"; + } + nui::calibration::CalibrationConfig config{}; + EXPECT_FALSE(nui::calibration::load_config(malformed, config, error)); + std::remove(malformed.c_str()); + + const std::string empty = "/tmp/kinect_armgain_empty.cfg"; + { std::ofstream f(empty); } + nui::calibration::CalibrationConfig config2{}; + EXPECT_FALSE(nui::calibration::load_config(empty, config2, error)); + std::remove(empty.c_str()); + + const nui::calibration::ArmGains gains = + nui::calibration::resolve_arm_gains(config2); + EXPECT_FLOAT_EQ(gains.x, nui::calibration::kDefaultArmGainX); + EXPECT_FLOAT_EQ(gains.y, nui::calibration::kDefaultArmGainY); +} + +// IS-2 mechanism proof (no game): derive gains from a synthetic extended-arm +// hold, round-trip them through save/load/resolve, then apply the shim's +// amp_arm math to a synthetic post-L/R-swap skeleton and assert the amplified +// HAND_R excursion lands on the real-Kinect target reach while hip/center-of- +// mass stay byte-unchanged. +TEST(calibration, ShimGainMechanismDeriveSaveResolveAmplifyHitsTarget) { + std::vector hold; + for (int i = 0; i < 20; ++i) { + nui::calibration::RaiseRightArmObservation o{}; + o.person_detected = true; + o.measured_reach_x = 0.5f; + o.measured_reach_y = 0.3f; + hold.push_back(o); + } + nui::calibration::ArmGains derived{}; + std::string error; + ASSERT_TRUE(nui::calibration::derive_arm_gains(hold, derived, error)); + + nui::calibration::CalibrationConfig config{}; + config.arm_gain_x = derived.x; + config.arm_gain_y = derived.y; + const std::string path = "/tmp/kinect_armgain_mechanism.cfg"; + ASSERT_TRUE(nui::calibration::save_config(config, path, error)); + nui::calibration::CalibrationConfig loaded{}; + ASSERT_TRUE(nui::calibration::load_config(path, loaded, error)); + std::remove(path.c_str()); + const nui::calibration::ArmGains resolved = + nui::calibration::resolve_arm_gains(loaded, nullptr, nullptr); + EXPECT_NEAR(resolved.x, derived.x, 1e-5f); + EXPECT_NEAR(resolved.y, derived.y, 1e-5f); + + // Drive the EXACT shipping transform: apply_arm_amplification is the same + // shared function the shim's BuildSkeletonFrame calls (no copied lambda). + std::array positions; + for (nui::contract::Vector4& p : positions) p = {0.0f, 0.0f, 0.0f, 1.0f}; + positions[8] = {0.20f, 1.40f, 2.5f, 1.0f}; // SHOULDER_RIGHT + positions[11] = {positions[8].x + 0.5f, // HAND_RIGHT: + positions[8].y + 0.3f, 2.5f, 1.0f}; // excursion == measured + const nui::contract::Vector4 hip_before{0.03f, 0.90f, 2.5f, 1.0f}; + positions[0] = hip_before; // HIP_CENTER joint + const nui::contract::Vector4 hand_before = positions[11]; + + nui::calibration::apply_arm_amplification(positions.data(), resolved); + + EXPECT_NEAR(positions[11].x - positions[8].x, + nui::calibration::kTargetArmReachX, 1e-4f); + EXPECT_NEAR(positions[11].y - positions[8].y, + nui::calibration::kTargetArmReachY, 1e-4f); + // EXACT bit preservation of the hip / center-of-mass. apply_arm_amplification + // touches only the 6 arm joints (5,6,7,9,10,11), so the HIP_CENTER joint must + // be byte-identical - prove it bit-exactly, not within a float tolerance. The + // shim's derived NUI Position (center-of-mass) is copied from this hip before + // amplification, so an untouched hip guarantees an untouched Position. + const nui::contract::Vector4 hip_after = positions[0]; + EXPECT_EQ(0, std::memcmp(&hip_before, &hip_after, sizeof(hip_before))); + EXPECT_EQ(hip_before.x, hip_after.x); + EXPECT_EQ(hip_before.y, hip_after.y); + EXPECT_EQ(hip_before.z, hip_after.z); + EXPECT_EQ(hip_before.w, hip_after.w); + // Amplification moves only x,y of the arm joint; z,w stay bit-exact. + EXPECT_EQ(hand_before.z, positions[11].z); + EXPECT_EQ(hand_before.w, positions[11].w); +} + +TEST(calibration, MalformedGainTokenInConfigFallsBackToDefault) { + const std::string path = "/tmp/kinect_armgain_token.cfg"; + { + std::ofstream f(path); + f << "depth_width 640\n" + << "depth_height 480\n" + << "z0_meters 2.5\n" + << "depth_gain 1\n" + << "mirror 1\n" + << "player_scale 1\n" + << "smoothing 0.6 0.4 0.4 0.04 0.07\n" + << "floor_plane 0 1 0 0\n" + << "arm_gain_x 2junk\n" + << "arm_gain_y 2.6\n"; + } + nui::calibration::CalibrationConfig config{}; + std::string error; + ASSERT_TRUE(nui::calibration::load_config(path, config, error)); + std::remove(path.c_str()); + // "2junk" is rejected (not read as 2.0), so arm_gain_x keeps the default. + EXPECT_FLOAT_EQ(config.arm_gain_x, nui::calibration::kDefaultArmGainX); + EXPECT_FLOAT_EQ(config.arm_gain_y, 2.6f); + const nui::calibration::ArmGains gains = + nui::calibration::resolve_arm_gains(config); + EXPECT_FLOAT_EQ(gains.x, 3.2f); + EXPECT_FLOAT_EQ(gains.y, 2.6f); +} + +TEST(calibration, DefaultResolveMatchesLegacyHardcodedGains) { + const nui::calibration::ArmGains gains = + nui::calibration::resolve_arm_gains(nui::calibration::CalibrationConfig{}); + EXPECT_FLOAT_EQ(gains.x, 3.2f); + EXPECT_FLOAT_EQ(gains.y, 2.6f); +} diff --git a/tracker-native/MANIFEST.sha256 b/tracker-native/MANIFEST.sha256 new file mode 100644 index 0000000..d0f8511 --- /dev/null +++ b/tracker-native/MANIFEST.sha256 @@ -0,0 +1,5 @@ +a92b05663bf998f8353539d0ee0ec1566c1ab598d5457769005b05d659889abf models/pose_landmarks_detector.onnx +82be6d591b9dad7d29fe21dc9fd892bf8b9602c458fb05209283de8282a0c488 models/pose_landmarks_detector.tflite +04f5a96483f8ce5913f8730ad2aa0c4c999c80a4b75653bc0e4712de18e104b2 models/pose_detector.tflite +4cb41e89b8bf30578e1dd95e9c40292d61974a4bfcd666409302c4f0c5aa8ce0 third_party/onnxruntime-win-x64/lib/onnxruntime.dll +c5a4f0b1af1e8f1edd11391e1a15a7d52832d94a1a67cf6b8f22ed29f863a06c third_party/onnxruntime-win-x64/lib/onnxruntime.lib diff --git a/tracker-native/README.md b/tracker-native/README.md index 0bb3b99..05e4930 100644 --- a/tracker-native/README.md +++ b/tracker-native/README.md @@ -5,14 +5,49 @@ Native replacement for the Python/MediaPipe `tracker/`. See camera + resolution picker, live preview, native pose + segmentation, and the shared-memory publish the `Kinect10.dll` shim reads. -No binaries are committed. Generate them locally: +No binaries are committed. Fetch the models and ONNX Runtime (no Python needed): ```sh -scripts/setup_models.sh # extract MediaPipe .task -> tflite, convert -> onnx -scripts/fetch_ort.sh # download prebuilt ONNX Runtime (linux + win x64) +scripts/fetch_models.sh # pose models: prebuilt .onnx + .tflite, checksum-verified +scripts/fetch_ort.sh # prebuilt ONNX Runtime 1.20.1 (linux + win x64) ./build.sh # headless Linux build (currently the ORT smoke test) ``` +After fetching, verify every artifact against the pinned manifest: + +```sh +sha256sum -c MANIFEST.sha256 # run from this directory (tracker-native/) +``` + +## Models & ONNX Runtime acquisition + +The player path is Python-free: `fetch_models.sh` downloads a prebuilt +`pose_landmarks_detector.onnx` and extracts the `.tflite` files from the +MediaPipe bundle with `unzip`; it never runs `tf2onnx`. Every download is +pinned by SHA256 (`MANIFEST.sha256` and the `*_SHA256` constants in the +scripts) and any mismatch aborts with a non-zero exit. + +| Artifact | Version / source | License | +| --- | --- | --- | +| `pose_landmarks_detector.onnx` (runtime-required) | project mirror asset, tf2onnx export of the bundle's landmark `.tflite` | Apache-2.0 (MediaPipe BlazePose) | +| `pose_landmarks_detector.tflite`, `pose_detector.tflite` | MediaPipe `pose_landmarker_full` bundle, Google model storage (`.../float16/1/pose_landmarker_full.task`) | Apache-2.0 (MediaPipe BlazePose) | +| `onnxruntime.dll` / `.lib`, `libonnxruntime.so` | ONNX Runtime 1.20.1, project mirror `cga-management/third-party-mirror` (tag `onnxruntime-1.20.1`) | MIT | + +Upstream `microsoft/onnxruntime` GitHub releases were removed on 2026-11-17, so +ONNX Runtime is pinned to the project mirror's unchanged 1.20.1 assets. + +The runtime loads only `pose_landmarks_detector.onnx` (see +`src/win_main.cpp` `kModelName`); the `.tflite` files are kept for development +and reference. The ROI detector model is not converted (`tf2onnx` cannot +convert it), so the tracker bootstraps the ROI instead. + +**Publishing the prebuilt `.onnx`:** `fetch_models.sh` fetches the landmark +`.onnx` from `MODEL_ONNX_URL` (default: the project mirror). Publish the file +whose SHA256 is in `MANIFEST.sha256` as that mirror asset (the same way the ORT +assets are mirrored), or point `MODEL_ONNX_URL` at a local copy +(`file:///path/...`). Regenerating that `.onnx` from the `.tflite` is a DEV-only +step via `scripts/setup_models.sh` (needs Python + `tf2onnx`). + ## Status - Inference foundation proven: the real MediaPipe BlazePose landmark weights diff --git a/tracker-native/build.sh b/tracker-native/build.sh old mode 100755 new mode 100644 index 0f4c7ff..5408b7b --- a/tracker-native/build.sh +++ b/tracker-native/build.sh @@ -10,7 +10,7 @@ g++ -std=c++17 -O2 -Wall -Wextra \ -I "${ORT}/include" \ "${HERE}/src/ort_smoke.cpp" \ -o "${HERE}/build/ort_smoke" \ - -L "${ORT}/lib" -lonnxruntime -Wl,-rpath,"${ORT}/lib" + -L "${ORT}/lib" -l:libonnxruntime.so.1 -Wl,-rpath,"${ORT}/lib" echo "built ${HERE}/build/ort_smoke" g++ -std=c++17 -O2 -Wall -Wextra \ @@ -23,7 +23,7 @@ g++ -std=c++17 -O2 -Wall -Wextra \ -I "${ORT}/include" -I "${HERE}/src" \ "${HERE}/src/pose_estimator.cpp" "${HERE}/src/pose_probe.cpp" \ -o "${HERE}/build/pose_probe" \ - -L "${ORT}/lib" -lonnxruntime -Wl,-rpath,"${ORT}/lib" + -L "${ORT}/lib" -l:libonnxruntime.so.1 -Wl,-rpath,"${ORT}/lib" echo "built ${HERE}/build/pose_probe" g++ -std=c++17 -O2 -Wall -Wextra \ @@ -33,12 +33,29 @@ g++ -std=c++17 -O2 -Wall -Wextra \ "${CORE}/mapping/mapping.cpp" "${CORE}/synth/synth.cpp" \ "${CORE}/synth/mask_stabilizer.cpp" "${CORE}/contract/contract.cpp" \ -o "${HERE}/build/pipeline_probe" \ - -L "${ORT}/lib" -lonnxruntime -Wl,-rpath,"${ORT}/lib" + -L "${ORT}/lib" -l:libonnxruntime.so.1 -Wl,-rpath,"${ORT}/lib" echo "built ${HERE}/build/pipeline_probe" g++ -std=c++17 -O2 -Wall -Wextra \ -I "${ORT}/include" -I "${HERE}/src" \ "${HERE}/src/pose_estimator.cpp" "${HERE}/src/skel_render_probe.cpp" \ -o "${HERE}/build/skel_render_probe" \ - -L "${ORT}/lib" -lonnxruntime -Wl,-rpath,"${ORT}/lib" + -L "${ORT}/lib" -l:libonnxruntime.so.1 -Wl,-rpath,"${ORT}/lib" echo "built ${HERE}/build/skel_render_probe" + +# Linux-only reproducible two-person experiment. +g++ -std=c++17 -O2 -Wall -Wextra \ + -I "${ORT}/include" -I "${HERE}/src" -I "${CORE}" \ + "${HERE}/src/pose_estimator.cpp" "${HERE}/src/two_person_probe.cpp" \ + -o "${HERE}/build/two_person_probe" \ + -L "${ORT}/lib" -l:libonnxruntime.so.1 -Wl,-rpath,"${ORT}/lib" +echo "built ${HERE}/build/two_person_probe" + +# The shim is a Windows DLL but this Linux host check drives the same fixed +# copy/offset policy used inside BuildSkeletonFrame's env-gated branch. +# gnu++17 (not c++17) so glibc exposes POSIX setenv/unsetenv, which the host +# probe uses to drive the REAL KINECT_SHIM_2P read inside the shared gate. +g++ -std=gnu++17 -O2 -Wall -Wextra -DNUI_SHIM_2P_HOST_TEST \ + "${HERE}/../fallback/windows-nui/src/sensor.cpp" \ + -o "${HERE}/build/two_person_shim_probe" +echo "built ${HERE}/build/two_person_shim_probe" diff --git a/tracker-native/scripts/fetch_models.sh b/tracker-native/scripts/fetch_models.sh new file mode 100755 index 0000000..55bf06a --- /dev/null +++ b/tracker-native/scripts/fetch_models.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# fetch_models.sh - obtain the pose models for a PLAYER with NO Python / tf2onnx. +# +# Produces (into MODELS_DEST, default tracker-native/models/): +# pose_landmarks_detector.onnx REQUIRED at runtime - kinect-tracker loads +# only this model (ONNX Runtime, see +# src/win_main.cpp kModelName, pose_estimator.cpp). +# pose_landmarks_detector.tflite dev/reference (BlazePose landmark weights). +# pose_detector.tflite dev/reference (ROI detector; tf2onnx cannot +# convert it, so it is not used at runtime). +# +# Pinned, checksummed sources (see README.md "Models & ONNX Runtime acquisition"): +# +# 1) MediaPipe BlazePose "pose_landmarker_full" bundle (Apache-2.0), hosted on +# Google's model storage at a version-pinned URL. A .task file is a plain +# zip, extracted here with `unzip` - no Python. +# +# 2) pose_landmarks_detector.onnx: the project's tf2onnx export of the bundle's +# landmark .tflite, published as a redistributable asset on the project +# mirror. Players fetch this prebuilt .onnx and NEVER run tf2onnx. +# Regenerating it from the .tflite is a DEV-only step (scripts/setup_models.sh, +# needs Python + tf2onnx). +# +# Every artifact's SHA256 is pinned below. Any mismatch (tampering, partial or +# stale download, wrong upstream version) aborts loudly with a non-zero exit. +# +# Overrides (for testing / mirrors): +# MODELS_DEST= where the models are written (default tracker-native/models) +# TASK_URL= MediaPipe .task bundle +# MODEL_ONNX_URL= prebuilt landmark .onnx (http(s):// or file://) +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +MODELS="${MODELS_DEST:-${HERE}/models}" + +TASK_URL="${TASK_URL:-https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_full/float16/1/pose_landmarker_full.task}" +TASK_SHA256="5134a3aad27a58b93da0088d431f366da362b44e3ccfbe3462b3827a839011b1" + +# Prebuilt landmark ONNX, published as a redistributable asset on the project +# mirror (Apache-2.0). If this asset is not yet published, publish the file whose +# sha256 is ONNX_SHA256 (see MANIFEST.sha256) to the mirror, or point +# MODEL_ONNX_URL at a local copy (file://...). Do NOT fall back to tf2onnx here. +MODEL_ONNX_URL="${MODEL_ONNX_URL:-https://github.com/cga-management/third-party-mirror/releases/download/mediapipe-pose-landmarker-full-1/pose_landmarks_detector.onnx}" + +ONNX_SHA256="a92b05663bf998f8353539d0ee0ec1566c1ab598d5457769005b05d659889abf" +TFLITE_LM_SHA256="82be6d591b9dad7d29fe21dc9fd892bf8b9602c458fb05209283de8282a0c488" +TFLITE_DET_SHA256="04f5a96483f8ce5913f8730ad2aa0c4c999c80a4b75653bc0e4712de18e104b2" + +need() { command -v "$1" >/dev/null 2>&1 || { echo "FATAL: required tool '$1' not found on PATH" >&2; exit 3; }; } +verify() { + local f="$1" want="$2" label="${3:-$(basename "$1")}" got + got="$(sha256sum "$f" | cut -d' ' -f1)" + if [ "$got" != "$want" ]; then + echo "FATAL: SHA256 mismatch for ${label}" >&2 + echo " expected ${want}" >&2 + echo " got ${got}" >&2 + exit 2 + fi + echo "ok: ${label} sha256 verified" +} + +need curl; need sha256sum; need unzip + +mkdir -p "${MODELS}" +TMP="$(mktemp -d)" +trap 'rm -rf "${TMP}"' EXIT + +echo "fetching MediaPipe BlazePose bundle ..." +curl -fSL --retry 3 --connect-timeout 30 -o "${TMP}/pose.task" "${TASK_URL}" +verify "${TMP}/pose.task" "${TASK_SHA256}" "pose_landmarker_full.task" +unzip -o -q "${TMP}/pose.task" -d "${TMP}/ext" +cp -f "${TMP}/ext/pose_landmarks_detector.tflite" "${MODELS}/" +cp -f "${TMP}/ext/pose_detector.tflite" "${MODELS}/" +verify "${MODELS}/pose_landmarks_detector.tflite" "${TFLITE_LM_SHA256}" +verify "${MODELS}/pose_detector.tflite" "${TFLITE_DET_SHA256}" + +echo "fetching prebuilt pose_landmarks_detector.onnx ..." +if ! curl -fSL --retry 3 --connect-timeout 30 -o "${TMP}/pose_landmarks_detector.onnx" "${MODEL_ONNX_URL}"; then + echo "FATAL: could not download the prebuilt landmark model from:" >&2 + echo " ${MODEL_ONNX_URL}" >&2 + echo "If the mirror asset is not published yet, publish the file whose sha256 is" >&2 + echo " ${ONNX_SHA256} (see MANIFEST.sha256)" >&2 + echo "to the project mirror, or re-run with MODEL_ONNX_URL=file:///path/to/pose_landmarks_detector.onnx" >&2 + echo "Do NOT run tf2onnx for the player path - setup_models.sh is DEV-only." >&2 + exit 4 +fi +verify "${TMP}/pose_landmarks_detector.onnx" "${ONNX_SHA256}" "pose_landmarks_detector.onnx" +cp -f "${TMP}/pose_landmarks_detector.onnx" "${MODELS}/" + +echo +echo "models ready in ${MODELS}:" +ls -la "${MODELS}" diff --git a/tracker-native/scripts/fetch_ort.sh b/tracker-native/scripts/fetch_ort.sh index 3ef20fb..7236960 100755 --- a/tracker-native/scripts/fetch_ort.sh +++ b/tracker-native/scripts/fetch_ort.sh @@ -1,22 +1,67 @@ #!/usr/bin/env bash -# Fetch prebuilt ONNX Runtime (linux-x64 for headless validation, win-x64 for -# the shipped build). The official microsoft/onnxruntime GitHub repo was removed -# on 2026-11-17; these are the unchanged 1.20.1 assets from a recovery mirror. +# fetch_ort.sh - download prebuilt ONNX Runtime 1.20.1 (MIT), checksum-verified. +# linux-x64 -> headless validation builds +# win-x64 -> the shipped Windows tracker (provides onnxruntime.dll + .lib) +# +# Source (pinned): the project third-party mirror +# https://github.com/cga-management/third-party-mirror (tag onnxruntime-1.20.1) +# The upstream microsoft/onnxruntime GitHub releases were removed on 2026-11-17; +# the mirror hosts the unchanged official 1.20.1 assets. The SHA256 values below +# pin the exact bytes, so a tampered, partial, or wrong asset aborts with a +# non-zero exit. Extraction uses tar/unzip only - no Python. +# +# Overrides: +# ORT_DEST= where onnxruntime-{linux,win}-x64/ are placed +# (default tracker-native/third_party) +# ORT_BASE_URL= release base URL (for a different mirror) set -euo pipefail -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -V="${ORT_VERSION:-1.20.1}" -B="https://github.com/cga-management/third-party-mirror/releases/download/onnxruntime-${V}" -mkdir -p "${HERE}/third_party" -cd "${HERE}/third_party" -if [ ! -d onnxruntime-linux-x64 ]; then - curl -fsSL -o ort-linux.tgz "${B}/onnxruntime-linux-x64-${V}.tgz" - tar xzf ort-linux.tgz && rm ort-linux.tgz +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +V="1.20.1" +DEST="${ORT_DEST:-${HERE}/third_party}" +BASE="${ORT_BASE_URL:-https://github.com/cga-management/third-party-mirror/releases/download/onnxruntime-${V}}" + +ORT_LINUX_SHA256="67db4dc1561f1e3fd42e619575c82c601ef89849afc7ea85a003abbac1a1a105" +ORT_WIN_SHA256="78d447051e48bd2e1e778bba378bec4ece11191c9e538cf7b2c4a4565e8f5581" + +need() { command -v "$1" >/dev/null 2>&1 || { echo "FATAL: required tool '$1' not found on PATH" >&2; exit 3; }; } +verify() { + local f="$1" want="$2" label="${3:-$(basename "$1")}" got + got="$(sha256sum "$f" | cut -d' ' -f1)" + if [ "$got" != "$want" ]; then + echo "FATAL: SHA256 mismatch for ${label}" >&2 + echo " expected ${want}" >&2 + echo " got ${got}" >&2 + exit 2 + fi + echo "ok: ${label} sha256 verified" +} + +need curl; need sha256sum; need tar; need unzip + +mkdir -p "${DEST}" +cd "${DEST}" + +if [ ! -f "onnxruntime-linux-x64/lib/libonnxruntime.so.${V}" ]; then + echo "fetching ONNX Runtime ${V} linux-x64 ..." + curl -fSL --retry 3 --connect-timeout 30 -o ort-linux.tgz "${BASE}/onnxruntime-linux-x64-${V}.tgz" + verify ort-linux.tgz "${ORT_LINUX_SHA256}" "onnxruntime-linux-x64-${V}.tgz" + rm -rf onnxruntime-linux-x64 "onnxruntime-linux-x64-${V}" + tar xzf ort-linux.tgz mv "onnxruntime-linux-x64-${V}" onnxruntime-linux-x64 + rm -f ort-linux.tgz fi -if [ ! -d onnxruntime-win-x64 ]; then - curl -fsSL -o ort-win.zip "${B}/onnxruntime-win-x64-${V}.zip" - python3 -c "import zipfile; zipfile.ZipFile('ort-win.zip').extractall('.')" - rm ort-win.zip && mv "onnxruntime-win-x64-${V}" onnxruntime-win-x64 + +if [ ! -f "onnxruntime-win-x64/lib/onnxruntime.dll" ]; then + echo "fetching ONNX Runtime ${V} win-x64 ..." + curl -fSL --retry 3 --connect-timeout 30 -o ort-win.zip "${BASE}/onnxruntime-win-x64-${V}.zip" + verify ort-win.zip "${ORT_WIN_SHA256}" "onnxruntime-win-x64-${V}.zip" + rm -rf onnxruntime-win-x64 "onnxruntime-win-x64-${V}" + unzip -q ort-win.zip + mv "onnxruntime-win-x64-${V}" onnxruntime-win-x64 + rm -f ort-win.zip fi -echo "ONNX Runtime ${V} ready: $(ls -d onnxruntime-*-x64)" + +echo +echo "ONNX Runtime ${V} ready in ${DEST}:" +ls -d onnxruntime-*-x64 diff --git a/tracker-native/scripts/setup_models.sh b/tracker-native/scripts/setup_models.sh index 5fe0d00..93708e8 100755 --- a/tracker-native/scripts/setup_models.sh +++ b/tracker-native/scripts/setup_models.sh @@ -1,4 +1,9 @@ #!/usr/bin/env bash +# setup_models.sh - DEV ONLY. Regenerates pose_landmarks_detector.onnx from the +# MediaPipe .task via tf2onnx (needs Python + tf2onnx). Players do NOT run this; +# the no-Python player path is scripts/fetch_models.sh + scripts/fetch_ort.sh. +# Use this only to produce a new prebuilt .onnx to publish to the project mirror +# (then update ONNX_SHA256 in fetch_models.sh and MANIFEST.sha256). set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" TASK="${1:-${HERE}/../tracker/models/pose_landmarker_full.task}" diff --git a/tracker-native/src/two_person_probe.cpp b/tracker-native/src/two_person_probe.cpp new file mode 100644 index 0000000..d67b421 --- /dev/null +++ b/tracker-native/src/two_person_probe.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include + +#include "frame_pipeline.h" +#include "pose_estimator.h" +#include "../testdata/two_person_sequence.h" + +using namespace kinect_tracker; +namespace sequence = two_person_sequence; + +static sequence::Image ReadRgb(const std::string& path) { + std::ifstream file(path, std::ios::binary); + sequence::Image image{}; + file.read(reinterpret_cast(&image.width), sizeof(image.width)); + file.read(reinterpret_cast(&image.height), sizeof(image.height)); + if (!file || image.width != 512 || image.height != 600) { + std::fprintf(stderr, "Expected the committed 512x600 RGB fixture: %s\n", path.c_str()); + std::exit(1); + } + image.rgb.resize(static_cast(image.width) * image.height * 3); + file.read(reinterpret_cast(image.rgb.data()), image.rgb.size()); + if (!file || image.width <= 0 || image.height <= 0) { + std::fprintf(stderr, "Cannot read RGB fixture: %s\n", path.c_str()); + std::exit(1); + } + return image; +} + +static char Selected(const PoseResult& pose, bool tracked, + const sequence::Stage& stage) { + if (!tracked) return '-'; + const float nose = pose.image_xy[0]; + const float hip = (pose.image_xy[23 * 2] + pose.image_xy[24 * 2]) * 0.5f; + const int heights[] = {stage.a_height, stage.b_height}; + const int centers[] = {160, 480}; + const int source_width = 512; + const int source_height = 600; + for (int p = 0; p < 2; ++p) { + const int half = (source_width * heights[p] / source_height) / 2; + if (nose >= centers[p] - half && nose <= centers[p] + half && + hip >= centers[p] - half && hip <= centers[p] + half) { + return p == 0 ? 'A' : 'B'; + } + } + return '?'; // Neither person's known x region; do not invent an identity. +} + +int main(int argc, char** argv) { + if (argc != 3 && argc != 4) { + std::fprintf(stderr, "usage: %s MODEL TESTDATA [FRAME_OUTPUT_DIRECTORY]\n", + argv[0]); + return 1; + } + const std::string testdata = argv[2]; + const auto a = ReadRgb(testdata + "/sample_rgb.bin"); + const auto b = a; + if (a.width != 512 || a.height != 600) { + std::fprintf(stderr, "Fixture dimensions changed; generator no longer applies\n"); + return 1; + } + PoseEstimator estimator(argv[1]); + const float threshold = PipelineConfig{}.presence_threshold; + Roi roi{}; + bool have_lock = false; + char last_person = '-'; + unsigned frame = 0, losses = 0, reacquisitions = 0, switches = 0, tracked_frames = 0; + std::printf("native PoseEstimator; shipping acquire/run policy; threshold=%.3f\n" + "A=left sample_rgb copy; B=right sample_rgb copy; ?=outside regions\n" + "640x480 already in tracker RGB coordinates; no extra mirror\n", threshold); + for (const auto& stage : sequence::kStages) { + const auto rgb = sequence::compose(a, b, stage); + // Independent cold acquisition measures prominence preference; it does not + // replace the sequential tracker's ROI or lock. + const auto cold = estimator.acquire(rgb.data(), sequence::kWidth, sequence::kHeight); + const bool cold_tracked = cold.valid && cold.presence >= threshold; + std::printf("cold heights=%d/%d selected=%c presence=%.6f nose_x=%.2f\n", + stage.a_height, stage.b_height, Selected(cold, cold_tracked, stage), + cold.presence, cold.image_xy[0]); + for (int repeat = 0; repeat < sequence::kFramesPerStage; ++repeat) { + ++frame; + if (argc == 4) { + std::ofstream ppm(std::string(argv[3]) + "/frame-" + + std::to_string(frame) + ".ppm", std::ios::binary); + ppm << "P6\n640 480\n255\n"; + ppm.write(reinterpret_cast(rgb.data()), rgb.size()); + if (!ppm) { + std::fprintf(stderr, "Cannot write frame %u\n", frame); + return 1; + } + } + const bool was_locked = have_lock; + const auto pose = have_lock + ? estimator.run(rgb.data(), sequence::kWidth, sequence::kHeight, roi) + : estimator.acquire(rgb.data(), sequence::kWidth, sequence::kHeight); + const bool tracked = pose.valid && pose.presence >= threshold; + const char person = Selected(pose, tracked, stage); + const bool loss = was_locked && !tracked; + const bool reacquired = frame > 1 && !was_locked && tracked; + const bool switched = (person == 'A' || person == 'B') && + (last_person == 'A' || last_person == 'B') && + person != last_person; + losses += loss; + reacquisitions += reacquired; + switches += switched; + tracked_frames += tracked; + std::printf("frame=%02u heights=%d/%d mode=%s skeletons=%d selected=%c " + "presence=%.6f nose_x=%.2f hip_x=%.2f loss=%d reacquire=%d switch=%d\n", + frame, stage.a_height, stage.b_height, was_locked ? "run" : "acquire", + tracked ? 1 : 0, person, pose.presence, pose.image_xy[0], + (pose.image_xy[46] + pose.image_xy[48]) * 0.5f, + loss, reacquired, switched); + have_lock = tracked; + if (tracked) roi = pose.next_roi; + if (person == 'A' || person == 'B') last_person = person; + } + } + std::printf("SUMMARY frames=%u tracked_frames=%u losses=%u reacquisitions=%u " + "identity_switches=%u; output capacity=one pose (no real 2P)\n", + frame, tracked_frames, losses, reacquisitions, switches); + return 0; +} diff --git a/tracker-native/src/win_main.cpp b/tracker-native/src/win_main.cpp index ecfb6d7..310cdff 100644 --- a/tracker-native/src/win_main.cpp +++ b/tracker-native/src/win_main.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -13,6 +14,7 @@ #include #include +#include "calibration/calibration.h" #include "frame_pipeline.h" #include "pose_estimator.h" #include "shm_publisher.h" @@ -27,6 +29,7 @@ constexpr int kIdDevice = 1001; constexpr int kIdResolution = 1002; constexpr int kIdStart = 1003; constexpr int kIdStatus = 1004; +constexpr int kIdCalibrate = 1005; constexpr wchar_t kShmName[] = L"kinect_virtual_frames"; constexpr wchar_t kModelName[] = L"pose_landmarks_detector.onnx"; @@ -35,6 +38,7 @@ struct App { HWND device_combo = nullptr; HWND res_combo = nullptr; HWND start_btn = nullptr; + HWND calibrate_btn = nullptr; HWND status = nullptr; std::vector devices; @@ -54,6 +58,12 @@ struct App { int test_w = 0; int test_h = 0; std::string status_text = "Idle"; + + // Cursor-reach calibration: while cal_active, the worker samples the live + // post-L/R-swap arm reach into cal_samples for derive_arm_gains. + std::atomic cal_active{false}; + std::mutex cal_mutex; + std::vector cal_samples; }; App g_app; @@ -81,6 +91,37 @@ bool LoadLastSelection(std::string& device_name, int& width, int& height) { !device_name.empty(); } +// Read a wide environment variable as a UTF-8 narrow string (empty = unset). +std::string EnvNarrow(const wchar_t* name) { + wchar_t buffer[1024]; + const DWORD n = GetEnvironmentVariableW(name, buffer, 1024); + if (n == 0 || n >= 1024) return std::string(); + const int len = WideCharToMultiByte(CP_UTF8, 0, buffer, static_cast(n), + nullptr, 0, nullptr, nullptr); + std::string out(static_cast(len), '\0'); + WideCharToMultiByte(CP_UTF8, 0, buffer, static_cast(n), out.data(), len, + nullptr, nullptr); + return out; +} + +// Canonical calibration config path, shared byte-for-byte with the shim reader. +std::string CalibrationConfigPath() { + const std::string override_path = EnvNarrow(L"KINECT_SHIM_CONFIG"); + const std::string local_app_data = EnvNarrow(L"LOCALAPPDATA"); + return nui::calibration::calibration_config_path( + override_path.empty() ? nullptr : override_path.c_str(), + local_app_data.empty() ? nullptr : local_app_data.c_str()); +} + +// Create the config file's parent directory (e.g. %LOCALAPPDATA%\VirtualKinect) +// before writing; its own parent always exists. +void EnsureParentDir(const std::string& path) { + const size_t slash = path.find_last_of("\\/"); + if (slash != std::string::npos) { + CreateDirectoryA(path.substr(0, slash).c_str(), nullptr); + } +} + std::string ModelPath() { const std::wstring dir = ExeDir(); const wchar_t* candidates[] = {L"\\", L"\\models\\"}; @@ -245,6 +286,17 @@ void WorkerLoop(bool image_mode, std::wstring symlink, int req_w, int req_h) { PipelineConfig cfg; FramePipeline pipeline(g_app.shm_base, cfg); + // A second mapper, configured identically to the pipeline's, lets the cursor + // calibration measure the live arm reach in the same skeleton space the shim + // amplifies (pipeline's own mapped skeleton is internal and not returned). + nui::mapping::MappingConfig cal_mapping_cfg; + cal_mapping_cfg.depth_width = static_cast(cfg.depth_width); + cal_mapping_cfg.depth_height = static_cast(cfg.depth_height); + cal_mapping_cfg.z0_meters = 2.5f; + cal_mapping_cfg.depth_gain = 1.0f; + cal_mapping_cfg.mirror = false; + nui::mapping::SkeletonMapper cal_mapper(cal_mapping_cfg); + Roi roi{}; bool have_lock = false; std::vector bgra; @@ -348,6 +400,30 @@ void WorkerLoop(bool image_mode, std::wstring symlink, int req_w, int req_h) { frame_number, w, h, pose.presence, tracked ? 1 : 0); } + if (tracked && g_app.cal_active.load()) { + std::array + landmarks{}; + for (size_t i = 0; i < nui::mapping::kMediaPipeLandmarkCount; ++i) { + landmarks[i].u = pose.image_xy[i * 2] / static_cast(w); + landmarks[i].v = pose.image_xy[i * 2 + 1] / static_cast(h); + landmarks[i].visibility = pose.visibility[i]; + landmarks[i].world_z = pose.world_z[i]; + } + const auto skeleton = cal_mapper.map(landmarks); + // Shim post-L/R-swap HAND_RIGHT = source HAND_LEFT (NUI idx 7); pivot + // SHOULDER_RIGHT = source SHOULDER_LEFT (NUI idx 4). The source mirror + // already routed the player's right arm into the left joints. + const auto& hand = skeleton.joints[7].position; + const auto& shoulder = skeleton.joints[4].position; + nui::calibration::RaiseRightArmObservation obs; + obs.person_detected = true; + obs.measured_reach_x = hand.x - shoulder.x; + obs.measured_reach_y = hand.y - shoulder.y; + std::lock_guard lock(g_app.cal_mutex); + g_app.cal_samples.push_back(obs); + } + std::vector overlay = bgra; if (tracked) DrawOverlay(overlay, w, h, pose); { @@ -482,6 +558,50 @@ void StopCapture() { SetStatus("Stopped"); } +// Run a short raised-arm hold, derive camera-specific cursor gains from it, and +// write them to the shared config the shim reads. Runs on a detached thread so +// the hold does not block the UI message loop. +void CalibrateCursor() { + if (!g_app.running) { + SetStatus("Start capture first, then raise your right arm to calibrate"); + return; + } + { + std::lock_guard lock(g_app.cal_mutex); + g_app.cal_samples.clear(); + } + g_app.cal_active = true; + SetStatus("Calibrating cursor: hold your right arm fully extended..."); + std::thread([] { + std::this_thread::sleep_for(std::chrono::milliseconds(1800)); + g_app.cal_active = false; + std::vector samples; + { + std::lock_guard lock(g_app.cal_mutex); + samples.swap(g_app.cal_samples); + } + nui::calibration::ArmGains gains; + std::string error; + if (!nui::calibration::derive_arm_gains(samples, gains, error)) { + SetStatus("Calibration failed: " + error); + return; + } + const std::string path = CalibrationConfigPath(); + nui::calibration::CalibrationConfig config; + std::string io_error; + nui::calibration::load_config(path, config, io_error); + config.arm_gain_x = gains.x; + config.arm_gain_y = gains.y; + EnsureParentDir(path); + if (nui::calibration::save_config(config, path, io_error)) { + SetStatus("Calibrated cursor gains X=" + std::to_string(gains.x) + + " Y=" + std::to_string(gains.y) + " (saved)"); + } else { + SetStatus("Calibration save failed: " + io_error); + } + }).detach(); +} + void PaintPreview(HWND hwnd, HDC hdc) { RECT rc; GetClientRect(hwnd, &rc); @@ -554,8 +674,13 @@ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { g_app.start_btn = CreateWindowA("BUTTON", "Start", WS_CHILD | WS_VISIBLE, 434, 8, 70, 26, hwnd, reinterpret_cast(kIdStart), inst, nullptr); + g_app.calibrate_btn = CreateWindowA("BUTTON", "Calibrate cursor", + WS_CHILD | WS_VISIBLE, 512, 8, 130, 26, + hwnd, + reinterpret_cast(kIdCalibrate), + inst, nullptr); g_app.status = CreateWindowA("STATIC", "Idle", WS_CHILD | WS_VISIBLE, - 512, 12, 300, 20, hwnd, + 650, 12, 300, 20, hwnd, reinterpret_cast(kIdStatus), inst, nullptr); g_app.devices = enumerate_cameras(); TraceLog("enumerated %zu camera(s)", g_app.devices.size()); @@ -609,6 +734,8 @@ LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { } else { StartCapture(); } + } else if (id == kIdCalibrate && code == BN_CLICKED) { + CalibrateCursor(); } return 0; } diff --git a/tracker-native/testdata/two_person_sequence.h b/tracker-native/testdata/two_person_sequence.h new file mode 100644 index 0000000..7f81391 --- /dev/null +++ b/tracker-native/testdata/two_person_sequence.h @@ -0,0 +1,55 @@ +#ifndef TWO_PERSON_SEQUENCE_H +#define TWO_PERSON_SEQUENCE_H + +#include +#include +#include + +// Deterministic 640x480 RGB sequence from two copies of the repository's +// sample_rgb.bin portrait (A, left; B, right). Integer nearest-neighbour +// sampling, no randomness or external image downloads. Synthetic subjects, +// not a recording of two independent moving people. +namespace two_person_sequence { +constexpr int kWidth = 640; +constexpr int kHeight = 480; +constexpr int kFramesPerStage = 4; +struct Stage { + int a_height; + int b_height; +}; +constexpr Stage kStages[] = { + {360, 140}, {330, 220}, {220, 330}, {140, 360}, + {60, 380}, {360, 120}}; + +struct Image { + int width; + int height; + std::vector rgb; +}; + +inline std::vector compose(const Image& a, const Image& b, + const Stage& stage) { + std::vector rgb(kWidth * kHeight * 3, 32); + const Image* images[] = {&a, &b}; + const int heights[] = {stage.a_height, stage.b_height}; + const int centers[] = {160, 480}; + for (int person = 0; person < 2; ++person) { + const Image& source = *images[person]; + const int height = heights[person]; + const int width = source.width * height / source.height; + const int left = centers[person] - width / 2; + const int top = 460 - height; + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + const int sx = x * source.width / width; + const int sy = y * source.height / height; + const auto src = (static_cast(sy) * source.width + sx) * 3; + const auto dst = (static_cast(top + y) * kWidth + left + x) * 3; + std::copy_n(source.rgb.data() + src, 3, rgb.data() + dst); + } + } + } + return rgb; +} +} +#endif