mSilhouetteExtractor.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _MSILHOUETTEEXTRACTOR_H_
  23. #define _MSILHOUETTEEXTRACTOR_H_
  24. #ifndef _FRAMEALLOCATOR_H_
  25. #include "core/frameAllocator.h"
  26. #endif
  27. #ifndef _TVECTOR_H_
  28. #include "core/util/tVector.h"
  29. #endif
  30. /// @file
  31. /// Routines for extracting silhouette polygons from polyhedrons.
  32. template< typename Polyhedron >
  33. struct SilhouetteExtractorBase
  34. {
  35. typedef Polyhedron PolyhedronType;
  36. protected:
  37. /// The polyhedron from which we are extracting silhouettes.
  38. const PolyhedronType* mPolyhedron;
  39. SilhouetteExtractorBase( const PolyhedronType& polyhedron )
  40. : mPolyhedron( &polyhedron ) {}
  41. };
  42. /// Silhouette extraction routines for perspective projections.
  43. template< typename Polyhedron >
  44. struct SilhouetteExtractorBasePerspective : public SilhouetteExtractorBase< Polyhedron >
  45. {
  46. private:
  47. enum Orientation
  48. {
  49. FrontFacing,
  50. BackFacing
  51. };
  52. /// @name Per-Extraction Data
  53. /// @{
  54. /// The facing direction of each of the polygons.
  55. mutable Orientation* mPolygonOrientations;
  56. /// Frame allocator water mark to release temporary memory after silhouette extraction.
  57. mutable U32 mWaterMark;
  58. /// @}
  59. public:
  60. SilhouetteExtractorBasePerspective( const Polyhedron& polyhedron )
  61. : SilhouetteExtractorBase< Polyhedron >( polyhedron ),
  62. mPolygonOrientations( NULL ),
  63. mWaterMark( 0 ) {}
  64. /// Initialize extraction.
  65. ///
  66. /// @param objectView View->object matrix.
  67. bool begin( const MatrixF& camView ) const
  68. {
  69. mWaterMark = FrameAllocator::getWaterMark();
  70. // Determine orientation of each of the polygons.
  71. const U32 numPolygons = this->mPolyhedron->getNumPlanes();
  72. mPolygonOrientations = ( Orientation* ) FrameAllocator::alloc( sizeof( Orientation ) * numPolygons );
  73. Point3F camPos = camView.getPosition();
  74. for( U32 i = 0; i < numPolygons; ++ i )
  75. {
  76. if (this->mPolyhedron->getPlanes()[i].whichSide( camPos ) == PlaneF::Front)
  77. mPolygonOrientations[i] = FrontFacing;
  78. else
  79. mPolygonOrientations[i] = BackFacing;
  80. }
  81. return true;
  82. }
  83. /// End extraction.
  84. void end() const
  85. {
  86. FrameAllocator::setWaterMark( mWaterMark );
  87. mWaterMark = 0;
  88. mPolygonOrientations = NULL;
  89. }
  90. /// Return true if the given edge is a silhouette edge with respect to the
  91. /// current perspective transform.
  92. ///
  93. /// @param edgeIndex Index of edge to test.
  94. /// @return True if the given edge is a silhouette when looked at from the given view position.
  95. ///
  96. /// @note This method depends on inward-facing normals!
  97. bool isSilhouetteEdge( U32 edgeIndex ) const
  98. {
  99. AssertFatal( edgeIndex < this->mPolyhedron->getNumEdges(), "SilhouetteExtractorBasePerspective::isSilhouetteEdge - Index out of range!" );
  100. const typename Polyhedron::EdgeType& edge = this->mPolyhedron->getEdges()[ edgeIndex ];
  101. const U32 face0 = edge.face[ 0 ];
  102. const U32 face1 = edge.face[ 1 ];
  103. return ( mPolygonOrientations[ face0 ] != mPolygonOrientations[ face1 ] );
  104. }
  105. };
  106. /// Silhouette extraction routines for orthographic projections.
  107. template< typename Polyhedron >
  108. struct SilhouetteExtractorBaseOrtho : public SilhouetteExtractorBase< Polyhedron >
  109. {
  110. private:
  111. /// @name Per-Extraction Data
  112. /// @{
  113. /// Precomputed dot products between view direction and plane normals
  114. /// in the polyhedron.
  115. mutable F32* mFaceDotProducts;
  116. /// Frame allocator water mark.
  117. mutable U32 mWaterMark;
  118. /// @}
  119. public:
  120. SilhouetteExtractorBaseOrtho( const Polyhedron& polyhedron )
  121. : SilhouetteExtractorBase< Polyhedron >( polyhedron ),
  122. mFaceDotProducts( NULL ),
  123. mWaterMark( 0 )
  124. {
  125. }
  126. /// Initialize the extractor.
  127. void begin( const Point3F& viewDirOS ) const
  128. {
  129. const typename Polyhedron::PlaneType* planes = this->mPolyhedron->getPlanes();
  130. const U32 numPlanes = this->mPolyhedron->getNumPlanes();
  131. mWaterMark = FrameAllocator::getWaterMark();
  132. mFaceDotProducts = ( F32* ) FrameAllocator::alloc( sizeof( F32 ) * numPlanes );
  133. for( U32 i = 0; i < numPlanes; ++ i )
  134. mFaceDotProducts[ i ] = mDot( planes[ i ], viewDirOS );
  135. }
  136. /// Finish extraction.
  137. void end() const
  138. {
  139. FrameAllocator::setWaterMark( mWaterMark );
  140. mFaceDotProducts = NULL;
  141. mWaterMark = 0;
  142. }
  143. /// Return true if the given edge is a silhouette edge with respect to the
  144. /// view direction.
  145. ///
  146. /// @param edgeIndex Index of edge to test.
  147. /// @return True if the given edge is a silhouette in the projection along the view direction.
  148. ///
  149. /// @note This method depends on inward-facing normals!
  150. bool isSilhouetteEdge( U32 edgeIndex ) const
  151. {
  152. AssertFatal( edgeIndex < this->mPolyhedron->getNumEdges(), "SilhouetteExtractorBaseOrtho::isSilhouetteEdge - Index out of range!" );
  153. const typename Polyhedron::EdgeType& edge = this->mPolyhedron->getEdges()[ edgeIndex ];
  154. const U32 face0 = edge.face[ 0 ];
  155. const U32 face1 = edge.face[ 1 ];
  156. // Not a silhouette if both planes are facing the same way.
  157. if( mSign( mFaceDotProducts[ face0 ] ) == mSign( mFaceDotProducts[ face1 ] ) )
  158. return false;
  159. // Find out which face is the front facing one. Since we expect normals
  160. // to be pointing inwards, this means a reversal of the normal back facing
  161. // test and we're looking for a normal facing the *same* way as our projection.
  162. const U32 frontFace = mFaceDotProducts[ face0 ] > 0.f ? face0 : face1;
  163. if( mFaceDotProducts[ frontFace ] <= 0.f )
  164. return false; // This face or other face is perpendicular to us.
  165. return true;
  166. }
  167. };
  168. /// Common implementation parts for silhouette extraction.
  169. template< typename Base >
  170. struct SilhouetteExtractorImpl : public Base
  171. {
  172. typedef typename Base::PolyhedronType PolyhedronType;
  173. SilhouetteExtractorImpl( const PolyhedronType& polyhedron )
  174. : Base( polyhedron ) {}
  175. U32 extractSilhouette( U32* outIndices, U32 maxOutIndices ) const
  176. {
  177. // First, find the silhouette edges. We do this with a brute-force
  178. // approach here. This can be optimized (see "Silhouette Algorithms" by Bruce Gooch, Mark
  179. // Hartner, and Nathan Beddes).
  180. U32 numSilhouetteEdges = 0;
  181. const U32 numTotalEdges = this->mPolyhedron->getNumEdges();
  182. const typename PolyhedronType::EdgeType* edges = this->mPolyhedron->getEdges();
  183. FrameTemp< const typename PolyhedronType::EdgeType* > silhouetteEdges( numTotalEdges );
  184. for( U32 i = 0; i < numTotalEdges; ++ i )
  185. if( this->isSilhouetteEdge( i ) )
  186. silhouetteEdges[ numSilhouetteEdges ++ ] = &edges[ i ];
  187. // Allow this to happen rather than asserting as projection-based silhouettes
  188. // may fail.
  189. if( numSilhouetteEdges < 3 )
  190. return 0;
  191. // Now walk the edge list and find the edges that are connected
  192. // with each other. From this information, emit the silhouette
  193. // polygon.
  194. U32 idx = 0;
  195. if( idx >= maxOutIndices )
  196. return 0;
  197. outIndices[ idx ++ ] = silhouetteEdges[ 0 ]->vertex[ 1 ];
  198. U32 currentIndex = silhouetteEdges[ 0 ]->vertex[ 1 ];
  199. U32 currentEdge = 0;
  200. for( U32 i = 1; i < numSilhouetteEdges; ++ i )
  201. {
  202. // Find edge that continues on from the current vertex.
  203. for( U32 n = 0; n < numSilhouetteEdges; ++ n )
  204. {
  205. // Skip current edge.
  206. if( n == currentEdge )
  207. continue;
  208. if( silhouetteEdges[ n ]->vertex[ 0 ] == currentIndex )
  209. currentIndex = silhouetteEdges[ n ]->vertex[ 1 ];
  210. else if( silhouetteEdges[ n ]->vertex[ 1 ] == currentIndex )
  211. currentIndex = silhouetteEdges[ n ]->vertex[ 0 ];
  212. else
  213. continue;
  214. if( idx >= maxOutIndices )
  215. return 0;
  216. currentEdge = n;
  217. outIndices[ idx ++ ] = currentIndex;
  218. break;
  219. }
  220. }
  221. return idx;
  222. }
  223. };
  224. /// Silhouette edge extraction for orthographic projections.
  225. template< typename Polyhedron >
  226. struct SilhouetteExtractorOrtho
  227. {
  228. protected:
  229. typedef SilhouetteExtractorImpl< SilhouetteExtractorBaseOrtho< Polyhedron > > ExtractorType;
  230. /// The actual extractor implementation.
  231. ExtractorType mExtractor;
  232. public:
  233. SilhouetteExtractorOrtho( const Polyhedron& polyhedron )
  234. : mExtractor( polyhedron ) {}
  235. /// Generate a silhouette polygon for the polyhedron based on the given view direction.
  236. ///
  237. /// @param viewDirOS Object-space normalized view vector.
  238. /// @param outIndices Array where the resulting vertex indices will be stored. Must have
  239. /// enough room. If you don't know the exact size that you need, just allocate one index
  240. /// for any point in the mesh.
  241. /// @param maxOutIndices The number of indices that can be stored in @a outIndices. If insufficient,
  242. /// the return value will be 0.
  243. ///
  244. /// @return Number of indices written to @a outIndices or 0 if the silhouette extraction failed.
  245. ///
  246. /// @note Be aware that silhouette polygons are in most cases non-planar!
  247. /// @note The direction of the ordering of the resulting indices is undefined meaning that
  248. /// different silhouettes extracted from the same polyhedron may have different CCW/CW ordering.
  249. /// The only guarantee is that the resulting indices are consecutive.
  250. U32 extractSilhouette( const Point3F& viewDirOS, U32* outIndices, U32 maxOutIndices ) const
  251. {
  252. U32 result = 0;
  253. mExtractor.begin( viewDirOS );
  254. result = mExtractor.extractSilhouette( outIndices, maxOutIndices );
  255. mExtractor.end();
  256. return result;
  257. }
  258. };
  259. /// Silhouette edge extraction for perspective projections.
  260. template< typename Polyhedron >
  261. struct SilhouetteExtractorPerspective
  262. {
  263. protected:
  264. typedef SilhouetteExtractorImpl< SilhouetteExtractorBasePerspective< Polyhedron > > ExtractorType;
  265. /// The actual extractor implementation.
  266. ExtractorType mExtractor;
  267. public:
  268. SilhouetteExtractorPerspective( const Polyhedron& polyhedron )
  269. : mExtractor( polyhedron ) {}
  270. /// Generate a silhouette polygon for this polyhedron based on the transforms.
  271. ///
  272. /// @param camView View->object matrix.
  273. /// @param outIndices Array where the resulting vertex indices will be stored. Must have
  274. /// enough room. If you don't know the exact size that you need, just allocate one index
  275. /// for any point in the mesh.
  276. /// @param maxOutIndices The number of indices that can be stored in @a outIndices. If insufficient,
  277. /// the return value will be 0.
  278. ///
  279. /// @return Number of indices written to @a outIndices.
  280. ///
  281. /// @note Be aware that silhouette polygons are in most cases non-planar!
  282. /// @note The direction of the ordering of the resulting indices is undefined meaning that
  283. /// different silhouettes extracted from the same polyhedron may have different CCW/CW ordering.
  284. /// The only guarantee is that the resulting indices are consecutive.
  285. U32 extractSilhouette( const MatrixF& camView, U32* outIndices, U32 maxOutIndices ) const
  286. {
  287. U32 result = 0;
  288. if( mExtractor.begin( camView ) )
  289. result = mExtractor.extractSilhouette( outIndices, maxOutIndices );
  290. mExtractor.end();
  291. return result;
  292. }
  293. };
  294. #endif // !_MSILHOUETTEEXTRACTOR_H_