openxr_api.cpp 81 KB

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