883 lines
30 KiB
C++
883 lines
30 KiB
C++
#include "sensor.h"
|
|
|
|
#include <timeapi.h>
|
|
|
|
#include "shim_log.h"
|
|
|
|
#include <algorithm>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <string>
|
|
|
|
namespace nui_shim {
|
|
namespace {
|
|
|
|
constexpr wchar_t kDefaultMappingName[] = L"kinect_virtual_frames";
|
|
constexpr DWORD kPlayerIndexMask = 0x7u;
|
|
|
|
VirtualKinectSensor* g_sensor = nullptr;
|
|
CRITICAL_SECTION g_sensor_lock;
|
|
INIT_ONCE g_sensor_lock_once = INIT_ONCE_STATIC_INIT;
|
|
|
|
// --- Diagnostic: read the game's own display-manager state directly. ---
|
|
// The shim is loaded in gamekdm.dll's process, so it can inspect the game's
|
|
// hid::Natal display manager to see why the camera panels never populate.
|
|
// Decompile facts (image base 0x10000000):
|
|
// *(gamekdm+0x3cf1b4) = manager (hid::Natal) pointer
|
|
// manager[0x00] = NuiThread object pointer
|
|
// manager[0x0c] = committed display-stream mask
|
|
// manager[0x10] = desired display-stream mask (bit 0x4=depth, 0x2=color)
|
|
// manager[0x14] = per-stream skip flags
|
|
// manager[0x16c0]= depth display-enable byte (set when armed -> LockRect runs)
|
|
// manager[0x1740]= color display-enable byte
|
|
// NuiThread[0x28] = status (3=no sensor, 7=ready)
|
|
// NuiThread[0x1598] = buffered depth frame ptr, +0x159c = color frame ptr
|
|
bool SafeReadU32(uintptr_t addr, uint32_t* out) {
|
|
if (addr == 0 || IsBadReadPtr(reinterpret_cast<const void*>(addr), 4)) {
|
|
return false;
|
|
}
|
|
*out = *reinterpret_cast<const volatile uint32_t*>(addr);
|
|
return true;
|
|
}
|
|
|
|
void DumpGameDisplayState() {
|
|
HMODULE mod = GetModuleHandleA("gamekdm.dll");
|
|
if (mod == nullptr) {
|
|
ShimLog("game-introspect: gamekdm.dll not loaded");
|
|
return;
|
|
}
|
|
const uintptr_t base = reinterpret_cast<uintptr_t>(mod);
|
|
uint32_t mgr = 0;
|
|
if (!SafeReadU32(base + 0x3cf1b4u, &mgr) || mgr == 0) {
|
|
ShimLog("game-introspect: mgr ptr null/unreadable (base=0x%08X raw=0x%08X)",
|
|
static_cast<uint32_t>(base), mgr);
|
|
return;
|
|
}
|
|
uint32_t nui = 0, committed = 0, mask = 0, flags = 0;
|
|
uint32_t en_depth = 0, en_color = 0, fp0 = 0, fp1 = 0, nui_status = 0;
|
|
SafeReadU32(mgr + 0x00u, &nui);
|
|
SafeReadU32(mgr + 0x0cu, &committed);
|
|
SafeReadU32(mgr + 0x10u, &mask);
|
|
SafeReadU32(mgr + 0x14u, &flags);
|
|
SafeReadU32(mgr + 0x16c0u, &en_depth);
|
|
SafeReadU32(mgr + 0x1740u, &en_color);
|
|
if (nui != 0) {
|
|
SafeReadU32(nui + 0x1598u, &fp0);
|
|
SafeReadU32(nui + 0x159cu, &fp1);
|
|
SafeReadU32(nui + 0x28u, &nui_status);
|
|
}
|
|
// Per-frame dedupe state: FUN_100125d0 skips LockRect when the copied frame's
|
|
// dwFrameNumber (fp+0x8) equals the display struct's last-processed value
|
|
// (manager + 0x1698 + idx*0x80 + 0x20). Also read pFrameTexture (fp+0x14).
|
|
uint32_t d_num = 0, d_tex = 0, c_num = 0, c_tex = 0, dedupe_d = 0, dedupe_c = 0;
|
|
if (fp0 != 0) {
|
|
SafeReadU32(fp0 + 0x08u, &d_num);
|
|
SafeReadU32(fp0 + 0x14u, &d_tex);
|
|
}
|
|
if (fp1 != 0) {
|
|
SafeReadU32(fp1 + 0x08u, &c_num);
|
|
SafeReadU32(fp1 + 0x14u, &c_tex);
|
|
}
|
|
SafeReadU32(mgr + 0x16b8u, &dedupe_d); // depth struct +0x20
|
|
SafeReadU32(mgr + 0x1738u, &dedupe_c); // color struct +0x20
|
|
ShimLog("game-introspect: mgr=0x%08X nui=0x%08X mask(+10)=0x%X committed(+c)=0x%X "
|
|
"flags(+14)=0x%X enDepth(+16c0)=0x%02X enColor(+1740)=0x%02X "
|
|
"fp0(+1598)=0x%08X fp1=0x%08X nuiStatus(+28)=%u | "
|
|
"depth[num=%u tex=0x%08X last=%u] color[num=%u tex=0x%08X last=%u]",
|
|
mgr, nui, mask, committed, flags, en_depth & 0xFFu, en_color & 0xFFu,
|
|
fp0, fp1, nui_status, d_num, d_tex, dedupe_d, c_num, c_tex, dedupe_c);
|
|
|
|
// Skeleton-selection introspection: the game's orientation-validation
|
|
// (gamekdm FUN_10018570) reads a reference direction at mgr+0x20 and a gravity
|
|
// vector at mgr+0x2c; the picker writes the chosen tracked IDs to mgr+0x1684/
|
|
// 0x1688. Logging the live values lets us reproduce the validation exactly.
|
|
uint32_t ref0 = 0, ref1 = 0, ref2 = 0, grav0 = 0, grav1 = 0, grav2 = 0;
|
|
uint32_t sel0 = 0, sel1 = 0, mode = 0, r20sel = 0;
|
|
SafeReadU32(mgr + 0x20u, &ref0);
|
|
SafeReadU32(mgr + 0x24u, &ref1);
|
|
SafeReadU32(mgr + 0x28u, &ref2);
|
|
SafeReadU32(mgr + 0x2cu, &grav0);
|
|
SafeReadU32(mgr + 0x30u, &grav1);
|
|
SafeReadU32(mgr + 0x34u, &grav2);
|
|
SafeReadU32(mgr + 0x1684u, &sel0);
|
|
SafeReadU32(mgr + 0x1688u, &sel1);
|
|
SafeReadU32(mgr + 0x17f4u, &mode);
|
|
SafeReadU32(mgr + 0x15f0u, &r20sel); // the sensor-side copy fed to SetTrackedSkeletons
|
|
auto asf = [](uint32_t u) {
|
|
float v;
|
|
std::memcpy(&v, &u, sizeof(v));
|
|
return v;
|
|
};
|
|
ShimLog("game-skel: ref(+20)=(%.3f,%.3f,%.3f) grav(+2c)=(%.3f,%.3f,%.3f) "
|
|
"selIDs(+1684)=[%u,%u] fedID(+15f0)=%u mode(+17f4)=%u",
|
|
asf(ref0), asf(ref1), asf(ref2), asf(grav0), asf(grav1), asf(grav2),
|
|
sel0, sel1, r20sel, mode & 0xFFu);
|
|
|
|
// Transform matrix (gamekdm DAT_103d4a80) diagonal + the 6 candidate
|
|
// validity flags/IDs (DAT_103e29cc, stride 0x20; flag byte at +0, id float at
|
|
// -4) so we can see live whether the filter validates our candidate and
|
|
// whether the matrix is identity.
|
|
uint32_t m0 = 0, m5 = 0, m10 = 0, m3 = 0, m7 = 0, m11 = 0;
|
|
SafeReadU32(base + 0x3d4a80u + 0x00u, &m0);
|
|
SafeReadU32(base + 0x3d4a80u + 0x14u, &m5);
|
|
SafeReadU32(base + 0x3d4a80u + 0x28u, &m10);
|
|
SafeReadU32(base + 0x3d4a80u + 0x0cu, &m3);
|
|
SafeReadU32(base + 0x3d4a80u + 0x1cu, &m7);
|
|
SafeReadU32(base + 0x3d4a80u + 0x2cu, &m11);
|
|
char cand[160];
|
|
int off = 0;
|
|
for (uint32_t i = 0; i < 6; ++i) {
|
|
uint32_t flag = 0, idf = 0;
|
|
SafeReadU32(base + 0x3e29ccu + i * 0x20u, &flag);
|
|
SafeReadU32(base + 0x3e29ccu + i * 0x20u - 4u, &idf);
|
|
off += _snprintf(cand + off, sizeof(cand) - off, "[%u v=%u id=%.0f]",
|
|
i, flag & 0xFFu, asf(idf));
|
|
if (off >= static_cast<int>(sizeof(cand)) - 24) break;
|
|
}
|
|
ShimLog("game-skel2: Mdiag=(%.3f,%.3f,%.3f) Mtrans=(%.3f,%.3f,%.3f) cand=%s",
|
|
asf(m0), asf(m5), asf(m10), asf(m3), asf(m7), asf(m11), cand);
|
|
|
|
// Reference stage points the filter/picker compare against (DAT_103d3248/
|
|
// 3254/3260), so we can compute offline the distance our transformed hip
|
|
// must satisfy.
|
|
uint32_t a0 = 0, a1 = 0, a2 = 0, b0 = 0, b1 = 0, b2 = 0, c0 = 0, c1 = 0, c2 = 0;
|
|
SafeReadU32(base + 0x3d3248u, &a0);
|
|
SafeReadU32(base + 0x3d324cu, &a1);
|
|
SafeReadU32(base + 0x3d3250u, &a2);
|
|
SafeReadU32(base + 0x3d3254u, &b0);
|
|
SafeReadU32(base + 0x3d3258u, &b1);
|
|
SafeReadU32(base + 0x3d325cu, &b2);
|
|
SafeReadU32(base + 0x3d3260u, &c0);
|
|
SafeReadU32(base + 0x3d3264u, &c1);
|
|
SafeReadU32(base + 0x3d3268u, &c2);
|
|
ShimLog("game-skel3: R48=(%.3f,%.3f,%.3f) R54=(%.3f,%.3f,%.3f) R60=(%.3f,%.3f,%.3f)",
|
|
asf(a0), asf(a1), asf(a2), asf(b0), asf(b1), asf(b2), asf(c0), asf(c1),
|
|
asf(c2));
|
|
}
|
|
|
|
BOOL CALLBACK InitSensorLock(PINIT_ONCE, PVOID, PVOID*) {
|
|
InitializeCriticalSection(&g_sensor_lock);
|
|
return TRUE;
|
|
}
|
|
|
|
CRITICAL_SECTION& SensorLock() {
|
|
InitOnceExecuteOnce(&g_sensor_lock_once, InitSensorLock, nullptr, nullptr);
|
|
return g_sensor_lock;
|
|
}
|
|
|
|
std::wstring MappingName() {
|
|
wchar_t buffer[256];
|
|
DWORD n = GetEnvironmentVariableW(L"KINECT_SHIM_SHM", buffer, 256);
|
|
if (n > 0 && n < 256) {
|
|
return std::wstring(buffer, n);
|
|
}
|
|
return std::wstring(kDefaultMappingName);
|
|
}
|
|
|
|
std::vector<uint16_t> ResizeDepthNearest(const std::vector<uint16_t>& src,
|
|
uint32_t sw,
|
|
uint32_t sh,
|
|
uint32_t dw,
|
|
uint32_t dh) {
|
|
std::vector<uint16_t> out(static_cast<std::size_t>(dw) * dh, 0);
|
|
if (sw == 0 || sh == 0 || dw == 0 || dh == 0 ||
|
|
src.size() != static_cast<std::size_t>(sw) * sh) {
|
|
return out;
|
|
}
|
|
for (uint32_t y = 0; y < dh; ++y) {
|
|
const uint32_t sy = std::min(static_cast<uint32_t>(
|
|
static_cast<uint64_t>(y) * sh / dh),
|
|
sh - 1);
|
|
for (uint32_t x = 0; x < dw; ++x) {
|
|
const uint32_t sx = std::min(static_cast<uint32_t>(
|
|
static_cast<uint64_t>(x) * sw / dw),
|
|
sw - 1);
|
|
out[static_cast<std::size_t>(y) * dw + x] =
|
|
src[static_cast<std::size_t>(sy) * sw + sx];
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
NUI_SKELETON_POSITION_TRACKING_STATE MapJointState(
|
|
contract::JointTrackingState s) {
|
|
switch (s) {
|
|
case contract::JointTrackingState::TRACKED:
|
|
return NUI_SKELETON_POSITION_TRACKED;
|
|
case contract::JointTrackingState::INFERRED:
|
|
return NUI_SKELETON_POSITION_INFERRED;
|
|
case contract::JointTrackingState::NOT_TRACKED:
|
|
return NUI_SKELETON_POSITION_NOT_TRACKED;
|
|
}
|
|
return NUI_SKELETON_POSITION_NOT_TRACKED;
|
|
}
|
|
|
|
}
|
|
|
|
bool resolution_to_size(NUI_IMAGE_RESOLUTION resolution,
|
|
uint32_t& width,
|
|
uint32_t& height) {
|
|
switch (resolution) {
|
|
case NUI_IMAGE_RESOLUTION_80x60:
|
|
width = 80;
|
|
height = 60;
|
|
return true;
|
|
case NUI_IMAGE_RESOLUTION_320x240:
|
|
width = 320;
|
|
height = 240;
|
|
return true;
|
|
case NUI_IMAGE_RESOLUTION_640x480:
|
|
width = 640;
|
|
height = 480;
|
|
return true;
|
|
case NUI_IMAGE_RESOLUTION_1280x960:
|
|
width = 1280;
|
|
height = 960;
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
VirtualKinectSensor::VirtualKinectSensor() {
|
|
InitializeCriticalSection(&lock_);
|
|
}
|
|
|
|
VirtualKinectSensor::~VirtualKinectSensor() {
|
|
Shutdown();
|
|
DeleteCriticalSection(&lock_);
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::Initialize(DWORD dwFlags) {
|
|
if (initialized_) {
|
|
return E_NUI_ALREADY_INITIALIZED;
|
|
}
|
|
init_flags_ = dwFlags;
|
|
std::wstring name = MappingName();
|
|
bool opened = source_.open(name.c_str());
|
|
DWORD err = opened ? 0u : GetLastError();
|
|
if (!opened) {
|
|
std::wstring global = L"Global\\" + name;
|
|
opened = source_.open(global.c_str());
|
|
ShimLog("NuiInitialize flags=0x%08X shm='%ls' local-open=0 (err=%lu) global-open=%d (err=%lu)",
|
|
dwFlags, name.c_str(), err, opened ? 1 : 0,
|
|
opened ? 0u : GetLastError());
|
|
} else {
|
|
ShimLog("NuiInitialize flags=0x%08X shm='%ls' local-open=1", dwFlags,
|
|
name.c_str());
|
|
}
|
|
|
|
stop_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
|
skeleton_ready_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
|
initialized_ = true;
|
|
|
|
producer_thread_ =
|
|
CreateThread(nullptr, 0, &VirtualKinectSensor::ProducerThunk, this, 0,
|
|
nullptr);
|
|
if (producer_thread_ == nullptr) {
|
|
initialized_ = false;
|
|
return E_FAIL;
|
|
}
|
|
return S_OK;
|
|
}
|
|
|
|
void VirtualKinectSensor::Shutdown() {
|
|
if (!initialized_) {
|
|
return;
|
|
}
|
|
ShimLog("NuiShutdown called");
|
|
initialized_ = false;
|
|
if (stop_event_ != nullptr) {
|
|
SetEvent(stop_event_);
|
|
}
|
|
if (producer_thread_ != nullptr) {
|
|
WaitForSingleObject(producer_thread_, 2000);
|
|
CloseHandle(producer_thread_);
|
|
producer_thread_ = nullptr;
|
|
}
|
|
|
|
EnterCriticalSection(&lock_);
|
|
for (auto& stream : streams_) {
|
|
for (auto* texture : stream.ring) {
|
|
if (texture != nullptr) {
|
|
texture->Release();
|
|
}
|
|
}
|
|
stream = ImageStream{};
|
|
}
|
|
skeleton_enabled_ = false;
|
|
has_skeleton_ = false;
|
|
frame_end_event_ = nullptr;
|
|
LeaveCriticalSection(&lock_);
|
|
|
|
source_.close();
|
|
if (stop_event_ != nullptr) {
|
|
CloseHandle(stop_event_);
|
|
stop_event_ = nullptr;
|
|
}
|
|
if (skeleton_ready_event_ != nullptr) {
|
|
CloseHandle(skeleton_ready_event_);
|
|
skeleton_ready_event_ = nullptr;
|
|
}
|
|
}
|
|
|
|
DWORD VirtualKinectSensor::InitializationFlags() const { return init_flags_; }
|
|
|
|
HRESULT VirtualKinectSensor::Status() const {
|
|
return initialized_ ? S_OK : E_NUI_DEVICE_NOT_READY;
|
|
}
|
|
|
|
void VirtualKinectSensor::SetFrameEndEvent(HANDLE hEvent, DWORD dwFrameEventFlag) {
|
|
EnterCriticalSection(&lock_);
|
|
frame_end_event_ = hEvent;
|
|
LeaveCriticalSection(&lock_);
|
|
ShimLog("NuiSetFrameEndEvent event=%p flag=0x%08X", hEvent, dwFrameEventFlag);
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::SkeletonTrackingEnable(HANDLE hNextFrameEvent,
|
|
DWORD dwFlags) {
|
|
EnterCriticalSection(&lock_);
|
|
skeleton_enabled_ = true;
|
|
skeleton_flags_ = dwFlags;
|
|
skeleton_app_event_ = hNextFrameEvent;
|
|
LeaveCriticalSection(&lock_);
|
|
ShimLog("SkeletonTrackingEnable flags=0x%08X event=%p", dwFlags,
|
|
hNextFrameEvent);
|
|
return S_OK;
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::SkeletonTrackingDisable() {
|
|
EnterCriticalSection(&lock_);
|
|
skeleton_enabled_ = false;
|
|
skeleton_app_event_ = nullptr;
|
|
LeaveCriticalSection(&lock_);
|
|
return S_OK;
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::SkeletonSetTrackedSkeletons(DWORD* pTrackingIDs) {
|
|
EnterCriticalSection(&lock_);
|
|
if (pTrackingIDs != nullptr) {
|
|
requested_tracked_ids_[0] = pTrackingIDs[0];
|
|
requested_tracked_ids_[1] = pTrackingIDs[1];
|
|
app_set_tracked_ids_ =
|
|
pTrackingIDs[0] != 0 || pTrackingIDs[1] != 0;
|
|
} else {
|
|
requested_tracked_ids_[0] = 0;
|
|
requested_tracked_ids_[1] = 0;
|
|
app_set_tracked_ids_ = false;
|
|
}
|
|
LeaveCriticalSection(&lock_);
|
|
return S_OK;
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::SkeletonGetNextFrame(
|
|
DWORD dwMillisecondsToWait,
|
|
NUI_SKELETON_FRAME* pSkeletonFrame) {
|
|
if (pSkeletonFrame == nullptr) {
|
|
return E_POINTER;
|
|
}
|
|
static unsigned skel_calls = 0;
|
|
const bool slog = skel_calls < 20u || (skel_calls % 150u) == 0u;
|
|
++skel_calls;
|
|
if (slog) {
|
|
ShimLog("SkeletonGetNextFrame ENTER enabled=%d waitMs=%lu flags=0x%X",
|
|
skeleton_enabled_ ? 1 : 0, dwMillisecondsToWait, skeleton_flags_);
|
|
}
|
|
if (!skeleton_enabled_) {
|
|
return E_NUI_STREAM_NOT_ENABLED;
|
|
}
|
|
|
|
const DWORD wait = WaitForSingleObject(skeleton_ready_event_,
|
|
dwMillisecondsToWait);
|
|
if (wait != WAIT_OBJECT_0) {
|
|
if (slog) {
|
|
ShimLog(" skeleton wait=%lu (not signalled)", wait);
|
|
}
|
|
if (skeleton_flags_ &
|
|
NUI_SKELETON_TRACKING_FLAG_TITLE_SETS_TRACKED_SKELETONS) {
|
|
return S_FALSE;
|
|
}
|
|
return E_NUI_FRAME_NO_DATA;
|
|
}
|
|
|
|
EnterCriticalSection(&lock_);
|
|
if (!has_skeleton_) {
|
|
LeaveCriticalSection(&lock_);
|
|
return E_NUI_FRAME_NO_DATA;
|
|
}
|
|
*pSkeletonFrame = latest_skeleton_;
|
|
last_delivered_skeleton_frame_ = latest_skeleton_.dwFrameNumber;
|
|
if (slog) {
|
|
ShimLog(" SkeletonGetNextFrame -> S_OK frame=%lu slot0 state=%d id=%lu",
|
|
latest_skeleton_.dwFrameNumber,
|
|
static_cast<int>(latest_skeleton_.SkeletonData[0].eTrackingState),
|
|
latest_skeleton_.SkeletonData[0].dwTrackingID);
|
|
}
|
|
ResetEvent(skeleton_ready_event_);
|
|
if (skeleton_app_event_ != nullptr) {
|
|
ResetEvent(skeleton_app_event_);
|
|
}
|
|
LeaveCriticalSection(&lock_);
|
|
return S_OK;
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::ImageStreamOpen(NUI_IMAGE_TYPE eImageType,
|
|
NUI_IMAGE_RESOLUTION eResolution,
|
|
DWORD,
|
|
DWORD dwFrameLimit,
|
|
HANDLE hNextFrameEvent,
|
|
HANDLE* phStreamHandle) {
|
|
if (phStreamHandle == nullptr) {
|
|
return E_POINTER;
|
|
}
|
|
uint32_t width = 0;
|
|
uint32_t height = 0;
|
|
if (!resolution_to_size(eResolution, width, height)) {
|
|
return E_INVALIDARG;
|
|
}
|
|
|
|
uint32_t bpp = 2;
|
|
switch (eImageType) {
|
|
case NUI_IMAGE_TYPE_COLOR:
|
|
case NUI_IMAGE_TYPE_COLOR_YUV:
|
|
case NUI_IMAGE_TYPE_COLOR_RAW_YUV:
|
|
bpp = 4;
|
|
break;
|
|
case NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX:
|
|
case NUI_IMAGE_TYPE_DEPTH:
|
|
case NUI_IMAGE_TYPE_COLOR_INFRARED:
|
|
bpp = 2;
|
|
break;
|
|
default:
|
|
return E_INVALIDARG;
|
|
}
|
|
|
|
EnterCriticalSection(&lock_);
|
|
ImageStream* slot = nullptr;
|
|
for (auto& stream : streams_) {
|
|
if (stream.open && stream.type == eImageType) {
|
|
slot = &stream;
|
|
break;
|
|
}
|
|
}
|
|
if (slot == nullptr) {
|
|
for (auto& stream : streams_) {
|
|
if (!stream.open) {
|
|
slot = &stream;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (slot == nullptr) {
|
|
LeaveCriticalSection(&lock_);
|
|
return E_NUI_DEVICE_NOT_READY;
|
|
}
|
|
|
|
for (auto* texture : slot->ring) {
|
|
if (texture != nullptr) {
|
|
texture->Release();
|
|
}
|
|
}
|
|
|
|
slot->open = true;
|
|
slot->type = eImageType;
|
|
slot->resolution = eResolution;
|
|
slot->width = width;
|
|
slot->height = height;
|
|
slot->bytes_per_pixel = bpp;
|
|
slot->app_event = hNextFrameEvent;
|
|
slot->ring_size = std::clamp<std::size_t>(
|
|
dwFrameLimit == 0 ? 2 : dwFrameLimit, 2, 4);
|
|
slot->ring.assign(slot->ring_size, nullptr);
|
|
slot->frames.assign(slot->ring_size, NUI_IMAGE_FRAME{});
|
|
for (std::size_t i = 0; i < slot->ring_size; ++i) {
|
|
slot->ring[i] = new NuiFrameTexture(width, height, bpp);
|
|
}
|
|
slot->write_index = 0;
|
|
slot->latest_index = 0;
|
|
slot->has_frame = false;
|
|
slot->outstanding = false;
|
|
|
|
*phStreamHandle = reinterpret_cast<HANDLE>(slot);
|
|
LeaveCriticalSection(&lock_);
|
|
ShimLog("ImageStreamOpen type=%d res=%d -> %ux%u bpp=%u ring=%zu event=%p",
|
|
static_cast<int>(eImageType), static_cast<int>(eResolution), width,
|
|
height, bpp, slot->ring_size, hNextFrameEvent);
|
|
return S_OK;
|
|
}
|
|
|
|
ImageStream* VirtualKinectSensor::StreamFromHandle(HANDLE hStream) {
|
|
for (auto& stream : streams_) {
|
|
if (stream.open && reinterpret_cast<HANDLE>(&stream) == hStream) {
|
|
return &stream;
|
|
}
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::ImageStreamGetNextFrame(
|
|
HANDLE hStream,
|
|
DWORD dwMillisecondsToWait,
|
|
const NUI_IMAGE_FRAME** ppcImageFrame) {
|
|
if (ppcImageFrame == nullptr) {
|
|
return E_POINTER;
|
|
}
|
|
ImageStream* stream = nullptr;
|
|
HANDLE app_event = nullptr;
|
|
int stype = -1;
|
|
EnterCriticalSection(&lock_);
|
|
stream = StreamFromHandle(hStream);
|
|
if (stream != nullptr) {
|
|
app_event = stream->app_event;
|
|
stype = static_cast<int>(stream->type);
|
|
}
|
|
LeaveCriticalSection(&lock_);
|
|
|
|
static unsigned gnf_calls[8] = {0};
|
|
const int log_idx = (stype >= 0 && stype < 7) ? stype : 7;
|
|
const bool do_log = gnf_calls[log_idx] < 20u;
|
|
++gnf_calls[log_idx];
|
|
if (do_log) {
|
|
ShimLog("ImageStreamGetNextFrame ENTER type=%d handle_ok=%d app_event=%p waitMs=%lu",
|
|
stype, stream != nullptr ? 1 : 0, app_event, dwMillisecondsToWait);
|
|
}
|
|
|
|
if (stream == nullptr) {
|
|
return E_INVALIDARG;
|
|
}
|
|
|
|
if (app_event != nullptr) {
|
|
const DWORD wait = WaitForSingleObject(app_event, dwMillisecondsToWait);
|
|
if (wait != WAIT_OBJECT_0) {
|
|
if (do_log) {
|
|
ShimLog(" type=%d event wait=%lu (not signalled) => NO_DATA", stype,
|
|
wait);
|
|
}
|
|
return E_NUI_FRAME_NO_DATA;
|
|
}
|
|
}
|
|
|
|
EnterCriticalSection(&lock_);
|
|
const bool has = stream->has_frame;
|
|
const uint32_t frame_no =
|
|
has ? stream->frames[stream->latest_index].dwFrameNumber : 0u;
|
|
const bool is_new = has && frame_no != stream->last_delivered_frame_number;
|
|
if (is_new) {
|
|
stream->last_delivered_frame_number = frame_no;
|
|
stream->outstanding = true;
|
|
// DEA's HidNatalNuiThread uses a by-VALUE NUI_IMAGE_FRAME ABI, not the
|
|
// standard "runtime returns a pointer" one. Verified from gamekdm.dll
|
|
// disasm: NuiThread::updateStream (FUN_1000f400) passes the address of a
|
|
// 40-byte (sizeof NUI_IMAGE_FRAME) buffer at this+0xad8 as ppcImageFrame
|
|
// and stores that same address as its outstanding-frame marker;
|
|
// NuiThread::updateFrame (FUN_1000f0a0) then copies 0x28 bytes straight
|
|
// from that buffer (single deref) into the display slot and the renderer
|
|
// reads pFrameTexture/dwFrameNumber from it. Writing only a 4-byte pointer
|
|
// here left dwFrameNumber/pFrameTexture zero, so the game never locked a
|
|
// texture (no picture). Copy the frame struct into the caller's buffer.
|
|
std::memcpy(reinterpret_cast<void*>(ppcImageFrame),
|
|
&stream->frames[stream->latest_index],
|
|
sizeof(NUI_IMAGE_FRAME));
|
|
}
|
|
LeaveCriticalSection(&lock_);
|
|
|
|
if (do_log) {
|
|
ShimLog(" type=%d has=%d new=%d frame=%u => %s", stype, has ? 1 : 0,
|
|
is_new ? 1 : 0, frame_no, is_new ? "S_OK" : "NO_DATA");
|
|
}
|
|
if (!is_new) {
|
|
return E_NUI_FRAME_NO_DATA;
|
|
}
|
|
// Edge-trigger the stream event: the game waits on these with
|
|
// WaitForMultipleObjects(bWaitAll=FALSE), which returns the lowest signalled
|
|
// index; if the depth event stays signalled it starves color/skeleton/
|
|
// frame-end. Reset on consume so WFMO advances to the next stream.
|
|
if (app_event != nullptr) {
|
|
ResetEvent(app_event);
|
|
}
|
|
static unsigned img_delivered = 0;
|
|
if (img_delivered < 6 || (img_delivered % 150u) == 0u) {
|
|
ShimLog("ImageStreamGetNextFrame delivered#%u type=%d frame=%u",
|
|
img_delivered, stype, frame_no);
|
|
}
|
|
++img_delivered;
|
|
return S_OK;
|
|
}
|
|
|
|
HRESULT VirtualKinectSensor::ImageStreamReleaseFrame(
|
|
HANDLE hStream,
|
|
const NUI_IMAGE_FRAME* pImageFrame) {
|
|
if (pImageFrame == nullptr) {
|
|
return E_INVALIDARG;
|
|
}
|
|
EnterCriticalSection(&lock_);
|
|
ImageStream* stream = StreamFromHandle(hStream);
|
|
if (stream == nullptr) {
|
|
LeaveCriticalSection(&lock_);
|
|
return E_INVALIDARG;
|
|
}
|
|
if (pImageFrame->pFrameTexture == nullptr) {
|
|
LeaveCriticalSection(&lock_);
|
|
return E_NOINTERFACE;
|
|
}
|
|
stream->outstanding = false;
|
|
const int stype = static_cast<int>(stream->type);
|
|
LeaveCriticalSection(&lock_);
|
|
static unsigned rel = 0;
|
|
if (rel < 6) {
|
|
ShimLog("ImageStreamReleaseFrame#%u type=%d", rel, stype);
|
|
}
|
|
++rel;
|
|
return S_OK;
|
|
}
|
|
|
|
void VirtualKinectSensor::BuildSkeletonFrame(const SourceFrame& src) {
|
|
NUI_SKELETON_FRAME frame{};
|
|
LARGE_INTEGER ts;
|
|
ts.QuadPart = src.meta.timestamp_micros / 1000;
|
|
frame.liTimeStamp = ts;
|
|
frame.dwFrameNumber = src.meta.frame_number;
|
|
frame.dwFlags = 0;
|
|
// A real Kinect always reports the floor plane (Hessian form Ax+By+Cz+D=0,
|
|
// unit up-normal, D = -sensor-height) and the up gravity normal. The game
|
|
// builds a floor/gravity-relative transform from these and validates each
|
|
// skeleton's center of mass against it; leaving them zero makes that
|
|
// transform degenerate so no skeleton is ever a selectable candidate.
|
|
frame.vFloorClipPlane = {0.0f, 1.0f, 0.0f, -1.5f};
|
|
frame.vNormalToGravity = {0.0f, 1.0f, 0.0f, 0.0f};
|
|
|
|
for (auto& data : frame.SkeletonData) {
|
|
data.eTrackingState = NUI_SKELETON_NOT_TRACKED;
|
|
data.dwTrackingID = 0;
|
|
for (auto& state : data.eSkeletonPositionTrackingState) {
|
|
state = NUI_SKELETON_POSITION_NOT_TRACKED;
|
|
}
|
|
}
|
|
|
|
if (src.has_player) {
|
|
NUI_SKELETON_DATA& data = frame.SkeletonData[0];
|
|
const DWORD id = src.meta.skeleton.skeleton_tracking_id;
|
|
data.dwTrackingID = id;
|
|
data.dwEnrollmentIndex = 0;
|
|
data.dwUserIndex = 0;
|
|
data.dwQualityFlags = src.meta.skeleton.quality_flags;
|
|
const contract::Vector4& hip =
|
|
src.meta.skeleton.joints[NUI_SKELETON_POSITION_HIP_CENTER].position;
|
|
data.Position = {hip.x, hip.y, hip.z, hip.w};
|
|
|
|
// The game derives its skeleton-validation view-transform from the joints
|
|
// whose tracking state == TRACKED, and only builds a valid (non-degenerate)
|
|
// transform when the weighted tracked-joint ratio exceeds 0.85 (gamekdm
|
|
// FUN_10018570, threshold DAT_102b9c18). MediaPipe leaves lower-body/hand
|
|
// joints below that visibility, so reporting them INFERRED keeps the ratio
|
|
// under 0.85 -> the transform is degenerate and EVERY skeleton (even a
|
|
// perfect one) is rejected, so the game selects nobody ([0,0]) and draws
|
|
// nothing. Report the whole skeleton TRACKED with every joint TRACKED so
|
|
// the ratio is 1.0 and the transform is built from our (correct) joints.
|
|
data.eTrackingState = NUI_SKELETON_TRACKED;
|
|
for (std::size_t j = 0; j < contract::kJointCount; ++j) {
|
|
const contract::JointData& joint = src.meta.skeleton.joints[j];
|
|
data.SkeletonPositions[j] = {joint.position.x, joint.position.y,
|
|
joint.position.z, joint.position.w};
|
|
data.eSkeletonPositionTrackingState[j] = NUI_SKELETON_POSITION_TRACKED;
|
|
}
|
|
}
|
|
|
|
static unsigned build_calls = 0;
|
|
if ((build_calls++ % 150u) == 0u) {
|
|
const NUI_SKELETON_DATA& d0 = frame.SkeletonData[0];
|
|
int tracked = 0, inferred = 0;
|
|
for (auto st : d0.eSkeletonPositionTrackingState) {
|
|
if (st == NUI_SKELETON_POSITION_TRACKED) ++tracked;
|
|
else if (st == NUI_SKELETON_POSITION_INFERRED) ++inferred;
|
|
}
|
|
ShimLog(
|
|
"BuildSkeleton: has_player=%d slot0 state=%d id=%lu "
|
|
"joints(tracked=%d inferred=%d) hip=(%.2f,%.2f,%.2f) "
|
|
"flags=0x%X appSet=%d reqIds=[%lu,%lu]",
|
|
src.has_player ? 1 : 0, static_cast<int>(d0.eTrackingState),
|
|
d0.dwTrackingID, tracked, inferred, d0.Position.x, d0.Position.y,
|
|
d0.Position.z, skeleton_flags_, app_set_tracked_ids_ ? 1 : 0,
|
|
requested_tracked_ids_[0], requested_tracked_ids_[1]);
|
|
}
|
|
|
|
latest_skeleton_ = frame;
|
|
has_skeleton_ = true;
|
|
}
|
|
|
|
void VirtualKinectSensor::FillStreams(const SourceFrame& src) {
|
|
for (auto& stream : streams_) {
|
|
if (!stream.open) {
|
|
continue;
|
|
}
|
|
const std::size_t next = (stream.has_frame)
|
|
? (stream.latest_index + 1) % stream.ring_size
|
|
: stream.write_index;
|
|
NuiFrameTexture* texture = stream.ring[next];
|
|
if (texture == nullptr) {
|
|
continue;
|
|
}
|
|
|
|
if (stream.type == NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX ||
|
|
stream.type == NUI_IMAGE_TYPE_DEPTH) {
|
|
std::vector<uint16_t> depth = ResizeDepthNearest(
|
|
src.depth_pixels, src.meta.depth.width, src.meta.depth.height,
|
|
stream.width, stream.height);
|
|
if (stream.type == NUI_IMAGE_TYPE_DEPTH) {
|
|
for (auto& pixel : depth) {
|
|
pixel = static_cast<uint16_t>(pixel & ~kPlayerIndexMask);
|
|
}
|
|
}
|
|
texture->set_bits(reinterpret_cast<const uint8_t*>(depth.data()),
|
|
depth.size() * sizeof(uint16_t));
|
|
} else if (stream.type == NUI_IMAGE_TYPE_COLOR_INFRARED) {
|
|
synth::BgraFrame source_color{
|
|
{src.meta.color.width, src.meta.color.height},
|
|
src.meta.color.width * 4u,
|
|
src.color_pixels};
|
|
synth::InfraredFrame ir = synth::synthesize_infrared(
|
|
source_color, {stream.width, stream.height});
|
|
texture->set_bits(reinterpret_cast<const uint8_t*>(ir.pixels.data()),
|
|
ir.pixels.size() * sizeof(uint16_t));
|
|
} else {
|
|
synth::BgraFrame source_color{
|
|
{src.meta.color.width, src.meta.color.height},
|
|
src.meta.color.width * 4u,
|
|
src.color_pixels};
|
|
synth::BgraFrame color = synth::passthrough_color(
|
|
source_color, {stream.width, stream.height});
|
|
texture->set_bits(color.pixels.data(), color.pixels.size());
|
|
}
|
|
|
|
NUI_IMAGE_FRAME& image = stream.frames[next];
|
|
LARGE_INTEGER ts;
|
|
ts.QuadPart = src.meta.timestamp_micros / 1000;
|
|
image.liTimeStamp = ts;
|
|
image.dwFrameNumber = src.meta.frame_number;
|
|
image.eImageType = stream.type;
|
|
image.eResolution = stream.resolution;
|
|
image.pFrameTexture = texture;
|
|
image.dwFrameFlags = 0;
|
|
image.ViewArea.eDigitalZoom = NUI_IMAGE_DIGITAL_ZOOM_1X;
|
|
image.ViewArea.lCenterX = 0;
|
|
image.ViewArea.lCenterY = 0;
|
|
|
|
stream.latest_index = next;
|
|
stream.write_index = (next + 1) % stream.ring_size;
|
|
stream.has_frame = true;
|
|
if (stream.app_event != nullptr) {
|
|
SetEvent(stream.app_event);
|
|
}
|
|
}
|
|
}
|
|
|
|
void VirtualKinectSensor::ProducerLoop() {
|
|
LARGE_INTEGER frequency;
|
|
LARGE_INTEGER start;
|
|
QueryPerformanceFrequency(&frequency);
|
|
QueryPerformanceCounter(&start);
|
|
uint32_t frame_number = 0;
|
|
timeBeginPeriod(1);
|
|
|
|
while (WaitForSingleObject(stop_event_, 0) != WAIT_OBJECT_0) {
|
|
LARGE_INTEGER now;
|
|
QueryPerformanceCounter(&now);
|
|
const int64_t micros =
|
|
(now.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart;
|
|
|
|
SourceFrame src;
|
|
const bool got = source_.is_open() && source_.read_latest(src);
|
|
if (frame_number < 10u || (frame_number % 60u) == 0u) {
|
|
std::size_t depth_nonzero = 0;
|
|
if (got) {
|
|
for (uint16_t p : src.depth_pixels) {
|
|
if (p != 0) {
|
|
++depth_nonzero;
|
|
}
|
|
}
|
|
}
|
|
ShimLog("producer tick=%u src_open=%d got_frame=%d has_player=%d depth_nonzero=%zu streams_open=%d skel_enabled=%d",
|
|
frame_number, source_.is_open() ? 1 : 0, got ? 1 : 0,
|
|
got && src.has_player ? 1 : 0, depth_nonzero,
|
|
std::any_of(streams_.begin(), streams_.end(),
|
|
[](const ImageStream& s) { return s.open; })
|
|
? 1
|
|
: 0,
|
|
skeleton_enabled_ ? 1 : 0);
|
|
DumpGameDisplayState();
|
|
}
|
|
if (!got) {
|
|
src = SourceFrame{};
|
|
src.has_player = false;
|
|
src.meta.depth.width = 640;
|
|
src.meta.depth.height = 480;
|
|
src.meta.color.width = 640;
|
|
src.meta.color.height = 480;
|
|
src.depth_pixels.assign(640u * 480u, 0);
|
|
src.color_pixels.assign(640u * 480u * 4u, 0);
|
|
}
|
|
++frame_number;
|
|
src.meta.frame_number = frame_number;
|
|
src.meta.timestamp_micros = micros;
|
|
|
|
EnterCriticalSection(&lock_);
|
|
if (skeleton_enabled_) {
|
|
BuildSkeletonFrame(src);
|
|
SetEvent(skeleton_ready_event_);
|
|
if (skeleton_app_event_ != nullptr) {
|
|
SetEvent(skeleton_app_event_);
|
|
}
|
|
}
|
|
FillStreams(src);
|
|
HANDLE frame_end = frame_end_event_;
|
|
LeaveCriticalSection(&lock_);
|
|
if (frame_end != nullptr) {
|
|
SetEvent(frame_end);
|
|
}
|
|
|
|
const int64_t target_qpc =
|
|
start.QuadPart +
|
|
static_cast<int64_t>(frame_number) * frequency.QuadPart / 30;
|
|
QueryPerformanceCounter(&now);
|
|
const int64_t remaining_qpc = target_qpc - now.QuadPart;
|
|
DWORD wait_ms = 0;
|
|
if (remaining_qpc > 0) {
|
|
wait_ms = static_cast<DWORD>(remaining_qpc * 1000 / frequency.QuadPart);
|
|
if (wait_ms > 100u) {
|
|
wait_ms = 100u;
|
|
}
|
|
}
|
|
WaitForSingleObject(stop_event_, wait_ms);
|
|
}
|
|
timeEndPeriod(1);
|
|
ShimLog("producer loop EXIT at tick=%u (stop_event signalled)", frame_number);
|
|
}
|
|
|
|
DWORD WINAPI VirtualKinectSensor::ProducerThunk(LPVOID param) {
|
|
static_cast<VirtualKinectSensor*>(param)->ProducerLoop();
|
|
return 0;
|
|
}
|
|
|
|
VirtualKinectSensor* GlobalSensor() { return g_sensor; }
|
|
|
|
VirtualKinectSensor* EnsureGlobalSensor() {
|
|
EnterCriticalSection(&SensorLock());
|
|
if (g_sensor == nullptr) {
|
|
g_sensor = new VirtualKinectSensor();
|
|
}
|
|
VirtualKinectSensor* sensor = g_sensor;
|
|
LeaveCriticalSection(&SensorLock());
|
|
return sensor;
|
|
}
|
|
|
|
void DestroyGlobalSensor() {
|
|
EnterCriticalSection(&SensorLock());
|
|
if (g_sensor != nullptr) {
|
|
delete g_sensor;
|
|
g_sensor = nullptr;
|
|
}
|
|
LeaveCriticalSection(&SensorLock());
|
|
}
|
|
|
|
}
|