bsp_tree.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /*************************************************************************/
  2. /* bsp_tree.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "error_macros.h"
  32. #include "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.pos[i] + p_aabb.size[i]));
  39. planes.push_back(Plane(-n, -p_aabb.pos[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. float dist_min = p.distance_to(min);
  72. float 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 if (dist_min <= 0) { //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. return 0;
  116. }
  117. int BSP_Tree::get_points_inside(const Vector3 *p_points, int p_point_count) const {
  118. if (nodes.size() == 0)
  119. return 0;
  120. #if 1
  121. //this version is easier to debug, and and MUCH faster in real world cases
  122. int pass_count = 0;
  123. const Node *nodesptr = &nodes[0];
  124. const Plane *planesptr = &planes[0];
  125. int plane_count = planes.size();
  126. int node_count = nodes.size();
  127. if (node_count == 0) // no nodes!
  128. return 0;
  129. for (int i = 0; i < p_point_count; i++) {
  130. const Vector3 &point = p_points[i];
  131. if (!aabb.has_point(point)) {
  132. continue;
  133. }
  134. int idx = node_count - 1;
  135. bool pass = false;
  136. while (true) {
  137. if (idx == OVER_LEAF) {
  138. pass = false;
  139. break;
  140. } else if (idx == UNDER_LEAF) {
  141. pass = true;
  142. break;
  143. }
  144. uint16_t plane = nodesptr[idx].plane;
  145. #ifdef DEBUG_ENABLED
  146. ERR_FAIL_INDEX_V(plane, plane_count, false);
  147. #endif
  148. idx = planesptr[nodesptr[idx].plane].is_point_over(point) ? nodes[idx].over : nodes[idx].under;
  149. #ifdef DEBUG_ENABLED
  150. ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false);
  151. #endif
  152. }
  153. if (pass)
  154. pass_count++;
  155. }
  156. return pass_count;
  157. #else
  158. //this version scales better but it's slower for real world cases
  159. int *indices = (int *)alloca(p_point_count * sizeof(int));
  160. AABB bounds;
  161. for (int i = 0; i < p_point_count; i++) {
  162. indices[i] = i;
  163. if (i == 0)
  164. bounds.pos = p_points[i];
  165. else
  166. bounds.expand_to(p_points[i]);
  167. }
  168. Vector3 half_extents = bounds.size / 2.0;
  169. return _get_points_inside(nodes.size() + 1, p_points, indices, bounds.pos + half_extents, half_extents, p_point_count);
  170. #endif
  171. }
  172. bool BSP_Tree::point_is_inside(const Vector3 &p_point) const {
  173. if (!aabb.has_point(p_point)) {
  174. return false;
  175. }
  176. int node_count = nodes.size();
  177. if (node_count == 0) // no nodes!
  178. return false;
  179. const Node *nodesptr = &nodes[0];
  180. const Plane *planesptr = &planes[0];
  181. int plane_count = planes.size();
  182. int idx = node_count - 1;
  183. int steps = 0;
  184. while (true) {
  185. if (idx == OVER_LEAF) {
  186. return false;
  187. }
  188. if (idx == UNDER_LEAF) {
  189. return true;
  190. }
  191. uint16_t plane = nodesptr[idx].plane;
  192. #ifdef DEBUG_ENABLED
  193. ERR_FAIL_INDEX_V(plane, plane_count, false);
  194. #endif
  195. bool over = planesptr[nodesptr[idx].plane].is_point_over(p_point);
  196. idx = over ? nodes[idx].over : nodes[idx].under;
  197. #ifdef DEBUG_ENABLED
  198. ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false);
  199. #endif
  200. steps++;
  201. }
  202. return false;
  203. }
  204. static int _bsp_find_best_half_plane(const Face3 *p_faces, const Vector<int> &p_indices, float p_tolerance) {
  205. int ic = p_indices.size();
  206. const int *indices = p_indices.ptr();
  207. int best_plane = -1;
  208. float best_plane_cost = 1e20;
  209. // Loop to find the polygon that best divides the set.
  210. for (int i = 0; i < ic; i++) {
  211. const Face3 &f = p_faces[indices[i]];
  212. Plane p = f.get_plane();
  213. int num_over = 0, num_under = 0, num_spanning = 0;
  214. for (int j = 0; j < ic; j++) {
  215. if (i == j)
  216. continue;
  217. const Face3 &g = p_faces[indices[j]];
  218. int over = 0, under = 0;
  219. for (int k = 0; k < 3; k++) {
  220. float d = p.distance_to(g.vertex[j]);
  221. if (Math::abs(d) > p_tolerance) {
  222. if (d > 0)
  223. over++;
  224. else
  225. under++;
  226. }
  227. }
  228. if (over && under)
  229. num_spanning++;
  230. else if (over)
  231. num_over++;
  232. else
  233. num_under++;
  234. }
  235. //double split_cost = num_spanning / (double) face_count;
  236. double relation = Math::abs(num_over - num_under) / (double)ic;
  237. // being honest, i never found a way to add split cost to the mix in a meaninguful way
  238. // in this engine, also, will likely be ignored anyway
  239. double plane_cost = /*split_cost +*/ relation;
  240. //printf("plane %i, %i over, %i under, %i spanning, cost is %g\n",i,num_over,num_under,num_spanning,plane_cost);
  241. if (plane_cost < best_plane_cost) {
  242. best_plane = i;
  243. best_plane_cost = plane_cost;
  244. }
  245. }
  246. return best_plane;
  247. }
  248. static int _bsp_create_node(const Face3 *p_faces, const Vector<int> &p_indices, Vector<Plane> &p_planes, Vector<BSP_Tree::Node> &p_nodes, float p_tolerance) {
  249. ERR_FAIL_COND_V(p_nodes.size() == BSP_Tree::MAX_NODES, -1);
  250. // should not reach here
  251. ERR_FAIL_COND_V(p_indices.size() == 0, -1)
  252. int ic = p_indices.size();
  253. const int *indices = p_indices.ptr();
  254. int divisor_idx = _bsp_find_best_half_plane(p_faces, p_indices, p_tolerance);
  255. // returned error
  256. ERR_FAIL_COND_V(divisor_idx < 0, -1);
  257. Vector<int> faces_over;
  258. Vector<int> faces_under;
  259. Plane divisor_plane = p_faces[indices[divisor_idx]].get_plane();
  260. for (int i = 0; i < ic; i++) {
  261. if (i == divisor_idx)
  262. continue;
  263. const Face3 &f = p_faces[indices[i]];
  264. //if (f.get_plane().is_almost_like(divisor_plane))
  265. // continue;
  266. int over_count = 0;
  267. int under_count = 0;
  268. for (int j = 0; j < 3; j++) {
  269. float d = divisor_plane.distance_to(f.vertex[j]);
  270. if (Math::abs(d) > p_tolerance) {
  271. if (d > 0)
  272. over_count++;
  273. else
  274. under_count++;
  275. }
  276. }
  277. if (over_count)
  278. faces_over.push_back(indices[i]);
  279. if (under_count)
  280. faces_under.push_back(indices[i]);
  281. }
  282. uint16_t over_idx = BSP_Tree::OVER_LEAF, under_idx = BSP_Tree::UNDER_LEAF;
  283. if (faces_over.size() > 0) { //have facess above?
  284. int idx = _bsp_create_node(p_faces, faces_over, p_planes, p_nodes, p_tolerance);
  285. if (idx >= 0)
  286. over_idx = idx;
  287. }
  288. if (faces_under.size() > 0) { //have facess above?
  289. int idx = _bsp_create_node(p_faces, faces_under, p_planes, p_nodes, p_tolerance);
  290. if (idx >= 0)
  291. under_idx = idx;
  292. }
  293. /* Create the node */
  294. // find existing divisor plane
  295. int divisor_plane_idx = -1;
  296. for (int i = 0; i < p_planes.size(); i++) {
  297. if (p_planes[i].is_almost_like(divisor_plane)) {
  298. divisor_plane_idx = i;
  299. break;
  300. }
  301. }
  302. if (divisor_plane_idx == -1) {
  303. ERR_FAIL_COND_V(p_planes.size() == BSP_Tree::MAX_PLANES, -1);
  304. divisor_plane_idx = p_planes.size();
  305. p_planes.push_back(divisor_plane);
  306. }
  307. BSP_Tree::Node node;
  308. node.plane = divisor_plane_idx;
  309. node.under = under_idx;
  310. node.over = over_idx;
  311. p_nodes.push_back(node);
  312. return p_nodes.size() - 1;
  313. }
  314. BSP_Tree::operator Variant() const {
  315. Dictionary d;
  316. d["error_radius"] = error_radius;
  317. Vector<float> plane_values;
  318. plane_values.resize(planes.size() * 4);
  319. for (int i = 0; i < planes.size(); i++) {
  320. plane_values[i * 4 + 0] = planes[i].normal.x;
  321. plane_values[i * 4 + 1] = planes[i].normal.y;
  322. plane_values[i * 4 + 2] = planes[i].normal.z;
  323. plane_values[i * 4 + 3] = planes[i].d;
  324. }
  325. d["planes"] = plane_values;
  326. DVector<int> dst_nodes;
  327. dst_nodes.resize(nodes.size() * 3);
  328. for (int i = 0; i < nodes.size(); i++) {
  329. dst_nodes.set(i * 3 + 0, nodes[i].over);
  330. dst_nodes.set(i * 3 + 1, nodes[i].under);
  331. dst_nodes.set(i * 3 + 2, nodes[i].plane);
  332. }
  333. d["nodes"] = dst_nodes;
  334. d["aabb"] = aabb;
  335. return Variant(d);
  336. }
  337. BSP_Tree::BSP_Tree() {
  338. }
  339. BSP_Tree::BSP_Tree(const Variant &p_variant) {
  340. Dictionary d = p_variant;
  341. ERR_FAIL_COND(!d.has("nodes"));
  342. ERR_FAIL_COND(!d.has("planes"));
  343. ERR_FAIL_COND(!d.has("aabb"));
  344. ERR_FAIL_COND(!d.has("error_radius"));
  345. DVector<int> src_nodes = d["nodes"];
  346. ERR_FAIL_COND(src_nodes.size() % 3);
  347. if (d["planes"].get_type() == Variant::REAL_ARRAY) {
  348. DVector<float> src_planes = d["planes"];
  349. int plane_count = src_planes.size();
  350. ERR_FAIL_COND(plane_count % 4);
  351. planes.resize(plane_count / 4);
  352. if (plane_count) {
  353. DVector<float>::Read r = src_planes.read();
  354. for (int i = 0; i < plane_count / 4; i++) {
  355. planes[i].normal.x = r[i * 4 + 0];
  356. planes[i].normal.y = r[i * 4 + 1];
  357. planes[i].normal.z = r[i * 4 + 2];
  358. planes[i].d = r[i * 4 + 3];
  359. }
  360. }
  361. } else {
  362. planes = d["planes"];
  363. }
  364. error_radius = d["error"];
  365. aabb = d["aabb"];
  366. // int node_count = src_nodes.size();
  367. nodes.resize(src_nodes.size() / 3);
  368. DVector<int>::Read r = src_nodes.read();
  369. for (int i = 0; i < nodes.size(); i++) {
  370. nodes[i].over = r[i * 3 + 0];
  371. nodes[i].under = r[i * 3 + 1];
  372. nodes[i].plane = r[i * 3 + 2];
  373. }
  374. }
  375. BSP_Tree::BSP_Tree(const DVector<Face3> &p_faces, float p_error_radius) {
  376. // compute aabb
  377. int face_count = p_faces.size();
  378. DVector<Face3>::Read faces_r = p_faces.read();
  379. const Face3 *facesptr = faces_r.ptr();
  380. bool first = true;
  381. Vector<int> indices;
  382. for (int i = 0; i < face_count; i++) {
  383. const Face3 &f = facesptr[i];
  384. if (f.is_degenerate())
  385. continue;
  386. for (int j = 0; j < 3; j++) {
  387. if (first) {
  388. aabb.pos = f.vertex[0];
  389. first = false;
  390. } else {
  391. aabb.expand_to(f.vertex[j]);
  392. }
  393. }
  394. indices.push_back(i);
  395. }
  396. ERR_FAIL_COND(aabb.has_no_area());
  397. int top = _bsp_create_node(faces_r.ptr(), indices, planes, nodes, aabb.get_longest_axis_size() * 0.0001);
  398. if (top < 0) {
  399. nodes.clear();
  400. planes.clear();
  401. ERR_FAIL_COND(top < 0);
  402. }
  403. error_radius = p_error_radius;
  404. }
  405. BSP_Tree::BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const AABB &p_aabb, float p_error_radius) {
  406. nodes = p_nodes;
  407. planes = p_planes;
  408. aabb = p_aabb;
  409. error_radius = p_error_radius;
  410. }
  411. BSP_Tree::~BSP_Tree() {
  412. }