浏览代码

Merge remote-tracking branch 'origin/master' into scriptablerenderloop-materialgraph

/scriptablerenderloop-materialgraph
Paul Demeulenaere 8 年前
当前提交
d6e910a1
共有 60 个文件被更改,包括 3992 次插入1265 次删除
  1. 14
      Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.cs
  2. 3
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Debug/DebugViewMaterialGBuffer.shader
  3. 3
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Lighting/Deferred.shader
  4. 4
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Lighting/SinglePass/SinglePass.hlsl
  5. 34
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/LayeredLit/LayeredLitCommon.hlsl
  6. 69
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/Lit.hlsl
  7. 118
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/LitData.hlsl
  8. 67
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/LitDefault.shader
  9. 48
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/LitUI.cs
  10. 53
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Material.hlsl
  11. 6
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Unlit/UnlitData.hlsl
  12. 8
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Unlit/UnlitDefault.shader
  13. 6
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/PostProcess/FinalPass.shader
  14. 2
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/ShaderPass/ShaderPassGBuffer.hlsl
  15. 39
      Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/ShaderVariables.hlsl
  16. 66
      Assets/ScriptableRenderLoop/ShaderLibrary/API/D3D11.hlsl
  17. 24
      Assets/ScriptableRenderLoop/ShaderLibrary/BSDF.hlsl
  18. 22
      Assets/ScriptableRenderLoop/ShaderLibrary/Filtering.hlsl
  19. 6
      Assets/ScriptableRenderLoop/ShaderLibrary/ImageBasedLighting.hlsl
  20. 2
      Assets/ScriptableRenderLoop/common/ShaderBase.h
  21. 41
      Assets/ScriptableRenderLoop/common/TextureCache.cs
  22. 4
      Assets/ScriptableRenderLoop/fptl/ClusteredUtils.h
  23. 1001
      Assets/ScriptableRenderLoop/fptl/FptlLighting.cs
  24. 5
      Assets/ScriptableRenderLoop/fptl/LightBoundsDebug.shader
  25. 3
      Assets/ScriptableRenderLoop/fptl/LightDefinitions.cs
  26. 4
      Assets/ScriptableRenderLoop/fptl/LightDefinitions.cs.hlsl
  27. 4
      Assets/ScriptableRenderLoop/fptl/LightingConvexHullUtils.hlsl
  28. 4
      Assets/ScriptableRenderLoop/fptl/LightingUtils.hlsl
  29. 8
      Assets/ScriptableRenderLoop/fptl/lightlistbuild-bigtile.compute
  30. 14
      Assets/ScriptableRenderLoop/fptl/lightlistbuild-clustered.compute
  31. 4
      Assets/ScriptableRenderLoop/fptl/lightlistbuild.compute
  32. 6
      Assets/ScriptableRenderLoop/fptl/scrbound.compute
  33. 9
      Assets/BasicRenderLoopTutorial.meta
  34. 112
      Assets/ScriptableRenderLoop/ShaderLibrary/EntityLighting.hlsl
  35. 9
      Assets/ScriptableRenderLoop/ShaderLibrary/EntityLighting.hlsl.meta
  36. 73
      Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/anisoTest.mat
  37. 8
      Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/anisoTest.mat.meta
  38. 73
      Assets/BasicRenderLoopTutorial/BasicMat_Colors.mat
  39. 8
      Assets/BasicRenderLoopTutorial/BasicMat_Colors.mat.meta
  40. 74
      Assets/BasicRenderLoopTutorial/BasicMat_Glass.mat
  41. 8
      Assets/BasicRenderLoopTutorial/BasicMat_Glass.mat.meta
  42. 73
      Assets/BasicRenderLoopTutorial/BasicMat_Tiles.mat
  43. 8
      Assets/BasicRenderLoopTutorial/BasicMat_Tiles.mat.meta
  44. 12
      Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs.meta
  45. 1001
      Assets/BasicRenderLoopTutorial/BasicRenderLoopScene.unity
  46. 8
      Assets/BasicRenderLoopTutorial/BasicRenderLoopScene.unity.meta
  47. 227
      Assets/BasicRenderLoopTutorial/BasicRenderLoopShader.shader
  48. 9
      Assets/BasicRenderLoopTutorial/BasicRenderLoopShader.shader.meta
  49. 9
      Assets/BasicRenderLoopTutorial/Textures.meta
  50. 14
      Assets/BasicRenderLoopTutorial/Textures/ColorGrid.png
  51. 31
      Assets/BasicRenderLoopTutorial/Textures/ColorGrid.png.meta
  52. 969
      Assets/BasicRenderLoopTutorial/Textures/Glass.tif
  53. 56
      Assets/BasicRenderLoopTutorial/Textures/Glass.tif.meta
  54. 338
      Assets/BasicRenderLoopTutorial/Textures/TilesDiffuse.tif
  55. 56
      Assets/BasicRenderLoopTutorial/Textures/TilesDiffuse.tif.meta
  56. 102
      Assets/BasicRenderLoopTutorial/Textures/TilesNormal.png
  57. 100
      Assets/BasicRenderLoopTutorial/Textures/TilesNormal.png.meta
  58. 178
      Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs

14
Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.cs


DrawRendererSettings settings = new DrawRendererSettings(cull, camera, new ShaderPassName(passName));
settings.sorting.sortOptions = SortOptions.SortByMaterialThenMesh;
settings.inputCullingOptions.SetQueuesOpaque();
settings.inputFilter.SetQueuesOpaque();
renderLoop.DrawRenderers(ref settings);
}

rendererConfiguration = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectReflectionProbes,
sorting = { sortOptions = SortOptions.SortByMaterialThenMesh }
};
settings.inputCullingOptions.SetQueuesTransparent();
settings.inputFilter.SetQueuesTransparent();
renderLoop.DrawRenderers(ref settings);
}

RenderOpaqueRenderList(cullResults, camera, renderLoop, "ForwardUnlit");
RenderTransparentRenderList(cullResults, camera, renderLoop, "ForwardUnlit");
}
}
void FinalPass(RenderLoop renderLoop)
{

if (light.lightType == LightType.Spot)
{
var spotAngle = light.light.spotAngle;
var spotAngle = light.spotAngle;
var innerConePercent = AdditionalLightData.GetInnerSpotPercent01(additionalLightData);
var cosSpotOuterHalfAngle = Mathf.Clamp(Mathf.Cos(spotAngle * 0.5f * Mathf.Deg2Rad), 0.0f, 1.0f);
var cosSpotInnerHalfAngle = Mathf.Clamp(Mathf.Cos(spotAngle * 0.5f * innerConePercent * Mathf.Deg2Rad), 0.0f, 1.0f); // inner cone

s.bias = light.light.shadowBias;
shadows.Add(s);
shadows.Add(s);
}
}

Shader.SetGlobalBuffer("_PunctualLightList", s_punctualLightList);
Shader.SetGlobalInt("_PunctualLightCount", lights.Count);
Shader.SetGlobalBuffer("_PunctualShadowList", s_punctualShadowList);
Shader.SetGlobalBuffer("_PunctualShadowList", s_punctualShadowList);
}
void UpdateReflectionProbes(VisibleReflectionProbe[] activeReflectionProbes)

3
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Debug/DebugViewMaterialGBuffer.shader


DECLARE_GBUFFER_TEXTURE(_CameraGBufferTexture);
DECLARE_GBUFFER_BAKE_LIGHTING(_CameraGBufferTexture);
UNITY_DECLARE_TEX2D(_CameraDepthTexture);
TEXTURE2D(_CameraDepthTexture);
SAMPLER2D(sampler_CameraDepthTexture);
int _DebugViewMaterial;
struct Attributes

3
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Lighting/Deferred.shader


DECLARE_GBUFFER_TEXTURE(_CameraGBufferTexture);
DECLARE_GBUFFER_BAKE_LIGHTING(_CameraGBufferTexture);
UNITY_DECLARE_TEX2D(_CameraDepthTexture);
TEXTURE2D(_CameraDepthTexture);
SAMPLER2D(sampler_CameraDepthTexture);
float4x4 _InvViewProjMatrix;

4
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Lighting/SinglePass/SinglePass.hlsl


// This code will be inlined as lightLoopContext is hardcoded in the light loop
if (lightLoopContext.sampleReflection == SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES)
{
return UNITY_SAMPLE_TEXCUBEARRAY_LOD(_EnvTextures, float4(texCoord, index), lod);
return SAMPLE_TEXTURECUBE_ARRAY_LOD(_EnvTextures, sampler_EnvTextures, float4(texCoord, index), lod);
return UNITY_SAMPLE_TEXCUBE_LOD(_SkyTexture, texCoord, lod);
return SAMPLE_TEXTURECUBE_LOD(_SkyTexture, sampler_SkyTexture, texCoord, lod);
}
}

34
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/LayeredLit/LayeredLitCommon.hlsl


