gBufferConditionerHLSL.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 "lighting/advanced/hlsl/gBufferConditionerHLSL.h"
  24. #include "shaderGen/featureMgr.h"
  25. #include "gfx/gfxStringEnumTranslate.h"
  26. #include "materials/materialFeatureTypes.h"
  27. #include "materials/materialFeatureData.h"
  28. #include "shaderGen/hlsl/shaderFeatureHLSL.h"
  29. #include "gfx/gfxDevice.h"
  30. GBufferConditionerHLSL::GBufferConditionerHLSL( const GFXFormat bufferFormat, const NormalSpace nrmSpace ) :
  31. Parent( bufferFormat )
  32. {
  33. // Figure out how we should store the normal data. These are the defaults.
  34. mCanWriteNegativeValues = false;
  35. mNormalStorageType = CartesianXYZ;
  36. // Note: We clear to a depth 1 (the w component) so
  37. // that the unrendered parts of the scene end up
  38. // farthest to the camera.
  39. const NormalStorage &twoCmpNrmStorageType = ( nrmSpace == WorldSpace ? Spherical : LambertAzimuthal );
  40. switch(bufferFormat)
  41. {
  42. case GFXFormatR8G8B8A8:
  43. mNormalStorageType = twoCmpNrmStorageType;
  44. mBitsPerChannel = 8;
  45. break;
  46. case GFXFormatR16G16B16A16F:
  47. // Floating point buffers don't need to encode negative values
  48. mCanWriteNegativeValues = true;
  49. mNormalStorageType = twoCmpNrmStorageType;
  50. mBitsPerChannel = 16;
  51. break;
  52. // Store a 32bit depth with a sperical normal in the
  53. // integer 16 format. This gives us perfect depth
  54. // precision and high quality normals within a 64bit
  55. // buffer format.
  56. case GFXFormatR16G16B16A16:
  57. mNormalStorageType = twoCmpNrmStorageType;
  58. mBitsPerChannel = 16;
  59. break;
  60. case GFXFormatR32G32B32A32F:
  61. mCanWriteNegativeValues = true;
  62. mNormalStorageType = CartesianXYZ;
  63. mBitsPerChannel = 32;
  64. break;
  65. default:
  66. AssertFatal(false, "Unsupported G-Buffer format");
  67. }
  68. }
  69. GBufferConditionerHLSL::~GBufferConditionerHLSL()
  70. {
  71. }
  72. void GBufferConditionerHLSL::processVert( Vector<ShaderComponent*> &componentList,
  73. const MaterialFeatureData &fd )
  74. {
  75. // If we have a normal map then that feature will
  76. // take care of passing gbNormal to the pixel shader.
  77. if ( fd.features[MFT_NormalMap] )
  78. return;
  79. MultiLine *meta = new MultiLine;
  80. output = meta;
  81. // grab incoming vert normal
  82. Var *inNormal = (Var*) LangElement::find( "normal" );
  83. if (!inNormal)
  84. {
  85. inNormal = new Var("normal", "float3");
  86. meta->addStatement(new GenOp(" @ = float3( 0.0, 0.0, 1.0 );\r\n", new DecOp(inNormal)));
  87. Con::errorf("ShagerGen: Something went bad with ShaderGen. The normal should be already defined.");
  88. }
  89. AssertFatal( inNormal, "Something went bad with ShaderGen. The normal should be already defined." );
  90. // grab output for gbuffer normal
  91. ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
  92. Var *outNormal = connectComp->getElement( RT_TEXCOORD );
  93. outNormal->setName( "gbNormal" );
  94. outNormal->setStructName( "OUT" );
  95. outNormal->setType( "float3" );
  96. if( !fd.features[MFT_ParticleNormal] )
  97. {
  98. // Kick out the view-space normal
  99. // TODO: Total hack because Conditioner is directly derived
  100. // from ShaderFeature and not from ShaderFeatureHLSL.
  101. NamedFeatureHLSL dummy( String::EmptyString );
  102. dummy.setInstancingFormat( mInstancingFormat );
  103. Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta );
  104. meta->addStatement( new GenOp(" @ = mul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n",
  105. outNormal, worldViewOnly, inNormal ) );
  106. }
  107. else
  108. {
  109. // Assume the particle normal generator has already put this in view space
  110. // and normalized it
  111. meta->addStatement( new GenOp( " @ = @;\r\n", outNormal, inNormal ) );
  112. }
  113. }
  114. void GBufferConditionerHLSL::processPix( Vector<ShaderComponent*> &componentList,
  115. const MaterialFeatureData &fd )
  116. {
  117. // sanity
  118. AssertFatal( fd.features[MFT_EyeSpaceDepthOut], "No depth-out feature enabled! Bad news!" );
  119. MultiLine *meta = new MultiLine;
  120. // grab connector normal
  121. ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
  122. Var *gbNormal = (Var*) LangElement::find( "gbNormal" );
  123. if( !gbNormal )
  124. {
  125. gbNormal = connectComp->getElement( RT_TEXCOORD );
  126. gbNormal->setName( "gbNormal" );
  127. gbNormal->setStructName( "IN" );
  128. gbNormal->setType( "float3" );
  129. gbNormal->uniform = false;
  130. }
  131. // find depth
  132. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  133. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  134. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  135. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  136. Var *unconditionedOut = new Var;
  137. unconditionedOut->setType("float4");
  138. unconditionedOut->setName("normal_depth");
  139. LangElement *outputDecl = new DecOp( unconditionedOut );
  140. // If we're doing deferred blending then we need
  141. // to steal away the alpha channel before the
  142. // conditioner stomps on it.
  143. Var *alphaVal = NULL;
  144. Var* targ = (Var*)LangElement::find(getOutputTargetVarName(DefaultTarget));
  145. if (fd.features[MFT_isDeferred])
  146. targ = (Var*)LangElement::find(getOutputTargetVarName(RenderTarget1));
  147. if ( fd.features[ MFT_IsTranslucentZWrite ] )
  148. {
  149. alphaVal = new Var( "outAlpha", "float" );
  150. meta->addStatement( new GenOp( " @ = @.a; // MFT_IsTranslucentZWrite\r\n", new DecOp( alphaVal ), targ) );
  151. }
  152. // NOTE: We renormalize the normal here as they
  153. // will not stay normalized during interpolation.
  154. meta->addStatement( new GenOp(" @ = @;", outputDecl, new GenOp( "float4(normalize(@), @)", gbNormal, depth ) ) );
  155. meta->addStatement( assignOutput( unconditionedOut ) );
  156. // If we have an alpha var then we're doing deferred lerp blending.
  157. if ( alphaVal )
  158. {
  159. meta->addStatement( new GenOp( " @.ba = float2( 0, @ ); // MFT_IsTranslucentZWrite\r\n", targ, alphaVal ) );
  160. }
  161. output = meta;
  162. }
  163. ShaderFeature::Resources GBufferConditionerHLSL::getResources( const MaterialFeatureData &fd )
  164. {
  165. Resources res;
  166. // Passing from VS->PS:
  167. // - world space normal (gbNormal)
  168. res.numTexReg = 1;
  169. return res;
  170. }
  171. Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  172. {
  173. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  174. Var *retVal = NULL;
  175. // The uncondition method inputs are changed
  176. if( isCondition )
  177. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  178. else
  179. {
  180. Var *methodVar = new Var;
  181. methodVar->setName(methodName);
  182. methodVar->setType("inline float4");
  183. DecOp *methodDecl = new DecOp(methodVar);
  184. Var *deferredSampler = new Var;
  185. deferredSampler->setName("deferredSamplerVar");
  186. deferredSampler->setType("SamplerState");
  187. DecOp *deferredSamplerDecl = new DecOp(deferredSampler);
  188. Var *screenUV = new Var;
  189. screenUV->setName("screenUVVar");
  190. screenUV->setType("float2");
  191. DecOp *screenUVDecl = new DecOp(screenUV);
  192. DecOp *deferredTexDecl = NULL;
  193. Var *deferredTex = new Var;
  194. deferredTex->setName("deferredTexVar");
  195. deferredTex->setType("Texture2D");
  196. deferredTex->texture = true;
  197. deferredTex->constNum = deferredSampler->constNum;
  198. deferredTexDecl = new DecOp(deferredTex);
  199. Var *bufferSample = new Var;
  200. bufferSample->setName("bufferSample");
  201. bufferSample->setType("float4");
  202. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  203. meta->addStatement(new GenOp("@(@, @, @)\r\n", methodDecl, deferredSamplerDecl, deferredTexDecl, screenUVDecl));
  204. meta->addStatement( new GenOp( "{\r\n" ) );
  205. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  206. // The gbuffer has no mipmaps, so use tex2dlod when
  207. // possible so that the shader compiler can optimize.
  208. meta->addStatement(new GenOp(" @ = @.SampleLevel(@, @,0);\r\n", bufferSampleDecl, deferredTex, deferredSampler, screenUV));
  209. // We don't use this way of passing var's around, so this should cause a crash
  210. // if something uses this improperly
  211. retVal = bufferSample;
  212. }
  213. return retVal;
  214. }
  215. GenOp* GBufferConditionerHLSL::_posnegEncode( GenOp *val )
  216. {
  217. if(mNormalStorageType == LambertAzimuthal)
  218. return mCanWriteNegativeValues ? val : new GenOp(avar("(%f * (@ + %f))", 1.0f/(M_SQRT2_F * 2.0f), M_SQRT2_F), val);
  219. else
  220. return mCanWriteNegativeValues ? val : new GenOp("(0.5 * (@ + 1.0))", val);
  221. }
  222. GenOp* GBufferConditionerHLSL::_posnegDecode( GenOp *val )
  223. {
  224. if(mNormalStorageType == LambertAzimuthal)
  225. return mCanWriteNegativeValues ? val : new GenOp(avar("(@ * %f - %f)", M_SQRT2_F * 2.0f, M_SQRT2_F), val);
  226. else
  227. return mCanWriteNegativeValues ? val : new GenOp("(@ * 2.0 - 1.0)", val);
  228. }
  229. Var* GBufferConditionerHLSL::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  230. {
  231. Var *retVar = new Var;
  232. retVar->setType("float4");
  233. retVar->setName("_gbConditionedOutput");
  234. LangElement *outputDecl = new DecOp( retVar );
  235. switch(mNormalStorageType)
  236. {
  237. case CartesianXYZ:
  238. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xyz, depth)\r\n" ) );
  239. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  240. _posnegEncode(new GenOp("@.xyz", unconditionedOutput)), unconditionedOutput ) );
  241. break;
  242. case CartesianXY:
  243. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) );
  244. meta->addStatement( new GenOp( " @ = float4(@, @.a);", outputDecl,
  245. _posnegEncode(new GenOp("float3(@.xy, sign(@.z))", unconditionedOutput, unconditionedOutput)), unconditionedOutput ) );
  246. break;
  247. case Spherical:
  248. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) );
  249. meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl,
  250. _posnegEncode(new GenOp("float2(atan2(@.y, @.x) / 3.14159265358979323846f, @.z)", unconditionedOutput, unconditionedOutput, unconditionedOutput ) ),
  251. unconditionedOutput ) );
  252. // HACK: This fixes the noise present when using a floating point
  253. // gbuffer on Geforce cards and the "flat areas unlit" issues.
  254. //
  255. // We need work around atan2() above to fix this issue correctly
  256. // without the extra overhead of this test.
  257. //
  258. meta->addStatement( new GenOp( " if ( abs( dot( @.xyz, float3( 0.0, 0.0, 1.0 ) ) ) > 0.999f ) @ = float4( 0, 1 * sign( @.z ), 0, @.a );\r\n",
  259. unconditionedOutput, retVar, unconditionedOutput, unconditionedOutput ) );
  260. break;
  261. case LambertAzimuthal:
  262. //http://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection
  263. //
  264. // Note we're casting to half to use partial precision
  265. // sqrt which is much faster on older Geforces while
  266. // still being acceptable for normals.
  267. //
  268. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) );
  269. meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl,
  270. _posnegEncode(new GenOp("sqrt(half(2.0/(1.0 - @.y))) * half2(@.xz)", unconditionedOutput, unconditionedOutput)),
  271. unconditionedOutput ) );
  272. break;
  273. }
  274. // Encode depth into two channels
  275. if(mNormalStorageType != CartesianXYZ)
  276. {
  277. const U64 maxValPerChannel = (U64)1 << mBitsPerChannel;
  278. meta->addStatement( new GenOp( " \r\n // Encode depth into hi/lo\r\n" ) );
  279. meta->addStatement( new GenOp( avar( " float2 _tempDepth = frac(@.a * float2(1.0, %llu.0));\r\n", maxValPerChannel - 1 ),
  280. unconditionedOutput ) );
  281. meta->addStatement( new GenOp( avar( " @.zw = _tempDepth.xy - _tempDepth.yy * float2(1.0/%llu.0, 0.0);\r\n\r\n", maxValPerChannel - 1 ),
  282. retVar ) );
  283. }
  284. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  285. return retVar;
  286. }
  287. Var* GBufferConditionerHLSL::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  288. {
  289. Var *retVar = new Var;
  290. retVar->setType("float4");
  291. retVar->setName("_gbUnconditionedInput");
  292. LangElement *outputDecl = new DecOp( retVar );
  293. switch(mNormalStorageType)
  294. {
  295. case CartesianXYZ:
  296. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xyz, depth)\r\n" ) );
  297. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  298. _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) );
  299. break;
  300. case CartesianXY:
  301. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) );
  302. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  303. _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) );
  304. meta->addStatement( new GenOp( " @.z *= sqrt(1.0 - dot(@.xy, @.xy));\r\n", retVar, retVar, retVar ) );
  305. break;
  306. case Spherical:
  307. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) );
  308. meta->addStatement( new GenOp( " float2 spGPUAngles = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) );
  309. meta->addStatement( new GenOp( " float2 sincosTheta;\r\n" ) );
  310. meta->addStatement( new GenOp( " sincos(spGPUAngles.x * 3.14159265358979323846f, sincosTheta.x, sincosTheta.y);\r\n" ) );
  311. meta->addStatement( new GenOp( " float2 sincosPhi = float2(sqrt(1.0 - spGPUAngles.y * spGPUAngles.y), spGPUAngles.y);\r\n" ) );
  312. meta->addStatement( new GenOp( " @ = float4(sincosTheta.y * sincosPhi.x, sincosTheta.x * sincosPhi.x, sincosPhi.y, @.a);\r\n", outputDecl, conditionedInput ) );
  313. break;
  314. case LambertAzimuthal:
  315. // Note we're casting to half to use partial precision
  316. // sqrt which is much faster on older Geforces while
  317. // still being acceptable for normals.
  318. //
  319. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) );
  320. meta->addStatement( new GenOp( " float2 _inpXY = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) );
  321. meta->addStatement( new GenOp( " float _xySQ = dot(_inpXY, _inpXY);\r\n" ) );
  322. meta->addStatement( new GenOp( " @ = float4( sqrt(half(1.0 - (_xySQ / 4.0))) * _inpXY, -1.0 + (_xySQ / 2.0), @.a).xzyw;\r\n", outputDecl, conditionedInput ) );
  323. break;
  324. }
  325. // Recover depth from encoding
  326. if(mNormalStorageType != CartesianXYZ)
  327. {
  328. const U64 maxValPerChannel = (U64)1 << mBitsPerChannel;
  329. meta->addStatement( new GenOp( " \r\n // Decode depth\r\n" ) );
  330. meta->addStatement( new GenOp( avar( " @.w = dot( @.zw, float2(1.0, 1.0/%llu.0));\r\n", maxValPerChannel - 1 ),
  331. retVar, conditionedInput ) );
  332. }
  333. AssertFatal( retVar != NULL, avar( "Cannot uncondition input from buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  334. return retVar;
  335. }