openxr_api.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441
  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. #include "extensions/openxr_android_extension.h"
  41. #endif
  42. #ifdef VULKAN_ENABLED
  43. #include "extensions/openxr_vulkan_extension.h"
  44. #endif
  45. #include "modules/openxr/openxr_interface.h"
  46. OpenXRAPI *OpenXRAPI::singleton = nullptr;
  47. void OpenXRAPI::setup_global_defs() {
  48. // As OpenXRAPI is not constructed if OpenXR is not enabled, we register our project and editor settings here
  49. // Project settings
  50. GLOBAL_DEF_BASIC("xr/openxr/enabled", false);
  51. GLOBAL_DEF_BASIC("xr/openxr/default_action_map", "res://default_action_map.tres");
  52. ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/default_action_map", PropertyInfo(Variant::STRING, "xr/openxr/default_action_map", PROPERTY_HINT_FILE, "*.tres"));
  53. GLOBAL_DEF_BASIC("xr/openxr/form_factor", "0");
  54. ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/form_factor", PropertyInfo(Variant::INT, "xr/openxr/form_factor", PROPERTY_HINT_ENUM, "Head mounted,Handheld"));
  55. GLOBAL_DEF_BASIC("xr/openxr/view_configuration", "1");
  56. ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/view_configuration", PropertyInfo(Variant::INT, "xr/openxr/view_configuration", PROPERTY_HINT_ENUM, "Mono,Stereo")); // "Mono,Stereo,Quad,Observer"
  57. GLOBAL_DEF_BASIC("xr/openxr/reference_space", "1");
  58. ProjectSettings::get_singleton()->set_custom_property_info("xr/openxr/reference_space", PropertyInfo(Variant::INT, "xr/openxr/reference_space", PROPERTY_HINT_ENUM, "Local,Stage"));
  59. #ifdef TOOLS_ENABLED
  60. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  61. // editor settings (it seems we're too early in the process when setting up rendering, to access editor settings...)
  62. // EDITOR_DEF_RST("xr/openxr/in_editor", false);
  63. // GLOBAL_DEF("xr/openxr/in_editor", false);
  64. #endif
  65. }
  66. bool OpenXRAPI::openxr_is_enabled() {
  67. // @TODO we need an overrule switch so we can force enable openxr, i.e run "godot --openxr_enabled"
  68. if (Engine::get_singleton()->is_editor_hint()) {
  69. #ifdef TOOLS_ENABLED
  70. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  71. return false;
  72. // bool enabled = GLOBAL_GET("xr/openxr/in_editor"); // EDITOR_GET("xr/openxr/in_editor");
  73. // return enabled;
  74. #else
  75. // we should never get here, editor hint won't be true if the editor isn't compiled in.
  76. return false;
  77. #endif
  78. } else {
  79. bool enabled = GLOBAL_GET("xr/openxr/enabled");
  80. return enabled;
  81. }
  82. }
  83. OpenXRAPI *OpenXRAPI::get_singleton() {
  84. if (singleton != nullptr) {
  85. // already constructed, return our singleton
  86. return singleton;
  87. } else if (openxr_is_enabled()) {
  88. // construct our singleton and return it
  89. singleton = memnew(OpenXRAPI);
  90. return singleton;
  91. } else {
  92. // not enabled, don't instantiate, return nullptr
  93. return nullptr;
  94. }
  95. }
  96. String OpenXRAPI::get_default_action_map_resource_name() {
  97. String name = GLOBAL_GET("xr/openxr/default_action_map");
  98. return name;
  99. }
  100. String OpenXRAPI::get_error_string(XrResult result) {
  101. if (XR_SUCCEEDED(result)) {
  102. return String("Succeeded");
  103. }
  104. if (instance == XR_NULL_HANDLE) {
  105. Array args;
  106. args.push_back(Variant(result));
  107. return String("Error code {0}").format(args);
  108. }
  109. char resultString[XR_MAX_RESULT_STRING_SIZE];
  110. xrResultToString(instance, result, resultString);
  111. return String(resultString);
  112. }
  113. String OpenXRAPI::get_swapchain_format_name(int64_t p_swapchain_format) const {
  114. // This is rendering engine dependend...
  115. if (graphics_extension) {
  116. return graphics_extension->get_swapchain_format_name(p_swapchain_format);
  117. }
  118. return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format));
  119. }
  120. bool OpenXRAPI::load_layer_properties() {
  121. // This queries additional layers that are available and can be initialised when we create our OpenXR instance
  122. if (layer_properties != nullptr) {
  123. // already retrieved this
  124. return true;
  125. }
  126. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  127. XrResult result = xrEnumerateApiLayerProperties(0, &num_layer_properties, nullptr);
  128. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of api layer properties");
  129. layer_properties = (XrApiLayerProperties *)memalloc(sizeof(XrApiLayerProperties) * num_layer_properties);
  130. ERR_FAIL_NULL_V(layer_properties, false);
  131. for (uint32_t i = 0; i < num_layer_properties; i++) {
  132. layer_properties[i].type = XR_TYPE_API_LAYER_PROPERTIES;
  133. layer_properties[i].next = nullptr;
  134. }
  135. result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties);
  136. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties");
  137. #ifdef DEBUG
  138. for (uint32_t i = 0; i < num_layer_properties; i++) {
  139. print_line("OpenXR: Found OpenXR layer ", layer_properties[i].layerName);
  140. }
  141. #endif
  142. return true;
  143. }
  144. bool OpenXRAPI::load_supported_extensions() {
  145. // This queries supported extensions that are available and can be initialised when we create our OpenXR instance
  146. if (supported_extensions != nullptr) {
  147. // already retrieved this
  148. return true;
  149. }
  150. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  151. XrResult result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &num_supported_extensions, nullptr);
  152. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of extension properties");
  153. supported_extensions = (XrExtensionProperties *)memalloc(sizeof(XrExtensionProperties) * num_supported_extensions);
  154. ERR_FAIL_NULL_V(supported_extensions, false);
  155. // set our types
  156. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  157. supported_extensions[i].type = XR_TYPE_EXTENSION_PROPERTIES;
  158. supported_extensions[i].next = nullptr;
  159. }
  160. result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions);
  161. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties");
  162. #ifdef DEBUG
  163. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  164. print_line("OpenXR: Found OpenXR extension ", supported_extensions[i].extensionName);
  165. }
  166. #endif
  167. return true;
  168. }
  169. bool OpenXRAPI::is_extension_supported(const char *p_extension) const {
  170. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  171. if (strcmp(supported_extensions[i].extensionName, p_extension)) {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. void OpenXRAPI::copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len) {
  178. CharString char_string = p_string.utf8();
  179. int len = char_string.length();
  180. if (len < p_buffer_len - 1) {
  181. // was having weird CI issues with strcpy so....
  182. memcpy(p_buffer, char_string.get_data(), len);
  183. p_buffer[len] = '\0';
  184. } else {
  185. memcpy(p_buffer, char_string.get_data(), p_buffer_len - 1);
  186. p_buffer[p_buffer_len - 1] = '\0';
  187. }
  188. }
  189. bool OpenXRAPI::create_instance() {
  190. // Create our OpenXR instance, this will query any registered extension wrappers for extensions we need to enable.
  191. // Append the extensions requested by the registered extension wrappers.
  192. Map<const char *, bool *> requested_extensions;
  193. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  194. Map<const char *, bool *> wrapper_request_extensions = wrapper->get_request_extensions();
  195. // requested_extensions.insert(wrapper_request_extensions.begin(), wrapper_request_extensions.end());
  196. for (auto &requested_extension : wrapper_request_extensions) {
  197. requested_extensions[requested_extension.key] = requested_extension.value;
  198. }
  199. }
  200. // Check which extensions are supported
  201. enabled_extensions.clear();
  202. for (auto &requested_extension : requested_extensions) {
  203. if (!is_extension_supported(requested_extension.key)) {
  204. if (requested_extension.value == nullptr) {
  205. // nullptr means this is a manditory extension so we fail
  206. ERR_FAIL_V_MSG(false, "OpenXR: OpenXR Runtime does not support OpenGL extension!");
  207. } else {
  208. // set this extension as not supported
  209. *requested_extension.value = false;
  210. }
  211. } else if (requested_extension.value != nullptr) {
  212. // set this extension as supported
  213. *requested_extension.value = true;
  214. // and record that we want to enable it
  215. enabled_extensions.push_back(requested_extension.key);
  216. } else {
  217. // record that we want to enable this
  218. enabled_extensions.push_back(requested_extension.key);
  219. }
  220. }
  221. // Get our project name
  222. String project_name = GLOBAL_GET("application/config/name");
  223. // Create our OpenXR instance
  224. XrApplicationInfo application_info{
  225. "", // applicationName, we'll set this down below
  226. 1, // applicationVersion, we don't currently have this
  227. "Godot Game Engine", // engineName
  228. VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH, // engineVersion 4.0 -> 40000, 4.0.1 -> 40001, 4.1 -> 40100, etc.
  229. XR_CURRENT_API_VERSION // apiVersion
  230. };
  231. XrInstanceCreateInfo instance_create_info = {
  232. XR_TYPE_INSTANCE_CREATE_INFO, // type
  233. nullptr, // next
  234. 0, // createFlags
  235. application_info, // applicationInfo
  236. 0, // enabledApiLayerCount, need to find out if we need support for this?
  237. nullptr, // enabledApiLayerNames
  238. uint32_t(enabled_extensions.size()), // enabledExtensionCount
  239. enabled_extensions.ptr() // enabledExtensionNames
  240. };
  241. copy_string_to_char_buffer(project_name, instance_create_info.applicationInfo.applicationName, XR_MAX_APPLICATION_NAME_SIZE);
  242. XrResult result = xrCreateInstance(&instance_create_info, &instance);
  243. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed to create XR instance.");
  244. // from this point on we can use get_error_string to get more info about our errors...
  245. XrInstanceProperties instanceProps = {
  246. XR_TYPE_INSTANCE_PROPERTIES, // type;
  247. nullptr, // next
  248. 0, // runtimeVersion, from here will be set by our get call
  249. "" // runtimeName
  250. };
  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 chosing 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 = NULL;
  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 = NULL;
  581. projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
  582. projection_views[i].next = NULL;
  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::initialise(const String &p_rendering_driver) {
  811. ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created");
  812. if (p_rendering_driver == "vulkan") {
  813. #ifdef VULKAN_ENABLED
  814. graphics_extension = memnew(OpenXRVulkanExtension(this));
  815. register_extension_wrapper(graphics_extension);
  816. #else
  817. // shouldn't be possible...
  818. ERR_FAIL_V(false);
  819. #endif
  820. } else if (p_rendering_driver == "opengl3") {
  821. #ifdef OPENGL3_ENABLED
  822. // graphics_extension = memnew(OpenXROpenGLExtension(this));
  823. // register_extension_wrapper(graphics_extension);
  824. ERR_FAIL_V_MSG(false, "OpenXR: OpenGL is not supported at this time.");
  825. #else
  826. // shouldn't be possible...
  827. ERR_FAIL_V(false);
  828. #endif
  829. } else {
  830. ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device.");
  831. }
  832. // initialise
  833. if (!load_layer_properties()) {
  834. destroy_instance();
  835. return false;
  836. }
  837. if (!load_supported_extensions()) {
  838. destroy_instance();
  839. return false;
  840. }
  841. if (!create_instance()) {
  842. destroy_instance();
  843. return false;
  844. }
  845. if (!get_system_info()) {
  846. destroy_instance();
  847. return false;
  848. }
  849. if (!load_supported_view_configuration_types()) {
  850. destroy_instance();
  851. return false;
  852. }
  853. if (!load_supported_view_configuration_views(view_configuration)) {
  854. destroy_instance();
  855. return false;
  856. }
  857. return true;
  858. }
  859. bool OpenXRAPI::initialise_session() {
  860. if (!create_session()) {
  861. destroy_session();
  862. return false;
  863. }
  864. if (!load_supported_reference_spaces()) {
  865. destroy_session();
  866. return false;
  867. }
  868. if (!setup_spaces()) {
  869. destroy_session();
  870. return false;
  871. }
  872. if (!load_supported_swapchain_formats()) {
  873. destroy_session();
  874. return false;
  875. }
  876. return true;
  877. }
  878. void OpenXRAPI::finish() {
  879. destroy_session();
  880. destroy_instance();
  881. }
  882. void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) {
  883. xr_interface = p_xr_interface;
  884. }
  885. void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  886. registered_extension_wrappers.push_back(p_extension_wrapper);
  887. }
  888. Size2 OpenXRAPI::get_recommended_target_size() {
  889. ERR_FAIL_NULL_V(view_configuration_views, Size2());
  890. Size2 target_size;
  891. target_size.width = view_configuration_views[0].recommendedImageRectWidth;
  892. target_size.height = view_configuration_views[0].recommendedImageRectHeight;
  893. return target_size;
  894. }
  895. XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  896. XrResult result;
  897. ERR_FAIL_COND_V(!running, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  898. // xrWaitFrame not run yet
  899. if (frame_state.predictedDisplayTime == 0) {
  900. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  901. }
  902. // Get timing for the next frame, as that is the current frame we're processing
  903. XrTime display_time = get_next_frame_time();
  904. XrSpaceVelocity velocity = {
  905. XR_TYPE_SPACE_VELOCITY, // type
  906. nullptr, // next
  907. 0, // velocityFlags
  908. { 0.0, 0.0, 0.0 }, // linearVelocity
  909. { 0.0, 0.0, 0.0 } // angularVelocity
  910. };
  911. XrSpaceLocation location = {
  912. XR_TYPE_SPACE_LOCATION, // type
  913. &velocity, // next
  914. 0, // locationFlags
  915. {
  916. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  917. { 0.0, 0.0, 0.0 } // position
  918. } // pose
  919. };
  920. result = xrLocateSpace(view_space, play_space, display_time, &location);
  921. if (XR_FAILED(result)) {
  922. print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]");
  923. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  924. }
  925. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  926. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  927. if (head_pose_confidence != confidence) {
  928. // prevent error spam
  929. head_pose_confidence = confidence;
  930. if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  931. print_line("OpenXR head space location not valid (check tracking?)");
  932. #ifdef DEBUG
  933. } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
  934. print_line("OpenVR Head pose now tracking with low confidence");
  935. } else {
  936. print_line("OpenVR Head pose now tracking with high confidence");
  937. #endif
  938. }
  939. }
  940. return confidence;
  941. }
  942. bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) {
  943. ERR_FAIL_COND_V(!running, false);
  944. // xrWaitFrame not run yet
  945. if (frame_state.predictedDisplayTime == 0) {
  946. return false;
  947. }
  948. // we don't have valid view info
  949. if (views == NULL || !view_pose_valid) {
  950. return false;
  951. }
  952. // Note, the timing of this is set right before rendering, which is what we need here.
  953. r_transform = transform_from_pose(views[p_view].pose);
  954. return true;
  955. }
  956. bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, CameraMatrix &p_camera_matrix) {
  957. ERR_FAIL_COND_V(!running, false);
  958. ERR_FAIL_NULL_V(graphics_extension, false);
  959. // xrWaitFrame not run yet
  960. if (frame_state.predictedDisplayTime == 0) {
  961. return false;
  962. }
  963. // we don't have valid view info
  964. if (views == NULL || !view_pose_valid) {
  965. return false;
  966. }
  967. return graphics_extension->create_projection_fov(views[p_view].fov, p_z_near, p_z_far, p_camera_matrix);
  968. }
  969. bool OpenXRAPI::poll_events() {
  970. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  971. XrEventDataBuffer runtimeEvent;
  972. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  973. runtimeEvent.next = nullptr;
  974. // runtimeEvent.varying = ...
  975. XrResult pollResult = xrPollEvent(instance, &runtimeEvent);
  976. while (pollResult == XR_SUCCESS) {
  977. bool handled = false;
  978. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  979. handled |= wrapper->on_event_polled(runtimeEvent);
  980. }
  981. switch (runtimeEvent.type) {
  982. case XR_TYPE_EVENT_DATA_EVENTS_LOST: {
  983. XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent;
  984. // We probably didn't poll fast enough, just output warning
  985. WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!");
  986. } break;
  987. case XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR: {
  988. // XrEventDataVisibilityMaskChangedKHR *event = (XrEventDataVisibilityMaskChangedKHR *)&runtimeEvent;
  989. // TODO implement this in the future, we should call xrGetVisibilityMaskKHR to obtain a mask,
  990. // this will allow us to prevent rendering the part of our view which is never displayed giving us
  991. // a decent performance improvement.
  992. print_verbose("OpenXR EVENT: STUB: visibility mask changed");
  993. } break;
  994. case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
  995. XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent;
  996. // TODO We get this event if we're about to loose our OpenXR instance.
  997. // We should queue exiting Godot at this point.
  998. print_verbose("OpenXR EVENT: instance loss pending at " + itos(event->lossTime));
  999. return false;
  1000. } break;
  1001. case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
  1002. XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent;
  1003. session_state = event->state;
  1004. if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
  1005. print_verbose("OpenXR EVENT: session state changed to UNKNOWN - " + itos(session_state));
  1006. } else {
  1007. print_verbose("OpenXR EVENT: session state changed to " + OpenXRUtil::get_session_state_name(session_state));
  1008. switch (session_state) {
  1009. case XR_SESSION_STATE_IDLE:
  1010. on_state_idle();
  1011. break;
  1012. case XR_SESSION_STATE_READY:
  1013. on_state_ready();
  1014. break;
  1015. case XR_SESSION_STATE_SYNCHRONIZED:
  1016. on_state_synchronized();
  1017. break;
  1018. case XR_SESSION_STATE_VISIBLE:
  1019. on_state_visible();
  1020. break;
  1021. case XR_SESSION_STATE_FOCUSED:
  1022. on_state_focused();
  1023. break;
  1024. case XR_SESSION_STATE_STOPPING:
  1025. on_state_stopping();
  1026. break;
  1027. case XR_SESSION_STATE_LOSS_PENDING:
  1028. on_state_loss_pending();
  1029. break;
  1030. case XR_SESSION_STATE_EXITING:
  1031. on_state_exiting();
  1032. break;
  1033. default:
  1034. break;
  1035. }
  1036. }
  1037. } break;
  1038. case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
  1039. XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
  1040. print_verbose("OpenXR EVENT: reference space type " + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
  1041. if (event->poseValid && xr_interface) {
  1042. xr_interface->on_pose_recentered();
  1043. }
  1044. } break;
  1045. case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
  1046. print_verbose("OpenXR EVENT: interaction profile changed!");
  1047. XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
  1048. List<RID> trackers;
  1049. tracker_owner.get_owned_list(&trackers);
  1050. for (int i = 0; i < trackers.size(); i++) {
  1051. tracker_check_profile(trackers[i], event->session);
  1052. }
  1053. } break;
  1054. default:
  1055. if (!handled) {
  1056. print_verbose("OpenXR Unhandled event type " + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
  1057. }
  1058. break;
  1059. }
  1060. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1061. pollResult = xrPollEvent(instance, &runtimeEvent);
  1062. }
  1063. if (pollResult == XR_EVENT_UNAVAILABLE) {
  1064. // processed all events in the queue
  1065. return true;
  1066. } else {
  1067. ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!");
  1068. }
  1069. }
  1070. bool OpenXRAPI::process() {
  1071. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1072. if (!poll_events()) {
  1073. return false;
  1074. }
  1075. if (!running) {
  1076. return false;
  1077. }
  1078. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1079. wrapper->on_process();
  1080. }
  1081. return true;
  1082. }
  1083. bool OpenXRAPI::acquire_image(XrSwapchain p_swapchain, uint32_t &r_image_index) {
  1084. ERR_FAIL_COND_V(image_acquired, true); // this was not released when it should be, error out and re-use...
  1085. XrResult result;
  1086. XrSwapchainImageAcquireInfo swapchain_image_acquire_info = {
  1087. XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type
  1088. nullptr // next
  1089. };
  1090. result = xrAcquireSwapchainImage(p_swapchain, &swapchain_image_acquire_info, &r_image_index);
  1091. if (XR_FAILED(result)) {
  1092. print_line("OpenXR: failed to acquire swapchain image [", get_error_string(result), "]");
  1093. return false;
  1094. }
  1095. XrSwapchainImageWaitInfo swapchain_image_wait_info = {
  1096. XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type
  1097. nullptr, // next
  1098. 17000000 // timeout in nanoseconds
  1099. };
  1100. result = xrWaitSwapchainImage(p_swapchain, &swapchain_image_wait_info);
  1101. if (XR_FAILED(result)) {
  1102. print_line("OpenXR: failed to wait for swapchain image [", get_error_string(result), "]");
  1103. return false;
  1104. }
  1105. return true;
  1106. }
  1107. bool OpenXRAPI::release_image(XrSwapchain p_swapchain) {
  1108. XrSwapchainImageReleaseInfo swapchain_image_release_info = {
  1109. XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type
  1110. nullptr // next
  1111. };
  1112. XrResult result = xrReleaseSwapchainImage(swapchain, &swapchain_image_release_info);
  1113. if (XR_FAILED(result)) {
  1114. print_line("OpenXR: failed to release swapchain image! [", get_error_string(result), "]");
  1115. return false;
  1116. }
  1117. return true;
  1118. }
  1119. void OpenXRAPI::pre_render() {
  1120. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1121. if (!running) {
  1122. return;
  1123. }
  1124. // Waitframe does 2 important things in our process:
  1125. // 1) It provides us with predictive timing, telling us when OpenXR expects to display the frame we're about to commit
  1126. // 2) It will use the previous timing to pause our thread so that rendering starts as close to displaying as possible
  1127. // This must thus be called as close to when we start rendering as possible
  1128. XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr };
  1129. XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state);
  1130. if (XR_FAILED(result)) {
  1131. print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]");
  1132. // reset just in case
  1133. frame_state.predictedDisplayTime = 0;
  1134. frame_state.predictedDisplayPeriod = 0;
  1135. frame_state.shouldRender = false;
  1136. return;
  1137. }
  1138. if (frame_state.predictedDisplayPeriod > 500000000) {
  1139. // display period more then 0.5 seconds? must be wrong data
  1140. print_verbose("OpenXR resetting invalid display period " + rtos(frame_state.predictedDisplayPeriod));
  1141. frame_state.predictedDisplayPeriod = 0;
  1142. }
  1143. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1144. wrapper->on_pre_render();
  1145. }
  1146. // Get our view info for the frame we're about to render, note from the OpenXR manual:
  1147. // "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"
  1148. // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling,
  1149. // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire
  1150. // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and
  1151. // update the view and projection matrix once more with a slightly more accurate predication and then submit the
  1152. // command queues.
  1153. // That is not possible yet but worth investigating in the future.
  1154. XrViewLocateInfo view_locate_info = {
  1155. XR_TYPE_VIEW_LOCATE_INFO, // type
  1156. nullptr, // next
  1157. view_configuration, // viewConfigurationType
  1158. frame_state.predictedDisplayTime, // displayTime
  1159. play_space // space
  1160. };
  1161. XrViewState view_state = {
  1162. XR_TYPE_VIEW_STATE, // type
  1163. nullptr, // next
  1164. 0 // viewStateFlags
  1165. };
  1166. uint32_t view_count_output;
  1167. result = xrLocateViews(session, &view_locate_info, &view_state, view_count, &view_count_output, views);
  1168. if (XR_FAILED(result)) {
  1169. print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");
  1170. return;
  1171. }
  1172. bool pose_valid = true;
  1173. for (uint64_t i = 0; i < view_count_output; i++) {
  1174. if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||
  1175. (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {
  1176. pose_valid = false;
  1177. }
  1178. }
  1179. if (view_pose_valid != pose_valid) {
  1180. view_pose_valid = pose_valid;
  1181. #ifdef DEBUG
  1182. if (!view_pose_valid) {
  1183. print_line("OpenXR View pose became invalid");
  1184. } else {
  1185. print_line("OpenXR View pose became valid");
  1186. }
  1187. #endif
  1188. }
  1189. // let's start our frame..
  1190. XrFrameBeginInfo frame_begin_info = {
  1191. XR_TYPE_FRAME_BEGIN_INFO, // type
  1192. nullptr // next
  1193. };
  1194. result = xrBeginFrame(session, &frame_begin_info);
  1195. if (XR_FAILED(result)) {
  1196. print_line("OpenXR: failed to being frame [", get_error_string(result), "]");
  1197. return;
  1198. }
  1199. }
  1200. bool OpenXRAPI::pre_draw_viewport(RID p_render_target) {
  1201. if (!can_render()) {
  1202. return false;
  1203. }
  1204. // TODO: at some point in time we may support multiple viewports in which case we need to handle that...
  1205. return true;
  1206. }
  1207. void OpenXRAPI::post_draw_viewport(RID p_render_target) {
  1208. if (!can_render()) {
  1209. return;
  1210. }
  1211. // TODO: at some point in time we may support multiple viewports in which case we need to handle that...
  1212. // 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
  1213. if (!image_acquired) {
  1214. if (!acquire_image(swapchain, image_index)) {
  1215. return;
  1216. }
  1217. image_acquired = true;
  1218. // print_line("OpenXR: acquired image " + itos(image_index) + ", copying...");
  1219. // Copy our buffer into our swap chain (remove once PR 51179 is done)
  1220. graphics_extension->copy_render_target_to_image(p_render_target, swapchain_graphics_data, image_index);
  1221. }
  1222. };
  1223. void OpenXRAPI::end_frame() {
  1224. XrResult result;
  1225. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1226. if (!running) {
  1227. return;
  1228. }
  1229. if (frame_state.shouldRender && view_pose_valid && !image_acquired) {
  1230. print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!");
  1231. }
  1232. // must have:
  1233. // - shouldRender set to true
  1234. // - a valid view pose for projection_views[eye].pose to submit layer
  1235. // - an image to render
  1236. if (!frame_state.shouldRender || !view_pose_valid || !image_acquired) {
  1237. // submit 0 layers when we shouldn't render
  1238. XrFrameEndInfo frame_end_info = {
  1239. XR_TYPE_FRAME_END_INFO, // type
  1240. nullptr, // next
  1241. frame_state.predictedDisplayTime, // displayTime
  1242. XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode
  1243. 0, // layerCount
  1244. nullptr // layers
  1245. };
  1246. result = xrEndFrame(session, &frame_end_info);
  1247. if (XR_FAILED(result)) {
  1248. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1249. return;
  1250. }
  1251. // neither eye is rendered
  1252. return;
  1253. }
  1254. // release our swapchain image if we acquired it
  1255. if (image_acquired) {
  1256. image_acquired = false; // whether we succeed or not, consider this released.
  1257. release_image(swapchain);
  1258. }
  1259. for (uint32_t eye = 0; eye < view_count; eye++) {
  1260. projection_views[eye].fov = views[eye].fov;
  1261. projection_views[eye].pose = views[eye].pose;
  1262. }
  1263. Vector<const XrCompositionLayerBaseHeader *> layers_list;
  1264. // Add composition layers from providers
  1265. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1266. XrCompositionLayerBaseHeader *layer = provider->get_composition_layer();
  1267. if (layer) {
  1268. layers_list.push_back(layer);
  1269. }
  1270. }
  1271. XrCompositionLayerProjection projection_layer = {
  1272. XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type
  1273. nullptr, // next
  1274. layers_list.size() > 1 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags
  1275. play_space, // space
  1276. view_count, // viewCount
  1277. projection_views, // views
  1278. };
  1279. layers_list.push_back((const XrCompositionLayerBaseHeader *)&projection_layer);
  1280. XrFrameEndInfo frame_end_info = {
  1281. XR_TYPE_FRAME_END_INFO, // type
  1282. nullptr, // next
  1283. frame_state.predictedDisplayTime, // displayTime
  1284. XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode
  1285. static_cast<uint32_t>(layers_list.size()), // layerCount
  1286. layers_list.ptr() // layers
  1287. };
  1288. result = xrEndFrame(session, &frame_end_info);
  1289. if (XR_FAILED(result)) {
  1290. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1291. return;
  1292. }
  1293. }
  1294. OpenXRAPI::OpenXRAPI() {
  1295. // OpenXRAPI is only constructed if OpenXR is enabled.
  1296. // It will be constructed when the rendering device first accesses OpenXR (be it the Vulkan or OpenGL rendering system)
  1297. if (Engine::get_singleton()->is_editor_hint()) {
  1298. // Enabled OpenXR in the editor? Adjust our settings for the editor
  1299. } else {
  1300. // Load settings from project settings
  1301. int ff = GLOBAL_GET("xr/openxr/form_factor");
  1302. switch (ff) {
  1303. case 0: {
  1304. form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
  1305. } break;
  1306. case 1: {
  1307. form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY;
  1308. } break;
  1309. default:
  1310. break;
  1311. }
  1312. int vc = GLOBAL_GET("xr/openxr/view_configuration");
  1313. switch (vc) {
  1314. case 0: {
  1315. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
  1316. } break;
  1317. case 1: {
  1318. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
  1319. } break;
  1320. /* we don't support quad and observer configurations (yet)
  1321. case 2: {
  1322. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
  1323. } break;
  1324. case 3: {
  1325. view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
  1326. } break;
  1327. */
  1328. default:
  1329. break;
  1330. }
  1331. int rs = GLOBAL_GET("xr/openxr/reference_space");
  1332. switch (rs) {
  1333. case 0: {
  1334. reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  1335. } break;
  1336. case 1: {
  1337. reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
  1338. } break;
  1339. default:
  1340. break;
  1341. }
  1342. }
  1343. // reset a few things that can't be done in our class definition
  1344. frame_state.predictedDisplayTime = 0;
  1345. frame_state.predictedDisplayPeriod = 0;
  1346. #ifdef ANDROID_ENABLED
  1347. // our android wrapper will initialise our android loader at this point
  1348. register_extension_wrapper(memnew(OpenXRAndroidExtension(this)));
  1349. #endif
  1350. }
  1351. OpenXRAPI::~OpenXRAPI() {
  1352. // cleanup our composition layer providers
  1353. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1354. memdelete(provider);
  1355. }
  1356. composition_layer_providers.clear();
  1357. // cleanup our extension wrappers
  1358. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1359. memdelete(extension_wrapper);
  1360. }
  1361. registered_extension_wrappers.clear();
  1362. if (supported_extensions != nullptr) {
  1363. memfree(supported_extensions);
  1364. supported_extensions = nullptr;
  1365. }
  1366. if (layer_properties != nullptr) {
  1367. memfree(layer_properties);
  1368. layer_properties = nullptr;
  1369. }
  1370. }
  1371. Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) {
  1372. Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w);
  1373. Basis basis(q);
  1374. Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z);
  1375. return Transform3D(basis, origin);
  1376. }
  1377. template <typename T>
  1378. XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) {
  1379. Basis basis;
  1380. Vector3 origin;
  1381. XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1382. const auto &pose = p_location.pose;
  1383. // Check orientation
  1384. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) {
  1385. Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
  1386. r_transform.basis = Basis(q);
  1387. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) {
  1388. // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING
  1389. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1390. } else {
  1391. // Orientation is being tracked but we're using old/predicted data, so low tracking confidence
  1392. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1393. }
  1394. } else {
  1395. r_transform.basis = Basis();
  1396. }
  1397. // Check location
  1398. if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) {
  1399. r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z);
  1400. if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) {
  1401. // Location is being tracked but we're using old/predicted data, so low tracking confidence
  1402. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1403. } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1404. // Position tracking without orientation tracking?
  1405. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1406. }
  1407. } else {
  1408. // No tracking or 3DOF I guess..
  1409. r_transform.origin = Vector3();
  1410. }
  1411. return confidence;
  1412. }
  1413. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) {
  1414. return _transform_from_location(p_location, r_transform);
  1415. }
  1416. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) {
  1417. return _transform_from_location(p_location, r_transform);
  1418. }
  1419. void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 r_angular_velocity) {
  1420. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) {
  1421. XrVector3f linear_velocity = p_velocity.linearVelocity;
  1422. r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z);
  1423. } else {
  1424. r_linear_velocity = Vector3();
  1425. }
  1426. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) {
  1427. XrVector3f angular_velocity = p_velocity.angularVelocity;
  1428. r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z);
  1429. } else {
  1430. r_angular_velocity = Vector3();
  1431. }
  1432. }
  1433. RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
  1434. List<RID> current;
  1435. tracker_owner.get_owned_list(&current);
  1436. for (int i = 0; i < current.size(); i++) {
  1437. Tracker *tracker = tracker_owner.get_or_null(current[i]);
  1438. if (tracker && tracker->toplevel_path == p_path) {
  1439. return current[i];
  1440. }
  1441. }
  1442. return RID();
  1443. }
  1444. RID OpenXRAPI::tracker_create(const String p_name) {
  1445. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1446. Tracker new_tracker;
  1447. new_tracker.name = p_name;
  1448. new_tracker.toplevel_path = XR_NULL_PATH;
  1449. new_tracker.active_profile_rid = RID();
  1450. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_tracker.toplevel_path);
  1451. if (XR_FAILED(result)) {
  1452. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1453. return RID();
  1454. }
  1455. return tracker_owner.make_rid(new_tracker);
  1456. }
  1457. String OpenXRAPI::tracker_get_name(RID p_tracker) {
  1458. if (p_tracker.is_null()) {
  1459. return String("None");
  1460. }
  1461. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1462. ERR_FAIL_NULL_V(tracker, String());
  1463. return tracker->name;
  1464. }
  1465. void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) {
  1466. if (p_session == XR_NULL_HANDLE) {
  1467. p_session = session;
  1468. }
  1469. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1470. ERR_FAIL_NULL(tracker);
  1471. if (tracker->toplevel_path == XR_NULL_PATH) {
  1472. // no path, how was this even created?
  1473. return;
  1474. }
  1475. XrInteractionProfileState profile_state = {
  1476. XR_TYPE_INTERACTION_PROFILE_STATE, // type
  1477. nullptr, // next
  1478. XR_NULL_PATH // interactionProfile
  1479. };
  1480. XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state);
  1481. if (XR_FAILED(result)) {
  1482. print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]");
  1483. return;
  1484. }
  1485. XrPath new_profile = profile_state.interactionProfile;
  1486. XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid);
  1487. if (was_profile != new_profile) {
  1488. tracker->active_profile_rid = get_interaction_profile_rid(new_profile);
  1489. if (xr_interface) {
  1490. xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid);
  1491. }
  1492. }
  1493. }
  1494. void OpenXRAPI::tracker_free(RID p_tracker) {
  1495. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1496. ERR_FAIL_NULL(tracker);
  1497. // there is nothing to free here
  1498. tracker_owner.free(p_tracker);
  1499. }
  1500. RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_name, const int p_priority) {
  1501. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1502. ActionSet action_set;
  1503. action_set.name = p_name;
  1504. action_set.is_attached = false;
  1505. // create our action set...
  1506. XrActionSetCreateInfo action_set_info = {
  1507. XR_TYPE_ACTION_SET_CREATE_INFO, // type
  1508. nullptr, // next
  1509. "", // actionSetName
  1510. "", // localizedActionSetName
  1511. uint32_t(p_priority) // priority
  1512. };
  1513. copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
  1514. copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
  1515. // print_line("Creating action set ", action_set_info.actionSetName, " - ", action_set_info.localizedActionSetName, " (", itos(action_set_info.priority), ")");
  1516. XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
  1517. if (XR_FAILED(result)) {
  1518. print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
  1519. return RID();
  1520. }
  1521. return action_set_owner.make_rid(action_set);
  1522. }
  1523. String OpenXRAPI::action_set_get_name(RID p_action_set) {
  1524. if (p_action_set.is_null()) {
  1525. return String("None");
  1526. }
  1527. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1528. ERR_FAIL_NULL_V(action_set, String());
  1529. return action_set->name;
  1530. }
  1531. bool OpenXRAPI::action_set_attach(RID p_action_set) {
  1532. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1533. ERR_FAIL_NULL_V(action_set, false);
  1534. if (action_set->is_attached) {
  1535. // already attached
  1536. return true;
  1537. }
  1538. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1539. // So according to the docs, once we attach our action set to our session it becomes read only..
  1540. // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html
  1541. XrSessionActionSetsAttachInfo attach_info = {
  1542. XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type
  1543. nullptr, // next
  1544. 1, // countActionSets,
  1545. &action_set->handle // actionSets
  1546. };
  1547. XrResult result = xrAttachSessionActionSets(session, &attach_info);
  1548. if (XR_FAILED(result)) {
  1549. print_line("OpenXR: failed to attach action set! [", get_error_string(result), "]");
  1550. return false;
  1551. }
  1552. action_set->is_attached = true;
  1553. /* For debugging:
  1554. print_verbose("Attached set " + action_set->name);
  1555. List<RID> action_rids;
  1556. action_owner.get_owned_list(&action_rids);
  1557. for (int i = 0; i < action_rids.size(); i++) {
  1558. Action * action = action_owner.get_or_null(action_rids[i]);
  1559. if (action && action->action_set_rid == p_action_set) {
  1560. print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type));
  1561. for (int j = 0; j < action->trackers.size(); j++) {
  1562. Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid);
  1563. if (tracker) {
  1564. print_verbose(" - " + tracker->name);
  1565. }
  1566. }
  1567. }
  1568. }
  1569. */
  1570. return true;
  1571. }
  1572. void OpenXRAPI::action_set_free(RID p_action_set) {
  1573. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1574. ERR_FAIL_NULL(action_set);
  1575. if (action_set->handle != XR_NULL_HANDLE) {
  1576. xrDestroyActionSet(action_set->handle);
  1577. }
  1578. action_set_owner.free(p_action_set);
  1579. }
  1580. RID OpenXRAPI::get_action_rid(XrAction p_action) {
  1581. List<RID> current;
  1582. action_owner.get_owned_list(&current);
  1583. for (int i = 0; i < current.size(); i++) {
  1584. Action *action = action_owner.get_or_null(current[i]);
  1585. if (action && action->handle == p_action) {
  1586. return current[i];
  1587. }
  1588. }
  1589. return RID();
  1590. }
  1591. 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) {
  1592. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1593. Action action;
  1594. action.name = p_name;
  1595. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1596. ERR_FAIL_NULL_V(action_set, RID());
  1597. ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID());
  1598. action.action_set_rid = p_action_set;
  1599. switch (p_action_type) {
  1600. case OpenXRAction::OPENXR_ACTION_BOOL:
  1601. action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT;
  1602. break;
  1603. case OpenXRAction::OPENXR_ACTION_FLOAT:
  1604. action.action_type = XR_ACTION_TYPE_FLOAT_INPUT;
  1605. break;
  1606. case OpenXRAction::OPENXR_ACTION_VECTOR2:
  1607. action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT;
  1608. break;
  1609. case OpenXRAction::OPENXR_ACTION_POSE:
  1610. action.action_type = XR_ACTION_TYPE_POSE_INPUT;
  1611. break;
  1612. case OpenXRAction::OPENXR_ACTION_HAPTIC:
  1613. action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT;
  1614. break;
  1615. default:
  1616. ERR_FAIL_V(RID());
  1617. break;
  1618. }
  1619. Vector<XrPath> toplevel_paths;
  1620. for (int i = 0; i < p_trackers.size(); i++) {
  1621. Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]);
  1622. if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) {
  1623. ActionTracker action_tracker = {
  1624. p_trackers[i], // tracker
  1625. XR_NULL_HANDLE, // space
  1626. false // was_location_valid
  1627. };
  1628. action.trackers.push_back(action_tracker);
  1629. toplevel_paths.push_back(tracker->toplevel_path);
  1630. }
  1631. }
  1632. XrActionCreateInfo action_info = {
  1633. XR_TYPE_ACTION_CREATE_INFO, // type
  1634. nullptr, // next
  1635. "", // actionName
  1636. action.action_type, // actionType
  1637. uint32_t(toplevel_paths.size()), // countSubactionPaths
  1638. toplevel_paths.ptr(), // subactionPaths
  1639. "" // localizedActionName
  1640. };
  1641. copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
  1642. copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
  1643. // print_line("Creating action ", action_info.actionName, action_info.localizedActionName, action_info.countSubactionPaths);
  1644. XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
  1645. if (XR_FAILED(result)) {
  1646. print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
  1647. return RID();
  1648. }
  1649. return action_owner.make_rid(action);
  1650. }
  1651. String OpenXRAPI::action_get_name(RID p_action) {
  1652. if (p_action.is_null()) {
  1653. return String("None");
  1654. }
  1655. Action *action = action_owner.get_or_null(p_action);
  1656. ERR_FAIL_NULL_V(action, String());
  1657. return action->name;
  1658. }
  1659. void OpenXRAPI::action_free(RID p_action) {
  1660. Action *action = action_owner.get_or_null(p_action);
  1661. ERR_FAIL_NULL(action);
  1662. if (action->handle != XR_NULL_HANDLE) {
  1663. xrDestroyAction(action->handle);
  1664. }
  1665. action_owner.free(p_action);
  1666. }
  1667. RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
  1668. List<RID> current;
  1669. interaction_profile_owner.get_owned_list(&current);
  1670. for (int i = 0; i < current.size(); i++) {
  1671. InteractionProfile *ip = interaction_profile_owner.get_or_null(current[i]);
  1672. if (ip && ip->path == p_path) {
  1673. return current[i];
  1674. }
  1675. }
  1676. return RID();
  1677. }
  1678. XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) {
  1679. if (p_interaction_profile.is_null()) {
  1680. return XR_NULL_PATH;
  1681. }
  1682. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1683. ERR_FAIL_NULL_V(ip, XR_NULL_PATH);
  1684. return ip->path;
  1685. }
  1686. RID OpenXRAPI::interaction_profile_create(const String p_name) {
  1687. InteractionProfile new_interaction_profile;
  1688. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path);
  1689. if (XR_FAILED(result)) {
  1690. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1691. return RID();
  1692. }
  1693. RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path);
  1694. if (existing_ip.is_valid()) {
  1695. return existing_ip;
  1696. }
  1697. new_interaction_profile.name = p_name;
  1698. return interaction_profile_owner.make_rid(new_interaction_profile);
  1699. }
  1700. String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) {
  1701. if (p_interaction_profile.is_null()) {
  1702. return String("None");
  1703. }
  1704. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1705. ERR_FAIL_NULL_V(ip, String());
  1706. return ip->name;
  1707. }
  1708. void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) {
  1709. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1710. ERR_FAIL_NULL(ip);
  1711. ip->bindings.clear();
  1712. }
  1713. bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) {
  1714. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1715. ERR_FAIL_NULL_V(ip, false);
  1716. XrActionSuggestedBinding binding;
  1717. Action *action = action_owner.get_or_null(p_action);
  1718. ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, false);
  1719. binding.action = action->handle;
  1720. XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &binding.binding);
  1721. if (XR_FAILED(result)) {
  1722. print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
  1723. return false;
  1724. }
  1725. ip->bindings.push_back(binding);
  1726. return true;
  1727. }
  1728. bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) {
  1729. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1730. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1731. ERR_FAIL_NULL_V(ip, false);
  1732. const XrInteractionProfileSuggestedBinding suggested_bindings = {
  1733. XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type
  1734. nullptr, // next
  1735. ip->path, // interactionProfile
  1736. uint32_t(ip->bindings.size()), // countSuggestedBindings
  1737. ip->bindings.ptr() // suggestedBindings
  1738. };
  1739. XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings);
  1740. if (result == XR_ERROR_PATH_UNSUPPORTED) {
  1741. // this is fine, not all runtimes support all devices.
  1742. print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime");
  1743. } else if (XR_FAILED(result)) {
  1744. print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]");
  1745. // reporting is enough...
  1746. }
  1747. /* For debugging:
  1748. print_verbose("Suggested bindings for " + ip->name);
  1749. for (int i = 0; i < ip->bindings.size(); i++) {
  1750. uint32_t strlen;
  1751. char path[XR_MAX_PATH_LENGTH];
  1752. String action_name = action_get_name(get_action_rid(ip->bindings[i].action));
  1753. XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path);
  1754. if (XR_FAILED(result)) {
  1755. print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]");
  1756. }
  1757. print_verbose(" - " + action_name + " => " + String(path));
  1758. }
  1759. */
  1760. return true;
  1761. }
  1762. void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) {
  1763. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1764. ERR_FAIL_NULL(ip);
  1765. ip->bindings.clear();
  1766. interaction_profile_owner.free(p_interaction_profile);
  1767. }
  1768. bool OpenXRAPI::sync_action_sets(const Vector<RID> p_active_sets) {
  1769. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1770. if (!running) {
  1771. return false;
  1772. }
  1773. Vector<XrActiveActionSet> active_sets;
  1774. for (int i = 0; i < p_active_sets.size(); i++) {
  1775. ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]);
  1776. if (action_set && action_set->handle != XR_NULL_HANDLE) {
  1777. XrActiveActionSet aset;
  1778. aset.actionSet = action_set->handle;
  1779. aset.subactionPath = XR_NULL_PATH;
  1780. active_sets.push_back(aset);
  1781. }
  1782. }
  1783. ERR_FAIL_COND_V(active_sets.size() == 0, false);
  1784. XrActionsSyncInfo sync_info = {
  1785. XR_TYPE_ACTIONS_SYNC_INFO, // type
  1786. nullptr, // next
  1787. uint32_t(active_sets.size()), // countActiveActionSets
  1788. active_sets.ptr() // activeActionSets
  1789. };
  1790. XrResult result = xrSyncActions(session, &sync_info);
  1791. if (XR_FAILED(result)) {
  1792. print_line("OpenXR: failed to sync active action sets! [", get_error_string(result), "]");
  1793. return false;
  1794. }
  1795. return true;
  1796. }
  1797. bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) {
  1798. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1799. Action *action = action_owner.get_or_null(p_action);
  1800. ERR_FAIL_NULL_V(action, false);
  1801. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1802. ERR_FAIL_NULL_V(tracker, false);
  1803. if (!running) {
  1804. return false;
  1805. }
  1806. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false);
  1807. XrActionStateGetInfo get_info = {
  1808. XR_TYPE_ACTION_STATE_GET_INFO, // type
  1809. nullptr, // next
  1810. action->handle, // action
  1811. tracker->toplevel_path // subactionPath
  1812. };
  1813. XrActionStateBoolean result_state;
  1814. result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN,
  1815. result_state.next = nullptr;
  1816. XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state);
  1817. if (XR_FAILED(result)) {
  1818. print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]");
  1819. return false;
  1820. }
  1821. return result_state.isActive && result_state.currentState;
  1822. }
  1823. float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) {
  1824. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0);
  1825. Action *action = action_owner.get_or_null(p_action);
  1826. ERR_FAIL_NULL_V(action, 0.0);
  1827. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1828. ERR_FAIL_NULL_V(tracker, 0.0);
  1829. if (!running) {
  1830. return 0.0;
  1831. }
  1832. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0);
  1833. XrActionStateGetInfo get_info = {
  1834. XR_TYPE_ACTION_STATE_GET_INFO, // type
  1835. nullptr, // next
  1836. action->handle, // action
  1837. tracker->toplevel_path // subactionPath
  1838. };
  1839. XrActionStateFloat result_state;
  1840. result_state.type = XR_TYPE_ACTION_STATE_FLOAT,
  1841. result_state.next = nullptr;
  1842. XrResult result = xrGetActionStateFloat(session, &get_info, &result_state);
  1843. if (XR_FAILED(result)) {
  1844. print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]");
  1845. return 0.0;
  1846. }
  1847. return result_state.isActive ? result_state.currentState : 0.0;
  1848. }
  1849. Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
  1850. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2());
  1851. Action *action = action_owner.get_or_null(p_action);
  1852. ERR_FAIL_NULL_V(action, Vector2());
  1853. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1854. ERR_FAIL_NULL_V(tracker, Vector2());
  1855. if (!running) {
  1856. return Vector2();
  1857. }
  1858. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2());
  1859. XrActionStateGetInfo get_info = {
  1860. XR_TYPE_ACTION_STATE_GET_INFO, // type
  1861. nullptr, // next
  1862. action->handle, // action
  1863. tracker->toplevel_path // subactionPath
  1864. };
  1865. XrActionStateVector2f result_state;
  1866. result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F,
  1867. result_state.next = nullptr;
  1868. XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state);
  1869. if (XR_FAILED(result)) {
  1870. print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]");
  1871. return Vector2();
  1872. }
  1873. return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
  1874. }
  1875. XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1876. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1877. Action *action = action_owner.get_or_null(p_action);
  1878. ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1879. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1880. ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1881. if (!running) {
  1882. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1883. }
  1884. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1885. // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")");
  1886. uint64_t index = 0xFFFFFFFF;
  1887. uint64_t size = uint64_t(action->trackers.size());
  1888. for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) {
  1889. if (action->trackers[i].tracker_rid == p_tracker) {
  1890. index = i;
  1891. }
  1892. }
  1893. if (index == 0xFFFFFFFF) {
  1894. // couldn't find it?
  1895. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1896. }
  1897. XrTime display_time = get_next_frame_time();
  1898. if (display_time == 0) {
  1899. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1900. }
  1901. if (action->trackers[index].space == XR_NULL_HANDLE) {
  1902. // if this is a pose we need to define spaces
  1903. XrActionSpaceCreateInfo action_space_info = {
  1904. XR_TYPE_ACTION_SPACE_CREATE_INFO, // type
  1905. nullptr, // next
  1906. action->handle, // action
  1907. tracker->toplevel_path, // subactionPath
  1908. {
  1909. { 0.0, 0.0, 0.0, 1.0 }, // orientation
  1910. { 0.0, 0.0, 0.0 } // position
  1911. } // poseInActionSpace
  1912. };
  1913. XrSpace space;
  1914. XrResult result = xrCreateActionSpace(session, &action_space_info, &space);
  1915. if (XR_FAILED(result)) {
  1916. print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]");
  1917. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1918. }
  1919. action->trackers.ptrw()[index].space = space;
  1920. }
  1921. XrSpaceVelocity velocity = {
  1922. XR_TYPE_SPACE_VELOCITY, // type
  1923. nullptr, // next
  1924. 0, // velocityFlags
  1925. { 0.0, 0.0, 0.0 }, // linearVelocity
  1926. { 0.0, 0.0, 0.0 } // angularVelocity
  1927. };
  1928. XrSpaceLocation location = {
  1929. XR_TYPE_SPACE_LOCATION, // type
  1930. &velocity, // next
  1931. 0, // locationFlags
  1932. {
  1933. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  1934. { 0.0, 0.0, 0.0 } // position
  1935. } // pose
  1936. };
  1937. XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location);
  1938. if (XR_FAILED(result)) {
  1939. print_line("OpenXR: failed to locate space! [", get_error_string(result), "]");
  1940. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1941. }
  1942. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  1943. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  1944. return confidence;
  1945. }
  1946. bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) {
  1947. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1948. Action *action = action_owner.get_or_null(p_action);
  1949. ERR_FAIL_NULL_V(action, false);
  1950. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1951. ERR_FAIL_NULL_V(tracker, false);
  1952. if (!running) {
  1953. return false;
  1954. }
  1955. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false);
  1956. XrHapticActionInfo action_info = {
  1957. XR_TYPE_HAPTIC_ACTION_INFO, // type
  1958. nullptr, // next
  1959. action->handle, // action
  1960. tracker->toplevel_path // subactionPath
  1961. };
  1962. XrHapticVibration vibration = {
  1963. XR_TYPE_HAPTIC_VIBRATION, // type
  1964. nullptr, // next
  1965. p_duration_ns, // duration
  1966. p_frequency, // frequency
  1967. p_amplitude, // amplitude
  1968. };
  1969. XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration);
  1970. if (XR_FAILED(result)) {
  1971. print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]");
  1972. return false;
  1973. }
  1974. return true;
  1975. }