reflector.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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/reflector.h"
  24. #include "console/consoleTypes.h"
  25. #include "gfx/gfxCubemap.h"
  26. #include "gfx/gfxDebugEvent.h"
  27. #include "gfx/gfxTransformSaver.h"
  28. #include "scene/sceneManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "core/stream/bitStream.h"
  31. #include "scene/reflectionManager.h"
  32. #include "gui/3d/guiTSControl.h"
  33. #include "ts/tsShapeInstance.h"
  34. #include "gfx/gfxOcclusionQuery.h"
  35. #include "lighting/lightManager.h"
  36. #include "lighting/shadowMap/lightShadowMap.h"
  37. #include "math/mathUtils.h"
  38. #include "math/util/frustum.h"
  39. #include "gfx/screenshot.h"
  40. #include "postFx/postEffectManager.h"
  41. extern ColorI gCanvasClearColor;
  42. //-------------------------------------------------------------------------
  43. // ReflectorDesc
  44. //-------------------------------------------------------------------------
  45. IMPLEMENT_CO_DATABLOCK_V1( ReflectorDesc );
  46. ConsoleDocClass( ReflectorDesc,
  47. "@brief A datablock which defines performance and quality properties for "
  48. "dynamic reflections.\n\n"
  49. "ReflectorDesc is not itself a reflection and does not render reflections. "
  50. "It is a dummy class for holding and exposing to the user a set of "
  51. "reflection related properties. Objects which support dynamic reflections "
  52. "may then reference a ReflectorDesc.\n\n"
  53. "@tsexample\n"
  54. "datablock ReflectorDesc( ExampleReflectorDesc )\n"
  55. "{\n"
  56. " texSize = 256;\n"
  57. " nearDist = 0.1;\n"
  58. " farDist = 500;\n"
  59. " objectTypeMask = 0xFFFFFFFF;\n"
  60. " detailAdjust = 1.0;\n"
  61. " priority = 1.0;\n"
  62. " maxRateMs = 0;\n"
  63. " useOcclusionQuery = true;\n"
  64. "};\n"
  65. "@endtsexample\n"
  66. "@see ShapeBaseData::cubeReflectorDesc\n"
  67. "@ingroup enviroMisc"
  68. );
  69. ReflectorDesc::ReflectorDesc()
  70. {
  71. texSize = 256;
  72. nearDist = 0.1f;
  73. farDist = 1000.0f;
  74. objectTypeMask = 0xFFFFFFFF;
  75. detailAdjust = 1.0f;
  76. priority = 1.0f;
  77. maxRateMs = 15;
  78. useOcclusionQuery = true;
  79. }
  80. ReflectorDesc::~ReflectorDesc()
  81. {
  82. }
  83. void ReflectorDesc::initPersistFields()
  84. {
  85. addGroup( "ReflectorDesc" );
  86. addField( "texSize", TypeS32, Offset( texSize, ReflectorDesc ),
  87. "Size in pixels of the (square) reflection texture. For a cubemap "
  88. "this value is interpreted as size of each face." );
  89. addField( "nearDist", TypeF32, Offset( nearDist, ReflectorDesc ),
  90. "Near plane distance to use when rendering this reflection. Adjust "
  91. "this to limit self-occlusion artifacts." );
  92. addField( "farDist", TypeF32, Offset( farDist, ReflectorDesc ),
  93. "Far plane distance to use when rendering reflections." );
  94. addField( "objectTypeMask", TypeS32, Offset( objectTypeMask, ReflectorDesc ),
  95. "Object types which render into this reflection." );
  96. addField( "detailAdjust", TypeF32, Offset( detailAdjust, ReflectorDesc ),
  97. "Scale applied to lod calculation of objects rendering into "
  98. "this reflection ( modulates $pref::TS::detailAdjust )." );
  99. addField( "priority", TypeF32, Offset( priority, ReflectorDesc ),
  100. "Priority for updating this reflection, relative to others." );
  101. addField( "maxRateMs", TypeS32, Offset( maxRateMs, ReflectorDesc ),
  102. "If less than maxRateMs has elapsed since this relfection was last "
  103. "updated, then do not update it again. This 'skip' can be disabled by "
  104. "setting maxRateMs to zero." );
  105. addField( "useOcclusionQuery", TypeBool, Offset( useOcclusionQuery, ReflectorDesc ),
  106. "If available on the device use HOQs to determine if the reflective object "
  107. "is visible before updating its reflection." );
  108. endGroup( "ReflectorDesc" );
  109. Parent::initPersistFields();
  110. }
  111. void ReflectorDesc::packData( BitStream *stream )
  112. {
  113. Parent::packData( stream );
  114. stream->write( texSize );
  115. stream->write( nearDist );
  116. stream->write( farDist );
  117. stream->write( objectTypeMask );
  118. stream->write( detailAdjust );
  119. stream->write( priority );
  120. stream->write( maxRateMs );
  121. stream->writeFlag( useOcclusionQuery );
  122. }
  123. void ReflectorDesc::unpackData( BitStream *stream )
  124. {
  125. Parent::unpackData( stream );
  126. stream->read( &texSize );
  127. stream->read( &nearDist );
  128. stream->read( &farDist );
  129. stream->read( &objectTypeMask );
  130. stream->read( &detailAdjust );
  131. stream->read( &priority );
  132. stream->read( &maxRateMs );
  133. useOcclusionQuery = stream->readFlag();
  134. }
  135. bool ReflectorDesc::preload( bool server, String &errorStr )
  136. {
  137. if ( !Parent::preload( server, errorStr ) )
  138. return false;
  139. return true;
  140. }
  141. //-------------------------------------------------------------------------
  142. // ReflectorBase
  143. //-------------------------------------------------------------------------
  144. ReflectorBase::ReflectorBase()
  145. {
  146. mEnabled = false;
  147. mOccluded = false;
  148. mIsRendering = false;
  149. mDesc = NULL;
  150. mObject = NULL;
  151. mOcclusionQuery = GFX->createOcclusionQuery();
  152. mQueryPending = false;
  153. score = 0.0f;
  154. lastUpdateMs = 0;
  155. }
  156. ReflectorBase::~ReflectorBase()
  157. {
  158. delete mOcclusionQuery;
  159. }
  160. void ReflectorBase::unregisterReflector()
  161. {
  162. if ( mEnabled )
  163. {
  164. REFLECTMGR->unregisterReflector( this );
  165. mEnabled = false;
  166. }
  167. }
  168. F32 ReflectorBase::calcScore( const ReflectParams &params )
  169. {
  170. PROFILE_SCOPE( ReflectorBase_calcScore );
  171. // First check the occlusion query to see if we're hidden.
  172. if ( mDesc->useOcclusionQuery &&
  173. mOcclusionQuery )
  174. {
  175. GFXOcclusionQuery::OcclusionQueryStatus status = mOcclusionQuery->getStatus( false );
  176. if ( status == GFXOcclusionQuery::Waiting )
  177. {
  178. mQueryPending = true;
  179. // Don't change mOccluded since we don't know yet, use the value
  180. // from last frame.
  181. }
  182. else
  183. {
  184. mQueryPending = false;
  185. if ( status == GFXOcclusionQuery::Occluded )
  186. mOccluded = true;
  187. else if ( status == GFXOcclusionQuery::NotOccluded )
  188. mOccluded = false;
  189. }
  190. }
  191. // If we're disabled for any reason then there
  192. // is nothing more left to do.
  193. if ( !mEnabled ||
  194. mOccluded ||
  195. params.culler.isCulled( mObject->getWorldBox() ) )
  196. {
  197. score = 0;
  198. return score;
  199. }
  200. // This mess is calculating a score based on LOD.
  201. /*
  202. F32 sizeWS = getMax( object->getWorldBox().len_z(), 0.001f );
  203. Point3F cameraOffset = params.culler.getPosition() - object->getPosition();
  204. F32 dist = getMax( cameraOffset.len(), 0.01f );
  205. F32 worldToScreenScaleY = ( params.culler.getNearDist() * params.viewportExtent.y ) /
  206. ( params.culler.getNearTop() - params.culler.getNearBottom() );
  207. F32 sizeSS = sizeWS / dist * worldToScreenScaleY;
  208. */
  209. if ( mDesc->priority == -1.0f )
  210. {
  211. score = 1000.0f;
  212. return score;
  213. }
  214. F32 lodFactor = 1.0f; //sizeSS;
  215. F32 maxRate = getMax( (F32)mDesc->maxRateMs, 1.0f );
  216. U32 delta = params.startOfUpdateMs - lastUpdateMs;
  217. F32 timeFactor = getMax( (F32)delta / maxRate - 1.0f, 0.0f );
  218. score = mDesc->priority * timeFactor * lodFactor;
  219. return score;
  220. }
  221. //-------------------------------------------------------------------------
  222. // CubeReflector
  223. //-------------------------------------------------------------------------
  224. CubeReflector::CubeReflector()
  225. : mLastTexSize( 0 )
  226. {
  227. }
  228. void CubeReflector::registerReflector( SceneObject *object,
  229. ReflectorDesc *desc )
  230. {
  231. if ( mEnabled )
  232. return;
  233. mEnabled = true;
  234. mObject = object;
  235. mDesc = desc;
  236. REFLECTMGR->registerReflector( this );
  237. }
  238. void CubeReflector::unregisterReflector()
  239. {
  240. if ( !mEnabled )
  241. return;
  242. REFLECTMGR->unregisterReflector( this );
  243. mEnabled = false;
  244. }
  245. void CubeReflector::updateReflection( const ReflectParams &params )
  246. {
  247. GFXDEBUGEVENT_SCOPE( CubeReflector_UpdateReflection, ColorI::WHITE );
  248. mIsRendering = true;
  249. // Setup textures and targets...
  250. S32 texDim = mDesc->texSize;
  251. texDim = getMax( texDim, 32 );
  252. // Protect against the reflection texture being bigger
  253. // than the current game back buffer.
  254. texDim = getMin( texDim, params.viewportExtent.x );
  255. texDim = getMin( texDim, params.viewportExtent.y );
  256. bool texResize = ( texDim != mLastTexSize );
  257. const GFXFormat reflectFormat = REFLECTMGR->getReflectFormat();
  258. if ( texResize ||
  259. cubemap.isNull() ||
  260. cubemap->getFormat() != reflectFormat )
  261. {
  262. cubemap = GFX->createCubemap();
  263. cubemap->initDynamic( texDim, reflectFormat );
  264. }
  265. GFXTexHandle depthBuff = LightShadowMap::_getDepthTarget( texDim, texDim );
  266. if ( renderTarget.isNull() )
  267. renderTarget = GFX->allocRenderToTextureTarget();
  268. GFX->pushActiveRenderTarget();
  269. renderTarget->attachTexture( GFXTextureTarget::DepthStencil, depthBuff );
  270. F32 oldVisibleDist = gClientSceneGraph->getVisibleDistance();
  271. gClientSceneGraph->setVisibleDistance( mDesc->farDist );
  272. for ( U32 i = 0; i < 6; i++ )
  273. updateFace( params, i );
  274. GFX->popActiveRenderTarget();
  275. gClientSceneGraph->setVisibleDistance(oldVisibleDist);
  276. mIsRendering = false;
  277. mLastTexSize = texDim;
  278. }
  279. void CubeReflector::updateFace( const ReflectParams &params, U32 faceidx )
  280. {
  281. GFXDEBUGEVENT_SCOPE( CubeReflector_UpdateFace, ColorI::WHITE );
  282. // store current matrices
  283. GFXTransformSaver saver;
  284. // set projection to 90 degrees vertical and horizontal
  285. F32 left, right, top, bottom;
  286. MathUtils::makeFrustum( &left, &right, &top, &bottom, M_HALFPI_F, 1.0f, mDesc->nearDist );
  287. GFX->setFrustum( left, right, bottom, top, mDesc->nearDist, mDesc->farDist );
  288. // We don't use a special clipping projection, but still need to initialize
  289. // this for objects like SkyBox which will use it during a reflect pass.
  290. gClientSceneGraph->setNonClipProjection( GFX->getProjectionMatrix() );
  291. // Standard view that will be overridden below.
  292. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  293. switch( faceidx )
  294. {
  295. case 0 : // D3DCUBEMAP_FACE_POSITIVE_X:
  296. vLookatPt = VectorF( 1.0f, 0.0f, 0.0f );
  297. vUpVec = VectorF( 0.0f, 1.0f, 0.0f );
  298. break;
  299. case 1 : // D3DCUBEMAP_FACE_NEGATIVE_X:
  300. vLookatPt = VectorF( -1.0f, 0.0f, 0.0f );
  301. vUpVec = VectorF( 0.0f, 1.0f, 0.0f );
  302. break;
  303. case 2 : // D3DCUBEMAP_FACE_POSITIVE_Y:
  304. vLookatPt = VectorF( 0.0f, 1.0f, 0.0f );
  305. vUpVec = VectorF( 0.0f, 0.0f,-1.0f );
  306. break;
  307. case 3 : // D3DCUBEMAP_FACE_NEGATIVE_Y:
  308. vLookatPt = VectorF( 0.0f, -1.0f, 0.0f );
  309. vUpVec = VectorF( 0.0f, 0.0f, 1.0f );
  310. break;
  311. case 4 : // D3DCUBEMAP_FACE_POSITIVE_Z:
  312. vLookatPt = VectorF( 0.0f, 0.0f, 1.0f );
  313. vUpVec = VectorF( 0.0f, 1.0f, 0.0f );
  314. break;
  315. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  316. vLookatPt = VectorF( 0.0f, 0.0f, -1.0f );
  317. vUpVec = VectorF( 0.0f, 1.0f, 0.0f );
  318. break;
  319. }
  320. // create camera matrix
  321. VectorF cross = mCross( vUpVec, vLookatPt );
  322. cross.normalizeSafe();
  323. MatrixF matView(true);
  324. matView.setColumn( 0, cross );
  325. matView.setColumn( 1, vLookatPt );
  326. matView.setColumn( 2, vUpVec );
  327. matView.setPosition( mObject->getPosition() );
  328. matView.inverse();
  329. GFX->setWorldMatrix(matView);
  330. renderTarget->attachTexture( GFXTextureTarget::Color0, cubemap, faceidx );
  331. GFX->setActiveRenderTarget( renderTarget );
  332. GFX->clear( GFXClearStencil | GFXClearTarget | GFXClearZBuffer, gCanvasClearColor, 1.0f, 0 );
  333. SceneRenderState reflectRenderState
  334. (
  335. gClientSceneGraph,
  336. SPT_Reflect,
  337. SceneCameraState::fromGFX()
  338. );
  339. reflectRenderState.getMaterialDelegate().bind( REFLECTMGR, &ReflectionManager::getReflectionMaterial );
  340. reflectRenderState.setDiffuseCameraTransform( params.query->headMatrix );
  341. // render scene
  342. LIGHTMGR->registerGlobalLights( &reflectRenderState.getCullingFrustum(), false );
  343. gClientSceneGraph->renderSceneNoLights( &reflectRenderState, mDesc->objectTypeMask );
  344. LIGHTMGR->unregisterAllLights();
  345. // Clean up.
  346. renderTarget->resolve();
  347. }
  348. F32 CubeReflector::calcFaceScore( const ReflectParams &params, U32 faceidx )
  349. {
  350. if ( Parent::calcScore( params ) <= 0.0f )
  351. return score;
  352. VectorF vLookatPt(0.0f, 0.0f, 0.0f);
  353. switch( faceidx )
  354. {
  355. case 0 : // D3DCUBEMAP_FACE_POSITIVE_X:
  356. vLookatPt = VectorF( 1.0f, 0.0f, 0.0f );
  357. break;
  358. case 1 : // D3DCUBEMAP_FACE_NEGATIVE_X:
  359. vLookatPt = VectorF( -1.0f, 0.0f, 0.0f );
  360. break;
  361. case 2 : // D3DCUBEMAP_FACE_POSITIVE_Y:
  362. vLookatPt = VectorF( 0.0f, 1.0f, 0.0f );
  363. break;
  364. case 3 : // D3DCUBEMAP_FACE_NEGATIVE_Y:
  365. vLookatPt = VectorF( 0.0f, -1.0f, 0.0f );
  366. break;
  367. case 4 : // D3DCUBEMAP_FACE_POSITIVE_Z:
  368. vLookatPt = VectorF( 0.0f, 0.0f, 1.0f );
  369. break;
  370. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  371. vLookatPt = VectorF( 0.0f, 0.0f, -1.0f );
  372. break;
  373. }
  374. VectorF cameraDir;
  375. params.query->cameraMatrix.getColumn( 1, &cameraDir );
  376. F32 dot = mDot( cameraDir, -vLookatPt );
  377. dot = getMax( ( dot + 1.0f ) / 2.0f, 0.1f );
  378. score *= dot;
  379. return score;
  380. }
  381. F32 CubeReflector::CubeFaceReflector::calcScore( const ReflectParams &params )
  382. {
  383. score = cube->calcFaceScore( params, faceIdx );
  384. mOccluded = cube->isOccluded();
  385. return score;
  386. }
  387. //-------------------------------------------------------------------------
  388. // PlaneReflector
  389. //-------------------------------------------------------------------------
  390. void PlaneReflector::registerReflector( SceneObject *object,
  391. ReflectorDesc *desc )
  392. {
  393. mEnabled = true;
  394. mObject = object;
  395. mDesc = desc;
  396. mLastDir = Point3F::One;
  397. mLastPos = Point3F::Max;
  398. REFLECTMGR->registerReflector( this );
  399. }
  400. F32 PlaneReflector::calcScore( const ReflectParams &params )
  401. {
  402. if ( Parent::calcScore( params ) <= 0.0f || score >= 1000.0f )
  403. return score;
  404. // The planar reflection is view dependent to score it
  405. // higher if the view direction and/or position has changed.
  406. // Get the current camera info.
  407. VectorF camDir = params.query->cameraMatrix.getForwardVector();
  408. Point3F camPos = params.query->cameraMatrix.getPosition();
  409. // Scale up the score based on the view direction change.
  410. F32 dot = mDot( camDir, mLastDir );
  411. dot = ( 1.0f - dot ) * 1000.0f;
  412. score += dot * mDesc->priority;
  413. // Also account for the camera movement.
  414. score += ( camPos - mLastPos ).lenSquared() * mDesc->priority;
  415. return score;
  416. }
  417. void PlaneReflector::updateReflection( const ReflectParams &params )
  418. {
  419. PROFILE_SCOPE(PlaneReflector_updateReflection);
  420. GFXDEBUGEVENT_SCOPE( PlaneReflector_updateReflection, ColorI::WHITE );
  421. mIsRendering = true;
  422. S32 texDim = mDesc->texSize;
  423. texDim = getMax( texDim, 32 );
  424. // Protect against the reflection texture being bigger
  425. // than the current game back buffer.
  426. texDim = getMin( texDim, params.viewportExtent.x );
  427. texDim = getMin( texDim, params.viewportExtent.y );
  428. bool texResize = ( texDim != mLastTexSize );
  429. mLastTexSize = texDim;
  430. const Point2I texSize( texDim, texDim );
  431. if ( texResize ||
  432. reflectTex.isNull() ||
  433. reflectTex->getFormat() != REFLECTMGR->getReflectFormat() )
  434. {
  435. reflectTex = REFLECTMGR->allocRenderTarget( texSize );
  436. depthBuff = LightShadowMap::_getDepthTarget( texSize.x, texSize.y );
  437. }
  438. // store current matrices
  439. GFXTransformSaver saver;
  440. Point2I viewport(params.viewportExtent);
  441. if(GFX->getCurrentRenderStyle() == GFXDevice::RS_StereoSideBySide)
  442. {
  443. viewport.x *= 0.5f;
  444. }
  445. F32 aspectRatio = F32( viewport.x ) / F32( viewport.y );
  446. Frustum frustum;
  447. frustum.set(false, params.query->fov, aspectRatio, params.query->nearPlane, params.query->farPlane);
  448. // Manipulate the frustum for tiled screenshots
  449. const bool screenShotMode = gScreenShot && gScreenShot->isPending();
  450. if ( screenShotMode )
  451. gScreenShot->tileFrustum( frustum );
  452. GFX->setFrustum( frustum );
  453. // Store the last view info for scoring.
  454. mLastDir = params.query->cameraMatrix.getForwardVector();
  455. mLastPos = params.query->cameraMatrix.getPosition();
  456. setGFXMatrices( params.query->cameraMatrix );
  457. // Adjust the detail amount
  458. F32 detailAdjustBackup = TSShapeInstance::smDetailAdjust;
  459. TSShapeInstance::smDetailAdjust *= mDesc->detailAdjust;
  460. if(reflectTarget.isNull())
  461. reflectTarget = GFX->allocRenderToTextureTarget();
  462. reflectTarget->attachTexture( GFXTextureTarget::Color0, reflectTex );
  463. reflectTarget->attachTexture( GFXTextureTarget::DepthStencil, depthBuff );
  464. GFX->pushActiveRenderTarget();
  465. GFX->setActiveRenderTarget( reflectTarget );
  466. U32 objTypeFlag = -1;
  467. SceneCameraState reflectCameraState = SceneCameraState::fromGFX();
  468. LIGHTMGR->registerGlobalLights( &reflectCameraState.getFrustum(), false );
  469. // Since we can sometime be rendering a reflection for 1 or 2 frames before
  470. // it gets updated do to the lag associated with getting the results from
  471. // a HOQ we can sometimes see into parts of the reflection texture that
  472. // have nothing but clear color ( eg. under the water ).
  473. // To make this look less crappy use the ambient color of the sun.
  474. //
  475. // In the future we may want to fix this instead by having the scatterSky
  476. // render a skirt or something in its lower half.
  477. //
  478. ColorF clearColor = gClientSceneGraph->getAmbientLightColor();
  479. GFX->clear( GFXClearZBuffer | GFXClearStencil | GFXClearTarget, clearColor, 1.0f, 0 );
  480. if(GFX->getCurrentRenderStyle() == GFXDevice::RS_StereoSideBySide)
  481. {
  482. // Store previous values
  483. RectI originalVP = GFX->getViewport();
  484. MatrixF origNonClipProjection = gClientSceneGraph->getNonClipProjection();
  485. PFXFrameState origPFXState = PFXMGR->getFrameState();
  486. const FovPort *currentFovPort = GFX->getStereoFovPort();
  487. MatrixF inverseEyeTransforms[2];
  488. // Calculate world transforms for eyes
  489. inverseEyeTransforms[0] = params.query->eyeTransforms[0];
  490. inverseEyeTransforms[1] = params.query->eyeTransforms[1];
  491. inverseEyeTransforms[0].inverse();
  492. inverseEyeTransforms[1].inverse();
  493. Frustum originalFrustum = GFX->getFrustum();
  494. // Render left half of display
  495. GFX->activateStereoTarget(0);
  496. GFX->setWorldMatrix(params.query->eyeTransforms[0]);
  497. Frustum gfxFrustum = originalFrustum;
  498. MathUtils::makeFovPortFrustum(&gfxFrustum, gfxFrustum.isOrtho(), gfxFrustum.getNearDist(), gfxFrustum.getFarDist(), currentFovPort[0], inverseEyeTransforms[0]);
  499. GFX->setFrustum(gfxFrustum);
  500. setGFXMatrices( params.query->eyeTransforms[0] );
  501. SceneCameraState cameraStateLeft = SceneCameraState::fromGFX();
  502. SceneRenderState renderStateLeft( gClientSceneGraph, SPT_Reflect, cameraStateLeft );
  503. renderStateLeft.setSceneRenderStyle(SRS_SideBySide);
  504. renderStateLeft.getMaterialDelegate().bind( REFLECTMGR, &ReflectionManager::getReflectionMaterial );
  505. renderStateLeft.setDiffuseCameraTransform( params.query->headMatrix );
  506. gClientSceneGraph->renderSceneNoLights( &renderStateLeft, objTypeFlag );
  507. // Render right half of display
  508. GFX->activateStereoTarget(1);
  509. GFX->setWorldMatrix(params.query->eyeTransforms[1]);
  510. gfxFrustum = originalFrustum;
  511. MathUtils::makeFovPortFrustum(&gfxFrustum, gfxFrustum.isOrtho(), gfxFrustum.getNearDist(), gfxFrustum.getFarDist(), currentFovPort[1], inverseEyeTransforms[1]);
  512. GFX->setFrustum(gfxFrustum);
  513. setGFXMatrices( params.query->eyeTransforms[1] );
  514. SceneCameraState cameraStateRight = SceneCameraState::fromGFX();
  515. SceneRenderState renderStateRight( gClientSceneGraph, SPT_Reflect, cameraStateRight );
  516. renderStateRight.setSceneRenderStyle(SRS_SideBySide);
  517. renderStateRight.getMaterialDelegate().bind( REFLECTMGR, &ReflectionManager::getReflectionMaterial );
  518. renderStateRight.setDiffuseCameraTransform( params.query->headMatrix );
  519. renderStateRight.disableAdvancedLightingBins(true);
  520. gClientSceneGraph->renderSceneNoLights( &renderStateRight, objTypeFlag );
  521. // Restore previous values
  522. GFX->setFrustum(gfxFrustum);
  523. GFX->setViewport(originalVP);
  524. gClientSceneGraph->setNonClipProjection(origNonClipProjection);
  525. PFXMGR->setFrameState(origPFXState);
  526. }
  527. else
  528. {
  529. SceneRenderState reflectRenderState
  530. (
  531. gClientSceneGraph,
  532. SPT_Reflect,
  533. SceneCameraState::fromGFX()
  534. );
  535. reflectRenderState.getMaterialDelegate().bind( REFLECTMGR, &ReflectionManager::getReflectionMaterial );
  536. reflectRenderState.setDiffuseCameraTransform( params.query->headMatrix );
  537. gClientSceneGraph->renderSceneNoLights( &reflectRenderState, objTypeFlag );
  538. }
  539. LIGHTMGR->unregisterAllLights();
  540. // Clean up.
  541. reflectTarget->resolve();
  542. GFX->popActiveRenderTarget();
  543. // Restore detail adjust amount.
  544. TSShapeInstance::smDetailAdjust = detailAdjustBackup;
  545. mIsRendering = false;
  546. }
  547. void PlaneReflector::setGFXMatrices( const MatrixF &camTrans )
  548. {
  549. if ( objectSpace )
  550. {
  551. // set up camera transform relative to object
  552. MatrixF invObjTrans = mObject->getRenderTransform();
  553. invObjTrans.inverse();
  554. MatrixF relCamTrans = invObjTrans * camTrans;
  555. MatrixF camReflectTrans = getCameraReflection( relCamTrans );
  556. MatrixF camTrans = mObject->getRenderTransform() * camReflectTrans;
  557. camTrans.inverse();
  558. GFX->setWorldMatrix( camTrans );
  559. // use relative reflect transform for modelview since clip plane is in object space
  560. camTrans = camReflectTrans;
  561. camTrans.inverse();
  562. // set new projection matrix
  563. gClientSceneGraph->setNonClipProjection( (MatrixF&) GFX->getProjectionMatrix() );
  564. MatrixF clipProj = getFrustumClipProj( camTrans );
  565. GFX->setProjectionMatrix( clipProj );
  566. }
  567. else
  568. {
  569. // set world mat from new camera view
  570. MatrixF camReflectTrans = getCameraReflection( camTrans );
  571. camReflectTrans.inverse();
  572. GFX->setWorldMatrix( camReflectTrans );
  573. // set new projection matrix
  574. gClientSceneGraph->setNonClipProjection( (MatrixF&) GFX->getProjectionMatrix() );
  575. MatrixF clipProj = getFrustumClipProj( camReflectTrans );
  576. GFX->setProjectionMatrix( clipProj );
  577. }
  578. }
  579. MatrixF PlaneReflector::getCameraReflection( const MatrixF &camTrans )
  580. {
  581. Point3F normal = refplane;
  582. // Figure out new cam position
  583. Point3F camPos = camTrans.getPosition();
  584. F32 dist = refplane.distToPlane( camPos );
  585. Point3F newCamPos = camPos - normal * dist * 2.0;
  586. // Figure out new look direction
  587. Point3F i, j, k;
  588. camTrans.getColumn( 0, &i );
  589. camTrans.getColumn( 1, &j );
  590. camTrans.getColumn( 2, &k );
  591. i = MathUtils::reflect( i, normal );
  592. j = MathUtils::reflect( j, normal );
  593. k = MathUtils::reflect( k, normal );
  594. //mCross( i, j, &k );
  595. MatrixF newTrans(true);
  596. newTrans.setColumn( 0, i );
  597. newTrans.setColumn( 1, j );
  598. newTrans.setColumn( 2, k );
  599. newTrans.setPosition( newCamPos );
  600. return newTrans;
  601. }
  602. inline F32 sgn(F32 a)
  603. {
  604. if (a > 0.0F) return (1.0F);
  605. if (a < 0.0F) return (-1.0F);
  606. return (0.0F);
  607. }
  608. MatrixF PlaneReflector::getFrustumClipProj( MatrixF &modelview )
  609. {
  610. static MatrixF rotMat(EulerF( static_cast<F32>(M_PI / 2.f), 0.0, 0.0));
  611. static MatrixF invRotMat(EulerF( -static_cast<F32>(M_PI / 2.f), 0.0, 0.0));
  612. MatrixF revModelview = modelview;
  613. revModelview = rotMat * revModelview; // add rotation to modelview because it needs to be removed from projection
  614. // rotate clip plane into modelview space
  615. Point4F clipPlane;
  616. Point3F pnt = refplane * -(refplane.d + 0.0 );
  617. Point3F norm = refplane;
  618. revModelview.mulP( pnt );
  619. revModelview.mulV( norm );
  620. norm.normalize();
  621. clipPlane.set( norm.x, norm.y, norm.z, -mDot( pnt, norm ) );
  622. // Manipulate projection matrix
  623. //------------------------------------------------------------------------
  624. MatrixF proj = GFX->getProjectionMatrix();
  625. proj.mul( invRotMat ); // reverse rotation imposed by Torque
  626. proj.transpose(); // switch to row-major order
  627. // Calculate the clip-space corner point opposite the clipping plane
  628. // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
  629. // transform it into camera space by multiplying it
  630. // by the inverse of the projection matrix
  631. Vector4F q;
  632. q.x = sgn(clipPlane.x) / proj(0,0);
  633. q.y = sgn(clipPlane.y) / proj(1,1);
  634. q.z = -1.0F;
  635. q.w = ( 1.0F - proj(2,2) ) / proj(3,2);
  636. F32 a = 1.0 / (clipPlane.x * q.x + clipPlane.y * q.y + clipPlane.z * q.z + clipPlane.w * q.w);
  637. Vector4F c = clipPlane * a;
  638. // CodeReview [ags 1/23/08] Come up with a better way to deal with this.
  639. if(GFX->getAdapterType() == OpenGL)
  640. c.z += 1.0f;
  641. // Replace the third column of the projection matrix
  642. proj.setColumn( 2, c );
  643. proj.transpose(); // convert back to column major order
  644. proj.mul( rotMat ); // restore Torque rotation
  645. return proj;
  646. }