openxr_api.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779
  1. /**************************************************************************/
  2. /* openxr_api.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "openxr_api.h"
  31. #include "openxr_util.h"
  32. #include "core/config/engine.h"
  33. #include "core/config/project_settings.h"
  34. #include "core/os/memory.h"
  35. #include "core/version.h"
  36. #ifdef TOOLS_ENABLED
  37. #include "editor/editor_settings.h"
  38. #endif
  39. #ifdef ANDROID_ENABLED
  40. #define OPENXR_LOADER_NAME "libopenxr_loader.so"
  41. #endif
  42. // We need to have all the graphics API defines before the Vulkan or OpenGL
  43. // extensions are included, otherwise we'll only get one graphics API.
  44. #ifdef VULKAN_ENABLED
  45. #define XR_USE_GRAPHICS_API_VULKAN
  46. #endif
  47. #ifdef GLES3_ENABLED
  48. #ifdef ANDROID_ENABLED
  49. #define XR_USE_GRAPHICS_API_OPENGL_ES
  50. #include <EGL/egl.h>
  51. #include <EGL/eglext.h>
  52. #include <GLES3/gl3.h>
  53. #include <GLES3/gl3ext.h>
  54. #else
  55. #define XR_USE_GRAPHICS_API_OPENGL
  56. #endif // ANDROID_ENABLED
  57. #ifdef X11_ENABLED
  58. #include OPENGL_INCLUDE_H
  59. #define GL_GLEXT_PROTOTYPES 1
  60. #define GL3_PROTOTYPES 1
  61. #include "thirdparty/glad/glad/gl.h"
  62. #include "thirdparty/glad/glad/glx.h"
  63. #include <X11/Xlib.h>
  64. #endif // X11_ENABLED
  65. #endif // GLES_ENABLED
  66. #ifdef VULKAN_ENABLED
  67. #include "extensions/openxr_vulkan_extension.h"
  68. #endif
  69. #ifdef GLES3_ENABLED
  70. #include "extensions/openxr_opengl_extension.h"
  71. #endif
  72. #include "extensions/openxr_composition_layer_depth_extension.h"
  73. #include "extensions/openxr_fb_display_refresh_rate_extension.h"
  74. #include "extensions/openxr_fb_passthrough_extension_wrapper.h"
  75. #include "modules/openxr/openxr_interface.h"
  76. OpenXRAPI *OpenXRAPI::singleton = nullptr;
  77. Vector<OpenXRExtensionWrapper *> OpenXRAPI::registered_extension_wrappers;
  78. bool OpenXRAPI::openxr_is_enabled(bool p_check_run_in_editor) {
  79. // @TODO we need an overrule switch so we can force enable openxr, i.e run "godot --openxr_enabled"
  80. if (Engine::get_singleton()->is_editor_hint() && p_check_run_in_editor) {
  81. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  82. return false;
  83. } else {
  84. if (XRServer::get_xr_mode() == XRServer::XRMODE_DEFAULT) {
  85. return GLOBAL_GET("xr/openxr/enabled");
  86. } else {
  87. return XRServer::get_xr_mode() == XRServer::XRMODE_ON;
  88. }
  89. }
  90. }
  91. String OpenXRAPI::get_default_action_map_resource_name() {
  92. String name = GLOBAL_GET("xr/openxr/default_action_map");
  93. return name;
  94. }
  95. String OpenXRAPI::get_error_string(XrResult result) {
  96. if (XR_SUCCEEDED(result)) {
  97. return String("Succeeded");
  98. }
  99. if (instance == XR_NULL_HANDLE) {
  100. Array args;
  101. args.push_back(Variant(result));
  102. return String("Error code {0}").format(args);
  103. }
  104. char resultString[XR_MAX_RESULT_STRING_SIZE];
  105. xrResultToString(instance, result, resultString);
  106. return String(resultString);
  107. }
  108. String OpenXRAPI::get_swapchain_format_name(int64_t p_swapchain_format) const {
  109. // This is rendering engine dependent...
  110. if (graphics_extension) {
  111. return graphics_extension->get_swapchain_format_name(p_swapchain_format);
  112. }
  113. return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format));
  114. }
  115. bool OpenXRAPI::load_layer_properties() {
  116. // This queries additional layers that are available and can be initialized when we create our OpenXR instance
  117. if (layer_properties != nullptr) {
  118. // already retrieved this
  119. return true;
  120. }
  121. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  122. XrResult result = xrEnumerateApiLayerProperties(0, &num_layer_properties, nullptr);
  123. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of api layer properties");
  124. layer_properties = (XrApiLayerProperties *)memalloc(sizeof(XrApiLayerProperties) * num_layer_properties);
  125. ERR_FAIL_NULL_V(layer_properties, false);
  126. for (uint32_t i = 0; i < num_layer_properties; i++) {
  127. layer_properties[i].type = XR_TYPE_API_LAYER_PROPERTIES;
  128. layer_properties[i].next = nullptr;
  129. }
  130. result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties);
  131. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties");
  132. for (uint32_t i = 0; i < num_layer_properties; i++) {
  133. print_verbose(String("OpenXR: Found OpenXR layer ") + layer_properties[i].layerName);
  134. }
  135. return true;
  136. }
  137. bool OpenXRAPI::load_supported_extensions() {
  138. // This queries supported extensions that are available and can be initialized when we create our OpenXR instance
  139. if (supported_extensions != nullptr) {
  140. // already retrieved this
  141. return true;
  142. }
  143. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  144. XrResult result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &num_supported_extensions, nullptr);
  145. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of extension properties");
  146. supported_extensions = (XrExtensionProperties *)memalloc(sizeof(XrExtensionProperties) * num_supported_extensions);
  147. ERR_FAIL_NULL_V(supported_extensions, false);
  148. // set our types
  149. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  150. supported_extensions[i].type = XR_TYPE_EXTENSION_PROPERTIES;
  151. supported_extensions[i].next = nullptr;
  152. }
  153. result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions);
  154. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties");
  155. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  156. print_verbose(String("OpenXR: Found OpenXR extension ") + supported_extensions[i].extensionName);
  157. }
  158. return true;
  159. }
  160. bool OpenXRAPI::is_extension_supported(const String &p_extension) const {
  161. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  162. if (supported_extensions[i].extensionName == p_extension) {
  163. return true;
  164. }
  165. }
  166. return false;
  167. }
  168. bool OpenXRAPI::is_extension_enabled(const String &p_extension) const {
  169. CharString extension = p_extension.ascii();
  170. for (int i = 0; i < enabled_extensions.size(); i++) {
  171. if (strcmp(enabled_extensions[i].ptr(), extension.ptr()) == 0) {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. bool OpenXRAPI::is_top_level_path_supported(const String &p_toplevel_path) {
  178. String required_extension = OpenXRInteractionProfileMetaData::get_singleton()->get_top_level_extension(p_toplevel_path);
  179. // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
  180. ERR_FAIL_COND_V_MSG(required_extension == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported toplevel path " + p_toplevel_path);
  181. if (required_extension == "") {
  182. // no extension needed, core top level are always "supported", they just won't be used if not really supported
  183. return true;
  184. }
  185. if (!is_extension_enabled(required_extension)) {
  186. // It is very likely we have top level paths for which the extension is not available so don't flood the logs with unnecessary spam.
  187. print_verbose("OpenXR: Top level path " + p_toplevel_path + " requires extension " + required_extension);
  188. return false;
  189. }
  190. return true;
  191. }
  192. bool OpenXRAPI::is_interaction_profile_supported(const String &p_ip_path) {
  193. String required_extension = OpenXRInteractionProfileMetaData::get_singleton()->get_interaction_profile_extension(p_ip_path);
  194. // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
  195. ERR_FAIL_COND_V_MSG(required_extension == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported interaction profile " + p_ip_path);
  196. if (required_extension == "") {
  197. // no extension needed, core interaction profiles are always "supported", they just won't be used if not really supported
  198. return true;
  199. }
  200. if (!is_extension_enabled(required_extension)) {
  201. // It is very likely we have interaction profiles for which the extension is not available so don't flood the logs with unnecessary spam.
  202. print_verbose("OpenXR: Interaction profile " + p_ip_path + " requires extension " + required_extension);
  203. return false;
  204. }
  205. return true;
  206. }
  207. bool OpenXRAPI::interaction_profile_supports_io_path(const String &p_ip_path, const String &p_io_path) {
  208. if (!is_interaction_profile_supported(p_ip_path)) {
  209. return false;
  210. }
  211. const OpenXRInteractionProfileMetaData::IOPath *io_path = OpenXRInteractionProfileMetaData::get_singleton()->get_io_path(p_ip_path, p_io_path);
  212. // If the io_path is not part of our meta data we've likely got a misspelled name or a bad action map, report
  213. ERR_FAIL_NULL_V_MSG(io_path, false, "OpenXR: Unsupported io path " + String(p_ip_path) + String(p_io_path));
  214. if (io_path->openxr_extension_name == "") {
  215. // no extension needed, core io paths are always "supported", they just won't be used if not really supported
  216. return true;
  217. }
  218. if (!is_extension_enabled(io_path->openxr_extension_name)) {
  219. // It is very likely we have io paths for which the extension is not available so don't flood the logs with unnecessary spam.
  220. print_verbose("OpenXR: IO path " + String(p_ip_path) + String(p_io_path) + " requires extension " + io_path->openxr_extension_name);
  221. return false;
  222. }
  223. return true;
  224. }
  225. void OpenXRAPI::copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len) {
  226. CharString char_string = p_string.utf8();
  227. int len = char_string.length();
  228. if (len < p_buffer_len - 1) {
  229. // was having weird CI issues with strcpy so....
  230. memcpy(p_buffer, char_string.get_data(), len);
  231. p_buffer[len] = '\0';
  232. } else {
  233. memcpy(p_buffer, char_string.get_data(), p_buffer_len - 1);
  234. p_buffer[p_buffer_len - 1] = '\0';
  235. }
  236. }
  237. bool OpenXRAPI::create_instance() {
  238. // Create our OpenXR instance, this will query any registered extension wrappers for extensions we need to enable.
  239. // Append the extensions requested by the registered extension wrappers.
  240. HashMap<String, bool *> requested_extensions;
  241. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  242. const HashMap<String, bool *> &wrapper_request_extensions = wrapper->get_requested_extensions();
  243. // requested_extensions.insert(wrapper_request_extensions.begin(), wrapper_request_extensions.end());
  244. for (auto &requested_extension : wrapper_request_extensions) {
  245. requested_extensions[requested_extension.key] = requested_extension.value;
  246. }
  247. }
  248. // Check which extensions are supported
  249. enabled_extensions.clear();
  250. for (auto &requested_extension : requested_extensions) {
  251. if (!is_extension_supported(requested_extension.key)) {
  252. if (requested_extension.value == nullptr) {
  253. // nullptr means this is a manditory extension so we fail
  254. ERR_FAIL_V_MSG(false, String("OpenXR: OpenXR Runtime does not support ") + requested_extension.key + String(" extension!"));
  255. } else {
  256. // set this extension as not supported
  257. *requested_extension.value = false;
  258. }
  259. } else if (requested_extension.value != nullptr) {
  260. // set this extension as supported
  261. *requested_extension.value = true;
  262. // and record that we want to enable it
  263. enabled_extensions.push_back(requested_extension.key.ascii());
  264. } else {
  265. // record that we want to enable this
  266. enabled_extensions.push_back(requested_extension.key.ascii());
  267. }
  268. }
  269. Vector<const char *> extension_ptrs;
  270. for (int i = 0; i < enabled_extensions.size(); i++) {
  271. print_verbose(String("OpenXR: Enabling extension ") + String(enabled_extensions[i]));
  272. extension_ptrs.push_back(enabled_extensions[i].get_data());
  273. }
  274. // Get our project name
  275. String project_name = GLOBAL_GET("application/config/name");
  276. // Create our OpenXR instance
  277. XrApplicationInfo application_info{
  278. "", // applicationName, we'll set this down below
  279. 1, // applicationVersion, we don't currently have this
  280. "Godot Game Engine", // engineName
  281. VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH, // engineVersion 4.0 -> 40000, 4.0.1 -> 40001, 4.1 -> 40100, etc.
  282. XR_CURRENT_API_VERSION // apiVersion
  283. };
  284. void *next_pointer = nullptr;
  285. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  286. void *np = wrapper->set_instance_create_info_and_get_next_pointer(next_pointer);
  287. if (np != nullptr) {
  288. next_pointer = np;
  289. }
  290. }
  291. XrInstanceCreateInfo instance_create_info = {
  292. XR_TYPE_INSTANCE_CREATE_INFO, // type
  293. next_pointer, // next
  294. 0, // createFlags
  295. application_info, // applicationInfo
  296. 0, // enabledApiLayerCount, need to find out if we need support for this?
  297. nullptr, // enabledApiLayerNames
  298. uint32_t(extension_ptrs.size()), // enabledExtensionCount
  299. extension_ptrs.ptr() // enabledExtensionNames
  300. };
  301. copy_string_to_char_buffer(project_name, instance_create_info.applicationInfo.applicationName, XR_MAX_APPLICATION_NAME_SIZE);
  302. XrResult result = xrCreateInstance(&instance_create_info, &instance);
  303. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed to create XR instance.");
  304. // from this point on we can use get_error_string to get more info about our errors...
  305. XrInstanceProperties instanceProps = {
  306. XR_TYPE_INSTANCE_PROPERTIES, // type;
  307. nullptr, // next
  308. 0, // runtimeVersion, from here will be set by our get call
  309. "" // runtimeName
  310. };
  311. OPENXR_API_INIT_XR_FUNC_V(xrGetInstanceProperties);
  312. result = xrGetInstanceProperties(instance, &instanceProps);
  313. if (XR_FAILED(result)) {
  314. // not fatal probably
  315. print_line("OpenXR: Failed to get XR instance properties [", get_error_string(result), "]");
  316. } else {
  317. print_line("OpenXR: Running on OpenXR runtime: ", instanceProps.runtimeName, " ", OpenXRUtil::make_xr_version_string(instanceProps.runtimeVersion));
  318. }
  319. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  320. wrapper->on_instance_created(instance);
  321. }
  322. return true;
  323. }
  324. bool OpenXRAPI::get_system_info() {
  325. // Retrieve basic OpenXR system info based on the form factor we desire
  326. // Retrieve the system for our form factor, fails if form factor is not available
  327. XrSystemGetInfo system_get_info = {
  328. XR_TYPE_SYSTEM_GET_INFO, // type;
  329. nullptr, // next
  330. form_factor // formFactor
  331. };
  332. XrResult result = xrGetSystem(instance, &system_get_info, &system_id);
  333. if (XR_FAILED(result)) {
  334. print_line("OpenXR: Failed to get system for our form factor [", get_error_string(result), "]");
  335. return false;
  336. }
  337. // obtain info about our system, writing this out completely to make CI on Linux happy..
  338. void *next_pointer = nullptr;
  339. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  340. void *np = wrapper->set_system_properties_and_get_next_pointer(next_pointer);
  341. if (np != nullptr) {
  342. next_pointer = np;
  343. }
  344. }
  345. XrSystemProperties system_properties = {
  346. XR_TYPE_SYSTEM_PROPERTIES, // type
  347. next_pointer, // next
  348. 0, // systemId, from here will be set by our get call
  349. 0, // vendorId
  350. "", // systemName
  351. {
  352. 0, // maxSwapchainImageHeight
  353. 0, // maxSwapchainImageWidth
  354. 0, // maxLayerCount
  355. }, // graphicsProperties
  356. {
  357. false, // orientationTracking
  358. false // positionTracking
  359. } // trackingProperties
  360. };
  361. result = xrGetSystemProperties(instance, system_id, &system_properties);
  362. if (XR_FAILED(result)) {
  363. print_line("OpenXR: Failed to get System properties [", get_error_string(result), "]");
  364. return false;
  365. }
  366. // remember this state, we'll use it later
  367. system_name = String(system_properties.systemName);
  368. vendor_id = system_properties.vendorId;
  369. graphics_properties = system_properties.graphicsProperties;
  370. tracking_properties = system_properties.trackingProperties;
  371. return true;
  372. }
  373. bool OpenXRAPI::load_supported_view_configuration_types() {
  374. // This queries the supported configuration types, likely there will only be one choosing between Mono (phone AR) and Stereo (HMDs)
  375. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  376. if (supported_view_configuration_types != nullptr) {
  377. // free previous results
  378. memfree(supported_view_configuration_types);
  379. supported_view_configuration_types = nullptr;
  380. }
  381. XrResult result = xrEnumerateViewConfigurations(instance, system_id, 0, &num_view_configuration_types, nullptr);
  382. if (XR_FAILED(result)) {
  383. print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
  384. return false;
  385. }
  386. supported_view_configuration_types = (XrViewConfigurationType *)memalloc(sizeof(XrViewConfigurationType) * num_view_configuration_types);
  387. ERR_FAIL_NULL_V(supported_view_configuration_types, false);
  388. result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types);
  389. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations");
  390. for (uint32_t i = 0; i < num_view_configuration_types; i++) {
  391. print_verbose(String("OpenXR: Found supported view configuration ") + OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i]));
  392. }
  393. return true;
  394. }
  395. bool OpenXRAPI::is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const {
  396. ERR_FAIL_NULL_V(supported_view_configuration_types, false);
  397. for (uint32_t i = 0; i < num_view_configuration_types; i++) {
  398. if (supported_view_configuration_types[i] == p_configuration_type) {
  399. return true;
  400. }
  401. }
  402. return false;
  403. }
  404. bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type) {
  405. // This loads our view configuration for each view so for a stereo HMD, we'll get two entries (that are likely identical)
  406. // The returned data supplies us with the recommended render target size
  407. if (!is_view_configuration_supported(p_configuration_type)) {
  408. print_line("OpenXR: View configuration ", OpenXRUtil::get_view_configuration_name(view_configuration), " is not supported.");
  409. return false;
  410. }
  411. if (view_configuration_views != nullptr) {
  412. // free previous results
  413. memfree(view_configuration_views);
  414. view_configuration_views = nullptr;
  415. }
  416. XrResult result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, 0, &view_count, nullptr);
  417. if (XR_FAILED(result)) {
  418. print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
  419. return false;
  420. }
  421. view_configuration_views = (XrViewConfigurationView *)memalloc(sizeof(XrViewConfigurationView) * view_count);
  422. ERR_FAIL_NULL_V(view_configuration_views, false);
  423. for (uint32_t i = 0; i < view_count; i++) {
  424. view_configuration_views[i].type = XR_TYPE_VIEW_CONFIGURATION_VIEW;
  425. view_configuration_views[i].next = nullptr;
  426. }
  427. result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views);
  428. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations");
  429. for (uint32_t i = 0; i < view_count; i++) {
  430. print_verbose("OpenXR: Found supported view configuration view");
  431. print_verbose(String(" - width: ") + itos(view_configuration_views[i].maxImageRectWidth));
  432. print_verbose(String(" - height: ") + itos(view_configuration_views[i].maxImageRectHeight));
  433. print_verbose(String(" - sample count: ") + itos(view_configuration_views[i].maxSwapchainSampleCount));
  434. print_verbose(String(" - recommended render width: ") + itos(view_configuration_views[i].recommendedImageRectWidth));
  435. print_verbose(String(" - recommended render height: ") + itos(view_configuration_views[i].recommendedImageRectHeight));
  436. print_verbose(String(" - recommended render sample count: ") + itos(view_configuration_views[i].recommendedSwapchainSampleCount));
  437. }
  438. return true;
  439. }
  440. void OpenXRAPI::destroy_instance() {
  441. if (view_configuration_views != nullptr) {
  442. memfree(view_configuration_views);
  443. view_configuration_views = nullptr;
  444. }
  445. if (supported_view_configuration_types != nullptr) {
  446. memfree(supported_view_configuration_types);
  447. supported_view_configuration_types = nullptr;
  448. }
  449. if (instance != XR_NULL_HANDLE) {
  450. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  451. wrapper->on_instance_destroyed();
  452. }
  453. xrDestroyInstance(instance);
  454. instance = XR_NULL_HANDLE;
  455. }
  456. enabled_extensions.clear();
  457. if (graphics_extension != nullptr) {
  458. unregister_extension_wrapper(graphics_extension);
  459. memdelete(graphics_extension);
  460. graphics_extension = nullptr;
  461. }
  462. }
  463. bool OpenXRAPI::create_session() {
  464. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  465. ERR_FAIL_COND_V(session != XR_NULL_HANDLE, false);
  466. void *next_pointer = nullptr;
  467. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  468. void *np = wrapper->set_session_create_and_get_next_pointer(next_pointer);
  469. if (np != nullptr) {
  470. next_pointer = np;
  471. }
  472. }
  473. XrSessionCreateInfo session_create_info = {
  474. XR_TYPE_SESSION_CREATE_INFO, // type
  475. next_pointer, // next
  476. 0, // createFlags
  477. system_id // systemId
  478. };
  479. XrResult result = xrCreateSession(instance, &session_create_info, &session);
  480. if (XR_FAILED(result)) {
  481. print_line("OpenXR: Failed to create session [", get_error_string(result), "]");
  482. return false;
  483. }
  484. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  485. wrapper->on_session_created(session);
  486. }
  487. return true;
  488. }
  489. bool OpenXRAPI::load_supported_reference_spaces() {
  490. // loads the supported reference spaces for our OpenXR session
  491. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  492. if (supported_reference_spaces != nullptr) {
  493. // free previous results
  494. memfree(supported_reference_spaces);
  495. supported_reference_spaces = nullptr;
  496. }
  497. XrResult result = xrEnumerateReferenceSpaces(session, 0, &num_reference_spaces, nullptr);
  498. if (XR_FAILED(result)) {
  499. print_line("OpenXR: Failed to get reference space count [", get_error_string(result), "]");
  500. return false;
  501. }
  502. supported_reference_spaces = (XrReferenceSpaceType *)memalloc(sizeof(XrReferenceSpaceType) * num_reference_spaces);
  503. ERR_FAIL_NULL_V(supported_reference_spaces, false);
  504. result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces);
  505. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces");
  506. for (uint32_t i = 0; i < num_reference_spaces; i++) {
  507. print_verbose(String("OpenXR: Found supported reference space ") + OpenXRUtil::get_reference_space_name(supported_reference_spaces[i]));
  508. }
  509. return true;
  510. }
  511. bool OpenXRAPI::is_reference_space_supported(XrReferenceSpaceType p_reference_space) {
  512. ERR_FAIL_NULL_V(supported_reference_spaces, false);
  513. for (uint32_t i = 0; i < num_reference_spaces; i++) {
  514. if (supported_reference_spaces[i] == p_reference_space) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. bool OpenXRAPI::setup_spaces() {
  521. XrResult result;
  522. XrPosef identityPose = {
  523. { 0.0, 0.0, 0.0, 1.0 },
  524. { 0.0, 0.0, 0.0 }
  525. };
  526. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  527. // create play space
  528. {
  529. if (!is_reference_space_supported(reference_space)) {
  530. print_line("OpenXR: reference space ", OpenXRUtil::get_reference_space_name(reference_space), " is not supported.");
  531. return false;
  532. }
  533. XrReferenceSpaceCreateInfo play_space_create_info = {
  534. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  535. nullptr, // next
  536. reference_space, // referenceSpaceType
  537. identityPose // poseInReferenceSpace
  538. };
  539. result = xrCreateReferenceSpace(session, &play_space_create_info, &play_space);
  540. if (XR_FAILED(result)) {
  541. print_line("OpenXR: Failed to create play space [", get_error_string(result), "]");
  542. return false;
  543. }
  544. }
  545. // create view space
  546. {
  547. if (!is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_VIEW)) {
  548. print_line("OpenXR: reference space XR_REFERENCE_SPACE_TYPE_VIEW is not supported.");
  549. return false;
  550. }
  551. XrReferenceSpaceCreateInfo view_space_create_info = {
  552. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  553. nullptr, // next
  554. XR_REFERENCE_SPACE_TYPE_VIEW, // referenceSpaceType
  555. identityPose // poseInReferenceSpace
  556. };
  557. result = xrCreateReferenceSpace(session, &view_space_create_info, &view_space);
  558. if (XR_FAILED(result)) {
  559. print_line("OpenXR: Failed to create view space [", get_error_string(result), "]");
  560. return false;
  561. }
  562. }
  563. return true;
  564. }
  565. bool OpenXRAPI::load_supported_swapchain_formats() {
  566. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  567. if (supported_swapchain_formats != nullptr) {
  568. // free previous results
  569. memfree(supported_swapchain_formats);
  570. supported_swapchain_formats = nullptr;
  571. }
  572. XrResult result = xrEnumerateSwapchainFormats(session, 0, &num_swapchain_formats, nullptr);
  573. if (XR_FAILED(result)) {
  574. print_line("OpenXR: Failed to get swapchain format count [", get_error_string(result), "]");
  575. return false;
  576. }
  577. supported_swapchain_formats = (int64_t *)memalloc(sizeof(int64_t) * num_swapchain_formats);
  578. ERR_FAIL_NULL_V(supported_swapchain_formats, false);
  579. result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats);
  580. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats");
  581. for (uint32_t i = 0; i < num_swapchain_formats; i++) {
  582. print_verbose(String("OpenXR: Found supported swapchain format ") + get_swapchain_format_name(supported_swapchain_formats[i]));
  583. }
  584. return true;
  585. }
  586. bool OpenXRAPI::is_swapchain_format_supported(int64_t p_swapchain_format) {
  587. ERR_FAIL_NULL_V(supported_swapchain_formats, false);
  588. for (uint32_t i = 0; i < num_swapchain_formats; i++) {
  589. if (supported_swapchain_formats[i] == p_swapchain_format) {
  590. return true;
  591. }
  592. }
  593. return false;
  594. }
  595. bool OpenXRAPI::create_swapchains() {
  596. ERR_FAIL_NULL_V(graphics_extension, false);
  597. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  598. /*
  599. TODO: We need to improve on this, for now we're taking our old approach of creating our main swapchains and substituting
  600. those for the ones Godot normally creates.
  601. This however means we can only use swapchains for our main XR view.
  602. It would have been nicer if we could override the swapchain creation in Godot with ours but we have a timing issue here.
  603. We can't create XR swapchains until after our XR session is fully instantiated, yet Godot creates its swapchain much earlier.
  604. Also Godot only creates a swapchain for the main output.
  605. OpenXR will require us to create swapchains as the render target for additional viewports if we want to use the layer system
  606. to optimize text rendering and background rendering as OpenXR may choose to re-use the results for reprojection while we're
  607. already rendering the next frame.
  608. Finally an area we need to expand upon is that Foveated rendering is only enabled for the swap chain we create,
  609. as we render 3D content into internal buffers that are copied into the swapchain, we do now have (basic) VRS support
  610. */
  611. Size2 recommended_size = get_recommended_target_size();
  612. // We start with our color swapchain...
  613. {
  614. // Build a vector with swapchain formats we want to use, from best fit to worst
  615. Vector<int64_t> usable_swapchain_formats;
  616. int64_t swapchain_format_to_use = 0;
  617. graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats);
  618. // now find out which one is supported
  619. for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) {
  620. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  621. swapchain_format_to_use = usable_swapchain_formats[i];
  622. }
  623. }
  624. if (swapchain_format_to_use == 0) {
  625. swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best...
  626. print_line("Couldn't find usable color swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead.");
  627. } else {
  628. print_verbose(String("Using color swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
  629. }
  630. if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain, &swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data)) {
  631. return false;
  632. }
  633. }
  634. views = (XrView *)memalloc(sizeof(XrView) * view_count);
  635. ERR_FAIL_NULL_V_MSG(views, false, "OpenXR Couldn't allocate memory for views");
  636. projection_views = (XrCompositionLayerProjectionView *)memalloc(sizeof(XrCompositionLayerProjectionView) * view_count);
  637. ERR_FAIL_NULL_V_MSG(projection_views, false, "OpenXR Couldn't allocate memory for projection views");
  638. // We create our depth swapchain if:
  639. // - we've enabled submitting depth buffer
  640. // - we support our depth layer extension
  641. // - we have our spacewarp extension (not yet implemented)
  642. if (submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
  643. // Build a vector with swapchain formats we want to use, from best fit to worst
  644. Vector<int64_t> usable_swapchain_formats;
  645. int64_t swapchain_format_to_use = 0;
  646. graphics_extension->get_usable_depth_formats(usable_swapchain_formats);
  647. // now find out which one is supported
  648. for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) {
  649. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  650. swapchain_format_to_use = usable_swapchain_formats[i];
  651. }
  652. }
  653. if (swapchain_format_to_use == 0) {
  654. swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best...
  655. print_line("Couldn't find usable depth swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead.");
  656. } else {
  657. print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
  658. }
  659. if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain, &swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data)) {
  660. return false;
  661. }
  662. depth_views = (XrCompositionLayerDepthInfoKHR *)memalloc(sizeof(XrCompositionLayerDepthInfoKHR) * view_count);
  663. ERR_FAIL_NULL_V_MSG(depth_views, false, "OpenXR Couldn't allocate memory for depth views");
  664. }
  665. // We create our velocity swapchain if:
  666. // - we have our spacewarp extension (not yet implemented)
  667. {
  668. // TBD
  669. }
  670. for (uint32_t i = 0; i < view_count; i++) {
  671. views[i].type = XR_TYPE_VIEW;
  672. views[i].next = nullptr;
  673. projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
  674. projection_views[i].next = nullptr;
  675. projection_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain;
  676. projection_views[i].subImage.imageArrayIndex = i;
  677. projection_views[i].subImage.imageRect.offset.x = 0;
  678. projection_views[i].subImage.imageRect.offset.y = 0;
  679. projection_views[i].subImage.imageRect.extent.width = recommended_size.width;
  680. projection_views[i].subImage.imageRect.extent.height = recommended_size.height;
  681. if (submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && depth_views) {
  682. projection_views[i].next = &depth_views[i];
  683. depth_views[i].type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR;
  684. depth_views[i].next = nullptr;
  685. depth_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain;
  686. depth_views[i].subImage.imageArrayIndex = i;
  687. depth_views[i].subImage.imageRect.offset.x = 0;
  688. depth_views[i].subImage.imageRect.offset.y = 0;
  689. depth_views[i].subImage.imageRect.extent.width = recommended_size.width;
  690. depth_views[i].subImage.imageRect.extent.height = recommended_size.height;
  691. depth_views[i].minDepth = 0.0;
  692. depth_views[i].maxDepth = 1.0;
  693. depth_views[i].nearZ = 0.01; // Near and far Z will be set to the correct values in fill_projection_matrix
  694. depth_views[i].farZ = 100.0;
  695. }
  696. };
  697. return true;
  698. };
  699. void OpenXRAPI::destroy_session() {
  700. if (running && session != XR_NULL_HANDLE) {
  701. xrEndSession(session);
  702. }
  703. if (graphics_extension) {
  704. graphics_extension->cleanup_swapchain_graphics_data(&swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data);
  705. }
  706. if (views != nullptr) {
  707. memfree(views);
  708. views = nullptr;
  709. }
  710. if (projection_views != nullptr) {
  711. memfree(projection_views);
  712. projection_views = nullptr;
  713. }
  714. if (depth_views != nullptr) {
  715. memfree(depth_views);
  716. depth_views = nullptr;
  717. }
  718. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  719. if (swapchains[i].swapchain != XR_NULL_HANDLE) {
  720. xrDestroySwapchain(swapchains[i].swapchain);
  721. swapchains[i].swapchain = XR_NULL_HANDLE;
  722. }
  723. }
  724. if (supported_swapchain_formats != nullptr) {
  725. memfree(supported_swapchain_formats);
  726. supported_swapchain_formats = nullptr;
  727. }
  728. // destroy our spaces
  729. if (play_space != XR_NULL_HANDLE) {
  730. xrDestroySpace(play_space);
  731. play_space = XR_NULL_HANDLE;
  732. }
  733. if (view_space != XR_NULL_HANDLE) {
  734. xrDestroySpace(view_space);
  735. view_space = XR_NULL_HANDLE;
  736. }
  737. if (supported_reference_spaces != nullptr) {
  738. // free previous results
  739. memfree(supported_reference_spaces);
  740. supported_reference_spaces = nullptr;
  741. }
  742. if (session != XR_NULL_HANDLE) {
  743. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  744. wrapper->on_session_destroyed();
  745. }
  746. xrDestroySession(session);
  747. session = XR_NULL_HANDLE;
  748. }
  749. }
  750. bool OpenXRAPI::create_swapchain(XrSwapchainUsageFlags p_usage_flags, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data) {
  751. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  752. ERR_FAIL_NULL_V(graphics_extension, false);
  753. XrResult result;
  754. void *next_pointer = nullptr;
  755. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  756. void *np = wrapper->set_swapchain_create_info_and_get_next_pointer(next_pointer);
  757. if (np != nullptr) {
  758. next_pointer = np;
  759. }
  760. }
  761. XrSwapchainCreateInfo swapchain_create_info = {
  762. XR_TYPE_SWAPCHAIN_CREATE_INFO, // type
  763. next_pointer, // next
  764. 0, // createFlags
  765. p_usage_flags, // usageFlags
  766. p_swapchain_format, // format
  767. p_sample_count, // sampleCount
  768. p_width, // width
  769. p_height, // height
  770. 1, // faceCount
  771. p_array_size, // arraySize
  772. 1 // mipCount
  773. };
  774. XrSwapchain new_swapchain;
  775. result = xrCreateSwapchain(session, &swapchain_create_info, &new_swapchain);
  776. if (XR_FAILED(result)) {
  777. print_line("OpenXR: Failed to get swapchain [", get_error_string(result), "]");
  778. return false;
  779. }
  780. if (!graphics_extension->get_swapchain_image_data(new_swapchain, p_swapchain_format, p_width, p_height, p_sample_count, p_array_size, r_swapchain_graphics_data)) {
  781. xrDestroySwapchain(new_swapchain);
  782. return false;
  783. }
  784. r_swapchain = new_swapchain;
  785. return true;
  786. }
  787. bool OpenXRAPI::on_state_idle() {
  788. print_verbose("On state idle");
  789. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  790. wrapper->on_state_idle();
  791. }
  792. return true;
  793. }
  794. bool OpenXRAPI::on_state_ready() {
  795. print_verbose("On state ready");
  796. // begin session
  797. XrSessionBeginInfo session_begin_info = {
  798. XR_TYPE_SESSION_BEGIN_INFO, // type
  799. nullptr, // next
  800. view_configuration // primaryViewConfigurationType
  801. };
  802. XrResult result = xrBeginSession(session, &session_begin_info);
  803. if (XR_FAILED(result)) {
  804. print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");
  805. return false;
  806. }
  807. // This is when we create our swapchain, this can be a "long" time after Godot finishes, we can deal with this for now
  808. // but once we want to provide Viewports for additional layers where OpenXR requires us to create further swapchains,
  809. // we'll be creating those viewport WAY before we reach this point.
  810. // We may need to implement a wait in our init in main.cpp polling our events until the session is ready.
  811. // That will be very very ugly
  812. // The other possibility is to create a separate OpenXRViewport type specifically for this goal as part of our OpenXR module
  813. if (!create_swapchains()) {
  814. return false;
  815. }
  816. // we're running
  817. running = true;
  818. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  819. wrapper->on_state_ready();
  820. }
  821. if (xr_interface) {
  822. xr_interface->on_state_ready();
  823. }
  824. // TODO Tell android
  825. return true;
  826. }
  827. bool OpenXRAPI::on_state_synchronized() {
  828. print_verbose("On state synchronized");
  829. // Just in case, see if we already have active trackers...
  830. List<RID> trackers;
  831. tracker_owner.get_owned_list(&trackers);
  832. for (int i = 0; i < trackers.size(); i++) {
  833. tracker_check_profile(trackers[i]);
  834. }
  835. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  836. wrapper->on_state_synchronized();
  837. }
  838. return true;
  839. }
  840. bool OpenXRAPI::on_state_visible() {
  841. print_verbose("On state visible");
  842. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  843. wrapper->on_state_visible();
  844. }
  845. if (xr_interface) {
  846. xr_interface->on_state_visible();
  847. }
  848. return true;
  849. }
  850. bool OpenXRAPI::on_state_focused() {
  851. print_verbose("On state focused");
  852. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  853. wrapper->on_state_focused();
  854. }
  855. if (xr_interface) {
  856. xr_interface->on_state_focused();
  857. }
  858. return true;
  859. }
  860. bool OpenXRAPI::on_state_stopping() {
  861. print_verbose("On state stopping");
  862. if (xr_interface) {
  863. xr_interface->on_state_stopping();
  864. }
  865. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  866. wrapper->on_state_stopping();
  867. }
  868. if (running) {
  869. XrResult result = xrEndSession(session);
  870. if (XR_FAILED(result)) {
  871. // we only report this..
  872. print_line("OpenXR: Failed to end session [", get_error_string(result), "]");
  873. }
  874. running = false;
  875. }
  876. // TODO further cleanup
  877. return true;
  878. }
  879. bool OpenXRAPI::on_state_loss_pending() {
  880. print_verbose("On state loss pending");
  881. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  882. wrapper->on_state_loss_pending();
  883. }
  884. // TODO need to look into the correct action here, read up on the spec but we may need to signal Godot to exit (if it's not already exiting)
  885. return true;
  886. }
  887. bool OpenXRAPI::on_state_exiting() {
  888. print_verbose("On state existing");
  889. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  890. wrapper->on_state_exiting();
  891. }
  892. // TODO need to look into the correct action here, read up on the spec but we may need to signal Godot to exit (if it's not already exiting)
  893. return true;
  894. }
  895. void OpenXRAPI::set_form_factor(XrFormFactor p_form_factor) {
  896. ERR_FAIL_COND(is_initialized());
  897. form_factor = p_form_factor;
  898. }
  899. void OpenXRAPI::set_view_configuration(XrViewConfigurationType p_view_configuration) {
  900. ERR_FAIL_COND(is_initialized());
  901. view_configuration = p_view_configuration;
  902. }
  903. void OpenXRAPI::set_reference_space(XrReferenceSpaceType p_reference_space) {
  904. ERR_FAIL_COND(is_initialized());
  905. reference_space = p_reference_space;
  906. }
  907. void OpenXRAPI::set_submit_depth_buffer(bool p_submit_depth_buffer) {
  908. ERR_FAIL_COND(is_initialized());
  909. submit_depth_buffer = p_submit_depth_buffer;
  910. }
  911. bool OpenXRAPI::is_initialized() {
  912. return (instance != XR_NULL_HANDLE);
  913. }
  914. bool OpenXRAPI::is_running() {
  915. if (instance == XR_NULL_HANDLE) {
  916. return false;
  917. }
  918. if (session == XR_NULL_HANDLE) {
  919. return false;
  920. }
  921. return running;
  922. }
  923. bool OpenXRAPI::openxr_loader_init() {
  924. #ifdef ANDROID_ENABLED
  925. ERR_FAIL_COND_V_MSG(openxr_loader_library_handle != nullptr, false, "OpenXR Loader library is already loaded.");
  926. {
  927. Error error_code = OS::get_singleton()->open_dynamic_library(OPENXR_LOADER_NAME, openxr_loader_library_handle);
  928. ERR_FAIL_COND_V_MSG(error_code != OK, false, "OpenXR loader not found.");
  929. }
  930. {
  931. Error error_code = OS::get_singleton()->get_dynamic_library_symbol_handle(openxr_loader_library_handle, "xrGetInstanceProcAddr", (void *&)xrGetInstanceProcAddr);
  932. ERR_FAIL_COND_V_MSG(error_code != OK, false, "Symbol xrGetInstanceProcAddr not found in OpenXR Loader library.");
  933. }
  934. #endif
  935. // Resolve the symbols that don't require an instance
  936. OPENXR_API_INIT_XR_FUNC_V(xrCreateInstance);
  937. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateApiLayerProperties);
  938. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateInstanceExtensionProperties);
  939. return true;
  940. }
  941. bool OpenXRAPI::resolve_instance_openxr_symbols() {
  942. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  943. OPENXR_API_INIT_XR_FUNC_V(xrAcquireSwapchainImage);
  944. OPENXR_API_INIT_XR_FUNC_V(xrApplyHapticFeedback);
  945. OPENXR_API_INIT_XR_FUNC_V(xrAttachSessionActionSets);
  946. OPENXR_API_INIT_XR_FUNC_V(xrBeginFrame);
  947. OPENXR_API_INIT_XR_FUNC_V(xrBeginSession);
  948. OPENXR_API_INIT_XR_FUNC_V(xrCreateAction);
  949. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSet);
  950. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSpace);
  951. OPENXR_API_INIT_XR_FUNC_V(xrCreateReferenceSpace);
  952. OPENXR_API_INIT_XR_FUNC_V(xrCreateSession);
  953. OPENXR_API_INIT_XR_FUNC_V(xrCreateSwapchain);
  954. OPENXR_API_INIT_XR_FUNC_V(xrDestroyAction);
  955. OPENXR_API_INIT_XR_FUNC_V(xrDestroyActionSet);
  956. OPENXR_API_INIT_XR_FUNC_V(xrDestroyInstance);
  957. OPENXR_API_INIT_XR_FUNC_V(xrDestroySession);
  958. OPENXR_API_INIT_XR_FUNC_V(xrDestroySpace);
  959. OPENXR_API_INIT_XR_FUNC_V(xrDestroySwapchain);
  960. OPENXR_API_INIT_XR_FUNC_V(xrEndFrame);
  961. OPENXR_API_INIT_XR_FUNC_V(xrEndSession);
  962. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateReferenceSpaces);
  963. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateSwapchainFormats);
  964. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurations);
  965. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurationViews);
  966. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateBoolean);
  967. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateFloat);
  968. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateVector2f);
  969. OPENXR_API_INIT_XR_FUNC_V(xrGetCurrentInteractionProfile);
  970. OPENXR_API_INIT_XR_FUNC_V(xrGetSystem);
  971. OPENXR_API_INIT_XR_FUNC_V(xrGetSystemProperties);
  972. OPENXR_API_INIT_XR_FUNC_V(xrLocateViews);
  973. OPENXR_API_INIT_XR_FUNC_V(xrLocateSpace);
  974. OPENXR_API_INIT_XR_FUNC_V(xrPathToString);
  975. OPENXR_API_INIT_XR_FUNC_V(xrPollEvent);
  976. OPENXR_API_INIT_XR_FUNC_V(xrReleaseSwapchainImage);
  977. OPENXR_API_INIT_XR_FUNC_V(xrResultToString);
  978. OPENXR_API_INIT_XR_FUNC_V(xrStringToPath);
  979. OPENXR_API_INIT_XR_FUNC_V(xrSuggestInteractionProfileBindings);
  980. OPENXR_API_INIT_XR_FUNC_V(xrSyncActions);
  981. OPENXR_API_INIT_XR_FUNC_V(xrWaitFrame);
  982. OPENXR_API_INIT_XR_FUNC_V(xrWaitSwapchainImage);
  983. return true;
  984. }
  985. XrResult OpenXRAPI::try_get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  986. return xrGetInstanceProcAddr(instance, p_name, p_addr);
  987. }
  988. XrResult OpenXRAPI::get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  989. XrResult result = try_get_instance_proc_addr(p_name, p_addr);
  990. if (result != XR_SUCCESS) {
  991. String error_message = String("Symbol ") + p_name + " not found in OpenXR instance.";
  992. ERR_FAIL_COND_V_MSG(true, result, error_message.utf8().get_data());
  993. }
  994. return result;
  995. }
  996. bool OpenXRAPI::initialize(const String &p_rendering_driver) {
  997. ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created");
  998. if (!openxr_loader_init()) {
  999. return false;
  1000. }
  1001. if (p_rendering_driver == "vulkan") {
  1002. #ifdef VULKAN_ENABLED
  1003. graphics_extension = memnew(OpenXRVulkanExtension);
  1004. register_extension_wrapper(graphics_extension);
  1005. #else
  1006. // shouldn't be possible...
  1007. ERR_FAIL_V(false);
  1008. #endif
  1009. } else if (p_rendering_driver == "opengl3") {
  1010. #ifdef GLES3_ENABLED
  1011. graphics_extension = memnew(OpenXROpenGLExtension);
  1012. register_extension_wrapper(graphics_extension);
  1013. #else
  1014. // shouldn't be possible...
  1015. ERR_FAIL_V(false);
  1016. #endif
  1017. } else {
  1018. ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device.");
  1019. }
  1020. // initialize
  1021. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1022. wrapper->on_before_instance_created();
  1023. }
  1024. if (!load_layer_properties()) {
  1025. destroy_instance();
  1026. return false;
  1027. }
  1028. if (!load_supported_extensions()) {
  1029. destroy_instance();
  1030. return false;
  1031. }
  1032. if (!create_instance()) {
  1033. destroy_instance();
  1034. return false;
  1035. }
  1036. if (!resolve_instance_openxr_symbols()) {
  1037. destroy_instance();
  1038. return false;
  1039. }
  1040. if (!get_system_info()) {
  1041. destroy_instance();
  1042. return false;
  1043. }
  1044. if (!load_supported_view_configuration_types()) {
  1045. destroy_instance();
  1046. return false;
  1047. }
  1048. if (!load_supported_view_configuration_views(view_configuration)) {
  1049. destroy_instance();
  1050. return false;
  1051. }
  1052. return true;
  1053. }
  1054. bool OpenXRAPI::initialize_session() {
  1055. if (!create_session()) {
  1056. destroy_session();
  1057. return false;
  1058. }
  1059. if (!load_supported_reference_spaces()) {
  1060. destroy_session();
  1061. return false;
  1062. }
  1063. if (!setup_spaces()) {
  1064. destroy_session();
  1065. return false;
  1066. }
  1067. if (!load_supported_swapchain_formats()) {
  1068. destroy_session();
  1069. return false;
  1070. }
  1071. return true;
  1072. }
  1073. void OpenXRAPI::finish() {
  1074. destroy_session();
  1075. destroy_instance();
  1076. }
  1077. void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) {
  1078. xr_interface = p_xr_interface;
  1079. }
  1080. void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1081. registered_extension_wrappers.push_back(p_extension_wrapper);
  1082. }
  1083. void OpenXRAPI::unregister_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1084. registered_extension_wrappers.erase(p_extension_wrapper);
  1085. }
  1086. void OpenXRAPI::register_extension_metadata() {
  1087. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1088. extension_wrapper->on_register_metadata();
  1089. }
  1090. }
  1091. void OpenXRAPI::cleanup_extension_wrappers() {
  1092. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1093. memdelete(extension_wrapper);
  1094. }
  1095. registered_extension_wrappers.clear();
  1096. }
  1097. Size2 OpenXRAPI::get_recommended_target_size() {
  1098. ERR_FAIL_NULL_V(view_configuration_views, Size2());
  1099. Size2 target_size;
  1100. target_size.width = view_configuration_views[0].recommendedImageRectWidth;
  1101. target_size.height = view_configuration_views[0].recommendedImageRectHeight;
  1102. return target_size;
  1103. }
  1104. XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1105. XrResult result;
  1106. ERR_FAIL_COND_V(!running, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1107. // xrWaitFrame not run yet
  1108. if (frame_state.predictedDisplayTime == 0) {
  1109. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1110. }
  1111. // Get timing for the next frame, as that is the current frame we're processing
  1112. XrTime display_time = get_next_frame_time();
  1113. XrSpaceVelocity velocity = {
  1114. XR_TYPE_SPACE_VELOCITY, // type
  1115. nullptr, // next
  1116. 0, // velocityFlags
  1117. { 0.0, 0.0, 0.0 }, // linearVelocity
  1118. { 0.0, 0.0, 0.0 } // angularVelocity
  1119. };
  1120. XrSpaceLocation location = {
  1121. XR_TYPE_SPACE_LOCATION, // type
  1122. &velocity, // next
  1123. 0, // locationFlags
  1124. {
  1125. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  1126. { 0.0, 0.0, 0.0 } // position
  1127. } // pose
  1128. };
  1129. result = xrLocateSpace(view_space, play_space, display_time, &location);
  1130. if (XR_FAILED(result)) {
  1131. print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]");
  1132. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1133. }
  1134. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  1135. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  1136. if (head_pose_confidence != confidence) {
  1137. // prevent error spam
  1138. head_pose_confidence = confidence;
  1139. if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1140. print_line("OpenXR head space location not valid (check tracking?)");
  1141. } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
  1142. print_verbose("OpenVR Head pose now tracking with low confidence");
  1143. } else {
  1144. print_verbose("OpenVR Head pose now tracking with high confidence");
  1145. }
  1146. }
  1147. return confidence;
  1148. }
  1149. bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) {
  1150. ERR_FAIL_COND_V(!running, false);
  1151. // xrWaitFrame not run yet
  1152. if (frame_state.predictedDisplayTime == 0) {
  1153. return false;
  1154. }
  1155. // we don't have valid view info
  1156. if (views == nullptr || !view_pose_valid) {
  1157. return false;
  1158. }
  1159. // Note, the timing of this is set right before rendering, which is what we need here.
  1160. r_transform = transform_from_pose(views[p_view].pose);
  1161. return true;
  1162. }
  1163. bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, Projection &p_camera_matrix) {
  1164. ERR_FAIL_COND_V(!running, false);
  1165. ERR_FAIL_NULL_V(graphics_extension, false);
  1166. // xrWaitFrame not run yet
  1167. if (frame_state.predictedDisplayTime == 0) {
  1168. return false;
  1169. }
  1170. // we don't have valid view info
  1171. if (views == nullptr || !view_pose_valid) {
  1172. return false;
  1173. }
  1174. // if we're using depth views, make sure we update our near and far there...
  1175. if (depth_views != nullptr) {
  1176. for (uint32_t i = 0; i < view_count; i++) {
  1177. depth_views[i].nearZ = p_z_near;
  1178. depth_views[i].farZ = p_z_far;
  1179. }
  1180. }
  1181. // now update our projection
  1182. return graphics_extension->create_projection_fov(views[p_view].fov, p_z_near, p_z_far, p_camera_matrix);
  1183. }
  1184. bool OpenXRAPI::poll_events() {
  1185. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1186. XrEventDataBuffer runtimeEvent;
  1187. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1188. runtimeEvent.next = nullptr;
  1189. // runtimeEvent.varying = ...
  1190. XrResult pollResult = xrPollEvent(instance, &runtimeEvent);
  1191. while (pollResult == XR_SUCCESS) {
  1192. bool handled = false;
  1193. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1194. handled |= wrapper->on_event_polled(runtimeEvent);
  1195. }
  1196. switch (runtimeEvent.type) {
  1197. case XR_TYPE_EVENT_DATA_EVENTS_LOST: {
  1198. XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent;
  1199. // We probably didn't poll fast enough, just output warning
  1200. WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!");
  1201. } break;
  1202. case XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR: {
  1203. // XrEventDataVisibilityMaskChangedKHR *event = (XrEventDataVisibilityMaskChangedKHR *)&runtimeEvent;
  1204. // TODO implement this in the future, we should call xrGetVisibilityMaskKHR to obtain a mask,
  1205. // this will allow us to prevent rendering the part of our view which is never displayed giving us
  1206. // a decent performance improvement.
  1207. print_verbose("OpenXR EVENT: STUB: visibility mask changed");
  1208. } break;
  1209. case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
  1210. XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent;
  1211. // TODO We get this event if we're about to loose our OpenXR instance.
  1212. // We should queue exiting Godot at this point.
  1213. print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime));
  1214. return false;
  1215. } break;
  1216. case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
  1217. XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent;
  1218. session_state = event->state;
  1219. if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
  1220. print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state));
  1221. } else {
  1222. print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state));
  1223. switch (session_state) {
  1224. case XR_SESSION_STATE_IDLE:
  1225. on_state_idle();
  1226. break;
  1227. case XR_SESSION_STATE_READY:
  1228. on_state_ready();
  1229. break;
  1230. case XR_SESSION_STATE_SYNCHRONIZED:
  1231. on_state_synchronized();
  1232. break;
  1233. case XR_SESSION_STATE_VISIBLE:
  1234. on_state_visible();
  1235. break;
  1236. case XR_SESSION_STATE_FOCUSED:
  1237. on_state_focused();
  1238. break;
  1239. case XR_SESSION_STATE_STOPPING:
  1240. on_state_stopping();
  1241. break;
  1242. case XR_SESSION_STATE_LOSS_PENDING:
  1243. on_state_loss_pending();
  1244. break;
  1245. case XR_SESSION_STATE_EXITING:
  1246. on_state_exiting();
  1247. break;
  1248. default:
  1249. break;
  1250. }
  1251. }
  1252. } break;
  1253. case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
  1254. XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
  1255. print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
  1256. if (event->poseValid && xr_interface) {
  1257. xr_interface->on_pose_recentered();
  1258. }
  1259. } break;
  1260. case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
  1261. print_verbose("OpenXR EVENT: interaction profile changed!");
  1262. XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
  1263. List<RID> trackers;
  1264. tracker_owner.get_owned_list(&trackers);
  1265. for (int i = 0; i < trackers.size(); i++) {
  1266. tracker_check_profile(trackers[i], event->session);
  1267. }
  1268. } break;
  1269. default:
  1270. if (!handled) {
  1271. print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
  1272. }
  1273. break;
  1274. }
  1275. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1276. pollResult = xrPollEvent(instance, &runtimeEvent);
  1277. }
  1278. if (pollResult == XR_EVENT_UNAVAILABLE) {
  1279. // processed all events in the queue
  1280. return true;
  1281. } else {
  1282. ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!");
  1283. }
  1284. }
  1285. bool OpenXRAPI::process() {
  1286. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1287. if (!poll_events()) {
  1288. return false;
  1289. }
  1290. if (!running) {
  1291. return false;
  1292. }
  1293. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1294. wrapper->on_process();
  1295. }
  1296. return true;
  1297. }
  1298. bool OpenXRAPI::acquire_image(OpenXRSwapChainInfo &p_swapchain) {
  1299. ERR_FAIL_COND_V(p_swapchain.image_acquired, true); // this was not released when it should be, error out and re-use...
  1300. XrResult result;
  1301. XrSwapchainImageAcquireInfo swapchain_image_acquire_info = {
  1302. XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type
  1303. nullptr // next
  1304. };
  1305. result = xrAcquireSwapchainImage(p_swapchain.swapchain, &swapchain_image_acquire_info, &p_swapchain.image_index);
  1306. if (XR_FAILED(result)) {
  1307. print_line("OpenXR: failed to acquire swapchain image [", get_error_string(result), "]");
  1308. return false;
  1309. }
  1310. XrSwapchainImageWaitInfo swapchain_image_wait_info = {
  1311. XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type
  1312. nullptr, // next
  1313. 17000000 // timeout in nanoseconds
  1314. };
  1315. result = xrWaitSwapchainImage(p_swapchain.swapchain, &swapchain_image_wait_info);
  1316. if (XR_FAILED(result)) {
  1317. print_line("OpenXR: failed to wait for swapchain image [", get_error_string(result), "]");
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. bool OpenXRAPI::release_image(OpenXRSwapChainInfo &p_swapchain) {
  1323. XrSwapchainImageReleaseInfo swapchain_image_release_info = {
  1324. XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type
  1325. nullptr // next
  1326. };
  1327. XrResult result = xrReleaseSwapchainImage(p_swapchain.swapchain, &swapchain_image_release_info);
  1328. if (XR_FAILED(result)) {
  1329. print_line("OpenXR: failed to release swapchain image! [", get_error_string(result), "]");
  1330. return false;
  1331. }
  1332. return true;
  1333. }
  1334. void OpenXRAPI::pre_render() {
  1335. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1336. if (!running) {
  1337. return;
  1338. }
  1339. // Waitframe does 2 important things in our process:
  1340. // 1) It provides us with predictive timing, telling us when OpenXR expects to display the frame we're about to commit
  1341. // 2) It will use the previous timing to pause our thread so that rendering starts as close to displaying as possible
  1342. // This must thus be called as close to when we start rendering as possible
  1343. XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr };
  1344. frame_state.predictedDisplayTime = 0;
  1345. frame_state.predictedDisplayPeriod = 0;
  1346. frame_state.shouldRender = false;
  1347. XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state);
  1348. if (XR_FAILED(result)) {
  1349. print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]");
  1350. // reset just in case
  1351. frame_state.predictedDisplayTime = 0;
  1352. frame_state.predictedDisplayPeriod = 0;
  1353. frame_state.shouldRender = false;
  1354. return;
  1355. }
  1356. if (frame_state.predictedDisplayPeriod > 500000000) {
  1357. // display period more then 0.5 seconds? must be wrong data
  1358. print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod));
  1359. frame_state.predictedDisplayPeriod = 0;
  1360. }
  1361. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1362. wrapper->on_pre_render();
  1363. }
  1364. // Get our view info for the frame we're about to render, note from the OpenXR manual:
  1365. // "Repeatedly calling xrLocateViews with the same time may not necessarily return the same result. Instead the prediction gets increasingly accurate as the function is called closer to the given time for which a prediction is made"
  1366. // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling,
  1367. // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire
  1368. // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and
  1369. // update the view and projection matrix once more with a slightly more accurate predication and then submit the
  1370. // command queues.
  1371. // That is not possible yet but worth investigating in the future.
  1372. XrViewLocateInfo view_locate_info = {
  1373. XR_TYPE_VIEW_LOCATE_INFO, // type
  1374. nullptr, // next
  1375. view_configuration, // viewConfigurationType
  1376. frame_state.predictedDisplayTime, // displayTime
  1377. play_space // space
  1378. };
  1379. XrViewState view_state = {
  1380. XR_TYPE_VIEW_STATE, // type
  1381. nullptr, // next
  1382. 0 // viewStateFlags
  1383. };
  1384. uint32_t view_count_output;
  1385. result = xrLocateViews(session, &view_locate_info, &view_state, view_count, &view_count_output, views);
  1386. if (XR_FAILED(result)) {
  1387. print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");
  1388. return;
  1389. }
  1390. bool pose_valid = true;
  1391. for (uint64_t i = 0; i < view_count_output; i++) {
  1392. if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||
  1393. (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {
  1394. pose_valid = false;
  1395. }
  1396. }
  1397. if (view_pose_valid != pose_valid) {
  1398. view_pose_valid = pose_valid;
  1399. if (!view_pose_valid) {
  1400. print_verbose("OpenXR View pose became invalid");
  1401. } else {
  1402. print_verbose("OpenXR View pose became valid");
  1403. }
  1404. }
  1405. // let's start our frame..
  1406. XrFrameBeginInfo frame_begin_info = {
  1407. XR_TYPE_FRAME_BEGIN_INFO, // type
  1408. nullptr // next
  1409. };
  1410. result = xrBeginFrame(session, &frame_begin_info);
  1411. if (XR_FAILED(result)) {
  1412. print_line("OpenXR: failed to being frame [", get_error_string(result), "]");
  1413. return;
  1414. }
  1415. }
  1416. bool OpenXRAPI::pre_draw_viewport(RID p_render_target) {
  1417. if (!can_render()) {
  1418. return false;
  1419. }
  1420. // TODO: at some point in time we may support multiple viewports in which case we need to handle that...
  1421. // Acquire our images
  1422. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1423. if (!swapchains[i].image_acquired && swapchains[i].swapchain != XR_NULL_HANDLE) {
  1424. if (!acquire_image(swapchains[i])) {
  1425. return false;
  1426. }
  1427. swapchains[i].image_acquired = true;
  1428. }
  1429. }
  1430. return true;
  1431. }
  1432. RID OpenXRAPI::get_color_texture() {
  1433. if (swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1434. return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_COLOR].image_index);
  1435. } else {
  1436. return RID();
  1437. }
  1438. }
  1439. RID OpenXRAPI::get_depth_texture() {
  1440. if (submit_depth_buffer && swapchains[OPENXR_SWAPCHAIN_DEPTH].image_acquired) {
  1441. return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_DEPTH].image_index);
  1442. } else {
  1443. return RID();
  1444. }
  1445. }
  1446. void OpenXRAPI::post_draw_viewport(RID p_render_target) {
  1447. if (!can_render()) {
  1448. return;
  1449. }
  1450. // Nothing to do here at this point in time...
  1451. };
  1452. void OpenXRAPI::end_frame() {
  1453. XrResult result;
  1454. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1455. if (!running) {
  1456. return;
  1457. }
  1458. if (frame_state.shouldRender && view_pose_valid && !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1459. print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!");
  1460. }
  1461. // must have:
  1462. // - shouldRender set to true
  1463. // - a valid view pose for projection_views[eye].pose to submit layer
  1464. // - an image to render
  1465. if (!frame_state.shouldRender || !view_pose_valid || !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1466. // submit 0 layers when we shouldn't render
  1467. XrFrameEndInfo frame_end_info = {
  1468. XR_TYPE_FRAME_END_INFO, // type
  1469. nullptr, // next
  1470. frame_state.predictedDisplayTime, // displayTime
  1471. XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode
  1472. 0, // layerCount
  1473. nullptr // layers
  1474. };
  1475. result = xrEndFrame(session, &frame_end_info);
  1476. if (XR_FAILED(result)) {
  1477. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1478. return;
  1479. }
  1480. // neither eye is rendered
  1481. return;
  1482. }
  1483. // release our swapchain image if we acquired it
  1484. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1485. if (swapchains[i].image_acquired) {
  1486. swapchains[i].image_acquired = false; // whether we succeed or not, consider this released.
  1487. release_image(swapchains[i]);
  1488. }
  1489. }
  1490. for (uint32_t eye = 0; eye < view_count; eye++) {
  1491. projection_views[eye].fov = views[eye].fov;
  1492. projection_views[eye].pose = views[eye].pose;
  1493. }
  1494. Vector<const XrCompositionLayerBaseHeader *> layers_list;
  1495. // Add composition layers from providers
  1496. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1497. XrCompositionLayerBaseHeader *layer = provider->get_composition_layer();
  1498. if (layer) {
  1499. layers_list.push_back(layer);
  1500. }
  1501. }
  1502. XrCompositionLayerProjection projection_layer = {
  1503. XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type
  1504. nullptr, // next
  1505. layers_list.size() > 0 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags
  1506. play_space, // space
  1507. view_count, // viewCount
  1508. projection_views, // views
  1509. };
  1510. layers_list.push_back((const XrCompositionLayerBaseHeader *)&projection_layer);
  1511. XrFrameEndInfo frame_end_info = {
  1512. XR_TYPE_FRAME_END_INFO, // type
  1513. nullptr, // next
  1514. frame_state.predictedDisplayTime, // displayTime
  1515. XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode
  1516. static_cast<uint32_t>(layers_list.size()), // layerCount
  1517. layers_list.ptr() // layers
  1518. };
  1519. result = xrEndFrame(session, &frame_end_info);
  1520. if (XR_FAILED(result)) {
  1521. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1522. return;
  1523. }
  1524. }
  1525. float OpenXRAPI::get_display_refresh_rate() const {
  1526. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1527. if (drrext) {
  1528. return drrext->get_refresh_rate();
  1529. }
  1530. return 0.0;
  1531. }
  1532. void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) {
  1533. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1534. if (drrext != nullptr) {
  1535. drrext->set_refresh_rate(p_refresh_rate);
  1536. }
  1537. }
  1538. Array OpenXRAPI::get_available_display_refresh_rates() const {
  1539. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1540. if (drrext != nullptr) {
  1541. return drrext->get_available_refresh_rates();
  1542. }
  1543. return Array();
  1544. }
  1545. OpenXRAPI::OpenXRAPI() {
  1546. // OpenXRAPI is only constructed if OpenXR is enabled.
  1547. singleton = this;
  1548. if (Engine::get_singleton()->is_editor_hint()) {
  1549. // Enabled OpenXR in the editor? Adjust our settings for the editor
  1550. } else {
  1551. // Load settings from project settings
  1552. int ff = GLOBAL_GET("xr/openxr/form_factor");
  1553. switch (ff) {
  1554. case 0: {
  1555. form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
  1556. } break;
  1557. case 1: {
  1558. form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY;
  1559. } break;
  1560. default:
  1561. break;
  1562. }
  1563. int vc = GLOBAL_GET("xr/openxr/view_configuration");
  1564. switch (vc) {
  1565. case 0: {
  1566. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
  1567. } break;
  1568. case 1: {
  1569. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
  1570. } break;
  1571. /* we don't support quad and observer configurations (yet)
  1572. case 2: {
  1573. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
  1574. } break;
  1575. case 3: {
  1576. view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
  1577. } break;
  1578. */
  1579. default:
  1580. break;
  1581. }
  1582. int rs = GLOBAL_GET("xr/openxr/reference_space");
  1583. switch (rs) {
  1584. case 0: {
  1585. reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  1586. } break;
  1587. case 1: {
  1588. reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
  1589. } break;
  1590. default:
  1591. break;
  1592. }
  1593. submit_depth_buffer = GLOBAL_GET("xr/openxr/submit_depth_buffer");
  1594. }
  1595. // reset a few things that can't be done in our class definition
  1596. frame_state.predictedDisplayTime = 0;
  1597. frame_state.predictedDisplayPeriod = 0;
  1598. }
  1599. OpenXRAPI::~OpenXRAPI() {
  1600. // cleanup our composition layer providers
  1601. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1602. memdelete(provider);
  1603. }
  1604. composition_layer_providers.clear();
  1605. if (supported_extensions != nullptr) {
  1606. memfree(supported_extensions);
  1607. supported_extensions = nullptr;
  1608. }
  1609. if (layer_properties != nullptr) {
  1610. memfree(layer_properties);
  1611. layer_properties = nullptr;
  1612. }
  1613. #ifdef ANDROID_ENABLED
  1614. if (openxr_loader_library_handle) {
  1615. OS::get_singleton()->close_dynamic_library(openxr_loader_library_handle);
  1616. openxr_loader_library_handle = nullptr;
  1617. }
  1618. #endif
  1619. singleton = nullptr;
  1620. }
  1621. Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) {
  1622. Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w);
  1623. Basis basis(q);
  1624. Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z);
  1625. return Transform3D(basis, origin);
  1626. }
  1627. template <typename T>
  1628. XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) {
  1629. Basis basis;
  1630. Vector3 origin;
  1631. XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1632. const auto &pose = p_location.pose;
  1633. // Check orientation
  1634. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) {
  1635. Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
  1636. r_transform.basis = Basis(q);
  1637. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) {
  1638. // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING
  1639. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1640. } else {
  1641. // Orientation is being tracked but we're using old/predicted data, so low tracking confidence
  1642. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1643. }
  1644. } else {
  1645. r_transform.basis = Basis();
  1646. }
  1647. // Check location
  1648. if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) {
  1649. r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z);
  1650. if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) {
  1651. // Location is being tracked but we're using old/predicted data, so low tracking confidence
  1652. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1653. } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1654. // Position tracking without orientation tracking?
  1655. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1656. }
  1657. } else {
  1658. // No tracking or 3DOF I guess..
  1659. r_transform.origin = Vector3();
  1660. }
  1661. return confidence;
  1662. }
  1663. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) {
  1664. return _transform_from_location(p_location, r_transform);
  1665. }
  1666. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) {
  1667. return _transform_from_location(p_location, r_transform);
  1668. }
  1669. void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1670. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) {
  1671. XrVector3f linear_velocity = p_velocity.linearVelocity;
  1672. r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z);
  1673. } else {
  1674. r_linear_velocity = Vector3();
  1675. }
  1676. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) {
  1677. XrVector3f angular_velocity = p_velocity.angularVelocity;
  1678. r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z);
  1679. } else {
  1680. r_angular_velocity = Vector3();
  1681. }
  1682. }
  1683. bool OpenXRAPI::xr_result(XrResult result, const char *format, Array args) const {
  1684. if (XR_SUCCEEDED(result))
  1685. return true;
  1686. char resultString[XR_MAX_RESULT_STRING_SIZE];
  1687. xrResultToString(instance, result, resultString);
  1688. print_error(String("OpenXR ") + String(format).format(args) + String(" [") + String(resultString) + String("]"));
  1689. return false;
  1690. }
  1691. RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
  1692. List<RID> current;
  1693. tracker_owner.get_owned_list(&current);
  1694. for (int i = 0; i < current.size(); i++) {
  1695. Tracker *tracker = tracker_owner.get_or_null(current[i]);
  1696. if (tracker && tracker->toplevel_path == p_path) {
  1697. return current[i];
  1698. }
  1699. }
  1700. return RID();
  1701. }
  1702. RID OpenXRAPI::tracker_create(const String p_name) {
  1703. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1704. Tracker new_tracker;
  1705. new_tracker.name = p_name;
  1706. new_tracker.toplevel_path = XR_NULL_PATH;
  1707. new_tracker.active_profile_rid = RID();
  1708. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_tracker.toplevel_path);
  1709. if (XR_FAILED(result)) {
  1710. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1711. return RID();
  1712. }
  1713. return tracker_owner.make_rid(new_tracker);
  1714. }
  1715. String OpenXRAPI::tracker_get_name(RID p_tracker) {
  1716. if (p_tracker.is_null()) {
  1717. return String("None");
  1718. }
  1719. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1720. ERR_FAIL_NULL_V(tracker, String());
  1721. return tracker->name;
  1722. }
  1723. void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) {
  1724. if (p_session == XR_NULL_HANDLE) {
  1725. p_session = session;
  1726. }
  1727. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1728. ERR_FAIL_NULL(tracker);
  1729. if (tracker->toplevel_path == XR_NULL_PATH) {
  1730. // no path, how was this even created?
  1731. return;
  1732. }
  1733. XrInteractionProfileState profile_state = {
  1734. XR_TYPE_INTERACTION_PROFILE_STATE, // type
  1735. nullptr, // next
  1736. XR_NULL_PATH // interactionProfile
  1737. };
  1738. XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state);
  1739. if (XR_FAILED(result)) {
  1740. print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]");
  1741. return;
  1742. }
  1743. XrPath new_profile = profile_state.interactionProfile;
  1744. XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid);
  1745. if (was_profile != new_profile) {
  1746. tracker->active_profile_rid = get_interaction_profile_rid(new_profile);
  1747. if (xr_interface) {
  1748. xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid);
  1749. }
  1750. }
  1751. }
  1752. void OpenXRAPI::tracker_free(RID p_tracker) {
  1753. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1754. ERR_FAIL_NULL(tracker);
  1755. // there is nothing to free here
  1756. tracker_owner.free(p_tracker);
  1757. }
  1758. RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_name, const int p_priority) {
  1759. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1760. ActionSet action_set;
  1761. action_set.name = p_name;
  1762. action_set.is_attached = false;
  1763. // create our action set...
  1764. XrActionSetCreateInfo action_set_info = {
  1765. XR_TYPE_ACTION_SET_CREATE_INFO, // type
  1766. nullptr, // next
  1767. "", // actionSetName
  1768. "", // localizedActionSetName
  1769. uint32_t(p_priority) // priority
  1770. };
  1771. copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
  1772. copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
  1773. XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
  1774. if (XR_FAILED(result)) {
  1775. print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
  1776. return RID();
  1777. }
  1778. return action_set_owner.make_rid(action_set);
  1779. }
  1780. String OpenXRAPI::action_set_get_name(RID p_action_set) {
  1781. if (p_action_set.is_null()) {
  1782. return String("None");
  1783. }
  1784. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1785. ERR_FAIL_NULL_V(action_set, String());
  1786. return action_set->name;
  1787. }
  1788. bool OpenXRAPI::action_set_attach(RID p_action_set) {
  1789. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1790. ERR_FAIL_NULL_V(action_set, false);
  1791. if (action_set->is_attached) {
  1792. // already attached
  1793. return true;
  1794. }
  1795. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1796. // So according to the docs, once we attach our action set to our session it becomes read only..
  1797. // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html
  1798. XrSessionActionSetsAttachInfo attach_info = {
  1799. XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type
  1800. nullptr, // next
  1801. 1, // countActionSets,
  1802. &action_set->handle // actionSets
  1803. };
  1804. XrResult result = xrAttachSessionActionSets(session, &attach_info);
  1805. if (XR_FAILED(result)) {
  1806. print_line("OpenXR: failed to attach action set! [", get_error_string(result), "]");
  1807. return false;
  1808. }
  1809. action_set->is_attached = true;
  1810. /* For debugging:
  1811. print_verbose("Attached set " + action_set->name);
  1812. List<RID> action_rids;
  1813. action_owner.get_owned_list(&action_rids);
  1814. for (int i = 0; i < action_rids.size(); i++) {
  1815. Action * action = action_owner.get_or_null(action_rids[i]);
  1816. if (action && action->action_set_rid == p_action_set) {
  1817. print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type));
  1818. for (int j = 0; j < action->trackers.size(); j++) {
  1819. Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid);
  1820. if (tracker) {
  1821. print_verbose(" - " + tracker->name);
  1822. }
  1823. }
  1824. }
  1825. }
  1826. */
  1827. return true;
  1828. }
  1829. void OpenXRAPI::action_set_free(RID p_action_set) {
  1830. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1831. ERR_FAIL_NULL(action_set);
  1832. if (action_set->handle != XR_NULL_HANDLE) {
  1833. xrDestroyActionSet(action_set->handle);
  1834. }
  1835. action_set_owner.free(p_action_set);
  1836. }
  1837. RID OpenXRAPI::get_action_rid(XrAction p_action) {
  1838. List<RID> current;
  1839. action_owner.get_owned_list(&current);
  1840. for (int i = 0; i < current.size(); i++) {
  1841. Action *action = action_owner.get_or_null(current[i]);
  1842. if (action && action->handle == p_action) {
  1843. return current[i];
  1844. }
  1845. }
  1846. return RID();
  1847. }
  1848. RID OpenXRAPI::action_create(RID p_action_set, const String p_name, const String p_localized_name, OpenXRAction::ActionType p_action_type, const Vector<RID> &p_trackers) {
  1849. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1850. Action action;
  1851. action.name = p_name;
  1852. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1853. ERR_FAIL_NULL_V(action_set, RID());
  1854. ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID());
  1855. action.action_set_rid = p_action_set;
  1856. switch (p_action_type) {
  1857. case OpenXRAction::OPENXR_ACTION_BOOL:
  1858. action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT;
  1859. break;
  1860. case OpenXRAction::OPENXR_ACTION_FLOAT:
  1861. action.action_type = XR_ACTION_TYPE_FLOAT_INPUT;
  1862. break;
  1863. case OpenXRAction::OPENXR_ACTION_VECTOR2:
  1864. action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT;
  1865. break;
  1866. case OpenXRAction::OPENXR_ACTION_POSE:
  1867. action.action_type = XR_ACTION_TYPE_POSE_INPUT;
  1868. break;
  1869. case OpenXRAction::OPENXR_ACTION_HAPTIC:
  1870. action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT;
  1871. break;
  1872. default:
  1873. ERR_FAIL_V(RID());
  1874. break;
  1875. }
  1876. Vector<XrPath> toplevel_paths;
  1877. for (int i = 0; i < p_trackers.size(); i++) {
  1878. Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]);
  1879. if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) {
  1880. ActionTracker action_tracker = {
  1881. p_trackers[i], // tracker
  1882. XR_NULL_HANDLE, // space
  1883. false // was_location_valid
  1884. };
  1885. action.trackers.push_back(action_tracker);
  1886. toplevel_paths.push_back(tracker->toplevel_path);
  1887. }
  1888. }
  1889. XrActionCreateInfo action_info = {
  1890. XR_TYPE_ACTION_CREATE_INFO, // type
  1891. nullptr, // next
  1892. "", // actionName
  1893. action.action_type, // actionType
  1894. uint32_t(toplevel_paths.size()), // countSubactionPaths
  1895. toplevel_paths.ptr(), // subactionPaths
  1896. "" // localizedActionName
  1897. };
  1898. copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
  1899. copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
  1900. XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
  1901. if (XR_FAILED(result)) {
  1902. print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
  1903. return RID();
  1904. }
  1905. return action_owner.make_rid(action);
  1906. }
  1907. String OpenXRAPI::action_get_name(RID p_action) {
  1908. if (p_action.is_null()) {
  1909. return String("None");
  1910. }
  1911. Action *action = action_owner.get_or_null(p_action);
  1912. ERR_FAIL_NULL_V(action, String());
  1913. return action->name;
  1914. }
  1915. void OpenXRAPI::action_free(RID p_action) {
  1916. Action *action = action_owner.get_or_null(p_action);
  1917. ERR_FAIL_NULL(action);
  1918. if (action->handle != XR_NULL_HANDLE) {
  1919. xrDestroyAction(action->handle);
  1920. }
  1921. action_owner.free(p_action);
  1922. }
  1923. RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
  1924. List<RID> current;
  1925. interaction_profile_owner.get_owned_list(&current);
  1926. for (int i = 0; i < current.size(); i++) {
  1927. InteractionProfile *ip = interaction_profile_owner.get_or_null(current[i]);
  1928. if (ip && ip->path == p_path) {
  1929. return current[i];
  1930. }
  1931. }
  1932. return RID();
  1933. }
  1934. XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) {
  1935. if (p_interaction_profile.is_null()) {
  1936. return XR_NULL_PATH;
  1937. }
  1938. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1939. ERR_FAIL_NULL_V(ip, XR_NULL_PATH);
  1940. return ip->path;
  1941. }
  1942. RID OpenXRAPI::interaction_profile_create(const String p_name) {
  1943. if (!is_interaction_profile_supported(p_name)) {
  1944. // The extension enabling this path must not be active, we will silently skip this interaction profile
  1945. return RID();
  1946. }
  1947. InteractionProfile new_interaction_profile;
  1948. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path);
  1949. if (XR_FAILED(result)) {
  1950. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1951. return RID();
  1952. }
  1953. RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path);
  1954. if (existing_ip.is_valid()) {
  1955. return existing_ip;
  1956. }
  1957. new_interaction_profile.name = p_name;
  1958. return interaction_profile_owner.make_rid(new_interaction_profile);
  1959. }
  1960. String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) {
  1961. if (p_interaction_profile.is_null()) {
  1962. return String("None");
  1963. }
  1964. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1965. ERR_FAIL_NULL_V(ip, String());
  1966. return ip->name;
  1967. }
  1968. void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) {
  1969. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1970. ERR_FAIL_NULL(ip);
  1971. ip->bindings.clear();
  1972. }
  1973. bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) {
  1974. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1975. ERR_FAIL_NULL_V(ip, false);
  1976. if (!interaction_profile_supports_io_path(ip->name, p_path)) {
  1977. return false;
  1978. }
  1979. XrActionSuggestedBinding binding;
  1980. Action *action = action_owner.get_or_null(p_action);
  1981. ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, false);
  1982. binding.action = action->handle;
  1983. XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &binding.binding);
  1984. if (XR_FAILED(result)) {
  1985. print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
  1986. return false;
  1987. }
  1988. ip->bindings.push_back(binding);
  1989. return true;
  1990. }
  1991. bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) {
  1992. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1993. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1994. ERR_FAIL_NULL_V(ip, false);
  1995. const XrInteractionProfileSuggestedBinding suggested_bindings = {
  1996. XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type
  1997. nullptr, // next
  1998. ip->path, // interactionProfile
  1999. uint32_t(ip->bindings.size()), // countSuggestedBindings
  2000. ip->bindings.ptr() // suggestedBindings
  2001. };
  2002. XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings);
  2003. if (result == XR_ERROR_PATH_UNSUPPORTED) {
  2004. // this is fine, not all runtimes support all devices.
  2005. print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime");
  2006. } else if (XR_FAILED(result)) {
  2007. print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]");
  2008. // reporting is enough...
  2009. }
  2010. /* For debugging:
  2011. print_verbose("Suggested bindings for " + ip->name);
  2012. for (int i = 0; i < ip->bindings.size(); i++) {
  2013. uint32_t strlen;
  2014. char path[XR_MAX_PATH_LENGTH];
  2015. String action_name = action_get_name(get_action_rid(ip->bindings[i].action));
  2016. XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path);
  2017. if (XR_FAILED(result)) {
  2018. print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]");
  2019. }
  2020. print_verbose(" - " + action_name + " => " + String(path));
  2021. }
  2022. */
  2023. return true;
  2024. }
  2025. void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) {
  2026. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2027. ERR_FAIL_NULL(ip);
  2028. ip->bindings.clear();
  2029. interaction_profile_owner.free(p_interaction_profile);
  2030. }
  2031. bool OpenXRAPI::sync_action_sets(const Vector<RID> p_active_sets) {
  2032. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2033. if (!running) {
  2034. return false;
  2035. }
  2036. Vector<XrActiveActionSet> active_sets;
  2037. for (int i = 0; i < p_active_sets.size(); i++) {
  2038. ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]);
  2039. if (action_set && action_set->handle != XR_NULL_HANDLE) {
  2040. XrActiveActionSet aset;
  2041. aset.actionSet = action_set->handle;
  2042. aset.subactionPath = XR_NULL_PATH;
  2043. active_sets.push_back(aset);
  2044. }
  2045. }
  2046. ERR_FAIL_COND_V(active_sets.size() == 0, false);
  2047. XrActionsSyncInfo sync_info = {
  2048. XR_TYPE_ACTIONS_SYNC_INFO, // type
  2049. nullptr, // next
  2050. uint32_t(active_sets.size()), // countActiveActionSets
  2051. active_sets.ptr() // activeActionSets
  2052. };
  2053. XrResult result = xrSyncActions(session, &sync_info);
  2054. if (XR_FAILED(result)) {
  2055. print_line("OpenXR: failed to sync active action sets! [", get_error_string(result), "]");
  2056. return false;
  2057. }
  2058. return true;
  2059. }
  2060. bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) {
  2061. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2062. Action *action = action_owner.get_or_null(p_action);
  2063. ERR_FAIL_NULL_V(action, false);
  2064. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2065. ERR_FAIL_NULL_V(tracker, false);
  2066. if (!running) {
  2067. return false;
  2068. }
  2069. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false);
  2070. XrActionStateGetInfo get_info = {
  2071. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2072. nullptr, // next
  2073. action->handle, // action
  2074. tracker->toplevel_path // subactionPath
  2075. };
  2076. XrActionStateBoolean result_state;
  2077. result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN,
  2078. result_state.next = nullptr;
  2079. XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state);
  2080. if (XR_FAILED(result)) {
  2081. print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]");
  2082. return false;
  2083. }
  2084. return result_state.isActive && result_state.currentState;
  2085. }
  2086. float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) {
  2087. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0);
  2088. Action *action = action_owner.get_or_null(p_action);
  2089. ERR_FAIL_NULL_V(action, 0.0);
  2090. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2091. ERR_FAIL_NULL_V(tracker, 0.0);
  2092. if (!running) {
  2093. return 0.0;
  2094. }
  2095. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0);
  2096. XrActionStateGetInfo get_info = {
  2097. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2098. nullptr, // next
  2099. action->handle, // action
  2100. tracker->toplevel_path // subactionPath
  2101. };
  2102. XrActionStateFloat result_state;
  2103. result_state.type = XR_TYPE_ACTION_STATE_FLOAT,
  2104. result_state.next = nullptr;
  2105. XrResult result = xrGetActionStateFloat(session, &get_info, &result_state);
  2106. if (XR_FAILED(result)) {
  2107. print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]");
  2108. return 0.0;
  2109. }
  2110. return result_state.isActive ? result_state.currentState : 0.0;
  2111. }
  2112. Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
  2113. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2());
  2114. Action *action = action_owner.get_or_null(p_action);
  2115. ERR_FAIL_NULL_V(action, Vector2());
  2116. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2117. ERR_FAIL_NULL_V(tracker, Vector2());
  2118. if (!running) {
  2119. return Vector2();
  2120. }
  2121. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2());
  2122. XrActionStateGetInfo get_info = {
  2123. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2124. nullptr, // next
  2125. action->handle, // action
  2126. tracker->toplevel_path // subactionPath
  2127. };
  2128. XrActionStateVector2f result_state;
  2129. result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F,
  2130. result_state.next = nullptr;
  2131. XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state);
  2132. if (XR_FAILED(result)) {
  2133. print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]");
  2134. return Vector2();
  2135. }
  2136. return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
  2137. }
  2138. XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  2139. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2140. Action *action = action_owner.get_or_null(p_action);
  2141. ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2142. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2143. ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2144. if (!running) {
  2145. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2146. }
  2147. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2148. // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")");
  2149. uint64_t index = 0xFFFFFFFF;
  2150. uint64_t size = uint64_t(action->trackers.size());
  2151. for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) {
  2152. if (action->trackers[i].tracker_rid == p_tracker) {
  2153. index = i;
  2154. }
  2155. }
  2156. if (index == 0xFFFFFFFF) {
  2157. // couldn't find it?
  2158. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2159. }
  2160. XrTime display_time = get_next_frame_time();
  2161. if (display_time == 0) {
  2162. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2163. }
  2164. if (action->trackers[index].space == XR_NULL_HANDLE) {
  2165. // if this is a pose we need to define spaces
  2166. XrActionSpaceCreateInfo action_space_info = {
  2167. XR_TYPE_ACTION_SPACE_CREATE_INFO, // type
  2168. nullptr, // next
  2169. action->handle, // action
  2170. tracker->toplevel_path, // subactionPath
  2171. {
  2172. { 0.0, 0.0, 0.0, 1.0 }, // orientation
  2173. { 0.0, 0.0, 0.0 } // position
  2174. } // poseInActionSpace
  2175. };
  2176. XrSpace space;
  2177. XrResult result = xrCreateActionSpace(session, &action_space_info, &space);
  2178. if (XR_FAILED(result)) {
  2179. print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]");
  2180. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2181. }
  2182. action->trackers.ptrw()[index].space = space;
  2183. }
  2184. XrSpaceVelocity velocity = {
  2185. XR_TYPE_SPACE_VELOCITY, // type
  2186. nullptr, // next
  2187. 0, // velocityFlags
  2188. { 0.0, 0.0, 0.0 }, // linearVelocity
  2189. { 0.0, 0.0, 0.0 } // angularVelocity
  2190. };
  2191. XrSpaceLocation location = {
  2192. XR_TYPE_SPACE_LOCATION, // type
  2193. &velocity, // next
  2194. 0, // locationFlags
  2195. {
  2196. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  2197. { 0.0, 0.0, 0.0 } // position
  2198. } // pose
  2199. };
  2200. XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location);
  2201. if (XR_FAILED(result)) {
  2202. print_line("OpenXR: failed to locate space! [", get_error_string(result), "]");
  2203. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2204. }
  2205. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  2206. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  2207. return confidence;
  2208. }
  2209. bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) {
  2210. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2211. Action *action = action_owner.get_or_null(p_action);
  2212. ERR_FAIL_NULL_V(action, false);
  2213. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2214. ERR_FAIL_NULL_V(tracker, false);
  2215. if (!running) {
  2216. return false;
  2217. }
  2218. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false);
  2219. XrHapticActionInfo action_info = {
  2220. XR_TYPE_HAPTIC_ACTION_INFO, // type
  2221. nullptr, // next
  2222. action->handle, // action
  2223. tracker->toplevel_path // subactionPath
  2224. };
  2225. XrHapticVibration vibration = {
  2226. XR_TYPE_HAPTIC_VIBRATION, // type
  2227. nullptr, // next
  2228. p_duration_ns, // duration
  2229. p_frequency, // frequency
  2230. p_amplitude, // amplitude
  2231. };
  2232. XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration);
  2233. if (XR_FAILED(result)) {
  2234. print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]");
  2235. return false;
  2236. }
  2237. return true;
  2238. }
  2239. void OpenXRAPI::register_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2240. composition_layer_providers.append(provider);
  2241. }
  2242. void OpenXRAPI::unregister_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2243. composition_layer_providers.erase(provider);
  2244. }