This commit is contained in:
YunfeiBai
2016-09-28 13:54:18 -07:00
70 changed files with 28977 additions and 749 deletions

View File

@@ -0,0 +1,104 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_ALIGNED_ALLOCATOR
#define BT_ALIGNED_ALLOCATOR
///we probably replace this with our own aligned memory allocator
///so we replace _aligned_malloc and _aligned_free with our own
///that is better portable and more predictable
#include "btScalar.h"
//#define BT_DEBUG_MEMORY_ALLOCATIONS 1
#ifdef BT_DEBUG_MEMORY_ALLOCATIONS
#define btAlignedAlloc(a, b) \
btAlignedAllocInternal(a, b, __LINE__, __FILE__)
#define btAlignedFree(ptr) \
btAlignedFreeInternal(ptr, __LINE__, __FILE__)
void* btAlignedAllocInternal(size_t size, int alignment, int line, char* filename);
void btAlignedFreeInternal(void* ptr, int line, char* filename);
#else
void* btAlignedAllocInternal(size_t size, int alignment);
void btAlignedFreeInternal(void* ptr);
#define btAlignedAlloc(size, alignment) btAlignedAllocInternal(size, alignment)
#define btAlignedFree(ptr) btAlignedFreeInternal(ptr)
#endif
typedef int size_type;
typedef void*(btAlignedAllocFunc)(size_t size, int alignment);
typedef void(btAlignedFreeFunc)(void* memblock);
typedef void*(btAllocFunc)(size_t size);
typedef void(btFreeFunc)(void* memblock);
///The developer can let all Bullet memory allocations go through a custom memory allocator, using btAlignedAllocSetCustom
void btAlignedAllocSetCustom(btAllocFunc* allocFunc, btFreeFunc* freeFunc);
///If the developer has already an custom aligned allocator, then btAlignedAllocSetCustomAligned can be used. The default aligned allocator pre-allocates extra memory using the non-aligned allocator, and instruments it.
void btAlignedAllocSetCustomAligned(btAlignedAllocFunc* allocFunc, btAlignedFreeFunc* freeFunc);
///The btAlignedAllocator is a portable class for aligned memory allocations.
///Default implementations for unaligned and aligned allocations can be overridden by a custom allocator using btAlignedAllocSetCustom and btAlignedAllocSetCustomAligned.
template <typename T, unsigned Alignment>
class btAlignedAllocator {
typedef btAlignedAllocator<T, Alignment> self_type;
public:
//just going down a list:
btAlignedAllocator() {}
/*
btAlignedAllocator( const self_type & ) {}
*/
template <typename Other>
btAlignedAllocator(const btAlignedAllocator<Other, Alignment>&) {}
typedef const T* const_pointer;
typedef const T& const_reference;
typedef T* pointer;
typedef T& reference;
typedef T value_type;
pointer address(reference ref) const { return &ref; }
const_pointer address(const_reference ref) const { return &ref; }
pointer allocate(size_type n, const_pointer* hint = 0)
{
(void)hint;
return reinterpret_cast<pointer>(btAlignedAlloc(sizeof(value_type) * n, Alignment));
}
void construct(pointer ptr, const value_type& value) { new (ptr) value_type(value); }
void deallocate(pointer ptr)
{
btAlignedFree(reinterpret_cast<void*>(ptr));
}
void destroy(pointer ptr) { ptr->~value_type(); }
template <typename O>
struct rebind {
typedef btAlignedAllocator<O, Alignment> other;
};
template <typename O>
self_type& operator=(const btAlignedAllocator<O, Alignment>&) { return *this; }
friend bool operator==(const self_type&, const self_type&) { return true; }
};
#endif //BT_ALIGNED_ALLOCATOR

View File

@@ -0,0 +1,448 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_OBJECT_ARRAY__
#define BT_OBJECT_ARRAY__
#include "btAlignedAllocator.h"
#include "btScalar.h" // has definitions like SIMD_FORCE_INLINE
///If the platform doesn't support placement new, you can disable BT_USE_PLACEMENT_NEW
///then the btAlignedObjectArray doesn't support objects with virtual methods, and non-trivial constructors/destructors
///You can enable BT_USE_MEMCPY, then swapping elements in the array will use memcpy instead of operator=
///see discussion here: http://continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1231 and
///http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1240
#define BT_USE_PLACEMENT_NEW 1
//#define BT_USE_MEMCPY 1 //disable, because it is cumbersome to find out for each platform where memcpy is defined. It can be in <memory.h> or <string.h> or otherwise...
#define BT_ALLOW_ARRAY_COPY_OPERATOR // enabling this can accidently perform deep copies of data if you are not careful
#ifdef BT_USE_MEMCPY
#include <memory.h>
#include <string.h>
#endif //BT_USE_MEMCPY
#ifdef BT_USE_PLACEMENT_NEW
#include <new> //for placement new
#endif //BT_USE_PLACEMENT_NEW
///The btAlignedObjectArray template class uses a subset of the stl::vector interface for its methods
///It is developed to replace stl::vector to avoid portability issues, including STL alignment issues to add SIMD/SSE data
template <typename T>
//template <class T>
class btAlignedObjectArray {
btAlignedAllocator<T, 16> m_allocator;
int m_size;
int m_capacity;
T* m_data;
//PCK: added this line
bool m_ownsMemory;
#ifdef BT_ALLOW_ARRAY_COPY_OPERATOR
public:
SIMD_FORCE_INLINE btAlignedObjectArray<T>& operator=(const btAlignedObjectArray<T>& other)
{
copyFromArray(other);
return *this;
}
#else //BT_ALLOW_ARRAY_COPY_OPERATOR
private:
SIMD_FORCE_INLINE btAlignedObjectArray<T>& operator=(const btAlignedObjectArray<T>& other);
#endif //BT_ALLOW_ARRAY_COPY_OPERATOR
protected:
SIMD_FORCE_INLINE int allocSize(int size)
{
return (size ? size * 2 : 1);
}
SIMD_FORCE_INLINE void copy(int start, int end, T* dest) const
{
int i;
for (i = start; i < end; ++i)
#ifdef BT_USE_PLACEMENT_NEW
new (&dest[i]) T(m_data[i]);
#else
dest[i] = m_data[i];
#endif //BT_USE_PLACEMENT_NEW
}
SIMD_FORCE_INLINE void init()
{
//PCK: added this line
m_ownsMemory = true;
m_data = 0;
m_size = 0;
m_capacity = 0;
}
SIMD_FORCE_INLINE void destroy(int first, int last)
{
int i;
for (i = first; i < last; i++) {
m_data[i].~T();
}
}
SIMD_FORCE_INLINE void* allocate(int size)
{
if (size)
return m_allocator.allocate(size);
return 0;
}
SIMD_FORCE_INLINE void deallocate()
{
if (m_data) {
//PCK: enclosed the deallocation in this block
if (m_ownsMemory) {
m_allocator.deallocate(m_data);
}
m_data = 0;
}
}
public:
btAlignedObjectArray()
{
init();
}
~btAlignedObjectArray()
{
clear();
}
///Generally it is best to avoid using the copy constructor of an btAlignedObjectArray, and use a (const) reference to the array instead.
btAlignedObjectArray(const btAlignedObjectArray& otherArray)
{
init();
int otherSize = otherArray.size();
resize(otherSize);
otherArray.copy(0, otherSize, m_data);
}
/// return the number of elements in the array
SIMD_FORCE_INLINE int size() const
{
return m_size;
}
SIMD_FORCE_INLINE const T& at(int n) const
{
btAssert(n >= 0);
btAssert(n < size());
return m_data[n];
}
SIMD_FORCE_INLINE T& at(int n)
{
btAssert(n >= 0);
btAssert(n < size());
return m_data[n];
}
SIMD_FORCE_INLINE const T& operator[](int n) const
{
btAssert(n >= 0);
btAssert(n < size());
return m_data[n];
}
SIMD_FORCE_INLINE T& operator[](int n)
{
btAssert(n >= 0);
btAssert(n < size());
return m_data[n];
}
///clear the array, deallocated memory. Generally it is better to use array.resize(0), to reduce performance overhead of run-time memory (de)allocations.
SIMD_FORCE_INLINE void clear()
{
destroy(0, size());
deallocate();
init();
}
SIMD_FORCE_INLINE void pop_back()
{
btAssert(m_size > 0);
m_size--;
m_data[m_size].~T();
}
///resize changes the number of elements in the array. If the new size is larger, the new elements will be constructed using the optional second argument.
///when the new number of elements is smaller, the destructor will be called, but memory will not be freed, to reduce performance overhead of run-time memory (de)allocations.
SIMD_FORCE_INLINE void resize(int newsize, const T& fillData = T())
{
int curSize = size();
if (newsize < curSize) {
for (int i = newsize; i < curSize; i++) {
m_data[i].~T();
}
}
else {
if (newsize > size()) {
reserve(newsize);
}
#ifdef BT_USE_PLACEMENT_NEW
for (int i = curSize; i < newsize; i++) {
new (&m_data[i]) T(fillData);
}
#endif //BT_USE_PLACEMENT_NEW
}
m_size = newsize;
}
SIMD_FORCE_INLINE T& expandNonInitializing()
{
int sz = size();
if (sz == capacity()) {
reserve(allocSize(size()));
}
m_size++;
return m_data[sz];
}
SIMD_FORCE_INLINE T& expand(const T& fillValue = T())
{
int sz = size();
if (sz == capacity()) {
reserve(allocSize(size()));
}
m_size++;
#ifdef BT_USE_PLACEMENT_NEW
new (&m_data[sz]) T(fillValue); //use the in-place new (not really allocating heap memory)
#endif
return m_data[sz];
}
SIMD_FORCE_INLINE void push_back(const T& _Val)
{
int sz = size();
if (sz == capacity()) {
reserve(allocSize(size()));
}
#ifdef BT_USE_PLACEMENT_NEW
new (&m_data[m_size]) T(_Val);
#else
m_data[size()] = _Val;
#endif //BT_USE_PLACEMENT_NEW
m_size++;
}
/// return the pre-allocated (reserved) elements, this is at least as large as the total number of elements,see size() and reserve()
SIMD_FORCE_INLINE int capacity() const
{
return m_capacity;
}
SIMD_FORCE_INLINE void reserve(int _Count)
{ // determine new minimum length of allocated storage
if (capacity() < _Count) { // not enough room, reallocate
T* s = (T*)allocate(_Count);
copy(0, size(), s);
destroy(0, size());
deallocate();
//PCK: added this line
m_ownsMemory = true;
m_data = s;
m_capacity = _Count;
}
}
class less {
public:
bool operator()(const T& a, const T& b)
{
return (a < b);
}
};
template <typename L>
void quickSortInternal(const L& CompareFunc, int lo, int hi)
{
// lo is the lower index, hi is the upper index
// of the region of array a that is to be sorted
int i = lo, j = hi;
T x = m_data[(lo + hi) / 2];
// partition
do {
while (CompareFunc(m_data[i], x))
i++;
while (CompareFunc(x, m_data[j]))
j--;
if (i <= j) {
swap(i, j);
i++;
j--;
}
} while (i <= j);
// recursion
if (lo < j)
quickSortInternal(CompareFunc, lo, j);
if (i < hi)
quickSortInternal(CompareFunc, i, hi);
}
template <typename L>
void quickSort(const L& CompareFunc)
{
//don't sort 0 or 1 elements
if (size() > 1) {
quickSortInternal(CompareFunc, 0, size() - 1);
}
}
///heap sort from http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Heap/
template <typename L>
void downHeap(T* pArr, int k, int n, const L& CompareFunc)
{
/* PRE: a[k+1..N] is a heap */
/* POST: a[k..N] is a heap */
T temp = pArr[k - 1];
/* k has child(s) */
while (k <= n / 2) {
int child = 2 * k;
if ((child < n) && CompareFunc(pArr[child - 1], pArr[child])) {
child++;
}
/* pick larger child */
if (CompareFunc(temp, pArr[child - 1])) {
/* move child up */
pArr[k - 1] = pArr[child - 1];
k = child;
}
else {
break;
}
}
pArr[k - 1] = temp;
} /*downHeap*/
void swap(int index0, int index1)
{
#ifdef BT_USE_MEMCPY
char temp[sizeof(T)];
memcpy(temp, &m_data[index0], sizeof(T));
memcpy(&m_data[index0], &m_data[index1], sizeof(T));
memcpy(&m_data[index1], temp, sizeof(T));
#else
T temp = m_data[index0];
m_data[index0] = m_data[index1];
m_data[index1] = temp;
#endif //BT_USE_PLACEMENT_NEW
}
template <typename L>
void heapSort(const L& CompareFunc)
{
/* sort a[0..N-1], N.B. 0 to N-1 */
int k;
int n = m_size;
for (k = n / 2; k > 0; k--) {
downHeap(m_data, k, n, CompareFunc);
}
/* a[1..N] is now a heap */
while (n >= 1) {
swap(0, n - 1); /* largest of a[0..n-1] */
n = n - 1;
/* restore a[1..i-1] heap */
downHeap(m_data, 1, n, CompareFunc);
}
}
///non-recursive binary search, assumes sorted array
int findBinarySearch(const T& key) const
{
int first = 0;
int last = size() - 1;
//assume sorted array
while (first <= last) {
int mid = (first + last) / 2; // compute mid point.
if (key > m_data[mid])
first = mid + 1; // repeat search in top half.
else if (key < m_data[mid])
last = mid - 1; // repeat search in bottom half.
else
return mid; // found it. return position /////
}
return size(); // failed to find key
}
int findLinearSearch(const T& key) const
{
int index = size();
int i;
for (i = 0; i < size(); i++) {
if (m_data[i] == key) {
index = i;
break;
}
}
return index;
}
void remove(const T& key)
{
int findIndex = findLinearSearch(key);
if (findIndex < size()) {
swap(findIndex, size() - 1);
pop_back();
}
}
//PCK: whole function
void initializeFromBuffer(void* buffer, int size, int capacity)
{
clear();
m_ownsMemory = false;
m_data = (T*)buffer;
m_size = size;
m_capacity = capacity;
}
void copyFromArray(const btAlignedObjectArray& otherArray)
{
int otherSize = otherArray.size();
resize(otherSize);
otherArray.copy(0, otherSize, m_data);
}
};
#endif //BT_OBJECT_ARRAY__

View File

@@ -0,0 +1,97 @@
/*
Copyright (c) 2011 Ole Kniemeyer, MAXON, www.maxon.net
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CONVEX_HULL_COMPUTER_H
#define BT_CONVEX_HULL_COMPUTER_H
#include "btAlignedObjectArray.h"
#include "btVector3.h"
/// Convex hull implementation based on Preparata and Hong
/// See http://code.google.com/p/bullet/issues/detail?id=275
/// Ole Kniemeyer, MAXON Computer GmbH
class btConvexHullComputer {
private:
btScalar compute(const void* coords, bool doubleCoords, int stride, int count, btScalar shrink, btScalar shrinkClamp);
public:
class Edge {
private:
int next;
int reverse;
int targetVertex;
friend class btConvexHullComputer;
public:
int getSourceVertex() const
{
return (this + reverse)->targetVertex;
}
int getTargetVertex() const
{
return targetVertex;
}
const Edge* getNextEdgeOfVertex() const // clockwise list of all edges of a vertex
{
return this + next;
}
const Edge* getNextEdgeOfFace() const // counter-clockwise list of all edges of a face
{
return (this + reverse)->getNextEdgeOfVertex();
}
const Edge* getReverseEdge() const
{
return this + reverse;
}
};
// Vertices of the output hull
btAlignedObjectArray<btVector3> vertices;
// Edges of the output hull
btAlignedObjectArray<Edge> edges;
// Faces of the convex hull. Each entry is an index into the "edges" array pointing to an edge of the face. Faces are planar n-gons
btAlignedObjectArray<int> faces;
/*
Compute convex hull of "count" vertices stored in "coords". "stride" is the difference in bytes
between the addresses of consecutive vertices. If "shrink" is positive, the convex hull is shrunken
by that amount (each face is moved by "shrink" length units towards the center along its normal).
If "shrinkClamp" is positive, "shrink" is clamped to not exceed "shrinkClamp * innerRadius", where "innerRadius"
is the minimum distance of a face to the center of the convex hull.
The returned value is the amount by which the hull has been shrunken. If it is negative, the amount was so large
that the resulting convex hull is empty.
The output convex hull can be found in the member variables "vertices", "edges", "faces".
*/
btScalar compute(const float* coords, int stride, int count, btScalar shrink, btScalar shrinkClamp)
{
return compute(coords, false, stride, count, shrink, shrinkClamp);
}
// same as above, but double precision
btScalar compute(const double* coords, int stride, int count, btScalar shrink, btScalar shrinkClamp)
{
return compute(coords, true, stride, count, shrink, shrinkClamp);
}
};
#endif //BT_CONVEX_HULL_COMPUTER_H

View File

@@ -0,0 +1,65 @@
/*
Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_GEN_MINMAX_H
#define BT_GEN_MINMAX_H
#include "btScalar.h"
template <class T>
SIMD_FORCE_INLINE const T& btMin(const T& a, const T& b)
{
return a < b ? a : b;
}
template <class T>
SIMD_FORCE_INLINE const T& btMax(const T& a, const T& b)
{
return a > b ? a : b;
}
template <class T>
SIMD_FORCE_INLINE const T& btClamped(const T& a, const T& lb, const T& ub)
{
return a < lb ? lb : (ub < a ? ub : a);
}
template <class T>
SIMD_FORCE_INLINE void btSetMin(T& a, const T& b)
{
if (b < a) {
a = b;
}
}
template <class T>
SIMD_FORCE_INLINE void btSetMax(T& a, const T& b)
{
if (a < b) {
a = b;
}
}
template <class T>
SIMD_FORCE_INLINE void btClamp(T& a, const T& lb, const T& ub)
{
if (a < lb) {
a = lb;
}
else if (ub < a) {
a = ub;
}
}
#endif //BT_GEN_MINMAX_H

532
Extras/VHACD/inc/btScalar.h Normal file
View File

@@ -0,0 +1,532 @@
/*
Copyright (c) 2003-2009 Erwin Coumans http://bullet.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SCALAR_H
#define BT_SCALAR_H
#ifdef BT_MANAGED_CODE
//Aligned data types not supported in managed code
#pragma unmanaged
#endif
#include <float.h>
#include <math.h>
#include <stdlib.h> //size_t for MSVC 6.0
/* SVN $Revision$ on $Date$ from http://bullet.googlecode.com*/
#define BT_BULLET_VERSION 279
inline int btGetVersion()
{
return BT_BULLET_VERSION;
}
#if defined(DEBUG) || defined(_DEBUG)
#define BT_DEBUG
#endif
#ifdef _WIN32
#if defined(__MINGW32__) || defined(__CYGWIN__) || (defined(_MSC_VER) && _MSC_VER < 1300)
#define SIMD_FORCE_INLINE inline
#define ATTRIBUTE_ALIGNED16(a) a
#define ATTRIBUTE_ALIGNED64(a) a
#define ATTRIBUTE_ALIGNED128(a) a
#else
//#define BT_HAS_ALIGNED_ALLOCATOR
#pragma warning(disable : 4324) // disable padding warning
// #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning.
// #pragma warning(disable:4996) //Turn off warnings about deprecated C routines
// #pragma warning(disable:4786) // Disable the "debug name too long" warning
#define SIMD_FORCE_INLINE __forceinline
#define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a
#define ATTRIBUTE_ALIGNED64(a) __declspec(align(64)) a
#define ATTRIBUTE_ALIGNED128(a) __declspec(align(128)) a
#ifdef _XBOX
#define BT_USE_VMX128
#include <ppcintrinsics.h>
#define BT_HAVE_NATIVE_FSEL
#define btFsel(a, b, c) __fsel((a), (b), (c))
#else
#if (defined(_WIN32) && (_MSC_VER) && _MSC_VER >= 1400) && (!defined(BT_USE_DOUBLE_PRECISION))
#define BT_USE_SSE
#include <emmintrin.h>
#endif
#endif //_XBOX
#endif //__MINGW32__
#include <assert.h>
#ifdef BT_DEBUG
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#if defined(__CELLOS_LV2__)
#define SIMD_FORCE_INLINE inline __attribute__((always_inline))
#define ATTRIBUTE_ALIGNED16(a) a __attribute__((aligned(16)))
#define ATTRIBUTE_ALIGNED64(a) a __attribute__((aligned(64)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__((aligned(128)))
#ifndef assert
#include <assert.h>
#endif
#ifdef BT_DEBUG
#ifdef __SPU__
#include <spu_printf.h>
#define printf spu_printf
#define btAssert(x) \
{ \
if (!(x)) { \
printf("Assert " __FILE__ ":%u (" #x ")\n", __LINE__); \
spu_hcmpeq(0, 0); \
} \
}
#else
#define btAssert assert
#endif
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#ifdef USE_LIBSPE2
#define SIMD_FORCE_INLINE __inline
#define ATTRIBUTE_ALIGNED16(a) a __attribute__((aligned(16)))
#define ATTRIBUTE_ALIGNED64(a) a __attribute__((aligned(64)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__((aligned(128)))
#ifndef assert
#include <assert.h>
#endif
#ifdef BT_DEBUG
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) __builtin_expect((_c), 1)
#define btUnlikely(_c) __builtin_expect((_c), 0)
#else
//non-windows systems
#if (defined(__APPLE__) && defined(__i386__) && (!defined(BT_USE_DOUBLE_PRECISION)))
#define BT_USE_SSE
#include <emmintrin.h>
#define SIMD_FORCE_INLINE inline
///@todo: check out alignment methods for other platforms/compilers
#define ATTRIBUTE_ALIGNED16(a) a __attribute__((aligned(16)))
#define ATTRIBUTE_ALIGNED64(a) a __attribute__((aligned(64)))
#define ATTRIBUTE_ALIGNED128(a) a __attribute__((aligned(128)))
#ifndef assert
#include <assert.h>
#endif
#if defined(DEBUG) || defined(_DEBUG)
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#else
#define SIMD_FORCE_INLINE inline
///@todo: check out alignment methods for other platforms/compilers
///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16)))
///#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64)))
///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128)))
#define ATTRIBUTE_ALIGNED16(a) a
#define ATTRIBUTE_ALIGNED64(a) a
#define ATTRIBUTE_ALIGNED128(a) a
#ifndef assert
#include <assert.h>
#endif
#if defined(DEBUG) || defined(_DEBUG)
#define btAssert assert
#else
#define btAssert(x)
#endif
//btFullAssert is optional, slows down a lot
#define btFullAssert(x)
#define btLikely(_c) _c
#define btUnlikely(_c) _c
#endif //__APPLE__
#endif // LIBSPE2
#endif //__CELLOS_LV2__
#endif
///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision.
#if defined(BT_USE_DOUBLE_PRECISION)
typedef double btScalar;
//this number could be bigger in double precision
#define BT_LARGE_FLOAT 1e30
#else
typedef float btScalar;
//keep BT_LARGE_FLOAT*BT_LARGE_FLOAT < FLT_MAX
#define BT_LARGE_FLOAT 1e18f
#endif
#define BT_DECLARE_ALIGNED_ALLOCATOR() \
SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes, 16); } \
SIMD_FORCE_INLINE void operator delete(void* ptr) { btAlignedFree(ptr); } \
SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \
SIMD_FORCE_INLINE void operator delete(void*, void*) {} \
SIMD_FORCE_INLINE void* operator new[](size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes, 16); } \
SIMD_FORCE_INLINE void operator delete[](void* ptr) { btAlignedFree(ptr); } \
SIMD_FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \
SIMD_FORCE_INLINE void operator delete[](void*, void*) {}
#if defined(BT_USE_DOUBLE_PRECISION) || defined(BT_FORCE_DOUBLE_FUNCTIONS)
SIMD_FORCE_INLINE btScalar btSqrt(btScalar x)
{
return sqrt(x);
}
SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabs(x); }
SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cos(x); }
SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sin(x); }
SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tan(x); }
SIMD_FORCE_INLINE btScalar btAcos(btScalar x)
{
if (x < btScalar(-1))
x = btScalar(-1);
if (x > btScalar(1))
x = btScalar(1);
return acos(x);
}
SIMD_FORCE_INLINE btScalar btAsin(btScalar x)
{
if (x < btScalar(-1))
x = btScalar(-1);
if (x > btScalar(1))
x = btScalar(1);
return asin(x);
}
SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atan(x); }
SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2(x, y); }
SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return exp(x); }
SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return log(x); }
SIMD_FORCE_INLINE btScalar btPow(btScalar x, btScalar y) { return pow(x, y); }
SIMD_FORCE_INLINE btScalar btFmod(btScalar x, btScalar y) { return fmod(x, y); }
#else
SIMD_FORCE_INLINE btScalar btSqrt(btScalar y)
{
#ifdef USE_APPROXIMATION
double x, z, tempf;
unsigned long* tfptr = ((unsigned long*)&tempf) + 1;
tempf = y;
*tfptr = (0xbfcdd90a - *tfptr) >> 1; /* estimate of 1/sqrt(y) */
x = tempf;
z = y * btScalar(0.5);
x = (btScalar(1.5) * x) - (x * x) * (x * z); /* iteration formula */
x = (btScalar(1.5) * x) - (x * x) * (x * z);
x = (btScalar(1.5) * x) - (x * x) * (x * z);
x = (btScalar(1.5) * x) - (x * x) * (x * z);
x = (btScalar(1.5) * x) - (x * x) * (x * z);
return x * y;
#else
return sqrtf(y);
#endif
}
SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabsf(x); }
SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cosf(x); }
SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sinf(x); }
SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); }
SIMD_FORCE_INLINE btScalar btAcos(btScalar x)
{
if (x < btScalar(-1))
x = btScalar(-1);
if (x > btScalar(1))
x = btScalar(1);
return acosf(x);
}
SIMD_FORCE_INLINE btScalar btAsin(btScalar x)
{
if (x < btScalar(-1))
x = btScalar(-1);
if (x > btScalar(1))
x = btScalar(1);
return asinf(x);
}
SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); }
SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); }
SIMD_FORCE_INLINE btScalar btExp(btScalar x) { return expf(x); }
SIMD_FORCE_INLINE btScalar btLog(btScalar x) { return logf(x); }
SIMD_FORCE_INLINE btScalar btPow(btScalar x, btScalar y) { return powf(x, y); }
SIMD_FORCE_INLINE btScalar btFmod(btScalar x, btScalar y) { return fmodf(x, y); }
#endif
#define SIMD_2_PI btScalar(6.283185307179586232)
#define SIMD_PI (SIMD_2_PI * btScalar(0.5))
#define SIMD_HALF_PI (SIMD_2_PI * btScalar(0.25))
#define SIMD_RADS_PER_DEG (SIMD_2_PI / btScalar(360.0))
#define SIMD_DEGS_PER_RAD (btScalar(360.0) / SIMD_2_PI)
#define SIMDSQRT12 btScalar(0.7071067811865475244008443621048490)
#define btRecipSqrt(x) ((btScalar)(btScalar(1.0) / btSqrt(btScalar(x)))) /* reciprocal square root */
#ifdef BT_USE_DOUBLE_PRECISION
#define SIMD_EPSILON DBL_EPSILON
#define SIMD_INFINITY DBL_MAX
#else
#define SIMD_EPSILON FLT_EPSILON
#define SIMD_INFINITY FLT_MAX
#endif
SIMD_FORCE_INLINE btScalar btAtan2Fast(btScalar y, btScalar x)
{
btScalar coeff_1 = SIMD_PI / 4.0f;
btScalar coeff_2 = 3.0f * coeff_1;
btScalar abs_y = btFabs(y);
btScalar angle;
if (x >= 0.0f) {
btScalar r = (x - abs_y) / (x + abs_y);
angle = coeff_1 - coeff_1 * r;
}
else {
btScalar r = (x + abs_y) / (abs_y - x);
angle = coeff_2 - coeff_1 * r;
}
return (y < 0.0f) ? -angle : angle;
}
SIMD_FORCE_INLINE bool btFuzzyZero(btScalar x) { return btFabs(x) < SIMD_EPSILON; }
SIMD_FORCE_INLINE bool btEqual(btScalar a, btScalar eps)
{
return (((a) <= eps) && !((a) < -eps));
}
SIMD_FORCE_INLINE bool btGreaterEqual(btScalar a, btScalar eps)
{
return (!((a) <= eps));
}
SIMD_FORCE_INLINE int btIsNegative(btScalar x)
{
return x < btScalar(0.0) ? 1 : 0;
}
SIMD_FORCE_INLINE btScalar btRadians(btScalar x) { return x * SIMD_RADS_PER_DEG; }
SIMD_FORCE_INLINE btScalar btDegrees(btScalar x) { return x * SIMD_DEGS_PER_RAD; }
#define BT_DECLARE_HANDLE(name) \
typedef struct name##__ { \
int unused; \
} * name
#ifndef btFsel
SIMD_FORCE_INLINE btScalar btFsel(btScalar a, btScalar b, btScalar c)
{
return a >= 0 ? b : c;
}
#endif
#define btFsels(a, b, c) (btScalar) btFsel(a, b, c)
SIMD_FORCE_INLINE bool btMachineIsLittleEndian()
{
long int i = 1;
const char* p = (const char*)&i;
if (p[0] == 1) // Lowest address contains the least significant byte
return true;
else
return false;
}
///btSelect avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360
///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html
SIMD_FORCE_INLINE unsigned btSelect(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero)
{
// Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero
// Rely on positive value or'ed with its negative having sign bit on
// and zero value or'ed with its negative (which is still zero) having sign bit off
// Use arithmetic shift right, shifting the sign bit through all 32 bits
unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31);
unsigned testEqz = ~testNz;
return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
}
SIMD_FORCE_INLINE int btSelect(unsigned condition, int valueIfConditionNonZero, int valueIfConditionZero)
{
unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31);
unsigned testEqz = ~testNz;
return static_cast<int>((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz));
}
SIMD_FORCE_INLINE float btSelect(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero)
{
#ifdef BT_HAVE_NATIVE_FSEL
return (float)btFsel((btScalar)condition - btScalar(1.0f), valueIfConditionNonZero, valueIfConditionZero);
#else
return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero;
#endif
}
template <typename T>
SIMD_FORCE_INLINE void btSwap(T& a, T& b)
{
T tmp = a;
a = b;
b = tmp;
}
//PCK: endian swapping functions
SIMD_FORCE_INLINE unsigned btSwapEndian(unsigned val)
{
return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24));
}
SIMD_FORCE_INLINE unsigned short btSwapEndian(unsigned short val)
{
return static_cast<unsigned short>(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8));
}
SIMD_FORCE_INLINE unsigned btSwapEndian(int val)
{
return btSwapEndian((unsigned)val);
}
SIMD_FORCE_INLINE unsigned short btSwapEndian(short val)
{
return btSwapEndian((unsigned short)val);
}
///btSwapFloat uses using char pointers to swap the endianness
////btSwapFloat/btSwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values
///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754.
///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception.
///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you.
///so instead of returning a float/double, we return integer/long long integer
SIMD_FORCE_INLINE unsigned int btSwapEndianFloat(float d)
{
unsigned int a = 0;
unsigned char* dst = (unsigned char*)&a;
unsigned char* src = (unsigned char*)&d;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
return a;
}
// unswap using char pointers
SIMD_FORCE_INLINE float btUnswapEndianFloat(unsigned int a)
{
float d = 0.0f;
unsigned char* src = (unsigned char*)&a;
unsigned char* dst = (unsigned char*)&d;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
return d;
}
// swap using char pointers
SIMD_FORCE_INLINE void btSwapEndianDouble(double d, unsigned char* dst)
{
unsigned char* src = (unsigned char*)&d;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
}
// unswap using char pointers
SIMD_FORCE_INLINE double btUnswapEndianDouble(const unsigned char* src)
{
double d = 0.0;
unsigned char* dst = (unsigned char*)&d;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
return d;
}
// returns normalized value in range [-SIMD_PI, SIMD_PI]
SIMD_FORCE_INLINE btScalar btNormalizeAngle(btScalar angleInRadians)
{
angleInRadians = btFmod(angleInRadians, SIMD_2_PI);
if (angleInRadians < -SIMD_PI) {
return angleInRadians + SIMD_2_PI;
}
else if (angleInRadians > SIMD_PI) {
return angleInRadians - SIMD_2_PI;
}
else {
return angleInRadians;
}
}
///rudimentary class to provide type info
struct btTypedObject {
btTypedObject(int objectType)
: m_objectType(objectType)
{
}
int m_objectType;
inline int getObjectType() const
{
return m_objectType;
}
};
#endif //BT_SCALAR_H

View File

