openxr_api.cpp 89 KB

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