openxr_api.cpp 98 KB

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