-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOctree.pas
1509 lines (1326 loc) · 51.9 KB
/
Octree.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: Octree<p>
Octree management classes and structures.<p>
TODO: move the many public vars/fields to private/protected<p>
<b>History : </b><font size=-1><ul>
<li>20/07/03 - DanB - Modified SphereSweepIntersect to deal with embedded spheres better
<li>08/05/03 - DanB - name changes + added ClosestPointOnTriangle + fixes
<li>08/05/03 - DanB - added AABBIntersect (Matheus Degiovani)
<li>22/01/03 - EG - GetTrianglesInCube moved in (Bernd Klaiber)
<li>29/11/02 - EG - Added triangleInfo
<li>14/07/02 - EG - Dropped GLvectorFileObjects dependency
<li>17/03/02 - EG - Added SphereIntersectAABB from Robert Hayes
<li>13/03/02 - EG - Made in a standalone unit, based on Robert Hayes code
</ul></font>
}
unit Octree;
interface
uses Classes, VectorGeometry, VectorLists, GeometryBB;
type
TProcInt = procedure(i: integer) of object;
TProcAffineAffineAffine = procedure(v1, v2, v3: TAffineFLTVector) of object;
// TOctreeTriangleInfo
//
{: Stores information about an intersected triangle. }
TOctreeTriangleInfo = record
index : Integer;
vertex : array [0..2] of TAffineVector;
end;
POctreeTriangleInfo = ^TOctreeTriangleInfo;
// TOctreeNode
//
POctreeNode = ^TOctreeNode;
TOctreeNode = record
MinExtent : TAffineFLTVector;
MaxExtent : TAffineFLTVector;
//Duplicates possible?
TriArray : array of Integer; // array of triangle references
ChildArray : array [0..7] of POctreeNode; //Octree's 8 children
end;
// TOctree
//
{: Manages an Octree containing references to triangles.<p> }
TOctree = class (TObject)
private
{ Private Declarations }
{$ifdef DEBUG}
intersections: integer; //for debugging - number of triangles intersecting an AABB plane
{$endif}
triangleFiler : TAffineVectorList;
protected
{ Protected Declarations }
//Find the exact centre of an AABB
function GetMidPoint (min, max: single): single;
//Check if a point lies within the AABB specified by min and max entents
function PointInNode(const min, max, aPoint : TAffineFLTVector): Boolean;
//Check if a triangle (vertices v1, v2, v3) lies within the AABB specified by min and max entents
function TriIntersectNode(const minExtent, maxExtent, v1, v2, v3: TAffineFLTVector): BOOLEAN;
//Check if a sphere (at point C with radius) lies within the AABB specified by min and max entents
function SphereInNode(const minExtent, maxExtent : TAffineVector;
const c: TVector; radius: Single): Boolean;
procedure WalkTriToLeafx(Onode: POctreeNode; const v1, v2, v3 : TAffineFLTVector);
procedure WalkPointToLeafx(ONode: POctreeNode; const p : TAffineVector);
procedure WalkSphereToLeafx(Onode: POctreeNode; const p : TVector; radius : Single);
procedure WalkRayToLeafx(Onode: POctreeNode; const p, v: TVector);
procedure GetExtent (const flags: array of byte; ParentNode: POctreeNode;var result: TAffineFLTVector);
{: Recursive routine to build nodes from parent to max depth level. }
procedure Refine(ParentNode: POctreeNode; level: integer);
//Main "walking" routines. Walks the item through the Octree down to a leaf node.
procedure WalkPointToLeaf(ONode: POctreeNode; const p : TAffineVector);
procedure WalkTriToLeaf(Onode: POctreeNode; const v1, v2, v3 : TAffineVector);
procedure WalkSphereToLeaf(Onode: POctreeNode; const p : TVector; radius : Single);
procedure WalkRayToLeaf(Onode: POctreeNode; const p, v : TVector);
//: Example of how to process each node in the tree
procedure ConvertR4(ONode: POctreeNode; const scale : TAffineFLTVector);
procedure CreateTree(depth: integer);
procedure CutMesh;
public
{ Public Declarations }
WorldMinExtent, WorldMaxExtent: TAffineFLTVector;
RootNode: POctreeNode; //always points to root node
MaxOlevel: integer; //max depth level of TOctreeNode
NodeCount : Integer; //number of nodes (ex: 8 for level 1, 72 for level 2 etc).
TriCountMesh : Integer; //total number of triangles in the mesh
TriCountOctree : Integer; //total number of triangles cut into the octree
MeshCount : Integer; //number of meshes currently cut into the Octree
ResultArray : array of POctreeNode; //holds the result nodes of various calls
{: Initializes the tree from the triangle list.<p>
All triangles must be contained in the world extent to be properly
taken into account. }
procedure InitializeTree(const worldMinExtent, worldMaxExtent : TAffineVector;
const triangles : TAffineVectorList;
const treeDepth : Integer);
procedure DisposeTree;
destructor Destroy; override;
function RayCastIntersect(const rayStart, rayVector : TVector;
intersectPoint : PVector = nil;
intersectNormal : PVector = nil;
triangleInfo : POctreeTriangleInfo = nil) : Boolean;
function SphereSweepIntersect(const rayStart, rayVector : TVector;
const velocity, radius : single;
intersectPoint : PVector = nil;
intersectNormal : PVector = nil) : Boolean;
function TriangleIntersect(const v1, v2, v3: TAffineVector): boolean;
{: Returns all triangles in the AABB. }
function GetTrianglesFromNodesIntersectingAABB(const objAABB : TAABB) : TAffineVectorList;
{: Returns all triangles in an arbitrarily placed cube}
function GetTrianglesFromNodesIntersectingCube(const objAABB : TAABB;
const objToSelf, selfToObj : TMatrix) : TAffineVectorList;
{: Checks if an AABB intersects a face on the octree}
function AABBIntersect(const AABB: TAABB; m1to2, m2to1: TMatrix; triangles: TAffineVectorList = nil): boolean;
// function SphereIntersect(position:TAffineVector; radius:single);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ----------------------------------------------------------------------
// Name : CheckPointInSphere()
// Input : point - point we wish to check for inclusion
// sO - Origin of sphere
// sR - radius of sphere
// Notes :
// Return: TRUE if point is in sphere, FALSE if not.
// -----------------------------------------------------------------------
function CheckPointInSphere(const point, sO : TVector; const sR : Single) : Boolean;
begin
//Allow small margin of error
Result:=(VectorDistance2(point, sO)<=Sqr(sR));
end;
// ----------------------------------------------------------------------
// Name : CheckPointInTriangle()
// Input : point - point we wish to check for inclusion
// a - first vertex in triangle
// b - second vertex in triangle
// c - third vertex in triangle
// Notes : Triangle should be defined in clockwise order a,b,c
// Return: TRUE if point is in triangle, FALSE if not.
// -----------------------------------------------------------------------
function CheckPointInTriangle(point, a, b, c: TAffineVector):boolean;
var
total_angles:Single;
v1,v2,v3:TAffineVector;
begin
total_angles := 0;
// make the 3 vectors
AffineVectorSubtract(point,a, v1 );
AffineVectorSubtract(point,b, v2 );
AffineVectorSubtract(point,c, v3 );
normalizeAffineVector(v1);
normalizeAffineVector(v2);
normalizeAffineVector(v3);
total_angles := total_angles + arccos(AffineVectorDotProduct(v1,v2));
total_angles := total_angles + arccos(AffineVectorDotProduct(v2,v3));
total_angles := total_angles + arccos(AffineVectorDotProduct(v3,v1));
if (abs(total_angles-2*PI) <= 0.005) then
result:= TRUE
else
result:=FALSE;
end;
// ----------------------------------------------------------------------
// Name : ClosestPointOnLine()
// Input : a - first end of line segment
// b - second end of line segment
// p - point we wish to find closest point on line from
// Notes : Helper function for closestPointOnTriangle()
// Return: closest point on line segment
// -----------------------------------------------------------------------
function ClosestPointOnLine(const a, b, p : TAffineVector): TAffineVector;
var d, t: double;
c, v: TAffineFLTVector;
begin
AffineVectorSubtract(p, a, c);
AffineVectorSubtract(b, a, v);
d:=AffineVectorLength(v);
NormalizeAffineVector(v);
t:=AffineVectorDotProduct(v,c);
//Check to see if t is beyond the extents of the line segment
if (t < 0.0) then result:=a
else if (t > d) then result:=b
else begin
v[0]:=v[0]*t;
v[1]:=v[1]*t;
v[2]:=v[2]*t;
AffineVectorAdd(a, v, result);
end;
end;
// ----------------------------------------------------------------------
// Name : ClosestPointOnTriangle()
// Input : a - first vertex in triangle
// b - second vertex in triangle
// c - third vertex in triangle
// p - point we wish to find closest point on triangle from
// Notes :
// Return: closest point on triangle
// -----------------------------------------------------------------------
{
function ClosestPointOnTriangle(const a, b, c, n, p: TAffineVector): TAffineVector;
var
dAB, dBC, dCA : Single;
Rab, Rbc, Rca, intPoint : TAffineFLTVector;
hit:boolean;
begin
//this would be faster if RayCastTriangleIntersect detected backwards hits
hit:=RayCastTriangleIntersect(VectorMake(p),VectorMake(n),a,b,c,@intPoint) or
RayCastTriangleIntersect(VectorMake(p),VectorMake(VectorNegate(n)),a,b,c,@intPoint);
if (hit) then
begin
Result:=intPoint;
end
else
begin
Rab:=ClosestPointOnLine(a, b, p);
Rbc:=ClosestPointOnLine(b, c, p);
Rca:=ClosestPointOnLine(c, a, p);
dAB:=VectorDistance2(p, Rab);
dBC:=VectorDistance2(p, Rbc);
dCA:=VectorDistance2(p, Rca);
if dBC<dAB then
if dCA<dBC then
Result:=Rca
else Result:=Rbc
else if dCA<dAB then
Result:=Rca
else Result:=Rab;
end;
end;
}
// ----------------------------------------------------------------------
// Name : ClosestPointOnTriangleEdge()
// Input : a - first vertex in triangle
// b - second vertex in triangle
// c - third vertex in triangle
// p - point we wish to find closest point on triangle from
// Notes :
// Return: closest point on line triangle edge
// -----------------------------------------------------------------------
function ClosestPointOnTriangleEdge(const a, b, c, p: TAffineVector): TAffineVector;
var
dAB, dBC, dCA : Single;
Rab, Rbc, Rca : TAffineFLTVector;
begin
Rab:=ClosestPointOnLine(a, b, p);
Rbc:=ClosestPointOnLine(b, c, p);
Rca:=ClosestPointOnLine(c, a, p);
dAB:=AffineVectorDistance2(p, Rab);
dBC:=AffineVectorDistance2(p, Rbc);
dCA:=AffineVectorDistance2(p, Rca);
if dBC<dAB then
if dCA<dBC then
Result:=Rca
else Result:=Rbc
else if dCA<dAB then
Result:=Rca
else Result:=Rab;
end;
// HitBoundingBox
//
function HitBoundingBox(const minB, maxB: TAffineFLTVector;
const origin, dir: TVector;
var coord: TVector): BOOLEAN;
const
NUMDIM = 2;
RIGHT = 0;
LEFT = 1;
MIDDLE = 2;
var
i, whichplane: integer;
inside: BOOLEAN;
quadrant: array [0..NUMDIM] of byte;
maxT: array [0..NUMDIM] of double;
candidatePlane: array [0..NUMDIM] of double;
begin
inside := TRUE;
// Find candidate planes; this loop can be avoided if
// rays cast all from the eye(assume perpsective view)
for i:=0 to NUMDIM do begin
if(origin[i] < minB[i]) then begin
quadrant[i] := LEFT;
candidatePlane[i] := minB[i];
inside := FALSE;
end
else if (origin[i] > maxB[i]) then begin
quadrant[i] := RIGHT;
candidatePlane[i] := maxB[i];
inside := FALSE;
end
else quadrant[i] := MIDDLE;
end;
//* Ray origin inside bounding box */
if inside then begin
SetVector(coord, origin);
result:= TRUE;
exit;
end;
//* Calculate T distances to candidate planes */
for i:=0 to NUMDIM do begin
if (quadrant[i] <> MIDDLE) AND (dir[i] <> 0) then
maxT[i] := (candidatePlane[i]-origin[i]) / dir[i]
else
maxT[i] := -1;
end;
//* Get largest of the maxT's for final choice of intersection */
whichPlane := 0;
for i:=1 to NUMDIM do
if (maxT[whichPlane] < maxT[i]) then whichPlane := i;
//* Check final candidate actually inside box */
if (maxT[whichPlane] < 0) then begin
result:=FALSE;
exit;
end;
for i:=0 to NUMDIM do begin
if whichPlane <> i then begin
coord[i] := origin[i] + maxT[whichPlane] * dir[i];
if (coord[i] < minB[i]) OR (coord[i] > maxB[i]) then begin
result:=FALSE;
exit;
end;
end
else coord[i] := candidatePlane[i];
end;
result:=TRUE; //* ray hits box */
end;
const USE_EPSILON_TEST = TRUE;
EPSILON = 0.000001;
// coplanar_tri_tri
//
function coplanar_tri_tri(const N,V0,V1,V2,U0,U1,U2: TAffineFLTVEctor): integer;
var
A: TAffineFLTVector;
i0,i1: shortint;
function EDGE_AGAINST_TRI_EDGES(const V0,V1,U0,U1,U2: TAffineFLTVector): integer;
var
Ax,Ay,Bx,By,Cx,Cy,e,d,f: single;
//* this edge to edge test is based on Franlin Antonio's gem:
// "Faster Line Segment Intersection", in Graphics Gems III,
// pp. 199-202 */
function EDGE_EDGE_TEST(const V0, U0, U1 : TAffineFLTVector) : Integer;
begin
result:=0;
Bx:=U0[i0]-U1[i0];
By:=U0[i1]-U1[i1];
Cx:=V0[i0]-U0[i0];
Cy:=V0[i1]-U0[i1];
f:=Ay*Bx-Ax*By;
d:=By*Cx-Bx*Cy;
if((f>0) and (d>=0) and (d<=f)) or ((f<0) and (d<=0) and (d>=f)) then begin
e:=Ax*Cy-Ay*Cx;
if(f>0) then begin
if (e>=0) and (e<=f) then result:=1
end else if(e<=0) and (e>=f) then result:=1;
end;
end;
begin
Ax:=V1[i0]-V0[i0];
Ay:=V1[i1]-V0[i1];
//* test edge U0,U1 against V0,V1 */
result:=EDGE_EDGE_TEST(V0,U0,U1);
if result=1 then exit;
//* test edge U1,U2 against V0,V1 */
result:=EDGE_EDGE_TEST(V0,U1,U2);
if result=1 then exit;
//* test edge U2,U1 against V0,V1 */
result:=EDGE_EDGE_TEST(V0,U2,U0);
end;
function POINT_IN_TRI(const V0,U0,U1,U2: TAffineFLTVector): integer;
var
a,b,c,d0,d1,d2: single;
begin
result:=0;
//* is T1 completly inside T2? */
//* check if V0 is inside tri(U0,U1,U2) */
a:=U1[i1]-U0[i1];
b:=-(U1[i0]-U0[i0]);
c:=-a*U0[i0]-b*U0[i1];
d0:=a*V0[i0]+b*V0[i1]+c;
a:=U2[i1]-U1[i1];
b:=-(U2[i0]-U1[i0]);
c:=-a*U1[i0]-b*U1[i1];
d1:=a*V0[i0]+b*V0[i1]+c;
a:=U0[i1]-U2[i1];
b:=-(U0[i0]-U2[i0]);
c:=-a*U2[i0]-b*U2[i1];
d2:=a*V0[i0]+b*V0[i1]+c;
if (d0*d1>0.0) then
if (d0*d2>0.0) then result:=1;
end;
/// Begin Main logic ///////////////////////////////
begin
//* first project onto an axis-aligned plane, that maximizes the area */
//* of the triangles, compute indices: i0,i1. */
A[0]:=abs(N[0]);
A[1]:=abs(N[1]);
A[2]:=abs(N[2]);
if(A[0]>A[1]) then begin
if(A[0]>A[2]) then begin
i0:=1; //* A[0] is greatest */
i1:=2;
end else begin
i0:=0; //* A[2] is greatest */
i1:=1;
end
end else begin //* A[0]<=A[1] */
if(A[2]>A[1]) then begin
i0:=0; //* A[2] is greatest */
i1:=1;
end else begin
i0:=0; //* A[1] is greatest */
i1:=2;
end
end;
//* test all edges of triangle 1 against the edges of triangle 2 */
result:=EDGE_AGAINST_TRI_EDGES(V0,V1,U0,U1,U2);
if result=1 then exit;
result:=EDGE_AGAINST_TRI_EDGES(V1,V2,U0,U1,U2);
if result=1 then exit;
result:=EDGE_AGAINST_TRI_EDGES(V2,V0,U0,U1,U2);
if result=1 then exit;
//* finally, test if tri1 is totally contained in tri2 or vice versa */
result:=POINT_IN_TRI(V0,U0,U1,U2);
if result=1 then exit;
result:=POINT_IN_TRI(U0,V0,V1,V2);
end;
// tri_tri_intersect
//
function tri_tri_intersect(const V0,V1,V2,U0,U1,U2: TAFFineFLTVector): integer;
var
E1,E2: TAffineFLTVector;
N1,N2: TAffineFLTVector;
d1,d2: single;
du0,du1,du2,dv0,dv1,dv2: single;
D: TAffineFLTVector;
isect1: array[0..1] of single;
isect2: array[0..1] of single;
du0du1,du0du2,dv0dv1,dv0dv2: single;
index: shortint;
vp0,vp1,vp2: single;
up0,up1,up2: single;
b,c,max: single;
procedure ISECT(VV0,VV1,VV2,D0,D1,D2: single; var isect0,isect1: single);
begin
isect0:=VV0+(VV1-VV0)*D0/(D0-D1);
isect1:=VV0+(VV2-VV0)*D0/(D0-D2);
end;
function COMPUTE_INTERVALS(VV0,VV1,VV2,D0,D1,D2,D0D1,D0D2: single; var isect0,isect1: single): integer;
begin
result:=0;
if(D0D1>0.0) then
//* here we know that D0D2<=0.0 */
//* that is D0, D1 are on the same side, D2 on the other or on the plane */ \
ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1)
else if(D0D2>0.0) then
//* here we know that d0d1<=0.0 */
ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1)
else if(D1*D2>0.0) or (D0<>0.0) then
//* here we know that d0d1<=0.0 or that D0!=0.0 */
ISECT(VV0,VV1,VV2,D0,D1,D2,isect0,isect1)
else if(D1<>0.0) then
ISECT(VV1,VV0,VV2,D1,D0,D2,isect0,isect1)
else if(D2<>0.0) then
ISECT(VV2,VV0,VV1,D2,D0,D1,isect0,isect1)
else
//* triangles are coplanar */
result:=coplanar_tri_tri(N1,V0,V1,V2,U0,U1,U2);
end;
//* sort so that a<=b */
procedure SORT(var a: single; var b: single);
var
c : single;
begin
if (a>b) then begin
c:=a;
a:=b;
b:=c;
end;
end;
begin
//* compute plane equation of triangle(V0,V1,V2) */
AffineVectorSubtract(V1,V0, E1);
AffineVectorSubtract(V2,V0, E2);
AffineVectorCrossProduct(E1, E2, N1);
d1:=-AffineVectorDotProduct(N1,V0);
//* plane equation 1: N1.X+d1=0 */
//* put U0,U1,U2 into plane equation 1 to compute signed distances to the plane*/
du0:=AffineVectorDotProduct(N1,U0)+d1;
du1:=AffineVectorDotProduct(N1,U1)+d1;
du2:=AffineVectorDotProduct(N1,U2)+d1;
//* coplanarity robustness check */
if USE_EPSILON_TEST=TRUE then begin
if (abs(du0)<EPSILON) then du0:=0.0;
if (abs(du1)<EPSILON) then du1:=0.0;
if (abs(du2)<EPSILON) then du2:=0.0;
end;
du0du1:=du0*du1;
du0du2:=du0*du2;
if(du0du1>0.0) and (du0du2>0.0) then begin//* same sign on all of them + not equal 0 ? */
result:=0; //* no intersection occurs */
exit;
end;
//* compute plane of triangle (U0,U1,U2) */
AffineVectorSubtract(U1,U0, E1);
AffineVectorSubtract(U2,U0, E2);
AffineVectorCrossProduct(E1, E2, N2);
d2:=-AffineVectorDotProduct(N2,U0);
//* plane equation 2: N2.X+d2=0 */
//* put V0,V1,V2 into plane equation 2 */
dv0:=AffineVectorDotProduct(N2,V0)+d2;
dv1:=AffineVectorDotProduct(N2,V1)+d2;
dv2:=AffineVectorDotProduct(N2,V2)+d2;
if USE_EPSILON_TEST=TRUE then begin
if(abs(dv0)<EPSILON) then dv0:=0.0;
if(abs(dv1)<EPSILON) then dv1:=0.0;
if(abs(dv2)<EPSILON) then dv2:=0.0;
end;
dv0dv1:=dv0*dv1;
dv0dv2:=dv0*dv2;
if(dv0dv1>0.0) and (dv0dv2>0.0) then begin //* same sign on all of them + not equal 0 ? */
result:=0; //* no intersection occurs */
exit;
end;
//* compute direction of intersection line */
AffineVectorCrossProduct(N1, N2, D);
//* compute and index to the largest component of D */
max:=abs(D[0]);
index:=0;
b:=abs(D[1]);
c:=abs(D[2]);
if(b>max) then begin
max:=b; index:=1;
end;
if(c>max) then begin
//max:=c; why?
index:=2;
end;
//* this is the simplified projection onto L*/
vp0:=V0[index];
vp1:=V1[index];
vp2:=V2[index];
up0:=U0[index];
up1:=U1[index];
up2:=U2[index];
//* compute interval for triangle 1 */
COMPUTE_INTERVALS(vp0,vp1,vp2,dv0,dv1,dv2,dv0dv1,dv0dv2,isect1[0],isect1[1]);
//* compute interval for triangle 2 */
COMPUTE_INTERVALS(up0,up1,up2,du0,du1,du2,du0du1,du0du2,isect2[0],isect2[1]);
SORT(isect1[0],isect1[1]);
SORT(isect2[0],isect2[1]);
if (isect1[1]<isect2[0]) or (isect2[1]<isect1[0]) then
result:=0
else result:=1;
end;
// ------------------
// ------------------ TOctree ------------------
// ------------------
const MIN = 0;
const MID = 1;
const MAX = 2;
const POINT = 0;
const TRIANGLE = 1;
const TOPFACE = 0;
const BOTTOMFACE = 1;
const LEFTFACE = 2;
const RIGHTFACE = 3;
const FRONTFACE = 4;
const BACKFACE = 5;
const TOPLEFT = 0;
const TOPRIGHT = 1;
const BOTTOMLEFT = 2;
const BOTTOMRIGHT = 3;
// Theory on FlagMax and FlagMin:
// When a node is subdivided, each of the 8 children assumes 1/8th ownership of its
// parent's bounding box (defined by parent extents). Calculating a child's min/max
// extent only requires 3 values: the parent's min extent, the parent's max extent
// and the midpoint of the parent's extents (since the cube is divided in half twice).
// The following arrays assume that the children are numbered from 0 to 7, named Upper
// and Lower (Upper = top 4 cubes on Y axis, Bottom = lower 4 cubes), Left and Right, and
// Fore and Back (Fore facing furthest away from you the viewer).
// Each node can use its corresponding element in the array to flag the operation needed
// to find its new min/max extent. Note that min, mid and max refer to an array of
// 3 coordinates (x,y,z); each of which are flagged separately. Also note that these
// flags are based on the Y vector being the up vector.
const
FlagMax: array[0..7] of array [0..2] of byte = (
(MID,MAX,MAX), //Upper Fore Left
(MAX,MAX,MAX), //Upper Fore Right
(MID,MAX,MID), //Upper Back Left
(MAX,MAX,MID), //Upper Back Right
(MID,MID,MAX), //Lower Fore Left (similar to above except height/2)
(MAX,MID,MAX), //Lower Fore Right
(MID,MID,MID), //Lower Back Left
(MAX,MID,MID) //Lower Back Right
);
FlagMin: array[0..7] of array [0..2] of byte = (
(MIN,MID,MID), //Upper Fore Left
(MID,MID,MID), //Upper Fore Right
(MIN,MID,MIN), //Upper Back Left
(MID,MID,MIN), //Upper Back Right
(MIN,MIN,MID), //Lower Fore Left (similar to above except height/2)
(MID,MIN,MID), //Lower Fore Right
(MIN,MIN,MIN), //Lower Back Left
(MID,MIN,MIN) //Lower Back Right
);
//Design of the AABB faces, using similar method to above.. Note than normals are not
//correct, but not needed for current tri-intersection test.
//Could be removed if the tri-plane collision is replaced with a tri-box routine.
FlagFaces: array [0..23] of array[0..2] of byte = (
//Top Face
(MIN,MAX,MAX), //Upper left corner
(MAX,MAX,MAX), //Upper right corner
(MAX,MIN,MAX), //Bottom right corner
(MIN,MIN,MAX),
//Bottom Face
(MIN,MAX,MIN), //Upper left corner
(MAX,MAX,MIN), //Upper right corner
(MAX,MIN,MIN), //Bottom right corner
(MIN,MIN,MIN),
//Back Face
(MIN,MAX,MAX), //Upper left corner
(MAX,MAX,MAX), //Upper right corner
(MAX,MAX,MIN), //Bottom right corner
(MIN,MAX,MIN),
//Front Face
(MIN,MIN,MAX), //Upper left corner
(MAX,MIN,MAX), //Upper right corner
(MAX,MIN,MIN), //Bottom right corner
(MIN,MIN,MIN),
//Left Face
(MIN,MAX,MAX), //Upper left corner
(MIN,MIN,MAX), //Upper right corner
(MIN,MIN,MIN), //Bottom right corner
(MIN,MAX,MIN),
//Right Face
(MAX,MIN,MAX), //Upper left corner
(MAX,MAX,MAX), //Upper right corner
(MAX,MAX,MIN), //Bottom right corner
(MAX,MIN,MIN));
// Destroy
//
destructor TOctree.Destroy;
begin
DisposeTree;
inherited Destroy;
end;
// DisposeTree
//
procedure TOctree.DisposeTree;
procedure WalkDispose(var node : POctreeNode);
var
i : Integer;
begin
if Assigned(node) then begin
for i:=0 to 7 do
WalkDispose(node.ChildArray[i]);
Dispose(node);
end;
end;
begin
WalkDispose(RootNode);
RootNode:=nil;
end;
// CreateTree
//
procedure TOctree.CreateTree(depth : Integer);
begin
MaxOlevel:=depth; //initialize max depth.
Refine(rootnode, 0);
end;
// "cuts" all the triangles in the mesh into the octree.
procedure TOctree.CutMesh;
procedure AddTriangleToNodes(n: integer);
var
x, k : integer;
p : POctreeNode;
begin
for x:=0 to High(resultArray) do begin
p:=resultarray[x]; // Pointer to a node.
k:=Length(p.TriArray);
SetLength(p.TriArray, k+1); // Increase array by 1.
p.TriArray[k]:=n; // Store triangle # reference.
{$ifdef DEBUG}
Inc(intersections);
{$endif}
end;
end;
var
n : Integer; //n = triangle # in mesh
begin
TriCountMesh:=triangleFiler.Count div 3;
n:=0;
while n<triangleFiler.Count do begin
WalkTriToLeaf(RootNode, triangleFiler.List[n],
triangleFiler.List[n+1],
triangleFiler.List[n+2]);
if resultArray <> NIL then begin
AddTriangleToNodes(n);
Inc(TriCountOctree, 1);
end;
Inc(n, 3);
end;
end;
function TOctree.GetMidPoint(min, max: single): single;
begin
result:=max/2+min/2; //This formula is non-quadrant specific; ie: good.
end;
procedure TOctree.GetExtent(const flags: array of byte; ParentNode: POctreeNode ;var result: TAffineFLTVector);
var emin, emax: TAffineFLTVector;
n: integer;
begin
emin:=ParentNode^.MinExtent; //Some easy to work with variables.
emax:=ParentNode^.MaxExtent;
for n:=0 to 2 do begin
case flags[n] of
MIN: result[n]:=emin[n];
MID: result[n]:=GetMidPoint(emin[n],emax[n]);
MAX: result[n]:=emax[n];
end;
end;
end;
// InitializeTree
//
procedure TOctree.InitializeTree(const worldMinExtent, worldMaxExtent : TAffineVector;
const triangles : TAffineVectorList;
const treeDepth : Integer);
var
n : Integer;
newnode : POctreeNode;
begin
Self.WorldMinExtent:=worldMinExtent;
Self.WorldMaxExtent:=worldMaxExtent;
//set up the filer data for this mesh
if triangleFiler=nil then
triangleFiler:=TAffineVectorList.Create;
triangleFiler.Assign(triangles);
New(newnode);
newnode^.MinExtent:=WorldMinExtent;
newnode^.MaxExtent:=WorldMaxExtent;
newnode^.TriArray:=NIL;
for n:=0 to 7 do newnode^.ChildArray[n]:=NIL;
//Initialize work variables for new tree.
rootnode:=newnode; //rootnode always points to root.
NodeCount:=0; //initialize node count
CreateTree(treeDepth);
CutMesh;
end;
// Refine
//
procedure TOctree.Refine(parentNode : POctreeNode; level : Integer);
var
n, x, z : Integer;
pwork : array [0..7] of POctreeNode; //Stores addresses of newly created children.
newnode : POctreeNode;
begin
if level < MaxOlevel then begin
for n:=0 to 7 do begin //Create 8 new children under this parent.
Inc(NodeCount);
New(newnode);
Pwork[n]:=newnode; //Create work pointers for the next for loop.
//Generate new extents based on parent's extents
GetExtent(flagMin[n], ParentNode, newnode^.MinExtent);
GetExtent(flagMax[n], ParentNode, newnode^.MaxExtent);
newnode^.TriArray:=nil; //Initialize.
for z:=0 to 7 do
newnode^.ChildArray[z]:=nil; //initialize all child pointers to NIL
ParentNode^.ChildArray[n]:=newnode; //initialize parent's child pointer to this node
end;
for x:=0 to 7 do // Now recursively Refine each child we just made
Refine(pwork[x], level+1);
end; //end if
end;
// ConvertR4
//
procedure TOctree.ConvertR4(ONode: POctreeNode; const scale : TAffineFLTVector);
var
n: smallint;
begin
ScaleAffineVector(Onode.MinExtent, scale);
ScaleAffineVector(Onode.MaxExtent, scale);
if ONode.ChildArray[0] <> NIL then begin //ie: if not a leaf then loop through children.
for n:=0 to 7 do begin
ConvertR4(Onode.ChildArray[n], scale);
end;
end
end;
// PointInNode
//
function TOctree.PointInNode(const min, max, aPoint: TAffineFLTVector) : BOOLEAN;
begin
Result:=(aPoint[0]>=min[0]) and (aPoint[1]>=min[1]) and (aPoint[2]>=min[2])
and (aPoint[0]<=max[0]) and (aPoint[1]<=max[1]) and (aPoint[2]<=max[2]);
end;
// WalkPointToLeaf
//
procedure TOctree.WalkPointToLeaf(Onode: POctreeNode; const p : TAffineVector);
begin
Finalize(resultarray);
WalkPointToLeafx(Onode, p);
end;
// WalkPointToLeafx
//
procedure TOctree.WalkPointToLeafx(Onode: POctreeNode; const p : TAffineVector);
var
n : integer;
begin
if PointInNode(Onode.MinExtent, Onode.MaxExtent, p) then begin
if Assigned(Onode.ChildArray[0]) then
for n:=0 to 7 do
WalkPointToLeafx(Onode.ChildArray[n], p)
else begin
SetLength(resultarray, Length(resultarray)+1);
resultarray[High(resultarray)]:=Onode;
end;
end;
end;
// SphereInNode
//
function TOctree.SphereInNode(const minExtent, maxExtent : TAffineVector;
const c : TVector; radius : Single): Boolean;
//Sphere-AABB intersection by Miguel Gomez
var
s, d : Single;
i : Integer;
begin
//find the square of the distance
//from the sphere to the box
d:=0;
for i:=0 to 2 do
begin
if(C[i] < MinExtent[i]) then
begin
s := C[i] - MinExtent[i];
d := d + s*s;
end
else if(C[i] > MaxExtent[i]) then
begin
s := C[i] - MaxExtent[i];
d := d + s*s;
end;
end; //end for
if d<= radius*radius then
result:=TRUE
else
result:=FALSE;
end;
// WalkSphereToLeaf
//
procedure TOctree.WalkSphereToLeaf(Onode : POctreeNode; const p : TVector;
radius : Single);
begin
Finalize(resultarray);
WalkSphereToLeafx(Onode, p, radius);
end;
// WalkSphereToLeafx
//
procedure TOctree.WalkSphereToLeafx(Onode : POctreeNode; const p : TVector;
radius : Single);
var
n : integer;
begin
if SphereInNode(Onode.MinExtent, Onode.MaxExtent, p, radius) then begin
if Assigned(Onode.ChildArray[0]) then
for n:=0 to 7 do
WalkSphereToLeafx(Onode.ChildArray[n], p, radius)
else begin
SetLength(resultarray, Length(resultarray)+1);