@@ -0,0 +1,715 @@
/*
Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_VECTOR3_H
#define BT_VECTOR3_H
#include "btMinMax.h"
#include "btScalar.h"
#ifdef BT_USE_DOUBLE_PRECISION
#define btVector3Data btVector3DoubleData
#define btVector3DataName "btVector3DoubleData"
#else
#define btVector3Data btVector3FloatData
#define btVector3DataName "btVector3FloatData"
#endif //BT_USE_DOUBLE_PRECISION
/**@brief btVector3 can be used to represent 3D points and vectors.
* It has an un-used w component to suit 16-byte alignment when btVector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user
* Ideally, this class should be replaced by a platform optimized SIMD version that keeps the data in registers
*/
ATTRIBUTE_ALIGNED16(class)
btVector3
{
public:
#if defined(__SPU__) && defined(__CELLOS_LV2__)
btScalar m_floats[4];
public:
SIMD_FORCE_INLINE const vec_float4& get128() const
{
return *((const vec_float4*)&m_floats[0]);
}
public:
#else //__CELLOS_LV2__ __SPU__
#ifdef BT_USE_SSE // _WIN32
union {
__m128 mVec128;
btScalar m_floats[4];
};
SIMD_FORCE_INLINE __m128 get128() const
{
return mVec128;
}
SIMD_FORCE_INLINE void set128(__m128 v128)
{
mVec128 = v128;
}
#else
btScalar m_floats[4];
#endif
#endif //__CELLOS_LV2__ __SPU__
public:
/**@brief No initialization constructor */
SIMD_FORCE_INLINE btVector3() {}
/**@brief Constructor from scalars
* @param x X value
* @param y Y value
* @param z Z value
*/
SIMD_FORCE_INLINE btVector3(const btScalar& x, const btScalar& y, const btScalar& z)
{
m_floats[0] = x;
m_floats[1] = y;
m_floats[2] = z;
m_floats[3] = btScalar(0.);
}
/**@brief Add a vector to this one
* @param The vector to add to this one */
SIMD_FORCE_INLINE btVector3& operator+=(const btVector3& v)
{
m_floats[0] += v.m_floats[0];
m_floats[1] += v.m_floats[1];
m_floats[2] += v.m_floats[2];
return *this;
}
/**@brief Subtract a vector from this one
* @param The vector to subtract */
SIMD_FORCE_INLINE btVector3& operator-=(const btVector3& v)
{
m_floats[0] -= v.m_floats[0];
m_floats[1] -= v.m_floats[1];
m_floats[2] -= v.m_floats[2];
return *this;
}
/**@brief Scale the vector
* @param s Scale factor */
SIMD_FORCE_INLINE btVector3& operator*=(const btScalar& s)
{
m_floats[0] *= s;
m_floats[1] *= s;
m_floats[2] *= s;
return *this;
}
/**@brief Inversely scale the vector
* @param s Scale factor to divide by */
SIMD_FORCE_INLINE btVector3& operator/=(const btScalar& s)
{
btFullAssert(s != btScalar(0.0));
return * this *= btScalar(1.0) / s;
}
/**@brief Return the dot product
* @param v The other vector in the dot product */
SIMD_FORCE_INLINE btScalar dot(const btVector3& v) const
{
return m_floats[0] * v.m_floats[0] + m_floats[1] * v.m_floats[1] + m_floats[2] * v.m_floats[2];
}
/**@brief Return the length of the vector squared */
SIMD_FORCE_INLINE btScalar length2() const
{
return dot(*this);
}
/**@brief Return the length of the vector */
SIMD_FORCE_INLINE btScalar length() const
{
return btSqrt(length2());
}
/**@brief Return the distance squared between the ends of this and another vector
* This is symantically treating the vector like a point */
SIMD_FORCE_INLINE btScalar distance2(const btVector3& v) const;
/**@brief Return the distance between the ends of this and another vector
* This is symantically treating the vector like a point */
SIMD_FORCE_INLINE btScalar distance(const btVector3& v) const;
SIMD_FORCE_INLINE btVector3& safeNormalize()
{
btVector3 absVec = this->absolute();
int maxIndex = absVec.maxAxis();
if (absVec[maxIndex] > 0) {
*this /= absVec[maxIndex];
return * this /= length();
}
setValue(1, 0, 0);
return *this;
}
/**@brief Normalize this vector
* x^2 + y^2 + z^2 = 1 */
SIMD_FORCE_INLINE btVector3& normalize()
{
return * this /= length();
}
/**@brief Return a normalized version of this vector */
SIMD_FORCE_INLINE btVector3 normalized() const;
/**@brief Return a rotated version of this vector
* @param wAxis The axis to rotate about
* @param angle The angle to rotate by */
SIMD_FORCE_INLINE btVector3 rotate(const btVector3& wAxis, const btScalar angle) const;
/**@brief Return the angle between this and another vector
* @param v The other vector */
SIMD_FORCE_INLINE btScalar angle(const btVector3& v) const
{
btScalar s = btSqrt(length2() * v.length2());
btFullAssert(s != btScalar(0.0));
return btAcos(dot(v) / s);
}
/**@brief Return a vector will the absolute values of each element */
SIMD_FORCE_INLINE btVector3 absolute() const
{
return btVector3(
btFabs(m_floats[0]),
btFabs(m_floats[1]),
btFabs(m_floats[2]));
}
/**@brief Return the cross product between this and another vector
* @param v The other vector */
SIMD_FORCE_INLINE btVector3 cross(const btVector3& v) const
{
return btVector3(
m_floats[1] * v.m_floats[2] - m_floats[2] * v.m_floats[1],
m_floats[2] * v.m_floats[0] - m_floats[0] * v.m_floats[2],
m_floats[0] * v.m_floats[1] - m_floats[1] * v.m_floats[0]);
}
SIMD_FORCE_INLINE btScalar triple(const btVector3& v1, const btVector3& v2) const
{
return m_floats[0] * (v1.m_floats[1] * v2.m_floats[2] - v1.m_floats[2] * v2.m_floats[1]) + m_floats[1] * (v1.m_floats[2] * v2.m_floats[0] - v1.m_floats[0] * v2.m_floats[2]) + m_floats[2] * (v1.m_floats[0] * v2.m_floats[1] - v1.m_floats[1] * v2.m_floats[0]);
}
/**@brief Return the axis with the smallest value
* Note return values are 0,1,2 for x, y, or z */
SIMD_FORCE_INLINE int minAxis() const
{
return m_floats[0] < m_floats[1] ? (m_floats[0] < m_floats[2] ? 0 : 2) : (m_floats[1] < m_floats[2] ? 1 : 2);
}
/**@brief Return the axis with the largest value
* Note return values are 0,1,2 for x, y, or z */
SIMD_FORCE_INLINE int maxAxis() const
{
return m_floats[0] < m_floats[1] ? (m_floats[1] < m_floats[2] ? 2 : 1) : (m_floats[0] < m_floats[2] ? 2 : 0);
}
SIMD_FORCE_INLINE int furthestAxis() const
{
return absolute().minAxis();
}
SIMD_FORCE_INLINE int closestAxis() const
{
return absolute().maxAxis();
}
SIMD_FORCE_INLINE void setInterpolate3(const btVector3& v0, const btVector3& v1, btScalar rt)
{
btScalar s = btScalar(1.0) - rt;
m_floats[0] = s * v0.m_floats[0] + rt * v1.m_floats[0];
m_floats[1] = s * v0.m_floats[1] + rt * v1.m_floats[1];
m_floats[2] = s * v0.m_floats[2] + rt * v1.m_floats[2];
//don't do the unused w component
// m_co[3] = s * v0[3] + rt * v1[3];
}
/**@brief Return the linear interpolation between this and another vector
* @param v The other vector
* @param t The ration of this to v (t = 0 => return this, t=1 => return other) */
SIMD_FORCE_INLINE btVector3 lerp(const btVector3& v, const btScalar& t) const
{
return btVector3(m_floats[0] + (v.m_floats[0] - m_floats[0]) * t,
m_floats[1] + (v.m_floats[1] - m_floats[1]) * t,
m_floats[2] + (v.m_floats[2] - m_floats[2]) * t);
}
/**@brief Elementwise multiply this vector by the other
* @param v The other vector */
SIMD_FORCE_INLINE btVector3& operator*=(const btVector3& v)
{
m_floats[0] *= v.m_floats[0];
m_floats[1] *= v.m_floats[1];
m_floats[2] *= v.m_floats[2];
return *this;
}
/**@brief Return the x value */
SIMD_FORCE_INLINE const btScalar& getX() const { return m_floats[0]; }
/**@brief Return the y value */
SIMD_FORCE_INLINE const btScalar& getY() const { return m_floats[1]; }
/**@brief Return the z value */
SIMD_FORCE_INLINE const btScalar& getZ() const { return m_floats[2]; }
/**@brief Set the x value */
SIMD_FORCE_INLINE void setX(btScalar x) { m_floats[0] = x; };
/**@brief Set the y value */
SIMD_FORCE_INLINE void setY(btScalar y) { m_floats[1] = y; };
/**@brief Set the z value */
SIMD_FORCE_INLINE void setZ(btScalar z) { m_floats[2] = z; };
/**@brief Set the w value */
SIMD_FORCE_INLINE void setW(btScalar w) { m_floats[3] = w; };
/**@brief Return the x value */
SIMD_FORCE_INLINE const btScalar& x() const { return m_floats[0]; }
/**@brief Return the y value */
SIMD_FORCE_INLINE const btScalar& y() const { return m_floats[1]; }
/**@brief Return the z value */
SIMD_FORCE_INLINE const btScalar& z() const { return m_floats[2]; }
/**@brief Return the w value */
SIMD_FORCE_INLINE const btScalar& w() const { return m_floats[3]; }
//SIMD_FORCE_INLINE btScalar& operator[](int i) { return (&m_floats[0])[i]; }
//SIMD_FORCE_INLINE const btScalar& operator[](int i) const { return (&m_floats[0])[i]; }
///operator btScalar*() replaces operator[], using implicit conversion. We added operator != and operator == to avoid pointer comparisons.
SIMD_FORCE_INLINE operator btScalar*() { return &m_floats[0]; }
SIMD_FORCE_INLINE operator const btScalar*() const { return &m_floats[0]; }
SIMD_FORCE_INLINE bool operator==(const btVector3& other) const
{
return ((m_floats[3] == other.m_floats[3]) && (m_floats[2] == other.m_floats[2]) && (m_floats[1] == other.m_floats[1]) && (m_floats[0] == other.m_floats[0]));
}
SIMD_FORCE_INLINE bool operator!=(const btVector3& other) const
{
return !(*this == other);
}
/**@brief Set each element to the max of the current values and the values of another btVector3
* @param other The other btVector3 to compare with
*/
SIMD_FORCE_INLINE void setMax(const btVector3& other)
{
btSetMax(m_floats[0], other.m_floats[0]);
btSetMax(m_floats[1], other.m_floats[1]);
btSetMax(m_floats[2], other.m_floats[2]);
btSetMax(m_floats[3], other.w());
}
/**@brief Set each element to the min of the current values and the values of another btVector3
* @param other The other btVector3 to compare with
*/
SIMD_FORCE_INLINE void setMin(const btVector3& other)
{
btSetMin(m_floats[0], other.m_floats[0]);
btSetMin(m_floats[1], other.m_floats[1]);
btSetMin(m_floats[2], other.m_floats[2]);
btSetMin(m_floats[3], other.w());
}
SIMD_FORCE_INLINE void setValue(const btScalar& x, const btScalar& y, const btScalar& z)
{
m_floats[0] = x;
m_floats[1] = y;
m_floats[2] = z;
m_floats[3] = btScalar(0.);
}
void getSkewSymmetricMatrix(btVector3 * v0, btVector3 * v1, btVector3 * v2) const
{
v0->setValue(0., -z(), y());
v1->setValue(z(), 0., -x());
v2->setValue(-y(), x(), 0.);
}
void setZero()
{
setValue(btScalar(0.), btScalar(0.), btScalar(0.));
}
SIMD_FORCE_INLINE bool isZero() const
{
return m_floats[0] == btScalar(0) && m_floats[1] == btScalar(0) && m_floats[2] == btScalar(0);
}
SIMD_FORCE_INLINE bool fuzzyZero() const
{
return length2() < SIMD_EPSILON;
}
SIMD_FORCE_INLINE void serialize(struct btVector3Data & dataOut) const;
SIMD_FORCE_INLINE void deSerialize(const struct btVector3Data& dataIn);
SIMD_FORCE_INLINE void serializeFloat(struct btVector3FloatData & dataOut) const;
SIMD_FORCE_INLINE void deSerializeFloat(const struct btVector3FloatData& dataIn);
SIMD_FORCE_INLINE void serializeDouble(struct btVector3DoubleData & dataOut) const;
SIMD_FORCE_INLINE void deSerializeDouble(const struct btVector3DoubleData& dataIn);
};
/**@brief Return the sum of two vectors (Point symantics)*/
SIMD_FORCE_INLINE btVector3
operator+(const btVector3& v1, const btVector3& v2)
{
return btVector3(v1.m_floats[0] + v2.m_floats[0], v1.m_floats[1] + v2.m_floats[1], v1.m_floats[2] + v2.m_floats[2]);
}
/**@brief Return the elementwise product of two vectors */
SIMD_FORCE_INLINE btVector3
operator*(const btVector3& v1, const btVector3& v2)
{
return btVector3(v1.m_floats[0] * v2.m_floats[0], v1.m_floats[1] * v2.m_floats[1], v1.m_floats[2] * v2.m_floats[2]);
}
/**@brief Return the difference between two vectors */
SIMD_FORCE_INLINE btVector3
operator-(const btVector3& v1, const btVector3& v2)
{
return btVector3(v1.m_floats[0] - v2.m_floats[0], v1.m_floats[1] - v2.m_floats[1], v1.m_floats[2] - v2.m_floats[2]);
}
/**@brief Return the negative of the vector */
SIMD_FORCE_INLINE btVector3
operator-(const btVector3& v)
{
return btVector3(-v.m_floats[0], -v.m_floats[1], -v.m_floats[2]);
}
/**@brief Return the vector scaled by s */
SIMD_FORCE_INLINE btVector3
operator*(const btVector3& v, const btScalar& s)
{
return btVector3(v.m_floats[0] * s, v.m_floats[1] * s, v.m_floats[2] * s);
}
/**@brief Return the vector scaled by s */
SIMD_FORCE_INLINE btVector3
operator*(const btScalar& s, const btVector3& v)
{
return v * s;
}
/**@brief Return the vector inversely scaled by s */
SIMD_FORCE_INLINE btVector3
operator/(const btVector3& v, const btScalar& s)
{
btFullAssert(s != btScalar(0.0));
return v * (btScalar(1.0) / s);
}
/**@brief Return the vector inversely scaled by s */
SIMD_FORCE_INLINE btVector3
operator/(const btVector3& v1, const btVector3& v2)
{
return btVector3(v1.m_floats[0] / v2.m_floats[0], v1.m_floats[1] / v2.m_floats[1], v1.m_floats[2] / v2.m_floats[2]);
}
/**@brief Return the dot product between two vectors */
SIMD_FORCE_INLINE btScalar
btDot(const btVector3& v1, const btVector3& v2)
{
return v1.dot(v2);
}
/**@brief Return the distance squared between two vectors */
SIMD_FORCE_INLINE btScalar
btDistance2(const btVector3& v1, const btVector3& v2)
{
return v1.distance2(v2);
}
/**@brief Return the distance between two vectors */
SIMD_FORCE_INLINE btScalar
btDistance(const btVector3& v1, const btVector3& v2)
{
return v1.distance(v2);
}
/**@brief Return the angle between two vectors */
SIMD_FORCE_INLINE btScalar
btAngle(const btVector3& v1, const btVector3& v2)
{
return v1.angle(v2);
}
/**@brief Return the cross product of two vectors */
SIMD_FORCE_INLINE btVector3
btCross(const btVector3& v1, const btVector3& v2)
{
return v1.cross(v2);
}
SIMD_FORCE_INLINE btScalar
btTriple(const btVector3& v1, const btVector3& v2, const btVector3& v3)
{
return v1.triple(v2, v3);
}
/**@brief Return the linear interpolation between two vectors
* @param v1 One vector
* @param v2 The other vector
* @param t The ration of this to v (t = 0 => return v1, t=1 => return v2) */
SIMD_FORCE_INLINE btVector3
lerp(const btVector3& v1, const btVector3& v2, const btScalar& t)
{
return v1.lerp(v2, t);
}
SIMD_FORCE_INLINE btScalar btVector3::distance2(const btVector3& v) const
{
return (v - *this).length2();
}
SIMD_FORCE_INLINE btScalar btVector3::distance(const btVector3& v) const
{
return (v - *this).length();
}
SIMD_FORCE_INLINE btVector3 btVector3::normalized() const
{
return *this / length();
}
SIMD_FORCE_INLINE btVector3 btVector3::rotate(const btVector3& wAxis, const btScalar angle) const
{
// wAxis must be a unit lenght vector
btVector3 o = wAxis * wAxis.dot(*this);
btVector3 x = *this - o;
btVector3 y;
y = wAxis.cross(*this);
return (o + x * btCos(angle) + y * btSin(angle));
}
class btVector4 : public btVector3 {
public:
SIMD_FORCE_INLINE btVector4() {}
SIMD_FORCE_INLINE btVector4(const btScalar& x, const btScalar& y, const btScalar& z, const btScalar& w)
: btVector3(x, y, z)
{
m_floats[3] = w;
}
SIMD_FORCE_INLINE btVector4 absolute4() const
{
return btVector4(
btFabs(m_floats[0]),
btFabs(m_floats[1]),
btFabs(m_floats[2]),
btFabs(m_floats[3]));
}
btScalar getW() const { return m_floats[3]; }
SIMD_FORCE_INLINE int maxAxis4() const
{
int maxIndex = -1;
btScalar maxVal = btScalar(-BT_LARGE_FLOAT);
if (m_floats[0] > maxVal) {
maxIndex = 0;
maxVal = m_floats[0];
}
if (m_floats[1] > maxVal) {
maxIndex = 1;
maxVal = m_floats[1];
}
if (m_floats[2] > maxVal) {
maxIndex = 2;
maxVal = m_floats[2];
}
if (m_floats[3] > maxVal) {
maxIndex = 3;
}
return maxIndex;
}
SIMD_FORCE_INLINE int minAxis4() const
{
int minIndex = -1;
btScalar minVal = btScalar(BT_LARGE_FLOAT);
if (m_floats[0] < minVal) {
minIndex = 0;
minVal = m_floats[0];
}
if (m_floats[1] < minVal) {
minIndex = 1;
minVal = m_floats[1];
}
if (m_floats[2] < minVal) {
minIndex = 2;
minVal = m_floats[2];
}
if (m_floats[3] < minVal) {
minIndex = 3;
}
return minIndex;
}
SIMD_FORCE_INLINE int closestAxis4() const
{
return absolute4().maxAxis4();
}
/**@brief Set x,y,z and zero w
* @param x Value of x
* @param y Value of y
* @param z Value of z
*/
/* void getValue(btScalar *m) const
{
m[0] = m_floats[0];
m[1] = m_floats[1];
m[2] =m_floats[2];
}
*/
/**@brief Set the values
* @param x Value of x
* @param y Value of y
* @param z Value of z
* @param w Value of w
*/
SIMD_FORCE_INLINE void setValue(const btScalar& x, const btScalar& y, const btScalar& z, const btScalar& w)
{
m_floats[0] = x;
m_floats[1] = y;
m_floats[2] = z;
m_floats[3] = w;
}
};
///btSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization
SIMD_FORCE_INLINE void btSwapScalarEndian(const btScalar& sourceVal, btScalar& destVal)
{
#ifdef BT_USE_DOUBLE_PRECISION
unsigned char* dest = (unsigned char*)&destVal;
unsigned char* src = (unsigned char*)&sourceVal;
dest[0] = src[7];
dest[1] = src[6];
dest[2] = src[5];
dest[3] = src[4];
dest[4] = src[3];
dest[5] = src[2];
dest[6] = src[1];
dest[7] = src[0];
#else
unsigned char* dest = (unsigned char*)&destVal;
unsigned char* src = (unsigned char*)&sourceVal;
dest[0] = src[3];
dest[1] = src[2];
dest[2] = src[1];
dest[3] = src[0];
#endif //BT_USE_DOUBLE_PRECISION
}
///btSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization
SIMD_FORCE_INLINE void btSwapVector3Endian(const btVector3& sourceVec, btVector3& destVec)
{
for (int i = 0; i < 4; i++) {
btSwapScalarEndian(sourceVec[i], destVec[i]);
}
}
///btUnSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization
SIMD_FORCE_INLINE void btUnSwapVector3Endian(btVector3& vector)
{
btVector3 swappedVec;
for (int i = 0; i < 4; i++) {
btSwapScalarEndian(vector[i], swappedVec[i]);
}
vector = swappedVec;
}
template <class T>
SIMD_FORCE_INLINE void btPlaneSpace1(const T& n, T& p, T& q)
{
if (btFabs(n[2]) > SIMDSQRT12) {
// choose p in y-z plane
btScalar a = n[1] * n[1] + n[2] * n[2];
btScalar k = btRecipSqrt(a);
p[0] = 0;
p[1] = -n[2] * k;
p[2] = n[1] * k;
// set q = n x p
q[0] = a * k;
q[1] = -n[0] * p[2];
q[2] = n[0] * p[1];
}
else {
// choose p in x-y plane
btScalar a = n[0] * n[0] + n[1] * n[1];
btScalar k = btRecipSqrt(a);
p[0] = -n[1] * k;
p[1] = n[0] * k;
p[2] = 0;
// set q = n x p
q[0] = -n[2] * p[1];
q[1] = n[2] * p[0];
q[2] = a * k;
}
}
struct btVector3FloatData {
float m_floats[4];
};
struct btVector3DoubleData {
double m_floats[4];
};
SIMD_FORCE_INLINE void btVector3::serializeFloat(struct btVector3FloatData& dataOut) const
{
///could also do a memcpy, check if it is worth it
for (int i = 0; i < 4; i++)
dataOut.m_floats[i] = float(m_floats[i]);
}
SIMD_FORCE_INLINE void btVector3::deSerializeFloat(const struct btVector3FloatData& dataIn)
{
for (int i = 0; i < 4; i++)
m_floats[i] = btScalar(dataIn.m_floats[i]);
}
SIMD_FORCE_INLINE void btVector3::serializeDouble(struct btVector3DoubleData& dataOut) const
{
///could also do a memcpy, check if it is worth it
for (int i = 0; i < 4; i++)
dataOut.m_floats[i] = double(m_floats[i]);
}
SIMD_FORCE_INLINE void btVector3::deSerializeDouble(const struct btVector3DoubleData& dataIn)
{
for (int i = 0; i < 4; i++)
m_floats[i] = btScalar(dataIn.m_floats[i]);
}
SIMD_FORCE_INLINE void btVector3::serialize(struct btVector3Data& dataOut) const
{
///could also do a memcpy, check if it is worth it
for (int i = 0; i < 4; i++)
dataOut.m_floats[i] = m_floats[i];
}
SIMD_FORCE_INLINE void btVector3::deSerialize(const struct btVector3Data& dataIn)
{
for (int i = 0; i < 4; i++)
m_floats[i] = dataIn.m_floats[i];
}
#endif //BT_VECTOR3_H

View File

