#define WIN32_LEAN_AND_MEAN #include #include #include #include #include #include #include #include "frame_pipeline.h" #include "pose_estimator.h" #include "shm_publisher.h" #include "trace_log.h" #include "win_camera.h" using namespace kinect_tracker; namespace { constexpr int kIdDevice = 1001; constexpr int kIdResolution = 1002; constexpr int kIdStart = 1003; constexpr int kIdStatus = 1004; constexpr wchar_t kShmName[] = L"kinect_virtual_frames"; constexpr wchar_t kModelName[] = L"pose_landmarks_detector.onnx"; struct App { HWND main = nullptr; HWND device_combo = nullptr; HWND res_combo = nullptr; HWND start_btn = nullptr; HWND status = nullptr; std::vector devices; std::vector resolutions; std::thread worker; std::atomic running{false}; HANDLE mapping = nullptr; uint8_t* shm_base = nullptr; std::mutex preview_mutex; std::vector preview_bgra; int preview_w = 0; int preview_h = 0; std::string status_text = "Idle"; }; App g_app; std::wstring ExeDir() { wchar_t path[MAX_PATH]; GetModuleFileNameW(nullptr, path, MAX_PATH); std::wstring p(path); const size_t slash = p.find_last_of(L"\\/"); return slash == std::wstring::npos ? L"." : p.substr(0, slash); } std::string ModelPath() { const std::wstring dir = ExeDir(); const wchar_t* candidates[] = {L"\\", L"\\models\\"}; for (const wchar_t* mid : candidates) { std::wstring w = dir + mid + kModelName; if (GetFileAttributesW(w.c_str()) != INVALID_FILE_ATTRIBUTES) { std::string s(w.begin(), w.end()); return s; } } std::wstring w = dir + L"\\" + kModelName; return std::string(w.begin(), w.end()); } void SetStatus(const std::string& text) { { std::lock_guard lock(g_app.preview_mutex); g_app.status_text = text; } SetWindowTextA(g_app.status, text.c_str()); } void DrawOverlay(std::vector& bgra, int w, int h, const PoseResult& pose) { auto plot = [&](int x, int y, uint8_t b, uint8_t g, uint8_t r) { for (int dy = -2; dy <= 2; ++dy) { for (int dx = -2; dx <= 2; ++dx) { const int px = x + dx, py = y + dy; if (px < 0 || py < 0 || px >= w || py >= h) continue; uint8_t* p = &bgra[(static_cast(py) * w + px) * 4]; p[0] = b; p[1] = g; p[2] = r; } } }; if (!pose.image_mask.empty() && pose.image_mask_width == w && pose.image_mask_height == h) { for (size_t i = 0; i < static_cast(w) * h; ++i) { if (pose.image_mask[i] > 0.5f) { uint8_t* p = &bgra[i * 4]; p[2] = static_cast((p[2] + 255) / 2); } } } for (int i = 0; i < kBodyLandmarks; ++i) { const int x = static_cast(pose.image_xy[i * 2]); const int y = static_cast(pose.image_xy[i * 2 + 1]); if (pose.visibility[i] > 0.5f) { plot(x, y, 0, 255, 0); } else { plot(x, y, 0, 160, 255); } } } void WorkerLoop(std::wstring symlink, int req_w, int req_h) { Camera camera; if (!camera.open(symlink, req_w, req_h)) { TraceLog("WorkerLoop: camera.open(%dx%d) FAILED", req_w, req_h); SetStatus("ERROR: could not open camera"); g_app.running = false; return; } const std::string model_path = ModelPath(); TraceLog("WorkerLoop: camera open, loading model '%s'", model_path.c_str()); PoseEstimator estimator(model_path.c_str()); TraceLog("WorkerLoop: model loaded, entering capture loop"); PipelineConfig cfg; FramePipeline pipeline(g_app.shm_base, cfg); Roi roi = PoseEstimator::bootstrap_roi(req_w, req_h); std::vector bgra; std::vector rgb; int w = 0, h = 0; uint32_t frame_number = 0; const LARGE_INTEGER t0_now = [] { LARGE_INTEGER x; QueryPerformanceCounter(&x); return x; }(); LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); while (g_app.running) { if (!camera.read_frame(bgra, w, h)) { continue; } rgb.resize(static_cast(w) * h * 3); for (size_t i = 0; i < static_cast(w) * h; ++i) { rgb[i * 3 + 0] = bgra[i * 4 + 2]; rgb[i * 3 + 1] = bgra[i * 4 + 1]; rgb[i * 3 + 2] = bgra[i * 4 + 0]; } PoseResult pose = estimator.run(rgb.data(), w, h, roi); const bool tracked = pose.valid && pose.presence >= cfg.presence_threshold; roi = tracked ? pose.next_roi : PoseEstimator::bootstrap_roi(w, h); LARGE_INTEGER now; QueryPerformanceCounter(&now); const int64_t ts_us = (now.QuadPart - t0_now.QuadPart) * 1000000 / freq.QuadPart; pipeline.publish(++frame_number, ts_us, tracked ? &pose : nullptr, bgra.data(), w, h); if (frame_number <= 3 || frame_number % 150u == 0) { TraceLog("frame#%u %dx%d presence=%.3f tracked=%d", frame_number, w, h, pose.presence, tracked ? 1 : 0); } std::vector overlay = bgra; if (tracked) DrawOverlay(overlay, w, h, pose); { std::lock_guard lock(g_app.preview_mutex); g_app.preview_bgra.swap(overlay); g_app.preview_w = w; g_app.preview_h = h; g_app.status_text = tracked ? "Tracking (player detected)" : "No player detected"; } } camera.close(); } bool StartShm() { PipelineConfig cfg; const size_t region = ShmPublisher::region_size(cfg.depth_width, cfg.depth_height, cfg.color_width, cfg.color_height); g_app.mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, static_cast((region >> 32) & 0xffffffffu), static_cast(region & 0xffffffffu), kShmName); if (!g_app.mapping) { TraceLog("shm CreateFileMapping FAILED err=%lu", GetLastError()); return false; } g_app.shm_base = static_cast( MapViewOfFile(g_app.mapping, FILE_MAP_ALL_ACCESS, 0, 0, region)); TraceLog("shm '%ls' region=%zu mapped=%d", kShmName, region, g_app.shm_base ? 1 : 0); return g_app.shm_base != nullptr; } void StopShm() { if (g_app.shm_base) { UnmapViewOfFile(g_app.shm_base); g_app.shm_base = nullptr; } if (g_app.mapping) { CloseHandle(g_app.mapping); g_app.mapping = nullptr; } } void PopulateResolutions() { SendMessage(g_app.res_combo, CB_RESETCONTENT, 0, 0); const int sel = static_cast(SendMessage(g_app.device_combo, CB_GETCURSEL, 0, 0)); if (sel < 0 || sel >= static_cast(g_app.devices.size())) return; g_app.resolutions = enumerate_resolutions(g_app.devices[sel].symbolic_link); for (const auto& r : g_app.resolutions) { wchar_t buf[64]; wsprintfW(buf, L"%d x %d", r.width, r.height); SendMessageW(g_app.res_combo, CB_ADDSTRING, 0, reinterpret_cast(buf)); } if (!g_app.resolutions.empty()) SendMessage(g_app.res_combo, CB_SETCURSEL, 0, 0); } void StartCapture() { const int dsel = static_cast(SendMessage(g_app.device_combo, CB_GETCURSEL, 0, 0)); const int rsel = static_cast(SendMessage(g_app.res_combo, CB_GETCURSEL, 0, 0)); if (dsel < 0 || rsel < 0 || rsel >= static_cast(g_app.resolutions.size())) { SetStatus("Pick a camera and resolution first"); return; } if (!StartShm()) { SetStatus("ERROR: shared memory create failed"); return; } g_app.running = true; const CameraResolution res = g_app.resolutions[rsel]; TraceLog("Start: device[%d]='%s' %dx%d", dsel, g_app.devices[dsel].name.c_str(), res.width, res.height); g_app.worker = std::thread(WorkerLoop, g_app.devices[dsel].symbolic_link, res.width, res.height); SetWindowTextA(g_app.start_btn, "Stop"); SetStatus("Starting..."); } void StopCapture() { g_app.running = false; if (g_app.worker.joinable()) g_app.worker.join(); StopShm(); SetWindowTextA(g_app.start_btn, "Start"); SetStatus("Stopped"); } void PaintPreview(HWND hwnd, HDC hdc) { std::lock_guard lock(g_app.preview_mutex); if (g_app.preview_bgra.empty()) return; BITMAPINFO bmi{}; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = g_app.preview_w; bmi.bmiHeader.biHeight = -g_app.preview_h; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; RECT rc; GetClientRect(hwnd, &rc); const int top = 44; SetStretchBltMode(hdc, HALFTONE); StretchDIBits(hdc, 0, top, rc.right, rc.bottom - top, 0, 0, g_app.preview_w, g_app.preview_h, g_app.preview_bgra.data(), &bmi, DIB_RGB_COLORS, SRCCOPY); } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_CREATE: { HINSTANCE inst = reinterpret_cast(lparam)->hInstance; g_app.device_combo = CreateWindowW(L"COMBOBOX", nullptr, WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST, 8, 8, 260, 300, hwnd, reinterpret_cast(kIdDevice), inst, nullptr); g_app.res_combo = CreateWindowW(L"COMBOBOX", nullptr, WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST, 276, 8, 150, 300, hwnd, reinterpret_cast(kIdResolution), inst, nullptr); g_app.start_btn = CreateWindowA("BUTTON", "Start", WS_CHILD | WS_VISIBLE, 434, 8, 70, 26, hwnd, reinterpret_cast(kIdStart), inst, nullptr); g_app.status = CreateWindowA("STATIC", "Idle", WS_CHILD | WS_VISIBLE, 512, 12, 300, 20, hwnd, reinterpret_cast(kIdStatus), inst, nullptr); g_app.devices = enumerate_cameras(); TraceLog("enumerated %zu camera(s)", g_app.devices.size()); for (const auto& d : g_app.devices) { TraceLog(" camera: %s", d.name.c_str()); } for (const auto& d : g_app.devices) { SendMessageA(g_app.device_combo, CB_ADDSTRING, 0, reinterpret_cast(d.name.c_str())); } if (!g_app.devices.empty()) { SendMessage(g_app.device_combo, CB_SETCURSEL, 0, 0); PopulateResolutions(); } SetTimer(hwnd, 1, 33, nullptr); return 0; } case WM_COMMAND: { const int id = LOWORD(wparam); const int code = HIWORD(wparam); if (id == kIdDevice && code == CBN_SELCHANGE) { PopulateResolutions(); } else if (id == kIdStart && code == BN_CLICKED) { if (g_app.running) { StopCapture(); } else { StartCapture(); } } return 0; } case WM_TIMER: { std::string st; { std::lock_guard lock(g_app.preview_mutex); st = g_app.status_text; } SetWindowTextA(g_app.status, st.c_str()); InvalidateRect(hwnd, nullptr, FALSE); return 0; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); PaintPreview(hwnd, hdc); EndPaint(hwnd, &ps); return 0; } case WM_DESTROY: StopCapture(); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, msg, wparam, lparam); } } int WINAPI wWinMain(HINSTANCE inst, HINSTANCE, PWSTR, int show) { CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); MFStartup(MF_VERSION); TraceLog("==== kinect-tracker starting ===="); WNDCLASSW wc{}; wc.lpfnWndProc = WndProc; wc.hInstance = inst; wc.lpszClassName = L"KinectTrackerWnd"; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = reinterpret_cast(COLOR_WINDOW + 1); RegisterClassW(&wc); g_app.main = CreateWindowW(L"KinectTrackerWnd", L"Kinect Tracker (native)", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 860, 560, nullptr, nullptr, inst, nullptr); ShowWindow(g_app.main, show); UpdateWindow(g_app.main); MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } MFShutdown(); CoUninitialize(); return 0; }