openxr_api.cpp 98 KB

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