Godot Engine – Multi-platform 2D and 3D game engine
visionOS: Implement additional Compositor Services features
Ricardo Sanchez-Saez053c7ddef1e3
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xmlindex 664d7dfbae5..69cc63a1c17 100644--- a/doc/classes/ProjectSettings.xml+++ b/doc/classes/ProjectSettings.xml@@ -3680,12 +3680,24 @@<member name="xr/shaders/enabled" type="bool" setter="" getter="" default="false">If [code]true[/code], Godot will compile shaders required for XR.</member>+ <member name="xr/visionos/dynamic_render_quality/enable" type="bool" setter="" getter="" default="false">+ If [code]true[/code], enables Dynamic Render Quality for the visionOS XR module. If enabled, you can dynamically set the render quality according to the complexity of your rendered scene. Higher render qualities increase the resolution of the textures provided by the visionOS XR module.+ </member>+ <member name="xr/visionos/dynamic_render_quality/maximum_quality" type="float" setter="" getter="" default="0.38">+ Set this value to the minimum value that makes sense for your app. The supported range is from [code]0.0[/code] (exclusive) to [code]1.0[/code] (inclusive). Setting a maximum render quality that you never use at runtime will use more memory than necessary.+ </member><member name="xr/visionos/enable_controller_tracking" type="bool" setter="" getter="" default="false">Enables and initializes visionOS controller tracking.</member><member name="xr/visionos/enable_hand_tracking" type="bool" setter="" getter="" default="false">Enables and initializes visionOS hand tracking.</member>+ <member name="xr/visionos/persistent_system_overlays" type="int" setter="" getter="" default="0">+ Initial visibility of the system overlays, such as the Home indicator, for the visionOS XR module's immersive scene. Change it at runtime with [member VisionOSXRInterface.persistent_system_overlays]. See [url=https://developer.apple.com/documentation/swiftui/view/persistentsystemoverlays(_:)]persistentSystemOverlays(_:)[/url].+ </member>+ <member name="xr/visionos/upper_limb_visibility" type="int" setter="" getter="" default="0">+ Initial visibility of the user's upper limbs for the visionOS XR module's immersive scene. Change it at runtime with [member VisionOSXRInterface.upper_limb_visibility]. See [url=https://developer.apple.com/documentation/swiftui/scene/upperlimbvisibility(_:)]upperLimbVisibility(_:)[/url].+ </member></members><signals><signal name="settings_changed">diff --git a/drivers/metal/rendering_context_driver_metal.cpp b/drivers/metal/rendering_context_driver_metal.cppindex d134eb2a921..109d32a2a52 100644--- a/drivers/metal/rendering_context_driver_metal.cpp+++ b/drivers/metal/rendering_context_driver_metal.cpp@@ -420,6 +420,8 @@ public:SurfaceCompositorServices(MTL::Device *p_device) :Surface(p_device) {dummy_framebuffer.set_texture_count(1);+ // Force the first screen_prepare_for_drawing to call resize() so the swap-chain format gets reported.+ needs_resize = true;}~SurfaceCompositorServices() override {@@ -431,7 +433,9 @@ public:}Error resize(uint32_t p_desired_framebuffer_count, RDD::DataFormat &r_format, RDD::ColorSpace &r_color_space) override final {- // Surface cannot be resized in Compositor Services mode+ // Compositor Services owns the swap chain; just report the format so the engine can initialize.+ r_format = RDD::DATA_FORMAT_R16G16B16A16_SFLOAT;+ r_color_space = RDD::COLOR_SPACE_REC709_LINEAR;return OK;}diff --git a/editor/export/editor_export_platform_apple_embedded.cpp b/editor/export/editor_export_platform_apple_embedded.cppindex 1073ca75071..6199070cad2 100644--- a/editor/export/editor_export_platform_apple_embedded.cpp+++ b/editor/export/editor_export_platform_apple_embedded.cpp@@ -412,7 +412,9 @@ void EditorExportPlatformAppleEmbedded::_fix_config_file(const Ref<EditorExportPString EditorExportPlatformAppleEmbedded::_process_config_file_line(const Ref<EditorExportPreset> &p_preset, const String &p_line, const AppleEmbeddedConfigData &p_config, bool p_debug, const CodeSigningDetails &p_code_signing) {String strnew;- if (p_line.contains("$binary")) {+ if (p_line.contains("$application_supports_multiple_scenes")) {+ strnew += p_line.replace("$application_supports_multiple_scenes", "<false/>") + "\n";+ } else if (p_line.contains("$binary")) {strnew += p_line.replace("$binary", p_config.binary_name) + "\n";} else if (p_line.contains("$modules_buildfile")) {strnew += p_line.replace("$modules_buildfile", p_config.modules_buildfile) + "\n";diff --git a/main/main.cpp b/main/main.cppindex 42dc481306f..31a3fed8840 100644--- a/main/main.cpp+++ b/main/main.cpp@@ -2899,6 +2899,14 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph// visionOS settingsGLOBAL_DEF_BASIC("xr/visionos/enable_hand_tracking", false);GLOBAL_DEF_BASIC("xr/visionos/enable_controller_tracking", false);+ // Dynamic render quality, to be used at runtime depending on the complexity of your scene, see https://developer.apple.com/documentation/compositorservices/defining-layer-renderer-quality.+ GLOBAL_DEF_BASIC("xr/visionos/dynamic_render_quality/enable", false);+ // The default value of 0.38 is equivalent to https://developer.apple.com/documentation/compositorservices/layerrenderer/capabilities/defaultrenderquality.+ // Do not set this value higher than the maximum value you're planning to use at runtime, or your app will use more memory than necessary.+ GLOBAL_DEF_BASIC(PropertyInfo(Variant::FLOAT, "xr/visionos/dynamic_render_quality/maximum_quality", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.38);+ // Initial values of the corresponding VisionOSXRInterface properties, applied when the immersive scene is created.+ GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/visionos/upper_limb_visibility", PROPERTY_HINT_ENUM, "Automatic,Visible,Hidden"), 0);+ GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/visionos/persistent_system_overlays", PROPERTY_HINT_ENUM, "Automatic,Visible,Hidden"), 0);#ifdef TOOLS_ENABLED// Disabled for now, using XR inside of the editor we'll be working on during the coming months.diff --git a/misc/dist/apple_embedded_xcode/godot_apple_embedded/godot_apple_embedded-Info.plist b/misc/dist/apple_embedded_xcode/godot_apple_embedded/godot_apple_embedded-Info.plistindex cce3fb5615c..8356dd507fc 100644--- a/misc/dist/apple_embedded_xcode/godot_apple_embedded/godot_apple_embedded-Info.plist+++ b/misc/dist/apple_embedded_xcode/godot_apple_embedded/godot_apple_embedded-Info.plist@@ -62,7 +62,7 @@<key>UIApplicationSceneManifest</key><dict>$application_scene_manifest_default_session_role- <key>UIApplicationSupportsMultipleScenes</key><false/>+ <key>UIApplicationSupportsMultipleScenes</key>$application_supports_multiple_scenes<key>UISceneConfigurations</key><dict><key>UIWindowSceneSessionRoleApplication</key>diff --git a/modules/visionos_xr/doc_classes/VisionOSXRInterface.xml b/modules/visionos_xr/doc_classes/VisionOSXRInterface.xmlindex 0e6606d75fc..8f836d26482 100644--- a/modules/visionos_xr/doc_classes/VisionOSXRInterface.xml+++ b/modules/visionos_xr/doc_classes/VisionOSXRInterface.xml@@ -25,6 +25,35 @@<tutorials></tutorials><members>+ <member name="immersion_style" type="int" setter="set_immersion_style" getter="get_immersion_style" enum="VisionOSXRInterface.ImmersionStyle" default="0">+ Immersion style of the immersive scene. Its initial value comes from the [member EditorExportPlatformVisionOS.application/immersion_style] export setting.+ </member>+ <member name="persistent_system_overlays" type="int" setter="set_persistent_system_overlays" getter="get_persistent_system_overlays" enum="VisionOSXRInterface.Visibility" default="0">+ Visibility of the system overlays, such as the Home indicator. Its initial value comes from the [member ProjectSettings.xr/visionos/persistent_system_overlays] project setting. See [url=https://developer.apple.com/documentation/swiftui/view/persistentsystemoverlays(_:)]persistentSystemOverlays(_:)[/url].+ </member>+ <member name="upper_limb_visibility" type="int" setter="set_upper_limb_visibility" getter="get_upper_limb_visibility" enum="VisionOSXRInterface.Visibility" default="0">+ Visibility of the user's upper limbs. Its initial value comes from the [member ProjectSettings.xr/visionos/upper_limb_visibility] project setting. See [url=https://developer.apple.com/documentation/swiftui/scene/upperlimbvisibility(_:)]upperLimbVisibility(_:)[/url].+ </member><member name="xr_play_area_mode" type="int" setter="set_play_area_mode" getter="get_play_area_mode" overrides="XRInterface" enum="XRInterface.PlayAreaMode" default="3" /></members>+ <constants>+ <constant name="IMMERSION_STYLE_FULL" value="0" enum="ImmersionStyle">+ The rendered content replaces the passthrough view of the real environment.+ </constant>+ <constant name="IMMERSION_STYLE_MIXED" value="1" enum="ImmersionStyle">+ The rendered content is displayed along with the passthrough view of the real environment.+ </constant>+ <constant name="IMMERSION_STYLE_PROGRESSIVE" value="2" enum="ImmersionStyle">+ The rendered content is displayed in a portal whose immersion level the user controls with the Digital Crown.+ </constant>+ <constant name="VISIBILITY_AUTOMATIC" value="0" enum="Visibility">+ The system decides whether the element is visible.+ </constant>+ <constant name="VISIBILITY_VISIBLE" value="1" enum="Visibility">+ The element is visible.+ </constant>+ <constant name="VISIBILITY_HIDDEN" value="2" enum="Visibility">+ The element is hidden.+ </constant>+ </constants></class>diff --git a/modules/visionos_xr/visionos_xr_interface.h b/modules/visionos_xr/visionos_xr_interface.hindex ece0f1d88c2..a8b5b7a61dc 100644--- a/modules/visionos_xr/visionos_xr_interface.h+++ b/modules/visionos_xr/visionos_xr_interface.h@@ -64,6 +64,18 @@ public:VISIONOS_XR_SIGNAL_MAX,};+ enum ImmersionStyle {+ IMMERSION_STYLE_FULL,+ IMMERSION_STYLE_MIXED,+ IMMERSION_STYLE_PROGRESSIVE,+ };++ enum Visibility {+ VISIBILITY_AUTOMATIC,+ VISIBILITY_VISIBLE,+ VISIBILITY_HIDDEN,+ };+private:bool initialized = false;XRInterface::TrackingStatus tracking_state;@@ -143,9 +155,16 @@ private:SafeNumeric<uint32_t> cached_render_target_width{ 0 };SafeNumeric<uint32_t> cached_render_target_height{ 0 };+ // Wraps cp_drawable_encode_present in a drawable render context with a no-op pass,+ // required by Compositor Services when the layer supports progressive immersion.+ // p_command_buffer is an id<MTLCommandBuffer> bridge-cast to void *, since this header+ // is included from non-Objective-C++ translation units.+ static void encode_drawable_no_op_and_present(cp_drawable_t p_drawable, cp_frame_t p_frame, void *p_command_buffer);+public:void initialize();void uninitialize();+ void prepare_screen();void set_minimum_supported_near_plane(float p_minimum_supported_near_plane);// p_current_frame should be an cp_frame_t pointer casted to uint64_t@@ -218,6 +237,18 @@ public:virtual XRInterface::PlayAreaMode get_play_area_mode() const override;virtual bool set_play_area_mode(XRInterface::PlayAreaMode p_mode) override;+ float get_current_render_quality();+ void set_current_render_quality(float p_render_quality);++ ImmersionStyle get_immersion_style();+ void set_immersion_style(ImmersionStyle p_immersion_style);++ Visibility get_upper_limb_visibility();+ void set_upper_limb_visibility(Visibility p_upper_limb_visibility);++ Visibility get_persistent_system_overlays();+ void set_persistent_system_overlays(Visibility p_persistent_system_overlays);+// Methods called from the game threadvirtual void process() override;virtual Size2 get_render_target_size() override;@@ -262,4 +293,7 @@ public:}};+VARIANT_ENUM_CAST(VisionOSXRInterface::ImmersionStyle);+VARIANT_ENUM_CAST(VisionOSXRInterface::Visibility);+#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_xr_interface.mm b/modules/visionos_xr/visionos_xr_interface.mmindex 0dca39f244d..8112ba39d4d 100644--- a/modules/visionos_xr/visionos_xr_interface.mm+++ b/modules/visionos_xr/visionos_xr_interface.mm@@ -39,6 +39,7 @@#include "core/input/input.h"#include "core/math/transform_3d.h"#include "core/object/callable_mp.h"+#include "core/object/class_db.h"#include "core/os/os.h"#include "core/os/thread.h"#include "core/string/print_string.h"@@ -85,6 +86,28 @@ void VisionOSXRInterface::_bind_methods() {for (int i = 0; i < VISIONOS_XR_SIGNAL_MAX; i++) {ADD_SIGNAL(MethodInfo(get_signal_name((SignalEnum)i)));}++ ClassDB::bind_method(D_METHOD("get_current_render_quality"), &VisionOSXRInterface::get_current_render_quality);+ ClassDB::bind_method(D_METHOD("set_current_render_quality", "render_quality"), &VisionOSXRInterface::set_current_render_quality);+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "current_render_quality"), "set_current_render_quality", "get_current_render_quality");++ BIND_ENUM_CONSTANT(IMMERSION_STYLE_FULL);+ BIND_ENUM_CONSTANT(IMMERSION_STYLE_MIXED);+ BIND_ENUM_CONSTANT(IMMERSION_STYLE_PROGRESSIVE);+ ClassDB::bind_method(D_METHOD("get_immersion_style"), &VisionOSXRInterface::get_immersion_style);+ ClassDB::bind_method(D_METHOD("set_immersion_style", "immersion_style"), &VisionOSXRInterface::set_immersion_style);+ ADD_PROPERTY(PropertyInfo(Variant::INT, "immersion_style", PROPERTY_HINT_ENUM, "Full,Mixed,Progressive"), "set_immersion_style", "get_immersion_style");++ BIND_ENUM_CONSTANT(VISIBILITY_AUTOMATIC);+ BIND_ENUM_CONSTANT(VISIBILITY_VISIBLE);+ BIND_ENUM_CONSTANT(VISIBILITY_HIDDEN);+ ClassDB::bind_method(D_METHOD("get_upper_limb_visibility"), &VisionOSXRInterface::get_upper_limb_visibility);+ ClassDB::bind_method(D_METHOD("set_upper_limb_visibility", "upper_limb_visibility"), &VisionOSXRInterface::set_upper_limb_visibility);+ ADD_PROPERTY(PropertyInfo(Variant::INT, "upper_limb_visibility", PROPERTY_HINT_ENUM, "Automatic,Visible,Hidden"), "set_upper_limb_visibility", "get_upper_limb_visibility");++ ClassDB::bind_method(D_METHOD("get_persistent_system_overlays"), &VisionOSXRInterface::get_persistent_system_overlays);+ ClassDB::bind_method(D_METHOD("set_persistent_system_overlays", "persistent_system_overlays"), &VisionOSXRInterface::set_persistent_system_overlays);+ ADD_PROPERTY(PropertyInfo(Variant::INT, "persistent_system_overlays", PROPERTY_HINT_ENUM, "Automatic,Visible,Hidden"), "set_persistent_system_overlays", "get_persistent_system_overlays");}VisionOSXRInterface::VisionOSXRInterface() {}@@ -143,6 +166,8 @@ bool VisionOSXRInterface::initialize() {float minimum_supported_near_plane = cp_layer_renderer_capabilities_supported_minimum_near_plane_distance(cs.layer_renderer_capabilities);rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::set_minimum_supported_near_plane).bind(minimum_supported_near_plane));+ rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::prepare_screen));+// Make this our primary interface, since it's used for renderingxr_server->set_primary_interface(this);}@@ -252,6 +277,13 @@ void VisionOSXRInterface::RenderThread::initialize() {initialized = true;}+void VisionOSXRInterface::RenderThread::prepare_screen() {+ ERR_NOT_ON_RENDER_THREAD;++ // Trigger the swap-chain resize so the format is initialized; must happen outside any submission.+ rendering_device->screen_prepare_for_drawing(DisplayServerEnums::MAIN_WINDOW_ID);+}+void VisionOSXRInterface::RenderThread::uninitialize() {ERR_NOT_ON_RENDER_THREAD;if (current_color_texture_id != RID()) {@@ -299,6 +331,98 @@ bool VisionOSXRInterface::set_play_area_mode(XRInterface::PlayAreaMode p_mode) {return p_mode == XR_PLAY_AREA_ROOMSCALE;}+float VisionOSXRInterface::get_current_render_quality() {+ return cp_layer_renderer_get_render_quality(cs.layer_renderer);+}++void VisionOSXRInterface::set_current_render_quality(float p_render_quality) {+ ERR_FAIL_COND_MSG(!GDTAppDelegateServiceVisionOS.isDynamicRenderQualityEnabled, "Attempting to set current render quality but Dynamic Render Quality has not been enabled in Project Settings.");+ float maxRenderQuality = GDTAppDelegateServiceVisionOS.maxRenderQuality;+ ERR_FAIL_COND_MSG(p_render_quality > GDTAppDelegateServiceVisionOS.maxRenderQuality, vformat("Attempting to set a current render quality higher than the Max Render Quality configured in Project Settings (%f).", maxRenderQuality));+ cp_layer_renderer_set_render_quality(cs.layer_renderer, p_render_quality);+}++VisionOSXRInterface::ImmersionStyle VisionOSXRInterface::get_immersion_style() {+ switch (GDTAppDelegateServiceVisionOS.immersionStyle) {+ case GDTImmersionStyleFull:+ return IMMERSION_STYLE_FULL;+ case GDTImmersionStyleMixed:+ return IMMERSION_STYLE_MIXED;+ case GDTImmersionStyleProgressive:+ return IMMERSION_STYLE_PROGRESSIVE;+ default:+ return IMMERSION_STYLE_FULL;+ }+}++void VisionOSXRInterface::set_immersion_style(ImmersionStyle p_immersion_style) {+ switch (p_immersion_style) {+ case IMMERSION_STYLE_FULL:+ GDTAppDelegateServiceVisionOS.immersionStyle = GDTImmersionStyleFull;+ break;+ case IMMERSION_STYLE_MIXED:+ GDTAppDelegateServiceVisionOS.immersionStyle = GDTImmersionStyleMixed;+ break;+ case IMMERSION_STYLE_PROGRESSIVE:+ GDTAppDelegateServiceVisionOS.immersionStyle = GDTImmersionStyleProgressive;+ break;+ }+}++VisionOSXRInterface::Visibility VisionOSXRInterface::get_upper_limb_visibility() {+ switch (GDTAppDelegateServiceVisionOS.upperLimbVisibility) {+ case GDTVisibilityAutomatic:+ return VISIBILITY_AUTOMATIC;+ case GDTVisibilityVisible:+ return VISIBILITY_VISIBLE;+ case GDTVisibilityHidden:+ return VISIBILITY_HIDDEN;+ default:+ return VISIBILITY_AUTOMATIC;+ }+}++void VisionOSXRInterface::set_upper_limb_visibility(Visibility p_upper_limb_visibility) {+ switch (p_upper_limb_visibility) {+ case VISIBILITY_AUTOMATIC:+ GDTAppDelegateServiceVisionOS.upperLimbVisibility = GDTVisibilityAutomatic;+ break;+ case VISIBILITY_VISIBLE:+ GDTAppDelegateServiceVisionOS.upperLimbVisibility = GDTVisibilityVisible;+ break;+ case VISIBILITY_HIDDEN:+ GDTAppDelegateServiceVisionOS.upperLimbVisibility = GDTVisibilityHidden;+ break;+ }+}++VisionOSXRInterface::Visibility VisionOSXRInterface::get_persistent_system_overlays() {+ switch (GDTAppDelegateServiceVisionOS.persistentSystemOverlays) {+ case GDTVisibilityAutomatic:+ return VISIBILITY_AUTOMATIC;+ case GDTVisibilityVisible:+ return VISIBILITY_VISIBLE;+ case GDTVisibilityHidden:+ return VISIBILITY_HIDDEN;+ default:+ return VISIBILITY_AUTOMATIC;+ }+}++void VisionOSXRInterface::set_persistent_system_overlays(Visibility p_persistent_system_overlays) {+ switch (p_persistent_system_overlays) {+ case VISIBILITY_AUTOMATIC:+ GDTAppDelegateServiceVisionOS.persistentSystemOverlays = GDTVisibilityAutomatic;+ break;+ case VISIBILITY_VISIBLE:+ GDTAppDelegateServiceVisionOS.persistentSystemOverlays = GDTVisibilityVisible;+ break;+ case VISIBILITY_HIDDEN:+ GDTAppDelegateServiceVisionOS.persistentSystemOverlays = GDTVisibilityHidden;+ break;+ }+}+void VisionOSXRInterface::set_head_pose_from_arkit() {ERR_FAIL_NULL_MSG(cs.current_frame, "Current frame is nil, process() has probably not been called, using identity transform.");@@ -692,6 +816,42 @@ Vector<RenderingServerTypes::BlitToScreen> VisionOSXRInterface::RenderThread::poreturn Vector<RenderingServerTypes::BlitToScreen>();}+// Wraps cp_drawable_encode_present in a drawable render context with a no-op load/store pass,+// which Compositor Services requires whenever the layer supports progressive immersion.+void VisionOSXRInterface::RenderThread::encode_drawable_no_op_and_present(cp_drawable_t p_drawable, cp_frame_t p_frame, void *p_command_buffer) {+ id<MTLCommandBuffer> command_buffer = (__bridge id<MTLCommandBuffer>)p_command_buffer;+ // A nil command buffer makes the Compositor Services API fail.+ ERR_FAIL_NULL_MSG(command_buffer, "Command buffer is nil, cannot add a drawable render context.");+ cp_drawable_render_context_t drawable_render_context = cp_drawable_add_render_context(p_drawable, command_buffer);++ id<MTLTexture> color_texture = cp_drawable_get_color_texture(p_drawable, 0);+ id<MTLTexture> depth_texture = cp_drawable_get_depth_texture(p_drawable, 0);++ MTLRenderPassDescriptor *render_pass_descriptor = [MTLRenderPassDescriptor renderPassDescriptor];+ render_pass_descriptor.colorAttachments[0].texture = color_texture;+ render_pass_descriptor.colorAttachments[0].loadAction = MTLLoadActionLoad;+ render_pass_descriptor.colorAttachments[0].storeAction = MTLStoreActionStore;+ // Compositor Services' compositing pipeline has no stencil attachment.+ render_pass_descriptor.depthAttachment.texture = depth_texture;+ render_pass_descriptor.depthAttachment.loadAction = MTLLoadActionLoad;+ render_pass_descriptor.depthAttachment.storeAction = MTLStoreActionStore;+ render_pass_descriptor.renderTargetArrayLength = cp_frame_get_drawable_target_view_count(p_frame, cp_drawable_get_target(p_drawable));+ size_t count = cp_drawable_get_rasterization_rate_map_count(p_drawable);+ if (count > 0) {+ id<MTLRasterizationRateMap> rasterization_rate_map = cp_drawable_get_rasterization_rate_map(p_drawable, 0);+ MTLSize logical_size = rasterization_rate_map.screenSize;+ render_pass_descriptor.rasterizationRateMap = rasterization_rate_map;+ render_pass_descriptor.renderTargetWidth = logical_size.width;+ render_pass_descriptor.renderTargetHeight = logical_size.height;+ }++ id<MTLRenderCommandEncoder> command_encoder = [command_buffer renderCommandEncoderWithDescriptor:render_pass_descriptor];++ cp_drawable_render_context_end_encoding(drawable_render_context, command_encoder);++ cp_drawable_encode_present(p_drawable, command_buffer);+}+void VisionOSXRInterface::RenderThread::encode_present(MTL3::MDCommandBuffer *p_cmd_buffer) {ERR_NOT_ON_RENDER_THREAD;@@ -700,7 +860,7 @@ void VisionOSXRInterface::RenderThread::encode_present(MTL3::MDCommandBuffer *p_}ERR_FAIL_NULL_MSG(current_drawable, "Current drawable is nil, process() has probably not been called.");- cp_drawable_encode_present(current_drawable, (__bridge id<MTLCommandBuffer>)p_cmd_buffer->get_command_buffer());+ encode_drawable_no_op_and_present(current_drawable, current_frame, p_cmd_buffer->get_command_buffer());current_drawable = nullptr;}diff --git a/platform/ios/SCsub b/platform/ios/SCsubindex e7969ae957e..1a9086ba1fe 100644--- a/platform/ios/SCsub+++ b/platform/ios/SCsub@@ -39,6 +39,9 @@ ios_lib = env_ios.add_library("ios", mm_file_names + list(swift_module))if "LIBS_EXTERNAL" in env_ios:env_ios.Depends(ios_lib, env_ios["LIBS_EXTERNAL"])+# Build the Swift->ObjC interop header before any ObjC++ source that #imports it.+env_ios.Depends(ios_lib, env_ios["SWIFT_OBJC_HEADER_TARGET"])+combine_command = env_ios.CommandNoCache("#bin/libgodot" + env_ios["LIBSUFFIX"], [ios_lib] + env_ios["LIBS"], env.Run(combine_libs_apple_embedded))diff --git a/platform/ios/bridging_header_ios.h b/platform/ios/bridging_header_ios.hindex 4fd31779a7a..dd9db768017 100644--- a/platform/ios/bridging_header_ios.h+++ b/platform/ios/bridging_header_ios.h@@ -32,5 +32,4 @@#import "godot_app_delegate_ios.h"-#import "drivers/apple_embedded/godot_app_delegate_service_apple_embedded.h"-#import "drivers/apple_embedded/godot_view_controller.h"+#import "drivers/apple_embedded/bridging_header_apple_embedded.h"diff --git a/platform/visionos/SCsub b/platform/visionos/SCsubindex 0d4d6a64f07..3eecadec5d0 100644--- a/platform/visionos/SCsub+++ b/platform/visionos/SCsub@@ -39,6 +39,9 @@ visionos_lib = env_visionos.add_library("visionos", mm_file_names + list(swift_mif "LIBS_EXTERNAL" in env_visionos:env_visionos.Depends(visionos_lib, env_visionos["LIBS_EXTERNAL"])+# Build the Swift->ObjC interop header before any ObjC++ source that #imports it.+env_visionos.Depends(visionos_lib, env_visionos["SWIFT_OBJC_HEADER_TARGET"])+combine_command = env_visionos.Command("#bin/libgodot" + env_visionos["LIBSUFFIX"], [visionos_lib] + env_visionos["LIBS"], combine_libs_apple_embedded)diff --git a/platform/visionos/app_visionos.swift b/platform/visionos/app_visionos.swiftindex 85d62141569..1675d4ecf52 100644--- a/platform/visionos/app_visionos.swift+++ b/platform/visionos/app_visionos.swift@@ -30,6 +30,13 @@import SwiftUI@preconcurrency import CompositorServices+import OSLog++// MARK: Helpers++extension os.Logger {+ static let godot = Logger(subsystem: "com.GodotFoundation.Godot", category: "SwiftUI")+}// MARK: Renderer@@ -37,7 +44,7 @@ final class RendererTaskExecutor: TaskExecutor {private let queue = DispatchQueue(label: "RenderThreadQueue", qos: .userInteractive)func enqueue(_ job: UnownedJob) {queue.async {- job.runSynchronously(on: self.asUnownedSerialExecutor())+ job.runSynchronously(on: self.asUnownedSerialExecutor())}}nonisolated func asUnownedSerialExecutor() -> UnownedTaskExecutor {@@ -46,6 +53,69 @@ final class RendererTaskExecutor: TaskExecutor {static let shared: RendererTaskExecutor = RendererTaskExecutor()}+// MARK: Swift Bridge++/// Source of truth for SwiftUI scene state. ObjC/C++ mutates it through+/// `GDTSwiftBridge`; the scene reads its properties directly (Observation tracking).+@MainActor+@Observable+final class Model {+ static let shared = Model()++ var immersionStyle: any ImmersionStyle+ var upperLimbVisibility: Visibility = .automatic+ var persistentSystemOverlays: Visibility = .automatic++ private init() {+ immersionStyle = Self.readInitialImmersionStyleFromInfoPlist()+ }++ /// Seeds the project-setting-backed properties. Called at layer creation rather than+ /// from `init()`, because `ProjectSettings` is not loaded yet when the scene is declared.+ func seedFromProjectSettings() {+ upperLimbVisibility = GDTAppDelegateServiceVisionOS.initialUpperLimbVisibility.swiftUI+ persistentSystemOverlays = GDTAppDelegateServiceVisionOS.initialPersistentSystemOverlays.swiftUI+ }++ private static func readInitialImmersionStyleFromInfoPlist() -> any ImmersionStyle {+ guard let sceneManifest = Bundle.main.infoDictionary?["UIApplicationSceneManifest"] as? [String: Any],+ let sceneConfigurations = sceneManifest["UISceneConfigurations"] as? [String: Any],+ let cpSceneConfiguration = sceneConfigurations["UISceneSessionRoleImmersiveSpaceApplication"] as? [[String: Any]],+ let immersionStyleString = cpSceneConfiguration.first?["UISceneInitialImmersionStyle"] as? String else {+ return .full+ }+ switch immersionStyleString {+ case "UIImmersionStyleFull": return .full+ case "UIImmersionStyleMixed": return .mixed+ case "UIImmersionStyleProgressive": return .progressive+ default: return .full+ }+ }+}++/// ObjC-accessible interface for `Model`.+@MainActor+@objc+public final class GDTSwiftBridge: NSObject {+ @objc public class var immersionStyle: GDTImmersionStyle {+ get { GDTImmersionStyle(fromSwiftUIType: Model.shared.immersionStyle) }+ set {+ guard let swiftUIStyle = newValue.swiftUI else { return }+ Model.shared.immersionStyle = swiftUIStyle+ }+ }++ @objc public class var upperLimbVisibility: GDTVisibility {+ get { GDTVisibility(fromSwiftUIType: Model.shared.upperLimbVisibility) }+ set { Model.shared.upperLimbVisibility = newValue.swiftUI }+ }++ @objc public class var persistentSystemOverlays: GDTVisibility {+ get { GDTVisibility(fromSwiftUIType: Model.shared.persistentSystemOverlays) }+ set { Model.shared.persistentSystemOverlays = newValue.swiftUI }+ }+}+// MARK: Compositor Services Scenestruct ContentStageConfiguration: CompositorLayerConfiguration {@@ -65,51 +135,106 @@ struct ContentStageConfiguration: CompositorLayerConfiguration {fatalError("Only the .layered layout is supported by Godot's visionOS XR module.")}configuration.layout = .layered++ if GDTAppDelegateServiceVisionOS.isDynamicRenderQualityEnabled {+ let maxRenderQuality = GDTAppDelegateServiceVisionOS.maxRenderQuality+ Logger.godot.log("Enabled dynamic render quality (maxRenderQuality: \(maxRenderQuality))")+ configuration.maxRenderQuality = .init(maxRenderQuality)+ }}}extension GDTCompositorServicesRenderer: @unchecked Sendable {}-struct CompositorServicesImmersiveSpace: Scene {+extension GDTImmersionStyle {- fileprivate static var initialImmersionStyle: ImmersionStyle {- guard let sceneManifest = Bundle.main.infoDictionary?["UIApplicationSceneManifest"] as? [String: Any],- let sceneConfigurations = sceneManifest["UISceneConfigurations"] as? [String: Any],- let cpSceneConfiguration = sceneConfigurations["UISceneSessionRoleImmersiveSpaceApplication"] as? [[String: Any]],- let immersionStyleString = cpSceneConfiguration.first?["UISceneInitialImmersionStyle"] as? String else {- return .full+ var swiftUI: ImmersionStyle? {+ switch self {+ case .full: return .full+ case .mixed: return .mixed+ case .progressive: return .progressive+ @unknown default: return nil+ }+ }++ init(fromSwiftUIType swiftUIType: ImmersionStyle) {+ switch swiftUIType.self {+ case is FullImmersionStyle: self = .full+ case is MixedImmersionStyle: self = .mixed+ case is ProgressiveImmersionStyle: self = .progressive+ default: fatalError("Unsupported style")+ }+ }++}++extension GDTVisibility {+ var swiftUI: Visibility {+ switch self {+ case .automatic: return .automatic+ case .visible: return .visible+ case .hidden: return .hidden+ @unknown default: return .automatic}- switch immersionStyleString {- case "UIImmersionStyleFull": return .full- case "UIImmersionStyleMixed": return .mixed- default: return .full+ }++ init(fromSwiftUIType visibility: Visibility) {+ switch visibility {+ case .automatic: self = .automatic+ case .visible: self = .visible+ case .hidden: self = .hidden}}+}++struct CompositorServicesImmersiveSpace: Scene {++ let model: Model = .shared- @State var renderer: GDTCompositorServicesRenderer!+ @State var renderer: GDTCompositorServicesRenderer!@State var didSetUpRenderer: Bool = falsevar body: some Scene {ImmersiveSpace(id: "ImmersiveSpace") {CompositorLayer(configuration: ContentStageConfiguration()) { @MainActor layerRenderer in++ Logger.godot.log("CompositorLayer init (initialImmersionStyle: \(String(describing: model.immersionStyle)))")++ model.seedFromProjectSettings()+GDTAppDelegateServiceVisionOS.layerRenderer = layerRendererrenderer = GDTCompositorServicesRenderer(layerRenderer: layerRenderer,capabilities: GDTAppDelegateServiceVisionOS.layerRendererCapabilities)++ let signposter = OSSignposter(subsystem: "org.godotengine.godot.compositorservices", category: "loading")+ let signpostID = signposter.makeSignpostID()+if !didSetUpRenderer {+ let signpost = signposter.beginInterval("setup", id: signpostID)renderer.setUp()didSetUpRenderer = true+ signposter.endInterval("setup", signpost)} else {+ let signpost = signposter.beginInterval("updateXRInterface", id: signpostID)renderer.updateXRInterface()+ signposter.endInterval("updateXRInterface", signpost)}Task(executorPreference: RendererTaskExecutor.shared) {+ let signpost = signposter.beginInterval("startRenderLoop", id: signpostID)await renderer.startRenderLoop()+ signposter.endInterval("startRenderLoop", signpost)}}.onWorldRecenter {renderer.worldRecentered()}}- .immersionStyle(selection: .constant(Self.initialImmersionStyle), in: .mixed, .full)+ .immersionStyle(+ selection: Binding(get: { model.immersionStyle }, set: { model.immersionStyle = $0 }),+ in: .mixed, .full, .progressive+ )+ .upperLimbVisibility(model.upperLimbVisibility)+ .persistentSystemOverlays(model.persistentSystemOverlays)}}@@ -128,7 +253,8 @@ struct SwiftUIApp: App {}()init() {- print("visionOS app init (useCompositorServices: \(useCompositorServices))")+ let useCompositorServices = self.useCompositorServices+ Logger.godot.log("visionOS app init (useCompositorServices: \(useCompositorServices))")GDTAppDelegateServiceVisionOS.renderMode = useCompositorServices ? .compositorServices : .windowed}diff --git a/platform/visionos/bridging_header_visionos.h b/platform/visionos/bridging_header_visionos.hindex 7dc98e708ac..75a76d1c785 100644--- a/platform/visionos/bridging_header_visionos.h+++ b/platform/visionos/bridging_header_visionos.h@@ -34,4 +34,4 @@#import "godot_app_delegate_visionos.h"#import "godot_compositor_services_renderer.h"-#import "drivers/apple_embedded/godot_view_controller.h"+#import "drivers/apple_embedded/bridging_header_apple_embedded.h"diff --git a/platform/visionos/detect.py b/platform/visionos/detect.pyindex 416c03f8693..7a76f4d6ad9 100644--- a/platform/visionos/detect.py+++ b/platform/visionos/detect.py@@ -138,7 +138,14 @@ def configure(env: "SConsEnvironment"):)env.Prepend(CPPPATH=["#platform/visionos"])- env.Append(CPPDEFINES=["VISIONOS_ENABLED", "APPLE_EMBEDDED_ENABLED", "UNIX_ENABLED", "COREAUDIO_ENABLED"])+ env.Append(+ CPPDEFINES=[+ "VISIONOS_ENABLED",+ "APPLE_EMBEDDED_ENABLED",+ "UNIX_ENABLED",+ "COREAUDIO_ENABLED",+ ]+ )if env["vulkan"]:print_warning("The visionOS platform does not support the Vulkan rendering driver")diff --git a/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xml b/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xmlindex f72b686f44d..0f56033d0bd 100644--- a/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xml+++ b/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xml@@ -48,7 +48,7 @@Interpolation method used to resize application icon.</member><member name="application/immersion_style" type="int" setter="" getter="">- The immersion style, only applicable if you have chosen the [code]Immersive[/code] app role. It can be [code]Full[/code] for a VR experience, or [code]Mixed[/code] for a mixed reality experience where the rendered content is display along with the real environment.+ Initial immersion style, only applicable if you have chosen the [code]Immersive[/code] app role. It can be [code]Full[/code] for a VR experience; [code]Mixed[/code] for a mixed reality experience where the rendered content is displayed along with the real environment; or [code]Progressive[/code] for a portal style experience where the user controls the immersion level. Change it at runtime with [member VisionOSXRInterface.immersion_style].</member><member name="application/min_visionos_version" type="String" setter="" getter=""></member>diff --git a/platform/visionos/export/export_plugin.cpp b/platform/visionos/export/export_plugin.cppindex 42045bcd68c..1bbaf9de256 100644--- a/platform/visionos/export/export_plugin.cpp+++ b/platform/visionos/export/export_plugin.cpp@@ -59,7 +59,7 @@ void EditorExportPlatformVisionOS::get_export_options(List<ExportOption> *r_optir_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "application/min_visionos_version"), get_minimum_deployment_target()));r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/app_role", PROPERTY_HINT_ENUM, "Window,Immersive"), 0));- r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/immersion_style", PROPERTY_HINT_ENUM, "Full,Mixed"), 1));+ r_options->push_back(ExportOption(PropertyInfo(Variant::INT, "application/immersion_style", PROPERTY_HINT_ENUM, "Full,Mixed,Progressive"), 1));// Front layer falls back to the project icon; middle/back use a black placeholder when unset.r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "icons/icon_front_layer_1024x1024", PROPERTY_HINT_FILE_PATH, "*.svg,*.png,*.webp,*.jpg,*.jpeg"), ""));@@ -229,6 +229,11 @@ String EditorExportPlatformVisionOS::_process_config_file_line(const Ref<EditorE} else if (p_line.contains("$valid_archs")) {strnew += p_line.replace("$valid_archs", "arm64") + "\n";+ // Application Scene Manifest - Supports Multiple Scenes+ } else if (p_line.contains("$application_supports_multiple_scenes")) {+ // visionOS overridden to true to support changing immersion style at runtime.+ strnew += p_line.replace("$application_supports_multiple_scenes", "<true/>") + "\n";+// Application Scene Manifest - Default Session Role} else if (p_line.contains("$application_scene_manifest_default_session_role")) {int app_role_enum = (int)p_preset->get("application/app_role");@@ -261,6 +266,9 @@ String EditorExportPlatformVisionOS::_process_config_file_line(const Ref<EditorEcase 1: // Mixedinitial_immersion_style = "UIImmersionStyleMixed";break;+ case 2: // Progressive+ initial_immersion_style = "UIImmersionStyleProgressive";+ break;}String value =diff --git a/platform/visionos/godot_app_delegate_service_visionos.h b/platform/visionos/godot_app_delegate_service_visionos.hindex 7cca40dacaf..f44cb92157f 100644--- a/platform/visionos/godot_app_delegate_service_visionos.h+++ b/platform/visionos/godot_app_delegate_service_visionos.h@@ -41,10 +41,34 @@ typedef NS_ENUM(NSInteger, GDTRenderMode) {GDTRenderModeCompositorServices = RenderModeVisionOS::COMPOSITOR_SERVICES};+typedef NS_ENUM(NSInteger, GDTImmersionStyle) {+ GDTImmersionStyleFull,+ GDTImmersionStyleMixed,+ GDTImmersionStyleProgressive+};++typedef NS_ENUM(NSInteger, GDTVisibility) {+ GDTVisibilityAutomatic,+ GDTVisibilityVisible,+ GDTVisibilityHidden+};+@interface GDTAppDelegateServiceVisionOS : GDTAppDelegateService-@property(assign, class, nonatomic) GDTRenderMode renderMode;-@property(weak, class, nonatomic, nullable) cp_layer_renderer_t layerRenderer;-@property(strong, class, nonatomic, nullable) cp_layer_renderer_capabilities_t layerRendererCapabilities;+@property(class, nonatomic, assign) GDTRenderMode renderMode;+@property(class, nonatomic, weak, nullable) cp_layer_renderer_t layerRenderer;+@property(class, nonatomic, strong, nullable) cp_layer_renderer_capabilities_t layerRendererCapabilities;++@property(class, nonatomic, assign, readonly) BOOL isDynamicRenderQualityEnabled;+@property(class, nonatomic, assign, readonly) float maxRenderQuality;++@property(class, nonatomic, assign, readonly) GDTVisibility initialUpperLimbVisibility;+@property(class, nonatomic, assign, readonly) GDTVisibility initialPersistentSystemOverlays;++@property(class, nonatomic, assign) GDTImmersionStyle immersionStyle;++@property(class, nonatomic, assign) GDTVisibility upperLimbVisibility;++@property(class, nonatomic, assign) GDTVisibility persistentSystemOverlays;@enddiff --git a/platform/visionos/godot_app_delegate_service_visionos.mm b/platform/visionos/godot_app_delegate_service_visionos.mmindex 5e9ed5e4a3e..fa59f75e903 100644--- a/platform/visionos/godot_app_delegate_service_visionos.mm+++ b/platform/visionos/godot_app_delegate_service_visionos.mm@@ -30,8 +30,13 @@#import "godot_app_delegate_service_visionos.h"+#include "core/config/project_settings.h"#import "drivers/apple_embedded/os_apple_embedded.h"+// Generated by `setup_swift_builder` (`platform_methods.py`). Exposes `@objc` Swift+// declarations (e.g. `GDTSwiftBridge`) to ObjC++.+#import "godot_swift_module-Swift.gen.h"+static GDTRenderMode _renderMode = GDTRenderModeWindowed;static __weak cp_layer_renderer_t _layerRenderer = nil;static __strong cp_layer_renderer_capabilities_t _layerRendererCapabilities = nil;@@ -78,6 +83,50 @@ static __strong cp_layer_renderer_capabilities_t _layerRendererCapabilities = ni_layerRendererCapabilities = layerRendererCapabilities;}++ (BOOL)isDynamicRenderQualityEnabled {+ return GLOBAL_GET("xr/visionos/dynamic_render_quality/enable");+}+++ (float)maxRenderQuality {+ return GLOBAL_GET("xr/visionos/dynamic_render_quality/maximum_quality");+}+++ (GDTVisibility)initialUpperLimbVisibility {+ return (GDTVisibility)(int)GLOBAL_GET("xr/visionos/upper_limb_visibility");+}+++ (GDTVisibility)initialPersistentSystemOverlays {+ return (GDTVisibility)(int)GLOBAL_GET("xr/visionos/persistent_system_overlays");+}++// `immersionStyle`, `upperLimbVisibility` and `persistentSystemOverlays` are stored on the+// SwiftUI `Model`; these accessors forward through `GDTSwiftBridge`, which does the+// SwiftUI<->ObjC conversion.+++ (GDTImmersionStyle)immersionStyle {+ return GDTSwiftBridge.immersionStyle;+}+++ (void)setImmersionStyle:(GDTImmersionStyle)immersionStyle {+ GDTSwiftBridge.immersionStyle = immersionStyle;+}+++ (GDTVisibility)upperLimbVisibility {+ return GDTSwiftBridge.upperLimbVisibility;+}+++ (void)setUpperLimbVisibility:(GDTVisibility)upperLimbVisibility {+ GDTSwiftBridge.upperLimbVisibility = upperLimbVisibility;+}+++ (GDTVisibility)persistentSystemOverlays {+ return GDTSwiftBridge.persistentSystemOverlays;+}+++ (void)setPersistentSystemOverlays:(GDTVisibility)persistentSystemOverlays {+ GDTSwiftBridge.persistentSystemOverlays = persistentSystemOverlays;+}+- (void)sceneDidBecomeActive:(UIScene *)scene API_AVAILABLE(ios(13.0), tvos(13.0), visionos(1.0)) {[super sceneDidBecomeActive:scene];diff --git a/platform_methods.py b/platform_methods.pyindex 983003dd978..c0a91355a08 100644--- a/platform_methods.py+++ b/platform_methods.py@@ -348,12 +348,16 @@ def setup_swift_builder(bridging_header_path = current_path + "/" + bridging_header_filenameswift_module_name = "godot_swift_module"+ # Standard `<module>-Swift.h` name plus `.gen.h` so it's covered by `*.gen.*` in `.gitignore`.+ swift_objc_header_path = current_path + "/" + swift_module_name + "-Swift.gen.h"env["SWIFTC"] = swiftc_path # Swift compiler# Flags for the whole-module Swift compile.common_swift_flags = ["-warnings-as-errors","-cxx-interoperability-mode=default","-emit-object",+ "-emit-objc-header-path",+ swift_objc_header_path,"-target",swiftc_target,"-sdk",@@ -368,6 +372,7 @@ def setup_swift_builder("-I./", # Pass the current directory as the header root so bridging headers can include files from any point of the hierarchy]# All sources are compiled together into a single object, which requires whole-module mode.+ # Whole-module mode is also required for `-emit-objc-header-path`; per-file mode drops it.env["SWIFTCFLAGS"] = ["-wmo"] + common_swift_flagsif "osxcross" in env:@@ -404,14 +409,23 @@ def setup_swift_builder(return swift_action- # Define Builder that compiles all Swift sources into a single object file.+ def swift_emitter(target, source, env):+ # Redirect the object, but keep the interop header next to the Swift sources so+ # ObjC++ in the same directory resolves it with a quoted `#import`.+ target, source = methods.redirect_emitter(target, source, env)+ return target + [env.File(swift_objc_header_path)], source++ # Define Builder that compiles all Swift sources into a single object file plus the+ # `@objc` interop header.swift_builder = Builder(- generator=generate_swift_action, suffix=env["OBJSUFFIX"], src_suffix=".swift", emitter=methods.redirect_emitter+ generator=generate_swift_action, suffix=env["OBJSUFFIX"], src_suffix=".swift", emitter=swift_emitter)env.Append(BUILDERS={"SwiftModule": swift_builder})swift_sources = [env.File(current_path + "/" + file) for file in all_swift_files]- swift_module = env.SwiftModule(current_path + "/" + swift_module_name, swift_sources)+ swift_module, swift_objc_header = env.SwiftModule(current_path + "/" + swift_module_name, swift_sources)+ # Lets ObjC++ sources that `#import` the interop header order against its generation.+ env["SWIFT_OBJC_HEADER_TARGET"] = swift_objc_header- return swift_module+ return [swift_module]