#define PROP_DECL(type, name) type name, name##0, name##1, name##2, name##3;
#define PROP_DECL_TEX2D(name)\
UNITY_DECLARE_TEX2D(name##0);\
UNITY_DECLARE_TEX2D_NOSAMPLER(name##1);\
UNITY_DECLARE_TEX2D_NOSAMPLER(name##2);\
UNITY_DECLARE_TEX2D_NOSAMPLER(name##3);
TEXTURE2D(name##0);\
SAMPLER2D(sampler##name##0); \
TEXTURE2D(name##1);\
TEXTURE2D(name##2);\
TEXTURE2D(name##3);
name##0 = UNITY_SAMPLE_TEX2D_SAMPLER(textureName##0, textureName##0, texcoord).##swizzle; \
name##1 = UNITY_SAMPLE_TEX2D_SAMPLER(textureName##1, textureName##0, texcoord).##swizzle; \
name##2 = UNITY_SAMPLE_TEX2D_SAMPLER(textureName##2, textureName##0, texcoord).##swizzle; \
name##3 = UNITY_SAMPLE_TEX2D_SAMPLER(textureName##3, textureName##0, texcoord).##swizzle;
name##0 = SAMPLE_TEXTURE2D(textureName##0, sampler##textureName##0, texcoord).##swizzle; \
name##1 = SAMPLE_TEXTURE2D(textureName##1, sampler##textureName##0, texcoord).##swizzle; \
name##2 = SAMPLE_TEXTURE2D(textureName##2, sampler##textureName##0, texcoord).##swizzle; \
name##3 = SAMPLE_TEXTURE2D(textureName##3, sampler##textureName##0, texcoord).##swizzle;
#define PROP_MUL(name, multiplier, swizzle)\
name##0 *= multiplier##0.##swizzle; \
name##1 *= multiplier##1.##swizzle; \

PROP_DECL(float, _EmissiveIntensity);
float _AlphaCutoff;
UNITY_DECLARE_TEX2D(_LayerMaskMap);
TEXTURE2D(_LayerMaskMap);
SAMPLER2D(sampler_LayerMaskMap);
//-------------------------------------------------------------------------------------
// Lighting architecture

float4 maskValues = float4(1.0, 1.0, 1.0, 1.0);// input.vertexColor;
#ifdef _LAYERMASKMAP
float4 maskMap = UNITY_SAMPLE_TEX2D(_LayerMaskMap, input.texCoord0);
float4 maskMap = SAMPLE_TEXTURE2D(_LayerMaskMap, sampler_LayerMaskMap, input.texCoord0);
maskValues *= maskMap;
#endif

#ifdef _NORMALMAP
#ifdef _NORMALMAP_TANGENT_SPACE
float3 normalTS0 = UnpackNormalAG(UNITY_SAMPLE_TEX2D_SAMPLER(_NormalMap0, _NormalMap0, input.texCoord0));
float3 normalTS1 = UnpackNormalAG(UNITY_SAMPLE_TEX2D_SAMPLER(_NormalMap1, _NormalMap0, input.texCoord0));
float3 normalTS2 = UnpackNormalAG(UNITY_SAMPLE_TEX2D_SAMPLER(_NormalMap2, _NormalMap0, input.texCoord0));
float3 normalTS3 = UnpackNormalAG(UNITY_SAMPLE_TEX2D_SAMPLER(_NormalMap3, _NormalMap0, input.texCoord0));
float3 normalTS0 = UnpackNormalAG(SAMPLE_TEXTURE2D(_NormalMap0, sampler_NormalMap0, input.texCoord0));
float3 normalTS1 = UnpackNormalAG(SAMPLE_TEXTURE2D(_NormalMap1, sampler_NormalMap0, input.texCoord0));
float3 normalTS2 = UnpackNormalAG(SAMPLE_TEXTURE2D(_NormalMap2, sampler_NormalMap0, input.texCoord0));
float3 normalTS3 = UnpackNormalAG(SAMPLE_TEXTURE2D(_NormalMap3, sampler_NormalMap0, input.texCoord0));
surfaceData.normalWS = UNITY_SAMPLE_TEX2D(_NormalMap, input.texCoord0).rgb;
surfaceData.normalWS = SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, input.texCoord0).rgb;
#endif
#else
surfaceData.normalWS = vertexNormalWS;

// TODO: Sample lightmap/lightprobe/volume proxy
// This should also handle projective lightmap
// Note that data input above can be use to sample into lightmap (like normal)
builtinData.bakeDiffuseLighting = float3(0.0, 0.0, 0.0);// tex2D(_DiffuseLightingMap, input.texCoord0).rgb;
builtinData.bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
// If we chose an emissive color, we have a dedicated texture for it and don't use MaskMap
PROP_DECL(float3, emissiveColor);

69
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/Lit.hlsl


// TODO: How can I declare a sampler for this one that is bilinear filtering
// TODO: This one should be set into a constant Buffer at pass frequency (with _Screensize)
UNITY_DECLARE_TEX2D(_PreIntegratedFGD);
UNITY_DECLARE_TEX2D(_LtcGGXMatrix);
UNITY_DECLARE_TEX2D(_LtcGGXMagnitude);
TEXTURE2D(_PreIntegratedFGD);
SAMPLER2D(sampler_PreIntegratedFGD);
TEXTURE2D(_LtcGGXMatrix);
SAMPLER2D(sampler_LtcGGXMatrix);
TEXTURE2D(_LtcGGXMagnitude);
SAMPLER2D(sampler_LtcGGXMagnitude);
// For image based lighting, a part of the BSDF is pre-integrated.
// This is done both for specular and diffuse (in case of DisneyDiffuse)

// _PreIntegratedFGD.y = Gv * Fc
// Pre integrate DisneyDiffuse FGD:
// _PreIntegratedFGD.z = DisneyDiffuse
float3 preFGD = UNITY_SAMPLE_TEX2D_LOD(_PreIntegratedFGD, float2(NdotV, perceptualRoughness), 0).xyz;
float3 preFGD = SAMPLE_TEXTURE2D_LOD(_PreIntegratedFGD, sampler_PreIntegratedFGD, float2(NdotV, perceptualRoughness), 0).xyz;
#if DIFFUSE_LAMBERT_BRDF
#ifdef DIFFUSE_LAMBERT_BRDF
diffuseFGD = 1.0;
#else
diffuseFGD = preFGD.z;

bsdfData.fresnel0 = lerp(float3(specular, specular, specular), baseColor, metallic);
bsdfData.tangentWS = UnpackNormalOctEncode(float2(inGBuffer2.rg * 2.0 - 1.0));
// TODO: Do we need to orthonormalize here, IIRC Eric say that we should
bsdfData.bitangentWS = cross(bsdfData.normalWS, bsdfData.tangentWS);
ConvertAnisotropyToRoughness(bsdfData.roughness, anisotropy, bsdfData.roughnessT, bsdfData.roughnessB);
bsdfData.anisotropy = anisotropy;

// Note we load the matrix transpose (avoid to have to transpose it in shader)
preLightData.minV = 0.0;
preLightData.minV._m22 = 1.0;
preLightData.minV._m00_m02_m11_m20 = UNITY_SAMPLE_TEX2D_LOD(_LtcGGXMatrix, uv, 0);
preLightData.minV._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_LOD(_LtcGGXMatrix, sampler_LtcGGXMatrix, uv, 0);
preLightData.ltcGGXMagnitude = UNITY_SAMPLE_TEX2D_LOD(_LtcGGXMagnitude, uv, 0).w;
preLightData.ltcGGXMagnitude = SAMPLE_TEXTURE2D_LOD(_LtcGGXMagnitude, sampler_LtcGGXMagnitude, uv, 0).w;
// Shadow
preLightData.unPositionSS = coord.unPositionSS;

#ifdef USE_BSDF_PRE_LAMBDAV
Vis = V_SmithJointGGXAnisoLambdaV( preLightData.TdotV, preLightData.BdotV, preLightData.NdotV, TdotL, BdotL, NdotL,
bsdfData.roughnessT, bsdfData.roughnessB, preLightData.anisoGGXlambdaV);
bsdfData.roughnessT, bsdfData.roughnessB, preLightData.anisoGGXLambdaV);
// TODO: Do comparison between this correct version and the one from isotropic and see if there is any visual difference
float TdotH = saturate(dot(bsdfData.tangentWS, H));
float BdotH = saturate(dot(bsdfData.bitangentWS, H));
D = D_GGXAnisoDividePI(TdotH, BdotH, NdotH, bsdfData.roughnessT, bsdfData.roughnessB);
// For anisotropy we must not saturate these values
float TdotH = dot(bsdfData.tangentWS, H);
float BdotH = dot(bsdfData.bitangentWS, H);
D = D_GGXAniso(TdotH, BdotH, NdotH, bsdfData.roughnessT, bsdfData.roughnessB);
}
else
{

Vis = V_SmithJointGGX(NdotL, preLightData.NdotV, bsdfData.roughness);
#endif
D = D_GGXDividePI(NdotH, bsdfData.roughness);
D = D_GGX(NdotH, bsdfData.roughness);
float diffuseTerm = LambertDividePI();
float diffuseTerm = Lambert();
float diffuseTerm = DisneyDiffuseDividePI(preLightData.NdotV, NdotL, LdotH, bsdfData.perceptualRoughness);
float diffuseTerm = DisneyDiffuse(preLightData.NdotV, NdotL, LdotH, bsdfData.perceptualRoughness);
#endif
diffuseLighting.rgb = bsdfData.diffuseColor * diffuseTerm;
}

diffuseLighting = float4(0.0, 0.0, 0.0, 1.0);
specularLighting = float4(0.0, 0.0, 0.0, 1.0);
// TODO: measure impact of having all these dynamic branch here and the gain (or not) of testing illuminace > 0
// TODO: measure impact of having all these dynamic branch here and the gain (or not) of testing illuminace > 0
[branch] if (lightData.cookieIndex && illuminance > 0.0f)
{
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
illuminance *= SampleCookie(lightData.cookieIndex, lightToWorld, L);
}
[branch] if (lightData.cookieIndex && illuminance > 0.0f)
{
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
illuminance *= SampleCookie(lightData.cookieIndex, lightToWorld, L);
}
[branch] if (lightData.IESIndex >= 0 && illuminance > 0.0f)
{
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
[branch] if (lightData.IESIndex >= 0 && illuminance > 0.0f)
{
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, lightData.forward);
}
}
[branch] if (lightData.shadowIndex >= 0 && illuminance > 0.0f)
{
float3 offset = float3(0.0, 0.0, 0.0); // GetShadowPosOffset(nDotL, normal);
[branch] if (lightData.shadowIndex >= 0 && illuminance > 0.0f)
{
float3 offset = float3(0.0, 0.0, 0.0); // GetShadowPosOffset(nDotL, normal);
shadowAttenuation = lerp(1.0, shadowAttenuation, lightData.shadowDimmer);
shadowAttenuation = lerp(1.0, shadowAttenuation, lightData.shadowDimmer);
illuminance *= shadowAttenuation;
}
illuminance *= shadowAttenuation;
}
[branch] if (illuminance > 0.0f)
{

float4 val = SampleEnv(lightLoopContext, lightData.envIndex, L, 0);
// diffuse Albedo is apply here as describe in ImportanceSampleLambert function
acc += bsdfData.diffuseColor * Lambert() * weightOverPdf * val.rgb;
acc += bsdfData.diffuseColor * LambertNoPI() * weightOverPdf * val.rgb;
}
}

118
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/LitData.hlsl


// Fill SurfaceData/Builtin data function
//-------------------------------------------------------------------------------------
// In unity we can have a mix of fully baked lightmap (static lightmap) + enlighten realtime lightmap (dynamic lightmap)
// for each case we can have directional lightmap or not.
// Else we have lightprobe for dynamic/moving entity. Either SH9 per object lightprobe or SH4 per pixel per object volume probe
float3 SampleBakedGI(float3 positionWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
{
// If there is no lightmap, it assume lightprobe
#if !defined(LIGHTMAP_ON) && !defined(DYNAMICLIGHTMAP_ON)
// TODO: Confirm with Ionut but it seems that UNITY_LIGHT_PROBE_PROXY_VOLUME is always define for high end and
// unity_ProbeVolumeParams always bind.
if (unity_ProbeVolumeParams.x == 0.0)
{
// TODO: pass a tab of coefficient instead!
float4 SHCoefficients[7];
SHCoefficients[0] = unity_SHAr;
SHCoefficients[1] = unity_SHAg;
SHCoefficients[2] = unity_SHAb;
SHCoefficients[3] = unity_SHBr;
SHCoefficients[4] = unity_SHBg;
SHCoefficients[5] = unity_SHBb;
SHCoefficients[6] = unity_SHC;
return SampleSH9(SHCoefficients, normalWS);
}
else
{
// TODO: Move all this to C++!
float4x4 identity = 0;
identity._m00_m11_m22_m33 = 1.0;
float4x4 WorldToTexture = (unity_ProbeVolumeParams.y == 1.0f) ? unity_ProbeVolumeWorldToObject : identity;
float4x4 translation = identity;
translation._m30_m31_m32 = -unity_ProbeVolumeMin.xyz;
float4x4 scale = 0;
scale._m00_m11_m22_m33 = float4(unity_ProbeVolumeSizeInv.xyz, 1.0);
WorldToTexture = mul(mul(scale, translation), WorldToTexture);
return SampleProbeVolumeSH4(TEXTURE3D_PASS(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), positionWS, normalWS, WorldToTexture, unity_ProbeVolumeParams.z);
}
#else
float3 bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
#ifdef LIGHTMAP_ON
#ifdef DIRLIGHTMAP_COMBINED
bakeDiffuseLighting += SampleDirectionalLightmap(TEXTURE2D_PASS(unity_Lightmap, samplerunity_Lightmap),
TEXTURE2D_PASS(unity_LightmapInd, samplerunity_Lightmap),
uvStaticLightmap, unity_LightmapST);
#else
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PASS(unity_Lightmap, samplerunity_Lightmap), uvStaticLightmap, unity_LightmapST);
#endif
#endif
#ifdef DYNAMICLIGHTMAP_ON
#ifdef DIRLIGHTMAP_COMBINED
bakeDiffuseLighting += SampleDirectionalLightmap(TEXTURE2D_PASS(unity_DynamicLightmap, samplerunity_DynamicLightmap),
TEXTURE2D_PASS(unity_DynamicDirectionality, samplerunity_DynamicLightmap),
uvDynamicLightmap, unity_DynamicLightmapST);
#else
bakeDiffuseLighting += SampleSingleLightmap(TEXTURE2D_PASS(unity_DynamicLightmap, samplerunity_DynamicLightmap), uvDynamicLightmap, unity_DynamicLightmapST);
#endif
#endif
return bakeDiffuseLighting;
#endif
}
void GetSurfaceAndBuiltinData(FragInput input, out SurfaceData surfaceData, out BuiltinData builtinData)
{
#ifdef _HEIGHTMAP

float height = UNITY_SAMPLE_TEX2D(_HeightMap, input.texCoord0).r * _HeightScale + _HeightBias;
float height = SAMPLE_TEXTURE2D(_HeightMap, sampler_HeightMap, input.texCoord0).r * _HeightScale + _HeightBias;
// Transform view vector in tangent space
TransformWorldToTangent(V, input.tangentToWorld);
float2 offset = ParallaxOffset(viewDirTS, height);

#endif
surfaceData.baseColor = UNITY_SAMPLE_TEX2D(_BaseColorMap, input.texCoord0).rgb * _BaseColor.rgb;
surfaceData.baseColor = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, input.texCoord0).rgb * _BaseColor.rgb;
float alpha = UNITY_SAMPLE_TEX2D(_BaseColorMap, input.texCoord0).a * _BaseColor.a;
float alpha = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, input.texCoord0).a * _BaseColor.a;
#endif
#ifdef _ALPHATEST_ON

#ifdef _SPECULAROCCLUSIONMAP
// TODO: Do something. For now just take alpha channel
surfaceData.specularOcclusion = UNITY_SAMPLE_TEX2D(_SpecularOcclusionMap, input.texCoord0).a;
surfaceData.specularOcclusion = SAMPLE_TEXTURE2D(_SpecularOcclusionMap, sampler_SpecularOcclusionMap, input.texCoord0).a;
#else
// Horizon Occlusion for Normal Mapped Reflections: http://marmosetco.tumblr.com/post/81245981087
//surfaceData.specularOcclusion = saturate(1.0 + horizonFade * dot(r, input.tangentToWorld[2].xyz);

#ifdef _NORMALMAP
#ifdef _NORMALMAP_TANGENT_SPACE
float3 normalTS = UnpackNormalAG(UNITY_SAMPLE_TEX2D(_NormalMap, input.texCoord0));
float3 normalTS = UnpackNormalAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, input.texCoord0));
surfaceData.normalWS = UNITY_SAMPLE_TEX2D(_NormalMap, input.texCoord0).rgb;
surfaceData.normalWS = SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, input.texCoord0).rgb;
#endif
#else
surfaceData.normalWS = vertexNormalWS;

