openxr_api.cpp 90 KB

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