forked from juj/MathGeoLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTriangle.cpp
2002 lines (1803 loc) · 54.5 KB
/
Triangle.cpp
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
/* Copyright Jukka Jylänki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/** @file Triangle.cpp
@author Jukka Jylänki
@brief Implementation for the Triangle geometry object. */
#include "Triangle.h"
#include "../Math/MathFunc.h"
#include "../Math/float2.h"
#include "../Math/float3.h"
#include "../Math/float3x3.h"
#include "../Math/float3x4.h"
#include "../Math/float4x4.h"
#include "../Math/Quat.h"
#include "Capsule.h"
#include "Frustum.h"
#include "Plane.h"
#include "Polygon.h"
#include "Polyhedron.h"
#include "Line.h"
#include "LineSegment.h"
#include "Ray.h"
#include "Sphere.h"
#include "AABB.h"
#include "OBB.h"
#include "../Algorithm/Random/LCG.h"
#ifdef MATH_ENABLE_STL_SUPPORT
#include <iostream>
#endif
#if defined(MATH_SSE) && defined(MATH_AUTOMATIC_SSE)
#include "../Math/float4_sse.h"
#include "../Math/float4_neon.h"
#endif
MATH_BEGIN_NAMESPACE
Triangle::Triangle(const vec &a_, const vec &b_, const vec &c_)
:a(a_), b(b_), c(c_)
{
}
void Triangle::Translate(const vec &offset)
{
a += offset;
b += offset;
c += offset;
}
void Triangle::Transform(const float3x3 &transform)
{
transform.BatchTransform(&a, 3);
}
void Triangle::Transform(const float3x4 &transform)
{
transform.BatchTransformPos(&a, 3);
}
void Triangle::Transform(const float4x4 &transform)
{
a = transform.MulPos(a);
b = transform.MulPos(b);
c = transform.MulPos(c);
}
void Triangle::Transform(const Quat &transform)
{
a = transform * a;
b = transform * b;
c = transform * c;
}
/// Implementation from Christer Ericson's Real-Time Collision Detection, pp. 51-52.
inline float TriArea2D(float x1, float y1, float x2, float y2, float x3, float y3)
{
return (x1-x2)*(y2-y3) - (x2-x3)*(y1-y2);
}
float3 Triangle::BarycentricUVW(const vec &point) const
{
// Implementation from Christer Ericson's Real-Time Collision Detection, pp. 51-52.
// Unnormalized triangle normal.
vec m = Cross(b-a, c-a);
// Nominators and one-over-denominator for u and v ratios.
float nu, nv, ood;
// Absolute components for determining projection plane.
float x = Abs(m.x);
float y = Abs(m.y);
float z = Abs(m.z);
if (x >= y && x >= z)
{
// Project to the yz plane.
nu = TriArea2D(point.y, point.z, b.y, b.z, c.y, c.z); // Area of PBC in yz-plane.
nv = TriArea2D(point.y, point.z, c.y, c.z, a.y, a.z); // Area OF PCA in yz-plane.
ood = 1.f / m.x; // 1 / (2*area of ABC in yz plane)
}
else if (y >= z) // Note: The book has a redundant 'if (y >= x)' comparison
{
// y is largest, project to the xz-plane.
nu = TriArea2D(point.x, point.z, b.x, b.z, c.x, c.z);
nv = TriArea2D(point.x, point.z, c.x, c.z, a.x, a.z);
ood = 1.f / -m.y;
}
else // z is largest, project to the xy-plane.
{
nu = TriArea2D(point.x, point.y, b.x, b.y, c.x, c.y);
nv = TriArea2D(point.x, point.y, c.x, c.y, a.x, a.y);
ood = 1.f / m.z;
}
float u = nu * ood;
float v = nv * ood;
float w = 1.f - u - v;
return float3(u,v,w);
#if 0 // TODO: This version should be more SIMD-friendly, but for some reason, it doesn't return good values for all points inside the triangle.
vec v0 = b - a;
vec v1 = c - a;
vec v2 = point - a;
float d00 = Dot(v0, v0);
float d01 = Dot(v0, v1);
float d02 = Dot(v0, v2);
float d11 = Dot(v1, v1);
float d12 = Dot(v1, v2);
float denom = 1.f / (d00 * d11 - d01 * d01);
float v = (d11 * d02 - d01 * d12) * denom;
float w = (d00 * d12 - d01 * d02) * denom;
float u = 1.0f - v - w;
return vec(u, v, w);
#endif
}
float2 Triangle::BarycentricUV(const vec &point) const
{
float3 uvw = BarycentricUVW(point);
return float2(uvw.y, uvw.z);
}
bool Triangle::BarycentricInsideTriangle(const float3 &barycentric)
{
return barycentric.x >= 0.f && barycentric.y >= 0.f && barycentric.z >= 0.f &&
EqualAbs(barycentric.x + barycentric.y + barycentric.z, 1.f);
}
vec Triangle::Point(float u, float v) const
{
// In case the triangle is far away from the origin but is small in size, the elements of 'a' will have large magnitudes,
// and the elements of (b-a) and (c-a) will be much smaller quantities. Therefore be extra careful with the
// parentheses and first sum the small floats together before adding it to the large one.
return a + ((b-a) * u + (c-a) * v);
}
vec Triangle::Point(float u, float v, float w) const
{
return u * a + v * b + w * c;
}
vec Triangle::Point(const float3 &uvw) const
{
return Point(uvw.x, uvw.y, uvw.z);
}
vec Triangle::Point(const float2 &uv) const
{
return Point(uv.x, uv.y);
}
vec Triangle::Centroid() const
{
return (a + b + c) * (1.f/3.f);
}
float Triangle::Area() const
{
return 0.5f * Cross(b-a, c-a).Length();
}
float Triangle::Perimeter() const
{
return a.Distance(b) + b.Distance(c) + c.Distance(a);
}
LineSegment Triangle::Edge(int i) const
{
assume(0 <= i);
assume(i <= 2);
if (i == 0)
return LineSegment(a, b);
else if (i == 1)
return LineSegment(b, c);
else if (i == 2)
return LineSegment(c, a);
else
return LineSegment(vec::nan, vec::nan);
}
vec Triangle::Vertex(int i) const
{
assume(0 <= i);
assume(i <= 2);
if (i == 0)
return a;
else if (i == 1)
return b;
else if (i == 2)
return c;
else
return vec::nan;
}
Plane Triangle::PlaneCCW() const
{
return Plane(a, b, c);
}
Plane Triangle::PlaneCW() const
{
return Plane(a, c, b);
}
vec Triangle::NormalCCW() const
{
return UnnormalizedNormalCCW().Normalized();
}
vec Triangle::NormalCW() const
{
return UnnormalizedNormalCW().Normalized();
}
vec Triangle::UnnormalizedNormalCCW() const
{
return Cross(b-a, c-a);
}
vec Triangle::UnnormalizedNormalCW() const
{
return Cross(c-a, b-a);
}
vec Triangle::ExtremePoint(const vec &direction) const
{
vec mostExtreme = vec::nan;
float mostExtremeDist = -FLT_MAX;
for(int i = 0; i < 3; ++i)
{
vec pt = Vertex(i);
float d = Dot(direction, pt);
if (d > mostExtremeDist)
{
mostExtremeDist = d;
mostExtreme = pt;
}
}
return mostExtreme;
}
vec Triangle::ExtremePoint(const vec &direction, float &projectionDistance) const
{
vec extremePoint = ExtremePoint(direction);
projectionDistance = extremePoint.Dot(direction);
return extremePoint;
}
Polygon Triangle::ToPolygon() const
{
Polygon p;
p.p.push_back(a);
p.p.push_back(b);
p.p.push_back(c);
return p;
}
Polyhedron Triangle::ToPolyhedron() const
{
return ToPolygon().ToPolyhedron();
}
AABB Triangle::BoundingAABB() const
{
AABB aabb;
aabb.minPoint = Min(a, b, c);
aabb.maxPoint = Max(a, b, c);
return aabb;
}
float Triangle::Area2D(const float2 &p1, const float2 &p2, const float2 &p3)
{
return (p1.x - p2.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p2.y);
}
float Triangle::SignedArea(const vec &pt, const vec &a, const vec &b, const vec &c)
{
return Dot(Cross(b-pt, c-pt), Cross(b-a, c-a).Normalized());
}
bool Triangle::IsFinite() const
{
return a.IsFinite() && b.IsFinite() && c.IsFinite();
}
bool Triangle::IsDegenerate(float epsilon) const
{
return IsDegenerate(a, b, c, epsilon);
}
bool Triangle::IsDegenerate(const vec &a, const vec &b, const vec &c, float epsilon)
{
return a.Equals(b, epsilon) || a.Equals(c, epsilon) || b.Equals(c, epsilon);
}
bool Triangle::Contains(const vec &point, float triangleThicknessSq) const
{
vec normal = (b-a).Cross(c-a);
float lenSq = normal.LengthSq();
float d = normal.Dot(b - point);
if (d*d > triangleThicknessSq * lenSq)
return false; ///@todo The plane-point distance test is omitted in Real-Time Collision Detection. p. 25. A bug in the book?
float3 br = BarycentricUVW(point);
return br.x >= -1e-3f && br.y >= -1e-3f && br.z >= -1e-3f; // Allow for a small epsilon to properly account for points very near the edges of the triangle.
}
bool Triangle::Contains(const LineSegment &lineSegment, float triangleThickness) const
{
return Contains(lineSegment.a, triangleThickness) && Contains(lineSegment.b, triangleThickness);
}
bool Triangle::Contains(const Triangle &triangle, float triangleThickness) const
{
return Contains(triangle.a, triangleThickness) && Contains(triangle.b, triangleThickness)
&& Contains(triangle.c, triangleThickness);
}
/*
bool Triangle::Contains(const Polygon &polygon, float triangleThickness) const
{
if (polygon.points.size() == 0)
return false;
for(int i = 0; i < polygon.points.size(); ++i)
if (!Contains(polygon.points[i], triangleThickness))
return false;
return true;
}
*/
float Triangle::Distance(const vec &point) const
{
return ClosestPoint(point).Distance(point);
}
float Triangle::DistanceSq(const vec &point) const
{
return ClosestPoint(point).DistanceSq(point);
}
float Triangle::Distance(const Sphere &sphere) const
{
return Max(0.f, Distance(sphere.pos) - sphere.r);
}
float Triangle::Distance(const Capsule &capsule) const
{
vec otherPt;
vec thisPt = ClosestPoint(capsule.l, &otherPt);
return Max(0.f, thisPt.Distance(otherPt) - capsule.r);
}
/** Calculates the intersection between a line and a triangle. The facing is not accounted for, so
rays are reported to intersect triangles that are both front and backfacing.
According to "T. Möller, B. Trumbore. Fast, Minimum Storage Ray/Triangle Intersection. 2005."
http://jgt.akpeters.com/papers/MollerTrumbore97/
@param linePos The starting point of the line.
@param lineDir The direction vector of the line. This does not need to be normalized.
@param v0 Vertex 0 of the triangle.
@param v1 Vertex 1 of the triangle.
@param v2 Vertex 2 of the triangle.
@param u [out] The barycentric u coordinate is returned here if an intersection occurred.
@param v [out] The barycentric v coordinate is returned here if an intersection occurred.
@return The distance along the ray to the point of intersection, or +inf if no intersection occurred.
If no intersection, then u and v and t will contain undefined values. If lineDir was not normalized, then to get the
real world-space distance, one must scale the returned value with lineDir.Length(). If the returned value is negative,
then the intersection occurs 'behind' the line starting position, with respect to the direction vector lineDir. */
float Triangle::IntersectLineTri(const vec &linePos, const vec &lineDir,
const vec &v0, const vec &v1, const vec &v2,
float &u, float &v)
{
const float epsilon = 1e-4f;
// Edge vectors
vec vE1 = v1 - v0;
vec vE2 = v2 - v0;
// begin calculating determinant - also used to calculate U parameter
vec vP = lineDir.Cross(vE2);
// If det < 0, intersecting backfacing tri, > 0, intersecting frontfacing tri, 0, parallel to plane.
const float det = vE1.Dot(vP);
// If determinant is near zero, ray lies in plane of triangle.
if (Abs(det) <= epsilon)
return FLOAT_INF;
const float recipDet = 1.f / det;
// Calculate distance from v0 to ray origin
vec vT = linePos - v0;
// Output barycentric u
u = vT.Dot(vP) * recipDet;
if (u < -epsilon || u > 1.f + epsilon)
return FLOAT_INF; // Barycentric U is outside the triangle - early out.
// Prepare to test V parameter
vec vQ = vT.Cross(vE1);
// Output barycentric v
v = lineDir.Dot(vQ) * recipDet;
if (v < -epsilon || u + v > 1.f + epsilon) // Barycentric V or the combination of U and V are outside the triangle - no intersection.
return FLOAT_INF;
// Barycentric u and v are in limits, the ray intersects the triangle.
// Output signed distance from ray to triangle.
return vE2.Dot(vQ) * recipDet;
// return (det < 0.f) ? IntersectBackface : IntersectFrontface;
}
/// [groupSyntax]
bool Triangle::Intersects(const LineSegment &l, float *d, vec *intersectionPoint) const
{
/** The Triangle-Line/LineSegment/Ray intersection tests are based on Möller-Trumbore method:
"T. Möller, B. Trumbore. Fast, Minimum Storage Ray/Triangle Intersection. 2005."
http://jgt.akpeters.com/papers/MollerTrumbore97/. */
float u, v;
float t = IntersectLineTri(l.a, l.b - l.a, a, b, c, u, v);
bool success = (t >= 0.0f && t <= 1.0f);
if (!success)
return false;
if (d)
*d = t;
if (intersectionPoint)
*intersectionPoint = l.GetPoint(t);
return true;
}
bool Triangle::Intersects(const Line &l, float *d, vec *intersectionPoint) const
{
float u, v;
float t = IntersectLineTri(l.pos, l.dir, a, b, c, u, v);
bool success = (t != FLOAT_INF);
if (!success)
return false;
if (d)
*d = t;
if (intersectionPoint)
*intersectionPoint = l.GetPoint(t);
return success;
}
bool Triangle::Intersects(const Ray &r, float *d, vec *intersectionPoint) const
{
float u, v;
float t = IntersectLineTri(r.pos, r.dir, a, b, c, u, v);
bool success = (t >= 0 && t != FLOAT_INF);
if (!success)
return false;
if (d)
*d = t;
if (intersectionPoint)
*intersectionPoint = r.GetPoint(t);
return success;
}
bool Triangle::Intersects(const Plane &plane) const
{
return plane.Intersects(*this);
}
/// [groupSyntax]
/** For Triangle-Sphere intersection code, see Christer Ericson's Real-Time Collision Detection, p.167. */
bool Triangle::Intersects(const Sphere &sphere, vec *closestPointOnTriangle) const
{
vec pt = ClosestPoint(sphere.pos);
if (closestPointOnTriangle)
*closestPointOnTriangle = pt;
return pt.DistanceSq(sphere.pos) <= sphere.r * sphere.r;
}
bool Triangle::Intersects(const Sphere &sphere) const
{
return Intersects(sphere, 0);
}
static void FindIntersectingLineSegments(const Triangle &t, float da, float db, float dc, LineSegment &l1, LineSegment &l2)
{
if (da*db > 0.f)
{
l1 = LineSegment(t.a, t.c);
l2 = LineSegment(t.b, t.c);
}
else if (db*dc > 0.f)
{
l1 = LineSegment(t.a, t.b);
l2 = LineSegment(t.a, t.c);
}
else
{
l1 = LineSegment(t.a, t.b);
l2 = LineSegment(t.b, t.c);
}
}
int IntervalIntersection(float u0, float u1, float v0, float v1, float &s, float &t)
{
if (u1 < v0 || u0 > v1)
{
s = t = FLOAT_NAN;
return 0;
}
if (u1 > v0)
{
if (u0 < v1)
{
s = Max(u0, v0);
t = Min(u1, v1);
return 2;
}
else // u0 == v1
{
s = t = u0;
return 1;
}
}
else
{
// u1 == v0
s = t = u1;
return 1;
}
}
/// 2D line segment-line segment intersection from Geometric Tools for Computer Graphics, pp. 807-813, by Schneider and Eberly.
bool LineSegment2DLineSegment2DIntersect(const float2 &p0, const float2 &dir0, const float2 &p1, const float2 &dir1, float &s, float &t)
{
float2 e = p1 - p0;
float cross = dir0.PerpDot(dir1);
float sqrCross = cross*cross;
float sqrLen0 = dir0.LengthSq();
float sqrLen1 = dir1.LengthSq();
const float sqrEpsilon = 1e-8f;
if (sqrCross > sqrEpsilon * sqrLen0 * sqrLen1)
{
// The lines are not parallel
s = e.PerpDot(dir1) / cross;
t = e.PerpDot(dir0) / cross;
// The intersection point is p0 + s * dir0;
return s >= 0.f && s <= 1.f && t >= 0.f && t <= 1.f;
}
// The line segments are parallel
float sqrLenE = e.LengthSq();
cross = e.PerpDot(dir0);
sqrCross = cross*cross;
if (sqrCross > sqrEpsilon * sqrLen0 * sqrLenE)
{
// The lines are at a positive distance, no intersection.
s = t = FLOAT_NAN;
return false;
}
// The line segments are along the same line. Do an overlap test.
float s0 = Dot(dir0, e) / sqrLen0;
float s1 = s0 + Dot(dir0, dir1) / sqrLen0;
float smin = Min(s0, s1);
float smax = Max(s0, s1);
int nIntersections = IntervalIntersection(0.f, 1.f, smin, smax, s, t);
return nIntersections > 0.f;
}
/// [groupSyntax]
/** The Triangle-Triangle test implementation is based on pseudo-code from Tomas Möller's
"A Fast Triangle-Triangle Intersection Test": http://jgt.akpeters.com/papers/Moller97/.
See also Christer Ericson's Real-Time Collision Detection, p. 172. */
bool Triangle::Intersects(const Triangle &t2, LineSegment *outLine) const
{
const float triangleThickness = 1e-4f;
// Is the triangle t2 completely on one side of the plane of this triangle?
Plane p1 = this->PlaneCCW();
Plane p2 = t2.PlaneCCW();
if (!p1.normal.Cross(p2.normal).IsZero())
{
float t2da = p1.SignedDistance(t2.a);
float t2db = p1.SignedDistance(t2.b);
float t2dc = p1.SignedDistance(t2.c);
float t2min = Min(Min(t2da, t2db), t2dc);
float t2max = Max(Max(t2da, t2db), t2dc);
if (t2max < -triangleThickness || t2min > triangleThickness)
return false;
// Is this triangle completely on one side of the plane of the triangle t2?
float t1da = p2.SignedDistance(this->a);
float t1db = p2.SignedDistance(this->b);
float t1dc = p2.SignedDistance(this->c);
float t1min = Min(Min(t1da, t1db), t1dc);
float t1max = Max(Max(t1da, t1db), t1dc);
if (t1max < -triangleThickness || t1min > triangleThickness)
return false;
// Find the intersection line of the two planes.
Line l;
bool success = p1.Intersects(p2, &l);
assume(success); // We already determined the two triangles have intersecting planes, so this should always succeed.
if (!success)
return false;
// Find the two line segments of both triangles which straddle the intersection line.
LineSegment l1a, l1b;
LineSegment l2a, l2b;
FindIntersectingLineSegments(*this, t1da, t1db, t1dc, l1a, l1b);
FindIntersectingLineSegments(t2, t2da, t2db, t2dc, l2a, l2b);
// Find the projection intervals on the intersection line.
float d1a, d1b, d2a, d2b;
l.Distance(l1a, d1a);
l.Distance(l1b, d1b);
l.Distance(l2a, d2a);
l.Distance(l2b, d2b);
if (d1a > d1b)
Swap(d1a, d1b);
if (d2a > d2b)
Swap(d2a, d2b);
float rStart = Max(d1a, d2a);
float rEnd = Min(d1b, d2b);
if (rStart <= rEnd)
{
if (outLine)
*outLine = LineSegment(l.GetPoint(rStart), l.GetPoint(rEnd));
return true;
}
return false;
}
else // The two triangles lie in the same plane. Perform the intersection test in 2D.
{
float tri0Pos = p1.normal.Dot(a);
float tri1Pos = p1.normal.Dot(t2.a);
if (Abs(tri0Pos-tri1Pos) > triangleThickness)
return false;
if (t2.Contains(a, FLOAT_INF) || this->Contains(t2.a, FLOAT_INF))
return true;
vec basisU, basisV;
p1.normal.PerpendicularBasis(basisU, basisV);
float2 a1 = float2::zero;
float2 a2 = float2(basisU.Dot(b-a), basisV.Dot(b-a));
float2 a3 = float2(basisU.Dot(c-a), basisV.Dot(c-a));
float2 b1 = float2(basisU.Dot(t2.a-a), basisV.Dot(t2.a-a));
float2 b2 = float2(basisU.Dot(t2.b-a), basisV.Dot(t2.b-a));
float2 b3 = float2(basisU.Dot(t2.c-a), basisV.Dot(t2.c-a));
float s, t;
if (LineSegment2DLineSegment2DIntersect(a1, a2-a1, b1, b2-b1, s, t)) { if (outLine) { float2 pt = s*(a2-a1); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a1, a2-a1, b2, b3-b2, s, t)) { if (outLine) { float2 pt = s*(a2-a1); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a1, a2-a1, b3, b1-b3, s, t)) { if (outLine) { float2 pt = s*(a2-a1); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a2, a3-a2, b1, b2-b1, s, t)) { if (outLine) { float2 pt = s*(a3-a2); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a2, a3-a2, b2, b3-b2, s, t)) { if (outLine) { float2 pt = s*(a3-a2); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a2, a3-a2, b3, b1-b3, s, t)) { if (outLine) { float2 pt = s*(a3-a2); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a3, a1-a3, b1, b2-b1, s, t)) { if (outLine) { float2 pt = s*(a1-a3); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a3, a1-a3, b2, b3-b2, s, t)) { if (outLine) { float2 pt = s*(a1-a3); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
if (LineSegment2DLineSegment2DIntersect(a3, a1-a3, b3, b1-b3, s, t)) { if (outLine) { float2 pt = s*(a1-a3); vec pt3d = a+pt.x*basisU+pt.y*basisV; *outLine = LineSegment(pt3d, pt3d); } return true; }
return false;
}
}
bool RangesOverlap(float start1, float end1, float start2, float end2)
{
return end1 >= start2 && end2 >= start1;
}
/// [groupSyntax]
bool Triangle::Intersects(const AABB &aabb) const
{
/** The AABB-Triangle test implementation is based on the pseudo-code in
Christer Ericson's Real-Time Collision Detection, pp. 169-172. It is
practically a standard SAT test. */
#if defined(MATH_AUTOMATIC_SSE) && defined(MATH_SSE)
// Benchmark 'Triangle_intersects_AABB': Triangle::Intersects(AABB)
// Best: 8.065 nsecs / 21.664 ticks, Avg: 8.207 nsecs, Worst: 9.985 nsecs
simd4f tMin = min_ps(a, min_ps(b, c));
simd4f tMax = max_ps(a, max_ps(b, c));
simd4f cmp = cmpge_ps(tMin, aabb.maxPoint.v);
cmp = or_ps(cmp, cmple_ps(tMax, aabb.minPoint.v));
// Mask off results from the W channel and test if all were zero.
if (!a_and_b_allzero_ps(cmp, set_ps_hex(0, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU))) return false;
simd4f center = mul_ps(add_ps(aabb.minPoint.v, aabb.maxPoint.v), set1_ps(0.5f));
simd4f h = sub_ps(aabb.maxPoint.v, center);
simd4f t0 = sub_ps(b, a);
simd4f t1 = sub_ps(c, a);
simd4f ac = sub_ps(a, center);
simd4f n = cross_ps(t0, t1);
if (_mm_ucomige_ss(abs_ps(dot4_ps(n, ac)), abs_ps(dot4_ps(h, abs_ps(n))))) return false;
// {eX, eY, eZ} cross t1
simd4f ac_wyxz = zxyw_ps(ac);
simd4f h_wyxz = zxyw_ps(h);
simd4f ac_wxzy = yzxw_ps(ac);
simd4f h_wxzy = yzxw_ps(h);
simd4f bc = sub_ps(b, center);
simd4f bc_wyxz = zxyw_ps(bc);
simd4f at1 = abs_ps(t1);
simd4f t1_wyxz = zxyw_ps(t1);
simd4f at1_wyxz = zxyw_ps(at1);
simd4f bc_wxzy = yzxw_ps(bc);
simd4f t1_wxzy = yzxw_ps(t1);
simd4f at1_wxzy = yzxw_ps(at1);
simd4f d1 = msub_ps(t1_wxzy, ac_wyxz, mul_ps(t1_wyxz, ac_wxzy));
simd4f d2 = msub_ps(t1_wxzy, bc_wyxz, mul_ps(t1_wyxz, bc_wxzy));
simd4f tc = mul_ps(add_ps(d1, d2), set1_ps(0.5f));
simd4f r = abs_ps(madd_ps(h_wyxz, at1_wxzy, mul_ps(h_wxzy, at1_wyxz)));
cmp = cmple_ps(add_ps(r, abs_ps(sub_ps(tc, d1))), abs_ps(tc));
// Note: The three masks of W channel could be omitted if cmplt_ps was used instead of cmple_ps, but
// want to be strict here and define that AABB and Triangle which touch at a vertex should not intersect.
// Mask off results from the W channel and test if all were zero.
if (!a_and_b_allzero_ps(cmp, set_ps_hex(0, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU))) return false;
// {eX, eY, eZ} cross t2
simd4f t2 = sub_ps(c, b);
simd4f at2 = abs_ps(t2);
simd4f t2_wyxz = zxyw_ps(t2);
simd4f at2_wyxz = zxyw_ps(at2);
simd4f t2_wxzy = yzxw_ps(t2);
simd4f at2_wxzy = yzxw_ps(at2);
d1 = msub_ps(t2_wxzy, ac_wyxz, mul_ps(t2_wyxz, ac_wxzy));
d2 = msub_ps(t2_wxzy, bc_wyxz, mul_ps(t2_wyxz, bc_wxzy));
tc = mul_ps(add_ps(d1, d2), set1_ps(0.5f));
r = abs_ps(madd_ps(h_wyxz, at2_wxzy, mul_ps(h_wxzy, at2_wyxz)));
cmp = cmple_ps(add_ps(r, abs_ps(sub_ps(tc, d1))), abs_ps(tc));
// Mask off results from the W channel and test if all were zero.
if (!a_and_b_allzero_ps(cmp, set_ps_hex(0, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU))) return false;
// {eX, eY, eZ} cross t0
simd4f cc = sub_ps(c, center);
simd4f cc_wyxz = zxyw_ps(cc);
simd4f t0_wyxz = zxyw_ps(t0);
simd4f at0 = abs_ps(t0);
simd4f at0_wyxz = zxyw_ps(at0);
simd4f at0_wxzy = yzxw_ps(at0);
simd4f t0_wxzy = yzxw_ps(t0);
simd4f cc_wxzy = yzxw_ps(cc);
d1 = msub_ps(t0_wxzy, ac_wyxz, mul_ps(t0_wyxz, ac_wxzy));
d2 = msub_ps(t0_wxzy, cc_wyxz, mul_ps(t0_wyxz, cc_wxzy));
tc = mul_ps(add_ps(d1, d2), set1_ps(0.5f));
r = abs_ps(madd_ps(h_wyxz, at0_wxzy, mul_ps(h_wxzy, at0_wyxz)));
cmp = cmple_ps(add_ps(r, abs_ps(sub_ps(tc, d1))), abs_ps(tc));
// Mask off results from the W channel and test if all were zero.
return a_and_b_allzero_ps(cmp, set_ps_hex(0, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU)) != 0;
#else
// Benchmark 'Triangle_intersects_AABB': Triangle::Intersects(AABB)
// Best: 17.282 nsecs / 46.496 ticks, Avg: 17.804 nsecs, Worst: 18.434 nsecs
vec tMin = a.Min(b.Min(c));
vec tMax = a.Max(b.Max(c));
if (tMin.x >= aabb.maxPoint.x || tMax.x <= aabb.minPoint.x
|| tMin.y >= aabb.maxPoint.y || tMax.y <= aabb.minPoint.y
|| tMin.z >= aabb.maxPoint.z || tMax.z <= aabb.minPoint.z)
return false;
vec center = (aabb.minPoint + aabb.maxPoint) * 0.5f;
vec h = aabb.maxPoint - center;
const vec t[3] = { b-a, c-a, c-b };
vec ac = a-center;
vec n = Cross(t[0], t[1]);
float s = n.Dot(ac);
float r = Abs(h.Dot(n.Abs()));
if (Abs(s) >= r)
return false;
const vec at[3] = { Abs(t[0]), Abs(t[1]), Abs(t[2]) };
vec bc = b-center;
vec cc = c-center;
// SAT test all cross-axes.
// The following is a fully unrolled loop of this code, stored here for reference:
/*
float d1, d2, a1, a2;
const vec e[3] = { DIR_VEC(1, 0, 0), DIR_VEC(0, 1, 0), DIR_VEC(0, 0, 1) };
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
{
vec axis = Cross(e[i], t[j]);
ProjectToAxis(axis, d1, d2);
aabb.ProjectToAxis(axis, a1, a2);
if (d2 <= a1 || d1 >= a2) return false;
}
*/
// eX <cross> t[0]
float d1 = t[0].y * ac.z - t[0].z * ac.y;
float d2 = t[0].y * cc.z - t[0].z * cc.y;
float tc = (d1 + d2) * 0.5f;
r = Abs(h.y * at[0].z + h.z * at[0].y);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eX <cross> t[1]
d1 = t[1].y * ac.z - t[1].z * ac.y;
d2 = t[1].y * bc.z - t[1].z * bc.y;
tc = (d1 + d2) * 0.5f;
r = Abs(h.y * at[1].z + h.z * at[1].y);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eX <cross> t[2]
d1 = t[2].y * ac.z - t[2].z * ac.y;
d2 = t[2].y * bc.z - t[2].z * bc.y;
tc = (d1 + d2) * 0.5f;
r = Abs(h.y * at[2].z + h.z * at[2].y);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eY <cross> t[0]
d1 = t[0].z * ac.x - t[0].x * ac.z;
d2 = t[0].z * cc.x - t[0].x * cc.z;
tc = (d1 + d2) * 0.5f;
r = Abs(h.x * at[0].z + h.z * at[0].x);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eY <cross> t[1]
d1 = t[1].z * ac.x - t[1].x * ac.z;
d2 = t[1].z * bc.x - t[1].x * bc.z;
tc = (d1 + d2) * 0.5f;
r = Abs(h.x * at[1].z + h.z * at[1].x);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eY <cross> t[2]
d1 = t[2].z * ac.x - t[2].x * ac.z;
d2 = t[2].z * bc.x - t[2].x * bc.z;
tc = (d1 + d2) * 0.5f;
r = Abs(h.x * at[2].z + h.z * at[2].x);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eZ <cross> t[0]
d1 = t[0].x * ac.y - t[0].y * ac.x;
d2 = t[0].x * cc.y - t[0].y * cc.x;
tc = (d1 + d2) * 0.5f;
r = Abs(h.y * at[0].x + h.x * at[0].y);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eZ <cross> t[1]
d1 = t[1].x * ac.y - t[1].y * ac.x;
d2 = t[1].x * bc.y - t[1].y * bc.x;
tc = (d1 + d2) * 0.5f;
r = Abs(h.y * at[1].x + h.x * at[1].y);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// eZ <cross> t[2]
d1 = t[2].x * ac.y - t[2].y * ac.x;
d2 = t[2].x * bc.y - t[2].y * bc.x;
tc = (d1 + d2) * 0.5f;
r = Abs(h.y * at[2].x + h.x * at[2].y);
if (r + Abs(tc - d1) <= Abs(tc))
return false;
// No separating axis exists, the AABB and triangle intersect.
return true;
#endif
}
bool Triangle::Intersects(const OBB &obb) const
{
return obb.Intersects(*this);
}
bool Triangle::Intersects(const Polygon &polygon) const
{
return polygon.Intersects(*this);
}
bool Triangle::Intersects(const Frustum &frustum) const
{
return frustum.Intersects(*this);
}
bool Triangle::Intersects(const Polyhedron &polyhedron) const
{
return polyhedron.Intersects(*this);
}
bool Triangle::Intersects(const Capsule &capsule) const
{
return capsule.Intersects(*this);
}
void Triangle::ProjectToAxis(const vec &axis, float &dMin, float &dMax) const
{
dMin = dMax = Dot(axis, a);
float t = Dot(axis, b);
dMin = Min(t, dMin);
dMax = Max(t, dMax);
t = Dot(axis, c);
dMin = Min(t, dMin);
dMax = Max(t, dMax);
}
int Triangle::UniqueFaceNormals(vec *out) const
{
out[0] = Cross(b-a, c-a);
// If testing a pair of coplanar triangles for SAT intersection,
// the common face normal will not be a separating axis, and neither will
// the cross products of the pairwise edges, since those all coincide with the face normals.
// Therefore to make SAT test work properly in that case, also report all the edge normals
// as possible separation test directions, which fixes the coplanar case.
// For more info, see Geometric Tools for Computer Graphics, 11.11.1, p. 612.
out[1] = Cross(out[0], b-a);
out[2] = Cross(out[0], c-a);
out[3] = Cross(out[0], c-b);
return 4;
}
int Triangle::UniqueEdgeDirections(vec *out) const
{
out[0] = b-a;
out[1] = c-a;
out[2] = c-b;
return 3;
}
/// [groupSyntax]
vec Triangle::ClosestPoint(const vec &p) const
{
/** The code for Triangle-float3 test is from Christer Ericson's Real-Time Collision Detection, pp. 141-142. */
// Check if P is in vertex region outside A.
vec ab = b - a;
vec ac = c - a;
vec ap = p - a;
float d1 = Dot(ab, ap);
float d2 = Dot(ac, ap);
if (d1 <= 0.f && d2 <= 0.f)
return a; // Barycentric coordinates are (1,0,0).
// Check if P is in vertex region outside B.
vec bp = p - b;
float d3 = Dot(ab, bp);
float d4 = Dot(ac, bp);
if (d3 >= 0.f && d4 <= d3)
return b; // Barycentric coordinates are (0,1,0).
// Check if P is in edge region of AB, and if so, return the projection of P onto AB.
float vc = d1*d4 - d3*d2;
if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f)
{
float v = d1 / (d1 - d3);
return a + v * ab; // The barycentric coordinates are (1-v, v, 0).
}
// Check if P is in vertex region outside C.
vec cp = p - c;
float d5 = Dot(ab, cp);
float d6 = Dot(ac, cp);
if (d6 >= 0.f && d5 <= d6)
return c; // The barycentric coordinates are (0,0,1).
// Check if P is in edge region of AC, and if so, return the projection of P onto AC.
float vb = d5*d2 - d1*d6;
if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f)
{
float w = d2 / (d2 - d6);
return a + w * ac; // The barycentric coordinates are (1-w, 0, w).