terrRender.cpp 16 KB

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