diff --git a/DrvOpenXR/DrvOpenXR.cpp b/DrvOpenXR/DrvOpenXR.cpp index 2312dbff..e48626e5 100644 --- a/DrvOpenXR/DrvOpenXR.cpp +++ b/DrvOpenXR/DrvOpenXR.cpp @@ -189,6 +189,11 @@ struct InstancePlan { XrGraphicsApiSupportedFlags apiFlags = 0; }; +// The running instance's plan, set once at start-up: an instance made again after a loss has the same +static InstancePlan currentPlan; +// A new instance after a loss whose headset isn't there yet (RemakeInstance keeps it); until FullShutdown +static bool madeAgain = false; + // The extensions OpenLamina enables, of those available, for a session of that kind InstancePlan PlanInstance(const std::set& available, SessionKind kind) { @@ -521,6 +526,7 @@ IBackend* DrvOpenXR::CreateOpenXRBackend(const char* startupInfo, vr::EVRInitErr // Create the OpenXR instance - this is the overall handle that connects us to the runtime, or take the one // VR_IsHmdPresent made for a scene application const InstancePlan plan = PlanInstance(availableExtensions, choice.kind); + currentPlan = plan; const std::vector& extensions = plan.extensions; const XrGraphicsApiSupportedFlags apiFlags = plan.apiFlags; xr_instance = TakeProbedInstance(plan, &xr_instance_version); @@ -656,6 +662,45 @@ XrResult DrvOpenXR::FindSystem() return CreateSystemID(); } +XrResult DrvOpenXR::RemakeInstance() +{ +#ifdef _DEBUG + // It went with the old instance + dbgMessenger = NULL; +#endif + // A new instance made at an earlier try is kept while the headset isn't there yet + if (!madeAgain) { + if (xr_instance) { + if (XR_FAILED(xrDestroyInstance(xr_instance))) + OOVR_LOG("xrDestroyInstance of the lost instance failed"); + xr_instance = XR_NULL_HANDLE; + } + if (XrResult res = MakeInstance(currentPlan, &xr_instance, &xr_instance_version); XR_FAILED(res)) { + OOVR_LOGF("The OpenXR instance can't be made again yet: %d", (int)res); + xr_instance = XR_NULL_HANDLE; + return res; + } + // The old function table isn't freed: a thread outside the session lock may still be reading it + xr_ext = new XrExt(currentPlan.apiFlags, currentPlan.extensions); + madeAgain = true; + } + if (XrResult res = CreateSystemID(); XR_FAILED(res)) + return res; + uint32_t viewCount = 0; + if (XrResult res = xrEnumerateViewConfigurationViews(xr_instance, xr_system, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, 0, &viewCount, nullptr); XR_FAILED(res)) + return res; + std::vector views(viewCount, { XR_TYPE_VIEW_CONFIGURATION_VIEW }); + if (XrResult res = xrEnumerateViewConfigurationViews(xr_instance, xr_system, XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, viewCount, &viewCount, views.data()); XR_FAILED(res)) + return res; + // The game sized its textures for two views: a headset with another count isn't one to go on with + if (viewCount != XruEyeCount) + return XR_ERROR_VIEW_CONFIGURATION_TYPE_UNSUPPORTED; + xr_views_list = views; + madeAgain = false; // the next loss makes another + OOVR_LOG("Made the OpenXR instance again"); + return XR_SUCCESS; +} + void DrvOpenXR::KeepOverlaysInstance() { if (currentBackend) @@ -726,6 +771,7 @@ void DrvOpenXR::FullShutdown() } initialised = false; + madeAgain = false; currentBackend = nullptr; SetCurrentSessionKind(SessionKind::Scene); } diff --git a/DrvOpenXR/XrBackend.cpp b/DrvOpenXR/XrBackend.cpp index 998940f9..f3683ad5 100644 --- a/DrvOpenXR/XrBackend.cpp +++ b/DrvOpenXR/XrBackend.cpp @@ -2119,6 +2119,10 @@ void XrBackend::PumpEvents() std::unique_lock pumpLock(pumping, std::try_to_lock); if (!pumpLock.owns_lock()) return; + // Nor while another thread makes the instance or session again (it holds the session lock, and pumps itself) + SessionLock sessionLock(xr_session, SessionLock::TryShared{}); + if (!sessionLock.IsHeld()) + return; // Poll for OpenXR events while (true) { @@ -2127,7 +2131,7 @@ void XrBackend::PumpEvents() if (XR_FAILED(res)) { OOVR_LOG_ONCE("xrPollEvent failed: no events this frame"); if (res == XR_ERROR_INSTANCE_LOST) - OnSessionLost(); + OnInstanceLost(); break; } @@ -2152,11 +2156,11 @@ void XrBackend::PumpEvents() continue; } - // The instance is going away (the runtime updating or shutting down): its session with it + // The instance is going away (the runtime updating or shutting down): it's made again, with its session if (ev.type == XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING) { OOVR_LOG("The OpenXR instance will be lost"); if (!exitExpected) - OnSessionLost(); + OnInstanceLost(); continue; } @@ -2379,7 +2383,9 @@ bool XrBackend::WaitForEvents(const std::function& done, int timeoutMs) void XrBackend::OnFrameCallFailed(XrResult res) { renderingFrame = false; - if (res == XR_ERROR_SESSION_LOST || res == XR_ERROR_INSTANCE_LOST || ++frameCallFailures >= 5) + if (res == XR_ERROR_INSTANCE_LOST) + OnInstanceLost(); + else if (res == XR_ERROR_SESSION_LOST || ++frameCallFailures >= 5) OnSessionLost(); // No waited frame to pace the game: about one frame's wait instead of a busy loop std::this_thread::sleep_for(std::chrono::milliseconds(11)); @@ -2403,6 +2409,70 @@ void XrBackend::OnSessionLost() } } +void XrBackend::OnInstanceLost() +{ + if (!instanceLost.exchange(true)) + OOVR_LOG("The OpenXR instance is lost: making it again once the runtime is back"); + OnSessionLost(); +} + +// A new instance's xrCreateSession wants the graphics requirements of the binding's API asked of it first +static void AskGraphicsRequirements(const void* binding) +{ + const auto* header = (const XrBaseInStructure*)binding; + if (!header) + return; + switch (header->type) { +#if defined(_WIN32) && defined(SUPPORT_DX) && defined(SUPPORT_DX11) + case XR_TYPE_GRAPHICS_BINDING_D3D11_KHR: { + XrGraphicsRequirementsD3D11KHR requirements{ XR_TYPE_GRAPHICS_REQUIREMENTS_D3D11_KHR }; + OC_XR_LOG(xr_ext->xrGetD3D11GraphicsRequirementsKHR(xr_instance, xr_system, &requirements)); + break; + } +#endif +#if defined(_WIN32) && defined(SUPPORT_DX) && defined(SUPPORT_DX12) + case XR_TYPE_GRAPHICS_BINDING_D3D12_KHR: { + XrGraphicsRequirementsD3D12KHR requirements{ XR_TYPE_GRAPHICS_REQUIREMENTS_D3D12_KHR }; + OC_XR_LOG(xr_ext->xrGetD3D12GraphicsRequirementsKHR(xr_instance, xr_system, &requirements)); + break; + } +#endif +#if defined(SUPPORT_VK) + case XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR: { + XrGraphicsRequirementsVulkanKHR requirements{ XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR }; + OC_XR_LOG(xr_ext->xrGetVulkanGraphicsRequirementsKHR(xr_instance, xr_system, &requirements)); + // The session's device must be the one the new instance names + const auto* vk = (const XrGraphicsBindingVulkanKHR*)binding; + VkPhysicalDevice wanted = VK_NULL_HANDLE; + if (XR_SUCCEEDED(xr_ext->xrGetVulkanGraphicsDeviceKHR(xr_instance, xr_system, vk->instance, &wanted)) && wanted != vk->physicalDevice) + OOVR_LOG("The new OpenXR instance wants another Vulkan device than the session's: its session may fail"); + break; + } +#endif +#if defined(SUPPORT_GL) +#ifdef _WIN32 + case XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR: +#else + case XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR: +#endif + { + XrGraphicsRequirementsOpenGLKHR requirements{ XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR }; + OC_XR_LOG(xr_ext->xrGetOpenGLGraphicsRequirementsKHR(xr_instance, xr_system, &requirements)); + break; + } +#endif +#if defined(SUPPORT_GLES) + case XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR: { + XrGraphicsRequirementsOpenGLESKHR requirements{ XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR }; + OC_XR_LOG(xr_ext->xrGetOpenGLESGraphicsRequirementsKHR(xr_instance, xr_system, &requirements)); + break; + } +#endif + default: + break; + } +} + void XrBackend::RecoverLostSession(std::mutex* passLock) { if (!sessionLost || quitting || ownFramesStopped) @@ -2432,16 +2502,38 @@ void XrBackend::RecoverLostSession(std::mutex* passLock) pass = std::unique_lock(*passLock); if (!sessionLost || quitting) return; - // The lost session first, once: its handles are no use any more + // With a lost instance, the game's actions go first (forgotten: they went with it, and are made again on the new + // one), with the paths and the trackers' list of devices made on it. The info set goes with the session. + if (instanceLost) { + if (BaseInput* input = GetUnsafeBaseInput()) + input->_ForgetInstance(); + subactionPaths[0] = subactionPaths[1] = XR_NULL_PATH; + generic_trackers_generation = UINT64_MAX; + generic_trackers_session = XR_NULL_HANDLE; + } + // The lost session, once: its handles are no use any more if (!lostSessionDestroyed) { if (xr_gbl || xr_session.get()) DrvOpenXR::ShutdownSession(); lostSessionDestroyed = true; } - if (XR_FAILED(DrvOpenXR::FindSystem())) + if (instanceLost) { + if (XR_FAILED(DrvOpenXR::RemakeInstance())) + return; // no runtime or headset yet: the next try in a second + instanceLost = false; + } else if (XrResult res = DrvOpenXR::FindSystem(); XR_FAILED(res)) { + if (res == XR_ERROR_INSTANCE_LOST) + instanceLost = true; // the instance went too while the session was lost: made again at the next try return; // no headset yet: the next try in a second - if (XR_SUCCEEDED(RebuildSession(RebuildReason::Loss)) && !sessionLost) - OOVR_LOG("The OpenXR session is back"); + } + // Asked of the system found (on a new instance, or a new system id), as xrCreateSession wants + AskGraphicsRequirements(GetCurrentGraphicsBinding()); + if (XR_FAILED(RebuildSession(RebuildReason::Loss)) || sessionLost) + return; + // After a new instance: the game's actions and bindings, from its manifest, on it and its session + if (BaseInput* input = GetUnsafeBaseInput()) + input->_RebuildForNewInstance(); + OOVR_LOG("The OpenXR session is back"); } // Own frames call xrEndFrame on their own thread, where the runtime may use the session's device while the game's diff --git a/DrvOpenXR/XrBackend.h b/DrvOpenXR/XrBackend.h index fe405bd8..a872c72f 100644 --- a/DrvOpenXR/XrBackend.h +++ b/DrvOpenXR/XrBackend.h @@ -72,6 +72,10 @@ class XrBackend : public IBackend { std::atomic sawStopping{ false }; // The game has been told the devices are deactivated (a loss), and not yet that they're back std::atomic devicesDeactivated{ false }; + // The instance was lost with the session (XR_ERROR_INSTANCE_LOST, or INSTANCE_LOSS_PENDING): made again first + std::atomic instanceLost{ false }; + // The instance loss: lost with the session (OnSessionLost) + void OnInstanceLost(); // The last try to find the system again (RecoverLostSession), and whether the lost session is destroyed yet std::atomic lastRecoveryTry{ 0 }; // 0 before the first bool lostSessionDestroyed = false; diff --git a/DrvOpenXR/XrDriverPrivate.h b/DrvOpenXR/XrDriverPrivate.h index 139fdb6f..0db84b32 100644 --- a/DrvOpenXR/XrDriverPrivate.h +++ b/DrvOpenXR/XrDriverPrivate.h @@ -20,5 +20,8 @@ XrResult SetupSession(); void ShutdownSession(); // xrGetSystem for the headset again (after a loss): XR_SUCCESS once it is there XrResult FindSystem(); +// After the instance was lost (its session already ended): the old instance destroyed, a new one made on the same +// extensions, with its function pointers, system and views. XR_SUCCESS once there's a headset on it. +XrResult RemakeInstance(); void FullShutdown(); } // namespace DrvOpenXR diff --git a/OpenOVR/Reimpl/BaseCompositor.cpp b/OpenOVR/Reimpl/BaseCompositor.cpp index 72f30a61..f1af181f 100644 --- a/OpenOVR/Reimpl/BaseCompositor.cpp +++ b/OpenOVR/Reimpl/BaseCompositor.cpp @@ -892,6 +892,7 @@ void BaseCompositor::UnlockGLSharedTextureForAccess(glSharedTextureHandle_t glSh uint32_t BaseCompositor::GetVulkanInstanceExtensionsRequired(char* pchValue, uint32_t unBufferSize) { + auto lock = xr_session.lock_shared(); // held while asking: a new instance waits for it if (pchValue && unBufferSize) pchValue[0] = 0; #if defined(SUPPORT_VK) @@ -914,6 +915,7 @@ uint32_t BaseCompositor::GetVulkanInstanceExtensionsRequired(char* pchValue, uin uint32_t BaseCompositor::GetVulkanDeviceExtensionsRequired(VkPhysicalDevice_T* pPhysicalDevice, char* pchValue, uint32_t unBufferSize) { + auto lock = xr_session.lock_shared(); // held while asking: a new instance waits for it if (pchValue && unBufferSize) pchValue[0] = 0; #if defined(SUPPORT_VK) diff --git a/OpenOVR/Reimpl/BaseInput.cpp b/OpenOVR/Reimpl/BaseInput.cpp index 8462a582..f182e394 100644 --- a/OpenOVR/Reimpl/BaseInput.cpp +++ b/OpenOVR/Reimpl/BaseInput.cpp @@ -411,6 +411,13 @@ EVRInputError BaseInput::SetActionManifestPath(const char* pchActionManifestPath // no other thread reads input. Taken before evaluatorLock (see its declaration). auto sessionLock = xr_session.lock(); + // While a lost instance is made again: this manifest is the one loaded on the new instance + if (rebuildPending) { + manifestToRebuild = pchActionManifestPath; + rebuildLegacy = false; + return vr::VRInputError_None; + } + bool reloading = hasLoadedActions; if (hasLoadedActions) { // It stands to reason that nothing would happen if we try to load the same manifest again @@ -418,31 +425,7 @@ EVRInputError BaseInput::SetActionManifestPath(const char* pchActionManifestPath return vr::VRInputError_None; OOVR_LOG("Received another manifest! Restarting session to reattach inputs..."); - std::lock_guard evalGuard(evaluatorLock); - for (std::unique_ptr& as : actionSets.GetItems()) { - OC_XR_LOG(xrDestroyActionSet(as->xr)); - } - OC_XR_LOG(xrDestroyActionSet(legacyInputsSet)); - legacyInputsSet = XR_NULL_HANDLE; - eyeGazeAction = XR_NULL_HANDLE; - eyeGazeSpace = XR_NULL_HANDLE; - if (rawInputsSet != XR_NULL_HANDLE) - OC_XR_LOG(xrDestroyActionSet(rawInputsSet)); - rawInputsSet = XR_NULL_HANDLE; - rawActions.clear(); - rawComponents.clear(); - evaluators.clear(); - bindingFiles.clear(); - aliasedBindingFiles.clear(); - evaluatedThisSync.clear(); - legacyEvaluators.clear(); - { - std::lock_guard queueGuard(hapticQueueLock); - pendingHaptics.clear(); - } - actions.Reset(); - actionSets.Reset(); - usingLegacyInput = false; + DropActions(true); } restartingSession = true; @@ -777,6 +760,97 @@ EVRInputError BaseInput::SetActionManifestPath(const char* pchActionManifestPath return vr::VRInputError_None; } +void BaseInput::DropActions(bool destroyHandles) +{ + std::lock_guard evalGuard(evaluatorLock); + if (destroyHandles) { + for (std::unique_ptr& as : actionSets.GetItems()) { + OC_XR_LOG(xrDestroyActionSet(as->xr)); + } + if (legacyInputsSet != XR_NULL_HANDLE) + OC_XR_LOG(xrDestroyActionSet(legacyInputsSet)); + if (rawInputsSet != XR_NULL_HANDLE) + OC_XR_LOG(xrDestroyActionSet(rawInputsSet)); + } + legacyInputsSet = XR_NULL_HANDLE; + eyeGazeAction = XR_NULL_HANDLE; + eyeGazeSpace = XR_NULL_HANDLE; + rawInputsSet = XR_NULL_HANDLE; + rawActions.clear(); + rawComponents.clear(); + evaluators.clear(); + bindingFiles.clear(); + aliasedBindingFiles.clear(); + evaluatedThisSync.clear(); + legacyEvaluators.clear(); + { + std::lock_guard queueGuard(hapticQueueLock); + pendingHaptics.clear(); + } + actions.Reset(); + actionSets.Reset(); + usingLegacyInput = false; +} + +void BaseInput::_ForgetInstance() +{ + auto sessionLock = xr_session.lock(); + // Paths are the instance's own too: looked up again on the new one + pathsStale = true; + // Until the new instance has a session, the game's input calls only say what to load on it + if (rebuildPending) + return; // forgotten at an earlier try + rebuildPending = true; + rebuildLegacy = false; + manifestToRebuild.clear(); + if (!hasLoadedActions) + return; + { + std::lock_guard pathGuard(loadedActionsPathLock); + manifestToRebuild = loadedActionsPath; + loadedActionsPath.clear(); + } + rebuildLegacy = manifestToRebuild.empty(); + // Their handles went with the old instance: forgotten, not destroyed + DropActions(false); + for (XrHandTrackerEXT& handTracker : handTrackers) + handTracker = XR_NULL_HANDLE; + hasLoadedActions = false; +} + +void BaseInput::_RebuildForNewInstance() +{ + // Exclusive to the end, as a manifest's loading is + auto sessionLock = xr_session.lock(); + if (pathsStale) { + pathsStale = false; + for (size_t i = 0; i < allSubactionPathNames.size() && i < allSubactionPaths.size(); i++) { + allSubactionPaths[i] = XR_NULL_PATH; + OC_XR_LOG(xrStringToPath(xr_instance, allSubactionPathNames[i].c_str(), &allSubactionPaths[i])); + } + std::fill(handInteractionProfiles.begin(), handInteractionProfiles.end(), nullptr); + std::lock_guard registryGuard(inputHandleRegistryLock); + for (auto& [name, handle] : inputHandleRegistry) { + handle->devicePath = XR_NULL_PATH; + if (!handle->devicePathString.empty()) + OC_XR_LOG(xrStringToPath(xr_instance, handle->devicePathString.c_str(), &handle->devicePath)); + } + } + if (!rebuildPending) + return; + rebuildPending = false; + if (manifestToRebuild.empty() && !rebuildLegacy) + return; // the game had no actions + OOVR_LOG("Making the game's actions again on the new OpenXR instance"); + if (!manifestToRebuild.empty()) { + if (EVRInputError err = SetActionManifestPath(manifestToRebuild.c_str()); err == vr::VRInputError_None) + return; + else + OOVR_LOGF("The game's manifest couldn't be loaded again (%d): legacy input instead", (int)err); + } + LoadEmptyManifestIfRequired(); +} + void BaseInput::LoadEmptyManifestIfRequired() { if (hasLoadedActions) @@ -788,9 +862,12 @@ void BaseInput::LoadEmptyManifestIfRequired() if (!XrBackend::InputsMayAttach()) return; - // As in SetActionManifestPath, exclusive to the end; another thread may have loaded the actions while this waited + // As in SetActionManifestPath, exclusive to the end; another thread may have loaded the actions while this waited. + // Nor while a lost instance is made again: the actions are made on the new one. auto sessionLock = xr_session.lock(); - if (hasLoadedActions) + if (rebuildPending && manifestToRebuild.empty()) + rebuildLegacy = true; + if (hasLoadedActions || rebuildPending) return; restartingSession = true; diff --git a/OpenOVR/Reimpl/BaseInput.h b/OpenOVR/Reimpl/BaseInput.h index 5230e377..837c965e 100644 --- a/OpenOVR/Reimpl/BaseInput.h +++ b/OpenOVR/Reimpl/BaseInput.h @@ -484,6 +484,12 @@ class BaseInput { */ void LoadEmptyManifestIfRequired(); + // The OpenXR instance is lost: the actions' handles went with it, and are forgotten (the session lock held) + void _ForgetInstance(); + // On the new instance and its session: the actions and bindings are made again from the manifest that was loaded + // (or legacy input's), if _ForgetInstance forgot any + void _RebuildForNewInstance(); + /** * Update the input stuff, called by BaseSystem. * @@ -512,6 +518,18 @@ class BaseInput { // set before it bool LegacyInputAsked() const { return legacyInputAsked; } +private: + // The actions, action sets and their evaluators go (destroyHandles: with xrDestroyActionSet; not when the instance + // they belonged to is gone) + void DropActions(bool destroyHandles); + // The manifest (empty for legacy input) whose actions _ForgetInstance forgot, to be loaded again; under the session + // lock + std::string manifestToRebuild; + bool rebuildPending = false; + bool rebuildLegacy = false; // legacy input's actions are made again (there's no manifest to) + bool pathsStale = false; // the cached paths are the lost instance's + +public: /** One hand's laser for pointing at overlays (LaserMouse) */ struct HandPointer { XrPosef aim; // the aim pose: the laser runs along its -Z diff --git a/OpenOVR/Reimpl/BaseSystem.cpp b/OpenOVR/Reimpl/BaseSystem.cpp index bdae52b5..bcbe2d1f 100644 --- a/OpenOVR/Reimpl/BaseSystem.cpp +++ b/OpenOVR/Reimpl/BaseSystem.cpp @@ -180,6 +180,7 @@ bool BaseSystem::GetTimeSinceLastVsync(float* pfSecondsSinceLastVsync, uint64_t* bool BaseSystem::_RuntimeAdapterLuid(uint64_t* luid) { #ifdef SUPPORT_DX + auto lock = xr_session.lock_shared(); // held while asking: a new instance waits for it if (!xr_ext || xr_instance == XR_NULL_HANDLE) return false; auto pack = [luid](const LUID& l) { diff --git a/tests/conformance/expect/xr_failures.json b/tests/conformance/expect/xr_failures.json index 9c43e825..178aa58e 100644 --- a/tests/conformance/expect/xr_failures.json +++ b/tests/conformance/expect/xr_failures.json @@ -94,6 +94,45 @@ "manifest": 0 } }, + "instance_lost": { + "cases": [ + "frame-loop" + ], + "frames": 120, + "quit_events": 0, + "device_events": [ + 101, + 100 + ], + "instances_lost": 1, + "instances_created_min": 2, + "sessions_created_min": 3 + }, + "instance_lost_overlay": { + "cases": [ + "overlay-app-loss" + ], + "loss_record": { + "device_events": [ + 101, + 100 + ], + "instances_lost": 1, + "instances_created_min": 2, + "sessions_created_min": 2, + "frames_ended_min": 20 + } + }, + "instance_lost_input": { + "cases": [ + "input-frames" + ], + "rebuilt_actions": [ + "haptic", + "legacy-right-trigger" + ], + "action_attaches_min": 3 + }, "exiting": { "cases": [ "frame-loop" diff --git a/tests/conformance/scripts/instance_lost.json b/tests/conformance/scripts/instance_lost.json new file mode 100644 index 00000000..7d880a1f --- /dev/null +++ b/tests/conformance/scripts/instance_lost.json @@ -0,0 +1 @@ +{ "#": "The instance is lost at frame 10 (the runtime's service died), and the runtime is back after 300 ms: the devices deactivated, a new instance and session made about a second later with the game's actions on them, the devices activated again, and no VREvent_Quit", "events": [{ "frame": 10, "type": "instance_lost" }], "loss_unavailable_ms": 300 } diff --git a/tests/conformance/scripts/instance_lost_input.json b/tests/conformance/scripts/instance_lost_input.json new file mode 100644 index 00000000..9fdfc86e --- /dev/null +++ b/tests/conformance/scripts/instance_lost_input.json @@ -0,0 +1 @@ +{ "#": "The instance is lost at frame 5 and the runtime is back at once (case input-frames): the game's actions and bindings are made again on the new instance, whose paths differ from the old one's, and its input calls keep working", "events": [{ "frame": 5, "type": "instance_lost" }], "interaction_profile": "/interaction_profiles/valve/index_controller" } diff --git a/tests/conformance/scripts/instance_lost_overlay.json b/tests/conformance/scripts/instance_lost_overlay.json new file mode 100644 index 00000000..11bc9079 --- /dev/null +++ b/tests/conformance/scripts/instance_lost_overlay.json @@ -0,0 +1 @@ +{ "#": "An overlay application's instance is lost at its frame 30 (the runtime's service died), and the runtime is back after 300 ms: its own loop makes the instance and session again about a second later; the devices deactivated and activated again, and no VREvent_Quit", "extensions": ["XR_KHR_D3D11_enable", "XR_EXTX_overlay", "XR_MND_headless"], "events": [{ "frame": 30, "type": "instance_lost" }], "loss_unavailable_ms": 300 } diff --git a/tests/conformance/xr_failures.py b/tests/conformance/xr_failures.py index cc30b8d4..e51a3301 100644 --- a/tests/conformance/xr_failures.py +++ b/tests/conformance/xr_failures.py @@ -73,10 +73,10 @@ def check(name, want, out): misses.append(f"frame-loop: device events {seq}, expected {want['device_events']} in that order") if 704 in seq: misses.append("frame-loop: VREvent_DriverRequestedQuit polled after a loss") - for key, at_least in (("sessions_lost", False), ("sessions_created_min", True)): + for key, at_least in (("sessions_lost", False), ("sessions_created_min", True), ("instances_lost", False), ("instances_created_min", True)): if key in want: dump = json.loads(dump_path.read_text(encoding="utf-8")) if dump_path.exists() else {} - name = "sessions_created" if at_least else key + name = key.removesuffix("_min") got = dump.get(name, 0) if (got < want[key]) if at_least else (got != want[key]): misses.append(f"frame-loop: the runtime saw {got} {name.replace('_', ' ')}, expected {'at least ' if at_least else ''}{want[key]}") @@ -96,12 +96,27 @@ def check(name, want, out): misses.append(f"overlay-app-loss: {key.removesuffix('_min')} {r.get(key.removesuffix('_min'))}, expected at least {value}") elif key in ("sessions_lost", "instances_lost", "manifest") and r.get(key) != value: misses.append(f"overlay-app-loss: {key} {r.get(key)}, expected {value}") + if "rebuilt_actions" in want: + # Case input-frames through an instance loss: the last instance has the game's manifest's actions and their + # bindings + path = out / "raw" / "case-input-frames.dump.json" + dump = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + if dump.get("instances_lost") != 1 or dump.get("instances_created", 0) < 2: + misses.append(f"input-frames: {dump.get('instances_lost')} instances lost and {dump.get('instances_created')} made, expected 1 and at least 2") + names = {a.get("name") for a in dump.get("actions", [])} + missing = [n for n in want["rebuilt_actions"] if n not in names] + if missing: + misses.append(f"input-frames: the new instance has no actions {missing}") + if not dump.get("suggested_bindings"): + misses.append("input-frames: the new instance had no bindings suggested") if "action_attaches_min" in want: - # Case input-frames through a loss: the game's actions are attached to the session made again too + # Case input-frames through a session or instance loss: the game's actions are attached to the session made + # again too path = out / "raw" / "case-input-frames.dump.json" dump = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} - if dump.get("sessions_lost") != 1 or dump.get("action_attaches", 0) < want["action_attaches_min"]: - misses.append(f"input-frames: {dump.get('sessions_lost')} sessions lost and {dump.get('action_attaches')} action attaches, expected 1 and at least {want['action_attaches_min']}") + lost = (dump.get("sessions_lost") or 0) + (dump.get("instances_lost") or 0) + if lost != 1 or dump.get("action_attaches", 0) < want["action_attaches_min"]: + misses.append(f"input-frames: {lost} sessions or instances lost and {dump.get('action_attaches')} action attaches, expected 1 and at least {want['action_attaches_min']}") if "old_event_quits" in want: # IVRSystem_009's events (case old-events): the quit arrives, and nothing is written past the 32-byte event olds = [r for r in records if r.get("case") == "old-events" and str(r.get("method", "")).startswith("frame ")] diff --git a/tests/runtime/CMakeLists.txt b/tests/runtime/CMakeLists.txt index 075a6197..daef72f5 100644 --- a/tests/runtime/CMakeLists.txt +++ b/tests/runtime/CMakeLists.txt @@ -28,7 +28,9 @@ if (WIN32) else () target_compile_definitions(oc_test_runtime PRIVATE XR_USE_PLATFORM_XLIB) # GL and GLX from libGL; X11 for the display the binding names; Vulkan's loader is opened at run time - target_link_libraries(oc_test_runtime PRIVATE jsoncpp GL X11 ${CMAKE_DL_LIBS} -Wl,--no-undefined) + # nodelete: the loader unloads a runtime whose last instance is destroyed, and the state of a scripted loss must + # outlive the lost instance + target_link_libraries(oc_test_runtime PRIVATE jsoncpp GL X11 ${CMAKE_DL_LIBS} -Wl,--no-undefined -Wl,-z,nodelete) endif () set_target_properties(oc_test_runtime PROPERTIES PREFIX "") diff --git a/tests/runtime/runtime.cpp b/tests/runtime/runtime.cpp index 1d1cfcce..44a70c97 100644 --- a/tests/runtime/runtime.cpp +++ b/tests/runtime/runtime.cpp @@ -280,6 +280,14 @@ XrResult XRAPI_CALL CreateInstance(const XrInstanceCreateInfo* info, XrInstance* std::lock_guard g(St().lock); if (St().instanceAlive) return XR_ERROR_LIMIT_REACHED; + if (std::chrono::steady_clock::now() < St().systemBackAt) + return XR_ERROR_RUNTIME_FAILURE; // the runtime is gone after a scripted loss +#ifdef _WIN32 + // Kept loaded once used: the loader unloads a runtime whose last instance is destroyed, and the state of a + // scripted loss must outlive the lost instance (on Linux, -z nodelete) + HMODULE self = nullptr; + GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, (LPCSTR)&CreateInstance, &self); +#endif std::set enabled; for (uint32_t i = 0; i < info->enabledExtensionCount; i++) { std::string name = info->enabledExtensionNames[i]; @@ -289,11 +297,21 @@ XrResult XRAPI_CALL CreateInstance(const XrInstanceCreateInfo* info, XrInstance* } St().instanceAlive = true; St().requirementsQueried.clear(); + // Each instance's paths are its own, as a real runtime's: a later instance's atoms start further on, so a client + // that keeps a lost instance's paths gets wrong ones + St().pathIds.clear(); + St().paths.assign(1 + 1000 * St().instancesMade++, ""); St().enabledExtensions = enabled; { Dump& d = GetDump(); std::lock_guard dg(d.lock); - d.root = Json::Value(Json::objectValue); + // The counts of losses and sessions go on across instances + Json::Value kept(Json::objectValue); + for (const char* key : { "sessions_created", "sessions_lost", "instances_lost", "instances_created", "action_attaches" }) + if (d.root.isMember(key)) + kept[key] = d.root[key]; + d.root = kept; + d.root["instances_created"] = d.root["instances_created"].asUInt64() + 1; d.root["instance"]["extensions"] = Json::Value(Json::arrayValue); for (const std::string& e : enabled) d.root["instance"]["extensions"].append(e); @@ -315,6 +333,7 @@ XrResult XRAPI_CALL DestroyInstance(XrInstance) St().session.reset(); St().events.clear(); St().instanceAlive = false; + St().instanceLost = false; Dump& d = GetDump(); std::lock_guard dg(d.lock); RtActionsDump(d.root); @@ -334,6 +353,8 @@ XrResult XRAPI_CALL GetInstanceProperties(XrInstance, XrInstanceProperties* prop XrResult XRAPI_CALL PollEvent(XrInstance, XrEventDataBuffer* out) { std::lock_guard g(St().lock); + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (St().events.empty()) return XR_EVENT_UNAVAILABLE; *out = St().events.front(); @@ -382,7 +403,7 @@ XrResult XRAPI_CALL StringToPath(XrInstance, const char* str, XrPath* path) XrResult XRAPI_CALL PathToString(XrInstance, XrPath path, uint32_t capacity, uint32_t* count, char* buffer) { std::lock_guard g(St().lock); - if (path == XR_NULL_PATH || path >= St().paths.size()) + if (path == XR_NULL_PATH || path >= St().paths.size() || St().paths[(size_t)path].empty()) return XR_ERROR_PATH_INVALID; const std::string& s = St().paths[(size_t)path]; *count = (uint32_t)s.size() + 1; @@ -403,6 +424,8 @@ XrResult XRAPI_CALL GetSystem(XrInstance, const XrSystemGetInfo* info, XrSystemI return XR_ERROR_FORM_FACTOR_UNSUPPORTED; { std::lock_guard g(St().lock); + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (std::chrono::steady_clock::now() < St().systemBackAt) return XR_ERROR_FORM_FACTOR_UNAVAILABLE; // gone after a scripted loss } @@ -469,6 +492,8 @@ XrResult XRAPI_CALL CreateSession(XrInstance, const XrSessionCreateInfo* info, X { FAIL_POINT("xrCreateSession"); std::lock_guard g(St().lock); + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (St().session) return XR_ERROR_LIMIT_REACHED; auto session = std::make_unique(); @@ -538,6 +563,8 @@ XrResult XRAPI_CALL BeginSession(XrSession, const XrSessionBeginInfo* info) RtSession* s = St().session.get(); if (!s) return XR_ERROR_HANDLE_INVALID; + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (s->lost) return XR_ERROR_SESSION_LOST; if (s->running) @@ -554,6 +581,8 @@ XrResult XRAPI_CALL EndSession(XrSession) RtSession* s = St().session.get(); if (!s) return XR_ERROR_HANDLE_INVALID; + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (s->lost) return XR_ERROR_SESSION_LOST; if (!s->running) @@ -830,6 +859,8 @@ XrResult XRAPI_CALL WaitFrame(XrSession, const XrFrameWaitInfo*, XrFrameState* f RtSession* s = St().session.get(); if (!s) return XR_ERROR_HANDLE_INVALID; + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (s->lost) return XR_ERROR_SESSION_LOST; if (!s->running) @@ -861,6 +892,18 @@ XrResult XRAPI_CALL WaitFrame(XrSession, const XrFrameWaitInfo*, XrFrameState* f } if (loss) continue; + if (ev.type == "instance_lost") { + if (ev.frame == s->framesWaited && St().lossesSent.insert(i).second) { + St().instanceLost = true; + St().systemBackAt = std::chrono::steady_clock::now() + std::chrono::milliseconds(GetScript().lossUnavailableMs); + if (Dump::Enabled()) { + Dump& d = GetDump(); + std::lock_guard dg(d.lock); + d.root["instances_lost"] = d.root["instances_lost"].asUInt64() + 1; + } + } + continue; + } // EXITING is the user quitting from the runtime: STOPPING first, EXITING once the session has ended if (ev.frame == s->framesWaited && ev.type == "session_state" && ev.state == "EXITING" && s->running) { s->exitRequested = true; @@ -888,6 +931,8 @@ XrResult XRAPI_CALL BeginFrame(XrSession, const XrFrameBeginInfo*) RtSession* s = St().session.get(); if (!s) return XR_ERROR_HANDLE_INVALID; + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (s->lost) return XR_ERROR_SESSION_LOST; if (!s->running) @@ -1229,6 +1274,8 @@ XrResult XRAPI_CALL EndFrame(XrSession, const XrFrameEndInfo* info) RtSession* s = St().session.get(); if (!s) return XR_ERROR_HANDLE_INVALID; + if (St().instanceLost) + return XR_ERROR_INSTANCE_LOST; if (s->lost) return XR_ERROR_SESSION_LOST; if (s->headless || !s->frameOpen) { diff --git a/tests/runtime/runtime_internal.h b/tests/runtime/runtime_internal.h index 516d586e..96172166 100644 --- a/tests/runtime/runtime_internal.h +++ b/tests/runtime/runtime_internal.h @@ -218,6 +218,8 @@ struct RtState { bool presenceSent = false; // A scripted loss: the system is gone (xrGetSystem fails) until then; the loss events already sent (by index) std::chrono::steady_clock::time_point systemBackAt{}; + bool instanceLost = false; // a scripted instance loss, until xrDestroyInstance + uint32_t instancesMade = 0; std::set lossesSent; }; diff --git a/tests/runtime/script.h b/tests/runtime/script.h index 96d0270e..915ac478 100644 --- a/tests/runtime/script.h +++ b/tests/runtime/script.h @@ -9,7 +9,10 @@ // "events": [{ "frame": 60, "type": "session_state", "state": "LOSS_PENDING" }] // (LOSS_PENDING loses the session for real, once per process: its calls answer XR_ERROR_SESSION_LOST // from then on, and xrGetSystem answers XR_ERROR_FORM_FACTOR_UNAVAILABLE for loss_unavailable_ms; -// EXITING on a running session is the user quitting: STOPPING, then EXITING after xrEndSession), +// EXITING on a running session is the user quitting: STOPPING, then EXITING after xrEndSession; +// { "frame": 60, "type": "instance_lost" } loses the instance, once per process, as a dead monado-service +// does: xrPollEvent and the frame, session and system calls answer XR_ERROR_INSTANCE_LOST until +// xrDestroyInstance, and xrCreateInstance fails for loss_unavailable_ms), // (or { "frame": 10, "type": "refresh_rate", "rate": 120 }: the display changes to that rate, announced // with XrEventDataDisplayRefreshRateChangedFB), // "fail": [{ "function": "xrEndFrame", "result": "XR_ERROR_RUNTIME_FAILURE", "after": 29, "count": 1 }]