#endif
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
surfaceData.perceptualSmoothness = UNITY_SAMPLE_TEX2D(_BaseColorMap, input.texCoord0).a;
surfaceData.perceptualSmoothness = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, input.texCoord0).a;
surfaceData.perceptualSmoothness = UNITY_SAMPLE_TEX2D(_MaskMap, input.texCoord0).a;
surfaceData.perceptualSmoothness = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, input.texCoord0).a;
#else
surfaceData.perceptualSmoothness = 1.0;
#endif

// MaskMap is Metallic, Ambient Occlusion, (Optional) - emissive Mask, Optional - Smoothness (in alpha)
#ifdef _MASKMAP
surfaceData.metallic = UNITY_SAMPLE_TEX2D(_MaskMap, input.texCoord0).r;
surfaceData.ambientOcclusion = UNITY_SAMPLE_TEX2D(_MaskMap, input.texCoord0).g;
surfaceData.metallic = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, input.texCoord0).r;
surfaceData.ambientOcclusion = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, input.texCoord0).g;
#else
surfaceData.metallic = 1.0;
surfaceData.ambientOcclusion = 1.0;

// TODO: think about using BC5
#ifdef _TANGENTMAP
#ifdef _NORMALMAP_TANGENT_SPACE // Normal and tangent use same space
float3 tangentTS = UnpackNormalAG(SAMPLE_TEXTURE2D(_TangentMap, sampler_TangentMap, input.texCoord0));
surfaceData.tangentWS = TransformTangentToWorld(tangentTS, input.tangentToWorld);
#else // Object space (TODO: We need to apply the world rotation here! - Require to pass world transform)
surfaceData.tangentWS = SAMPLE_TEXTURE2D(_TangentMap, sampler_TangentMap, input.texCoord0).rgb;
#endif
#else
surfaceData.tangentWS = input.tangentToWorld[0].xyz;
#endif
// TODO: Is there anything todo regarding flip normal but for the tangent ?
surfaceData.tangentWS = input.tangentToWorld[0].xyz; // TODO: do with tangent same as with normal, sample into texture etc...
surfaceData.anisotropy = 0;
#ifdef _ANISOTROPYMAP
surfaceData.anisotropy = SAMPLE_TEXTURE2D(_AnisotropyMap, sampler_AnisotropyMap, input.texCoord0).r;
#else
surfaceData.anisotropy = 1.0;
#endif
surfaceData.anisotropy *= _Anisotropy;
surfaceData.specular = 0.04;
surfaceData.subSurfaceRadius = 1.0;

// TODO: Sample lightmap/lightprobe/volume proxy
// This should also handle projective lightmap
// Note that data input above can be use to sample into lightmap (like normal)
builtinData.bakeDiffuseLighting = UNITY_SAMPLE_TEX2D(_DiffuseLightingMap, input.texCoord1).rgb;
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionWS, surfaceData.normalWS, input.texCoord1, input.texCoord2);
builtinData.emissiveColor = UNITY_SAMPLE_TEX2D(_EmissiveColorMap, input.texCoord0).rgb * _EmissiveColor;
builtinData.emissiveColor = SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, input.texCoord0).rgb * _EmissiveColor;
builtinData.emissiveColor = surfaceData.baseColor * UNITY_SAMPLE_TEX2D(_MaskMap, input.texCoord0).bbb;
builtinData.emissiveColor = surfaceData.baseColor * SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, input.texCoord0).bbb;
#else
builtinData.emissiveColor = float3(0.0, 0.0, 0.0);
#endif

67
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/LitDefault.shader


_HeightBias("Height Bias", Float) = 0
[Enum(Parallax, 0, Displacement, 1)] _HeightMapMode("Heightmap usage", Float) = 0
_TangentMap("TangentMap", 2D) = "bump" {}
_Anisotropy("Anisotropy", Range(0.0, 1.0)) = 0
_AnisotropyMap("AnisotropyMap", 2D) = "white" {}
_SubSurfaceRadius("SubSurfaceRadius", Range(0.0, 1.0)) = 0
_SubSurfaceRadiusMap("SubSurfaceRadiusMap", 2D) = "white" {}
//_Thickness("Thickness", Range(0.0, 1.0)) = 0

// Following options are for the GUI inspector and different from the input parameters above
// These option below will cause different compilation flag.
_DiffuseLightingMap("DiffuseLightingMap", 2D) = "black" {}
_EmissiveColor("EmissiveColor", Color) = (0, 0, 0)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0

#pragma shader_feature _EMISSIVE_COLOR_MAP
#pragma shader_feature _HEIGHTMAP
#pragma shader_feature _HEIGHTMAP_AS_DISPLACEMENT
#pragma shader_feature _TANGENTMAP
#pragma shader_feature _ANISOTROPYMAP
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
//-------------------------------------------------------------------------------------
// Define

// Set of users variables
float4 _BaseColor;
UNITY_DECLARE_TEX2D(_BaseColorMap);
TEXTURE2D(_BaseColorMap);
SAMPLER2D(sampler_BaseColorMap);
UNITY_DECLARE_TEX2D(_MaskMap);
UNITY_DECLARE_TEX2D(_SpecularOcclusionMap);
TEXTURE2D(_MaskMap);
SAMPLER2D(sampler_MaskMap);
TEXTURE2D(_SpecularOcclusionMap);
SAMPLER2D(sampler_SpecularOcclusionMap);
TEXTURE2D(_NormalMap);
SAMPLER2D(sampler_NormalMap);
TEXTURE2D(_Heightmap);
SAMPLER2D(sampler_Heightmap);
UNITY_DECLARE_TEX2D(_NormalMap);
UNITY_DECLARE_TEX2D(_Heightmap);
UNITY_DECLARE_TEX2D(_DiffuseLightingMap);
TEXTURE2D(_TangentMap);
SAMPLER2D(sampler_TangentMap);
float _Anisotropy;
TEXTURE2D(_AnisotropyMap);
SAMPLER2D(sampler_AnisotropyMap);
TEXTURE2D(_DiffuseLightingMap);
SAMPLER2D(sampler_DiffuseLightingMap);
UNITY_DECLARE_TEX2D(_EmissiveColorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER2D(sampler_EmissiveColorMap);
UNITY_DECLARE_TEX2D(_SubSurfaceRadiusMap);
TEXTURE2D(_SubSurfaceRadiusMap);
SAMPLER2D(sampler_SubSurfaceRadiusMap);
// UNITY_DECLARE_TEX2D(_ThicknessMap);
//TEXTURE2D(_ThicknessMap);
//SAMPLER2D(sampler_ThicknessMap);
// UNITY_DECLARE_TEX2D(_CoatCoverageMap);
//TEXTURE2D(_CoatCoverageMap);
//SAMPLER2D(sampler_CoatCoverageMap);
// UNITY_DECLARE_TEX2D(_CoatRoughnessMap);
//TEXTURE2D(_CoatRoughnessMap);
//SAMPLER2D(sampler_CoatRoughnessMap);
float _AlphaCutoff;
ENDHLSL

// ------------------------------------------------------------------
Pass
{
Name "ShadowCaster"
Tags{ "LightMode" = "ShadowCaster" }
Name "ShadowCaster"
Tags{ "LightMode" = "ShadowCaster" }
Cull[_CullMode]
Cull[_CullMode]
ZWrite On ZTest LEqual
ZWrite On ZTest LEqual
HLSLPROGRAM

48
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Lit/LitUI.cs


public static GUIContent specularOcclusionMapText = new GUIContent("Specular Occlusion Map (RGBA)", "Specular Occlusion Map");
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map (BC5) - DXT5 for test");
public static GUIContent normalMapSpaceText = new GUIContent("Normal Map space", "");
public static GUIContent normalMapSpaceText = new GUIContent("Normal/Tangent Map space", "");
// public static GUIContent diffuseLightingMapText = new GUIContent("DiffuseLightingMap", "Lightmap/Lightprobe data (fill by system is not done");
public static GUIContent tangentMapText = new GUIContent("Tangent Map", "Tangent Map (BC5) - DXT5 for test");
public static GUIContent anisotropyText = new GUIContent("Anisotropy", "Anisotropy scale factor");
public static GUIContent anisotropyMapText = new GUIContent("Anisotropy Map", "Anisotropy (R)");
public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive.");
public static GUIContent emissiveColorWarning = new GUIContent("Ensure emissive color is non-black for emission to have effect.");
}
MaterialProperty surfaceType = null;

MaterialProperty heightMap = null;
MaterialProperty heightScale = null;
MaterialProperty heightBias = null;
MaterialProperty tangentMap = null;
MaterialProperty anisotropy = null;
MaterialProperty anisotropyMap = null;
// MaterialProperty diffuseLightingMap = null;
MaterialProperty emissiveColor = null;
MaterialProperty emissiveColorMap = null;
MaterialProperty emissiveIntensity = null;

protected const string kspecularOcclusionMap = "_SpecularOcclusionMap";
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected const string kHeightMap = "_HeightMap";
protected const string kTangentMap = "_TangentMap";
protected const string kAnisotropyMap = "_AnisotropyMap";
public void FindOptionProperties(MaterialProperty[] props)
{

heightMap = FindProperty(kHeightMap, props);
heightScale = FindProperty("_HeightScale", props);
heightBias = FindProperty("_HeightBias", props);
// diffuseLightingMap = FindProperty("_DiffuseLightingMap", props);
tangentMap = FindProperty("_TangentMap", props);
anisotropy = FindProperty("_Anisotropy", props);
anisotropyMap = FindProperty("_AnisotropyMap", props);
emissiveColor = FindProperty("_EmissiveColor", props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
emissiveIntensity = FindProperty("_EmissiveIntensity", props);

m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightScale, heightBias);
m_MaterialEditor.TexturePropertySingleLine(Styles.tangentMapText, tangentMap);
m_MaterialEditor.ShaderProperty(anisotropy, Styles.anisotropyText);
m_MaterialEditor.TexturePropertySingleLine(Styles.anisotropyMapText, anisotropyMap);
if (!useEmissiveMask)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);

SetKeyword(material, "_SPECULAROCCLUSIONMAP", material.GetTexture(kspecularOcclusionMap));
SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
SetKeyword(material, "_HEIGHTMAP", material.GetTexture(kHeightMap));
SetKeyword(material, "_TANGENTMAP", material.GetTexture(kTangentMap));
SetKeyword(material, "_ANISOTROPYMAP", material.GetTexture(kAnisotropyMap));
}
protected void SetupMaterial(Material material)

