imposterCapture.cpp 17 KB

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