@@ -0,0 +1,79 @@
/* 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_CIRCULAR_LIST_H
#define VHACD_CIRCULAR_LIST_H
#include <stdlib.h>
namespace VHACD {
//! CircularListElement class.
template <typename T>
class CircularListElement {
public:
T& GetData() { return m_data; }
const T& GetData() const { return m_data; }
CircularListElement<T>*& GetNext() { return m_next; }
CircularListElement<T>*& GetPrev() { return m_prev; }
const CircularListElement<T>*& GetNext() const { return m_next; }
const CircularListElement<T>*& GetPrev() const { return m_prev; }
//! Constructor
CircularListElement(const T& data) { m_data = data; }
CircularListElement(void) {}
//! Destructor
~CircularListElement(void) {}
private:
T m_data;
CircularListElement<T>* m_next;
CircularListElement<T>* m_prev;
CircularListElement(const CircularListElement& rhs);
};
//! CircularList class.
template <typename T>
class CircularList {
public:
CircularListElement<T>*& GetHead() { return m_head; }
const CircularListElement<T>* GetHead() const { return m_head; }
bool IsEmpty() const { return (m_size == 0); }
size_t GetSize() const { return m_size; }
const T& GetData() const { return m_head->GetData(); }
T& GetData() { return m_head->GetData(); }
bool Delete();
bool Delete(CircularListElement<T>* element);
CircularListElement<T>* Add(const T* data = 0);
CircularListElement<T>* Add(const T& data);
bool Next();
bool Prev();
void Clear()
{
while (Delete())
;
};
const CircularList& operator=(const CircularList& rhs);
//! Constructor
CircularList()
{
m_head = 0;
m_size = 0;
}
CircularList(const CircularList& rhs);
//! Destructor
~CircularList(void) { Clear(); };
private:
CircularListElement<T>* m_head; //!< a pointer to the head of the circular list
size_t m_size; //!< number of element in the circular list
};
}
#include "vhacdCircularList.inl"
#endif // VHACD_CIRCULAR_LIST_H

View File

@@ -0,0 +1,161 @@
#pragma once
#ifndef HACD_CIRCULAR_LIST_INL
#define HACD_CIRCULAR_LIST_INL
namespace VHACD
{
template < typename T >
inline bool CircularList<T>::Delete(CircularListElement<T> * element)
{
if (!element)
{
return false;
}
if (m_size > 1)
{
CircularListElement<T> * next = element->GetNext();
CircularListElement<T> * prev = element->GetPrev();
delete element;
m_size--;
if (element == m_head)
{
m_head = next;
}
next->GetPrev() = prev;
prev->GetNext() = next;
return true;
}
else if (m_size == 1)
{
delete m_head;
m_size--;
m_head = 0;
return true;
}
else
{
return false;
}
}
template < typename T >
inline bool CircularList<T>::Delete()
{
if (m_size > 1)
{
CircularListElement<T> * next = m_head->GetNext();
CircularListElement<T> * prev = m_head->GetPrev();
delete m_head;
m_size--;
m_head = next;
next->GetPrev() = prev;
prev->GetNext() = next;
return true;
}
else if (m_size == 1)
{
delete m_head;
m_size--;
m_head = 0;
return true;
}
else
{
return false;
}
}
template < typename T >
inline CircularListElement<T> * CircularList<T>::Add(const T * data)
{
if (m_size == 0)
{
if (data)
{
m_head = new CircularListElement<T>(*data);
}
else
{
m_head = new CircularListElement<T>();
}
m_head->GetNext() = m_head->GetPrev() = m_head;
}
else
{
CircularListElement<T> * next = m_head->GetNext();
CircularListElement<T> * element = m_head;
if (data)
{
m_head = new CircularListElement<T>(*data);
}
else
{
m_head = new CircularListElement<T>();
}
m_head->GetNext() = next;
m_head->GetPrev() = element;
element->GetNext() = m_head;
next->GetPrev() = m_head;
}
m_size++;
return m_head;
}
template < typename T >
inline CircularListElement<T> * CircularList<T>::Add(const T & data)
{
const T * pData = &data;
return Add(pData);
}
template < typename T >
inline bool CircularList<T>::Next()
{
if (m_size == 0)
{
return false;
}
m_head = m_head->GetNext();
return true;
}
template < typename T >
inline bool CircularList<T>::Prev()
{
if (m_size == 0)
{
return false;
}
m_head = m_head->GetPrev();
return true;
}
template < typename T >
inline CircularList<T>::CircularList(const CircularList& rhs)
{
if (rhs.m_size > 0)
{
CircularListElement<T> * current = rhs.m_head;
do
{
current = current->GetNext();
Add(current->GetData());
}
while ( current != rhs.m_head );
}
}
template < typename T >
inline const CircularList<T>& CircularList<T>::operator=(const CircularList& rhs)
{
if (&rhs != this)
{
Clear();
if (rhs.m_size > 0)
{
CircularListElement<T> * current = rhs.m_head;
do
{
current = current->GetNext();
Add(current->GetData());
}
while ( current != rhs.m_head );
}
}
return (*this);
}
}
#endif

View File

@@ -0,0 +1,98 @@
/* 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_ICHULL_H
#define VHACD_ICHULL_H
#include "vhacdManifoldMesh.h"
#include "vhacdVector.h"
namespace VHACD {
//! Incremental Convex Hull algorithm (cf. http://cs.smith.edu/~orourke/books/ftp.html ).
enum ICHullError {
ICHullErrorOK = 0,
ICHullErrorCoplanarPoints,
ICHullErrorNoVolume,
ICHullErrorInconsistent,
ICHullErrorNotEnoughPoints
};
class ICHull {
public:
static const double sc_eps;
//!
bool IsFlat() { return m_isFlat; }
//! Returns the computed mesh
TMMesh& GetMesh() { return m_mesh; }
//! Add one point to the convex-hull
bool AddPoint(const Vec3<double>& point) { return AddPoints(&point, 1); }
//! Add one point to the convex-hull
bool AddPoint(const Vec3<double>& point, int id);
//! Add points to the convex-hull
bool AddPoints(const Vec3<double>* points, size_t nPoints);
//!
ICHullError Process();
//!
ICHullError Process(const unsigned int nPointsCH, const double minVolume = 0.0);
//!
bool IsInside(const Vec3<double>& pt0, const double eps = 0.0);
//!
const ICHull& operator=(ICHull& rhs);
//! Constructor
ICHull();
//! Destructor
~ICHull(void){};
private:
//! DoubleTriangle builds the initial double triangle. It first finds 3 noncollinear points and makes two faces out of them, in opposite order. It then finds a fourth point that is not coplanar with that face. The vertices are stored in the face structure in counterclockwise order so that the volume between the face and the point is negative. Lastly, the 3 newfaces to the fourth point are constructed and the data structures are cleaned up.
ICHullError DoubleTriangle();
//! MakeFace creates a new face structure from three vertices (in ccw order). It returns a pointer to the face.
CircularListElement<TMMTriangle>* MakeFace(CircularListElement<TMMVertex>* v0,
CircularListElement<TMMVertex>* v1,
CircularListElement<TMMVertex>* v2,
CircularListElement<TMMTriangle>* fold);
//!
CircularListElement<TMMTriangle>* MakeConeFace(CircularListElement<TMMEdge>* e, CircularListElement<TMMVertex>* v);
//!
bool ProcessPoint();
//!
bool ComputePointVolume(double& totalVolume, bool markVisibleFaces);
//!
bool FindMaxVolumePoint(const double minVolume = 0.0);
//!
bool CleanEdges();
//!
bool CleanVertices(unsigned int& addedPoints);
//!
bool CleanTriangles();
//!
bool CleanUp(unsigned int& addedPoints);
//!
bool MakeCCW(CircularListElement<TMMTriangle>* f,
CircularListElement<TMMEdge>* e,
CircularListElement<TMMVertex>* v);
void Clear();
private:
static const int sc_dummyIndex;
TMMesh m_mesh;
SArray<CircularListElement<TMMEdge>*> m_edgesToDelete;
SArray<CircularListElement<TMMEdge>*> m_edgesToUpdate;
SArray<CircularListElement<TMMTriangle>*> m_trianglesToDelete;
Vec3<double> m_normal;
bool m_isFlat;
ICHull(const ICHull& rhs);
};
}
#endif // VHACD_ICHULL_H

View File

@@ -0,0 +1,142 @@
/* 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_MANIFOLD_MESH_H
#define VHACD_MANIFOLD_MESH_H
#include "vhacdCircularList.h"
#include "vhacdSArray.h"
#include "vhacdVector.h"
namespace VHACD {
class TMMTriangle;
class TMMEdge;
class TMMesh;
class ICHull;
//! Vertex data structure used in a triangular manifold mesh (TMM).
class TMMVertex {
public:
void Initialize();
TMMVertex(void);
~TMMVertex(void);
private:
Vec3<double> m_pos;
int m_name;
size_t m_id;
CircularListElement<TMMEdge>* m_duplicate; // pointer to incident cone edge (or NULL)
bool m_onHull;
bool m_tag;
TMMVertex(const TMMVertex& rhs);
friend class ICHull;
friend class TMMesh;
friend class TMMTriangle;
friend class TMMEdge;
};
//! Edge data structure used in a triangular manifold mesh (TMM).
class TMMEdge {
public:
void Initialize();
TMMEdge(void);
~TMMEdge(void);
private:
size_t m_id;
CircularListElement<TMMTriangle>* m_triangles[2];
CircularListElement<TMMVertex>* m_vertices[2];
CircularListElement<TMMTriangle>* m_newFace;
TMMEdge(const TMMEdge& rhs);
friend class ICHull;
friend class TMMTriangle;
friend class TMMVertex;
friend class TMMesh;
};
//! Triangle data structure used in a triangular manifold mesh (TMM).
class TMMTriangle {
public:
void Initialize();
TMMTriangle(void);
~TMMTriangle(void);
private:
size_t m_id;
CircularListElement<TMMEdge>* m_edges[3];
CircularListElement<TMMVertex>* m_vertices[3];
bool m_visible;
TMMTriangle(const TMMTriangle& rhs);
friend class ICHull;
friend class TMMesh;
friend class TMMVertex;
friend class TMMEdge;
};
//! triangular manifold mesh data structure.
class TMMesh {
public:
//! Returns the number of vertices>
inline size_t GetNVertices() const { return m_vertices.GetSize(); }
//! Returns the number of edges
inline size_t GetNEdges() const { return m_edges.GetSize(); }
//! Returns the number of triangles
inline size_t GetNTriangles() const { return m_triangles.GetSize(); }
//! Returns the vertices circular list
inline const CircularList<TMMVertex>& GetVertices() const { return m_vertices; }
//! Returns the edges circular list
inline const CircularList<TMMEdge>& GetEdges() const { return m_edges; }
//! Returns the triangles circular list
inline const CircularList<TMMTriangle>& GetTriangles() const { return m_triangles; }
//! Returns the vertices circular list
inline CircularList<TMMVertex>& GetVertices() { return m_vertices; }
//! Returns the edges circular list
inline CircularList<TMMEdge>& GetEdges() { return m_edges; }
//! Returns the triangles circular list
inline CircularList<TMMTriangle>& GetTriangles() { return m_triangles; }
//! Add vertex to the mesh
CircularListElement<TMMVertex>* AddVertex() { return m_vertices.Add(); }
//! Add vertex to the mesh
CircularListElement<TMMEdge>* AddEdge() { return m_edges.Add(); }
//! Add vertex to the mesh
CircularListElement<TMMTriangle>* AddTriangle() { return m_triangles.Add(); }
//! Print mesh information
void Print();
//!
void GetIFS(Vec3<double>* const points, Vec3<int>* const triangles);
//!
void Clear();
//!
void Copy(TMMesh& mesh);
//!
bool CheckConsistancy();
//!
bool Normalize();
//!
bool Denormalize();
//! Constructor
TMMesh();
//! Destructor
virtual ~TMMesh(void);
private:
CircularList<TMMVertex> m_vertices;
CircularList<TMMEdge> m_edges;
CircularList<TMMTriangle> m_triangles;
// not defined
TMMesh(const TMMesh& rhs);
friend class ICHull;
};
}
#endif // VHACD_MANIFOLD_MESH_H

View File

@@ -0,0 +1,129 @@
/* 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_MESH_H
#define VHACD_MESH_H
#include "vhacdSArray.h"
#include "vhacdVector.h"
#define VHACD_DEBUG_MESH
namespace VHACD {
enum AXIS {
AXIS_X = 0,
AXIS_Y = 1,
AXIS_Z = 2
};
struct Plane {
double m_a;
double m_b;
double m_c;
double m_d;
AXIS m_axis;
short m_index;
};
#ifdef VHACD_DEBUG_MESH
struct Material {
Vec3<double> m_diffuseColor;
double m_ambientIntensity;
Vec3<double> m_specularColor;
Vec3<double> m_emissiveColor;
double m_shininess;
double m_transparency;
Material(void)
{
m_diffuseColor.X() = 0.5;
m_diffuseColor.Y() = 0.5;
m_diffuseColor.Z() = 0.5;
m_specularColor.X() = 0.5;
m_specularColor.Y() = 0.5;
m_specularColor.Z() = 0.5;
m_ambientIntensity = 0.4;
m_emissiveColor.X() = 0.0;
m_emissiveColor.Y() = 0.0;
m_emissiveColor.Z() = 0.0;
m_shininess = 0.4;
m_transparency = 0.0;
};
};
#endif // VHACD_DEBUG_MESH
//! Triangular mesh data structure
class Mesh {
public:
void AddPoint(const Vec3<double>& pt) { m_points.PushBack(pt); };
void SetPoint(size_t index, const Vec3<double>& pt) { m_points[index] = pt; };
const Vec3<double>& GetPoint(size_t index) const { return m_points[index]; };
Vec3<double>& GetPoint(size_t index) { return m_points[index]; };
size_t GetNPoints() const { return m_points.Size(); };
double* GetPoints() { return (double*)m_points.Data(); } // ugly
const double* const GetPoints() const { return (double*)m_points.Data(); } // ugly
const Vec3<double>* const GetPointsBuffer() const { return m_points.Data(); } //
Vec3<double>* const GetPointsBuffer() { return m_points.Data(); } //
void AddTriangle(const Vec3<int>& tri) { m_triangles.PushBack(tri); };
void SetTriangle(size_t index, const Vec3<int>& tri) { m_triangles[index] = tri; };
const Vec3<int>& GetTriangle(size_t index) const { return m_triangles[index]; };
Vec3<int>& GetTriangle(size_t index) { return m_triangles[index]; };
size_t GetNTriangles() const { return m_triangles.Size(); };
int* GetTriangles() { return (int*)m_triangles.Data(); } // ugly
const int* const GetTriangles() const { return (int*)m_triangles.Data(); } // ugly
const Vec3<int>* const GetTrianglesBuffer() const { return m_triangles.Data(); }
Vec3<int>* const GetTrianglesBuffer() { return m_triangles.Data(); }
const Vec3<double>& GetCenter() const { return m_center; }
const Vec3<double>& GetMinBB() const { return m_minBB; }
const Vec3<double>& GetMaxBB() const { return m_maxBB; }
void ClearPoints() { m_points.Clear(); }
void ClearTriangles() { m_triangles.Clear(); }
void Clear()
{
ClearPoints();
ClearTriangles();
}
void ResizePoints(size_t nPts) { m_points.Resize(nPts); }
void ResizeTriangles(size_t nTri) { m_triangles.Resize(nTri); }
void CopyPoints(SArray<Vec3<double> >& points) const { points = m_points; }
double GetDiagBB() const { return m_diag; }
double ComputeVolume() const;
void ComputeConvexHull(const double* const pts,
const size_t nPts);
void Clip(const Plane& plane,
SArray<Vec3<double> >& positivePart,
SArray<Vec3<double> >& negativePart) const;
bool IsInside(const Vec3<double>& pt) const;
double ComputeDiagBB();
#ifdef VHACD_DEBUG_MESH
bool LoadOFF(const std::string& fileName, bool invert);
bool SaveVRML2(const std::string& fileName) const;
bool SaveVRML2(std::ofstream& fout, const Material& material) const;
bool SaveOFF(const std::string& fileName) const;
#endif // VHACD_DEBUG_MESH
//! Constructor.
Mesh();
//! Destructor.
~Mesh(void);
private:
SArray<Vec3<double> > m_points;
SArray<Vec3<int> > m_triangles;
Vec3<double> m_minBB;
Vec3<double> m_maxBB;
Vec3<double> m_center;
double m_diag;
};
}
#endif

View File

@@ -0,0 +1,146 @@
/*!
**
** Copyright (c) 2009 by John W. Ratcliff mailto:jratcliffscarab@gmail.com
**
** Portions of this source has been released with the PhysXViewer application, as well as
** Rocket, CreateDynamics, ODF, and as a number of sample code snippets.
**
** If you find this code useful or you are feeling particularily generous I would
** ask that you please go to http://www.amillionpixels.us and make a donation
** to Troy DeMolay.
**
** DeMolay is a youth group for young men between the ages of 12 and 21.
** It teaches strong moral principles, as well as leadership skills and
** public speaking. The donations page uses the 'pay for pixels' paradigm
** where, in this case, a pixel is only a single penny. Donations can be
** made for as small as $4 or as high as a $100 block. Each person who donates
** will get a link to their own site as well as acknowledgement on the
** donations blog located here http://www.amillionpixels.blogspot.com/
**
** If you wish to contact me you can use the following methods:
**
** Skype ID: jratcliff63367
** Yahoo: jratcliff63367
** AOL: jratcliff1961
** email: jratcliffscarab@gmail.com
**
**
** The MIT license:
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is furnished
** to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#ifndef VHACD_MUTEX_H
#define VHACD_MUTEX_H
#if defined(WIN32)
//#define _WIN32_WINNT 0x400
#include <windows.h>
#pragma comment(lib, "winmm.lib")
#endif
#if defined(__linux__)
//#include <sys/time.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#define __stdcall
#endif
#if defined(__APPLE__) || defined(__linux__)
#include <pthread.h>
#endif
#if defined(__APPLE__)
#define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE
#endif
#define VHACD_DEBUG
//#define VHACD_NDEBUG
#ifdef VHACD_NDEBUG
#define VHACD_VERIFY(x) (x)
#else
#define VHACD_VERIFY(x) assert((x))
#endif
namespace VHACD {
class Mutex {
public:
Mutex(void)
{
#if defined(WIN32) || defined(_XBOX)
InitializeCriticalSection(&m_mutex);
#elif defined(__APPLE__) || defined(__linux__)
pthread_mutexattr_t mutexAttr; // Mutex Attribute
VHACD_VERIFY(pthread_mutexattr_init(&mutexAttr) == 0);
VHACD_VERIFY(pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE_NP) == 0);
VHACD_VERIFY(pthread_mutex_init(&m_mutex, &mutexAttr) == 0);
VHACD_VERIFY(pthread_mutexattr_destroy(&mutexAttr) == 0);
#endif
}
~Mutex(void)
{
#if defined(WIN32) || defined(_XBOX)
DeleteCriticalSection(&m_mutex);
#elif defined(__APPLE__) || defined(__linux__)
VHACD_VERIFY(pthread_mutex_destroy(&m_mutex) == 0);
#endif
}
void Lock(void)
{
#if defined(WIN32) || defined(_XBOX)
EnterCriticalSection(&m_mutex);
#elif defined(__APPLE__) || defined(__linux__)
VHACD_VERIFY(pthread_mutex_lock(&m_mutex) == 0);
#endif
}
bool TryLock(void)
{
#if defined(WIN32) || defined(_XBOX)
bool bRet = false;
//assert(("TryEnterCriticalSection seems to not work on XP???", 0));
bRet = TryEnterCriticalSection(&m_mutex) ? true : false;
return bRet;
#elif defined(__APPLE__) || defined(__linux__)
int result = pthread_mutex_trylock(&m_mutex);
return (result == 0);
#endif
}
void Unlock(void)
{
#if defined(WIN32) || defined(_XBOX)
LeaveCriticalSection(&m_mutex);
#elif defined(__APPLE__) || defined(__linux__)
VHACD_VERIFY(pthread_mutex_unlock(&m_mutex) == 0);
#endif
}
private:
#if defined(WIN32) || defined(_XBOX)
CRITICAL_SECTION m_mutex;
#elif defined(__APPLE__) || defined(__linux__)
pthread_mutex_t m_mutex;
#endif
};
}
#endif // VHACD_MUTEX_H

View File

@@ -0,0 +1,158 @@
/* 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_SARRAY_H
#define VHACD_SARRAY_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SARRAY_DEFAULT_MIN_SIZE 16
namespace VHACD {
//! SArray.
template <typename T, size_t N = 64>
class SArray {
public:
T& operator[](size_t i)
{
T* const data = Data();
return data[i];
}
const T& operator[](size_t i) const
{
const T* const data = Data();
return data[i];
}
size_t Size() const
{
return m_size;
}
T* const Data()
{
return (m_maxSize == N) ? m_data0 : m_data;
}
const T* const Data() const
{
return (m_maxSize == N) ? m_data0 : m_data;
}
void Clear()
{
m_size = 0;
delete[] m_data;
m_data = 0;
m_maxSize = N;
}
void PopBack()
{
--m_size;
}
void Allocate(size_t size)
{
if (size > m_maxSize) {
T* temp = new T[size];
memcpy(temp, Data(), m_size * sizeof(T));
delete[] m_data;
m_data = temp;
m_maxSize = size;
}
}
void Resize(size_t size)
{
Allocate(size);
m_size = size;
}
void PushBack(const T& value)
{
if (m_size == m_maxSize) {
size_t maxSize = (m_maxSize << 1);
T* temp = new T[maxSize];
memcpy(temp, Data(), m_maxSize * sizeof(T));
delete[] m_data;
m_data = temp;
m_maxSize = maxSize;
}
T* const data = Data();
data[m_size++] = value;
}
bool Find(const T& value, size_t& pos)
{
T* const data = Data();
for (pos = 0; pos < m_size; ++pos)
if (value == data[pos])
return true;
return false;
}
bool Insert(const T& value)
{
size_t pos;
if (Find(value, pos))
return false;
PushBack(value);
return true;
}
bool Erase(const T& value)
{
size_t pos;
T* const data = Data();
if (Find(value, pos)) {
for (size_t j = pos + 1; j < m_size; ++j)
data[j - 1] = data[j];
--m_size;
return true;
}
return false;
}
void operator=(const SArray& rhs)
{
if (m_maxSize < rhs.m_size) {
delete[] m_data;
m_maxSize = rhs.m_maxSize;
m_data = new T[m_maxSize];
}
m_size = rhs.m_size;
memcpy(Data(), rhs.Data(), m_size * sizeof(T));
}
void Initialize()
{
m_data = 0;
m_size = 0;
m_maxSize = N;
}
SArray(const SArray& rhs)
{
m_data = 0;
m_size = 0;
m_maxSize = N;
*this = rhs;
}
SArray()
{
Initialize();
}
~SArray()
{
delete[] m_data;
}
private:
T m_data0[N];
T* m_data;
size_t m_size;
size_t m_maxSize;
};
}
#endif

View File

@@ -0,0 +1,121 @@
/* 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_TIMER_H
#define VHACD_TIMER_H
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#endif
#include <windows.h>
#elif __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#else
#include <sys/time.h>
#include <time.h>
#endif
namespace VHACD {
#ifdef _WIN32
class Timer {
public:
Timer(void)
{
m_start.QuadPart = 0;
m_stop.QuadPart = 0;
QueryPerformanceFrequency(&m_freq);
};
~Timer(void){};
void Tic()
{
QueryPerformanceCounter(&m_start);
}
void Toc()
{
QueryPerformanceCounter(&m_stop);
}
double GetElapsedTime() // in ms
{
LARGE_INTEGER delta;
delta.QuadPart = m_stop.QuadPart - m_start.QuadPart;
return (1000.0 * delta.QuadPart) / (double)m_freq.QuadPart;
}
private:
LARGE_INTEGER m_start;
LARGE_INTEGER m_stop;
LARGE_INTEGER m_freq;
};
#elif __MACH__
class Timer {
public:
Timer(void)
{
memset(this, 0, sizeof(Timer));
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &m_cclock);
};
~Timer(void)
{
mach_port_deallocate(mach_task_self(), m_cclock);
};
void Tic()
{
clock_get_time(m_cclock, &m_start);
}
void Toc()
{
clock_get_time(m_cclock, &m_stop);
}
double GetElapsedTime() // in ms
{
return 1000.0 * (m_stop.tv_sec - m_start.tv_sec + (1.0E-9) * (m_stop.tv_nsec - m_start.tv_nsec));
}
private:
clock_serv_t m_cclock;
mach_timespec_t m_start;
mach_timespec_t m_stop;
};
#else
class Timer {
public:
Timer(void)
{
memset(this, 0, sizeof(Timer));
};
~Timer(void){};
void Tic()
{
clock_gettime(CLOCK_REALTIME, &m_start);
}
void Toc()
{
clock_gettime(CLOCK_REALTIME, &m_stop);
}
double GetElapsedTime() // in ms
{
return 1000.0 * (m_stop.tv_sec - m_start.tv_sec + (1.0E-9) * (m_stop.tv_nsec - m_start.tv_nsec));
}
private:
struct timespec m_start;
struct timespec m_stop;
};
#endif
}
#endif // VHACD_TIMER_H

View File

@@ -0,0 +1,350 @@
/* 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_VHACD_H
#define VHACD_VHACD_H
#ifdef OPENCL_FOUND
#ifdef __MACH__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#endif //OPENCL_FOUND
#include "vhacdMutex.h"
#include "vhacdVolume.h"
#define USE_THREAD 1
#define OCL_MIN_NUM_PRIMITIVES 4096
#define CH_APP_MIN_NUM_PRIMITIVES 64000
namespace VHACD {
class VHACD : public IVHACD {
public:
//! Constructor.
VHACD()
{
#if USE_THREAD == 1 && _OPENMP
m_ompNumProcessors = 2 * omp_get_num_procs();
omp_set_num_threads(m_ompNumProcessors);
#else //USE_THREAD == 1 && _OPENMP
m_ompNumProcessors = 1;
#endif //USE_THREAD == 1 && _OPENMP
#ifdef CL_VERSION_1_1
m_oclWorkGroupSize = 0;
m_oclDevice = 0;
m_oclQueue = 0;
m_oclKernelComputePartialVolumes = 0;
m_oclKernelComputeSum = 0;
#endif //CL_VERSION_1_1
Init();
}
//! Destructor.
~VHACD(void) {}
unsigned int GetNConvexHulls() const
{
return (unsigned int)m_convexHulls.Size();
}
void Cancel()
{
SetCancel(true);
}
void GetConvexHull(const unsigned int index, ConvexHull& ch) const
{
Mesh* mesh = m_convexHulls[index];
ch.m_nPoints = (unsigned int)mesh->GetNPoints();
ch.m_nTriangles = (unsigned int)mesh->GetNTriangles();
ch.m_points = mesh->GetPoints();
ch.m_triangles = mesh->GetTriangles();
}
void Clean(void)
{
delete m_volume;
delete m_pset;
size_t nCH = m_convexHulls.Size();
for (size_t p = 0; p < nCH; ++p) {
delete m_convexHulls[p];
}
m_convexHulls.Clear();
Init();
}
void Release(void)
{
delete this;
}
bool Compute(const float* const points,
const unsigned int stridePoints,
const unsigned int nPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int nTriangles,
const Parameters& params);
bool Compute(const double* const points,
const unsigned int stridePoints,
const unsigned int nPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int nTriangles,
const Parameters& params);
bool OCLInit(void* const oclDevice,
IUserLogger* const logger = 0);
bool OCLRelease(IUserLogger* const logger = 0);
private:
void SetCancel(bool cancel)
{
m_cancelMutex.Lock();
m_cancel = cancel;
m_cancelMutex.Unlock();
}
bool GetCancel()
{
m_cancelMutex.Lock();
bool cancel = m_cancel;
m_cancelMutex.Unlock();
return cancel;
}
void Update(const double stageProgress,
const double operationProgress,
const Parameters& params)
{
m_stageProgress = stageProgress;
m_operationProgress = operationProgress;
if (params.m_callback) {
params.m_callback->Update(m_overallProgress,
m_stageProgress,
m_operationProgress,
m_stage.c_str(),
m_operation.c_str());
}
}
void Init()
{
memset(m_rot, 0, sizeof(double) * 9);
m_dim = 64;
m_volume = 0;
m_volumeCH0 = 0.0;
m_pset = 0;
m_overallProgress = 0.0;
m_stageProgress = 0.0;
m_operationProgress = 0.0;
m_stage = "";
m_operation = "";
m_barycenter[0] = m_barycenter[1] = m_barycenter[2] = 0.0;
m_rot[0][0] = m_rot[1][1] = m_rot[2][2] = 1.0;
SetCancel(false);
}
void ComputePrimitiveSet(const Parameters& params);
void ComputeACD(const Parameters& params);
void MergeConvexHulls(const Parameters& params);
void SimplifyConvexHulls(const Parameters& params);
void ComputeBestClippingPlane(const PrimitiveSet* inputPSet,
const double volume,
const SArray<Plane>& planes,
const Vec3<double>& preferredCuttingDirection,
const double w,
const double alpha,
const double beta,
const int convexhullDownsampling,
const double progress0,
const double progress1,
Plane& bestPlane,
double& minConcavity,
const Parameters& params);
template <class T>
void AlignMesh(const T* const points,
const unsigned int stridePoints,
const unsigned int nPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int nTriangles,
const Parameters& params)
{
if (GetCancel() || !params.m_pca) {
return;
}
m_timer.Tic();
m_stage = "Align mesh";
m_operation = "Voxelization";
std::ostringstream msg;
if (params.m_logger) {
msg << "+ " << m_stage << std::endl;
params.m_logger->Log(msg.str().c_str());
}
Update(0.0, 0.0, params);
if (GetCancel()) {
return;
}
m_dim = (size_t)(pow((double)params.m_resolution, 1.0 / 3.0) + 0.5);
Volume volume;
volume.Voxelize(points, stridePoints, nPoints,
triangles, strideTriangles, nTriangles,
m_dim, m_barycenter, m_rot);
size_t n = volume.GetNPrimitivesOnSurf() + volume.GetNPrimitivesInsideSurf();
Update(50.0, 100.0, params);
if (params.m_logger) {
msg.str("");
msg << "\t dim = " << m_dim << "\t-> " << n << " voxels" << std::endl;
params.m_logger->Log(msg.str().c_str());
}
if (GetCancel()) {
return;
}
m_operation = "PCA";
Update(50.0, 0.0, params);
volume.AlignToPrincipalAxes(m_rot);
m_overallProgress = 1.0;
Update(100.0, 100.0, params);
m_timer.Toc();
if (params.m_logger) {
msg.str("");
msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
params.m_logger->Log(msg.str().c_str());
}
}
template <class T>
void VoxelizeMesh(const T* const points,
const unsigned int stridePoints,
const unsigned int nPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int nTriangles,
const Parameters& params)
{
if (GetCancel()) {
return;
}
m_timer.Tic();
m_stage = "Voxelization";
std::ostringstream msg;
if (params.m_logger) {
msg << "+ " << m_stage << std::endl;
params.m_logger->Log(msg.str().c_str());
}
delete m_volume;
m_volume = 0;
int iteration = 0;
const int maxIteration = 5;
double progress = 0.0;
while (iteration++ < maxIteration && !m_cancel) {
msg.str("");
msg << "Iteration " << iteration;
m_operation = msg.str();
progress = iteration * 100.0 / maxIteration;
Update(progress, 0.0, params);
m_volume = new Volume;
m_volume->Voxelize(points, stridePoints, nPoints,
triangles, strideTriangles, nTriangles,
m_dim, m_barycenter, m_rot);
Update(progress, 100.0, params);
size_t n = m_volume->GetNPrimitivesOnSurf() + m_volume->GetNPrimitivesInsideSurf();
if (params.m_logger) {
msg.str("");
msg << "\t dim = " << m_dim << "\t-> " << n << " voxels" << std::endl;
params.m_logger->Log(msg.str().c_str());
}
double a = pow((double)(params.m_resolution) / n, 0.33);
size_t dim_next = (size_t)(m_dim * a + 0.5);
if (n < params.m_resolution && iteration < maxIteration && m_volume->GetNPrimitivesOnSurf() < params.m_resolution / 8 && m_dim != dim_next) {
delete m_volume;
m_volume = 0;
m_dim = dim_next;
}
else {
break;
}
}
m_overallProgress = 10.0;
Update(100.0, 100.0, params);
m_timer.Toc();
if (params.m_logger) {
msg.str("");
msg << "\t time " << m_timer.GetElapsedTime() / 1000.0 << "s" << std::endl;
params.m_logger->Log(msg.str().c_str());
}
}
template <class T>
bool ComputeACD(const T* const points,
const unsigned int stridePoints,
const unsigned int nPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int nTriangles,
const Parameters& params)
{
Init();
if (params.m_oclAcceleration) {
// build kernals
}
AlignMesh(points, stridePoints, nPoints, triangles, strideTriangles, nTriangles, params);
VoxelizeMesh(points, stridePoints, nPoints, triangles, strideTriangles, nTriangles, params);
ComputePrimitiveSet(params);
ComputeACD(params);
MergeConvexHulls(params);
SimplifyConvexHulls(params);
if (params.m_oclAcceleration) {
// Release kernals
}
if (GetCancel()) {
Clean();
return false;
}
return true;
}
private:
SArray<Mesh*> m_convexHulls;
std::string m_stage;
std::string m_operation;
double m_overallProgress;
double m_stageProgress;
double m_operationProgress;
double m_rot[3][3];
double m_volumeCH0;
Vec3<double> m_barycenter;
Timer m_timer;
size_t m_dim;
Volume* m_volume;
PrimitiveSet* m_pset;
Mutex m_cancelMutex;
bool m_cancel;
int m_ompNumProcessors;
#ifdef CL_VERSION_1_1
cl_device_id* m_oclDevice;
cl_context m_oclContext;
cl_program m_oclProgram;
cl_command_queue* m_oclQueue;
cl_kernel* m_oclKernelComputePartialVolumes;
cl_kernel* m_oclKernelComputeSum;
size_t m_oclWorkGroupSize;
#endif //CL_VERSION_1_1
};
}
#endif // VHACD_VHACD_H

View File

@@ -0,0 +1,103 @@
/* 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_VECTOR_H
#define VHACD_VECTOR_H
#include <iostream>
#include <math.h>
namespace VHACD {
//! Vector dim 3.
template <typename T>
class Vec3 {
public:
T& operator[](size_t i) { return m_data[i]; }
const T& operator[](size_t i) const { return m_data[i]; }
T& X();
T& Y();
T& Z();
const T& X() const;
const T& Y() const;
const T& Z() const;
void Normalize();
T GetNorm() const;
void operator=(const Vec3& rhs);
void operator+=(const Vec3& rhs);
void operator-=(const Vec3& rhs);
void operator-=(T a);
void operator+=(T a);
void operator/=(T a);
void operator*=(T a);
Vec3 operator^(const Vec3& rhs) const;
T operator*(const Vec3& rhs) const;
Vec3 operator+(const Vec3& rhs) const;
Vec3 operator-(const Vec3& rhs) const;
Vec3 operator-() const;
Vec3 operator*(T rhs) const;
Vec3 operator/(T rhs) const;
bool operator<(const Vec3& rhs) const;
bool operator>(const Vec3& rhs) const;
Vec3();
Vec3(T a);
Vec3(T x, T y, T z);
Vec3(const Vec3& rhs);
/*virtual*/ ~Vec3(void);
private:
T m_data[3];
};
//! Vector dim 2.
template <typename T>
class Vec2 {
public:
T& operator[](size_t i) { return m_data[i]; }
const T& operator[](size_t i) const { return m_data[i]; }
T& X();
T& Y();
const T& X() const;
const T& Y() const;
void Normalize();
T GetNorm() const;
void operator=(const Vec2& rhs);
void operator+=(const Vec2& rhs);
void operator-=(const Vec2& rhs);
void operator-=(T a);
void operator+=(T a);
void operator/=(T a);
void operator*=(T a);
T operator^(const Vec2& rhs) const;
T operator*(const Vec2& rhs) const;
Vec2 operator+(const Vec2& rhs) const;
Vec2 operator-(const Vec2& rhs) const;
Vec2 operator-() const;
Vec2 operator*(T rhs) const;
Vec2 operator/(T rhs) const;
Vec2();
Vec2(T a);
Vec2(T x, T y);
Vec2(const Vec2& rhs);
/*virtual*/ ~Vec2(void);
private:
T m_data[2];
};
template <typename T>
const bool Colinear(const Vec3<T>& a, const Vec3<T>& b, const Vec3<T>& c);
template <typename T>
const T ComputeVolume4(const Vec3<T>& a, const Vec3<T>& b, const Vec3<T>& c, const Vec3<T>& d);
}
#include "vhacdVector.inl" // template implementation
#endif

View File

@@ -0,0 +1,362 @@
#pragma once
#ifndef VHACD_VECTOR_INL
#define VHACD_VECTOR_INL
namespace VHACD
{
template <typename T>
inline Vec3<T> operator*(T lhs, const Vec3<T> & rhs)
{
return Vec3<T>(lhs * rhs.X(), lhs * rhs.Y(), lhs * rhs.Z());
}
template <typename T>
inline T & Vec3<T>::X()
{
return m_data[0];
}
template <typename T>
inline T & Vec3<T>::Y()
{
return m_data[1];
}
template <typename T>
inline T & Vec3<T>::Z()
{
return m_data[2];
}
template <typename T>
inline const T & Vec3<T>::X() const
{
return m_data[0];
}
template <typename T>
inline const T & Vec3<T>::Y() const
{
return m_data[1];
}
template <typename T>
inline const T & Vec3<T>::Z() const
{
return m_data[2];
}
template <typename T>
inline void Vec3<T>::Normalize()
{
T n = sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]+m_data[2]*m_data[2]);
if (n != 0.0) (*this) /= n;
}
template <typename T>
inline T Vec3<T>::GetNorm() const
{
return sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]+m_data[2]*m_data[2]);
}
template <typename T>
inline void Vec3<T>::operator= (const Vec3 & rhs)
{
this->m_data[0] = rhs.m_data[0];
this->m_data[1] = rhs.m_data[1];
this->m_data[2] = rhs.m_data[2];
}
template <typename T>
inline void Vec3<T>::operator+=(const Vec3 & rhs)
{
this->m_data[0] += rhs.m_data[0];
this->m_data[1] += rhs.m_data[1];
this->m_data[2] += rhs.m_data[2];
}
template <typename T>
inline void Vec3<T>::operator-=(const Vec3 & rhs)
{
this->m_data[0] -= rhs.m_data[0];
this->m_data[1] -= rhs.m_data[1];
this->m_data[2] -= rhs.m_data[2];
}
template <typename T>
inline void Vec3<T>::operator-=(T a)
{
this->m_data[0] -= a;
this->m_data[1] -= a;
this->m_data[2] -= a;
}
template <typename T>
inline void Vec3<T>::operator+=(T a)
{
this->m_data[0] += a;
this->m_data[1] += a;
this->m_data[2] += a;
}
template <typename T>
inline void Vec3<T>::operator/=(T a)
{
this->m_data[0] /= a;
this->m_data[1] /= a;
this->m_data[2] /= a;
}
template <typename T>
inline void Vec3<T>::operator*=(T a)
{
this->m_data[0] *= a;
this->m_data[1] *= a;
this->m_data[2] *= a;
}
template <typename T>
inline Vec3<T> Vec3<T>::operator^ (const Vec3<T> & rhs) const
{
return Vec3<T>(m_data[1] * rhs.m_data[2] - m_data[2] * rhs.m_data[1],
m_data[2] * rhs.m_data[0] - m_data[0] * rhs.m_data[2],
m_data[0] * rhs.m_data[1] - m_data[1] * rhs.m_data[0]);
}
template <typename T>
inline T Vec3<T>::operator*(const Vec3<T> & rhs) const
{
return (m_data[0] * rhs.m_data[0] + m_data[1] * rhs.m_data[1] + m_data[2] * rhs.m_data[2]);
}
template <typename T>
inline Vec3<T> Vec3<T>::operator+(const Vec3<T> & rhs) const
{
return Vec3<T>(m_data[0] + rhs.m_data[0],m_data[1] + rhs.m_data[1],m_data[2] + rhs.m_data[2]);
}
template <typename T>
inline Vec3<T> Vec3<T>::operator-(const Vec3<T> & rhs) const
{
return Vec3<T>(m_data[0] - rhs.m_data[0],m_data[1] - rhs.m_data[1],m_data[2] - rhs.m_data[2]) ;
}
template <typename T>
inline Vec3<T> Vec3<T>::operator-() const
{
return Vec3<T>(-m_data[0],-m_data[1],-m_data[2]) ;
}
template <typename T>
inline Vec3<T> Vec3<T>::operator*(T rhs) const
{
return Vec3<T>(rhs * this->m_data[0], rhs * this->m_data[1], rhs * this->m_data[2]);
}
template <typename T>
inline Vec3<T> Vec3<T>::operator/ (T rhs) const
{
return Vec3<T>(m_data[0] / rhs, m_data[1] / rhs, m_data[2] / rhs);
}
template <typename T>
inline Vec3<T>::Vec3(T a)
{
m_data[0] = m_data[1] = m_data[2] = a;
}
template <typename T>
inline Vec3<T>::Vec3(T x, T y, T z)
{
m_data[0] = x;
m_data[1] = y;
m_data[2] = z;
}
template <typename T>
inline Vec3<T>::Vec3(const Vec3 & rhs)
{
m_data[0] = rhs.m_data[0];
m_data[1] = rhs.m_data[1];
m_data[2] = rhs.m_data[2];
}
template <typename T>
inline Vec3<T>::~Vec3(void){};
template <typename T>
inline Vec3<T>::Vec3() {}
template<typename T>
inline const bool Colinear(const Vec3<T> & a, const Vec3<T> & b, const Vec3<T> & c)
{
return ((c.Z() - a.Z()) * (b.Y() - a.Y()) - (b.Z() - a.Z()) * (c.Y() - a.Y()) == 0.0 /*EPS*/) &&
((b.Z() - a.Z()) * (c.X() - a.X()) - (b.X() - a.X()) * (c.Z() - a.Z()) == 0.0 /*EPS*/) &&
((b.X() - a.X()) * (c.Y() - a.Y()) - (b.Y() - a.Y()) * (c.X() - a.X()) == 0.0 /*EPS*/);
}
template<typename T>
inline const T ComputeVolume4(const Vec3<T> & a, const Vec3<T> & b, const Vec3<T> & c, const Vec3<T> & d)
{
return (a-d) * ((b-d) ^ (c-d));
}
template <typename T>
inline bool Vec3<T>::operator<(const Vec3 & rhs) const
{
if (X() == rhs[0])
{
if (Y() == rhs[1])
{
return (Z()<rhs[2]);
}
return (Y()<rhs[1]);
}
return (X()<rhs[0]);
}
template <typename T>
inline bool Vec3<T>::operator>(const Vec3 & rhs) const
{
if (X() == rhs[0])
{
if (Y() == rhs[1])
{
return (Z()>rhs[2]);
}
return (Y()>rhs[1]);
}
return (X()>rhs[0]);
}
template <typename T>
inline Vec2<T> operator*(T lhs, const Vec2<T> & rhs)
{
return Vec2<T>(lhs * rhs.X(), lhs * rhs.Y());
}
template <typename T>
inline T & Vec2<T>::X()
{
return m_data[0];
}
template <typename T>
inline T & Vec2<T>::Y()
{
return m_data[1];
}
template <typename T>
inline const T & Vec2<T>::X() const
{
return m_data[0];
}
template <typename T>
inline const T & Vec2<T>::Y() const
{
return m_data[1];
}
template <typename T>
inline void Vec2<T>::Normalize()
{
T n = sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]);
if (n != 0.0) (*this) /= n;
}
template <typename T>
inline T Vec2<T>::GetNorm() const
{
return sqrt(m_data[0]*m_data[0]+m_data[1]*m_data[1]);
}
template <typename T>
inline void Vec2<T>::operator= (const Vec2 & rhs)
{
this->m_data[0] = rhs.m_data[0];
this->m_data[1] = rhs.m_data[1];
}
template <typename T>
inline void Vec2<T>::operator+=(const Vec2 & rhs)
{
this->m_data[0] += rhs.m_data[0];
this->m_data[1] += rhs.m_data[1];
}
template <typename T>
inline void Vec2<T>::operator-=(const Vec2 & rhs)
{
this->m_data[0] -= rhs.m_data[0];
this->m_data[1] -= rhs.m_data[1];
}
template <typename T>
inline void Vec2<T>::operator-=(T a)
{
this->m_data[0] -= a;
this->m_data[1] -= a;
}
template <typename T>
inline void Vec2<T>::operator+=(T a)
{
this->m_data[0] += a;
this->m_data[1] += a;
}
template <typename T>
inline void Vec2<T>::operator/=(T a)
{
this->m_data[0] /= a;
this->m_data[1] /= a;
}
template <typename T>
inline void Vec2<T>::operator*=(T a)
{
this->m_data[0] *= a;
this->m_data[1] *= a;
}
template <typename T>
inline T Vec2<T>::operator^ (const Vec2<T> & rhs) const
{
return m_data[0] * rhs.m_data[1] - m_data[1] * rhs.m_data[0];
}
template <typename T>
inline T Vec2<T>::operator*(const Vec2<T> & rhs) const
{
return (m_data[0] * rhs.m_data[0] + m_data[1] * rhs.m_data[1]);
}
template <typename T>
inline Vec2<T> Vec2<T>::operator+(const Vec2<T> & rhs) const
{
return Vec2<T>(m_data[0] + rhs.m_data[0],m_data[1] + rhs.m_data[1]);
}
template <typename T>
inline Vec2<T> Vec2<T>::operator-(const Vec2<T> & rhs) const
{
return Vec2<T>(m_data[0] - rhs.m_data[0],m_data[1] - rhs.m_data[1]);
}
template <typename T>
inline Vec2<T> Vec2<T>::operator-() const
{
return Vec2<T>(-m_data[0],-m_data[1]) ;
}
template <typename T>
inline Vec2<T> Vec2<T>::operator*(T rhs) const
{
return Vec2<T>(rhs * this->m_data[0], rhs * this->m_data[1]);
}
template <typename T>
inline Vec2<T> Vec2<T>::operator/ (T rhs) const
{
return Vec2<T>(m_data[0] / rhs, m_data[1] / rhs);
}
template <typename T>
inline Vec2<T>::Vec2(T a)
{
m_data[0] = m_data[1] = a;
}
template <typename T>
inline Vec2<T>::Vec2(T x, T y)
{
m_data[0] = x;
m_data[1] = y;
}
template <typename T>
inline Vec2<T>::Vec2(const Vec2 & rhs)
{
m_data[0] = rhs.m_data[0];
m_data[1] = rhs.m_data[1];
}
template <typename T>
inline Vec2<T>::~Vec2(void){};
template <typename T>
inline Vec2<T>::Vec2() {}
/*
InsideTriangle decides if a point P is Inside of the triangle
defined by A, B, C.
*/
template<typename T>
inline const bool InsideTriangle(const Vec2<T> & a, const Vec2<T> & b, const Vec2<T> & c, const Vec2<T> & p)
{
T ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
T cCROSSap, bCROSScp, aCROSSbp;
ax = c.X() - b.X(); ay = c.Y() - b.Y();
bx = a.X() - c.X(); by = a.Y() - c.Y();
cx = b.X() - a.X(); cy = b.Y() - a.Y();
apx= p.X() - a.X(); apy= p.Y() - a.Y();
bpx= p.X() - b.X(); bpy= p.Y() - b.Y();
cpx= p.X() - c.X(); cpy= p.Y() - c.Y();
aCROSSbp = ax*bpy - ay*bpx;
cCROSSap = cx*apy - cy*apx;
bCROSScp = bx*cpy - by*cpx;
return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0));
}
}
#endif //VHACD_VECTOR_INL

View File

