1 (* Copyright (C) DooM 2D:Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *)
16 {$INCLUDE ../shared/a_modes.inc}
17 {$DEFINE aabbtree_many_asserts}
18 {$DEFINE aabbtree_query_count}
21 interface
26 // ////////////////////////////////////////////////////////////////////////// //
27 type
34 // ////////////////////////////////////////////////////////////////////////// //
35 type
37 public
41 public
54 // ////////////////////////////////////////////////////////////////////////// //
55 type
57 public
60 private
67 public
81 // return true if the current AABB contains the AABB given in parameter
85 // return true if the current AABB is overlapping with the AABB in parameter
86 // two AABBs overlap if they overlap in the two axes at the same time
89 // ray direction must be normalized
101 // ////////////////////////////////////////////////////////////////////////// //
102 (* Dynamic AABB tree (bounding volume hierarchy)
103 * based on the code from ReactPhysics3D physics library, http://www.reactphysics3d.com
104 * Copyright (c) 2010-2016 Daniel Chappuis
105 *
106 * This software is provided 'as-is', without any express or implied warranty.
107 * In no event will the authors be held liable for any damages arising from the
108 * use of this software.
109 *
110 * Permission is granted to anyone to use this software for any purpose,
111 * including commercial applications, and to alter it and redistribute it
112 * freely, subject to the following restrictions:
113 *
114 * 1. The origin of this software must not be misrepresented; you must not claim
115 * that you wrote the original software. If you use this software in a
116 * product, an acknowledgment in the product documentation would be
117 * appreciated but is not required.
118 *
119 * 2. Altered source versions must be plainly marked as such, and must not be
120 * misrepresented as being the original software.
121 *
122 * 3. This notice may not be removed or altered from any source distribution.
123 *)
124 // ////////////////////////////////////////////////////////////////////////// //
125 (*
126 * This class implements a dynamic AABB tree that is used for broad-phase
127 * collision detection. This data structure is inspired by Nathanael Presson's
128 * dynamic tree implementation in BulletPhysics. The following implementation is
129 * based on the one from Erin Catto in Box2D as described in the book
130 * "Introduction to Game Physics with Box2D" by Ian Parberry.
131 *)
132 // ////////////////////////////////////////////////////////////////////////// //
133 // Dynamic AABB Tree: can be used to speed up broad phase in various engines
134 type
136 private
137 type
140 public
144 public
145 // a node is either in the tree (has a parent) or in the free nodes list (has a next node)
147 //nextNodeId: Integer;
148 // a node is either a leaf (has data) or is an internal node (has children)
149 children: array [0..1] of Integer; // left and right child of the node (children[0] = left child)
150 //TODO: `flesh` can be united with `children`
152 // height of the node in the tree (-1 for free nodes)
154 // fat axis aligned bounding box (AABB) corresponding to the node
156 public
157 // return true if the node is a leaf of the tree
162 //property flesh: Integer read children[0] write children[0];
168 public
169 // return `true` to stop
170 type TForEachLeafCB = function (abody: TTreeFlesh; const aabb: AABB2D): Boolean is nested; // WARNING! don't modify AABB here!
172 public
173 // in the broad-phase collision detection (dynamic AABB tree), the AABBs are
174 // also inflated in direction of the linear motion of the body by mutliplying the
175 // followin constant with the linear velocity and the elapsed time between two frames
178 private
181 mFreeNodeId: Integer; // id of the first node of the list of free (allocated) nodes in the tree that we can use
185 // extra AABB Gap used to allow the collision shape to move a little bit
186 // without triggering a large modification of the tree which can be costly
189 private
200 public
201 {$IFDEF aabbtree_query_count}
203 {$ENDIF}
205 public
206 // called when a overlapping node has been found during the call to forEachAABBOverlap()
207 // return `true` to stop
209 type TSegQueryCallback = function (abody: TTreeFlesh; ax, ay, bx, by: Float): Float is nested; // return dist from (ax,ay) to abody
219 public
223 // clear all the nodes and reset the tree
233 // return `false` for invalid flesh
236 // insert an object into the tree
237 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
238 // AABB for static object will not be "fat" (simple optimization)
239 // WARNING! inserting the same object several times *WILL* break everything!
242 // remove an object from the tree
243 // WARNING: ids of removed objects can be reused on later insertions!
246 (** update the dynamic tree after an object has moved.
247 *
248 * if the new AABB of the object that has moved is still inside its fat AABB, then nothing is done.
249 * otherwise, the corresponding node is removed and reinserted into the tree.
250 * the method returns true if the object has been reinserted into the tree.
251 * the `dispX` and `dispY` parameters are the linear velocity of the AABB multiplied by the elapsed time between two frames.
252 * if the `forceReinsert` parameter is `true`, we force a removal and reinsertion of the node
253 * (this can be useful if the shape AABB has become much smaller than the previous one for instance).
254 *
255 * note that you should call this method if body's AABB was modified, even if the body wasn't moved.
256 *
257 * if `forceReinsert` = `true` and both `dispX` and `dispY` are zeroes, convert object to "static" (don't extrude AABB).
258 *
259 * return `true` if the tree was modified.
260 *)
261 function updateObject (nodeId: Integer; dispX, dispY: Float; forceReinsert: Boolean=false): Boolean;
265 function segmentQuery (var qr: TSegmentQueryResult; ax, ay, bx, by: Float; cb: TSegQueryCallback): Boolean;
275 implementation
277 uses
278 SysUtils;
281 // ////////////////////////////////////////////////////////////////////////// //
282 function minI (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
283 function maxI (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
285 function minF (a, b: Float): Float; inline; begin if (a < b) then result := a else result := b; end;
286 function maxF (a, b: Float): Float; inline; begin if (a > b) then result := a else result := b; end;
289 // ////////////////////////////////////////////////////////////////////////// //
291 constructor Ray2D.Create (ax0, ay0, ax1, ay1: Float); begin setX0Y0X1Y1(ax0, ay0, ax1, ay1); end;
296 begin
304 var
306 begin
313 begin
321 begin
330 // ////////////////////////////////////////////////////////////////////////// //
332 begin
337 begin
342 begin
346 function AABB2D.getvalid (): Boolean; inline; begin result := (minX < maxX) and (minY < maxY); end;
355 begin
360 {$IF DEFINED(D2F_DEBUG)}
362 {$ENDIF}
367 begin
372 {$IF DEFINED(D2F_DEBUG)}
374 {$ENDIF}
379 begin
380 {$IF DEFINED(D2F_DEBUG)}
383 {$ENDIF}
388 {$IF DEFINED(D2F_DEBUG)}
390 {$ENDIF}
395 begin
401 begin
402 {$IF DEFINED(D2F_DEBUG)}
404 {$ENDIF}
409 {$IF DEFINED(D2F_DEBUG)}
411 {$ENDIF}
416 begin
417 result :=
424 begin
430 begin
432 // exit with no intersection if found separated along any axis
439 // something to consider here is that 0 * inf =nan which occurs when the ray starts exactly on the edge of a box
440 // https://tavianator.com/fast-branchless-raybounding-box-intersections-part-2-nans/
441 function AABB2D.intersects (const ray: Ray2D; tmino: PFloat=nil; tmaxo: PFloat=nil): Boolean; overload;
442 var
445 begin
446 // ok with coplanars
449 // do X
451 begin
458 // do Y
460 begin
464 // tmin
468 // tmax
475 begin
479 end
480 else
481 begin
487 var
490 begin
492 // it may be faster to first check if start or end point is inside AABB (this is sometimes enough for dyntree)
495 // nope, do it hard way
505 // ////////////////////////////////////////////////////////////////////////// //
506 procedure TDynAABBTree.TSegmentQueryResult.reset (); inline; begin dist := -1; flesh := nil; end;
507 function TDynAABBTree.TSegmentQueryResult.valid (): Boolean; inline; begin result := (dist >= 0) and (flesh <> nil); end;
510 // ////////////////////////////////////////////////////////////////////////// //
515 begin
528 // ////////////////////////////////////////////////////////////////////////// //
529 // allocate and return a node to use in the tree
531 var
534 begin
535 // if there is no more allocated node to use
537 begin
539 // allocate more nodes in the tree
543 // initialize the allocated nodes
545 begin
552 // get the next free node
554 {$IFDEF aabbtree_many_asserts}assert((freeNodeId >= mNodeCount) and (freeNodeId < mAllocCount));{$ENDIF}
565 // release a node
567 begin
579 // insert a leaf node in the tree
580 // the process of inserting a new leaf node in the dynamic tree is described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
582 var
589 begin
590 // if the tree is empty
592 begin
595 exit;
600 // find the best sibling node for the new node
604 begin
608 // compute the merged AABB
613 // compute the cost of making the current node the sibling of the new node
616 // compute the minimum cost of pushing the new node further down the tree (inheritance cost)
619 // compute the cost of descending into the left child
624 // compute the cost of descending into the right child
629 // if the cost of making the current node a sibling of the new node is smaller than the cost of going down into the left or right child
632 // it is cheaper to go down into a child of the current node, choose the best child
633 //currentNodeId = (costLeft < costRight ? leftChild : rightChild);
639 // create a new parent for the new node and the sibling node
647 // if the sibling node was not the root node
649 begin
652 begin
654 end
655 else
656 begin
663 end
664 else
665 begin
666 // if the sibling node was the root node
674 // move up in the tree to change the AABBs that have changed
678 begin
679 // balance the sub-tree of the current node if it is not balanced
689 // recompute the height of the node in the tree
693 // recompute the AABB of the node
703 // remove a leaf node from the tree
705 var
708 begin
712 // if we are removing the root node (root node is a leaf in this case)
719 begin
721 end
722 else
723 begin
727 // if the parent of the node to remove is not the root node
729 begin
730 // destroy the parent node
732 begin
734 end
735 else
736 begin
737 {$IFDEF aabbtree_many_asserts}assert(mNodes[grandParentNodeId].children[TTreeNode.Right] = parentNodeId);{$ENDIF}
743 // now, we need to recompute the AABBs of the node on the path back to the root and make sure that the tree is still balanced
746 begin
747 // balance the current sub-tree if necessary
752 // get the two children of the current node
756 // recompute the AABB and the height of the current node
758 mNodes[currentNodeId].height := maxI(mNodes[leftChildId].height, mNodes[rightChildId].height)+1;
763 end
764 else
765 begin
766 // if the parent of the node to remove is the root node, the sibling node becomes the new root node
774 // balance the sub-tree of a given node using left or right rotations
775 // the rotation schemes are described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
776 // this method returns the new root node id
778 var
782 begin
787 // if the node is a leaf or the height of A's sub-tree is less than 2
788 if (nodeA.leaf) or (nodeA.height < 2) then begin result := nodeId; exit; end; // do not perform any rotation
790 // get the two children nodes
798 // compute the factor of the left and right sub-trees
801 // if the right node C is 2 higher than left node B
803 begin
818 begin
820 begin
822 end
823 else
824 begin
825 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeC.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
828 end
829 else
830 begin
837 // if the right node C was higher than left node B because of the F node
839 begin
844 // recompute the AABB of node A and C
848 // recompute the height of node A and C
853 end
854 else
855 begin
856 // if the right node C was higher than left node B because of node G
861 // recompute the AABB of node A and C
865 // recompute the height of node A and C
872 // return the new root of the sub-tree
874 exit;
877 // if the left node B is 2 higher than right node C
879 begin
894 begin
896 begin
898 end
899 else
900 begin
901 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeB.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
904 end
905 else
906 begin
913 // if the left node B was higher than right node C because of the F node
915 begin
920 // recompute the AABB of node A and B
924 // recompute the height of node A and B
929 end
930 else
931 begin
932 // if the left node B was higher than right node C because of node G
937 // recompute the AABB of node A and B
941 // recompute the height of node A and B
948 // return the new root of the sub-tree
950 exit;
953 // if the sub-tree is balanced, return the current root node
958 // compute the height of a given node in the tree
960 var
963 begin
967 // if the node is a leaf, its height is zero
970 // compute the height of the left and right sub-tree
974 // return the height of the node
979 // internally add an object into the tree
981 var
983 begin
984 // get the next available node (or allocate new ones if necessary)
987 // create the fat aabb to use in the tree
990 begin
997 // set the height of the node in the tree
1000 // insert the new leaf node in the tree
1006 // return the id of the node
1011 // initialize the tree
1013 var
1015 begin
1021 //memset(mNodes, 0, mAllocCount*TTreeNode.sizeof);
1024 // initialize the allocated nodes
1026 begin
1035 // also, checks if the tree structure is valid (for debugging purpose)
1038 var
1042 begin
1045 // if it is the root
1047 // get the children nodes
1051 begin
1052 e_WriteLog(Format('AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d; height=%d; leaf=%d', [pNode.aabb.minX, pNode.aabb.minY, pNode.aabb.maxX, pNode.aabb.maxY, pNode.aabb.volume, Integer(pNode.aabb.valid), pNode.height, Integer(pNode.leaf)]), MSG_NOTIFY);
1054 begin
1056 e_WriteLog(Format(' LEAF AABB:(%f,%f)-(%f,%f); valid=%d; volume=%f', [aabb.minX, aabb.minY, aabb.maxX, aabb.maxY, Integer(aabb.valid), aabb.volume]), MSG_NOTIFY);
1061 // if the current node is a leaf
1063 begin
1066 end
1067 else
1068 begin
1071 // check that the children node Ids are valid
1074 // check that the children nodes have the correct parent node
1077 // check the height of node
1080 // check the AABB of the node
1086 // recursively check the children nodes
1092 begin
1093 // recursively check each node
1098 // return `true` from visitor to stop immediately
1099 // checker should check if this node should be considered to further checking
1100 // returns tree node if visitor says stop or -1
1102 var
1108 var
1110 begin
1112 begin
1113 // use "small stack"
1116 end
1117 else
1118 begin
1119 // use "big stack"
1122 begin
1123 // reuse
1125 end
1126 else
1127 begin
1128 // grow
1137 begin
1140 begin
1141 // use "small stack"
1144 end
1145 else
1146 begin
1147 // use "big stack"
1153 var
1156 begin
1158 //if not assigned(visitor) then begin result := -1; exit; end;
1159 try
1160 {$IFDEF aabbtree_query_count}
1163 {$ENDIF}
1165 // start from root node
1168 // while there are still nodes to visit
1170 begin
1171 // get the next node id to visit
1173 // skip it if it is a nil node
1176 // get the corresponding node
1178 // should we investigate this node?
1180 begin
1181 // if the node is a leaf
1183 begin
1184 // call visitor on it
1187 begin
1190 end
1191 else
1192 begin
1193 // if the node is not a leaf, we need to visit its children
1201 finally
1207 // add `extraAABBGap` to bounding boxes so slight object movement won't cause tree rebuilds
1208 // extra AABB Gap used to allow the collision shape to move a little bit without triggering a large modification of the tree which can be costly
1210 begin
1217 begin
1223 // clear all the nodes and reset the tree
1225 begin
1231 function TDynAABBTree.computeTreeHeight (): Integer; begin result := computeHeight(mRootNodeId); end;
1234 // return the root AABB of the tree
1236 begin
1237 {$IFDEF aabbtree_many_asserts}assert((mRootNodeId >= 0) and (mRootNodeId < mNodeCount));{$ENDIF}
1242 // does the given id represents a valid object?
1243 // WARNING: ids of removed objects can be reused on later insertions!
1245 begin
1250 // get object by nodeid; can return nil for invalid ids
1252 begin
1253 if (nodeid >= 0) and (nodeid < mNodeCount) and (mNodes[nodeid].leaf) then result := mNodes[nodeid].flesh else result := nil;
1256 // get fat object AABB by nodeid; returns random shit for invalid ids
1258 begin
1259 if (nodeid >= 0) and (nodeid < mNodeCount) and (not mNodes[nodeid].isfree) then aabb.copyFrom(mNodes[nodeid].aabb) else aabb.setDims(0, 0, 0, 0);
1263 // insert an object into the tree
1264 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
1265 // AABB for static object will not be "fat" (simple optimization)
1266 // WARNING! inserting the same object several times *WILL* break everything!
1268 var
1271 begin
1273 begin
1274 e_WriteLog(Format('trying to insert FUCKED FLESH:(%f,%f)-(%f,%f); volume=%f; valid=%d', [aabb.minX, aabb.minY, aabb.maxX, aabb.maxY, aabb.volume, Integer(aabb.valid)]), MSG_WARNING);
1275 //raise Exception.Create('trying to insert invalid flesh in dyntree');
1277 exit;
1280 begin
1281 e_WriteLog(Format('trying to insert FUCKED AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d', [aabb.minX, aabb.minY, aabb.maxX, aabb.maxY, aabb.volume, Integer(aabb.valid)]), MSG_WARNING);
1284 exit;
1286 //e_WriteLog(Format('inserting AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d', [aabb.minX, aabb.minY, aabb.maxX, aabb.maxY, aabb.volume, Integer(aabb.valid)]), MSG_NOTIFY);
1294 // remove an object from the tree
1295 // WARNING: ids of removed objects can be reused on later insertions!
1297 begin
1298 if (nodeId < 0) or (nodeId >= mNodeCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTree');
1299 // remove the node from the tree
1305 function TDynAABBTree.updateObject (nodeId: Integer; dispX, dispY: Float; forceReinsert: Boolean=false): Boolean;
1306 var
1308 begin
1309 if (nodeId < 0) or (nodeId >= mNodeCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTree.updateObject');
1311 if not getFleshAABB(newAABB, mNodes[nodeId].flesh) then raise Exception.Create('invalid node id in TDynAABBTree.updateObject');
1312 if not newAABB.valid then raise Exception.Create('invalid flesh aabb in TDynAABBTree.updateObject');
1314 // if the new AABB is still inside the fat AABB of the node
1315 if (not forceReinsert) and (mNodes[nodeId].aabb.contains(newAABB)) then begin result := false; exit; end;
1317 // if the new AABB is outside the fat AABB, we remove the corresponding node
1320 // compute the fat AABB by inflating the AABB with a constant gap
1323 begin
1330 // inflate the fat AABB in direction of the linear motion of the AABB
1332 begin
1334 end
1335 else
1336 begin
1340 begin
1342 end
1343 else
1344 begin
1350 // reinsert the node into the tree
1357 // report all shapes overlapping with the AABB given in parameter
1359 var
1362 begin
1365 begin
1373 // report body that contains the given point, or nil
1375 var
1378 begin
1381 begin
1383 {$IFDEF aabbtree_many_asserts}assert((nid < 0) or ((nid >= 0) and (nid < mNodeCount) and (mNodes[nid].leaf)));{$ENDIF}
1388 // segment querying method
1389 function TDynAABBTree.segmentQuery (var qr: TSegmentQueryResult; ax, ay, bx, by: Float; cb: TSegQueryCallback): Boolean;
1390 var
1398 begin
1403 var
1405 begin
1407 // if the user returned a hitFraction of zero, it means that the raycasting should stop here
1409 begin
1413 exit;
1415 // if the user returned a positive fraction
1417 begin
1418 // we update the maxFraction value and the ray AABB using the new maximum fraction
1420 begin
1424 // fix curb here
1425 //curb := cura+dir*hitFraction;
1433 begin
1445 // normalize