openxr_api.cpp 117 KB

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