SetupKeywordsForInputMaps(material);
/*
bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(material, material.GetFloat("_EmissiveIntensity"));
{
flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack;
if (!shouldEmissionBeEnabled)
{
if (shouldEmissionBeEnabled)
flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack;
else
*/
static bool ShouldEmissionBeEnabled(Material mat, Color color)
static bool ShouldEmissionBeEnabled(Material mat, float emissiveIntensity)
//var realtimeEmission = (mat.globalIlluminationFlags & MaterialGlobalIlluminationFlags.RealtimeEmissive) > 0;
//return color.maxColorComponent > 0.1f / 255.0f || realtimeEmission;
return false;
var realtimeEmission = (mat.globalIlluminationFlags & MaterialGlobalIlluminationFlags.RealtimeEmissive) > 0;
return emissiveIntensity > 0.0f || realtimeEmission;
}
bool HasValidEmissiveKeyword(Material material)

53
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Material.hlsl


#include "Debug.hlsl"
#include "GeometricTools.hlsl"
#include "CommonMaterial.hlsl"
#include "EntityLighting.hlsl"
//-----------------------------------------------------------------------------
// common Encode/Decode functions

out float4 MERGE_NAME(NAME, 2) : SV_Target2
#define DECLARE_GBUFFER_TEXTURE(NAME) \
Texture2D MERGE_NAME(NAME, 0); \
Texture2D MERGE_NAME(NAME, 1); \
Texture2D MERGE_NAME(NAME, 2);
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2));
float4 MERGE_NAME(NAME, 0) = MERGE_NAME(TEX, 0).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 1) = MERGE_NAME(TEX, 1).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 2) = MERGE_NAME(TEX, 2).Load(uint3(UV, 0));
float4 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), uint3(UV, 0));
#define ENCODE_INTO_GBUFFER(SURFACE_DATA, NAME) EncodeIntoGBuffer(SURFACE_DATA, MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2))
#define DECODE_FROM_GBUFFER(NAME) DecodeFromGBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2))

out float4 MERGE_NAME(NAME, 3) : SV_Target3
#define DECLARE_GBUFFER_TEXTURE(NAME) \
Texture2D MERGE_NAME(NAME, 0); \
Texture2D MERGE_NAME(NAME, 1); \
Texture2D MERGE_NAME(NAME, 2); \
Texture2D MERGE_NAME(NAME, 3);
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2)); \
TEXTURE2D(MERGE_NAME(NAME, 3));
float4 MERGE_NAME(NAME, 0) = MERGE_NAME(TEX, 0).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 1) = MERGE_NAME(TEX, 1).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 2) = MERGE_NAME(TEX, 2).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 3) = MERGE_NAME(TEX, 3).Load(uint3(UV, 0));
float4 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 3), uint3(UV, 0));
#define ENCODE_INTO_GBUFFER(SURFACE_DATA, NAME) EncodeIntoGBuffer(SURFACE_DATA, MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3))
#define DECODE_FROM_GBUFFER(NAME) DecodeFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3))

out float4 MERGE_NAME(NAME, 4) : SV_Target4
#define DECLARE_GBUFFER_TEXTURE(NAME) \
Texture2D MERGE_NAME(NAME, 0); \
Texture2D MERGE_NAME(NAME, 1); \
Texture2D MERGE_NAME(NAME, 2); \
Texture2D MERGE_NAME(NAME, 3); \
Texture2D MERGE_NAME(NAME, 4);
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2)); \
TEXTURE2D(MERGE_NAME(NAME, 3)); \
TEXTURE2D(MERGE_NAME(NAME, 4));
float4 MERGE_NAME(NAME, 0) = MERGE_NAME(TEX, 0).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 1) = MERGE_NAME(TEX, 1).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 2) = MERGE_NAME(TEX, 2).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 3) = MERGE_NAME(TEX, 3).Load(uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 4) = MERGE_NAME(TEX, 4).Load(uint3(UV, 0));
float4 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 3), uint3(UV, 0)); \
float4 MERGE_NAME(NAME, 4) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 4), uint3(UV, 0));
#define ENCODE_INTO_GBUFFER(SURFACE_DATA, NAME) EncodeIntoGBuffer(SURFACE_DATA, MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4))
#define DECODE_FROM_GBUFFER(NAME) DecodeFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4))

// Generic whatever the number of GBuffer
#ifdef VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) out float4 GBUFFER_VELOCITY_NAME(NAME) : GBUFFER_VELOCITY_TARGET(SV_Target)
#define DECLARE_GBUFFER_VELOCITY_TEXTURE(NAME) Texture2D GBUFFER_VELOCITY_NAME(NAME);
#define DECLARE_GBUFFER_VELOCITY_TEXTURE(NAME) TEXTURE2D(GBUFFER_VELOCITY_NAME(NAME));
#define DECLARE_GBUFFER_BAKE_LIGHTING(NAME) Texture2D GBUFFER_BAKE_LIGHTING_NAME(NAME);
#define DECLARE_GBUFFER_BAKE_LIGHTING(NAME) TEXTURE2D(GBUFFER_BAKE_LIGHTING_NAME(NAME));
#define ENCODE_BAKE_LIGHTING_INTO_GBUFFER(BAKE_DIFFUSE_LIGHTING, NAME) EncodeBakedDiffuseLigthingIntoGBuffer(BAKE_DIFFUSE_LIGHTING, GBUFFER_BAKE_LIGHTING_NAME(NAME))
#define FETCH_BAKE_LIGHTING_GBUFFER(NAME, TEX, UV) float4 GBUFFER_BAKE_LIGHTING_NAME(NAME) = GBUFFER_BAKE_LIGHTING_NAME(TEX).Load(uint3(UV, 0));
#define DECODE_BAKE_LIGHTING_FROM_GBUFFER(NAME) DecodeBakedDiffuseLigthingFromGBuffer(GBUFFER_BAKE_LIGHTING_NAME(NAME))

6
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Unlit/UnlitData.hlsl


void GetSurfaceAndBuiltinData(FragInput input, out SurfaceData surfaceData, out BuiltinData builtinData)
{
surfaceData.color = UNITY_SAMPLE_TEX2D(_ColorMap, input.texCoord0).rgb * _Color.rgb;
float alpha = UNITY_SAMPLE_TEX2D(_ColorMap, input.texCoord0).a * _Color.a;
surfaceData.color = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, input.texCoord0).rgb * _Color.rgb;
float alpha = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, input.texCoord0).a * _Color.a;
#ifdef _ALPHATEST_ON
clip(alpha - _AlphaCutoff);

builtinData.bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
#ifdef _EMISSIVE_COLOR_MAP
builtinData.emissiveColor = UNITY_SAMPLE_TEX2D(_EmissiveColorMap, input.texCoord0).rgb * _EmissiveColor;
builtinData.emissiveColor = SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, input.texCoord0).rgb * _EmissiveColor;
#else
builtinData.emissiveColor = _EmissiveColor;
#endif

8
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/Material/Unlit/UnlitDefault.shader