@@ -0,0 +1,419 @@
/* 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_VOLUME_H
#define VHACD_VOLUME_H
#include "vhacdMesh.h"
#include "vhacdVector.h"
#include <assert.h>
namespace VHACD {
enum VOXEL_VALUE {
PRIMITIVE_UNDEFINED = 0,
PRIMITIVE_OUTSIDE_SURFACE = 1,
PRIMITIVE_INSIDE_SURFACE = 2,
PRIMITIVE_ON_SURFACE = 3
};
struct Voxel {
public:
short m_coord[3];
short m_data;
};
class PrimitiveSet {
public:
virtual ~PrimitiveSet(){};
virtual PrimitiveSet* Create() const = 0;
virtual const size_t GetNPrimitives() const = 0;
virtual const size_t GetNPrimitivesOnSurf() const = 0;
virtual const size_t GetNPrimitivesInsideSurf() const = 0;
virtual const double GetEigenValue(AXIS axis) const = 0;
virtual const double ComputeMaxVolumeError() const = 0;
virtual const double ComputeVolume() const = 0;
virtual void Clip(const Plane& plane, PrimitiveSet* const positivePart,
PrimitiveSet* const negativePart) const = 0;
virtual void Intersect(const Plane& plane, SArray<Vec3<double> >* const positivePts,
SArray<Vec3<double> >* const negativePts, const size_t sampling) const = 0;
virtual void ComputeExteriorPoints(const Plane& plane, const Mesh& mesh,
SArray<Vec3<double> >* const exteriorPts) const = 0;
virtual void ComputeClippedVolumes(const Plane& plane, double& positiveVolume,
double& negativeVolume) const = 0;
virtual void SelectOnSurface(PrimitiveSet* const onSurfP) const = 0;
virtual void ComputeConvexHull(Mesh& meshCH, const size_t sampling = 1) const = 0;
virtual void ComputeBB() = 0;
virtual void ComputePrincipalAxes() = 0;
virtual void AlignToPrincipalAxes() = 0;
virtual void RevertAlignToPrincipalAxes() = 0;
virtual void Convert(Mesh& mesh, const VOXEL_VALUE value) const = 0;
const Mesh& GetConvexHull() const { return m_convexHull; };
Mesh& GetConvexHull() { return m_convexHull; };
private:
Mesh m_convexHull;
};
//!
class VoxelSet : public PrimitiveSet {
friend class Volume;
public:
//! Destructor.
~VoxelSet(void);
//! Constructor.
VoxelSet();
const size_t GetNPrimitives() const { return m_voxels.Size(); }
const size_t GetNPrimitivesOnSurf() const { return m_numVoxelsOnSurface; }
const size_t GetNPrimitivesInsideSurf() const { return m_numVoxelsInsideSurface; }
const double GetEigenValue(AXIS axis) const { return m_D[axis][axis]; }
const double ComputeVolume() const { return m_unitVolume * m_voxels.Size(); }
const double ComputeMaxVolumeError() const { return m_unitVolume * m_numVoxelsOnSurface; }
const Vec3<short>& GetMinBBVoxels() const { return m_minBBVoxels; }
const Vec3<short>& GetMaxBBVoxels() const { return m_maxBBVoxels; }
const Vec3<double>& GetMinBB() const { return m_minBB; }
const double& GetScale() const { return m_scale; }
const double& GetUnitVolume() const { return m_unitVolume; }
Vec3<double> GetPoint(Vec3<short> voxel) const
{
return Vec3<double>(voxel[0] * m_scale + m_minBB[0],
voxel[1] * m_scale + m_minBB[1],
voxel[2] * m_scale + m_minBB[2]);
}
Vec3<double> GetPoint(const Voxel& voxel) const
{
return Vec3<double>(voxel.m_coord[0] * m_scale + m_minBB[0],
voxel.m_coord[1] * m_scale + m_minBB[1],
voxel.m_coord[2] * m_scale + m_minBB[2]);
}
Vec3<double> GetPoint(Vec3<double> voxel) const
{
return Vec3<double>(voxel[0] * m_scale + m_minBB[0],
voxel[1] * m_scale + m_minBB[1],
voxel[2] * m_scale + m_minBB[2]);
}
void GetPoints(const Voxel& voxel, Vec3<double>* const pts) const;
void ComputeConvexHull(Mesh& meshCH, const size_t sampling = 1) const;
void Clip(const Plane& plane, PrimitiveSet* const positivePart, PrimitiveSet* const negativePart) const;
void Intersect(const Plane& plane, SArray<Vec3<double> >* const positivePts,
SArray<Vec3<double> >* const negativePts, const size_t sampling) const;
void ComputeExteriorPoints(const Plane& plane, const Mesh& mesh,
SArray<Vec3<double> >* const exteriorPts) const;
void ComputeClippedVolumes(const Plane& plane, double& positiveVolume, double& negativeVolume) const;
void SelectOnSurface(PrimitiveSet* const onSurfP) const;
void ComputeBB();
void Convert(Mesh& mesh, const VOXEL_VALUE value) const;
void ComputePrincipalAxes();
PrimitiveSet* Create() const
{
return new VoxelSet();
}
void AlignToPrincipalAxes(){};
void RevertAlignToPrincipalAxes(){};
Voxel* const GetVoxels() { return m_voxels.Data(); }
const Voxel* const GetVoxels() const { return m_voxels.Data(); }
private:
size_t m_numVoxelsOnSurface;
size_t m_numVoxelsInsideSurface;
Vec3<double> m_minBB;
double m_scale;
SArray<Voxel, 8> m_voxels;
double m_unitVolume;
Vec3<double> m_minBBPts;
Vec3<double> m_maxBBPts;
Vec3<short> m_minBBVoxels;
Vec3<short> m_maxBBVoxels;
Vec3<short> m_barycenter;
double m_Q[3][3];
double m_D[3][3];
Vec3<double> m_barycenterPCA;
};
struct Tetrahedron {
public:
Vec3<double> m_pts[4];
unsigned char m_data;
};
//!
class TetrahedronSet : public PrimitiveSet {
friend class Volume;
public:
//! Destructor.
~TetrahedronSet(void);
//! Constructor.
TetrahedronSet();
const size_t GetNPrimitives() const { return m_tetrahedra.Size(); }
const size_t GetNPrimitivesOnSurf() const { return m_numTetrahedraOnSurface; }
const size_t GetNPrimitivesInsideSurf() const { return m_numTetrahedraInsideSurface; }
const Vec3<double>& GetMinBB() const { return m_minBB; }
const Vec3<double>& GetMaxBB() const { return m_maxBB; }
const Vec3<double>& GetBarycenter() const { return m_barycenter; }
const double GetEigenValue(AXIS axis) const { return m_D[axis][axis]; }
const double GetSacle() const { return m_scale; }
const double ComputeVolume() const;
const double ComputeMaxVolumeError() const;
void ComputeConvexHull(Mesh& meshCH, const size_t sampling = 1) const;
void ComputePrincipalAxes();
void AlignToPrincipalAxes();
void RevertAlignToPrincipalAxes();
void Clip(const Plane& plane, PrimitiveSet* const positivePart, PrimitiveSet* const negativePart) const;
void Intersect(const Plane& plane, SArray<Vec3<double> >* const positivePts,
SArray<Vec3<double> >* const negativePts, const size_t sampling) const;
void ComputeExteriorPoints(const Plane& plane, const Mesh& mesh,
SArray<Vec3<double> >* const exteriorPts) const;
void ComputeClippedVolumes(const Plane& plane, double& positiveVolume, double& negativeVolume) const;
void SelectOnSurface(PrimitiveSet* const onSurfP) const;
void ComputeBB();
void Convert(Mesh& mesh, const VOXEL_VALUE value) const;
inline bool Add(Tetrahedron& tetrahedron);
PrimitiveSet* Create() const
{
return new TetrahedronSet();
}
static const double EPS;
private:
void AddClippedTetrahedra(const Vec3<double> (&pts)[10], const int nPts);
size_t m_numTetrahedraOnSurface;
size_t m_numTetrahedraInsideSurface;
double m_scale;
Vec3<double> m_minBB;
Vec3<double> m_maxBB;
Vec3<double> m_barycenter;
SArray<Tetrahedron, 8> m_tetrahedra;
double m_Q[3][3];
double m_D[3][3];
};
//!
class Volume {
public:
//! Destructor.
~Volume(void);
//! Constructor.
Volume();
//! Voxelize
template <class T>
void Voxelize(const T* const points, const unsigned int stridePoints, const unsigned int nPoints,
const int* const triangles, const unsigned int strideTriangles, const unsigned int nTriangles,
const size_t dim, const Vec3<double>& barycenter, const double (&rot)[3][3]);
unsigned char& GetVoxel(const size_t i, const size_t j, const size_t k)
{
assert(i < m_dim[0] || i >= 0);
assert(j < m_dim[0] || j >= 0);
assert(k < m_dim[0] || k >= 0);
return m_data[i + j * m_dim[0] + k * m_dim[0] * m_dim[1]];
}
const unsigned char& GetVoxel(const size_t i, const size_t j, const size_t k) const
{
assert(i < m_dim[0] || i >= 0);
assert(j < m_dim[0] || j >= 0);
assert(k < m_dim[0] || k >= 0);
return m_data[i + j * m_dim[0] + k * m_dim[0] * m_dim[1]];
}
const size_t GetNPrimitivesOnSurf() const { return m_numVoxelsOnSurface; }
const size_t GetNPrimitivesInsideSurf() const { return m_numVoxelsInsideSurface; }
void Convert(Mesh& mesh, const VOXEL_VALUE value) const;
void Convert(VoxelSet& vset) const;
void Convert(TetrahedronSet& tset) const;
void AlignToPrincipalAxes(double (&rot)[3][3]) const;
private:
void FillOutsideSurface(const size_t i0, const size_t j0, const size_t k0, const size_t i1,
const size_t j1, const size_t k1);
void FillInsideSurface();
template <class T>
void ComputeBB(const T* const points, const unsigned int stridePoints, const unsigned int nPoints,
const Vec3<double>& barycenter, const double (&rot)[3][3]);
void Allocate();
void Free();
Vec3<double> m_minBB;
Vec3<double> m_maxBB;
double m_scale;
size_t m_dim[3]; //>! dim
size_t m_numVoxelsOnSurface;
size_t m_numVoxelsInsideSurface;
size_t m_numVoxelsOutsideSurface;
unsigned char* m_data;
};
int TriBoxOverlap(const Vec3<double>& boxcenter, const Vec3<double>& boxhalfsize, const Vec3<double>& triver0,
const Vec3<double>& triver1, const Vec3<double>& triver2);
template <class T>
inline void ComputeAlignedPoint(const T* const points, const unsigned int idx, const Vec3<double>& barycenter,
const double (&rot)[3][3], Vec3<double>& pt){};
template <>
inline void ComputeAlignedPoint<float>(const float* const points, const unsigned int idx, const Vec3<double>& barycenter, const double (&rot)[3][3], Vec3<double>& pt)
{
double x = points[idx + 0] - barycenter[0];
double y = points[idx + 1] - barycenter[1];
double z = points[idx + 2] - barycenter[2];
pt[0] = rot[0][0] * x + rot[1][0] * y + rot[2][0] * z;
pt[1] = rot[0][1] * x + rot[1][1] * y + rot[2][1] * z;
pt[2] = rot[0][2] * x + rot[1][2] * y + rot[2][2] * z;
}
template <>
inline void ComputeAlignedPoint<double>(const double* const points, const unsigned int idx, const Vec3<double>& barycenter, const double (&rot)[3][3], Vec3<double>& pt)
{
double x = points[idx + 0] - barycenter[0];
double y = points[idx + 1] - barycenter[1];
double z = points[idx + 2] - barycenter[2];
pt[0] = rot[0][0] * x + rot[1][0] * y + rot[2][0] * z;
pt[1] = rot[0][1] * x + rot[1][1] * y + rot[2][1] * z;
pt[2] = rot[0][2] * x + rot[1][2] * y + rot[2][2] * z;
}
template <class T>
void Volume::ComputeBB(const T* const points, const unsigned int stridePoints, const unsigned int nPoints,
const Vec3<double>& barycenter, const double (&rot)[3][3])
{
Vec3<double> pt;
ComputeAlignedPoint(points, 0, barycenter, rot, pt);
m_maxBB = pt;
m_minBB = pt;
for (unsigned int v = 1; v < nPoints; ++v) {
ComputeAlignedPoint(points, v * stridePoints, barycenter, rot, pt);
for (int i = 0; i < 3; ++i) {
if (pt[i] < m_minBB[i])
m_minBB[i] = pt[i];
else if (pt[i] > m_maxBB[i])
m_maxBB[i] = pt[i];
}
}
}
template <class T>
void Volume::Voxelize(const T* const points, const unsigned int stridePoints, const unsigned int nPoints,
const int* const triangles, const unsigned int strideTriangles, const unsigned int nTriangles,
const size_t dim, const Vec3<double>& barycenter, const double (&rot)[3][3])
{
if (nPoints == 0) {
return;
}
ComputeBB(points, stridePoints, nPoints, barycenter, rot);
double d[3] = { m_maxBB[0] - m_minBB[0], m_maxBB[1] - m_minBB[1], m_maxBB[2] - m_minBB[2] };
double r;
if (d[0] > d[1] && d[0] > d[2]) {
r = d[0];
m_dim[0] = dim;
m_dim[1] = 2 + static_cast<size_t>(dim * d[1] / d[0]);
m_dim[2] = 2 + static_cast<size_t>(dim * d[2] / d[0]);
}
else if (d[1] > d[0] && d[1] > d[2]) {
r = d[1];
m_dim[1] = dim;
m_dim[0] = 2 + static_cast<size_t>(dim * d[0] / d[1]);
m_dim[2] = 2 + static_cast<size_t>(dim * d[2] / d[1]);
}
else {
r = d[2];
m_dim[2] = dim;
m_dim[0] = 2 + static_cast<size_t>(dim * d[0] / d[2]);
m_dim[1] = 2 + static_cast<size_t>(dim * d[1] / d[2]);
}
m_scale = r / (dim - 1);
double invScale = (dim - 1) / r;
Allocate();
m_numVoxelsOnSurface = 0;
m_numVoxelsInsideSurface = 0;
m_numVoxelsOutsideSurface = 0;
Vec3<double> p[3];
size_t i, j, k;
size_t i0, j0, k0;
size_t i1, j1, k1;
Vec3<double> boxcenter;
Vec3<double> pt;
const Vec3<double> boxhalfsize(0.5, 0.5, 0.5);
for (size_t t = 0, ti = 0; t < nTriangles; ++t, ti += strideTriangles) {
Vec3<int> tri(triangles[ti + 0],
triangles[ti + 1],
triangles[ti + 2]);
for (int c = 0; c < 3; ++c) {
ComputeAlignedPoint(points, tri[c] * stridePoints, barycenter, rot, pt);
p[c][0] = (pt[0] - m_minBB[0]) * invScale;
p[c][1] = (pt[1] - m_minBB[1]) * invScale;
p[c][2] = (pt[2] - m_minBB[2]) * invScale;
i = static_cast<size_t>(p[c][0] + 0.5);
j = static_cast<size_t>(p[c][1] + 0.5);
k = static_cast<size_t>(p[c][2] + 0.5);
assert(i < m_dim[0] && i >= 0 && j < m_dim[1] && j >= 0 && k < m_dim[2] && k >= 0);
if (c == 0) {
i0 = i1 = i;
j0 = j1 = j;
k0 = k1 = k;
}
else {
if (i < i0)
i0 = i;
if (j < j0)
j0 = j;
if (k < k0)
k0 = k;
if (i > i1)
i1 = i;
if (j > j1)
j1 = j;
if (k > k1)
k1 = k;
}
}
if (i0 > 0)
--i0;
if (j0 > 0)
--j0;
if (k0 > 0)
--k0;
if (i1 < m_dim[0])
++i1;
if (j1 < m_dim[1])
++j1;
if (k1 < m_dim[2])
++k1;
for (size_t i = i0; i < i1; ++i) {
boxcenter[0] = (double)i;
for (size_t j = j0; j < j1; ++j) {
boxcenter[1] = (double)j;
for (size_t k = k0; k < k1; ++k) {
boxcenter[2] = (double)k;
int res = TriBoxOverlap(boxcenter, boxhalfsize, p[0], p[1], p[2]);
unsigned char& value = GetVoxel(i, j, k);
if (res == 1 && value == PRIMITIVE_UNDEFINED) {
value = PRIMITIVE_ON_SURFACE;
++m_numVoxelsOnSurface;
}
}
}
}
}
FillOutsideSurface(0, 0, 0, m_dim[0], m_dim[1], 1);
FillOutsideSurface(0, 0, m_dim[2] - 1, m_dim[0], m_dim[1], m_dim[2]);
FillOutsideSurface(0, 0, 0, m_dim[0], 1, m_dim[2]);
FillOutsideSurface(0, m_dim[1] - 1, 0, m_dim[0], m_dim[1], m_dim[2]);
FillOutsideSurface(0, 0, 0, 1, m_dim[1], m_dim[2]);
FillOutsideSurface(m_dim[0] - 1, 0, 0, m_dim[0], m_dim[1], m_dim[2]);
FillInsideSurface();
}
}
#endif // VHACD_VOLUME_H

View File

@@ -0,0 +1,4 @@
include "src"
include "test/src"

121
Extras/VHACD/public/VHACD.h Normal file
View File

@@ -0,0 +1,121 @@
/* 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
#define VHACD_VERSION_MAJOR 2
#define VHACD_VERSION_MINOR 2
namespace VHACD {
class IVHACD {
public:
class IUserCallback {
public:
virtual ~IUserCallback(){};
virtual void Update(const double overallProgress,
const double stageProgress,
const double operationProgress,
const char* const stage,
const char* const operation)
= 0;
};
class IUserLogger {
public:
virtual ~IUserLogger(){};
virtual void Log(const char* const msg) = 0;
};
class ConvexHull {
public:
double* m_points;
int* m_triangles;
unsigned int m_nPoints;
unsigned int m_nTriangles;
};
class Parameters {
public:
Parameters(void) { Init(); }
void Init(void)
{
m_resolution = 1000000;
m_depth = 20;
m_concavity = 0.001;
m_planeDownsampling = 4;
m_convexhullDownsampling = 4;
m_alpha = 0.05;
m_beta = 0.05;
m_gamma = 0.0005;
m_pca = 0;
m_mode = 0; // 0: voxel-based (recommended), 1: tetrahedron-based
m_maxNumVerticesPerCH = 64;
m_minVolumePerCH = 0.0001;
m_callback = 0;
m_logger = 0;
m_convexhullApproximation = true;
m_oclAcceleration = true;
}
double m_concavity;
double m_alpha;
double m_beta;
double m_gamma;
double m_minVolumePerCH;
IUserCallback* m_callback;
IUserLogger* m_logger;
unsigned int m_resolution;
unsigned int m_maxNumVerticesPerCH;
int m_depth;
int m_planeDownsampling;
int m_convexhullDownsampling;
int m_pca;
int m_mode;
int m_convexhullApproximation;
int m_oclAcceleration;
};
virtual void Cancel() = 0;
virtual bool Compute(const float* const points,
const unsigned int stridePoints,
const unsigned int countPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int countTriangles,
const Parameters& params)
= 0;
virtual bool Compute(const double* const points,
const unsigned int stridePoints,
const unsigned int countPoints,
const int* const triangles,
const unsigned int strideTriangles,
const unsigned int countTriangles,
const Parameters& params)
= 0;
virtual unsigned int GetNConvexHulls() const = 0;
virtual void GetConvexHull(const unsigned int index, ConvexHull& ch) const = 0;
virtual void Clean(void) = 0; // release internally allocated memory
virtual void Release(void) = 0; // release IVHACD
virtual bool OCLInit(void* const oclDevice,
IUserLogger* const logger = 0)
= 0;
virtual bool OCLRelease(IUserLogger* const logger = 0) = 0;
protected:
virtual ~IVHACD(void) {}
};
IVHACD* CreateVHACD(void);
}
#endif // VHACD_H

1433
Extras/VHACD/src/VHACD.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,176 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btAlignedAllocator.h"
int gNumAlignedAllocs = 0;
int gNumAlignedFree = 0;
int gTotalBytesAlignedAllocs = 0; //detect memory leaks
static void* btAllocDefault(size_t size)
{
return malloc(size);
}
static void btFreeDefault(void* ptr)
{
free(ptr);
}
static btAllocFunc* sAllocFunc = btAllocDefault;
static btFreeFunc* sFreeFunc = btFreeDefault;
#if defined(BT_HAS_ALIGNED_ALLOCATOR)
#include <malloc.h>
static void* btAlignedAllocDefault(size_t size, int alignment)
{
return _aligned_malloc(size, (size_t)alignment);
}
static void btAlignedFreeDefault(void* ptr)
{
_aligned_free(ptr);
}
#elif defined(__CELLOS_LV2__)
#include <stdlib.h>
static inline void* btAlignedAllocDefault(size_t size, int alignment)
{
return memalign(alignment, size);
}
static inline void btAlignedFreeDefault(void* ptr)
{
free(ptr);
}
#else
static inline void* btAlignedAllocDefault(size_t size, int alignment)
{
void* ret;
char* real;
unsigned long offset;
real = (char*)sAllocFunc(size + sizeof(void*) + (alignment - 1));
if (real) {
offset = (alignment - (unsigned long)(real + sizeof(void*))) & (alignment - 1);
ret = (void*)((real + sizeof(void*)) + offset);
*((void**)(ret)-1) = (void*)(real);
}
else {
ret = (void*)(real);
}
return (ret);
}
static inline void btAlignedFreeDefault(void* ptr)
{
void* real;
if (ptr) {
real = *((void**)(ptr)-1);
sFreeFunc(real);
}
}
#endif
static btAlignedAllocFunc* sAlignedAllocFunc = btAlignedAllocDefault;
static btAlignedFreeFunc* sAlignedFreeFunc = btAlignedFreeDefault;
void btAlignedAllocSetCustomAligned(btAlignedAllocFunc* allocFunc, btAlignedFreeFunc* freeFunc)
{
sAlignedAllocFunc = allocFunc ? allocFunc : btAlignedAllocDefault;
sAlignedFreeFunc = freeFunc ? freeFunc : btAlignedFreeDefault;
}
void btAlignedAllocSetCustom(btAllocFunc* allocFunc, btFreeFunc* freeFunc)
{
sAllocFunc = allocFunc ? allocFunc : btAllocDefault;
sFreeFunc = freeFunc ? freeFunc : btFreeDefault;
}
#ifdef BT_DEBUG_MEMORY_ALLOCATIONS
//this generic allocator provides the total allocated number of bytes
#include <stdio.h>
void* btAlignedAllocInternal(size_t size, int alignment, int line, char* filename)
{
void* ret;
char* real;
unsigned long offset;
gTotalBytesAlignedAllocs += size;
gNumAlignedAllocs++;
real = (char*)sAllocFunc(size + 2 * sizeof(void*) + (alignment - 1));
if (real) {
offset = (alignment - (unsigned long)(real + 2 * sizeof(void*))) & (alignment - 1);
ret = (void*)((real + 2 * sizeof(void*)) + offset);
*((void**)(ret)-1) = (void*)(real);
*((int*)(ret)-2) = size;
}
else {
ret = (void*)(real); //??
}
printf("allocation#%d at address %x, from %s,line %d, size %d\n", gNumAlignedAllocs, real, filename, line, size);
int* ptr = (int*)ret;
*ptr = 12;
return (ret);
}
void btAlignedFreeInternal(void* ptr, int line, char* filename)
{
void* real;
gNumAlignedFree++;
if (ptr) {
real = *((void**)(ptr)-1);
int size = *((int*)(ptr)-2);
gTotalBytesAlignedAllocs -= size;
printf("free #%d at address %x, from %s,line %d, size %d\n", gNumAlignedFree, real, filename, line, size);
sFreeFunc(real);
}
else {
printf("NULL ptr\n");
}
}
#else //BT_DEBUG_MEMORY_ALLOCATIONS
void* btAlignedAllocInternal(size_t size, int alignment)
{
gNumAlignedAllocs++;
void* ptr;
ptr = sAlignedAllocFunc(size, alignment);
// printf("btAlignedAllocInternal %d, %x\n",size,ptr);
return ptr;
}
void btAlignedFreeInternal(void* ptr)
{
if (!ptr) {
return;
}
gNumAlignedFree++;
// printf("btAlignedFreeInternal %x\n",ptr);
sAlignedFreeFunc(ptr);
}
#endif //BT_DEBUG_MEMORY_ALLOCATIONS

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
project "vhacd"
kind "StaticLib"
includedirs {
"../inc","../public",
}
files {
"*.cpp",
"*.h"
}

View File

@@ -0,0 +1,725 @@
/* 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.
*/
#include "vhacdICHull.h"
#include <limits>
namespace VHACD {
const double ICHull::sc_eps = 1.0e-15;
const int ICHull::sc_dummyIndex = std::numeric_limits<int>::max();
ICHull::ICHull()
{
m_isFlat = false;
}
bool ICHull::AddPoints(const Vec3<double>* points, size_t nPoints)
{
if (!points) {
return false;
}
CircularListElement<TMMVertex>* vertex = NULL;
for (size_t i = 0; i < nPoints; i++) {
vertex = m_mesh.AddVertex();
vertex->GetData().m_pos.X() = points[i].X();
vertex->GetData().m_pos.Y() = points[i].Y();
vertex->GetData().m_pos.Z() = points[i].Z();
vertex->GetData().m_name = static_cast<int>(i);
}
return true;
}
bool ICHull::AddPoint(const Vec3<double>& point, int id)
{
if (AddPoints(&point, 1)) {
m_mesh.m_vertices.GetData().m_name = id;
return true;
}
return false;
}
ICHullError ICHull::Process()
{
unsigned int addedPoints = 0;
if (m_mesh.GetNVertices() < 3) {
return ICHullErrorNotEnoughPoints;
}
if (m_mesh.GetNVertices() == 3) {
m_isFlat = true;
CircularListElement<TMMTriangle>* t1 = m_mesh.AddTriangle();
CircularListElement<TMMTriangle>* t2 = m_mesh.AddTriangle();
CircularListElement<TMMVertex>* v0 = m_mesh.m_vertices.GetHead();
CircularListElement<TMMVertex>* v1 = v0->GetNext();
CircularListElement<TMMVertex>* v2 = v1->GetNext();
// Compute the normal to the plane
Vec3<double> p0 = v0->GetData().m_pos;
Vec3<double> p1 = v1->GetData().m_pos;
Vec3<double> p2 = v2->GetData().m_pos;
m_normal = (p1 - p0) ^ (p2 - p0);
m_normal.Normalize();
t1->GetData().m_vertices[0] = v0;
t1->GetData().m_vertices[1] = v1;
t1->GetData().m_vertices[2] = v2;
t2->GetData().m_vertices[0] = v1;
t2->GetData().m_vertices[1] = v2;
t2->GetData().m_vertices[2] = v2;
return ICHullErrorOK;
}
if (m_isFlat) {
m_mesh.m_edges.Clear();
m_mesh.m_triangles.Clear();
m_isFlat = false;
}
if (m_mesh.GetNTriangles() == 0) // we have to create the first polyhedron
{
ICHullError res = DoubleTriangle();
if (res != ICHullErrorOK) {
return res;
}
else {
addedPoints += 3;
}
}
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
// go to the first added and not processed vertex
while (!(vertices.GetHead()->GetPrev()->GetData().m_tag)) {
vertices.Prev();
}
while (!vertices.GetData().m_tag) // not processed
{
vertices.GetData().m_tag = true;
if (ProcessPoint()) {
addedPoints++;
CleanUp(addedPoints);
vertices.Next();
if (!GetMesh().CheckConsistancy()) {
size_t nV = m_mesh.GetNVertices();
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
for (size_t v = 0; v < nV; ++v) {
if (vertices.GetData().m_name == sc_dummyIndex) {
vertices.Delete();
break;
}
vertices.Next();
}
return ICHullErrorInconsistent;
}
}
}
if (m_isFlat) {
SArray<CircularListElement<TMMTriangle>*> trianglesToDuplicate;
size_t nT = m_mesh.GetNTriangles();
for (size_t f = 0; f < nT; f++) {
TMMTriangle& currentTriangle = m_mesh.m_triangles.GetHead()->GetData();
if (currentTriangle.m_vertices[0]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[1]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[2]->GetData().m_name == sc_dummyIndex) {
m_trianglesToDelete.PushBack(m_mesh.m_triangles.GetHead());
for (int k = 0; k < 3; k++) {
for (int h = 0; h < 2; h++) {
if (currentTriangle.m_edges[k]->GetData().m_triangles[h] == m_mesh.m_triangles.GetHead()) {
currentTriangle.m_edges[k]->GetData().m_triangles[h] = 0;
break;
}
}
}
}
else {
trianglesToDuplicate.PushBack(m_mesh.m_triangles.GetHead());
}
m_mesh.m_triangles.Next();
}
size_t nE = m_mesh.GetNEdges();
for (size_t e = 0; e < nE; e++) {
TMMEdge& currentEdge = m_mesh.m_edges.GetHead()->GetData();
if (currentEdge.m_triangles[0] == 0 && currentEdge.m_triangles[1] == 0) {
m_edgesToDelete.PushBack(m_mesh.m_edges.GetHead());
}
m_mesh.m_edges.Next();
}
size_t nV = m_mesh.GetNVertices();
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
for (size_t v = 0; v < nV; ++v) {
if (vertices.GetData().m_name == sc_dummyIndex) {
vertices.Delete();
}
else {
vertices.GetData().m_tag = false;
vertices.Next();
}
}
CleanEdges();
CleanTriangles();
CircularListElement<TMMTriangle>* newTriangle;
for (size_t t = 0; t < trianglesToDuplicate.Size(); t++) {
newTriangle = m_mesh.AddTriangle();
newTriangle->GetData().m_vertices[0] = trianglesToDuplicate[t]->GetData().m_vertices[1];
newTriangle->GetData().m_vertices[1] = trianglesToDuplicate[t]->GetData().m_vertices[0];
newTriangle->GetData().m_vertices[2] = trianglesToDuplicate[t]->GetData().m_vertices[2];
}
}
return ICHullErrorOK;
}
ICHullError ICHull::Process(const unsigned int nPointsCH,
const double minVolume)
{
unsigned int addedPoints = 0;
if (nPointsCH < 3 || m_mesh.GetNVertices() < 3) {
return ICHullErrorNotEnoughPoints;
}
if (m_mesh.GetNVertices() == 3) {
m_isFlat = true;
CircularListElement<TMMTriangle>* t1 = m_mesh.AddTriangle();
CircularListElement<TMMTriangle>* t2 = m_mesh.AddTriangle();
CircularListElement<TMMVertex>* v0 = m_mesh.m_vertices.GetHead();
CircularListElement<TMMVertex>* v1 = v0->GetNext();
CircularListElement<TMMVertex>* v2 = v1->GetNext();
// Compute the normal to the plane
Vec3<double> p0 = v0->GetData().m_pos;
Vec3<double> p1 = v1->GetData().m_pos;
Vec3<double> p2 = v2->GetData().m_pos;
m_normal = (p1 - p0) ^ (p2 - p0);
m_normal.Normalize();
t1->GetData().m_vertices[0] = v0;
t1->GetData().m_vertices[1] = v1;
t1->GetData().m_vertices[2] = v2;
t2->GetData().m_vertices[0] = v1;
t2->GetData().m_vertices[1] = v0;
t2->GetData().m_vertices[2] = v2;
return ICHullErrorOK;
}
if (m_isFlat) {
m_mesh.m_triangles.Clear();
m_mesh.m_edges.Clear();
m_isFlat = false;
}
if (m_mesh.GetNTriangles() == 0) // we have to create the first polyhedron
{
ICHullError res = DoubleTriangle();
if (res != ICHullErrorOK) {
return res;
}
else {
addedPoints += 3;
}
}
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
while (!vertices.GetData().m_tag && addedPoints < nPointsCH) // not processed
{
if (!FindMaxVolumePoint((addedPoints > 4) ? minVolume : 0.0)) {
break;
}
vertices.GetData().m_tag = true;
if (ProcessPoint()) {
addedPoints++;
CleanUp(addedPoints);
if (!GetMesh().CheckConsistancy()) {
size_t nV = m_mesh.GetNVertices();
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
for (size_t v = 0; v < nV; ++v) {
if (vertices.GetData().m_name == sc_dummyIndex) {
vertices.Delete();
break;
}
vertices.Next();
}
return ICHullErrorInconsistent;
}
vertices.Next();
}
}
// delete remaining points
while (!vertices.GetData().m_tag) {
vertices.Delete();
}
if (m_isFlat) {
SArray<CircularListElement<TMMTriangle>*> trianglesToDuplicate;
size_t nT = m_mesh.GetNTriangles();
for (size_t f = 0; f < nT; f++) {
TMMTriangle& currentTriangle = m_mesh.m_triangles.GetHead()->GetData();
if (currentTriangle.m_vertices[0]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[1]->GetData().m_name == sc_dummyIndex || currentTriangle.m_vertices[2]->GetData().m_name == sc_dummyIndex) {
m_trianglesToDelete.PushBack(m_mesh.m_triangles.GetHead());
for (int k = 0; k < 3; k++) {
for (int h = 0; h < 2; h++) {
if (currentTriangle.m_edges[k]->GetData().m_triangles[h] == m_mesh.m_triangles.GetHead()) {
currentTriangle.m_edges[k]->GetData().m_triangles[h] = 0;
break;
}
}
}
}
else {
trianglesToDuplicate.PushBack(m_mesh.m_triangles.GetHead());
}
m_mesh.m_triangles.Next();
}
size_t nE = m_mesh.GetNEdges();
for (size_t e = 0; e < nE; e++) {
TMMEdge& currentEdge = m_mesh.m_edges.GetHead()->GetData();
if (currentEdge.m_triangles[0] == 0 && currentEdge.m_triangles[1] == 0) {
m_edgesToDelete.PushBack(m_mesh.m_edges.GetHead());
}
m_mesh.m_edges.Next();
}
size_t nV = m_mesh.GetNVertices();
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
for (size_t v = 0; v < nV; ++v) {
if (vertices.GetData().m_name == sc_dummyIndex) {
vertices.Delete();
}
else {
vertices.GetData().m_tag = false;
vertices.Next();
}
}
CleanEdges();
CleanTriangles();
CircularListElement<TMMTriangle>* newTriangle;
for (size_t t = 0; t < trianglesToDuplicate.Size(); t++) {
newTriangle = m_mesh.AddTriangle();
newTriangle->GetData().m_vertices[0] = trianglesToDuplicate[t]->GetData().m_vertices[1];
newTriangle->GetData().m_vertices[1] = trianglesToDuplicate[t]->GetData().m_vertices[0];
newTriangle->GetData().m_vertices[2] = trianglesToDuplicate[t]->GetData().m_vertices[2];
}
}
return ICHullErrorOK;
}
bool ICHull::FindMaxVolumePoint(const double minVolume)
{
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
CircularListElement<TMMVertex>* vMaxVolume = 0;
CircularListElement<TMMVertex>* vHeadPrev = vertices.GetHead()->GetPrev();
double maxVolume = minVolume;
double volume = 0.0;
while (!vertices.GetData().m_tag) // not processed
{
if (ComputePointVolume(volume, false)) {
if (maxVolume < volume) {
maxVolume = volume;
vMaxVolume = vertices.GetHead();
}
vertices.Next();
}
}
CircularListElement<TMMVertex>* vHead = vHeadPrev->GetNext();
vertices.GetHead() = vHead;
if (!vMaxVolume) {
return false;
}
if (vMaxVolume != vHead) {
Vec3<double> pos = vHead->GetData().m_pos;
int id = vHead->GetData().m_name;
vHead->GetData().m_pos = vMaxVolume->GetData().m_pos;
vHead->GetData().m_name = vMaxVolume->GetData().m_name;
vMaxVolume->GetData().m_pos = pos;
vHead->GetData().m_name = id;
}
return true;
}
ICHullError ICHull::DoubleTriangle()
{
// find three non colinear points
m_isFlat = false;
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
CircularListElement<TMMVertex>* v0 = vertices.GetHead();
while (Colinear(v0->GetData().m_pos,
v0->GetNext()->GetData().m_pos,
v0->GetNext()->GetNext()->GetData().m_pos)) {
if ((v0 = v0->GetNext()) == vertices.GetHead()) {
return ICHullErrorCoplanarPoints;
}
}
CircularListElement<TMMVertex>* v1 = v0->GetNext();
CircularListElement<TMMVertex>* v2 = v1->GetNext();
// mark points as processed
v0->GetData().m_tag = v1->GetData().m_tag = v2->GetData().m_tag = true;
// create two triangles
CircularListElement<TMMTriangle>* f0 = MakeFace(v0, v1, v2, 0);
MakeFace(v2, v1, v0, f0);
// find a fourth non-coplanar point to form tetrahedron
CircularListElement<TMMVertex>* v3 = v2->GetNext();
vertices.GetHead() = v3;
double vol = ComputeVolume4(v0->GetData().m_pos, v1->GetData().m_pos, v2->GetData().m_pos, v3->GetData().m_pos);
while (fabs(vol) < sc_eps && !v3->GetNext()->GetData().m_tag) {
v3 = v3->GetNext();
vol = ComputeVolume4(v0->GetData().m_pos, v1->GetData().m_pos, v2->GetData().m_pos, v3->GetData().m_pos);
}
if (fabs(vol) < sc_eps) {
// compute the barycenter
Vec3<double> bary(0.0, 0.0, 0.0);
CircularListElement<TMMVertex>* vBary = v0;
do {
bary += vBary->GetData().m_pos;
} while ((vBary = vBary->GetNext()) != v0);
bary /= static_cast<double>(vertices.GetSize());
// Compute the normal to the plane
Vec3<double> p0 = v0->GetData().m_pos;
Vec3<double> p1 = v1->GetData().m_pos;
Vec3<double> p2 = v2->GetData().m_pos;
m_normal = (p1 - p0) ^ (p2 - p0);
m_normal.Normalize();
// add dummy vertex placed at (bary + normal)
vertices.GetHead() = v2;
Vec3<double> newPt = bary + m_normal;
AddPoint(newPt, sc_dummyIndex);
m_isFlat = true;
return ICHullErrorOK;
}
else if (v3 != vertices.GetHead()) {
TMMVertex temp;
temp.m_name = v3->GetData().m_name;
temp.m_pos = v3->GetData().m_pos;
v3->GetData().m_name = vertices.GetHead()->GetData().m_name;
v3->GetData().m_pos = vertices.GetHead()->GetData().m_pos;
vertices.GetHead()->GetData().m_name = temp.m_name;
vertices.GetHead()->GetData().m_pos = temp.m_pos;
}
return ICHullErrorOK;
}
CircularListElement<TMMTriangle>* ICHull::MakeFace(CircularListElement<TMMVertex>* v0,
CircularListElement<TMMVertex>* v1,
CircularListElement<TMMVertex>* v2,
CircularListElement<TMMTriangle>* fold)
{
CircularListElement<TMMEdge>* e0;
CircularListElement<TMMEdge>* e1;
CircularListElement<TMMEdge>* e2;
int index = 0;
if (!fold) // if first face to be created
{
e0 = m_mesh.AddEdge(); // create the three edges
e1 = m_mesh.AddEdge();
e2 = m_mesh.AddEdge();
}
else // otherwise re-use existing edges (in reverse order)
{
e0 = fold->GetData().m_edges[2];
e1 = fold->GetData().m_edges[1];
e2 = fold->GetData().m_edges[0];
index = 1;
}
e0->GetData().m_vertices[0] = v0;
e0->GetData().m_vertices[1] = v1;
e1->GetData().m_vertices[0] = v1;
e1->GetData().m_vertices[1] = v2;
e2->GetData().m_vertices[0] = v2;
e2->GetData().m_vertices[1] = v0;
// create the new face
CircularListElement<TMMTriangle>* f = m_mesh.AddTriangle();
f->GetData().m_edges[0] = e0;
f->GetData().m_edges[1] = e1;
f->GetData().m_edges[2] = e2;
f->GetData().m_vertices[0] = v0;
f->GetData().m_vertices[1] = v1;
f->GetData().m_vertices[2] = v2;
// link edges to face f
e0->GetData().m_triangles[index] = e1->GetData().m_triangles[index] = e2->GetData().m_triangles[index] = f;
return f;
}
CircularListElement<TMMTriangle>* ICHull::MakeConeFace(CircularListElement<TMMEdge>* e, CircularListElement<TMMVertex>* p)
{
// create two new edges if they don't already exist
CircularListElement<TMMEdge>* newEdges[2];
for (int i = 0; i < 2; ++i) {
if (!(newEdges[i] = e->GetData().m_vertices[i]->GetData().m_duplicate)) { // if the edge doesn't exits add it and mark the vertex as duplicated
newEdges[i] = m_mesh.AddEdge();
newEdges[i]->GetData().m_vertices[0] = e->GetData().m_vertices[i];
newEdges[i]->GetData().m_vertices[1] = p;
e->GetData().m_vertices[i]->GetData().m_duplicate = newEdges[i];
}
}
// make the new face
CircularListElement<TMMTriangle>* newFace = m_mesh.AddTriangle();
newFace->GetData().m_edges[0] = e;
newFace->GetData().m_edges[1] = newEdges[0];
newFace->GetData().m_edges[2] = newEdges[1];
MakeCCW(newFace, e, p);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
if (!newEdges[i]->GetData().m_triangles[j]) {
newEdges[i]->GetData().m_triangles[j] = newFace;
break;
}
}
}
return newFace;
}
bool ICHull::ComputePointVolume(double& totalVolume, bool markVisibleFaces)
{
// mark visible faces
CircularListElement<TMMTriangle>* fHead = m_mesh.GetTriangles().GetHead();
CircularListElement<TMMTriangle>* f = fHead;
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
CircularListElement<TMMVertex>* vertex0 = vertices.GetHead();
bool visible = false;
Vec3<double> pos0 = Vec3<double>(vertex0->GetData().m_pos.X(),
vertex0->GetData().m_pos.Y(),
vertex0->GetData().m_pos.Z());
double vol = 0.0;
totalVolume = 0.0;
Vec3<double> ver0, ver1, ver2;
do {
ver0.X() = f->GetData().m_vertices[0]->GetData().m_pos.X();
ver0.Y() = f->GetData().m_vertices[0]->GetData().m_pos.Y();
ver0.Z() = f->GetData().m_vertices[0]->GetData().m_pos.Z();
ver1.X() = f->GetData().m_vertices[1]->GetData().m_pos.X();
ver1.Y() = f->GetData().m_vertices[1]->GetData().m_pos.Y();
ver1.Z() = f->GetData().m_vertices[1]->GetData().m_pos.Z();
ver2.X() = f->GetData().m_vertices[2]->GetData().m_pos.X();
ver2.Y() = f->GetData().m_vertices[2]->GetData().m_pos.Y();
ver2.Z() = f->GetData().m_vertices[2]->GetData().m_pos.Z();
vol = ComputeVolume4(ver0, ver1, ver2, pos0);
if (vol < -sc_eps) {
vol = fabs(vol);
totalVolume += vol;
if (markVisibleFaces) {
f->GetData().m_visible = true;
m_trianglesToDelete.PushBack(f);
}
visible = true;
}
f = f->GetNext();
} while (f != fHead);
if (m_trianglesToDelete.Size() == m_mesh.m_triangles.GetSize()) {
for (size_t i = 0; i < m_trianglesToDelete.Size(); i++) {
m_trianglesToDelete[i]->GetData().m_visible = false;
}
visible = false;
}
// if no faces visible from p then p is inside the hull
if (!visible && markVisibleFaces) {
vertices.Delete();
m_trianglesToDelete.Resize(0);
return false;
}
return true;
}
bool ICHull::ProcessPoint()
{
double totalVolume = 0.0;
if (!ComputePointVolume(totalVolume, true)) {
return false;
}
// Mark edges in interior of visible region for deletion.
// Create a new face based on each border edge
CircularListElement<TMMVertex>* v0 = m_mesh.GetVertices().GetHead();
CircularListElement<TMMEdge>* eHead = m_mesh.GetEdges().GetHead();
CircularListElement<TMMEdge>* e = eHead;
CircularListElement<TMMEdge>* tmp = 0;
int nvisible = 0;
m_edgesToDelete.Resize(0);
m_edgesToUpdate.Resize(0);
do {
tmp = e->GetNext();
nvisible = 0;
for (int k = 0; k < 2; k++) {
if (e->GetData().m_triangles[k]->GetData().m_visible) {
nvisible++;
}
}
if (nvisible == 2) {
m_edgesToDelete.PushBack(e);
}
else if (nvisible == 1) {
e->GetData().m_newFace = MakeConeFace(e, v0);
m_edgesToUpdate.PushBack(e);
}
e = tmp;
} while (e != eHead);
return true;
}
bool ICHull::MakeCCW(CircularListElement<TMMTriangle>* f,
CircularListElement<TMMEdge>* e,
CircularListElement<TMMVertex>* v)
{
// the visible face adjacent to e
CircularListElement<TMMTriangle>* fv;
if (e->GetData().m_triangles[0]->GetData().m_visible) {
fv = e->GetData().m_triangles[0];
}
else {
fv = e->GetData().m_triangles[1];
}
// set vertex[0] and vertex[1] to have the same orientation as the corresponding vertices of fv.
int i; // index of e->m_vertices[0] in fv
CircularListElement<TMMVertex>* v0 = e->GetData().m_vertices[0];
CircularListElement<TMMVertex>* v1 = e->GetData().m_vertices[1];
for (i = 0; fv->GetData().m_vertices[i] != v0; i++)
;
if (fv->GetData().m_vertices[(i + 1) % 3] != e->GetData().m_vertices[1]) {
f->GetData().m_vertices[0] = v1;
f->GetData().m_vertices[1] = v0;
}
else {
f->GetData().m_vertices[0] = v0;
f->GetData().m_vertices[1] = v1;
// swap edges
CircularListElement<TMMEdge>* tmp = f->GetData().m_edges[0];
f->GetData().m_edges[0] = f->GetData().m_edges[1];
f->GetData().m_edges[1] = tmp;
}
f->GetData().m_vertices[2] = v;
return true;
}
bool ICHull::CleanUp(unsigned int& addedPoints)
{
bool r0 = CleanEdges();
bool r1 = CleanTriangles();
bool r2 = CleanVertices(addedPoints);
return r0 && r1 && r2;
}
bool ICHull::CleanEdges()
{
// integrate the new faces into the data structure
CircularListElement<TMMEdge>* e;
const size_t ne_update = m_edgesToUpdate.Size();
for (size_t i = 0; i < ne_update; ++i) {
e = m_edgesToUpdate[i];
if (e->GetData().m_newFace) {
if (e->GetData().m_triangles[0]->GetData().m_visible) {
e->GetData().m_triangles[0] = e->GetData().m_newFace;
}
else {
e->GetData().m_triangles[1] = e->GetData().m_newFace;
}
e->GetData().m_newFace = 0;
}
}
// delete edges maked for deletion
CircularList<TMMEdge>& edges = m_mesh.GetEdges();
const size_t ne_delete = m_edgesToDelete.Size();
for (size_t i = 0; i < ne_delete; ++i) {
edges.Delete(m_edgesToDelete[i]);
}
m_edgesToDelete.Resize(0);
m_edgesToUpdate.Resize(0);
return true;
}
bool ICHull::CleanTriangles()
{
CircularList<TMMTriangle>& triangles = m_mesh.GetTriangles();
const size_t nt_delete = m_trianglesToDelete.Size();
for (size_t i = 0; i < nt_delete; ++i) {
triangles.Delete(m_trianglesToDelete[i]);
}
m_trianglesToDelete.Resize(0);
return true;
}
bool ICHull::CleanVertices(unsigned int& addedPoints)
{
// mark all vertices incident to some undeleted edge as on the hull
CircularList<TMMEdge>& edges = m_mesh.GetEdges();
CircularListElement<TMMEdge>* e = edges.GetHead();
size_t nE = edges.GetSize();
for (size_t i = 0; i < nE; i++) {
e->GetData().m_vertices[0]->GetData().m_onHull = true;
e->GetData().m_vertices[1]->GetData().m_onHull = true;
e = e->GetNext();
}
// delete all the vertices that have been processed but are not on the hull
CircularList<TMMVertex>& vertices = m_mesh.GetVertices();
CircularListElement<TMMVertex>* vHead = vertices.GetHead();
CircularListElement<TMMVertex>* v = vHead;
v = v->GetPrev();
do {
if (v->GetData().m_tag && !v->GetData().m_onHull) {
CircularListElement<TMMVertex>* tmp = v->GetPrev();
vertices.Delete(v);
v = tmp;
addedPoints--;
}
else {
v->GetData().m_duplicate = 0;
v->GetData().m_onHull = false;
v = v->GetPrev();
}
} while (v->GetData().m_tag && v != vHead);
return true;
}
void ICHull::Clear()
{
m_mesh.Clear();
m_edgesToDelete.Resize(0);
m_edgesToUpdate.Resize(0);
m_trianglesToDelete.Resize(0);
m_isFlat = false;
}
const ICHull& ICHull::operator=(ICHull& rhs)
{
if (&rhs != this) {
m_mesh.Copy(rhs.m_mesh);
m_edgesToDelete = rhs.m_edgesToDelete;
m_edgesToUpdate = rhs.m_edgesToUpdate;
m_trianglesToDelete = rhs.m_trianglesToDelete;
m_isFlat = rhs.m_isFlat;
}
return (*this);
}
bool ICHull::IsInside(const Vec3<double>& pt0, const double eps)
{
const Vec3<double> pt(pt0.X(), pt0.Y(), pt0.Z());
if (m_isFlat) {
size_t nT = m_mesh.m_triangles.GetSize();
Vec3<double> ver0, ver1, ver2, a, b, c;
double u, v;
for (size_t t = 0; t < nT; t++) {
ver0.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.X();
ver0.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Y();
ver0.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Z();
ver1.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.X();
ver1.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Y();
ver1.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Z();
ver2.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.X();
ver2.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Y();
ver2.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Z();
a = ver1 - ver0;
b = ver2 - ver0;
c = pt - ver0;
u = c * a;
v = c * b;
if (u >= 0.0 && u <= 1.0 && v >= 0.0 && u + v <= 1.0) {
return true;
}
m_mesh.m_triangles.Next();
}
return false;
}
else {
size_t nT = m_mesh.m_triangles.GetSize();
Vec3<double> ver0, ver1, ver2;
double vol;
for (size_t t = 0; t < nT; t++) {
ver0.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.X();
ver0.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Y();
ver0.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[0]->GetData().m_pos.Z();
ver1.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.X();
ver1.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Y();
ver1.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[1]->GetData().m_pos.Z();
ver2.X() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.X();
ver2.Y() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Y();
ver2.Z() = m_mesh.m_triangles.GetHead()->GetData().m_vertices[2]->GetData().m_pos.Z();
vol = ComputeVolume4(ver0, ver1, ver2, pt);
if (vol < eps) {
return false;
}
m_mesh.m_triangles.Next();
}
return true;
}
}
}

