renderParticleMgr.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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 "renderInstance/renderParticleMgr.h"
  24. #include "renderInstance/renderPrePassMgr.h"
  25. #include "scene/sceneManager.h"
  26. #include "scene/sceneObject.h"
  27. #include "scene/sceneRenderState.h"
  28. #include "gfx/gfxPrimitiveBuffer.h"
  29. #include "gfx/gfxTransformSaver.h"
  30. #include "gfx/gfxDebugEvent.h"
  31. #include "materials/shaderData.h"
  32. #include "materials/sceneData.h"
  33. #include "materials/matInstance.h"
  34. #include "gfx/util/screenspace.h"
  35. #include "gfx/gfxDrawUtil.h"
  36. #include "collision/clippedPolyList.h"
  37. static const Point4F cubePoints[9] =
  38. {
  39. Point4F(-0.5, -0.5, -0.5, 1.0f), Point4F(-0.5, -0.5, 0.5, 1.0f), Point4F(-0.5, 0.5, -0.5, 1.0f), Point4F(-0.5, 0.5, 0.5, 1.0f),
  40. Point4F( 0.5, -0.5, -0.5, 1.0f), Point4F( 0.5, -0.5, 0.5, 1.0f), Point4F( 0.5, 0.5, -0.5, 1.0f), Point4F( 0.5, 0.5, 0.5, 1.0f)
  41. };
  42. GFXImplementVertexFormat( CompositeQuadVert )
  43. {
  44. addElement( "COLOR", GFXDeclType_Color );
  45. }
  46. IMPLEMENT_CONOBJECT(RenderParticleMgr);
  47. ConsoleDocClass( RenderParticleMgr,
  48. "@brief A render bin which renders particle geometry.\n\n"
  49. "This render bin gathers particle render instances, sorts, and renders them. "
  50. "It is currently used by ParticleEmitter and LightFlareData.\n\n"
  51. "@ingroup RenderBin\n" );
  52. const RenderInstType RenderParticleMgr::RIT_Particles("ParticleSystem");
  53. // TODO: Replace these once they are supported via options
  54. const bool RenderToParticleTarget = true;
  55. const bool RenderToSingleTarget = true;
  56. RenderParticleMgr::RenderParticleMgr()
  57. : Parent( RenderParticleMgr::RIT_Particles,
  58. 1.0f,
  59. 1.0f,
  60. GFXFormatR8G8B8A8,
  61. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  62. RenderToParticleTarget ? Parent::DefaultTargetChainLength : 0 ),
  63. mParticleShader( NULL )
  64. {
  65. // Render particles at 1/4 resolution
  66. mTargetSizeType = WindowSizeScaled;
  67. mTargetScale.set(0.5f, 0.5f);
  68. // We use the target chain like a texture pool, not like a swap chain
  69. if(!RenderToSingleTarget)
  70. setTargetChainLength(5);
  71. else
  72. mOffscreenSystems.setSize(1);
  73. notifyType( RenderPassManager::RIT_Particle );
  74. LightManager::smActivateSignal.notify( this, &RenderParticleMgr::_onLMActivate );
  75. }
  76. RenderParticleMgr::~RenderParticleMgr()
  77. {
  78. LightManager::smActivateSignal.remove( this, &RenderParticleMgr::_onLMActivate );
  79. }
  80. void RenderParticleMgr::setTargetChainLength( const U32 chainLength )
  81. {
  82. Parent::setTargetChainLength(chainLength);
  83. if(!RenderToSingleTarget)
  84. mOffscreenSystems.setSize(chainLength);
  85. }
  86. void RenderParticleMgr::addElement( RenderInst *inst )
  87. {
  88. ParticleRenderInst *pri = reinterpret_cast<ParticleRenderInst *>(inst);
  89. // If this system isn't waiting for an offscreen draw, skip it
  90. if( pri->systemState != PSS_AwaitingOffscreenDraw )
  91. return;
  92. // If offscreen rendering isn't enabled, set to high-res, and skip
  93. if(!mOffscreenRenderEnabled)
  94. {
  95. pri->systemState = PSS_AwaitingHighResDraw;
  96. return;
  97. }
  98. // Assign a target index
  99. RectF screenRect;
  100. S32 chainIndex = -1;
  101. if(RenderToSingleTarget)
  102. {
  103. pri->targetIndex = 0;
  104. screenRect.point.set(-1.0f, -1.0f);
  105. screenRect.extent.set(2.0f, 2.0f);
  106. mElementList.setSize(1);
  107. }
  108. else
  109. {
  110. // If we can't fit this into the offscreen systems, skip it, it will render
  111. // high resolution
  112. //
  113. // TODO: Improve this once we are grouping systems
  114. if( mTargetChainIdx == OffscreenPoolSize )
  115. return;
  116. // Transform bounding box into screen space
  117. const static PlaneF planes[] = {
  118. PlaneF(Point3F( 1.0f, 0.0f, 0.0f), Point3F(-1.0f, 0.0f, 0.0f)),
  119. PlaneF(Point3F(-1.0f, 0.0f, 0.0f), Point3F( 1.0f, 0.0f, 0.0f)),
  120. PlaneF(Point3F( 0.0f, 1.0f, 0.0f), Point3F( 0.0f, -1.0f, 0.0f)),
  121. PlaneF(Point3F( 0.0f, -1.0f, 0.0f), Point3F( 0.0f, 1.0f, 0.0f)),
  122. PlaneF(Point3F( 0.0f, 0.0f, 0.0f), Point3F( 0.0f, 0.0f, 1.0f)),
  123. PlaneF(Point3F( 0.0f, 0.0f, 1.0f), Point3F( 0.0f, 0.0f, -1.0f)),
  124. };
  125. const static dsize_t numPlanes = sizeof(planes) / sizeof(PlaneF);
  126. // Set up a clipper
  127. ClippedPolyList screenClipper;
  128. screenClipper.setBaseTransform(MatrixF::Identity);
  129. screenClipper.setTransform(&MatrixF::Identity, Point3F::One);
  130. TORQUE_UNUSED(numPlanes);
  131. Point4F tempPt(0.0f, 0.0f, 0.0f, 1.0f);
  132. pri->bbModelViewProj->mul(tempPt);
  133. tempPt = tempPt / tempPt.w;
  134. for(S32 i = 0; i < 1; i++)
  135. {
  136. screenClipper.mPlaneList.push_back(planes[i]);
  137. screenClipper.mPlaneList.last() += tempPt.asPoint3F();
  138. }
  139. Box3F screenSpaceBoundingBox;
  140. screenSpaceBoundingBox.minExtents = Point3F::Zero;
  141. screenSpaceBoundingBox.maxExtents = Point3F::Zero;
  142. for(S32 i = 0; i < 8; i++)
  143. {
  144. tempPt = cubePoints[i];
  145. pri->bbModelViewProj->mul(tempPt);
  146. tempPt = tempPt / tempPt.w;
  147. screenSpaceBoundingBox.maxExtents.setMax(tempPt.asPoint3F());
  148. screenSpaceBoundingBox.minExtents.setMin(tempPt.asPoint3F());
  149. }
  150. screenClipper.addBox(screenSpaceBoundingBox);
  151. screenClipper.cullUnusedVerts();
  152. //screenClipper.triangulate();
  153. // Empty vertex list? Skip!
  154. if(screenClipper.mVertexList.empty())
  155. {
  156. pri->systemState = PSS_AwaitingHighResDraw;
  157. return;
  158. }
  159. Point2F minExtents(0.0f, 0.0f), maxExtents(0.0f, 0.0f);
  160. for(ClippedPolyList::VertexList::const_iterator itr = screenClipper.mVertexList.begin();
  161. itr != screenClipper.mVertexList.end(); itr++)
  162. {
  163. minExtents.x = getMin(minExtents.x, (*itr).point.x);
  164. minExtents.y = getMin(minExtents.y, (*itr).point.y);
  165. maxExtents.x = getMax(maxExtents.x, (*itr).point.x);
  166. maxExtents.y = getMax(maxExtents.y, (*itr).point.y);
  167. }
  168. screenRect.set( minExtents, maxExtents - minExtents );
  169. // Check the size of the system on screen. If it is small, it won't
  170. // be eating fillrate anyway, so just draw it high-resolution.
  171. // The value it checks against is one I found from experimentation,
  172. // not anything really meaningful.
  173. if( screenRect.extent.x < 0.35f || screenRect.extent.y < 0.35f )
  174. {
  175. pri->systemState = PSS_AwaitingHighResDraw;
  176. return;
  177. }
  178. pri->targetIndex = mTargetChainIdx;
  179. chainIndex = mTargetChainIdx;
  180. mTargetChainIdx++;
  181. // TODO: Rewrite this...
  182. mElementList.increment();
  183. }
  184. // Set up system entry
  185. OffscreenSystemEntry &systemEntry = mOffscreenSystems[pri->targetIndex];
  186. systemEntry.screenRect = screenRect;
  187. systemEntry.targetChainIdx = chainIndex;
  188. systemEntry.pInstances.push_back(pri);
  189. // TODO: Rewrite this block
  190. // Assign proper values to sort element
  191. MainSortElem& elem = mElementList.last();
  192. elem.inst = reinterpret_cast<RenderInst *>(&systemEntry);
  193. elem.key = *((U32*)&inst->sortDistSq);
  194. elem.key2 = inst->defaultKey;
  195. // TODO: [re]move this block
  196. systemEntry.clipMatrix.identity();
  197. if(!RenderToSingleTarget)
  198. {
  199. // Construct crop matrix
  200. Point3F scale( getMax(2.0f / systemEntry.screenRect.extent.x, 1.0f),
  201. getMax(2.0f / systemEntry.screenRect.extent.y, 1.0f),
  202. 1.0f);
  203. Point3F offset((systemEntry.screenRect.point.x + systemEntry.screenRect.extent.x * 0.5f) * scale.x,
  204. (systemEntry.screenRect.point.y + systemEntry.screenRect.extent.y * 0.5f) * scale.y,
  205. 0.0f);
  206. //systemEntry.clipMatrix.scale(scale);
  207. //systemEntry.clipMatrix.setPosition(-offset);
  208. }
  209. // The translucent mgr will also pick up particles, and will call this class
  210. // to composiste the particle systems back into the main scene
  211. }
  212. void RenderParticleMgr::sort()
  213. {
  214. Parent::sort();
  215. }
  216. void RenderParticleMgr::clear()
  217. {
  218. Parent::clear();
  219. // Reset pool index
  220. if(!RenderToSingleTarget)
  221. mTargetChainIdx = 0;
  222. for(Vector<OffscreenSystemEntry>::iterator itr = mOffscreenSystems.begin();
  223. itr != mOffscreenSystems.end(); itr++)
  224. {
  225. (*itr).drawnThisFrame = false;
  226. (*itr).pInstances.clear();
  227. }
  228. }
  229. void RenderParticleMgr::render( SceneRenderState *state )
  230. {
  231. PROFILE_SCOPE(RenderParticleMgr_render);
  232. // Early out if nothing to draw
  233. if( !mElementList.size() ||
  234. (!mParticleShader && !_initShader()) )
  235. return;
  236. GFXDEBUGEVENT_SCOPE(RenderParticleMgr_Render, ColorI::RED);
  237. GFXTransformSaver saver;
  238. // Iterate render instances
  239. for( Vector<MainSortElem>::const_iterator itr = mElementList.begin();
  240. itr != mElementList.end(); itr++ )
  241. {
  242. OffscreenSystemEntry &systemEntry = *reinterpret_cast<OffscreenSystemEntry *>(itr->inst);
  243. // Setup target
  244. // NOTE: If you are using this on the Xbox360 with Basic Lighting,
  245. // you are going to have to mess with either the render order, or
  246. // you are going to have to make this a 'preserve' draw
  247. if(!RenderToSingleTarget)
  248. mTargetChainIdx = systemEntry.targetChainIdx;
  249. _onPreRender(state);
  250. // Clear offscreen target
  251. GFX->clear(GFXClearTarget, ColorI::ZERO, 1.0f, 0);
  252. // Draw offscreen systems
  253. for( Vector<ParticleRenderInst *>::const_iterator itr2 = systemEntry.pInstances.begin();
  254. itr2 != systemEntry.pInstances.end(); itr2++ )
  255. {
  256. ParticleRenderInst *ri = *itr2;
  257. // Sanity check
  258. if(ri->systemState == PSS_AwaitingOffscreenDraw)
  259. {
  260. // If this is not a diffuse path, flag the system appropriately, and skip
  261. // the offscreen processing.
  262. if( !state->isDiffusePass() )
  263. {
  264. if(state->isReflectPass())
  265. ri->systemState = PSS_AwaitingHighResDraw;
  266. else
  267. ri->systemState = PSS_DrawComplete;
  268. continue;
  269. }
  270. // Draw system offscreen
  271. renderInstance(ri, state);
  272. }
  273. }
  274. // Cleanup
  275. _onPostRender();
  276. }
  277. }
  278. void RenderParticleMgr::_initGFXResources()
  279. {
  280. // Screen quad
  281. U16 *prims = NULL;
  282. mScreenQuadPrimBuff.set(GFX, 4, 2, GFXBufferTypeStatic);
  283. mScreenQuadPrimBuff.lock(&prims);
  284. (*prims++) = 0;
  285. (*prims++) = 1;
  286. (*prims++) = 2;
  287. (*prims++) = 3;
  288. mScreenQuadPrimBuff.unlock();
  289. mScreenQuadVertBuff.set(GFX, 4, GFXBufferTypeStatic);
  290. CompositeQuadVert *verts = mScreenQuadVertBuff.lock();
  291. (*verts++).uvCoord.set(0, 0, 0, 0);
  292. (*verts++).uvCoord.set(0, 255, 0, 0);
  293. (*verts++).uvCoord.set(255, 0, 0, 0);
  294. (*verts++).uvCoord.set(255, 255, 0, 0);
  295. mScreenQuadVertBuff.unlock();
  296. // Stencil setup state block
  297. GFXStateBlockDesc d;
  298. d.setCullMode(GFXCullNone);
  299. d.setColorWrites(false, false, false, false);
  300. d.setBlend(false);
  301. d.setZReadWrite(false, false);
  302. d.stencilDefined = true;
  303. d.stencilEnable = true;
  304. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  305. d.stencilWriteMask = RenderParticleMgr::ParticleSystemStencilMask;
  306. d.stencilFunc = GFXCmpAlways;
  307. d.stencilPassOp = GFXStencilOpZero;
  308. mStencilClearSB = GFX->createStateBlock(d);
  309. }
  310. void RenderParticleMgr::renderInstance(ParticleRenderInst *ri, SceneRenderState *state)
  311. {
  312. // Draw system path, or draw composite path
  313. if(ri->systemState == PSS_DrawComplete)
  314. return;
  315. if(ri->systemState != PSS_AwaitingCompositeDraw)
  316. {
  317. // Set proper stateblock, and update state
  318. if(ri->systemState == PSS_AwaitingOffscreenDraw)
  319. {
  320. GFX->setStateBlock( _getOffscreenStateBlock(ri) );
  321. ri->systemState = PSS_AwaitingCompositeDraw;
  322. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mModelViewProjSC,
  323. *ri->modelViewProj * mOffscreenSystems[ri->targetIndex].clipMatrix );
  324. }
  325. else
  326. {
  327. if(ri->systemState == PSS_AwaitingMixedResDraw)
  328. GFX->setStateBlock( _getMixedResStateBlock( ri ) );
  329. else
  330. GFX->setStateBlock( _getHighResStateBlock( ri ) );
  331. ri->systemState = PSS_DrawComplete;
  332. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mModelViewProjSC, *ri->modelViewProj );
  333. }
  334. renderParticle(ri, state);
  335. }
  336. else if(ri->systemState == PSS_AwaitingCompositeDraw)
  337. {
  338. OffscreenSystemEntry &systemEntry = mOffscreenSystems[ri->targetIndex];
  339. // If this system has already been composited this frame, skip it
  340. if(systemEntry.drawnThisFrame)
  341. return;
  342. // Non-target render, composite the particle system back into the scene
  343. GFX->setVertexBuffer(mScreenQuadVertBuff);
  344. GFX->setPrimitiveBuffer(mScreenQuadPrimBuff);
  345. // Set up shader constants
  346. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mScreenRect, *((Point4F *)&systemEntry.screenRect) );
  347. // Set offscreen texture
  348. Point4F rtParams;
  349. GFXTextureObject *particleSource = mNamedTarget.getTexture();
  350. GFX->setTexture( mParticleCompositeShaderConsts.mSamplerColorSource->getSamplerRegister(), particleSource );
  351. if(particleSource)
  352. {
  353. ScreenSpace::RenderTargetParameters(particleSource->getSize(), mNamedTarget.getViewport(), rtParams);
  354. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mOffscreenTargetParamsSC, rtParams );
  355. }
  356. // And edges
  357. GFXTextureObject *texObject = mEdgeTarget ? mEdgeTarget->getTexture() : NULL;
  358. GFX->setTexture( mParticleCompositeShaderConsts.mSamplerEdgeSource->getSamplerRegister(), texObject );
  359. if(texObject)
  360. {
  361. ScreenSpace::RenderTargetParameters(texObject->getSize(), mEdgeTarget->getViewport(), rtParams);
  362. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mEdgeTargetParamsSC, rtParams );
  363. }
  364. else
  365. {
  366. AssertFatal(false, "No edge texture target defined, if you want to use mixed particle"
  367. "rendering, then make sure that the EdgeDetectPostEffect is enabled.");
  368. ri->systemState = PSS_AwaitingHighResDraw;
  369. return;
  370. }
  371. // Set shader and constant buffer
  372. GFX->setShader( mParticleCompositeShader );
  373. GFX->setShaderConstBuffer( mParticleCompositeShaderConsts.mShaderConsts );
  374. // Draw to stencil buffer only to clear the stencil values
  375. GFX->setStateBlock( mStencilClearSB );
  376. GFX->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, 4, 0, 2 );
  377. // composite particle system back into the scene
  378. GFX->setStateBlock( _getCompositeStateBlock(ri) );
  379. GFX->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, 4, 0, 2 );
  380. // Re-draw the particle systems in high-res, but only to the stenciled
  381. // areas which were enabled via the edge buffer
  382. for( Vector<ParticleRenderInst *>::const_iterator itr = systemEntry.pInstances.begin();
  383. itr != systemEntry.pInstances.end(); itr++ )
  384. {
  385. ParticleRenderInst *pri = *itr;
  386. if(pri->systemState == PSS_AwaitingCompositeDraw)
  387. {
  388. pri->systemState = PSS_AwaitingMixedResDraw;
  389. renderInstance(pri, state);
  390. }
  391. }
  392. // Mark this system as having been composited this frame
  393. systemEntry.drawnThisFrame = true;
  394. }
  395. }
  396. void RenderParticleMgr::renderParticle(ParticleRenderInst* ri, SceneRenderState* state)
  397. {
  398. // We want to turn everything into variation on a pre-multiplied alpha blend
  399. F32 alphaFactor = 0.0f, alphaScale = 1.0f;
  400. switch(ri->blendStyle)
  401. {
  402. // SrcAlpha, InvSrcAlpha
  403. case ParticleRenderInst::BlendNormal:
  404. alphaFactor = 1.0f;
  405. break;
  406. // SrcAlpha, One
  407. case ParticleRenderInst::BlendAdditive:
  408. alphaFactor = 1.0f;
  409. alphaScale = 0.0f;
  410. break;
  411. // SrcColor, One
  412. case ParticleRenderInst::BlendGreyscale:
  413. alphaFactor = -1.0f;
  414. alphaScale = 0.0f;
  415. break;
  416. }
  417. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mAlphaFactorSC, alphaFactor );
  418. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mAlphaScaleSC, alphaScale );
  419. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mFSModelViewProjSC, *ri->modelViewProj );
  420. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mOneOverFarSC, 1.0f / state->getFarPlane() );
  421. if ( mParticleShaderConsts.mOneOverSoftnessSC->isValid() )
  422. {
  423. F32 oneOverSoftness = 1.0f;
  424. if ( ri->softnessDistance > 0.0f )
  425. oneOverSoftness = 1.0f / ( ri->softnessDistance / state->getFarPlane() );
  426. mParticleShaderConsts.mShaderConsts->set( mParticleShaderConsts.mOneOverSoftnessSC, oneOverSoftness );
  427. }
  428. GFX->setShader( mParticleShader );
  429. GFX->setShaderConstBuffer( mParticleShaderConsts.mShaderConsts );
  430. GFX->setTexture( mParticleShaderConsts.mSamplerDiffuse->getSamplerRegister(), ri->diffuseTex );
  431. // Set up the prepass texture.
  432. if ( mParticleShaderConsts.mPrePassTargetParamsSC->isValid() )
  433. {
  434. GFXTextureObject *texObject = mPrepassTarget ? mPrepassTarget->getTexture(0) : NULL;
  435. GFX->setTexture( mParticleShaderConsts.mSamplerPrePassTex->getSamplerRegister(), texObject );
  436. Point4F rtParams( 0.0f, 0.0f, 1.0f, 1.0f );
  437. if ( texObject )
  438. ScreenSpace::RenderTargetParameters(texObject->getSize(), mPrepassTarget->getViewport(), rtParams);
  439. mParticleShaderConsts.mShaderConsts->set( mParticleShaderConsts.mPrePassTargetParamsSC, rtParams );
  440. }
  441. GFX->setPrimitiveBuffer( *ri->primBuff );
  442. GFX->setVertexBuffer( *ri->vertBuff );
  443. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, ri->count * 4, 0, ri->count * 2 );
  444. }
  445. bool RenderParticleMgr::_initShader()
  446. {
  447. ShaderData *shaderData = NULL;
  448. bool ret = true;
  449. // Need depth from pre-pass, so get the macros
  450. Vector<GFXShaderMacro> macros;
  451. if ( mPrepassTarget )
  452. mPrepassTarget->getShaderMacros( &macros );
  453. // Create particle shader
  454. if ( !Sim::findObject( "ParticlesShaderData", shaderData ) || !shaderData )
  455. Con::warnf( "RenderParticleMgr::_initShader - failed to locate shader ParticlesShaderData!" );
  456. if( shaderData )
  457. mParticleShader = shaderData->getShader( macros );
  458. ret &= (mParticleShader != NULL);
  459. if ( mParticleShader )
  460. {
  461. mParticleShaderConsts.mShaderConsts = mParticleShader->allocConstBuffer();
  462. mParticleShaderConsts.mModelViewProjSC = mParticleShader->getShaderConstHandle( "$modelViewProj" );
  463. mParticleShaderConsts.mOneOverFarSC = mParticleShader->getShaderConstHandle( "$oneOverFar" );
  464. mParticleShaderConsts.mOneOverSoftnessSC = mParticleShader->getShaderConstHandle( "$oneOverSoftness" );
  465. mParticleShaderConsts.mAlphaFactorSC = mParticleShader->getShaderConstHandle( "$alphaFactor" );
  466. mParticleShaderConsts.mAlphaScaleSC = mParticleShader->getShaderConstHandle( "$alphaScale" );
  467. mParticleShaderConsts.mFSModelViewProjSC = mParticleShader->getShaderConstHandle( "$fsModelViewProj" );
  468. mParticleShaderConsts.mPrePassTargetParamsSC = mParticleShader->getShaderConstHandle( "$prePassTargetParams" );
  469. //samplers
  470. mParticleShaderConsts.mSamplerDiffuse = mParticleShader->getShaderConstHandle("$diffuseMap");
  471. mParticleShaderConsts.mSamplerPrePassTex = mParticleShader->getShaderConstHandle("$prepassTex");
  472. mParticleShaderConsts.mSamplerParaboloidLightMap = mParticleShader->getShaderConstHandle("$paraboloidLightMap");
  473. }
  474. shaderData = NULL;
  475. // Create off screen particle composite shader
  476. if ( !Sim::findObject( "OffscreenParticleCompositeShaderData", shaderData ) || !shaderData )
  477. Con::warnf( "RenderParticleMgr::_initShader - failed to locate shader OffscreenParticleCompositeShaderData!" );
  478. if( shaderData )
  479. mParticleCompositeShader = shaderData->getShader( macros );
  480. ret &= (mParticleCompositeShader != NULL);
  481. if ( mParticleCompositeShader )
  482. {
  483. mParticleCompositeShaderConsts.mShaderConsts = mParticleCompositeShader->allocConstBuffer();
  484. mParticleCompositeShaderConsts.mScreenRect = mParticleCompositeShader->getShaderConstHandle( "$screenRect" );
  485. mParticleCompositeShaderConsts.mSamplerColorSource = mParticleCompositeShader->getShaderConstHandle( "$colorSource" );
  486. mParticleCompositeShaderConsts.mSamplerEdgeSource = mParticleCompositeShader->getShaderConstHandle( "$edgeSource" );
  487. mParticleCompositeShaderConsts.mEdgeTargetParamsSC = mParticleCompositeShader->getShaderConstHandle( "$edgeTargetParams" );
  488. mParticleCompositeShaderConsts.mOffscreenTargetParamsSC = mParticleCompositeShader->getShaderConstHandle( "$offscreenTargetParams" );
  489. }
  490. return ret;
  491. }
  492. void RenderParticleMgr::_onLMActivate( const char*, bool activate )
  493. {
  494. RenderPassManager *rpm = getRenderPass();
  495. if ( !rpm )
  496. return;
  497. // Hunt for the pre-pass manager/target
  498. RenderPrePassMgr *prePassBin = NULL;
  499. for( U32 i = 0; i < rpm->getManagerCount(); i++ )
  500. {
  501. RenderBinManager *bin = rpm->getManager(i);
  502. if( bin->getRenderInstType() == RenderPrePassMgr::RIT_PrePass )
  503. {
  504. prePassBin = (RenderPrePassMgr*)bin;
  505. break;
  506. }
  507. }
  508. // If we found the prepass bin, set this bin to render very shortly afterwards
  509. // and re-add this render-manager. If there is no pre-pass bin, or it doesn't
  510. // have a depth-texture, we can't render offscreen.
  511. mOffscreenRenderEnabled = prePassBin && (prePassBin->getTargetChainLength() > 0);
  512. if(mOffscreenRenderEnabled)
  513. {
  514. rpm->removeManager(this);
  515. setRenderOrder( prePassBin->getRenderOrder() + 0.011f );
  516. rpm->addManager(this);
  517. }
  518. // Find the targets we use
  519. mPrepassTarget = NamedTexTarget::find( "prepass" );
  520. mEdgeTarget = NamedTexTarget::find( "edge" );
  521. // Setup the shader
  522. if ( activate )
  523. _initShader();
  524. if ( mScreenQuadVertBuff.isNull() )
  525. _initGFXResources();
  526. }
  527. GFXStateBlockRef RenderParticleMgr::_getOffscreenStateBlock(ParticleRenderInst *ri)
  528. {
  529. const U8 blendStyle = ri->blendStyle;
  530. if ( mOffscreenBlocks[blendStyle].isValid() )
  531. return mOffscreenBlocks[blendStyle];
  532. GFXStateBlockDesc d;
  533. d.setCullMode(GFXCullNone);
  534. d.setZReadWrite(false, false); // No zreads or writes, all z-testing is done in the pixel shader
  535. // Draw everything either subtractive, or using a variation on premultiplied
  536. // alpha
  537. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  538. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  539. else
  540. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  541. // Offscreen target, we need to add alpha.
  542. d.separateAlphaBlendDefined = true;
  543. d.separateAlphaBlendEnable = true;
  544. d.separateAlphaBlendSrc = GFXBlendOne;
  545. d.separateAlphaBlendDest = GFXBlendInvSrcAlpha;
  546. d.samplersDefined = true;
  547. // Diffuse texture sampler
  548. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  549. d.samplers[0].alphaOp = GFXTOPModulate;
  550. d.samplers[0].alphaArg1 = GFXTATexture;
  551. d.samplers[0].alphaArg2 = GFXTADiffuse;
  552. // Prepass sampler
  553. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  554. mOffscreenBlocks[blendStyle] = GFX->createStateBlock(d);
  555. return mOffscreenBlocks[blendStyle];
  556. }
  557. GFXStateBlockRef RenderParticleMgr::_getHighResStateBlock(ParticleRenderInst *ri)
  558. {
  559. const U8 blendStyle = ri->blendStyle;
  560. if ( mHighResBlocks[blendStyle].isValid() )
  561. return mHighResBlocks[blendStyle];
  562. GFXStateBlockDesc d;
  563. d.setZReadWrite(true, false);
  564. d.setCullMode(GFXCullNone);
  565. // Draw everything either subtractive, or using a variation on premultiplied
  566. // alpha
  567. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  568. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  569. else
  570. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  571. d.samplersDefined = true;
  572. // Diffuse texture sampler
  573. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  574. d.samplers[0].alphaOp = GFXTOPModulate;
  575. d.samplers[0].alphaArg1 = GFXTATexture;
  576. d.samplers[0].alphaArg2 = GFXTADiffuse;
  577. // Prepass sampler
  578. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  579. mHighResBlocks[blendStyle] = GFX->createStateBlock(d);
  580. return mHighResBlocks[blendStyle];
  581. }
  582. GFXStateBlockRef RenderParticleMgr::_getMixedResStateBlock(ParticleRenderInst *ri)
  583. {
  584. const U8 blendStyle = ri->blendStyle;
  585. if ( mMixedResBlocks[blendStyle].isValid() )
  586. return mMixedResBlocks[blendStyle];
  587. GFXStateBlockDesc d;
  588. d.setZReadWrite(true, false);
  589. d.setCullMode(GFXCullNone);
  590. /*
  591. // Old blend styles...
  592. switch (blendStyle)
  593. {
  594. case ParticleRenderInst::BlendNormal:
  595. d.blendSrc = GFXBlendSrcAlpha;
  596. d.blendDest = GFXBlendInvSrcAlpha;
  597. break;
  598. case ParticleRenderInst::BlendSubtractive:
  599. d.blendSrc = GFXBlendZero;
  600. d.blendDest = GFXBlendInvSrcColor;
  601. break;
  602. case ParticleRenderInst::BlendPremultAlpha:
  603. d.blendSrc = GFXBlendOne;
  604. d.blendDest = GFXBlendInvSrcAlpha;
  605. break;
  606. // Default to additive blend mode
  607. case ParticleRenderInst::BlendAdditive:
  608. case ParticleRenderInst::BlendUndefined:
  609. default:
  610. d.blendSrc = GFXBlendSrcAlpha;
  611. d.blendDest = GFXBlendOne;
  612. break;
  613. }
  614. */
  615. // Draw everything either subtractive, or using a variation on premultiplied
  616. // alpha
  617. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  618. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  619. else
  620. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  621. // Draw to anything but the stencil ref value (the edges)
  622. d.stencilDefined = true;
  623. d.stencilEnable = true;
  624. d.stencilRef = RenderParticleMgr::HighResStencilRef;
  625. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  626. d.stencilPassOp = GFXStencilOpKeep;
  627. d.stencilFailOp = GFXStencilOpKeep;
  628. d.stencilZFailOp = GFXStencilOpKeep;
  629. d.stencilFunc = GFXCmpNotEqual;
  630. d.samplersDefined = true;
  631. // Diffuse texture sampler
  632. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  633. d.samplers[0].alphaOp = GFXTOPModulate;
  634. d.samplers[0].alphaArg1 = GFXTATexture;
  635. d.samplers[0].alphaArg2 = GFXTADiffuse;
  636. // Prepass sampler
  637. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  638. mMixedResBlocks[blendStyle] = GFX->createStateBlock(d);
  639. return mMixedResBlocks[blendStyle];
  640. }
  641. GFXStateBlockRef RenderParticleMgr::_getCompositeStateBlock(ParticleRenderInst *ri)
  642. {
  643. const U8 blendStyle = ri->blendStyle;
  644. if ( mBackbufferBlocks[blendStyle].isValid() )
  645. return mBackbufferBlocks[blendStyle];
  646. GFXStateBlockDesc d;
  647. // This is a billboard
  648. d.setCullMode(GFXCullNone);
  649. d.setZReadWrite(false, false);
  650. // When we re-composite the particles, it is always either a pre-mult alpha
  651. // blend, or a subtractive blend!
  652. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  653. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  654. else
  655. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  656. // All areas which are not along the edges of geometry where the particle system
  657. // is being drawn get assigned a stencil ref value as the system is composited
  658. // back into the scene. The high-res stateblock uses this value as a mask, and
  659. // draws only in areas which are NOT this ref value. This causes high resolution
  660. // draws to ONLY the edge areas.
  661. d.stencilDefined = true;
  662. d.stencilEnable = true;
  663. d.stencilRef = RenderParticleMgr::HighResStencilRef;
  664. d.stencilWriteMask = RenderParticleMgr::ParticleSystemStencilMask;
  665. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  666. d.stencilPassOp = GFXStencilOpReplace;
  667. d.stencilFunc = GFXCmpGreater;
  668. // Diffuse texture sampler and
  669. d.samplersDefined = true;
  670. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  671. d.samplers[1] = GFXSamplerStateDesc::getClampLinear();
  672. mBackbufferBlocks[blendStyle] = GFX->createStateBlock(d);
  673. return mBackbufferBlocks[blendStyle];
  674. }
  675. bool RenderParticleMgr::_handleGFXEvent( GFXDevice::GFXDeviceEventType event )
  676. {
  677. if(RenderToSingleTarget)
  678. return Parent::_handleGFXEvent( event );
  679. // Do nothing. This render manager uses its target chain as a pool of targets.
  680. return true;
  681. }