//-------------------------------------------------------------------------------------
float4 _Color;
UNITY_DECLARE_TEX2D(_ColorMap);
TEXTURE2D(_ColorMap);
SAMPLER2D(sampler_ColorMap);
UNITY_DECLARE_TEX2D(_EmissiveColorMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER2D(sampler_EmissiveColorMap);
float _EmissiveIntensity;
float _AlphaCutoff;

6
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/PostProcess/FinalPass.shader


#include "Color.hlsl"
#include "Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/ShaderVariables.hlsl"
UNITY_DECLARE_TEX2D(_MainTex);
TEXTURE2D(_MainTex);
SAMPLER2D(sampler_MainTex);
float4 _ToneMapCoeffs1;
float4 _ToneMapCoeffs2;

float4 Frag(Varyings input) : SV_Target
{
float4 c = UNITY_SAMPLE_TEX2D(_MainTex, input.texcoord);
float4 c = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.texcoord);
// Gamma correction
// TODO: Currenlt in the editor there a an additional pass were the result is copyed in a render target RGBA8_sRGB.

2
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/ShaderPass/ShaderPassGBuffer.hlsl


GetSurfaceAndBuiltinData(input, surfaceData, builtinData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(surfaceData);
Coordinate coord = GetCoordinate(input.unPositionSS, _ScreenSize.zw);
Coordinate coord = GetCoordinate(input.unPositionSS.xy, _ScreenSize.zw);
PreLightData preLightData = GetPreLightData(V, positionWS, coord, bsdfData);
ENCODE_INTO_GBUFFER(surfaceData, outGBuffer);

39
Assets/ScriptableRenderLoop/HDRenderLoop/Shaders/ShaderVariables.hlsl


CBUFFER_END
CBUFFER_START(UnityLighting)
// SH lighting environment
float4 unity_SHAr;
float4 unity_SHAg;
float4 unity_SHAb;
float4 unity_SHBr;
float4 unity_SHBg;
float4 unity_SHBb;
float4 unity_SHC;
CBUFFER_END
UNITY_DECLARE_TEX2D_HALF(unity_Lightmap);
TEXTURE2D(unity_Lightmap);
SAMPLER2D(samplerunity_Lightmap);
UNITY_DECLARE_TEX2D_NOSAMPLER_HALF(unity_LightmapInd);
TEXTURE2D(unity_LightmapInd);
UNITY_DECLARE_TEX2D(unity_DynamicLightmap);
UNITY_DECLARE_TEX2D_NOSAMPLER(unity_DynamicDirectionality);
UNITY_DECLARE_TEX2D_NOSAMPLER(unity_DynamicNormal);
TEXTURE2D(unity_DynamicLightmap);
SAMPLER2D(samplerunity_DynamicLightmap);
TEXTURE2D(unity_DynamicDirectionality);
CBUFFER_END
// TODO: Change code here so probe volume use only one transform instead of all this parameters!
TEXTURE3D(unity_ProbeVolumeSH);
SAMPLER3D(samplerunity_ProbeVolumeSH)
CBUFFER_START(UnityProbeVolume)
// x = Disabled(0)/Enabled(1)
// y = Computation are done in global space(0) or local space(1)
// z = Texel size on U texture coordinate
float4 unity_ProbeVolumeParams;
float4x4 unity_ProbeVolumeWorldToObject;
float3 unity_ProbeVolumeSizeInv;
float3 unity_ProbeVolumeMin;
CBUFFER_END
// ----------------------------------------------------------------------------

66
Assets/ScriptableRenderLoop/ShaderLibrary/API/D3D11.hlsl


// Do not exist on some platform, in this case we need to have a standard name that call a function that will initialize all parameters to 0
#define ZERO_INITIALIZE(type, name) name = (type)0;
// Macros to declare textures and samplers, possibly separately. For platforms
// that have separate samplers & textures (like DX11), and we'd want to conserve
// the samplers.
// - UNITY_DECLARE_TEX*_NOSAMPLER declares a texture, without a sampler.
// - UNITY_SAMPLE_TEX*_SAMPLER samples a texture, using sampler from another texture.
// That another texture must also be actually used in the current shader, otherwise
// the correct sampler will not be set.
// 2D textures
#define UNITY_DECLARE_TEX2D(tex) Texture2D tex; SamplerState sampler##tex
#define UNITY_DECLARE_TEX2D_NOSAMPLER(tex) Texture2D tex
#define UNITY_SAMPLE_TEX2D(tex,coord) tex.Sample (sampler##tex,coord)
#define UNITY_SAMPLE_TEX2D_LOD(tex,coord,lod) tex.SampleLevel (sampler##tex,coord, lod)
#define UNITY_SAMPLE_TEX2D_SAMPLER(tex,samplertex,coord) tex.Sample (sampler##samplertex,coord)
// Cubemaps
#define UNITY_DECLARE_TEXCUBE(tex) TextureCube tex; SamplerState sampler##tex
#define UNITY_ARGS_TEXCUBE(tex) TextureCube tex, SamplerState sampler##tex
#define UNITY_PASS_TEXCUBE(tex) tex, sampler##tex
#define UNITY_PASS_TEXCUBE_SAMPLER(tex,samplertex) tex, sampler##samplertex
#define UNITY_DECLARE_TEXCUBE_NOSAMPLER(tex) TextureCube tex
#define UNITY_SAMPLE_TEXCUBE(tex,coord) tex.Sample (sampler##tex,coord)
#define UNITY_SAMPLE_TEXCUBE_LOD(tex,coord,lod) tex.SampleLevel (sampler##tex,coord, lod)
#define UNITY_SAMPLE_TEXCUBE_SAMPLER(tex,samplertex,coord) tex.Sample (sampler##samplertex,coord)
// 3D textures
#define UNITY_DECLARE_TEX3D(tex) Texture3D tex; SamplerState sampler##tex
#define UNITY_DECLARE_TEX3D_NOSAMPLER(tex) Texture3D tex
#define UNITY_SAMPLE_TEX3D(tex,coord) tex.Sample (sampler##tex,coord)
#define UNITY_SAMPLE_TEX3D_LOD(tex,coord,lod) tex.SampleLevel (sampler##tex,coord, lod)
#define UNITY_SAMPLE_TEX3D_SAMPLER(tex,samplertex,coord) tex.Sample (sampler##samplertex,coord)
// 2D arrays
#define UNITY_DECLARE_TEX2DARRAY(tex) Texture2DArray tex; SamplerState sampler##tex
#define UNITY_DECLARE_TEX2DARRAY_NOSAMPLER(tex) Texture2DArray tex
#define UNITY_ARGS_TEX2DARRAY(tex) Texture2DArray tex, SamplerState sampler##tex
#define UNITY_PASS_TEX2DARRAY(tex) tex, sampler##tex
#define UNITY_SAMPLE_TEX2DARRAY(tex,coord) tex.Sample (sampler##tex,coord)
#define UNITY_SAMPLE_TEX2DARRAY_LOD(tex,coord,lod) tex.SampleLevel (sampler##tex,coord, lod)
#define UNITY_SAMPLE_TEX2DARRAY_SAMPLER(tex,samplertex,coord) tex.Sample (sampler##samplertex,coord)
// Cube arrays
#define UNITY_DECLARE_TEXCUBEARRAY(tex) TextureCubeArray tex; SamplerState sampler##tex
#define UNITY_DECLARE_TEXCUBEARRAY_NOSAMPLER(tex) TextureCubeArray tex
#define UNITY_ARGS_TEXCUBEARRAY(tex) TextureCubeArray tex, SamplerState sampler##tex
#define UNITY_PASS_TEXCUBEARRAY(tex) tex, sampler##tex
#define UNITY_SAMPLE_TEXCUBEARRAY(tex,coord) tex.Sample (sampler##tex,coord)
#define UNITY_SAMPLE_TEXCUBEARRAY_LOD(tex,coord,lod) tex.SampleLevel (sampler##tex,coord, lod)
#define UNITY_SAMPLE_TEXCUBEARRAY_SAMPLER(tex,samplertex,coord) tex.Sample (sampler##samplertex,coord)
// Shadow
#define UNITY_DECLARE_SHADOWMAP(tex) Texture2D tex; SamplerComparisonState sampler##tex
#define UNITY_SAMPLE_SHADOW(tex,coord) tex.SampleCmpLevelZero (sampler##tex,(coord).xy,(coord).z)
#define UNITY_SAMPLE_SHADOW_PROJ(tex,coord) tex.SampleCmpLevelZero (sampler##tex,(coord).xy/(coord).w,(coord).z/(coord).w)
// Texture abstraction
// Alternative
#define TEXTURE2D(textureName) Texture2D textureName;
#define TEXTURE2D_ARRAY(textureName) Texture2DArray textureName;
#define TEXTURECUBE(textureName) TextureCube textureName;

#define SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index) textureName.Sample(samplerName, float3((coord2).xy, index))
#define SAMPLE_TEXTURE2D_ARRAY_LOD(textureName, samplerName, coord2, index, lod) textureName.SampleLevel(samplerName, float3((coord2).xy, index), lod)
#define SAMPLE_TEXTURECUBE(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define SAMPLE_TEXTURECUBE_LOD(textureName, samplerName, coord3) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURECUBE_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
#define TEXTURE2D_HALF TEXTURE2D
#define TEXTURE2D_FLOAT TEXTURE2D
#define SAMPLER2D_HALF SAMPLER2D
#define SAMPLER2D_FLOAT SAMPLER2D
#define LOAD_TEXTURE2D(textureName, unCoord3) textureName.Load(unCoord3)

24
Assets/ScriptableRenderLoop/ShaderLibrary/BSDF.hlsl


// With analytical light (not image based light) we clamp the minimun roughness in the NDF to avoid numerical instability.
#define UNITY_MIN_ROUGHNESS 0.002
float D_GGX(float NdotH, float roughness)
float D_GGXNoPI(float NdotH, float roughness)
{
roughness = max(roughness, UNITY_MIN_ROUGHNESS);

}
float D_GGXDividePI(float NdotH, float roughness)
float D_GGX(float NdotH, float roughness)
return INV_PI * D_GGX(NdotH, roughness);
return INV_PI * D_GGXNoPI(NdotH, roughness);
}
// Ref: http://jcgt.org/published/0003/02/03/paper.pdf

float GetSmithJointGGXApproxLambdaV(float NdotV, float roughness)
{
float a = roughness;
return (NdotV * (1 - a) + a);
return NdotV * (1 - a) + a;
}
float V_SmithJointGGXApprox(float NdotL, float NdotV, float roughness, float lambdaV)

// roughnessT -> roughness in tangent direction
// roughnessB -> roughness in bitangent direction
float D_GGXAniso(float TdotH, float BdotH, float NdotH, float roughnessT, float roughnessB)
float D_GGXAnisoNoPI(float TdotH, float BdotH, float NdotH, float roughnessT, float roughnessB)
{
roughnessT = max(roughnessT, UNITY_MIN_ROUGHNESS);
roughnessB = max(roughnessB, UNITY_MIN_ROUGHNESS);

}
float D_GGXAnisoDividePI(float TdotH, float BdotH, float NdotH, float roughnessT, float roughnessB)
float D_GGXAniso(float TdotH, float BdotH, float NdotH, float roughnessT, float roughnessB)
return INV_PI * D_GGXAniso(TdotH, BdotH, NdotH, roughnessT, roughnessB);
return INV_PI * D_GGXAnisoNoPI(TdotH, BdotH, NdotH, roughnessT, roughnessB);
}
// Ref: https://cedec.cesa.or.jp/2015/session/ENG/14698.html The Rendering Materials of Far Cry 4

// Diffuse BRDF - diffuseColor is expected to be multiply by the caller
//-----------------------------------------------------------------------------
float Lambert()
float LambertNoPI()
float LambertDividePI()
float Lambert()
float DisneyDiffuse(float NdotV, float NdotL, float LdotH, float perceptualRoughness)
float DisneyDiffuseNoPI(float NdotV, float NdotL, float LdotH, float perceptualRoughness)
{
float fd90 = 0.5 + 2 * LdotH * LdotH * perceptualRoughness;
// Two schlick fresnel term

return lightScatter * viewScatter;
}
float DisneyDiffuseDividePI(float NdotV, float NdotL, float LdotH, float perceptualRoughness)
float DisneyDiffuse(float NdotV, float NdotL, float LdotH, float perceptualRoughness)
return INV_PI * DisneyDiffuse(NdotV, NdotL, LdotH, perceptualRoughness);
return INV_PI * DisneyDiffuseNoPI(NdotV, NdotL, LdotH, perceptualRoughness);
}

22
Assets/ScriptableRenderLoop/ShaderLibrary/Filtering.hlsl


