terrRender.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 "terrain/terrRender.h"
  24. #include "terrain/terrData.h"
  25. #include "terrain/terrCell.h"
  26. #include "terrain/terrMaterial.h"
  27. #include "terrain/terrCellMaterial.h"
  28. #include "materials/shaderData.h"
  29. #include "platform/profiler.h"
  30. #include "scene/sceneRenderState.h"
  31. #include "math/util/frustum.h"
  32. #include "renderInstance/renderPassManager.h"
  33. #include "renderInstance/renderTerrainMgr.h"
  34. #include "lighting/lightInfo.h"
  35. #include "lighting/lightManager.h"
  36. #include "materials/matInstance.h"
  37. #include "materials/materialManager.h"
  38. #include "materials/matTextureTarget.h"
  39. #include "shaderGen/conditionerFeature.h"
  40. #include "gfx/gfxDrawUtil.h"
  41. #include "gfx/gfxTransformSaver.h"
  42. #include "gfx/bitmap/gBitmap.h"
  43. #include "gfx/bitmap/ddsFile.h"
  44. #include "gfx/bitmap/ddsUtils.h"
  45. #include "terrain/terrMaterial.h"
  46. #include "gfx/gfxDebugEvent.h"
  47. #include "gfx/gfxCardProfile.h"
  48. #include "core/stream/fileStream.h"
  49. bool TerrainBlock::smDebugRender = false;
  50. GFX_ImplementTextureProfile( TerrainLayerTexProfile,
  51. GFXTextureProfile::DiffuseMap,
  52. GFXTextureProfile::PreserveSize |
  53. GFXTextureProfile::Dynamic,
  54. GFXTextureProfile::None );
  55. void TerrainBlock::_onFlushMaterials()
  56. {
  57. if ( mCell )
  58. mCell->deleteMaterials();
  59. SAFE_DELETE( mBaseMaterial );
  60. }
  61. void TerrainBlock::_updateMaterials()
  62. {
  63. mBaseTextures.setSize( mFile->mMaterials.size() );
  64. mMaxDetailDistance = 0.0f;
  65. for ( U32 i=0; i < mFile->mMaterials.size(); i++ )
  66. {
  67. TerrainMaterial *mat = mFile->mMaterials[i];
  68. if( !mat->getDiffuseMap().isEmpty() )
  69. mBaseTextures[i].set( mat->getDiffuseMap(),
  70. &GFXDefaultStaticDiffuseProfile,
  71. "TerrainBlock::_updateMaterials() - DiffuseMap" );
  72. else
  73. mBaseTextures[ i ] = GFXTexHandle();
  74. // Find the maximum detail distance.
  75. if ( mat->getDetailMap().isNotEmpty() &&
  76. mat->getDetailDistance() > mMaxDetailDistance )
  77. mMaxDetailDistance = mat->getDetailDistance();
  78. }
  79. if ( mCell )
  80. mCell->deleteMaterials();
  81. }
  82. void TerrainBlock::_updateLayerTexture()
  83. {
  84. const U32 layerSize = mFile->mSize;
  85. const Vector<U8> &layerMap = mFile->mLayerMap;
  86. const U32 pixelCount = layerMap.size();
  87. if ( mLayerTex.isNull() ||
  88. mLayerTex.getWidth() != layerSize ||
  89. mLayerTex.getHeight() != layerSize )
  90. mLayerTex.set( layerSize, layerSize, GFXFormatR8G8B8A8, &TerrainLayerTexProfile, "" );
  91. AssertFatal( mLayerTex.getWidth() == layerSize &&
  92. mLayerTex.getHeight() == layerSize,
  93. "TerrainBlock::_updateLayerTexture - The texture size doesn't match the requested size!" );
  94. // Update the layer texture.
  95. GFXLockedRect *lock = mLayerTex.lock();
  96. for ( U32 i=0; i < pixelCount; i++ )
  97. {
  98. lock->bits[0] = layerMap[i];
  99. if ( i + 1 >= pixelCount )
  100. lock->bits[1] = lock->bits[0];
  101. else
  102. lock->bits[1] = layerMap[i+1];
  103. if ( i + layerSize >= pixelCount )
  104. lock->bits[2] = lock->bits[0];
  105. else
  106. lock->bits[2] = layerMap[i + layerSize];
  107. if ( i + layerSize + 1 >= pixelCount )
  108. lock->bits[3] = lock->bits[0];
  109. else
  110. lock->bits[3] = layerMap[i + layerSize + 1];
  111. lock->bits += 4;
  112. }
  113. mLayerTex.unlock();
  114. //mLayerTex->dumpToDisk( "png", "./layerTex.png" );
  115. }
  116. bool TerrainBlock::_initBaseShader()
  117. {
  118. ShaderData *shaderData = NULL;
  119. if ( !Sim::findObject( "TerrainBlendShader", shaderData ) || !shaderData )
  120. return false;
  121. mBaseShader = shaderData->getShader();
  122. mBaseShaderConsts = mBaseShader->allocConstBuffer();
  123. mBaseTexScaleConst = mBaseShader->getShaderConstHandle( "$texScale" );
  124. mBaseTexIdConst = mBaseShader->getShaderConstHandle( "$texId" );
  125. mBaseLayerSizeConst = mBaseShader->getShaderConstHandle( "$layerSize" );
  126. mBaseTarget = GFX->allocRenderToTextureTarget();
  127. GFXStateBlockDesc desc;
  128. desc.samplersDefined = true;
  129. desc.samplers[0] = GFXSamplerStateDesc::getClampPoint();
  130. desc.samplers[1] = GFXSamplerStateDesc::getWrapLinear();
  131. desc.zDefined = true;
  132. desc.zWriteEnable = false;
  133. desc.zEnable = false;
  134. desc.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  135. desc.cullDefined = true;
  136. desc.cullMode = GFXCullNone;
  137. mBaseShaderSB = GFX->createStateBlock( desc );
  138. return true;
  139. }
  140. void TerrainBlock::_updateBaseTexture( bool writeToCache )
  141. {
  142. if ( !mBaseShader && !_initBaseShader() )
  143. return;
  144. // This can sometimes occur outside a begin/end scene.
  145. const bool sceneBegun = GFX->canCurrentlyRender();
  146. if ( !sceneBegun )
  147. GFX->beginScene();
  148. GFXDEBUGEVENT_SCOPE( TerrainBlock_UpdateBaseTexture, ColorI::GREEN );
  149. PROFILE_SCOPE( TerrainBlock_UpdateBaseTexture );
  150. GFXTransformSaver saver;
  151. const U32 maxTextureSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 1024 );
  152. U32 baseTexSize = getNextPow2( mBaseTexSize );
  153. baseTexSize = getMin( maxTextureSize, baseTexSize );
  154. Point2I destSize( baseTexSize, baseTexSize );
  155. // Setup geometry
  156. GFXVertexBufferHandle<GFXVertexPT> vb;
  157. {
  158. F32 copyOffsetX = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.x;
  159. F32 copyOffsetY = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.y;
  160. const bool needsYFlip = GFX->getAdapterType() == OpenGL;
  161. GFXVertexPT points[4];
  162. points[0].point = Point3F( -1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
  163. points[0].texCoord = Point2F( 0.0, needsYFlip ? 0.0f : 1.0f );
  164. points[1].point = Point3F( -1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
  165. points[1].texCoord = Point2F( 0.0, needsYFlip ? 1.0f : 0.0f );
  166. points[2].point = Point3F( 1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
  167. points[2].texCoord = Point2F( 1.0, needsYFlip ? 1.0f : 0.0f );
  168. points[3].point = Point3F( 1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
  169. points[3].texCoord = Point2F( 1.0, needsYFlip ? 0.0f : 1.0f );
  170. vb.set( GFX, 4, GFXBufferTypeVolatile );
  171. dMemcpy( vb.lock(), points, sizeof(GFXVertexPT) * 4 );
  172. vb.unlock();
  173. }
  174. GFXTexHandle blendTex;
  175. // If the base texture is already a valid render target then
  176. // use it to render to else we create one.
  177. if ( mBaseTex.isValid() &&
  178. mBaseTex->isRenderTarget() &&
  179. mBaseTex->getFormat() == GFXFormatR8G8B8A8 &&
  180. mBaseTex->getWidth() == destSize.x &&
  181. mBaseTex->getHeight() == destSize.y )
  182. blendTex = mBaseTex;
  183. else
  184. blendTex.set( destSize.x, destSize.y, GFXFormatR8G8B8A8, &GFXDefaultRenderTargetProfile, "" );
  185. GFX->pushActiveRenderTarget();
  186. // Set our shader stuff
  187. GFX->setShader( mBaseShader );
  188. GFX->setShaderConstBuffer( mBaseShaderConsts );
  189. GFX->setStateBlock( mBaseShaderSB );
  190. GFX->setVertexBuffer( vb );
  191. mBaseTarget->attachTexture( GFXTextureTarget::Color0, blendTex );
  192. GFX->setActiveRenderTarget( mBaseTarget );
  193. GFX->setTexture( 0, mLayerTex );
  194. mBaseShaderConsts->setSafe( mBaseLayerSizeConst, (F32)mLayerTex->getWidth() );
  195. for ( U32 i=0; i < mBaseTextures.size(); i++ )
  196. {
  197. GFXTextureObject *tex = mBaseTextures[i];
  198. if ( !tex )
  199. continue;
  200. GFX->setTexture( 1, tex );
  201. F32 baseSize = mFile->mMaterials[i]->getDiffuseSize();
  202. F32 scale = 1.0f;
  203. if ( !mIsZero( baseSize ) )
  204. scale = getWorldBlockSize() / baseSize;
  205. // A mistake early in development means that texture
  206. // coords are not flipped correctly. To compensate
  207. // we flip the y scale here.
  208. mBaseShaderConsts->setSafe( mBaseTexScaleConst, Point2F( scale, -scale ) );
  209. mBaseShaderConsts->setSafe( mBaseTexIdConst, (F32)i );
  210. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  211. }
  212. mBaseTarget->resolve();
  213. GFX->setShader( NULL );
  214. //GFX->setStateBlock( NULL ); // WHY NOT?
  215. GFX->setShaderConstBuffer( NULL );
  216. GFX->setVertexBuffer( NULL );
  217. GFX->popActiveRenderTarget();
  218. // End it if we begun it... Yeehaw!
  219. if ( !sceneBegun )
  220. GFX->endScene();
  221. /// Do we cache this sucker?
  222. if ( writeToCache )
  223. {
  224. String cachePath = _getBaseTexCacheFileName();
  225. FileStream fs;
  226. if ( fs.open( _getBaseTexCacheFileName(), Torque::FS::File::Write ) )
  227. {
  228. // Read back the render target, dxt compress it, and write it to disk.
  229. GBitmap blendBmp( destSize.x, destSize.y, false, GFXFormatR8G8B8A8 );
  230. blendTex.copyToBmp( &blendBmp );
  231. /*
  232. // Test code for dumping uncompressed bitmap to disk.
  233. {
  234. FileStream fs;
  235. if ( fs.open( "./basetex.png", Torque::FS::File::Write ) )
  236. {
  237. blendBmp.writeBitmap( "png", fs );
  238. fs.close();
  239. }
  240. }
  241. */
  242. blendBmp.extrudeMipLevels();
  243. DDSFile *blendDDS = DDSFile::createDDSFileFromGBitmap( &blendBmp );
  244. DDSUtil::squishDDS( blendDDS, GFXFormatDXT1 );
  245. // Write result to file stream
  246. blendDDS->write( fs );
  247. delete blendDDS;
  248. }
  249. fs.close();
  250. }
  251. else
  252. {
  253. // We didn't cache the result, so set the base texture
  254. // to the render target we updated. This should be good
  255. // for realtime painting cases.
  256. mBaseTex = blendTex;
  257. }
  258. }
  259. void TerrainBlock::_renderBlock( SceneRenderState *state )
  260. {
  261. PROFILE_SCOPE( TerrainBlock_RenderBlock );
  262. // Prevent rendering shadows if feature is disabled
  263. if ( !mCastShadows && state->isShadowPass() )
  264. return;
  265. MatrixF worldViewXfm = state->getWorldViewMatrix();
  266. worldViewXfm.mul( getRenderTransform() );
  267. MatrixF worldViewProjXfm = state->getProjectionMatrix();
  268. worldViewProjXfm.mul( worldViewXfm );
  269. const MatrixF &objectXfm = getRenderWorldTransform();
  270. Point3F objCamPos = state->getDiffuseCameraPosition();
  271. objectXfm.mulP( objCamPos );
  272. // Get the shadow material.
  273. if ( !mDefaultMatInst )
  274. mDefaultMatInst = TerrainCellMaterial::getShadowMat();
  275. // Make sure we have a base material.
  276. if ( !mBaseMaterial )
  277. {
  278. mBaseMaterial = new TerrainCellMaterial();
  279. mBaseMaterial->init( this, 0, false, false, true );
  280. }
  281. // Did the detail layers change?
  282. if ( mDetailsDirty )
  283. {
  284. _updateMaterials();
  285. mDetailsDirty = false;
  286. }
  287. // If the layer texture has been cleared or is
  288. // dirty then update it.
  289. if ( mLayerTex.isNull() || mLayerTexDirty )
  290. _updateLayerTexture();
  291. // If the layer texture is dirty or we lost the base
  292. // texture then regenerate it.
  293. if ( mLayerTexDirty || mBaseTex.isNull() )
  294. {
  295. _updateBaseTexture( false );
  296. mLayerTexDirty = false;
  297. }
  298. static Vector<TerrCell*> renderCells;
  299. renderCells.clear();
  300. mCell->cullCells( state,
  301. objCamPos,
  302. &renderCells );
  303. RenderPassManager *renderPass = state->getRenderPass();
  304. MatrixF *riObjectToWorldXfm = renderPass->allocUniqueXform( getRenderTransform() );
  305. const bool isColorDrawPass = state->isDiffusePass() || state->isReflectPass();
  306. // This is here for shadows mostly... it allows the
  307. // proper shadow material to be generated.
  308. BaseMatInstance *defaultMatInst = state->getOverrideMaterial( mDefaultMatInst );
  309. // Only pass and use the light manager if this is not a shadow pass.
  310. LightManager *lm = NULL;
  311. if ( isColorDrawPass )
  312. lm = LIGHTMGR;
  313. for ( U32 i=0; i < renderCells.size(); i++ )
  314. {
  315. TerrCell *cell = renderCells[i];
  316. // Ok this cell is fit to render.
  317. TerrainRenderInst *inst = renderPass->allocInst<TerrainRenderInst>();
  318. // Setup lights for this cell.
  319. if ( lm )
  320. {
  321. SphereF bounds = cell->getSphereBounds();
  322. getRenderTransform().mulP( bounds.center );
  323. LightQuery query;
  324. query.init( bounds );
  325. query.getLights( inst->lights, 8 );
  326. }
  327. GFXVertexBufferHandleBase vertBuff;
  328. GFXPrimitiveBufferHandle primBuff;
  329. cell->getRenderPrimitive( &inst->prim, &vertBuff, &primBuff );
  330. inst->mat = defaultMatInst;
  331. inst->vertBuff = vertBuff.getPointer();
  332. if ( primBuff.isValid() )
  333. {
  334. // Use the cell's custom primitive buffer
  335. inst->primBuff = primBuff.getPointer();
  336. }
  337. else
  338. {
  339. // Use the standard primitive buffer for this cell
  340. inst->primBuff = mPrimBuffer.getPointer();
  341. }
  342. inst->objectToWorldXfm = riObjectToWorldXfm;
  343. // If we're not drawing to the shadow map then we need
  344. // to include the normal rendering materials.
  345. if ( isColorDrawPass )
  346. {
  347. const SphereF &bounds = cell->getSphereBounds();
  348. F32 sqDist = ( bounds.center - objCamPos ).lenSquared();
  349. F32 radiusSq = mSquared( ( mMaxDetailDistance + bounds.radius ) * smDetailScale );
  350. // If this cell is near enough to get detail textures then
  351. // use the full detail mapping material. Else we use the
  352. // simple base only material.
  353. if ( !state->isReflectPass() && sqDist < radiusSq )
  354. inst->cellMat = cell->getMaterial();
  355. else if ( state->isReflectPass() )
  356. inst->cellMat = mBaseMaterial->getReflectMat();
  357. else
  358. inst->cellMat = mBaseMaterial;
  359. }
  360. inst->defaultKey = (U32)cell->getMaterials();
  361. // Submit it for rendering.
  362. renderPass->addInst( inst );
  363. }
  364. // Trigger the debug rendering.
  365. if ( state->isDiffusePass() &&
  366. !renderCells.empty() &&
  367. smDebugRender )
  368. {
  369. // Store the render cells for later.
  370. mDebugCells = renderCells;
  371. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  372. ri->renderDelegate.bind( this, &TerrainBlock::_renderDebug );
  373. ri->type = RenderPassManager::RIT_Editor;
  374. state->getRenderPass()->addInst( ri );
  375. }
  376. }
  377. void TerrainBlock::_renderDebug( ObjectRenderInst *ri,
  378. SceneRenderState *state,
  379. BaseMatInstance *overrideMat )
  380. {
  381. GFXTransformSaver saver;
  382. GFX->multWorld( getRenderTransform() );
  383. for ( U32 i=0; i < mDebugCells.size(); i++ )
  384. mDebugCells[i]->renderBounds();
  385. mDebugCells.clear();
  386. }