View File

@@ -0,0 +1,202 @@
/* 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.
*/
#include "vhacdManifoldMesh.h"
namespace VHACD {
TMMVertex::TMMVertex(void)
{
Initialize();
}
void TMMVertex::Initialize()
{
m_name = 0;
m_id = 0;
m_duplicate = 0;
m_onHull = false;
m_tag = false;
}
TMMVertex::~TMMVertex(void)
{
}
TMMEdge::TMMEdge(void)
{
Initialize();
}
void TMMEdge::Initialize()
{
m_id = 0;
m_triangles[0] = m_triangles[1] = m_newFace = 0;
m_vertices[0] = m_vertices[1] = 0;
}
TMMEdge::~TMMEdge(void)
{
}
void TMMTriangle::Initialize()
{
m_id = 0;
for (int i = 0; i < 3; i++) {
m_edges[i] = 0;
m_vertices[0] = 0;
}
m_visible = false;
}
TMMTriangle::TMMTriangle(void)
{
Initialize();
}
TMMTriangle::~TMMTriangle(void)
{
}
TMMesh::TMMesh()
{
}
TMMesh::~TMMesh(void)
{
}
void TMMesh::GetIFS(Vec3<double>* const points, Vec3<int>* const triangles)
{
size_t nV = m_vertices.GetSize();
size_t nT = m_triangles.GetSize();
for (size_t v = 0; v < nV; v++) {
points[v] = m_vertices.GetData().m_pos;
m_vertices.GetData().m_id = v;
m_vertices.Next();
}
for (size_t f = 0; f < nT; f++) {
TMMTriangle& currentTriangle = m_triangles.GetData();
triangles[f].X() = static_cast<int>(currentTriangle.m_vertices[0]->GetData().m_id);
triangles[f].Y() = static_cast<int>(currentTriangle.m_vertices[1]->GetData().m_id);
triangles[f].Z() = static_cast<int>(currentTriangle.m_vertices[2]->GetData().m_id);
m_triangles.Next();
}
}
void TMMesh::Clear()
{
m_vertices.Clear();
m_edges.Clear();
m_triangles.Clear();
}
void TMMesh::Copy(TMMesh& mesh)
{
Clear();
// updating the id's
size_t nV = mesh.m_vertices.GetSize();
size_t nE = mesh.m_edges.GetSize();
size_t nT = mesh.m_triangles.GetSize();
for (size_t v = 0; v < nV; v++) {
mesh.m_vertices.GetData().m_id = v;
mesh.m_vertices.Next();
}
for (size_t e = 0; e < nE; e++) {
mesh.m_edges.GetData().m_id = e;
mesh.m_edges.Next();
}
for (size_t f = 0; f < nT; f++) {
mesh.m_triangles.GetData().m_id = f;
mesh.m_triangles.Next();
}
// copying data
m_vertices = mesh.m_vertices;
m_edges = mesh.m_edges;
m_triangles = mesh.m_triangles;
// generate mapping
CircularListElement<TMMVertex>** vertexMap = new CircularListElement<TMMVertex>*[nV];
CircularListElement<TMMEdge>** edgeMap = new CircularListElement<TMMEdge>*[nE];
CircularListElement<TMMTriangle>** triangleMap = new CircularListElement<TMMTriangle>*[nT];
for (size_t v = 0; v < nV; v++) {
vertexMap[v] = m_vertices.GetHead();
m_vertices.Next();
}
for (size_t e = 0; e < nE; e++) {
edgeMap[e] = m_edges.GetHead();
m_edges.Next();
}
for (size_t f = 0; f < nT; f++) {
triangleMap[f] = m_triangles.GetHead();
m_triangles.Next();
}
// updating pointers
for (size_t v = 0; v < nV; v++) {
if (vertexMap[v]->GetData().m_duplicate) {
vertexMap[v]->GetData().m_duplicate = edgeMap[vertexMap[v]->GetData().m_duplicate->GetData().m_id];
}
}
for (size_t e = 0; e < nE; e++) {
if (edgeMap[e]->GetData().m_newFace) {
edgeMap[e]->GetData().m_newFace = triangleMap[edgeMap[e]->GetData().m_newFace->GetData().m_id];
}
if (nT > 0) {
for (int f = 0; f < 2; f++) {
if (edgeMap[e]->GetData().m_triangles[f]) {
edgeMap[e]->GetData().m_triangles[f] = triangleMap[edgeMap[e]->GetData().m_triangles[f]->GetData().m_id];
}
}
}
for (int v = 0; v < 2; v++) {
if (edgeMap[e]->GetData().m_vertices[v]) {
edgeMap[e]->GetData().m_vertices[v] = vertexMap[edgeMap[e]->GetData().m_vertices[v]->GetData().m_id];
}
}
}
for (size_t f = 0; f < nT; f++) {
if (nE > 0) {
for (int e = 0; e < 3; e++) {
if (triangleMap[f]->GetData().m_edges[e]) {
triangleMap[f]->GetData().m_edges[e] = edgeMap[triangleMap[f]->GetData().m_edges[e]->GetData().m_id];
}
}
}
for (int v = 0; v < 3; v++) {
if (triangleMap[f]->GetData().m_vertices[v]) {
triangleMap[f]->GetData().m_vertices[v] = vertexMap[triangleMap[f]->GetData().m_vertices[v]->GetData().m_id];
}
}
}
delete[] vertexMap;
delete[] edgeMap;
delete[] triangleMap;
}
bool TMMesh::CheckConsistancy()
{
size_t nE = m_edges.GetSize();
size_t nT = m_triangles.GetSize();
for (size_t e = 0; e < nE; e++) {
for (int f = 0; f < 2; f++) {
if (!m_edges.GetHead()->GetData().m_triangles[f]) {
return false;
}
}
m_edges.Next();
}
for (size_t f = 0; f < nT; f++) {
for (int e = 0; e < 3; e++) {
int found = 0;
for (int k = 0; k < 2; k++) {
if (m_triangles.GetHead()->GetData().m_edges[e]->GetData().m_triangles[k] == m_triangles.GetHead()) {
found++;
}
}
if (found != 1) {
return false;
}
}
m_triangles.Next();
}
return true;
}
}

View File