// Ref: https://gist.github.com/TheRealMJP/c83b8c0f46b63f3a88a5986f4fa982b1 from MJP
// Samples a texture with Catmull-Rom filtering, using 9 texture fetches instead of 16.
// See http://vec3.ca/bicubic-filtering-in-fewer-taps/ for more details
float4 SampleTextureCatmullRom(Texture2D<float4> tex, SamplerState linearSampler, float2 uv, float2 texSize)
float4 SampleTextureCatmullRom(TEXTURE2D_ARGS(tex, linearSampler), float2 uv, float2 texSize)
{
// We're going to sample a a 4x4 grid of texels surrounding the target UV coordinate. We'll do this by rounding
// down the sample location to get the exact center of our "starting" texel. The starting texel will be at

texPos3 /= texSize;
texPos12 /= texSize;
float4 result = 0.0f;
result += tex.SampleLevel(linearSampler, float2(texPos0.x, texPos0.y), 0.0f) * w0.x * w0.y;
result += tex.SampleLevel(linearSampler, float2(texPos12.x, texPos0.y), 0.0f) * w12.x * w0.y;
result += tex.SampleLevel(linearSampler, float2(texPos3.x, texPos0.y), 0.0f) * w3.x * w0.y;
float4 result = 0.0;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos0.x, texPos0.y), 0.0) * w0.x * w0.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos12.x, texPos0.y), 0.0) * w12.x * w0.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos3.x, texPos0.y), 0.0) * w3.x * w0.y;
result += tex.SampleLevel(linearSampler, float2(texPos0.x, texPos12.y), 0.0f) * w0.x * w12.y;
result += tex.SampleLevel(linearSampler, float2(texPos12.x, texPos12.y), 0.0f) * w12.x * w12.y;
result += tex.SampleLevel(linearSampler, float2(texPos3.x, texPos12.y), 0.0f) * w3.x * w12.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos0.x, texPos12.y), 0.0) * w0.x * w12.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos12.x, texPos12.y), 0.0) * w12.x * w12.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos3.x, texPos12.y), 0.0) * w3.x * w12.y;
result += tex.SampleLevel(linearSampler, float2(texPos0.x, texPos3.y), 0.0f) * w0.x * w3.y;
result += tex.SampleLevel(linearSampler, float2(texPos12.x, texPos3.y), 0.0f) * w12.x * w3.y;
result += tex.SampleLevel(linearSampler, float2(texPos3.x, texPos3.y), 0.0f) * w3.x * w3.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos0.x, texPos3.y), 0.0) * w0.x * w3.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos12.x, texPos3.y), 0.0) * w12.x * w3.y;
result += TEXTURE2D_SAMPLE_LOD(tex, linearSampler, float2(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y;
return result;
}

6
Assets/ScriptableRenderLoop/ShaderLibrary/ImageBasedLighting.hlsl


}
// Ref: Listing 19 in "Moving Frostbite to PBR"
float4 IntegrateLD( UNITY_ARGS_TEXCUBE(tex),
float4 IntegrateLD(TEXTURECUBE_ARGS(tex, sampl),
float3 V,
float3 N,
float roughness,

// - OmegaS : Solid angle associated to a sample
// - OmegaP : Solid angle associated to a pixel of the cubemap
float pdf = D_GGXDividePI(NdotH, roughness) * NdotH / (4.0 * LdotH);
float pdf = D_GGXNoPI(NdotH, roughness) * NdotH / (4.0 * LdotH); // TODO: Check if divide PI is required here
float omegaS = 1.0 / (sampleCount * pdf); // Solid angle associated to a sample
// invOmegaP is precomputed on CPU and provide as a parameter of the function
// float omegaP = FOUR_PI / (6.0f * cubemapWidth * cubemapWidth); // Solid angle associated to a pixel of the cubemap

if (NdotL > 0.0f)
{
float3 val = UNITY_SAMPLE_TEXCUBE_LOD(tex, L, mipLevel).rgb;
float3 val = SAMPLE_TEXTURECUBE_LOD(tex, sampl, L, mipLevel).rgb;
// See p63 equation (53) of moving Frostbite to PBR v2 for the extra NdotL here (both in weight and value)
acc += val * NdotL;

2
Assets/ScriptableRenderLoop/common/ShaderBase.h


#endif
#ifndef firstbithigh
#define firstbithigh FirstSetBit_Hi_MSB
#define firstbithigh FirstSetBit_Hi
#endif
#endif

41
Assets/ScriptableRenderLoop/common/TextureCache.cs


if (mismatch)
{
Debug.LogErrorFormat(texture, "Texture size or format of \"{0}\" doesn't match renderloop settings (should be {1}x{2} {3})",
texture.name, m_Cache.width, m_Cache.height, m_Cache.format);
return;
if (!Graphics.ConvertTexture(texture, 0, m_Cache, sliceIndex))
{
Debug.LogErrorFormat(texture, "Unable to convert texture \"{0}\" to match renderloop settings ({1}x{2} {3})",
texture.name, m_Cache.width, m_Cache.height, m_Cache.format);
}
Graphics.CopyTexture(texture, 0, m_Cache, sliceIndex);
else
{
Graphics.CopyTexture(texture, 0, m_Cache, sliceIndex);
}
}
public override Texture GetTexCache()

if (mismatch)
{
Debug.LogErrorFormat(texture, "Texture size or format of \"{0}\" doesn't match renderloop settings (should be {1}x{2} {3})",
texture.name, m_Cache.width, m_Cache.height, m_Cache.format);
return;
bool failed = false;
for (int f = 0; f < 6; f++)
{
if (!Graphics.ConvertTexture(texture, f, m_Cache, 6 * sliceIndex + f))
{
failed = true;
break;
}
}
if (failed)
{
Debug.LogErrorFormat(texture, "Unable to convert texture \"{0}\" to match renderloop settings ({1}x{2} {3})",
texture.name, m_Cache.width, m_Cache.height, m_Cache.format);
}
}
else
{
for (int f = 0; f < 6; f++)
Graphics.CopyTexture(texture, f, m_Cache, 6 * sliceIndex + f);
for (int f = 0; f < 6; f++)
Graphics.CopyTexture(texture, f, m_Cache, 6 * sliceIndex + f);
}
public override Texture GetTexCache()

4
Assets/ScriptableRenderLoop/fptl/ClusteredUtils.h


int SnapToClusterIdxFlex(float z_in, float suggestedBase, bool logBasePerTile)
{
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float z = z_in;
#else
float z = -z_in;

float dist = (pow(suggestedBase, (float)k) - 1.0) / (userscale * (suggestedBase - 1.0f));
res = dist + g_fNearPlane;
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
return res;
#else
return -res;

1001
Assets/ScriptableRenderLoop/fptl/FptlLighting.cs
文件差异内容过多而无法显示
查看文件

5
Assets/ScriptableRenderLoop/fptl/LightBoundsDebug.shader


coord.xy *= (coordIndex >= 4) ? lightData.scaleXY : float2(1, 1);
float3 viewPos = lightData.center + coord.x * lightData.boxAxisX.xyz + coord.y * lightData.boxAxisY.xyz + coord.z * -lightData.boxAxisZ.xyz;
#if USE_LEFTHAND_CAMERASPACE
// not completely sure why this is necessary since the old stuff pretends camera coordinate system is also left-hand.
// see: Camera::CalculateMatrixShaderProps()
viewPos.z = -viewPos.z;
#endif
return UnityViewToClipPos(viewPos);
}

3
Assets/ScriptableRenderLoop/fptl/LightDefinitions.cs


public static int MAX_NR_BIGTILE_LIGHTS_PLUSONE = 512; // may be overkill but the footprint is 2 bits per pixel using uint16.
public static float VIEWPORT_SCALE_Z = 1.0f;
// enable unity's original left-hand shader camera space (right-hand internally in unity).
public static int USE_LEFTHAND_CAMERASPACE = 0;
// flags
public static int IS_CIRCULAR_SPOT_SHAPE = 1;
public static int HAS_COOKIE_TEXTURE = 2;

4
Assets/ScriptableRenderLoop/fptl/LightDefinitions.cs.hlsl


//
// LightDefinitions: static fields
//
#define USE_LEFTHAND_CAMERASPACE (0)
#define MAX_NR_LIGHTS_PER_CAMERA (1024)
#define MAX_NR_BIGTILE_LIGHTS_PLUSONE (512)
#define VIEWPORT_SCALE_Z (1)

4
Assets/ScriptableRenderLoop/fptl/LightingConvexHullUtils.hlsl


p0 = center + (vA + vB - vC); // center + vA is center of face when scaleXY is 1.0
float3 vNout = cross( vB2, 0.5*(vA-vA2) - vC );
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
vNout = -vNout;
#endif

#endif
// enlarge sphere so it overlaps the center of the tile assuming it overlaps the tile to begin with.
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float sphRadius = sphRadiusIn + (sphCen.z+offs)*halfTileSizeAtZDistOne;
#else
float sphRadius = sphRadiusIn - (sphCen.z-offs)*halfTileSizeAtZDistOne;

4
Assets/ScriptableRenderLoop/fptl/LightingUtils.hlsl


//float fCy = g_mScrProjection[2].y;
float fCy = g_mScrProjection[1].z;
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

float GetLinearZFromSVPosW(float posW)
{
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float linZ = posW;
#else
float linZ = -posW;

8
Assets/ScriptableRenderLoop/fptl/lightlistbuild-bigtile.compute


float fSy = g_mScrProjection[1].y;
float fCy = g_mScrProjection[1].z;
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
void SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate)
{
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
#else
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);

float x = (i&1)==0 ? viTilLL.x : viTilUR.x;
float y = (i&2)==0 ? viTilLL.y : viTilUR.y;
float z = (i&4)==0 ? g_fNearPlane : fTileFarPlane;
#ifndef LEFT_HAND_COORDINATES
#if !USE_LEFTHAND_CAMERASPACE
z = -z;
#endif
return GetViewPosFromLinDepth( float2(x, y), z);

const float3 boxX = lgtDat.boxAxisX.xyz;
const float3 boxY = lgtDat.boxAxisY.xyz;
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip an axis to make it right handed since Determinant(worldToView)<0
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip axis (so it points away from the light direction for a spot-light)
const float3 center = lgtDat.center.xyz;
const float2 scaleXY = lgtDat.scaleXY;

14
Assets/ScriptableRenderLoop/fptl/lightlistbuild-clustered.compute


#endif
#define MAX_NR_COARSE_ENTRIES 64
#define MAX_NR_COARSE_ENTRIES 128
groupshared unsigned int coarseList[MAX_NR_COARSE_ENTRIES];
groupshared unsigned int clusterIdxs[MAX_NR_COARSE_ENTRIES/2];

float fSy = g_mScrProjection[1].y;
float fCy = g_mScrProjection[1].z;
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

#ifdef ENABLE_DEPTH_TEXTURE_BACKPLANE
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float fTileFarPlane = GetLinearDepth(dpt_ma);
#else
float fTileFarPlane = -GetLinearDepth(dpt_ma);

const float3 boxX = lgtDat.boxAxisX.xyz;
const float3 boxY = lgtDat.boxAxisY.xyz;
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip an axis to make it right handed since Determinant(worldToView)<0
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip axis (so it points away from the light direction for a spot-light)
const float3 center = lgtDat.center.xyz;
const float radius = lgtDat.radius;
const float2 scaleXY = lgtDat.scaleXY;

#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
int SphericalIntersectionTests(uint threadID, int iNrCoarseLights, float2 screenCoordinate)
{
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
#else
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);

float x = (i&1)==0 ? viTilLL.x : viTilUR.x;
float y = (i&2)==0 ? viTilLL.y : viTilUR.y;
float z = (i&4)==0 ? g_fNearPlane : fTileFarPlane;
#ifndef LEFT_HAND_COORDINATES
#if !USE_LEFTHAND_CAMERASPACE
z = -z;
#endif
return GetViewPosFromLinDepth( float2(x, y), z);

const float3 boxX = lgtDat.boxAxisX.xyz;
const float3 boxY = lgtDat.boxAxisY.xyz;
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip an axis to make it right handed since Determinant(worldToView)<0
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip axis (so it points away from the light direction for a spot-light)
const float3 center = lgtDat.center.xyz;
const float2 scaleXY = lgtDat.scaleXY;

4
Assets/ScriptableRenderLoop/fptl/lightlistbuild.compute


float fSy = g_mScrProjection[1].y;
float fCy = g_mScrProjection[1].z;
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
return fLinDepth*float3( ((v2ScrPos.x-fCx)/fSx), ((v2ScrPos.y-fCy)/fSy), 1.0 );
#else
return fLinDepth*float3( -((v2ScrPos.x+fCx)/fSx), -((v2ScrPos.y+fCy)/fSy), 1.0 );

GroupMemoryBarrierWithGroupSync();
#endif
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
float3 V = GetViewPosFromLinDepth( screenCoordinate, 1.0);
#else
float3 V = GetViewPosFromLinDepth( screenCoordinate, -1.0);

6
Assets/ScriptableRenderLoop/fptl/scrbound.compute


const float3 boxX = lgtDat.boxAxisX.xyz;
const float3 boxY = lgtDat.boxAxisY.xyz;
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip an axis to make it right handed since Determinant(worldToView)<0
const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip axis (so it points away from the light direction for a spot-light)
const float3 center = lgtDat.center.xyz;
const float radius = lgtDat.radius;
const float2 scaleXY = lgtDat.scaleXY;

vMax.xy = bMa ? min(vMax.xy, vMa) : vMax.xy;
}
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
if((center.z-radius)>0.0)
{
float4 vPosF = mul(g_mProjection, float4(0,0,center.z-radius,1));

float4 planeY = EvalPlanePair(float2(pos_view_space.y, pos_view_space.z), r);
#ifdef LEFT_HAND_COORDINATES
#if USE_LEFTHAND_CAMERASPACE
planeX = planeX.zwxy; // need to swap left/right and top/bottom planes when using left hand system
planeY = planeY.zwxy;
#endif

9
Assets/BasicRenderLoopTutorial.meta


fileFormatVersion: 2
guid: 129d9c5b5ed1a6147a8bc74f844e4d2e
folderAsset: yes
timeCreated: 1478093341
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

112
Assets/ScriptableRenderLoop/ShaderLibrary/EntityLighting.hlsl


#ifndef UNITY_ENTITY_LIGHTING_INCLUDED
#define UNITY_ENTITY_LIGHTING_INCLUDED
#include "common.hlsl"
// TODO: Check if PI is correctly handled!
// Ref: "Efficient Evaluation of Irradiance Environment Maps" from ShaderX 2
float3 SHEvalLinearL0L1(float3 N, float4 shAr, float4 shAg, float4 shAb)
{
float4 vA = float4(N, 1.0);
float3 x1;
// Linear (L1) + constant (L0) polynomial terms
x1.r = dot(shAr, vA);
x1.g = dot(shAg, vA);
x1.b = dot(shAb, vA);
return x1;
}
float3 SHEvalLinearL2(float3 N, float4 shBr, float4 shBg, float4 shBb, float4 shC)
{
float3 x2;
// 4 of the quadratic (L2) polynomials
float4 vB = N.xyzz * N.yzzx;
x2.r = dot(shBr, vB);
x2.g = dot(shBg, vB);
x2.b = dot(shBb, vB);
// Final (5th) quadratic (L2) polynomial
float vC = N.x * N.x - N.y * N.y;
float3 x3 = shC.rgb * vC;
return x2 + x3;
}
float3 SampleSH9(float4 SHCoefficients[7], float3 N)
{
float4 shAr = SHCoefficients[0];
float4 shAg = SHCoefficients[1];
float4 shAb = SHCoefficients[2];
float4 shBr = SHCoefficients[3];
float4 shBg = SHCoefficients[4];
float4 shBb = SHCoefficients[5];
float4 shCr = SHCoefficients[6];
// Linear + constant polynomial terms
float3 res = SHEvalLinearL0L1(N, shAr, shAg, shAb);
// Quadratic polynomials
res += SHEvalLinearL2(N, shBr, shBg, shBb, shCr);
return res;
}
// This sample a 3D volume storing SH
// Volume is store as 3D texture with 4 R, G, B, X set of 4 coefficient store atlas in same 3D texture. X unused.
// TODO: the packing here is innefficient as we will fetch values far away from each other and they may not fit into the cache
// Suggest we pack only RGB not X and continuous
float3 SampleProbeVolumeSH4(TEXTURE3D_ARGS(SHVolumeTexture, SHVolumeSampler), float3 positionWS, float3 normalWS, float4x4 WorldToTexture, float texelSizeX)
{
float3 texCoord = mul(WorldToTexture, float4(positionWS, 1.0)).xyz;
// Each component is store in the same texture 3D. Each use one quater on the x axis
// Here we get R component then increase by step size (0.25) to get other component. This assume 4 component
// but last one is not used.
// Clamp to edge of the "internal" texture, as R is from half texel to size of R texture minus half texel.
// This avoid leaking
texCoord.x = clamp(texCoord.x * 0.25, 0.5 * texelSizeX, 0.25 - 0.5 * texelSizeX);
float4 shAr = SAMPLE_TEXTURE3D(SHVolumeTexture, SHVolumeSampler, texCoord);
texCoord.x += 0.25;
float4 shAg = SAMPLE_TEXTURE3D(SHVolumeTexture, SHVolumeSampler, texCoord);
texCoord.x += 0.25;
float4 shAb = SAMPLE_TEXTURE3D(SHVolumeTexture, SHVolumeSampler, texCoord);
return SHEvalLinearL0L1(normalWS, shAr, shAg, shAb);
}
// Following functions are to sample enlighten lightmaps (or lightmaps encoded the same way as our
// enlighten implementation). They assume use of RGB9E5 for illuminance map.
// It is required for other platform that aren't supporting this format to implement variant of these functions
// (But these kind of platform should use regular render loop and not news shaders).
float3 SampleSingleLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), float2 uv, float4 transform)
{
// transform is scale and bias
uv = uv * transform.xy + transform.zw;
// Remark: Lightmap is RGB9E5
return SAMPLE_TEXTURE2D(lightmapTex, lightmapSampler, uv).rgb;
}
float3 SampleDirectionalLightmap(TEXTURE2D_ARGS(lightmapTex, lightmapSampler), TEXTURE2D_ARGS(lightmapDirTex, lightmapDirSampler), float2 uv, float4 transform, float3 normalWS)
{
// In directional mode Enlighten bakes dominant light direction
// in a way, that using it for half Lambert and then dividing by a "rebalancing coefficient"
// gives a result close to plain diffuse response lightmaps, but normalmapped.
// Note that dir is not unit length on purpose. Its length is "directionality", like
// for the directional specular lightmaps.
// transform is scale and bias
uv = uv * transform.xy + transform.zw;
float4 direction = SAMPLE_TEXTURE2D(lightmapDirTex, lightmapDirSampler, uv);
// Remark: Lightmap is RGB9E5
float3 illuminance = SAMPLE_TEXTURE2D(lightmapTex, lightmapSampler, uv).rgb;
float halfLambert = dot(normalWS, direction.xyz - 0.5) + 0.5;
return illuminance * halfLambert / max(1e-4, direction.w);
}
#endif // UNITY_ENTITY_LIGHTING_INCLUDED

9
Assets/ScriptableRenderLoop/ShaderLibrary/EntityLighting.hlsl.meta


fileFormatVersion: 2
guid: 0303be75670325342b4bf5697686e77b
timeCreated: 1477930471
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

73
Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/anisoTest.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: anisoTest
m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords: _EMISSION
m_LightmapFlags: 1
m_CustomRenderQueue: -1
stringTagMap: {}
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

8
Assets/TestScenes/HDTest/Material/HDRenderLoopMaterials/anisoTest.mat.meta


fileFormatVersion: 2
guid: eaec57fbf2cf08c4e8f4b6322cb0a015
timeCreated: 1478226940
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

73
Assets/BasicRenderLoopTutorial/BasicMat_Colors.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: BasicMat_Colors
m_Shader: {fileID: 4800000, guid: 6d46db48cdecd4d4cbc2b28521fa4feb, type: 3}
m_ShaderKeywords: _EMISSION _METALLICGLOSSMAP
m_LightmapFlags: 1
m_CustomRenderQueue: -1
stringTagMap: {}
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 4e96aadeab75a4745b17d60a1fea54c5, type: 3}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 2800000, guid: 4e96aadeab75a4745b17d60a1fea54c5, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.474
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

