terrRender.cpp 17 KB

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