Debian Codegraph @

src/transform/castleinternaloctree.pas

raw
1 {
2 Copyright 2003-2022 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 (*Base octree classes (TOctreeNode and TOctree) and utilities.
17 Used by actual octrees in units like
18 @link(CastleInternalTriangleOctree),
19 @link(CastleInternalBaseTriangleOctree),
20 @link(CastleInternalShapeOctree).
21
22 Typical way to derive actual (non-abstract) octrees goes like this;
23
24 @longcode(#
25 type
26 TMyOctree = class;
27
28 TMyOctreeNode = class(TOctreeNode)
29 protected
30 function ItemBoundingBox(const ItemIndex: integer): TBox3D; override;
31 procedure PutItemIntoSubNodes(ItemIndex: integer); override;
32 public
33 function ParentTree: TMyOctree;
34 end;
35
36 TMyOctree = class(TOctree)
37 public
38 constructor Create(AMaxDepth, ALeafCapacity: Integer;
39 const ARootBox: TBox3D);
40 function TreeRoot: TMyOctreeNode;
41 end;
42
43 { implementation }
44
45 function TMyOctreeNode.ItemBoundingBox(const ItemIndex: integer): TBox3D;
46 begin
47 Result := ...;
48 end;
49
50 procedure TMyOctreeNode.PutItemIntoSubNodes(ItemIndex: integer);
51 begin
52 { See comments at @link(TOctreeNode.PutItemIntoSubNodes)
53 to know how you should implement this. }
54 end;
55
56 function TMyOctreeNode.ParentTree: TMyOctree;
57 begin
58 Result := TMyOctree(InternalParentTree);
59 end;
60
61 constructor TMyOctree.Create(AMaxDepth, ALeafCapacity: Integer;
62 const ARootBox: TBox3D);
63 begin
64 inherited Create(AMaxDepth, ALeafCapacity, ARootBox, TMyOctreeNode);
65 end;
66
67 function TMyOctree.TreeRoot: TMyOctreeNode;
68 begin
69 Result := TMyOctreeNode(InternalTreeRoot);
70 end;
71 #)
72 *)
73 unit CastleInternalOctree;
74
75 {$I castleconf.inc}
76
77 interface
78
79 uses SysUtils, CastleVectors, CastleBoxes, CastleUtils, CastleFrustum, Contnrs;
80
81 type
82 { }
83 TOctree = class;
84 TOctreeNode = class;
85
86 TOctreeNodeClass = class of TOctreeNode;
87
88 TOctreeSubnodeIndex = array[0..2]of boolean;
89
90 TEnumerateOctreeItemsFunc = procedure(ItemIndex: Integer;
91 CollidesForSure: boolean) of object;
92
93 { Octree node.
94
95 @unorderedList(
96 @item(@italic(Leaf nodes) store a list of indexes in ItemsIndices array.
97 These are usuallly indexes to some array of items on TOctree.
98 For the sake of this unit they are just some integers that
99 uniquely describe items that you want to keep in octree leafs.
100 The base abstract TOctreeNode class doesn't clarify what
101 kind of items are actually kept.)
102
103 @item(@italic(Not leaf (internal) nodes) have 8 children
104 nodes in TreeSubNodes.)
105 )
106
107 Each @link(TOctreeNode) also has some essential properties like
108 Box, MiddlePoint and ParentTree. }
109 TOctreeNode = class
110 private
111 { read-only after the object is created }
112 FBox: TBox3D;
113 FMiddlePoint: TVector3;
114 FDepth: Integer;
115 FParentTree: TOctree;
116 FParentNode: TOctreeNode;
117 FBoundingSphereRadiusSqr: Single;
118 FBoundingSphereCenter: TVector3;
119
120 FItemsIndices: TIntegerList;
121 FIsLeaf: Boolean;
122 StatisticsAdded: Boolean;
123 SplitNotSensible: Boolean;
124
125 { Neither CreateTreeSubNodes nor CreateLeafItems call
126 Items.Free or Subnodes[].Free, that is they don't cleanup after their
127 previous calls. If you want, you have to cleanup yourself. }
128 { Create TreeSubNodes. }
129 procedure CreateTreeSubNodes(AsLeaves: Boolean);
130 { Create ItemsIndices. }
131 procedure CreateLeafItems;
132 procedure FreeAndNilTreeSubNodes;
133
134 procedure SetLeaf(value: Boolean);
135
136 procedure EnumerateCollidingOctreeItems(
137 const Frustum: TFrustum;
138 EnumerateOctreeItemsFunc: TEnumerateOctreeItemsFunc);
139 procedure StatisticsRemove;
140 procedure StatisticsAdd;
141 protected
142 function ItemBoundingBox(const ItemIndex: integer): TBox3D; virtual; abstract;
143
144 { Insert given index into appropriate subnodes.
145 This should call SubNode.AddItem(ItemIndex) for chosen TreeSubNodes
146 (maybe all, maybe none). It all depends on what is your definition of
147 "an octree item" -- you generally want to check how given item
148 collides with BoundingBoxes of your TreeSubNodes and call
149 SubNode.AddItem(ItemIndex) for each SubNode that contains
150 (al least part) of your ItemIndex.
151
152 Don't ever call this directly from subclasses of TOctreeNode.
153 TOctreeNode internally calls it when it needs to.
154
155 You can assume here that all TreeSubNodes are <> nil.
156 But you shouldn't assume here anything about value of IsLeaf
157 or ItemIndices <> nil (yes, this means that this function
158 may be internally called when the state of this object
159 is partially invalid). }
160 procedure PutItemIntoSubNodes(ItemIndex: integer); virtual; abstract;
161
162 property InternalParentTree: TOctree read FParentTree;
163
164 { Parent node of the octree. @nil for the root node. }
165 property InternalParentNode: TOctreeNode read FParentNode;
166 public
167 { Child octree nodes, only if this is an internal node (IsLeaf = @false).
168 When this is a leaf (IsLeaf = @true), these are all @nil.
169
170 Indexed by Booleans, "true" means that given coordinate
171 is >= than corresponding MiddlePoint coordinate.
172 For example TreeSubNodes[true, true, true] are coordinates
173 between MiddlePoint and Box[1].
174
175 Subnodes class is always the same as our (Self) class.
176
177 This field is read-only from outside of this unit. }
178 TreeSubNodes: array [Boolean, Boolean, Boolean] of TOctreeNode;
179
180 { Items stored at the octree node.
181 Items are stored here (and ItemsIndices <> nil) only
182 when this is a leaf item (IsLeaf = @true) or when
183 ParentTree.ItemsInNonLeafNodes is @true. In the latter case,
184 we store items even in internal nodes, see TOctree.ItemsInNonLeafNodes.
185
186 Never put any items in the octree node by direct ItemsIndices.Add.
187 Instead you must use @link(AddItem) method. }
188 property ItemsIndices: TIntegerList read FItemsIndices;
189
190 { Number of items stored here.
191 Same thing as ItemsIndices.Count, but has somewhat nicer name
192 if you have Items[] property defined in a subclass.
193 Use this only when you know that @link(ItemsIndices) <> nil. }
194 function ItemsCount: integer;
195
196 { Insert an item into this octree node.
197
198 It takes care of the octree structure properties:
199
200 @unorderedList(
201 @item(Splits a leaf node into non-leaf node
202 if maximum number of items in leaf is exceeded (and Depth < MaxDepth).)
203
204 @item(And when you insert an item into non-leaf node,
205 it correctly puts it into children subnodes too.)
206 ) }
207 procedure AddItem(ItemIndex: integer);
208
209 { Is this a leaf node.
210
211 Changing this property rearranges items correctly.
212 If you change this from @false to @true then all items from subnodes
213 are correctly gathered and stored in our ItemsIndices.
214 If you change this from @true to @false then subnodes are created
215 and we insert to them our items, following the MiddlePoint rule. }
216 property IsLeaf: Boolean read fIsLeaf write SetLeaf;
217
218 { Middle point of the octree node, determines how our subnodes divide
219 the space. This is defined for leaf nodes too, since leaf nodes
220 may have to be converted into internal nodes at some point.
221
222 Note that MiddlePoint does not need to be exactly in the
223 middle of the octree node. This is it's default value
224 (if you called constructor without explicitly
225 providing MiddlePoint value), but it's not a requirement.
226 MiddlePoint may be anywhere inside @link(Box).
227
228 This way you can explicitly specify some MiddlePoint if you know that
229 if will yield better hierarchical division of your scene.
230
231 When @link(Box) is empty, then value of MiddlePoint is undefined. }
232 property MiddlePoint: TVector3 read fMiddlePoint;
233
234 { Axis-aligned box in the 3D space that contains all items within
235 this node. It's allowed that some items are actually larger
236 and go (partially) outside of this box too (so you don't have
237 to split one triangle into many when it doesn't fit perfectly
238 into octree node), but it's undefined if the parts that go outside
239 will be detected by collision routines of this node.
240
241 Special case: when this is empty, then MiddlePoint has undefined
242 value and IsLeaf must be true. }
243 property Box: TBox3D read fBox;
244
245 { Bounding sphere of this box.
246 Right now simply calculated
247 as the smallest possible sphere enclosing Box.
248 So they are only a bad approximation of bounding Box,
249 but they can be sometimes useful in stuations when detecting
250 collision versus bounding sphere is much faster than detecting
251 them versus bounding box.
252
253 BoundingSphereRadiusSqr = 0 and BoundingSphereCenter is undefined
254 if Box is empty. }
255 property BoundingSphereCenter: TVector3 read FBoundingSphereCenter;
256 property BoundingSphereRadiusSqr: Single read FBoundingSphereRadiusSqr;
257
258 property Depth: integer read fDepth;
259
260 { Simple constructor. Calculates MiddlePoint as a middle of the ABox,
261 or as (0, 0, 0) if ABox is empty. }
262 constructor Create(const ABox: TBox3D; AParentTree: TOctree;
263 AParentNode: TOctreeNode;
264 ADepth: integer; AsLeaf: Boolean);
265
266 { Virtual constructor, not to be called directly, only to be overridden.
267 (But a constructor should be public, not protected.)
268
269 You want to override this in descendants.
270 This constructor must be virtual,
271 since in this unit CreateTreeSubNodes and TOctree.Create
272 must be able to construct new instances of class
273 using class reference (given by Self.ClassType in CreateTreeSubNodes
274 or OctreeNodeFinalClass in TOctree.Create).
275
276 @exclude }
277 constructor CreateBase(const ABox: TBox3D; AParentTree: TOctree;
278 AParentNode: TOctreeNode;
279 ADepth: integer; AsLeaf: Boolean;
280 const AMiddlePoint: TVector3); virtual;
281
282 destructor Destroy; override;
283
284 { In which subnode does the given point lie.
285 Decides using MiddlePoint.
286
287 This is a simple utility, ignores what is our @link(Box) (doesn't check
288 is P is inside @link(Box) at all), ignores if we're leaf or not. }
289 function SubnodeWithPoint(const P: TVector3): TOctreeSubnodeIndex; overload;
290
291 procedure SubnodesWithBox(const ABox: TBox3D;
292 out SubnodeLow, SubnodeHigh: TOctreeSubnodeIndex);
293
294 { Ignore Z coords of boxes, like they were infinite in Z. }
295 procedure SubnodesWithBox2D(const ABoxMin, ABoxMax: TVector2;
296 out SubnodeLow, SubnodeHigh: TOctreeSubnodeIndex);
297
298 { Simple check for frustum collision. }
299 function FrustumCollisionPossible(const Frustum: TFrustum): Boolean;
300
301 { Push children nodes (use this only for non-leafs) into the List.
302 @groupBegin }
303 procedure PushChildrenFrontToBack(List: TOrderedList; const Position: TVector3);
304 procedure PushChildrenBackToFront(List: TOrderedList; const Position: TVector3);
305 procedure PushChildren(List: TOrderedList);
306 { @groupEnd }
307 end;
308
309 { Helper structure to keep octree limits. Useful to implement
310 VRML/X3D extension
311 [https://castle-engine.io/x3d_extensions.php#section_ext_octree_properties]. }
312 TOctreeLimits = record
313 MaxDepth: integer;
314 LeafCapacity: Integer;
315 end;
316 POctreeLimits = ^TOctreeLimits;
317
318 { Base abstract octree class.
319
320 Like most 3D engines, Castle Game Engine uses a smart
321 tree structure to handle collision detection in arbitrary 3D worlds.
322 The structure used in our engine is the @italic(octree), with a couple
323 of special twists to handle dynamic scenes. See
324 @url(https://castle-engine.io/vrml_engine_doc/output/xsl/html/chapter.octree.html
325 documentation chapter "octrees" for more explanation).
326
327 This class holds some settings common for the whole octree (like @link(MaxDepth),
328 @link(LeafCapacity))
329 and a reference to the root octree node (of @link(TOctreeNode) class)
330 in the protected property InternalTreeRoot.
331
332 The @link(MaxDepth), @link(LeafCapacity) define limits that determine how fast the octree
333 is constructed,
334 how much memory does it use,
335 and how fast can it answer collision queries. }
336 TOctree = class
337 private
338 FTreeRoot: TOctreeNode;
339 FOctreeNodeFinalClass: TOctreeNodeClass;
340 FItemsInNonLeafNodes: Boolean;
341 FMaxDepth: integer;
342 FLeafCapacity: Integer;
343
344 { current octree total statistics }
345 FTotalLeafNodes, FTotalNonLeafNodes, FTotalItemsInLeafs: Int64;
346 protected
347 { Text appended to the @link(Statistics).
348 In this class this returns ''.
349 Every line, including the last one, must be terminated by a newline. }
350 function StatisticsBonus: string; virtual;
351 public
352 property InternalTreeRoot: TOctreeNode read FTreeRoot;
353
354 { Maximum tree depth.
355
356 For educational purposes, you can make an experiment and set
357 @link(MaxDepth) to 0. This forces a one-leaf tree, effectively
358 making octree searching work like a normal linear searching.
359 You should see a dramatic loss of game speed on non-trivial models then.
360
361 Currently, you should not change MaxDepth and LeafCapacity after creating
362 the octree, as they will not rebuild the octree to obey the given limits. }
363 property MaxDepth: integer read FMaxDepth write FMaxDepth;
364
365 { Maximum number of items inside a leaf, unless this leaf is already
366 at maximum depth (MaxDepth). When you add an item to a leaf,
367 to keep LeafCapacity correct. Must be >= 1. }
368 property LeafCapacity: Integer
369 read FLeafCapacity write FLeafCapacity;
370
371 { Does this octree keep items also in internal nodes.
372 Leaf nodes always store items (have ItemIndices).
373
374 If you set this property to @true when constructing this object
375 then all created TOctreeNode will have ItemIndices property
376 that keeps the items inside.
377
378 Advantages: e.g. consider frustum culling using octree.
379 In some situations you know that some OctreeNode is
380 completely inside frustum. Then you want to mark all
381 items inside this OctreeNode as "visible".
382 If you would have to traverse all children of this
383 OctreeNode, you could have horribly slow algorithm
384 (especially since one item is often stored in many leafs,
385 since it collides with many leafs BoundingBoxes).
386 So you can set ItemsInNonLeafNodes and simply
387 use ItemIndices list of your OctreeNode.
388 And you don't have to traverse children of this OctreeNode.
389
390 Disadvantages: if you have many items in your octree
391 (as is typical with e.g. @link(TTriangleOctree))
392 then this property can cost you a @italic(lot) of memory. }
393 property ItemsInNonLeafNodes: Boolean
394 read FItemsInNonLeafNodes;
395
396 { The actual (non-abstract) TOctreeNode descendant class for this octree.
397 Set when constructing this octree.
398
399 This tells what class should have FTreeRoot.
400 Since inside TOctreeNode, each children node
401 (in TreeSubNodes) always has the same class as it's parent,
402 so class OctreeNodeFinalClass determines the TOctreeNode descendant
403 that will be used to construct your whole octree. }
404 property OctreeNodeFinalClass: TOctreeNodeClass
405 read FOctreeNodeFinalClass;
406
407 constructor Create(const Limits: TOctreeLimits;
408 const ARootBox: TBox3D; AOctreeNodeFinalClass: TOctreeNodeClass;
409 AItemsInNonLeafNodes: Boolean);
410 destructor Destroy; override;
411
412 { Traverse octree seeking for nodes that (possibly) collide
413 with given Frustum. For every such item
414 calls given EnumerateOctreeItemsFunc.
415
416 Requires that ParentTree.ItemsInNonLeafNodes = true
417 (checked by assertion here, so only if you have assertions on).
418 May be implemented one day to work with
419 ParentTree.ItemsInNonLeafNodes = false too, but it will be
420 (usually) much slower on such tree.
421
422 It gives to EnumerateOctreeItemsFunc an ItemIndex,
423 an index to octrees items. This is just taken from ItemIndices array.
424 May call EnumerateOctreeItemsFunc with the same ItemIndex multiple times.
425
426 It also gives to EnumerateOctreeItemsFunc parameter CollidesForSure:
427
428 @unorderedList(
429 @item(If CollidesForSure = true then octree node that
430 had this item was found to be entirely in the frustum.
431 This means that (assuming that octree item that is in some
432 octree node always collides with Box of this node,
433 and it should always be true)
434 given octree item for sure collides with frustum.)
435
436 @item(If CollidesForSure = false then given octree item
437 was found inside some octree leaf that may only partially
438 (or not at all) collide with frustum.
439 And this function doesn't check whether your @italic(octree item)
440 possibly collides with Frustum (since in this generic
441 octree unit, @link(CastleInternalOctree), we have no knowledge about
442 geometry of your octree items).
443 So you may want to check inside EnumerateOctreeItemsFunc handler
444 your octree items versus Frustum, if you want to
445 have greatest possibility of eliminating octree items
446 that are not within your frustum (but beware that too many
447 checks for visibility can also cost you too much time...).
448
449 That why CollidesForSure may be useful:
450 if it's true then you already know for sure that frustum
451 collides with this octree item, so you don't have to waste your
452 time on additional checks.)
453 )
454
455 @italic(Notes for implementing descendants of this class:)
456 This method simply calls TreeRoot.EnumerateCollidingOctreeItems. }
457 procedure EnumerateCollidingOctreeItems(
458 const Frustum: TFrustum;
459 EnumerateOctreeItemsFunc: TEnumerateOctreeItemsFunc);
460
461 { Multi-line description of how the octree levels look like.
462 Describes how many leaves / non-leaves we have,
463 how many items in leaves we have and on each level and in summary.
464
465 Every line, including the last one, is terminated by newline.
466
467 @italic(Notes for implementing descendants of this class:)
468 You can override StatisticsBonus, it's appended to the result of this
469 method. }
470 function Statistics: string;
471
472 property TotalLeafNodes: Int64 read FTotalLeafNodes;
473 property TotalNonLeafNodes: Int64 read FTotalNonLeafNodes;
474 property TotalItemsInLeafs: Int64 read FTotalItemsInLeafs;
475 function TotalItemsInOctree: Int64; virtual; abstract;
476 end;
477
478 function OctreeSubnodeIndexToNiceStr(const SI: TOctreeSubnodeIndex): string; deprecated;
479 function OctreeSubnodeIndexesEqual(const SI1, SI2: TOctreeSubnodeIndex): Boolean;
480
481 implementation
482
483 uses Math,
484 CastleStringUtils;
485
486 { TOctreeNode ------------------------------------------------------------ }
487
488 procedure TOctreeNode.CreateTreeSubNodes(AsLeaves: Boolean);
489 var
490 b: TOctreeSubnodeIndex;
491 b_0, b_1, b_2: Boolean;
492 SubBox: TBox3D;
493 i: integer;
494 begin
495 { we can't do "for b[0] := Low(Boolean) ... " in FPC 1.9.5,
496 so we're using variables b_0, b_1, b_2. }
497 for b_0 := Low(Boolean) to High(Boolean) do
498 for b_1 := Low(Boolean) to High(Boolean) do
499 for b_2 := Low(Boolean) to High(Boolean) do
500 begin
501 b[0] := b_0;
502 b[1] := b_1;
503 b[2] := b_2;
504
505 { calculate SubBox }
506 SubBox := Box;
507 for i := 0 to 2 do
508 if b[i] then
509 SubBox.Data[0].Data[i] := MiddlePoint[i] else
510 SubBox.Data[1].Data[i] := MiddlePoint[i];
511
512 TreeSubNodes[b[0], b[1], b[2]] :=
513 TOctreeNodeClass(Self.ClassType).Create(
514 SubBox, FParentTree, Self, Depth + 1, AsLeaves);
515 end;
516 end;
517
518 procedure TOctreeNode.CreateLeafItems;
519 begin
520 FItemsIndices := TIntegerList.Create;
521 ItemsIndices.Capacity := Max(FParentTree.LeafCapacity div 4, 4);
522 end;
523
524 procedure TOctreeNode.FreeAndNilTreeSubNodes;
525 var b1, b2, b3: Boolean;
526 begin
527 for b1 := Low(Boolean) to High(Boolean) do
528 for b2 := Low(Boolean) to High(Boolean) do
529 for b3 := Low(Boolean) to High(Boolean) do
530 FreeAndNil(TreeSubNodes[b1, b2, b3]);
531 end;
532
533 procedure TOctreeNode.SetLeaf(value: Boolean);
534 var
535 I: integer;
536 begin
537 if value <> FIsLeaf then
538 begin
539 StatisticsRemove;
540 SplitNotSensible := false;
541 if Value then
542 begin
543 CreateLeafItems;
544
545 { TODO -- gather all items from subNode's to Items }
546 raise Exception.Create('TODO -- setting from not-leaf back to leaf not '+
547 'implemented yet (because not used anywhere)');
548
549 FreeAndNilTreeSubNodes;
550 end else
551 begin
552 CreateTreeSubNodes(true);
553 for i := 0 to ItemsIndices.Count - 1 do
554 PutItemIntoSubNodes(ItemsIndices[i]);
555 if not FParentTree.ItemsInNonLeafNodes then
556 FreeAndNil(FItemsIndices);
557 end;
558 FIsLeaf := value;
559 StatisticsAdd;
560 end;
561 end;
562
563 function TOctreeNode.ItemsCount: integer;
564 begin
565 Result := ItemsIndices.Count;
566 end;
567
568 procedure TOctreeNode.AddItem(ItemIndex: integer);
569
570 { If we would split leaf into non-leaf, can we redistribute the existing
571 items into subleafs sensibly? (If all items would go into all leafs,
572 e.g. because their bboxes are equal, then splitting makes no sense,
573 even when LeafCapacity is reached.)
574
575 Testcase: BrainStem glTF with 59 materials, so 59 shapes, with equal bbox.
576 Since 59 > LeafCapacity, a naive implementation would fill entire octree
577 to max depth with all items...
578 But it would be a waste of time and memory, as all 59 shapes are all in all nodes,
579 because they all have equal bbox.
580 }
581 function SplitSensible: Boolean;
582 var
583 M: TVector3;
584 I: Integer;
585 begin
586 if SplitNotSensible then
587 Exit(false);
588
589 M := MiddlePoint;
590 for I := 0 to ItemsIndices.Count - 1 do
591 if not ItemBoundingBox(ItemsIndices[I]).Contains(M) then
592 Exit(true);
593
594 Result := false;
595 { Cache, to return SplitSensible = false faster next time.
596 This caching relies on the fact that SplitSensible is called only when
597 LeafCapacity is reached. So we have at least LeafCapacity items containing M.
598
599 Otherwise (if SplitSensible was called earlier) then caching this would
600 not be correct. Newly added items could make splitting sensible then. }
601 SplitNotSensible := true;
602 end;
603
604 begin
605 if IsLeaf and
606 (ItemsCount = FParentTree.LeafCapacity) and
607 (Depth < FParentTree.MaxDepth) and
608 SplitSensible then
609 IsLeaf := false;
610
611 if not IsLeaf then
612 begin
613 if FParentTree.ItemsInNonLeafNodes then
614 ItemsIndices.Add(ItemIndex);
615 PutItemIntoSubNodes(ItemIndex)
616 end else
617 begin
618 if StatisticsAdded then
619 Inc(FParentTree.FTotalItemsInLeafs);
620 ItemsIndices.Add(ItemIndex);
621 end;
622 end;
623
624 constructor TOctreeNode.Create(const ABox: TBox3D; AParentTree: TOctree;
625 AParentNode: TOctreeNode;
626 ADepth: integer; AsLeaf: Boolean);
627 var
628 AMiddlePoint: TVector3;
629 begin
630 if ABox.IsEmpty then
631 begin
632 Check(AsLeaf, 'TOctreeNode.Create error: attempt to create non-leaf'
633 +' node with empty bounding box');
634 AMiddlePoint := Vector3(0, 0, 0);
635 end else
636 AMiddlePoint := ABox.Center;
637
638 CreateBase(ABox, AParentTree, AParentNode, ADepth, AsLeaf, AMiddlePoint);
639 end;
640
641 constructor TOctreeNode.CreateBase(const ABox: TBox3D;
642 AParentTree: TOctree; AParentNode: TOctreeNode;
643 ADepth: integer; AsLeaf: Boolean; const AMiddlePoint: TVector3);
644 begin
645 inherited Create;
646
647 FBox := ABox;
648 Box.BoundingSphere(FBoundingSphereCenter, FBoundingSphereRadiusSqr);
649 FMiddlePoint := AMiddlePoint;
650
651 FParentTree := AParentTree;
652 FParentNode := AParentNode;
653 FDepth := ADepth;
654 FIsLeaf := AsLeaf;
655 if IsLeaf then
656 CreateLeafItems
657 else
658 CreateTreeSubNodes(true);
659 StatisticsAdd;
660 end;
661
662 destructor TOctreeNode.Destroy;
663 begin
664 { Update statistics when removing node.
665 Not needed for now, we destroy TOctreeNode only when destroying the parent octree now.
666 if StatisticsAdded then
667 begin
668 if IsLeaf then
669 FParentTree.FTotalItemsInLeafs := FParentTree.FTotalItemsInLeafs - ItemIndices.Count;
670 StatisticsRemove;
671 end; }
672
673 FreeAndNilTreeSubNodes;
674 FreeAndNil(FItemsIndices);
675 inherited;
676 end;
677
678 procedure TOctreeNode.StatisticsAdd;
679 begin
680 if IsLeaf then
681 begin
682 Inc(FParentTree.FTotalLeafNodes);
683 FParentTree.FTotalItemsInLeafs := FParentTree.FTotalItemsInLeafs + ItemsIndices.Count;
684 end else
685 begin
686 Inc(FParentTree.FTotalNonLeafNodes);
687 end;
688 StatisticsAdded := true;
689 end;
690
691 procedure TOctreeNode.StatisticsRemove;
692 begin
693 if IsLeaf then
694 begin
695 Dec(FParentTree.FTotalLeafNodes);
696 FParentTree.FTotalItemsInLeafs := FParentTree.FTotalItemsInLeafs - ItemsIndices.Count;
697 end else
698 begin
699 Dec(FParentTree.FTotalNonLeafNodes);
700 end;
701 StatisticsAdded := false;
702 end;
703
704 function TOctreeNode.SubnodeWithPoint(const P: TVector3): TOctreeSubnodeIndex;
705 begin
706 result[0] := P[0] >= MiddlePoint[0];
707 result[1] := P[1] >= MiddlePoint[1];
708 result[2] := P[2] >= MiddlePoint[2];
709 end;
710
711 procedure TOctreeNode.SubnodesWithBox(const ABox: TBox3D;
712 out SubnodeLow, SubnodeHigh: TOctreeSubnodeIndex);
713 var
714 i: Integer;
715 begin
716 for i := 0 to 2 do
717 begin
718 SubnodeLow[i] := false;
719 SubnodeHigh[i] := true;
720 if ABox.Data[0][i] >= MiddlePoint[i] then
721 SubnodeLow[i] := true else
722 if ABox.Data[1][i] < MiddlePoint[i] then
723 SubnodeHigh[i] := false;
724 end;
725 end;
726
727 procedure TOctreeNode.SubnodesWithBox2D(const ABoxMin, ABoxMax: TVector2;
728 out SubnodeLow, SubnodeHigh: TOctreeSubnodeIndex);
729 var
730 i: Integer;
731 begin
732 for i := 0 to 1 do
733 begin
734 SubnodeLow[i] := false;
735 SubnodeHigh[i] := true;
736 if ABoxMin[i] >= MiddlePoint[i] then
737 SubnodeLow[i] := true else
738 if ABoxMax[i] < MiddlePoint[i] then
739 SubnodeHigh[i] := false;
740 end;
741 SubnodeLow[2] := false;
742 SubnodeHigh[2] := true;
743 end;
744
745 procedure TOctreeNode.EnumerateCollidingOctreeItems(
746 const Frustum: TFrustum;
747 EnumerateOctreeItemsFunc: TEnumerateOctreeItemsFunc);
748
749 procedure EnumerateAllItems(CollidesForSure: Boolean);
750 var i: Integer;
751 begin
752 for i := 0 to ItemsIndices.Count - 1 do
753 EnumerateOctreeItemsFunc(ItemsIndices[i], CollidesForSure);
754 end;
755
756 begin
757 { Key to understand thing below is that I have two methods
758 to check collision of octree node with frustum:
759 using node's BoundingSphere and using node's
760 bounding Box.
761
762 Advantage of testing for collision with sphere:
763 it's much faster than checking for collision versus box,
764 which can be clearly seen comparing implementations of
765 Frustum.SphereCollisionPossible and
766 FrustumBox3DCollisionPossible.
767
768 Disadvantage: bounding sphere is worse description of
769 octree node's geometry (i.e. it's simply always larger then
770 node's bounding Box), so such testing is not so effective
771 in eliminating Shapes from visibility.
772
773 So there are a couple things to do below.
774 1. You can check each octree node versus it's BoundingSphere
775 2. You can check each octree node versus it's Box
776 3. And one that prooves the most efficient one in practice:
777 check for collision versus sphere first, and then,
778 it test versus sphere succeeds, check versus box. }
779
780 if Frustum.SphereCollisionPossibleSimple(
781 BoundingSphereCenter, BoundingSphereRadiusSqr) then
782 begin
783 case Frustum.Box3DCollisionPossible(Box) of
784 fcNoCollision: ;
785 fcSomeCollisionPossible:
786 if IsLeaf then
787 EnumerateAllItems(false) else
788 begin
789 { Once I had an idea to do an optimization to code below.
790 For now, every recursive call to EnumerateCollidingOctreeItems
791 potentially results in a call to FrustumBox3DCollisionPossible.
792 But inside this call, the same points are often calculated
793 versus the same Frustum many times
794 (because 8 points, on 8 edges of my Box, are shared by 2 children;
795 bacause 6 points, on 6 faces of my Box, are shared by 4 children;
796 and because 1 point in the middle of my Box is shared by all 8 children).
797 Also note that Box[0] point of my Box is the same as Box[0] point
798 of my [false, false, false] child and
799 Box[1] point of my Box is the same as Box[1] point of my
800 [true, true, true] child. So these points need not be calculated
801 versus the frustum ever again.
802
803 1) So first I tried to implement passing the calculations of
804 points versus frustum down the recursive calls.
805 I.e. EnumerateCollidingOctreeItems gets from it's caller
806 8 * 6 Boolean results for it's 8 corner point.
807 Then before recursive calls below it calculates
808 8 + 6 + 1 points versus frustum and passes them down
809 to children. This way instead of evaluating
810 8 points versus frustum in each call (for all nodes, leaves or not),
811 I would be doing 15 evaluations versus frustum but
812 only at non-leaf nodes that collide with frustum as
813 fcSomeCollisionPossible.
814
815 a) answer first : this is actually not necessarily faster,
816 since now in some children first call to
817 Frustum.SphereCollisionPossibleSimple may eliminate
818 any need to compare this child's Box versus Frustum.
819 But above scheme makes an assumption that every child
820 will need to compare it's Box against Frustum.
821
822 b) Honestly, passing down to the recursive calls
823 proper corners prooved to be damn hard to implement
824 with a clear and conside code.
825 I didn't finish it yet. And (because of b))
826 I don't think I will ever do, since it's probably not worth
827 the trouble.
828
829 2) So second idea is to use memoization on point comparison
830 vs frustum planes.
831 This would potentially give me the same advantages as 1)
832 but without it's disadvantage 1.a).
833 I didn't implement it (yet?) simply because I don't
834 believe it's worth the trouble. }
835
836 TreeSubNodes[false, false, false].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
837 TreeSubNodes[false, false, true ].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
838 TreeSubNodes[false, true , false].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
839 TreeSubNodes[false, true , true ].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
840 TreeSubNodes[true , false, false].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
841 TreeSubNodes[true , false, true ].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
842 TreeSubNodes[true , true , false].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
843 TreeSubNodes[true , true , true ].EnumerateCollidingOctreeItems(Frustum, EnumerateOctreeItemsFunc);
844 end;
845 { fcInsideFrustum: } else EnumerateAllItems(true);
846 end;
847 end;
848 end;
849
850 function TOctreeNode.FrustumCollisionPossible(const Frustum: TFrustum): Boolean;
851 begin
852 Result :=
853 Frustum.SphereCollisionPossibleSimple(
854 BoundingSphereCenter, BoundingSphereRadiusSqr) and
855 Frustum.Box3DCollisionPossibleSimple(Box);
856 end;
857
858 procedure TOctreeNode.PushChildrenFrontToBack(List: TOrderedList;
859 const Position: TVector3);
860 var
861 Index: TOctreeSubnodeIndex;
862 begin
863 Index := SubnodeWithPoint(Position);
864 List.Push(TreeSubNodes[Index[0], Index[1], Index[2]]);
865
866 { next, push 3 children with one Index bit negated }
867 List.Push(TreeSubNodes[not Index[0], Index[1], Index[2]]);
868 List.Push(TreeSubNodes[ Index[0], not Index[1], Index[2]]);
869 List.Push(TreeSubNodes[ Index[0], Index[1], not Index[2]]);
870
871 Index[0] := not Index[0];
872 Index[1] := not Index[1];
873 Index[2] := not Index[2];
874
875 { next, push 3 children with two Index bits negated.
876 We just negated all 3 bits, so below we negate one back... }
877 List.Push(TreeSubNodes[not Index[0], Index[1], Index[2]]);
878 List.Push(TreeSubNodes[ Index[0], not Index[1], Index[2]]);
879 List.Push(TreeSubNodes[ Index[0], Index[1], not Index[2]]);
880
881 List.Push(TreeSubNodes[Index[0], Index[1], Index[2]]);
882 end;
883
884 procedure TOctreeNode.PushChildrenBackToFront(List: TOrderedList;
885 const Position: TVector3);
886 var
887 FrontIndex, BackIndex: TOctreeSubnodeIndex;
888 begin
889 FrontIndex := SubnodeWithPoint(Position);
890 BackIndex[0] := not FrontIndex[0];
891 BackIndex[1] := not FrontIndex[1];
892 BackIndex[2] := not FrontIndex[2];
893
894 List.Push(TreeSubNodes[BackIndex[0], BackIndex[1], BackIndex[2]]);
895
896 { next, push 3 children with one BackIndex bit negated }
897 List.Push(TreeSubNodes[not BackIndex[0], BackIndex[1], BackIndex[2]]);
898 List.Push(TreeSubNodes[ BackIndex[0], not BackIndex[1], BackIndex[2]]);
899 List.Push(TreeSubNodes[ BackIndex[0], BackIndex[1], not BackIndex[2]]);
900
901
902 { next, push 3 children with one FrontIndex bit negated. }
903 List.Push(TreeSubNodes[not FrontIndex[0], FrontIndex[1], FrontIndex[2]]);
904 List.Push(TreeSubNodes[ FrontIndex[0], not FrontIndex[1], FrontIndex[2]]);
905 List.Push(TreeSubNodes[ FrontIndex[0], FrontIndex[1], not FrontIndex[2]]);
906
907 List.Push(TreeSubNodes[FrontIndex[0], FrontIndex[1], FrontIndex[2]]);
908 end;
909
910 procedure TOctreeNode.PushChildren(List: TOrderedList);
911 begin
912 List.Push(TreeSubNodes[false, false, false]);
913 List.Push(TreeSubNodes[false, false, true ]);
914 List.Push(TreeSubNodes[false, true , false]);
915 List.Push(TreeSubNodes[false, true , true ]);
916 List.Push(TreeSubNodes[true , false, false]);
917 List.Push(TreeSubNodes[true , false, true ]);
918 List.Push(TreeSubNodes[true , true , false]);
919 List.Push(TreeSubNodes[true , true , true ]);
920 end;
921
922 { TOctree ------------------------------------------------------------ }
923
924 constructor TOctree.Create(const Limits: TOctreeLimits;
925 const ARootBox: TBox3D; AOctreeNodeFinalClass: TOctreeNodeClass;
926 AItemsInNonLeafNodes: Boolean);
927 begin
928 inherited Create;
929 FMaxDepth := Limits.MaxDepth;
930 FLeafCapacity := Limits.LeafCapacity;
931 FOctreeNodeFinalClass := AOctreeNodeFinalClass;
932 FItemsInNonLeafNodes := AItemsInNonLeafNodes;
933 FTreeRoot := OctreeNodeFinalClass.Create(ARootBox, Self, nil, 0, true);
934 end;
935
936 destructor TOctree.Destroy;
937 begin
938 FreeAndNil(FTreeRoot);
939 inherited;
940 end;
941
942 procedure TOctree.EnumerateCollidingOctreeItems(
943 const Frustum: TFrustum;
944 EnumerateOctreeItemsFunc: TEnumerateOctreeItemsFunc);
945 begin
946 Assert(ItemsInNonLeafNodes);
947 FTreeRoot.EnumerateCollidingOctreeItems(
948 Frustum, EnumerateOctreeItemsFunc);
949 end;
950
951 function TOctree.Statistics: string;
952
953 procedure WritelnStatLine(const Header: string;
954 const LeafNodesCount, ItemsInLeafsCount, NonLeafNodesCount: Cardinal);
955 begin
956 Result := Result + Format(
957 ' %-12s%4d leaves (%6d items in leaves), %4d non-leaf nodes.' +nl,
958 [Header, LeafNodesCount, ItemsInLeafsCount, NonLeafNodesCount]);
959 end;
960
961 var
962 LeafNodes: TCardinalList;
963 NonLeafNodes: TCardinalList;
964 ItemsInLeafs: TCardinalList;
965
966 procedure StatNode(TreeNode: TOctreeNode);
967 var
968 B0, B1, B2: Boolean;
969 begin
970 if TreeNode.IsLeaf then
971 begin
972 Inc(LeafNodes.L[TreeNode.Depth]);
973 ItemsInLeafs.L[TreeNode.Depth] := ItemsInLeafs.L[TreeNode.Depth] + Cardinal(TreeNode.ItemsCount);
974 end else
975 begin
976 Inc(NonLeafNodes.L[TreeNode.Depth]);
977 for b0 := Low(Boolean) to High(Boolean) do
978 for b1 := Low(Boolean) to High(Boolean) do
979 for b2 := Low(Boolean) to High(Boolean) do
980 StatNode(TreeNode.TreeSubNodes[b0, b1, b2]);
981 end;
982 end;
983
984 var
985 I: Integer;
986 begin
987 LeafNodes := nil;
988 NonLeafNodes := nil;
989 ItemsInLeafs := nil;
990 try
991 LeafNodes := TCardinalList.Create;
992 LeafNodes.Count := MaxDepth + 1; { TFPGList initialized everything to 0 }
993 NonLeafNodes := TCardinalList.Create;
994 NonLeafNodes.Count := MaxDepth + 1; { TFPGList initialized everything to 0 }
995 ItemsInLeafs := TCardinalList.Create;
996 ItemsInLeafs.Count := MaxDepth + 1; { TFPGList initialized everything to false }
997
998 StatNode(FTreeRoot);
999
1000 Result := 'Octree statistics :' + NL;
1001 for I := 0 to MaxDepth do
1002 begin
1003 WritelnStatLine('Depth '+Format('%3d',[I])+' :',
1004 LeafNodes[I], ItemsInLeafs[I], NonLeafNodes[I]);
1005
1006 if (NonLeafNodes[I] = 0) then
1007 begin
1008 if i < MaxDepth then
1009 Result := Result + Format(
1010 ' No nodes on lower depths (%d ... %d).' + NL, [I+1, MaxDepth]);
1011 break;
1012 end;
1013 end;
1014
1015 Assert(TotalLeafNodes = LeafNodes.BigSum);
1016 Assert(TotalNonLeafNodes = NonLeafNodes.BigSum);
1017 Assert(TotalItemsInLeafs = ItemsInLeafs.BigSum);
1018
1019 WritelnStatLine('SUM :', TotalLeafNodes, TotalItemsInLeafs, TotalNonLeafNodes);
1020
1021 Result := Result + NL + Format(
1022 ' Octree constructed with limits: max depth %d, leaf capacity %d.',
1023 [MaxDepth, LeafCapacity]) + NL;
1024
1025 Result := Result + StatisticsBonus;
1026 finally
1027 FreeAndNil(LeafNodes);
1028 FreeAndNil(NonLeafNodes);
1029 FreeAndNil(ItemsInLeafs);
1030 end;
1031 end;
1032
1033 function TOctree.StatisticsBonus: string;
1034 begin
1035 Result := '';
1036 end;
1037
1038 { some global procs ---------------------------------------------------------- }
1039
1040 function OctreeSubnodeIndexToNiceStr(const SI: TOctreeSubnodeIndex): string;
1041 begin
1042 result :=
1043 BoolToStr(SI[0], true) +'-'+
1044 BoolToStr(SI[1], true) +'-'+
1045 BoolToStr(SI[2], true);
1046 end;
1047
1048 function OctreeSubnodeIndexesEqual(const SI1, SI2: TOctreeSubnodeIndex): Boolean;
1049 begin
1050 result := (SI1[0] = SI2[0]) and
1051 (SI1[1] = SI2[1]) and
1052 (SI1[2] = SI2[2]);
1053 end;
1054
1055 end.