8
Assets/BasicRenderLoopTutorial/BasicMat_Colors.mat.meta


fileFormatVersion: 2
guid: d3d4ee74007ca504baacdf86a59dd991
timeCreated: 1478093906
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

74
Assets/BasicRenderLoopTutorial/BasicMat_Glass.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: BasicMat_Glass
m_Shader: {fileID: 4800000, guid: 6d46db48cdecd4d4cbc2b28521fa4feb, type: 3}
m_ShaderKeywords: _ALPHABLEND_ON _EMISSION _METALLICGLOSSMAP
m_LightmapFlags: 1
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 894ecea3849c1417180f79a5ca555a6a, type: 3}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 2800000, guid: 894ecea3849c1417180f79a5ca555a6a, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 10
- _GlossMapScale: 1
- _Glossiness: 0.474
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 2
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 5
- _UVSec: 0
- _ZWrite: 0
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

8
Assets/BasicRenderLoopTutorial/BasicMat_Glass.mat.meta


fileFormatVersion: 2
guid: 2fee9f51314ef4046b13d8291efdbc6d
timeCreated: 1478093906
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

73
Assets/BasicRenderLoopTutorial/BasicMat_Tiles.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: BasicMat_Tiles
m_Shader: {fileID: 4800000, guid: 6d46db48cdecd4d4cbc2b28521fa4feb, type: 3}
m_ShaderKeywords: _EMISSION
m_LightmapFlags: 1
m_CustomRenderQueue: -1
stringTagMap: {}
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 57e020d5e89e349a7b1db77f3f80db54, type: 3}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.474
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

8
Assets/BasicRenderLoopTutorial/BasicMat_Tiles.mat.meta


fileFormatVersion: 2
guid: fe33d2a6bf672f44b8cc1f2da95e8454
timeCreated: 1478093906
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

12
Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs.meta


fileFormatVersion: 2
guid: 22228a1bd982b864ea6c84db2fc11dd1
timeCreated: 1478093647
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

1001
Assets/BasicRenderLoopTutorial/BasicRenderLoopScene.unity
文件差异内容过多而无法显示
查看文件

8
Assets/BasicRenderLoopTutorial/BasicRenderLoopScene.unity.meta


fileFormatVersion: 2
guid: 3b0ce1a6123f2ad4dafc215e41e43949
timeCreated: 1478094608
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

227
Assets/BasicRenderLoopTutorial/BasicRenderLoopShader.shader


