Godot Engine – Multi-platform 2D and 3D game engine
Added support for hand tracking and PSVR2 controllers on Apple Vision Pro, in XR.
Olivier Pinone0c10e673009
diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xmlindex 53f3037f912..664d7dfbae5 100644--- a/doc/classes/ProjectSettings.xml+++ b/doc/classes/ProjectSettings.xml@@ -3680,6 +3680,12 @@<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/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></members><signals><signal name="settings_changed">diff --git a/editor/export/editor_export_platform_apple_embedded.cpp b/editor/export/editor_export_platform_apple_embedded.cppindex 40563d6e341..36e6ac4c88c 100644--- a/editor/export/editor_export_platform_apple_embedded.cpp+++ b/editor/export/editor_export_platform_apple_embedded.cpp@@ -213,6 +213,12 @@ String EditorExportPlatformAppleEmbedded::get_export_option_warning(const Editorreturn String();}+void EditorExportPlatformAppleEmbedded::get_usage_descriptions(List<EditorExportPlatformAppleEmbedded::UsageDescription> *r_descriptions) const {+ r_descriptions->push_back({ "privacy/camera_usage_description", "NSCameraUsageDescription", "Provide a message if you need to use the camera" });+ r_descriptions->push_back({ "privacy/microphone_usage_description", "NSMicrophoneUsageDescription", "Provide a message if you need to use the microphone" });+ r_descriptions->push_back({ "privacy/photolibrary_usage_description", "NSPhotoLibraryUsageDescription", "Provide a message if you need access to the photo library" });+}+void EditorExportPlatformAppleEmbedded::_notification(int p_what) {#ifdef MACOS_ENABLEDif (p_what == NOTIFICATION_POSTINITIALIZE) {@@ -330,12 +336,12 @@ void EditorExportPlatformAppleEmbedded::get_export_options(List<ExportOption> *rr_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data/accessible_from_files_app"), false));r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data/accessible_from_itunes_sharing"), false));- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/camera_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need to use the camera"), ""));- r_options->push_back(ExportOption(PropertyInfo(Variant::DICTIONARY, "privacy/camera_usage_description_localized", PROPERTY_HINT_LOCALIZABLE_STRING), Dictionary()));- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/microphone_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need to use the microphone"), ""));- r_options->push_back(ExportOption(PropertyInfo(Variant::DICTIONARY, "privacy/microphone_usage_description_localized", PROPERTY_HINT_LOCALIZABLE_STRING), Dictionary()));- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "privacy/photolibrary_usage_description", PROPERTY_HINT_PLACEHOLDER_TEXT, "Provide a message if you need access to the photo library"), ""));- r_options->push_back(ExportOption(PropertyInfo(Variant::DICTIONARY, "privacy/photolibrary_usage_description_localized", PROPERTY_HINT_LOCALIZABLE_STRING), Dictionary()));+ List<UsageDescription> usage_descriptions;+ get_usage_descriptions(&usage_descriptions);+ for (const UsageDescription &usage_description : usage_descriptions) {+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, usage_description.preset_key, PROPERTY_HINT_PLACEHOLDER_TEXT, usage_description.placeholder), ""));+ r_options->push_back(ExportOption(PropertyInfo(Variant::DICTIONARY, usage_description.preset_key + "_localized", PROPERTY_HINT_LOCALIZABLE_STRING), Dictionary()));+ }for (uint64_t i = 0; i < std_size(api_info); ++i) {String prop_name = vformat("privacy/%s_access_reasons", api_info[i].prop_name);@@ -2053,9 +2059,8 @@ Error EditorExportPlatformAppleEmbedded::_export_project_helper(const Ref<Editorreturn ERR_FILE_NOT_FOUND;}- Dictionary camera_usage_descriptions = p_preset->get("privacy/camera_usage_description_localized");- Dictionary microphone_usage_descriptions = p_preset->get("privacy/microphone_usage_description_localized");- Dictionary photolibrary_usage_descriptions = p_preset->get("privacy/photolibrary_usage_description_localized");+ List<UsageDescription> usage_descriptions;+ get_usage_descriptions(&usage_descriptions);const String project_name = get_project_setting(p_preset, "application/config/name");const Dictionary appnames = get_project_setting(p_preset, "application/config/name_localized");@@ -2072,9 +2077,9 @@ Error EditorExportPlatformAppleEmbedded::_export_project_helper(const Ref<Editorf->store_line("/* Localized versions of Info.plist keys */");f->store_line("");f->store_line("CFBundleDisplayName = \"" + project_name.xml_escape(true) + "\";");- f->store_line("NSCameraUsageDescription = \"" + p_preset->get("privacy/camera_usage_description").operator String().xml_escape(true) + "\";");- f->store_line("NSMicrophoneUsageDescription = \"" + p_preset->get("privacy/microphone_usage_description").operator String().xml_escape(true) + "\";");- f->store_line("NSPhotoLibraryUsageDescription = \"" + p_preset->get("privacy/photolibrary_usage_description").operator String().xml_escape(true) + "\";");+ for (const UsageDescription &usage_description : usage_descriptions) {+ f->store_line(usage_description.plist_key + " = \"" + p_preset->get(usage_description.preset_key).operator String().xml_escape(true) + "\";");+ }}for (const String &lang : locales) {@@ -2098,14 +2103,11 @@ Error EditorExportPlatformAppleEmbedded::_export_project_helper(const Ref<Editorf->store_line("CFBundleDisplayName = \"" + appnames[lang].operator String().xml_escape(true) + "\";");}- if (camera_usage_descriptions.has(lang)) {- f->store_line("NSCameraUsageDescription = \"" + camera_usage_descriptions[lang].operator String().xml_escape(true) + "\";");- }- if (microphone_usage_descriptions.has(lang)) {- f->store_line("NSMicrophoneUsageDescription = \"" + microphone_usage_descriptions[lang].operator String().xml_escape(true) + "\";");- }- if (photolibrary_usage_descriptions.has(lang)) {- f->store_line("NSPhotoLibraryUsageDescription = \"" + photolibrary_usage_descriptions[lang].operator String().xml_escape(true) + "\";");+ for (const UsageDescription &usage_description : usage_descriptions) {+ Dictionary localized = p_preset->get(usage_description.preset_key + "_localized");+ if (localized.has(lang)) {+ f->store_line(usage_description.plist_key + " = \"" + localized[lang].operator String().xml_escape(true) + "\";");+ }}}}diff --git a/editor/export/editor_export_platform_apple_embedded.h b/editor/export/editor_export_platform_apple_embedded.hindex 55156f975f5..bbea996d2c6 100644--- a/editor/export/editor_export_platform_apple_embedded.h+++ b/editor/export/editor_export_platform_apple_embedded.h@@ -187,6 +187,12 @@ protected:bool force_opaque;};+ struct UsageDescription {+ String preset_key;+ String plist_key;+ String placeholder;+ };+private:void _fix_config_file(const Ref<EditorExportPreset> &p_preset, Vector<uint8_t> &pfile, const AppleEmbeddedConfigData &p_config, bool p_debug);@@ -228,6 +234,8 @@ protected:virtual Vector<IconInfo> get_icon_infos() const = 0;+ virtual void get_usage_descriptions(List<UsageDescription> *r_descriptions) const;+void _notification(int p_what);virtual void get_platform_features(List<String> *r_features) const override {diff --git a/main/main.cpp b/main/main.cppindex be4016f14d9..42dc481306f 100644--- a/main/main.cpp+++ b/main/main.cpp@@ -2896,6 +2896,10 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phGLOBAL_DEF_BASIC("xr/openxr/binding_modifiers/analog_threshold", false);GLOBAL_DEF_RST_BASIC("xr/openxr/binding_modifiers/dpad_binding", false);+ // visionOS settings+ GLOBAL_DEF_BASIC("xr/visionos/enable_hand_tracking", false);+ GLOBAL_DEF_BASIC("xr/visionos/enable_controller_tracking", false);+#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 72b448f7f13..cce3fb5615c 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@@ -75,5 +75,7 @@$application_scene_manifest_immersive_configuration</dict></dict>+ $hand_tracking_usage_description+ $accessory_tracking_usage_description</dict></plist>diff --git a/modules/visionos_xr/doc_classes/VisionOSXRInterface.xml b/modules/visionos_xr/doc_classes/VisionOSXRInterface.xmlindex 363c277384b..0e6606d75fc 100644--- a/modules/visionos_xr/doc_classes/VisionOSXRInterface.xml+++ b/modules/visionos_xr/doc_classes/VisionOSXRInterface.xml@@ -1,10 +1,14 @@<?xml version="1.0" encoding="UTF-8" ?><class name="VisionOSXRInterface" inherits="XRInterface" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"><brief_description>- visionOS XR implementation for rendering in immersive mode.+ visionOS XR implementation for rendering in immersive mode, hand tracking, and controller tracking.</brief_description><description>- This is a visionOS XR implementation for rendering in immersive mode. It uses the Compositor Services framework to render an Immersive scene. It supports the full and mixed immersive modes mode. To use this module, you must set the [member EditorExportPlatformVisionOS.application/app_role] export setting to [code]Immersive[/code]. You can choose the immersion style using the [member EditorExportPlatformVisionOS.application/immersion_style] export setting. You must use the Metal rendering driver, and only the Mobile renderer is supported for now. You can initialize this interface in the [method Node._ready] method of any of your nodes as follows:+ This is a visionOS XR implementation. It has three modules:+ - the CompositorServices module, to render with Godot in immersive mode+ - the hand tracking module, using Apple's ARKit+ - the spatial controller module, using Apple's ARKit and GCController.+ Those modules can be enabled/disabled independently. The rendering module uses the CompositorServices framework to render an Immersive scene. It supports the full and mixed immersion modes. To use this module, you must set the [member EditorExportPlatformVisionOS.application/app_role] export setting to [code]Immersive[/code]. You can choose the immersion style using the [member EditorExportPlatformVisionOS.application/immersion_style] export setting. You must use the Metal rendering driver, and only the Mobile renderer is supported for now. You can initialize this interface in the [method Node._ready] method of any of your nodes as follows:[codeblock]func _ready() -> void:var interface = XRServer.find_interface("visionOS")@@ -15,6 +19,8 @@viewport.use_hdr_2d = true[/codeblock]Do not initialize the XR interface in the [method Node._process] method, as this will initialize it at some unspecified point in the middle of the frame rendering, possibly causing incorrect visionOS API usage.+ Enable the hand tracking module with the [member ProjectSettings.xr/visionos/enable_hand_tracking] project setting. It will populate the [code]"/user/hand_tracker/left"[/code] and [code]"/user/hand_tracker/right"[/code] XRHandTrackers.+ Enable the spatial controller module using the [member ProjectSettings.xr/visionos/enable_controller_tracking] project setting. It will populate the [code]"left_hand"[/code] and [code]"right_hand"[/code] reserved XRController trackers.</description><tutorials></tutorials>diff --git a/modules/visionos_xr/visionos_controller_tracking.h b/modules/visionos_xr/visionos_controller_tracking.hnew file mode 100644index 00000000000..e28f4d8a4b8--- /dev/null+++ b/modules/visionos_xr/visionos_controller_tracking.h@@ -0,0 +1,91 @@+/**************************************************************************/+/* visionos_controller_tracking.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++#ifdef VISIONOS_ENABLED++#include "visionos_definitions.h"++#ifdef __OBJC__+#define Key GodotKey+#import <CoreHaptics/CoreHaptics.h>+#import <GameController/GameController.h>+#undef Key+#else // __OBJC__+typedef struct GCController *GCController_t;+typedef struct CHHapticEngine *CHHapticEngine_t;+#endif // __OBJC__++class VisionOSXRInterface;++// Controller tracking using ARKit and GCController+struct VisionOSControllerTracking {+ bool enabled = false;+ VisionOSAuthorizationStatus authorization = VisionOSAuthorizationStatus::NOT_DETERMINED;++ bool active() const { return enabled && authorization == VisionOSAuthorizationStatus::ALLOWED; }++ // ARKit state+ ar_accessory_tracking_provider_t accessory_tracking_provider = nullptr;+ ar_accessories_t accessories = nullptr;+ ar_accessory_anchor_t left_controller_anchor = nullptr;+ ar_accessory_anchor_t right_controller_anchor = nullptr;++ // Controller state+ Ref<XRControllerTracker> left_controller_tracker;+ Ref<XRControllerTracker> right_controller_tracker;+ GCController *left_gc_controller = nullptr;+ GCController *right_gc_controller = nullptr;+ CHHapticEngine *left_haptic_engine = nullptr;+ CHHapticEngine *right_haptic_engine = nullptr;++ // Notification observers+ id controller_observer = nullptr;+ id controller_disconnect_observer = nullptr;++ void initialize(XRServer *p_xr_server, VisionOSXRInterface *p_xr_interface);+ void uninitialize(XRServer *p_xr_server);++ void init_for_controller(GCController *p_controller);+ void setup_controller_notifications();+ void cleanup_controller_notifications();+ void handle_controller_disconnect(GCController *p_controller);+ void update_accessories_list();+ void update_controller_trackers_from_arkit(CFTimeInterval p_trackable_anchor_time);+ void update_controller_from_anchor(Ref<XRControllerTracker> p_controller_tracker, ar_accessory_anchor_t p_controller_anchor, GCController *p_gc_controller);++ // Called directly from the same function on the XRInterface+ void trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec);++ VisionOSXRInterface *xr_interface = nullptr; // assigned on initialization+};++#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_controller_tracking.mm b/modules/visionos_xr/visionos_controller_tracking.mmnew file mode 100644index 00000000000..d8e8162bd7e--- /dev/null+++ b/modules/visionos_xr/visionos_controller_tracking.mm@@ -0,0 +1,395 @@+/**************************************************************************/+/* visionos_controller_tracking.mm */+/**************************************************************************/+/* 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. */+/**************************************************************************/++#ifdef VISIONOS_ENABLED++#include "visionos_controller_tracking.h"++#include "visionos_simd_helpers.h"+#include "visionos_xr_interface.h"++void VisionOSControllerTracking::initialize(XRServer *p_xr_server, VisionOSXRInterface *p_xr_interface) {+ accessories = ar_accessories_create();++ xr_interface = p_xr_interface;++ // Scan existing controllers+ for (GCController *controller in GCController.controllers) {+ init_for_controller(controller);+ }++ setup_controller_notifications();++ left_controller_tracker.instantiate();+ left_controller_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_LEFT);+ left_controller_tracker->set_tracker_name("left_hand");+ left_controller_tracker->set_tracker_desc("visionOS Left Controller");+ p_xr_server->add_tracker(left_controller_tracker);++ right_controller_tracker.instantiate();+ right_controller_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_RIGHT);+ right_controller_tracker->set_tracker_name("right_hand");+ right_controller_tracker->set_tracker_desc("visionOS Right Controller");+ p_xr_server->add_tracker(right_controller_tracker);++ ar_accessory_tracking_configuration_t accessory_tracking_configuration = ar_accessory_tracking_configuration_create();+ ar_accessory_tracking_configuration_set_accessories(accessory_tracking_configuration, accessories);+ accessory_tracking_provider = ar_accessory_tracking_provider_create(accessory_tracking_configuration);+}++void VisionOSControllerTracking::uninitialize(XRServer *p_xr_server) {+ if (accessory_tracking_provider != nullptr) {+ accessory_tracking_provider = nullptr;+ }++ if (p_xr_server != nullptr) {+ if (left_controller_tracker.is_valid()) {+ p_xr_server->remove_tracker(left_controller_tracker);+ left_controller_tracker.unref();+ }+ if (right_controller_tracker.is_valid()) {+ p_xr_server->remove_tracker(right_controller_tracker);+ right_controller_tracker.unref();+ }+ }++ left_controller_anchor = nullptr;+ right_controller_anchor = nullptr;+ left_gc_controller = nullptr;+ right_gc_controller = nullptr;+ left_haptic_engine = nullptr;+ right_haptic_engine = nullptr;++ cleanup_controller_notifications();+}++void VisionOSControllerTracking::init_for_controller(GCController *p_controller) {+ ar_accessory_load_from_device(+ p_controller,+ ^(id<GCDevice> _Nonnull device, bool success, ar_error_t _Nullable error, ar_accessory_t _Nullable accessory) {+ ERR_FAIL_COND_MSG(!success, "Error loading from GCDevice...");++ dispatch_async(dispatch_get_main_queue(), ^{+ ar_accessory_chirality_t chirality = ar_accessory_get_inherent_chirality(accessory);+ if (chirality == ar_accessory_chirality_left) {+ left_gc_controller = p_controller;+ if (left_gc_controller != nullptr && left_gc_controller.haptics != nullptr) {+ left_haptic_engine = [left_gc_controller.haptics createEngineWithLocality:GCHapticsLocalityDefault];+ }+ ar_accessories_add_accessory(accessories, accessory);+ } else if (chirality == ar_accessory_chirality_right) {+ right_gc_controller = p_controller;+ if (right_gc_controller != nullptr && right_gc_controller.haptics != nullptr) {+ right_haptic_engine = [right_gc_controller.haptics createEngineWithLocality:GCHapticsLocalityDefault];+ }+ ar_accessories_add_accessory(accessories, accessory);+ } else {+ ERR_PRINT("Accessory with undefined chirality...");+ }+ update_accessories_list();+ });+ });+}++void VisionOSControllerTracking::setup_controller_notifications() {+ controller_observer = [NSNotificationCenter.defaultCenter+ addObserverForName:GCControllerDidConnectNotification+ object:nil+ queue:NSOperationQueue.mainQueue+ usingBlock:^(NSNotification *notification) {+ GCController *controller = (GCController *)notification.object;+ init_for_controller(controller);+ }];++ controller_disconnect_observer = [NSNotificationCenter.defaultCenter+ addObserverForName:GCControllerDidDisconnectNotification+ object:nil+ queue:NSOperationQueue.mainQueue+ usingBlock:^(NSNotification *notification) {+ GCController *controller = (GCController *)notification.object;+ handle_controller_disconnect(controller);+ }];+}++void VisionOSControllerTracking::handle_controller_disconnect(GCController *p_controller) {+ if (left_gc_controller != nullptr && left_gc_controller == p_controller) {+ if (left_controller_anchor != nullptr) {+ ar_accessory_t accessory_left = ar_accessory_anchor_get_accessory(left_controller_anchor);+ if (accessory_left != nullptr) {+ ar_accessories_remove_accessory(accessories, accessory_left);+ left_controller_anchor = nullptr;+ left_gc_controller = nullptr;+ left_haptic_engine = nullptr;+ update_accessories_list();+ }+ }+ } else if (right_gc_controller != nullptr && right_gc_controller == p_controller) {+ if (right_controller_anchor != nullptr) {+ ar_accessory_t accessory_right = ar_accessory_anchor_get_accessory(right_controller_anchor);+ if (accessory_right != nullptr) {+ ar_accessories_remove_accessory(accessories, accessory_right);+ right_controller_anchor = nullptr;+ right_gc_controller = nullptr;+ right_haptic_engine = nullptr;+ update_accessories_list();+ }+ }+ }+}++void VisionOSControllerTracking::cleanup_controller_notifications() {+ if (controller_observer) {+ [NSNotificationCenter.defaultCenter removeObserver:controller_observer];+ controller_observer = nullptr;+ }++ if (controller_disconnect_observer) {+ [NSNotificationCenter.defaultCenter removeObserver:controller_disconnect_observer];+ controller_disconnect_observer = nullptr;+ }+}++void VisionOSControllerTracking::update_accessories_list() {+ // Restarting the ar_session when the configuration changed+ ar_accessory_tracking_configuration_t accessory_tracking_configuration = ar_accessory_tracking_configuration_create();+ ar_accessory_tracking_configuration_set_accessories(accessory_tracking_configuration, accessories);++ accessory_tracking_provider = ar_accessory_tracking_provider_create(accessory_tracking_configuration);++ if (authorization == VisionOSAuthorizationStatus::ALLOWED) {+ xr_interface->run_ar_session();+ }+}++// Button mapping logic+namespace {++struct ButtonMapping {+ GCInputButtonName gc_input;+ // Used for triggers+ const char *action_name_float;+ // Used for button presses+ const char *action_name_bool;+};++static const ButtonMapping button_mappings[] = {+ { GCInputGripButton, "grip", "grip_click" },+ { GCInputTrigger, "trigger", "trigger_click" },+ { GCInputButtonA, nullptr, "ax_button" },+ { GCInputButtonB, nullptr, "by_button" },+ { GCInputButtonMenu, nullptr, "menu_button" },+ { GCInputThumbstickButton, nullptr, "primary_click" },+};++struct PoseMapping {+ const char *action_name;+ const char *ar_accessory_location_name;+};++static const PoseMapping pose_mappings[] = {+ { "default", ar_accessory_location_name_aim },+ { "aim", ar_accessory_location_name_aim },+ { "grip", ar_accessory_location_name_grip },+ { "palm", ar_accessory_location_name_grip_surface }+};++void process_button(GCControllerLiveInput *input, const ButtonMapping &button_mapping, Ref<XRControllerTracker> controller_tracker) {+ id<GCButtonElement> button = input.buttons[button_mapping.gc_input];+ if (button != nullptr) {+ if (button_mapping.action_name_float) {+ controller_tracker->set_input(button_mapping.action_name_float, button.pressedInput.value);+ }+ if (button_mapping.action_name_bool) {+ controller_tracker->set_input(button_mapping.action_name_bool, button.pressedInput.isPressed);+ }+ }+}++void process_thumbstick(GCControllerLiveInput *input, Ref<XRControllerTracker> controller_tracker) {+ id<GCDirectionPadElement> thumbstick = input.dpads[GCInputThumbstick];+ if (thumbstick != nullptr) {+ float x_value = thumbstick.xAxis.value;+ float y_value = thumbstick.yAxis.value;+ controller_tracker->set_input("primary", Vector2(x_value, y_value));+ }+}++} // namespace++void VisionOSControllerTracking::update_controller_from_anchor(Ref<XRControllerTracker> p_controller_tracker,+ ar_accessory_anchor_t p_controller_anchor, GCController *p_gc_controller) {+ simd_float4x4 origin_from_controller_anchor_simd = ar_anchor_get_origin_from_anchor_transform(p_controller_anchor);+ Transform3D origin_from_controller_anchor = MTL::simd_to_transform3D(origin_from_controller_anchor_simd);++ for (const PoseMapping &mapping : pose_mappings) {+ simd_float4x4 anchor_from_location = ar_accessory_anchor_get_anchor_from_location_transform_with_correction(p_controller_anchor, mapping.ar_accessory_location_name, ar_transform_correction_rendered);+ Transform3D pose = origin_from_controller_anchor * MTL::simd_to_transform3D(anchor_from_location);+ p_controller_tracker->set_pose(mapping.action_name, pose, Vector3(), Vector3());+ }++ // Button inputs+ if (p_gc_controller && p_gc_controller.input) {+ GCControllerLiveInput *input = p_gc_controller.input;++ for (const ButtonMapping &mapping : button_mappings) {+ process_button(input, mapping, p_controller_tracker);+ }+ process_thumbstick(input, p_controller_tracker);+ }+}++void VisionOSControllerTracking::update_controller_trackers_from_arkit(CFTimeInterval p_trackable_anchor_time) {+ if (accessory_tracking_provider != nullptr) {+ ar_accessory_anchors_t accessory_anchors = ar_accessory_tracking_provider_get_latest_anchors(accessory_tracking_provider);++ __block bool left_found = false;+ __block bool right_found = false;++ if (accessory_anchors != nullptr) {+ ar_accessory_anchors_enumerate_anchors(accessory_anchors, ^bool(ar_accessory_anchor_t accessory_anchor) {+ ar_data_provider_state_t provider_state = ar_data_provider_get_state((ar_data_provider_t)accessory_tracking_provider);+ if (provider_state != ar_data_provider_state_running) {+ return true;+ }++ if (!ar_trackable_anchor_is_tracked(accessory_anchor)) {+ return true;+ }++ // Predict anchor at target time if we have timing info+ if (p_trackable_anchor_time != 0) {+ bool success = ar_accessory_tracking_provider_predict_anchor_at_timestamp(+ accessory_tracking_provider, accessory_anchor, p_trackable_anchor_time, accessory_anchor);+ if (!success) {+ return true;+ }+ }++ ar_accessory_t accessory = ar_accessory_anchor_get_accessory(accessory_anchor);+ ar_accessory_chirality_t chirality = ar_accessory_get_inherent_chirality(accessory);++ if (chirality == ar_accessory_chirality_left && !left_found) {+ left_controller_anchor = accessory_anchor;+ update_controller_from_anchor(left_controller_tracker, left_controller_anchor, left_gc_controller);+ left_found = true;+ } else if (chirality == ar_accessory_chirality_right && !right_found) {+ right_controller_anchor = accessory_anchor;+ update_controller_from_anchor(right_controller_tracker, right_controller_anchor, right_gc_controller);+ right_found = true;+ }+ return true;+ });+ }+ }+}++void VisionOSControllerTracking::trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec) {+ GCController *target_controller = nullptr;+ CHHapticEngine *target_engine = nullptr;++ if (p_tracker_name == left_controller_tracker->get_tracker_name()) {+ target_controller = left_gc_controller;+ target_engine = left_haptic_engine;+ } else if (p_tracker_name == right_controller_tracker->get_tracker_name()) {+ target_controller = right_gc_controller;+ target_engine = right_haptic_engine;+ }++ ERR_FAIL_NULL_MSG(target_controller, "Controller is nil. No haptics supported.");++ ERR_FAIL_NULL_MSG(target_engine, "Haptic engine is nil.");++ float intensity = CLAMP(p_amplitude, 0.0f, 1.0f);+ float sharpness = CLAMP(p_frequency / 1000.0f, 0.0f, 1.0f);++ NSError *error = nil;++ [target_engine startAndReturnError:&error];+ if (error) {+ ERR_FAIL_MSG(vformat("Failed to start engine: %s.", [error.localizedDescription UTF8String]));+ }++ CHHapticEventParameter *intensity_param = [[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticIntensity value:intensity];+ CHHapticEventParameter *sharpness_param = [[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticSharpness value:sharpness];++ CHHapticEvent *event;+ if (p_duration_sec > 0) {+ event = [[CHHapticEvent alloc]+ initWithEventType:CHHapticEventTypeHapticContinuous+ parameters:@[ intensity_param, sharpness_param ]+ relativeTime:0.0+ duration:p_duration_sec];+ } else {+ event = [[CHHapticEvent alloc]+ initWithEventType:CHHapticEventTypeHapticTransient+ parameters:@[ intensity_param, sharpness_param ]+ relativeTime:0.0];+ }++ CHHapticPattern *pattern = [[CHHapticPattern alloc]+ initWithEvents:@[ event ]+ parameterCurves:@[]+ error:&error];++ if (error) {+ ERR_FAIL_MSG(vformat("Failed to create a haptics pattern: %s.", [error.localizedDescription UTF8String]));+ }++ id<CHHapticPatternPlayer> player = [target_engine createPlayerWithPattern:pattern error:&error];+ if (error) {+ ERR_FAIL_MSG(vformat("Failed to create a haptics player: %s.", [error.localizedDescription UTF8String]));+ }++ [player startAtTime:CHHapticTimeImmediate error:&error];+ if (error) {+ WARN_PRINT_ONCE(vformat("Failed to start a haptics playback: %s.", [error.localizedDescription UTF8String]));+ }++ // Stopping the engine+ {+ int64_t delay;+ if (p_duration_sec <= 0) {+ // Transient - can stop engine soon after+ delay = (int64_t)(0.1 * NSEC_PER_SEC);+ } else {+ // Continuous - stop after duration + small buffer+ delay = (int64_t)((p_duration_sec + 0.1) * NSEC_PER_SEC);+ }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay), dispatch_get_main_queue(), ^{+ [target_engine stopWithCompletionHandler:^(NSError *_Nullable error) {+ if (error) {+ ERR_PRINT(vformat("Error stopping haptics engine: %s.", [error.localizedDescription UTF8String]));+ }+ }];+ });+ }+}++#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_definitions.h b/modules/visionos_xr/visionos_definitions.hnew file mode 100644index 00000000000..2d73f351ea1--- /dev/null+++ b/modules/visionos_xr/visionos_definitions.h@@ -0,0 +1,74 @@+/**************************************************************************/+/* visionos_definitions.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++#ifdef VISIONOS_ENABLED++#include "core/templates/safe_refcount.h"+#include "drivers/metal/metal_objects_shared.h"+#include "drivers/metal/rendering_context_driver_metal.h"+#include "drivers/metal/rendering_device_driver_metal.h"+#include "servers/rendering/renderer_compositor.h"+#include "servers/rendering/rendering_device.h"+#include "servers/rendering/rendering_server.h"+#include "servers/xr/xr_controller_tracker.h"+#include "servers/xr/xr_hand_tracker.h"+#include "servers/xr/xr_interface.h"+#include "servers/xr/xr_positional_tracker.h"+#include "servers/xr/xr_vrs.h"++#ifdef __OBJC__+// When compiling as Objective-C++, include the actual headers+#import <ARKit/ARKit.h>+#else // __OBJC__+// When compiling as C++, use forward declarations for ARKit and CompositorServices types (opaque pointers)+typedef struct ar_world_tracking_provider *ar_world_tracking_provider_t;+typedef struct ar_hand_tracking_provider *ar_hand_tracking_provider_t;+typedef struct ar_accessory_tracking_provider *ar_accessory_tracking_provider_t;+typedef struct ar_data_providers *ar_data_providers_t;+typedef struct ar_data_provider *ar_data_provider_t;+;+typedef struct ar_authorization_results *ar_authorization_results_t;+typedef struct ar_session *ar_session_t;+typedef struct ar_device_anchor *ar_device_anchor_t;+typedef struct ar_hand_anchor *ar_hand_anchor_t;+typedef struct ar_accessories *ar_accessories_t;+typedef struct ar_accessory_anchor *ar_accessory_anchor_t;+#endif // __OBJC__++// Equivalent to ARKit's `ar_authorization_status`+enum class VisionOSAuthorizationStatus {+ NOT_DETERMINED,+ ALLOWED,+ DENIED,+};++#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_hand_tracking.h b/modules/visionos_xr/visionos_hand_tracking.hnew file mode 100644index 00000000000..eaabae963bd--- /dev/null+++ b/modules/visionos_xr/visionos_hand_tracking.h@@ -0,0 +1,58 @@+/**************************************************************************/+/* visionos_hand_tracking.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++#ifdef VISIONOS_ENABLED++#include "visionos_definitions.h"++// Hand tracking using ARKit+struct VisionOSHandTracking {+ bool enabled = false;+ VisionOSAuthorizationStatus authorization = VisionOSAuthorizationStatus::NOT_DETERMINED;++ bool active() const { return enabled && authorization == VisionOSAuthorizationStatus::ALLOWED; }++ ar_hand_tracking_provider_t hand_tracking_provider = nullptr;++ // Hand trackers+ Ref<XRHandTracker> left_hand_tracker;+ Ref<XRHandTracker> right_hand_tracker;+ ar_hand_anchor_t left_hand_anchor = nullptr;+ ar_hand_anchor_t right_hand_anchor = nullptr;++ void initialize(XRServer *xr_server);+ void update_hand_trackers_from_arkit(CFTimeInterval trackable_anchor_time);+ void reset_hand_tracker_data(Ref<XRHandTracker> hand_tracker);+ void set_hand_tracker_data_from_arkit(Ref<XRHandTracker> hand_tracker, ar_hand_anchor_t hand_anchor);+};++#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_hand_tracking.mm b/modules/visionos_xr/visionos_hand_tracking.mmnew file mode 100644index 00000000000..2e0563a6350--- /dev/null+++ b/modules/visionos_xr/visionos_hand_tracking.mm@@ -0,0 +1,222 @@+/**************************************************************************/+/* visionos_hand_tracking.mm */+/**************************************************************************/+/* 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. */+/**************************************************************************/++#ifdef VISIONOS_ENABLED++#include "visionos_hand_tracking.h"++#include "visionos_simd_helpers.h"++namespace {++_FORCE_INLINE_ XRHandTracker::HandJoint joint_from_arkit(ar_hand_skeleton_joint_name_t p_joint_name) {+ switch (p_joint_name) {+ case ar_hand_skeleton_joint_name_wrist:+ return XRHandTracker::HAND_JOINT_WRIST;+ case ar_hand_skeleton_joint_name_thumb_knuckle:+ return XRHandTracker::HAND_JOINT_THUMB_METACARPAL;+ case ar_hand_skeleton_joint_name_thumb_intermediate_base:+ return XRHandTracker::HAND_JOINT_THUMB_PHALANX_PROXIMAL;+ case ar_hand_skeleton_joint_name_thumb_intermediate_tip:+ return XRHandTracker::HAND_JOINT_THUMB_PHALANX_DISTAL;+ case ar_hand_skeleton_joint_name_thumb_tip:+ return XRHandTracker::HAND_JOINT_THUMB_TIP;+ case ar_hand_skeleton_joint_name_index_finger_metacarpal:+ return XRHandTracker::HAND_JOINT_INDEX_FINGER_METACARPAL;+ case ar_hand_skeleton_joint_name_index_finger_knuckle:+ return XRHandTracker::HAND_JOINT_INDEX_FINGER_PHALANX_PROXIMAL;+ case ar_hand_skeleton_joint_name_index_finger_intermediate_base:+ return XRHandTracker::HAND_JOINT_INDEX_FINGER_PHALANX_INTERMEDIATE;+ case ar_hand_skeleton_joint_name_index_finger_intermediate_tip:+ return XRHandTracker::HAND_JOINT_INDEX_FINGER_PHALANX_DISTAL;+ case ar_hand_skeleton_joint_name_index_finger_tip:+ return XRHandTracker::HAND_JOINT_INDEX_FINGER_TIP;+ case ar_hand_skeleton_joint_name_middle_finger_metacarpal:+ return XRHandTracker::HAND_JOINT_MIDDLE_FINGER_METACARPAL;+ case ar_hand_skeleton_joint_name_middle_finger_knuckle:+ return XRHandTracker::HAND_JOINT_MIDDLE_FINGER_PHALANX_PROXIMAL;+ case ar_hand_skeleton_joint_name_middle_finger_intermediate_base:+ return XRHandTracker::HAND_JOINT_MIDDLE_FINGER_PHALANX_INTERMEDIATE;+ case ar_hand_skeleton_joint_name_middle_finger_intermediate_tip:+ return XRHandTracker::HAND_JOINT_MIDDLE_FINGER_PHALANX_DISTAL;+ case ar_hand_skeleton_joint_name_middle_finger_tip:+ return XRHandTracker::HAND_JOINT_MIDDLE_FINGER_TIP;+ case ar_hand_skeleton_joint_name_ring_finger_metacarpal:+ return XRHandTracker::HAND_JOINT_RING_FINGER_METACARPAL;+ case ar_hand_skeleton_joint_name_ring_finger_knuckle:+ return XRHandTracker::HAND_JOINT_RING_FINGER_PHALANX_PROXIMAL;+ case ar_hand_skeleton_joint_name_ring_finger_intermediate_base:+ return XRHandTracker::HAND_JOINT_RING_FINGER_PHALANX_INTERMEDIATE;+ case ar_hand_skeleton_joint_name_ring_finger_intermediate_tip:+ return XRHandTracker::HAND_JOINT_RING_FINGER_PHALANX_DISTAL;+ case ar_hand_skeleton_joint_name_ring_finger_tip:+ return XRHandTracker::HAND_JOINT_RING_FINGER_TIP;+ case ar_hand_skeleton_joint_name_little_finger_metacarpal:+ return XRHandTracker::HAND_JOINT_PINKY_FINGER_METACARPAL;+ case ar_hand_skeleton_joint_name_little_finger_knuckle:+ return XRHandTracker::HAND_JOINT_PINKY_FINGER_PHALANX_PROXIMAL;+ case ar_hand_skeleton_joint_name_little_finger_intermediate_base:+ return XRHandTracker::HAND_JOINT_PINKY_FINGER_PHALANX_INTERMEDIATE;+ case ar_hand_skeleton_joint_name_little_finger_intermediate_tip:+ return XRHandTracker::HAND_JOINT_PINKY_FINGER_PHALANX_DISTAL;+ case ar_hand_skeleton_joint_name_little_finger_tip:+ return XRHandTracker::HAND_JOINT_PINKY_FINGER_TIP;+ case ar_hand_skeleton_joint_name_forearm_wrist:+ case ar_hand_skeleton_joint_name_forearm_arm:+ default:+ // These don't have direct equivalents or are invalid+ return XRHandTracker::HAND_JOINT_MAX;+ }+}+} // namespace++void VisionOSHandTracking::initialize(XRServer *p_xr_server) {+ // Hand tracking provider (registered with the shared ARKit session)+ ar_hand_tracking_configuration_t hand_tracking_configuration = ar_hand_tracking_configuration_create();+ hand_tracking_provider = ar_hand_tracking_provider_create(hand_tracking_configuration);++ // Hand tracker initialization+ left_hand_tracker.instantiate();+ left_hand_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_LEFT);+ left_hand_tracker->set_tracker_name("/user/hand_tracker/left");+ p_xr_server->add_tracker(left_hand_tracker);++ right_hand_tracker.instantiate();+ right_hand_tracker->set_tracker_hand(XRPositionalTracker::TRACKER_HAND_RIGHT);+ right_hand_tracker->set_tracker_name("/user/hand_tracker/right");+ p_xr_server->add_tracker(right_hand_tracker);++ left_hand_anchor = ar_hand_anchor_create();+ right_hand_anchor = ar_hand_anchor_create();+}++void VisionOSHandTracking::update_hand_trackers_from_arkit(CFTimeInterval p_trackable_anchor_time) {+ if (p_trackable_anchor_time != 0) {+ ar_hand_anchor_query_status_t query_anchor_result =+ ar_hand_tracking_provider_query_anchors_at_timestamp(hand_tracking_provider,+ p_trackable_anchor_time,+ left_hand_anchor,+ right_hand_anchor);++ if (query_anchor_result != ar_hand_anchor_query_status_success) {+ reset_hand_tracker_data(left_hand_tracker);+ reset_hand_tracker_data(right_hand_tracker);+ ERR_FAIL_MSG("Cannot query hand anchors, result: " + itos(query_anchor_result) + ".");+ }+ } else {+ // If we failed to get a trackable_anchor_time, we just get the latest anchors.+ // Tracking will be less precise in this case+ bool result = ar_hand_tracking_provider_get_latest_anchors(hand_tracking_provider, left_hand_anchor, right_hand_anchor);+ if (!result) {+ reset_hand_tracker_data(left_hand_tracker);+ reset_hand_tracker_data(right_hand_tracker);+ ERR_FAIL_MSG("Cannot query latest anchors, the ARKit session is probably not running.");+ }+ }++ if (ar_hand_anchor_is_tracked(left_hand_anchor)) {+ set_hand_tracker_data_from_arkit(left_hand_tracker, left_hand_anchor);+ } else {+ reset_hand_tracker_data(left_hand_tracker);+ }++ if (ar_hand_anchor_is_tracked(right_hand_anchor)) {+ set_hand_tracker_data_from_arkit(right_hand_tracker, right_hand_anchor);+ } else {+ reset_hand_tracker_data(right_hand_tracker);+ }+}++void VisionOSHandTracking::reset_hand_tracker_data(Ref<XRHandTracker> p_hand_tracker) {+ p_hand_tracker->set_hand_tracking_source(XRHandTracker::HAND_TRACKING_SOURCE_UNKNOWN);+ p_hand_tracker->set_has_tracking_data(false);+ p_hand_tracker->invalidate_pose("default");+}++void VisionOSHandTracking::set_hand_tracker_data_from_arkit(Ref<XRHandTracker> p_hand_tracker, ar_hand_anchor_t p_hand_anchor) {+ simd_float4x4 origin_from_hand_anchor_simd = ar_hand_anchor_get_origin_from_anchor_transform(p_hand_anchor);++ ar_hand_skeleton_t hand_skeleton = ar_hand_anchor_get_hand_skeleton(p_hand_anchor);+ Transform3D origin_from_hand_anchor = MTL::simd_to_transform3D(origin_from_hand_anchor_simd);++ // Rotate from ARKit coordinates to Godot Humanoid coordinates+ ar_hand_chirality_t chirality = ar_hand_anchor_get_chirality(p_hand_anchor);+ bool is_left_hand = (chirality == ar_hand_chirality_left);+ real_t rotation_angle = (is_left_hand ? -1 : 1) * Math::PI * 0.5;+ const Quaternion rotationX(Vector3(1, 0, 0), rotation_angle);++ BitField<XRHandTracker::HandJointFlags> flags = {};+ flags.set_flag(XRHandTracker::HAND_JOINT_FLAG_ORIENTATION_VALID);+ flags.set_flag(XRHandTracker::HAND_JOINT_FLAG_POSITION_VALID);+ flags.set_flag(XRHandTracker::HAND_JOINT_FLAG_ORIENTATION_TRACKED);+ flags.set_flag(XRHandTracker::HAND_JOINT_FLAG_POSITION_TRACKED);++ // Updating all the hand joints+ const Quaternion rotationZ(Vector3(0, 0, 1), rotation_angle);+ const Quaternion joint_axis_adjustment = rotationX * rotationZ;+ ar_hand_skeleton_enumerate_joints(hand_skeleton, ^bool(ar_skeleton_joint_t joint) {+ uint64_t joint_index = ar_skeleton_joint_get_index(joint);+ XRHandTracker::HandJoint hand_joint = joint_from_arkit((ar_hand_skeleton_joint_name_t)joint_index);+ if (hand_joint == XRHandTracker::HAND_JOINT_MAX) {+ return true;+ }+ simd_float4x4 hand_anchor_from_joint_simd = ar_skeleton_joint_get_anchor_from_joint_transform(joint);+ Transform3D hand_anchor_from_joint = MTL::simd_to_transform3D(hand_anchor_from_joint_simd);+ Transform3D origin_from_joint = origin_from_hand_anchor * hand_anchor_from_joint;+ origin_from_joint.basis = origin_from_joint.basis * joint_axis_adjustment;+ p_hand_tracker->set_hand_joint_transform(hand_joint, origin_from_joint);+ p_hand_tracker->set_hand_joint_flags(hand_joint, flags);+ return true;+ });++ // ARKit hands don't have a palm joint, so computing it the same way WebXR (webxr_interface_js.cpp) does it:+ // finding the middle of the middle-finger's metacarpal bone+ {+ // Start by getting the middle finger metacarpal joint.+ Transform3D palm_transform = p_hand_tracker->get_hand_joint_transform(XRHandTracker::HAND_JOINT_MIDDLE_FINGER_METACARPAL);++ // Get the middle finger phalanx position.+ Vector3 phalanx = p_hand_tracker->get_hand_joint_transform(XRHandTracker::HAND_JOINT_MIDDLE_FINGER_PHALANX_PROXIMAL).origin;++ // Offset the palm half-way towards the phalanx joint.+ palm_transform.origin = (palm_transform.origin + phalanx) / 2.0;++ // Set the palm joint and the pose.+ p_hand_tracker->set_hand_joint_transform(XRHandTracker::HAND_JOINT_PALM, palm_transform);+ p_hand_tracker->set_hand_joint_flags(XRHandTracker::HAND_JOINT_PALM, flags);+ // Note: ARKit does not have API for linear/angular velocity; so leaving it at 0+ p_hand_tracker->set_pose("default", palm_transform, Vector3(), Vector3());+ }++ p_hand_tracker->set_hand_tracking_source(XRHandTracker::HAND_TRACKING_SOURCE_UNOBSTRUCTED);+ p_hand_tracker->set_has_tracking_data(true);+}++#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_xr_interface.h b/modules/visionos_xr/visionos_xr_interface.hindex 8e5314c1b9b..ece0f1d88c2 100644--- a/modules/visionos_xr/visionos_xr_interface.h+++ b/modules/visionos_xr/visionos_xr_interface.h@@ -32,26 +32,18 @@#ifdef VISIONOS_ENABLED-#include "core/object/ref_counted.h"-#include "drivers/metal/metal_objects_shared.h"-#include "servers/rendering/rendering_device.h"-#include "servers/rendering/rendering_server_types.h"-#include "servers/xr/xr_interface.h"-#include "servers/xr/xr_positional_tracker.h"+#include "visionos_controller_tracking.h"+#include "visionos_definitions.h"+#include "visionos_hand_tracking.h"#ifdef __OBJC__-// When compiling as Objective-C++, include the actual headers-#import <ARKit/ARKit.h>#import <CompositorServices/CompositorServices.h>#else-// When compiling as C++, use forward declarations for ARKit and CompositorServices types (opaque pointers)-typedef struct ar_world_tracking_provider *ar_world_tracking_provider_t;typedef struct cp_layer_renderer *cp_layer_renderer_t;typedef struct cp_layer_renderer_capabilities *cp_layer_renderer_capabilities_t;-typedef struct ar_session *ar_session_t;-typedef struct ar_device_anchor *ar_device_anchor_t;typedef struct cp_frame *cp_frame_t;typedef struct cp_drawable *cp_drawable_t;+typedef struct cp_frame_timing *cp_frame_timing_t;#endifclass RenderingServer;@@ -78,15 +70,44 @@ private:RenderingServer *rendering_server;- // Static so it can be used from the render thread- static ar_world_tracking_provider_t world_tracking_provider;-- cp_layer_renderer_t layer_renderer = nullptr;- cp_layer_renderer_capabilities_t layer_renderer_capabilities = nullptr;ar_session_t ar_session = nullptr;- ar_device_anchor_t current_device_anchor = nullptr;- cp_frame_t current_frame = nullptr;+ // Rendering in XR with CompositorServices+ struct CompositorServicesData {+ bool enabled = false;++ cp_layer_renderer_t layer_renderer = nullptr;+ cp_layer_renderer_capabilities_t layer_renderer_capabilities = nullptr;++ ar_world_tracking_provider_t world_tracking_provider = nullptr;++ cp_frame_t current_frame = nullptr;+ cp_frame_timing_t current_timing = nullptr;++ // Head tracker+ Ref<XRPositionalTracker> head_tracker;++ ar_device_anchor_t current_device_anchor = nullptr;++ bool initialize(XRServer *xr_server);+ } cs;++ void set_head_pose_from_arkit();++ // Checks the ARKit authorizations asynchronously+ // and updates the ARKit session if they changed.+ void update_authorizations_async();++ // Time used for pose prediction+ CFTimeInterval get_trackable_anchor_time();++ void update_from_authorizations(ar_authorization_results_t);++ // Hand tracking+ VisionOSHandTracking hands;++ // Controller tracking+ VisionOSControllerTracking controllers;// Data and functions only accessible from the rendering threadclass RenderThread : public Object {@@ -104,6 +125,7 @@ private:// RenderThread must query the device anchor again,// because ar_device_anchor_t objects cannot be safely shared between threadsar_device_anchor_t current_device_anchor = nullptr;+ ar_world_tracking_provider_t world_tracking_provider = nullptr;Transform3D origin_from_head;cp_frame_t current_frame = nullptr;@@ -129,6 +151,9 @@ private:// p_current_frame should be an cp_frame_t pointer casted to uint64_tvoid set_current_frame(uint64_t p_current_frame);+ // Expects an ar_world_tracking_provider_t+ void set_world_tracking_provider(uint64_t p_world_tracking_provider);+// Safe to be called from the game threadvoid start_frame_update();void end_frame_update();@@ -151,15 +176,10 @@ private:RID get_vrs_texture();} rt;- // Head tracker- Ref<XRPositionalTracker> head_tracker;-static void _bind_methods();static const String name;static StringName get_signal_name(SignalEnum p_signal);- void set_head_pose_from_arkit();-public:static Ref<VisionOSXRInterface> find_interface() {return XRServer::get_singleton()->find_interface(name);@@ -168,17 +188,25 @@ public:VisionOSXRInterface();~VisionOSXRInterface();+ cp_frame_timing_t get_current_timing();+void emit_signal_enum(SignalEnum p_signal);virtual StringName get_name() const override;virtual uint32_t get_capabilities() const override;virtual TrackingStatus get_tracking_status() const override;+ virtual void trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec = 0) override;virtual bool is_initialized() const override;virtual bool initialize() override;virtual void uninitialize() override;+ // Running the ARKit session.+ // Note that we need to re-run it when the privacy authorizations changed+ // or when a new controller was connected (on visionOS 26 and earlier).+ void run_ar_session();+// The LayerRenderer and Capabilities are polled from the app delegate when initializing the VisionOSXRInterface,// but they need to be updated when the app backgrounds and foregrounds because they are recreated by visionOSvoid update_layer_renderer(cp_layer_renderer_t p_layer_renderer, cp_layer_renderer_capabilities_t p_layer_renderer_capabilities);@@ -234,4 +262,4 @@ public:}};-#endif+#endif // VISIONOS_ENABLEDdiff --git a/modules/visionos_xr/visionos_xr_interface.mm b/modules/visionos_xr/visionos_xr_interface.mmindex f180dec47da..b9c1898b1a2 100644--- a/modules/visionos_xr/visionos_xr_interface.mm+++ b/modules/visionos_xr/visionos_xr_interface.mm@@ -34,21 +34,25 @@#include "visionos_simd_helpers.h"+#include "core/config/project_settings.h"+#include "core/error/error_macros.h"+#include "core/input/input.h"+#include "core/math/transform_3d.h"#include "core/object/callable_mp.h"#include "core/os/os.h"+#include "core/os/thread.h"+#include "core/string/print_string.h"#include "drivers/metal/metal3_objects.h"-#include "drivers/metal/rendering_device_driver_metal.h"-#include "servers/rendering/rendering_server.h"+#include "servers/rendering/rendering_device.h"+#include "servers/rendering/rendering_server.h" // ERR_NOT_ON_RENDER_THREAD_V+#include "servers/rendering/rendering_server_globals.h"+#include "servers/rendering/rendering_server_types.h"+#include "servers/xr/xr_server.h"#include "platform/visionos/godot_app_delegate_service_visionos.h"-#import <ARKit/ARKit.h>-#import <CompositorServices/CompositorServices.h>-const String VisionOSXRInterface::name = "visionOS";-ar_world_tracking_provider_t VisionOSXRInterface::world_tracking_provider = nullptr;-StringName VisionOSXRInterface::get_signal_name(SignalEnum p_signal) {switch (p_signal) {case VISIONOS_XR_SIGNAL_SESSION_STARTED:@@ -104,7 +108,11 @@ XRInterface::TrackingStatus VisionOSXRInterface::get_tracking_status() const {}bool VisionOSXRInterface::is_initialized() const {- return (initialized);+ return initialized;+}++void VisionOSXRInterface::RenderThread::set_world_tracking_provider(uint64_t p_world_tracking_provider) {+ this->world_tracking_provider = (__bridge ar_world_tracking_provider_t)(void *)p_world_tracking_provider;}bool VisionOSXRInterface::initialize() {@@ -113,47 +121,79 @@ bool VisionOSXRInterface::initialize() {XRServer *xr_server = XRServer::get_singleton();ERR_FAIL_NULL_V(xr_server, false);+ // Checking features+ GDTRenderMode app_delegate_render_mode = GDTAppDelegateServiceVisionOS.renderMode;+ cs.enabled = (app_delegate_render_mode == GDTRenderModeCompositorServices);+ hands.enabled = GLOBAL_GET("xr/visionos/enable_hand_tracking");+ controllers.enabled = GLOBAL_GET("xr/visionos/enable_controller_tracking");++ // ARKit session+ ar_session = ar_session_create();++ // CompositorServices+ if (cs.enabled) {+ cs.initialize(xr_server);++ // RenderThread+ rendering_server = RenderingServer::get_singleton();+ ERR_FAIL_NULL_V(rendering_server, false);+ rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::initialize));+ rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::set_world_tracking_provider).bind((uint64_t)(__bridge void *)cs.world_tracking_provider));++ 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));++ // Make this our primary interface, since it's used for rendering+ xr_server->set_primary_interface(this);+ }++ // Hand tracking+ if (hands.enabled) {+ hands.initialize(xr_server);+ }++ // Controllers+ if (controllers.enabled) {+ controllers.initialize(xr_server, this);+ }++ // Running the ARKit session for head tracking, at first+ run_ar_session();++ // Check the authorizations asynchronously+ if (hands.enabled || controllers.enabled) {+ update_authorizations_async();+ }++ initialized = true;++ print_verbose(String("VisionOSXRInterface initialized with:") + " compositorservices=" + (cs.enabled ? "yes" : "no") + " hands=" + (hands.enabled ? "yes" : "no") + " controllers=" + (controllers.enabled ? "yes" : "no"));++ return initialized;+}++bool VisionOSXRInterface::CompositorServicesData::initialize(XRServer *p_xr_server) {String driver_name = OS::get_singleton()->get_current_rendering_driver_name().to_lower();ERR_FAIL_COND_V_MSG(driver_name != "metal", false, "The visionOS XR interface requires the Metal rendering driver.");- GDTRenderMode app_delegate_render_mode = GDTAppDelegateServiceVisionOS.renderMode;- ERR_FAIL_COND_V_MSG(app_delegate_render_mode != GDTRenderModeCompositorServices, false, "The visionOS XR interface requires GDTRenderModeCompositorServices render mode.");-layer_renderer = GDTAppDelegateServiceVisionOS.layerRenderer;layer_renderer_capabilities = GDTAppDelegateServiceVisionOS.layerRendererCapabilities;- ERR_FAIL_NULL_V_MSG(layer_renderer, false, "GDTAppDelegateServiceVisionOS.layerRenderer not set");- ERR_FAIL_NULL_V_MSG(layer_renderer_capabilities, false, "GDTAppDelegateServiceVisionOS.layerRendererCapabilities not set");+ ERR_FAIL_NULL_V_MSG(layer_renderer, false, "GDTAppDelegateServiceVisionOS.layerRenderer not set.");+ ERR_FAIL_NULL_V_MSG(layer_renderer_capabilities, false, "GDTAppDelegateServiceVisionOS.layerRendererCapabilities not set.");- // ARKit session initialization- ar_session = ar_session_create();ar_world_tracking_configuration_t world_tracking_configuration = ar_world_tracking_configuration_create();world_tracking_provider = ar_world_tracking_provider_create(world_tracking_configuration);current_device_anchor = ar_device_anchor_create();- ar_data_providers_t data_providers = ar_data_providers_create();- ar_data_providers_add_data_provider(data_providers, world_tracking_provider);- ar_session_run(ar_session, data_providers);// Head tracker initializationhead_tracker.instantiate();head_tracker->set_tracker_type(XRServer::TRACKER_HEAD);head_tracker->set_tracker_name("head");head_tracker->set_tracker_desc("Device head pose");- xr_server->add_tracker(head_tracker);-- // RenderThread- rendering_server = RenderingServer::get_singleton();- ERR_FAIL_NULL_V(rendering_server, false);- rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::initialize));-- float minimum_supported_near_plane = cp_layer_renderer_capabilities_supported_minimum_near_plane_distance(layer_renderer_capabilities);- rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::set_minimum_supported_near_plane).bind(minimum_supported_near_plane));+ p_xr_server->add_tracker(head_tracker);- // Make this our primary interface- xr_server->set_primary_interface(this);-- initialized = true;- return initialized;+ return true;}void VisionOSXRInterface::uninitialize() {@@ -161,22 +201,44 @@ void VisionOSXRInterface::uninitialize() {return;}- rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::uninitialize));+ if (cs.enabled && rendering_server) {+ rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::uninitialize));+ }XRServer *xr_server = XRServer::get_singleton();if (xr_server != nullptr) {- if (head_tracker.is_valid()) {- xr_server->remove_tracker(head_tracker);- head_tracker.unref();+ if (controllers.enabled) {+ controllers.uninitialize(xr_server);}- if (xr_server->get_primary_interface() == this) {- // no longer our primary interface- xr_server->set_primary_interface(nullptr);+ if (hands.enabled) {+ if (hands.left_hand_tracker.is_valid()) {+ xr_server->remove_tracker(hands.left_hand_tracker);+ hands.left_hand_tracker.unref();+ }+ if (hands.right_hand_tracker.is_valid()) {+ xr_server->remove_tracker(hands.right_hand_tracker);+ hands.right_hand_tracker.unref();+ }+ }++ if (cs.enabled) {+ if (cs.head_tracker.is_valid()) {+ xr_server->remove_tracker(cs.head_tracker);+ cs.head_tracker.unref();+ }++ if (xr_server->get_primary_interface() == this) {+ // no longer our primary interface+ xr_server->set_primary_interface(nullptr);+ }}initialized = false;}++ // equivalent to "ar_release(ar_session)" since automatic reference counting is enabled+ ar_session = nullptr;}void VisionOSXRInterface::RenderThread::initialize() {@@ -205,10 +267,10 @@ void VisionOSXRInterface::RenderThread::uninitialize() {}void VisionOSXRInterface::update_layer_renderer(cp_layer_renderer_t p_layer_renderer, cp_layer_renderer_capabilities_t p_layer_renderer_capabilities) {- layer_renderer = p_layer_renderer;- layer_renderer_capabilities = p_layer_renderer_capabilities;+ cs.layer_renderer = p_layer_renderer;+ cs.layer_renderer_capabilities = p_layer_renderer_capabilities;- float minimum_supported_near_plane = cp_layer_renderer_capabilities_supported_minimum_near_plane_distance(layer_renderer_capabilities);+ 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));}@@ -238,41 +300,179 @@ bool VisionOSXRInterface::set_play_area_mode(XRInterface::PlayAreaMode p_mode) {}void VisionOSXRInterface::set_head_pose_from_arkit() {- ERR_FAIL_NULL_MSG(current_frame, "Current frame is nil, process() has probably not been called, using identity transform.");+ ERR_FAIL_NULL_MSG(cs.current_frame, "Current frame is nil, process() has probably not been called, using identity transform.");- cp_frame_timing_t frame_timing = cp_frame_predict_timing(current_frame);+ cs.current_timing = cp_frame_predict_timing(cs.current_frame);- CFTimeInterval presentation_time = cp_time_to_cf_time_interval(cp_frame_timing_get_presentation_time(frame_timing));- ar_device_anchor_query_status_t query_anchor_result = ar_world_tracking_provider_query_device_anchor_at_timestamp(world_tracking_provider, presentation_time, current_device_anchor);+ CFTimeInterval presentation_time = cp_time_to_cf_time_interval(cp_frame_timing_get_presentation_time(cs.current_timing));+ ar_device_anchor_query_status_t query_anchor_result = ar_world_tracking_provider_query_device_anchor_at_timestamp(cs.world_tracking_provider, presentation_time, cs.current_device_anchor);if (query_anchor_result != ar_device_anchor_query_status_success) {tracking_state = XRInterface::XR_NOT_TRACKING;- ERR_FAIL_MSG("cannot query device anchor, result: " + itos(query_anchor_result));+ ERR_FAIL_MSG("Cannot query device anchor, result: " + itos(query_anchor_result) + ".");}- simd_float4x4 origin_from_head_simd = ar_anchor_get_origin_from_anchor_transform(current_device_anchor);+ simd_float4x4 origin_from_head_simd = ar_anchor_get_origin_from_anchor_transform(cs.current_device_anchor);tracking_state = XRInterface::XR_NORMAL_TRACKING;- if (head_tracker.is_valid()) {+ if (cs.head_tracker.is_valid()) {// Set our head position (in real space, reference frame and world scale is applied later)- head_tracker->set_pose("default", MTL::simd_to_transform3D(origin_from_head_simd), Vector3(), Vector3(), XRPose::XR_TRACKING_CONFIDENCE_HIGH);+ cs.head_tracker->set_pose("default", MTL::simd_to_transform3D(origin_from_head_simd), Vector3(), Vector3(), XRPose::XR_TRACKING_CONFIDENCE_HIGH);}}+namespace {+VisionOSAuthorizationStatus convert(ar_authorization_status_t p_status) {+ switch (p_status) {+ case ar_authorization_status_not_determined:+ return VisionOSAuthorizationStatus::NOT_DETERMINED;+ case ar_authorization_status_allowed:+ return VisionOSAuthorizationStatus::ALLOWED;+ case ar_authorization_status_denied:+ return VisionOSAuthorizationStatus::DENIED;+ }+ // Unknown/future cases+ return VisionOSAuthorizationStatus::NOT_DETERMINED;+}+} // namespace++void VisionOSXRInterface::update_authorizations_async() {+ uintptr_t types = ar_authorization_type_none;++ if (hands.enabled) {+ types |= ar_authorization_type_hand_tracking;+ }++ if (controllers.enabled) {+ types |= ar_authorization_type_accessory_tracking;+ }++ if (types == ar_authorization_type_none) {+ // Nothing to request+ return;+ }++ Ref<VisionOSXRInterface> ref_this = this;+ ar_session_request_authorization(ar_session, static_cast<ar_authorization_type_t>(types), ^(ar_authorization_results_t authorization_results, ar_error_t _Nullable error) {+ dispatch_async(dispatch_get_main_queue(), ^(void) {+ ERR_FAIL_COND_MSG(error != nullptr, "Could not query ARKit authorizations.");++ if (ref_this->is_initialized()) {+ ref_this->update_from_authorizations(authorization_results);+ }+ });+ });+}++void VisionOSXRInterface::update_from_authorizations(ar_authorization_results_t p_authorization_results) {+ VisionOSAuthorizationStatus previous_hands = hands.authorization;+ VisionOSAuthorizationStatus previous_controllers = controllers.authorization;++ ar_authorization_results_enumerate_results(p_authorization_results, ^bool(ar_authorization_result_t authorization_result) {+ ar_authorization_type_t type = ar_authorization_result_get_authorization_type(authorization_result);+ ar_authorization_status_t status = ar_authorization_result_get_status(authorization_result);++ switch (type) {+ case ar_authorization_type_hand_tracking:+ hands.authorization = convert(status);+ if (status == ar_authorization_status_denied) {+ ERR_PRINT("Hand tracking not authorized. Enable it in `Settings > Privacy` and restart the app.");+ }+ break;+ case ar_authorization_type_accessory_tracking:+ controllers.authorization = convert(status);+ if (status == ar_authorization_status_denied) {+ ERR_PRINT("Controller tracking not authorized. Enable it in `Settings > Privacy` and restart the app.");+ }+ break;+ default:+ break;+ }++ return true; // continue with the enumeration+ });++ // If something changed, re-run the ARKit session with updated authorizations+ if (previous_hands != hands.authorization || previous_controllers != controllers.authorization) {+ run_ar_session();+ }+}++void VisionOSXRInterface::run_ar_session() {+ ar_data_providers_t ar_data_providers = ar_data_providers_create();++ if (cs.enabled) {+ ar_data_providers_add_data_provider(ar_data_providers, cs.world_tracking_provider);+ }++ if (hands.active()) {+ ar_data_providers_add_data_provider(ar_data_providers, hands.hand_tracking_provider);+ }++ if (controllers.active()) {+ ar_data_providers_add_data_provider(ar_data_providers, controllers.accessory_tracking_provider);+ }++ // Running the ARSession with the given providers, after it has been configured+ ar_session_run(ar_session, ar_data_providers);+}++CFTimeInterval VisionOSXRInterface::get_trackable_anchor_time() {+ // Computing the time to use for pose prediction+ CFTimeInterval trackable_anchor_time = 0;++ if (cs.enabled) {+ // If CompositorServices is enabled, use its presentation time for pose prediction+ trackable_anchor_time = cp_time_to_cf_time_interval(cp_frame_timing_get_trackable_anchor_time(cs.current_timing));+ } else {+ // If not using CompositorServices, we obtain the estimatedPresentationTime from the active UIScene+ UIWindowScene *window_scene = nil;+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {+ if ([scene isKindOfClass:[UIWindowScene class]]) {+ UIWindowScene *window_scene_candidate = (UIWindowScene *)scene;+ if (window_scene_candidate.activationState == UISceneActivationStateForegroundActive) {+ window_scene = window_scene_candidate;+ break;+ }+ }+ }+ if (window_scene != nil) {+ UIUpdateInfo *ui_update_info = [UIUpdateInfo currentUpdateInfoForWindowScene:window_scene];+ trackable_anchor_time = ui_update_info.estimatedPresentationTime;+ }+ }++ return trackable_anchor_time;+}+void VisionOSXRInterface::process() {if (!initialized) {return;}- current_frame = cp_layer_renderer_query_next_frame(layer_renderer);+ if (cs.enabled) {+ cs.current_frame = cp_layer_renderer_query_next_frame(cs.layer_renderer);- ERR_FAIL_NULL_MSG(current_frame, "Layer renderer unexpectedly returned a nil frame, the layer renderer has probably been invalidated and it hasn't been updated to a new one.");+ ERR_FAIL_NULL_MSG(cs.current_frame, "Layer renderer unexpectedly returned a nil frame, the layer renderer has probably been invalidated and it hasn't been updated to a new one.");- // Set head pose before engine update, so scripts can access fresh head tracker data- set_head_pose_from_arkit();+ // Set head pose before engine update, so scripts can access fresh head tracker data+ set_head_pose_from_arkit();- rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::set_current_frame).bind((uint64_t)current_frame));- rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::start_frame_update));+ rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::set_current_frame).bind((uint64_t)cs.current_frame));+ rendering_server->call_on_render_thread(callable_mp(&rt, &RenderThread::start_frame_update));+ }++ if (hands.active() || controllers.active()) {+ CFTimeInterval trackable_anchor_time = get_trackable_anchor_time();++ if (hands.active()) {+ hands.update_hand_trackers_from_arkit(trackable_anchor_time);+ }++ if (controllers.active()) {+ controllers.update_controller_trackers_from_arkit(trackable_anchor_time);+ }+ }}Size2 VisionOSXRInterface::get_render_target_size() {@@ -294,7 +494,7 @@ void VisionOSXRInterface::RenderThread::set_current_frame(uint64_t p_current_fraar_device_anchor_query_status_t query_anchor_result = ar_world_tracking_provider_query_device_anchor_at_timestamp(world_tracking_provider, presentation_time, current_device_anchor);if (query_anchor_result != ar_device_anchor_query_status_success) {- ERR_FAIL_MSG("Cannot query device anchor, result: " + itos(query_anchor_result));+ ERR_FAIL_MSG("Cannot query device anchor, result: " + itos(query_anchor_result) + ".");}simd_float4x4 origin_from_head_simd = ar_anchor_get_origin_from_anchor_transform(current_device_anchor);@@ -343,7 +543,7 @@ Transform3D VisionOSXRInterface::RenderThread::get_transform_for_view(uint32_t pfloat world_scale = xr_server->get_world_scale();origin_from_eye.origin *= world_scale;} else {- ERR_PRINT("vision_vr_interface not initialized, returning received camera transform");+ ERR_PRINT("vision_vr_interface not initialized, returning received camera transform.");origin_from_eye = Transform3D();}Transform3D reference_frame = xr_server->get_reference_frame();@@ -465,7 +665,7 @@ void VisionOSXRInterface::RenderThread::pre_render() {current_drawable = drawable;}}- ERR_FAIL_NULL_MSG(current_drawable, "Built-in drawable not found, aborting");+ ERR_FAIL_NULL_MSG(current_drawable, "Built-in drawable not found, aborting.");// Cache the render target size so it can be read from the game thread.id<MTLTexture> color_texture = cp_drawable_get_color_texture(current_drawable, 0);@@ -475,7 +675,7 @@ void VisionOSXRInterface::RenderThread::pre_render() {if (current_device_anchor != nil) {cp_drawable_set_device_anchor(current_drawable, current_device_anchor);} else {- ERR_PRINT("Current device anchor is nil, will present drawable without a device anchor");+ ERR_PRINT("Current device anchor is nil, will present drawable without a device anchor.");}}@@ -587,7 +787,7 @@ RID VisionOSXRInterface::RenderThread::get_vrs_texture() {ERR_FAIL_NULL_V_MSG(current_drawable, RID(), "Current drawable is nil, pre_render() has probably not been called.");size_t count = cp_drawable_get_rasterization_rate_map_count(current_drawable);- ERR_FAIL_COND_V_MSG(count == 0, RID(), "No rasterizationRateMaps found");+ ERR_FAIL_COND_V_MSG(count == 0, RID(), "No rasterizationRateMaps found.");id<MTLRasterizationRateMap> rasterization_rate_map = cp_drawable_get_rasterization_rate_map(current_drawable, 0);MTLSize logical_size = rasterization_rate_map.screenSize;@@ -612,4 +812,10 @@ RID VisionOSXRInterface::RenderThread::get_vrs_texture() {return current_rasterization_rate_map_id;}+void VisionOSXRInterface::trigger_haptic_pulse(const String &p_action_name, const StringName &p_tracker_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec) {+ if (controllers.enabled) {+ controllers.trigger_haptic_pulse(p_action_name, p_tracker_name, p_frequency, p_amplitude, p_duration_sec, p_delay_sec);+ }+}+#endif // VISIONOS_ENABLEDdiff --git a/platform/ios/export/export_plugin.cpp b/platform/ios/export/export_plugin.cppindex ff407b8c812..25a778e96c9 100644--- a/platform/ios/export/export_plugin.cpp+++ b/platform/ios/export/export_plugin.cpp@@ -490,6 +490,14 @@ String EditorExportPlatformIOS::_process_config_file_line(const Ref<EditorExport} else if (p_line.contains("$application_scene_manifest_immersive_configuration")) {strnew += p_line.replace("$application_scene_manifest_immersive_configuration", "") + "\n";+ // Info.plist NSHandsTrackingUsageDescription+ } else if (p_line.contains("$hand_tracking_usage_description")) {+ strnew += p_line.replace("$hand_tracking_usage_description", "") + "\n";++ // Info.plist NSAccessoryTrackingUsageDescription+ } else if (p_line.contains("$accessory_tracking_usage_description")) {+ strnew += p_line.replace("$accessory_tracking_usage_description", "") + "\n";+// Apple Embedded common} else {strnew += EditorExportPlatformAppleEmbedded::_process_config_file_line(p_preset, p_line, p_config, p_debug, p_code_signing);diff --git a/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xml b/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xmlindex 4737e38b7bf..b60da22bff5 100644--- a/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xml+++ b/platform/visionos/doc_classes/EditorExportPlatformVisionOS.xml@@ -130,6 +130,12 @@<member name="modules/camera" type="bool" setter="" getter="">If [code]true[/code], [CameraServer] module is added to the exported project.</member>+ <member name="privacy/accessory_tracking_usage_description" type="String" setter="" getter="">+ A message displayed when requesting access to controller tracking on visionOS (in English).+ </member>+ <member name="privacy/accessory_tracking_usage_description_localized" type="Dictionary" setter="" getter="">+ A message displayed when requesting access to controller tracking on visionOS (localized).+ </member><member name="privacy/active_keyboard_access_reasons" type="int" setter="" getter="">The reasons your app use active keyboard API. See [url=https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api]Describing use of required reason API[/url].</member>@@ -565,6 +571,12 @@<member name="privacy/file_timestamp_access_reasons" type="int" setter="" getter="">The reasons your app use file timestamp/metadata API. See [url=https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api]Describing use of required reason API[/url].</member>+ <member name="privacy/hand_tracking_usage_description" type="String" setter="" getter="">+ A message displayed when requesting access to hand tracking on visionOS (in English).+ </member>+ <member name="privacy/hand_tracking_usage_description_localized" type="Dictionary" setter="" getter="">+ A message displayed when requesting access to hand tracking on visionOS (localized).+ </member><member name="privacy/microphone_usage_description" type="String" setter="" getter="">A message displayed when requesting access to the device's microphone (in English).</member>diff --git a/platform/visionos/export/export_plugin.cpp b/platform/visionos/export/export_plugin.cppindex 12482b8c69b..6d096d341d1 100644--- a/platform/visionos/export/export_plugin.cpp+++ b/platform/visionos/export/export_plugin.cpp@@ -34,6 +34,7 @@#include "run_icon_svg.gen.h"#include "editor/editor_node.h"+#include "editor/export/editor_export_platform_apple_embedded.h"Vector<String> EditorExportPlatformVisionOS::device_types({ "realityDevice" });@@ -152,9 +153,45 @@ String EditorExportPlatformVisionOS::_process_config_file_line(const Ref<EditorEstrnew += p_line.replace("$application_scene_manifest_immersive_configuration", value) + "\n";+ // Info.plist NSHandsTrackingUsageDescription+ } else if (p_line.contains("$hand_tracking_usage_description")) {+ if (GLOBAL_GET("xr/visionos/enable_hand_tracking")) {+ String description = p_preset->get("privacy/hand_tracking_usage_description");+ String value = "<key>NSHandsTrackingUsageDescription</key>\n";+ value += "<string>" + description + "</string>";+ strnew += p_line.replace("$hand_tracking_usage_description", value) + "\n";+ } else {+ strnew += p_line.replace("$hand_tracking_usage_description", "") + "\n";+ }++ // Info.plist NSAccessoryTrackingUsageDescription+ } else if (p_line.contains("$accessory_tracking_usage_description")) {+ if (GLOBAL_GET("xr/visionos/enable_controller_tracking")) {+ String description = p_preset->get("privacy/accessory_tracking_usage_description");+ String value = "<key>NSAccessoryTrackingUsageDescription</key>\n";+ value += "<string>" + description + "</string>\n";+ value += "<key>GCSupportedGameControllers</key>\n"+ "<array>\n"+ " <dict>\n"+ " <key>ProfileName</key>\n"+ " <string>SpatialGamepad</string>\n"+ " </dict>\n"+ "</array>";+ strnew += p_line.replace("$accessory_tracking_usage_description", value) + "\n";+ } else {+ strnew += p_line.replace("$accessory_tracking_usage_description", "") + "\n";+ }+// Apple Embedded common} else {strnew += EditorExportPlatformAppleEmbedded::_process_config_file_line(p_preset, p_line, p_config, p_debug, p_code_signing);}return strnew;}++void EditorExportPlatformVisionOS::get_usage_descriptions(List<UsageDescription> *r_descriptions) const {+ EditorExportPlatformAppleEmbedded::get_usage_descriptions(r_descriptions);++ r_descriptions->push_back({ "privacy/hand_tracking_usage_description", "NSHandsTrackingUsageDescription", "Provide a message if you need to use hand tracking" });+ r_descriptions->push_back({ "privacy/accessory_tracking_usage_description", "NSAccessoryTrackingUsageDescription", "Provide a message if you need to use controller tracking" });+}diff --git a/platform/visionos/export/export_plugin.h b/platform/visionos/export/export_plugin.hindex 7535710089c..4fab7ea25ab 100644--- a/platform/visionos/export/export_plugin.h+++ b/platform/visionos/export/export_plugin.h@@ -49,6 +49,8 @@ class EditorExportPlatformVisionOS : public EditorExportPlatformAppleEmbedded {virtual String _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) override;+ virtual void get_usage_descriptions(List<UsageDescription> *r_descriptions) const override;+public:virtual String get_name() const override { return "visionOS"; }virtual String get_os_name() const override { return "visionOS"; }