nav_mesh_generator_3d.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. /**************************************************************************/
  2. /* nav_mesh_generator_3d.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. #ifndef _3D_DISABLED
  31. #include "nav_mesh_generator_3d.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/math/convex_hull.h"
  34. #include "core/os/thread.h"
  35. #include "scene/3d/mesh_instance_3d.h"
  36. #include "scene/3d/multimesh_instance_3d.h"
  37. #include "scene/3d/navigation_obstacle_3d.h"
  38. #include "scene/3d/physics/static_body_3d.h"
  39. #include "scene/resources/3d/box_shape_3d.h"
  40. #include "scene/resources/3d/capsule_shape_3d.h"
  41. #include "scene/resources/3d/concave_polygon_shape_3d.h"
  42. #include "scene/resources/3d/convex_polygon_shape_3d.h"
  43. #include "scene/resources/3d/cylinder_shape_3d.h"
  44. #include "scene/resources/3d/height_map_shape_3d.h"
  45. #include "scene/resources/3d/navigation_mesh_source_geometry_data_3d.h"
  46. #include "scene/resources/3d/primitive_meshes.h"
  47. #include "scene/resources/3d/shape_3d.h"
  48. #include "scene/resources/3d/sphere_shape_3d.h"
  49. #include "scene/resources/3d/world_boundary_shape_3d.h"
  50. #include "scene/resources/navigation_mesh.h"
  51. #include "modules/modules_enabled.gen.h" // For csg, gridmap.
  52. #ifdef MODULE_CSG_ENABLED
  53. #include "modules/csg/csg_shape.h"
  54. #endif
  55. #ifdef MODULE_GRIDMAP_ENABLED
  56. #include "modules/gridmap/grid_map.h"
  57. #endif
  58. #include <Recast.h>
  59. NavMeshGenerator3D *NavMeshGenerator3D::singleton = nullptr;
  60. Mutex NavMeshGenerator3D::baking_navmesh_mutex;
  61. Mutex NavMeshGenerator3D::generator_task_mutex;
  62. RWLock NavMeshGenerator3D::generator_rid_rwlock;
  63. bool NavMeshGenerator3D::use_threads = true;
  64. bool NavMeshGenerator3D::baking_use_multiple_threads = true;
  65. bool NavMeshGenerator3D::baking_use_high_priority_threads = true;
  66. HashSet<Ref<NavigationMesh>> NavMeshGenerator3D::baking_navmeshes;
  67. HashMap<WorkerThreadPool::TaskID, NavMeshGenerator3D::NavMeshGeneratorTask3D *> NavMeshGenerator3D::generator_tasks;
  68. RID_Owner<NavMeshGenerator3D::NavMeshGeometryParser3D> NavMeshGenerator3D::generator_parser_owner;
  69. LocalVector<NavMeshGenerator3D::NavMeshGeometryParser3D *> NavMeshGenerator3D::generator_parsers;
  70. NavMeshGenerator3D *NavMeshGenerator3D::get_singleton() {
  71. return singleton;
  72. }
  73. NavMeshGenerator3D::NavMeshGenerator3D() {
  74. ERR_FAIL_COND(singleton != nullptr);
  75. singleton = this;
  76. baking_use_multiple_threads = GLOBAL_GET("navigation/baking/thread_model/baking_use_multiple_threads");
  77. baking_use_high_priority_threads = GLOBAL_GET("navigation/baking/thread_model/baking_use_high_priority_threads");
  78. // Using threads might cause problems on certain exports or with the Editor on certain devices.
  79. // This is the main switch to turn threaded navmesh baking off should the need arise.
  80. use_threads = baking_use_multiple_threads;
  81. }
  82. NavMeshGenerator3D::~NavMeshGenerator3D() {
  83. cleanup();
  84. }
  85. void NavMeshGenerator3D::sync() {
  86. if (generator_tasks.size() == 0) {
  87. return;
  88. }
  89. MutexLock baking_navmesh_lock(baking_navmesh_mutex);
  90. {
  91. MutexLock generator_task_lock(generator_task_mutex);
  92. LocalVector<WorkerThreadPool::TaskID> finished_task_ids;
  93. for (KeyValue<WorkerThreadPool::TaskID, NavMeshGeneratorTask3D *> &E : generator_tasks) {
  94. if (WorkerThreadPool::get_singleton()->is_task_completed(E.key)) {
  95. WorkerThreadPool::get_singleton()->wait_for_task_completion(E.key);
  96. finished_task_ids.push_back(E.key);
  97. NavMeshGeneratorTask3D *generator_task = E.value;
  98. DEV_ASSERT(generator_task->status == NavMeshGeneratorTask3D::TaskStatus::BAKING_FINISHED);
  99. baking_navmeshes.erase(generator_task->navigation_mesh);
  100. if (generator_task->callback.is_valid()) {
  101. generator_emit_callback(generator_task->callback);
  102. }
  103. memdelete(generator_task);
  104. }
  105. }
  106. for (WorkerThreadPool::TaskID finished_task_id : finished_task_ids) {
  107. generator_tasks.erase(finished_task_id);
  108. }
  109. }
  110. }
  111. void NavMeshGenerator3D::cleanup() {
  112. MutexLock baking_navmesh_lock(baking_navmesh_mutex);
  113. {
  114. MutexLock generator_task_lock(generator_task_mutex);
  115. baking_navmeshes.clear();
  116. for (KeyValue<WorkerThreadPool::TaskID, NavMeshGeneratorTask3D *> &E : generator_tasks) {
  117. WorkerThreadPool::get_singleton()->wait_for_task_completion(E.key);
  118. NavMeshGeneratorTask3D *generator_task = E.value;
  119. memdelete(generator_task);
  120. }
  121. generator_tasks.clear();
  122. generator_rid_rwlock.write_lock();
  123. for (NavMeshGeometryParser3D *parser : generator_parsers) {
  124. generator_parser_owner.free(parser->self);
  125. }
  126. generator_parsers.clear();
  127. generator_rid_rwlock.write_unlock();
  128. }
  129. }
  130. void NavMeshGenerator3D::finish() {
  131. cleanup();
  132. }
  133. void NavMeshGenerator3D::parse_source_geometry_data(Ref<NavigationMesh> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_root_node, const Callable &p_callback) {
  134. ERR_FAIL_COND(!Thread::is_main_thread());
  135. ERR_FAIL_COND(!p_navigation_mesh.is_valid());
  136. ERR_FAIL_NULL(p_root_node);
  137. ERR_FAIL_COND(!p_root_node->is_inside_tree());
  138. ERR_FAIL_COND(!p_source_geometry_data.is_valid());
  139. generator_parse_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_root_node);
  140. if (p_callback.is_valid()) {
  141. generator_emit_callback(p_callback);
  142. }
  143. }
  144. void NavMeshGenerator3D::bake_from_source_geometry_data(Ref<NavigationMesh> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, const Callable &p_callback) {
  145. ERR_FAIL_COND(!p_navigation_mesh.is_valid());
  146. ERR_FAIL_COND(!p_source_geometry_data.is_valid());
  147. if (!p_source_geometry_data->has_data()) {
  148. p_navigation_mesh->clear();
  149. if (p_callback.is_valid()) {
  150. generator_emit_callback(p_callback);
  151. }
  152. return;
  153. }
  154. if (is_baking(p_navigation_mesh)) {
  155. ERR_FAIL_MSG("NavigationMesh is already baking. Wait for current bake to finish.");
  156. }
  157. baking_navmesh_mutex.lock();
  158. baking_navmeshes.insert(p_navigation_mesh);
  159. baking_navmesh_mutex.unlock();
  160. generator_bake_from_source_geometry_data(p_navigation_mesh, p_source_geometry_data);
  161. baking_navmesh_mutex.lock();
  162. baking_navmeshes.erase(p_navigation_mesh);
  163. baking_navmesh_mutex.unlock();
  164. if (p_callback.is_valid()) {
  165. generator_emit_callback(p_callback);
  166. }
  167. }
  168. void NavMeshGenerator3D::bake_from_source_geometry_data_async(Ref<NavigationMesh> p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, const Callable &p_callback) {
  169. ERR_FAIL_COND(!p_navigation_mesh.is_valid());
  170. ERR_FAIL_COND(!p_source_geometry_data.is_valid());
  171. if (!p_source_geometry_data->has_data()) {
  172. p_navigation_mesh->clear();
  173. if (p_callback.is_valid()) {
  174. generator_emit_callback(p_callback);
  175. }
  176. return;
  177. }
  178. if (!use_threads) {
  179. bake_from_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_callback);
  180. return;
  181. }
  182. if (is_baking(p_navigation_mesh)) {
  183. ERR_FAIL_MSG("NavigationMesh is already baking. Wait for current bake to finish.");
  184. return;
  185. }
  186. baking_navmesh_mutex.lock();
  187. baking_navmeshes.insert(p_navigation_mesh);
  188. baking_navmesh_mutex.unlock();
  189. MutexLock generator_task_lock(generator_task_mutex);
  190. NavMeshGeneratorTask3D *generator_task = memnew(NavMeshGeneratorTask3D);
  191. generator_task->navigation_mesh = p_navigation_mesh;
  192. generator_task->source_geometry_data = p_source_geometry_data;
  193. generator_task->callback = p_callback;
  194. generator_task->status = NavMeshGeneratorTask3D::TaskStatus::BAKING_STARTED;
  195. generator_task->thread_task_id = WorkerThreadPool::get_singleton()->add_native_task(&NavMeshGenerator3D::generator_thread_bake, generator_task, NavMeshGenerator3D::baking_use_high_priority_threads, SNAME("NavMeshGeneratorBake3D"));
  196. generator_tasks.insert(generator_task->thread_task_id, generator_task);
  197. }
  198. bool NavMeshGenerator3D::is_baking(Ref<NavigationMesh> p_navigation_mesh) {
  199. MutexLock baking_navmesh_lock(baking_navmesh_mutex);
  200. return baking_navmeshes.has(p_navigation_mesh);
  201. }
  202. void NavMeshGenerator3D::generator_thread_bake(void *p_arg) {
  203. NavMeshGeneratorTask3D *generator_task = static_cast<NavMeshGeneratorTask3D *>(p_arg);
  204. generator_bake_from_source_geometry_data(generator_task->navigation_mesh, generator_task->source_geometry_data);
  205. generator_task->status = NavMeshGeneratorTask3D::TaskStatus::BAKING_FINISHED;
  206. }
  207. void NavMeshGenerator3D::generator_parse_geometry_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node, bool p_recurse_children) {
  208. generator_parse_meshinstance3d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  209. generator_parse_multimeshinstance3d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  210. generator_parse_staticbody3d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  211. #ifdef MODULE_CSG_ENABLED
  212. generator_parse_csgshape3d_node(p_navigation_mesh, p_source_geometry_data, p_node);
  213. #endif
  214. #ifdef MODULE_GRIDMAP_ENABLED
  215. generator_parse_gridmap_node(p_navigation_mesh, p_source_geometry_data, p_node);
  216. #endif
  217. generator_parse_navigationobstacle_node(p_navigation_mesh, p_source_geometry_data, p_node);
  218. generator_rid_rwlock.read_lock();
  219. for (const NavMeshGeometryParser3D *parser : generator_parsers) {
  220. if (!parser->callback.is_valid()) {
  221. continue;
  222. }
  223. parser->callback.call(p_navigation_mesh, p_source_geometry_data, p_node);
  224. }
  225. generator_rid_rwlock.read_unlock();
  226. if (p_recurse_children) {
  227. for (int i = 0; i < p_node->get_child_count(); i++) {
  228. generator_parse_geometry_node(p_navigation_mesh, p_source_geometry_data, p_node->get_child(i), p_recurse_children);
  229. }
  230. }
  231. }
  232. void NavMeshGenerator3D::generator_parse_meshinstance3d_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node) {
  233. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(p_node);
  234. if (mesh_instance) {
  235. NavigationMesh::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  236. if (parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES || parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_BOTH) {
  237. Ref<Mesh> mesh = mesh_instance->get_mesh();
  238. if (mesh.is_valid()) {
  239. p_source_geometry_data->add_mesh(mesh, mesh_instance->get_global_transform());
  240. }
  241. }
  242. }
  243. }
  244. void NavMeshGenerator3D::generator_parse_multimeshinstance3d_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node) {
  245. MultiMeshInstance3D *multimesh_instance = Object::cast_to<MultiMeshInstance3D>(p_node);
  246. if (multimesh_instance) {
  247. NavigationMesh::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  248. if (parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES || parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_BOTH) {
  249. Ref<MultiMesh> multimesh = multimesh_instance->get_multimesh();
  250. if (multimesh.is_valid()) {
  251. Ref<Mesh> mesh = multimesh->get_mesh();
  252. if (mesh.is_valid()) {
  253. int n = multimesh->get_visible_instance_count();
  254. if (n == -1) {
  255. n = multimesh->get_instance_count();
  256. }
  257. for (int i = 0; i < n; i++) {
  258. p_source_geometry_data->add_mesh(mesh, multimesh_instance->get_global_transform() * multimesh->get_instance_transform(i));
  259. }
  260. }
  261. }
  262. }
  263. }
  264. }
  265. void NavMeshGenerator3D::generator_parse_staticbody3d_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node) {
  266. StaticBody3D *static_body = Object::cast_to<StaticBody3D>(p_node);
  267. if (static_body) {
  268. NavigationMesh::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  269. uint32_t parsed_collision_mask = p_navigation_mesh->get_collision_mask();
  270. if ((parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_BOTH) && (static_body->get_collision_layer() & parsed_collision_mask)) {
  271. List<uint32_t> shape_owners;
  272. static_body->get_shape_owners(&shape_owners);
  273. for (uint32_t shape_owner : shape_owners) {
  274. if (static_body->is_shape_owner_disabled(shape_owner)) {
  275. continue;
  276. }
  277. const int shape_count = static_body->shape_owner_get_shape_count(shape_owner);
  278. for (int shape_index = 0; shape_index < shape_count; shape_index++) {
  279. Ref<Shape3D> s = static_body->shape_owner_get_shape(shape_owner, shape_index);
  280. if (s.is_null()) {
  281. continue;
  282. }
  283. const Transform3D transform = static_body->get_global_transform() * static_body->shape_owner_get_transform(shape_owner);
  284. BoxShape3D *box = Object::cast_to<BoxShape3D>(*s);
  285. if (box) {
  286. Array arr;
  287. arr.resize(RS::ARRAY_MAX);
  288. BoxMesh::create_mesh_array(arr, box->get_size());
  289. p_source_geometry_data->add_mesh_array(arr, transform);
  290. }
  291. CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s);
  292. if (capsule) {
  293. Array arr;
  294. arr.resize(RS::ARRAY_MAX);
  295. CapsuleMesh::create_mesh_array(arr, capsule->get_radius(), capsule->get_height());
  296. p_source_geometry_data->add_mesh_array(arr, transform);
  297. }
  298. CylinderShape3D *cylinder = Object::cast_to<CylinderShape3D>(*s);
  299. if (cylinder) {
  300. Array arr;
  301. arr.resize(RS::ARRAY_MAX);
  302. CylinderMesh::create_mesh_array(arr, cylinder->get_radius(), cylinder->get_radius(), cylinder->get_height());
  303. p_source_geometry_data->add_mesh_array(arr, transform);
  304. }
  305. SphereShape3D *sphere = Object::cast_to<SphereShape3D>(*s);
  306. if (sphere) {
  307. Array arr;
  308. arr.resize(RS::ARRAY_MAX);
  309. SphereMesh::create_mesh_array(arr, sphere->get_radius(), sphere->get_radius() * 2.0);
  310. p_source_geometry_data->add_mesh_array(arr, transform);
  311. }
  312. ConcavePolygonShape3D *concave_polygon = Object::cast_to<ConcavePolygonShape3D>(*s);
  313. if (concave_polygon) {
  314. p_source_geometry_data->add_faces(concave_polygon->get_faces(), transform);
  315. }
  316. ConvexPolygonShape3D *convex_polygon = Object::cast_to<ConvexPolygonShape3D>(*s);
  317. if (convex_polygon) {
  318. Vector<Vector3> varr = Variant(convex_polygon->get_points());
  319. Geometry3D::MeshData md;
  320. Error err = ConvexHullComputer::convex_hull(varr, md);
  321. if (err == OK) {
  322. PackedVector3Array faces;
  323. for (const Geometry3D::MeshData::Face &face : md.faces) {
  324. for (uint32_t k = 2; k < face.indices.size(); ++k) {
  325. faces.push_back(md.vertices[face.indices[0]]);
  326. faces.push_back(md.vertices[face.indices[k - 1]]);
  327. faces.push_back(md.vertices[face.indices[k]]);
  328. }
  329. }
  330. p_source_geometry_data->add_faces(faces, transform);
  331. }
  332. }
  333. HeightMapShape3D *heightmap_shape = Object::cast_to<HeightMapShape3D>(*s);
  334. if (heightmap_shape) {
  335. int heightmap_depth = heightmap_shape->get_map_depth();
  336. int heightmap_width = heightmap_shape->get_map_width();
  337. if (heightmap_depth >= 2 && heightmap_width >= 2) {
  338. const Vector<real_t> &map_data = heightmap_shape->get_map_data();
  339. Vector2 heightmap_gridsize(heightmap_width - 1, heightmap_depth - 1);
  340. Vector3 start = Vector3(heightmap_gridsize.x, 0, heightmap_gridsize.y) * -0.5;
  341. Vector<Vector3> vertex_array;
  342. vertex_array.resize((heightmap_depth - 1) * (heightmap_width - 1) * 6);
  343. Vector3 *vertex_array_ptrw = vertex_array.ptrw();
  344. const real_t *map_data_ptr = map_data.ptr();
  345. int vertex_index = 0;
  346. for (int d = 0; d < heightmap_depth - 1; d++) {
  347. for (int w = 0; w < heightmap_width - 1; w++) {
  348. vertex_array_ptrw[vertex_index] = start + Vector3(w, map_data_ptr[(heightmap_width * d) + w], d);
  349. vertex_array_ptrw[vertex_index + 1] = start + Vector3(w + 1, map_data_ptr[(heightmap_width * d) + w + 1], d);
  350. vertex_array_ptrw[vertex_index + 2] = start + Vector3(w, map_data_ptr[(heightmap_width * d) + heightmap_width + w], d + 1);
  351. vertex_array_ptrw[vertex_index + 3] = start + Vector3(w + 1, map_data_ptr[(heightmap_width * d) + w + 1], d);
  352. vertex_array_ptrw[vertex_index + 4] = start + Vector3(w + 1, map_data_ptr[(heightmap_width * d) + heightmap_width + w + 1], d + 1);
  353. vertex_array_ptrw[vertex_index + 5] = start + Vector3(w, map_data_ptr[(heightmap_width * d) + heightmap_width + w], d + 1);
  354. vertex_index += 6;
  355. }
  356. }
  357. if (vertex_array.size() > 0) {
  358. p_source_geometry_data->add_faces(vertex_array, transform);
  359. }
  360. }
  361. }
  362. }
  363. }
  364. }
  365. }
  366. }
  367. #ifdef MODULE_CSG_ENABLED
  368. void NavMeshGenerator3D::generator_parse_csgshape3d_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node) {
  369. CSGShape3D *csgshape3d = Object::cast_to<CSGShape3D>(p_node);
  370. if (csgshape3d) {
  371. NavigationMesh::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  372. uint32_t parsed_collision_mask = p_navigation_mesh->get_collision_mask();
  373. if (parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES || (parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS && csgshape3d->is_using_collision() && (csgshape3d->get_collision_layer() & parsed_collision_mask)) || parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_BOTH) {
  374. CSGShape3D *csg_shape = Object::cast_to<CSGShape3D>(p_node);
  375. Array meshes = csg_shape->get_meshes();
  376. if (!meshes.is_empty()) {
  377. Ref<Mesh> mesh = meshes[1];
  378. if (mesh.is_valid()) {
  379. p_source_geometry_data->add_mesh(mesh, csg_shape->get_global_transform());
  380. }
  381. }
  382. }
  383. }
  384. }
  385. #endif // MODULE_CSG_ENABLED
  386. #ifdef MODULE_GRIDMAP_ENABLED
  387. void NavMeshGenerator3D::generator_parse_gridmap_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node) {
  388. GridMap *gridmap = Object::cast_to<GridMap>(p_node);
  389. if (gridmap) {
  390. NavigationMesh::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  391. uint32_t parsed_collision_mask = p_navigation_mesh->get_collision_mask();
  392. if (parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES || parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_BOTH) {
  393. Array meshes = gridmap->get_meshes();
  394. Transform3D xform = gridmap->get_global_transform();
  395. for (int i = 0; i < meshes.size(); i += 2) {
  396. Ref<Mesh> mesh = meshes[i + 1];
  397. if (mesh.is_valid()) {
  398. p_source_geometry_data->add_mesh(mesh, xform * (Transform3D)meshes[i]);
  399. }
  400. }
  401. }
  402. else if ((parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationMesh::PARSED_GEOMETRY_BOTH) && (gridmap->get_collision_layer() & parsed_collision_mask)) {
  403. Array shapes = gridmap->get_collision_shapes();
  404. for (int i = 0; i < shapes.size(); i += 2) {
  405. RID shape = shapes[i + 1];
  406. PhysicsServer3D::ShapeType type = PhysicsServer3D::get_singleton()->shape_get_type(shape);
  407. Variant data = PhysicsServer3D::get_singleton()->shape_get_data(shape);
  408. switch (type) {
  409. case PhysicsServer3D::SHAPE_SPHERE: {
  410. real_t radius = data;
  411. Array arr;
  412. arr.resize(RS::ARRAY_MAX);
  413. SphereMesh::create_mesh_array(arr, radius, radius * 2.0);
  414. p_source_geometry_data->add_mesh_array(arr, shapes[i]);
  415. } break;
  416. case PhysicsServer3D::SHAPE_BOX: {
  417. Vector3 extents = data;
  418. Array arr;
  419. arr.resize(RS::ARRAY_MAX);
  420. BoxMesh::create_mesh_array(arr, extents * 2.0);
  421. p_source_geometry_data->add_mesh_array(arr, shapes[i]);
  422. } break;
  423. case PhysicsServer3D::SHAPE_CAPSULE: {
  424. Dictionary dict = data;
  425. real_t radius = dict["radius"];
  426. real_t height = dict["height"];
  427. Array arr;
  428. arr.resize(RS::ARRAY_MAX);
  429. CapsuleMesh::create_mesh_array(arr, radius, height);
  430. p_source_geometry_data->add_mesh_array(arr, shapes[i]);
  431. } break;
  432. case PhysicsServer3D::SHAPE_CYLINDER: {
  433. Dictionary dict = data;
  434. real_t radius = dict["radius"];
  435. real_t height = dict["height"];
  436. Array arr;
  437. arr.resize(RS::ARRAY_MAX);
  438. CylinderMesh::create_mesh_array(arr, radius, radius, height);
  439. p_source_geometry_data->add_mesh_array(arr, shapes[i]);
  440. } break;
  441. case PhysicsServer3D::SHAPE_CONVEX_POLYGON: {
  442. PackedVector3Array vertices = data;
  443. Geometry3D::MeshData md;
  444. Error err = ConvexHullComputer::convex_hull(vertices, md);
  445. if (err == OK) {
  446. PackedVector3Array faces;
  447. for (const Geometry3D::MeshData::Face &face : md.faces) {
  448. for (uint32_t k = 2; k < face.indices.size(); ++k) {
  449. faces.push_back(md.vertices[face.indices[0]]);
  450. faces.push_back(md.vertices[face.indices[k - 1]]);
  451. faces.push_back(md.vertices[face.indices[k]]);
  452. }
  453. }
  454. p_source_geometry_data->add_faces(faces, shapes[i]);
  455. }
  456. } break;
  457. case PhysicsServer3D::SHAPE_CONCAVE_POLYGON: {
  458. Dictionary dict = data;
  459. PackedVector3Array faces = Variant(dict["faces"]);
  460. p_source_geometry_data->add_faces(faces, shapes[i]);
  461. } break;
  462. case PhysicsServer3D::SHAPE_HEIGHTMAP: {
  463. Dictionary dict = data;
  464. ///< dict( int:"width", int:"depth",float:"cell_size", float_array:"heights"
  465. int heightmap_depth = dict["depth"];
  466. int heightmap_width = dict["width"];
  467. if (heightmap_depth >= 2 && heightmap_width >= 2) {
  468. const Vector<real_t> &map_data = dict["heights"];
  469. Vector2 heightmap_gridsize(heightmap_width - 1, heightmap_depth - 1);
  470. Vector3 start = Vector3(heightmap_gridsize.x, 0, heightmap_gridsize.y) * -0.5;
  471. Vector<Vector3> vertex_array;
  472. vertex_array.resize((heightmap_depth - 1) * (heightmap_width - 1) * 6);
  473. Vector3 *vertex_array_ptrw = vertex_array.ptrw();
  474. const real_t *map_data_ptr = map_data.ptr();
  475. int vertex_index = 0;
  476. for (int d = 0; d < heightmap_depth - 1; d++) {
  477. for (int w = 0; w < heightmap_width - 1; w++) {
  478. vertex_array_ptrw[vertex_index] = start + Vector3(w, map_data_ptr[(heightmap_width * d) + w], d);
  479. vertex_array_ptrw[vertex_index + 1] = start + Vector3(w + 1, map_data_ptr[(heightmap_width * d) + w + 1], d);
  480. vertex_array_ptrw[vertex_index + 2] = start + Vector3(w, map_data_ptr[(heightmap_width * d) + heightmap_width + w], d + 1);
  481. vertex_array_ptrw[vertex_index + 3] = start + Vector3(w + 1, map_data_ptr[(heightmap_width * d) + w + 1], d);
  482. vertex_array_ptrw[vertex_index + 4] = start + Vector3(w + 1, map_data_ptr[(heightmap_width * d) + heightmap_width + w + 1], d + 1);
  483. vertex_array_ptrw[vertex_index + 5] = start + Vector3(w, map_data_ptr[(heightmap_width * d) + heightmap_width + w], d + 1);
  484. vertex_index += 6;
  485. }
  486. }
  487. if (vertex_array.size() > 0) {
  488. p_source_geometry_data->add_faces(vertex_array, shapes[i]);
  489. }
  490. }
  491. } break;
  492. default: {
  493. WARN_PRINT("Unsupported collision shape type.");
  494. } break;
  495. }
  496. }
  497. }
  498. }
  499. }
  500. #endif // MODULE_GRIDMAP_ENABLED
  501. void NavMeshGenerator3D::generator_parse_navigationobstacle_node(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_node) {
  502. NavigationObstacle3D *obstacle = Object::cast_to<NavigationObstacle3D>(p_node);
  503. if (obstacle == nullptr) {
  504. return;
  505. }
  506. if (!obstacle->get_affect_navigation_mesh()) {
  507. return;
  508. }
  509. const float elevation = obstacle->get_global_position().y + p_source_geometry_data->root_node_transform.origin.y;
  510. // Prevent non-positive scaling.
  511. const Vector3 safe_scale = obstacle->get_global_basis().get_scale().abs().maxf(0.001);
  512. const float obstacle_radius = obstacle->get_radius();
  513. if (obstacle_radius > 0.0) {
  514. // Radius defined obstacle should be uniformly scaled from obstacle basis max scale axis.
  515. const float scaling_max_value = safe_scale[safe_scale.max_axis_index()];
  516. const Vector3 uniform_max_scale = Vector3(scaling_max_value, scaling_max_value, scaling_max_value);
  517. const Transform3D obstacle_circle_transform = p_source_geometry_data->root_node_transform * Transform3D(Basis().scaled(uniform_max_scale), obstacle->get_global_position());
  518. Vector<Vector3> obstruction_circle_vertices;
  519. // The point of this is that the moving obstacle can make a simple hole in the navigation mesh and affect the pathfinding.
  520. // Without, navigation paths can go directly through the middle of the obstacle and conflict with the avoidance to get agents stuck.
  521. // No place for excessive "round" detail here. Every additional edge adds a high cost for something that needs to be quick, not pretty.
  522. static const int circle_points = 12;
  523. obstruction_circle_vertices.resize(circle_points);
  524. Vector3 *circle_vertices_ptrw = obstruction_circle_vertices.ptrw();
  525. const real_t circle_point_step = Math_TAU / circle_points;
  526. for (int i = 0; i < circle_points; i++) {
  527. const float angle = i * circle_point_step;
  528. circle_vertices_ptrw[i] = obstacle_circle_transform.xform(Vector3(Math::cos(angle) * obstacle_radius, 0.0, Math::sin(angle) * obstacle_radius));
  529. }
  530. p_source_geometry_data->add_projected_obstruction(obstruction_circle_vertices, elevation - obstacle_radius, scaling_max_value * obstacle_radius, obstacle->get_carve_navigation_mesh());
  531. }
  532. // Obstacles are projected to the xz-plane, so only rotation around the y-axis can be taken into account.
  533. const Transform3D node_xform = p_source_geometry_data->root_node_transform * Transform3D(Basis().scaled(safe_scale).rotated(Vector3(0.0, 1.0, 0.0), obstacle->get_global_rotation().y), obstacle->get_global_position());
  534. const Vector<Vector3> &obstacle_vertices = obstacle->get_vertices();
  535. if (obstacle_vertices.is_empty()) {
  536. return;
  537. }
  538. Vector<Vector3> obstruction_shape_vertices;
  539. obstruction_shape_vertices.resize(obstacle_vertices.size());
  540. const Vector3 *obstacle_vertices_ptr = obstacle_vertices.ptr();
  541. Vector3 *obstruction_shape_vertices_ptrw = obstruction_shape_vertices.ptrw();
  542. for (int i = 0; i < obstacle_vertices.size(); i++) {
  543. obstruction_shape_vertices_ptrw[i] = node_xform.xform(obstacle_vertices_ptr[i]);
  544. obstruction_shape_vertices_ptrw[i].y = 0.0;
  545. }
  546. p_source_geometry_data->add_projected_obstruction(obstruction_shape_vertices, elevation, safe_scale.y * obstacle->get_height(), obstacle->get_carve_navigation_mesh());
  547. }
  548. void NavMeshGenerator3D::generator_parse_source_geometry_data(const Ref<NavigationMesh> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData3D> p_source_geometry_data, Node *p_root_node) {
  549. List<Node *> parse_nodes;
  550. if (p_navigation_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_ROOT_NODE_CHILDREN) {
  551. parse_nodes.push_back(p_root_node);
  552. } else {
  553. p_root_node->get_tree()->get_nodes_in_group(p_navigation_mesh->get_source_group_name(), &parse_nodes);
  554. }
  555. Transform3D root_node_transform = Transform3D();
  556. if (Object::cast_to<Node3D>(p_root_node)) {
  557. root_node_transform = Object::cast_to<Node3D>(p_root_node)->get_global_transform().affine_inverse();
  558. }
  559. p_source_geometry_data->clear();
  560. p_source_geometry_data->root_node_transform = root_node_transform;
  561. bool recurse_children = p_navigation_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT;
  562. for (Node *parse_node : parse_nodes) {
  563. generator_parse_geometry_node(p_navigation_mesh, p_source_geometry_data, parse_node, recurse_children);
  564. }
  565. }
  566. void NavMeshGenerator3D::generator_bake_from_source_geometry_data(Ref<NavigationMesh> p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data) {
  567. if (p_navigation_mesh.is_null() || p_source_geometry_data.is_null()) {
  568. return;
  569. }
  570. Vector<float> source_geometry_vertices;
  571. Vector<int> source_geometry_indices;
  572. Vector<NavigationMeshSourceGeometryData3D::ProjectedObstruction> projected_obstructions;
  573. p_source_geometry_data->get_data(
  574. source_geometry_vertices,
  575. source_geometry_indices,
  576. projected_obstructions);
  577. if (source_geometry_vertices.size() < 3 || source_geometry_indices.size() < 3) {
  578. return;
  579. }
  580. rcHeightfield *hf = nullptr;
  581. rcCompactHeightfield *chf = nullptr;
  582. rcContourSet *cset = nullptr;
  583. rcPolyMesh *poly_mesh = nullptr;
  584. rcPolyMeshDetail *detail_mesh = nullptr;
  585. rcContext ctx;
  586. // added to keep track of steps, no functionality right now
  587. String bake_state = "";
  588. bake_state = "Setting up Configuration..."; // step #1
  589. const float *verts = source_geometry_vertices.ptr();
  590. const int nverts = source_geometry_vertices.size() / 3;
  591. const int *tris = source_geometry_indices.ptr();
  592. const int ntris = source_geometry_indices.size() / 3;
  593. float bmin[3], bmax[3];
  594. rcCalcBounds(verts, nverts, bmin, bmax);
  595. rcConfig cfg;
  596. memset(&cfg, 0, sizeof(cfg));
  597. cfg.cs = p_navigation_mesh->get_cell_size();
  598. cfg.ch = p_navigation_mesh->get_cell_height();
  599. if (p_navigation_mesh->get_border_size() > 0.0) {
  600. cfg.borderSize = (int)Math::ceil(p_navigation_mesh->get_border_size() / cfg.cs);
  601. }
  602. cfg.walkableSlopeAngle = p_navigation_mesh->get_agent_max_slope();
  603. cfg.walkableHeight = (int)Math::ceil(p_navigation_mesh->get_agent_height() / cfg.ch);
  604. cfg.walkableClimb = (int)Math::floor(p_navigation_mesh->get_agent_max_climb() / cfg.ch);
  605. cfg.walkableRadius = (int)Math::ceil(p_navigation_mesh->get_agent_radius() / cfg.cs);
  606. cfg.maxEdgeLen = (int)(p_navigation_mesh->get_edge_max_length() / p_navigation_mesh->get_cell_size());
  607. cfg.maxSimplificationError = p_navigation_mesh->get_edge_max_error();
  608. cfg.minRegionArea = (int)(p_navigation_mesh->get_region_min_size() * p_navigation_mesh->get_region_min_size());
  609. cfg.mergeRegionArea = (int)(p_navigation_mesh->get_region_merge_size() * p_navigation_mesh->get_region_merge_size());
  610. cfg.maxVertsPerPoly = (int)p_navigation_mesh->get_vertices_per_polygon();
  611. cfg.detailSampleDist = MAX(p_navigation_mesh->get_cell_size() * p_navigation_mesh->get_detail_sample_distance(), 0.1f);
  612. cfg.detailSampleMaxError = p_navigation_mesh->get_cell_height() * p_navigation_mesh->get_detail_sample_max_error();
  613. if (p_navigation_mesh->get_border_size() > 0.0 && Math::fmod(p_navigation_mesh->get_border_size(), p_navigation_mesh->get_cell_size()) != 0.0) {
  614. WARN_PRINT("Property border_size is ceiled to cell_size voxel units and loses precision.");
  615. }
  616. if (!Math::is_equal_approx((float)cfg.walkableHeight * cfg.ch, p_navigation_mesh->get_agent_height())) {
  617. WARN_PRINT("Property agent_height is ceiled to cell_height voxel units and loses precision.");
  618. }
  619. if (!Math::is_equal_approx((float)cfg.walkableClimb * cfg.ch, p_navigation_mesh->get_agent_max_climb())) {
  620. WARN_PRINT("Property agent_max_climb is floored to cell_height voxel units and loses precision.");
  621. }
  622. if (!Math::is_equal_approx((float)cfg.walkableRadius * cfg.cs, p_navigation_mesh->get_agent_radius())) {
  623. WARN_PRINT("Property agent_radius is ceiled to cell_size voxel units and loses precision.");
  624. }
  625. if (!Math::is_equal_approx((float)cfg.maxEdgeLen * cfg.cs, p_navigation_mesh->get_edge_max_length())) {
  626. WARN_PRINT("Property edge_max_length is rounded to cell_size voxel units and loses precision.");
  627. }
  628. if (!Math::is_equal_approx((float)cfg.minRegionArea, p_navigation_mesh->get_region_min_size() * p_navigation_mesh->get_region_min_size())) {
  629. WARN_PRINT("Property region_min_size is converted to int and loses precision.");
  630. }
  631. if (!Math::is_equal_approx((float)cfg.mergeRegionArea, p_navigation_mesh->get_region_merge_size() * p_navigation_mesh->get_region_merge_size())) {
  632. WARN_PRINT("Property region_merge_size is converted to int and loses precision.");
  633. }
  634. if (!Math::is_equal_approx((float)cfg.maxVertsPerPoly, p_navigation_mesh->get_vertices_per_polygon())) {
  635. WARN_PRINT("Property vertices_per_polygon is converted to int and loses precision.");
  636. }
  637. if (p_navigation_mesh->get_cell_size() * p_navigation_mesh->get_detail_sample_distance() < 0.1f) {
  638. WARN_PRINT("Property detail_sample_distance is clamped to 0.1 world units as the resulting value from multiplying with cell_size is too low.");
  639. }
  640. cfg.bmin[0] = bmin[0];
  641. cfg.bmin[1] = bmin[1];
  642. cfg.bmin[2] = bmin[2];
  643. cfg.bmax[0] = bmax[0];
  644. cfg.bmax[1] = bmax[1];
  645. cfg.bmax[2] = bmax[2];
  646. AABB baking_aabb = p_navigation_mesh->get_filter_baking_aabb();
  647. if (baking_aabb.has_volume()) {
  648. Vector3 baking_aabb_offset = p_navigation_mesh->get_filter_baking_aabb_offset();
  649. cfg.bmin[0] = baking_aabb.position[0] + baking_aabb_offset.x;
  650. cfg.bmin[1] = baking_aabb.position[1] + baking_aabb_offset.y;
  651. cfg.bmin[2] = baking_aabb.position[2] + baking_aabb_offset.z;
  652. cfg.bmax[0] = cfg.bmin[0] + baking_aabb.size[0];
  653. cfg.bmax[1] = cfg.bmin[1] + baking_aabb.size[1];
  654. cfg.bmax[2] = cfg.bmin[2] + baking_aabb.size[2];
  655. }
  656. bake_state = "Calculating grid size..."; // step #2
  657. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  658. // ~30000000 seems to be around sweetspot where Editor baking breaks
  659. if ((cfg.width * cfg.height) > 30000000 && GLOBAL_GET("navigation/baking/use_crash_prevention_checks")) {
  660. ERR_FAIL_MSG("Baking interrupted."
  661. "\nNavigationMesh baking process would likely crash the engine."
  662. "\nSource geometry is suspiciously big for the current Cell Size and Cell Height in the NavMesh Resource bake settings."
  663. "\nIf baking does not crash the engine or fail, the resulting NavigationMesh will create serious pathfinding performance issues."
  664. "\nIt is advised to increase Cell Size and/or Cell Height in the NavMesh Resource bake settings or reduce the size / scale of the source geometry."
  665. "\nIf you would like to try baking anyway, disable the 'navigation/baking/use_crash_prevention_checks' project setting.");
  666. return;
  667. }
  668. bake_state = "Creating heightfield..."; // step #3
  669. hf = rcAllocHeightfield();
  670. ERR_FAIL_NULL(hf);
  671. ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
  672. bake_state = "Marking walkable triangles..."; // step #4
  673. {
  674. Vector<unsigned char> tri_areas;
  675. tri_areas.resize(ntris);
  676. ERR_FAIL_COND(tri_areas.is_empty());
  677. memset(tri_areas.ptrw(), 0, ntris * sizeof(unsigned char));
  678. rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, tri_areas.ptrw());
  679. ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
  680. }
  681. if (p_navigation_mesh->get_filter_low_hanging_obstacles()) {
  682. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
  683. }
  684. if (p_navigation_mesh->get_filter_ledge_spans()) {
  685. rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
  686. }
  687. if (p_navigation_mesh->get_filter_walkable_low_height_spans()) {
  688. rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
  689. }
  690. bake_state = "Constructing compact heightfield..."; // step #5
  691. chf = rcAllocCompactHeightfield();
  692. ERR_FAIL_NULL(chf);
  693. ERR_FAIL_COND(!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf, *chf));
  694. rcFreeHeightField(hf);
  695. hf = nullptr;
  696. // Add obstacles to the source geometry. Those will be affected by e.g. agent_radius.
  697. if (!projected_obstructions.is_empty()) {
  698. for (const NavigationMeshSourceGeometryData3D::ProjectedObstruction &projected_obstruction : projected_obstructions) {
  699. if (projected_obstruction.carve) {
  700. continue;
  701. }
  702. if (projected_obstruction.vertices.is_empty() || projected_obstruction.vertices.size() % 3 != 0) {
  703. continue;
  704. }
  705. const float *projected_obstruction_verts = projected_obstruction.vertices.ptr();
  706. const int projected_obstruction_nverts = projected_obstruction.vertices.size() / 3;
  707. rcMarkConvexPolyArea(&ctx, projected_obstruction_verts, projected_obstruction_nverts, projected_obstruction.elevation, projected_obstruction.elevation + projected_obstruction.height, RC_NULL_AREA, *chf);
  708. }
  709. }
  710. bake_state = "Eroding walkable area..."; // step #6
  711. ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
  712. // Carve obstacles to the eroded geometry. Those will NOT be affected by e.g. agent_radius because that step is already done.
  713. if (!projected_obstructions.is_empty()) {
  714. for (const NavigationMeshSourceGeometryData3D::ProjectedObstruction &projected_obstruction : projected_obstructions) {
  715. if (!projected_obstruction.carve) {
  716. continue;
  717. }
  718. if (projected_obstruction.vertices.is_empty() || projected_obstruction.vertices.size() % 3 != 0) {
  719. continue;
  720. }
  721. const float *projected_obstruction_verts = projected_obstruction.vertices.ptr();
  722. const int projected_obstruction_nverts = projected_obstruction.vertices.size() / 3;
  723. rcMarkConvexPolyArea(&ctx, projected_obstruction_verts, projected_obstruction_nverts, projected_obstruction.elevation, projected_obstruction.elevation + projected_obstruction.height, RC_NULL_AREA, *chf);
  724. }
  725. }
  726. bake_state = "Partitioning..."; // step #7
  727. if (p_navigation_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
  728. ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf));
  729. ERR_FAIL_COND(!rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea));
  730. } else if (p_navigation_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_MONOTONE) {
  731. ERR_FAIL_COND(!rcBuildRegionsMonotone(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea));
  732. } else {
  733. ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea));
  734. }
  735. bake_state = "Creating contours..."; // step #8
  736. cset = rcAllocContourSet();
  737. ERR_FAIL_NULL(cset);
  738. ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
  739. bake_state = "Creating polymesh..."; // step #9
  740. poly_mesh = rcAllocPolyMesh();
  741. ERR_FAIL_NULL(poly_mesh);
  742. ERR_FAIL_COND(!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *poly_mesh));
  743. detail_mesh = rcAllocPolyMeshDetail();
  744. ERR_FAIL_NULL(detail_mesh);
  745. ERR_FAIL_COND(!rcBuildPolyMeshDetail(&ctx, *poly_mesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *detail_mesh));
  746. rcFreeCompactHeightfield(chf);
  747. chf = nullptr;
  748. rcFreeContourSet(cset);
  749. cset = nullptr;
  750. bake_state = "Converting to native navigation mesh..."; // step #10
  751. Vector<Vector3> nav_vertices;
  752. Vector<Vector<int>> nav_polygons;
  753. HashMap<Vector3, int> recast_vertex_to_native_index;
  754. LocalVector<int> recast_index_to_native_index;
  755. recast_index_to_native_index.resize(detail_mesh->nverts);
  756. for (int i = 0; i < detail_mesh->nverts; i++) {
  757. const float *v = &detail_mesh->verts[i * 3];
  758. const Vector3 vertex = Vector3(v[0], v[1], v[2]);
  759. int *existing_index_ptr = recast_vertex_to_native_index.getptr(vertex);
  760. if (!existing_index_ptr) {
  761. int new_index = recast_vertex_to_native_index.size();
  762. recast_index_to_native_index[i] = new_index;
  763. recast_vertex_to_native_index[vertex] = new_index;
  764. nav_vertices.push_back(vertex);
  765. } else {
  766. recast_index_to_native_index[i] = *existing_index_ptr;
  767. }
  768. }
  769. for (int i = 0; i < detail_mesh->nmeshes; i++) {
  770. const unsigned int *detail_mesh_m = &detail_mesh->meshes[i * 4];
  771. const unsigned int detail_mesh_bverts = detail_mesh_m[0];
  772. const unsigned int detail_mesh_m_btris = detail_mesh_m[2];
  773. const unsigned int detail_mesh_ntris = detail_mesh_m[3];
  774. const unsigned char *detail_mesh_tris = &detail_mesh->tris[detail_mesh_m_btris * 4];
  775. for (unsigned int j = 0; j < detail_mesh_ntris; j++) {
  776. Vector<int> nav_indices;
  777. nav_indices.resize(3);
  778. // Polygon order in recast is opposite than godot's
  779. int index1 = ((int)(detail_mesh_bverts + detail_mesh_tris[j * 4 + 0]));
  780. int index2 = ((int)(detail_mesh_bverts + detail_mesh_tris[j * 4 + 2]));
  781. int index3 = ((int)(detail_mesh_bverts + detail_mesh_tris[j * 4 + 1]));
  782. nav_indices.write[0] = recast_index_to_native_index[index1];
  783. nav_indices.write[1] = recast_index_to_native_index[index2];
  784. nav_indices.write[2] = recast_index_to_native_index[index3];
  785. nav_polygons.push_back(nav_indices);
  786. }
  787. }
  788. p_navigation_mesh->set_data(nav_vertices, nav_polygons);
  789. bake_state = "Cleanup..."; // step #11
  790. rcFreePolyMesh(poly_mesh);
  791. poly_mesh = nullptr;
  792. rcFreePolyMeshDetail(detail_mesh);
  793. detail_mesh = nullptr;
  794. bake_state = "Baking finished."; // step #12
  795. }
  796. bool NavMeshGenerator3D::generator_emit_callback(const Callable &p_callback) {
  797. ERR_FAIL_COND_V(!p_callback.is_valid(), false);
  798. Callable::CallError ce;
  799. Variant result;
  800. p_callback.callp(nullptr, 0, result, ce);
  801. return ce.error == Callable::CallError::CALL_OK;
  802. }
  803. RID NavMeshGenerator3D::source_geometry_parser_create() {
  804. RWLockWrite write_lock(generator_rid_rwlock);
  805. RID rid = generator_parser_owner.make_rid();
  806. NavMeshGeometryParser3D *parser = generator_parser_owner.get_or_null(rid);
  807. parser->self = rid;
  808. generator_parsers.push_back(parser);
  809. return rid;
  810. }
  811. void NavMeshGenerator3D::source_geometry_parser_set_callback(RID p_parser, const Callable &p_callback) {
  812. RWLockWrite write_lock(generator_rid_rwlock);
  813. NavMeshGeometryParser3D *parser = generator_parser_owner.get_or_null(p_parser);
  814. ERR_FAIL_NULL(parser);
  815. parser->callback = p_callback;
  816. }
  817. bool NavMeshGenerator3D::owns(RID p_object) {
  818. RWLockRead read_lock(generator_rid_rwlock);
  819. return generator_parser_owner.owns(p_object);
  820. }
  821. void NavMeshGenerator3D::free(RID p_object) {
  822. RWLockWrite write_lock(generator_rid_rwlock);
  823. if (generator_parser_owner.owns(p_object)) {
  824. NavMeshGeometryParser3D *parser = generator_parser_owner.get_or_null(p_object);
  825. generator_parsers.erase(parser);
  826. generator_parser_owner.free(p_object);
  827. } else {
  828. ERR_PRINT("Attempted to free a NavMeshGenerator3D RID that did not exist (or was already freed).");
  829. }
  830. }
  831. #endif // _3D_DISABLED