openxr_api.cpp 117 KB

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