bsp_tree.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*************************************************************************/
  2. /* bsp_tree.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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 "bsp_tree.h"
  31. #include "core/error_macros.h"
  32. #include "core/print_string.h"
  33. void BSP_Tree::from_aabb(const AABB &p_aabb) {
  34. planes.clear();
  35. for (int i = 0; i < 3; i++) {
  36. Vector3 n;
  37. n[i] = 1;
  38. planes.push_back(Plane(n, p_aabb.position[i] + p_aabb.size[i]));
  39. planes.push_back(Plane(-n, -p_aabb.position[i]));
  40. }
  41. nodes.clear();
  42. for (int i = 0; i < 6; i++) {
  43. Node n;
  44. n.plane = i;
  45. n.under = (i == 0) ? UNDER_LEAF : i - 1;
  46. n.over = OVER_LEAF;
  47. nodes.push_back(n);
  48. }
  49. aabb = p_aabb;
  50. error_radius = 0;
  51. }
  52. Vector<BSP_Tree::Node> BSP_Tree::get_nodes() const {
  53. return nodes;
  54. }
  55. Vector<Plane> BSP_Tree::get_planes() const {
  56. return planes;
  57. }
  58. AABB BSP_Tree::get_aabb() const {
  59. return aabb;
  60. }
  61. int BSP_Tree::_get_points_inside(int p_node, const Vector3 *p_points, int *p_indices, const Vector3 &p_center, const Vector3 &p_half_extents, int p_indices_count) const {
  62. const Node *node = &nodes[p_node];
  63. const Plane &p = planes[node->plane];
  64. Vector3 min(
  65. (p.normal.x > 0) ? -p_half_extents.x : p_half_extents.x,
  66. (p.normal.y > 0) ? -p_half_extents.y : p_half_extents.y,
  67. (p.normal.z > 0) ? -p_half_extents.z : p_half_extents.z);
  68. Vector3 max = -min;
  69. max += p_center;
  70. min += p_center;
  71. real_t dist_min = p.distance_to(min);
  72. real_t dist_max = p.distance_to(max);
  73. if ((dist_min * dist_max) < CMP_EPSILON) { //intersection, test point by point
  74. int under_count = 0;
  75. //sort points, so the are under first, over last
  76. for (int i = 0; i < p_indices_count; i++) {
  77. int index = p_indices[i];
  78. if (p.is_point_over(p_points[index])) {
  79. // kind of slow (but cache friendly), should try something else,
  80. // but this is a corner case most of the time
  81. for (int j = index; j < p_indices_count - 1; j++)
  82. p_indices[j] = p_indices[j + 1];
  83. p_indices[p_indices_count - 1] = index;
  84. } else {
  85. under_count++;
  86. }
  87. }
  88. int total = 0;
  89. if (under_count > 0) {
  90. if (node->under == UNDER_LEAF) {
  91. total += under_count;
  92. } else {
  93. total += _get_points_inside(node->under, p_points, p_indices, p_center, p_half_extents, under_count);
  94. }
  95. }
  96. if (under_count != p_indices_count) {
  97. if (node->over == OVER_LEAF) {
  98. //total+=0 //if they are over an OVER_LEAF, they are outside the model
  99. } else {
  100. total += _get_points_inside(node->over, p_points, &p_indices[under_count], p_center, p_half_extents, p_indices_count - under_count);
  101. }
  102. }
  103. return total;
  104. } else if (dist_min > 0) { //all points over plane
  105. if (node->over == OVER_LEAF) {
  106. return 0; // all these points are not visible
  107. }
  108. return _get_points_inside(node->over, p_points, p_indices, p_center, p_half_extents, p_indices_count);
  109. } else { //all points behind plane
  110. if (node->under == UNDER_LEAF) {
  111. return p_indices_count; // all these points are visible
  112. }
  113. return _get_points_inside(node->under, p_points, p_indices, p_center, p_half_extents, p_indices_count);
  114. }
  115. }
  116. int BSP_Tree::get_points_inside(const Vector3 *p_points, int p_point_count) const {
  117. if (nodes.size() == 0)
  118. return 0;
  119. #if 1
  120. //this version is easier to debug, and and MUCH faster in real world cases
  121. int pass_count = 0;
  122. const Node *nodesptr = &nodes[0];
  123. const Plane *planesptr = &planes[0];
  124. int node_count = nodes.size();
  125. if (node_count == 0) // no nodes!
  126. return 0;
  127. for (int i = 0; i < p_point_count; i++) {
  128. const Vector3 &point = p_points[i];
  129. if (!aabb.has_point(point)) {
  130. continue;
  131. }
  132. int idx = node_count - 1;
  133. bool pass = false;
  134. while (true) {
  135. if (idx == OVER_LEAF) {
  136. pass = false;
  137. break;
  138. } else if (idx == UNDER_LEAF) {
  139. pass = true;
  140. break;
  141. }
  142. #ifdef DEBUG_ENABLED
  143. int plane_count = planes.size();
  144. uint16_t plane = nodesptr[idx].plane;
  145. ERR_FAIL_UNSIGNED_INDEX_V(plane, plane_count, false);
  146. #endif
  147. idx = planesptr[nodesptr[idx].plane].is_point_over(point) ? nodes[idx].over : nodes[idx].under;
  148. #ifdef DEBUG_ENABLED
  149. ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false);
  150. #endif
  151. }
  152. if (pass)
  153. pass_count++;
  154. }
  155. return pass_count;
  156. #else
  157. //this version scales better but it's slower for real world cases
  158. int *indices = (int *)alloca(p_point_count * sizeof(int));
  159. AABB bounds;
  160. for (int i = 0; i < p_point_count; i++) {
  161. indices[i] = i;
  162. if (i == 0)
  163. bounds.pos = p_points[i];
  164. else
  165. bounds.expand_to(p_points[i]);
  166. }
  167. Vector3 half_extents = bounds.size / 2.0;
  168. return _get_points_inside(nodes.size() + 1, p_points, indices, bounds.pos + half_extents, half_extents, p_point_count);
  169. #endif
  170. }
  171. bool BSP_Tree::point_is_inside(const Vector3 &p_point) const {
  172. if (!aabb.has_point(p_point)) {
  173. return false;
  174. }
  175. int node_count = nodes.size();
  176. if (node_count == 0) // no nodes!
  177. return false;
  178. const Node *nodesptr = &nodes[0];
  179. const Plane *planesptr = &planes[0];
  180. int idx = node_count - 1;
  181. while (true) {
  182. if (idx == OVER_LEAF) {
  183. return false;
  184. }
  185. if (idx == UNDER_LEAF) {
  186. return true;
  187. }
  188. #ifdef DEBUG_ENABLED
  189. int plane_count = planes.size();
  190. uint16_t plane = nodesptr[idx].plane;
  191. ERR_FAIL_UNSIGNED_INDEX_V(plane, plane_count, false);
  192. #endif
  193. bool over = planesptr[nodesptr[idx].plane].is_point_over(p_point);
  194. idx = over ? nodes[idx].over : nodes[idx].under;
  195. #ifdef DEBUG_ENABLED
  196. ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false);
  197. #endif
  198. }
  199. }
  200. static int _bsp_find_best_half_plane(const Face3 *p_faces, const Vector<int> &p_indices, real_t p_tolerance) {
  201. int ic = p_indices.size();
  202. const int *indices = p_indices.ptr();
  203. int best_plane = -1;
  204. real_t best_plane_cost = 1e20;
  205. // Loop to find the polygon that best divides the set.
  206. for (int i = 0; i < ic; i++) {
  207. const Face3 &f = p_faces[indices[i]];
  208. Plane p = f.get_plane();
  209. int num_over = 0, num_under = 0, num_spanning = 0;
  210. for (int j = 0; j < ic; j++) {
  211. if (i == j)
  212. continue;
  213. const Face3 &g = p_faces[indices[j]];
  214. int over = 0, under = 0;
  215. for (int k = 0; k < 3; k++) {
  216. real_t d = p.distance_to(g.vertex[j]);
  217. if (Math::abs(d) > p_tolerance) {
  218. if (d > 0)
  219. over++;
  220. else
  221. under++;
  222. }
  223. }
  224. if (over && under)
  225. num_spanning++;
  226. else if (over)
  227. num_over++;
  228. else
  229. num_under++;
  230. }
  231. //real_t split_cost = num_spanning / (real_t) face_count;
  232. real_t relation = Math::abs(num_over - num_under) / (real_t)ic;
  233. // being honest, i never found a way to add split cost to the mix in a meaninguful way
  234. // in this engine, also, will likely be ignored anyway
  235. real_t plane_cost = /*split_cost +*/ relation;
  236. //printf("plane %i, %i over, %i under, %i spanning, cost is %g\n",i,num_over,num_under,num_spanning,plane_cost);
  237. if (plane_cost < best_plane_cost) {
  238. best_plane = i;
  239. best_plane_cost = plane_cost;
  240. }
  241. }
  242. return best_plane;
  243. }
  244. static int _bsp_create_node(const Face3 *p_faces, const Vector<int> &p_indices, Vector<Plane> &p_planes, Vector<BSP_Tree::Node> &p_nodes, real_t p_tolerance) {
  245. ERR_FAIL_COND_V(p_nodes.size() == BSP_Tree::MAX_NODES, -1);
  246. // should not reach here
  247. ERR_FAIL_COND_V(p_indices.size() == 0, -1)
  248. int ic = p_indices.size();
  249. const int *indices = p_indices.ptr();
  250. int divisor_idx = _bsp_find_best_half_plane(p_faces, p_indices, p_tolerance);
  251. // returned error
  252. ERR_FAIL_COND_V(divisor_idx < 0, -1);
  253. Vector<int> faces_over;
  254. Vector<int> faces_under;
  255. Plane divisor_plane = p_faces[indices[divisor_idx]].get_plane();
  256. for (int i = 0; i < ic; i++) {
  257. if (i == divisor_idx)
  258. continue;
  259. const Face3 &f = p_faces[indices[i]];
  260. /*
  261. if (f.get_plane().is_almost_like(divisor_plane))
  262. continue;
  263. */
  264. int over_count = 0;
  265. int under_count = 0;
  266. for (int j = 0; j < 3; j++) {
  267. real_t d = divisor_plane.distance_to(f.vertex[j]);
  268. if (Math::abs(d) > p_tolerance) {
  269. if (d > 0)
  270. over_count++;
  271. else
  272. under_count++;
  273. }
  274. }
  275. if (over_count)
  276. faces_over.push_back(indices[i]);
  277. if (under_count)
  278. faces_under.push_back(indices[i]);
  279. }
  280. uint16_t over_idx = BSP_Tree::OVER_LEAF, under_idx = BSP_Tree::UNDER_LEAF;
  281. if (faces_over.size() > 0) { //have facess above?
  282. int idx = _bsp_create_node(p_faces, faces_over, p_planes, p_nodes, p_tolerance);
  283. if (idx >= 0)
  284. over_idx = idx;
  285. }
  286. if (faces_under.size() > 0) { //have facess above?
  287. int idx = _bsp_create_node(p_faces, faces_under, p_planes, p_nodes, p_tolerance);
  288. if (idx >= 0)
  289. under_idx = idx;
  290. }
  291. /* Create the node */
  292. // find existing divisor plane
  293. int divisor_plane_idx = -1;
  294. for (int i = 0; i < p_planes.size(); i++) {
  295. if (p_planes[i].is_almost_like(divisor_plane)) {
  296. divisor_plane_idx = i;
  297. break;
  298. }
  299. }
  300. if (divisor_plane_idx == -1) {
  301. ERR_FAIL_COND_V(p_planes.size() == BSP_Tree::MAX_PLANES, -1);
  302. divisor_plane_idx = p_planes.size();
  303. p_planes.push_back(divisor_plane);
  304. }
  305. BSP_Tree::Node node;
  306. node.plane = divisor_plane_idx;
  307. node.under = under_idx;
  308. node.over = over_idx;
  309. p_nodes.push_back(node);
  310. return p_nodes.size() - 1;
  311. }
  312. BSP_Tree::operator Variant() const {
  313. Dictionary d;
  314. d["error_radius"] = error_radius;
  315. Vector<real_t> plane_values;
  316. plane_values.resize(planes.size() * 4);
  317. for (int i = 0; i < planes.size(); i++) {
  318. plane_values.write[i * 4 + 0] = planes[i].normal.x;
  319. plane_values.write[i * 4 + 1] = planes[i].normal.y;
  320. plane_values.write[i * 4 + 2] = planes[i].normal.z;
  321. plane_values.write[i * 4 + 3] = planes[i].d;
  322. }
  323. d["planes"] = plane_values;
  324. PoolVector<int> dst_nodes;
  325. dst_nodes.resize(nodes.size() * 3);
  326. for (int i = 0; i < nodes.size(); i++) {
  327. dst_nodes.set(i * 3 + 0, nodes[i].over);
  328. dst_nodes.set(i * 3 + 1, nodes[i].under);
  329. dst_nodes.set(i * 3 + 2, nodes[i].plane);
  330. }
  331. d["nodes"] = dst_nodes;
  332. d["aabb"] = aabb;
  333. return Variant(d);
  334. }
  335. BSP_Tree::BSP_Tree() {
  336. }
  337. BSP_Tree::BSP_Tree(const Variant &p_variant) {
  338. Dictionary d = p_variant;
  339. ERR_FAIL_COND(!d.has("nodes"));
  340. ERR_FAIL_COND(!d.has("planes"));
  341. ERR_FAIL_COND(!d.has("aabb"));
  342. ERR_FAIL_COND(!d.has("error_radius"));
  343. PoolVector<int> src_nodes = d["nodes"];
  344. ERR_FAIL_COND(src_nodes.size() % 3);
  345. if (d["planes"].get_type() == Variant::POOL_REAL_ARRAY) {
  346. PoolVector<real_t> src_planes = d["planes"];
  347. int plane_count = src_planes.size();
  348. ERR_FAIL_COND(plane_count % 4);
  349. planes.resize(plane_count / 4);
  350. if (plane_count) {
  351. PoolVector<real_t>::Read r = src_planes.read();
  352. for (int i = 0; i < plane_count / 4; i++) {
  353. planes.write[i].normal.x = r[i * 4 + 0];
  354. planes.write[i].normal.y = r[i * 4 + 1];
  355. planes.write[i].normal.z = r[i * 4 + 2];
  356. planes.write[i].d = r[i * 4 + 3];
  357. }
  358. }
  359. } else {
  360. planes = d["planes"];
  361. }
  362. error_radius = d["error"];
  363. aabb = d["aabb"];
  364. //int node_count = src_nodes.size();
  365. nodes.resize(src_nodes.size() / 3);
  366. PoolVector<int>::Read r = src_nodes.read();
  367. for (int i = 0; i < nodes.size(); i++) {
  368. nodes.write[i].over = r[i * 3 + 0];
  369. nodes.write[i].under = r[i * 3 + 1];
  370. nodes.write[i].plane = r[i * 3 + 2];
  371. }
  372. }
  373. BSP_Tree::BSP_Tree(const PoolVector<Face3> &p_faces, real_t p_error_radius) {
  374. // compute aabb
  375. int face_count = p_faces.size();
  376. PoolVector<Face3>::Read faces_r = p_faces.read();
  377. const Face3 *facesptr = faces_r.ptr();
  378. bool first = true;
  379. Vector<int> indices;
  380. for (int i = 0; i < face_count; i++) {
  381. const Face3 &f = facesptr[i];
  382. if (f.is_degenerate())
  383. continue;
  384. for (int j = 0; j < 3; j++) {
  385. if (first) {
  386. aabb.position = f.vertex[0];
  387. first = false;
  388. } else {
  389. aabb.expand_to(f.vertex[j]);
  390. }
  391. }
  392. indices.push_back(i);
  393. }
  394. ERR_FAIL_COND(aabb.has_no_area());
  395. int top = _bsp_create_node(faces_r.ptr(), indices, planes, nodes, aabb.get_longest_axis_size() * 0.0001);
  396. if (top < 0) {
  397. nodes.clear();
  398. planes.clear();
  399. ERR_FAIL_COND(top < 0);
  400. }
  401. error_radius = p_error_radius;
  402. }
  403. BSP_Tree::BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const AABB &p_aabb, real_t p_error_radius) :
  404. nodes(p_nodes),
  405. planes(p_planes),
  406. aabb(p_aabb),
  407. error_radius(p_error_radius) {
  408. }
  409. BSP_Tree::~BSP_Tree() {
  410. }