openxr_api.cpp 114 KB

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