@@ -0,0 +1,323 @@
/* 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.
*/
#define _CRT_SECURE_NO_WARNINGS
#include "btConvexHullComputer.h"
#include "vhacdMesh.h"
#include <fstream>
#include <iosfwd>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
namespace VHACD {
Mesh::Mesh()
{
m_diag = 1.0;
}
Mesh::~Mesh()
{
}
double Mesh::ComputeVolume() const
{
const size_t nV = GetNPoints();
const size_t nT = GetNTriangles();
if (nV == 0 || nT == 0) {
return 0.0;
}
Vec3<double> bary(0.0, 0.0, 0.0);
for (size_t v = 0; v < nV; v++) {
bary += GetPoint(v);
}
bary /= static_cast<double>(nV);
Vec3<double> ver0, ver1, ver2;
double totalVolume = 0.0;
for (int t = 0; t < nT; t++) {
const Vec3<int>& tri = GetTriangle(t);
ver0 = GetPoint(tri[0]);
ver1 = GetPoint(tri[1]);
ver2 = GetPoint(tri[2]);
totalVolume += ComputeVolume4(ver0, ver1, ver2, bary);
}
return totalVolume / 6.0;
}
void Mesh::ComputeConvexHull(const double* const pts,
const size_t nPts)
{
ResizePoints(0);
ResizeTriangles(0);
btConvexHullComputer ch;
ch.compute(pts, 3 * sizeof(double), (int)nPts, -1.0, -1.0);
for (int v = 0; v < ch.vertices.size(); v++) {
AddPoint(Vec3<double>(ch.vertices[v].getX(), ch.vertices[v].getY(), ch.vertices[v].getZ()));
}
const int nt = ch.faces.size();
for (int t = 0; t < nt; ++t) {
const btConvexHullComputer::Edge* sourceEdge = &(ch.edges[ch.faces[t]]);
int a = sourceEdge->getSourceVertex();
int b = sourceEdge->getTargetVertex();
const btConvexHullComputer::Edge* edge = sourceEdge->getNextEdgeOfFace();
int c = edge->getTargetVertex();
while (c != a) {
AddTriangle(Vec3<int>(a, b, c));
edge = edge->getNextEdgeOfFace();
b = c;
c = edge->getTargetVertex();
}
}
}
void Mesh::Clip(const Plane& plane,
SArray<Vec3<double> >& positivePart,
SArray<Vec3<double> >& negativePart) const
{
const size_t nV = GetNPoints();
if (nV == 0) {
return;
}
double d;
for (size_t v = 0; v < nV; v++) {
const Vec3<double>& pt = GetPoint(v);
d = plane.m_a * pt[0] + plane.m_b * pt[1] + plane.m_c * pt[2] + plane.m_d;
if (d > 0.0) {
positivePart.PushBack(pt);
}
else if (d < 0.0) {
negativePart.PushBack(pt);
}
else {
positivePart.PushBack(pt);
negativePart.PushBack(pt);
}
}
}
bool Mesh::IsInside(const Vec3<double>& pt) const
{
const size_t nV = GetNPoints();
const size_t nT = GetNTriangles();
if (nV == 0 || nT == 0) {
return false;
}
Vec3<double> ver0, ver1, ver2;
double volume;
for (int t = 0; t < nT; t++) {
const Vec3<int>& tri = GetTriangle(t);
ver0 = GetPoint(tri[0]);
ver1 = GetPoint(tri[1]);
ver2 = GetPoint(tri[2]);
volume = ComputeVolume4(ver0, ver1, ver2, pt);
if (volume < 0.0) {
return false;
}
}
return true;
}
double Mesh::ComputeDiagBB()
{
const size_t nPoints = GetNPoints();
if (nPoints == 0)
return 0.0;
Vec3<double> minBB = m_points[0];
Vec3<double> maxBB = m_points[0];
double x, y, z;
for (size_t v = 1; v < nPoints; v++) {
x = m_points[v][0];
y = m_points[v][1];
z = m_points[v][2];
if (x < minBB[0])
minBB[0] = x;
else if (x > maxBB[0])
maxBB[0] = x;
if (y < minBB[1])
minBB[1] = y;
else if (y > maxBB[1])
maxBB[1] = y;
if (z < minBB[2])
minBB[2] = z;
else if (z > maxBB[2])
maxBB[2] = z;
}
return (m_diag = (maxBB - minBB).GetNorm());
}
#ifdef VHACD_DEBUG_MESH
bool Mesh::SaveVRML2(const std::string& fileName) const
{
std::ofstream fout(fileName.c_str());
if (fout.is_open()) {
const Material material;
if (SaveVRML2(fout, material)) {
fout.close();
return true;
}
return false;
}
return false;
}
bool Mesh::SaveVRML2(std::ofstream& fout, const Material& material) const
{
if (fout.is_open()) {
fout.setf(std::ios::fixed, std::ios::floatfield);
fout.setf(std::ios::showpoint);
fout.precision(6);
size_t nV = m_points.Size();
size_t nT = m_triangles.Size();
fout << "#VRML V2.0 utf8" << std::endl;
fout << "" << std::endl;
fout << "# Vertices: " << nV << std::endl;
fout << "# Triangles: " << nT << std::endl;
fout << "" << std::endl;
fout << "Group {" << std::endl;
fout << " children [" << std::endl;
fout << " Shape {" << std::endl;
fout << " appearance Appearance {" << std::endl;
fout << " material Material {" << std::endl;
fout << " diffuseColor " << material.m_diffuseColor[0] << " "
<< material.m_diffuseColor[1] << " "
<< material.m_diffuseColor[2] << std::endl;
fout << " ambientIntensity " << material.m_ambientIntensity << std::endl;
fout << " specularColor " << material.m_specularColor[0] << " "
<< material.m_specularColor[1] << " "
<< material.m_specularColor[2] << std::endl;
fout << " emissiveColor " << material.m_emissiveColor[0] << " "
<< material.m_emissiveColor[1] << " "
<< material.m_emissiveColor[2] << std::endl;
fout << " shininess " << material.m_shininess << std::endl;
fout << " transparency " << material.m_transparency << std::endl;
fout << " }" << std::endl;
fout << " }" << std::endl;
fout << " geometry IndexedFaceSet {" << std::endl;
fout << " ccw TRUE" << std::endl;
fout << " solid TRUE" << std::endl;
fout << " convex TRUE" << std::endl;
if (nV > 0) {
fout << " coord DEF co Coordinate {" << std::endl;
fout << " point [" << std::endl;
for (size_t v = 0; v < nV; v++) {
fout << " " << m_points[v][0] << " "
<< m_points[v][1] << " "
<< m_points[v][2] << "," << std::endl;
}
fout << " ]" << std::endl;
fout << " }" << std::endl;
}
if (nT > 0) {
fout << " coordIndex [ " << std::endl;
for (size_t f = 0; f < nT; f++) {
fout << " " << m_triangles[f][0] << ", "
<< m_triangles[f][1] << ", "
<< m_triangles[f][2] << ", -1," << std::endl;
}
fout << " ]" << std::endl;
}
fout << " }" << std::endl;
fout << " }" << std::endl;
fout << " ]" << std::endl;
fout << "}" << std::endl;
return true;
}
return false;
}
bool Mesh::SaveOFF(const std::string& fileName) const
{
std::ofstream fout(fileName.c_str());
if (fout.is_open()) {
size_t nV = m_points.Size();
size_t nT = m_triangles.Size();
fout << "OFF" << std::endl;
fout << nV << " " << nT << " " << 0 << std::endl;
for (size_t v = 0; v < nV; v++) {
fout << m_points[v][0] << " "
<< m_points[v][1] << " "
<< m_points[v][2] << std::endl;
}
for (size_t f = 0; f < nT; f++) {
fout << "3 " << m_triangles[f][0] << " "
<< m_triangles[f][1] << " "
<< m_triangles[f][2] << std::endl;
}
fout.close();
return true;
}
return false;
}
bool Mesh::LoadOFF(const std::string& fileName, bool invert)
{
FILE* fid = fopen(fileName.c_str(), "r");
if (fid) {
const std::string strOFF("OFF");
char temp[1024];
fscanf(fid, "%s", temp);
if (std::string(temp) != strOFF) {
fclose(fid);
return false;
}
else {
int nv = 0;
int nf = 0;
int ne = 0;
fscanf(fid, "%i", &nv);
fscanf(fid, "%i", &nf);
fscanf(fid, "%i", &ne);
m_points.Resize(nv);
m_triangles.Resize(nf);
Vec3<double> coord;
float x, y, z;
for (int p = 0; p < nv; p++) {
fscanf(fid, "%f", &x);
fscanf(fid, "%f", &y);
fscanf(fid, "%f", &z);
m_points[p][0] = x;
m_points[p][1] = y;
m_points[p][2] = z;
}
int i, j, k, s;
for (int t = 0; t < nf; ++t) {
fscanf(fid, "%i", &s);
if (s == 3) {
fscanf(fid, "%i", &i);
fscanf(fid, "%i", &j);
fscanf(fid, "%i", &k);
m_triangles[t][0] = i;
if (invert) {
m_triangles[t][1] = k;
m_triangles[t][2] = j;
}
else {
m_triangles[t][1] = j;
m_triangles[t][2] = k;
}
}
else // Fix me: support only triangular meshes
{
for (int h = 0; h < s; ++h)
fscanf(fid, "%i", &s);
}
}
fclose(fid);
}
}
else {
return false;
}
return true;
}
#endif // VHACD_DEBUG_MESH
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,50 @@
/* 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.
*/
#ifdef OPENCL_FOUND
#pragma once
#ifndef OCL_HELPER_H
#define OCL_HELPER_H
#include <string>
#include <vector>
#ifdef __MACH__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
class OCLHelper {
public:
OCLHelper(void){};
~OCLHelper(void){};
bool InitPlatform(const unsigned int platformIndex = 0);
bool InitDevice(const unsigned int deviceIndex);
bool GetPlatformsInfo(std::vector<std::string>& info, const std::string& indentation);
bool GetDevicesInfo(std::vector<std::string>& info, const std::string& indentation);
cl_platform_id* GetPlatform() { return &m_platform; }
const cl_platform_id* GetPlatform() const { return &m_platform; }
cl_device_id* GetDevice() { return &m_device; }
const cl_device_id* GetDevice() const { return &m_device; }
private:
cl_platform_id m_platform;
cl_device_id m_device;
cl_int m_lastError;
};
#endif // OCL_HELPER_H
#endif //OPENCL_FOUND

View File

@@ -0,0 +1,648 @@
/* 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.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <assert.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
//#define _CRTDBG_MAP_ALLOC
#ifdef _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>
#endif // _CRTDBG_MAP_ALLOC
#include "VHACD.h"
using namespace VHACD;
using namespace std;
class MyCallback : public IVHACD::IUserCallback {
public:
MyCallback(void) {}
~MyCallback(){};
void Update(const double overallProgress, const double stageProgress, const double operationProgress,
const char* const stage, const char* const operation)
{
cout << setfill(' ') << setw(3) << (int)(overallProgress + 0.5) << "% "
<< "[ " << stage << " " << setfill(' ') << setw(3) << (int)(stageProgress + 0.5) << "% ] "
<< operation << " " << setfill(' ') << setw(3) << (int)(operationProgress + 0.5) << "%" << endl;
};
};
class MyLogger : public IVHACD::IUserLogger {
public:
MyLogger(void) {}
MyLogger(const string& fileName) { OpenFile(fileName); }
~MyLogger(){};
void Log(const char* const msg)
{
if (m_file.is_open()) {
m_file << msg;
m_file.flush();
}
}
void OpenFile(const string& fileName)
{
m_file.open(fileName.c_str());
}
private:
ofstream m_file;
};
struct Material {
float m_diffuseColor[3];
float m_ambientIntensity;
float m_specularColor[3];
float m_emissiveColor[3];
float m_shininess;
float m_transparency;
Material(void)
{
m_diffuseColor[0] = 0.5f;
m_diffuseColor[1] = 0.5f;
m_diffuseColor[2] = 0.5f;
m_specularColor[0] = 0.5f;
m_specularColor[1] = 0.5f;
m_specularColor[2] = 0.5f;
m_ambientIntensity = 0.4f;
m_emissiveColor[0] = 0.0f;
m_emissiveColor[1] = 0.0f;
m_emissiveColor[2] = 0.0f;
m_shininess = 0.4f;
m_transparency = 0.5f;
};
};
struct Parameters {
unsigned int m_oclPlatformID;
unsigned int m_oclDeviceID;
string m_fileNameIn;
string m_fileNameOut;
string m_fileNameLog;
bool m_run;
IVHACD::Parameters m_paramsVHACD;
Parameters(void)
{
m_run = true;
m_oclPlatformID = 0;
m_oclDeviceID = 0;
m_fileNameIn = "";
m_fileNameOut = "output.obj";
m_fileNameLog = "log.txt";
}
};
bool LoadOFF(const string& fileName, vector<float>& points, vector<int>& triangles, IVHACD::IUserLogger& logger);
bool LoadOBJ(const string& fileName, vector<float>& points, vector<int>& triangles, IVHACD::IUserLogger& logger);
bool SaveOFF(const string& fileName, const float* const& points, const int* const& triangles, const unsigned int& nPoints,
const unsigned int& nTriangles, IVHACD::IUserLogger& logger);
bool SaveOBJ(ofstream& fout, const double* const& points, const int* const& triangles, const unsigned int& nPoints,
const unsigned int& nTriangles, const Material& material, IVHACD::IUserLogger& logger, int convexPart, int vertexOffset);
bool SaveVRML2(ofstream& fout, const double* const& points, const int* const& triangles, const unsigned int& nPoints,
const unsigned int& nTriangles, const Material& material, IVHACD::IUserLogger& logger);
void GetFileExtension(const string& fileName, string& fileExtension);
void ComputeRandomColor(Material& mat);
void Usage(const Parameters& params);
void ParseParameters(int argc, char* argv[], Parameters& params);
int main(int argc, char* argv[])
{
// --input camel.off --output camel_acd.obj --log log.txt --resolution 1000000 --depth 20 --concavity 0.0025 --planeDownsampling 4 --convexhullDownsampling 4 --alpha 0.05 --beta 0.05 --gamma 0.00125 --pca 0 --mode 0 --maxNumVerticesPerCH 256 --minVolumePerCH 0.0001 --convexhullApproximation 1 --oclDeviceID 2
{
// set parameters
Parameters params;
ParseParameters(argc, argv, params);
MyCallback myCallback;
MyLogger myLogger(params.m_fileNameLog);
params.m_paramsVHACD.m_logger = &myLogger;
params.m_paramsVHACD.m_callback = &myCallback;
Usage(params);
if (!params.m_run) {
return 0;
}
std::ostringstream msg;
msg << "+ OpenCL (OFF)" << std::endl;
msg << "+ Parameters" << std::endl;
msg << "\t input " << params.m_fileNameIn << endl;
msg << "\t resolution " << params.m_paramsVHACD.m_resolution << endl;
msg << "\t max. depth " << params.m_paramsVHACD.m_depth << endl;
msg << "\t max. concavity " << params.m_paramsVHACD.m_concavity << endl;
msg << "\t plane down-sampling " << params.m_paramsVHACD.m_planeDownsampling << endl;
msg << "\t convex-hull down-sampling " << params.m_paramsVHACD.m_convexhullDownsampling << endl;
msg << "\t alpha " << params.m_paramsVHACD.m_alpha << endl;
msg << "\t beta " << params.m_paramsVHACD.m_beta << endl;
msg << "\t gamma " << params.m_paramsVHACD.m_gamma << endl;
msg << "\t pca " << params.m_paramsVHACD.m_pca << endl;
msg << "\t mode " << params.m_paramsVHACD.m_mode << endl;
msg << "\t max. vertices per convex-hull " << params.m_paramsVHACD.m_maxNumVerticesPerCH << endl;
msg << "\t min. volume to add vertices to convex-hulls " << params.m_paramsVHACD.m_minVolumePerCH << endl;
msg << "\t convex-hull approximation " << params.m_paramsVHACD.m_convexhullApproximation << endl;
msg << "\t OpenCL acceleration " << params.m_paramsVHACD.m_oclAcceleration << endl;
msg << "\t OpenCL platform ID " << params.m_oclPlatformID << endl;
msg << "\t OpenCL device ID " << params.m_oclDeviceID << endl;
msg << "\t output " << params.m_fileNameOut << endl;
msg << "\t log " << params.m_fileNameLog << endl;
msg << "+ Load mesh" << std::endl;
myLogger.Log(msg.str().c_str());
cout << msg.str().c_str();
// load mesh
vector<float> points;
vector<int> triangles;
string fileExtension;
GetFileExtension(params.m_fileNameIn, fileExtension);
if (fileExtension == ".OFF") {
if (!LoadOFF(params.m_fileNameIn, points, triangles, myLogger)) {
return -1;
}
}
else if (fileExtension == ".OBJ") {
if (!LoadOBJ(params.m_fileNameIn, points, triangles, myLogger)) {
return -1;
}
}
else {
myLogger.Log("Format not supported!\n");
return -1;
}
// run V-HACD
IVHACD* interfaceVHACD = CreateVHACD();
#ifdef CL_VERSION_1_1
if (params.m_paramsVHACD.m_oclAcceleration) {
bool res = interfaceVHACD->OCLInit(oclHelper.GetDevice(), &myLogger);
if (!res) {
params.m_paramsVHACD.m_oclAcceleration = false;
}
}
#endif //CL_VERSION_1_1
bool res = interfaceVHACD->Compute(&points[0], 3, (unsigned int)points.size() / 3,
&triangles[0], 3, (unsigned int)triangles.size() / 3, params.m_paramsVHACD);
if (res) {
// save output
unsigned int nConvexHulls = interfaceVHACD->GetNConvexHulls();
msg.str("");
msg << "+ Generate output: " << nConvexHulls << " convex-hulls " << endl;
myLogger.Log(msg.str().c_str());
ofstream foutCH(params.m_fileNameOut.c_str());
IVHACD::ConvexHull ch;
if (foutCH.is_open()) {
Material mat;
int vertexOffset = 1;//obj wavefront starts counting at 1...
for (unsigned int p = 0; p < nConvexHulls; ++p) {
interfaceVHACD->GetConvexHull(p, ch);
SaveOBJ(foutCH, ch.m_points, ch.m_triangles, ch.m_nPoints, ch.m_nTriangles, mat, myLogger, p, vertexOffset);
vertexOffset+=ch.m_nPoints;
msg.str("");
msg << "\t CH[" << setfill('0') << setw(5) << p << "] " << ch.m_nPoints << " V, " << ch.m_nTriangles << " T" << endl;
myLogger.Log(msg.str().c_str());
}
foutCH.close();
}
}
else {
myLogger.Log("Decomposition cancelled by user!\n");
}
#ifdef CL_VERSION_1_1
if (params.m_paramsVHACD.m_oclAcceleration) {
bool res = interfaceVHACD->OCLRelease(&myLogger);
if (!res) {
assert(-1);
}
}
#endif //CL_VERSION_1_1
interfaceVHACD->Clean();
interfaceVHACD->Release();
}
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif // _CRTDBG_MAP_ALLOC
return 0;
}
void Usage(const Parameters& params)
{
std::ostringstream msg;
msg << "V-HACD V" << VHACD_VERSION_MAJOR << "." << VHACD_VERSION_MINOR << endl;
msg << "Syntax: testVHACD [options] --input infile.obj --output outfile.obj --log logfile.txt" << endl
<< endl;
msg << "Options:" << endl;
msg << " --input Wavefront .obj input file name" << endl;
msg << " --output VRML 2.0 output file name" << endl;
msg << " --log Log file name" << endl;
msg << " --resolution Maximum number of voxels generated during the voxelization stage (default=100,000, range=10,000-16,000,000)" << endl;
msg << " --depth Maximum number of clipping stages. During each split stage, parts with a concavity higher than the user defined threshold are clipped according the \"best\" clipping plane (default=20, range=1-32)" << endl;
msg << " --concavity Maximum allowed concavity (default=0.0025, range=0.0-1.0)" << endl;
msg << " --planeDownsampling Controls the granularity of the search for the \"best\" clipping plane (default=4, range=1-16)" << endl;
msg << " --convexhullDownsampling Controls the precision of the convex-hull generation process during the clipping plane selection stage (default=4, range=1-16)" << endl;
msg << " --alpha Controls the bias toward clipping along symmetry planes (default=0.05, range=0.0-1.0)" << endl;
msg << " --beta Controls the bias toward clipping along revolution axes (default=0.05, range=0.0-1.0)" << endl;
msg << " --gamma Controls the maximum allowed concavity during the merge stage (default=0.00125, range=0.0-1.0)" << endl;
msg << " --delta Controls the bias toward maximaxing local concavity (default=0.05, range=0.0-1.0)" << endl;
msg << " --pca Enable/disable normalizing the mesh before applying the convex decomposition (default=0, range={0,1})" << endl;
msg << " --mode 0: voxel-based approximate convex decomposition, 1: tetrahedron-based approximate convex decomposition (default=0, range={0,1})" << endl;
msg << " --maxNumVerticesPerCH Controls the maximum number of triangles per convex-hull (default=64, range=4-1024)" << endl;
msg << " --minVolumePerCH Controls the adaptive sampling of the generated convex-hulls (default=0.0001, range=0.0-0.01)" << endl;
msg << " --convexhullApproximation Enable/disable approximation when computing convex-hulls (default=1, range={0,1})" << endl;
msg << " --oclAcceleration Enable/disable OpenCL acceleration (default=0, range={0,1})" << endl;
msg << " --oclPlatformID OpenCL platform id (default=0, range=0-# OCL platforms)" << endl;
msg << " --oclDeviceID OpenCL device id (default=0, range=0-# OCL devices)" << endl;
msg << " --help Print usage" << endl
<< endl;
msg << "Examples:" << endl;
msg << " testVHACD.exe --input bunny.obj --output bunny_acd.obj --log log.txt" << endl
<< endl;
cout << msg.str();
if (params.m_paramsVHACD.m_logger) {
params.m_paramsVHACD.m_logger->Log(msg.str().c_str());
}
}
void ParseParameters(int argc, char* argv[], Parameters& params)
{
for (int i = 1; i < argc; ++i) {
if (!strcmp(argv[i], "--input")) {
if (++i < argc)
params.m_fileNameIn = argv[i];
}
else if (!strcmp(argv[i], "--output")) {
if (++i < argc)
params.m_fileNameOut = argv[i];
}
else if (!strcmp(argv[i], "--log")) {
if (++i < argc)
params.m_fileNameLog = argv[i];
}
else if (!strcmp(argv[i], "--resolution")) {
if (++i < argc)
params.m_paramsVHACD.m_resolution = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--depth")) {
if (++i < argc)
params.m_paramsVHACD.m_depth = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--concavity")) {
if (++i < argc)
params.m_paramsVHACD.m_concavity = atof(argv[i]);
}
else if (!strcmp(argv[i], "--planeDownsampling")) {
if (++i < argc)
params.m_paramsVHACD.m_planeDownsampling = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--convexhullDownsampling")) {
if (++i < argc)
params.m_paramsVHACD.m_convexhullDownsampling = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--alpha")) {
if (++i < argc)
params.m_paramsVHACD.m_alpha = atof(argv[i]);
}
else if (!strcmp(argv[i], "--beta")) {
if (++i < argc)
params.m_paramsVHACD.m_beta = atof(argv[i]);
}
else if (!strcmp(argv[i], "--gamma")) {
if (++i < argc)
params.m_paramsVHACD.m_gamma = atof(argv[i]);
}
else if (!strcmp(argv[i], "--pca")) {
if (++i < argc)
params.m_paramsVHACD.m_pca = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--mode")) {
if (++i < argc)
params.m_paramsVHACD.m_mode = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--maxNumVerticesPerCH")) {
if (++i < argc)
params.m_paramsVHACD.m_maxNumVerticesPerCH = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--minVolumePerCH")) {
if (++i < argc)
params.m_paramsVHACD.m_minVolumePerCH = atof(argv[i]);
}
else if (!strcmp(argv[i], "--convexhullApproximation")) {
if (++i < argc)
params.m_paramsVHACD.m_convexhullApproximation = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--oclAcceleration")) {
if (++i < argc)
params.m_paramsVHACD.m_oclAcceleration = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--oclPlatformID")) {
if (++i < argc)
params.m_oclPlatformID = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--oclDeviceID")) {
if (++i < argc)
params.m_oclDeviceID = atoi(argv[i]);
}
else if (!strcmp(argv[i], "--help")) {
params.m_run = false;
}
}
params.m_paramsVHACD.m_resolution = (params.m_paramsVHACD.m_resolution < 64) ? 0 : params.m_paramsVHACD.m_resolution;
params.m_paramsVHACD.m_planeDownsampling = (params.m_paramsVHACD.m_planeDownsampling < 1) ? 1 : params.m_paramsVHACD.m_planeDownsampling;
params.m_paramsVHACD.m_convexhullDownsampling = (params.m_paramsVHACD.m_convexhullDownsampling < 1) ? 1 : params.m_paramsVHACD.m_convexhullDownsampling;
}
void GetFileExtension(const string& fileName, string& fileExtension)
{
size_t lastDotPosition = fileName.find_last_of(".");
if (lastDotPosition == string::npos) {
fileExtension = "";
}
else {
fileExtension = fileName.substr(lastDotPosition, fileName.size());
transform(fileExtension.begin(), fileExtension.end(), fileExtension.begin(), ::toupper);
}
}
void ComputeRandomColor(Material& mat)
{
mat.m_diffuseColor[0] = mat.m_diffuseColor[1] = mat.m_diffuseColor[2] = 0.0f;
while (mat.m_diffuseColor[0] == mat.m_diffuseColor[1] || mat.m_diffuseColor[2] == mat.m_diffuseColor[1] || mat.m_diffuseColor[2] == mat.m_diffuseColor[0]) {
mat.m_diffuseColor[0] = (rand() % 100) / 100.0f;
mat.m_diffuseColor[1] = (rand() % 100) / 100.0f;
mat.m_diffuseColor[2] = (rand() % 100) / 100.0f;
}
}
bool LoadOFF(const string& fileName, vector<float>& points, vector<int>& triangles, IVHACD::IUserLogger& logger)
{
FILE* fid = fopen(fileName.c_str(), "r");
if (fid) {
const string strOFF("OFF");
char temp[1024];
fscanf(fid, "%s", temp);
if (string(temp) != strOFF) {
logger.Log("Loading error: format not recognized \n");
fclose(fid);
return false;
}
else {
int nv = 0;
int nf = 0;
int ne = 0;
fscanf(fid, "%i", &nv);
fscanf(fid, "%i", &nf);
fscanf(fid, "%i", &ne);
points.resize(nv * 3);
triangles.resize(nf * 3);
const int np = nv * 3;
for (int p = 0; p < np; p++) {
fscanf(fid, "%f", &(points[p]));
}
int s;
for (int t = 0, r = 0; t < nf; ++t) {
fscanf(fid, "%i", &s);
if (s == 3) {
fscanf(fid, "%i", &(triangles[r++]));
fscanf(fid, "%i", &(triangles[r++]));
fscanf(fid, "%i", &(triangles[r++]));
}
else // Fix me: support only triangular meshes
{
for (int h = 0; h < s; ++h)
fscanf(fid, "%i", &s);
}
}
fclose(fid);
}
}
else {
logger.Log("Loading error: file not found \n");
return false;
}
return true;
}
bool LoadOBJ(const string& fileName, vector<float>& points, vector<int>& triangles, IVHACD::IUserLogger& logger)
{
const unsigned int BufferSize = 1024;
FILE* fid = fopen(fileName.c_str(), "r");
if (fid) {
char buffer[BufferSize];
int ip[4];
float x[3];
char* pch;
char* str;
while (!feof(fid)) {
if (!fgets(buffer, BufferSize, fid)) {
break;
}
else if (buffer[0] == 'v') {
if (buffer[1] == ' ') {
str = buffer + 2;
for (int k = 0; k < 3; ++k) {
pch = strtok(str, " ");
if (pch)
x[k] = (float)atof(pch);
else {
return false;
}
str = NULL;
}
points.push_back(x[0]);
points.push_back(x[1]);
points.push_back(x[2]);
}
}
else if (buffer[0] == 'f') {
pch = str = buffer + 2;
int k = 0;
while (pch) {
pch = strtok(str, " ");
if (pch) {
ip[k++] = atoi(pch) - 1;
}
else {
break;
}
str = NULL;
}
if (k == 3) {
triangles.push_back(ip[0]);
triangles.push_back(ip[1]);
triangles.push_back(ip[2]);
}
else if (k == 4) {
triangles.push_back(ip[0]);
triangles.push_back(ip[1]);
triangles.push_back(ip[2]);
triangles.push_back(ip[0]);
triangles.push_back(ip[2]);
triangles.push_back(ip[3]);
}
}
}
fclose(fid);
}
else {
logger.Log("File not found\n");
return false;
}
return true;
}
bool SaveOFF(const string& fileName, const float* const& points, const int* const& triangles, const unsigned int& nPoints,
const unsigned int& nTriangles, IVHACD::IUserLogger& logger)
{
ofstream fout(fileName.c_str());
if (fout.is_open()) {
size_t nV = nPoints * 3;
size_t nT = nTriangles * 3;
fout << "OFF" << std::endl;
fout << nPoints << " " << nTriangles << " " << 0 << std::endl;
for (size_t v = 0; v < nV; v += 3) {
fout << points[v + 0] << " "
<< points[v + 1] << " "
<< points[v + 2] << std::endl;
}
for (size_t f = 0; f < nT; f += 3) {
fout << "3 " << triangles[f + 0] << " "
<< triangles[f + 1] << " "
<< triangles[f + 2] << std::endl;
}
fout.close();
return true;
}
else {
logger.Log("Can't open file\n");
return false;
}
}
bool SaveOBJ(ofstream& fout, const double* const& points, const int* const& triangles, const unsigned int& nPoints,
const unsigned int& nTriangles, const Material& material, IVHACD::IUserLogger& logger, int convexPart, int vertexOffset)
{
if (fout.is_open()) {
fout.setf(std::ios::fixed, std::ios::floatfield);
fout.setf(std::ios::showpoint);
fout.precision(6);
size_t nV = nPoints * 3;
size_t nT = nTriangles * 3;
fout << "o convex_" << convexPart << std::endl;
if (nV > 0) {
for (size_t v = 0; v < nV; v += 3) {
fout << "v " << points[v + 0] << " " << points[v + 1] << " " << points[v + 2] << std::endl;
}
}
if (nT > 0) {
for (size_t f = 0; f < nT; f += 3) {
fout << "f "
<< triangles[f + 0]+vertexOffset << " "
<< triangles[f + 1]+vertexOffset << " "
<< triangles[f + 2]+vertexOffset << " " << std::endl;
}
}
return true;
}
else {
logger.Log("Can't open file\n");
return false;
}
}
bool SaveVRML2(ofstream& fout, const double* const& points, const int* const& triangles, const unsigned int& nPoints,
const unsigned int& nTriangles, const Material& material, IVHACD::IUserLogger& logger)
{
if (fout.is_open()) {
fout.setf(std::ios::fixed, std::ios::floatfield);
fout.setf(std::ios::showpoint);
fout.precision(6);
size_t nV = nPoints * 3;
size_t nT = nTriangles * 3;
fout << "#VRML V2.0 utf8" << std::endl;
fout << "" << std::endl;
fout << "# Vertices: " << nPoints << std::endl;
fout << "# Triangles: " << nTriangles << std::endl;
fout << "" << std::endl;
fout << "Group {" << std::endl;
fout << " children [" << std::endl;
fout << " Shape {" << std::endl;
fout << " appearance Appearance {" << std::endl;
fout << " material Material {" << std::endl;
fout << " diffuseColor " << material.m_diffuseColor[0] << " "
<< material.m_diffuseColor[1] << " "
<< material.m_diffuseColor[2] << std::endl;
fout << " ambientIntensity " << material.m_ambientIntensity << std::endl;
fout << " specularColor " << material.m_specularColor[0] << " "
<< material.m_specularColor[1] << " "
<< material.m_specularColor[2] << std::endl;
fout << " emissiveColor " << material.m_emissiveColor[0] << " "
<< material.m_emissiveColor[1] << " "
<< material.m_emissiveColor[2] << std::endl;
fout << " shininess " << material.m_shininess << std::endl;
fout << " transparency " << material.m_transparency << std::endl;
fout << " }" << std::endl;
fout << " }" << std::endl;
fout << " geometry IndexedFaceSet {" << std::endl;
fout << " ccw TRUE" << std::endl;
fout << " solid TRUE" << std::endl;
fout << " convex TRUE" << std::endl;
if (nV > 0) {
fout << " coord DEF co Coordinate {" << std::endl;
fout << " point [" << std::endl;
for (size_t v = 0; v < nV; v += 3) {
fout << " " << points[v + 0] << " "
<< points[v + 1] << " "
<< points[v + 2] << "," << std::endl;
}
fout << " ]" << std::endl;
fout << " }" << std::endl;
}
if (nT > 0) {
fout << " coordIndex [ " << std::endl;
for (size_t f = 0; f < nT; f += 3) {
fout << " " << triangles[f + 0] << ", "
<< triangles[f + 1] << ", "
<< triangles[f + 2] << ", -1," << std::endl;
}
fout << " ]" << std::endl;
}
fout << " }" << std::endl;
fout << " }" << std::endl;
fout << " ]" << std::endl;
fout << "}" << std::endl;
return true;
}
else {
logger.Log("Can't open file\n");
return false;
}
}

View File

@@ -0,0 +1,329 @@
/* 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.
*/
#ifdef OPENCL_FOUND
#include "oclHelper.h"
#include <assert.h>
#include <sstream>
bool OCLHelper::InitPlatform(const unsigned int platformIndex)
{
cl_uint numPlatforms;
m_lastError = clGetPlatformIDs(1, NULL, &numPlatforms);
if (m_lastError != CL_SUCCESS || platformIndex >= numPlatforms)
return false;
cl_platform_id* platforms = new cl_platform_id[numPlatforms];
m_lastError = clGetPlatformIDs(numPlatforms, platforms, NULL);
if (m_lastError != CL_SUCCESS) {
delete[] platforms;
return false;
}
m_platform = platforms[platformIndex];
delete[] platforms;
return true;
}
bool OCLHelper::GetPlatformsInfo(std::vector<std::string>& info, const std::string& indentation)
{
const char* platformInfoParameters[] = { "CL_PLATFORM_NAME",
"CL_PLATFORM_VENDOR",
"CL_PLATFORM_VERSION",
"CL_PLATFORM_PROFILE",
"CL_PLATFORM_EXTENSIONS" };
cl_uint numPlatforms;
m_lastError = clGetPlatformIDs(1, NULL, &numPlatforms);
if (m_lastError != CL_SUCCESS)
return false;
cl_platform_id* platforms = new cl_platform_id[numPlatforms];
m_lastError = clGetPlatformIDs(numPlatforms, platforms, NULL);
if (m_lastError != CL_SUCCESS) {
delete[] platforms;
return false;
}
size_t bufferSize = 4096;
char* buffer = new char[bufferSize];
size_t size;
info.resize(numPlatforms);
for (cl_uint i = 0; i < numPlatforms; ++i) {
for (int j = CL_PLATFORM_PROFILE; j <= CL_PLATFORM_EXTENSIONS; ++j) {
info[i] += indentation + platformInfoParameters[j - CL_PLATFORM_PROFILE] + std::string(": ");
m_lastError = clGetPlatformInfo(platforms[i], j, 0, NULL, &size);
if (m_lastError != CL_SUCCESS) {
delete[] buffer;
delete[] platforms;
return false;
}
if (bufferSize < size) {
delete[] buffer;
bufferSize = size;
buffer = new char[bufferSize];
}
m_lastError = clGetPlatformInfo(platforms[i], j, size, buffer, NULL);
if (m_lastError != CL_SUCCESS) {
delete[] buffer;
delete[] platforms;
return false;
}
info[i] += buffer + std::string("\n");
}
}
delete[] platforms;
delete[] buffer;
return true;
}
bool OCLHelper::InitDevice(const unsigned int deviceIndex)
{
cl_uint numDevices;
m_lastError = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices);
if (m_lastError != CL_SUCCESS || deviceIndex >= numDevices)
return false;
cl_device_id* devices = new cl_device_id[numDevices];
m_lastError = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_ALL, numDevices, devices, NULL);
if (m_lastError != CL_SUCCESS) {
delete[] devices;
return false;
}
m_device = devices[deviceIndex];
delete[] devices;
return true;
}
bool OCLHelper::GetDevicesInfo(std::vector<std::string>& info, const std::string& indentation)
{
enum {
DATA_TYPE_CL_UINT,
DATA_TYPE_CL_BOOL,
DATA_TYPE_STRING,
DATA_TYPE_CL_ULONG,
DATA_TYPE_CL_DEVICE_FP_CONFIG,
DATA_TYPE_CL_DEVICE_EXEC_CAPABILITIES,
DATA_TYPE_CL_DEVICE_MEM_CACHE_TYPE,
DATA_TYPE_CL_DEVICE_MEM_LOCAL_TYPE,
DATA_TYPE_CL_DEVICE_CMD_QUEUE_PROP,
DATA_TYPE_CL_DEVICE_TYPE,
DATA_TYPE_SIZE_T,
DATA_TYPE_SIZE_T_3,
};
typedef struct
{
cl_device_info id;
const char* name;
int type;
} DeviceInfoParam;
const int numDeviceInfoParameters = 49;
const DeviceInfoParam deviceInfoParameters[numDeviceInfoParameters] = {
{ CL_DEVICE_NAME, "CL_DEVICE_NAME", DATA_TYPE_STRING },
{ CL_DEVICE_PROFILE, "CL_DEVICE_PROFILE", DATA_TYPE_STRING },
{ CL_DEVICE_VENDOR, "CL_DEVICE_VENDOR", DATA_TYPE_STRING },
{ CL_DEVICE_VERSION, "CL_DEVICE_VERSION", DATA_TYPE_STRING },
{ CL_DRIVER_VERSION, "CL_DRIVER_VERSION", DATA_TYPE_STRING },
{ CL_DEVICE_EXTENSIONS, "CL_DEVICE_EXTENSIONS", DATA_TYPE_STRING },
{ CL_DEVICE_VERSION, "CL_DEVICE_VERSION", DATA_TYPE_STRING },
{ CL_DEVICE_ADDRESS_BITS, "CL_DEVICE_ADDRESS_BITS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, "CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_CLOCK_FREQUENCY, "CL_DEVICE_MAX_CLOCK_FREQUENCY", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_COMPUTE_UNITS, "CL_DEVICE_MAX_COMPUTE_UNITS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_CONSTANT_ARGS, "CL_DEVICE_MAX_CONSTANT_ARGS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_READ_IMAGE_ARGS, "CL_DEVICE_MAX_READ_IMAGE_ARGS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_SAMPLERS, "CL_DEVICE_MAX_SAMPLERS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MAX_WRITE_IMAGE_ARGS, "CL_DEVICE_MAX_WRITE_IMAGE_ARGS", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MEM_BASE_ADDR_ALIGN, "CL_DEVICE_MEM_BASE_ADDR_ALIGN", DATA_TYPE_CL_UINT },
{ CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE, "CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE", DATA_TYPE_CL_UINT },
{ CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, "CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR", DATA_TYPE_CL_UINT },
{ CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, "CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT", DATA_TYPE_CL_UINT },
{ CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, "CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT", DATA_TYPE_CL_UINT },
{ CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG, "CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG", DATA_TYPE_CL_UINT },
{ CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, "CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT", DATA_TYPE_CL_UINT },
{ CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, "CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE", DATA_TYPE_CL_UINT },
{ CL_DEVICE_VENDOR_ID, "CL_DEVICE_VENDOR_ID", DATA_TYPE_CL_UINT },
{ CL_DEVICE_AVAILABLE, "CL_DEVICE_AVAILABLE", DATA_TYPE_CL_BOOL },
{ CL_DEVICE_COMPILER_AVAILABLE, "CL_DEVICE_COMPILER_AVAILABLE", DATA_TYPE_CL_BOOL },
{ CL_DEVICE_ENDIAN_LITTLE, "CL_DEVICE_ENDIAN_LITTLE", DATA_TYPE_CL_BOOL },
{ CL_DEVICE_ERROR_CORRECTION_SUPPORT, "CL_DEVICE_ERROR_CORRECTION_SUPPORT", DATA_TYPE_CL_BOOL },
{ CL_DEVICE_IMAGE_SUPPORT, "CL_DEVICE_IMAGE_SUPPORT", DATA_TYPE_CL_BOOL },
{ CL_DEVICE_EXECUTION_CAPABILITIES, "CL_DEVICE_EXECUTION_CAPABILITIES", DATA_TYPE_CL_DEVICE_EXEC_CAPABILITIES },
{ CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, "CL_DEVICE_GLOBAL_MEM_CACHE_SIZE", DATA_TYPE_CL_ULONG },
{ CL_DEVICE_GLOBAL_MEM_SIZE, "CL_DEVICE_GLOBAL_MEM_SIZE", DATA_TYPE_CL_ULONG },
{ CL_DEVICE_LOCAL_MEM_SIZE, "CL_DEVICE_LOCAL_MEM_SIZE", DATA_TYPE_CL_ULONG },
{ CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, "CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE", DATA_TYPE_CL_ULONG },
{ CL_DEVICE_MAX_MEM_ALLOC_SIZE, "CL_DEVICE_MAX_MEM_ALLOC_SIZE", DATA_TYPE_CL_ULONG },
{ CL_DEVICE_GLOBAL_MEM_CACHE_TYPE, "CL_DEVICE_GLOBAL_MEM_CACHE_TYPE", DATA_TYPE_CL_DEVICE_MEM_CACHE_TYPE },
{ CL_DEVICE_IMAGE2D_MAX_HEIGHT, "CL_DEVICE_IMAGE2D_MAX_HEIGHT", DATA_TYPE_SIZE_T },
{ CL_DEVICE_IMAGE2D_MAX_WIDTH, "CL_DEVICE_IMAGE2D_MAX_WIDTH", DATA_TYPE_SIZE_T },
{ CL_DEVICE_IMAGE3D_MAX_DEPTH, "CL_DEVICE_IMAGE3D_MAX_DEPTH", DATA_TYPE_SIZE_T },
{ CL_DEVICE_IMAGE3D_MAX_HEIGHT, "CL_DEVICE_IMAGE3D_MAX_HEIGHT", DATA_TYPE_SIZE_T },
{ CL_DEVICE_IMAGE3D_MAX_WIDTH, "CL_DEVICE_IMAGE3D_MAX_WIDTH", DATA_TYPE_SIZE_T },
{ CL_DEVICE_MAX_PARAMETER_SIZE, "CL_DEVICE_MAX_PARAMETER_SIZE", DATA_TYPE_SIZE_T },
{ CL_DEVICE_MAX_WORK_GROUP_SIZE, "CL_DEVICE_MAX_WORK_GROUP_SIZE", DATA_TYPE_SIZE_T },
{ CL_DEVICE_PROFILING_TIMER_RESOLUTION, "CL_DEVICE_PROFILING_TIMER_RESOLUTION", DATA_TYPE_SIZE_T },
{ CL_DEVICE_QUEUE_PROPERTIES, "CL_DEVICE_QUEUE_PROPERTIES", DATA_TYPE_CL_DEVICE_CMD_QUEUE_PROP },
{ CL_DEVICE_TYPE, "CL_DEVICE_TYPE", DATA_TYPE_CL_DEVICE_TYPE },
{ CL_DEVICE_LOCAL_MEM_TYPE, "CL_DEVICE_LOCAL_MEM_TYPE", DATA_TYPE_CL_DEVICE_MEM_LOCAL_TYPE },
{ CL_DEVICE_MAX_WORK_ITEM_SIZES, "CL_DEVICE_MAX_WORK_ITEM_SIZES", DATA_TYPE_SIZE_T_3 }
// { CL_DEVICE_DOUBLE_FP_CONFIG, "CL_DEVICE_DOUBLE_FP_CONFIG", DATA_TYPE_CL_DEVICE_FP_CONFIG },
//
};
cl_uint numDevices;
m_lastError = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_ALL, 0, NULL, &numDevices);
if (m_lastError != CL_SUCCESS)
return false;
cl_device_id* devices = new cl_device_id[numDevices];
m_lastError = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_ALL, numDevices, devices, NULL);
if (m_lastError != CL_SUCCESS) {
delete[] devices;
return false;
}
size_t bufferSize = 4096;
char* buffer = new char[bufferSize];
size_t size;
info.resize(numDevices);
for (cl_uint i = 0; i < numDevices; ++i) {
for (int j = 0; j < numDeviceInfoParameters; ++j) {
const DeviceInfoParam& infoParam = deviceInfoParameters[j];
info[i] += indentation + infoParam.name + std::string(": ");
if (infoParam.type == DATA_TYPE_STRING) {
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, 0, NULL, &size);
if (m_lastError == CL_SUCCESS) {
if (bufferSize < size) {
delete[] buffer;
bufferSize = size;
buffer = new char[bufferSize];
}
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, size, buffer, NULL);
if (m_lastError != CL_SUCCESS) {
delete[] devices;
delete[] buffer;
return false;
}
info[i] += buffer + std::string("\n");
}
}
else if (infoParam.type == DATA_TYPE_CL_UINT) {
cl_uint value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_uint), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_BOOL) {
cl_bool value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_bool), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_ULONG) {
cl_ulong value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_ulong), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_DEVICE_FP_CONFIG) {
cl_device_fp_config value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_device_fp_config), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_DEVICE_EXEC_CAPABILITIES) {
cl_device_exec_capabilities value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_device_exec_capabilities), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_DEVICE_MEM_CACHE_TYPE) {
cl_device_mem_cache_type value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_device_mem_cache_type), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_DEVICE_MEM_LOCAL_TYPE) {
cl_device_local_mem_type value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_device_local_mem_type), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_DEVICE_CMD_QUEUE_PROP) {
cl_command_queue_properties value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_command_queue_properties), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_CL_DEVICE_TYPE) {
cl_device_type value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(cl_device_type), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_SIZE_T) {
size_t value;
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, sizeof(size_t), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << value;
info[i] += svalue.str() + "\n";
}
}
else if (infoParam.type == DATA_TYPE_SIZE_T_3) {
size_t value[3];
m_lastError = clGetDeviceInfo(devices[i], infoParam.id, 3 * sizeof(size_t), &value, &size);
if (m_lastError == CL_SUCCESS) {
std::ostringstream svalue;
svalue << "(" << value[0] << ", " << value[1] << ", " << value[2] << ")";
info[i] += svalue.str() + "\n";
}
}
else {
assert(0);
}
}
}
delete[] devices;
delete[] buffer;
return true;
}
#endif // OPENCL_FOUND

View File

@@ -0,0 +1,25 @@
project "test_vhacd"
if _OPTIONS["ios"] then
kind "WindowedApp"
else
kind "ConsoleApp"
end
includedirs {"../../public"}
links {
"vhacd"
}
language "C++"
files {
"main.cpp",
}
if os.is("Linux") then
links {"pthread"}
end

View File

@@ -1,5 +1,6 @@
include "HACD"
include "VHACD"
include "ConvexDecomposition"
include "InverseDynamics"
include "Serialize/BulletFileLoader"

13
data/duck.mtl Normal file
View File

@@ -0,0 +1,13 @@
# Blender MTL File: 'None'
# Material Count: 1
newmtl blinn3
Ns 96.078431
Ka 0.000000 0.000000 0.000000
Kd 0.640000 0.640000 0.640000
Ks 0.000000 0.000000 0.000000
Ni 1.000000
d 1.000000
illum 2
map_Ka duckCM.png
map_Kd duckCM.png

8604
data/duck.obj Normal file

File diff suppressed because it is too large Load Diff

BIN
data/duckCM.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

609
data/duck_vhacd.obj Normal file
View File

