sceneCullingState.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. #include "platform/platform.h"
  23. #include "scene/culling/sceneCullingState.h"
  24. #include "scene/sceneManager.h"
  25. #include "scene/sceneObject.h"
  26. #include "scene/zones/sceneZoneSpace.h"
  27. #include "math/mathUtils.h"
  28. #include "platform/profiler.h"
  29. #include "terrain/terrData.h"
  30. #include "util/tempAlloc.h"
  31. #include "gfx/sim/debugDraw.h"
  32. extern bool gEditingMission;
  33. bool SceneCullingState::smDisableTerrainOcclusion = true;
  34. bool SceneCullingState::smDisableZoneCulling = false;
  35. U32 SceneCullingState::smMaxOccludersPerZone = 4;
  36. F32 SceneCullingState::smOccluderMinWidthPercentage = 0.1f;
  37. F32 SceneCullingState::smOccluderMinHeightPercentage = 0.1f;
  38. //-----------------------------------------------------------------------------
  39. SceneCullingState::SceneCullingState( SceneManager* sceneManager, const SceneCameraState& viewState )
  40. : mSceneManager( sceneManager ),
  41. mCameraState( viewState ),
  42. mDisableTerrainOcclusion( smDisableTerrainOcclusion ),
  43. mDisableZoneCulling( smDisableZoneCulling )
  44. {
  45. AssertFatal( sceneManager->getZoneManager(), "SceneCullingState::SceneCullingState - SceneManager must have a zone manager!" );
  46. VECTOR_SET_ASSOCIATION( mZoneStates );
  47. VECTOR_SET_ASSOCIATION( mAddedOccluderObjects );
  48. // Allocate zone states.
  49. const U32 numZones = sceneManager->getZoneManager()->getNumZones();
  50. mZoneStates.setSize( numZones );
  51. dMemset( mZoneStates.address(), 0, sizeof( SceneZoneCullingState ) * numZones );
  52. // Allocate the zone visibility flags.
  53. mZoneVisibilityFlags.setSize( numZones );
  54. mZoneVisibilityFlags.clear();
  55. // Culling frustum
  56. mCullingFrustum = mCameraState.getFrustum();
  57. mCullingFrustum.bakeProjectionOffset();
  58. // Construct the root culling volume from
  59. // the culling frustum. Omit the frustum's
  60. // near and far plane so we don't test it repeatedly.
  61. PlaneF* planes = allocateData< PlaneF >( 4 );
  62. planes[ 0 ] = mCullingFrustum.getPlanes()[ Frustum::PlaneLeft ];
  63. planes[ 1 ] = mCullingFrustum.getPlanes()[ Frustum::PlaneRight ];
  64. planes[ 2 ] = mCullingFrustum.getPlanes()[ Frustum::PlaneTop];
  65. planes[ 3 ] = mCullingFrustum.getPlanes()[ Frustum::PlaneBottom ];
  66. mRootVolume = SceneCullingVolume(
  67. SceneCullingVolume::Includer,
  68. PlaneSetF( planes, 4 )
  69. );
  70. clearExtraPlanesCull();
  71. }
  72. //-----------------------------------------------------------------------------
  73. bool SceneCullingState::isWithinVisibleZone( SceneObject* object ) const
  74. {
  75. for( SceneObject::ZoneRef* ref = object->_getZoneRefHead();
  76. ref != NULL; ref = ref->nextInObj )
  77. if( mZoneVisibilityFlags.test( ref->zone ) )
  78. return true;
  79. return false;
  80. }
  81. //-----------------------------------------------------------------------------
  82. void SceneCullingState::addOccluder( SceneObject* object )
  83. {
  84. PROFILE_SCOPE( SceneCullingState_addOccluder );
  85. // If the occluder is itself occluded, don't add it.
  86. //
  87. // NOTE: We do allow near plane intersections here. Silhouette extraction
  88. // should take that into account.
  89. if( cullObjects( &object, 1, DontCullRenderDisabled ) != 1 )
  90. return;
  91. // If the occluder has already been added, do nothing. Check this
  92. // after the culling check since the same occluder can be added by
  93. // two separate zones and not be visible in one yet be visible in the
  94. // other.
  95. if( mAddedOccluderObjects.contains( object ) )
  96. return;
  97. mAddedOccluderObjects.push_back( object );
  98. // Let the object build a silhouette. If it doesn't
  99. // return one, abort.
  100. Vector< Point3F > silhouette;
  101. object->buildSilhouette( getCameraState(), silhouette );
  102. if( silhouette.empty() || silhouette.size() < 3 )
  103. return;
  104. // Generate the culling volume.
  105. SceneCullingVolume volume;
  106. if( !createCullingVolume(
  107. silhouette.address(),
  108. silhouette.size(),
  109. SceneCullingVolume::Occluder,
  110. volume ) )
  111. return;
  112. // Add the frustum to all zones that the object is assigned to.
  113. for( SceneObject::ZoneRef* ref = object->_getZoneRefHead(); ref != NULL; ref = ref->nextInObj )
  114. addCullingVolumeToZone( ref->zone, volume );
  115. }
  116. //-----------------------------------------------------------------------------
  117. bool SceneCullingState::addCullingVolumeToZone( U32 zoneId, const SceneCullingVolume& volume )
  118. {
  119. PROFILE_SCOPE( SceneCullingState_addCullingVolumeToZone );
  120. AssertFatal( zoneId < mZoneStates.size(), "SceneCullingState::addCullingVolumeToZone - Zone ID out of range" );
  121. SceneZoneCullingState& zoneState = mZoneStates[ zoneId ];
  122. // [rene, 07-Apr-10] I previously used to attempt to merge things here and detect whether
  123. // the visibility state of the zone has changed at all. Since we allow polyhedra to be
  124. // degenerate here and since polyhedra cannot be merged easily like frustums, I have opted
  125. // to remove this for now. I'm also convinced that with the current traversal system it
  126. // adds little benefit.
  127. // Link the volume to the zone state.
  128. typedef SceneZoneCullingState::CullingVolumeLink LinkType;
  129. LinkType* link = reinterpret_cast< LinkType* >( allocateData( sizeof( LinkType ) ) );
  130. link->mVolume = volume;
  131. link->mNext = zoneState.mCullingVolumes;
  132. zoneState.mCullingVolumes = link;
  133. if( volume.isOccluder() )
  134. zoneState.mHaveOccluders = true;
  135. else
  136. zoneState.mHaveIncluders = true;
  137. // Mark sorting state as dirty.
  138. zoneState.mHaveSortedVolumes = false;
  139. // Set the visibility flag for the zone.
  140. if( volume.isIncluder() )
  141. mZoneVisibilityFlags.set( zoneId );
  142. return true;
  143. }
  144. //-----------------------------------------------------------------------------
  145. bool SceneCullingState::addCullingVolumeToZone( U32 zoneId, SceneCullingVolume::Type type, const AnyPolyhedron& polyhedron )
  146. {
  147. // Allocate space on our chunker.
  148. const U32 numPlanes = polyhedron.getNumPlanes();
  149. PlaneF* planes = allocateData< PlaneF >( numPlanes );
  150. // Copy the planes over.
  151. dMemcpy( planes, polyhedron.getPlanes(), numPlanes * sizeof( planes[ 0 ] ) );
  152. // Create a culling volume.
  153. SceneCullingVolume volume(
  154. type,
  155. PlaneSetF( planes, numPlanes )
  156. );
  157. // And add it.
  158. return addCullingVolumeToZone( zoneId, volume );
  159. }
  160. //-----------------------------------------------------------------------------
  161. bool SceneCullingState::createCullingVolume( const Point3F* vertices, U32 numVertices, SceneCullingVolume::Type type, SceneCullingVolume& outVolume )
  162. {
  163. const Point3F& viewPos = getCameraState().getViewPosition();
  164. const Point3F& viewDir = getCameraState().getViewDirection();
  165. const bool isOrtho = getCullingFrustum().isOrtho();
  166. //TODO: check if we need to handle penetration of the near plane for occluders specially
  167. // Allocate space for the clipping planes we generate. Assume the worst case
  168. // of every edge generating a plane and, for includers, all edges meeting at
  169. // steep angles so we need to insert extra planes (the latter is not possible,
  170. // of course, but it makes things less complicated here). For occluders, add
  171. // an extra plane for the near cap.
  172. const U32 maxPlanes = ( type == SceneCullingVolume::Occluder ? numVertices + 1 : numVertices * 2 );
  173. PlaneF* planes = allocateData< PlaneF >( maxPlanes );
  174. // Keep track of the world-space bounds of the polygon. We use this later
  175. // to derive some metrics.
  176. Box3F wsPolyBounds;
  177. wsPolyBounds.minExtents = Point3F( TypeTraits< F32 >::MAX, TypeTraits< F32 >::MAX, TypeTraits< F32 >::MAX );
  178. wsPolyBounds.maxExtents = Point3F( TypeTraits< F32 >::MIN, TypeTraits< F32 >::MIN, TypeTraits< F32 >::MIN );
  179. // For occluders, also keep track of the nearest, and two farthest silhouette points. We use
  180. // this later to construct a near capping plane.
  181. F32 minVertexDistanceSquared = TypeTraits< F32 >::MAX;
  182. U32 leastDistantVert = 0;
  183. F32 maxVertexDistancesSquared[ 2 ] = { TypeTraits< F32 >::MIN, TypeTraits< F32 >::MIN };
  184. U32 mostDistantVertices[ 2 ] = { 0, 0 };
  185. // Generate the extrusion volume. For orthographic projections, extrude
  186. // parallel to the view direction whereas for parallel projections, extrude
  187. // from the viewpoint.
  188. U32 numPlanes = 0;
  189. U32 lastVertex = numVertices - 1;
  190. bool invert = false;
  191. for( U32 i = 0; i < numVertices; lastVertex = i, ++ i )
  192. {
  193. AssertFatal( numPlanes < maxPlanes, "SceneCullingState::createCullingVolume - Did not allocate enough planes!" );
  194. const Point3F& v1 = vertices[ i ];
  195. const Point3F& v2 = vertices[ lastVertex ];
  196. // Keep track of bounds.
  197. wsPolyBounds.minExtents.setMin( v1 );
  198. wsPolyBounds.maxExtents.setMax( v1 );
  199. // Skip the edge if it's length is really short.
  200. const Point3F edgeVector = v2 - v1;
  201. const F32 edgeVectorLenSquared = edgeVector.lenSquared();
  202. if( edgeVectorLenSquared < 0.025f )
  203. continue;
  204. //TODO: might need to do additional checks here for non-planar polygons used by occluders
  205. //TODO: test for colinearity of edge vector with view vector (occluders only)
  206. // Create a plane for the edge.
  207. if( isOrtho )
  208. {
  209. // Compute a plane through the two edge vertices and one
  210. // of the vertices extended along the view direction.
  211. if( !invert )
  212. planes[ numPlanes ] = PlaneF( v1, v1 + viewDir, v2 );
  213. else
  214. planes[ numPlanes ] = PlaneF( v2, v1 + viewDir, v1 );
  215. }
  216. else
  217. {
  218. // Compute a plane going through the viewpoint and the two
  219. // edge vertices.
  220. if( !invert )
  221. planes[ numPlanes ] = PlaneF( v1, viewPos, v2 );
  222. else
  223. planes[ numPlanes ] = PlaneF( v2, viewPos, v1 );
  224. }
  225. numPlanes ++;
  226. // If this is the first plane that we have created, find out whether
  227. // the vertex ordering is giving us the plane orientations that we want
  228. // (facing inside). If not, invert vertex order from now on.
  229. if( numPlanes == 1 )
  230. {
  231. Point3F center( 0, 0, 0 );
  232. for( U32 n = 0; n < numVertices; ++ n )
  233. center += vertices[n];
  234. center /= numVertices;
  235. if( planes[numPlanes - 1].whichSide( center ) == PlaneF::Back )
  236. {
  237. invert = true;
  238. planes[ numPlanes - 1 ].invert();
  239. }
  240. }
  241. // For occluders, keep tabs of the nearest, and two farthest vertices.
  242. if( type == SceneCullingVolume::Occluder )
  243. {
  244. const F32 distSquared = ( v1 - viewPos ).lenSquared();
  245. if( distSquared < minVertexDistanceSquared )
  246. {
  247. minVertexDistanceSquared = distSquared;
  248. leastDistantVert = i;
  249. }
  250. if( distSquared > maxVertexDistancesSquared[ 0 ] )
  251. {
  252. // Move 0 to 1.
  253. maxVertexDistancesSquared[ 1 ] = maxVertexDistancesSquared[ 0 ];
  254. mostDistantVertices[ 1 ] = mostDistantVertices[ 0 ];
  255. // Replace 0.
  256. maxVertexDistancesSquared[ 0 ] = distSquared;
  257. mostDistantVertices[ 0 ] = i;
  258. }
  259. else if( distSquared > maxVertexDistancesSquared[ 1 ] )
  260. {
  261. // Replace 1.
  262. maxVertexDistancesSquared[ 1 ] = distSquared;
  263. mostDistantVertices[ 1 ] = i;
  264. }
  265. }
  266. }
  267. // If the extrusion produced no useful result, abort.
  268. if( numPlanes < 3 )
  269. return false;
  270. // For includers, test the angle of the edges at the current vertex.
  271. // If too steep, add an extra plane to improve culling efficiency.
  272. if( false )//type == SceneCullingVolume::Includer )
  273. {
  274. const U32 numOriginalPlanes = numPlanes;
  275. U32 lastPlaneIndex = numPlanes - 1;
  276. for( U32 i = 0; i < numOriginalPlanes; lastPlaneIndex = i, ++ i )
  277. {
  278. const PlaneF& currentPlane = planes[ i ];
  279. const PlaneF& lastPlane = planes[ lastPlaneIndex ];
  280. // Compute the cosine of the angle between the two plane normals.
  281. const F32 cosAngle = mFabs( mDot( currentPlane, lastPlane ) );
  282. // The planes meet at increasingly steep angles the more they point
  283. // in opposite directions, i.e the closer the angle of their normals
  284. // is to 180 degrees. Skip any two planes that don't get near that.
  285. if( cosAngle > 0.1f )
  286. continue;
  287. Point3F newNormal = currentPlane + lastPlane;//addNormals - mDot( addNormals, crossNormals ) * crossNormals;
  288. //
  289. planes[ numPlanes ] = PlaneF( currentPlane.getPosition(), newNormal );
  290. numPlanes ++;
  291. }
  292. }
  293. // Compute the metrics of the culling volume in relation to the view frustum.
  294. //
  295. // For this, we are short-circuiting things slightly. The correct way (other than doing
  296. // full screen projections) would be to transform all the polygon points into camera
  297. // space, lay an AABB around those points, and then find the X and Z extents on the near plane.
  298. //
  299. // However, while not as accurate, a faster way is to just project the axial vectors
  300. // of the bounding box onto both the camera right and up vector. This gives us a rough
  301. // estimate of the camera-space size of the polygon we're looking at.
  302. const MatrixF& cameraTransform = getCameraState().getViewWorldMatrix();
  303. const Point3F cameraRight = cameraTransform.getRightVector();
  304. const Point3F cameraUp = cameraTransform.getUpVector();
  305. const Point3F wsPolyBoundsExtents = wsPolyBounds.getExtents();
  306. F32 widthEstimate =
  307. getMax( mFabs( wsPolyBoundsExtents.x * cameraRight.x ),
  308. getMax( mFabs( wsPolyBoundsExtents.y * cameraRight.y ),
  309. mFabs( wsPolyBoundsExtents.z * cameraRight.z ) ) );
  310. F32 heightEstimate =
  311. getMax( mFabs( wsPolyBoundsExtents.x * cameraUp.x ),
  312. getMax( mFabs( wsPolyBoundsExtents.y * cameraUp.y ),
  313. mFabs( wsPolyBoundsExtents.z * cameraUp.z ) ) );
  314. // If the current camera is a perspective one, divide the two estimates
  315. // by the distance of the nearest bounding box vertex to the camera
  316. // to account for perspective distortion.
  317. if( !isOrtho )
  318. {
  319. const Point3F nearestVertex = wsPolyBounds.computeVertex(
  320. Box3F::getPointIndexFromOctant( - viewDir )
  321. );
  322. const F32 distance = ( nearestVertex - viewPos ).len();
  323. widthEstimate /= distance;
  324. heightEstimate /= distance;
  325. }
  326. // If we are creating an occluder, check to see if the estimates fit
  327. // our minimum requirements.
  328. if( type == SceneCullingVolume::Occluder )
  329. {
  330. const F32 widthEstimatePercentage = widthEstimate / getCullingFrustum().getWidth();
  331. const F32 heightEstimatePercentage = heightEstimate / getCullingFrustum().getHeight();
  332. if( widthEstimatePercentage < smOccluderMinWidthPercentage ||
  333. heightEstimatePercentage < smOccluderMinHeightPercentage )
  334. return false; // Reject.
  335. }
  336. // Use the area estimate as the volume's sort point.
  337. const F32 sortPoint = widthEstimate * heightEstimate;
  338. // Finally, if it's an occluder, compute a near cap. The near cap prevents objects
  339. // in front of the occluder from testing positive. The same could be achieved by
  340. // manually comparing distances before testing objects but since that would amount
  341. // to the same checks the plane/AABB tests do, it's easier to just add another plane.
  342. // Additionally, it gives the benefit of being able to create more precise culling
  343. // results by angling the plane.
  344. //NOTE: Could consider adding a near cap for includers too when generating a volume
  345. // for the outdoor zone as that may prevent quite a bit of space from being included.
  346. // However, given that this space will most likely just be filled with interior
  347. // stuff anyway, it's probably not worth it.
  348. if( type == SceneCullingVolume::Occluder )
  349. {
  350. const U32 nearCapIndex = numPlanes;
  351. planes[ nearCapIndex ] = PlaneF(
  352. vertices[ mostDistantVertices[ 0 ] ],
  353. vertices[ mostDistantVertices[ 1 ] ],
  354. vertices[ leastDistantVert ] );
  355. // Invert the plane, if necessary.
  356. if( planes[ nearCapIndex ].whichSide( viewPos ) == PlaneF::Front )
  357. planes[ nearCapIndex ].invert();
  358. numPlanes ++;
  359. }
  360. // Create the volume from the planes.
  361. outVolume = SceneCullingVolume(
  362. type,
  363. PlaneSetF( planes, numPlanes )
  364. );
  365. outVolume.setSortPoint( sortPoint );
  366. // Done.
  367. return true;
  368. }
  369. //-----------------------------------------------------------------------------
  370. namespace {
  371. struct ZoneArrayIterator
  372. {
  373. U32 mCurrent;
  374. U32 mNumZones;
  375. const U32* mZones;
  376. ZoneArrayIterator( const U32* zones, U32 numZones )
  377. : mCurrent( 0 ),
  378. mNumZones( numZones ),
  379. mZones( zones ) {}
  380. bool isValid() const
  381. {
  382. return ( mCurrent < mNumZones );
  383. }
  384. ZoneArrayIterator& operator ++()
  385. {
  386. mCurrent ++;
  387. return *this;
  388. }
  389. U32 operator *() const
  390. {
  391. return mZones[ mCurrent ];
  392. }
  393. };
  394. }
  395. template< typename T, typename Iter >
  396. inline SceneZoneCullingState::CullingTestResult SceneCullingState::_testOccludersOnly( const T& bounds, Iter zoneIter ) const
  397. {
  398. // Test the culling states of all zones that the object
  399. // is assigned to.
  400. for( ; zoneIter.isValid(); ++ zoneIter )
  401. {
  402. const SceneZoneCullingState& zoneState = getZoneState( *zoneIter );
  403. // Skip zone if there are no occluders.
  404. if( !zoneState.hasOccluders() )
  405. continue;
  406. // If the object's world bounds overlaps any of the volumes
  407. // for this zone, it's rendered.
  408. if( zoneState.testVolumes( bounds, true ) == SceneZoneCullingState::CullingTestPositiveByOcclusion )
  409. return SceneZoneCullingState::CullingTestPositiveByOcclusion;
  410. }
  411. return SceneZoneCullingState::CullingTestNegative;
  412. }
  413. template< typename T, typename Iter >
  414. inline SceneZoneCullingState::CullingTestResult SceneCullingState::_test( const T& bounds, Iter zoneIter,
  415. const PlaneF& nearPlane, const PlaneF& farPlane ) const
  416. {
  417. // Defer test of near and far plane until we've hit a zone
  418. // which actually has visible space. This prevents us from
  419. // doing near/far tests on objects that were included in the
  420. // potential render list but aren't actually in any visible
  421. // zone.
  422. bool haveTestedNearAndFar = false;
  423. // Test the culling states of all zones that the object
  424. // is assigned to.
  425. for( ; zoneIter.isValid(); ++ zoneIter )
  426. {
  427. const SceneZoneCullingState& zoneState = getZoneState( *zoneIter );
  428. // Skip zone if there are no positive culling volumes.
  429. if( !zoneState.hasIncluders() )
  430. continue;
  431. // If we haven't tested the near and far plane yet, do so
  432. // now.
  433. if( !haveTestedNearAndFar )
  434. {
  435. // Test near plane.
  436. PlaneF::Side nearSide = nearPlane.whichSide( bounds );
  437. if( nearSide == PlaneF::Back )
  438. return SceneZoneCullingState::CullingTestNegative;
  439. // Test far plane.
  440. PlaneF::Side farSide = farPlane.whichSide( bounds );
  441. if( farSide == PlaneF::Back )
  442. return SceneZoneCullingState::CullingTestNegative;
  443. haveTestedNearAndFar = true;
  444. }
  445. // If the object's world bounds overlaps any of the volumes
  446. // for this zone, it's rendered.
  447. SceneZoneCullingState::CullingTestResult result = zoneState.testVolumes( bounds );
  448. if( result == SceneZoneCullingState::CullingTestPositiveByInclusion )
  449. return result;
  450. else if( result == SceneZoneCullingState::CullingTestPositiveByOcclusion )
  451. return result;
  452. }
  453. return SceneZoneCullingState::CullingTestNegative;
  454. }
  455. //-----------------------------------------------------------------------------
  456. template< bool OCCLUDERS_ONLY, typename T >
  457. inline SceneZoneCullingState::CullingTestResult SceneCullingState::_test( const T& bounds, const U32* zones, U32 numZones ) const
  458. {
  459. // If zone culling is disabled, only test against
  460. // the root frustum.
  461. if( disableZoneCulling() )
  462. {
  463. if( !OCCLUDERS_ONLY && !getCullingFrustum().isCulled( bounds ) )
  464. return SceneZoneCullingState::CullingTestPositiveByInclusion;
  465. return SceneZoneCullingState::CullingTestNegative;
  466. }
  467. // Otherwise test each of the zones.
  468. if( OCCLUDERS_ONLY )
  469. {
  470. return _testOccludersOnly(
  471. bounds,
  472. ZoneArrayIterator( zones, numZones )
  473. );
  474. }
  475. else
  476. {
  477. const PlaneF* frustumPlanes = getCullingFrustum().getPlanes();
  478. return _test(
  479. bounds,
  480. ZoneArrayIterator( zones, numZones ),
  481. frustumPlanes[ Frustum::PlaneNear ],
  482. frustumPlanes[ Frustum::PlaneFar ]
  483. );
  484. }
  485. }
  486. //-----------------------------------------------------------------------------
  487. bool SceneCullingState::isCulled( const Box3F& aabb, const U32* zones, U32 numZones ) const
  488. {
  489. SceneZoneCullingState::CullingTestResult result = _test< false >( aabb, zones, numZones );
  490. return ( result == SceneZoneCullingState::CullingTestNegative ||
  491. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  492. }
  493. //-----------------------------------------------------------------------------
  494. bool SceneCullingState::isCulled( const OrientedBox3F& obb, const U32* zones, U32 numZones ) const
  495. {
  496. SceneZoneCullingState::CullingTestResult result = _test< false >( obb, zones, numZones );
  497. return ( result == SceneZoneCullingState::CullingTestNegative ||
  498. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  499. }
  500. //-----------------------------------------------------------------------------
  501. bool SceneCullingState::isCulled( const SphereF& sphere, const U32* zones, U32 numZones ) const
  502. {
  503. SceneZoneCullingState::CullingTestResult result = _test< false >( sphere, zones, numZones );
  504. return ( result == SceneZoneCullingState::CullingTestNegative ||
  505. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  506. }
  507. //-----------------------------------------------------------------------------
  508. bool SceneCullingState::isOccluded( SceneObject* object ) const
  509. {
  510. if( disableZoneCulling() )
  511. return false;
  512. CullingTestResult result = _testOccludersOnly(
  513. object->getWorldBox(),
  514. SceneObject::ObjectZonesIterator( object )
  515. );
  516. return ( result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  517. }
  518. //-----------------------------------------------------------------------------
  519. bool SceneCullingState::isOccluded( const Box3F& aabb, const U32* zones, U32 numZones ) const
  520. {
  521. return ( _test< true >( aabb, zones, numZones ) == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  522. }
  523. //-----------------------------------------------------------------------------
  524. bool SceneCullingState::isOccluded( const OrientedBox3F& obb, const U32* zones, U32 numZones ) const
  525. {
  526. return ( _test< true >( obb, zones, numZones ) == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  527. }
  528. //-----------------------------------------------------------------------------
  529. bool SceneCullingState::isOccluded( const SphereF& sphere, const U32* zones, U32 numZones ) const
  530. {
  531. return ( _test< true >( sphere, zones, numZones ) == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  532. }
  533. //-----------------------------------------------------------------------------
  534. U32 SceneCullingState::cullObjects( SceneObject** objects, U32 numObjects, U32 cullOptions ) const
  535. {
  536. PROFILE_SCOPE( SceneCullingState_cullObjects );
  537. U32 numRemainingObjects = 0;
  538. // We test near and far planes separately in order to not do the tests
  539. // repeatedly, so fetch the planes now.
  540. const PlaneF& nearPlane = getCullingFrustum().getPlanes()[ Frustum::PlaneNear ];
  541. const PlaneF& farPlane = getCullingFrustum().getPlanes()[ Frustum::PlaneFar ];
  542. for( U32 i = 0; i < numObjects; ++ i )
  543. {
  544. SceneObject* object = objects[ i ];
  545. bool isCulled = true;
  546. // If we should respect editor overrides, test that now.
  547. if( !( cullOptions & CullEditorOverrides ) &&
  548. gEditingMission &&
  549. ( ( object->isCullingDisabledInEditor() && object->isRenderEnabled() ) || object->isSelected() ) )
  550. {
  551. isCulled = false;
  552. }
  553. // If the object is render-disabled, it gets culled. The only
  554. // way around this is the editor override above.
  555. else if( !( cullOptions & DontCullRenderDisabled ) &&
  556. !object->isRenderEnabled() )
  557. {
  558. isCulled = true;
  559. }
  560. // Global bounds objects are never culled. Note that this means
  561. // that if these objects are to respect zoning, they need to manually
  562. // trigger the respective culling checks for whatever they want to
  563. // batch.
  564. else if( object->isGlobalBounds() )
  565. isCulled = false;
  566. // If terrain occlusion checks are enabled, run them now.
  567. else if( !mDisableTerrainOcclusion &&
  568. object->getWorldBox().minExtents.x > -1e5 &&
  569. isOccludedByTerrain( object ) )
  570. {
  571. // Occluded by terrain.
  572. isCulled = true;
  573. }
  574. // If the object shouldn't be subjected to more fine-grained culling
  575. // or if zone culling is disabled, just test against the root frustum.
  576. else if( !( object->getTypeMask() & CULLING_INCLUDE_TYPEMASK ) ||
  577. ( object->getTypeMask() & CULLING_EXCLUDE_TYPEMASK ) ||
  578. disableZoneCulling() )
  579. {
  580. isCulled = getCullingFrustum().isCulled( object->getWorldBox() );
  581. }
  582. // Go through the zones that the object is assigned to and
  583. // test the object against the frustums of each of the zones.
  584. else
  585. {
  586. CullingTestResult result = _test(
  587. object->getWorldBox(),
  588. SceneObject::ObjectZonesIterator( object ),
  589. nearPlane,
  590. farPlane
  591. );
  592. isCulled = ( result == SceneZoneCullingState::CullingTestNegative ||
  593. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  594. }
  595. if( !isCulled )
  596. isCulled = isOccludedWithExtraPlanesCull( object->getWorldBox() );
  597. if( !isCulled )
  598. objects[ numRemainingObjects ++ ] = object;
  599. }
  600. return numRemainingObjects;
  601. }
  602. //-----------------------------------------------------------------------------
  603. bool SceneCullingState::isOccludedByTerrain( SceneObject* object ) const
  604. {
  605. PROFILE_SCOPE( SceneCullingState_isOccludedByTerrain );
  606. // Don't try to occlude globally bounded objects.
  607. if( object->isGlobalBounds() )
  608. return false;
  609. const Vector< SceneObject* >& terrains = getSceneManager()->getContainer()->getTerrains();
  610. const U32 numTerrains = terrains.size();
  611. for( U32 terrainIdx = 0; terrainIdx < numTerrains; ++ terrainIdx )
  612. {
  613. TerrainBlock* terrain = dynamic_cast< TerrainBlock* >( terrains[ terrainIdx ] );
  614. if( !terrain )
  615. continue;
  616. MatrixF terrWorldTransform = terrain->getWorldTransform();
  617. Point3F localCamPos = getCameraState().getViewPosition();
  618. terrWorldTransform.mulP(localCamPos);
  619. F32 height;
  620. terrain->getHeight( Point2F( localCamPos.x, localCamPos.y ), &height );
  621. bool aboveTerrain = ( height <= localCamPos.z );
  622. // Don't occlude if we're below the terrain. This prevents problems when
  623. // looking out from underground bases...
  624. if( !aboveTerrain )
  625. continue;
  626. const Box3F& oBox = object->getObjBox();
  627. F32 minSide = getMin(oBox.len_x(), oBox.len_y());
  628. if (minSide > 85.0f)
  629. continue;
  630. const Box3F& rBox = object->getWorldBox();
  631. Point3F ul(rBox.minExtents.x, rBox.minExtents.y, rBox.maxExtents.z);
  632. Point3F ur(rBox.minExtents.x, rBox.maxExtents.y, rBox.maxExtents.z);
  633. Point3F ll(rBox.maxExtents.x, rBox.minExtents.y, rBox.maxExtents.z);
  634. Point3F lr(rBox.maxExtents.x, rBox.maxExtents.y, rBox.maxExtents.z);
  635. terrWorldTransform.mulP(ul);
  636. terrWorldTransform.mulP(ur);
  637. terrWorldTransform.mulP(ll);
  638. terrWorldTransform.mulP(lr);
  639. Point3F xBaseL0_s = ul - localCamPos;
  640. Point3F xBaseL0_e = lr - localCamPos;
  641. Point3F xBaseL1_s = ur - localCamPos;
  642. Point3F xBaseL1_e = ll - localCamPos;
  643. static F32 checkPoints[3] = {0.75, 0.5, 0.25};
  644. RayInfo rinfo;
  645. for( U32 i = 0; i < 3; i ++ )
  646. {
  647. Point3F start = (xBaseL0_s * checkPoints[i]) + localCamPos;
  648. Point3F end = (xBaseL0_e * checkPoints[i]) + localCamPos;
  649. if (terrain->castRay(start, end, &rinfo))
  650. continue;
  651. terrain->getHeight(Point2F(start.x, start.y), &height);
  652. if ((height <= start.z) == aboveTerrain)
  653. continue;
  654. start = (xBaseL1_s * checkPoints[i]) + localCamPos;
  655. end = (xBaseL1_e * checkPoints[i]) + localCamPos;
  656. if (terrain->castRay(start, end, &rinfo))
  657. continue;
  658. Point3F test = (start + end) * 0.5;
  659. if (terrain->castRay(localCamPos, test, &rinfo) == false)
  660. continue;
  661. return true;
  662. }
  663. }
  664. return false;
  665. }
  666. //-----------------------------------------------------------------------------
  667. void SceneCullingState::debugRenderCullingVolumes() const
  668. {
  669. const ColorI occluderColor( 255, 0, 0, 255 );
  670. const ColorI includerColor( 0, 255, 0, 255 );
  671. const PlaneF& nearPlane = getCullingFrustum().getPlanes()[ Frustum::PlaneNear ];
  672. const PlaneF& farPlane = getCullingFrustum().getPlanes()[ Frustum::PlaneFar ];
  673. DebugDrawer* drawer = DebugDrawer::get();
  674. const SceneZoneSpaceManager* zoneManager = mSceneManager->getZoneManager();
  675. bool haveDebugZone = false;
  676. const U32 numZones = mZoneStates.size();
  677. for( S32 zoneId = numZones - 1; zoneId >= 0; -- zoneId )
  678. {
  679. if( !zoneManager->isValidZoneId( zoneId ) )
  680. continue;
  681. const SceneZoneCullingState& zoneState = mZoneStates[ zoneId ];
  682. if( !zoneManager->getZoneOwner( zoneId )->isSelected() && ( zoneId != SceneZoneSpaceManager::RootZoneId || haveDebugZone ) )
  683. continue;
  684. haveDebugZone = true;
  685. for( SceneZoneCullingState::CullingVolumeIterator iter( zoneState );
  686. iter.isValid(); ++ iter )
  687. {
  688. // Temporarily add near and far plane to culling volume so that
  689. // no matter how it is defined, it has a chance of being properly
  690. // capped.
  691. const U32 numPlanes = iter->getPlanes().getNumPlanes();
  692. const PlaneF* planes = iter->getPlanes().getPlanes();
  693. TempAlloc< PlaneF > tempPlanes( numPlanes + 2 );
  694. tempPlanes[ 0 ] = nearPlane;
  695. tempPlanes[ 1 ] = farPlane;
  696. dMemcpy( &tempPlanes[ 2 ], planes, numPlanes * sizeof( PlaneF ) );
  697. // Build a polyhedron from the plane set.
  698. Polyhedron polyhedron;
  699. polyhedron.buildFromPlanes(
  700. PlaneSetF( tempPlanes, numPlanes + 2 )
  701. );
  702. // If the polyhedron has any renderable data,
  703. // hand it over to the debug drawer.
  704. if( polyhedron.getNumEdges() )
  705. drawer->drawPolyhedron( polyhedron, iter->isOccluder() ? occluderColor : includerColor );
  706. }
  707. }
  708. }