reflectionManager.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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/reflectionManager.h"
  24. #include "platform/profiler.h"
  25. #include "platform/platformTimer.h"
  26. #include "console/consoleTypes.h"
  27. #include "core/tAlgorithm.h"
  28. #include "math/mMathFn.h"
  29. #include "T3D/gameBase/gameConnection.h"
  30. #include "ts/tsShapeInstance.h"
  31. #include "gui/3d/guiTSControl.h"
  32. #include "scene/sceneManager.h"
  33. #include "gfx/gfxDebugEvent.h"
  34. #include "gfx/gfxStringEnumTranslate.h"
  35. #include "gfx/screenshot.h"
  36. #include "core/module.h"
  37. #include "scene/reflectionMatHook.h"
  38. #include "console/engineAPI.h"
  39. MODULE_BEGIN( ReflectionManager )
  40. MODULE_INIT
  41. {
  42. ManagedSingleton< ReflectionManager >::createSingleton();
  43. ReflectionManager::initConsole();
  44. }
  45. MODULE_SHUTDOWN
  46. {
  47. ManagedSingleton< ReflectionManager >::deleteSingleton();
  48. }
  49. MODULE_END;
  50. GFX_ImplementTextureProfile( ReflectRenderTargetProfile,
  51. GFXTextureProfile::DiffuseMap,
  52. GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled,
  53. GFXTextureProfile::None );
  54. GFX_ImplementTextureProfile( RefractTextureProfile,
  55. GFXTextureProfile::DiffuseMap,
  56. GFXTextureProfile::PreserveSize |
  57. GFXTextureProfile::RenderTarget |
  58. GFXTextureProfile::Pooled,
  59. GFXTextureProfile::None );
  60. static S32 QSORT_CALLBACK compareReflectors( const void *a, const void *b )
  61. {
  62. const ReflectorBase *A = *((ReflectorBase**)a);
  63. const ReflectorBase *B = *((ReflectorBase**)b);
  64. F32 dif = B->score - A->score;
  65. return (S32)mFloor( dif );
  66. }
  67. U32 ReflectionManager::smFrameReflectionMS = 10;
  68. F32 ReflectionManager::smRefractTexScale = 0.5f;
  69. ReflectionManager::ReflectionManager()
  70. : mUpdateRefract( true ),
  71. mReflectFormat( GFXFormatR8G8B8A8 )
  72. {
  73. mTimer = PlatformTimer::create();
  74. GFXDevice::getDeviceEventSignal().notify( this, &ReflectionManager::_handleDeviceEvent );
  75. }
  76. void ReflectionManager::initConsole()
  77. {
  78. Con::addVariable( "$pref::Reflect::refractTexScale", TypeF32, &ReflectionManager::smRefractTexScale, "RefractTex has dimensions equal to the active render target scaled in both x and y by this float.\n"
  79. "@ingroup Rendering");
  80. Con::addVariable( "$pref::Reflect::frameLimitMS", TypeS32, &ReflectionManager::smFrameReflectionMS, "ReflectionManager tries not to spend more than this amount of time updating reflections per frame.\n"
  81. "@ingroup Rendering");
  82. }
  83. ReflectionManager::~ReflectionManager()
  84. {
  85. SAFE_DELETE( mTimer );
  86. AssertFatal( mReflectors.size() == 0, "ReflectionManager, some reflectors were left nregistered!" );
  87. GFXDevice::getDeviceEventSignal().remove( this, &ReflectionManager::_handleDeviceEvent );
  88. }
  89. void ReflectionManager::registerReflector( ReflectorBase *reflector )
  90. {
  91. mReflectors.push_back_unique( reflector );
  92. }
  93. void ReflectionManager::unregisterReflector( ReflectorBase *reflector )
  94. {
  95. mReflectors.remove( reflector );
  96. }
  97. void ReflectionManager::update( F32 timeSlice,
  98. const Point2I &resolution,
  99. const CameraQuery &query )
  100. {
  101. GFXDEBUGEVENT_SCOPE( UpdateReflections, ColorI::WHITE );
  102. if ( mReflectors.empty() )
  103. return;
  104. PROFILE_SCOPE( ReflectionManager_Update );
  105. // Calculate our target time from the slice.
  106. U32 targetMs = timeSlice * smFrameReflectionMS;
  107. // Setup a culler for testing the
  108. // visibility of reflectors.
  109. Frustum culler;
  110. culler.set( false,
  111. query.fov,
  112. (F32)resolution.x / (F32)resolution.y,
  113. query.nearPlane,
  114. query.farPlane,
  115. query.cameraMatrix );
  116. // Manipulate the frustum for tiled screenshots
  117. const bool screenShotMode = gScreenShot && gScreenShot->isPending();
  118. if ( screenShotMode )
  119. gScreenShot->tileFrustum( culler );
  120. // We use the frame time and not real time
  121. // here as this may be called multiple times
  122. // within a frame.
  123. U32 startOfUpdateMs = Platform::getVirtualMilliseconds();
  124. // Save this for interested parties.
  125. mLastUpdateMs = startOfUpdateMs;
  126. ReflectParams refparams;
  127. refparams.query = &query;
  128. refparams.viewportExtent = resolution;
  129. refparams.culler = culler;
  130. refparams.startOfUpdateMs = startOfUpdateMs;
  131. // Update the reflection score.
  132. ReflectorList::iterator reflectorIter = mReflectors.begin();
  133. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  134. (*reflectorIter)->calcScore( refparams );
  135. // Sort them by the score.
  136. dQsort( mReflectors.address(), mReflectors.size(), sizeof(ReflectorBase*), compareReflectors );
  137. // Update as many reflections as we can
  138. // within the target time limit.
  139. mTimer->getElapsedMs();
  140. mTimer->reset();
  141. U32 numUpdated = 0;
  142. reflectorIter = mReflectors.begin();
  143. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  144. {
  145. // We're sorted by score... so once we reach
  146. // a zero score we have nothing more to update.
  147. if ( (*reflectorIter)->score <= 0.0f && !screenShotMode )
  148. break;
  149. (*reflectorIter)->updateReflection( refparams );
  150. (*reflectorIter)->lastUpdateMs = startOfUpdateMs;
  151. numUpdated++;
  152. // If we run out of update time then stop.
  153. if ( mTimer->getElapsedMs() > targetMs && !screenShotMode && (*reflectorIter)->score < 1000.0f )
  154. break;
  155. }
  156. U32 totalElapsed = mTimer->getElapsedMs();
  157. // Set metric/debug related script variables...
  158. U32 numEnabled = mReflectors.size();
  159. U32 numVisible = 0;
  160. U32 numOccluded = 0;
  161. reflectorIter = mReflectors.begin();
  162. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  163. {
  164. ReflectorBase *pReflector = (*reflectorIter);
  165. if ( pReflector->isOccluded() )
  166. numOccluded++;
  167. else
  168. numVisible++;
  169. }
  170. #ifdef TORQUE_GATHER_METRICS
  171. const GFXTextureProfileStats &stats = ReflectRenderTargetProfile.getStats();
  172. F32 mb = ( stats.activeBytes / 1024.0f ) / 1024.0f;
  173. char temp[256];
  174. dSprintf( temp, 256, "%s %d %0.2f\n",
  175. ReflectRenderTargetProfile.getName().c_str(),
  176. stats.activeCount,
  177. mb );
  178. Con::setVariable( "$Reflect::textureStats", temp );
  179. Con::setIntVariable( "$Reflect::renderTargetsAllocated", stats.allocatedTextures );
  180. Con::setIntVariable( "$Reflect::poolSize", stats.activeCount );
  181. Con::setIntVariable( "$Reflect::numObjects", numEnabled );
  182. Con::setIntVariable( "$Reflect::numVisible", numVisible );
  183. Con::setIntVariable( "$Reflect::numOccluded", numOccluded );
  184. Con::setIntVariable( "$Reflect::numUpdated", numUpdated );
  185. Con::setIntVariable( "$Reflect::elapsed", totalElapsed );
  186. #endif
  187. }
  188. GFXTexHandle ReflectionManager::allocRenderTarget( const Point2I &size )
  189. {
  190. return GFXTexHandle( size.x, size.y, mReflectFormat,
  191. &ReflectRenderTargetProfile,
  192. avar("%s() - mReflectTex (line %d)", __FUNCTION__, __LINE__) );
  193. }
  194. GFXTextureObject* ReflectionManager::getRefractTex( bool forceUpdate )
  195. {
  196. GFXTarget *target = GFX->getActiveRenderTarget();
  197. GFXFormat targetFormat = target->getFormat();
  198. const Point2I &targetSize = target->getSize();
  199. #if defined(TORQUE_OS_XENON)
  200. // On the Xbox360, it needs to do a resolveTo from the active target, so this
  201. // may as well be the full size of the active target
  202. const U32 desWidth = targetSize.x;
  203. const U32 desHeight = targetSize.y;
  204. #else
  205. const U32 desWidth = mFloor( (F32)targetSize.x * smRefractTexScale );
  206. const U32 desHeight = mFloor( ( F32)targetSize.y * smRefractTexScale );
  207. #endif
  208. if ( mRefractTex.isNull() ||
  209. mRefractTex->getWidth() != desWidth ||
  210. mRefractTex->getHeight() != desHeight ||
  211. mRefractTex->getFormat() != targetFormat )
  212. {
  213. mRefractTex.set( desWidth, desHeight, targetFormat, &RefractTextureProfile, "mRefractTex" );
  214. mUpdateRefract = true;
  215. }
  216. if ( forceUpdate || mUpdateRefract )
  217. {
  218. target->resolveTo( mRefractTex );
  219. mUpdateRefract = false;
  220. }
  221. return mRefractTex;
  222. }
  223. BaseMatInstance* ReflectionManager::getReflectionMaterial( BaseMatInstance *inMat ) const
  224. {
  225. // See if we have an existing material hook.
  226. ReflectionMaterialHook *hook = static_cast<ReflectionMaterialHook*>( inMat->getHook( ReflectionMaterialHook::Type ) );
  227. if ( !hook )
  228. {
  229. // Create a hook and initialize it using the incoming material.
  230. hook = new ReflectionMaterialHook;
  231. hook->init( inMat );
  232. inMat->addHook( hook );
  233. }
  234. return hook->getReflectMat();
  235. }
  236. bool ReflectionManager::_handleDeviceEvent( GFXDevice::GFXDeviceEventType evt )
  237. {
  238. switch( evt )
  239. {
  240. case GFXDevice::deStartOfFrame:
  241. mUpdateRefract = true;
  242. break;
  243. case GFXDevice::deDestroy:
  244. mRefractTex = NULL;
  245. break;
  246. default:
  247. break;
  248. }
  249. return true;
  250. }
  251. DefineEngineFunction( setReflectFormat, void, ( GFXFormat format ),,
  252. "Set the reflection texture format.\n"
  253. "@ingroup GFX\n" )
  254. {
  255. REFLECTMGR->setReflectFormat( format );
  256. }