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;
272 {$IFDEF aabbtree_query_count}
275 {$ELSE}
278 {$ENDIF}
282 implementation
284 uses
285 SysUtils;
288 // ////////////////////////////////////////////////////////////////////////// //
289 function minI (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
290 function maxI (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
292 function minF (a, b: Float): Float; inline; begin if (a < b) then result := a else result := b; end;
293 function maxF (a, b: Float): Float; inline; begin if (a > b) then result := a else result := b; end;
296 // ////////////////////////////////////////////////////////////////////////// //
298 constructor Ray2D.Create (ax0, ay0, ax1, ay1: Float); begin setX0Y0X1Y1(ax0, ay0, ax1, ay1); end;
303 begin
311 var
313 begin
320 begin
328 begin
337 // ////////////////////////////////////////////////////////////////////////// //
339 begin
344 begin
349 begin
353 function AABB2D.getvalid (): Boolean; inline; begin result := (minX < maxX) and (minY < maxY); end;
362 begin
367 {$IF DEFINED(D2F_DEBUG)}
369 {$ENDIF}
374 begin
379 {$IF DEFINED(D2F_DEBUG)}
381 {$ENDIF}
386 begin
387 {$IF DEFINED(D2F_DEBUG)}
390 {$ENDIF}
395 {$IF DEFINED(D2F_DEBUG)}
397 {$ENDIF}
402 begin
408 begin
409 {$IF DEFINED(D2F_DEBUG)}
411 {$ENDIF}
416 {$IF DEFINED(D2F_DEBUG)}
418 {$ENDIF}
423 begin
424 result :=
431 begin
437 begin
439 // exit with no intersection if found separated along any axis
446 // something to consider here is that 0 * inf =nan which occurs when the ray starts exactly on the edge of a box
447 // https://tavianator.com/fast-branchless-raybounding-box-intersections-part-2-nans/
448 function AABB2D.intersects (const ray: Ray2D; tmino: PFloat=nil; tmaxo: PFloat=nil): Boolean; overload;
449 var
452 begin
453 // ok with coplanars
456 // do X
458 begin
465 // do Y
467 begin
471 // tmin
475 // tmax
482 begin
486 end
487 else
488 begin
494 var
497 begin
499 // it may be faster to first check if start or end point is inside AABB (this is sometimes enough for dyntree)
502 // nope, do it hard way
512 // ////////////////////////////////////////////////////////////////////////// //
513 procedure TDynAABBTree.TSegmentQueryResult.reset (); inline; begin dist := -1; flesh := nil; end;
514 function TDynAABBTree.TSegmentQueryResult.valid (): Boolean; inline; begin result := (dist >= 0) and (flesh <> nil); end;
517 // ////////////////////////////////////////////////////////////////////////// //
522 begin
535 // ////////////////////////////////////////////////////////////////////////// //
536 // allocate and return a node to use in the tree
538 var
541 begin
542 // if there is no more allocated node to use
544 begin
546 // allocate more nodes in the tree
550 // initialize the allocated nodes
552 begin
559 // get the next free node
561 {$IFDEF aabbtree_many_asserts}assert((freeNodeId >= mNodeCount) and (freeNodeId < mAllocCount));{$ENDIF}
572 // release a node
574 begin
586 // insert a leaf node in the tree
587 // 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
589 var
596 begin
597 // if the tree is empty
599 begin
602 exit;
607 // find the best sibling node for the new node
611 begin
615 // compute the merged AABB
620 // compute the cost of making the current node the sibling of the new node
623 // compute the minimum cost of pushing the new node further down the tree (inheritance cost)
626 // compute the cost of descending into the left child
631 // compute the cost of descending into the right child
636 // 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
639 // it is cheaper to go down into a child of the current node, choose the best child
640 //currentNodeId = (costLeft < costRight ? leftChild : rightChild);
646 // create a new parent for the new node and the sibling node
654 // if the sibling node was not the root node
656 begin
659 begin
661 end
662 else
663 begin
670 end
671 else
672 begin
673 // if the sibling node was the root node
681 // move up in the tree to change the AABBs that have changed
685 begin
686 // balance the sub-tree of the current node if it is not balanced
696 // recompute the height of the node in the tree
700 // recompute the AABB of the node
710 // remove a leaf node from the tree
712 var
715 begin
719 // if we are removing the root node (root node is a leaf in this case)
726 begin
728 end
729 else
730 begin
734 // if the parent of the node to remove is not the root node
736 begin
737 // destroy the parent node
739 begin
741 end
742 else
743 begin
744 {$IFDEF aabbtree_many_asserts}assert(mNodes[grandParentNodeId].children[TTreeNode.Right] = parentNodeId);{$ENDIF}
750 // 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
753 begin
754 // balance the current sub-tree if necessary
759 // get the two children of the current node
763 // recompute the AABB and the height of the current node
765 mNodes[currentNodeId].height := maxI(mNodes[leftChildId].height, mNodes[rightChildId].height)+1;
770 end
771 else
772 begin
773 // if the parent of the node to remove is the root node, the sibling node becomes the new root node
781 // balance the sub-tree of a given node using left or right rotations
782 // the rotation schemes are described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
783 // this method returns the new root node id
785 var
789 begin
794 // if the node is a leaf or the height of A's sub-tree is less than 2
795 if (nodeA.leaf) or (nodeA.height < 2) then begin result := nodeId; exit; end; // do not perform any rotation
797 // get the two children nodes
805 // compute the factor of the left and right sub-trees
808 // if the right node C is 2 higher than left node B
810 begin
825 begin
827 begin
829 end
830 else
831 begin
832 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeC.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
835 end
836 else
837 begin
844 // if the right node C was higher than left node B because of the F node
846 begin
851 // recompute the AABB of node A and C
855 // recompute the height of node A and C
860 end
861 else
862 begin
863 // if the right node C was higher than left node B because of node G
868 // recompute the AABB of node A and C
872 // recompute the height of node A and C
879 // return the new root of the sub-tree
881 exit;
884 // if the left node B is 2 higher than right node C
886 begin
901 begin
903 begin
905 end
906 else
907 begin
908 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeB.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
911 end
912 else
913 begin
920 // if the left node B was higher than right node C because of the F node
922 begin
927 // recompute the AABB of node A and B
931 // recompute the height of node A and B
936 end
937 else
938 begin
939 // if the left node B was higher than right node C because of node G
944 // recompute the AABB of node A and B
948 // recompute the height of node A and B
955 // return the new root of the sub-tree
957 exit;
960 // if the sub-tree is balanced, return the current root node
965 // compute the height of a given node in the tree
967 var
970 begin
974 // if the node is a leaf, its height is zero
977 // compute the height of the left and right sub-tree
981 // return the height of the node
986 // internally add an object into the tree
988 var
990 begin
991 // get the next available node (or allocate new ones if necessary)
994 // create the fat aabb to use in the tree
997 begin
1004 // set the height of the node in the tree
1007 // insert the new leaf node in the tree
1013 // return the id of the node
1018 // initialize the tree
1020 var
1022 begin
1028 //memset(mNodes, 0, mAllocCount*TTreeNode.sizeof);
1031 // initialize the allocated nodes
1033 begin
1042 // also, checks if the tree structure is valid (for debugging purpose)
1045 var
1049 begin
1052 // if it is the root
1054 // get the children nodes
1058 begin
1059 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);
1061 begin
1063 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);
1068 // if the current node is a leaf
1070 begin
1073 end
1074 else
1075 begin
1078 // check that the children node Ids are valid
1081 // check that the children nodes have the correct parent node
1084 // check the height of node
1087 // check the AABB of the node
1093 // recursively check the children nodes
1099 begin
1100 // recursively check each node
1105 // return `true` from visitor to stop immediately
1106 // checker should check if this node should be considered to further checking
1107 // returns tree node if visitor says stop or -1
1109 var
1115 var
1117 begin
1119 begin
1120 // use "small stack"
1123 end
1124 else
1125 begin
1126 // use "big stack"
1129 begin
1130 // reuse
1132 end
1133 else
1134 begin
1135 // grow
1143 (*
1144 function spop (): Integer; inline;
1145 begin
1146 {$IFDEF aabbtree_many_asserts}assert(sp > 0);{$ENDIF}
1147 if (sp <= length(stack)) then
1148 begin
1149 // use "small stack"
1150 Dec(sp);
1151 result := stack[sp];
1152 end
1153 else
1154 begin
1155 // use "big stack"
1156 Dec(sp);
1157 result := bigstack[sp-length(stack)];
1158 end;
1159 end;
1160 *)
1162 var
1165 begin
1167 //if not assigned(visitor) then begin result := -1; exit; end;
1168 try
1169 {$IFDEF aabbtree_query_count}
1172 {$ENDIF}
1174 // start from root node
1177 // while there are still nodes to visit
1179 begin
1180 // get the next node id to visit
1181 //nodeId := spop();
1184 begin
1185 // use "small stack"
1188 end
1189 else
1190 begin
1191 // use "big stack"
1196 // skip it if it is a nil node
1199 // get the corresponding node
1201 // should we investigate this node?
1203 begin
1204 // if the node is a leaf
1206 begin
1207 // call visitor on it
1210 begin
1213 end
1214 else
1215 begin
1216 // if the node is not a leaf, we need to visit its children
1224 finally
1230 // add `extraAABBGap` to bounding boxes so slight object movement won't cause tree rebuilds
1231 // 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
1233 begin
1240 begin
1246 // clear all the nodes and reset the tree
1248 begin
1254 function TDynAABBTree.computeTreeHeight (): Integer; begin result := computeHeight(mRootNodeId); end;
1257 // return the root AABB of the tree
1259 begin
1260 {$IFDEF aabbtree_many_asserts}assert((mRootNodeId >= 0) and (mRootNodeId < mNodeCount));{$ENDIF}
1265 // does the given id represents a valid object?
1266 // WARNING: ids of removed objects can be reused on later insertions!
1268 begin
1273 // get object by nodeid; can return nil for invalid ids
1275 begin
1276 if (nodeid >= 0) and (nodeid < mNodeCount) and (mNodes[nodeid].leaf) then result := mNodes[nodeid].flesh else result := nil;
1279 // get fat object AABB by nodeid; returns random shit for invalid ids
1281 begin
1282 if (nodeid >= 0) and (nodeid < mNodeCount) and (not mNodes[nodeid].isfree) then aabb.copyFrom(mNodes[nodeid].aabb) else aabb.setDims(0, 0, 0, 0);
1286 // insert an object into the tree
1287 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
1288 // AABB for static object will not be "fat" (simple optimization)
1289 // WARNING! inserting the same object several times *WILL* break everything!
1291 var
1294 begin
1296 begin
1297 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);
1298 //raise Exception.Create('trying to insert invalid flesh in dyntree');
1300 exit;
1303 begin
1304 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);
1307 exit;
1309 //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);
1317 // remove an object from the tree
1318 // WARNING: ids of removed objects can be reused on later insertions!
1320 begin
1321 if (nodeId < 0) or (nodeId >= mNodeCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTree');
1322 // remove the node from the tree
1328 function TDynAABBTree.updateObject (nodeId: Integer; dispX, dispY: Float; forceReinsert: Boolean=false): Boolean;
1329 var
1331 begin
1332 if (nodeId < 0) or (nodeId >= mNodeCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTree.updateObject');
1334 if not getFleshAABB(newAABB, mNodes[nodeId].flesh) then raise Exception.Create('invalid node id in TDynAABBTree.updateObject');
1335 if not newAABB.valid then raise Exception.Create('invalid flesh aabb in TDynAABBTree.updateObject');
1337 // if the new AABB is still inside the fat AABB of the node
1338 if (not forceReinsert) and (mNodes[nodeId].aabb.contains(newAABB)) then begin result := false; exit; end;
1340 // if the new AABB is outside the fat AABB, we remove the corresponding node
1343 // compute the fat AABB by inflating the AABB with a constant gap
1346 begin
1353 // inflate the fat AABB in direction of the linear motion of the AABB
1355 begin
1357 end
1358 else
1359 begin
1363 begin
1365 end
1366 else
1367 begin
1373 // reinsert the node into the tree
1380 // report all shapes overlapping with the AABB given in parameter
1382 var
1385 begin
1388 begin
1396 // report body that contains the given point, or nil
1398 var
1401 begin
1404 begin
1406 {$IFDEF aabbtree_many_asserts}assert((nid < 0) or ((nid >= 0) and (nid < mNodeCount) and (mNodes[nid].leaf)));{$ENDIF}
1411 // segment querying method
1412 function TDynAABBTree.segmentQuery (var qr: TSegmentQueryResult; ax, ay, bx, by: Float; cb: TSegQueryCallback): Boolean;
1413 var
1421 begin
1426 var
1428 begin
1430 // if the user returned a hitFraction of zero, it means that the raycasting should stop here
1432 begin
1436 exit;
1438 // if the user returned a positive fraction
1440 begin
1441 // we update the maxFraction value and the ray AABB using the new maximum fraction
1443 begin
1447 // fix curb here
1448 //curb := cura+dir*hitFraction;
1456 begin
1468 // normalize