gBufferConditionerGLSL.cpp 16 KB

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