@@ -0,0 +1,609 @@
o convex_0
v -0.086018 0.502143 0.615873
v -0.225720 0.427101 -0.544625
v -0.268729 0.362660 -0.533833
v 0.623016 0.276638 -0.017993
v 0.601512 0.867587 -0.082516
v -0.601818 0.867587 0.003477
v -0.677007 0.126174 0.228965
v 0.386620 0.244455 0.476150
v 0.300756 0.137003 -0.351171
v 0.569331 0.835252 0.282696
v -0.677007 0.190691 -0.286648
v -0.709188 0.631101 0.379366
v -0.472792 0.706295 -0.383432
v 0.483314 0.577413 -0.404901
v -0.859718 0.545154 -0.050254
v 0.150225 0.104745 0.432983
v -0.386774 0.867587 0.293487
v -0.537305 0.244455 0.486828
v -0.247225 0.094067 -0.329701
v 0.623016 0.588166 0.368574
v -0.666179 0.534402 -0.394110
v -0.257901 0.867587 -0.232917
v -0.107523 0.620348 -0.512363
v -0.290081 0.620348 0.572820
v 0.386620 0.104745 0.121503
v 0.666025 0.523649 -0.189864
v -0.838214 0.287390 0.121503
v 0.515647 0.856758 -0.200656
v 0.161053 0.373413 -0.523041
v 0.225414 0.577413 0.562029
v -0.257901 0.362660 0.615873
v -0.279405 0.094067 0.400949
v 0.687529 0.502295 0.207382
v -0.655503 0.405595 0.476150
v 0.461810 0.330402 -0.394110
v -0.633999 0.104745 -0.146925
v 0.526323 0.222949 0.293374
v -0.677007 0.770811 -0.168508
v -0.161207 0.169261 -0.447841
v 0.515647 0.867587 0.271904
v -0.838214 0.620424 0.132295
v 0.118045 0.341079 0.594290
v -0.805881 0.287390 -0.168508
v 0.311431 0.094067 -0.157716
v -0.601818 0.287466 -0.415579
v 0.676853 0.749306 0.024946
v 0.483314 0.566660 0.486828
v -0.193388 0.169261 0.519089
v -0.752196 0.341154 0.357896
v -0.644674 0.792241 0.250435
v 0.128721 0.577413 -0.512250
v 0.633845 0.652607 -0.254387
v -0.580314 0.663359 0.454567
v 0.472638 0.180014 -0.222239
v -0.419107 0.566660 -0.490894
v -0.118199 0.663359 0.540559
v -0.504972 0.158508 -0.372527
v -0.773701 0.179938 -0.039576
v 0.289927 0.094067 0.304165
v -0.397603 0.523649 0.583612
v -0.483620 0.867587 -0.179186
v 0.547827 0.362660 0.400949
v -0.655503 0.169186 0.357896
v -0.773701 0.727800 -0.039576
f 41 50 64
f 5 6 17
f 6 5 22
f 13 22 23
f 22 5 28
f 23 22 28
f 3 2 29
f 24 1 30
f 4 26 33
f 18 31 34
f 9 29 35
f 29 14 35
f 32 7 36
f 19 32 36
f 25 4 37
f 4 33 37
f 13 21 38
f 9 19 39
f 3 29 39
f 29 9 39
f 10 5 40
f 5 17 40
f 30 10 40
f 15 27 41
f 16 8 42
f 30 1 42
f 1 31 42
f 15 21 43
f 27 15 43
f 19 9 44
f 32 19 44
f 11 43 45
f 43 21 45
f 5 10 46
f 10 20 46
f 20 33 46
f 33 26 46
f 20 10 47
f 10 30 47
f 42 8 47
f 30 42 47
f 31 18 48
f 32 16 48
f 16 42 48
f 42 31 48
f 34 12 49
f 12 41 49
f 41 27 49
f 17 6 50
f 41 12 50
f 2 23 51
f 28 14 51
f 23 28 51
f 29 2 51
f 14 29 51
f 28 5 52
f 14 28 52
f 26 35 52
f 35 14 52
f 5 46 52
f 46 26 52
f 24 17 53
f 12 34 53
f 17 50 53
f 50 12 53
f 4 25 54
f 26 4 54
f 9 35 54
f 35 26 54
f 44 9 54
f 25 44 54
f 2 3 55
f 21 13 55
f 23 2 55
f 13 23 55
f 3 45 55
f 45 21 55
f 17 24 56
f 24 30 56
f 40 17 56
f 30 40 56
f 36 11 57
f 19 36 57
f 3 39 57
f 39 19 57
f 45 3 57
f 11 45 57
f 7 27 58
f 11 36 58
f 36 7 58
f 43 11 58
f 27 43 58
f 8 16 59
f 16 32 59
f 37 8 59
f 25 37 59
f 44 25 59
f 32 44 59
f 1 24 60
f 31 1 60
f 34 31 60
f 24 53 60
f 53 34 60
f 6 22 61
f 22 13 61
f 38 6 61
f 13 38 61
f 33 20 62
f 8 37 62
f 37 33 62
f 47 8 62
f 20 47 62
f 27 7 63
f 7 32 63
f 18 34 63
f 48 18 63
f 32 48 63
f 49 27 63
f 34 49 63
f 21 15 64
f 6 38 64
f 38 21 64
f 15 41 64
f 50 6 64
o convex_1
v -0.193580 1.125601 0.443872
v -0.236532 1.179294 -0.383444
v -0.236532 1.275851 -0.383444
v -0.741519 1.222234 0.368646
v -0.150542 1.619669 0.089200
v -0.032381 0.867587 -0.007315
v -0.709262 1.114847 -0.179140
v -0.601710 1.544392 -0.125539
v 0.139599 1.254419 -0.018086
v -0.526501 0.867587 0.207508
v -0.451206 1.533714 0.347105
v -0.365302 0.867587 -0.232909
v 0.021352 1.297359 0.314961
v -0.139847 1.512131 -0.243679
v -0.000124 1.104094 -0.275907
v -0.043162 0.942863 0.261193
v -0.440511 1.061079 0.454558
v -0.505025 1.200802 -0.351133
v -0.677005 0.953692 -0.028772
v -0.300960 1.437006 0.422331
v -0.741519 1.372559 0.175280
v -0.215056 0.867587 0.293336
v 0.053609 1.458514 -0.071770
v -0.386864 1.641176 -0.028772
v -0.365388 1.501453 -0.286593
v -0.741519 1.093340 0.336418
v 0.107342 1.039647 0.067827
v -0.000124 1.480021 0.207340
v -0.000124 1.340298 -0.265136
v -0.612577 1.533714 0.164510
v -0.150628 0.932109 -0.265136
v -0.505025 1.050325 -0.329676
v -0.537196 0.867587 -0.136226
v -0.741519 1.275851 -0.082541
v -0.558758 1.447760 -0.254366
v -0.440511 1.190048 0.476184
v -0.279570 1.608991 0.228881
v 0.075085 1.028817 -0.125455
v 0.064304 1.125601 0.261193
v 0.118037 1.286605 0.153739
v -0.193580 1.608991 -0.114684
v -0.096809 1.404745 0.368646
v -0.451206 1.630422 0.099886
v -0.225837 1.050325 -0.361903
v 0.096561 1.254419 -0.168453
v -0.741519 1.082662 -0.050229
v -0.515806 0.953692 0.347105
v -0.644748 1.211556 -0.265136
v -0.107590 1.028893 0.379332
v -0.182799 1.555222 0.282734
v -0.096895 0.867587 -0.157683
v -0.397559 1.350976 -0.361903
v -0.139847 1.232987 0.433185
v -0.698481 1.447760 -0.050229
v -0.666224 1.018139 -0.189910
v -0.193580 1.404745 -0.340446
v -0.096809 1.232987 -0.351133
v -0.032381 1.555222 -0.028772
v -0.580234 0.867587 0.110741
v -0.354693 1.576729 -0.200765
v -0.558758 1.523036 0.282650
v 0.075085 1.437006 0.089200
v -0.397559 1.480021 0.400874
v -0.053943 0.867587 0.153655
f 91 80 128
f 70 74 76
f 67 66 82
f 74 70 86
f 81 68 90
f 68 85 90
f 78 87 93
f 82 66 96
f 76 74 97
f 96 76 97
f 90 85 98
f 72 89 99
f 68 81 100
f 81 65 100
f 73 91 102
f 91 70 102
f 80 91 103
f 103 91 104
f 91 73 104
f 92 77 104
f 77 103 104
f 88 69 105
f 77 92 106
f 69 88 107
f 88 72 107
f 72 94 107
f 75 101 107
f 101 69 107
f 95 76 108
f 79 95 108
f 96 66 108
f 76 96 108
f 87 73 109
f 79 93 109
f 93 87 109
f 73 102 109
f 102 79 109
f 83 90 110
f 98 71 110
f 90 98 110
f 74 86 111
f 86 81 111
f 81 90 111
f 90 74 111
f 82 96 112
f 71 98 112
f 99 82 112
f 65 81 113
f 86 80 113
f 81 86 113
f 80 103 113
f 92 69 114
f 101 75 114
f 69 101 114
f 84 106 114
f 106 92 114
f 70 76 115
f 76 95 115
f 95 79 115
f 79 102 115
f 102 70 115
f 67 82 116
f 82 99 116
f 99 89 116
f 100 65 117
f 84 100 117
f 103 77 117
f 77 106 117
f 106 84 117
f 65 113 117
f 113 103 117
f 85 94 118
f 94 72 118
f 98 85 118
f 72 99 118
f 112 98 118
f 99 112 118
f 97 83 119
f 96 97 119
f 110 71 119
f 83 110 119
f 112 96 119
f 71 112 119
f 89 78 120
f 78 93 120
f 67 116 120
f 116 89 120
f 66 67 121
f 93 79 121
f 108 66 121
f 79 108 121
f 67 120 121
f 120 93 121
f 87 78 122
f 69 92 122
f 105 69 122
f 78 105 122
f 74 90 123
f 90 83 123
f 97 74 123
f 83 97 123
f 72 88 124
f 78 89 124
f 89 72 124
f 105 78 124
f 88 105 124
f 68 75 125
f 85 68 125
f 94 85 125
f 75 107 125
f 107 94 125
f 73 87 126
f 104 73 126
f 92 104 126
f 87 122 126
f 122 92 126
f 75 68 127
f 68 100 127
f 100 84 127
f 114 75 127
f 84 114 127
f 86 70 128
f 80 86 128
f 70 91 128
o convex_2
v -0.881191 1.372585 0.314915
v -0.752297 1.157735 -0.093320
v -0.741541 1.157735 -0.093320
v -0.741541 1.157735 0.357909
v -0.945660 1.243704 0.078656
v -0.741541 1.340341 0.046399
v -0.956394 1.361845 0.100130
v -0.891925 1.275925 0.347218
v -0.741541 1.361845 0.185979
v -0.870435 1.168500 0.035662
v -0.945660 1.404830 0.228973
v -0.741541 1.211460 0.379476
v -0.806010 1.179240 0.357909
v -0.752297 1.232964 -0.082537
v -0.945660 1.254444 0.035662
v -0.967172 1.351105 0.228973
v -0.838256 1.157735 -0.039589
v -0.902681 1.404830 0.207499
v -0.902681 1.351105 0.336481
v -0.827500 1.329601 0.336481
v -0.848990 1.222224 0.368692
v -0.741541 1.318861 0.003405
v -0.924170 1.394066 0.153815
v -0.827500 1.179240 -0.061063
v -0.967172 1.318861 0.078656
v -0.848990 1.297381 0.368692
v -0.773787 1.157735 0.336481
v -0.945660 1.297381 0.046399
v -0.741541 1.243704 0.357909
v -0.967172 1.383326 0.228973
v -0.956394 1.265185 0.100130
v -0.881191 1.394066 0.261230
v -0.741541 1.361845 0.132341
f 146 137 161
f 130 131 132
f 132 131 134
f 132 134 137
f 132 137 140
f 133 138 141
f 132 140 141
f 131 130 142
f 138 133 143
f 130 132 145
f 138 143 145
f 129 139 147
f 144 136 147
f 137 129 148
f 133 141 149
f 141 140 149
f 134 131 150
f 131 142 150
f 142 135 150
f 135 139 151
f 146 134 151
f 139 146 151
f 134 150 151
f 150 135 151
f 142 130 152
f 130 145 152
f 145 143 152
f 129 147 154
f 147 136 154
f 148 129 154
f 136 149 154
f 149 140 154
f 132 141 155
f 141 138 155
f 145 132 155
f 138 145 155
f 135 142 156
f 142 152 156
f 152 143 156
f 153 135 156
f 143 153 156
f 140 137 157
f 137 148 157
f 148 154 157
f 154 140 157
f 139 135 158
f 147 139 158
f 144 147 158
f 135 153 158
f 153 144 158
f 143 133 159
f 136 144 159
f 133 149 159
f 149 136 159
f 153 143 159
f 144 153 159
f 129 137 160
f 139 129 160
f 137 146 160
f 146 139 160
f 137 134 161
f 134 146 161
o convex_3
v 0.343788 0.867587 0.153823
v 0.623140 0.878339 0.057098
v 0.623140 0.867587 0.057098
v 0.429760 0.878339 -0.168537
v 0.483464 0.953541 0.046370
v 0.515649 0.878339 0.261277
v 0.547888 0.867587 -0.147038
v 0.408267 0.921300 -0.093312
v 0.408267 0.921300 0.164552
v 0.558634 0.910564 -0.093312
v 0.558634 0.921300 0.164552
v 0.354535 0.867587 -0.103998
v 0.569381 0.867587 0.229007
v 0.580127 0.921300 0.024913
v 0.494156 0.932044 -0.093312
v 0.376028 0.910564 0.024913
v 0.429760 0.867587 0.250506
v 0.472745 0.932044 0.175280
v 0.537142 0.942788 0.024913
v 0.408267 0.932044 0.024913
v 0.429760 0.889084 0.239778
v 0.515649 0.878339 -0.168537
v 0.590874 0.878339 -0.082541
v 0.343788 0.878339 0.153823
v 0.354535 0.878339 -0.103998
f 185 177 186
f 164 162 168
f 168 162 173
f 165 168 173
f 162 164 174
f 164 163 174
f 163 172 174
f 172 167 174
f 172 163 175
f 169 166 176
f 165 169 176
f 162 174 178
f 174 167 178
f 166 170 179
f 167 172 179
f 172 166 179
f 166 172 180
f 175 171 180
f 172 175 180
f 176 166 180
f 171 176 180
f 166 169 181
f 170 166 181
f 169 177 181
f 177 170 181
f 178 167 182
f 179 170 182
f 167 179 182
f 168 165 183
f 171 168 183
f 165 176 183
f 176 171 183
f 163 164 184
f 164 168 184
f 168 171 184
f 175 163 184
f 171 175 184
f 173 162 185
f 170 177 185
f 162 178 185
f 182 170 185
f 178 182 185
f 169 165 186
f 165 173 186
f 177 169 186
f 173 185 186
o convex_4
v -0.924164 1.082508 0.121620
v -0.741519 1.136206 0.357985
v -0.752291 1.136206 0.357985
v -0.741519 1.157711 -0.082575
v -0.741519 1.061012 0.089363
v -0.881191 1.157711 0.089363
v -0.902678 1.061012 0.250519
v -0.902678 1.125462 0.261257
v -0.816750 1.114719 -0.050317
v -0.752291 1.157711 0.336466
v -0.741519 1.071765 0.271952
v -0.902678 1.146949 0.057149
v -0.773777 1.082508 -0.018060
v -0.902678 1.061012 0.143009
v -0.795264 1.093251 0.336466
v -0.827503 1.146949 0.325728
v -0.924164 1.136206 0.164529
v -0.806017 1.157711 -0.071793
v -0.741519 1.093251 -0.039580
v -0.870438 1.103995 0.304252
v -0.934917 1.103995 0.153747
v -0.741519 1.061012 0.207480
f 197 193 208
f 190 188 191
f 189 188 196
f 188 190 196
f 190 192 196
f 191 188 197
f 195 187 198
f 195 199 200
f 193 187 200
f 191 193 200
f 187 195 200
f 199 191 200
f 188 189 201
f 197 188 201
f 193 197 201
f 189 196 202
f 196 192 202
f 192 198 203
f 202 192 203
f 194 202 203
f 192 190 204
f 190 195 204
f 198 192 204
f 195 198 204
f 190 191 205
f 195 190 205
f 191 199 205
f 199 195 205
f 194 193 206
f 201 189 206
f 193 201 206
f 202 194 206
f 189 202 206
f 187 193 207
f 193 194 207
f 198 187 207
f 194 203 207
f 203 198 207
f 193 191 208
f 191 197 208

32
data/duck_vhacd.urdf Normal file
View File

@@ -0,0 +1,32 @@
<?xml version="0.0" ?>
<robot name="cube.urdf">
<link name="baseLink">
<contact>
<lateral_friction value="1.0"/>
<rolling_friction value="0.0"/>
<contact_cfm value="0.0"/>
<contact_erp value="1.0"/>
</contact>
<inertial>
<origin rpy="0 0 0" xyz="0.0 0.02 0.0"/>
<mass value=".1"/>
<inertia ixx="1" ixy="0" ixz="0" iyy="1" iyz="0" izz="1"/>
</inertial>
<visual>
<origin rpy="0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="duck.obj" scale=".05 .05 .05"/>
</geometry>
<material name="yellow">
<color rgba="1 1 0.4 1"/>
</material>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="duck_vhacd.obj" scale=".05 .05 .05"/>
</geometry>
</collision>
</link>
</robot>

View File

@@ -1,364 +0,0 @@
<?xml version="1.0" ?>
<sdf version='1.6'>
<world name='default'>
<model name='wsg50_with_gripper'>
<link name='base_link'>
<pose frame=''>0 0 0 0 0 0</pose>
<inertial>
<pose frame=''>0 0 0 0 0 0</pose>
<mass>1.2</mass>
<inertia>
<ixx>1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>1</iyy>
<iyz>0</iyz>
<izz>1</izz>
</inertia>
</inertial>
<visual name='base_link_visual'>
<pose frame=''>0 0 0 0 -0 0</pose>
<geometry>
<mesh>
<scale>1 1 1</scale>
<uri>meshes/WSG50_110.stl</uri>
</mesh>
</geometry>
<material>
</material>
</visual>
</link>
<link name='motor'>
<pose frame=''>0 0 0.03 0 0 0</pose>
<inertial>
<pose frame=''>0 0 0 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<visual name='motor_visual'>
<pose frame=''>0 0 0.01 0 0 0</pose>
<geometry>
<box>
<size>0.02 0.02 0.02 </size>
</box>
</geometry>
</visual>
</link>
<joint name='base_joint_motor' type='prismatic'>
<child>motor</child>
<parent>base_link</parent>
<axis>
<xyz>0 0 1</xyz>
<limit>
<lower>-0.047</lower>
<upper>0.001</upper>
<effort>10.0</effort>
<velocity>10.0</velocity>
</limit>
<dynamics>
<damping>0</damping>
<friction>0</friction>
<spring_reference>0</spring_reference>
<spring_stiffness>0</spring_stiffness>
</dynamics>
</axis>
</joint>
<link name='left_hinge'>
<pose frame=''>0 0 0.04 0 0 0</pose>
<inertial>
<pose frame=''>0 0 0.035 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<visual name='motor_visual'>
<pose frame=''>-0.03 0 0.01 0 -1.2 0</pose>
<geometry>
<box>
<size>0.02 0.02 0.07 </size>
</box>
</geometry>
</visual>
</link>
<joint name='motor_left_hinge_joint' type='revolute'>
<child>left_hinge</child>
<parent>motor</parent>
<axis>
<xyz>0 1 0</xyz>
<limit>
<lower>-20.0</lower>
<upper>20.0</upper>
<effort>10</effort>
<velocity>10</velocity>
</limit>
<dynamics>
<damping>0</damping>
<friction>0</friction>
<spring_reference>0</spring_reference>
<spring_stiffness>0</spring_stiffness>
</dynamics>
<use_parent_model_frame>0</use_parent_model_frame>
</axis>
</joint>
<link name='right_hinge'>
<pose frame=''>0 0 0.04 0 0 0</pose>
<inertial>
<pose frame=''>0 0 0.035 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<visual name='motor_visual'>
<pose frame=''>0.03 0 0.01 0 1.2 0</pose>
<geometry>
<box>
<size>0.02 0.02 0.07 </size>
</box>
</geometry>
</visual>
</link>
<joint name='motor_right_hinge_joint' type='revolute'>
<child>right_hinge</child>
<parent>motor</parent>
<axis>
<xyz>0 1 0</xyz>
<limit>
<lower>-20.0</lower>
<upper>20.0</upper>
<effort>10</effort>
<velocity>10</velocity>
</limit>
<dynamics>
<damping>0</damping>
<friction>0</friction>
<spring_reference>0</spring_reference>
<spring_stiffness>0</spring_stiffness>
</dynamics>
<use_parent_model_frame>0</use_parent_model_frame>
</axis>
</joint>
<link name='gripper_left'>
<pose frame=''>-0.055 0 0.06 0 -0 0</pose>
<inertial>
<pose frame=''>0 0 0.0115 0 -0 0</pose>
<mass>0.2</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<visual name='gripper_left_visual'>
<pose frame=''>0 0 -0.06 0 0 0</pose>
<geometry>
<mesh>
<scale>0.001 0.001 0.001</scale>
<uri>meshes/GUIDE_WSG50_110.stl</uri>
</mesh>
</geometry>
</visual>
<visual name='gripper_left_fixed_joint_lump__finger_left_visual_1'>
<pose frame=''>0 0 -0.037 0 0 0</pose>
<geometry>
<mesh>
<scale>0.001 0.001 0.001</scale>
<uri>meshes/WSG-FMF.stl</uri>
</mesh>
</geometry>
</visual>
</link>
<joint name='gripper_left_hinge_joint' type='revolute'>
<child>gripper_left</child>
<parent>left_hinge</parent>
<axis>
<xyz>0 1 0</xyz>
<limit>
<lower>-1.0</lower>
<upper>1.0</upper>
<effort>10</effort>
<velocity>10</velocity>
</limit>
<dynamics>
<damping>0.01</damping>
<friction>0</friction>
<spring_reference>0</spring_reference>
<spring_stiffness>0</spring_stiffness>
</dynamics>
<use_parent_model_frame>0</use_parent_model_frame>
</axis>
</joint>
<link name='gripper_right'>
<pose frame=''>0.055 0 0.06 0 0 3.14159</pose>
<inertial>
<pose frame=''>0 0 0.0115 0 -0 0</pose>
<mass>0.2</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<visual name='gripper_right_visual'>
<pose frame=''>0 0 -0.06 0 0 0</pose>
<geometry>
<mesh>
<scale>0.001 0.001 0.001</scale>
<uri>meshes/GUIDE_WSG50_110.stl</uri>
</mesh>
</geometry>
</visual>
<visual name='gripper_right_fixed_joint_lump__finger_right_visual_1'>
<pose frame=''>0 0 -0.037 0 0 0</pose>
<geometry>
<mesh>
<scale>0.001 0.001 0.001</scale>
<uri>meshes/WSG-FMF.stl</uri>
</mesh>
</geometry>
</visual>
</link>
<joint name='gripper_right_hinge_joint' type='revolute'>
<child>gripper_right</child>
<parent>right_hinge</parent>
<axis>
<xyz>0 1 0</xyz>
<limit>
<lower>-1.0</lower>
<upper>1.0</upper>
<effort>10</effort>
<velocity>10</velocity>
</limit>
<dynamics>
<damping>0.01</damping>
<friction>0</friction>
<spring_reference>0</spring_reference>
<spring_stiffness>0</spring_stiffness>
</dynamics>
<use_parent_model_frame>0</use_parent_model_frame>
</axis>
</joint>
<link name='finger_right'>
<pose frame=''>0.062 0 0.145 0 0 1.5708</pose>
<inertial>
<mass>0.2</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<collision name='finger_right_collision'>
<pose frame=''>0 0 0.042 0 0 0 </pose>
<geometry>
<box>
<size>0.02 0.02 0.15 </size>
</box>
</geometry>
</collision>
<visual name='finger_right_visual'>
<pose frame=''>0 0 0 0 0 0 </pose>
<geometry>
<mesh>
<scale>1 1 1 </scale>
<uri>meshes/l_gripper_tip_scaled.stl</uri>
</mesh>
</geometry>
</visual>
</link>
<joint name='gripper_finger_right' type='fixed'>
<parent>gripper_right</parent>
<child>finger_right</child>
</joint>
<link name='finger_left'>
<pose frame=''>-0.062 0 0.145 0 0 4.71239</pose>
<inertial>
<mass>0.2</mass>
<inertia>
<ixx>0.1</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.1</iyy>
<iyz>0</iyz>
<izz>0.1</izz>
</inertia>
</inertial>
<collision name='finger_left_collision'>
<pose frame=''>0 0 0.042 0 0 0 </pose>
<geometry>
<box>
<size>0.02 0.02 0.15 </size>
</box>
</geometry>
</collision>
<visual name='finger_left_visual'>
<pose frame=''>0 0 0 0 0 0 </pose>
<geometry>
<mesh>
<scale>1 1 1 </scale>
<uri>meshes/l_gripper_tip_scaled.stl</uri>
</mesh>
</geometry>
</visual>
</link>
<joint name='gripper_finger_left' type='fixed'>
<parent>gripper_left</parent>
<child>finger_left</child>
</joint>
</model>
</world>
</sdf>

View File

@@ -31,25 +31,175 @@
<collision concave="yes" name="pod_collision">
<pose>0 0 0 1.5707 0 0</pose>
<pose>0 0 1.21515 1.5707 0 0</pose>
<geometry>
<mesh>
<uri>meshes/pod_lowres.stl</uri>
</mesh>
<box>
<size>0.875 1.754 0.03</size>
</box>
</geometry>
<surface>
<friction>
<ode>
<mu>0.8</mu>
<mu2>0.8</mu2>
<fdir1>0.0 0.0 0.0</fdir1>
<slip1>1.0</slip1>
<slip2>1.0</slip2>
</ode>
</friction>
</surface>
</collision>
<collision concave="yes" name="pod_collision">
<pose>-0.42 0 1.18 1.5707 0 1.5707 </pose>
<geometry>
<box>
<size>0.875 1.754 0.03</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0.42 0.42 1.17 1.5707 0 0</pose>
<geometry>
<box>
<size>0.03 2.3 0.03</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>-0.42 0.42 1.17 1.5707 0 0</pose>
<geometry>
<box>
<size>0.03 2.3 0.03</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>-0.42 -0.42 1.17 1.5707 0 0</pose>
<geometry>
<box>
<size>0.03 2.3 0.03</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0.42 -0.42 1.17 1.5707 0 0</pose>
<geometry>
<box>
<size>0.03 2.3 0.03</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0.15 0 1.49 1.5707 0 1.5707 </pose>
<geometry>
<box>
<size>0.875 1.32 0.01</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>-0.15 0 1.49 1.5707 0 1.5707 </pose>
<geometry>
<box>
<size>0.875 1.32 0.01</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 .57 1.5707 0 1.5707 </pose>
<geometry>
<box>
<size>0.875 0.45 0.01</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0.42 0 1.18 1.5707 0 1.5707 </pose>
<geometry>
<box>
<size>0.875 1.754 0.03</size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 1.06 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 1.06 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 0.80 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0.43 0.81 0 0 0 </pose>
<geometry>
<box>
<size>0.856 0.018 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 -0.43 0.81 0 0 0 </pose>
<geometry>
<box>
<size>0.856 0.018 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0.43 1.08 0 0 0 </pose>
<geometry>
<box>
<size>0.856 0.018 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 -0.43 1.08 0 0 0 </pose>
<geometry>
<box>
<size>0.856 0.018 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 0.37 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 1.29 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 1.53 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
<collision concave="yes" name="pod_collision">
<pose>0 0 1.78 0 0 0 </pose>
<geometry>
<box>
<size>0.905 0.856 0.028 </size>
</box>
</geometry>
</collision>
</link>
</model>
</sdf>

3751
data/lego/lego.obj Normal file

File diff suppressed because it is too large Load Diff

32
data/lego/lego.urdf Normal file
View File

@@ -0,0 +1,32 @@
<?xml version="0.0" ?>
<robot name="cube.urdf">
<link name="legobrick">
<contact>
<lateral_friction value="1.0"/>
<rolling_friction value="0.0"/>
<contact_cfm value="0.0"/>
<contact_erp value="1.0"/>
</contact>
<inertial>
<origin rpy="0 0 0" xyz="0.0 0.0 0.0"/>
<mass value=".1"/>
<inertia ixx="1" ixy="0" ixz="0" iyy="1" iyz="0" izz="1"/>
</inertial>
<visual>
<origin rpy="1.570796 0 0" xyz="-0.016 -0.016 -0.0115"/>
<geometry>
<mesh filename="lego.obj" scale=".1 .1 .1"/>
</geometry>
<material name="yellow">
<color rgba="1 1 0.4 1"/>
</material>
</visual>
<collision>
<origin rpy="1.570796 0 0" xyz="0 0 0"/>
<geometry>
<box size="0.032 0.023 0.032"/>
</geometry>
</collision>
</link>
</robot>

3072
data/lego/lego_vhacd.obj Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -1,142 +0,0 @@
<?xml version="1.0"?>
<robot name="physics">
<link name="gripper_pole">
<visual>
<geometry>
<cylinder length="0.04" radius=".01"/>
</geometry>
<origin rpy="0 1.57075 0 " xyz="0.02 0 0"/>
<material name="Gray">
<color rgba=".7 .7 .7 1"/>
</material>
</visual>
<collision>
<geometry>
<cylinder length="0.04" radius=".01"/>
</geometry>
<origin rpy="0 1.57075 0 " xyz="0.02 0 0"/>
</collision>
<inertial>
<mass value="0.5"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_gripper_joint" type="revolute">
<axis xyz="0 0 1"/>
<limit effort="1000.0" lower="0.0" upper="0.548" velocity="0.5"/>
<origin rpy="0 0 0" xyz="0.02 0.01 0"/>
<parent link="gripper_pole"/>
<child link="left_gripper"/>
</joint>
<link name="left_gripper">
<contact>
<lateral_friction value="1.0"/>
<spinning_friction value="1.5"/>
</contact>
<visual>
<origin rpy="0.0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger_collision.stl"/>
</geometry>
</visual>
<collision>
<origin rpy="0.0 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger_collision.stl"/>
</geometry>
</collision>
<inertial>
<mass value="0.1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="left_tip_joint" type="fixed">
<parent link="left_gripper"/>
<child link="left_tip"/>
</joint>
<link name="left_tip">
<contact>
<lateral_friction value="1.0"/>
<spinning_friction value="1.5"/>
</contact>
<visual>
<origin rpy="0.0 0 0" xyz="0.09137 0.00495 0"/>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<box size=".03 .03 .02"/>
</geometry>
<origin rpy="0.0 0 0" xyz="0.105 0.00495 0"/>
</collision>
<inertial>
<mass value="0.1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_gripper_joint" type="revolute">
<axis xyz="0 0 -1"/>
<limit effort="1000.0" lower="0.0" upper="0.548" velocity="0.5"/>
<origin rpy="0 0 0" xyz="0.02 -0.01 0"/>
<parent link="gripper_pole"/>
<child link="right_gripper"/>
</joint>
<link name="right_gripper">
<contact>
<lateral_friction value="1.0"/>
<spinning_friction value="1.5"/>
</contact>
<visual>
<origin rpy="-3.1415 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger_collision.stl"/>
</geometry>
</visual>
<collision>
<origin rpy="-3.1415 0 0" xyz="0 0 0"/>
<geometry>
<mesh filename="l_finger_collision.stl"/>
</geometry>
</collision>
<inertial>
<mass value="0.1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
<joint name="right_tip_joint" type="fixed">
<parent link="right_gripper"/>
<child link="right_tip"/>
</joint>
<link name="right_tip">
<contact>
<lateral_friction value="1.0"/>
<spinning_friction value="1.5"/>
</contact>
<visual>
<origin rpy="-3.1415 0 0" xyz="0.09137 0.00495 0"/>
<geometry>
<mesh filename="l_finger_tip.stl"/>
</geometry>
</visual>
<collision>
<geometry>
<box size=".03 .03 .02"/>
</geometry>
<origin rpy="-3.1415 0 0" xyz="0.105 0.00495 0"/>
</collision>
<inertial>
<mass value="0.1"/>
<inertia ixx="1.0" ixy="0.0" ixz="0.0" iyy="1.0" iyz="0.0" izz="1.0"/>
</inertial>
</link>
</robot>

View File

@@ -1,61 +0,0 @@
<?xml version="0.0" ?>
<robot name="urdf_table">
<link name="world"/>
<joint name="fixed" type="fixed">
<parent link="world"/>
<child link="baseLink"/>
<origin xyz="0 0 0"/>
</joint>
<link name="baseLink">
<inertial>
<origin rpy="0 0 0" xyz="0 0 0.6"/>
<mass value="0"/>
<inertia ixx="0.1" ixy="0" ixz="0" iyy="0.1" iyz="0" izz="0.1"/>
</inertial>
<visual>
<origin rpy="0 0 0" xyz="0 0 0.6"/>
<geometry>
<box size="1.5 1.0 0.08"/>
</geometry>
<material name="framemat0">
<color
rgba="1 1 1 1" />
</material>
</visual>
<visual>
<origin rpy="0 0 0" xyz="-0.65 -0.4 0.28"/>
<geometry>
<box size="0.1 0.1 0.56"/>
</geometry>
<material name="framemat0"/>
</visual>
<visual>
<origin rpy="0 0 0" xyz="-0.65 0.4 0.28"/>
<geometry>
<box size="0.1 0.1 0.56"/>
</geometry>
<material name="framemat0"/>
</visual>
<visual>
<origin rpy="0 0 0" xyz="0.65 -0.4 0.28"/>
<geometry>
<box size="0.1 0.1 0.56"/>
</geometry>
<material name="framemat0"/>
</visual>
<visual>
<origin rpy="0 0 0" xyz="0.65 0.4 0.28"/>
<geometry>
<box size="0.1 0.1 0.56"/>
</geometry>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0 0.6"/>
<geometry>
<box size="1.5 1.0 0.08"/>
</geometry>
</collision>
</link>
</robot>

View File

