Godot Engine – Multi-platform 2D and 3D game engine
Add support for the spatial container extension
Fredia Huya-Kouadio8078d0162760
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xmlindex 1e81590026c..83d63351bc6 100644--- a/doc/classes/ProjectSettings.xml+++ b/doc/classes/ProjectSettings.xml@@ -3649,6 +3649,15 @@If [code]true[/code] we enable the render model extension if available.[b]Note:[/b] This relates to the core OpenXR render model extension and has no relation to any vendor render model extensions.</member>+ <member name="xr/openxr/extensions/spatial_container/bounds" type="Vector3" setter="" getter="" default="Vector3(0.5, 0.5, 0.5)">+ Specifies the starting bounds for the main spatial container, in meters.+ </member>+ <member name="xr/openxr/extensions/spatial_container/bounds_mode" type="int" setter="" getter="" default=""0"">+ Specifies the bounds mode, [code]bounded[/code] or [code]immersive[/code], for the main spatial container.+ </member>+ <member name="xr/openxr/extensions/spatial_container/enabled" type="bool" setter="" getter="" default="false">+ Enables the spatial container extension.+ </member><member name="xr/openxr/extensions/spatial_entity/enable_builtin_anchor_detection" type="bool" setter="" getter="" default="false">If [code]true[/code], we enable the built-in logic for handling anchors. Godot will query (persistent) anchors and manage [OpenXRAnchorTracker] instances for you. If disabled you'll need to create your own spatial and persistence context and perform your own discovery queries.[b]Note:[/b] This functionality requires that spatial anchors are supported and enabled.diff --git a/main/main.cpp b/main/main.cppindex 64452fba316..ff4edca77d5 100644--- a/main/main.cpp+++ b/main/main.cpp@@ -2890,6 +2890,9 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phGLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking_unobstructed_data_source", false); // XR_HAND_TRACKING_DATA_SOURCE_UNOBSTRUCTED_EXTGLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking_controller_data_source", false); // XR_HAND_TRACKING_DATA_SOURCE_CONTROLLER_EXTGLOBAL_DEF_RST_BASIC("xr/openxr/extensions/hand_interaction_profile", false);+ GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_container/enabled", false);+ GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/extensions/spatial_container/bounds_mode", PROPERTY_HINT_ENUM, "Bounded,Immersive"), "0");+ GLOBAL_DEF_BASIC(PropertyInfo(Variant::VECTOR3, "xr/openxr/extensions/spatial_container/bounds", PROPERTY_HINT_NONE, ""), Vector3(0.5f, 0.5f, 0.5f));GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enabled", false);GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_spatial_anchors", false);GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_persistent_anchors", false);diff --git a/modules/openxr/config.py b/modules/openxr/config.pyindex eac756df36b..d91d239c822 100644--- a/modules/openxr/config.py+++ b/modules/openxr/config.py@@ -76,6 +76,9 @@ def get_doc_classes():"OpenXRSpatialMarkerTrackingCapability","OpenXRAndroidThreadSettingsExtension","OpenXRUserPresenceExtension",+ "OpenXRSpatialContainerExtension",+ "OpenXRSpatialContainerSelfRenderingExtension",+ "OpenXRSpatialContainerState",]diff --git a/modules/openxr/doc_classes/OpenXRExtensionWrapper.xml b/modules/openxr/doc_classes/OpenXRExtensionWrapper.xmlindex ad51c227dbf..71f77b96265 100644--- a/modules/openxr/doc_classes/OpenXRExtensionWrapper.xml+++ b/modules/openxr/doc_classes/OpenXRExtensionWrapper.xml@@ -309,6 +309,24 @@Add additional data structures when the OpenXR session is created.</description></method>+ <method name="_set_spatial_container_create_info_and_get_next_pointer" qualifiers="virtual">+ <return type="int" />+ <param index="0" name="spatial_container" type="RID" />+ <param index="1" name="next_pointer" type="void*" />+ <description>+ Add additional data structures when the spatial container is created.+ </description>+ </method>+ <method name="_set_spatial_container_views_locate_info_and_get_next_pointer" qualifiers="virtual">+ <return type="int" />+ <param index="0" name="spatial_container" type="RID" />+ <param index="1" name="next_pointer" type="void*" />+ <description>+ Add additional data structures to [code]XrSpatialContainerViewsLocateInfoEXT[/code] for the spatial container specified by [param spatial_container].+ This will only be called if the extension previously registered itself with [method OpenXRAPIExtension.register_frame_info_extension].+ [b]Note:[/b] This virtual method will be called on the render thread. Additionally, the data it returns will be used shortly after this method is called, so it needs to remain valid until the next time [method _on_pre_render] runs.+ </description>+ </method><method name="_set_swapchain_create_info_and_get_next_pointer" qualifiers="virtual"><return type="int" /><param index="0" name="next_pointer" type="void*" />diff --git a/modules/openxr/doc_classes/OpenXRSpatialContainerExtension.xml b/modules/openxr/doc_classes/OpenXRSpatialContainerExtension.xmlnew file mode 100644index 00000000000..71f1aca2600--- /dev/null+++ b/modules/openxr/doc_classes/OpenXRSpatialContainerExtension.xml@@ -0,0 +1,104 @@+<?xml version="1.0" encoding="UTF-8" ?>+<class name="OpenXRSpatialContainerExtension" inherits="OpenXRExtensionWrapper" api_type="core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">+ <brief_description>+ OpenXR extension that handles spatial containers.+ </brief_description>+ <description>+ OpenXR extension that handles spatial containers. Enabling this extension will automatically create a main spatial container, and update the lifecycle of the XR application.+ </description>+ <tutorials>+ </tutorials>+ <methods>+ <method name="get_spatial_container_bounds">+ <return type="Vector3" />+ <description>+ Retrieves the bounds of the main spatial container.+ </description>+ </method>+ <method name="get_spatial_container_state">+ <return type="OpenXRSpatialContainerState" />+ <description>+ Retrieves the [OpenXRSpatialContainerState] of the main spatial container.+ </description>+ </method>+ <method name="get_supported_bounds_modes">+ <return type="Array" />+ <description>+ Returns an array of supported spatial container bounds mode, see [enum OpenXRSpatialContainerState.BoundsMode].+ </description>+ </method>+ <method name="is_enabled" qualifiers="const">+ <return type="bool" />+ <description>+ Returns [code]true[/code] if spatial containers are enabled in the project settings and available on the current runtime.+ </description>+ </method>+ <method name="is_spatial_container_active" qualifiers="const">+ <return type="bool" />+ <description>+ Returns [code]true[/code] if the main spatial container is active.+ </description>+ </method>+ <method name="request_spatial_container_bounds_mode">+ <return type="bool" />+ <param index="0" name="bounds_mode" type="int" enum="OpenXRSpatialContainerState.BoundsMode" />+ <description>+ Sends a request to the runtime to update the bounds mode of the main spatial container.+ If the request is accepted, [signal spatial_container_bounds_changed] will be emitted with the updated bounds mode.+ Otherwise, [signal spatial_container_bounds_mode_request_denied] will be emitted.+ </description>+ </method>+ <method name="request_spatial_container_visible">+ <return type="bool" />+ <param index="0" name="visible" type="bool" />+ <description>+ Sends a request to the runtime to update the visibility of the spatial container.+ If the request is accepted, [signal spatial_container_visible_changed] will be emitted with the updated visibility.+ Otherwise, [signal spatial_container_visible_request_denied] will be emitted.+ </description>+ </method>+ </methods>+ <signals>+ <signal name="spatial_container_bounds_changed">+ <param index="0" name="spatial_container_rid" type="RID" />+ <param index="1" name="spatial_container_infinite_bounds" type="bool" />+ <param index="2" name="spatial_container_bounds_mode" type="int" />+ <param index="3" name="spatial_container_bounds" type="Vector3" />+ <description>+ Emitted when the bounds of the spatial container specified by [param spatial_container_rid] are updated.+ </description>+ </signal>+ <signal name="spatial_container_bounds_mode_request_denied">+ <param index="0" name="spatial_container_rid" type="RID" />+ <description>+ Emitted when a request to update the bounds mode of the spatial container specified by [param spatial_container_rid] is denied by the runtime.+ </description>+ </signal>+ <signal name="spatial_container_closed">+ <param index="0" name="spatial_container_rid" type="RID" />+ <description>+ Emitted when the spatial container specified by [param spatial_container_rid] is closed.+ </description>+ </signal>+ <signal name="spatial_container_interactable_changed">+ <param index="0" name="spatial_container_rid" type="RID" />+ <param index="1" name="spatial_container_interactable" type="bool" />+ <description>+ Emitted when the interactability of the spatial container specified by [param spatial_container_rid] is updated.+ </description>+ </signal>+ <signal name="spatial_container_visible_changed">+ <param index="0" name="spatial_container_rid" type="RID" />+ <param index="1" name="spatial_container_visible" type="bool" />+ <description>+ Emitted when the visibility of the spatial container specified by [param spatial_container_rid] is updated.+ </description>+ </signal>+ <signal name="spatial_container_visible_request_denied">+ <param index="0" name="spatial_container_rid" type="RID" />+ <description>+ Emitted when the runtime denies the visibility request of the spatial container specified by [param spatial_container_rid].+ </description>+ </signal>+ </signals>+</class>diff --git a/modules/openxr/doc_classes/OpenXRSpatialContainerSelfRenderingExtension.xml b/modules/openxr/doc_classes/OpenXRSpatialContainerSelfRenderingExtension.xmlnew file mode 100644index 00000000000..afe9d9e3077--- /dev/null+++ b/modules/openxr/doc_classes/OpenXRSpatialContainerSelfRenderingExtension.xml@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="UTF-8" ?>+<class name="OpenXRSpatialContainerSelfRenderingExtension" inherits="OpenXRExtensionWrapper" api_type="core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">+ <brief_description>+ OpenXR extension that defines "self rendering" for spatial containers.+ </brief_description>+ <description>+ OpenXR extension that defines "self rendering" for spatial containers. A self rendered spatial container's pixels are all generated by an app and submitted to the runtime using standard OpenXR swapchains and composition layers.+ </description>+ <tutorials>+ </tutorials>+ <methods>+ <method name="is_enabled" qualifiers="const">+ <return type="bool" />+ <description>+ Returns [code]true[/code] if spatial container self rendering is enabled in the project settings and available on the current runtime.+ </description>+ </method>+ </methods>+</class>diff --git a/modules/openxr/doc_classes/OpenXRSpatialContainerState.xml b/modules/openxr/doc_classes/OpenXRSpatialContainerState.xmlnew file mode 100644index 00000000000..5e9cfef1624--- /dev/null+++ b/modules/openxr/doc_classes/OpenXRSpatialContainerState.xml@@ -0,0 +1,39 @@+<?xml version="1.0" encoding="UTF-8" ?>+<class name="OpenXRSpatialContainerState" inherits="RefCounted" api_type="core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">+ <brief_description>+ An object representing the state of an OpenXR spatial container.+ </brief_description>+ <description>+ The [OpenXRSpatialContainerState] object holds information about the current state of a spatial container, including its visibility, interactability, and bounds mode.+ </description>+ <tutorials>+ </tutorials>+ <methods>+ <method name="get_bounds_mode" qualifiers="const">+ <return type="int" enum="OpenXRSpatialContainerState.BoundsMode" />+ <description>+ Returns the current bounds mode of the spatial container.+ </description>+ </method>+ <method name="is_interactable" qualifiers="const">+ <return type="bool" />+ <description>+ Returns the current interactability of the spatial container.+ </description>+ </method>+ <method name="is_visible" qualifiers="const">+ <return type="bool" />+ <description>+ Returns the current visibility state of the spatial container.+ </description>+ </method>+ </methods>+ <constants>+ <constant name="BOUNDS_MODE_BOUNDED" value="0" enum="BoundsMode">+ The spatial container is in bounded mode.+ </constant>+ <constant name="BOUNDS_MODE_IMMERSIVE" value="1" enum="BoundsMode">+ The spatial container is in immersive mode.+ </constant>+ </constants>+</class>diff --git a/modules/openxr/editor/openxr_editor_plugin.cpp b/modules/openxr/editor/openxr_editor_plugin.cppindex 85444631b30..093cee7962c 100644--- a/modules/openxr/editor/openxr_editor_plugin.cpp+++ b/modules/openxr/editor/openxr_editor_plugin.cpp@@ -31,6 +31,7 @@#include "openxr_editor_plugin.h"#include "../action_map/openxr_action_map.h"+#include "../extensions/spatial_container/openxr_spatial_container_state.h"#include "../openxr_api.h"#include "editor/docks/editor_dock_manager.h"@@ -56,6 +57,10 @@ bool OpenXRExportPlugin::is_openxr_mode() const {return openxr_enabled && xr_mode_index == XR_MODE_OPENXR;}+bool OpenXRExportPlugin::is_spatial_container_enabled() const {+ return (bool)get_export_platform()->get_project_setting(get_export_preset(), "xr/openxr/extensions/spatial_container/enabled");+}+String OpenXRExportPlugin::_get_export_option_warning(const Ref<EditorExportPlatform> &p_export_platform, const String &p_option_name) const {if (!supports_platform(p_export_platform)) {return String();@@ -150,15 +155,34 @@ String OpenXRExportPlugin::get_android_manifest_activity_element_contents(constreturn contents;}- contents += R"n(+ if (!is_spatial_container_enabled()) {+ contents += R"n(<intent-filter><action android:name="android.intent.action.MAIN" />-<category android:name="android.intent.category.DEFAULT" />-<category android:name="org.khronos.openxr.intent.category.IMMERSIVE_HMD" /></intent-filter>)n";+ } else {+ contents += R"n(+ <property android:name="org.khronos.openxr.PROPERTY_ACTIVITY_HINT_XR_SPATIAL_CONTAINER_USED_BOUNDS_MODES" android:value="" />+)n";++ // Get the initial bounds mode.+ OpenXRSpatialContainerState::BoundsMode initial_bounds_mode = (OpenXRSpatialContainerState::BoundsMode)get_export_platform()->get_project_setting(get_export_preset(), "xr/openxr/extensions/spatial_container/bounds_mode");+ String manifest_initial_bounds_mode_value = "XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE_UNDEFINED";+ switch (initial_bounds_mode) {+ case OpenXRSpatialContainerState::BOUNDS_MODE_BOUNDED:+ manifest_initial_bounds_mode_value = "XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE_BOUNDED";+ break;+ case OpenXRSpatialContainerState::BOUNDS_MODE_IMMERSIVE:+ manifest_initial_bounds_mode_value = "XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE_IMMERSIVE";+ break;+ }+ contents += vformat(+ " <property android:name=\"org.khronos.openxr.PROPERTY_ACTIVITY_HINT_XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE\" android:value=\"%s\" />\n",+ manifest_initial_bounds_mode_value);+ }return contents;}diff --git a/modules/openxr/editor/openxr_editor_plugin.h b/modules/openxr/editor/openxr_editor_plugin.hindex 74effd33cc2..0a5bcea6ff4 100644--- a/modules/openxr/editor/openxr_editor_plugin.h+++ b/modules/openxr/editor/openxr_editor_plugin.h@@ -54,6 +54,7 @@ protected:private:bool is_openxr_mode() const;+ bool is_spatial_container_enabled() const;};class OpenXREditorPlugin : public EditorPlugin {diff --git a/modules/openxr/extensions/SCsub b/modules/openxr/extensions/SCsubindex 18fc2af3a2c..d0571a89afa 100644--- a/modules/openxr/extensions/SCsub+++ b/modules/openxr/extensions/SCsub@@ -7,6 +7,7 @@ Import("env_openxr")module_obj = []env_openxr.add_source_files(module_obj, "*.cpp")+env_openxr.add_source_files(module_obj, "spatial_container/*.cpp")env_openxr.add_source_files(module_obj, "spatial_entities/*.cpp")# These are platform dependentdiff --git a/modules/openxr/extensions/openxr_extension_wrapper.cpp b/modules/openxr/extensions/openxr_extension_wrapper.cppindex b3d3bd0ee87..a5eed6abecd 100644--- a/modules/openxr/extensions/openxr_extension_wrapper.cpp+++ b/modules/openxr/extensions/openxr_extension_wrapper.cpp@@ -47,7 +47,9 @@ void OpenXRExtensionWrapper::_bind_methods() {GDVIRTUAL_BIND(_set_frame_end_info_and_get_next_pointer, "next_pointer");GDVIRTUAL_BIND(_set_projection_layer_and_get_next_pointer, "next_pointer");GDVIRTUAL_BIND(_set_view_locate_info_and_get_next_pointer, "next_pointer");+ GDVIRTUAL_BIND(_set_spatial_container_views_locate_info_and_get_next_pointer, "spatial_container", "next_pointer");GDVIRTUAL_BIND(_set_reference_space_create_info_and_get_next_pointer, "reference_space_type", "next_pointer");+ GDVIRTUAL_BIND(_set_spatial_container_create_info_and_get_next_pointer, "spatial_container", "next_pointer");GDVIRTUAL_BIND(_prepare_view_configuration, "view_count");GDVIRTUAL_BIND(_set_view_configuration_and_get_next_pointer, "view", "next_pointer");GDVIRTUAL_BIND(_print_view_configuration_info, "view");@@ -224,6 +226,16 @@ void *OpenXRExtensionWrapper::set_projection_layer_and_get_next_pointer(void *p_return nullptr;}+void *OpenXRExtensionWrapper::set_spatial_container_create_info_and_get_next_pointer(RID p_spatial_container, void *p_next_pointer) {+ uint64_t pointer = 0;++ if (GDVIRTUAL_CALL(_set_spatial_container_create_info_and_get_next_pointer, p_spatial_container, GDExtensionPtr<void>(p_next_pointer), pointer)) {+ return reinterpret_cast<void *>(pointer);+ }++ return nullptr;+}+void OpenXRExtensionWrapper::prepare_view_configuration(uint32_t p_view_count) {GDVIRTUAL_CALL(_prepare_view_configuration, p_view_count);}@@ -252,6 +264,16 @@ void *OpenXRExtensionWrapper::set_view_locate_info_and_get_next_pointer(void *p_return nullptr;}+void *OpenXRExtensionWrapper::set_spatial_container_views_locate_info_and_get_next_pointer(RID p_spatial_container, void *p_next_pointer) {+ uint64_t pointer = 0;++ if (GDVIRTUAL_CALL(_set_spatial_container_views_locate_info_and_get_next_pointer, p_spatial_container, GDExtensionPtr<void>(p_next_pointer), pointer)) {+ return reinterpret_cast<void *>(pointer);+ }++ return nullptr;+}+PackedStringArray OpenXRExtensionWrapper::get_suggested_tracker_names() {PackedStringArray ret;diff --git a/modules/openxr/extensions/openxr_extension_wrapper.h b/modules/openxr/extensions/openxr_extension_wrapper.hindex 3c1f43f91fc..75bdf2070f8 100644--- a/modules/openxr/extensions/openxr_extension_wrapper.h+++ b/modules/openxr/extensions/openxr_extension_wrapper.h@@ -81,6 +81,7 @@ public:virtual void *set_system_properties_and_get_next_pointer(void *p_next_pointer); // Add additional data structures when we interrogate OpenXR's system abilities.virtual void *set_instance_create_info_and_get_next_pointer(XrVersion p_xr_version, void *p_next_pointer); // Add additional data structures when we create our OpenXR instance.virtual void *set_session_create_and_get_next_pointer(void *p_next_pointer); // Add additional data structures when we create our OpenXR session.+ virtual void *set_spatial_container_create_info_and_get_next_pointer(RID p_spatial_container, void *p_next_pointer); // Add additional data structures when we create a spatial container.virtual void *set_swapchain_create_info_and_get_next_pointer(void *p_next_pointer); // Add additional data structures when creating OpenXR swap chains.virtual void *set_hand_joint_locations_and_get_next_pointer(int p_hand_index, void *p_next_pointer);virtual void *set_projection_views_and_get_next_pointer(int p_view_index, void *p_next_pointer);@@ -88,6 +89,7 @@ public:// These will only be called for extensions registered via OpenXRApi::register_frame_info_extension().virtual void *set_frame_wait_info_and_get_next_pointer(void *p_next_pointer); // Add additional data structures when calling xrWaitFramevirtual void *set_view_locate_info_and_get_next_pointer(void *p_next_pointer); // Add additional data structures when calling xrLocateViews+ virtual void *set_spatial_container_views_locate_info_and_get_next_pointer(RID p_spatial_container, void *p_next_pointer); // Add additional data structures when calling xrLocateSpatialContainerViewsEXTvirtual void *set_frame_end_info_and_get_next_pointer(void *p_next_pointer); // Add additional data structures when calling xrEndFrame// This will only be called for extensions registered via OpenXRAPI::register_projection_layer_extension().virtual void *set_projection_layer_and_get_next_pointer(void *p_next_pointer); // Add additional data structures to XrCompositionLayerProjection@@ -108,6 +110,8 @@ public:GDVIRTUAL1R(uint64_t, _set_projection_layer_and_get_next_pointer, GDExtensionPtr<void>);GDVIRTUAL1R(uint64_t, _set_view_locate_info_and_get_next_pointer, GDExtensionPtr<void>);GDVIRTUAL2R(uint64_t, _set_reference_space_create_info_and_get_next_pointer, int, GDExtensionPtr<void>);+ GDVIRTUAL2R(uint64_t, _set_spatial_container_create_info_and_get_next_pointer, RID, GDExtensionPtr<void>);+ GDVIRTUAL2R(uint64_t, _set_spatial_container_views_locate_info_and_get_next_pointer, RID, GDExtensionPtr<void>);GDVIRTUAL0R(int, _get_composition_layer_count);GDVIRTUAL1R(uint64_t, _get_composition_layer, int);GDVIRTUAL1R(int, _get_composition_layer_order, int);diff --git a/modules/openxr/extensions/spatial_container/openxr_spatial_container_extension.cpp b/modules/openxr/extensions/spatial_container/openxr_spatial_container_extension.cppnew file mode 100644index 00000000000..9124c80f400--- /dev/null+++ b/modules/openxr/extensions/spatial_container/openxr_spatial_container_extension.cpp@@ -0,0 +1,477 @@+/**************************************************************************/+/* openxr_spatial_container_extension.cpp */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* 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. */+/**************************************************************************/++#include "openxr_spatial_container_extension.h"++#include "../../openxr_api.h"+#include "openxr_spatial_container_self_rendering_extension.h"++#include "core/config/project_settings.h"+#include "core/object/class_db.h"++OpenXRSpatialContainerExtension *OpenXRSpatialContainerExtension::singleton = nullptr;++OpenXRSpatialContainerExtension *OpenXRSpatialContainerExtension::get_singleton() {+ return singleton;+}++OpenXRSpatialContainerExtension::OpenXRSpatialContainerExtension() {+ singleton = this;+}++OpenXRSpatialContainerExtension::~OpenXRSpatialContainerExtension() {+ _cleanup();+ singleton = nullptr;+}++bool OpenXRSpatialContainerExtension::is_enabled() const {+ return spatial_container_ext && rendering_mechanism && rendering_mechanism->is_enabled();+}++bool OpenXRSpatialContainerExtension::is_spatial_container_active() const {+ return is_enabled() && spatial_container_data.spatial_container_handle != XR_NULL_HANDLE;+}++bool OpenXRSpatialContainerExtension::can_create_spatial_container() const {+ print_line("OpenXR: Max spatial container count: ", spatial_container_properties.maxSpatialContainerCount);+ return is_enabled() && spatial_container_properties.maxSpatialContainerCount > 0;+}++void OpenXRSpatialContainerExtension::_bind_methods() {+ ClassDB::bind_method(D_METHOD("is_enabled"), &OpenXRSpatialContainerExtension::is_enabled);+ ClassDB::bind_method(D_METHOD("is_spatial_container_active"), &OpenXRSpatialContainerExtension::is_spatial_container_active);+ ClassDB::bind_method(D_METHOD("get_supported_bounds_modes"), &OpenXRSpatialContainerExtension::get_supported_bounds_modes);++ ClassDB::bind_method(D_METHOD("get_spatial_container_state"), &OpenXRSpatialContainerExtension::get_spatial_container_state);+ ClassDB::bind_method(D_METHOD("get_spatial_container_bounds"), &OpenXRSpatialContainerExtension::get_spatial_container_bounds);+ ClassDB::bind_method(D_METHOD("request_spatial_container_bounds_mode", "bounds_mode"), &OpenXRSpatialContainerExtension::request_spatial_container_bounds_mode);+ ClassDB::bind_method(D_METHOD("request_spatial_container_visible", "visible"), &OpenXRSpatialContainerExtension::request_spatial_container_visible);++ ADD_SIGNAL(MethodInfo("spatial_container_bounds_changed", PropertyInfo(Variant::RID, "spatial_container_rid"), PropertyInfo(Variant::BOOL, "spatial_container_infinite_bounds"), PropertyInfo(Variant::INT, "spatial_container_bounds_mode", PROPERTY_HINT_ENUM, "Bounded,Immersive"), PropertyInfo(Variant::VECTOR3, "spatial_container_bounds")));+ ADD_SIGNAL(MethodInfo("spatial_container_bounds_mode_request_denied", PropertyInfo(Variant::RID, "spatial_container_rid")));+ ADD_SIGNAL(MethodInfo("spatial_container_closed", PropertyInfo(Variant::RID, "spatial_container_rid")));+ ADD_SIGNAL(MethodInfo("spatial_container_interactable_changed", PropertyInfo(Variant::RID, "spatial_container_rid"), PropertyInfo(Variant::BOOL, "spatial_container_interactable")));+ ADD_SIGNAL(MethodInfo("spatial_container_visible_changed", PropertyInfo(Variant::RID, "spatial_container_rid"), PropertyInfo(Variant::BOOL, "spatial_container_visible")));+ ADD_SIGNAL(MethodInfo("spatial_container_visible_request_denied", PropertyInfo(Variant::RID, "spatial_container_rid")));+}++HashMap<String, bool *> OpenXRSpatialContainerExtension::get_requested_extensions(XrVersion p_version) {+ HashMap<String, bool *> request_extensions;++ request_extensions[XR_EXT_SPATIAL_CONTAINER_EXTENSION_NAME] = &spatial_container_ext;++ return request_extensions;+}++bool OpenXRSpatialContainerExtension::_initialize_spatial_container_extension(const XrInstance &p_instance) {+ EXT_INIT_XR_FUNC_V(xrCreateSpatialContainerEXT);+ EXT_INIT_XR_FUNC_V(xrDestroySpatialContainerEXT);+ EXT_INIT_XR_FUNC_V(xrCreateSpatialContainerSpaceEXT);+ EXT_INIT_XR_FUNC_V(xrRequestSpatialContainerVisibleEXT);+ EXT_INIT_XR_FUNC_V(xrRequestSpatialContainerBoundsModeEXT);+ EXT_INIT_XR_FUNC_V(xrGetSpatialContainerBoundsEXT);+ EXT_INIT_XR_FUNC_V(xrGetSpatialContainerStateEXT);+ EXT_INIT_XR_FUNC_V(xrEnumerateSupportedSpatialContainerGraphicsPresentationsEXT);++ return true;+}++void OpenXRSpatialContainerExtension::_cleanup() {+ spatial_container_ext = false;+}++void OpenXRSpatialContainerExtension::on_instance_created(const XrInstance p_instance) {+ if (!spatial_container_ext) {+ return;+ }++ if (!_initialize_spatial_container_extension(p_instance)) {+ print_error("OpenXR: Failed to initialize spatial container extension.");+ spatial_container_ext = false;+ return;+ }++ rendering_mechanism = OpenXRSpatialContainerSelfRenderingExtension::get_singleton();+}++void OpenXRSpatialContainerExtension::on_instance_destroyed() {+ rendering_mechanism = nullptr;+}++Array OpenXRSpatialContainerExtension::get_supported_bounds_modes() {+ Array modes;++ if (spatial_container_properties.supportsBounded) {+ modes.push_back(OpenXRSpatialContainerState::BOUNDS_MODE_BOUNDED);+ }+ if (spatial_container_properties.supportsImmersive) {+ modes.push_back(OpenXRSpatialContainerState::BOUNDS_MODE_IMMERSIVE);+ }+ return modes;+}++void OpenXRSpatialContainerExtension::on_session_created(const XrSession p_session) {+ if (!can_create_spatial_container()) {+ print_verbose("OpenXR: Unable to create spatial container!");+ return;+ }++ // Retrieve the bounds from the project settings.+ Vector3 bounds = GLOBAL_GET_CACHED(Vector3, "xr/openxr/extensions/spatial_container/bounds");+ create_spatial_container(bounds);+}++void OpenXRSpatialContainerExtension::on_session_destroyed() {+ if (!can_create_spatial_container()) {+ print_verbose("OpenXR: Unable to destroy spatial container!");+ return;+ }++ destroy_spatial_container();+}++void *OpenXRSpatialContainerExtension::set_session_create_and_get_next_pointer(void *p_next_pointer) {+ if (!is_enabled()) {+ return p_next_pointer;+ }++ session_create_info.next = p_next_pointer;+ return &session_create_info;+}++void *OpenXRSpatialContainerExtension::set_system_properties_and_get_next_pointer(void *p_next_pointer) {+ if (!is_enabled()) {+ return p_next_pointer;+ }++ spatial_container_properties.next = p_next_pointer;+ return &spatial_container_properties;+}++bool OpenXRSpatialContainerExtension::on_event_polled(const XrEventDataBuffer &event) {+ if (!is_enabled()) {+ return false;+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL_V(openxr_api, false);++ switch ((int)event.type) {+ case XR_TYPE_EVENT_DATA_SPATIAL_CONTAINER_BOUNDS_CHANGED_EXT: {+ const XrEventDataSpatialContainerBoundsChangedEXT *event_data = (XrEventDataSpatialContainerBoundsChangedEXT *)&event;+ if (event_data->spatialContainer == spatial_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container bounds changed...");+ emit_signal(SNAME("spatial_container_bounds_changed"), spatial_container_data.spatial_container_rid, event_data->infiniteBounds, OpenXRSpatialContainerState::_to_bounds_mode(event_data->boundsMode), Vector3(event_data->bounds.width, event_data->bounds.height, event_data->bounds.depth));+ return true;+ }+ return false;+ } break;++ case XR_TYPE_EVENT_DATA_SPATIAL_CONTAINER_BOUNDS_MODE_REQUEST_DENIED_EXT: {+ const XrEventDataSpatialContainerBoundsModeRequestDeniedEXT *event_data = (XrEventDataSpatialContainerBoundsModeRequestDeniedEXT *)&event;+ if (event_data->spatialContainer == spatial_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container bounds mode request denied...");+ emit_signal(SNAME("spatial_container_bounds_mode_request_denied"), spatial_container_data.spatial_container_rid);+ return true;+ }+ return false;+ } break;++ case XR_TYPE_EVENT_DATA_SPATIAL_CONTAINER_CLOSED_EXT: {+ const XrEventDataSpatialContainerClosedEXT *event_data = (XrEventDataSpatialContainerClosedEXT *)&event;+ if (event_data->spatialContainer == spatial_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container closed...");+ emit_signal(SNAME("spatial_container_closed"), spatial_container_data.spatial_container_rid);++ // Backward compatibility logic.+ openxr_api->on_state_exiting();++ destroy_spatial_container();+ return true;+ }+ return false;+ } break;++ case XR_TYPE_EVENT_DATA_SPATIAL_CONTAINER_INTERACTABLE_CHANGED_EXT: {+ const XrEventDataSpatialContainerInteractableChangedEXT *event_data = (XrEventDataSpatialContainerInteractableChangedEXT *)&event;+ if (event_data->spatialContainer == spatial_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container interactability changed...");+ emit_signal(SNAME("spatial_container_interactable_changed"), spatial_container_data.spatial_container_rid, event_data->interactable);++ // Backward compatibility logic.+ // TODO: When we add support for multiple spatial containers within a session, this will need to be revisited as follow:+ // - Switch to state focused when AT LEAST ONE spatial container is interactable+ // - Switch to state visible when NONE of the spatial containers are interactable+ if (event_data->interactable) {+ openxr_api->on_state_focused();+ } else {+ openxr_api->on_state_visible();+ }+ return true;+ }+ return false;+ } break;++ case XR_TYPE_EVENT_DATA_SPATIAL_CONTAINER_VISIBLE_CHANGED_EXT: {+ const XrEventDataSpatialContainerVisibleChangedEXT *event_data = (XrEventDataSpatialContainerVisibleChangedEXT *)&event;+ if (event_data->spatialContainer == spatial_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container visibility changed...");+ emit_signal(SNAME("spatial_container_visible_changed"), spatial_container_data.spatial_container_rid, event_data->visible);++ if (rendering_mechanism) {+ rendering_mechanism->on_spatial_container_visibility_changed(spatial_container_data, event_data->visible);+ }++ // Backward compatibility logic.+ // TODO: When we add support for multiple spatial containers within a session, this will need to be revisited as follow:+ // - Switch to state visible when AT LEAST ONE spatial container is visible+ // - Switch to state synchronized when NONE of the spatial containers are visible+ if (event_data->visible) {+ openxr_api->on_state_visible();+ } else {+ openxr_api->on_state_synchronized();+ }+ return true;+ }+ return false;+ } break;++ case XR_TYPE_EVENT_DATA_SPATIAL_CONTAINER_VISIBLE_REQUEST_DENIED_EXT: {+ const XrEventDataSpatialContainerVisibleRequestDeniedEXT *event_data = (XrEventDataSpatialContainerVisibleRequestDeniedEXT *)&event;+ if (event_data->spatialContainer == spatial_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container visibility request denied...");+ emit_signal(SNAME("spatial_container_visible_request_denied"), spatial_container_data.spatial_container_rid);+ return true;+ }+ return false;+ } break;++ default: {+ return false;+ } break;+ }+}++void OpenXRSpatialContainerExtension::on_state_loss_pending() {+ if (!is_enabled()) {+ return;+ }++ destroy_spatial_container();+}++Ref<OpenXRSpatialContainerState> OpenXRSpatialContainerExtension::get_spatial_container_state() {+ Ref<OpenXRSpatialContainerState> container_state;+ if (!is_spatial_container_active()) {+ return container_state;+ }++ print_verbose("OpenXR: Retrieving Spatial container state...");+ XrSpatialContainerStateGetInfoEXT get_info = {+ XR_TYPE_SPATIAL_CONTAINER_STATE_GET_INFO_EXT, // type+ nullptr, // next+ };+ XrSpatialContainerStateEXT state = {+ XR_TYPE_SPATIAL_CONTAINER_STATE_EXT, // type+ nullptr, // next+ false, // visible+ false, // anyInteractable+ XR_SPATIAL_CONTAINER_BOUNDS_MODE_MAX_ENUM_EXT // boundsMode+ };+ XrResult result = xrGetSpatialContainerStateEXT(spatial_container_data.spatial_container_handle, &get_info, &state);+ ERR_FAIL_COND_V_MSG(XR_FAILED(result), container_state, vformat("Failed to retrieve spatial container state: %d", result));++ container_state.instantiate(state);+ return container_state;+}++Vector3 OpenXRSpatialContainerExtension::get_spatial_container_bounds() {+ if (!is_spatial_container_active()) {+ return Vector3();+ }++ print_verbose("OpenXR: Retrieving spatial container bounds...");+ XrSpatialContainerBoundsGetInfoEXT bounds_get_info = {+ XR_TYPE_SPATIAL_CONTAINER_BOUNDS_GET_INFO_EXT, // type+ nullptr, // next+ };+ XrSpatialContainerBoundsEXT bounds = {+ XR_TYPE_SPATIAL_CONTAINER_BOUNDS_EXT, // type+ nullptr, // next+ { 0.0, 0.0, 0.0 }, // bounds+ false, // infiniteBounds+ };+ XrResult result = xrGetSpatialContainerBoundsEXT(spatial_container_data.spatial_container_handle, &bounds_get_info, &bounds);+ ERR_FAIL_COND_V_MSG(XR_FAILED(result), Vector3(), "Failed to retrieve spatial container bounds.");++ return Vector3(bounds.bounds.width, bounds.bounds.height, bounds.bounds.depth);+}++bool OpenXRSpatialContainerExtension::request_spatial_container_bounds_mode(OpenXRSpatialContainerState::BoundsMode p_mode) {+ if (!is_spatial_container_active()) {+ return false;+ }++ // Is bounds mode supported?+ if (p_mode == OpenXRSpatialContainerState::BOUNDS_MODE_BOUNDED && !spatial_container_properties.supportsBounded) {+ ERR_FAIL_V_MSG(false, "Bounded mode is not supported.");+ }+ if (p_mode == OpenXRSpatialContainerState::BOUNDS_MODE_IMMERSIVE && !spatial_container_properties.supportsImmersive) {+ ERR_FAIL_V_MSG(false, "Immersive mode is not supported.");+ }++ XrSpatialContainerBoundsModeRequestInfoEXT request_info = {+ XR_TYPE_SPATIAL_CONTAINER_BOUNDS_MODE_REQUEST_INFO_EXT, // type+ nullptr, // next+ OpenXRSpatialContainerState::_from_bounds_mode(p_mode), // boundsMode+ };+ XrResult result = xrRequestSpatialContainerBoundsModeEXT(spatial_container_data.spatial_container_handle, &request_info);+ ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed requesting bounds mode update.");++ return true;+}++XrResult OpenXRSpatialContainerExtension::locate_spatial_container_views(XrView *p_views, bool &r_view_pose_valid, bool &r_should_submit_layers) {+ if (!is_spatial_container_active()) {+ return XR_ERROR_INITIALIZATION_FAILED;+ }++ return rendering_mechanism->locate_spatial_container_views(spatial_container_data.spatial_container_rid, p_views, r_view_pose_valid, r_should_submit_layers);+}++bool OpenXRSpatialContainerExtension::request_spatial_container_visible(bool p_visible) {+ if (!is_spatial_container_active()) {+ return false;+ }++ XrSpatialContainerVisibleRequestInfoEXT request_info = {+ XR_TYPE_SPATIAL_CONTAINER_VISIBLE_REQUEST_INFO_EXT, // type+ nullptr, // next+ p_visible, // visible+ };+ XrResult result = xrRequestSpatialContainerVisibleEXT(spatial_container_data.spatial_container_handle, &request_info);+ ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed requesting visibility update.");++ return true;+}++void OpenXRSpatialContainerExtension::create_spatial_container(Vector3 p_suggested_bounds) {+ if (!can_create_spatial_container()) {+ ERR_FAIL_MSG("OpenXR: Unable to create spatial container!");+ }++ if (is_spatial_container_active()) {+ ERR_FAIL_MSG("OpenXR: Spatial container is already active.");+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL(openxr_api);+ const XrSession session = openxr_api->get_session();++ print_verbose("OpenXR: Creating spatial container...");++ // Store this as a RID so we can keep track of it.+ spatial_container_data.spatial_container_rid = spatial_container_owner.make_rid(spatial_container_data);++ void *create_info_next_pointer = nullptr;+ for (OpenXRExtensionWrapper *extension : openxr_api->get_registered_extension_wrappers()) {+ void *np = extension->set_spatial_container_create_info_and_get_next_pointer(spatial_container_data.spatial_container_rid, create_info_next_pointer);+ if (np != nullptr) {+ create_info_next_pointer = np;+ }+ }++ XrSpatialContainerCreateInfoEXT create_info = {+ XR_TYPE_SPATIAL_CONTAINER_CREATE_INFO_EXT, // type+ create_info_next_pointer, // next+ rendering_mechanism->get_spatial_container_graphics_presentation(), // graphicsPresentation+ { (float)p_suggested_bounds.x, (float)p_suggested_bounds.y, (float)p_suggested_bounds.z } // suggestedBounds+ };+ XrResult result = xrCreateSpatialContainerEXT(session, &create_info, &spatial_container_data.spatial_container_handle);+ if (XR_FAILED(result)) {+ ERR_PRINT("OpenXR: Failed to create spatial container.");+ destroy_spatial_container();+ return;+ }++ print_verbose("OpenXR: Creating spatial container space...");+ XrSpatialContainerSpaceCreateInfoEXT space_create_info = {+ XR_TYPE_SPATIAL_CONTAINER_SPACE_CREATE_INFO_EXT, // type+ nullptr, // next+ spatial_container_data.spatial_container_handle // spatialContainer+ };+ result = xrCreateSpatialContainerSpaceEXT(session, &space_create_info, &spatial_container_data.space_handle);+ if (XR_FAILED(result)) {+ ERR_PRINT("OpenXR: Failed to create spatial container space.. Destroying spatial container.");+ destroy_spatial_container();+ return;+ }++ openxr_api->set_custom_play_space(spatial_container_data.space_handle);++ print_verbose("OpenXR: Updating spatial container bounds mode...");+ OpenXRSpatialContainerState::BoundsMode bounds_mode = (OpenXRSpatialContainerState::BoundsMode)GLOBAL_GET_CACHED(int, "xr/openxr/extensions/spatial_container/bounds_mode");+ if (!request_spatial_container_bounds_mode(bounds_mode)) {+ ERR_PRINT("OpenXR: Failed updating spatial container bounds mode.");+ }++ print_verbose("OpenXR: Updating spatial container visibility...");+ if (!request_spatial_container_visible(true)) {+ ERR_PRINT("OpenXR: Failed updating spatial container visibility.");+ }++ if (rendering_mechanism) {+ rendering_mechanism->on_spatial_container_created(spatial_container_data);+ }+}++void OpenXRSpatialContainerExtension::destroy_spatial_container() {+ if (is_spatial_container_active()) {+ request_spatial_container_visible(false);+ // TODO: Ideally we should wait until the visibility request has been honored before continuing with the logic below.++ if (rendering_mechanism) {+ rendering_mechanism->on_spatial_container_closed(spatial_container_data);+ }++ ERR_FAIL_NULL(OpenXRAPI::get_singleton());+ OpenXRAPI::get_singleton()->set_custom_play_space(XR_NULL_HANDLE);++ print_verbose("OpenXR: Destroying spatial container...");+ XrResult result = xrDestroySpatialContainerEXT(spatial_container_data.spatial_container_handle);+ ERR_FAIL_COND_MSG(XR_FAILED(result), "Failed to destroy spatial container.");++ spatial_container_data.spatial_container_handle = XR_NULL_HANDLE;+ spatial_container_data.space_handle = XR_NULL_HANDLE;++ spatial_container_owner.free(spatial_container_data.spatial_container_rid);+ spatial_container_data.spatial_container_rid = RID();+ }+}diff --git a/modules/openxr/extensions/spatial_container/openxr_spatial_container_extension.h b/modules/openxr/extensions/spatial_container/openxr_spatial_container_extension.hnew file mode 100644index 00000000000..1209c423880--- /dev/null+++ b/modules/openxr/extensions/spatial_container/openxr_spatial_container_extension.h@@ -0,0 +1,149 @@+/**************************************************************************/+/* openxr_spatial_container_extension.h */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* 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. */+/**************************************************************************/++#pragma once++#include "../../openxr_util.h"+#include "../../util.h"+#include "../openxr_extension_wrapper.h"+#include "openxr_spatial_container_state.h"++#include "core/templates/rid_owner.h"++#include <openxr/openxr.h>++class OpenXRSpatialContainerSelfRenderingExtension;++// Spatial container extension+class OpenXRSpatialContainerExtension : public OpenXRExtensionWrapper {+ GDCLASS(OpenXRSpatialContainerExtension, OpenXRExtensionWrapper);++public:+ struct SpatialContainerData {+ RID spatial_container_rid = RID();+ XrSpatialContainerEXT spatial_container_handle = XR_NULL_HANDLE;+ XrSpace space_handle = XR_NULL_HANDLE;+ };++ static OpenXRSpatialContainerExtension *get_singleton();++ OpenXRSpatialContainerExtension();+ virtual ~OpenXRSpatialContainerExtension() override;++ virtual HashMap<String, bool *> get_requested_extensions(XrVersion p_version) override;++ virtual void on_instance_created(const XrInstance p_instance) override;+ virtual void on_instance_destroyed() override;+ virtual void on_session_created(const XrSession p_session) override;+ virtual void on_session_destroyed() override;+ virtual bool on_event_polled(const XrEventDataBuffer &event) override;+ virtual void on_state_loss_pending() override;++ virtual void *set_session_create_and_get_next_pointer(void *p_next_pointer) override;+ virtual void *set_system_properties_and_get_next_pointer(void *p_next_pointer) override;++ bool is_enabled() const;++ bool is_spatial_container_active() const;++ Array get_supported_bounds_modes();++ Ref<OpenXRSpatialContainerState> get_spatial_container_state();+ Vector3 get_spatial_container_bounds();+ bool request_spatial_container_bounds_mode(OpenXRSpatialContainerState::BoundsMode p_mode);+ bool request_spatial_container_visible(bool p_visible);++ XrResult locate_spatial_container_views(XrView *p_views, bool &r_view_pose_valid, bool &r_should_submit_layers);++protected:+ static void _bind_methods();++private:+ // OpenXR API call wrappers+ EXT_PROTO_XRRESULT_FUNC3(xrCreateSpatialContainerEXT,+ (XrSession), session,+ (const XrSpatialContainerCreateInfoEXT *), create_info,+ (XrSpatialContainerEXT *), spatial_container);+ EXT_PROTO_XRRESULT_FUNC1(xrDestroySpatialContainerEXT,+ (XrSpatialContainerEXT), spatial_container);+ EXT_PROTO_XRRESULT_FUNC3(xrCreateSpatialContainerSpaceEXT,+ (XrSession), session,+ (const XrSpatialContainerSpaceCreateInfoEXT *), create_info,+ (XrSpace *), space);+ EXT_PROTO_XRRESULT_FUNC2(xrRequestSpatialContainerVisibleEXT,+ (XrSpatialContainerEXT), spatial_container,+ (const XrSpatialContainerVisibleRequestInfoEXT *), info);+ EXT_PROTO_XRRESULT_FUNC2(xrRequestSpatialContainerBoundsModeEXT,+ (XrSpatialContainerEXT), spatial_container,+ (const XrSpatialContainerBoundsModeRequestInfoEXT *), info);+ EXT_PROTO_XRRESULT_FUNC3(xrGetSpatialContainerBoundsEXT,+ (XrSpatialContainerEXT), spatial_container,+ (const XrSpatialContainerBoundsGetInfoEXT *), get_info,+ (XrSpatialContainerBoundsEXT *), bounds);+ EXT_PROTO_XRRESULT_FUNC3(xrGetSpatialContainerStateEXT,+ (XrSpatialContainerEXT), spatial_container,+ (const XrSpatialContainerStateGetInfoEXT *), get_info,+ (XrSpatialContainerStateEXT *), state);+ EXT_PROTO_XRRESULT_FUNC5(xrEnumerateSupportedSpatialContainerGraphicsPresentationsEXT,+ (XrInstance), instance,+ (XrSystemId), system_id,+ (uint32_t), graphics_presentation_capacity_input,+ (uint32_t *), graphics_presentation_count_output,+ (XrSpatialContainerGraphicsPresentationEXT *), graphics_presentations);++ bool can_create_spatial_container() const;++ void create_spatial_container(Vector3 p_suggested_bounds);+ void destroy_spatial_container();+ void _cleanup();++ mutable RID_Owner<SpatialContainerData> spatial_container_owner;++ bool _initialize_spatial_container_extension(const XrInstance &p_instance);++ static OpenXRSpatialContainerExtension *singleton;++ bool spatial_container_ext = false;+ XrSessionCreateInfoSpatialContainersEXT session_create_info = {+ XR_TYPE_SESSION_CREATE_INFO_SPATIAL_CONTAINERS_EXT, // type+ nullptr, // next+ };+ XrSystemSpatialContainerPropertiesEXT spatial_container_properties = {+ XR_TYPE_SYSTEM_SPATIAL_CONTAINER_PROPERTIES_EXT, // type+ nullptr, // next+ 0, // maxSpatialContainerCount+ XR_FALSE, // supportsBounded+ XR_FALSE, // supportsImmersive+ };+ SpatialContainerData spatial_container_data;++ // TODO: For now we are hardcoding self rendering as the rendering mechanism.+ OpenXRSpatialContainerSelfRenderingExtension *rendering_mechanism = nullptr;+};diff --git a/modules/openxr/extensions/spatial_container/openxr_spatial_container_self_rendering_extension.cpp b/modules/openxr/extensions/spatial_container/openxr_spatial_container_self_rendering_extension.cppnew file mode 100644index 00000000000..0b72eff072d--- /dev/null+++ b/modules/openxr/extensions/spatial_container/openxr_spatial_container_self_rendering_extension.cpp@@ -0,0 +1,324 @@+/**************************************************************************/+/* openxr_spatial_container_self_rendering_extension.cpp */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* 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. */+/**************************************************************************/++#include "openxr_spatial_container_self_rendering_extension.h"++#include "../../openxr_api.h"++#include "core/object/class_db.h"++OpenXRSpatialContainerSelfRenderingExtension *OpenXRSpatialContainerSelfRenderingExtension::singleton = nullptr;++OpenXRSpatialContainerSelfRenderingExtension *OpenXRSpatialContainerSelfRenderingExtension::get_singleton() {+ return singleton;+}++OpenXRSpatialContainerSelfRenderingExtension::OpenXRSpatialContainerSelfRenderingExtension() {+ singleton = this;+}++OpenXRSpatialContainerSelfRenderingExtension::~OpenXRSpatialContainerSelfRenderingExtension() {+ _cleanup();+ singleton = nullptr;+}++void OpenXRSpatialContainerSelfRenderingExtension::_bind_methods() {+ ClassDB::bind_method(D_METHOD("is_enabled"), &OpenXRSpatialContainerSelfRenderingExtension::is_enabled);+}++bool OpenXRSpatialContainerSelfRenderingExtension::is_enabled() const {+ return spatial_container_self_rendering_ext;+}++XrSpatialContainerGraphicsPresentationEXT OpenXRSpatialContainerSelfRenderingExtension::get_spatial_container_graphics_presentation() const {+ return XR_SPATIAL_CONTAINER_GRAPHICS_PRESENTATION_SELF_RENDERING_EXT;+}++HashMap<String, bool *> OpenXRSpatialContainerSelfRenderingExtension::get_requested_extensions(XrVersion p_version) {+ HashMap<String, bool *> request_extensions;++ request_extensions[XR_EXT_SPATIAL_CONTAINER_SELF_RENDERING_EXTENSION_NAME] = &spatial_container_self_rendering_ext;+ return request_extensions;+}++bool OpenXRSpatialContainerSelfRenderingExtension::_initialize_spatial_container_self_rendering_extension(const XrInstance &p_instance) {+ EXT_INIT_XR_FUNC_V(xrBeginSpatialContainerRenderingEXT);+ EXT_INIT_XR_FUNC_V(xrEndSpatialContainerRenderingEXT);+ EXT_INIT_XR_FUNC_V(xrLocateSpatialContainerViewsEXT);++ return true;+}++void OpenXRSpatialContainerSelfRenderingExtension::_cleanup() {+ spatial_container_self_rendering_ext = false;+}++void OpenXRSpatialContainerSelfRenderingExtension::on_instance_created(const XrInstance p_instance) {+ if (!spatial_container_self_rendering_ext) {+ return;+ }++ if (!_initialize_spatial_container_self_rendering_extension(p_instance)) {+ print_error("OpenXR: Failed to initialize spatial container self rendering extension");+ spatial_container_self_rendering_ext = false;+ }+}++void OpenXRSpatialContainerSelfRenderingExtension::on_session_created(const XrSession p_session) {+ if (!is_enabled()) {+ return;+ }++ ERR_FAIL_NULL(OpenXRAPI::get_singleton());+ OpenXRAPI::get_singleton()->register_frame_info_extension(this);+ OpenXRAPI::get_singleton()->register_projection_layer_extension(this);+}++void OpenXRSpatialContainerSelfRenderingExtension::on_session_destroyed() {+ if (!is_enabled()) {+ return;+ }++ ERR_FAIL_NULL(OpenXRAPI::get_singleton());+ OpenXRAPI::get_singleton()->unregister_frame_info_extension(this);+ OpenXRAPI::get_singleton()->unregister_projection_layer_extension(this);+}++void OpenXRSpatialContainerSelfRenderingExtension::on_process() {+ if (!is_enabled()) {+ return;+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL(openxr_api);++ if (openxr_api->is_running() && has_pending_container) {+ print_verbose("OpenXR: Adding pending container to render set...");+ _add_spatial_container_to_render_set(pending_container_data);+ }+}++void OpenXRSpatialContainerSelfRenderingExtension::on_spatial_container_created(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container_data) {+ if (!is_enabled()) {+ return;+ }++ _add_spatial_container_to_render_set(p_container_data);+}++void OpenXRSpatialContainerSelfRenderingExtension::on_spatial_container_visibility_changed(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container_data, bool p_visible) {+ if (!is_enabled()) {+ return;+ }++ if (p_visible) {+ _add_spatial_container_to_render_set(p_container_data);+ } else {+ _remove_spatial_container_from_render_set(p_container_data.spatial_container_handle);+ }+}++void OpenXRSpatialContainerSelfRenderingExtension::on_spatial_container_closed(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container_data) {+ if (!is_enabled()) {+ return;+ }++ _remove_spatial_container_from_render_set(p_container_data.spatial_container_handle);+}++void OpenXRSpatialContainerSelfRenderingExtension::_add_spatial_container_to_render_set(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container_data) {+ // Check if the spatial container is already part of the active render set.+ if (active_spatial_container == p_container_data.spatial_container_handle) {+ print_verbose("OpenXR: Spatial container is already part of the active render set.");+ return;+ }++ pending_container_data = p_container_data;+ has_pending_container = true;++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL(openxr_api);+ if (!openxr_api->is_running()) {+ print_verbose("OpenXR: Session is not running yet...");+ return;+ }+ const XrSession session = openxr_api->get_session();++ if (active_spatial_container != XR_NULL_HANDLE) {+ // Shouldn't happen, but in case it does...+ print_verbose("OpenXR: Pre-existing active spatial container. Cleaning it up.");+ _remove_spatial_container_from_render_set(active_spatial_container);+ }++ XrSpatialContainerBeginInfoEXT begin_info = {+ XR_TYPE_SPATIAL_CONTAINER_BEGIN_INFO_EXT, // type+ nullptr, // next+ p_container_data.spatial_container_handle, // spatialContainer+ openxr_api->get_view_configuration() // primaryViewConfigurationType+ };+ XrResult result = xrBeginSpatialContainerRenderingEXT(session, &begin_info);+ if (XR_FAILED(result)) {+ ERR_PRINT("OpenXR: Failed to begin spatial container rendering.");+ has_pending_container = false;+ return;+ }++ has_pending_container = false;++ // Add the spatial container to the active render set.+ print_verbose("OpenXR: Setting active spatial container.");+ active_spatial_container = p_container_data.spatial_container_handle;++ active_view_locate_info.viewConfigurationType = openxr_api->get_view_configuration();+ active_view_locate_info.space = p_container_data.space_handle;+ active_view_locate_info.spatialContainer = active_spatial_container;++ active_view_state.viewConfigurationType = openxr_api->get_view_configuration();++ active_layer.spatialContainer = active_spatial_container;+}++void OpenXRSpatialContainerSelfRenderingExtension::_remove_spatial_container_from_render_set(const XrSpatialContainerEXT &p_container) {+ // Check if the spatial container is in the active render set.+ if (active_spatial_container != p_container) {+ print_verbose("OpenXR: Spatial container is not part of the active render set.");+ return;+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL(openxr_api);+ const XrSession session = openxr_api->get_session();++ XrSpatialContainerEndInfoEXT end_info = {+ XR_TYPE_SPATIAL_CONTAINER_END_INFO_EXT, // type+ nullptr, // next+ p_container, // spatialContainer+ };+ XrResult result = xrEndSpatialContainerRenderingEXT(session, &end_info);+ if (XR_FAILED(result)) {+ ERR_PRINT("OpenXR: Failed to end spatial container rendering.");+ return;+ }++ // Reset the active spatial container.+ print_verbose("OpenXR: Resetting active spatial container.");+ active_spatial_container = XR_NULL_HANDLE;++ active_view_locate_info.viewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;+ active_view_locate_info.space = XR_NULL_HANDLE;+ active_view_locate_info.spatialContainer = XR_NULL_HANDLE;++ active_view_state.viewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;+ active_view_state.viewStateFlags = 0;+ active_view_state.shouldSubmitLayers = false;+ active_view_state.recommendedImageExtent = { 0, 0 };++ active_layer.spatialContainer = XR_NULL_HANDLE;+ active_layer.retainPreviousSubmission = false;+ active_layer.layerCount = 0;+ active_layer.layers = nullptr;+}++void *OpenXRSpatialContainerSelfRenderingExtension::set_frame_end_info_and_get_next_pointer(void *p_next_pointer) {+ if (!is_enabled() || active_spatial_container == XR_NULL_HANDLE) {+ return p_next_pointer;+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL_V(openxr_api, p_next_pointer);++ if (active_view_state.shouldSubmitLayers) {+ submit_layers[0] = reinterpret_cast<const XrCompositionLayerBaseHeader *>(openxr_api->get_projection_layer());+ active_layer.layerCount = 1;+ active_layer.layers = submit_layers;+ } else {+ active_layer.layerCount = 0;+ active_layer.layers = nullptr;+ }++ // Update the container layers.+ frame_end_info.containerLayerCount = 1;+ frame_end_info.containerLayers = &active_layer;++ frame_end_info.next = p_next_pointer;+ return &frame_end_info;+}++void *OpenXRSpatialContainerSelfRenderingExtension::set_projection_layer_and_get_next_pointer(void *p_next_pointer) {+ if (!is_enabled() || active_spatial_container == XR_NULL_HANDLE) {+ return p_next_pointer;+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL_V(openxr_api, p_next_pointer);++ container_view_config.viewConfigurationType = openxr_api->get_view_configuration();+ container_view_config.next = p_next_pointer;+ return &container_view_config;+}++XrResult OpenXRSpatialContainerSelfRenderingExtension::locate_spatial_container_views(RID p_spatial_container_rid, XrView *p_views, bool &r_view_pose_valid, bool &r_should_submit_layers) {+ if (!is_enabled() || active_spatial_container == XR_NULL_HANDLE) {+ return XR_ERROR_INITIALIZATION_FAILED;+ }++ OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();+ ERR_FAIL_NULL_V(openxr_api, XR_ERROR_VALIDATION_FAILURE);+ const XrSession session = openxr_api->get_session();++ void *spatial_container_views_locate_info_next_pointer = nullptr;+ for (OpenXRExtensionWrapper *extension : openxr_api->frame_info_extensions) {+ void *np = extension->set_spatial_container_views_locate_info_and_get_next_pointer(p_spatial_container_rid, spatial_container_views_locate_info_next_pointer);+ if (np != nullptr) {+ spatial_container_views_locate_info_next_pointer = np;+ }+ }++ XrSpatialContainerViewsLocateInfoEXT locate_info = {+ XR_TYPE_SPATIAL_CONTAINER_VIEWS_LOCATE_INFO_EXT, // type+ spatial_container_views_locate_info_next_pointer, // next+ openxr_api->get_predicted_display_time(), // displayTime+ 1, // viewLocateInfoCount+ &active_view_locate_info, // viewLocateInfos+ };++ uint32_t total_view_count = openxr_api->get_view_count();++ XrResult result = xrLocateSpatialContainerViewsEXT(session, &locate_info, 1, &active_view_state, total_view_count, p_views);+ if (XR_FAILED(result)) {+ ERR_FAIL_V_MSG(result, "OpenXR: Couldn't locate spatial container views [" + openxr_api->get_error_string(result) + "]");+ }++ r_should_submit_layers = active_view_state.shouldSubmitLayers;+ r_view_pose_valid = !((active_view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||+ (active_view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0);++ return result;+}diff --git a/modules/openxr/extensions/spatial_container/openxr_spatial_container_self_rendering_extension.h b/modules/openxr/extensions/spatial_container/openxr_spatial_container_self_rendering_extension.hnew file mode 100644index 00000000000..9f224eb213d--- /dev/null+++ b/modules/openxr/extensions/spatial_container/openxr_spatial_container_self_rendering_extension.h@@ -0,0 +1,140 @@+/**************************************************************************/+/* openxr_spatial_container_self_rendering_extension.h */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* 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. */+/**************************************************************************/++#pragma once++#include "../../openxr_util.h"+#include "../../util.h"+#include "../openxr_extension_wrapper.h"+#include "openxr_spatial_container_extension.h"+#include "openxr_spatial_container_state.h"++#include <openxr/openxr.h>++// Spatial container self rendering extension+class OpenXRSpatialContainerSelfRenderingExtension : public OpenXRExtensionWrapper {+ GDCLASS(OpenXRSpatialContainerSelfRenderingExtension, OpenXRExtensionWrapper);++public:+ static OpenXRSpatialContainerSelfRenderingExtension *get_singleton();++ OpenXRSpatialContainerSelfRenderingExtension();+ virtual ~OpenXRSpatialContainerSelfRenderingExtension() override;++ virtual HashMap<String, bool *> get_requested_extensions(XrVersion p_version) override;++ virtual void on_instance_created(const XrInstance p_instance) override;+ virtual void on_session_created(const XrSession p_session) override;+ virtual void on_session_destroyed() override;+ virtual void on_process() override;++ virtual void *set_frame_end_info_and_get_next_pointer(void *p_next_pointer) override;+ virtual void *set_projection_layer_and_get_next_pointer(void *p_next_pointer) override;++ bool is_enabled() const;++ // Spatial container rendering mechanism APIs.+ void on_spatial_container_created(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container_data);+ void on_spatial_container_visibility_changed(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container, bool p_visible);+ void on_spatial_container_closed(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container);+ XrSpatialContainerGraphicsPresentationEXT get_spatial_container_graphics_presentation() const;+ XrResult locate_spatial_container_views(RID p_spatial_container_rid, XrView *p_views, bool &r_view_pose_valid, bool &r_should_submit_layers);++protected:+ static void _bind_methods();++private:+ // OpenXR API call wrappers+ EXT_PROTO_XRRESULT_FUNC2(xrBeginSpatialContainerRenderingEXT,+ (XrSession), session,+ (const XrSpatialContainerBeginInfoEXT *), begin_info);+ EXT_PROTO_XRRESULT_FUNC2(xrEndSpatialContainerRenderingEXT,+ (XrSession), session,+ (const XrSpatialContainerEndInfoEXT *), end_info);+ EXT_PROTO_XRRESULT_FUNC6(xrLocateSpatialContainerViewsEXT,+ (XrSession), session,+ (const XrSpatialContainerViewsLocateInfoEXT *), locate_info,+ (uint32_t), view_state_count,+ (XrSpatialContainerViewStateEXT *), view_states,+ (uint32_t), view_count,+ (XrView *), views);++ void _add_spatial_container_to_render_set(const OpenXRSpatialContainerExtension::SpatialContainerData &p_container_data);+ void _remove_spatial_container_from_render_set(const XrSpatialContainerEXT &p_container);+ void _cleanup();++ bool _initialize_spatial_container_self_rendering_extension(const XrInstance &p_instance);++ static OpenXRSpatialContainerSelfRenderingExtension *singleton;++ bool spatial_container_self_rendering_ext = false;++ XrSpatialContainerEXT active_spatial_container = XR_NULL_HANDLE;+ XrSpatialContainerViewLocateInfoEXT active_view_locate_info = {+ XR_TYPE_SPATIAL_CONTAINER_VIEW_LOCATE_INFO_EXT, // type+ nullptr, // next+ XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, // viewConfigurationType+ XR_NULL_HANDLE, // space+ XR_NULL_HANDLE, // spatialContainer+ };+ XrSpatialContainerViewStateEXT active_view_state = {+ XR_TYPE_SPATIAL_CONTAINER_VIEW_STATE_EXT, // type+ nullptr, // next+ 0, // viewStateFlags+ XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, // viewConfigurationType+ false, // shouldSubmitLayers+ { 0, 0 }, // recommendedImageExtent+ };+ XrSpatialContainerLayerEXT active_layer = {+ XR_TYPE_SPATIAL_CONTAINER_LAYER_EXT, // type+ nullptr, // next+ XR_NULL_HANDLE, // spatialContainer+ false, // retainPreviousSubmission+ 0, // layerCount+ nullptr, // layers+ };++ XrSpatialContainerLayerFrameEndInfoEXT frame_end_info = {+ XR_TYPE_SPATIAL_CONTAINER_LAYER_FRAME_END_INFO_EXT, // type+ nullptr, // next+ 0, // containerLayerCount+ nullptr // containerLayers+ };++ XrSpatialContainerCompositionLayerViewConfigurationEXT container_view_config = {+ XR_TYPE_SPATIAL_CONTAINER_COMPOSITION_LAYER_VIEW_CONFIGURATION_EXT, // type+ nullptr, // next+ XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, // viewConfigurationType+ };++ OpenXRSpatialContainerExtension::SpatialContainerData pending_container_data;+ bool has_pending_container = false;+ const XrCompositionLayerBaseHeader *submit_layers[1] = { nullptr };+};diff --git a/modules/openxr/extensions/spatial_container/openxr_spatial_container_state.cpp b/modules/openxr/extensions/spatial_container/openxr_spatial_container_state.cppnew file mode 100644index 00000000000..8e22867579f--- /dev/null+++ b/modules/openxr/extensions/spatial_container/openxr_spatial_container_state.cpp@@ -0,0 +1,84 @@+/**************************************************************************/+/* openxr_spatial_container_state.cpp */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* 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. */+/**************************************************************************/++#include "openxr_spatial_container_state.h"++#include "core/object/class_db.h"++OpenXRSpatialContainerState::OpenXRSpatialContainerState(const XrSpatialContainerStateEXT &p_state) {+ bounds_mode = _to_bounds_mode(p_state.boundsMode);+ interactable = p_state.interactable;+ visible = p_state.visible;+}++void OpenXRSpatialContainerState::_bind_methods() {+ ClassDB::bind_method(D_METHOD("get_bounds_mode"), &OpenXRSpatialContainerState::get_bounds_mode);+ ClassDB::bind_method(D_METHOD("is_interactable"), &OpenXRSpatialContainerState::is_interactable);+ ClassDB::bind_method(D_METHOD("is_visible"), &OpenXRSpatialContainerState::is_visible);++ BIND_ENUM_CONSTANT(BOUNDS_MODE_BOUNDED);+ BIND_ENUM_CONSTANT(BOUNDS_MODE_IMMERSIVE);+}++OpenXRSpatialContainerState::BoundsMode OpenXRSpatialContainerState::get_bounds_mode() const {+ return bounds_mode;+}++bool OpenXRSpatialContainerState::is_interactable() const {+ return interactable;+}++bool OpenXRSpatialContainerState::is_visible() const {+ return visible;+}++XrSpatialContainerBoundsModeEXT OpenXRSpatialContainerState::_from_bounds_mode(OpenXRSpatialContainerState::BoundsMode p_mode) {+ switch (p_mode) {+ case BOUNDS_MODE_BOUNDED:+ default: {+ return XR_SPATIAL_CONTAINER_BOUNDS_MODE_BOUNDED_EXT;+ } break;+ case BOUNDS_MODE_IMMERSIVE: {+ return XR_SPATIAL_CONTAINER_BOUNDS_MODE_IMMERSIVE_EXT;+ } break;+ }+}++OpenXRSpatialContainerState::BoundsMode OpenXRSpatialContainerState::_to_bounds_mode(XrSpatialContainerBoundsModeEXT p_mode) {+ switch (p_mode) {+ case XR_SPATIAL_CONTAINER_BOUNDS_MODE_BOUNDED_EXT:+ default: {+ return BOUNDS_MODE_BOUNDED;+ } break;+ case XR_SPATIAL_CONTAINER_BOUNDS_MODE_IMMERSIVE_EXT: {+ return BOUNDS_MODE_IMMERSIVE;+ } break;+ }+}diff --git a/modules/openxr/extensions/spatial_container/openxr_spatial_container_state.h b/modules/openxr/extensions/spatial_container/openxr_spatial_container_state.hnew file mode 100644index 00000000000..1b68ff79472--- /dev/null+++ b/modules/openxr/extensions/spatial_container/openxr_spatial_container_state.h@@ -0,0 +1,68 @@+/**************************************************************************/+/* openxr_spatial_container_state.h */+/**************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/**************************************************************************/+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */+/* */+/* 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. */+/**************************************************************************/++#pragma once++#include "core/object/ref_counted.h"+#include "core/variant/binder_common.h"++#include <openxr/openxr.h>++class OpenXRSpatialContainerState : public RefCounted {+ GDCLASS(OpenXRSpatialContainerState, RefCounted);++public:+ enum BoundsMode {+ BOUNDS_MODE_BOUNDED,+ BOUNDS_MODE_IMMERSIVE,+ };++ BoundsMode get_bounds_mode() const;+ bool is_interactable() const;+ bool is_visible() const;++ OpenXRSpatialContainerState() {}+ OpenXRSpatialContainerState(const XrSpatialContainerStateEXT &p_state);++protected:+ static void _bind_methods();++private:+ friend class OpenXRSpatialContainerExtension;++ static XrSpatialContainerBoundsModeEXT _from_bounds_mode(BoundsMode p_mode);+ static BoundsMode _to_bounds_mode(XrSpatialContainerBoundsModeEXT p_mode);++ BoundsMode bounds_mode = BOUNDS_MODE_BOUNDED;+ bool interactable = false;+ bool visible = false;+};++VARIANT_ENUM_CAST(OpenXRSpatialContainerState::BoundsMode);diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cppindex 831fa9fe7d5..3ae2f08582e 100644--- a/modules/openxr/openxr_api.cpp+++ b/modules/openxr/openxr_api.cpp@@ -72,6 +72,7 @@#include "extensions/openxr_fb_foveation_extension.h"#include "extensions/openxr_fb_update_swapchain_extension.h"#include "extensions/openxr_hand_tracking_extension.h"+#include "extensions/spatial_container/openxr_spatial_container_extension.h"#ifndef DISABLE_DEPRECATED#include "extensions/openxr_extension_wrapper_extension.h"@@ -1375,7 +1376,9 @@ void OpenXRAPI::destroy_session() {if (running) {if (session != XR_NULL_HANDLE) {- xrEndSession(session);+ if (!is_spatial_container_enabled()) {+ xrEndSession(session);+ }}running = false;@@ -1442,17 +1445,19 @@ bool OpenXRAPI::on_state_idle() {bool OpenXRAPI::on_state_ready() {print_verbose("On state ready");- // begin session- XrSessionBeginInfo session_begin_info = {- XR_TYPE_SESSION_BEGIN_INFO, // type- nullptr, // next- view_configuration // primaryViewConfigurationType- };+ if (!is_spatial_container_enabled()) {+ // begin session+ XrSessionBeginInfo session_begin_info = {+ XR_TYPE_SESSION_BEGIN_INFO, // type+ nullptr, // next+ view_configuration // primaryViewConfigurationType+ };- XrResult result = xrBeginSession(session, &session_begin_info);- if (XR_FAILED(result)) {- print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");- return false;+ XrResult result = xrBeginSession(session, &session_begin_info);+ if (XR_FAILED(result)) {+ print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");+ return false;+ }}// we're running@@ -1524,10 +1529,12 @@ bool OpenXRAPI::on_state_stopping() {}if (running) {- XrResult result = xrEndSession(session);- if (XR_FAILED(result)) {- // we only report this..- print_line("OpenXR: Failed to end session [", get_error_string(result), "]");+ if (!is_spatial_container_enabled()) {+ XrResult result = xrEndSession(session);+ if (XR_FAILED(result)) {+ // we only report this..+ print_line("OpenXR: Failed to end session [", get_error_string(result), "]");+ }}running = false;@@ -2086,6 +2093,14 @@ bool OpenXRAPI::poll_events() {switch (session_state) {case XR_SESSION_STATE_IDLE:on_state_idle();++ // If spatial container is enabled, then we also invoke on_state_ready() and+ // on_state_synchronized() as the corresponding events are no longer dispatched by+ // the runtime.+ if (is_spatial_container_enabled()) {+ on_state_ready();+ on_state_synchronized();+ }break;case XR_SESSION_STATE_READY:on_state_ready();@@ -2103,6 +2118,12 @@ bool OpenXRAPI::poll_events() {on_state_stopping();break;case XR_SESSION_STATE_LOSS_PENDING:+ // If spatial container is enabled, then we also invoke on_state_stopping()+ // as the corresponding event is no longer dispatched by the runtime.+ if (is_spatial_container_enabled()) {+ on_state_stopping();+ }+on_state_loss_pending();break;case XR_SESSION_STATE_EXITING:@@ -2215,7 +2236,7 @@ void OpenXRAPI::_set_render_display_info_rt(XrTime p_predicted_display_time, booOpenXRAPI *openxr_api = OpenXRAPI::get_singleton();ERR_FAIL_NULL(openxr_api);openxr_api->render_state.predicted_display_time = p_predicted_display_time;- openxr_api->render_state.should_render = p_should_render;+ openxr_api->render_state.should_render = p_should_render || openxr_api->render_state.should_submit_spatial_container_layers;}void OpenXRAPI::_set_render_environment_blend_mode_rt(int32_t p_environment_blend_mode) {@@ -2433,14 +2454,6 @@ void OpenXRAPI::pre_render() {// Process any swapchains that were queued to be freedOpenXRSwapChainInfo::free_queued();- void *view_locate_info_next_pointer = nullptr;- for (OpenXRExtensionWrapper *extension : frame_info_extensions) {- void *np = extension->set_view_locate_info_and_get_next_pointer(view_locate_info_next_pointer);- if (np != nullptr) {- view_locate_info_next_pointer = np;- }- }-// Get our view info for the frame we're about to render, note from the OpenXR manual:// "Repeatedly calling xrLocateViews with the same time may not necessarily return the same result. Instead the prediction gets increasingly accurate as the function is called closer to the given time for which a prediction is made"@@ -2452,32 +2465,51 @@ void OpenXRAPI::pre_render() {// That is not possible yet but worth investigating in the future.- XrViewLocateInfo view_locate_info = {- XR_TYPE_VIEW_LOCATE_INFO, // type- view_locate_info_next_pointer, // next- view_configuration, // viewConfigurationType- render_state.predicted_display_time, // displayTime- render_state.play_space // space- };- XrViewState view_state = {- XR_TYPE_VIEW_STATE, // type- nullptr, // next- 0 // viewStateFlags- };- uint32_t view_count_output;- XrResult result = xrLocateViews(session, &view_locate_info, &view_state, render_state.views.size(), &view_count_output, render_state.views.ptr());- if (XR_FAILED(result)) {- print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");- return;- }-+ XrResult result;bool pose_valid = true;- for (uint64_t i = 0; i < view_count_output; i++) {+ if (is_spatial_container_enabled()) {+ OpenXRSpatialContainerExtension *spatial_container_ext = OpenXRSpatialContainerExtension::get_singleton();+ ERR_FAIL_NULL(spatial_container_ext);+ result = spatial_container_ext->locate_spatial_container_views(render_state.views.ptr(), pose_valid,+ render_state.should_submit_spatial_container_layers);+ if (XR_FAILED(result)) {+ print_line("OpenXR: Couldn't locate spatial container views [", get_error_string(result), "]");+ return;+ }+ } else {+ void *view_locate_info_next_pointer = nullptr;+ for (OpenXRExtensionWrapper *extension : frame_info_extensions) {+ void *np = extension->set_view_locate_info_and_get_next_pointer(view_locate_info_next_pointer);+ if (np != nullptr) {+ view_locate_info_next_pointer = np;+ }+ }++ XrViewLocateInfo view_locate_info = {+ XR_TYPE_VIEW_LOCATE_INFO, // type+ view_locate_info_next_pointer, // next+ view_configuration, // viewConfigurationType+ render_state.predicted_display_time, // displayTime+ render_state.play_space // space+ };+ XrViewState view_state = {+ XR_TYPE_VIEW_STATE, // type+ nullptr, // next+ 0 // viewStateFlags+ };+ uint32_t view_count_output;+ result = xrLocateViews(session, &view_locate_info, &view_state, render_state.views.size(), &view_count_output, render_state.views.ptr());+ if (XR_FAILED(result)) {+ print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");+ return;+ }+if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||(view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {pose_valid = false;}}+if (render_state.view_pose_valid != pose_valid) {render_state.view_pose_valid = pose_valid;if (!render_state.view_pose_valid) {@@ -2802,8 +2834,8 @@ void OpenXRAPI::end_frame() {frame_end_info_next_pointer, // nextrender_state.predicted_display_time, // displayTimerender_state.environment_blend_mode, // environmentBlendMode- static_cast<uint32_t>(layers_list.size()), // layerCount- layers_list.ptr() // layers+ is_spatial_container_enabled() ? 0 : static_cast<uint32_t>(layers_list.size()), // layerCount+ is_spatial_container_enabled() ? nullptr : layers_list.ptr() // layers};result = xrEndFrame(session, &frame_end_info);if (XR_FAILED(result)) {@@ -2857,6 +2889,11 @@ void OpenXRAPI::set_render_region(const Rect2i &p_render_region) {set_render_state_render_region(p_render_region);}+bool OpenXRAPI::is_spatial_container_enabled() const {+ OpenXRSpatialContainerExtension *spatial_container_ext = OpenXRSpatialContainerExtension::get_singleton();+ return spatial_container_ext != nullptr && spatial_container_ext->is_enabled();+}+bool OpenXRAPI::is_foveation_supported() const {OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();return fov_ext != nullptr && fov_ext->is_enabled();diff --git a/modules/openxr/openxr_api.h b/modules/openxr/openxr_api.hindex 8ca2e44e82c..b6f05efd98c 100644--- a/modules/openxr/openxr_api.h+++ b/modules/openxr/openxr_api.h@@ -52,6 +52,8 @@// forward declarations, we don't want to include these fullyclass OpenXRInterface;+class OpenXRSpatialContainerExtension;+class OpenXRSpatialContainerSelfRenderingExtension;class OpenXRAPI {public:@@ -334,6 +336,9 @@ private:}};+ friend class OpenXRSpatialContainerExtension;+ friend class OpenXRSpatialContainerSelfRenderingExtension;+// state changesbool poll_events();bool on_state_idle();@@ -351,6 +356,7 @@ private:// Render state, Only accessible in rendering threadstruct RenderState {bool running = false;+ bool should_submit_spatial_container_layers = false;bool should_render = false;bool has_xr_viewport = false;XrTime predicted_display_time = 0;@@ -516,6 +522,9 @@ public:Rect2i get_render_region() const;void set_render_region(const Rect2i &p_render_region);+ // Spatial container settings.+ bool is_spatial_container_enabled() const;+// Foveation settingsbool is_foveation_supported() const;diff --git a/modules/openxr/openxr_interface.cpp b/modules/openxr/openxr_interface.cppindex 38e7916a34d..34568467803 100644--- a/modules/openxr/openxr_interface.cpp+++ b/modules/openxr/openxr_interface.cpp@@ -1055,7 +1055,7 @@ Size2 OpenXRInterface::get_render_target_size() {}uint32_t OpenXRInterface::get_view_count() {- // TODO set this based on our configuration+ // TODO: set this based on our configuration and the active spatial containers.return 2;}diff --git a/modules/openxr/register_types.cpp b/modules/openxr/register_types.cppindex ec3066b292b..87087279e97 100644--- a/modules/openxr/register_types.cpp+++ b/modules/openxr/register_types.cpp@@ -79,6 +79,9 @@#include "extensions/openxr_valve_controller_extension.h"#include "extensions/openxr_visibility_mask_extension.h"#include "extensions/openxr_wmr_controller_extension.h"+#include "extensions/spatial_container/openxr_spatial_container_extension.h"+#include "extensions/spatial_container/openxr_spatial_container_self_rendering_extension.h"+#include "extensions/spatial_container/openxr_spatial_container_state.h"#include "extensions/spatial_entities/openxr_spatial_anchor.h"#include "extensions/spatial_entities/openxr_spatial_entity_extension.h"#include "extensions/spatial_entities/openxr_spatial_marker_tracking.h"@@ -116,6 +119,25 @@ static OpenXRAPI *openxr_api = nullptr;static OpenXRInteractionProfileMetadata *openxr_interaction_profile_metadata = nullptr;static Ref<OpenXRInterface> openxr_interface;+struct ExtensionSingleton {+ String class_name;+ OpenXRExtensionWrapper *extension;+ bool registered_with_openxr;+ bool registered_as_singleton;+};++static Vector<ExtensionSingleton> extensions_singletons;+static inline void _register_extension(OpenXRExtensionWrapper *p_extension, bool p_register_with_openxr = true, bool p_register_as_singleton = false) {+ String class_name = p_extension->get_class();+ if (p_register_with_openxr) {+ OpenXRAPI::register_extension_wrapper(p_extension);+ }+ if (p_register_as_singleton) {+ Engine::get_singleton()->add_singleton(Engine::Singleton(class_name, p_extension));+ }+ extensions_singletons.push_back({ class_name, p_extension, p_register_with_openxr, p_register_as_singleton });+}+#ifdef TOOLS_ENABLEDstatic void _editor_init() {if (OpenXRAPI::openxr_is_enabled(false)) {@@ -156,88 +178,67 @@ void initialize_openxr_module(ModuleInitializationLevel p_level) {// Always register our extension wrappers even if we don't initialize OpenXR.// Some of these wrappers will add functionality to our editor.#ifdef ANDROID_ENABLED- OpenXRAPI::register_extension_wrapper(memnew(OpenXRAndroidExtension));+ _register_extension(memnew(OpenXRAndroidExtension));#endif// register our other extensions- OpenXRAPI::register_extension_wrapper(memnew(OpenXRPalmPoseExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRLocalFloorExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRPicoControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRCompositionLayerDepthExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRCompositionLayerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRHTCControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRHTCViveTrackerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRHuaweiControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRDisplayRefreshRateExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRWMRControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRML2ControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRMetaControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXREyeGazeInteractionExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRHandInteractionExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRMxInkExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRVisibilityMaskExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRPerformanceSettingsExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRValveControllerExtension));- OpenXRAPI::register_extension_wrapper(memnew(OpenXRKHRGenericController));+ _register_extension(memnew(OpenXRPalmPoseExtension));+ _register_extension(memnew(OpenXRLocalFloorExtension));+ _register_extension(memnew(OpenXRPicoControllerExtension));+ _register_extension(memnew(OpenXRCompositionLayerDepthExtension));+ _register_extension(memnew(OpenXRCompositionLayerExtension));+ _register_extension(memnew(OpenXRHTCControllerExtension));+ _register_extension(memnew(OpenXRHTCViveTrackerExtension));+ _register_extension(memnew(OpenXRHuaweiControllerExtension));+ _register_extension(memnew(OpenXRDisplayRefreshRateExtension));+ _register_extension(memnew(OpenXRWMRControllerExtension));+ _register_extension(memnew(OpenXRML2ControllerExtension));+ _register_extension(memnew(OpenXRMetaControllerExtension));+ _register_extension(memnew(OpenXREyeGazeInteractionExtension));+ _register_extension(memnew(OpenXRHandInteractionExtension));+ _register_extension(memnew(OpenXRMxInkExtension));+ _register_extension(memnew(OpenXRVisibilityMaskExtension));+ _register_extension(memnew(OpenXRPerformanceSettingsExtension));+ _register_extension(memnew(OpenXRValveControllerExtension));+ _register_extension(memnew(OpenXRKHRGenericController));// Futures extension has to be registered as a singleton so extensions can access it.- OpenXRFutureExtension *future_extension = memnew(OpenXRFutureExtension);- OpenXRAPI::register_extension_wrapper(future_extension);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRFutureExtension", future_extension));+ _register_extension(memnew(OpenXRFutureExtension), true, true);// Register render model extension as a singleton.#ifdef MODULE_GLTF_ENABLED- OpenXRRenderModelExtension *render_model_extension = memnew(OpenXRRenderModelExtension);- OpenXRAPI::register_extension_wrapper(render_model_extension);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRRenderModelExtension", render_model_extension));+ _register_extension(memnew(OpenXRRenderModelExtension), true, true);#endif// Register spatial entity extensions- OpenXRSpatialEntityExtension *spatial_entity_extension = memnew(OpenXRSpatialEntityExtension);- OpenXRAPI::register_extension_wrapper(spatial_entity_extension);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRSpatialEntityExtension", spatial_entity_extension));-- OpenXRSpatialAnchorCapability *anchor_capability = memnew(OpenXRSpatialAnchorCapability);- OpenXRAPI::register_extension_wrapper(anchor_capability);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRSpatialAnchorCapability", anchor_capability));-- OpenXRSpatialPlaneTrackingCapability *plane_tracking_capability = memnew(OpenXRSpatialPlaneTrackingCapability);- OpenXRAPI::register_extension_wrapper(plane_tracking_capability);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRSpatialPlaneTrackingCapability", plane_tracking_capability));-- OpenXRSpatialMarkerTrackingCapability *marker_tracking_capability = memnew(OpenXRSpatialMarkerTrackingCapability);- OpenXRAPI::register_extension_wrapper(marker_tracking_capability);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRSpatialMarkerTrackingCapability", marker_tracking_capability));+ _register_extension(memnew(OpenXRSpatialEntityExtension), true, true);+ _register_extension(memnew(OpenXRSpatialAnchorCapability), true, true);+ _register_extension(memnew(OpenXRSpatialPlaneTrackingCapability), true, true);+ _register_extension(memnew(OpenXRSpatialMarkerTrackingCapability), true, true);// Register frame synthesis extension as a singleton.- OpenXRFrameSynthesisExtension *frame_synthesis_extension = memnew(OpenXRFrameSynthesisExtension);- OpenXRAPI::register_extension_wrapper(frame_synthesis_extension);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRFrameSynthesisExtension", frame_synthesis_extension));+ _register_extension(memnew(OpenXRFrameSynthesisExtension), true, true);// Register android thread settings extension as a singleton.- OpenXRAndroidThreadSettingsExtension *android_thread_settings = memnew(OpenXRAndroidThreadSettingsExtension);- OpenXRAPI::register_extension_wrapper(android_thread_settings);- Engine::get_singleton()->add_singleton(Engine::Singleton("OpenXRAndroidThreadSettingsExtension", android_thread_settings));+ _register_extension(memnew(OpenXRAndroidThreadSettingsExtension), true, true);// Register user presence extension as a singleton- OpenXRUserPresenceExtension *user_presence_extension = memnew(OpenXRUserPresenceExtension);- OpenXRAPI::register_extension_wrapper(user_presence_extension);+ _register_extension(memnew(OpenXRUserPresenceExtension), true, true);// register gated extensions- if (int(GLOBAL_GET("xr/openxr/extensions/debug_utils")) > 0) {- OpenXRAPI::register_extension_wrapper(memnew(OpenXRDebugUtilsExtension));- }- if (GLOBAL_GET("xr/openxr/extensions/hand_tracking")) {- OpenXRAPI::register_extension_wrapper(memnew(OpenXRHandTrackingExtension));- }+ _register_extension(memnew(OpenXRDebugUtilsExtension), int(GLOBAL_GET("xr/openxr/extensions/debug_utils")) > 0);+ _register_extension(memnew(OpenXRHandTrackingExtension), GLOBAL_GET("xr/openxr/extensions/hand_tracking"));++ // Spatial container extensions+ bool spatial_container_enabled = GLOBAL_GET("xr/openxr/extensions/spatial_container/enabled");+ _register_extension(memnew(OpenXRSpatialContainerExtension), spatial_container_enabled, true);+ // For now we gate the self rendering extension under the same preference as the spatial_container extension.+ // TODO: When we add support for system rendering, gate self rendering under a different project setting.+ _register_extension(memnew(OpenXRSpatialContainerSelfRenderingExtension), spatial_container_enabled, true);// register gated binding modifiers- if (GLOBAL_GET("xr/openxr/binding_modifiers/analog_threshold")) {- OpenXRAPI::register_extension_wrapper(memnew(OpenXRValveAnalogThresholdExtension));- }- if (GLOBAL_GET("xr/openxr/binding_modifiers/dpad_binding")) {- OpenXRAPI::register_extension_wrapper(memnew(OpenXRDPadBindingExtension));- }+ _register_extension(memnew(OpenXRValveAnalogThresholdExtension), GLOBAL_GET("xr/openxr/binding_modifiers/analog_threshold"));+ _register_extension(memnew(OpenXRDPadBindingExtension), GLOBAL_GET("xr/openxr/binding_modifiers/dpad_binding"));}if (OpenXRAPI::openxr_is_enabled()) {@@ -306,6 +307,10 @@ void initialize_openxr_module(ModuleInitializationLevel p_level) {GDREGISTER_CLASS(OpenXRRenderModelManager);#endif+ GDREGISTER_CLASS(OpenXRSpatialContainerExtension);+ GDREGISTER_CLASS(OpenXRSpatialContainerSelfRenderingExtension);+ GDREGISTER_VIRTUAL_CLASS(OpenXRSpatialContainerState);+GDREGISTER_CLASS(OpenXRSpatialEntityExtension);GDREGISTER_VIRTUAL_CLASS(OpenXRSpatialEntityTracker);GDREGISTER_CLASS(OpenXRAnchorTracker);@@ -366,6 +371,17 @@ void uninitialize_openxr_module(ModuleInitializationLevel p_level) {return;}+ for (const ExtensionSingleton &extension_singleton : extensions_singletons) {+ if (extension_singleton.registered_as_singleton) {+ Engine::get_singleton()->remove_singleton(extension_singleton.class_name);+ }+ if (!extension_singleton.registered_with_openxr) {+ // OpenXRAPI handles the cleanup for registered extensions.+ memdelete(extension_singleton.extension);+ }+ }+ extensions_singletons.clear();+if (openxr_interface.is_valid()) {// uninitialize just in caseif (openxr_interface->is_initialized()) {diff --git a/platform/android/java/app/config.gradle b/platform/android/java/app/config.gradleindex 767d30374b0..7d811a2163c 100644--- a/platform/android/java/app/config.gradle+++ b/platform/android/java/app/config.gradle@@ -1,5 +1,5 @@ext.versions = [- androidGradlePlugin: '8.6.1',+ androidGradlePlugin: '8.9.1',compileSdk : 36,// Also update:// - 'editor/export/android_sdk_manager.h#DEFAULT_MIN_SDK_VERSION'diff --git a/platform/android/java/editor/build.gradle b/platform/android/java/editor/build.gradleindex 8f299420b16..269df35358b 100644--- a/platform/android/java/editor/build.gradle+++ b/platform/android/java/editor/build.gradle@@ -223,6 +223,8 @@ dependencies {// Android XR dependenciesandroidImplementation "org.godotengine:godot-openxr-vendors-androidxr:$versions.openxrVendorsVersion"+ androidImplementation "androidx.xr.scenecore:scenecore:1.0.0-beta02"+// Meta dependencieshorizonosImplementation "org.godotengine:godot-openxr-vendors-meta:$versions.openxrVendorsVersion"// Pico dependenciesdiff --git a/platform/android/java/editor/src/android/AndroidManifest.xml b/platform/android/java/editor/src/android/AndroidManifest.xmlindex 8d47735c7ea..913ba127208 100644--- a/platform/android/java/editor/src/android/AndroidManifest.xml+++ b/platform/android/java/editor/src/android/AndroidManifest.xml@@ -16,7 +16,13 @@<uses-feature android:name="android.hardware.xr.input.hand_tracking" android:required="false" /><uses-permission android:name="android.permission.HAND_TRACKING" />+ <!-- Head tracking -->+ <uses-permission android:name="android.permission.HEAD_TRACKING" />+<application>+ <!-- Required for spatial container support on AndroidXR. -->+ <meta-data android:name="com.android.extensions.xr.uses_experimental_openxr_feature" android:value="true" />+<uses-native-library android:name="libopenxr.google.so" android:required="false" /><property@@ -37,6 +43,31 @@android:name="android.window.PROPERTY_XR_ACTIVITY_START_MODE"android:value="XR_ACTIVITY_START_MODE_FULL_SPACE_UNMANAGED" /></activity>++ <activity+ android:name=".GodotSpatialContainerGame0"+ android:exported="false"+ tools:node="merge">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ <property+ android:name="android.window.PROPERTY_XR_ACTIVITY_START_MODE"+ android:value="XR_ACTIVITY_START_MODE_FULL_SPACE_MANAGED" />+ </activity>+ <activity+ android:name=".GodotSpatialContainerGame1"+ android:exported="false"+ tools:node="merge">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ <property+ android:name="android.window.PROPERTY_XR_ACTIVITY_START_MODE"+ android:value="XR_ACTIVITY_START_MODE_FULL_SPACE_MANAGED" />+ </activity></application></manifest>diff --git a/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotEditor.kt b/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotEditor.ktindex 52ee12f76cb..351c1ac7588 100644--- a/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotEditor.kt+++ b/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotEditor.kt@@ -30,6 +30,24 @@package org.godotengine.editor+import android.app.ActivityOptions+import android.content.Intent+import android.os.Build+import android.os.Handler+import android.util.Log+import androidx.xr.runtime.Session+import androidx.xr.runtime.SessionCreateSuccess+import androidx.xr.runtime.math.IntSize2d+import androidx.xr.runtime.math.Pose+import androidx.xr.runtime.math.Quaternion+import androidx.xr.runtime.math.Vector3+import androidx.xr.scenecore.ActivityPanelEntity+import androidx.xr.scenecore.MovableComponent+import androidx.xr.scenecore.SpatialCapability+import androidx.xr.scenecore.scene+import java.util.LinkedList+import java.util.function.Consumer+/*** Primary window of the Godot Editor.*@@ -37,6 +55,117 @@ package org.godotengine.editor*/open class GodotEditor : BaseGodotEditor() {+ companion object {+ private val TAG = GodotEditor::class.java.simpleName+ }++ private val handler = Handler()++ private var pendingFullSpaceRequest = false+ private val pendingSpatialContainerLaunches = LinkedList<Intent>()++ private val spatialCapabilitiesChangedListener = Consumer<Set<SpatialCapability>> {+ if (canEmbedActivity()) {+ pendingFullSpaceRequest = false++ // Launch any queued spatial containers.+ Log.v(TAG, "Launching pending spatial container launches..")+ for (pendingLaunch in pendingSpatialContainerLaunches) {+ startSpatialContainerActivity(pendingLaunch)+ }+ pendingSpatialContainerLaunches.clear()+ } else {+ // Already in HSM, so remove any request to transition.+ handler.removeCallbacks(requestHomeSpaceRunnable)+ }+ }++ private val session: Session? by lazy {+ val result = Session.create(this)+ if (result is SessionCreateSuccess) {+ result.session.scene.apply{+ addSpatialCapabilitiesChangedListener(spatialCapabilitiesChangedListener)+ mainPanelEntity.addComponent(MovableComponent.createSystemMovable(result.session))+ }+ return@lazy result.session+ } else {+ return@lazy null+ }+ }++ private val requestHomeSpaceRunnable: Runnable = Runnable {+ val scene = session?.scene ?: return@Runnable++ handler.removeCallbacks(requestHomeSpaceRunnable)+ if (canEmbedActivity()) {+ scene.requestHomeSpace()+ }+ }++ private fun canEmbedActivity(): Boolean {+ val scene = session?.scene ?: return false+ return scene.spatialCapabilities.contains(SpatialCapability.EMBED_ACTIVITY)+ }++ private fun launchSpatialContainerUsingSceneCore(newInstance: Intent, activityOptions: ActivityOptions?): Boolean {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ try {+ if (session != null) {+ val scene = session!!.scene++ handler.removeCallbacks(requestHomeSpaceRunnable)+ if (canEmbedActivity()) {+ Log.v(TAG, "Launching spatial container in FSM")+ startSpatialContainerActivity(newInstance)+ } else {+ pendingSpatialContainerLaunches.push(newInstance)+ if (!pendingFullSpaceRequest) {+ Log.v(TAG, "Requesting full space")+ scene.requestFullSpace()+ pendingFullSpaceRequest = true+ }+ }+ return true+ }+ } catch (e: Exception) {+ Log.e(TAG, "Unable to launch spatial container", e)+ }+ }+ return false+ }++ private fun startSpatialContainerActivity(newInstance: Intent) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val scene = session!!.scene++ val activityPanel = ActivityPanelEntity.create(+ session!!,+ IntSize2d(500, 500),+ "Godot Spatial Container Panel for $newInstance",+ Pose(Vector3(0.0f, -scene.mainPanelEntity.size.height, 0.05f), Quaternion.Identity),+ scene.activitySpace+ )+ activityPanel.addComponent(MovableComponent.createSystemMovable(session!!))++ // We remove the 'NEW_TASK' flag as launching in a new task prevents embedding.+ newInstance.removeFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ activityPanel.startActivity(newInstance)+ }+ }++ private fun exitFullSpaceUsingSceneCore() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ handler.postDelayed(requestHomeSpaceRunnable, 250L)++ session?.scene?.activitySpace?.children?.forEach { child ->+ if (child is ActivityPanelEntity) {+ Log.d(TAG, "Removing entity $child from the scene graph.")+ child.parent = null+ }+ }+ }+ }+override fun getXRRuntimePermissions(): MutableSet<String> {val xrRuntimePermissions = super.getXRRuntimePermissions()@@ -45,4 +174,29 @@ open class GodotEditor : BaseGodotEditor() {return xrRuntimePermissions}++ override fun dispatchNewInstance(+ editorWindowInfo: EditorWindowInfo,+ newInstance: Intent,+ activityOptions: ActivityOptions?+ ) {+ if (isSpatialContainerRunGameInfo(editorWindowInfo) && launchSpatialContainerUsingSceneCore(newInstance, activityOptions)) {+ return+ }+ super.dispatchNewInstance(editorWindowInfo, newInstance, activityOptions)+ }++ override fun onEditorDisconnected(editorId: Int) {+ if (isSpatialContainerRunGameInfoWindowId(editorId)) {+ val spatialContainersRunning =+ (SPATIAL_CONTAINER_RUN_GAME_INFO_0.windowId != editorId && editorMessageDispatcher.hasEditorConnection(SPATIAL_CONTAINER_RUN_GAME_INFO_0)) ||+ (SPATIAL_CONTAINER_RUN_GAME_INFO_1.windowId != editorId && editorMessageDispatcher.hasEditorConnection(SPATIAL_CONTAINER_RUN_GAME_INFO_1))+ if (!spatialContainersRunning) {+ // No spatial container is running, time to exit FSM.+ Log.v(TAG, "Exiting FSM.")+ exitFullSpaceUsingSceneCore()+ }+ }+ super.onEditorDisconnected(editorId)+ }}diff --git a/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotSpatialContainerGame.kt b/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotSpatialContainerGame.ktnew file mode 100644index 00000000000..f9f863166cc--- /dev/null+++ b/platform/android/java/editor/src/android/java/org/godotengine/editor/GodotSpatialContainerGame.kt@@ -0,0 +1,43 @@+/*************************************************************************/+/* GodotSpatialContainerGame.kt */+/*************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/*************************************************************************/+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */+/* */+/* 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. */+/*************************************************************************/++package org.godotengine.editor++/**+ * Provide support for running spatial container apps / games from the editor window on Android XR.+ */+abstract class GodotSpatialContainerGame : BaseGodotSpatialContainerGame() {++ companion object {+ internal fun isSpatialContainerEnabled() = BaseGodotSpatialContainerGame.isSpatialContainerEnabled()+ }++ override fun getGodotAppLayout() = R.layout.godot_spatial_container_game_layout+}diff --git a/platform/android/java/editor/src/android/res/layout/godot_spatial_container_game_layout.xml b/platform/android/java/editor/src/android/res/layout/godot_spatial_container_game_layout.xmlnew file mode 100644index 00000000000..f6b37e2b81e--- /dev/null+++ b/platform/android/java/editor/src/android/res/layout/godot_spatial_container_game_layout.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="match_parent">++ <include layout="@layout/godot_fragment_container_layout" />++ <ImageView+ android:id="@+id/godot_spatial_container_icon"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_gravity="center"+ android:src="@mipmap/ic_play_window"+ />+</FrameLayout>diff --git a/platform/android/java/editor/src/horizonos/java/org/godotengine/editor/GodotSpatialContainerGame.kt b/platform/android/java/editor/src/horizonos/java/org/godotengine/editor/GodotSpatialContainerGame.ktnew file mode 100644index 00000000000..32c66530f90--- /dev/null+++ b/platform/android/java/editor/src/horizonos/java/org/godotengine/editor/GodotSpatialContainerGame.kt@@ -0,0 +1,42 @@+/*************************************************************************/+/* GodotSpatialContainerGame.kt */+/*************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/*************************************************************************/+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */+/* */+/* 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. */+/*************************************************************************/++package org.godotengine.editor++import android.os.Bundle++/**+ * Provide support for running spatial container apps / games from the editor window on HorizonOS.+ */+abstract class GodotSpatialContainerGame : BaseGodotSpatialContainerGame() {+ companion object {+ internal fun isSpatialContainerEnabled() = false+ }+}diff --git a/platform/android/java/editor/src/main/AndroidManifest.xml b/platform/android/java/editor/src/main/AndroidManifest.xmlindex fabe47ea067..781c895f366 100644--- a/platform/android/java/editor/src/main/AndroidManifest.xml+++ b/platform/android/java/editor/src/main/AndroidManifest.xml@@ -163,6 +163,37 @@android:resizeableActivity="false"android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />+ <activity+ android:name=".GodotSpatialContainerGame0"+ android:configChanges="layoutDirection|locale|orientation|keyboardHidden|screenSize|smallestScreenSize|density|keyboard|navigation|screenLayout|uiMode"+ android:process=":GodotSpatialContainerGame0"+ android:icon="@mipmap/ic_play_window"+ android:label="@string/godot_game_activity_name"+ android:exported="false"+ android:autoRemoveFromRecents="true"+ android:screenOrientation="landscape"+ android:resizeableActivity="false"+ android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >++ <property android:name="org.khronos.openxr.PROPERTY_ACTIVITY_HINT_XR_SPATIAL_CONTAINER_USED_BOUNDS_MODES" android:value="" />+ <property android:name="org.khronos.openxr.PROPERTY_ACTIVITY_HINT_XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE" android:value="XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE_UNDEFINED" />+ </activity>+ <activity+ android:name=".GodotSpatialContainerGame1"+ android:configChanges="layoutDirection|locale|orientation|keyboardHidden|screenSize|smallestScreenSize|density|keyboard|navigation|screenLayout|uiMode"+ android:process=":GodotSpatialContainerGame1"+ android:icon="@mipmap/ic_play_window"+ android:label="@string/godot_game_activity_name"+ android:exported="false"+ android:autoRemoveFromRecents="true"+ android:screenOrientation="landscape"+ android:resizeableActivity="false"+ android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >++ <property android:name="org.khronos.openxr.PROPERTY_ACTIVITY_HINT_XR_SPATIAL_CONTAINER_USED_BOUNDS_MODES" android:value="" />+ <property android:name="org.khronos.openxr.PROPERTY_ACTIVITY_HINT_XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE" android:value="XR_SPATIAL_CONTAINER_INITIAL_BOUNDS_MODE_UNDEFINED" />+ </activity>+<!--We remove this meta-data originating from the vendors plugin as we only need the loader fornow since the project being edited provides its own version of the vendors plugin.diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.ktindex dd408971a53..f8d115d62ec 100644--- a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotEditor.kt@@ -117,7 +117,12 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe// Info for the various classes used by the editor.internal val EDITOR_MAIN_INFO = EditorWindowInfo(GodotEditor::class.java, 777, "")internal val EMBEDDED_RUN_GAME_INFO = EditorWindowInfo(EmbeddedGodotGame::class.java, 2667, ":EmbeddedGodotGame")- internal val XR_RUN_GAME_INFO = EditorWindowInfo(GodotXRGame::class.java, 1667, ":GodotXRGame")+ internal val XR_RUN_GAME_INFO = EditorWindowInfo(GodotXRGame::class.java, 1667, ":GodotXRGame", LaunchPolicy.ADJACENT)++ internal val SPATIAL_CONTAINER_RUN_GAME_INFO_0 = EditorWindowInfo(GodotSpatialContainerGame0::class.java,+ 3667, ":GodotSpatialContainerGame0", LaunchPolicy.ADJACENT)+ internal val SPATIAL_CONTAINER_RUN_GAME_INFO_1 = EditorWindowInfo(GodotSpatialContainerGame1::class.java,+ 3668, ":GodotSpatialContainerGame1", LaunchPolicy.ADJACENT)internal val RUN_GAME_INFO_0 = EditorWindowInfo(GodotGame0::class.java, 667, ":GodotGame0", LaunchPolicy.AUTO)internal val RUN_GAME_INFO_1 = EditorWindowInfo(GodotGame1::class.java, 668, ":GodotGame1", LaunchPolicy.AUTO)@@ -126,6 +131,30 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListereturn editorWindowInfo == RUN_GAME_INFO_0 || editorWindowInfo == RUN_GAME_INFO_1}+ private fun getRunGameInfoForInstance(runInstance: Int): EditorWindowInfo {+ return when (runInstance) {+ 1 -> RUN_GAME_INFO_1+ else -> RUN_GAME_INFO_0+ }+ }++ internal fun isSpatialContainerRunGameInfo(editorWindowInfo: EditorWindowInfo): Boolean {+ return editorWindowInfo == SPATIAL_CONTAINER_RUN_GAME_INFO_0 ||+ editorWindowInfo == SPATIAL_CONTAINER_RUN_GAME_INFO_1+ }++ internal fun isSpatialContainerRunGameInfoWindowId(windowId: Int): Boolean {+ return windowId == SPATIAL_CONTAINER_RUN_GAME_INFO_0.windowId ||+ windowId == SPATIAL_CONTAINER_RUN_GAME_INFO_1.windowId+ }++ private fun getSpatialContainerRunGameInfoForInstance(runInstance: Int): EditorWindowInfo {+ return when (runInstance) {+ 1 -> SPATIAL_CONTAINER_RUN_GAME_INFO_1+ else -> SPATIAL_CONTAINER_RUN_GAME_INFO_0+ }+ }+/** Default behavior, means we check project settings **/private const val XR_MODE_DEFAULT = "default"@@ -633,24 +662,23 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe// Launching a game.if (isNativeXRDevice(applicationContext)) {- if (xrMode == XR_MODE_ON) {- return XR_RUN_GAME_INFO- }-- if ((xrMode == XR_MODE_DEFAULT && GodotLib.getGlobal("xr/openxr/enabled").toBoolean())) {- val hybridLaunchMode = getHybridAppLaunchMode()-- if (hybridLaunchMode != HybridMode.PANEL) {- return XR_RUN_GAME_INFO+ val gameInfo = if (xrMode == XR_MODE_ON) {+ XR_RUN_GAME_INFO+ } else if ((xrMode == XR_MODE_DEFAULT && GodotLib.getGlobal("xr/openxr/enabled").toBoolean())) {+ if (getHybridAppLaunchMode() == HybridMode.PANEL) {+ getRunGameInfoForInstance(runInstance)} else {- // Hybrid launch mode is PANEL, fall-through and return RUN_GAME_INFO.+ XR_RUN_GAME_INFO}+ } else {+ // Native XR devices don't support embed mode yet.+ getRunGameInfoForInstance(runInstance)}- // XR devices support doing multiple runs; check which run we are performing.- return when (runInstance) {- 1 -> RUN_GAME_INFO_1- else -> RUN_GAME_INFO_0+ return if (gameInfo == XR_RUN_GAME_INFO && GodotSpatialContainerGame.isSpatialContainerEnabled()) {+ getSpatialContainerRunGameInfoForInstance(runInstance)+ } else {+ gameInfo}}@@ -670,11 +698,16 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListeprivate fun getEditorWindowInfoForInstanceId(instanceId: Int): EditorWindowInfo? {return when (instanceId) {- RUN_GAME_INFO_0.windowId -> RUN_GAME_INFO_0- RUN_GAME_INFO_1.windowId -> RUN_GAME_INFO_1EDITOR_MAIN_INFO.windowId -> EDITOR_MAIN_INFOXR_RUN_GAME_INFO.windowId -> XR_RUN_GAME_INFOEMBEDDED_RUN_GAME_INFO.windowId -> EMBEDDED_RUN_GAME_INFO++ RUN_GAME_INFO_0.windowId -> RUN_GAME_INFO_0+ RUN_GAME_INFO_1.windowId -> RUN_GAME_INFO_1++ SPATIAL_CONTAINER_RUN_GAME_INFO_0.windowId -> SPATIAL_CONTAINER_RUN_GAME_INFO_0+ SPATIAL_CONTAINER_RUN_GAME_INFO_1.windowId -> SPATIAL_CONTAINER_RUN_GAME_INFO_1+else -> null}}@@ -743,11 +776,15 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListeLog.d(TAG, "Starting ${editorWindowInfo.windowClassName} with parameters ${args.contentToString()}")newInstance.putExtra(EXTRA_NEW_LAUNCH, true).putExtra(EditorMessageDispatcher.EXTRA_MSG_DISPATCHER_PAYLOAD, editorMessageDispatcher.getMessageDispatcherPayload())- startActivity(newInstance, activityOptions?.toBundle())+ dispatchNewInstance(editorWindowInfo, newInstance, activityOptions)}return editorWindowInfo.windowId}+ protected open fun dispatchNewInstance(editorWindowInfo: EditorWindowInfo, newInstance: Intent, activityOptions: ActivityOptions?) {+ startActivity(newInstance, activityOptions?.toBundle())+ }+override fun onGodotForceQuit(instance: Godot) {if (!isRunningInInstrumentationOrUserTestHarness()) {// For instrumented tests, we disable force-quitting to allow the tests to complete successfully, otherwise@@ -972,7 +1009,8 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListereturn super.supportsFeature(featureTag)}- internal fun onEditorConnected(editorId: Int) {+ @CallSuper+ internal open fun onEditorConnected(editorId: Int) {Log.d(TAG, "Editor $editorId connected!")when (editorId) {EMBEDDED_RUN_GAME_INFO.windowId,@@ -991,7 +1029,8 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListe}}- internal fun onEditorDisconnected(editorId: Int) {+ @CallSuper+ internal open fun onEditorDisconnected(editorId: Int) {Log.d(TAG, "Editor $editorId disconnected!")}@@ -1025,10 +1064,14 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListereturn}+ val spatialContainerRunning =+ editorMessageDispatcher.hasEditorConnection(SPATIAL_CONTAINER_RUN_GAME_INFO_0) ||+ editorMessageDispatcher.hasEditorConnection(SPATIAL_CONTAINER_RUN_GAME_INFO_1)val xrGameRunning = editorMessageDispatcher.hasEditorConnection(XR_RUN_GAME_INFO)+ val gameRunning = spatialContainerRunning || xrGameRunningval gameEmbedMode = resolveGameEmbedModeIfNeeded(fetchGameEmbedMode())runOnUiThread {- updateEmbeddedGameView(xrGameRunning, gameEmbedMode != GameEmbedMode.DISABLED)+ updateEmbeddedGameView(gameRunning, gameEmbedMode != GameEmbedMode.DISABLED)embeddedGameViewContainerWindow?.isVisible = true}}@@ -1061,7 +1104,7 @@ abstract class BaseGodotEditor : GodotActivity(), GameMenuFragment.GameMenuListeval relaunchIntent = Intent(intent)// Don't restart.relaunchIntent.putExtra(EXTRA_NEW_LAUNCH, false)- startActivity(relaunchIntent)+ dispatchNewInstance(getEditorWindowInfo(), relaunchIntent, null)}}diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotSpatialContainerGame.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotSpatialContainerGame.ktnew file mode 100644index 00000000000..96bd8dc231d--- /dev/null+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/BaseGodotSpatialContainerGame.kt@@ -0,0 +1,43 @@+/*************************************************************************/+/* BaseGodotSpatialContainerGame.kt */+/*************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/*************************************************************************/+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */+/* */+/* 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. */+/*************************************************************************/++package org.godotengine.editor++import org.godotengine.godot.GodotLib++/**+ * Provide support for running spatial container apps / games from the editor window.+ */+abstract class BaseGodotSpatialContainerGame : GodotXRGame() {+ companion object {+ @JvmStatic+ protected fun isSpatialContainerEnabled() = GodotLib.getGlobal("xr/openxr/extensions/spatial_container/enabled").toBoolean()+ }+}diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotSpatialContainerGame0.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotSpatialContainerGame0.ktnew file mode 100644index 00000000000..2996455ded8--- /dev/null+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotSpatialContainerGame0.kt@@ -0,0 +1,39 @@+/*************************************************************************/+/* GodotSpatialContainerGame0.kt */+/*************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/*************************************************************************/+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */+/* */+/* 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. */+/*************************************************************************/++package org.godotengine.editor++/**+ * First instance for the spatial container game volume. Typically, this is the default instance launched when+ * multi-instance is not enabled / supported.+ */+class GodotSpatialContainerGame0 : GodotSpatialContainerGame() {+ override fun getEditorWindowInfo() = SPATIAL_CONTAINER_RUN_GAME_INFO_0+}diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotSpatialContainerGame1.kt b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotSpatialContainerGame1.ktnew file mode 100644index 00000000000..bdf82800a55--- /dev/null+++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotSpatialContainerGame1.kt@@ -0,0 +1,40 @@+/*************************************************************************/+/* GodotSpatialContainerGame1.kt */+/*************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/*************************************************************************/+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */+/* */+/* 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. */+/*************************************************************************/++package org.godotengine.editor++/**+ * Second instance for the spatial container game volume.+ *+ * Used when multi-instance is enabled.+ */+class GodotSpatialContainerGame1 : GodotSpatialContainerGame() {+ override fun getEditorWindowInfo() = SPATIAL_CONTAINER_RUN_GAME_INFO_1+}diff --git a/platform/android/java/editor/src/main/res/layout/godot_fragment_container_layout.xml b/platform/android/java/editor/src/main/res/layout/godot_fragment_container_layout.xmlnew file mode 100644index 00000000000..fa8025f6f3a--- /dev/null+++ b/platform/android/java/editor/src/main/res/layout/godot_fragment_container_layout.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<merge xmlns:android="http://schemas.android.com/apk/res/android"+ android:layout_width="match_parent"+ android:layout_height="match_parent">++ <FrameLayout+ android:id="@+id/godot_fragment_container"+ android:layout_width="match_parent"+ android:layout_height="match_parent"/>++</merge>diff --git a/platform/android/java/editor/src/picoos/java/org/godotengine/editor/GodotSpatialContainerGame.kt b/platform/android/java/editor/src/picoos/java/org/godotengine/editor/GodotSpatialContainerGame.ktnew file mode 100644index 00000000000..83b765d9209--- /dev/null+++ b/platform/android/java/editor/src/picoos/java/org/godotengine/editor/GodotSpatialContainerGame.kt@@ -0,0 +1,42 @@+/*************************************************************************/+/* GodotSpatialContainerGame.kt */+/*************************************************************************/+/* This file is part of: */+/* GODOT ENGINE */+/* https://godotengine.org */+/*************************************************************************/+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */+/* */+/* 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. */+/*************************************************************************/++package org.godotengine.editor++import android.os.Bundle++/**+ * Provide support for running spatial container apps / games from the editor window on PicoOS.+ */+abstract class GodotSpatialContainerGame : BaseGodotSpatialContainerGame() {+ companion object {+ internal fun isSpatialContainerEnabled() = false+ }+}