-
Notifications
You must be signed in to change notification settings - Fork 270
/
VHACD.h
8364 lines (7287 loc) · 253 KB
/
VHACD.h
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 (c) 2011 Khaled Mamou (kmamou at gmail dot com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#ifndef VHACD_H
# define VHACD_H
// Please view this slide deck which describes usage and how the algorithm works.
// https://docs.google.com/presentation/d/1OZ4mtZYrGEC8qffqb8F7Le2xzufiqvaPpRbLHKKgTIM/edit?usp=sharing
// VHACD is now a header only library.
// In just *one* of your CPP files *before* you include 'VHACD.h' you must declare
// #define ENABLE_VHACD_IMPLEMENTATION 1
// This will compile the implementation code into your project. If you don't
// have this define, you will get link errors since the implementation code will
// not be present. If you define it more than once in your code base, you will get
// link errors due to a duplicate implementation. This is the same pattern used by
// ImGui and StbLib and other popular open source libraries.
# define VHACD_VERSION_MAJOR 4
# define VHACD_VERSION_MINOR 1
// Changes for version 4.1
//
// Various minor tweaks mostly to the test application and some default values.
// Changes for version 4.0
//
// * The code has been significantly refactored to be cleaner and easier to maintain
// * All OpenCL related code removed
// * All Bullet code removed
// * All SIMD code removed
// * Old plane splitting code removed
//
// * The code is now delivered as a single header file 'VHACD.h' which has both the API
// * declaration as well as the implementation. Simply add '#define ENABLE_VHACD_IMPLEMENTATION 1'
// * to any CPP in your application prior to including 'VHACD.h'. Only do this in one CPP though.
// * If you do not have this define once, you will get link errors since the implementation code
// * will not be compiled in. If you have this define more than once, you are likely to get
// * duplicate symbol link errors.
//
// * Since the library is now delivered as a single header file, we do not provide binaries
// * or build scripts as these are not needed.
//
// * The old DebugView and test code has all been removed and replaced with a much smaller and
// * simpler test console application with some test meshes to work with.
//
// * The convex hull generation code has changed. The previous version came from Bullet.
// * However, the new version is courtesy of Julio Jerez, the author of the Newton
// * physics engine. His new version is faster and more numerically stable.
//
// * The code can now detect if the input mesh is, itself, already a convex object and
// * can early out.
//
// * Significant performance improvements have been made to the code and it is now much
// * faster, stable, and is easier to tune than previous versions.
//
// * A bug was fixed with the shrink wrapping code (project hull vertices) that could
// * sometime produce artifacts in the results. The new version uses a 'closest point'
// * algorithm that is more reliable.
//
// * You can now select which 'fill mode' to use. For perfectly closed meshes, the default
// * behavior using a flood fill generally works fine. However, some meshes have small
// * holes in them and therefore the flood fill will fail, treating the mesh as being
// * hollow. In these cases, you can use the 'raycast' fill option to determine which
// * parts of the voxelized mesh are 'inside' versus being 'outside'. Finally, there
// * are some rare instances where a user might actually want the mesh to be treated as
// * hollow, in which case you can pass in 'surface' only.
// *
// * A new optional virtual interface called 'IUserProfiler' was provided.
// * This allows the user to provide an optional profiling callback interface to assist in
// * diagnosing performance issues. This change was made by Danny Couture at Epic for the UE4 integration.
// * Some profiling macros were also declared in support of this feature.
// *
// * Another new optional virtual interface called 'IUserTaskRunner' was provided.
// * This interface is used to run logical 'tasks' in a background thread. If none is provided
// * then a default implementation using std::thread will be executed.
// * This change was made by Danny Couture at Epic to speed up the voxelization step.
// *
// The history of V-HACD:
//
// The initial version was written by John W. Ratcliff and was called 'ACD'
// This version did not perform CSG operations on the source mesh, so if you
// recursed too deeply it would produce hollow results.
//
// The next version was written by Khaled Mamou and was called 'HACD'
// In this version Khaled tried to perform a CSG operation on the source
// mesh to produce more robust results. However, Khaled learned that the
// CSG library he was using had licensing issues so he started work on the
// next version.
//
// The next version was called 'V-HACD' because Khaled made the observation
// that plane splitting would be far easier to implement working in voxel space.
//
// V-HACD has been integrated into UE4, Blender, and a number of other projects.
// This new release, version4, is a significant refactor of the code to fix
// some bugs, improve performance, and to make the codebase easier to maintain
// going forward.
#include <stdint.h>
#include <functional>
#include <vector>
#include <array>
#include <cmath>
#include <algorithm>
namespace VHACD {
struct Vertex
{
double mX;
double mY;
double mZ;
Vertex() = default;
Vertex(double x, double y, double z) : mX(x), mY(y), mZ(z) {}
const double& operator[](size_t idx) const
{
switch(idx)
{
case 0: return mX;
case 1: return mY;
case 2: return mZ;
};
return mX;
}
};
struct Triangle
{
uint32_t mI0;
uint32_t mI1;
uint32_t mI2;
Triangle() = default;
Triangle(uint32_t i0, uint32_t i1, uint32_t i2) : mI0(i0), mI1(i1), mI2(i2) {}
};
template <typename T>
class Vector3
{
public:
/*
* Getters
*/
T& operator[](size_t i);
const T& operator[](size_t i) const;
T& GetX();
T& GetY();
T& GetZ();
const T& GetX() const;
const T& GetY() const;
const T& GetZ() const;
/*
* Normalize and norming
*/
T Normalize();
Vector3 Normalized();
T GetNorm() const;
T GetNormSquared() const;
int LongestAxis() const;
/*
* Vector-vector operations
*/
Vector3& operator=(const Vector3& rhs);
Vector3& operator+=(const Vector3& rhs);
Vector3& operator-=(const Vector3& rhs);
Vector3 CWiseMul(const Vector3& rhs) const;
Vector3 Cross(const Vector3& rhs) const;
T Dot(const Vector3& rhs) const;
Vector3 operator+(const Vector3& rhs) const;
Vector3 operator-(const Vector3& rhs) const;
/*
* Vector-scalar operations
*/
Vector3& operator-=(T a);
Vector3& operator+=(T a);
Vector3& operator/=(T a);
Vector3& operator*=(T a);
Vector3 operator*(T rhs) const;
Vector3 operator/(T rhs) const;
/*
* Unary operations
*/
Vector3 operator-() const;
/*
* Comparison operators
*/
bool operator<(const Vector3& rhs) const;
bool operator>(const Vector3& rhs) const;
/*
* Returns true if all elements of *this are greater than or equal to all elements of rhs, coefficient wise
* LE is less than or equal
*/
bool CWiseAllGE(const Vector3<T>& rhs) const;
bool CWiseAllLE(const Vector3<T>& rhs) const;
Vector3 CWiseMin(const Vector3& rhs) const;
Vector3 CWiseMax(const Vector3& rhs) const;
T MinCoeff() const;
T MaxCoeff() const;
T MinCoeff(uint32_t& idx) const;
T MaxCoeff(uint32_t& idx) const;
/*
* Constructors
*/
Vector3() = default;
Vector3(T a);
Vector3(T x, T y, T z);
Vector3(const Vector3& rhs);
~Vector3() = default;
template <typename U>
Vector3(const Vector3<U>& rhs);
Vector3(const VHACD::Vertex&);
Vector3(const VHACD::Triangle&);
operator VHACD::Vertex() const;
private:
std::array<T, 3> m_data{ T(0.0) };
};
typedef VHACD::Vector3<double> Vect3;
struct BoundsAABB
{
BoundsAABB() = default;
BoundsAABB(const std::vector<VHACD::Vertex>& points);
BoundsAABB(const Vect3& min,
const Vect3& max);
BoundsAABB Union(const BoundsAABB& b);
bool Intersects(const BoundsAABB& b) const;
double SurfaceArea() const;
double Volume() const;
BoundsAABB Inflate(double ratio) const;
VHACD::Vect3 ClosestPoint(const VHACD::Vect3& p) const;
VHACD::Vect3& GetMin();
VHACD::Vect3& GetMax();
const VHACD::Vect3& GetMin() const;
const VHACD::Vect3& GetMax() const;
VHACD::Vect3 GetSize() const;
VHACD::Vect3 GetCenter() const;
VHACD::Vect3 m_min{ double(0.0) };
VHACD::Vect3 m_max{ double(0.0) };
};
/**
* This enumeration determines how the voxels as filled to create a solid
* object. The default should be 'FLOOD_FILL' which generally works fine
* for closed meshes. However, if the mesh is not watertight, then using
* RAYCAST_FILL may be preferable as it will determine if a voxel is part
* of the interior of the source mesh by raycasting around it.
*
* Finally, there are some cases where you might actually want a convex
* decomposition to treat the source mesh as being hollow. If that is the
* case you can pass in 'SURFACE_ONLY' and then the convex decomposition
* will converge only onto the 'skin' of the surface mesh.
*/
enum class FillMode
{
FLOOD_FILL, // This is the default behavior, after the voxelization step it uses a flood fill to determine 'inside'
// from 'outside'. However, meshes with holes can fail and create hollow results.
SURFACE_ONLY, // Only consider the 'surface', will create 'skins' with hollow centers.
RAYCAST_FILL, // Uses raycasting to determine inside from outside.
};
class IVHACD
{
public:
/**
* This optional pure virtual interface is used to notify the caller of the progress
* of convex decomposition as well as a signal when it is complete when running in
* a background thread
*/
class IUserCallback
{
public:
virtual ~IUserCallback(){};
/**
* Notifies the application of the current state of the convex decomposition operation
*
* @param overallProgress : Total progress from 0-100%
* @param stageProgress : Progress of the current stage 0-100%
* @param stage : A text description of the current stage we are in
* @param operation : A text description of what operation is currently being performed.
*/
virtual void Update(const double overallProgress,
const double stageProgress,
const char* const stage,
const char* operation) = 0;
// This is an optional user callback which is only called when running V-HACD asynchronously.
// This is a callback performed to notify the user that the
// convex decomposition background process is completed. This call back will occur from
// a different thread so the user should take that into account.
virtual void NotifyVHACDComplete()
{
}
};
/**
* Optional user provided pure virtual interface to be notified of warning or informational messages
*/
class IUserLogger
{
public:
virtual ~IUserLogger(){};
virtual void Log(const char* const msg) = 0;
};
/**
* An optional user provided pure virtual interface to perform a background task.
* This was added by Danny Couture at Epic as they wanted to use their own
* threading system instead of the standard library version which is the default.
*/
class IUserTaskRunner
{
public:
virtual ~IUserTaskRunner(){};
virtual void* StartTask(std::function<void()> func) = 0;
virtual void JoinTask(void* Task) = 0;
};
/**
* A simple class that represents a convex hull as a triangle mesh with
* double precision vertices. Polygons are not currently provided.
*/
class ConvexHull
{
public:
std::vector<VHACD::Vertex> m_points;
std::vector<VHACD::Triangle> m_triangles;
double m_volume{ 0 }; // The volume of the convex hull
VHACD::Vect3 m_center{ 0, 0, 0 }; // The centroid of the convex hull
uint32_t m_meshId{ 0 }; // A unique id for this convex hull
VHACD::Vect3 mBmin; // Bounding box minimum of the AABB
VHACD::Vect3 mBmax; // Bounding box maximum of the AABB
};
/**
* This class provides the parameters controlling the convex decomposition operation
*/
class Parameters
{
public:
IUserCallback* m_callback{nullptr}; // Optional user provided callback interface for progress
IUserLogger* m_logger{nullptr}; // Optional user provided callback interface for log messages
IUserTaskRunner* m_taskRunner{nullptr}; // Optional user provided interface for creating tasks
uint32_t m_maxConvexHulls{ 64 }; // The maximum number of convex hulls to produce
uint32_t m_resolution{ 400000 }; // The voxel resolution to use
double m_minimumVolumePercentErrorAllowed{ 1 }; // if the voxels are within 1% of the volume of the hull, we consider this a close enough approximation
uint32_t m_maxRecursionDepth{ 10 }; // The maximum recursion depth
bool m_shrinkWrap{true}; // Whether or not to shrinkwrap the voxel positions to the source mesh on output
FillMode m_fillMode{ FillMode::FLOOD_FILL }; // How to fill the interior of the voxelized mesh
uint32_t m_maxNumVerticesPerCH{ 64 }; // The maximum number of vertices allowed in any output convex hull
bool m_asyncACD{ true }; // Whether or not to run asynchronously, taking advantage of additional cores
uint32_t m_minEdgeLength{ 2 }; // Once a voxel patch has an edge length of less than 4 on all 3 sides, we don't keep recursing
bool m_findBestPlane{ false }; // Whether or not to attempt to split planes along the best location. Experimental feature. False by default.
};
/**
* Will cause the convex decomposition operation to be canceled early. No results will be produced but the background operation will end as soon as it can.
*/
virtual void Cancel() = 0;
/**
* Compute a convex decomposition of a triangle mesh using float vertices and the provided user parameters.
*
* @param points : The vertices of the source mesh as floats in the form of X1,Y1,Z1, X2,Y2,Z2,.. etc.
* @param countPoints : The number of vertices in the source mesh.
* @param triangles : The indices of triangles in the source mesh in the form of I1,I2,I3, ....
* @param countTriangles : The number of triangles in the source mesh
* @param params : The convex decomposition parameters to apply
* @return : Returns true if the convex decomposition operation can be started
*/
virtual bool Compute(const float* const points,
const uint32_t countPoints,
const uint32_t* const triangles,
const uint32_t countTriangles,
const Parameters& params) = 0;
/**
* Compute a convex decomposition of a triangle mesh using double vertices and the provided user parameters.
*
* @param points : The vertices of the source mesh as floats in the form of X1,Y1,Z1, X2,Y2,Z2,.. etc.
* @param countPoints : The number of vertices in the source mesh.
* @param triangles : The indices of triangles in the source mesh in the form of I1,I2,I3, ....
* @param countTriangles : The number of triangles in the source mesh
* @param params : The convex decomposition parameters to apply
* @return : Returns true if the convex decomposition operation can be started
*/
virtual bool Compute(const double* const points,
const uint32_t countPoints,
const uint32_t* const triangles,
const uint32_t countTriangles,
const Parameters& params) = 0;
/**
* Returns the number of convex hulls that were produced.
*
* @return : Returns the number of convex hulls produced, or zero if it failed or was canceled
*/
virtual uint32_t GetNConvexHulls() const = 0;
/**
* Retrieves one of the convex hulls in the solution set
*
* @param index : Which convex hull to retrieve
* @param ch : The convex hull descriptor to return
* @return : Returns true if the convex hull exists and could be retrieved
*/
virtual bool GetConvexHull(const uint32_t index,
ConvexHull& ch) const = 0;
/**
* Releases any memory allocated by the V-HACD class
*/
virtual void Clean() = 0; // release internally allocated memory
/**
* Releases this instance of the V-HACD class
*/
virtual void Release() = 0; // release IVHACD
// Will compute the center of mass of the convex hull decomposition results and return it
// in 'centerOfMass'. Returns false if the center of mass could not be computed.
virtual bool ComputeCenterOfMass(double centerOfMass[3]) const = 0;
// In synchronous mode (non-multi-threaded) the state is always 'ready'
// In asynchronous mode, this returns true if the background thread is not still actively computing
// a new solution. In an asynchronous config the 'IsReady' call will report any update or log
// messages in the caller's current thread.
virtual bool IsReady() const
{
return true;
}
/**
* At the request of LegionFu : out_look@foxmail.com
* This method will return which convex hull is closest to the source position.
* You can use this method to figure out, for example, which vertices in the original
* source mesh are best associated with which convex hull.
*
* @param pos : The input 3d position to test against
*
* @return : Returns which convex hull this position is closest to.
*/
virtual uint32_t findNearestConvexHull(const double pos[3],
double& distanceToHull) = 0;
protected:
virtual ~IVHACD()
{
}
};
/*
* Out of line definitions
*/
template <typename T>
T clamp(const T& v, const T& lo, const T& hi)
{
if (v < lo)
{
return lo;
}
if (v > hi)
{
return hi;
}
return v ;
}
/*
* Getters
*/
template <typename T>
inline T& Vector3<T>::operator[](size_t i)
{
return m_data[i];
}
template <typename T>
inline const T& Vector3<T>::operator[](size_t i) const
{
return m_data[i];
}
template <typename T>
inline T& Vector3<T>::GetX()
{
return m_data[0];
}
template <typename T>
inline T& Vector3<T>::GetY()
{
return m_data[1];
}
template <typename T>
inline T& Vector3<T>::GetZ()
{
return m_data[2];
}
template <typename T>
inline const T& Vector3<T>::GetX() const
{
return m_data[0];
}
template <typename T>
inline const T& Vector3<T>::GetY() const
{
return m_data[1];
}
template <typename T>
inline const T& Vector3<T>::GetZ() const
{
return m_data[2];
}
/*
* Normalize and norming
*/
template <typename T>
inline T Vector3<T>::Normalize()
{
T n = GetNorm();
if (n != T(0.0)) (*this) /= n;
return n;
}
template <typename T>
inline Vector3<T> Vector3<T>::Normalized()
{
Vector3<T> ret = *this;
T n = GetNorm();
if (n != T(0.0)) ret /= n;
return ret;
}
template <typename T>
inline T Vector3<T>::GetNorm() const
{
return std::sqrt(GetNormSquared());
}
template <typename T>
inline T Vector3<T>::GetNormSquared() const
{
return this->Dot(*this);
}
template <typename T>
inline int Vector3<T>::LongestAxis() const
{
auto it = std::max_element(m_data.begin(), m_data.end());
return int(std::distance(m_data.begin(), it));
}
/*
* Vector-vector operations
*/
template <typename T>
inline Vector3<T>& Vector3<T>::operator=(const Vector3<T>& rhs)
{
GetX() = rhs.GetX();
GetY() = rhs.GetY();
GetZ() = rhs.GetZ();
return *this;
}
template <typename T>
inline Vector3<T>& Vector3<T>::operator+=(const Vector3<T>& rhs)
{
GetX() += rhs.GetX();
GetY() += rhs.GetY();
GetZ() += rhs.GetZ();
return *this;
}
template <typename T>
inline Vector3<T>& Vector3<T>::operator-=(const Vector3<T>& rhs)
{
GetX() -= rhs.GetX();
GetY() -= rhs.GetY();
GetZ() -= rhs.GetZ();
return *this;
}
template <typename T>
inline Vector3<T> Vector3<T>::CWiseMul(const Vector3<T>& rhs) const
{
return Vector3<T>(GetX() * rhs.GetX(),
GetY() * rhs.GetY(),
GetZ() * rhs.GetZ());
}
template <typename T>
inline Vector3<T> Vector3<T>::Cross(const Vector3<T>& rhs) const
{
return Vector3<T>(GetY() * rhs.GetZ() - GetZ() * rhs.GetY(),
GetZ() * rhs.GetX() - GetX() * rhs.GetZ(),
GetX() * rhs.GetY() - GetY() * rhs.GetX());
}
template <typename T>
inline T Vector3<T>::Dot(const Vector3<T>& rhs) const
{
return GetX() * rhs.GetX()
+ GetY() * rhs.GetY()
+ GetZ() * rhs.GetZ();
}
template <typename T>
inline Vector3<T> Vector3<T>::operator+(const Vector3<T>& rhs) const
{
return Vector3<T>(GetX() + rhs.GetX(),
GetY() + rhs.GetY(),
GetZ() + rhs.GetZ());
}
template <typename T>
inline Vector3<T> Vector3<T>::operator-(const Vector3<T>& rhs) const
{
return Vector3<T>(GetX() - rhs.GetX(),
GetY() - rhs.GetY(),
GetZ() - rhs.GetZ());
}
template <typename T>
inline Vector3<T> operator*(T lhs, const Vector3<T>& rhs)
{
return Vector3<T>(lhs * rhs.GetX(),
lhs * rhs.GetY(),
lhs * rhs.GetZ());
}
/*
* Vector-scalar operations
*/
template <typename T>
inline Vector3<T>& Vector3<T>::operator-=(T a)
{
GetX() -= a;
GetY() -= a;
GetZ() -= a;
return *this;
}
template <typename T>
inline Vector3<T>& Vector3<T>::operator+=(T a)
{
GetX() += a;
GetY() += a;
GetZ() += a;
return *this;
}
template <typename T>
inline Vector3<T>& Vector3<T>::operator/=(T a)
{
GetX() /= a;
GetY() /= a;
GetZ() /= a;
return *this;
}
template <typename T>
inline Vector3<T>& Vector3<T>::operator*=(T a)
{
GetX() *= a;
GetY() *= a;
GetZ() *= a;
return *this;
}
template <typename T>
inline Vector3<T> Vector3<T>::operator*(T rhs) const
{
return Vector3<T>(GetX() * rhs,
GetY() * rhs,
GetZ() * rhs);
}
template <typename T>
inline Vector3<T> Vector3<T>::operator/(T rhs) const
{
return Vector3<T>(GetX() / rhs,
GetY() / rhs,
GetZ() / rhs);
}
/*
* Unary operations
*/
template <typename T>
inline Vector3<T> Vector3<T>::operator-() const
{
return Vector3<T>(-GetX(),
-GetY(),
-GetZ());
}
/*
* Comparison operators
*/
template <typename T>
inline bool Vector3<T>::operator<(const Vector3<T>& rhs) const
{
if (GetX() == rhs.GetX())
{
if (GetY() == rhs.GetY())
{
return (GetZ() < rhs.GetZ());
}
return (GetY() < rhs.GetY());
}
return (GetX() < rhs.GetX());
}
template <typename T>
inline bool Vector3<T>::operator>(const Vector3<T>& rhs) const
{
if (GetX() == rhs.GetX())
{
if (GetY() == rhs.GetY())
{
return (GetZ() > rhs.GetZ());
}
return (GetY() > rhs.GetY());
}
return (GetX() > rhs.GetZ());
}
template <typename T>
inline bool Vector3<T>::CWiseAllGE(const Vector3<T>& rhs) const
{
return GetX() >= rhs.GetX()
&& GetY() >= rhs.GetY()
&& GetZ() >= rhs.GetZ();
}
template <typename T>
inline bool Vector3<T>::CWiseAllLE(const Vector3<T>& rhs) const
{
return GetX() <= rhs.GetX()
&& GetY() <= rhs.GetY()
&& GetZ() <= rhs.GetZ();
}
template <typename T>
inline Vector3<T> Vector3<T>::CWiseMin(const Vector3<T>& rhs) const
{
return Vector3<T>(std::min(GetX(), rhs.GetX()),
std::min(GetY(), rhs.GetY()),
std::min(GetZ(), rhs.GetZ()));
}
template <typename T>
inline Vector3<T> Vector3<T>::CWiseMax(const Vector3<T>& rhs) const
{
return Vector3<T>(std::max(GetX(), rhs.GetX()),
std::max(GetY(), rhs.GetY()),
std::max(GetZ(), rhs.GetZ()));
}
template <typename T>
inline T Vector3<T>::MinCoeff() const
{
return *std::min_element(m_data.begin(), m_data.end());
}
template <typename T>
inline T Vector3<T>::MaxCoeff() const
{
return *std::max_element(m_data.begin(), m_data.end());
}
template <typename T>
inline T Vector3<T>::MinCoeff(uint32_t& idx) const
{
auto it = std::min_element(m_data.begin(), m_data.end());
idx = uint32_t(std::distance(m_data.begin(), it));
return *it;
}
template <typename T>
inline T Vector3<T>::MaxCoeff(uint32_t& idx) const
{
auto it = std::max_element(m_data.begin(), m_data.end());
idx = uint32_t(std::distance(m_data.begin(), it));
return *it;
}
/*
* Constructors
*/
template <typename T>
inline Vector3<T>::Vector3(T a)
: m_data{a, a, a}
{
}
template <typename T>
inline Vector3<T>::Vector3(T x, T y, T z)
: m_data{x, y, z}
{
}
template <typename T>
inline Vector3<T>::Vector3(const Vector3& rhs)
: m_data{rhs.m_data}
{
}
template <typename T>
template <typename U>
inline Vector3<T>::Vector3(const Vector3<U>& rhs)
: m_data{T(rhs.GetX()), T(rhs.GetY()), T(rhs.GetZ())}
{
}
template <typename T>
inline Vector3<T>::Vector3(const VHACD::Vertex& rhs)
: Vector3<T>(rhs.mX, rhs.mY, rhs.mZ)
{
static_assert(std::is_same<T, double>::value, "Vertex to Vector3 constructor only enabled for double");
}
template <typename T>
inline Vector3<T>::Vector3(const VHACD::Triangle& rhs)
: Vector3<T>(rhs.mI0, rhs.mI1, rhs.mI2)
{
static_assert(std::is_same<T, uint32_t>::value, "Triangle to Vector3 constructor only enabled for uint32_t");
}
template <typename T>
inline Vector3<T>::operator VHACD::Vertex() const
{
static_assert(std::is_same<T, double>::value, "Vector3 to Vertex conversion only enable for double");
return ::VHACD::Vertex( GetX(), GetY(), GetZ());
}
IVHACD* CreateVHACD(); // Create a synchronous (blocking) implementation of V-HACD
IVHACD* CreateVHACD_ASYNC(); // Create an asynchronous (non-blocking) implementation of V-HACD
} // namespace VHACD
#if ENABLE_VHACD_IMPLEMENTATION
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include <limits.h>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <future>
#include <iostream>
#include <list>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4100 4127 4189 4244 4456 4701 4702 4996)
#endif // _MSC_VER
#ifdef __GNUC__
#pragma GCC diagnostic push
// Minimum set of warnings used for cleanup
// #pragma GCC diagnostic warning "-Wall"
// #pragma GCC diagnostic warning "-Wextra"
// #pragma GCC diagnostic warning "-Wpedantic"
// #pragma GCC diagnostic warning "-Wold-style-cast"
// #pragma GCC diagnostic warning "-Wnon-virtual-dtor"
// #pragma GCC diagnostic warning "-Wshadow"
#endif // __GNUC__
// Scoped Timer
namespace VHACD {
class Timer
{
public:
Timer()
: m_startTime(std::chrono::high_resolution_clock::now())
{
}
void Reset()
{
m_startTime = std::chrono::high_resolution_clock::now();
}
double GetElapsedSeconds()
{
auto s = PeekElapsedSeconds();
Reset();
return s;
}
double PeekElapsedSeconds()
{
auto now = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = now - m_startTime;
return diff.count();
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> m_startTime;
};
class ScopedTime
{
public:
ScopedTime(const char* action,
VHACD::IVHACD::IUserLogger* logger)
: m_action(action)
, m_logger(logger)
{
m_timer.Reset();
}
~ScopedTime()
{
double dtime = m_timer.GetElapsedSeconds();
if( m_logger )
{
char scratch[512];
snprintf(scratch,
sizeof(scratch),"%s took %0.5f seconds",
m_action,
dtime);
m_logger->Log(scratch);
}
}
const char* m_action{ nullptr };
Timer m_timer;
VHACD::IVHACD::IUserLogger* m_logger{ nullptr };
};
BoundsAABB::BoundsAABB(const std::vector<VHACD::Vertex>& points)
: m_min(points[0])
, m_max(points[0])
{
for (uint32_t i = 1; i < points.size(); ++i)
{
const VHACD::Vertex& p = points[i];