Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

343 рядки
14 KiB

  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the helper class to quickly find vertices close to a given position */
  35. #include "AssimpPCH.h"
  36. #include "SpatialSort.h"
  37. using namespace Assimp;
  38. // CHAR_BIT seems to be defined under MVSC, but not under GCC. Pray that the correct value is 8.
  39. #ifndef CHAR_BIT
  40. # define CHAR_BIT 8
  41. #endif
  42. // ------------------------------------------------------------------------------------------------
  43. // Constructs a spatially sorted representation from the given position array.
  44. SpatialSort::SpatialSort( const aiVector3D* pPositions, unsigned int pNumPositions,
  45. unsigned int pElementOffset)
  46. // define the reference plane. We choose some arbitrary vector away from all basic axises
  47. // in the hope that no model spreads all its vertices along this plane.
  48. : mPlaneNormal(0.8523f, 0.34321f, 0.5736f)
  49. {
  50. mPlaneNormal.Normalize();
  51. Fill(pPositions,pNumPositions,pElementOffset);
  52. }
  53. // ------------------------------------------------------------------------------------------------
  54. SpatialSort :: SpatialSort()
  55. : mPlaneNormal(0.8523f, 0.34321f, 0.5736f)
  56. {
  57. mPlaneNormal.Normalize();
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. // Destructor
  61. SpatialSort::~SpatialSort()
  62. {
  63. // nothing to do here, everything destructs automatically
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. void SpatialSort::Fill( const aiVector3D* pPositions, unsigned int pNumPositions,
  67. unsigned int pElementOffset,
  68. bool pFinalize /*= true */)
  69. {
  70. mPositions.clear();
  71. Append(pPositions,pNumPositions,pElementOffset,pFinalize);
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. void SpatialSort :: Finalize()
  75. {
  76. std::sort( mPositions.begin(), mPositions.end());
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. void SpatialSort::Append( const aiVector3D* pPositions, unsigned int pNumPositions,
  80. unsigned int pElementOffset,
  81. bool pFinalize /*= true */)
  82. {
  83. // store references to all given positions along with their distance to the reference plane
  84. const size_t initial = mPositions.size();
  85. mPositions.reserve(initial + (pFinalize?pNumPositions:pNumPositions*2));
  86. for( unsigned int a = 0; a < pNumPositions; a++)
  87. {
  88. const char* tempPointer = reinterpret_cast<const char*> (pPositions);
  89. const aiVector3D* vec = reinterpret_cast<const aiVector3D*> (tempPointer + a * pElementOffset);
  90. // store position by index and distance
  91. float distance = *vec * mPlaneNormal;
  92. mPositions.push_back( Entry( a+initial, *vec, distance));
  93. }
  94. if (pFinalize) {
  95. // now sort the array ascending by distance.
  96. Finalize();
  97. }
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Returns an iterator for all positions close to the given position.
  101. void SpatialSort::FindPositions( const aiVector3D& pPosition,
  102. float pRadius, std::vector<unsigned int>& poResults) const
  103. {
  104. const float dist = pPosition * mPlaneNormal;
  105. const float minDist = dist - pRadius, maxDist = dist + pRadius;
  106. // clear the array in this strange fashion because a simple clear() would also deallocate
  107. // the array which we want to avoid
  108. poResults.erase( poResults.begin(), poResults.end());
  109. // quick check for positions outside the range
  110. if( mPositions.size() == 0)
  111. return;
  112. if( maxDist < mPositions.front().mDistance)
  113. return;
  114. if( minDist > mPositions.back().mDistance)
  115. return;
  116. // do a binary search for the minimal distance to start the iteration there
  117. unsigned int index = (unsigned int)mPositions.size() / 2;
  118. unsigned int binaryStepSize = (unsigned int)mPositions.size() / 4;
  119. while( binaryStepSize > 1)
  120. {
  121. if( mPositions[index].mDistance < minDist)
  122. index += binaryStepSize;
  123. else
  124. index -= binaryStepSize;
  125. binaryStepSize /= 2;
  126. }
  127. // depending on the direction of the last step we need to single step a bit back or forth
  128. // to find the actual beginning element of the range
  129. while( index > 0 && mPositions[index].mDistance > minDist)
  130. index--;
  131. while( index < (mPositions.size() - 1) && mPositions[index].mDistance < minDist)
  132. index++;
  133. // Mow start iterating from there until the first position lays outside of the distance range.
  134. // Add all positions inside the distance range within the given radius to the result aray
  135. std::vector<Entry>::const_iterator it = mPositions.begin() + index;
  136. const float pSquared = pRadius*pRadius;
  137. while( it->mDistance < maxDist)
  138. {
  139. if( (it->mPosition - pPosition).SquareLength() < pSquared)
  140. poResults.push_back( it->mIndex);
  141. ++it;
  142. if( it == mPositions.end())
  143. break;
  144. }
  145. // that's it
  146. }
  147. namespace {
  148. // Binary, signed-integer representation of a single-precision floating-point value.
  149. // IEEE 754 says: "If two floating-point numbers in the same format are ordered then they are
  150. // ordered the same way when their bits are reinterpreted as sign-magnitude integers."
  151. // This allows us to convert all floating-point numbers to signed integers of arbitrary size
  152. // and then use them to work with ULPs (Units in the Last Place, for high-precision
  153. // computations) or to compare them (integer comparisons are faster than floating-point
  154. // comparisons on many platforms).
  155. typedef signed int BinFloat;
  156. // --------------------------------------------------------------------------------------------
  157. // Converts the bit pattern of a floating-point number to its signed integer representation.
  158. BinFloat ToBinary( const float & pValue) {
  159. // If this assertion fails, signed int is not big enough to store a float on your platform.
  160. // Please correct the declaration of BinFloat a few lines above - but do it in a portable,
  161. // #ifdef'd manner!
  162. BOOST_STATIC_ASSERT( sizeof(BinFloat) >= sizeof(float));
  163. #if defined( _MSC_VER)
  164. // If this assertion fails, Visual C++ has finally moved to ILP64. This means that this
  165. // code has just become legacy code! Find out the current value of _MSC_VER and modify
  166. // the #if above so it evaluates false on the current and all upcoming VC versions (or
  167. // on the current platform, if LP64 or LLP64 are still used on other platforms).
  168. BOOST_STATIC_ASSERT( sizeof(BinFloat) == sizeof(float));
  169. // This works best on Visual C++, but other compilers have their problems with it.
  170. const BinFloat binValue = reinterpret_cast<BinFloat const &>(pValue);
  171. #else
  172. // On many compilers, reinterpreting a float address as an integer causes aliasing
  173. // problems. This is an ugly but more or less safe way of doing it.
  174. union {
  175. float asFloat;
  176. BinFloat asBin;
  177. } conversion;
  178. conversion.asBin = 0; // zero empty space in case sizeof(BinFloat) > sizeof(float)
  179. conversion.asFloat = pValue;
  180. const BinFloat binValue = conversion.asBin;
  181. #endif
  182. // floating-point numbers are of sign-magnitude format, so find out what signed number
  183. // representation we must convert negative values to.
  184. // See http://en.wikipedia.org/wiki/Signed_number_representations.
  185. // Two's complement?
  186. if( (-42 == (~42 + 1)) && (binValue & 0x80000000))
  187. return BinFloat(1 << (CHAR_BIT * sizeof(BinFloat) - 1)) - binValue;
  188. // One's complement?
  189. else if( (-42 == ~42) && (binValue & 0x80000000))
  190. return BinFloat(-0) - binValue;
  191. // Sign-magnitude?
  192. else if( (-42 == (42 | (-0))) && (binValue & 0x80000000)) // -0 = 1000... binary
  193. return binValue;
  194. else
  195. return binValue;
  196. }
  197. } // namespace
  198. // ------------------------------------------------------------------------------------------------
  199. // Fills an array with indices of all positions indentical to the given position. In opposite to
  200. // FindPositions(), not an epsilon is used but a (very low) tolerance of four floating-point units.
  201. void SpatialSort::FindIdenticalPositions( const aiVector3D& pPosition,
  202. std::vector<unsigned int>& poResults) const
  203. {
  204. // Epsilons have a huge disadvantage: they are of constant precision, while floating-point
  205. // values are of log2 precision. If you apply e=0.01 to 100, the epsilon is rather small, but
  206. // if you apply it to 0.001, it is enormous.
  207. // The best way to overcome this is the unit in the last place (ULP). A precision of 2 ULPs
  208. // tells us that a float does not differ more than 2 bits from the "real" value. ULPs are of
  209. // logarithmic precision - around 1, they are 1÷(2^24) and around 10000, they are 0.00125.
  210. // For standard C math, we can assume a precision of 0.5 ULPs according to IEEE 754. The
  211. // incoming vertex positions might have already been transformed, probably using rather
  212. // inaccurate SSE instructions, so we assume a tolerance of 4 ULPs to safely identify
  213. // identical vertex positions.
  214. static const int toleranceInULPs = 4;
  215. // An interesting point is that the inaccuracy grows linear with the number of operations:
  216. // multiplying to numbers, each inaccurate to four ULPs, results in an inaccuracy of four ULPs
  217. // plus 0.5 ULPs for the multiplication.
  218. // To compute the distance to the plane, a dot product is needed - that is a multiplication and
  219. // an addition on each number.
  220. static const int distanceToleranceInULPs = toleranceInULPs + 1;
  221. // The squared distance between two 3D vectors is computed the same way, but with an additional
  222. // subtraction.
  223. static const int distance3DToleranceInULPs = distanceToleranceInULPs + 1;
  224. // Convert the plane distance to its signed integer representation so the ULPs tolerance can be
  225. // applied. For some reason, VC won't optimize two calls of the bit pattern conversion.
  226. const BinFloat minDistBinary = ToBinary( pPosition * mPlaneNormal) - distanceToleranceInULPs;
  227. const BinFloat maxDistBinary = minDistBinary + 2 * distanceToleranceInULPs;
  228. // clear the array in this strange fashion because a simple clear() would also deallocate
  229. // the array which we want to avoid
  230. poResults.erase( poResults.begin(), poResults.end());
  231. // do a binary search for the minimal distance to start the iteration there
  232. unsigned int index = (unsigned int)mPositions.size() / 2;
  233. unsigned int binaryStepSize = (unsigned int)mPositions.size() / 4;
  234. while( binaryStepSize > 1)
  235. {
  236. // Ugly, but conditional jumps are faster with integers than with floats
  237. if( minDistBinary > ToBinary(mPositions[index].mDistance))
  238. index += binaryStepSize;
  239. else
  240. index -= binaryStepSize;
  241. binaryStepSize /= 2;
  242. }
  243. // depending on the direction of the last step we need to single step a bit back or forth
  244. // to find the actual beginning element of the range
  245. while( index > 0 && minDistBinary < ToBinary(mPositions[index].mDistance) )
  246. index--;
  247. while( index < (mPositions.size() - 1) && minDistBinary > ToBinary(mPositions[index].mDistance))
  248. index++;
  249. // Now start iterating from there until the first position lays outside of the distance range.
  250. // Add all positions inside the distance range within the tolerance to the result aray
  251. std::vector<Entry>::const_iterator it = mPositions.begin() + index;
  252. while( ToBinary(it->mDistance) < maxDistBinary)
  253. {
  254. if( distance3DToleranceInULPs >= ToBinary((it->mPosition - pPosition).SquareLength()))
  255. poResults.push_back(it->mIndex);
  256. ++it;
  257. if( it == mPositions.end())
  258. break;
  259. }
  260. // that's it
  261. }
  262. // ------------------------------------------------------------------------------------------------
  263. unsigned int SpatialSort::GenerateMappingTable(std::vector<unsigned int>& fill,float pRadius) const
  264. {
  265. fill.resize(mPositions.size(),UINT_MAX);
  266. float dist, maxDist;
  267. unsigned int t=0;
  268. const float pSquared = pRadius*pRadius;
  269. for (size_t i = 0; i < mPositions.size();) {
  270. dist = mPositions[i].mPosition * mPlaneNormal;
  271. maxDist = dist + pRadius;
  272. fill[mPositions[i].mIndex] = t;
  273. const aiVector3D& oldpos = mPositions[i].mPosition;
  274. for (++i; i < fill.size() && mPositions[i].mDistance < maxDist
  275. && (mPositions[i].mPosition - oldpos).SquareLength() < pSquared; ++i)
  276. {
  277. fill[mPositions[i].mIndex] = t;
  278. }
  279. ++t;
  280. }
  281. #ifdef ASSIMP_BUILD_DEBUG
  282. // debug invariant: mPositions[i].mIndex values must range from 0 to mPositions.size()-1
  283. for (size_t i = 0; i < fill.size(); ++i) {
  284. ai_assert(fill[i]<mPositions.size());
  285. }
  286. #endif
  287. return t;
  288. }