reflector.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. reflectRenderState.disableAdvancedLightingBins(true);
  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. Point2F projOffset = GFX->getCurrentProjectionOffset();
  485. const FovPort *currentFovPort = GFX->getStereoFovPort();
  486. MatrixF inverseEyeTransforms[2];
  487. // Calculate world transforms for eyes
  488. inverseEyeTransforms[0] = params.query->eyeTransforms[0];
  489. inverseEyeTransforms[1] = params.query->eyeTransforms[1];
  490. inverseEyeTransforms[0].inverse();
  491. inverseEyeTransforms[1].inverse();
  492. Frustum originalFrustum = GFX->getFrustum();
  493. // Render left half of display
  494. GFX->activateStereoTarget(0);
  495. GFX->setWorldMatrix(params.query->eyeTransforms[0]);
  496. Frustum gfxFrustum = originalFrustum;
  497. MathUtils::makeFovPortFrustum(&gfxFrustum, gfxFrustum.isOrtho(), gfxFrustum.getNearDist(), gfxFrustum.getFarDist(), currentFovPort[0], inverseEyeTransforms[0]);
  498. GFX->setFrustum(gfxFrustum);
  499. setGFXMatrices( params.query->eyeTransforms[0] );
  500. SceneCameraState cameraStateLeft = SceneCameraState::fromGFX();
  501. SceneRenderState renderStateLeft( gClientSceneGraph, SPT_Reflect, cameraStateLeft );
  502. renderStateLeft.setSceneRenderStyle(SRS_SideBySide);
  503. renderStateLeft.setSceneRenderField(0);
  504. renderStateLeft.getMaterialDelegate().bind( REFLECTMGR, &ReflectionManager::getReflectionMaterial );
  505. renderStateLeft.setDiffuseCameraTransform( params.query->eyeTransforms[0] );
  506. renderStateLeft.disableAdvancedLightingBins(true);
  507. gClientSceneGraph->renderSceneNoLights( &renderStateLeft, objTypeFlag );
  508. // Render right half of display
  509. GFX->activateStereoTarget(1);
  510. GFX->setWorldMatrix(params.query->eyeTransforms[1]);
  511. gfxFrustum = originalFrustum;
  512. MathUtils::makeFovPortFrustum(&gfxFrustum, gfxFrustum.isOrtho(), gfxFrustum.getNearDist(), gfxFrustum.getFarDist(), currentFovPort[1], inverseEyeTransforms[1]);
  513. GFX->setFrustum(gfxFrustum);
  514. setGFXMatrices( params.query->eyeTransforms[1] );
  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->eyeTransforms[1] );
  521. renderStateRight.disableAdvancedLightingBins(true);
  522. gClientSceneGraph->renderSceneNoLights( &renderStateRight, objTypeFlag );
  523. // Restore previous values
  524. GFX->setFrustum(gfxFrustum);
  525. GFX->setViewport(originalVP);
  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->cameraMatrix );
  537. reflectRenderState.disableAdvancedLightingBins(true);
  538. gClientSceneGraph->renderSceneNoLights( &reflectRenderState, objTypeFlag );
  539. }
  540. LIGHTMGR->unregisterAllLights();
  541. // Clean up.
  542. reflectTarget->resolve();
  543. GFX->popActiveRenderTarget();
  544. // Restore detail adjust amount.
  545. TSShapeInstance::smDetailAdjust = detailAdjustBackup;
  546. mIsRendering = false;
  547. }
  548. void PlaneReflector::setGFXMatrices( const MatrixF &camTrans )
  549. {
  550. if ( objectSpace )
  551. {
  552. // set up camera transform relative to object
  553. MatrixF invObjTrans = mObject->getRenderTransform();
  554. invObjTrans.inverse();
  555. MatrixF relCamTrans = invObjTrans * camTrans;
  556. MatrixF camReflectTrans = getCameraReflection( relCamTrans );
  557. MatrixF camTrans = mObject->getRenderTransform() * camReflectTrans;
  558. camTrans.inverse();
  559. GFX->setWorldMatrix( camTrans );
  560. // use relative reflect transform for modelview since clip plane is in object space
  561. camTrans = camReflectTrans;
  562. camTrans.inverse();
  563. // set new projection matrix
  564. gClientSceneGraph->setNonClipProjection( (MatrixF&) GFX->getProjectionMatrix() );
  565. MatrixF clipProj = getFrustumClipProj( camTrans );
  566. GFX->setProjectionMatrix( clipProj );
  567. }
  568. else
  569. {
  570. // set world mat from new camera view
  571. MatrixF camReflectTrans = getCameraReflection( camTrans );
  572. camReflectTrans.inverse();
  573. GFX->setWorldMatrix( camReflectTrans );
  574. // set new projection matrix
  575. gClientSceneGraph->setNonClipProjection( (MatrixF&) GFX->getProjectionMatrix() );
  576. MatrixF clipProj = getFrustumClipProj( camReflectTrans );
  577. GFX->setProjectionMatrix( clipProj );
  578. }
  579. }
  580. MatrixF PlaneReflector::getCameraReflection( const MatrixF &camTrans )
  581. {
  582. Point3F normal = refplane;
  583. // Figure out new cam position
  584. Point3F camPos = camTrans.getPosition();
  585. F32 dist = refplane.distToPlane( camPos );
  586. Point3F newCamPos = camPos - normal * dist * 2.0;
  587. // Figure out new look direction
  588. Point3F i, j, k;
  589. camTrans.getColumn( 0, &i );
  590. camTrans.getColumn( 1, &j );
  591. camTrans.getColumn( 2, &k );
  592. i = MathUtils::reflect( i, normal );
  593. j = MathUtils::reflect( j, normal );
  594. k = MathUtils::reflect( k, normal );
  595. //mCross( i, j, &k );
  596. MatrixF newTrans(true);
  597. newTrans.setColumn( 0, i );
  598. newTrans.setColumn( 1, j );
  599. newTrans.setColumn( 2, k );
  600. newTrans.setPosition( newCamPos );
  601. return newTrans;
  602. }
  603. inline F32 sgn(F32 a)
  604. {
  605. if (a > 0.0F) return (1.0F);
  606. if (a < 0.0F) return (-1.0F);
  607. return (0.0F);
  608. }
  609. MatrixF PlaneReflector::getFrustumClipProj( MatrixF &modelview )
  610. {
  611. static MatrixF rotMat(EulerF( static_cast<F32>(M_PI / 2.f), 0.0, 0.0));
  612. static MatrixF invRotMat(EulerF( -static_cast<F32>(M_PI / 2.f), 0.0, 0.0));
  613. MatrixF revModelview = modelview;
  614. revModelview = rotMat * revModelview; // add rotation to modelview because it needs to be removed from projection
  615. // rotate clip plane into modelview space
  616. Point4F clipPlane;
  617. Point3F pnt = refplane * -(refplane.d + 0.0 );
  618. Point3F norm = refplane;
  619. revModelview.mulP( pnt );
  620. revModelview.mulV( norm );
  621. norm.normalize();
  622. clipPlane.set( norm.x, norm.y, norm.z, -mDot( pnt, norm ) );
  623. // Manipulate projection matrix
  624. //------------------------------------------------------------------------
  625. MatrixF proj = GFX->getProjectionMatrix();
  626. proj.mul( invRotMat ); // reverse rotation imposed by Torque
  627. proj.transpose(); // switch to row-major order
  628. // Calculate the clip-space corner point opposite the clipping plane
  629. // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
  630. // transform it into camera space by multiplying it
  631. // by the inverse of the projection matrix
  632. Vector4F q;
  633. q.x = sgn(clipPlane.x) / proj(0,0);
  634. q.y = sgn(clipPlane.y) / proj(1,1);
  635. q.z = -1.0F;
  636. q.w = ( 1.0F - proj(2,2) ) / proj(3,2);
  637. F32 a = 1.0 / (clipPlane.x * q.x + clipPlane.y * q.y + clipPlane.z * q.z + clipPlane.w * q.w);
  638. Vector4F c = clipPlane * a;
  639. // CodeReview [ags 1/23/08] Come up with a better way to deal with this.
  640. if(GFX->getAdapterType() == OpenGL)
  641. c.z += 1.0f;
  642. // Replace the third column of the projection matrix
  643. proj.setColumn( 2, c );
  644. proj.transpose(); // convert back to column major order
  645. proj.mul( rotMat ); // restore Torque rotation
  646. return proj;
  647. }