2
0

reflector.cpp 26 KB

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