imposterCapture.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 "util/imposterCapture.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "core/color.h"
  26. #include "renderInstance/renderPassManager.h"
  27. #include "renderInstance/renderMeshMgr.h"
  28. #include "materials/materialManager.h"
  29. #include "materials/materialFeatureTypes.h"
  30. #include "materials/customMaterialDefinition.h"
  31. #include "ts/tsShapeInstance.h"
  32. #include "scene/sceneManager.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "lighting/lightInfo.h"
  35. #include "gfx/gfxTransformSaver.h"
  36. #include "gfx/gfxDebugEvent.h"
  37. #include "core/stream/fileStream.h"
  38. /// A material hook used to hold imposter generation
  39. /// rendering materials for an object.
  40. class ImposterCaptureMaterialHook : public MatInstanceHook
  41. {
  42. public:
  43. ImposterCaptureMaterialHook();
  44. // MatInstanceHook
  45. virtual ~ImposterCaptureMaterialHook();
  46. virtual const MatInstanceHookType& getType() const { return Type; }
  47. /// The material hook type.
  48. static const MatInstanceHookType Type;
  49. void init( BaseMatInstance *mat );
  50. static BaseMatInstance* getDiffuseInst( BaseMatInstance *inMat )
  51. { return _getOrCreateHook( inMat )->mDiffuseMatInst; }
  52. static BaseMatInstance* getNormalsInst( BaseMatInstance *inMat )
  53. { return _getOrCreateHook( inMat )->mNormalsMatInst; }
  54. protected:
  55. static void _overrideFeatures( ProcessedMaterial *mat,
  56. U32 stageNum,
  57. MaterialFeatureData &fd,
  58. const FeatureSet &features );
  59. static ImposterCaptureMaterialHook* _getOrCreateHook( BaseMatInstance *inMat );
  60. ///
  61. BaseMatInstance *mDiffuseMatInst;
  62. ///
  63. BaseMatInstance *mNormalsMatInst;
  64. };
  65. const MatInstanceHookType ImposterCaptureMaterialHook::Type( "ImposterCapture" );
  66. ImposterCaptureMaterialHook::ImposterCaptureMaterialHook()
  67. : mDiffuseMatInst( NULL ),
  68. mNormalsMatInst( NULL )
  69. {
  70. }
  71. ImposterCaptureMaterialHook::~ImposterCaptureMaterialHook()
  72. {
  73. SAFE_DELETE( mDiffuseMatInst );
  74. SAFE_DELETE( mNormalsMatInst );
  75. }
  76. void ImposterCaptureMaterialHook::init( BaseMatInstance *inMat )
  77. {
  78. // We cannot capture impostors on custom materials
  79. // as we don't know how to get just diffuse and just
  80. // normals rendering.
  81. if ( dynamic_cast<CustomMaterial*>( inMat->getMaterial() ) )
  82. return;
  83. // Tweak the feature data to include just what we need.
  84. FeatureSet features;
  85. features.addFeature( MFT_VertTransform );
  86. features.addFeature( MFT_DiffuseMap );
  87. features.addFeature( MFT_OverlayMap );
  88. features.addFeature( MFT_DetailMap );
  89. features.addFeature( MFT_DiffuseColor );
  90. features.addFeature( MFT_AlphaTest );
  91. features.addFeature( MFT_IsTranslucent );
  92. const String &matName = inMat->getMaterial()->getName();
  93. mDiffuseMatInst = MATMGR->createMatInstance( matName );
  94. mDiffuseMatInst->getFeaturesDelegate().bind( &ImposterCaptureMaterialHook::_overrideFeatures );
  95. mDiffuseMatInst->init( features, inMat->getVertexFormat() );
  96. features.addFeature( MFT_IsBC3nm );
  97. features.addFeature( MFT_NormalMap );
  98. features.addFeature( MFT_NormalsOut );
  99. features.addFeature( MFT_AccuMap );
  100. mNormalsMatInst = MATMGR->createMatInstance( matName );
  101. mNormalsMatInst->getFeaturesDelegate().bind( &ImposterCaptureMaterialHook::_overrideFeatures );
  102. mNormalsMatInst->init( features, inMat->getVertexFormat() );
  103. }
  104. void ImposterCaptureMaterialHook::_overrideFeatures( ProcessedMaterial *mat,
  105. U32 stageNum,
  106. MaterialFeatureData &fd,
  107. const FeatureSet &features )
  108. {
  109. if ( features.hasFeature( MFT_NormalsOut) )
  110. fd.features.addFeature( MFT_NormalsOut );
  111. fd.features.addFeature( MFT_ForwardShading );
  112. fd.features.addFeature( MFT_Imposter );
  113. }
  114. ImposterCaptureMaterialHook* ImposterCaptureMaterialHook::_getOrCreateHook( BaseMatInstance *inMat )
  115. {
  116. ImposterCaptureMaterialHook *hook = inMat->getHook<ImposterCaptureMaterialHook>();
  117. if ( !hook )
  118. {
  119. // Create a hook and initialize it using the incoming material.
  120. hook = new ImposterCaptureMaterialHook;
  121. hook->init( inMat );
  122. inMat->addHook( hook );
  123. }
  124. return hook;
  125. }
  126. ImposterCapture::ImposterCapture()
  127. : mDl( 0 ),
  128. mDim( 0 ),
  129. mRadius( 0.0f ),
  130. mCenter( Point3F( 0, 0, 0 ) ),
  131. mBlackBmp( NULL ),
  132. mWhiteBmp( NULL ),
  133. mState( NULL ),
  134. mShapeInstance( NULL ),
  135. mRenderTarget( NULL ),
  136. mRenderPass( NULL ),
  137. mMeshRenderBin( NULL )
  138. {
  139. }
  140. ImposterCapture::~ImposterCapture()
  141. {
  142. AssertFatal( !mShapeInstance, "ImposterCapture destructor - TSShapeInstance hasn't been cleared!" );
  143. }
  144. void ImposterCapture::_colorAverageFilter( U32 dimensions, const U8 *inBmpBits, U8 *outBmpBits )
  145. {
  146. LinearColorF color;
  147. U32 count = 0;
  148. U32 index, index2;
  149. for ( S32 y = 0; y < dimensions; y++ )
  150. {
  151. for( S32 x = 0; x < dimensions; x++ )
  152. {
  153. // We only blend on transparent pixels.
  154. index = ( ( y * dimensions ) + x ) * 4;
  155. if ( inBmpBits[index+3] > 84 )
  156. {
  157. outBmpBits[index+0] = inBmpBits[index+0];
  158. outBmpBits[index+1] = inBmpBits[index+1];
  159. outBmpBits[index+2] = inBmpBits[index+2];
  160. outBmpBits[index+3] = inBmpBits[index+3]; //hack
  161. continue;
  162. }
  163. color.set(0,0,0);
  164. count = 0;
  165. for ( S32 fy = y-6; fy <= y+6; fy++ )
  166. {
  167. for ( S32 fx = x-6; fx <= x+6; fx++ )
  168. {
  169. if ( fy >= 0 && fy < (dimensions-1) &&
  170. fx >= 0 && fx < (dimensions-1) )
  171. {
  172. index2 = ( ( fy * dimensions ) + fx ) * 4;
  173. if ( inBmpBits[index2+3] > 84 )
  174. {
  175. color.red += inBmpBits[index2+0];
  176. color.green += inBmpBits[index2+1];
  177. color.blue += inBmpBits[index2+2];
  178. ++count;
  179. }
  180. }
  181. }
  182. }
  183. outBmpBits[index+0] = (U8)( (F32)color.red / (F32)count );
  184. outBmpBits[index+1] = (U8)( (F32)color.green / (F32)count );
  185. outBmpBits[index+2] = (U8)( (F32)color.blue / (F32)count );
  186. outBmpBits[index+3] = 0;
  187. }
  188. }
  189. }
  190. void ImposterCapture::_renderToTexture( GFXTexHandle texHandle, GBitmap *outBitmap, const ColorI &color )
  191. {
  192. GFXDEBUGEVENT_SCOPE( ImposterCapture_RenderToTexture, ColorI::RED );
  193. PROFILE_SCOPE( ImposterCapture_RenderToTexture );
  194. mRenderTarget->attachTexture( GFXTextureTarget::Color0, texHandle );
  195. mRenderTarget->attachTexture( GFXTextureTarget::DepthStencil, mDepthBuffer );
  196. GFX->setActiveRenderTarget( mRenderTarget );
  197. GFX->clear( GFXClearZBuffer | GFXClearStencil | GFXClearTarget, color, 1.0f, 0 );
  198. mShapeInstance->render( mRData, mDl, 1.0f );
  199. mState->getRenderPass()->renderPass( mState );
  200. mRenderTarget->resolve();
  201. texHandle->copyToBmp( outBitmap );
  202. }
  203. void ImposterCapture::_separateAlpha( GBitmap *imposterOut )
  204. {
  205. PROFILE_START(TSShapeInstance_snapshot_sb_separate);
  206. // TODO: Remove all this when we get rid of the 'render on black/white'.
  207. // now separate the color and alpha channels
  208. GBitmap *bmp = new GBitmap;
  209. bmp->allocateBitmap(mDim, mDim, false, GFXFormatR8G8B8A8);
  210. U8 * wbmp = (U8*)mWhiteBmp->getBits(0);
  211. U8 * bbmp = (U8*)mBlackBmp->getBits(0);
  212. U8 * dst = (U8*)bmp->getBits(0);
  213. const U32 pixCount = mDim * mDim;
  214. // simpler, probably faster...
  215. for ( U32 i=0; i < pixCount; i++ )
  216. {
  217. // Shape on black background is alpha * color, shape on white
  218. // background is alpha * color + (1-alpha) * 255 we want 255 *
  219. // alpha, or 255 - (white - black).
  220. //
  221. // JMQ: or more verbosely:
  222. // cB = alpha * color + (0 * (1 - alpha))
  223. // cB = alpha * color
  224. // cW = alpha * color + (255 * (1 - alpha))
  225. // cW = cB + (255 * (1 - alpha))
  226. // solving for alpha
  227. // cW - cB = 255 * (1 - alpha)
  228. // (cW - cB)/255 = (1 - alpha)
  229. // alpha = 1 - (cW - cB)/255
  230. // since we want alpha*255, multiply through by 255
  231. // alpha * 255 = 255 - cW - cB
  232. U32 alpha = 255 - (wbmp[i*3+0] - bbmp[i*3+0]);
  233. alpha += 255 - (wbmp[i*3+1] - bbmp[i*3+1]);
  234. alpha += 255 - (wbmp[i*3+2] - bbmp[i*3+2]);
  235. if ( alpha != 0 )
  236. {
  237. F32 floatAlpha = ((F32)alpha)/(3.0f*255.0f);
  238. dst[i*4+0] = (U8)(bbmp[i*3+0] / floatAlpha);
  239. dst[i*4+1] = (U8)(bbmp[i*3+1] / floatAlpha);
  240. dst[i*4+2] = (U8)(bbmp[i*3+2] / floatAlpha);
  241. // Before we assign the alpha we "fizzle" the value
  242. // if its greater than 84. This causes the imposter
  243. // to dissolve instead of popping into view.
  244. alpha /= 3;
  245. dst[i*4+3] = (U8)alpha;
  246. }
  247. else
  248. {
  249. dst[i*4+0] = dst[i*4+1] = dst[i*4+2] = dst[i*4+3] = 0;
  250. }
  251. }
  252. PROFILE_END(); // TSShapeInstance_snapshot_sb_separate
  253. PROFILE_START(TSShapeInstance_snapshot_sb_filter);
  254. // We now run a special kernel filter over the image that
  255. // averages color into the transparent areas. This should
  256. // in essence give us a border around the edges of the
  257. // imposter silhouette which fixes the artifacts around the
  258. // alpha test billboards.
  259. U8* dst2 = (U8*)imposterOut->getBits(0);
  260. _colorAverageFilter( mDim, dst, dst2 );
  261. if ( 0 )
  262. {
  263. FileStream fs;
  264. if ( fs.open( "./imposterout.png", Torque::FS::File::Write ) )
  265. imposterOut->writeBitmap( "png", fs );
  266. fs.close();
  267. if ( fs.open( "./temp.png", Torque::FS::File::Write ) )
  268. bmp->writeBitmap( "png", fs );
  269. fs.close();
  270. }
  271. PROFILE_END(); // TSShapeInstance_snapshot_sb_filter
  272. delete bmp;
  273. }
  274. void ImposterCapture::_convertDXT5nm( GBitmap *normalsOut )
  275. {
  276. PROFILE_SCOPE(ImposterCapture_ConvertDXT5nm);
  277. U8 *bits = (U8*)normalsOut->getBits(0);
  278. const U32 pixCount = mDim * mDim;
  279. U8 x, y, z;
  280. // Encoding in object space DXT5 which moves
  281. // one of the coords to the alpha channel for
  282. // improved precision.... in our case z.
  283. for ( U32 i=0; i < pixCount; i++ )
  284. {
  285. x = bits[i*4+0];
  286. y = bits[i*4+1];
  287. z = bits[i*4+2];
  288. bits[i*4+0] = x;
  289. bits[i*4+1] = y;
  290. bits[i*4+2] = 0;
  291. bits[i*4+3] = z;
  292. }
  293. }
  294. void ImposterCapture::begin( TSShapeInstance *shapeInst,
  295. S32 dl,
  296. S32 dim,
  297. F32 radius,
  298. const Point3F &center )
  299. {
  300. mShapeInstance = shapeInst;
  301. mDl = dl;
  302. mDim = dim;
  303. mRadius = radius;
  304. mCenter = center;
  305. mBlackTex.set( mDim, mDim, GFXFormatR8G8B8A8_SRGB, &GFXRenderTargetSRGBProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  306. mWhiteTex.set( mDim, mDim, GFXFormatR8G8B8A8_SRGB, &GFXRenderTargetSRGBProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  307. mNormalTex.set( mDim, mDim, GFXFormatR8G8B8A8, &GFXRenderTargetProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  308. mDepthBuffer.set( mDim, mDim, GFXFormatD24S8, &GFXZTargetProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  309. // copy the black render target data into a bitmap
  310. mBlackBmp = new GBitmap;
  311. mBlackBmp->allocateBitmap(mDim, mDim, false, GFXFormatR8G8B8);
  312. // copy the white target data into a bitmap
  313. mWhiteBmp = new GBitmap;
  314. mWhiteBmp->allocateBitmap(mDim, mDim, false, GFXFormatR8G8B8);
  315. // Setup viewport and frustrum to do orthographic projection.
  316. RectI viewport( 0, 0, mDim, mDim );
  317. GFX->setViewport( viewport );
  318. GFX->setOrtho( -mRadius, mRadius, -mRadius, mRadius, 1, 20.0f * mRadius );
  319. // Position camera looking out the X axis.
  320. MatrixF cameraMatrix( true );
  321. cameraMatrix.setColumn( 0, Point3F( 0, 0, 1 ) );
  322. cameraMatrix.setColumn( 1, Point3F( 1, 0, 0 ) );
  323. cameraMatrix.setColumn( 2, Point3F( 0, 1, 0 ) );
  324. // setup scene state required for TS mesh render...this is messy and inefficient;
  325. // should have a mode where most of this is done just once (and then
  326. // only the camera matrix changes between snapshots).
  327. // note that we use getFrustum here, but we set up an ortho projection above.
  328. // it doesn't seem like the scene state object pays attention to whether the projection is
  329. // ortho or not. this could become a problem if some code downstream tries to
  330. // reconstruct the projection matrix using the dimensions and doesn't
  331. // realize it should be ortho. at the moment no code is doing that.
  332. F32 left, right, top, bottom, nearPlane, farPlane;
  333. bool isOrtho;
  334. GFX->getFrustum( &left, &right, &bottom, &top, &nearPlane, &farPlane, &isOrtho );
  335. Frustum frust( isOrtho, left, right, top, bottom, nearPlane, farPlane, cameraMatrix );
  336. // Set up render pass.
  337. mRenderPass = new RenderPassManager();
  338. mRenderPass->assignName( "DiffuseRenderPass" );
  339. mMeshRenderBin = new RenderMeshMgr();
  340. mRenderPass->addManager( mMeshRenderBin );
  341. // Set up scene state.
  342. mState = new SceneRenderState(
  343. gClientSceneGraph,
  344. SPT_Diffuse,
  345. SceneCameraState( viewport, frust, GFX->getWorldMatrix(),GFX->getProjectionMatrix() ),
  346. mRenderPass,
  347. false
  348. );
  349. // Set up our TS render state.
  350. mRData.setSceneState( mState );
  351. mRData.setCubemap( NULL );
  352. mRData.setFadeOverride( 1.0f );
  353. // set gfx up for render to texture
  354. GFX->pushActiveRenderTarget();
  355. mRenderTarget = GFX->allocRenderToTextureTarget();
  356. }
  357. void ImposterCapture::capture( const MatrixF &rotMatrix,
  358. GBitmap **imposterOut,
  359. GBitmap **normalMapOut )
  360. {
  361. GFXTransformSaver saver;
  362. // this version of the snapshot function renders the shape to a black texture, then to white, then reads bitmaps
  363. // back for both renders and combines them, restoring the alpha and color values. this is based on the
  364. // TGE implementation. it is not fast due to the copy and software combination operations. the generated bitmaps
  365. // are upside-down (which is how TGE generated them...)
  366. (*imposterOut) = new GBitmap( mDim, mDim, false, GFXFormatR8G8B8A8 );
  367. (*normalMapOut) = new GBitmap( mDim, mDim, false, GFXFormatR8G8B8A8 );
  368. // The object to world transform.
  369. MatrixF centerMat( true );
  370. centerMat.setPosition( -mCenter );
  371. MatrixF objMatrix( rotMatrix );
  372. objMatrix.mul( centerMat );
  373. GFX->setWorldMatrix( objMatrix );
  374. // The view transform.
  375. MatrixF view( EulerF( M_PI_F / 2.0f, 0, M_PI_F ), Point3F( 0, 0, -10.0f * mRadius ) );
  376. mRenderPass->assignSharedXform( RenderPassManager::View, view );
  377. mRenderPass->assignSharedXform( RenderPassManager::Projection, GFX->getProjectionMatrix() );
  378. // Render the diffuse pass.
  379. mRenderPass->clear();
  380. mMeshRenderBin->getMatOverrideDelegate().bind( ImposterCaptureMaterialHook::getDiffuseInst );
  381. _renderToTexture( mBlackTex, mBlackBmp, ColorI(0, 0, 0, 0) );
  382. _renderToTexture( mWhiteTex, mWhiteBmp, ColorI(255, 255, 255, 255) );
  383. // Now render the normals.
  384. mRenderPass->clear();
  385. mMeshRenderBin->getMatOverrideDelegate().bind( ImposterCaptureMaterialHook::getNormalsInst );
  386. _renderToTexture( mNormalTex, *normalMapOut, ColorI(0, 0, 0, 0) );
  387. _separateAlpha( *imposterOut );
  388. _convertDXT5nm( *normalMapOut );
  389. if ( 0 )
  390. {
  391. // Render out the bitmaps for debug purposes.
  392. FileStream fs;
  393. if ( fs.open( "./blackbmp.png", Torque::FS::File::Write ) )
  394. mBlackBmp->writeBitmap( "png", fs );
  395. fs.close();
  396. if ( fs.open( "./whitebmp.png", Torque::FS::File::Write ) )
  397. mWhiteBmp->writeBitmap( "png", fs );
  398. fs.close();
  399. if ( fs.open( "./normalbmp.png", Torque::FS::File::Write ) )
  400. (*normalMapOut)->writeBitmap( "png", fs );
  401. fs.close();
  402. if ( fs.open( "./finalimposter.png", Torque::FS::File::Write ) )
  403. (*imposterOut)->writeBitmap( "png", fs );
  404. fs.close();
  405. }
  406. }
  407. void ImposterCapture::end()
  408. {
  409. GFX->popActiveRenderTarget();
  410. mBlackTex.free();
  411. mWhiteTex.free();
  412. mNormalTex.free();
  413. mShapeInstance = NULL;
  414. mRenderTarget = NULL;
  415. mMeshRenderBin = NULL; // Deleted by mRenderPass
  416. SAFE_DELETE( mState );
  417. SAFE_DELETE( mRenderPass );
  418. SAFE_DELETE( mBlackBmp );
  419. SAFE_DELETE( mWhiteBmp );
  420. }