2
0

openxr_api.cpp 98 KB

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