openxr_api.cpp 120 KB

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