forked from juj/MathGeoLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOBB.cpp
2876 lines (2540 loc) · 94.7 KB
/
OBB.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 OBB.cpp
@author Jukka Jylänki
@brief Implementation for the Oriented Bounding Box (OBB) geometry object. */
#include "OBB.h"
#ifdef MATH_ENABLE_STL_SUPPORT
#include <iostream>
#include <utility>
#endif
#include "../Math/MathFunc.h"
#include "AABB.h"
#include "Frustum.h"
#include "../Algorithm/Random/LCG.h"
#include "LineSegment.h"
#include "Line.h"
#include "Plane.h"
#include "Polygon.h"
#include "Polyhedron.h"
#include "Sphere.h"
#include "Capsule.h"
#include "../Math/float2.inl"
#include "../Math/float3x3.h"
#include "../Math/float3x4.h"
#include "../Math/float4.h"
#include "../Math/float4x4.h"
#include "../Math/Quat.h"
#include "PBVolume.h"
#include "Ray.h"
#include "Triangle.h"
#include <stdlib.h>
#include "../Time/Clock.h"
#include <set>
#ifdef MATH_CONTAINERLIB_SUPPORT
#include "Algorithm/Sort/Sort.h"
#endif
#ifdef MATH_GRAPHICSENGINE_INTEROP
#include "VertexBuffer.h"
#endif
#if defined(MATH_SIMD) && defined(MATH_AUTOMATIC_SSE)
#include "../Math/float4_neon.h"
#include "../Math/float4_sse.h"
#include "../Math/float4x4_sse.h"
#endif
#define MATH_ENCLOSINGOBB_DOUBLE_PRECISION
#ifdef MATH_ENCLOSINGOBB_DOUBLE_PRECISION
#include "../Math/float4d.h"
#endif
MATH_BEGIN_NAMESPACE
#ifdef MATH_ENCLOSINGOBB_DOUBLE_PRECISION
typedef float4d cv;
typedef double cs;
typedef std::vector<float4d> VecdArray;
#else
typedef vec cv;
typedef float cs;
typedef VecArray VecdArray;
#endif
OBB::OBB(const vec &pos, const vec &r, const vec &axis0, const vec &axis1, const vec &axis2)
:pos(pos), r(r)
{
axis[0] = axis0;
axis[1] = axis1;
axis[2] = axis2;
}
OBB::OBB(const AABB &aabb)
{
SetFrom(aabb);
}
void OBB::SetNegativeInfinity()
{
pos = POINT_VEC_SCALAR(0.f);
r.SetFromScalar(-FLOAT_INF);
axis[0] = DIR_VEC(1,0,0);
axis[1] = DIR_VEC(0, 1, 0);
axis[2] = DIR_VEC(0, 0, 1);
}
void OBB::SetFrom(const AABB &aabb)
{
pos = aabb.CenterPoint();
r = aabb.HalfSize();
axis[0] = DIR_VEC(1, 0, 0);
axis[1] = DIR_VEC(0, 1, 0);
axis[2] = DIR_VEC(0, 0, 1);
}
template<typename Matrix>
void OBBSetFrom(OBB &obb, const AABB &aabb, const Matrix &m)
{
assume(m.IsColOrthogonal()); // We cannot convert transform an AABB to OBB if it gets sheared in the process.
assume(m.HasUniformScale()); // Nonuniform scale will produce shear as well.
obb.pos = m.MulPos(aabb.CenterPoint());
obb.r = aabb.HalfSize();
obb.axis[0] = DIR_VEC(m.Col(0));
obb.axis[1] = DIR_VEC(m.Col(1));
obb.axis[2] = DIR_VEC(m.Col(2));
// If the matrix m contains scaling, propagate the scaling from the axis vectors to the half-length vectors,
// since we want to keep the axis vectors always normalized in our representation.
float matrixScale = obb.axis[0].LengthSq();
matrixScale = Sqrt(matrixScale);
obb.r *= matrixScale;
matrixScale = 1.f / matrixScale;
obb.axis[0] *= matrixScale;
obb.axis[1] *= matrixScale;
obb.axis[2] *= matrixScale;
// mathassert(vec::AreOrthogonal(obb.axis[0], obb.axis[1], obb.axis[2]));
// mathassert(vec::AreOrthonormal(obb.axis[0], obb.axis[1], obb.axis[2]));
///@todo Would like to simply do the above, but instead numerical stability requires to do the following:
vec::Orthonormalize(obb.axis[0], obb.axis[1], obb.axis[2]);
}
void OBB::SetFrom(const AABB &aabb, const float3x3 &transform)
{
assume(transform.IsColOrthogonal());
OBBSetFrom(*this, aabb, transform);
}
void OBB::SetFrom(const AABB &aabb, const float3x4 &transform)
{
OBBSetFrom(*this, aabb, transform);
}
void OBB::SetFrom(const AABB &aabb, const float4x4 &transform)
{
assume(transform.Row(3).Equals(0,0,0,1));
OBBSetFrom(*this, aabb, transform.Float3x4Part());
}
void OBB::SetFrom(const AABB &aabb, const Quat &transform)
{
OBBSetFrom(*this, aabb, float3x3(transform));
}
void OBB::SetFrom(const Sphere &sphere)
{
pos = sphere.pos;
r.SetFromScalar(sphere.r);
axis[0] = DIR_VEC(1,0,0);
axis[1] = DIR_VEC(0,1,0);
axis[2] = DIR_VEC(0,0,1);
}
#ifdef MATH_CONTAINERLIB_SUPPORT
bool OBB::SetFrom(const Polyhedron &polyhedron)
{
if (!polyhedron.v.empty())
{
*this = OBB::OptimalEnclosingOBB((vec*)&polyhedron.v[0], (int)polyhedron.v.size());
return true;
}
else
{
SetNegativeInfinity();
return false;
}
}
#endif
Polyhedron OBB::ToPolyhedron() const
{
// Note to maintainer: This function is an exact copy of AABB:ToPolyhedron() and Frustum::ToPolyhedron().
Polyhedron p;
// Populate the corners of this OBB.
// The will be in the order 0: ---, 1: --+, 2: -+-, 3: -++, 4: +--, 5: +-+, 6: ++-, 7: +++.
for(int i = 0; i < 8; ++i)
p.v.push_back(CornerPoint(i));
// Generate the 6 faces of this OBB.
const int faces[6][4] =
{
{ 0, 1, 3, 2 }, // X-
{ 4, 6, 7, 5 }, // X+
{ 0, 4, 5, 1 }, // Y-
{ 7, 6, 2, 3 }, // Y+
{ 0, 2, 6, 4 }, // Z-
{ 1, 5, 7, 3 }, // Z+
};
for(int f = 0; f < 6; ++f)
{
Polyhedron::Face face;
for(int v = 0; v < 4; ++v)
face.v.push_back(faces[f][v]);
p.f.push_back(face);
}
return p;
}
PBVolume<6> OBB::ToPBVolume() const
{
PBVolume<6> pbVolume;
for(int i = 0; i < 6; ++i)
pbVolume.p[i] = FacePlane(i);
return pbVolume;
}
AABB OBB::MinimalEnclosingAABB() const
{
AABB aabb;
aabb.SetFrom(*this);
return aabb;
}
#if 0
AABB OBB::MaximalContainedAABB() const
{
#ifdef _MSC_VER
#pragma warning(OBB::MaximalContainedAABB not implemented!)
#else
#warning OBB::MaximalContainedAABB not implemented!
#endif
assume(false && "OBB::MaximalContainedAABB not implemented!"); /// @todo Implement.
return AABB();
}
#endif
Sphere OBB::MinimalEnclosingSphere() const
{
Sphere s;
s.pos = pos;
s.r = HalfDiagonal().Length();
return s;
}
Sphere OBB::MaximalContainedSphere() const
{
Sphere s;
s.pos = pos;
s.r = r.MinElement();
return s;
}
bool OBB::IsFinite() const
{
return pos.IsFinite() && r.IsFinite() && axis[0].IsFinite() && axis[1].IsFinite() && axis[2].IsFinite();
}
bool OBB::IsDegenerate() const
{
return !(r.x > 0.f && r.y > 0.f && r.z > 0.f);
}
vec OBB::CenterPoint() const
{
return pos;
}
vec OBB::PointInside(float x, float y, float z) const
{
assume(0.f <= x && x <= 1.f);
assume(0.f <= y && y <= 1.f);
assume(0.f <= z && z <= 1.f);
return pos + axis[0] * (2.f * r.x * x - r.x)
+ axis[1] * (2.f * r.y * y - r.y)
+ axis[2] * (2.f * r.z * z - r.z);
}
LineSegment OBB::Edge(int edgeIndex) const
{
assume(0 <= edgeIndex && edgeIndex <= 11);
switch(edgeIndex)
{
default: // For release builds where assume() is disabled, return always the first option if out-of-bounds.
case 0: return LineSegment(CornerPoint(0), CornerPoint(1));
case 1: return LineSegment(CornerPoint(0), CornerPoint(2));
case 2: return LineSegment(CornerPoint(0), CornerPoint(4));
case 3: return LineSegment(CornerPoint(1), CornerPoint(3));
case 4: return LineSegment(CornerPoint(1), CornerPoint(5));
case 5: return LineSegment(CornerPoint(2), CornerPoint(3));
case 6: return LineSegment(CornerPoint(2), CornerPoint(6));
case 7: return LineSegment(CornerPoint(3), CornerPoint(7));
case 8: return LineSegment(CornerPoint(4), CornerPoint(5));
case 9: return LineSegment(CornerPoint(4), CornerPoint(6));
case 10: return LineSegment(CornerPoint(5), CornerPoint(7));
case 11: return LineSegment(CornerPoint(6), CornerPoint(7));
}
}
vec OBB::CornerPoint(int cornerIndex) const
{
assume(0 <= cornerIndex && cornerIndex <= 7);
switch(cornerIndex)
{
default: // For release builds where assume() is disabled, return always the first option if out-of-bounds.
case 0: return pos - r.x * axis[0] - r.y * axis[1] - r.z * axis[2];
case 1: return pos - r.x * axis[0] - r.y * axis[1] + r.z * axis[2];
case 2: return pos - r.x * axis[0] + r.y * axis[1] - r.z * axis[2];
case 3: return pos - r.x * axis[0] + r.y * axis[1] + r.z * axis[2];
case 4: return pos + r.x * axis[0] - r.y * axis[1] - r.z * axis[2];
case 5: return pos + r.x * axis[0] - r.y * axis[1] + r.z * axis[2];
case 6: return pos + r.x * axis[0] + r.y * axis[1] - r.z * axis[2];
case 7: return pos + r.x * axis[0] + r.y * axis[1] + r.z * axis[2];
}
}
vec OBB::ExtremePoint(const vec &direction) const
{
vec pt = pos;
pt += axis[0] * (Dot(direction, axis[0]) >= 0.f ? r.x : -r.x);
pt += axis[1] * (Dot(direction, axis[1]) >= 0.f ? r.y : -r.y);
pt += axis[2] * (Dot(direction, axis[2]) >= 0.f ? r.z : -r.z);
return pt;
}
vec OBB::ExtremePoint(const vec &direction, float &projectionDistance) const
{
vec extremePoint = ExtremePoint(direction);
projectionDistance = extremePoint.Dot(direction);
return extremePoint;
}
void OBB::ProjectToAxis(const vec &direction, float &outMin, float &outMax) const
{
float x = Abs(Dot(direction, axis[0]) * r.x);
float y = Abs(Dot(direction, axis[1]) * r.y);
float z = Abs(Dot(direction, axis[2]) * r.z);
float pt = Dot(direction, pos);
outMin = pt - x - y - z;
outMax = pt + x + y + z;
}
int OBB::UniqueFaceNormals(vec *out) const
{
out[0] = axis[0];
out[1] = axis[1];
out[2] = axis[2];
return 3;
}
int OBB::UniqueEdgeDirections(vec *out) const
{
out[0] = axis[0];
out[1] = axis[1];
out[2] = axis[2];
return 3;
}
vec OBB::PointOnEdge(int edgeIndex, float u) const
{
assume(0 <= edgeIndex && edgeIndex <= 11);
assume(0 <= u && u <= 1.f);
edgeIndex = Clamp(edgeIndex, 0, 11);
vec d = axis[edgeIndex/4] * (2.f * u - 1.f) * r[edgeIndex/4];
switch(edgeIndex)
{
default: // For release builds where assume() is disabled, return always the first option if out-of-bounds.
case 0: return pos - r.y * axis[1] - r.z * axis[2] + d;
case 1: return pos - r.y * axis[1] + r.z * axis[2] + d;
case 2: return pos + r.y * axis[1] - r.z * axis[2] + d;
case 3: return pos + r.y * axis[1] + r.z * axis[2] + d;
case 4: return pos - r.x * axis[0] - r.z * axis[2] + d;
case 5: return pos - r.x * axis[0] + r.z * axis[2] + d;
case 6: return pos + r.x * axis[0] - r.z * axis[2] + d;
case 7: return pos + r.x * axis[0] + r.z * axis[2] + d;
case 8: return pos - r.x * axis[0] - r.y * axis[1] + d;
case 9: return pos - r.x * axis[0] + r.y * axis[1] + d;
case 10: return pos + r.x * axis[0] - r.y * axis[1] + d;
case 11: return pos + r.x * axis[0] + r.y * axis[1] + d;
}
}
vec OBB::FaceCenterPoint(int faceIndex) const
{
assume(0 <= faceIndex && faceIndex <= 5);
switch(faceIndex)
{
default: // For release builds where assume() is disabled, return always the first option if out-of-bounds.
case 0: return pos - r.x * axis[0];
case 1: return pos + r.x * axis[0];
case 2: return pos - r.y * axis[1];
case 3: return pos + r.y * axis[1];
case 4: return pos - r.z * axis[2];
case 5: return pos + r.z * axis[2];
}
}
vec OBB::FacePoint(int faceIndex, float u, float v) const
{
assume(0 <= faceIndex && faceIndex <= 5);
assume(0 <= u && u <= 1.f);
assume(0 <= v && v <= 1.f);
int uIdx = faceIndex/2;
int vIdx = (faceIndex/2 + 1) % 3;
vec U = axis[uIdx] * (2.f * u - 1.f) * r[uIdx];
vec V = axis[vIdx] * (2.f * v - 1.f) * r[vIdx];
switch(faceIndex)
{
default: // For release builds where assume() is disabled, return always the first option if out-of-bounds.
case 0: return pos - r.z * axis[2] + U + V;
case 1: return pos + r.z * axis[2] + U + V;
case 2: return pos - r.x * axis[0] + U + V;
case 3: return pos + r.x * axis[0] + U + V;
case 4: return pos - r.y * axis[1] + U + V;
case 5: return pos + r.y * axis[1] + U + V;
}
}
Plane OBB::FacePlane(int faceIndex) const
{
assume(0 <= faceIndex && faceIndex <= 5);
switch(faceIndex)
{
default: // For release builds where assume() is disabled, return always the first option if out-of-bounds.
case 0: return Plane(FaceCenterPoint(0), -axis[0]);
case 1: return Plane(FaceCenterPoint(1), axis[0]);
case 2: return Plane(FaceCenterPoint(2), -axis[1]);
case 3: return Plane(FaceCenterPoint(3), axis[1]);
case 4: return Plane(FaceCenterPoint(4), -axis[2]);
case 5: return Plane(FaceCenterPoint(5), axis[2]);
}
}
void OBB::GetCornerPoints(vec *outPointArray) const
{
assume(outPointArray);
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (!outPointArray)
return;
#endif
for(int i = 0; i < 8; ++i)
outPointArray[i] = CornerPoint(i);
}
void OBB::GetFacePlanes(Plane *outPlaneArray) const
{
assume(outPlaneArray);
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (!outPlaneArray)
return;
#endif
for(int i = 0; i < 6; ++i)
outPlaneArray[i] = FacePlane(i);
}
/// See Christer Ericson's book Real-Time Collision Detection, page 83.
void OBB::ExtremePointsAlongDirection(const vec &dir, const vec *pointArray, int numPoints, int &idxSmallest, int &idxLargest, float &smallestD, float &largestD)
{
assume(pointArray || numPoints == 0);
idxSmallest = idxLargest = 0;
#ifndef MATH_ENABLE_INSECURE_OPTIMIZATIONS
if (!pointArray)
return;
#endif
smallestD = FLOAT_INF;
largestD = -FLOAT_INF;
for(int i = 0; i < numPoints; ++i)
{
float d = Dot(pointArray[i], dir);
if (d < smallestD)
{
smallestD = d;
idxSmallest = i;
}
if (d > largestD)
{
largestD = d;
idxLargest = i;
}
}
}
float SmallestOBBVolumeJiggle(const vec &edge_, const Polyhedron &convexHull, std::vector<float2> &pts,
vec &outEdgeA, vec &outEdgeB)
{
vec edge = edge_;
int numTimesNotImproved = 0;
float bestVolume = FLOAT_INF;
float2 c10, c20;
vec u, v;
vec prevSecondChoice = vec::nan;
int numJiggles = 2;
while(numTimesNotImproved < 2)
{
int e1, e2;
OBB::ExtremePointsAlongDirection(edge, (const vec*)&convexHull.v[0], (int)convexHull.v.size(), e1, e2);
float edgeLength = Abs(Dot((vec)convexHull.v[e1] - convexHull.v[e2], edge));
edge.PerpendicularBasis(u, v);
for(size_t k = 0; k < convexHull.v.size(); ++k)
pts[k] = float2(u.Dot(convexHull.v[k]), v.Dot(convexHull.v[k]));
float2 rectCenter;
float2 uDir;
float2 vDir;
float minU, maxU, minV, maxV;
float rectArea = float2::MinAreaRectInPlace(&pts[0], (int)pts.size(), rectCenter, uDir, vDir, minU, maxU, minV, maxV);
c10 = (maxV - minV) * vDir;
c20 = (maxU - minU) * uDir;
float volume = rectArea*edgeLength;
if (volume + 1e-5f < bestVolume)
{
bestVolume = volume;
edge = (c10.x*u + c10.y*v);
float len = edge.Normalize();
if (len <= 0.f)
edge = u;
numTimesNotImproved = 0;
prevSecondChoice = (c20.x*u + c20.y*v);
len = prevSecondChoice.Normalize();
if (len <= 0.f)
prevSecondChoice = u;
outEdgeA = edge;
outEdgeB = prevSecondChoice;
// Enable for a dirty hack to experiment with performance.
//#define NO_JIGGLES
#ifdef NO_JIGGLES
break;
#endif
}
else
{
++numTimesNotImproved;
edge = prevSecondChoice;
}
if (--numJiggles <= 0)
break;
}
return bestVolume;
}
// Moves the floating point sign bit from src to dst.
#ifdef MATH_SSE
#define MoveSign(dst, src) \
dst = s4f_x(xor_ps(setx_ps(dst), and_ps(setx_ps(src), simd4fSignBit))); \
src = s4f_x(abs_ps(setx_ps(src)));
#else
#define MoveSign(dst, src) if (src < 0.f) { dst = -dst; src = -src; }
#endif
int ComputeBasis(const vec &f1a, const vec &f1b,
const vec &f2a, const vec &f2b,
const vec &f3a, const vec &f3b,
vec *n1,
vec *n2,
vec *n3)
{
const float eps = 1e-4f;
const float angleEps = 1e-3f;
{
vec a = f1b;
vec b = f1a-f1b;
vec c = f2b;
vec d = f2a-f2b;
vec e = f3b;
vec f = f3a-f3b;
float g = a.Dot(c)*d.Dot(e) - a.Dot(d)*c.Dot(e);
float h = a.Dot(c)*d.Dot(f) - a.Dot(d)*c.Dot(f);
float i = b.Dot(c)*d.Dot(e) - b.Dot(d)*c.Dot(e);
float j = b.Dot(c)*d.Dot(f) - b.Dot(d)*c.Dot(f);
float k = g*b.Dot(e) - a.Dot(e)*i;
float l = h*b.Dot(e) + g*b.Dot(f) - a.Dot(f)*i - a.Dot(e)*j;
float m = h*b.Dot(f) - a.Dot(f)*j;
float s = l*l - 4*m*k;
if (Abs(m) < 1e-5f || Abs(s) < 1e-5f)
{
// The equation is linear instead.
float v = -k / l;
float t = -(g + h*v) / (i + j*v);
float u = -(c.Dot(e) + c.Dot(f)*v) / (d.Dot(e) + d.Dot(f)*v);
int nSolutions = 0;
// If we happened to divide by zero above, the following checks handle them.
if (v >= -eps && t >= -eps && u >= -eps && v <= 1.f + eps && t <= 1.f + eps && u <= 1.f + eps)
{
n1[0] = (a + b*t).Normalized();
n2[0] = (c + d*u).Normalized();
n3[0] = (e + f*v).Normalized();
if (Abs(n1[0].Dot(n2[0])) < angleEps
&& Abs(n1[0].Dot(n3[0])) < angleEps
&& Abs(n2[0].Dot(n3[0])) < angleEps)
return 1;
else
return 0;
}
return nSolutions;
}
if (s < 0.f)
return 0; // Discriminant negative, no solutions for v.
float sgnL = l < 0 ? -1.f : 1.f;
float V1 = -(l + sgnL*Sqrt(s))/ (2.f*m);
float V2 = k / (m*V1);
float T1 = -(g + h*V1) / (i + j*V1);
float T2 = -(g + h*V2) / (i + j*V2);
float U1 = -(c.Dot(e) + c.Dot(f)*V1) / (d.Dot(e) + d.Dot(f)*V1);
float U2 = -(c.Dot(e) + c.Dot(f)*V2) / (d.Dot(e) + d.Dot(f)*V2);
int nSolutions = 0;
if (V1 >= -eps && T1 >= -eps && U1 >= -eps && V1 <= 1.f + eps && T1 <= 1.f + eps && U1 <= 1.f + eps)
{
n1[nSolutions] = (a + b*T1).Normalized();
n2[nSolutions] = (c + d*U1).Normalized();
n3[nSolutions] = (e + f*V1).Normalized();
if (Abs(n1[nSolutions].Dot(n2[nSolutions])) < angleEps
&& Abs(n1[nSolutions].Dot(n3[nSolutions])) < angleEps
&& Abs(n2[nSolutions].Dot(n3[nSolutions])) < angleEps)
++nSolutions;
}
if (V2 >= -eps && T2 >= -eps && U2 >= -eps && V2 <= 1.f + eps && T2 <= 1.f + eps && U2 <= 1.f + eps)
{
n1[nSolutions] = (a + b*T2).Normalized();
n2[nSolutions] = (c + d*U2).Normalized();
n3[nSolutions] = (e + f*V2).Normalized();
if (Abs(n1[nSolutions].Dot(n2[nSolutions])) < angleEps
&& Abs(n1[nSolutions].Dot(n3[nSolutions])) < angleEps
&& Abs(n2[nSolutions].Dot(n3[nSolutions])) < angleEps)
++nSolutions;
}
if (s < 1e-4f && nSolutions == 2)
nSolutions = 1;
return nSolutions;
}
}
// A heuristic(?) that checks of the face normals of two edges are not suitably oriented.
// This is used to skip certain configurations.
static bool AreEdgesBad(const vec &f1a, const vec &f1b, const vec &f2a, const vec &f2b)
{
MARK_UNUSED(f1a);
MARK_UNUSED(f1b);
MARK_UNUSED(f2a);
MARK_UNUSED(f2b);
return false;
// Currently disabled. It's not completely certain if there's a form of this heuristic that
// might be perfect, needs more tweaking.
#if 0
float a1 = Abs(f1a.Dot(f1b));
float a2 = Abs(f2a.Dot(f2b));
float b1 = Abs(f1a.Dot(f2b));
float b2 = Abs(f2a.Dot(f1b));
const float limitEpsilon = 1e-4f;
if ((a1 > 1.f - limitEpsilon && a2 < limitEpsilon) || (a2 > 1.f - limitEpsilon && a1 < limitEpsilon))
return true;
if ((b1 > 1.f - limitEpsilon && b2 < limitEpsilon) || (b2 > 1.f - limitEpsilon && b1 < limitEpsilon))
return true;
if ((a1 > 1.f - limitEpsilon || a1 < limitEpsilon) && (a2 > 1.f - limitEpsilon || a2 < limitEpsilon))
return true;
if ((b1 > 1.f - limitEpsilon || b1 < limitEpsilon) && (b2 > 1.f - limitEpsilon || b2 < limitEpsilon))
return true;
return false;
#endif
}
static bool AreEdgesCompatibleForOBB(const vec &f1a, const vec &f1b, const vec &f2a, const vec &f2b)
{
const vec f1a_f1b = f1a-f1b;
const vec f2a_f2b = f2a-f2b;
float a = f1b.Dot(f2b);
float b = (f1a_f1b).Dot(f2b);
float c = (f2a_f2b).Dot(f1b);
float d = (f1a_f1b).Dot(f2a_f2b);
/*
n1 = f1a*t + f1b*(1-t) = f1b + (f1a-f1b)*t
n2 = f2a*u + f2b*(1-u) = f2b + (f2a-f2b)*u
n1.n2 = 0
f1b.f2b + t*(f1a-f1b).f2b + u*(f2a-f2b).f1b + t*u*(f1a-f1b).(f2a-f2b) = 0
a + t*b + u*c + t*u*d = 0
Does this equation have a solution within t & u \in [0,1]?
// The function f(t,u) = a + t*b + u*c + t*u*d is continuous and bilinear
// with respect to t and u, so test the four corners to get the minimum
// and maximum of the function. If minimum <= 0 and
// maximum >= 0, we know it must have a zero inside t,u \in [0,1].
t=0: f(t,u)=a+uc => min: a, max: a+c
u=0: f(t,u)=a+tb => min: a, max: a+b
t=1: f(t,u)=a+uc + b+ud => min: a+b, max: a+b+c+d
u=1: f(t,u)=a+tb + c+td => min: a+c, max: a+b+c+d
*/
float ab = a+b;
float ac = a+c;
float abcd = ab+c+d;
float minVal = Min(a, ab, ac, abcd);
float maxVal = Max(a, ab, ac, abcd);
return minVal <= 0.f && maxVal >= 0.f;
}
// Enable this to add extra runtime checks to sanity test that the generated OBB is actually valid.
//#define OBB_ASSERT_VALIDITY
// Enable this to add internal debug prints for tracking internal behavior.
//#define OBB_DEBUG_PRINT
// Enable this to print out detailed profiling info.
//#define ENABLE_TIMING
#ifdef ENABLE_TIMING
#define TIMING_TICK(...) __VA_ARGS__
#define TIMING LOGI
#else
#define TIMING(...) ((void)0)
#define TIMING_TICK(...) ((void)0)
#endif
namespace
{
struct hash_edge
{
size_t operator()(const std::pair<int, int> &e) const
{
return (e.first << 16) ^ e.second;
}
};
}
bool AreCompatibleOpposingEdges(const vec &f1a, const vec &f1b, const vec &f2a, const vec &f2b, vec &outN)
{
/*
n1 = f1a*t + f1b*(1-t)
n2 = f2a*u + f2b*(1-u)
n1 = -c*n2, where c > 0
f1a*t + f1b*(1-t) = -c*f2a*u - c*f2b*(1-u)
f1a*t - f1b*t + cu*f2a + c*f2b - cu*f2b = -f1b
c*f2b + t*(f1a-f1b) + cu*(f2a-f2b) = -f1b
M * v = -f1b, where
M = [ f2b, (f1a-f1b), (f2a-f2b) ] column vectors
v = [c, t, cu]
*/
const float tooCloseToFaceEpsilon = 1e-4f;
float3x3 A;
A.SetCol(0, f2b.xyz()); // c
A.SetCol(1, (f1a - f1b).xyz()); // t
A.SetCol(2, (f2a - f2b).xyz()); // r = c*u
float3 x;
bool success = A.SolveAxb(-f1b.xyz(), x);
float c = x[0];
float t = x[1];
float cu = x[2];
if (!success || c <= 0.f || t < 0.f || t > 1.f)
return false;
float u = cu / c;
if (t < tooCloseToFaceEpsilon || t > 1.f - tooCloseToFaceEpsilon
|| u < tooCloseToFaceEpsilon || u > 1.f - tooCloseToFaceEpsilon)
return false;
if (cu < 0.f || cu > c)
return false;
outN = f1b + (f1a-f1b)*t;
return true;
}
OBB OBB::OptimalEnclosingOBB(const vec *pointArray, int numPoints)
{
// Precomputation: Generate the convex hull of the input point set. This is because
// we need vertex-edge-face connectivity information about the convex hull shape, and
// this also allows discarding all points in the interior of the input hull, which
// are irrelevant.
Polyhedron convexHull = Polyhedron::ConvexHull(pointArray, numPoints);
if (!pointArray || convexHull.v.size() == 0)
{
OBB minOBB;
minOBB.SetNegativeInfinity();
return minOBB;
}
return OptimalEnclosingOBB(convexHull);
}
bool SortedArrayContains(const std::vector<int> &arr, int i)
{
size_t left = 0;
size_t right = arr.size() - 1;
if (arr[left] == i || arr[right] == i)
return true;
if (arr[left] > i || arr[right] < i)
return false;
while(left < right)
{
size_t middle = (left + right + 1) >> 1;
if (arr[middle] < i)
left = i;
else if (arr[middle] > i)
right = i;
else
return true;
}
return false;
}
bool IsVertexAntipodalToEdge(const Polyhedron &convexHull, int vi, const std::vector<int> &neighbors, const vec &f1a, const vec &f1b)
{
float tMin = 0.f;
float tMax = 1.f;
vec v = convexHull.v[vi];
vec f1b_f1a = f1b-f1a;
for(size_t i = 0; i < neighbors.size(); ++i)
{
/* Is an edge and a vertex compatible to be antipodal?
n1 = f1b + (f1a-f1b)*t
e { v-vn }
n1.e <= 0
(f1b + (f1a-f1b)*t).e <= 0
t*(f1a-f1b).e <= -f1b.e
if (f1a-f1b).e > 0:
t <= -f1b.e / (f1a-f1b).e && t \in [0,1]
-f1b.e / (f1a-f1b).e >= 0
f1b.e <= 0
if (f1a-f1b).e < 0:
t >= -f1b.e / (f1a-f1b).e && t \in [0,1]
-f1b.e / (f1a-f1b).e <= 1
-f1b.e >= (f1a-f1b).e
f1b.e + (f1a-f1b).e <= 0
if (f1a-f1b).e == 0:
0 <= -f1b.e
*/
vec e = vec(convexHull.v[neighbors[i]]) - v;
float s = f1b_f1a.Dot(e);
float n = f1b.Dot(e);
const float epsilon = 1e-4f;
if (s > epsilon)
tMax = Min(tMax, n / s);
else if (s < -epsilon)
tMin = Max(tMin, n / s);
else if (n < -epsilon)
return false;
// The interval of possible solutions for t is now degenerate?
if (tMax - tMin < -5e-2f) // -1e-3f has been seen to be too strict here.
return false;
}
return true;
}
void FORCE_INLINE TestThreeAdjacentFaces(const vec &n1, const vec &n2, const vec &n3,
int edgeI, int edgeJ, int edgeK,
const Polyhedron &convexHull, const std::vector<std::pair<int, int> > &edges,
const std::vector<std::vector<int> > &antipodalPointsForEdge,
float *minVolume, OBB *minOBB)
{
// Compute the most extreme points in each direction.
float maxN1 = n1.Dot(convexHull.v[edges[edgeI].first]);
float maxN2 = n2.Dot(convexHull.v[edges[edgeJ].first]);
float maxN3 = n3.Dot(convexHull.v[edges[edgeK].first]);
float minN1 = FLOAT_INF;
float minN2 = FLOAT_INF;
float minN3 = FLOAT_INF;
for(size_t l = 0; l < antipodalPointsForEdge[edgeI].size(); ++l) // O(constant)?
minN1 = Min(minN1, n1.Dot(convexHull.v[antipodalPointsForEdge[edgeI][l]]));
for(size_t l = 0; l < antipodalPointsForEdge[edgeJ].size(); ++l) // O(constant)?
minN2 = Min(minN2, n2.Dot(convexHull.v[antipodalPointsForEdge[edgeJ][l]]));
for(size_t l = 0; l < antipodalPointsForEdge[edgeK].size(); ++l) // O(constant)?
minN3 = Min(minN3, n3.Dot(convexHull.v[antipodalPointsForEdge[edgeK][l]]));
float volume = (maxN1 - minN1) * (maxN2 - minN2) * (maxN3 - minN3);
if (volume < *minVolume)
{
minOBB->axis[0] = n1;
minOBB->axis[1] = n2;
minOBB->axis[2] = n3;
minOBB->r[0] = (maxN1 - minN1) * 0.5f;
minOBB->r[1] = (maxN2 - minN2) * 0.5f;
minOBB->r[2] = (maxN3 - minN3) * 0.5f;
minOBB->pos = (minN1 + minOBB->r[0])*n1 + (minN2 + minOBB->r[1])*n2 + (minN3 + minOBB->r[2])*n3;
assert(volume > 0.f);
#ifdef OBB_ASSERT_VALIDITY
OBB o = OBB::FixedOrientationEnclosingOBB((const vec*)&convexHull.v[0], convexHull.v.size(), minOBB->axis[0], minOBB->axis[1]);
assert2(EqualRel(o.Volume(), volume), o.Volume(), volume);
#endif
*minVolume = volume;
}
}
OBB OBB::OptimalEnclosingOBB(const Polyhedron &convexHull)
{
/* Outline of the algorithm:
0. Compute the convex hull of the point set (given as input to this function) O(VlogV)
1. Compute vertex adjacency data, i.e. given a vertex, return a list of its neighboring vertices. O(V)
2. Precompute face normal direction vectors, since these are needed often. (does not affect big-O complexity, just a micro-opt) O(F)
3. Compute edge adjacency data, i.e. given an edge, return the two indices of its neighboring faces. O(V)
4. Precompute antipodal vertices for each edge. O(A*ElogV), where A is the size of antipodal vertices per edge. A ~ O(1) on average.
5. Precompute all sidepodal edges for each edge. O(E*S), where S is the size of sidepodal edges per edge. S ~ O(sqrtE) on average.
- Sort the sidepodal edges to a linear order so that it's possible to do fast set intersection computations on them. O(E*S*logS), or O(E*sqrtE*logE).
6. Test all configurations where all three edges are on adjacent faces. O(E*S^2) = O(E^2) or if smart with graph search, O(ES) = O(E*sqrtE)?
7. Test all configurations where two edges are on opposing faces, and the third one is on a face adjacent to the two. O(E*sqrtE*logV)?
8. Test all configurations where two edges are on the same face (OBB aligns with a face of the convex hull). O(F*sqrtE*logV).
9. Return the best found OBB.
*/
OBB minOBB;
float minVolume = FLOAT_INF;
// Handle degenerate planar cases up front.
if (convexHull.v.size() <= 3 || convexHull.f.size() <= 1)
{
// TODO
LOGW("Convex hull is degenerate and has only %d vertices/%d faces!", (int)convexHull.v.size(), (int)convexHull.f.size());
minOBB.SetNegativeInfinity();
return minOBB;
}
TIMING_TICK(tick_t t1 = Clock::Tick());
// Precomputation: For each vertex in the convex hull, compute their neighboring vertices.
std::vector<std::vector<int> > adjacencyData = convexHull.GenerateVertexAdjacencyData(); // O(V)
TIMING_TICK(tick_t t2 = Clock::Tick());
TIMING("Adjacencygeneration: %f msecs", Clock::TimespanToMillisecondsF(t1, t2));
// Precomputation: Compute normalized face direction vectors for each face of the hull.
//std::vector<vec_storage> faceNormals;
VecArray faceNormals;
faceNormals.reserve(convexHull.NumFaces());
for(int i = 0; i < convexHull.NumFaces(); ++i) // O(F)
{
if (convexHull.f[i].v.size() < 3)
{
LOGE("Input convex hull contains a degenerate face %d with only %d vertices! Cannot process this!",
i, (int)convexHull.f[i].v.size());
return minOBB;
}
vec normal = convexHull.FaceNormal(i);
faceNormals.push_back(DIR_VEC((float)normal.x, (float)normal.y, (float)normal.z));
}
TIMING_TICK(tick_t t23 = Clock::Tick());
TIMING("Facenormalsgen: %f msecs", Clock::TimespanToMillisecondsF(t2, t23));
#ifdef OBB_ASSERT_VALIDITY
// For debugging, assert that face normals in the input Polyhedron are pointing in valid directions:
for(size_t i = 0; i < faceNormals.size(); ++i)
{
vec pointOnFace = convexHull.v[convexHull.f[i].v[0]];
for(size_t j = 0; j < convexHull.v.size(); ++j)
{
vec pointDiff = vec(convexHull.v[j]) - pointOnFace;
float signedDistance = pointDiff.Dot(faceNormals[i]);
if (signedDistance > 1e-1f)
{
// Find how deep there are points on the opposite side.
int extremeOpposite = convexHull.ExtremeVertex(-vec(faceNormals[i]));
float signedDistanceOpposite = Dot(vec(convexHull.v[extremeOpposite]) - pointOnFace, faceNormals[i]);
LOGE("Vertex %d is %f units deep on the wrong side of face %d (which has %d vertices and surface area %f): On the opposite side, extreme signed distance is vtx %d at d %f.", (int)j, signedDistance,
(int)i, (int)convexHull.f[i].v.size(), convexHull.FacePolygon(i).Area(), extremeOpposite, signedDistanceOpposite);
break;
}
}
}
#endif