openxr_api.cpp 89 KB

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