// Example shader for a scriptable render loop that calculates multiple lights
// in a single forward-rendered shading pass. Uses same PBR shading model as the
// Standard shader.
//
// The parameters and inspector of the shader are the same as Standard shader,
// for easier experimentation.
Shader "RenderLoop/Basic/Standard"
{
// Properties is just a copy of Standard.shader. Our example shader does not use all of them,
// but the inspector UI expects all these to exist.
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
_GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0
[Enum(Metallic Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel ("Smoothness texture channel", Float) = 0
[Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
_MetallicGlossMap("Metallic", 2D) = "white" {}
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
_BumpMap("Normal Map", 2D) = "bump" {}
_Parallax ("Height Scale", Range (0.005, 0.08)) = 0.02
_ParallaxMap ("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
_DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec("UV Set for secondary textures", Float) = 0
[HideInInspector] _Mode("__mode", Float) = 0.0
[HideInInspector] _SrcBlend("__src", Float) = 1.0
[HideInInspector] _DstBlend("__dst", Float) = 0.0
[HideInInspector] _ZWrite("__zw", Float) = 1.0
}
SubShader
{
Tags { "RenderType" = "Opaque" "PerformanceChecks" = "False" }
LOD 300
// Include forward (base + additive) pass from regular Standard shader.
// They are not used by the scriptable render loop; only here so that
// if we turn off our example loop, then regular forward rendering kicks in
// and objects look just like with a Standard shader.
UsePass "Standard/FORWARD"
UsePass "Standard/FORWARD_DELTA"
// Multiple lights at once pass, for our example Basic render loop.
Pass
{
Tags { "LightMode" = "BasicPass" }
// Use same blending / depth states as Standard shader
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
CGPROGRAM
#pragma target 3.0
#pragma vertex vert
#pragma fragment frag
#pragma shader_feature _METALLICGLOSSMAP
#include "UnityCG.cginc"
#include "UnityStandardBRDF.cginc"
#include "UnityStandardUtils.cginc"
// Global lighting data (setup from C# code once per frame).
CBUFFER_START(GlobalLightData)
// The variables are very similar to built-in unity_LightColor, unity_LightPosition,
// unity_LightAtten, unity_SpotDirection as used by the VertexLit shaders, except here
// we use world space positions instead of view space.
half4 globalLightColor[8];
float4 globalLightPos[8];
float4 globalLightSpotDir[8];
float4 globalLightAtten[8];
int4 globalLightCount;
// Global ambient/SH probe, similar to unity_SH* built-in variables.
float4 globalSH[7];
CBUFFER_END
// Surface inputs for evaluating Standard BRDF
struct SurfaceInputData
{
half3 diffColor, specColor;
half oneMinusReflectivity, smoothness;
};
// Compute attenuation & illumination from one light
half3 EvaluateOneLight(int idx, float3 positionWS, half3 normalWS, half3 eyeVec, SurfaceInputData s)
{
// direction to light
float3 dirToLight = globalLightPos[idx].xyz;
dirToLight -= positionWS * globalLightPos[idx].w;
// distance attenuation
float att = 1.0;
float distSqr = dot(dirToLight, dirToLight);
att /= (1.0 + globalLightAtten[idx].z * distSqr);
if (globalLightPos[idx].w != 0 && distSqr > globalLightAtten[idx].w) att = 0.0; // set to 0 if outside of range
distSqr = max(distSqr, 0.000001); // don't produce NaNs if some vertex position overlaps with the light
dirToLight *= rsqrt(distSqr);
// spotlight angular attenuation
float rho = max(dot(dirToLight, globalLightSpotDir[idx].xyz), 0.0);
float spotAtt = (rho - globalLightAtten[idx].x) * globalLightAtten[idx].y;
att *= saturate(spotAtt);
// Super simple diffuse lighting instead of PBR would be this:
//half ndotl = max(dot(normalWS, dirToLight), 0.0);
//half3 color = ndotl * s.diffColor * globalLightColor[idx].rgb;
//return color * att;
// Fill in light & indirect structures, and evaluate Standard BRDF
UnityLight light;
light.color = globalLightColor[idx].rgb * att;
light.dir = dirToLight;
UnityIndirect indirect;
indirect.diffuse = 0;
indirect.specular = 0;
half4 c = BRDF1_Unity_PBS(s.diffColor, s.specColor, s.oneMinusReflectivity, s.smoothness, normalWS, -eyeVec, light, indirect);
return c.rgb;
}
// Evaluate 2nd order spherical harmonics, given normalized world space direction.
// Similar to ShadeSH9 in UnityCG.cginc
half3 EvaluateSH(half3 n)
{
half3 res;
half4 normal = half4(n, 1);
// Linear (L1) + constant (L0) polynomial terms
res.r = dot(globalSH[0], normal);
res.g = dot(globalSH[1], normal);
res.b = dot(globalSH[2], normal);
// 4 of the quadratic (L2) polynomials
half4 vB = normal.xyzz * normal.yzzx;
res.r += dot(globalSH[3], vB);
res.g += dot(globalSH[4], vB);
res.b += dot(globalSH[5], vB);
// Final (5th) quadratic (L2) polynomial
half vC = normal.x*normal.x - normal.y*normal.y;
res += globalSH[6].rgb * vC;
return res;
}
// Vertex shader
struct v2f
{
float2 uv : TEXCOORD0;
float3 positionWS : TEXCOORD1;
float3 normalWS : TEXCOORD2;
float4 hpos : SV_POSITION;
};
float4 _MainTex_ST;
v2f vert(appdata_base v)
{
v2f o;
o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);
o.hpos = UnityObjectToClipPos(v.vertex);
o.positionWS = mul(unity_ObjectToWorld, v.vertex).xyz;
o.normalWS = UnityObjectToWorldNormal(v.normal);
return o;
}
sampler2D _MainTex;
sampler2D _MetallicGlossMap;
float _Metallic;
float _Glossiness;
// Fragment shader
half4 frag(v2f i) : SV_Target
{
i.normalWS = normalize(i.normalWS);
half3 eyeVec = normalize(i.positionWS - _WorldSpaceCameraPos);
// Sample textures
half4 diffuseAlbedo = tex2D(_MainTex, i.uv);
half2 metalSmooth;
#ifdef _METALLICGLOSSMAP
metalSmooth = tex2D(_MetallicGlossMap, i.uv).ra;
#else
metalSmooth.r = _Metallic;
metalSmooth.g = _Glossiness;
#endif
// Fill in surface input structure
SurfaceInputData s;
s.diffColor = DiffuseAndSpecularFromMetallic(diffuseAlbedo.rgb, metalSmooth.x, s.specColor, s.oneMinusReflectivity);
s.smoothness = metalSmooth.y;
// Ambient lighting
half4 color = half4(0,0,0, diffuseAlbedo.a);
UnityLight light;
light.color = 0;
light.dir = 0;
UnityIndirect indirect;
indirect.diffuse = EvaluateSH(i.normalWS);
indirect.specular = 0;
color.rgb += BRDF1_Unity_PBS(s.diffColor, s.specColor, s.oneMinusReflectivity, s.smoothness, i.normalWS, -eyeVec, light, indirect);
// Add illumination from all lights
for (int il = 0; il < globalLightCount.x; ++il)
{
color.rgb += EvaluateOneLight(il, i.positionWS, i.normalWS, eyeVec, s);
}
return color;
}
ENDCG
}
}
CustomEditor "StandardShaderGUI"
}

9
Assets/BasicRenderLoopTutorial/BasicRenderLoopShader.shader.meta


fileFormatVersion: 2
guid: 6d46db48cdecd4d4cbc2b28521fa4feb
timeCreated: 1478093850
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

9
Assets/BasicRenderLoopTutorial/Textures.meta


fileFormatVersion: 2
guid: 7cb98251ab4712a4fafbd54b0606ea87
folderAsset: yes
timeCreated: 1478162472
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

14
Assets/BasicRenderLoopTutorial/Textures/ColorGrid.png

之前 之后
宽度: 32  |  高度: 32  |  大小: 3.7 KiB

31
Assets/BasicRenderLoopTutorial/Textures/ColorGrid.png.meta


fileFormatVersion: 2
guid: 4e96aadeab75a4745b17d60a1fea54c5
TextureImporter:
importerVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 1
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.250000
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 1
generateCubemap: 0
textureFormat: -1
maxTextureSize: 1024
textureSettings:
filterMode: -1
aniso: -1
mipBias: -1.000000
wrapMode: -1
nPOTScale: 1
lightmap: 0
textureType: 0
buildTargetSettings: []

969
Assets/BasicRenderLoopTutorial/Textures/Glass.tif
文件差异内容过多而无法显示
查看文件

56
Assets/BasicRenderLoopTutorial/Textures/Glass.tif.meta


fileFormatVersion: 2
guid: 894ecea3849c1417180f79a5ca555a6a
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 1
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 2
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 1
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 7
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: -1
maxTextureSize: 512
textureSettings:
filterMode: 1
aniso: 1
mipBias: 0
wrapMode: 0
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

338
Assets/BasicRenderLoopTutorial/Textures/TilesDiffuse.tif
文件差异内容过多而无法显示
查看文件

56
Assets/BasicRenderLoopTutorial/Textures/TilesDiffuse.tif.meta


fileFormatVersion: 2
guid: 57e020d5e89e349a7b1db77f3f80db54
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 1
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 2
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 1
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 7
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: -1
maxTextureSize: 1024
textureSettings:
filterMode: 1
aniso: 1
mipBias: 0
wrapMode: 0
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

102
Assets/BasicRenderLoopTutorial/Textures/TilesNormal.png

之前 之后
宽度: 256  |  高度: 256  |  大小: 22 KiB

100
Assets/BasicRenderLoopTutorial/Textures/TilesNormal.png.meta


fileFormatVersion: 2
guid: 248293ea5aa814673970690d6f0707f1
timeCreated: 1468422114
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 4
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 2
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 1
externalNormalMap: 1
heightScale: 0.213871
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: -1
maxTextureSize: 1024
textureSettings:
filterMode: 1
aniso: 1
mipBias: 0
wrapMode: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 1
textureShape: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- buildTarget: DefaultTexturePlatform
maxTextureSize: 1024
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
- buildTarget: iPhone
maxTextureSize: 1024
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
- buildTarget: Standalone
maxTextureSize: 1024
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
- buildTarget: tvOS
maxTextureSize: 1024
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
- buildTarget: WebGL
maxTextureSize: 1024
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

178
Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs


using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
// Very basic scriptable rendering loop example:
// - Use with BasicRenderLoopShader.shader (the loop expects "BasicPass" pass type to exist)
// - Supports up to 8 enabled lights in the scene (directional, point or spot)
// - Does the same physically based BRDF as the Standard shader
// - No shadows
// - This loop also does not setup lightmaps, light probes, reflection probes or light cookies
[ExecuteInEditMode]
public class BasicRenderLoop : MonoBehaviour
{
private ShaderPassName shaderPassBasic;
public void OnEnable ()
{
shaderPassBasic = new ShaderPassName ("BasicPass");
RenderLoop.renderLoopDelegate += Render;
}
public void OnDisable ()
{
RenderLoop.renderLoopDelegate -= Render;
}
// Main entry point for our scriptable render loop
bool Render (Camera[] cameras, RenderLoop loop)
{
foreach (var camera in cameras)
{
// Culling
CullingParameters cullingParams;
if (!CullResults.GetCullingParameters (camera, out cullingParams))
continue;
CullResults cull = CullResults.Cull (ref cullingParams, loop);
// Setup camera for rendering (sets render target, view/projection matrices and other
// per-camera built-in shader variables).
loop.SetupCameraProperties (camera);
// Setup global lighting shader variables
SetupLightShaderVariables (cull.visibleLights, loop);
// Draw opaque objects using BasicPass shader pass
var settings = new DrawRendererSettings (cull, camera, shaderPassBasic);
settings.sorting.sortOptions = SortOptions.SortByMaterialThenMesh;
settings.inputFilter.SetQueuesOpaque ();
loop.DrawRenderers (ref settings);
// Draw skybox
loop.DrawSkybox (camera);
// Draw transparent objects using BasicPass shader pass
settings.sorting.sortOptions = SortOptions.BackToFront; // sort back to front
settings.inputFilter.SetQueuesTransparent ();
loop.DrawRenderers (ref settings);
loop.Submit ();
}
return true;
}
// Setup lighting variables for shader to use
static void SetupLightShaderVariables (VisibleLight[] lights, RenderLoop loop)
{
// We only support up to 8 visible lights here. More complex approaches would
// be doing some sort of per-object light setups, but here we go for simplest possible
// approach.
const int kMaxLights = 8;
// Just take first 8 lights. Possible improvements: sort lights by intensity or distance
// to the viewer, so that "most important" lights in the scene are picked, and not the 8
// that happened to be first.
int lightCount = Mathf.Min (lights.Length, kMaxLights);
// Prepare light data
Vector4[] lightColors = new Vector4[kMaxLights];
Vector4[] lightPositions = new Vector4[kMaxLights];
Vector4[] lightSpotDirections = new Vector4[kMaxLights];
Vector4[] lightAtten = new Vector4[kMaxLights];
for (var i = 0; i < lightCount; ++i)
{
VisibleLight light = lights[i];
lightColors[i] = light.finalColor;
if (light.lightType == LightType.Directional)
{
// light position for directional lights is: (-direction, 0)
var dir = light.localToWorld.GetColumn (2);
lightPositions[i] = new Vector4 (-dir.x, -dir.y, -dir.z, 0);
}
else
{
// light position for point/spot lights is: (position, 1)
var pos = light.localToWorld.GetColumn (3);
lightPositions[i] = new Vector4 (pos.x, pos.y, pos.z, 1);
}
// attenuation set in a way where distance attenuation can be computed:
// float lengthSq = dot(toLight, toLight);
// float atten = 1.0 / (1.0 + lengthSq * LightAtten[i].z);
// and spot cone attenuation:
// float rho = max (0, dot(normalize(toLight), SpotDirection[i].xyz));
// float spotAtt = (rho - LightAtten[i].x) * LightAtten[i].y;
// spotAtt = saturate(spotAtt);
// and the above works for all light types, i.e. spot light code works out
// to correct math for point & directional lights as well.
float rangeSq = light.range * light.range;
float quadAtten = (light.lightType == LightType.Directional) ? 0.0f : 25.0f / rangeSq;
// spot direction & attenuation
if (light.lightType == LightType.Spot)
{
var dir = light.localToWorld.GetColumn (2);
lightSpotDirections[i] = new Vector4 (-dir.x, -dir.y, -dir.z, 0);
float radAngle = Mathf.Deg2Rad * light.spotAngle;
float cosTheta = Mathf.Cos (radAngle * 0.25f);
float cosPhi = Mathf.Cos (radAngle * 0.5f);
float cosDiff = cosTheta - cosPhi;
lightAtten[i] = new Vector4 (cosPhi, (cosDiff != 0.0f) ? 1.0f / cosDiff : 1.0f, quadAtten, rangeSq);
}
else
{
// non-spot light
lightSpotDirections[i] = new Vector4 (0, 0, 1, 0);
lightAtten[i] = new Vector4 (-1, 1, quadAtten, rangeSq);
}
}
// ambient lighting spherical harmonics values
const int kSHCoefficients = 7;
Vector4[] shConstants = new Vector4[kSHCoefficients];
SphericalHarmonicsL2 ambientSH = RenderSettings.ambientProbe * RenderSettings.ambientIntensity;
GetShaderConstantsFromNormalizedSH (ref ambientSH, shConstants);
// setup global shader variables to contain all the data computed above
CommandBuffer cmd = new CommandBuffer();
cmd.SetGlobalVectorArray ("globalLightColor", lightColors);
cmd.SetGlobalVectorArray ("globalLightPos", lightPositions);
cmd.SetGlobalVectorArray ("globalLightSpotDir", lightSpotDirections);
cmd.SetGlobalVectorArray ("globalLightAtten", lightAtten);
cmd.SetGlobalVector ("globalLightCount", new Vector4 (lightCount, 0, 0, 0));
cmd.SetGlobalVectorArray ("globalSH", shConstants);
loop.ExecuteCommandBuffer (cmd);
cmd.Dispose ();
}
// Prepare L2 spherical harmonics values for efficient evaluation in a shader
static void GetShaderConstantsFromNormalizedSH (ref SphericalHarmonicsL2 ambientProbe, Vector4[] outCoefficients)
{
for (int channelIdx = 0; channelIdx < 3; ++channelIdx)
{
// Constant + Linear
// In the shader we multiply the normal is not swizzled, so it's normal.xyz.
// Swizzle the coefficients to be in { x, y, z, DC } order.
outCoefficients[channelIdx].x = ambientProbe[channelIdx, 3];
outCoefficients[channelIdx].y = ambientProbe[channelIdx, 1];
outCoefficients[channelIdx].z = ambientProbe[channelIdx, 2];
outCoefficients[channelIdx].w = ambientProbe[channelIdx, 0] - ambientProbe[channelIdx, 6];
// Quadratic polynomials
outCoefficients[channelIdx + 3].x = ambientProbe[channelIdx, 4];
outCoefficients[channelIdx + 3].y = ambientProbe[channelIdx, 5];
outCoefficients[channelIdx + 3].z = ambientProbe[channelIdx, 6] * 3.0f;
outCoefficients[channelIdx + 3].w = ambientProbe[channelIdx, 7];
}
// Final quadratic polynomial
outCoefficients[6].x = ambientProbe[0, 8];
outCoefficients[6].y = ambientProbe[1, 8];
outCoefficients[6].z = ambientProbe[2, 8];
outCoefficients[6].w = 1.0f;
}
}
正在加载...
取消
保存