openxr_spatial_plane_tracking.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. /**************************************************************************/
  2. /* openxr_spatial_plane_tracking.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_spatial_plane_tracking.h"
  31. #include "../../openxr_api.h"
  32. #include "core/config/project_settings.h"
  33. #include "scene/resources/3d/box_shape_3d.h"
  34. #include "scene/resources/3d/concave_polygon_shape_3d.h"
  35. #include "scene/resources/3d/primitive_meshes.h"
  36. #include "servers/xr_server.h"
  37. ////////////////////////////////////////////////////////////////////////////
  38. // OpenXRSpatialCapabilityConfigurationPlaneTracking
  39. void OpenXRSpatialCapabilityConfigurationPlaneTracking::_bind_methods() {
  40. ClassDB::bind_method(D_METHOD("supports_mesh_2d"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_mesh_2d);
  41. ClassDB::bind_method(D_METHOD("supports_polygons"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_polygons);
  42. ClassDB::bind_method(D_METHOD("supports_labels"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_labels);
  43. ClassDB::bind_method(D_METHOD("get_enabled_components"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::_get_enabled_components);
  44. }
  45. bool OpenXRSpatialCapabilityConfigurationPlaneTracking::has_valid_configuration() const {
  46. OpenXRSpatialPlaneTrackingCapability *capability = OpenXRSpatialPlaneTrackingCapability::get_singleton();
  47. ERR_FAIL_NULL_V(capability, false);
  48. return capability->is_supported();
  49. }
  50. XrSpatialCapabilityConfigurationBaseHeaderEXT *OpenXRSpatialCapabilityConfigurationPlaneTracking::get_configuration() {
  51. OpenXRSpatialPlaneTrackingCapability *capability = OpenXRSpatialPlaneTrackingCapability::get_singleton();
  52. ERR_FAIL_NULL_V(capability, nullptr);
  53. if (capability->is_supported()) {
  54. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  55. ERR_FAIL_NULL_V(se_extension, nullptr);
  56. // Guaranteed components:
  57. plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_BOUNDED_2D_EXT);
  58. plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_PLANE_ALIGNMENT_EXT);
  59. // Optional components:
  60. if (get_supports_mesh_2d()) {
  61. plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_MESH_2D_EXT);
  62. } else if (get_supports_polygons()) {
  63. plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_POLYGON_2D_EXT);
  64. }
  65. if (get_supports_labels()) {
  66. plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_PLANE_SEMANTIC_LABEL_EXT);
  67. }
  68. // Set up our enabled components.
  69. plane_config.enabledComponentCount = plane_enabled_components.size();
  70. plane_config.enabledComponents = plane_enabled_components.ptr();
  71. // and return this.
  72. return (XrSpatialCapabilityConfigurationBaseHeaderEXT *)&plane_config;
  73. }
  74. return nullptr;
  75. }
  76. bool OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_mesh_2d() {
  77. if (supports_mesh_2d == -1) {
  78. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  79. ERR_FAIL_NULL_V(se_extension, false);
  80. supports_mesh_2d = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT, XR_SPATIAL_COMPONENT_TYPE_MESH_2D_EXT) ? 1 : 0;
  81. }
  82. return supports_mesh_2d == 1;
  83. }
  84. bool OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_polygons() {
  85. if (supports_polygons == -1) {
  86. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  87. ERR_FAIL_NULL_V(se_extension, false);
  88. supports_polygons = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT, XR_SPATIAL_COMPONENT_TYPE_POLYGON_2D_EXT) ? 1 : 0;
  89. }
  90. return supports_polygons == 1;
  91. }
  92. bool OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_labels() {
  93. if (supports_labels == -1) {
  94. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  95. ERR_FAIL_NULL_V(se_extension, false);
  96. supports_labels = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT, XR_SPATIAL_COMPONENT_TYPE_PLANE_SEMANTIC_LABEL_EXT) ? 1 : 0;
  97. }
  98. return supports_labels == 1;
  99. }
  100. PackedInt64Array OpenXRSpatialCapabilityConfigurationPlaneTracking::_get_enabled_components() const {
  101. PackedInt64Array components;
  102. for (const XrSpatialComponentTypeEXT &component_type : plane_enabled_components) {
  103. components.push_back((int64_t)component_type);
  104. }
  105. return components;
  106. }
  107. ////////////////////////////////////////////////////////////////////////////
  108. // OpenXRSpatialComponentPlaneAlignmentList
  109. void OpenXRSpatialComponentPlaneAlignmentList::_bind_methods() {
  110. ClassDB::bind_method(D_METHOD("get_plane_alignment", "index"), &OpenXRSpatialComponentPlaneAlignmentList::_get_plane_alignment);
  111. BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_HORIZONTAL_UPWARD);
  112. BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_HORIZONTAL_DOWNWARD);
  113. BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_VERTICAL);
  114. BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_ARBITRARY);
  115. }
  116. void OpenXRSpatialComponentPlaneAlignmentList::set_capacity(uint32_t p_capacity) {
  117. plane_alignment_data.resize(p_capacity);
  118. plane_alignment_list.planeAlignmentCount = uint32_t(plane_alignment_data.size());
  119. plane_alignment_list.planeAlignments = plane_alignment_data.ptrw();
  120. }
  121. XrSpatialComponentTypeEXT OpenXRSpatialComponentPlaneAlignmentList::get_component_type() const {
  122. return XR_SPATIAL_COMPONENT_TYPE_PLANE_ALIGNMENT_EXT;
  123. }
  124. void *OpenXRSpatialComponentPlaneAlignmentList::get_structure_data(void *p_next) {
  125. plane_alignment_list.next = p_next;
  126. return &plane_alignment_list;
  127. }
  128. XrSpatialPlaneAlignmentEXT OpenXRSpatialComponentPlaneAlignmentList::get_plane_alignment(int64_t p_index) const {
  129. ERR_FAIL_INDEX_V(p_index, plane_alignment_data.size(), XR_SPATIAL_PLANE_ALIGNMENT_MAX_ENUM_EXT);
  130. return plane_alignment_data[p_index];
  131. }
  132. OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment OpenXRSpatialComponentPlaneAlignmentList::_get_plane_alignment(int64_t p_index) const {
  133. return (PlaneAlignment)get_plane_alignment(p_index);
  134. }
  135. ////////////////////////////////////////////////////////////////////////////
  136. // Spatial component polygon2d list
  137. void OpenXRSpatialComponentPolygon2DList::_bind_methods() {
  138. ClassDB::bind_method(D_METHOD("get_transform", "index"), &OpenXRSpatialComponentPolygon2DList::get_transform);
  139. ClassDB::bind_method(D_METHOD("get_vertices", "snapshot", "index"), &OpenXRSpatialComponentPolygon2DList::get_vertices);
  140. }
  141. void OpenXRSpatialComponentPolygon2DList::set_capacity(uint32_t p_capacity) {
  142. polygon2d_data.resize(p_capacity);
  143. polygon2d_list.polygonCount = uint32_t(polygon2d_data.size());
  144. polygon2d_list.polygons = polygon2d_data.ptrw();
  145. }
  146. XrSpatialComponentTypeEXT OpenXRSpatialComponentPolygon2DList::get_component_type() const {
  147. return XR_SPATIAL_COMPONENT_TYPE_POLYGON_2D_EXT;
  148. }
  149. void *OpenXRSpatialComponentPolygon2DList::get_structure_data(void *p_next) {
  150. polygon2d_list.next = p_next;
  151. return &polygon2d_list;
  152. }
  153. Transform3D OpenXRSpatialComponentPolygon2DList::get_transform(int64_t p_index) const {
  154. ERR_FAIL_INDEX_V(p_index, polygon2d_data.size(), Transform3D());
  155. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  156. ERR_FAIL_NULL_V(openxr_api, Transform3D());
  157. return openxr_api->transform_from_pose(polygon2d_data[p_index].origin);
  158. }
  159. PackedVector2Array OpenXRSpatialComponentPolygon2DList::get_vertices(RID p_snapshot, int64_t p_index) const {
  160. ERR_FAIL_INDEX_V(p_index, polygon2d_data.size(), PackedVector2Array());
  161. const XrSpatialBufferEXT &buffer = polygon2d_data[p_index].vertexBuffer;
  162. if (buffer.bufferId == XR_NULL_SPATIAL_BUFFER_ID_EXT) {
  163. // We don't have data (yet).
  164. return PackedVector2Array();
  165. }
  166. ERR_FAIL_COND_V(buffer.bufferType != XR_SPATIAL_BUFFER_TYPE_VECTOR2F_EXT, PackedVector2Array());
  167. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  168. ERR_FAIL_NULL_V(se_extension, PackedVector2Array());
  169. return se_extension->get_vector2_buffer(p_snapshot, buffer.bufferId);
  170. }
  171. ////////////////////////////////////////////////////////////////////////////
  172. // OpenXRSpatialComponentPlaneSemanticLabelList
  173. void OpenXRSpatialComponentPlaneSemanticLabelList::_bind_methods() {
  174. ClassDB::bind_method(D_METHOD("get_plane_semantic_label", "index"), &OpenXRSpatialComponentPlaneSemanticLabelList::_get_plane_semantic_label);
  175. BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_UNCATEGORIZED);
  176. BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_FLOOR);
  177. BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_WALL);
  178. BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_CEILING);
  179. BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_TABLE);
  180. }
  181. void OpenXRSpatialComponentPlaneSemanticLabelList::set_capacity(uint32_t p_capacity) {
  182. plane_semantic_label_data.resize(p_capacity);
  183. plane_semantic_label_list.semanticLabelCount = uint32_t(plane_semantic_label_data.size());
  184. plane_semantic_label_list.semanticLabels = plane_semantic_label_data.ptrw();
  185. }
  186. XrSpatialComponentTypeEXT OpenXRSpatialComponentPlaneSemanticLabelList::get_component_type() const {
  187. return XR_SPATIAL_COMPONENT_TYPE_PLANE_SEMANTIC_LABEL_EXT;
  188. }
  189. void *OpenXRSpatialComponentPlaneSemanticLabelList::get_structure_data(void *p_next) {
  190. plane_semantic_label_list.next = p_next;
  191. return &plane_semantic_label_list;
  192. }
  193. XrSpatialPlaneSemanticLabelEXT OpenXRSpatialComponentPlaneSemanticLabelList::get_plane_semantic_label(int64_t p_index) const {
  194. ERR_FAIL_INDEX_V(p_index, plane_semantic_label_data.size(), XR_SPATIAL_PLANE_SEMANTIC_LABEL_MAX_ENUM_EXT);
  195. return plane_semantic_label_data[p_index];
  196. }
  197. OpenXRSpatialComponentPlaneSemanticLabelList::PlaneSemanticLabel OpenXRSpatialComponentPlaneSemanticLabelList::_get_plane_semantic_label(int64_t p_index) const {
  198. return (PlaneSemanticLabel)get_plane_semantic_label(p_index);
  199. }
  200. ////////////////////////////////////////////////////////////////////////////
  201. // OpenXRPlaneTracker
  202. void OpenXRPlaneTracker::_bind_methods() {
  203. ClassDB::bind_method(D_METHOD("set_bounds_size", "bounds_size"), &OpenXRPlaneTracker::set_bounds_size);
  204. ClassDB::bind_method(D_METHOD("get_bounds_size"), &OpenXRPlaneTracker::get_bounds_size);
  205. ADD_PROPERTY(PropertyInfo(Variant::INT, "bounds_size"), "set_bounds_size", "get_bounds_size");
  206. ClassDB::bind_method(D_METHOD("set_plane_alignment", "plane_alignment"), &OpenXRPlaneTracker::set_plane_alignment);
  207. ClassDB::bind_method(D_METHOD("get_plane_alignment"), &OpenXRPlaneTracker::get_plane_alignment);
  208. ADD_PROPERTY(PropertyInfo(Variant::INT, "plane_alignment"), "set_plane_alignment", "get_plane_alignment");
  209. ClassDB::bind_method(D_METHOD("set_plane_label", "plane_label"), &OpenXRPlaneTracker::set_plane_label);
  210. ClassDB::bind_method(D_METHOD("get_plane_label"), &OpenXRPlaneTracker::get_plane_label);
  211. ADD_PROPERTY(PropertyInfo(Variant::STRING, "plane_label"), "set_plane_label", "get_plane_label");
  212. ClassDB::bind_method(D_METHOD("set_mesh_data", "origin", "vertices", "indices"), &OpenXRPlaneTracker::set_mesh_data, DEFVAL(PackedInt32Array()));
  213. ClassDB::bind_method(D_METHOD("clear_mesh_data"), &OpenXRPlaneTracker::clear_mesh_data);
  214. ClassDB::bind_method(D_METHOD("get_mesh_offset"), &OpenXRPlaneTracker::get_mesh_offset);
  215. ClassDB::bind_method(D_METHOD("get_mesh"), &OpenXRPlaneTracker::get_mesh);
  216. ClassDB::bind_method(D_METHOD("get_shape", "thickness"), &OpenXRPlaneTracker::get_shape, DEFVAL(0.01));
  217. ADD_SIGNAL(MethodInfo("mesh_changed"));
  218. }
  219. void OpenXRPlaneTracker::set_bounds_size(const Vector2 &p_bounds_size) {
  220. if (Math::abs(bounds_size.x - p_bounds_size.x) > 0.001 || Math::abs(bounds_size.y - p_bounds_size.y) > 0.001) {
  221. bounds_size = p_bounds_size;
  222. if (!mesh.has_mesh_data) {
  223. // Bounds changing only effects mesh data if we don't have polygon data.
  224. clear_mesh_data();
  225. emit_signal(SNAME("mesh_changed"));
  226. }
  227. }
  228. }
  229. Vector2 OpenXRPlaneTracker::get_bounds_size() const {
  230. return bounds_size;
  231. }
  232. void OpenXRPlaneTracker::set_plane_alignment(OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment p_plane_alignment) {
  233. if (plane_alignment != p_plane_alignment) {
  234. plane_alignment = p_plane_alignment;
  235. }
  236. }
  237. OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment OpenXRPlaneTracker::get_plane_alignment() const {
  238. return plane_alignment;
  239. }
  240. void OpenXRPlaneTracker::set_plane_label(const String &p_plane_label) {
  241. if (plane_label != p_plane_label) {
  242. plane_label = p_plane_label;
  243. // Also copy to description, should do something nicer here.
  244. set_tracker_desc(plane_label);
  245. }
  246. }
  247. String OpenXRPlaneTracker::get_plane_label() const {
  248. return plane_label;
  249. }
  250. void OpenXRPlaneTracker::set_mesh_data(const Transform3D &p_origin, const PackedVector2Array &p_vertices, const PackedInt32Array &p_indices) {
  251. if (p_vertices.size() < 3) {
  252. if (mesh.has_mesh_data) {
  253. clear_mesh_data();
  254. emit_signal(SNAME("mesh_changed"));
  255. }
  256. } else {
  257. bool has_changed = !mesh.has_mesh_data;
  258. mesh.has_mesh_data = true;
  259. mesh.origin = p_origin;
  260. if (mesh.vertices.size() != p_vertices.size()) {
  261. has_changed = true;
  262. } else {
  263. // Compare the vertices with a bit of margin, we ignore small jittering on vertices.
  264. for (uint32_t i = 0; i < p_vertices.size() && !has_changed; i++) {
  265. const Vector2 &a = p_vertices[i];
  266. const Vector2 &b = mesh.vertices[i];
  267. has_changed = (Math::abs(a.x - b.x) > 0.001) || (Math::abs(a.y - b.y) > 0.001);
  268. }
  269. }
  270. if (has_changed) {
  271. mesh.vertices = p_vertices;
  272. }
  273. // Q: Should we keep our indices list empty if we get polygon data
  274. // and create different meshes/collision shapes as a result?
  275. if (p_indices.is_empty()) {
  276. // Assume polygon, turn into triangle strip...
  277. int count = (p_vertices.size() - 2) * 3;
  278. // If our vertices haven't changed and our indices are already the correct size,
  279. // assume we don't need to rerun this.
  280. if (has_changed || mesh.indices.size() != count) {
  281. has_changed = true;
  282. int offset = 1;
  283. mesh.indices.resize(count);
  284. int32_t *idx = mesh.indices.ptrw();
  285. for (int i = 0; i < count; i += 3) {
  286. idx[i + 0] = 0;
  287. idx[i + 2] = offset++;
  288. idx[i + 1] = offset;
  289. }
  290. }
  291. } else {
  292. if (mesh.indices.size() != p_indices.size()) {
  293. has_changed = true;
  294. } else {
  295. for (uint32_t i = 0; i < p_indices.size() && !has_changed; i++) {
  296. has_changed = mesh.indices[i] != p_indices[i];
  297. }
  298. }
  299. if (has_changed) {
  300. mesh.indices = p_indices;
  301. }
  302. }
  303. if (has_changed) {
  304. mesh.mesh.unref();
  305. mesh.shape3d.unref();
  306. emit_signal(SNAME("mesh_changed"));
  307. }
  308. }
  309. }
  310. void OpenXRPlaneTracker::clear_mesh_data() {
  311. mesh.mesh.unref();
  312. mesh.shape3d.unref();
  313. if (mesh.has_mesh_data) {
  314. mesh.has_mesh_data = false;
  315. mesh.origin = Transform3D();
  316. mesh.vertices.clear();
  317. mesh.indices.clear();
  318. emit_signal(SNAME("mesh_changed"));
  319. }
  320. }
  321. Transform3D OpenXRPlaneTracker::get_mesh_offset() const {
  322. Transform3D offset;
  323. if (mesh.has_mesh_data) {
  324. offset = mesh.origin;
  325. Ref<XRPose> pose = get_pose(SNAME("default"));
  326. if (pose.is_valid()) {
  327. // Q is this offset * transform.inverse?
  328. offset = pose->get_transform().inverse() * offset;
  329. }
  330. // Reference frame will already be applied to pose used on our XRNode3D but we do need to apply our scale
  331. XRServer *xr_server = XRServer::get_singleton();
  332. if (xr_server) {
  333. offset.origin *= xr_server->get_world_scale();
  334. }
  335. }
  336. return offset;
  337. }
  338. Ref<Mesh> OpenXRPlaneTracker::get_mesh() {
  339. // We've already created this? Just return it!
  340. if (mesh.mesh.is_valid()) {
  341. return mesh.mesh;
  342. }
  343. if (mesh.has_mesh_data) {
  344. Ref<ArrayMesh> array_mesh;
  345. Array arr;
  346. // We need our vertices as Vector3
  347. PackedVector3Array vertices;
  348. vertices.resize(mesh.vertices.size());
  349. const Vector2 *read = mesh.vertices.ptr();
  350. Vector3 *write = vertices.ptrw();
  351. for (int v = 0; v < mesh.vertices.size(); v++) {
  352. write[v] = Vector3(read[v].x, read[v].y, 0.0);
  353. }
  354. // Build our array with data.
  355. arr.resize(RS::ARRAY_MAX);
  356. arr[RS::ARRAY_VERTEX] = vertices;
  357. arr[RS::ARRAY_INDEX] = mesh.indices;
  358. // Create our array mesh.
  359. array_mesh.instantiate();
  360. array_mesh->add_surface_from_arrays(Mesh::PrimitiveType::PRIMITIVE_TRIANGLES, arr);
  361. // Cache this.
  362. mesh.mesh = array_mesh;
  363. } else if (bounds_size.x > 0.0 && bounds_size.y > 0.0) {
  364. // We can use a plane mesh here.
  365. Ref<PlaneMesh> plane_mesh;
  366. plane_mesh.instantiate();
  367. plane_mesh->set_orientation(PlaneMesh::Orientation::FACE_Z);
  368. plane_mesh->set_size(bounds_size);
  369. // Cache this.
  370. mesh.mesh = plane_mesh;
  371. } else {
  372. print_verbose("OpenXR: Can't create mesh for plane, no data.");
  373. }
  374. return mesh.mesh;
  375. }
  376. Ref<Shape3D> OpenXRPlaneTracker::get_shape(real_t p_thickness) {
  377. // We've already created this? Just return it!
  378. if (mesh.shape3d.is_valid()) {
  379. return mesh.shape3d;
  380. }
  381. if (mesh.has_mesh_data) {
  382. Ref<ConcavePolygonShape3D> shape;
  383. Vector<Vector3> faces;
  384. // Get some direct access to our data.
  385. int isize = mesh.indices.size();
  386. const Vector2 *vr = mesh.vertices.ptr();
  387. const int32_t *ir = mesh.indices.ptr();
  388. // Find our edges.
  389. HashMap<Edge, int, Edge> edge_counts;
  390. for (int i = 0; i < isize; i += 3) {
  391. for (int j = 0; j < 3; j++) {
  392. Edge e(ir[i + j], ir[i + ((j + 1) % 3)]);
  393. edge_counts[e]++;
  394. }
  395. }
  396. // Find our outer edges.
  397. thread_local LocalVector<Edge> outer_edges;
  398. outer_edges.clear();
  399. for (const KeyValue<Edge, int> &e : edge_counts) {
  400. if (e.value > 1) {
  401. outer_edges.push_back(e.key);
  402. }
  403. }
  404. // Make space for these.
  405. faces.resize(2 * isize + 6 * outer_edges.size());
  406. Vector3 *write = faces.ptrw();
  407. // Add top and bottom.
  408. for (int i = 0; i < isize; i += 3) {
  409. Vector3 a = Vector3(vr[ir[i]].x, vr[ir[i]].y, 0.0);
  410. Vector3 b = Vector3(vr[ir[i + 1]].x, vr[ir[i + 1]].y, 0.0);
  411. Vector3 c = Vector3(vr[ir[i + 2]].x, vr[ir[i + 2]].y, 0.0);
  412. *write++ = a;
  413. *write++ = b;
  414. *write++ = c;
  415. a.z = -p_thickness;
  416. b.z = -p_thickness;
  417. c.z = -p_thickness;
  418. *write++ = a;
  419. *write++ = c;
  420. *write++ = b;
  421. }
  422. // Add outer edges.
  423. for (const Edge &edge : outer_edges) {
  424. Vector3 a = Vector3(vr[edge.a].x, vr[edge.a].y, 0.0);
  425. Vector3 b = Vector3(vr[edge.b].x, vr[edge.b].y, 0.0);
  426. Vector3 c = b + Vector3(0.0, 0.0, -p_thickness);
  427. Vector3 d = a + Vector3(0.0, 0.0, -p_thickness);
  428. *write++ = a;
  429. *write++ = b;
  430. *write++ = c;
  431. *write++ = a;
  432. *write++ = c;
  433. *write++ = d;
  434. }
  435. // Create our shape.
  436. shape.instantiate();
  437. shape->set_faces(faces);
  438. mesh.shape3d = shape;
  439. } else if (bounds_size.x > 0.0 && bounds_size.y > 0.0) {
  440. // We can use a box shape here
  441. Ref<BoxShape3D> box_shape;
  442. box_shape.instantiate();
  443. box_shape->set_size(Vector3(bounds_size.x, bounds_size.y, p_thickness));
  444. mesh.shape3d = box_shape;
  445. }
  446. return mesh.shape3d;
  447. }
  448. ////////////////////////////////////////////////////////////////////////////
  449. // OpenXRSpatialPlaneTrackingCapability
  450. OpenXRSpatialPlaneTrackingCapability *OpenXRSpatialPlaneTrackingCapability::singleton = nullptr;
  451. OpenXRSpatialPlaneTrackingCapability *OpenXRSpatialPlaneTrackingCapability::get_singleton() {
  452. return singleton;
  453. }
  454. OpenXRSpatialPlaneTrackingCapability::OpenXRSpatialPlaneTrackingCapability() {
  455. singleton = this;
  456. }
  457. OpenXRSpatialPlaneTrackingCapability::~OpenXRSpatialPlaneTrackingCapability() {
  458. singleton = nullptr;
  459. }
  460. void OpenXRSpatialPlaneTrackingCapability::_bind_methods() {
  461. ClassDB::bind_method(D_METHOD("is_supported"), &OpenXRSpatialPlaneTrackingCapability::is_supported);
  462. }
  463. HashMap<String, bool *> OpenXRSpatialPlaneTrackingCapability::get_requested_extensions() {
  464. HashMap<String, bool *> request_extensions;
  465. if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enabled") && GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_plane_tracking")) {
  466. request_extensions[XR_EXT_SPATIAL_PLANE_TRACKING_EXTENSION_NAME] = &spatial_plane_tracking_ext;
  467. }
  468. return request_extensions;
  469. }
  470. void OpenXRSpatialPlaneTrackingCapability::on_session_created(const XrSession p_session) {
  471. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  472. ERR_FAIL_NULL(se_extension);
  473. if (!spatial_plane_tracking_ext) {
  474. return;
  475. }
  476. spatial_plane_tracking_supported = se_extension->supports_capability(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT);
  477. if (!spatial_plane_tracking_supported) {
  478. // Supported by XR runtime but not by device? We're done.
  479. return;
  480. }
  481. se_extension->connect(SNAME("spatial_discovery_recommended"), callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_on_spatial_discovery_recommended));
  482. if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_builtin_plane_detection")) {
  483. // Start by creating our spatial context
  484. _create_spatial_context();
  485. }
  486. }
  487. void OpenXRSpatialPlaneTrackingCapability::on_session_destroyed() {
  488. if (!spatial_plane_tracking_supported) {
  489. return;
  490. }
  491. spatial_plane_tracking_supported = false;
  492. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  493. ERR_FAIL_NULL(se_extension);
  494. XRServer *xr_server = XRServer::get_singleton();
  495. ERR_FAIL_NULL(xr_server);
  496. // Free and unregister our anchors
  497. for (const KeyValue<XrSpatialEntityIdEXT, Ref<OpenXRPlaneTracker>> &plane_tracker : plane_trackers) {
  498. xr_server->remove_tracker(plane_tracker.value);
  499. }
  500. plane_trackers.clear();
  501. // Free our spatial context
  502. if (spatial_context.is_valid()) {
  503. se_extension->free_spatial_context(spatial_context);
  504. spatial_context = RID();
  505. }
  506. se_extension->disconnect(SNAME("spatial_discovery_recommended"), callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_on_spatial_discovery_recommended));
  507. }
  508. void OpenXRSpatialPlaneTrackingCapability::on_process() {
  509. if (!spatial_context.is_valid()) {
  510. return;
  511. }
  512. // Protection against plane discovery happening too often.
  513. if (discovery_cooldown > 0) {
  514. discovery_cooldown--;
  515. }
  516. // Check if we need to start our discovery.
  517. if (need_discovery && discovery_cooldown == 0 && !discovery_query_result.is_valid()) {
  518. need_discovery = false;
  519. discovery_cooldown = 60; // Set our cooldown to 60 frames, it doesn't need to be an exact science.
  520. _start_entity_discovery();
  521. }
  522. }
  523. bool OpenXRSpatialPlaneTrackingCapability::is_supported() {
  524. return spatial_plane_tracking_supported;
  525. }
  526. ////////////////////////////////////////////////////////////////////////////
  527. // Discovery logic
  528. Ref<OpenXRFutureResult> OpenXRSpatialPlaneTrackingCapability::_create_spatial_context() {
  529. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  530. ERR_FAIL_NULL_V(se_extension, nullptr);
  531. TypedArray<OpenXRSpatialCapabilityConfigurationBaseHeader> capability_configurations;
  532. // Create our configuration objects.
  533. plane_configuration.instantiate();
  534. capability_configurations.push_back(plane_configuration);
  535. return se_extension->create_spatial_context(capability_configurations, nullptr, callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_on_spatial_context_created));
  536. }
  537. void OpenXRSpatialPlaneTrackingCapability::_on_spatial_context_created(RID p_spatial_context) {
  538. spatial_context = p_spatial_context;
  539. need_discovery = true;
  540. }
  541. void OpenXRSpatialPlaneTrackingCapability::_on_spatial_discovery_recommended(RID p_spatial_context) {
  542. if (p_spatial_context == spatial_context) {
  543. // Trigger new discovery.
  544. need_discovery = true;
  545. }
  546. }
  547. Ref<OpenXRFutureResult> OpenXRSpatialPlaneTrackingCapability::_start_entity_discovery() {
  548. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  549. ERR_FAIL_NULL_V(se_extension, nullptr);
  550. // Already running or ran discovery, cancel/clean up.
  551. if (discovery_query_result.is_valid()) {
  552. WARN_PRINT("OpenXR: Starting new discovery before previous discovery has been processed!");
  553. discovery_query_result->cancel_future();
  554. discovery_query_result.unref();
  555. }
  556. // Start our new snapshot.
  557. discovery_query_result = se_extension->discover_spatial_entities(spatial_context, plane_configuration->get_enabled_components(), nullptr, callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_process_snapshot));
  558. return discovery_query_result;
  559. }
  560. void OpenXRSpatialPlaneTrackingCapability::_process_snapshot(RID p_snapshot) {
  561. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  562. ERR_FAIL_NULL(se_extension);
  563. XRServer *xr_server = XRServer::get_singleton();
  564. ERR_FAIL_NULL(xr_server);
  565. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  566. ERR_FAIL_NULL(openxr_api);
  567. // Make a copy of the planes we have right now, so we know which ones to clean up.
  568. LocalVector<XrSpatialEntityIdEXT> current_planes;
  569. current_planes.resize(plane_trackers.size());
  570. int p = 0;
  571. for (const KeyValue<XrSpatialEntityIdEXT, Ref<OpenXRPlaneTracker>> &plane : plane_trackers) {
  572. current_planes[p++] = plane.key;
  573. }
  574. // Build our component data
  575. TypedArray<OpenXRSpatialComponentData> component_data;
  576. // We always need a query result data object
  577. Ref<OpenXRSpatialQueryResultData> query_result_data;
  578. query_result_data.instantiate();
  579. component_data.push_back(query_result_data);
  580. // Add bounded2D
  581. Ref<OpenXRSpatialComponentBounded2DList> bounded2d_list;
  582. bounded2d_list.instantiate();
  583. component_data.push_back(bounded2d_list);
  584. // Plane alignment list
  585. Ref<OpenXRSpatialComponentPlaneAlignmentList> alignment_list;
  586. alignment_list.instantiate();
  587. component_data.push_back(alignment_list);
  588. Ref<OpenXRSpatialComponentMesh2DList> mesh2d_list;
  589. Ref<OpenXRSpatialComponentPolygon2DList> poly2d_list;
  590. if (plane_configuration->get_supports_mesh_2d()) {
  591. mesh2d_list.instantiate();
  592. component_data.push_back(mesh2d_list);
  593. } else if (plane_configuration->get_supports_polygons()) {
  594. poly2d_list.instantiate();
  595. component_data.push_back(poly2d_list);
  596. }
  597. // Plane semantic label
  598. Ref<OpenXRSpatialComponentPlaneSemanticLabelList> label_list;
  599. if (plane_configuration->get_supports_labels()) {
  600. label_list.instantiate();
  601. component_data.push_back(label_list);
  602. }
  603. if (se_extension->query_snapshot(p_snapshot, component_data, nullptr)) {
  604. // Now loop through our data and update our anchors.
  605. // Q we're assuming entity ID, size and state size are equal, is there ever a situation where they would not be?
  606. int64_t size = query_result_data->get_capacity();
  607. for (int64_t i = 0; i < size; i++) {
  608. XrSpatialEntityIdEXT entity_id = query_result_data->get_entity_id(i);
  609. XrSpatialEntityTrackingStateEXT entity_state = query_result_data->get_entity_state(i);
  610. // Erase it from our current planes (if we have it, else this is ignored).
  611. current_planes.erase(entity_id);
  612. if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT) {
  613. // We should only get this status on updates as a prelude to needing to remove this marker.
  614. // So we just update the status.
  615. if (plane_trackers.has(entity_id)) {
  616. Ref<OpenXRPlaneTracker> plane_tracker = plane_trackers[entity_id];
  617. plane_tracker->invalidate_pose(SNAME("default"));
  618. plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT);
  619. }
  620. } else {
  621. // Process our entity
  622. bool add_to_xr_server = false;
  623. Ref<OpenXRPlaneTracker> plane_tracker;
  624. if (plane_trackers.has(entity_id)) {
  625. // We know about this one already
  626. plane_tracker = plane_trackers[entity_id];
  627. } else {
  628. // Create a new anchor
  629. plane_tracker.instantiate();
  630. plane_tracker->set_entity(se_extension->make_spatial_entity(se_extension->get_spatial_snapshot_context(p_snapshot), entity_id));
  631. plane_trackers[entity_id] = plane_tracker;
  632. add_to_xr_server = true;
  633. }
  634. // Handle component data
  635. if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT) {
  636. plane_tracker->invalidate_pose(SNAME("default"));
  637. plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT);
  638. // No further component data will be valid in this state, we need to ignore it!
  639. } else if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT) {
  640. Transform3D transform = bounded2d_list->get_center_pose(i);
  641. plane_tracker->set_pose(SNAME("default"), transform, Vector3(), Vector3());
  642. plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT);
  643. // Process our component data.
  644. plane_tracker->set_bounds_size(bounded2d_list->get_size(i));
  645. plane_tracker->set_plane_alignment((OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment)alignment_list->get_plane_alignment(i));
  646. if (mesh2d_list.is_valid()) {
  647. plane_tracker->set_mesh_data(mesh2d_list->get_transform(i), mesh2d_list->get_vertices(p_snapshot, i), mesh2d_list->get_indices(p_snapshot, i));
  648. } else if (poly2d_list.is_valid()) {
  649. plane_tracker->set_mesh_data(poly2d_list->get_transform(i), poly2d_list->get_vertices(p_snapshot, i));
  650. } else {
  651. // Just in case we set this before.
  652. plane_tracker->clear_mesh_data();
  653. }
  654. if (label_list.is_valid()) {
  655. switch (label_list->get_plane_semantic_label(i)) {
  656. case XR_SPATIAL_PLANE_SEMANTIC_LABEL_UNCATEGORIZED_EXT: {
  657. plane_tracker->set_plane_label("Uncategorized plane");
  658. } break;
  659. case XR_SPATIAL_PLANE_SEMANTIC_LABEL_FLOOR_EXT: {
  660. plane_tracker->set_plane_label("Floor plane");
  661. } break;
  662. case XR_SPATIAL_PLANE_SEMANTIC_LABEL_WALL_EXT: {
  663. plane_tracker->set_plane_label("Wall plane");
  664. } break;
  665. case XR_SPATIAL_PLANE_SEMANTIC_LABEL_CEILING_EXT: {
  666. plane_tracker->set_plane_label("Ceiling plane");
  667. } break;
  668. case XR_SPATIAL_PLANE_SEMANTIC_LABEL_TABLE_EXT: {
  669. plane_tracker->set_plane_label("Table plane");
  670. } break;
  671. default: {
  672. plane_tracker->set_plane_label("Unknown plane");
  673. } break;
  674. }
  675. }
  676. }
  677. if (add_to_xr_server) {
  678. // Register with XR server
  679. xr_server->add_tracker(plane_tracker);
  680. }
  681. }
  682. }
  683. // Remove any planes that are no longer there...
  684. for (const XrSpatialEntityIdEXT &entity_id : current_planes) {
  685. if (plane_trackers.has(entity_id)) {
  686. Ref<OpenXRPlaneTracker> plane_tracker = plane_trackers[entity_id];
  687. // Just in case there are still references out there to this marker,
  688. // reset some stuff.
  689. plane_tracker->invalidate_pose(SNAME("default"));
  690. plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT);
  691. // Remove it from our XRServer
  692. xr_server->remove_tracker(plane_tracker);
  693. // Remove it from our trackers
  694. plane_trackers.erase(entity_id);
  695. }
  696. }
  697. }
  698. // Now that we're done, clean up our snapshot!
  699. se_extension->free_spatial_snapshot(p_snapshot);
  700. // And if this was our discovery snapshot, lets reset it
  701. if (discovery_query_result.is_valid() && discovery_query_result->get_result_value() == p_snapshot) {
  702. discovery_query_result.unref();
  703. }
  704. }