forked from juj/MathGeoLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSphere.cpp
1497 lines (1263 loc) · 43.7 KB
/
Sphere.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 Sphere.cpp
@author Jukka Jylänki
@brief Implementation for the Sphere geometry object. */
#include "Sphere.h"
#ifdef MATH_ENABLE_STL_SUPPORT
#include <utility>
#include <vector>
#include <iostream>
#include <algorithm>
#else
#include "Container/Array.h"
#endif
#include "../Math/MathLog.h"
#include "../Math/MathFunc.h"
#include "OBB.h"
#include "AABB.h"
#include "Capsule.h"
#include "Frustum.h"
#include "../Algorithm/Random/LCG.h"
#include "LineSegment.h"
#include "Line.h"
#include "Ray.h"
#include "Polygon.h"
#include "Polyhedron.h"
#include "Plane.h"
#include "Circle.h"
#include "../Math/float2.h"
#include "../Math/float3x3.h"
#include "../Math/float3x4.h"
#include "../Math/float4.h"
#include "../Math/float4x4.h"
#include "../Math/Quat.h"
#include "Triangle.h"
#ifdef MATH_GRAPHICSENGINE_INTEROP
#include "VertexBuffer.h"
#endif
MATH_BEGIN_NAMESPACE
Sphere::Sphere(const vec ¢er, float radius)
:pos(center), r(radius)
{
}
Sphere::Sphere(const vec &a, const vec &b)
{
*this = FitThroughPoints(a, b);
}
Sphere::Sphere(const vec &a, const vec &b, const vec &c)
{
*this = FitThroughPoints(a, b, c);
}
Sphere::Sphere(const vec &a, const vec &b, const vec &c, const vec &d)
{
*this = FitThroughPoints(a, b, c, d);
}
void Sphere::Translate(const vec &offset)
{
pos += offset;
}
void Sphere::Transform(const float3x3 &transform)
{
assume(transform.HasUniformScale());
pos = transform * pos;
r *= transform.Col(0).Length();
}
void Sphere::Transform(const float3x4 &transform)
{
assume(transform.HasUniformScale());
pos = transform.MulPos(pos);
r *= transform.Col(0).Length();
}
void Sphere::Transform(const float4x4 &transform)
{
assume(transform.HasUniformScale());
assume(!transform.ContainsProjection());
pos = transform.MulPos(pos);
r *= transform.Col3(0).Length();
}
void Sphere::Transform(const Quat &transform)
{
pos = transform * pos;
}
AABB Sphere::MinimalEnclosingAABB() const
{
AABB aabb;
aabb.SetFrom(*this);
return aabb;
}
AABB Sphere::MaximalContainedAABB() const
{
AABB aabb;
static const float recipSqrt3 = RSqrt(3);
float halfSideLength = r * recipSqrt3;
aabb.SetFromCenterAndSize(pos, DIR_VEC(halfSideLength,halfSideLength,halfSideLength));
return aabb;
}
void Sphere::SetNegativeInfinity()
{
pos = POINT_VEC(0,0,0);
r = -FLOAT_INF;
}
float Sphere::Volume() const
{
return 4.f * pi * r*r*r / 3.f;
}
float Sphere::SurfaceArea() const
{
return 4.f * pi * r*r;
}
vec Sphere::ExtremePoint(const vec &direction) const
{
float len = direction.Length();
assume(len > 0.f);
return pos + direction * (r / len);
}
vec Sphere::ExtremePoint(const vec &direction, float &projectionDistance) const
{
vec extremePoint = ExtremePoint(direction);
projectionDistance = extremePoint.Dot(direction);
return extremePoint;
}
void Sphere::ProjectToAxis(const vec &direction, float &outMin, float &outMax) const
{
float d = Dot(direction, pos);
outMin = d - r;
outMax = d + r;
}
bool Sphere::IsFinite() const
{
return pos.IsFinite() && MATH_NS::IsFinite(r);
}
bool Sphere::IsDegenerate() const
{
return !(r > 0.f) || !pos.IsFinite(); // Peculiar order of testing so that NaNs end up being degenerate.
}
void Sphere::SetDegenerate()
{
pos = vec::nan;
r = nan;
}
bool Sphere::Contains(const vec &point) const
{
return pos.DistanceSq(point) <= r*r;
}
bool Sphere::Contains(const vec &point, float epsilon) const
{
return pos.DistanceSq(point) <= r*r + epsilon;
}
bool Sphere::Contains(const LineSegment &lineSegment) const
{
return Contains(lineSegment.a) && Contains(lineSegment.b);
}
bool Sphere::Contains(const Triangle &triangle) const
{
return Contains(triangle.a) && Contains(triangle.b) && Contains(triangle.c);
}
bool Sphere::Contains(const Polygon &polygon) const
{
for(int i = 0; i < polygon.NumVertices(); ++i)
if (!Contains(polygon.Vertex(i)))
return false;
return true;
}
bool Sphere::Contains(const AABB &aabb) const
{
for(int i = 0; i < 8; ++i)
if (!Contains(aabb.CornerPoint(i)))
return false;
return true;
}
bool Sphere::Contains(const OBB &obb) const
{
for(int i = 0; i < 8; ++i)
if (!Contains(obb.CornerPoint(i)))
return false;
return true;
}
bool Sphere::Contains(const Frustum &frustum) const
{
for(int i = 0; i < 8; ++i)
if (!Contains(frustum.CornerPoint(i)))
return false;
return true;
}
bool Sphere::Contains(const Polyhedron &polyhedron) const
{
assume(polyhedron.IsClosed());
for(int i = 0; i < polyhedron.NumVertices(); ++i)
if (!Contains(polyhedron.Vertex(i)))
return false;
return true;
}
bool Sphere::Contains(const Sphere &sphere) const
{
return pos.Distance(sphere.pos) + sphere.r <= r;
}
bool Sphere::Contains(const Sphere &sphere, float epsilon) const
{
return pos.Distance(sphere.pos) + sphere.r -r <= epsilon;
}
bool Sphere::Contains(const Capsule &capsule) const
{
return pos.Distance(capsule.l.a) + capsule.r <= r &&
pos.Distance(capsule.l.b) + capsule.r <= r;
}
Sphere Sphere::FastEnclosingSphere(const vec *pts, int numPoints)
{
Sphere s;
if (numPoints == 0)
{
s.SetNegativeInfinity();
return s;
}
assume(pts || numPoints == 0);
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (!pts)
return Sphere();
#endif
// First pass: Pick the cardinal axis (X,Y or Z) which has the two most distant points.
int minx, maxx, miny, maxy, minz, maxz;
AABB::ExtremePointsAlongAABB(pts, numPoints, minx, maxx, miny, maxy, minz, maxz);
float dist2x = pts[minx].DistanceSq(pts[maxx]);
float dist2y = pts[miny].DistanceSq(pts[maxy]);
float dist2z = pts[minz].DistanceSq(pts[maxz]);
int min = minx;
int max = maxx;
if (dist2y > dist2x && dist2y > dist2z)
{
min = miny;
max = maxy;
}
else if (dist2z > dist2x && dist2z > dist2y)
{
min = minz;
max = maxz;
}
// The two points on the longest axis define the initial sphere.
s.pos = (pts[min] + pts[max]) * 0.5f;
s.r = pts[min].Distance(s.pos);
// Second pass: Make sure each point lies inside this sphere, expand if necessary.
for(int i = 0; i < numPoints; ++i)
s.Enclose(pts[i]);
return s;
}
/* This implementation was adapted from Christer Ericson's Real-time Collision Detection, pp. 99-100.
@bug This implementation is broken! */
/*
Sphere WelzlSphere(const vec *pts, int numPoints, vec *support, int numSupports)
{
if (numPoints == 0)
{
switch(numSupports)
{
default: assert(false);
case 0: return Sphere();
case 1: return Sphere(support[0], 0.f);
case 2: return Sphere(support[0], support[1]);
case 3: return Sphere(support[0], support[1], support[2]);
case 4: return Sphere(support[0], support[1], support[2], support[3]);
}
}
// todo The following recursion can easily crash the stack for large inputs. Convert this to proper form.
Sphere smallestSphere = WelzlSphere(pts, numPoints - 1, support, numSupports);
if (smallestSphere.Contains(pts[numPoints-1]))
return smallestSphere;
support[numSupports] = pts[numPoints-1];
return WelzlSphere(pts, numPoints - 1, support, numSupports + 1);
}
*/
// The epsilon value used for enclosing sphere computations.
static const float sEpsilon = 1e-4f;
Sphere Sphere::OptimalEnclosingSphere(const vec *pts, int numPoints)
{
// If we have only a small number of points, can solve with a specialized function.
switch(numPoints)
{
case 0: return Sphere();
case 1: return Sphere(pts[0], 0.f); // Sphere around a single point will be degenerate with r = 0.
case 2: return OptimalEnclosingSphere(pts[0], pts[1]);
case 3: return OptimalEnclosingSphere(pts[0], pts[1], pts[2]);
case 4: return OptimalEnclosingSphere(pts[0], pts[1], pts[2], pts[3]);
default: break;
}
// The set of supporting points for the minimal sphere. Even though the minimal enclosing
// sphere might have 2, 3 or 4 points in its support (sphere surface), always store here
// indices to exactly four points.
int sp[4] = { 0, 1, 2, 3 };
// Due to numerical issues, it can happen that the minimal sphere for four points {a,b,c,d} does not
// accommodate a fifth point e, but replacing any of the points a-d from the support with the point e
// does not accommodate the all the five points either.
// Therefore, keep a set of flags for each support point to avoid going in cycles, where the same
// set of points are again and again added and removed from the support, causing an infinite loop.
bool expendable[4] = { true, true, true, true };
// The so-far constructed minimal sphere.
Sphere s = OptimalEnclosingSphere(pts[sp[0]], pts[sp[1]], pts[sp[2]], pts[sp[3]]);
float rSq = s.r * s.r + sEpsilon;
for(int i = 4; i < numPoints; ++i)
{
if (i == sp[0] || i == sp[1] || i == sp[2] || i == sp[3])
continue; // Take care not to add the same point twice to the support set.
// If the next point (pts[i]) does not fit inside the currently computed minimal sphere, compute
// a new minimal sphere that also contains pts[i].
if (pts[i].DistanceSq(s.pos) > rSq)
{
int redundant;
s = OptimalEnclosingSphere(pts[sp[0]], pts[sp[1]], pts[sp[2]], pts[sp[3]], pts[i], redundant);
rSq = s.r*s.r + sEpsilon;
// A sphere is uniquely defined by four points, so one of the five points passed in above is
// now redundant, and can be removed from the support set.
if (redundant != 4 && (sp[redundant] < i || expendable[redundant]))
{
sp[redundant] = i; // Replace the old point with the new one.
expendable[redundant] = false; // This new one cannot be evicted (until we proceed past it in the input list later)
// Mark all points in the array before this index "expendable", meaning that they can be removed from the support set.
if (sp[0] < i) expendable[0] = true;
if (sp[1] < i) expendable[1] = true;
if (sp[2] < i) expendable[2] = true;
if (sp[3] < i) expendable[3] = true;
// Have to start all over and make sure all old points also lie inside this new sphere,
// since our guess for the minimal enclosing sphere changed.
i = 0;
}
}
}
return s;
}
float Sphere::Distance(const vec &point) const
{
return Max(0.f, pos.Distance(point) - r);
}
float Sphere::Distance(const Sphere &sphere) const
{
return Max(0.f, pos.Distance(sphere.pos) - r - sphere.r);
}
float Sphere::Distance(const Capsule &capsule) const
{
return capsule.Distance(*this);
}
float Sphere::Distance(const AABB &aabb) const
{
return aabb.Distance(*this);
}
float Sphere::Distance(const OBB &obb) const
{
return obb.Distance(*this);
}
float Sphere::Distance(const Plane &plane) const
{
return plane.Distance(*this);
}
float Sphere::Distance(const Triangle &triangle) const
{
return triangle.Distance(*this);
}
float Sphere::Distance(const Ray &ray) const
{
return ray.Distance(*this);
}
float Sphere::Distance(const LineSegment &lineSegment) const
{
return lineSegment.Distance(*this);
}
float Sphere::Distance(const Line &line) const
{
return line.Distance(*this);
}
float Sphere::MaxDistance(const vec &point) const
{
return point.Distance(pos) + r;
}
vec Sphere::ClosestPoint(const vec &point) const
{
float d = pos.Distance(point);
float t = (d >= r ? r : d);
return pos + (point - pos) * (t / d);
}
Circle Sphere::Intersect(const Plane &plane) const
{
Circle c;
c.pos = plane.ClosestPoint(pos);
c.normal = plane.normal;
c.r = Sqrt(r*r - c.pos.DistanceSq(pos));
return c;
}
bool Sphere::Intersects(const Sphere &sphere) const
{
return (pos - sphere.pos).LengthSq() <= (r + sphere.r) * (r + sphere.r);
}
bool Sphere::Intersects(const Capsule &capsule) const
{
return capsule.Intersects(*this);
}
int Sphere::IntersectLine(const vec &linePos, const vec &lineDir, const vec &sphereCenter,
float sphereRadius, float &t1, float &t2)
{
assume2(lineDir.IsNormalized(), lineDir, lineDir.LengthSq());
assume1(sphereRadius >= 0.f, sphereRadius);
/* A line is represented explicitly by the set { linePos + t * lineDir }, where t is an arbitrary float.
A sphere is represented implictly by the set of vectors that satisfy ||v - sphereCenter|| == sphereRadius.
To solve which points on the line are also points on the sphere, substitute v <- linePos + t * lineDir
to obtain:
|| linePos + t * lineDir - sphereCenter || == sphereRadius, and squaring both sides we get
|| linePos + t * lineDir - sphereCenter ||^2 == sphereRadius^2, or rearranging:
|| (linePos - sphereCenter) + t * lineDir ||^2 == sphereRadius^2. */
// This equation represents the set of points which lie both on the line and the sphere. There is only one
// unknown variable, t, for which we solve to get the actual points of intersection.
// Compute variables from the above equation:
const vec a = linePos - sphereCenter;
const float radSq = sphereRadius * sphereRadius;
/* so now the equation looks like
|| a + t * lineDir ||^2 == radSq.
Since ||x||^2 == <x,x> (i.e. the square of a vector norm equals the dot product with itself), we get
<a + t * lineDir, a + t * lineDir> == radSq,
and using the identity <a+b, a+b> == <a,a> + 2*<a,b> + <b,b> (which holds for dot product when a and b are reals),
we have
<a,a> + 2 * <a, t * lineDir> + <t * lineDir, t * lineDir> == radSq, or
<a,a> - radSq + 2 * <a, lineDir> * t + <lineDir, lineDir> * t^2 == 0, or
C + Bt + At^2 == 0, where
C = <a,a> - radSq,
B = 2 * <a, lineDir>, and
A = <lineDir, lineDir> == 1, since we assumed lineDir is normalized. */
// Warning! If Dot(a,a) is large (distance between line pos and sphere center) and sphere radius very small,
// catastrophic cancellation can occur here!
const float C = Dot(a,a) - radSq;
const float B = 2.f * Dot(a, lineDir);
/* The equation A + Bt + Ct^2 == 0 is a second degree equation on t, which is easily solvable using the
known formula, and we obtain
t = [-B +/- Sqrt(B^2 - 4AC)] / 2A. */
float D = B*B - 4.f * C; // D = B^2 - 4AC.
if (D < 0.f) // There is no solution to the square root, so the ray doesn't intersect the sphere.
{
// Output a degenerate enter-exit range so that batch processing code may use min of t1's and max of t2's to
// compute the nearest enter and farthest exit without requiring branching on the return value of this function.
t1 = FLOAT_INF;
t2 = -FLOAT_INF;
return 0;
}
if (D < 1e-4f) // The expression inside Sqrt is ~ 0. The line is tangent to the sphere, and we have one solution.
{
t1 = t2 = -B * 0.5f;
return 1;
}
// The Sqrt expression is strictly positive, so we get two different solutions for t.
D = Sqrt(D);
t1 = (-B - D) * 0.5f;
t2 = (-B + D) * 0.5f;
return 2;
}
int Sphere::Intersects(const Ray &ray, vec *intersectionPoint, vec *intersectionNormal, float *d, float *d2) const
{
float t1, t2;
int numIntersections = IntersectLine(ray.pos, ray.dir, pos, r, t1, t2);
// If the line of this ray intersected in two places, but the first intersection was "behind" this ray,
// handle the second point of intersection instead. This case occurs when the origin of the ray is inside
// the Sphere.
if (t1 < 0.f && numIntersections == 2)
t1 = t2;
if (t1 < 0.f)
return 0; // The intersection position is on the negative direction of the ray.
vec hitPoint = ray.pos + t1 * ray.dir;
if (intersectionPoint)
*intersectionPoint = hitPoint;
if (intersectionNormal)
*intersectionNormal = (hitPoint - pos).Normalized();
if (d)
*d = t1;
if (d2)
*d2 = t2;
return numIntersections;
}
int Sphere::Intersects(const Line &line, vec *intersectionPoint, vec *intersectionNormal, float *d, float *d2) const
{
float t1, t2;
int numIntersections = IntersectLine(line.pos, line.dir, pos, r, t1, t2);
if (numIntersections == 0)
return 0;
vec hitPoint = line.pos + t1 * line.dir;
if (intersectionPoint)
*intersectionPoint = hitPoint;
if (intersectionNormal)
*intersectionNormal = (hitPoint - pos).Normalized();
if (d)
*d = t1;
if (d2)
*d2 = t2;
return numIntersections;
}
int Sphere::Intersects(const LineSegment &l, vec *intersectionPoint, vec *intersectionNormal, float *d, float *d2) const
{
float t1, t2;
int numIntersections = IntersectLine(l.a, l.Dir(), pos, r, t1, t2);
if (numIntersections == 0)
return 0;
float lineLength = l.Length();
if (t2 < 0.f || t1 > lineLength)
return 0;
vec hitPoint = l.GetPoint(t1 / lineLength);
if (intersectionPoint)
*intersectionPoint = hitPoint;
if (intersectionNormal)
*intersectionNormal = (hitPoint - pos).Normalized();
if (d)
*d = t1 / lineLength;
if (d2)
*d2 = t2 / lineLength;
return true;
}
bool Sphere::Intersects(const Plane &plane) const
{
return plane.Intersects(*this);
}
bool Sphere::Intersects(const AABB &aabb, vec *closestPointOnAABB) const
{
return aabb.Intersects(*this, closestPointOnAABB);
}
bool Sphere::Intersects(const OBB &obb, vec *closestPointOnOBB) const
{
return obb.Intersects(*this, closestPointOnOBB);
}
bool Sphere::Intersects(const Triangle &triangle, vec *closestPointOnTriangle) const
{
return triangle.Intersects(*this, closestPointOnTriangle);
}
bool Sphere::Intersects(const Polygon &polygon) const
{
return polygon.Intersects(*this);
}
bool Sphere::Intersects(const Frustum &frustum) const
{
return frustum.Intersects(*this);
}
bool Sphere::Intersects(const Polyhedron &polyhedron) const
{
return polyhedron.Intersects(*this);
}
void Sphere::Enclose(const vec &point, float epsilon)
{
vec d = point - pos;
float dist2 = d.LengthSq();
if (dist2 + epsilon > r*r)
{
#ifdef MATH_ASSERT_CORRECTNESS
Sphere copy = *this;
#endif
float dist = Sqrt(dist2);
float halfDist = (dist - r) * 0.5f;
// Nudge this Sphere towards the target point. Add half the missing distance to radius,
// and the other half to position. This gives a tighter enclosure, instead of if
// the whole missing distance were just added to radius.
pos += d * halfDist / dist;
r += halfDist + 1e-4f; // Use a fixed epsilon deliberately, the param is a squared epsilon, so different order of magnitude.
#ifdef MATH_ASSERT_CORRECTNESS
mathassert(this->Contains(copy, epsilon));
#endif
}
assume(this->Contains(point));
}
struct PointWithDistance
{
vec pt;
float d;
bool operator <(const PointWithDistance &rhs) const { return d < rhs.d; }
};
// A quick and dirty RAII container for allocated AlignedNew-AlignedFree array to avoid leaking
// memory if a test throws an exception.
template<typename T>
class AutoArrayPtr
{
public:
T *ptr;
AutoArrayPtr(T *ptr):ptr(ptr) {}
~AutoArrayPtr() { AlignedFree(ptr); }
private:
AutoArrayPtr(const AutoArrayPtr&);
void operator=(const AutoArrayPtr&);
};
// Encloses n points into the Sphere s, in the order of farthest first, in order to
// generate the tightest resulting enclosure.
void Sphere_Enclose_pts(Sphere &s, const vec *pts, int n)
{
AutoArrayPtr<PointWithDistance> cornersPtr(AlignedNew<PointWithDistance>(n, 16));
PointWithDistance *corners = cornersPtr.ptr;
for(int i = 0; i < n; ++i)
{
corners[i].pt = pts[i];
corners[i].d = s.pos.DistanceSq(corners[i].pt);
}
std::sort(corners, corners+n);
for(int i = n-1; i >= 0; --i)
s.Enclose(corners[i].pt);
}
// Optimize/reimplement the above function in the case when enclosing geometric objects where the number of
// points to enclose is fixed at compile-time. This avoids dynamic memory allocation.
template<typename T, int n>
void Sphere_Enclose(Sphere &s, const T &obj)
{
PointWithDistance corners[n];
for(int i = 0; i < n; ++i)
{
corners[i].pt = obj.CornerPoint(i);
corners[i].d = s.pos.DistanceSq(corners[i].pt);
}
std::sort(corners, corners+n);
for(int i = n-1; i >= 0; --i)
s.Enclose(corners[i].pt);
}
void Sphere::Enclose(const AABB &aabb)
{
Sphere_Enclose<AABB, 8>(*this, aabb);
assume(this->Contains(aabb));
}
void Sphere::Enclose(const OBB &obb)
{
Sphere_Enclose<OBB, 8>(*this, obb);
assume(this->Contains(obb));
}
void Sphere::Enclose(const Sphere &sphere)
{
// To enclose another sphere into this sphere, we only need to enclose two points:
// 1) Enclose the farthest point on the other sphere into this sphere.
// 2) Enclose the opposite point of the farthest point into this sphere.
vec toFarthestPoint = (sphere.pos - pos).ScaledToLength(sphere.r);
Enclose(sphere.pos + toFarthestPoint);
Enclose(sphere.pos - toFarthestPoint);
assume(this->Contains(sphere));
}
void Sphere::Enclose(const LineSegment &lineSegment)
{
if (pos.DistanceSq(lineSegment.a) > pos.DistanceSq(lineSegment.b))
{
Enclose(lineSegment.a);
Enclose(lineSegment.b);
}
else
{
Enclose(lineSegment.b);
Enclose(lineSegment.a);
}
}
void Sphere::Enclose(const vec *pointArray, int numPoints)
{
assume(pointArray || numPoints == 0);
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (!pointArray)
return;
#endif
Sphere_Enclose_pts(*this, pointArray, numPoints);
}
void Sphere::Enclose(const Triangle &triangle)
{
Sphere_Enclose<Triangle, 3>(*this, triangle);
}
void Sphere::Enclose(const Polygon &polygon)
{
Enclose(polygon.VertexArrayPtr(), polygon.NumVertices());
}
void Sphere::Enclose(const Polyhedron &polyhedron)
{
Enclose(polyhedron.VertexArrayPtr(), polyhedron.NumVertices());
}
void Sphere::Enclose(const Frustum &frustum)
{
Sphere_Enclose<Frustum, 8>(*this, frustum);
}
void Sphere::Enclose(const Capsule &capsule)
{
// Capsule is a convex object spanned by the endpoint spheres - enclosing
// the endpoint spheres will also cause this Sphere to enclose the middle
// section since Sphere is convex as well.
float da = pos.DistanceSq(capsule.l.a);
float db = pos.DistanceSq(capsule.l.b);
// Enclose the farther Sphere of the Capsule first, and the closer one second to retain the tightest fit.
if (da > db)
{
Enclose(capsule.SphereA());
Enclose(capsule.SphereB());
}
else
{
Enclose(capsule.SphereB());
Enclose(capsule.SphereA());
}
}
void Sphere::ExtendRadiusToContain(const vec &point, float epsilon)
{
float requiredRadius = pos.Distance(point) + epsilon;
r = Max(r, requiredRadius);
}
void Sphere::ExtendRadiusToContain(const Sphere &sphere, float epsilon)
{
float requiredRadius = pos.Distance(sphere.pos) + sphere.r + epsilon;
r = Max(r, requiredRadius);
}
int Sphere::Triangulate(vec *outPos, vec *outNormal, float2 *outUV, int numVertices, bool ccwIsFrontFacing) const
{
assume(outPos);
assume(numVertices >= 24 && "At minimum, sphere triangulation will contain at least 8 triangles, which is 24 vertices, but fewer were specified!");
assume(numVertices % 3 == 0 && "Warning:: The size of output should be divisible by 3 (each triangle takes up 3 vertices!)");
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (!outPos)
return 0;
#endif
assume(this->r > 0.f);
if (numVertices < 24)
return 0;
#ifdef MATH_ENABLE_STL_SUPPORT
TriangleArray temp;
#else
Array<Triangle> temp;
#endif
// Start subdividing from a diamond shape.
vec xp = POINT_VEC(r,0,0);
vec xn = POINT_VEC(-r, 0, 0);
vec yp = POINT_VEC(0, r, 0);
vec yn = POINT_VEC(0, -r, 0);
vec zp = POINT_VEC(0, 0, r);
vec zn = POINT_VEC(0, 0, -r);
if (ccwIsFrontFacing)
{
temp.push_back(Triangle(yp,xp,zp));
temp.push_back(Triangle(xp,yp,zn));
temp.push_back(Triangle(yn,zp,xp));
temp.push_back(Triangle(yn,xp,zn));
temp.push_back(Triangle(zp,xn,yp));
temp.push_back(Triangle(yp,xn,zn));
temp.push_back(Triangle(yn,xn,zp));
temp.push_back(Triangle(xn,yn,zn));
}
else
{
temp.push_back(Triangle(yp,zp,xp));
temp.push_back(Triangle(xp,zn,yp));
temp.push_back(Triangle(yn,xp,zp));
temp.push_back(Triangle(yn,zn,xp));
temp.push_back(Triangle(zp,yp,xn));
temp.push_back(Triangle(yp,zn,xn));
temp.push_back(Triangle(yn,zp,xn));
temp.push_back(Triangle(xn,zn,yn));
}
int oldEnd = 0;
while(((int)temp.size()-oldEnd+3)*3 <= numVertices)
{
Triangle cur = temp[oldEnd];
vec a = ((cur.a + cur.b) * 0.5f).ScaledToLength(this->r);
vec b = ((cur.a + cur.c) * 0.5f).ScaledToLength(this->r);
vec c = ((cur.b + cur.c) * 0.5f).ScaledToLength(this->r);
temp.push_back(Triangle(cur.a, a, b));
temp.push_back(Triangle(cur.b, c, a));
temp.push_back(Triangle(cur.c, b, c));
temp.push_back(Triangle(a, c, b));
++oldEnd;
}
// Check that we really did tessellate as many new triangles as possible.
assert(((int)temp.size()-oldEnd)*3 <= numVertices && ((int)temp.size()-oldEnd)*3 + 9 > numVertices);
for(size_t i = oldEnd, j = 0; i < temp.size(); ++i, ++j)
{
outPos[3*j] = this->pos + TRIANGLE(temp[i]).a;
outPos[3*j+1] = this->pos + TRIANGLE(temp[i]).b;
outPos[3*j+2] = this->pos + TRIANGLE(temp[i]).c;
}
if (outNormal)
for(size_t i = oldEnd, j = 0; i < temp.size(); ++i, ++j)
{
outNormal[3*j] = TRIANGLE(temp[i]).a.Normalized();
outNormal[3*j+1] = TRIANGLE(temp[i]).b.Normalized();
outNormal[3*j+2] = TRIANGLE(temp[i]).c.Normalized();
}
if (outUV)
for(size_t i = oldEnd, j = 0; i < temp.size(); ++i, ++j)
{
outUV[3*j] = float2(atan2(TRIANGLE(temp[i]).a.y, TRIANGLE(temp[i]).a.x) / (2.f * 3.141592654f) + 0.5f, (TRIANGLE(temp[i]).a.z + r) / (2.f * r));
outUV[3*j+1] = float2(atan2(TRIANGLE(temp[i]).b.y, TRIANGLE(temp[i]).b.x) / (2.f * 3.141592654f) + 0.5f, (TRIANGLE(temp[i]).b.z + r) / (2.f * r));
outUV[3*j+2] = float2(atan2(TRIANGLE(temp[i]).c.y, TRIANGLE(temp[i]).c.x) / (2.f * 3.141592654f) + 0.5f, (TRIANGLE(temp[i]).c.z + r) / (2.f * r));
}
return ((int)temp.size() - oldEnd) * 3;
}
vec Sphere::RandomPointInside(LCG &lcg)
{
assume(r > 1e-3f);
vec v = vec::zero;
// Rejection sampling analysis: The unit sphere fills ~52.4% of the volume of its enclosing box, so this
// loop is expected to take only very few iterations before succeeding.
for(int i = 0; i < 1000; ++i)
{
v.x = lcg.Float(-r, r);
v.y = lcg.Float(-r, r);
v.z = lcg.Float(-r, r);
if (v.LengthSq() <= r*r)
return pos + v;
}
assume(false && "Sphere::RandomPointInside failed!");
// Failed to generate a point inside this sphere. Return the sphere center as fallback.
return pos;
}
vec Sphere::RandomPointOnSurface(LCG &lcg)
{
vec v = vec::zero;
// Rejection sampling analysis: The unit sphere fills ~52.4% of the volume of its enclosing box, so this
// loop is expected to take only very few iterations before succeeding.
for(int i = 0; i < 1000; ++i)
{
v.x = lcg.FloatNeg1_1();
v.y = lcg.FloatNeg1_1();
v.z = lcg.FloatNeg1_1();
float lenSq = v.LengthSq();
if (lenSq >= 1e-6f && lenSq <= 1.f)
return pos + (r / Sqrt(lenSq)) * v;
}
// Astronomically small probability to reach here, and if we do so, the provided random number generator must have been in a bad state.
assume(false && "Sphere::RandomPointOnSurface failed!");
// Failed to generate a point inside this sphere. Return an arbitrary point on the surface as fallback.
return pos + DIR_VEC(r, 0, 0);
}
vec Sphere::RandomPointInside(LCG &lcg, const vec ¢er, float radius)
{
return Sphere(center, radius).RandomPointInside(lcg);
}
vec Sphere::RandomPointOnSurface(LCG &lcg, const vec ¢er, float radius)
{
return Sphere(center, radius).RandomPointOnSurface(lcg);
}
Sphere Sphere::OptimalEnclosingSphere(const vec &a, const vec &b)
{
Sphere s;
s.pos = (a + b) * 0.5f;
s.r = (b - s.pos).Length();
assume(s.pos.IsFinite());
assume(s.r >= 0.f);
// Allow floating point inconsistency and expand the radius by a small epsilon so that the containment tests
// really contain the points (note that the points must be sufficiently near enough to the origin)
s.r += sEpsilon;
mathassert(s.Contains(a));
mathassert(s.Contains(b));
return s;
}
/** Computes the (s,t) coordinates of the smallest sphere that passes through three points (0,0,0), ab and ac.