terrRender.cpp 16 KB

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