@@ -1,91 +0,0 @@
<?xml version="1.0"?>
<robot name="tray">
<link name="baseLink">
<inertial>
<origin rpy="0 0 0" xyz="0 0 0"/>
<mass value="0.0"/>
<inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/>
</inertial>
<visual>
<origin rpy="0 0 0" xyz="-0.29 0.0 0.05"/>
<geometry>
<box size="0.02 0.6 0.06"/>
</geometry>
<material name="framemat0">
<color rgba="0.6 0.6 0.6 1"/>
</material>
</visual>
<collision>
<origin rpy="0 0 0" xyz="-0.29 0.0 0.05"/>
<geometry>
<box size="0.02 0.6 0.06"/>
</geometry>
</collision>
<visual>
<origin rpy="0 0 0" xyz="0.29 0.0 0.05"/>
<geometry>
<box size="0.02 0.6 0.06"/>
</geometry>
<material name="framemat0">
<color rgba="0.6 0.6 0.6 1"/>
</material>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0.29 0.0 0.05"/>
<geometry>
<box size="0.02 0.6 0.06"/>
</geometry>
</collision>
<visual>
<origin rpy="0 0 0" xyz="0.0 -0.29 0.05"/>
<geometry>
<box size="0.56 0.02 0.06"/>
</geometry>
<material name="framemat0">
<color rgba="0.6 0.6 0.6 1"/>
</material>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0.0 -0.29 0.05"/>
<geometry>
<box size="0.56 0.02 0.06"/>
</geometry>
</collision>
<visual>
<origin rpy="0 0 0" xyz="0.0 0.29 0.05"/>
<geometry>
<box size="0.56 0.02 0.06"/>
</geometry>
<material name="framemat0">
<color rgba="0.6 0.6 0.6 1"/>
</material>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0.0 0.29 0.05"/>
<geometry>
<box size="0.56 0.02 0.06"/>
</geometry>
</collision>
<!-- base -->
<visual>
<origin rpy="0 0 0" xyz="0 0 0.01"/>
<geometry>
<box size="0.6 0.6 0.02"/>
</geometry>
<material name="framemat0"/>
<color rgba="0.4 0.4 0.4 1"/>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0 0.01"/>
<geometry>
<box size="0.6 0.6 0.02"/>
</geometry>
</collision>
</link>
</robot>

View File

@@ -225,7 +225,8 @@ void ConvertURDF2BulletInternal(
{
btVector3 color = selectColor2();
btVector4 color = selectColor2();
u2b.getLinkColor(urdfLinkIndex,color);
/*
if (visual->material.get())
{
@@ -255,7 +256,7 @@ void ConvertURDF2BulletInternal(
btRigidBody* body = creation.allocateRigidBody(urdfLinkIndex, mass, localInertiaDiagonal, inertialFrameInWorldSpace, compoundShape);
linkRigidBody = body;
world1->addRigidBody(body, bodyCollisionFilterGroup, bodyCollisionFilterMask);
world1->addRigidBody(body);
compoundShape->setUserIndex(graphicsIndex);

View File

@@ -43,7 +43,7 @@ bool IKTrajectoryHelper::computeIK(const double endEffectorTargetPosition[3],
const double endEffectorWorldPosition[3],
const double endEffectorWorldOrientation[4],
const double* q_current, int numQ,int endEffectorIndex,
double* q_new, int ikMethod, const double* linear_jacobian, const double* angular_jacobian, int jacobian_size, double dampIk)
double* q_new, int ikMethod, const double* linear_jacobian, const double* angular_jacobian, int jacobian_size, const double dampIk[6])
{
bool useAngularPart = (ikMethod==IK2_VEL_DLS_WITH_ORIENTATION) ? true : false;
@@ -69,7 +69,7 @@ bool IKTrajectoryHelper::computeIK(const double endEffectorTargetPosition[3],
VectorRn deltaS(3);
for (int i = 0; i < 3; ++i)
{
deltaS.Set(i,dampIk*(endEffectorTargetPosition[i]-endEffectorWorldPosition[i]));
deltaS.Set(i,dampIk[i]*(endEffectorTargetPosition[i]-endEffectorWorldPosition[i]));
}
// Set one end effector world orientation from Bullet
@@ -79,13 +79,12 @@ bool IKTrajectoryHelper::computeIK(const double endEffectorTargetPosition[3],
btQuaternion deltaQ = endQ*startQ.inverse();
float angle = deltaQ.getAngle();
btVector3 axis = deltaQ.getAxis();
float angleDot = angle*dampIk;
float angleDot = angle;
btVector3 angularVel = angleDot*axis.normalize();
for (int i = 0; i < 3; ++i)
{
deltaR.Set(i,angularVel[i]);
deltaR.Set(i,dampIk[i+3]*angularVel[i]);
}
deltaR[2] = 0.0;
{

View File

@@ -21,13 +21,12 @@ public:
IKTrajectoryHelper();
virtual ~IKTrajectoryHelper();
bool computeIK(const double endEffectorTargetPosition[3],
const double endEffectorTargetOrientation[4],
const double endEffectorWorldPosition[3],
const double endEffectorWorldOrientation[4],
const double* q_old, int numQ,int endEffectorIndex,
double* q_new, int ikMethod, const double* linear_jacobian, const double* angular_jacobian, int jacobian_size, double dampIk=1.);
const double* q_old, int numQ, int endEffectorIndex,
double* q_new, int ikMethod, const double* linear_jacobian, const double* angular_jacobian, int jacobian_size, const double dampIk[6]);
};
#endif //IK_TRAJECTORY_HELPER_H

View File

@@ -24,9 +24,15 @@ public:
virtual bool submitClientCommand(const struct SharedMemoryCommand& command) = 0;
virtual int getNumJoints(int bodyIndex) const = 0;
virtual int getNumBodies() const = 0;
virtual bool getJointInfo(int bodyIndex, int jointIndex, struct b3JointInfo& info) const = 0;
virtual int getBodyUniqueId(int serialIndex) const = 0;
virtual bool getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const = 0;
virtual int getNumJoints(int bodyUniqueId) const = 0;
virtual bool getJointInfo(int bodyUniqueId, int jointIndex, struct b3JointInfo& info) const = 0;
virtual void setSharedMemoryKey(int key) = 0;

View File

@@ -739,6 +739,29 @@ b3SharedMemoryStatusHandle b3SubmitClientCommandAndWaitStatus(b3PhysicsClientHan
}
///return the total number of bodies in the simulation
int b3GetNumBodies(b3PhysicsClientHandle physClient)
{
PhysicsClient* cl = (PhysicsClient* ) physClient;
return cl->getNumBodies();
}
/// return the body unique id, given the index in range [0 , b3GetNumBodies() )
int b3GetBodyUniqueId(b3PhysicsClientHandle physClient, int serialIndex)
{
PhysicsClient* cl = (PhysicsClient* ) physClient;
return cl->getBodyUniqueId(serialIndex);
}
///given a body unique id, return the body information. See b3BodyInfo in SharedMemoryPublic.h
int b3GetBodyInfo(b3PhysicsClientHandle physClient, int bodyUniqueId, struct b3BodyInfo* info)
{
PhysicsClient* cl = (PhysicsClient* ) physClient;
return cl->getBodyInfo(bodyUniqueId,*info);
}
int b3GetNumJoints(b3PhysicsClientHandle physClient, int bodyId)
{
PhysicsClient* cl = (PhysicsClient* ) physClient;

View File

@@ -53,6 +53,15 @@ int b3GetStatusActualState(b3SharedMemoryStatusHandle statusHandle,
const double* actualStateQdot[],
const double* jointReactionForces[]);
///return the total number of bodies in the simulation
int b3GetNumBodies(b3PhysicsClientHandle physClient);
/// return the body unique id, given the index in range [0 , b3GetNumBodies() )
int b3GetBodyUniqueId(b3PhysicsClientHandle physClient, int serialIndex);
///given a body unique id, return the body information. See b3BodyInfo in SharedMemoryPublic.h
int b3GetBodyInfo(b3PhysicsClientHandle physClient, int bodyUniqueId, struct b3BodyInfo* info);
///give a unique body index (after loading the body) return the number of joints.
int b3GetNumJoints(b3PhysicsClientHandle physClient, int bodyIndex);

View File

@@ -624,7 +624,7 @@ void PhysicsClientExample::initPhysics()
{
MyCallback(CMD_LOAD_URDF, true, this);
MyCallback(CMD_STEP_FORWARD_SIMULATION,true,this);
MyCallback(CMD_STEP_FORWARD_SIMULATION,true,this);
MyCallback(CMD_RESET_SIMULATION,true,this);
}

View File

@@ -18,6 +18,7 @@
struct BodyJointInfoCache
{
std::string m_baseName;
btAlignedObjectArray<b3JointInfo> m_jointInfo;
};
@@ -74,10 +75,37 @@ struct PhysicsClientSharedMemoryInternalData {
int PhysicsClientSharedMemory::getNumJoints(int bodyIndex) const
int PhysicsClientSharedMemory::getNumBodies() const
{
BodyJointInfoCache** bodyJointsPtr = m_data->m_bodyJointMap[bodyIndex];
return m_data->m_bodyJointMap.size();
}
int PhysicsClientSharedMemory::getBodyUniqueId(int serialIndex) const
{
if ((serialIndex >= 0) && (serialIndex < getNumBodies()))
{
return m_data->m_bodyJointMap.getKeyAtIndex(serialIndex).getUid1();
}
return -1;
}
bool PhysicsClientSharedMemory::getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const
{
BodyJointInfoCache** bodyJointsPtr = m_data->m_bodyJointMap[bodyUniqueId];
if (bodyJointsPtr && *bodyJointsPtr)
{
BodyJointInfoCache* bodyJoints = *bodyJointsPtr;
info.m_baseName = bodyJoints->m_baseName.c_str();
return true;
}
return false;
}
int PhysicsClientSharedMemory::getNumJoints(int bodyUniqueId) const
{
BodyJointInfoCache** bodyJointsPtr = m_data->m_bodyJointMap[bodyUniqueId];
if (bodyJointsPtr && *bodyJointsPtr)
{
BodyJointInfoCache* bodyJoints = *bodyJointsPtr;
@@ -88,9 +116,9 @@ int PhysicsClientSharedMemory::getNumJoints(int bodyIndex) const
}
bool PhysicsClientSharedMemory::getJointInfo(int bodyIndex, int jointIndex, b3JointInfo& info) const
bool PhysicsClientSharedMemory::getJointInfo(int bodyUniqueId, int jointIndex, b3JointInfo& info) const
{
BodyJointInfoCache** bodyJointsPtr = m_data->m_bodyJointMap[bodyIndex];
BodyJointInfoCache** bodyJointsPtr = m_data->m_bodyJointMap[bodyUniqueId];
if (bodyJointsPtr && *bodyJointsPtr)
{
BodyJointInfoCache* bodyJoints = *bodyJointsPtr;
@@ -196,12 +224,13 @@ void PhysicsClientSharedMemory::processBodyJointInfo(int bodyUniqueId, const Sha
Bullet::btMultiBodyDoubleData* mb =
(Bullet::btMultiBodyDoubleData*)bf.m_multiBodies[i];
bodyJoints->m_baseName = mb->m_baseName;
addJointInfoFromMultiBodyData(mb,bodyJoints, m_data->m_verboseOutput);
} else
{
Bullet::btMultiBodyFloatData* mb =
(Bullet::btMultiBodyFloatData*)bf.m_multiBodies[i];
bodyJoints->m_baseName = mb->m_baseName;
addJointInfoFromMultiBodyData(mb,bodyJoints, m_data->m_verboseOutput);
}
}
@@ -272,10 +301,10 @@ const SharedMemoryStatus* PhysicsClientSharedMemory::processServerStatus() {
serverCmd.m_dataStreamArguments.m_streamChunkLength);
bf.setFileDNAisMemoryDNA();
bf.parse(false);
int bodyIndex = serverCmd.m_dataStreamArguments.m_bodyUniqueId;
int bodyUniqueId = serverCmd.m_dataStreamArguments.m_bodyUniqueId;
BodyJointInfoCache* bodyJoints = new BodyJointInfoCache;
m_data->m_bodyJointMap.insert(bodyIndex,bodyJoints);
m_data->m_bodyJointMap.insert(bodyUniqueId,bodyJoints);
for (int i = 0; i < bf.m_multiBodies.size(); i++) {

View File

@@ -34,9 +34,15 @@ public:
virtual bool submitClientCommand(const struct SharedMemoryCommand& command);
virtual int getNumJoints(int bodyIndex) const;
virtual int getNumBodies() const;
virtual bool getJointInfo(int bodyIndex, int jointIndex, struct b3JointInfo& info) const;
virtual int getBodyUniqueId(int serialIndex) const;
virtual bool getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const;
virtual int getNumJoints(int bodyUniqueId) const;
virtual bool getJointInfo(int bodyUniqueId, int jointIndex, struct b3JointInfo& info) const;
virtual void setSharedMemoryKey(int key);

View File

@@ -9,10 +9,11 @@
#include "../../Extras/Serialize/BulletFileLoader/btBulletFile.h"
#include "../../Extras/Serialize/BulletFileLoader/autogenerated/bullet.h"
#include "BodyJointInfoUtility.h"
#include <string>
struct BodyJointInfoCache2
{
std::string m_baseName;
btAlignedObjectArray<b3JointInfo> m_jointInfo;
};
@@ -330,7 +331,6 @@ void PhysicsDirect::processBodyJointInfo(int bodyUniqueId, const SharedMemorySta
bf.setFileDNAisMemoryDNA();
bf.parse(false);
BodyJointInfoCache2* bodyJoints = new BodyJointInfoCache2;
m_data->m_bodyJointMap.insert(bodyUniqueId,bodyJoints);
@@ -341,6 +341,7 @@ void PhysicsDirect::processBodyJointInfo(int bodyUniqueId, const SharedMemorySta
{
Bullet::btMultiBodyDoubleData* mb =
(Bullet::btMultiBodyDoubleData*)bf.m_multiBodies[i];
bodyJoints->m_baseName = mb->m_baseName;
addJointInfoFromMultiBodyData(mb,bodyJoints, m_data->m_verboseOutput);
} else
@@ -348,6 +349,7 @@ void PhysicsDirect::processBodyJointInfo(int bodyUniqueId, const SharedMemorySta
Bullet::btMultiBodyFloatData* mb =
(Bullet::btMultiBodyFloatData*)bf.m_multiBodies[i];
bodyJoints->m_baseName = mb->m_baseName;
addJointInfoFromMultiBodyData(mb,bodyJoints, m_data->m_verboseOutput);
}
}
@@ -458,6 +460,34 @@ bool PhysicsDirect::submitClientCommand(const struct SharedMemoryCommand& comman
return hasStatus;
}
int PhysicsDirect::getNumBodies() const
{
return m_data->m_bodyJointMap.size();
}
int PhysicsDirect::getBodyUniqueId(int serialIndex) const
{
if ((serialIndex >= 0) && (serialIndex < getNumBodies()))
{
return m_data->m_bodyJointMap.getKeyAtIndex(serialIndex).getUid1();
}
return -1;
}
bool PhysicsDirect::getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const
{
BodyJointInfoCache2** bodyJointsPtr = m_data->m_bodyJointMap[bodyUniqueId];
if (bodyJointsPtr && *bodyJointsPtr)
{
BodyJointInfoCache2* bodyJoints = *bodyJointsPtr;
info.m_baseName = bodyJoints->m_baseName.c_str();
return true;
}
return false;
}
int PhysicsDirect::getNumJoints(int bodyIndex) const
{
BodyJointInfoCache2** bodyJointsPtr = m_data->m_bodyJointMap[bodyIndex];

View File

@@ -49,6 +49,12 @@ public:
virtual bool submitClientCommand(const struct SharedMemoryCommand& command);
virtual int getNumBodies() const;
virtual int getBodyUniqueId(int serialIndex) const;
virtual bool getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const;
virtual int getNumJoints(int bodyIndex) const;
virtual bool getJointInfo(int bodyIndex, int jointIndex, struct b3JointInfo& info) const;

View File

@@ -74,6 +74,21 @@ bool PhysicsLoopBack::submitClientCommand(const struct SharedMemoryCommand& comm
return m_data->m_physicsClient->submitClientCommand(command);
}
int PhysicsLoopBack::getNumBodies() const
{
return m_data->m_physicsClient->getNumBodies();
}
int PhysicsLoopBack::getBodyUniqueId(int serialIndex) const
{
return m_data->m_physicsClient->getBodyUniqueId(serialIndex);
}
bool PhysicsLoopBack::getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const
{
return m_data->m_physicsClient->getBodyInfo(bodyUniqueId, info);
}
int PhysicsLoopBack::getNumJoints(int bodyIndex) const
{
return m_data->m_physicsClient->getNumJoints(bodyIndex);

View File

@@ -38,6 +38,12 @@ public:
virtual bool submitClientCommand(const struct SharedMemoryCommand& command);
virtual int getNumBodies() const;
virtual int getBodyUniqueId(int serialIndex) const;
virtual bool getBodyInfo(int bodyUniqueId, struct b3BodyInfo& info) const;
virtual int getNumJoints(int bodyIndex) const;
virtual bool getJointInfo(int bodyIndex, int jointIndex, struct b3JointInfo& info) const;

View File

@@ -1,6 +1,5 @@
#include "PhysicsServerCommandProcessor.h"
#include "../Importers/ImportURDFDemo/BulletUrdfImporter.h"
#include "../Importers/ImportURDFDemo/MyMultiBodyCreator.h"
#include "../Importers/ImportURDFDemo/URDF2Bullet.h"
@@ -569,7 +568,7 @@ PhysicsServerCommandProcessor::PhysicsServerCommandProcessor()
m_data = new PhysicsServerCommandProcessorInternalData();
createEmptyDynamicsWorld();
m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop = 0.0001;
m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop = 0.00001;
m_data->m_dynamicsWorld->getSolverInfo().m_numIterations = 100;
}
@@ -610,7 +609,7 @@ void PhysicsServerCommandProcessor::createEmptyDynamicsWorld()
m_data->m_dynamicsWorld->setGravity(btVector3(0, 0, 0));
m_data->m_dynamicsWorld->getSolverInfo().m_erp2 = 0.05;
m_data->m_dynamicsWorld->getSolverInfo().m_erp2 = 0.08;
}
@@ -1071,6 +1070,10 @@ int PhysicsServerCommandProcessor::createBodyInfoStream(int bodyUniqueId, char*
util->m_memSerializer = new btDefaultSerializer(bufferSizeInBytes ,(unsigned char*)bufferServerToClient);
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
util->m_memSerializer->m_skipPointers.insert(mb->getBaseCollider(),0);
if (mb->getBaseName())
{
util->m_memSerializer->registerNameForPointer(mb->getBaseName(),mb->getBaseName());
}
bodyHandle->m_linkLocalInertialFrames.reserve(mb->getNumLinks());
for (int i=0;i<mb->getNumLinks();i++)
@@ -1893,6 +1896,9 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
applyJointDamping(i);
}
btScalar deltaTimeScaled = m_data->m_physicsDeltaTime*simTimeScalingFactor;
if (m_data->m_numSimulationSubSteps > 0)
@@ -2650,12 +2656,12 @@ bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryComm
endEffectorPosWorld.serializeDouble(endEffectorWorldPosition);
endEffectorOri.serializeDouble(endEffectorWorldOrientation);
double dampIK[6] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
ikHelperPtr->computeIK(clientCmd.m_calculateInverseKinematicsArguments.m_targetPosition, clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation,
endEffectorWorldPosition.m_floats, endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs, clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndex,
&q_new[0], ikMethod, &jacobian_linear[0], &jacobian_angular[0], jacSize*2);
&q_new[0], ikMethod, &jacobian_linear[0], &jacobian_angular[0], jacSize*2, dampIK);
serverCmd.m_inverseKinematicsResultArgs.m_bodyUniqueId =clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
for (int i=0;i<numDofs;i++)
@@ -2825,6 +2831,7 @@ void PhysicsServerCommandProcessor::removePickingConstraint()
m_data->m_dynamicsWorld->removeConstraint(m_data->m_pickedConstraint);
delete m_data->m_pickedConstraint;
m_data->m_pickedConstraint = 0;
m_data->m_pickedBody->forceActivationState(ACTIVE_TAG);
m_data->m_pickedBody = 0;
}
if (m_data->m_pickingMultiBodyPoint2Point)
@@ -2894,11 +2901,12 @@ void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec)
btVector3 shiftPos = spawnDir*spawnDistance;
btVector3 spawnPos = gVRGripperPos + shiftPos;
loadUrdf("sphere_small.urdf", spawnPos, gVRGripperOrn, true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
//loadUrdf("lego/lego.urdf", spawnPos, gVRGripperOrn, true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
m_data->m_sphereId = bodyId;
InteralBodyData* parentBody = m_data->getHandle(bodyId);
if (parentBody->m_multiBody)
{
parentBody->m_multiBody->setBaseVel(spawnDir * 3);
parentBody->m_multiBody->setBaseVel(spawnDir * 5);
}
}
@@ -2941,11 +2949,15 @@ void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec)
}
}
loadUrdf("kuka_iiwa/model.urdf", btVector3(0, -2.3, 0.6), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("kuka_iiwa/model.urdf", btVector3(0, -3.0, 0.0), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
m_data->m_KukaId = bodyId;
loadUrdf("lego/lego.urdf", btVector3(0, -2.5, .1), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("lego/lego.urdf", btVector3(0, -2.5, .2), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("lego/lego.urdf", btVector3(0, -2.5, .3), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("r2d2.urdf", btVector3(2, -2, 1), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
// Load one motor gripper for kuka
loadSdf("gripper/wsg50_one_motor_gripper_new.sdf", &gBufferServerToClient[0], gBufferServerToClient.size(), true);
loadSdf("gripper/wsg50_one_motor_gripper_free_base.sdf", &gBufferServerToClient[0], gBufferServerToClient.size(), true);
m_data->m_gripperId = bodyId + 1;
InteralBodyData* kukaBody = m_data->getHandle(m_data->m_KukaId);
InteralBodyData* gripperBody = m_data->getHandle(m_data->m_gripperId);
@@ -2963,6 +2975,13 @@ void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec)
}
}
for (int i = 0; i < 6; i++)
{
loadUrdf("jenga/jenga.urdf", btVector3(-1-0.1*i,-0.5, .07), btQuaternion(btVector3(0,1,0),SIMD_HALF_PI), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
}
//loadUrdf("nao/nao.urdf", btVector3(2,5, 1), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
// Add slider joint for fingers
btVector3 pivotInParent1(0, 0, 0.06);
btVector3 pivotInChild1(0, 0, 0);
@@ -3005,7 +3024,6 @@ void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec)
loadUrdf("sphere2.urdf", btVector3(-5, 0, 1), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("sphere2.urdf", btVector3(-5, 0, 2), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("sphere2.urdf", btVector3(-5, 0, 3), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("r2d2.urdf", btVector3(2, -2, 1), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
// Shelf area
loadSdf("kiva_shelf/model.sdf", &gBufferServerToClient[0], gBufferServerToClient.size(), true);
@@ -3013,15 +3031,6 @@ void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec)
loadUrdf("sphere_small.urdf", btVector3(-0.1, 0.6, 1.25), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("cube_small.urdf", btVector3(0.3, 0.6, 0.85), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
// Table area
loadUrdf("table.urdf", btVector3(0, -1.9, 0.0), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("tray.urdf", btVector3(0, -1.7, 0.64), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("cup_small.urdf", btVector3(0.5, -2.0, 0.85), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("pitcher_small.urdf", btVector3(0.4, -1.8, 0.85), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("teddy_vhacd.urdf", btVector3(-0.1, -1.9, 0.7), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("cube_small.urdf", btVector3(0.1, -1.8, 0.7), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("sphere_small.urdf", btVector3(-0.2, -1.7, 0.7), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
// Chess area
loadUrdf("table_square.urdf", btVector3(2.0, 0, 0.0), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
loadUrdf("pawn.urdf", btVector3(1.8, -0.1, 0.7), btQuaternion(0, 0, 0, 1), true, false, &bodyId, &gBufferServerToClient[0], gBufferServerToClient.size());
@@ -3114,7 +3123,7 @@ void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec)
if (closeToKuka)
{
int dampIk = 1;
double dampIk[6] = {1.0, 1.0, 1.0, 1.0, 1.0, 0.0};
IKTrajectoryHelper** ikHelperPtrPtr = m_data->m_inverseKinematicsHelpers.find(bodyHandle->m_multiBody);
IKTrajectoryHelper* ikHelperPtr = 0;

View File

@@ -1181,16 +1181,22 @@ void PhysicsServerExample::vrControllerButtonCallback(int controllerId, int butt
} else
{
gDebugRenderToggle = 0;
simTimeScalingFactor *= 0.5;
if (simTimeScalingFactor==0)
{
simTimeScalingFactor = 1;
} else
{
if (simTimeScalingFactor==1)
{
simTimeScalingFactor = 0.25;
}
if (simTimeScalingFactor<0.01)
else
{
simTimeScalingFactor = 0;
}
}
}
} else
{

View File

@@ -117,6 +117,13 @@ struct b3JointInfo
double m_jointAxis[3]; // joint axis in parent local frame
};
struct b3BodyInfo
{
const char* m_baseName;
};
struct b3JointSensorState
{
double m_jointPosition;

View File

@@ -3,8 +3,7 @@
project ("pybullet")
language "C++"
kind "SharedLib"
targetsuffix ("")
targetprefix ("")
includedirs {"../../src", "../../examples",
"../../examples/ThirdPartyLibs"}
defines {"PHYSICS_IN_PROCESS_EXAMPLE_BROWSER"}

View File

@@ -567,7 +567,7 @@ static int pybullet_internalGetBasePositionAndOrientation(
const int status_type = b3GetStatusType(status_handle);
const double* actualStateQ;
// const double* jointReactionForces[];
int i;
if (status_type != CMD_ACTUAL_STATE_UPDATE_COMPLETED) {
PyErr_SetString(SpamError, "getBasePositionAndOrientation failed.");
@@ -661,10 +661,88 @@ static PyObject* pybullet_getBasePositionAndOrientation(PyObject* self,
}
}
static PyObject* pybullet_getNumBodies(PyObject* self, PyObject* args)
{
if (0 == sm) {
PyErr_SetString(SpamError, "Not connected to physics server.");
return NULL;
}
{
int numBodies = b3GetNumBodies(sm);
#if PY_MAJOR_VERSION >= 3
return PyLong_FromLong(numBodies);
#else
return PyInt_FromLong(numBodies);
#endif
}
}
static PyObject* pybullet_getBodyUniqueId(PyObject* self, PyObject* args)
{
if (0 == sm) {
PyErr_SetString(SpamError, "Not connected to physics server.");
return NULL;
}
{
int serialIndex = -1;
int bodyUniqueId = -1;
if (!PyArg_ParseTuple(args, "i", &serialIndex)) {
PyErr_SetString(SpamError, "Expected a serialIndex in range [0..number of bodies).");
return NULL;
}
bodyUniqueId = b3GetBodyUniqueId(sm, serialIndex);
#if PY_MAJOR_VERSION >= 3
return PyLong_FromLong(bodyUniqueId);
#else
return PyInt_FromLong(bodyUniqueId);
#endif
}
}
static PyObject* pybullet_getBodyInfo(PyObject* self, PyObject* args)
{
if (0 == sm) {
PyErr_SetString(SpamError, "Not connected to physics server.");
return NULL;
}
{
int bodyUniqueId= -1;
int numJoints = 0;
if (!PyArg_ParseTuple(args, "i", &bodyUniqueId))
{
PyErr_SetString(SpamError, "Expected a body unique id (integer).");
return NULL;
}
{
struct b3BodyInfo info;
if (b3GetBodyInfo(sm,bodyUniqueId,&info))
{
PyObject* pyListJointInfo = PyTuple_New(1);
PyTuple_SetItem(pyListJointInfo, 0, PyString_FromString(info.m_baseName));
return pyListJointInfo;
} else
{
PyErr_SetString(SpamError, "Couldn't get body info");
return NULL;
}
}
}
PyErr_SetString(SpamError, "error in getBodyInfo.");
return NULL;
}
// Return the number of joints in an object based on
// body index; body index is based on order of sequence
// the object is loaded into simulation
static PyObject* pybullet_getNumJoints(PyObject* self, PyObject* args) {
static PyObject* pybullet_getNumJoints(PyObject* self, PyObject* args)
{
if (0 == sm) {
PyErr_SetString(SpamError, "Not connected to physics server.");
return NULL;
@@ -888,16 +966,15 @@ static PyObject* pybullet_getJointInfo(PyObject* self, PyObject* args) {
static PyObject* pybullet_getJointState(PyObject* self, PyObject* args) {
PyObject* pyListJointForceTorque;
PyObject* pyListJointState;
PyObject* item;
struct b3JointInfo info;
struct b3JointSensorState sensorState;
int bodyIndex = -1;
int jointIndex = -1;
int sensorStateSize = 4; // size of struct b3JointSensorState
int forceTorqueSize = 6; // size of force torque list from b3JointSensorState
int i, j;
int j;
int size = PySequence_Size(args);
@@ -909,6 +986,11 @@ static PyObject* pybullet_getJointState(PyObject* self, PyObject* args) {
if (size == 2) // get body index and joint index
{
if (PyArg_ParseTuple(args, "ii", &bodyIndex, &jointIndex)) {
int status_type = 0;
b3SharedMemoryCommandHandle cmd_handle;
b3SharedMemoryStatusHandle status_handle;
if (bodyIndex < 0) {
PyErr_SetString(SpamError, "getJointState failed; invalid bodyIndex");
return NULL;
@@ -918,10 +1000,10 @@ static PyObject* pybullet_getJointState(PyObject* self, PyObject* args) {
return NULL;
}
int status_type = 0;
b3SharedMemoryCommandHandle cmd_handle =
cmd_handle =
b3RequestActualStateCommandInit(sm, bodyIndex);
b3SharedMemoryStatusHandle status_handle =
status_handle =
b3SubmitClientCommandAndWaitStatus(sm, cmd_handle);
status_type = b3GetStatusType(status_handle);
@@ -984,6 +1066,10 @@ static PyObject* pybullet_getLinkState(PyObject* self, PyObject* args) {
if (PySequence_Size(args) == 2) // body index and link index
{
if (PyArg_ParseTuple(args, "ii", &bodyIndex, &linkIndex)) {
int status_type = 0;
b3SharedMemoryCommandHandle cmd_handle;
b3SharedMemoryStatusHandle status_handle;
if (bodyIndex < 0) {
PyErr_SetString(SpamError, "getLinkState failed; invalid bodyIndex");
return NULL;
@@ -993,10 +1079,10 @@ static PyObject* pybullet_getLinkState(PyObject* self, PyObject* args) {
return NULL;
}
int status_type = 0;
b3SharedMemoryCommandHandle cmd_handle =
cmd_handle =
b3RequestActualStateCommandInit(sm, bodyIndex);
b3SharedMemoryStatusHandle status_handle =
status_handle =
b3SubmitClientCommandAndWaitStatus(sm, cmd_handle);
status_type = b3GetStatusType(status_handle);
@@ -1996,6 +2082,15 @@ static PyMethodDef SpamMethods[] = {
{"loadSDF", pybullet_loadSDF, METH_VARARGS,
"Load multibodies from an SDF file."},
{"getNumBodies", pybullet_getNumBodies, METH_VARARGS,
"Get the number of bodies in the simulation."},
{"getBodyUniqueId", pybullet_getBodyUniqueId, METH_VARARGS,
"Get the unique id of the body, given a integer serial index in range [0.. number of bodies)."},
{"getBodyInfo", pybullet_getBodyInfo, METH_VARARGS,
"Get the body info, given a body unique id."},
{"getBasePositionAndOrientation", pybullet_getBasePositionAndOrientation,
METH_VARARGS,
"Get the world position and orientation of the base of the object. "

View File

@@ -77,7 +77,7 @@ struct btContactSolverInfo : public btContactSolverInfoData
m_maxErrorReduction = btScalar(20.);
m_numIterations = 10;
m_erp = btScalar(0.2);
m_erp2 = btScalar(0.8);
m_erp2 = btScalar(0.2);
m_globalCfm = btScalar(0.);
m_sor = btScalar(1.);
m_splitImpulse = true;

View File

@@ -769,8 +769,8 @@ void btMultiBody::computeAccelerationsArticulatedBodyAlgorithmMultiDof(btScalar
//adding damping terms (only)
btScalar linDampMult = 1., angDampMult = 1.;
zeroAccSpatFrc[0].addVector(angDampMult * m_baseInertia * spatVel[0].getAngular() * (DAMPING_K1_ANGULAR + DAMPING_K2_ANGULAR * spatVel[0].getAngular().norm()),
linDampMult * m_baseMass * spatVel[0].getLinear() * (DAMPING_K1_LINEAR + DAMPING_K2_LINEAR * spatVel[0].getLinear().norm()));
zeroAccSpatFrc[0].addVector(angDampMult * m_baseInertia * spatVel[0].getAngular() * (DAMPING_K1_ANGULAR + DAMPING_K2_ANGULAR * spatVel[0].getAngular().safeNorm()),
linDampMult * m_baseMass * spatVel[0].getLinear() * (DAMPING_K1_LINEAR + DAMPING_K2_LINEAR * spatVel[0].getLinear().safeNorm()));
//
//p += vhat x Ihat vhat - done in a simpler way
@@ -856,8 +856,8 @@ void btMultiBody::computeAccelerationsArticulatedBodyAlgorithmMultiDof(btScalar
//
//adding damping terms (only)
btScalar linDampMult = 1., angDampMult = 1.;
zeroAccSpatFrc[i+1].addVector(angDampMult * m_links[i].m_inertiaLocal * spatVel[i+1].getAngular() * (DAMPING_K1_ANGULAR + DAMPING_K2_ANGULAR * spatVel[i+1].getAngular().norm()),
linDampMult * m_links[i].m_mass * spatVel[i+1].getLinear() * (DAMPING_K1_LINEAR + DAMPING_K2_LINEAR * spatVel[i+1].getLinear().norm()));
zeroAccSpatFrc[i+1].addVector(angDampMult * m_links[i].m_inertiaLocal * spatVel[i+1].getAngular() * (DAMPING_K1_ANGULAR + DAMPING_K2_ANGULAR * spatVel[i+1].getAngular().safeNorm()),
linDampMult * m_links[i].m_mass * spatVel[i+1].getLinear() * (DAMPING_K1_LINEAR + DAMPING_K2_LINEAR * spatVel[i+1].getLinear().safeNorm()));
// calculate Ihat_i^A
//init the spatial AB inertia (it has the simple form thanks to choosing local body frames origins at their COMs)

View File

@@ -133,7 +133,7 @@ void btMultiBodySliderConstraint::createConstraintRows(btMultiBodyConstraintArra
for (int i = 0; i < 3; ++i)
{
constraintAxis[0] = frameAworld.getColumn(i).cross(jointAxis);
if (constraintAxis[0].norm() > EPSILON)
if (constraintAxis[0].safeNorm() > EPSILON)
{
constraintAxis[0] = constraintAxis[0].normalized();
constraintAxis[1] = jointAxis.cross(constraintAxis[0]);

View File

@@ -271,6 +271,16 @@ public:
return length();
}
/**@brief Return the norm (length) of the vector */
SIMD_FORCE_INLINE btScalar safeNorm() const
{
btScalar d = length2();
//workaround for some clang/gcc issue of sqrtf(tiny number) = -INF
if (d>SIMD_EPSILON)
return btSqrt(d);
return btScalar(0);
}
/**@brief Return the distance squared between the ends of this and another vector
* This is symantically treating the vector like a point */
SIMD_FORCE_INLINE btScalar distance2(const btVector3& v) const;