openxr_api.cpp 123 KB

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