reflector.cpp 26 KB

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