From dd03169ae8a72057b31aee98d04f2f831aa39815 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 20 Jul 2020 16:35:07 -0700 Subject: [PATCH 001/209] Implement clipping and culling (does not consider view frustum corners) --- .../ShaderLibrary/Macros.hlsl | 1 + .../Runtime/Lighting/LightLoop/LightLoop.cs | 9 +- .../Lighting/LightLoop/scrbound.compute | 529 +++++++++++++++++- 3 files changed, 533 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl index c318581e16b..3981ef50a88 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl @@ -46,6 +46,7 @@ #define HALF_MIN_SQRT 0.0078125 // 2^-7 == sqrt(HALF_MIN), useful for ensuring HALF_MIN after x^2 #define HALF_MAX 65504.0 #define UINT_MAX 0xFFFFFFFFu +#define INT_MAX 0x7FFFFFFF #ifdef SHADER_API_GLES diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index eb8ef22ab93..f171399ed1c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -1780,9 +1780,12 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig } else if (gpuLightType == GPULightType.Point) { - Vector3 vx = xAxisVS; - Vector3 vy = yAxisVS; - Vector3 vz = zAxisVS; + // Construct a view-space axis-aligned bounding cube around the bounding sphere. + // This allows us to utilize the same polygon clipping technique for all lights. + // Non-axis-aligned vectors may result in a larger screen-space AABB. + Vector3 vx = new Vector3(1, 0, 0); + Vector3 vy = new Vector3(0, 1, 0); + Vector3 vz = new Vector3(0, 0, 1); bound.center = positionVS; bound.boxAxisX = vx * range; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index be07511307d..355de58e942 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -11,6 +11,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" +// #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch StructuredBuffer g_data : register( t0 ); @@ -20,6 +21,288 @@ StructuredBuffer g_data : register( t0 ); // output buffer RWStructuredBuffer g_vBoundsBuffer : register( u0 ); +#define DUMB_COMPILER +// #define USE_WAVE_INTRINSICS // We use TGSM and atomic operations if wave intrinsics are not supported + +#ifdef Z_BINNING + +// Computes r=(n/d) and rounds the result towards the largest adjacent integer. +uint DivRoundUp(uint n, uint d) +{ + return (n + d - 1) / d; // No division by 0 checks +} + +// Returns the location of the N-th set bit starting from the lowest order bit and working upward. +// Slow implementation - do not use for large bit sets. +// Could be optimized - see https://graphics.stanford.edu/~seander/bithacks.html +uint NthBitLow(uint value, uint n) +{ + uint b = -1; // Consistent with the behavior of firstbitlow() + uint c = countbits(value); + + if (n < c) // Validate inputs + { + uint r = n + 1; // Compute the number of remaining bits + + do + { + uint f = firstbitlow(value >> (b + 1)); // Find the next set bit + b += f + r; // Make a guess (assume all [b+f+1,b+f+r] bits are set) + c = countbits(value << (32 - (b + 1))); // Count the number of bits actually set + r = (n + 1) - c; // Compute the number of remaining bits + } while (r > 0); + } + + return b; +} + +// Clipping a plane by a cube may produce a hexagon (6-gon). +// Clipping a hexagon by 4 planes may produce a decagon (10-gon). +#define MAX_CLIP_VERTS (10) +#define NUM_EDGES (12) +#define NUM_VERTS (8) +#define NUM_FACES (6) +#define NUM_PLANES (6) +#define THREADS_PER_LIGHT (4) +#define THREADS_PER_GROUP (64) +#define LIGHTS_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_LIGHT) +#define VERTS_PER_GROUP (NUM_VERTS * LIGHTS_PER_GROUP) +#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_LIGHT) +#define FACES_PER_THREAD DivRoundUp(NUM_FACES, THREADS_PER_LIGHT) + +// All planes and faces are always in the standard order (see below). +#define FACE_LEFT (1 << 0) // x = -1 +#define FACE_RIGHT (1 << 1) // x = +1 +#define FACE_FRONT (1 << 2) // y = -1 +#define FACE_BACK (1 << 3) // y = +1 +#define FACE_TOP (1 << 4) // z = -1 +#define FACE_BOTTOM (1 << 5) // z = +1 +#define FACE_MASK ((1 << NUM_FACES) - 1) + +// TODO: the compiler generates 'tbuffer_load_format_x' instructions +// when we access the look-up tables. Can we avoid this? + +// All vertices are always in the standard order (see below). +static const uint s_FaceMasksOfVerts[NUM_VERTS] = +{ + FACE_LEFT | FACE_FRONT | FACE_TOP, // 0: (-1, -1, -1) + FACE_RIGHT | FACE_FRONT | FACE_TOP, // 1: (+1, -1, -1) + FACE_RIGHT | FACE_BACK | FACE_TOP, // 2: (+1, +1, -1) + FACE_LEFT | FACE_BACK | FACE_TOP, // 3: (-1, +1, -1) + FACE_LEFT | FACE_FRONT | FACE_BOTTOM, // 4: (-1, -1, +1) + FACE_RIGHT | FACE_FRONT | FACE_BOTTOM, // 5: (+1, -1, +1) + FACE_RIGHT | FACE_BACK | FACE_BOTTOM, // 6: (+1, +1, +1) + FACE_LEFT | FACE_BACK | FACE_BOTTOM // 7: (-1, +1, +1) +}; + +// CCW order (starting with the LSB) of vertices for each face (w.r.t. its normal), +// with normals pointing in the interior of the volume. +static const uint s_VertMasksOfFaces[NUM_FACES] = +{ + 3 << 9 | 7 << 6 | 4 << 3 | 0 << 0, // 0: FACE_LEFT + 5 << 9 | 6 << 6 | 2 << 3 | 1 << 0, // 1: FACE_RIGHT + 4 << 9 | 5 << 6 | 1 << 3 | 0 << 0, // 2: FACE_FRONT + 2 << 9 | 6 << 6 | 7 << 3 | 3 << 0, // 3: FACE_BACK + 1 << 9 | 2 << 6 | 3 << 3 | 0 << 0, // 4: FACE_TOP + 7 << 9 | 6 << 6 | 5 << 3 | 4 << 0 // 5: FACE_BOTTOM +}; + +// 5 arrays * 128 elements * 4 bytes each = 2560 bytes. +groupshared float gs_HapVertsX[VERTS_PER_GROUP]; +groupshared float gs_HapVertsY[VERTS_PER_GROUP]; +groupshared float gs_HapVertsZ[VERTS_PER_GROUP]; +groupshared float gs_HapVertsW[VERTS_PER_GROUP]; +groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) + +#ifndef USE_WAVE_INTRINSICS +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_CullClipFaceMasks[LIGHTS_PER_GROUP]; // 6 faces each (HLSL does not support small data types) + +// 6 arrays * 16 elements * 4 bytes each = 384 bytes. +// Note that these are actually floats reinterpreted as uints. +// The reason is because floating-point atomic operations are not supported. +groupshared uint gs_RapAaBbMinPtX[LIGHTS_PER_GROUP]; +groupshared uint gs_RapAaBbMaxPtX[LIGHTS_PER_GROUP]; +groupshared uint gs_RapAaBbMinPtY[LIGHTS_PER_GROUP]; +groupshared uint gs_RapAaBbMaxPtY[LIGHTS_PER_GROUP]; +groupshared uint gs_RapAaBbMinPtZ[LIGHTS_PER_GROUP]; +groupshared uint gs_RapAaBbMaxPtZ[LIGHTS_PER_GROUP]; +#endif // USE_WAVE_INTRINSICS + +// Returns 'true' if it manages to cull the face. +bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) +{ + uint cullMaskOfFace = FACE_MASK; // Initially behind + uint vertMaskOfFace = s_VertMasksOfFaces[f]; + + for (int j = 0; j < 4; j++) + { + uint v = BitFieldExtract(vertMaskOfFace, 3 * j, 3); + // Non-zero if ALL the vertices are behind any of the planes. + cullMaskOfFace &= behindMasksOfVerts[v]; + } + + return (cullMaskOfFace != 0); +} + +struct ClipVertex +{ + float4 pt; // Homogeneous coordinate after perspective + float bc; // Boundary coordinate with respect to the plane 'p' +}; + +ClipVertex CreateClipVertex(uint p, float4 v) +{ + bool evenPlane = (p % 2) == 0; + + float c = v[p / 2]; + float w = v.w; + + ClipVertex cv; + + cv.pt = v; + cv.bc = evenPlane ? c : w - c; // dot(PlaneEquation, HapVertex); + + return cv; +} + +float4 IntersectEdgeAgainstPlane(ClipVertex v0, ClipVertex v1) +{ + float alpha = saturate(v0.bc * rcp(v0.bc - v1.bc)); // Guaranteed to lie between 0 and 1 + + return lerp(v0.pt, v1.pt, alpha); +} + +void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, + inout float4 vertRingBuffer[MAX_CLIP_VERTS], + out uint dstBegin, out uint dstSize) +{ + dstBegin = srcBegin + srcSize; // Start at the end; we don't use modular arithmetic here + dstSize = 0; + + ClipVertex tailVert = CreateClipVertex(p, vertRingBuffer[(srcBegin + srcSize - 1) % MAX_CLIP_VERTS]); + +#ifdef DUMB_COMPILER + uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; + uint modDstIdx = dstBegin % MAX_CLIP_VERTS; +#endif + + for (uint k = srcBegin; k < (srcBegin + srcSize); k++) + { + #ifndef DUMB_COMPILER + uint modSrcIdx = k % MAX_CLIP_VERTS; + #endif + ClipVertex leadVert = CreateClipVertex(p, vertRingBuffer[modSrcIdx]); + + // Execute Blinn's line clipping algorithm. + // Classify the line segment. 4 cases: + // 0. v0 out, v1 out -> add nothing + // 1. v0 in, v1 out -> add intersection + // 2. v0 out, v1 in -> add intersection, add v1 + // 3. v0 in, v1 in -> add v1 + // (bc >= 0) <-> in, (bc < 0) <-> out. Beware of the signed zero. + + if ((tailVert.bc >= 0) != (leadVert.bc >= 0)) + { + // The line segment is guaranteed to cross the plane. + float4 clipVert = IntersectEdgeAgainstPlane(tailVert, leadVert); + #ifndef DUMB_COMPILER + uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; + #endif + vertRingBuffer[modDstIdx] = clipVert; + #ifdef DUMB_COMPILER + dstSize++; + modDstIdx++; + modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; + #endif + } + + if (leadVert.bc >= 0) + { + #ifndef DUMB_COMPILER + uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; + #endif + vertRingBuffer[modDstIdx] = leadVert.pt; + #ifdef DUMB_COMPILER + dstSize++; + modDstIdx++; + modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; + #endif + } + + #ifdef DUMB_COMPILER + modSrcIdx++; + modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; + #endif + tailVert = leadVert; // Avoid recomputation and overwriting the vertex in the ring buffer + } +} + +void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_VERTS], uint firstVertexOffset, + inout float3 rapAaBbMinPt, inout float3 rapAaBbMaxPt) +{ + float4 vertRingBuffer[MAX_CLIP_VERTS]; + uint srcBegin = 0, srcSize = 4; + + uint clipMaskOfFace = 0; // Initially in front + uint vertMaskOfFace = s_VertMasksOfFaces[f]; + + for (int j = 0; j < 4; j++) + { + uint v = BitFieldExtract(vertMaskOfFace, 3 * j, 3); + // Non-zero if ANY of the vertices are behind any of the planes. + clipMaskOfFace |= behindMasksOfVerts[v]; + + // Note that not all edges may require clipping. However, + // filtering the vertex list is somewhat expensive, so we currently don't do it. + vertRingBuffer[j].x = gs_HapVertsX[firstVertexOffset + v]; + vertRingBuffer[j].y = gs_HapVertsY[firstVertexOffset + v]; + vertRingBuffer[j].z = gs_HapVertsZ[firstVertexOffset + v]; + vertRingBuffer[j].w = gs_HapVertsW[firstVertexOffset + v]; + } + + const uint numPlanesToClipAgainst = countbits(clipMaskOfFace); // [1, 6] + + // Sutherland-Hodgeman polygon clipping algorithm. + // It works by clipping the entire polygon against one clipping plane at a time. + for (uint j = 0; j < numPlanesToClipAgainst; j++) + { + uint p = firstbitlow(clipMaskOfFace); + + uint dstBegin, dstSize; + ClipPolygonAgainstPlane(p, srcBegin, srcSize, vertRingBuffer, dstBegin, dstSize); + + srcBegin = dstBegin; + srcSize = dstSize; + + clipMaskOfFace ^= 1 << p; // Clear the bit to continue using firstbitlow() + } + +#ifdef DUMB_COMPILER + uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; +#endif + + for (int j = srcBegin; j < (srcBegin + srcSize); j++) + { + #ifndef DUMB_COMPILER + uint modSrcIdx = j % MAX_CLIP_VERTS; + #endif + + float4 hapVert = vertRingBuffer[modSrcIdx]; + float3 rapVert = hapVert.xyz * rcp(hapVert.w); + + rapAaBbMinPt = min(rapAaBbMinPt, rapVert); + rapAaBbMaxPt = max(rapAaBbMaxPt, rapVert); + + #ifdef DUMB_COMPILER + modSrcIdx++; + modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; + #endif + } +} + +#else // !Z_BINNING + #define MAX_PNTS 9 // strictly this should be 10=6+4 but we get more wavefronts and 10 seems to never hit (fingers crossed) // However, worst case the plane that would be skipped if such an extreme case ever happened would be backplane // clipping gets skipped which doesn't cause any errors. @@ -39,6 +322,7 @@ void CalcBound(out bool2 bIsMinValid, out bool2 bIsMaxValid, out float2 vMin, ou #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl" +#endif // Z_BINNING [numthreads(NR_THREADS, 1, 1)] void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) @@ -54,13 +338,248 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI unsigned int g = groupID; unsigned int t = threadID; - const int subLigt = (int) (t/8); - const int lgtIndex = subLigt+(int) g*8; - const int sideIndex = (int) (t%8); + const int subLigt = (uint) (t/8); + const int lgtIndex = subLigt+(uint) g*8; + const int sideIndex = (uint) (t%8); const int eyeAdjustedLgtIndex = GenerateLightCullDataIndex(lgtIndex, g_iNrVisibLights, eyeIndex); SFiniteLightBound lgtDat = g_data[eyeAdjustedLgtIndex]; +#ifdef Z_BINNING + //********************************************************************************************** + // The goal of this program is to compute the AABB of the light in the NDC space ([0, 1] range). + // The light is represented by a convex volume (a cuboid) with 6 faces (planar quads) and 8 vertices. + // + // Since a light volume may be partially off-screen, we must clip it before computing the AABB. + // Clipping the resulting AABB (rather than the light volume itself) may result in a loose AABB. + // + // To avoid having to deal with toroidal properties of the perspective transform, + // we perform clipping using the homogeneous (projective) post-perspective coordinates. + // This clipping method in described in Blinn's paper titled "Line Clipping". + // + // The algorithm processes a light on 4 threads. While all 6 faces may require clipping in the + // worst case, clipping more than 4 faces is very uncommon (typically, we clip 0, 3 or 4). + // Note that some faces may require culling rather than clipping (the former is simpler). + // + // It's important to realize that face culling may end up culling 5 (or even all 6) faces. + // This means that the clipped light volume may be reduced to a single polygon, or nothing at all. + // (Imagine a view volume completely or partially inside a light volume). + // Therefore, we must perform view-volume-corner-inside-light-volume tests. + // + // + // Notation: + // rbp - real (3D) coordinates before perspective + // hbp - hom. (4D) coordinates before perspective + // hap - hom. (4D) coordinates after perspective + // rap - real (3D) coordinates after perspective (after division by w) + // ********************************************************************************************* + + const uint groupLocalLightIndex = t / THREADS_PER_LIGHT; + const uint firstVertexOffset = NUM_VERTS * groupLocalLightIndex; + + const float2 scale = lgtDat.scaleXY.xy; + const float3 rbpC = lgtDat.center.xyz; + const float3 rbpX = lgtDat.boxAxisX.xyz; + const float3 rbpY = lgtDat.boxAxisY.xyz; + const float3 rbpZ = lgtDat.boxAxisZ.xyz; + +#ifndef USE_WAVE_INTRINSICS + // Initialize the TGSM. All threads write the same value -> no data races. + // The hardware will coalesce the writes. + gs_CullClipFaceMasks[groupLocalLightIndex] = 0; // Initially inside + gs_RapAaBbMinPtX[groupLocalLightIndex] = asuint(1.0f); + gs_RapAaBbMaxPtX[groupLocalLightIndex] = asuint(0.0f); + gs_RapAaBbMinPtY[groupLocalLightIndex] = asuint(1.0f); + gs_RapAaBbMaxPtY[groupLocalLightIndex] = asuint(0.0f); + gs_RapAaBbMinPtZ[groupLocalLightIndex] = asuint(1.0f); + gs_RapAaBbMaxPtZ[groupLocalLightIndex] = asuint(0.0f); +#endif // USE_WAVE_INTRINSICS + + float3 rapAaBbMinPt = 1; + float3 rapAaBbMaxPt = 0; + + // We must determine whether we have to clip or cull any of the faces. + // If all vertices of a face are inside with respect to all the culling planes, + // we can trivially accept that face. If all vertices of a face are behind + // any single plane, we can trivially reject (cull) that face. + uint cullClipFaceMask = 0; // Initially inside + + // (1) Compute the vertices of the light volume. + for (uint i = 0; i < VERTS_PER_THREAD; i++) + { + uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + + // rbpVerts[0] = rbpC - rbpX * scale.x - rbpY * scale.y - rbpZ; // (-1, -1, -1) + // rbpVerts[1] = rbpC + rbpX * scale.x - rbpY * scale.y - rbpZ; // (+1, -1, -1) + // rbpVerts[2] = rbpC + rbpX * scale.x + rbpY * scale.y - rbpZ; // (+1, +1, -1) + // rbpVerts[3] = rbpC - rbpX * scale.x + rbpY * scale.y - rbpZ; // (-1, +1, -1) + // rbpVerts[4] = rbpC - rbpX - rbpY + rbpZ; // (-1, -1, +1) + // rbpVerts[5] = rbpC + rbpX - rbpY + rbpZ; // (+1, -1, +1) + // rbpVerts[6] = rbpC + rbpX + rbpY + rbpZ; // (+1, +1, +1) + // rbpVerts[7] = rbpC - rbpX + rbpY + rbpZ; // (-1, +1, +1) + + float3 m; // See the comment above + + m.x = (countbits(v % 4) == 1) ? 1 : -1; + m.y = (v & 2 != 0) ? 1 : -1; + m.z = (v >= 4) ? 1 : -1; + + m.xy *= (v >= 4) ? 1 : scale; + + float3 rbpVert = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; + float4 hapVert = mul(g_mProjection, float4(rbpVert, 1)); + + // Make sure the W component is strictly positive. + // It is helpful in order to simplify clipping and to avoid perspective division by 0. + float w = hapVert.w; + float s = (w >= 0) ? 1 : -1; + + // Transform the X and Y components: [-w, w] -> [0, w]. + hapVert.x = (0.5 * s) * hapVert.x + ((0.5 * s) * w); + hapVert.y = (0.5 * s) * hapVert.y + ((0.5 * s) * w); + hapVert.z = s * hapVert.z; + hapVert.w = max(abs(w), FLT_MIN); + + // For each vertex, we must determine whether it is within the bounds. + // For culling and clipping, we must know, per culling plane, whether the vertex + // is in the positive or the negative half-space. + uint behindMask = 0; // Initially in front + + // Consider the vertex to be inside the view volume if: + // 0 <= x <= w + // 0 <= y <= w + // 0 <= z <= w + w = hapVert.w; + + for (uint j = 0; j < (NUM_PLANES / 2); j++) + { + behindMask |= (hapVert[j] < 0 ? 1 : 0) << (2 * j + 0); // Planes crossing '0' + behindMask |= (hapVert[j] > w ? 1 : 0) << (2 * j + 1); // Planes crossing 'w' + } + + if (behindMask == 0) // Inside? + { + float3 rapVert = hapVert.xyz * rcp(hapVert.w); + + rapAaBbMinPt = min(rapAaBbMinPt, rapVert); + rapAaBbMaxPt = max(rapAaBbMaxPt, rapVert); + } + else // Outside + { + cullClipFaceMask |= s_FaceMasksOfVerts[v]; + } + + gs_HapVertsX[firstVertexOffset + v] = hapVert.x; + gs_HapVertsY[firstVertexOffset + v] = hapVert.y; + gs_HapVertsZ[firstVertexOffset + v] = hapVert.z; + gs_HapVertsW[firstVertexOffset + v] = hapVert.w; + gs_BehindMasksOfVerts[firstVertexOffset + v] = behindMask; + } + +#ifdef USE_WAVE_INTRINSICS + // ... +#else + InterlockedOr(gs_CullClipFaceMasks[groupLocalLightIndex], cullClipFaceMask); + + GroupMemoryBarrierWithGroupSync(); + + cullClipFaceMask = gs_CullClipFaceMasks[groupLocalLightIndex]; +#endif + + if (cullClipFaceMask != 0) + { + // The light may be partially outside the view volume. + } + + uint behindMasksOfVerts[NUM_VERTS]; + + for (uint i = 0; i < NUM_VERTS; i++) + { + behindMasksOfVerts[i] = gs_BehindMasksOfVerts[firstVertexOffset + i]; + } + + // (2) Cull the faces. + const uint cullFaceMask = cullClipFaceMask; + const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] + + for (uint i = 0; i < FACES_PER_THREAD; i++) + { + uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + + if (n < numFacesToCull) + { + uint f = NthBitLow(cullFaceMask, n); + + if (TryCullFace(f, behindMasksOfVerts)) + { + cullClipFaceMask ^= 1 << f; // Clear the bit + } + } + } + +#ifdef USE_WAVE_INTRINSICS + // ... +#else + InterlockedAnd(gs_CullClipFaceMasks[groupLocalLightIndex], cullClipFaceMask); + + GroupMemoryBarrierWithGroupSync(); + + cullClipFaceMask = gs_CullClipFaceMasks[groupLocalLightIndex]; +#endif + + // (3) Clip the faces. + const uint clipFaceMask = cullClipFaceMask; + const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] + + for (uint i = 0; i < FACES_PER_THREAD; i++) + { + uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + + if (n < numFacesToCull) + { + uint f = NthBitLow(clipFaceMask, n); + + ClipFaceAgainstViewVolumeAndUpdateAaBb(f, behindMasksOfVerts, firstVertexOffset, + rapAaBbMinPt, rapAaBbMaxPt); + } + } + +#ifdef USE_WAVE_INTRINSICS + // ... +#else + // Integer comparison works for floating-point numbers as long as the sign bit is 0. + // We must take care of the signed zero ourselves. + InterlockedMin(gs_RapAaBbMinPtX[groupLocalLightIndex], asuint(rapAaBbMinPt.x) & INT_MAX); + InterlockedMax(gs_RapAaBbMaxPtX[groupLocalLightIndex], asuint(rapAaBbMaxPt.x) & INT_MAX); + InterlockedMin(gs_RapAaBbMinPtY[groupLocalLightIndex], asuint(rapAaBbMinPt.y) & INT_MAX); + InterlockedMax(gs_RapAaBbMaxPtY[groupLocalLightIndex], asuint(rapAaBbMaxPt.y) & INT_MAX); + InterlockedMin(gs_RapAaBbMinPtZ[groupLocalLightIndex], asuint(rapAaBbMinPt.z) & INT_MAX); + InterlockedMax(gs_RapAaBbMaxPtZ[groupLocalLightIndex], asuint(rapAaBbMaxPt.z) & INT_MAX); + + GroupMemoryBarrierWithGroupSync(); + + rapAaBbMinPt.x = asfloat(gs_RapAaBbMinPtX[groupLocalLightIndex]); + rapAaBbMaxPt.x = asfloat(gs_RapAaBbMaxPtX[groupLocalLightIndex]); + rapAaBbMinPt.y = asfloat(gs_RapAaBbMinPtY[groupLocalLightIndex]); + rapAaBbMaxPt.y = asfloat(gs_RapAaBbMaxPtY[groupLocalLightIndex]); + rapAaBbMinPt.z = asfloat(gs_RapAaBbMinPtZ[groupLocalLightIndex]); + rapAaBbMaxPt.z = asfloat(gs_RapAaBbMaxPtZ[groupLocalLightIndex]); +#endif // USE_WAVE_INTRINSICS + + if (t % THREADS_PER_LIGHT == 0) + { + // Each light's AABB is represented by two float3s, the min and max of the box. + // And for stereo, we have two sets of lights. Therefore, each eye has a set of mins, followed by + // a set of maxs, and each set is equal to g_iNrVisibLights. + const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex); + + float minLinearDepth = -1, maxLinearDepth = -1; // TODO + + g_vBoundsBuffer[boundsIndices.min] = float4(rapAaBbMinPt, minLinearDepth); + g_vBoundsBuffer[boundsIndices.max] = float4(rapAaBbMaxPt, maxLinearDepth); + } + +#else // !Z_BINNING const float3 boxX = lgtDat.boxAxisX.xyz; const float3 boxY = lgtDat.boxAxisY.xyz; const float3 boxZ = -lgtDat.boxAxisZ.xyz; // flip axis (so it points away from the light direction for a spot-light) @@ -385,8 +904,10 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI g_vBoundsBuffer[boundsIndices.max] = float4(0.5*vMax.x + 0.5, 0.5*vMax.y + 0.5, vMax.z*VIEWPORT_SCALE_Z, linMaZ); } } +#endif // Z_BINNING } +#ifndef Z_BINNING float4 GenNewVert(const float4 vVisib, const float4 vInvisib, const int p); @@ -531,3 +1052,5 @@ void CalcBound(out bool2 bIsMinValid, out bool2 bIsMaxValid, out float2 vMin, ou vMin = B; vMax = A; } + +#endif // !Z_BINNING \ No newline at end of file From d3b4b95d67bf81a61faa1267f6613bb4d352c7f1 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 5 Aug 2020 14:04:30 -0700 Subject: [PATCH 002/209] Support orthographic projection --- .../Runtime/Lighting/LightLoop/scrbound.compute | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 355de58e942..7ac90c4d52c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -431,7 +431,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Make sure the W component is strictly positive. // It is helpful in order to simplify clipping and to avoid perspective division by 0. - float w = hapVert.w; + // For the orthographic projection, we only consider (w = 1) + float w = g_isOrthographic ? 1 : hapVert.w; float s = (w >= 0) ? 1 : -1; // Transform the X and Y components: [-w, w] -> [0, w]. From 10a585e7fa5212076384a5c875c703a24ed813f9 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 5 Aug 2020 15:52:27 -0700 Subject: [PATCH 003/209] Turn 'scaleXY' into a scalar --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 30 +++++++++---------- .../Lighting/LightLoop/LightLoop.cs.hlsl | 2 +- .../Lighting/LightLoop/scrbound.compute | 8 ++--- .../Runtime/Material/Decal/DecalSystem.cs | 6 ++-- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index f171399ed1c..57f186dbb82 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -130,8 +130,8 @@ struct SFiniteLightBound public Vector3 boxAxisY; // Scaled by the extents (half-size) public Vector3 boxAxisZ; // Scaled by the extents (half-size) public Vector3 center; // Center of the bounds (box) in camera space - public Vector2 scaleXY; // Scale applied to the top of the box to turn it into a truncated pyramid - public float radius; // Circumscribed sphere for the bounds (box) + public float scaleXY; // Scale applied to the top of the box to turn it into a truncated pyramid (X = Y) + public float radius; // Circumscribed sphere for the bounds (box) }; [GenerateHLSL] @@ -1766,9 +1766,9 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig fAltDx *= range; fAltDy *= range; // Handle case of pyramid with this select (currently unused) - var altDist = Mathf.Sqrt(fAltDy * fAltDy + (true ? 1.0f : 2.0f) * fAltDx * fAltDx); - bound.radius = altDist > (0.5f * range) ? altDist : (0.5f * range); // will always pick fAltDist - bound.scaleXY = squeeze ? new Vector2(0.01f, 0.01f) : new Vector2(1.0f, 1.0f); + var altDist = Mathf.Sqrt(fAltDy * fAltDy + (true ? 1.0f : 2.0f) * fAltDx * fAltDx); + bound.radius = altDist > (0.5f * range) ? altDist : (0.5f * range); // will always pick fAltDist + bound.scaleXY = squeeze ? 0.01f : 1.0f; lightVolumeData.lightAxisX = vx; lightVolumeData.lightAxisY = vy; @@ -1791,8 +1791,8 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig bound.boxAxisX = vx * range; bound.boxAxisY = vy * range; bound.boxAxisZ = vz * range; - bound.scaleXY.Set(1.0f, 1.0f); - bound.radius = range; + bound.scaleXY = 1.0f; + bound.radius = range; // fill up ldata lightVolumeData.lightAxisX = vx; @@ -1813,7 +1813,7 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig bound.boxAxisY = extents.y * yAxisVS; bound.boxAxisZ = extents.z * zAxisVS; bound.radius = extents.magnitude; - bound.scaleXY.Set(1.0f, 1.0f); + bound.scaleXY = 1.0f; lightVolumeData.lightPos = centerVS; lightVolumeData.lightAxisX = xAxisVS; @@ -1833,7 +1833,7 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig bound.boxAxisY = extents.y * yAxisVS; bound.boxAxisZ = extents.z * zAxisVS; bound.radius = extents.magnitude; - bound.scaleXY.Set(1.0f, 1.0f); + bound.scaleXY = 1.0f; lightVolumeData.lightPos = centerVS; lightVolumeData.lightAxisX = xAxisVS; @@ -1853,7 +1853,7 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig bound.boxAxisY = extents.y * yAxisVS; bound.boxAxisZ = extents.z * zAxisVS; bound.radius = extents.magnitude; - bound.scaleXY.Set(1.0f, 1.0f); + bound.scaleXY = 1.0f; lightVolumeData.lightPos = centerVS; lightVolumeData.lightAxisX = xAxisVS; @@ -2055,8 +2055,8 @@ void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeTyp bound.boxAxisX = influenceRightVS * influenceExtents.x; bound.boxAxisY = influenceUpVS * influenceExtents.x; bound.boxAxisZ = influenceForwardVS * influenceExtents.x; - bound.scaleXY.Set(1.0f, 1.0f); - bound.radius = influenceExtents.x; + bound.scaleXY = 1.0f; + bound.radius = influenceExtents.x; break; } case LightVolumeType.Box: @@ -2065,8 +2065,8 @@ void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeTyp bound.boxAxisX = influenceExtents.x * influenceRightVS; bound.boxAxisY = influenceExtents.y * influenceUpVS; bound.boxAxisZ = influenceExtents.z * influenceForwardVS; - bound.scaleXY.Set(1.0f, 1.0f); - bound.radius = influenceExtents.magnitude; + bound.scaleXY = 1.0f; + bound.radius = influenceExtents.magnitude; // The culling system culls pixels that are further // than a threshold to the box influence extents. @@ -2114,7 +2114,7 @@ void CreateBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, Light bound.boxAxisY = extentConservativeY * upVS; bound.boxAxisZ = extentConservativeZ * forwardVS; bound.radius = extentConservativeMagnitude; - bound.scaleXY.Set(1.0f, 1.0f); + bound.scaleXY = 1.0f; // The culling system culls pixels that are further // than a threshold to the box influence extents. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index f4a18fa8f36..dc8f41cf636 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -74,7 +74,7 @@ struct SFiniteLightBound float3 boxAxisY; float3 boxAxisZ; float3 center; - float2 scaleXY; + float scaleXY; float radius; }; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 7ac90c4d52c..44984045787 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -377,11 +377,11 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI const uint groupLocalLightIndex = t / THREADS_PER_LIGHT; const uint firstVertexOffset = NUM_VERTS * groupLocalLightIndex; - const float2 scale = lgtDat.scaleXY.xy; + const float scale = lgtDat.scaleXY.x; // scale.x = scale.y const float3 rbpC = lgtDat.center.xyz; - const float3 rbpX = lgtDat.boxAxisX.xyz; - const float3 rbpY = lgtDat.boxAxisY.xyz; - const float3 rbpZ = lgtDat.boxAxisZ.xyz; + const float3 rbpX = lgtDat.boxAxisX.xyz; // Pre-scaled + const float3 rbpY = lgtDat.boxAxisY.xyz; // Pre-scaled + const float3 rbpZ = lgtDat.boxAxisZ.xyz; // Pre-scaled #ifndef USE_WAVE_INTRINSICS // Initialize the TGSM. All threads write the same value -> no data races. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs index 509ae94928a..ec262a398f7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs @@ -629,12 +629,12 @@ private void GetDecalVolumeDataAndBound(Matrix4x4 decalToWorld, Matrix4x4 worldT var influenceForwardVS = worldToView.MultiplyVector(influenceZ / influenceExtents.z); var influencePositionVS = worldToView.MultiplyPoint(pos); // place the mesh pivot in the center - m_Bounds[m_DecalDatasCount].center = influencePositionVS; + m_Bounds[m_DecalDatasCount].center = influencePositionVS; m_Bounds[m_DecalDatasCount].boxAxisX = influenceRightVS * influenceExtents.x; m_Bounds[m_DecalDatasCount].boxAxisY = influenceUpVS * influenceExtents.y; m_Bounds[m_DecalDatasCount].boxAxisZ = influenceForwardVS * influenceExtents.z; - m_Bounds[m_DecalDatasCount].scaleXY.Set(1.0f, 1.0f); - m_Bounds[m_DecalDatasCount].radius = influenceExtents.magnitude; + m_Bounds[m_DecalDatasCount].scaleXY = 1.0f; + m_Bounds[m_DecalDatasCount].radius = influenceExtents.magnitude; // The culling system culls pixels that are further // than a threshold to the box influence extents. From 7a7d8f38f1cb41adaef4fa04fff76d58d9675efd Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 5 Aug 2020 18:53:33 -0700 Subject: [PATCH 004/209] Test corners of the view volume --- .../Lighting/LightLoop/scrbound.compute | 138 +++++++++++++++++- 1 file changed, 130 insertions(+), 8 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 44984045787..8cde9454319 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -56,6 +56,55 @@ uint NthBitLow(uint value, uint n) return b; } +float4x4 Translation4x4(float3 d) +{ + float4x4 M = k_Identity4x4; + + M._14_24_34 = d; // Last column + + return M; +} + +float3x3 Rotation3x3(float3 xAxis, float3 yAxis, float3 zAxis) +{ + float3x3 R = float3x3(xAxis, yAxis, zAxis); + float3x3 C = transpose(R); // Row to column + + return C; +} + +float3x3 Invert3x3(float3x3 R) +{ + float3x3 C = transpose(R); // Row to column + float det = dot(C[0], cross(C[1], C[2])); + float3x3 adj = float3x3(cross(C[1], C[2]), + cross(C[2], C[0]), + cross(C[0], C[1])); + + return rcp(det) * adj; +} + +float4x4 Homogenize3x3(float3x3 R) +{ + float4x4 M = float4x4(float4(R[0], 0), + float4(R[1], 0), + float4(R[2], 0), + float4(0,0,0,1)); + + return M; +} + +float4x4 PerspectiveProjection4x4(float s, float g, float n, float f) +{ + float a = (f + n) * rcp(f - n); + float b = -2 * f * n * rcp(f - n); + + return float4x4(g/s, 0, 0, 0, + 0, g, 0, 0, + 0, 0, a, b, + 0, 0, 1, 0); +} + // Clipping a plane by a cube may produce a hexagon (6-gon). // Clipping a hexagon by 4 planes may produce a decagon (10-gon). #define MAX_CLIP_VERTS (10) @@ -377,7 +426,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI const uint groupLocalLightIndex = t / THREADS_PER_LIGHT; const uint firstVertexOffset = NUM_VERTS * groupLocalLightIndex; - const float scale = lgtDat.scaleXY.x; // scale.x = scale.y + const float scale = lgtDat.scaleXY; // scale.x = scale.y const float3 rbpC = lgtDat.center.xyz; const float3 rbpX = lgtDat.boxAxisX.xyz; // Pre-scaled const float3 rbpY = lgtDat.boxAxisY.xyz; // Pre-scaled @@ -427,19 +476,21 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI m.xy *= (v >= 4) ? 1 : scale; float3 rbpVert = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; + // Avoid generating (w = 0). + rbpVert.z = (abs(rbpVert.z) >= FLT_EPS) ? rbpVert.z : FLT_EPS; + float4 hapVert = mul(g_mProjection, float4(rbpVert, 1)); // Make sure the W component is strictly positive. // It is helpful in order to simplify clipping and to avoid perspective division by 0. - // For the orthographic projection, we only consider (w = 1) - float w = g_isOrthographic ? 1 : hapVert.w; + float w = hapVert.w; float s = (w >= 0) ? 1 : -1; // Transform the X and Y components: [-w, w] -> [0, w]. hapVert.x = (0.5 * s) * hapVert.x + ((0.5 * s) * w); hapVert.y = (0.5 * s) * hapVert.y + ((0.5 * s) * w); hapVert.z = s * hapVert.z; - hapVert.w = max(abs(w), FLT_MIN); + hapVert.w = s * hapVert.w; // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex @@ -448,8 +499,11 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Consider the vertex to be inside the view volume if: // 0 <= x <= w - // 0 <= y <= w + // 0 <= y <= w <-- include boundary points, to avoid clipping them later // 0 <= z <= w + // w is always valid + // For the orthographic projection, (w = 1), so no modifications are necessary. + // TODO: epsilon for numerical robustness? w = hapVert.w; for (uint j = 0; j < (NUM_PLANES / 2); j++) @@ -487,9 +541,77 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI cullClipFaceMask = gs_CullClipFaceMasks[groupLocalLightIndex]; #endif + // (2) Test the corners of the view volume. if (cullClipFaceMask != 0) { - // The light may be partially outside the view volume. + // The light is partially outside the view volume. + // Therefore, some of the corners of the view volume may be inside the light volume. + // We perform aggressive culling, so we must make sure they are accounted for. + // The light volume is a special type of cuboid - a right frustum. + // We can exploit this fact by building a light-space projection matrix. + float4x4 invTranslateToLightSpace = Translation4x4(-rbpC); + float4x4 invRotateAndScaleInLightSpace = Homogenize3x3(Invert3x3(Rotation3x3(rbpX, rbpY, rbpZ))); + // TODO: avoid full inversion by using unit vectors and passing magnitudes explicitly. + + // This (orhographic) projection matrix maps a view-space point to a light-space [-1, 1]^3 cube. + float4x4 lightSpaceMatrix = mul(invRotateAndScaleInLightSpace, invTranslateToLightSpace); + + if (scale != 1) // Perspective light space? + { + // Compute the parameters of the perspective projection. + float s = scale; + float e = -1 - 2 * (s * rcp(1 - s)); // Signed distance from the origin to the eye + float n = -e - 1; // Distance from the eye to the near plane + float f = -e + 1; // Distance from the eye to the far plane + float g = f; // Distance from the eye to the projection plane + + float4x4 invTranslateEye = Translation4x4(float3(0, 0, -e)); + float4x4 perspProjMatrix = PerspectiveProjection4x4(s, g, n, f); + + lightSpaceMatrix = mul(perspProjMatrix, mul(invTranslateEye, lightSpaceMatrix)); + } + + for (uint i = 0; i < VERTS_PER_THREAD; i++) + { + uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + + // rapVertsCS[0] = (-1, -1, 0) + // rapVertsCS[1] = (+1, -1, 0) + // rapVertsCS[2] = (+1, +1, 0) + // rapVertsCS[3] = (-1, +1, 0) + // rapVertsCS[4] = (-1, -1, 1) + // rapVertsCS[5] = (+1, -1, 1) + // rapVertsCS[6] = (+1, +1, 1) + // rapVertsCS[7] = (-1, +1, 1) + + float3 rapVertCS; // See the comment above + + rapVertCS.x = (countbits(v % 4) == 1) ? 1 : -1; + rapVertCS.y = (v & 2 != 0) ? 1 : -1; + rapVertCS.z = (v >= 4) ? 1 : 0; + + float4 hbpVertVS = mul(g_mInvProjection, float4(rapVertCS, 1)); // Clip to view space + float4 hapVertLS = mul(lightSpaceMatrix, hbpVertVS); // View to light space + + // Consider the vertex to be inside the light volume if: + // -w < x < w + // -w < y < w <-- exclude boundary points, as we will not clip using these vertices + // -w < z < w + // 0 < w + // For the orthographic projection, (w = 1), so no modifications are necessary. + // TODO: epsilon for numerical robustness? + + bool inside = Max3(abs(hapVertLS.x), abs(hapVertLS.y), abs(hapVertLS.z)) < hapVertLS.w; + + if (inside) + { + float3 rapVertNDC = float3(rapVertCS.xy * 0.5 + 0.5, rapVertCS.z); + + // Update the AABB. + rapAaBbMinPt = min(rapAaBbMinPt, rapVertNDC); + rapAaBbMaxPt = max(rapAaBbMaxPt, rapVertNDC); + } + } } uint behindMasksOfVerts[NUM_VERTS]; @@ -499,7 +621,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI behindMasksOfVerts[i] = gs_BehindMasksOfVerts[firstVertexOffset + i]; } - // (2) Cull the faces. + // (3) Cull the faces. const uint cullFaceMask = cullClipFaceMask; const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] @@ -528,7 +650,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI cullClipFaceMask = gs_CullClipFaceMasks[groupLocalLightIndex]; #endif - // (3) Clip the faces. + // (4) Clip the faces. const uint clipFaceMask = cullClipFaceMask; const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] From a8d04ba5c5d9a5d376d1b50b29986367f3a19fa0 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 5 Aug 2020 18:58:56 -0700 Subject: [PATCH 005/209] Improve the placeholder for the linear depth --- .../Runtime/Lighting/LightLoop/scrbound.compute | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 8cde9454319..2c483b79058 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -696,7 +696,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // a set of maxs, and each set is equal to g_iNrVisibLights. const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex); - float minLinearDepth = -1, maxLinearDepth = -1; // TODO + float minLinearDepth = 0, maxLinearDepth = FLT_MAX; // TODO g_vBoundsBuffer[boundsIndices.min] = float4(rapAaBbMinPt, minLinearDepth); g_vBoundsBuffer[boundsIndices.max] = float4(rapAaBbMaxPt, maxLinearDepth); From 2ea9f8b7d33bc06e77c768fc60f7407acadef4f5 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 5 Aug 2020 20:08:03 -0700 Subject: [PATCH 006/209] Fix aspect --- .../Runtime/Lighting/LightLoop/scrbound.compute | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 2c483b79058..1a1b42f609b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -94,14 +94,14 @@ float4x4 Homogenize3x3(float3x3 R) return M; } -float4x4 PerspectiveProjection4x4(float s, float g, float n, float f) +float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) { - float a = (f + n) * rcp(f - n); - float b = -2 * f * n * rcp(f - n); + float b = (f + n) * rcp(f - n); + float c = -2 * f * n * rcp(f - n); - return float4x4(g/s, 0, 0, 0, + return float4x4(g/a, 0, 0, 0, 0, g, 0, 0, - 0, 0, a, b, + 0, 0, b, c, 0, 0, 1, 0); } @@ -566,7 +566,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float g = f; // Distance from the eye to the projection plane float4x4 invTranslateEye = Translation4x4(float3(0, 0, -e)); - float4x4 perspProjMatrix = PerspectiveProjection4x4(s, g, n, f); + float4x4 perspProjMatrix = PerspectiveProjection4x4(1, g, n, f); lightSpaceMatrix = mul(perspProjMatrix, mul(invTranslateEye, lightSpaceMatrix)); } From 0b870dbc07eff4ebda06c93e75f5e6467f6b9ca1 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 5 Aug 2020 20:41:09 -0700 Subject: [PATCH 007/209] Bugfix --- .../Lighting/LightLoop/scrbound.compute | 155 +++++++++--------- 1 file changed, 81 insertions(+), 74 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 1a1b42f609b..6a7d315ad24 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -11,7 +11,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" -// #pragma enable_d3d11_debug_symbols +#pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch StructuredBuffer g_data : register( t0 ); @@ -21,17 +21,12 @@ StructuredBuffer g_data : register( t0 ); // output buffer RWStructuredBuffer g_vBoundsBuffer : register( u0 ); -#define DUMB_COMPILER +#define Z_BINNING +// #define DUMB_COMPILER // #define USE_WAVE_INTRINSICS // We use TGSM and atomic operations if wave intrinsics are not supported #ifdef Z_BINNING -// Computes r=(n/d) and rounds the result towards the largest adjacent integer. -uint DivRoundUp(uint n, uint d) -{ - return (n + d - 1) / d; // No division by 0 checks -} - // Returns the location of the N-th set bit starting from the lowest order bit and working upward. // Slow implementation - do not use for large bit sets. // Could be optimized - see https://graphics.stanford.edu/~seander/bithacks.html @@ -105,21 +100,24 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) 0, 0, 1, 0); } +#define CLEAR_SIGN_BIT(X) (asuint(X) & INT_MAX) +#define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks + // Clipping a plane by a cube may produce a hexagon (6-gon). // Clipping a hexagon by 4 planes may produce a decagon (10-gon). #define MAX_CLIP_VERTS (10) -#define NUM_EDGES (12) #define NUM_VERTS (8) #define NUM_FACES (6) #define NUM_PLANES (6) -#define THREADS_PER_LIGHT (4) #define THREADS_PER_GROUP (64) +#define THREADS_PER_LIGHT (1) // Set to 1 for debugging #define LIGHTS_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_LIGHT) #define VERTS_PER_GROUP (NUM_VERTS * LIGHTS_PER_GROUP) #define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_LIGHT) -#define FACES_PER_THREAD DivRoundUp(NUM_FACES, THREADS_PER_LIGHT) +#define FACES_PER_THREAD DIV_ROUND_UP(NUM_FACES, THREADS_PER_LIGHT) // All planes and faces are always in the standard order (see below). +// Near and far planes may be swapped for Reverse Z-Buffering, but it does not change the algorithm. #define FACE_LEFT (1 << 0) // x = -1 #define FACE_RIGHT (1 << 1) // x = +1 #define FACE_FRONT (1 << 2) // y = -1 @@ -131,6 +129,8 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) // TODO: the compiler generates 'tbuffer_load_format_x' instructions // when we access the look-up tables. Can we avoid this? +// TODO: try vert order (0 0 0), (1 0 0), (0 1 0), (1 1 0), (0 0 1), (1 0 1), (0 1 1), (1 1 1) + // All vertices are always in the standard order (see below). static const uint s_FaceMasksOfVerts[NUM_VERTS] = { @@ -148,12 +148,12 @@ static const uint s_FaceMasksOfVerts[NUM_VERTS] = // with normals pointing in the interior of the volume. static const uint s_VertMasksOfFaces[NUM_FACES] = { - 3 << 9 | 7 << 6 | 4 << 3 | 0 << 0, // 0: FACE_LEFT - 5 << 9 | 6 << 6 | 2 << 3 | 1 << 0, // 1: FACE_RIGHT - 4 << 9 | 5 << 6 | 1 << 3 | 0 << 0, // 2: FACE_FRONT - 2 << 9 | 6 << 6 | 7 << 3 | 3 << 0, // 3: FACE_BACK - 1 << 9 | 2 << 6 | 3 << 3 | 0 << 0, // 4: FACE_TOP - 7 << 9 | 6 << 6 | 5 << 3 | 4 << 0 // 5: FACE_BOTTOM + (3) << 9 | (7) << 6 | (4) << 3 | (0) << 0, // 0: FACE_LEFT + (5) << 9 | (6) << 6 | (2) << 3 | (1) << 0, // 1: FACE_RIGHT + (4) << 9 | (5) << 6 | (1) << 3 | (0) << 0, // 2: FACE_FRONT + (6) << 9 | (7) << 6 | (3) << 3 | (2) << 0, // 3: FACE_BACK + (1) << 9 | (2) << 6 | (3) << 3 | (0) << 0, // 4: FACE_TOP + (7) << 9 | (6) << 6 | (5) << 3 | (4) << 0 // 5: FACE_BOTTOM }; // 5 arrays * 128 elements * 4 bytes each = 2560 bytes. @@ -168,7 +168,7 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL groupshared uint gs_CullClipFaceMasks[LIGHTS_PER_GROUP]; // 6 faces each (HLSL does not support small data types) // 6 arrays * 16 elements * 4 bytes each = 384 bytes. -// Note that these are actually floats reinterpreted as uints. +// These are actually floats reinterpreted as uints. // The reason is because floating-point atomic operations are not supported. groupshared uint gs_RapAaBbMinPtX[LIGHTS_PER_GROUP]; groupshared uint gs_RapAaBbMaxPtX[LIGHTS_PER_GROUP]; @@ -302,8 +302,8 @@ void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_ // Non-zero if ANY of the vertices are behind any of the planes. clipMaskOfFace |= behindMasksOfVerts[v]; - // Note that not all edges may require clipping. However, - // filtering the vertex list is somewhat expensive, so we currently don't do it. + // Not all edges may require clipping. However, filtering the vertex list + // is somewhat expensive, so we currently don't do it. vertRingBuffer[j].x = gs_HapVertsX[firstVertexOffset + v]; vertRingBuffer[j].y = gs_HapVertsY[firstVertexOffset + v]; vertRingBuffer[j].z = gs_HapVertsZ[firstVertexOffset + v]; @@ -331,14 +331,14 @@ void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_ uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; #endif - for (int j = srcBegin; j < (srcBegin + srcSize); j++) + for (uint j = srcBegin; j < (srcBegin + srcSize); j++) { #ifndef DUMB_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif float4 hapVert = vertRingBuffer[modSrcIdx]; - float3 rapVert = hapVert.xyz * rcp(hapVert.w); + float3 rapVert = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values rapAaBbMinPt = min(rapAaBbMinPt, rapVert); rapAaBbMaxPt = max(rapAaBbMaxPt, rapVert); @@ -352,7 +352,10 @@ void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_ #else // !Z_BINNING -#define MAX_PNTS 9 // strictly this should be 10=6+4 but we get more wavefronts and 10 seems to never hit (fingers crossed) +#define THREADS_PER_LIGHT (8) +#define THREADS_PER_GROUP (64) +#define LIGHTS_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_LIGHT) +#define MAX_PNTS (9) // strictly this should be 10=6+4 but we get more wavefronts and 10 seems to never hit (fingers crossed) // However, worst case the plane that would be skipped if such an extreme case ever happened would be backplane // clipping gets skipped which doesn't cause any errors. @@ -387,8 +390,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI unsigned int g = groupID; unsigned int t = threadID; - const int subLigt = (uint) (t/8); - const int lgtIndex = subLigt+(uint) g*8; + const int subLigt = (uint) (t/THREADS_PER_LIGHT); + const int lgtIndex = subLigt+(uint) g*LIGHTS_PER_GROUP; const int sideIndex = (uint) (t%8); const int eyeAdjustedLgtIndex = GenerateLightCullDataIndex(lgtIndex, g_iNrVisibLights, eyeIndex); @@ -402,13 +405,13 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Since a light volume may be partially off-screen, we must clip it before computing the AABB. // Clipping the resulting AABB (rather than the light volume itself) may result in a loose AABB. // - // To avoid having to deal with toroidal properties of the perspective transform, + // To avoid having to deal with the "Moebius twist" property of the perspective transform, // we perform clipping using the homogeneous (projective) post-perspective coordinates. // This clipping method in described in Blinn's paper titled "Line Clipping". // // The algorithm processes a light on 4 threads. While all 6 faces may require clipping in the // worst case, clipping more than 4 faces is very uncommon (typically, we clip 0, 3 or 4). - // Note that some faces may require culling rather than clipping (the former is simpler). + // Some faces may require culling rather than clipping (the former is simpler). // // It's important to realize that face culling may end up culling 5 (or even all 6) faces. // This means that the clipped light volume may be reduced to a single polygon, or nothing at all. @@ -428,20 +431,23 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI const float scale = lgtDat.scaleXY; // scale.x = scale.y const float3 rbpC = lgtDat.center.xyz; + // TODO: store X, Y, Scale const float3 rbpX = lgtDat.boxAxisX.xyz; // Pre-scaled const float3 rbpY = lgtDat.boxAxisY.xyz; // Pre-scaled const float3 rbpZ = lgtDat.boxAxisZ.xyz; // Pre-scaled #ifndef USE_WAVE_INTRINSICS - // Initialize the TGSM. All threads write the same value -> no data races. - // The hardware will coalesce the writes. - gs_CullClipFaceMasks[groupLocalLightIndex] = 0; // Initially inside - gs_RapAaBbMinPtX[groupLocalLightIndex] = asuint(1.0f); - gs_RapAaBbMaxPtX[groupLocalLightIndex] = asuint(0.0f); - gs_RapAaBbMinPtY[groupLocalLightIndex] = asuint(1.0f); - gs_RapAaBbMaxPtY[groupLocalLightIndex] = asuint(0.0f); - gs_RapAaBbMinPtZ[groupLocalLightIndex] = asuint(1.0f); - gs_RapAaBbMaxPtZ[groupLocalLightIndex] = asuint(0.0f); + // (0) Initialize the TGSM. + if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts + { + gs_CullClipFaceMasks[groupLocalLightIndex] = 0; // Initially inside + gs_RapAaBbMinPtX[groupLocalLightIndex] = asuint(1.0f); + gs_RapAaBbMaxPtX[groupLocalLightIndex] = asuint(0.0f); + gs_RapAaBbMinPtY[groupLocalLightIndex] = asuint(1.0f); + gs_RapAaBbMaxPtY[groupLocalLightIndex] = asuint(0.0f); + gs_RapAaBbMinPtZ[groupLocalLightIndex] = asuint(1.0f); + gs_RapAaBbMaxPtZ[groupLocalLightIndex] = asuint(0.0f); + } #endif // USE_WAVE_INTRINSICS float3 rapAaBbMinPt = 1; @@ -477,20 +483,16 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float3 rbpVert = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; // Avoid generating (w = 0). - rbpVert.z = (abs(rbpVert.z) >= FLT_EPS) ? rbpVert.z : FLT_EPS; + rbpVert.z = (abs(rbpVert.z) > FLT_MIN) ? rbpVert.z : FLT_MIN; float4 hapVert = mul(g_mProjection, float4(rbpVert, 1)); - // Make sure the W component is strictly positive. - // It is helpful in order to simplify clipping and to avoid perspective division by 0. - float w = hapVert.w; - float s = (w >= 0) ? 1 : -1; + // Warning: the W component may be negative. + // Flipping the -W pyramid by negating all coordinates is incorrect + // and will break both classification and clipping. // Transform the X and Y components: [-w, w] -> [0, w]. - hapVert.x = (0.5 * s) * hapVert.x + ((0.5 * s) * w); - hapVert.y = (0.5 * s) * hapVert.y + ((0.5 * s) * w); - hapVert.z = s * hapVert.z; - hapVert.w = s * hapVert.w; + hapVert.xy = 0.5 * hapVert.xy + (0.5 * hapVert.w); // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex @@ -504,17 +506,18 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // w is always valid // For the orthographic projection, (w = 1), so no modifications are necessary. // TODO: epsilon for numerical robustness? - w = hapVert.w; for (uint j = 0; j < (NUM_PLANES / 2); j++) { + float w = hapVert.w; + behindMask |= (hapVert[j] < 0 ? 1 : 0) << (2 * j + 0); // Planes crossing '0' behindMask |= (hapVert[j] > w ? 1 : 0) << (2 * j + 1); // Planes crossing 'w' } if (behindMask == 0) // Inside? { - float3 rapVert = hapVert.xyz * rcp(hapVert.w); + float3 rapVert = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values rapAaBbMinPt = min(rapAaBbMinPt, rapVert); rapAaBbMaxPt = max(rapAaBbMaxPt, rapVert); @@ -568,7 +571,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float4x4 invTranslateEye = Translation4x4(float3(0, 0, -e)); float4x4 perspProjMatrix = PerspectiveProjection4x4(1, g, n, f); - lightSpaceMatrix = mul(perspProjMatrix, mul(invTranslateEye, lightSpaceMatrix)); + lightSpaceMatrix = mul(mul(perspProjMatrix, invTranslateEye), lightSpaceMatrix); } for (uint i = 0; i < VERTS_PER_THREAD; i++) @@ -596,7 +599,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Consider the vertex to be inside the light volume if: // -w < x < w // -w < y < w <-- exclude boundary points, as we will not clip using these vertices - // -w < z < w + // -w < z < w <-- assume that Z-precision is not very important here // 0 < w // For the orthographic projection, (w = 1), so no modifications are necessary. // TODO: epsilon for numerical robustness? @@ -622,20 +625,22 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI } // (3) Cull the faces. - const uint cullFaceMask = cullClipFaceMask; - const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] - - for (uint i = 0; i < FACES_PER_THREAD; i++) { - uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + const uint cullFaceMask = cullClipFaceMask; + const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] - if (n < numFacesToCull) + for (uint i = 0; i < FACES_PER_THREAD; i++) { - uint f = NthBitLow(cullFaceMask, n); + uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; - if (TryCullFace(f, behindMasksOfVerts)) + if (n < numFacesToCull) { - cullClipFaceMask ^= 1 << f; // Clear the bit + uint f = NthBitLow(cullFaceMask, n); + + if (TryCullFace(f, behindMasksOfVerts)) + { + cullClipFaceMask ^= 1 << f; // Clear the bit + } } } } @@ -651,19 +656,21 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI #endif // (4) Clip the faces. - const uint clipFaceMask = cullClipFaceMask; - const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] - - for (uint i = 0; i < FACES_PER_THREAD; i++) { - uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + const uint clipFaceMask = cullClipFaceMask; + const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] - if (n < numFacesToCull) + for (uint i = 0; i < FACES_PER_THREAD; i++) { - uint f = NthBitLow(clipFaceMask, n); + uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + + if (n < numFacesToClip) + { + uint f = NthBitLow(clipFaceMask, n); - ClipFaceAgainstViewVolumeAndUpdateAaBb(f, behindMasksOfVerts, firstVertexOffset, - rapAaBbMinPt, rapAaBbMaxPt); + ClipFaceAgainstViewVolumeAndUpdateAaBb(f, behindMasksOfVerts, firstVertexOffset, + rapAaBbMinPt, rapAaBbMaxPt); + } } } @@ -672,12 +679,12 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. // We must take care of the signed zero ourselves. - InterlockedMin(gs_RapAaBbMinPtX[groupLocalLightIndex], asuint(rapAaBbMinPt.x) & INT_MAX); - InterlockedMax(gs_RapAaBbMaxPtX[groupLocalLightIndex], asuint(rapAaBbMaxPt.x) & INT_MAX); - InterlockedMin(gs_RapAaBbMinPtY[groupLocalLightIndex], asuint(rapAaBbMinPt.y) & INT_MAX); - InterlockedMax(gs_RapAaBbMaxPtY[groupLocalLightIndex], asuint(rapAaBbMaxPt.y) & INT_MAX); - InterlockedMin(gs_RapAaBbMinPtZ[groupLocalLightIndex], asuint(rapAaBbMinPt.z) & INT_MAX); - InterlockedMax(gs_RapAaBbMaxPtZ[groupLocalLightIndex], asuint(rapAaBbMaxPt.z) & INT_MAX); + InterlockedMin(gs_RapAaBbMinPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMinPt.x))); + InterlockedMax(gs_RapAaBbMaxPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMaxPt.x))); + InterlockedMin(gs_RapAaBbMinPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMinPt.y))); + InterlockedMax(gs_RapAaBbMaxPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMaxPt.y))); + InterlockedMin(gs_RapAaBbMinPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMinPt.z))); + InterlockedMax(gs_RapAaBbMaxPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMaxPt.z))); GroupMemoryBarrierWithGroupSync(); @@ -689,7 +696,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI rapAaBbMaxPt.z = asfloat(gs_RapAaBbMaxPtZ[groupLocalLightIndex]); #endif // USE_WAVE_INTRINSICS - if (t % THREADS_PER_LIGHT == 0) + if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts { // Each light's AABB is represented by two float3s, the min and max of the box. // And for stereo, we have two sets of lights. Therefore, each eye has a set of mins, followed by From 83d73e935b84ddae99438bb432cb4673f7c2775e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 6 Aug 2020 21:38:10 -0700 Subject: [PATCH 008/209] Optimize --- .../Lighting/LightLoop/scrbound.compute | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 6a7d315ad24..197589bf12c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -11,7 +11,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" -#pragma enable_d3d11_debug_symbols +// #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch StructuredBuffer g_data : register( t0 ); @@ -22,7 +22,7 @@ StructuredBuffer g_data : register( t0 ); RWStructuredBuffer g_vBoundsBuffer : register( u0 ); #define Z_BINNING -// #define DUMB_COMPILER +#define DUMB_COMPILER // #define USE_WAVE_INTRINSICS // We use TGSM and atomic operations if wave intrinsics are not supported #ifdef Z_BINNING @@ -75,7 +75,6 @@ float3x3 Invert3x3(float3x3 R) float3x3 adj = float3x3(cross(C[1], C[2]), cross(C[2], C[0]), cross(C[0], C[1])); - return rcp(det) * adj; } @@ -85,14 +84,13 @@ float4x4 Homogenize3x3(float3x3 R) float4(R[1], 0), float4(R[2], 0), float4(0,0,0,1)); - return M; } float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) { - float b = (f + n) * rcp(f - n); - float c = -2 * f * n * rcp(f - n); + float b = (f + n) * rcp(f - n); // z: [-1, 1] + float c = -2 * f * n * rcp(f - n); // No Z-reversal return float4x4(g/a, 0, 0, 0, 0, g, 0, 0, @@ -110,14 +108,14 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) #define NUM_FACES (6) #define NUM_PLANES (6) #define THREADS_PER_GROUP (64) -#define THREADS_PER_LIGHT (1) // Set to 1 for debugging +#define THREADS_PER_LIGHT (4) // Set to 1 for debugging #define LIGHTS_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_LIGHT) #define VERTS_PER_GROUP (NUM_VERTS * LIGHTS_PER_GROUP) #define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_LIGHT) #define FACES_PER_THREAD DIV_ROUND_UP(NUM_FACES, THREADS_PER_LIGHT) // All planes and faces are always in the standard order (see below). -// Near and far planes may be swapped for Reverse Z-Buffering, but it does not change the algorithm. +// Near and far planes are swapped in the case of Z-reversal, but it does not affect the algorithm. #define FACE_LEFT (1 << 0) // x = -1 #define FACE_RIGHT (1 << 1) // x = +1 #define FACE_FRONT (1 << 2) // y = -1 @@ -476,7 +474,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float3 m; // See the comment above m.x = (countbits(v % 4) == 1) ? 1 : -1; - m.y = (v & 2 != 0) ? 1 : -1; + m.y = ((v & 2) != 0) ? 1 : -1; m.z = (v >= 4) ? 1 : -1; m.xy *= (v >= 4) ? 1 : scale; @@ -501,7 +499,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Consider the vertex to be inside the view volume if: // 0 <= x <= w - // 0 <= y <= w <-- include boundary points, to avoid clipping them later + // 0 <= y <= w <-- include boundary points to avoid clipping them later // 0 <= z <= w // w is always valid // For the orthographic projection, (w = 1), so no modifications are necessary. @@ -556,7 +554,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float4x4 invRotateAndScaleInLightSpace = Homogenize3x3(Invert3x3(Rotation3x3(rbpX, rbpY, rbpZ))); // TODO: avoid full inversion by using unit vectors and passing magnitudes explicitly. - // This (orhographic) projection matrix maps a view-space point to a light-space [-1, 1]^3 cube. + // This (orthographic) projection matrix maps a view-space point to a light-space [-1, 1]^3 cube. float4x4 lightSpaceMatrix = mul(invRotateAndScaleInLightSpace, invTranslateToLightSpace); if (scale != 1) // Perspective light space? @@ -590,7 +588,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float3 rapVertCS; // See the comment above rapVertCS.x = (countbits(v % 4) == 1) ? 1 : -1; - rapVertCS.y = (v & 2 != 0) ? 1 : -1; + rapVertCS.y = ((v & 2) != 0) ? 1 : -1; rapVertCS.z = (v >= 4) ? 1 : 0; float4 hbpVertVS = mul(g_mInvProjection, float4(rapVertCS, 1)); // Clip to view space @@ -703,10 +701,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // a set of maxs, and each set is equal to g_iNrVisibLights. const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex); - float minLinearDepth = 0, maxLinearDepth = FLT_MAX; // TODO - - g_vBoundsBuffer[boundsIndices.min] = float4(rapAaBbMinPt, minLinearDepth); - g_vBoundsBuffer[boundsIndices.max] = float4(rapAaBbMaxPt, maxLinearDepth); + g_vBoundsBuffer[boundsIndices.min] = float4(rapAaBbMinPt, 0); // TODO: add me - lin depth + g_vBoundsBuffer[boundsIndices.max] = float4(rapAaBbMaxPt, 100000); // } #else // !Z_BINNING From 3f137abbe1c24ef55d71f0083f0cae6a622fbfbc Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 7 Aug 2020 13:15:40 -0700 Subject: [PATCH 009/209] Also store view space Z --- .../Lighting/LightLoop/scrbound.compute | 112 ++++++++++-------- 1 file changed, 65 insertions(+), 47 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 197589bf12c..118ec9c2374 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -165,15 +165,17 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL // 1 array * 16 elements * 4 bytes each = 64 bytes. groupshared uint gs_CullClipFaceMasks[LIGHTS_PER_GROUP]; // 6 faces each (HLSL does not support small data types) -// 6 arrays * 16 elements * 4 bytes each = 384 bytes. +// 8 arrays * 16 elements * 4 bytes each = 512 bytes. // These are actually floats reinterpreted as uints. // The reason is because floating-point atomic operations are not supported. -groupshared uint gs_RapAaBbMinPtX[LIGHTS_PER_GROUP]; -groupshared uint gs_RapAaBbMaxPtX[LIGHTS_PER_GROUP]; -groupshared uint gs_RapAaBbMinPtY[LIGHTS_PER_GROUP]; -groupshared uint gs_RapAaBbMaxPtY[LIGHTS_PER_GROUP]; -groupshared uint gs_RapAaBbMinPtZ[LIGHTS_PER_GROUP]; -groupshared uint gs_RapAaBbMaxPtZ[LIGHTS_PER_GROUP]; +groupshared uint gs_NdcAaBbMinPtX[LIGHTS_PER_GROUP]; +groupshared uint gs_NdcAaBbMaxPtX[LIGHTS_PER_GROUP]; +groupshared uint gs_NdcAaBbMinPtY[LIGHTS_PER_GROUP]; +groupshared uint gs_NdcAaBbMaxPtY[LIGHTS_PER_GROUP]; +groupshared uint gs_NdcAaBbMinPtZ[LIGHTS_PER_GROUP]; // Note that min-max Z cannot be trivially reconstructed +groupshared uint gs_NdcAaBbMaxPtZ[LIGHTS_PER_GROUP]; // from min-max W if the projection is oblique. +groupshared uint gs_NdcAaBbMinPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate +groupshared uint gs_NdcAaBbMaxPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate #endif // USE_WAVE_INTRINSICS // Returns 'true' if it manages to cull the face. @@ -285,8 +287,8 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, } } -void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_VERTS], uint firstVertexOffset, - inout float3 rapAaBbMinPt, inout float3 rapAaBbMaxPt) +void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_VERTS], uint firstVertexOffset, float4x4 g_mInvProjection, + inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) { float4 vertRingBuffer[MAX_CLIP_VERTS]; uint srcBegin = 0, srcSize = 4; @@ -335,11 +337,15 @@ void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_ uint modSrcIdx = j % MAX_CLIP_VERTS; #endif - float4 hapVert = vertRingBuffer[modSrcIdx]; - float3 rapVert = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values + float4 hapVert = vertRingBuffer[modSrcIdx]; + float4 hbpVertVS = mul(g_mInvProjection, hapVert); // Just to support orthographic projection + float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values + float rbpVertVSz = hbpVertVS.z * rcp(hbpVertVS.w); - rapAaBbMinPt = min(rapAaBbMinPt, rapVert); - rapAaBbMaxPt = max(rapAaBbMaxPt, rapVert); + ndcAaBbMinPt.xyz = min(ndcAaBbMinPt.xyz, rapVertNDC); + ndcAaBbMaxPt.xyz = max(ndcAaBbMaxPt.xyz, rapVertNDC); + ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, rbpVertVSz); + ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, rbpVertVSz); #ifdef DUMB_COMPILER modSrcIdx++; @@ -439,17 +445,19 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts { gs_CullClipFaceMasks[groupLocalLightIndex] = 0; // Initially inside - gs_RapAaBbMinPtX[groupLocalLightIndex] = asuint(1.0f); - gs_RapAaBbMaxPtX[groupLocalLightIndex] = asuint(0.0f); - gs_RapAaBbMinPtY[groupLocalLightIndex] = asuint(1.0f); - gs_RapAaBbMaxPtY[groupLocalLightIndex] = asuint(0.0f); - gs_RapAaBbMinPtZ[groupLocalLightIndex] = asuint(1.0f); - gs_RapAaBbMaxPtZ[groupLocalLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtX[groupLocalLightIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtX[groupLocalLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtY[groupLocalLightIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtY[groupLocalLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtZ[groupLocalLightIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtZ[groupLocalLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtW[groupLocalLightIndex] = asuint(FLT_INF); + gs_NdcAaBbMaxPtW[groupLocalLightIndex] = asuint(0.0f); } #endif // USE_WAVE_INTRINSICS - float3 rapAaBbMinPt = 1; - float3 rapAaBbMaxPt = 0; + float4 ndcAaBbMinPt = float4(1, 1, 1, FLT_INF); + float4 ndcAaBbMaxPt = 0; // We must determine whether we have to clip or cull any of the faces. // If all vertices of a face are inside with respect to all the culling planes, @@ -479,11 +487,11 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI m.xy *= (v >= 4) ? 1 : scale; - float3 rbpVert = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; + float3 rbpVertVS = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; // Avoid generating (w = 0). - rbpVert.z = (abs(rbpVert.z) > FLT_MIN) ? rbpVert.z : FLT_MIN; + rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; - float4 hapVert = mul(g_mProjection, float4(rbpVert, 1)); + float4 hapVert = mul(g_mProjection, float4(rbpVertVS, 1)); // Warning: the W component may be negative. // Flipping the -W pyramid by negating all coordinates is incorrect @@ -492,6 +500,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Transform the X and Y components: [-w, w] -> [0, w]. hapVert.xy = 0.5 * hapVert.xy + (0.5 * hapVert.w); + // TODO: multiply vertex by ViewZ if orthographic for unified processing! + // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex // is in the positive or the negative half-space. @@ -515,10 +525,12 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI if (behindMask == 0) // Inside? { - float3 rapVert = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values + float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values - rapAaBbMinPt = min(rapAaBbMinPt, rapVert); - rapAaBbMaxPt = max(rapAaBbMaxPt, rapVert); + ndcAaBbMinPt.xyz = min(ndcAaBbMinPt.xyz, rapVertNDC); + ndcAaBbMaxPt.xyz = max(ndcAaBbMaxPt.xyz, rapVertNDC); + ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, rbpVertVS.z); + ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, rbpVertVS.z); } else // Outside { @@ -607,10 +619,12 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI if (inside) { float3 rapVertNDC = float3(rapVertCS.xy * 0.5 + 0.5, rapVertCS.z); + float rbpVertVSz = hbpVertVS.z * rcp(hbpVertVS.w); - // Update the AABB. - rapAaBbMinPt = min(rapAaBbMinPt, rapVertNDC); - rapAaBbMaxPt = max(rapAaBbMaxPt, rapVertNDC); + ndcAaBbMinPt.xyz = min(ndcAaBbMinPt.xyz, rapVertNDC); + ndcAaBbMaxPt.xyz = max(ndcAaBbMaxPt.xyz, rapVertNDC); + ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, rbpVertVSz); + ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, rbpVertVSz); } } } @@ -666,8 +680,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI { uint f = NthBitLow(clipFaceMask, n); - ClipFaceAgainstViewVolumeAndUpdateAaBb(f, behindMasksOfVerts, firstVertexOffset, - rapAaBbMinPt, rapAaBbMaxPt); + ClipFaceAgainstViewVolumeAndUpdateAaBb(f, behindMasksOfVerts, firstVertexOffset, g_mInvProjection, + ndcAaBbMinPt, ndcAaBbMaxPt); } } } @@ -676,22 +690,26 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // ... #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. - // We must take care of the signed zero ourselves. - InterlockedMin(gs_RapAaBbMinPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMinPt.x))); - InterlockedMax(gs_RapAaBbMaxPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMaxPt.x))); - InterlockedMin(gs_RapAaBbMinPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMinPt.y))); - InterlockedMax(gs_RapAaBbMaxPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMaxPt.y))); - InterlockedMin(gs_RapAaBbMinPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMinPt.z))); - InterlockedMax(gs_RapAaBbMaxPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(rapAaBbMaxPt.z))); + // We must take care of the signed zero ourselves. saturate() does not help here. + InterlockedMin(gs_NdcAaBbMinPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); + InterlockedMax(gs_NdcAaBbMaxPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); + InterlockedMin(gs_NdcAaBbMinPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); + InterlockedMax(gs_NdcAaBbMaxPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); + InterlockedMin(gs_NdcAaBbMinPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.z))); + InterlockedMax(gs_NdcAaBbMaxPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.z))); + InterlockedMin(gs_NdcAaBbMinPtW[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); + InterlockedMax(gs_NdcAaBbMaxPtW[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); GroupMemoryBarrierWithGroupSync(); - rapAaBbMinPt.x = asfloat(gs_RapAaBbMinPtX[groupLocalLightIndex]); - rapAaBbMaxPt.x = asfloat(gs_RapAaBbMaxPtX[groupLocalLightIndex]); - rapAaBbMinPt.y = asfloat(gs_RapAaBbMinPtY[groupLocalLightIndex]); - rapAaBbMaxPt.y = asfloat(gs_RapAaBbMaxPtY[groupLocalLightIndex]); - rapAaBbMinPt.z = asfloat(gs_RapAaBbMinPtZ[groupLocalLightIndex]); - rapAaBbMaxPt.z = asfloat(gs_RapAaBbMaxPtZ[groupLocalLightIndex]); + ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[groupLocalLightIndex]); + ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[groupLocalLightIndex]); + ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[groupLocalLightIndex]); + ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[groupLocalLightIndex]); + ndcAaBbMinPt.z = asfloat(gs_NdcAaBbMinPtZ[groupLocalLightIndex]); + ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[groupLocalLightIndex]); + ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[groupLocalLightIndex]); + ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[groupLocalLightIndex]); #endif // USE_WAVE_INTRINSICS if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts @@ -701,8 +719,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // a set of maxs, and each set is equal to g_iNrVisibLights. const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex); - g_vBoundsBuffer[boundsIndices.min] = float4(rapAaBbMinPt, 0); // TODO: add me - lin depth - g_vBoundsBuffer[boundsIndices.max] = float4(rapAaBbMaxPt, 100000); // + g_vBoundsBuffer[boundsIndices.min] = ndcAaBbMinPt; + g_vBoundsBuffer[boundsIndices.max] = ndcAaBbMaxPt; } #else // !Z_BINNING From be9e040608676823de4727d59534afefd71804ce Mon Sep 17 00:00:00 2001 From: Evgenii Date: Sat, 8 Aug 2020 14:05:14 -0700 Subject: [PATCH 010/209] Optimize orthographic --- .../Lighting/LightLoop/scrbound.compute | 65 ++++++++++--------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 118ec9c2374..ee373ec6081 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -115,7 +115,7 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) #define FACES_PER_THREAD DIV_ROUND_UP(NUM_FACES, THREADS_PER_LIGHT) // All planes and faces are always in the standard order (see below). -// Near and far planes are swapped in the case of Z-reversal, but it does not affect the algorithm. +// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. #define FACE_LEFT (1 << 0) // x = -1 #define FACE_RIGHT (1 << 1) // x = +1 #define FACE_FRONT (1 << 2) // y = -1 @@ -249,7 +249,7 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, // 1. v0 in, v1 out -> add intersection // 2. v0 out, v1 in -> add intersection, add v1 // 3. v0 in, v1 in -> add v1 - // (bc >= 0) <-> in, (bc < 0) <-> out. Beware of the signed zero. + // (bc >= 0) <-> in, (bc < 0) <-> out. Beware of -0. if ((tailVert.bc >= 0) != (leadVert.bc >= 0)) { @@ -287,11 +287,12 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, } } -void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_VERTS], uint firstVertexOffset, float4x4 g_mInvProjection, - inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) +void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint firstVertexOffset, + out uint srcBegin, out uint srcSize, + out float4 vertRingBuffer[MAX_CLIP_VERTS]) { - float4 vertRingBuffer[MAX_CLIP_VERTS]; - uint srcBegin = 0, srcSize = 4; + srcBegin = 0; + srcSize = 4; uint clipMaskOfFace = 0; // Initially in front uint vertMaskOfFace = s_VertMasksOfFaces[f]; @@ -326,7 +327,12 @@ void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_ clipMaskOfFace ^= 1 << p; // Clear the bit to continue using firstbitlow() } +} +void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERTS], + bool isOrthoProj, float4x4 invProj, + inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) +{ #ifdef DUMB_COMPILER uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; #endif @@ -336,17 +342,18 @@ void ClipFaceAgainstViewVolumeAndUpdateAaBb(uint f, uint behindMasksOfVerts[NUM_ #ifndef DUMB_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif - float4 hapVert = vertRingBuffer[modSrcIdx]; - float4 hbpVertVS = mul(g_mInvProjection, hapVert); // Just to support orthographic projection - float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values - float rbpVertVSz = hbpVertVS.z * rcp(hbpVertVS.w); + // Clamp to the bounds in case of numerical errors (may still generate -0). + float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); + float rbpVertVSz = hapVert.w; - ndcAaBbMinPt.xyz = min(ndcAaBbMinPt.xyz, rapVertNDC); - ndcAaBbMaxPt.xyz = max(ndcAaBbMaxPt.xyz, rapVertNDC); - ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, rbpVertVSz); - ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, rbpVertVSz); + if (isOrthoProj) // Must replace (w = 1) + { + rbpVertVSz = dot(invProj[2], hapVert); + } + ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); + ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVSz)); #ifdef DUMB_COMPILER modSrcIdx++; modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; @@ -496,12 +503,11 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // Warning: the W component may be negative. // Flipping the -W pyramid by negating all coordinates is incorrect // and will break both classification and clipping. + // For the orthographic projection, (w = 1). // Transform the X and Y components: [-w, w] -> [0, w]. hapVert.xy = 0.5 * hapVert.xy + (0.5 * hapVert.w); - // TODO: multiply vertex by ViewZ if orthographic for unified processing! - // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex // is in the positive or the negative half-space. @@ -512,7 +518,6 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // 0 <= y <= w <-- include boundary points to avoid clipping them later // 0 <= z <= w // w is always valid - // For the orthographic projection, (w = 1), so no modifications are necessary. // TODO: epsilon for numerical robustness? for (uint j = 0; j < (NUM_PLANES / 2); j++) @@ -525,12 +530,11 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI if (behindMask == 0) // Inside? { - float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); // Must not generate negative values + // Clamp to the bounds in case of numerical errors (may still generate -0). + float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); - ndcAaBbMinPt.xyz = min(ndcAaBbMinPt.xyz, rapVertNDC); - ndcAaBbMaxPt.xyz = max(ndcAaBbMaxPt.xyz, rapVertNDC); - ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, rbpVertVS.z); - ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, rbpVertVS.z); + ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVS.z)); + ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVS.z)); } else // Outside { @@ -611,7 +615,6 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // -w < y < w <-- exclude boundary points, as we will not clip using these vertices // -w < z < w <-- assume that Z-precision is not very important here // 0 < w - // For the orthographic projection, (w = 1), so no modifications are necessary. // TODO: epsilon for numerical robustness? bool inside = Max3(abs(hapVertLS.x), abs(hapVertLS.y), abs(hapVertLS.z)) < hapVertLS.w; @@ -621,10 +624,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI float3 rapVertNDC = float3(rapVertCS.xy * 0.5 + 0.5, rapVertCS.z); float rbpVertVSz = hbpVertVS.z * rcp(hbpVertVS.w); - ndcAaBbMinPt.xyz = min(ndcAaBbMinPt.xyz, rapVertNDC); - ndcAaBbMaxPt.xyz = max(ndcAaBbMaxPt.xyz, rapVertNDC); - ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, rbpVertVSz); - ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, rbpVertVSz); + ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); + ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVSz)); } } } @@ -680,8 +681,12 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI { uint f = NthBitLow(clipFaceMask, n); - ClipFaceAgainstViewVolumeAndUpdateAaBb(f, behindMasksOfVerts, firstVertexOffset, g_mInvProjection, - ndcAaBbMinPt, ndcAaBbMaxPt); + uint srcBegin, srcSize; + float4 vertRingBuffer[MAX_CLIP_VERTS]; + ClipFaceAgainstViewVolume(f, behindMasksOfVerts, firstVertexOffset, + srcBegin, srcSize, vertRingBuffer); + UpdateAaBb(srcBegin, srcSize, vertRingBuffer, g_isOrthographic != 0, g_mInvProjection, + ndcAaBbMinPt, ndcAaBbMaxPt); } } } @@ -690,7 +695,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // ... #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. - // We must take care of the signed zero ourselves. saturate() does not help here. + // We must take care of -0 ourselves. saturate() does not help here. InterlockedMin(gs_NdcAaBbMinPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); InterlockedMax(gs_NdcAaBbMaxPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); InterlockedMin(gs_NdcAaBbMinPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); From e4d275c7ea890b6d6689b514e1482f04bcaf7dff Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 10 Aug 2020 13:10:23 -0700 Subject: [PATCH 011/209] Optimize LUT --- .../Lighting/LightLoop/scrbound.compute | 144 +++++++++--------- 1 file changed, 71 insertions(+), 73 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index ee373ec6081..8d20322bccf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -60,7 +60,8 @@ float4x4 Translation4x4(float3 d) return M; } -float3x3 Rotation3x3(float3 xAxis, float3 yAxis, float3 zAxis) +// Scale followed by rotation (scaled axes). +float3x3 ScaledRotation3x3(float3 xAxis, float3 yAxis, float3 zAxis) { float3x3 R = float3x3(xAxis, yAxis, zAxis); float3x3 C = transpose(R); // Row to column @@ -89,7 +90,7 @@ float4x4 Homogenize3x3(float3x3 R) float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) { - float b = (f + n) * rcp(f - n); // z: [-1, 1] + float b = (f + n) * rcp(f - n); // Z in [-1, 1] float c = -2 * f * n * rcp(f - n); // No Z-reversal return float4x4(g/a, 0, 0, 0, @@ -98,7 +99,7 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) 0, 0, 1, 0); } -#define CLEAR_SIGN_BIT(X) (asuint(X) & INT_MAX) +#define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) #define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks // Clipping a plane by a cube may produce a hexagon (6-gon). @@ -116,43 +117,60 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) // All planes and faces are always in the standard order (see below). // Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. -#define FACE_LEFT (1 << 0) // x = -1 -#define FACE_RIGHT (1 << 1) // x = +1 -#define FACE_FRONT (1 << 2) // y = -1 -#define FACE_BACK (1 << 3) // y = +1 -#define FACE_TOP (1 << 4) // z = -1 -#define FACE_BOTTOM (1 << 5) // z = +1 +#define FACE_LEFT (1 << 0) // -X z +#define FACE_RIGHT (1 << 1) // +X / +#define FACE_TOP (1 << 2) // -Y 0 -- x +#define FACE_BOTTOM (1 << 3) // +Y | +#define FACE_FRONT (1 << 4) // -Z y +#define FACE_BACK (1 << 5) // +Z #define FACE_MASK ((1 << NUM_FACES) - 1) -// TODO: the compiler generates 'tbuffer_load_format_x' instructions -// when we access the look-up tables. Can we avoid this? - -// TODO: try vert order (0 0 0), (1 0 0), (0 1 0), (1 1 0), (0 0 1), (1 0 1), (0 1 1), (1 1 1) +// A list of vertices for each face (CCW order w.r.t. its normal, starting from the LSB). +#define VERT_LIST_LEFT ((2) << 9 | (6) << 6 | (4) << 3 | (0) << 0) +#define VERT_LIST_RIGHT ((5) << 9 | (7) << 6 | (3) << 3 | (1) << 0) +#define VERT_LIST_TOP ((1) << 9 | (3) << 6 | (2) << 3 | (0) << 0) +#define VERT_LIST_BOTTOM ((6) << 9 | (7) << 6 | (5) << 3 | (4) << 0) +#define VERT_LIST_FRONT ((4) << 9 | (5) << 6 | (1) << 3 | (0) << 0) +#define VERT_LIST_BACK ((3) << 9 | (7) << 6 | (6) << 3 | (2) << 0) // All vertices are always in the standard order (see below). -static const uint s_FaceMasksOfVerts[NUM_VERTS] = +uint GetFaceMaskOfVertex(uint v) { - FACE_LEFT | FACE_FRONT | FACE_TOP, // 0: (-1, -1, -1) - FACE_RIGHT | FACE_FRONT | FACE_TOP, // 1: (+1, -1, -1) - FACE_RIGHT | FACE_BACK | FACE_TOP, // 2: (+1, +1, -1) - FACE_LEFT | FACE_BACK | FACE_TOP, // 3: (-1, +1, -1) - FACE_LEFT | FACE_FRONT | FACE_BOTTOM, // 4: (-1, -1, +1) - FACE_RIGHT | FACE_FRONT | FACE_BOTTOM, // 5: (+1, -1, +1) - FACE_RIGHT | FACE_BACK | FACE_BOTTOM, // 6: (+1, +1, +1) - FACE_LEFT | FACE_BACK | FACE_BOTTOM // 7: (-1, +1, +1) + // 0: (-1, -1, -1) -> { FACE_LEFT | FACE_TOP | FACE_FRONT } + // 1: (+1, -1, -1) -> { FACE_RIGHT | FACE_TOP | FACE_FRONT } + // 2: (-1, +1, -1) -> { FACE_LEFT | FACE_BOTTOM | FACE_FRONT } + // 3: (+1, +1, -1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_FRONT } + // 4: (-1, -1, +1) -> { FACE_LEFT | FACE_TOP | FACE_BACK } + // 5: (+1, -1, +1) -> { FACE_RIGHT | FACE_TOP | FACE_BACK } + // 6: (-1, +1, +1) -> { FACE_LEFT | FACE_BOTTOM | FACE_BACK } + // 7: (+1, +1, +1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_BACK } + // ((v & 1) == 0) ? 1 : 2) | ((v & 2) == 0) ? 4 : 8) | ((v & 4) == 0) ? 16 : 32) + uint f = (FACE_LEFT << BitFieldExtract(v, 0, 1)) + | (FACE_TOP << BitFieldExtract(v, 1, 1)) + | (FACE_FRONT << BitFieldExtract(v, 2, 1)); + + return f; }; -// CCW order (starting with the LSB) of vertices for each face (w.r.t. its normal), -// with normals pointing in the interior of the volume. -static const uint s_VertMasksOfFaces[NUM_FACES] = +float3 GenerateVertexOfStandardCube(uint v) { - (3) << 9 | (7) << 6 | (4) << 3 | (0) << 0, // 0: FACE_LEFT - (5) << 9 | (6) << 6 | (2) << 3 | (1) << 0, // 1: FACE_RIGHT - (4) << 9 | (5) << 6 | (1) << 3 | (0) << 0, // 2: FACE_FRONT - (6) << 9 | (7) << 6 | (3) << 3 | (2) << 0, // 3: FACE_BACK - (1) << 9 | (2) << 6 | (3) << 3 | (0) << 0, // 4: FACE_TOP - (7) << 9 | (6) << 6 | (5) << 3 | (4) << 0 // 5: FACE_BOTTOM -}; + float3 p; + + p.x = ((v & 1) == 0) ? -1 : 1; + p.y = ((v & 2) == 0) ? -1 : 1; + p.z = ((v & 4) == 0) ? -1 : 1; + + return p; +} + +uint GetVertexListOfFace(uint f) +{ + static const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, + (VERT_LIST_BOTTOM << 12) | VERT_LIST_TOP, + (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); + + return BitFieldExtract(allVertLists[f >> 1], 12 * (f & 1), 12); +} // 5 arrays * 128 elements * 4 bytes each = 2560 bytes. groupshared float gs_HapVertsX[VERTS_PER_GROUP]; @@ -182,11 +200,11 @@ groupshared uint gs_NdcAaBbMaxPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) { uint cullMaskOfFace = FACE_MASK; // Initially behind - uint vertMaskOfFace = s_VertMasksOfFaces[f]; + uint vertListOfFace = GetVertexListOfFace(f); for (int j = 0; j < 4; j++) { - uint v = BitFieldExtract(vertMaskOfFace, 3 * j, 3); + uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); // Non-zero if ALL the vertices are behind any of the planes. cullMaskOfFace &= behindMasksOfVerts[v]; } @@ -202,9 +220,9 @@ struct ClipVertex ClipVertex CreateClipVertex(uint p, float4 v) { - bool evenPlane = (p % 2) == 0; + bool evenPlane = (p & 1) == 0; - float c = v[p / 2]; + float c = v[p >> 1]; float w = v.w; ClipVertex cv; @@ -295,7 +313,7 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint srcSize = 4; uint clipMaskOfFace = 0; // Initially in front - uint vertMaskOfFace = s_VertMasksOfFaces[f]; + uint vertListOfFace = GetVertexListOfFace(f); for (int j = 0; j < 4; j++) { @@ -311,11 +329,9 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint vertRingBuffer[j].w = gs_HapVertsW[firstVertexOffset + v]; } - const uint numPlanesToClipAgainst = countbits(clipMaskOfFace); // [1, 6] - // Sutherland-Hodgeman polygon clipping algorithm. // It works by clipping the entire polygon against one clipping plane at a time. - for (uint j = 0; j < numPlanesToClipAgainst; j++) + while (clipMaskOfFace != 0) { uint p = firstbitlow(clipMaskOfFace); @@ -336,13 +352,12 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT #ifdef DUMB_COMPILER uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; #endif - for (uint j = srcBegin; j < (srcBegin + srcSize); j++) { #ifndef DUMB_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif - float4 hapVert = vertRingBuffer[modSrcIdx]; + float4 hapVert = vertRingBuffer[modSrcIdx]; // Clamp to the bounds in case of numerical errors (may still generate -0). float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); float rbpVertVSz = hapVert.w; @@ -477,22 +492,17 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI { uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; - // rbpVerts[0] = rbpC - rbpX * scale.x - rbpY * scale.y - rbpZ; // (-1, -1, -1) - // rbpVerts[1] = rbpC + rbpX * scale.x - rbpY * scale.y - rbpZ; // (+1, -1, -1) - // rbpVerts[2] = rbpC + rbpX * scale.x + rbpY * scale.y - rbpZ; // (+1, +1, -1) - // rbpVerts[3] = rbpC - rbpX * scale.x + rbpY * scale.y - rbpZ; // (-1, +1, -1) - // rbpVerts[4] = rbpC - rbpX - rbpY + rbpZ; // (-1, -1, +1) - // rbpVerts[5] = rbpC + rbpX - rbpY + rbpZ; // (+1, -1, +1) - // rbpVerts[6] = rbpC + rbpX + rbpY + rbpZ; // (+1, +1, +1) - // rbpVerts[7] = rbpC - rbpX + rbpY + rbpZ; // (-1, +1, +1) + // rbpVerts[0] = rbpC - rbpX * scale - rbpY * scale - rbpZ; (-s, -s, -1) + // rbpVerts[1] = rbpC + rbpX * scale - rbpY * scale - rbpZ; (+s, -s, -1) + // rbpVerts[2] = rbpC - rbpX * scale + rbpY * scale - rbpZ; (-s, +s, -1) + // rbpVerts[3] = rbpC + rbpX * scale + rbpY * scale - rbpZ; (+s, +s, -1) + // rbpVerts[4] = rbpC - rbpX - rbpY + rbpZ; (-1, -1, +1) + // rbpVerts[5] = rbpC + rbpX - rbpY + rbpZ; (+1, -1, +1) + // rbpVerts[6] = rbpC - rbpX + rbpY + rbpZ; (-1, +1, +1) + // rbpVerts[7] = rbpC + rbpX + rbpY + rbpZ; (+1, +1, +1) - float3 m; // See the comment above - - m.x = (countbits(v % 4) == 1) ? 1 : -1; - m.y = ((v & 2) != 0) ? 1 : -1; - m.z = (v >= 4) ? 1 : -1; - - m.xy *= (v >= 4) ? 1 : scale; + float3 m = GenerateVertexOfStandardCube(v); + m.xy *= ((v & 4) == 0) ? scale : 1; // X, Y in [-scale, scale] float3 rbpVertVS = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; // Avoid generating (w = 0). @@ -538,7 +548,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI } else // Outside { - cullClipFaceMask |= s_FaceMasksOfVerts[v]; + cullClipFaceMask |= GetFaceMaskOfVertex(v); } gs_HapVertsX[firstVertexOffset + v] = hapVert.x; @@ -567,7 +577,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI // The light volume is a special type of cuboid - a right frustum. // We can exploit this fact by building a light-space projection matrix. float4x4 invTranslateToLightSpace = Translation4x4(-rbpC); - float4x4 invRotateAndScaleInLightSpace = Homogenize3x3(Invert3x3(Rotation3x3(rbpX, rbpY, rbpZ))); + float4x4 invRotateAndScaleInLightSpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); // TODO: avoid full inversion by using unit vectors and passing magnitudes explicitly. // This (orthographic) projection matrix maps a view-space point to a light-space [-1, 1]^3 cube. @@ -592,20 +602,8 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI { uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; - // rapVertsCS[0] = (-1, -1, 0) - // rapVertsCS[1] = (+1, -1, 0) - // rapVertsCS[2] = (+1, +1, 0) - // rapVertsCS[3] = (-1, +1, 0) - // rapVertsCS[4] = (-1, -1, 1) - // rapVertsCS[5] = (+1, -1, 1) - // rapVertsCS[6] = (+1, +1, 1) - // rapVertsCS[7] = (-1, +1, 1) - - float3 rapVertCS; // See the comment above - - rapVertCS.x = (countbits(v % 4) == 1) ? 1 : -1; - rapVertCS.y = ((v & 2) != 0) ? 1 : -1; - rapVertCS.z = (v >= 4) ? 1 : 0; + float3 rapVertCS = GenerateVertexOfStandardCube(v); + rapVertCS.z = rapVertCS.z * 0.5 + 0.5; // View's projection matrix MUST map Z to [0, 1] float4 hbpVertVS = mul(g_mInvProjection, float4(rapVertCS, 1)); // Clip to view space float4 hapVertLS = mul(lightSpaceMatrix, hbpVertVS); // View to light space From e1a5fccc9901689a4aa0b9e4742762a52d54885e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 12:54:05 -0700 Subject: [PATCH 012/209] Add wave intrinsic support --- .../Lighting/LightLoop/scrbound.compute | 66 ++++++++++++++----- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 8d20322bccf..76a53afb673 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -23,7 +23,6 @@ RWStructuredBuffer g_vBoundsBuffer : register( u0 ); #define Z_BINNING #define DUMB_COMPILER -// #define USE_WAVE_INTRINSICS // We use TGSM and atomic operations if wave intrinsics are not supported #ifdef Z_BINNING @@ -165,9 +164,10 @@ float3 GenerateVertexOfStandardCube(uint v) uint GetVertexListOfFace(uint f) { - static const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, - (VERT_LIST_BOTTOM << 12) | VERT_LIST_TOP, - (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); + // Warning: don't add 'static' here unless you want really bad code gen. + const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, + (VERT_LIST_BOTTOM << 12) | VERT_LIST_TOP, + (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); return BitFieldExtract(allVertLists[f >> 1], 12 * (f & 1), 12); } @@ -179,7 +179,7 @@ groupshared float gs_HapVertsZ[VERTS_PER_GROUP]; groupshared float gs_HapVertsW[VERTS_PER_GROUP]; groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) -#ifndef USE_WAVE_INTRINSICS +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // 1 array * 16 elements * 4 bytes each = 64 bytes. groupshared uint gs_CullClipFaceMasks[LIGHTS_PER_GROUP]; // 6 faces each (HLSL does not support small data types) @@ -194,7 +194,7 @@ groupshared uint gs_NdcAaBbMinPtZ[LIGHTS_PER_GROUP]; // Note that min-max Z can groupshared uint gs_NdcAaBbMaxPtZ[LIGHTS_PER_GROUP]; // from min-max W if the projection is oblique. groupshared uint gs_NdcAaBbMinPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate groupshared uint gs_NdcAaBbMaxPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate -#endif // USE_WAVE_INTRINSICS +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS // Returns 'true' if it manages to cull the face. bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) @@ -317,7 +317,7 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint for (int j = 0; j < 4; j++) { - uint v = BitFieldExtract(vertMaskOfFace, 3 * j, 3); + uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); // Non-zero if ANY of the vertices are behind any of the planes. clipMaskOfFace |= behindMasksOfVerts[v]; @@ -462,7 +462,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI const float3 rbpY = lgtDat.boxAxisY.xyz; // Pre-scaled const float3 rbpZ = lgtDat.boxAxisZ.xyz; // Pre-scaled -#ifndef USE_WAVE_INTRINSICS +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // (0) Initialize the TGSM. if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts { @@ -476,7 +476,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI gs_NdcAaBbMinPtW[groupLocalLightIndex] = asuint(FLT_INF); gs_NdcAaBbMaxPtW[groupLocalLightIndex] = asuint(0.0f); } -#endif // USE_WAVE_INTRINSICS +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS float4 ndcAaBbMinPt = float4(1, 1, 1, FLT_INF); float4 ndcAaBbMaxPt = 0; @@ -558,8 +558,15 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI gs_BehindMasksOfVerts[firstVertexOffset + v] = behindMask; } -#ifdef USE_WAVE_INTRINSICS - // ... +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (uint i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + // TODO: Francesco - expose the right intrinsic. + cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, orMask, 0, xorMask); + } #else InterlockedOr(gs_CullClipFaceMasks[groupLocalLightIndex], cullClipFaceMask); @@ -628,6 +635,10 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI } } +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + GroupMemoryBarrierWithGroupSync(); +#endif + uint behindMasksOfVerts[NUM_VERTS]; for (uint i = 0; i < NUM_VERTS; i++) @@ -656,8 +667,15 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI } } -#ifdef USE_WAVE_INTRINSICS - // ... +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (uint i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + // TODO: Francesco - expose the right intrinsic. + cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, orMask, 0, xorMask); + } #else InterlockedAnd(gs_CullClipFaceMasks[groupLocalLightIndex], cullClipFaceMask); @@ -689,11 +707,25 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI } } -#ifdef USE_WAVE_INTRINSICS - // ... +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (uint i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + // TODO: Francesco - expose the right intrinsic. + ndcAaBbMinPt.x = min(ndcAaBbMinPt.x, LaneSwizzle(ndcAaBbMinPt.x, orMask, 0, xorMask)); + ndcAaBbMaxPt.x = max(ndcAaBbMaxPt.x, LaneSwizzle(ndcAaBbMaxPt.x, orMask, 0, xorMask)); + ndcAaBbMinPt.y = min(ndcAaBbMinPt.y, LaneSwizzle(ndcAaBbMinPt.y, orMask, 0, xorMask)); + ndcAaBbMaxPt.y = max(ndcAaBbMaxPt.y, LaneSwizzle(ndcAaBbMaxPt.y, orMask, 0, xorMask)); + ndcAaBbMinPt.z = min(ndcAaBbMinPt.z, LaneSwizzle(ndcAaBbMinPt.z, orMask, 0, xorMask)); + ndcAaBbMaxPt.z = max(ndcAaBbMaxPt.z, LaneSwizzle(ndcAaBbMaxPt.z, orMask, 0, xorMask)); + ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, LaneSwizzle(ndcAaBbMinPt.w, orMask, 0, xorMask)); + ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, LaneSwizzle(ndcAaBbMaxPt.w, orMask, 0, xorMask)); + } #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. - // We must take care of -0 ourselves. saturate() does not help here. + // We must take care of -0 ourselves. saturate() does not help. InterlockedMin(gs_NdcAaBbMinPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); InterlockedMax(gs_NdcAaBbMaxPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); InterlockedMin(gs_NdcAaBbMinPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); @@ -713,7 +745,7 @@ void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupI ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[groupLocalLightIndex]); ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[groupLocalLightIndex]); ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[groupLocalLightIndex]); -#endif // USE_WAVE_INTRINSICS +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts { From c648e2ac35a6b18f122097e7a928ab233b1e86cd Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 16:07:59 -0700 Subject: [PATCH 013/209] Fix group count --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 57f186dbb82..897fa9c4d4b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3083,7 +3083,12 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList); - cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, (parameters.totalLightCount + 7) / 8, parameters.viewCount, 1); + const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + + int groupCount = HDUtils.DivRoundUp(parameters.totalLightCount * threadsPerLight, threadsPerGroup); + + cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); } } From d6cfa8fc130d3cf733be3a5c2ea9a37f862cf137 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 16:14:11 -0700 Subject: [PATCH 014/209] Reduce the kernel count to 1 --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 10 +--------- .../Runtime/Lighting/LightLoop/scrbound.compute | 17 ++++++++++------- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 897fa9c4d4b..c1850bd6602 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -696,7 +696,6 @@ enum ClusterDepthSource : int { "TileLightListGen_NoDepthRT_SrcBigTile", "TileLightListGen_DepthRT_SrcBigTile_Oblique", "TileLightListGen_DepthRT_MSAA_SrcBigTile_Oblique" } }; - static int s_GenAABBKernel; static int s_GenListPerTileKernel; static int[,] s_ClusterKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; static int[,] s_ClusterObliqueKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; @@ -879,8 +878,6 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) m_MaxLightsOnScreen = m_MaxDirectionalLightsOnScreen + m_MaxPunctualLightsOnScreen + m_MaxAreaLightsOnScreen + m_MaxEnvLightsOnScreen; m_MaxPlanarReflectionOnScreen = lightLoopSettings.maxPlanarReflectionOnScreen; - s_GenAABBKernel = buildScreenAABBShader.FindKernel("ScreenBoundsAABB"); - // Cluster { s_ClearVoxelAtomicKernel = clearClusterAtomicIndexShader.FindKernel("ClearAtomic"); @@ -3403,12 +3400,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera // Screen space AABB parameters.screenSpaceAABBShader = buildScreenAABBShader; - parameters.screenSpaceAABBShader.shaderKeywords = null; - if (isProjectionOblique) - { - parameters.screenSpaceAABBShader.EnableKeyword("USE_OBLIQUE_MODE"); - } - parameters.screenSpaceAABBKernel = s_GenAABBKernel; + parameters.screenSpaceAABBKernel = 0; // Big tile prepass parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 76a53afb673..438e5fdc77f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -1,11 +1,6 @@ // The implementation is based on the demo on "fine pruned tiled lighting" published in GPU Pro 7. // https://github.com/wolfgangfengel/GPU-Pro-7 -#pragma kernel ScreenBoundsAABB - -#pragma multi_compile _ USE_OBLIQUE_MODE - - #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" @@ -14,6 +9,14 @@ // #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch +#pragma kernel GenLightAABB + +uniform int g_isOrthographic; +uniform int g_iNrVisibLights; + +uniform float4x4 g_mInvProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; +uniform float4x4 g_mProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; + StructuredBuffer g_data : register( t0 ); #define NR_THREADS 64 @@ -403,7 +406,7 @@ void CalcBound(out bool2 bIsMinValid, out bool2 bIsMaxValid, out float2 vMin, ou #endif // Z_BINNING [numthreads(NR_THREADS, 1, 1)] -void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) +void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) { uint groupID = u3GroupID.x; uint eyeIndex = u3GroupID.y; // currently, can only be 0 or 1 @@ -1232,4 +1235,4 @@ void CalcBound(out bool2 bIsMinValid, out bool2 bIsMaxValid, out float2 vMin, ou vMax = A; } -#endif // !Z_BINNING \ No newline at end of file +#endif // !Z_BINNING From f3f540f08d92cf5d5a257f48be84b853deb8f4a1 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 16:49:23 -0700 Subject: [PATCH 015/209] Remove old code --- .../Lighting/LightLoop/scrbound.compute | 701 +++--------------- 1 file changed, 96 insertions(+), 605 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 438e5fdc77f..86144d43973 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -11,23 +11,21 @@ #pragma kernel GenLightAABB +/* ------------------------------ Inputs ------------------------------------ */ + uniform int g_isOrthographic; uniform int g_iNrVisibLights; uniform float4x4 g_mInvProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; uniform float4x4 g_mProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; -StructuredBuffer g_data : register( t0 ); - -#define NR_THREADS 64 +StructuredBuffer g_data : register(t0); -// output buffer -RWStructuredBuffer g_vBoundsBuffer : register( u0 ); +/* ------------------------------ Outputs ----------------------------------- */ -#define Z_BINNING -#define DUMB_COMPILER +RWStructuredBuffer g_vBoundsBuffer : register(u0); -#ifdef Z_BINNING +/* ------------------------------ Utilities --------------------------------- */ // Returns the location of the N-th set bit starting from the lowest order bit and working upward. // Slow implementation - do not use for large bit sets. @@ -101,6 +99,10 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) 0, 0, 1, 0); } +/* ------------------------------ Implementation ---------------------------- */ + +#define DUMB_COMPILER // Improve the quality of generated code + #define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) #define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks @@ -349,7 +351,7 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint } void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERTS], - bool isOrthoProj, float4x4 invProj, + bool isOrthoProj, float4x4 invProjMat, inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) { #ifdef DUMB_COMPILER @@ -367,7 +369,7 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT if (isOrthoProj) // Must replace (w = 1) { - rbpVertVSz = dot(invProj[2], hapVert); + rbpVertVSz = dot(invProjMat[2], hapVert); } ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); @@ -379,105 +381,70 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT } } -#else // !Z_BINNING - -#define THREADS_PER_LIGHT (8) -#define THREADS_PER_GROUP (64) -#define LIGHTS_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_LIGHT) -#define MAX_PNTS (9) // strictly this should be 10=6+4 but we get more wavefronts and 10 seems to never hit (fingers crossed) - // However, worst case the plane that would be skipped if such an extreme case ever happened would be backplane - // clipping gets skipped which doesn't cause any errors. - - -// LDS (2496 bytes) -groupshared float posX[MAX_PNTS*8*2]; -groupshared float posY[MAX_PNTS*8*2]; -groupshared float posZ[MAX_PNTS*8*2]; -groupshared float posW[MAX_PNTS*8*2]; -groupshared unsigned int clipFlags[48]; - +//********************************************************************************************** +// The goal of this program is to compute the AABB of the light in the NDC space ([0, 1] range). +// The light is represented by a convex volume (a cuboid) with 6 faces (planar quads) and 8 vertices. +// +// Since a light volume may be partially off-screen, we must clip it before computing the AABB. +// Clipping the resulting AABB (rather than the light volume itself) may result in a loose AABB. +// +// To avoid having to deal with the "Moebius twist" property of the perspective transform, +// we perform clipping using the homogeneous (projective) post-perspective coordinates. +// This clipping method in described in Blinn's paper titled "Line Clipping". +// +// The algorithm processes a light on 4 threads. While all 6 faces may require clipping in the +// worst case, clipping more than 4 faces is very uncommon (typically, we clip 0, 3 or 4). +// Some faces may require culling rather than clipping (the former is simpler). +// +// It's important to realize that face culling may end up culling 5 (or even all 6) faces. +// This means that the clipped light volume may be reduced to a single polygon, or nothing at all. +// (Imagine a view volume completely or partially inside a light volume). +// Therefore, we must perform view-volume-corner-inside-light-volume tests. +// +// +// Notation: +// rbp - real (3D) coordinates before perspective +// hbp - hom. (4D) coordinates before perspective +// hap - hom. (4D) coordinates after perspective +// rap - real (3D) coordinates after perspective (after division by w) +// ********************************************************************************************* + +[numthreads(THREADS_PER_GROUP, 1, 1)] +void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +{ + const uint t = threadID; + const uint g = groupID.x; + const uint eyeIndex = groupID.y; // Currently, can only be 0 or 1 -unsigned int GetClip(const float4 P); -int ClipAgainstPlane(const int iSrcIndex, const int iNrSrcVerts, const int subLigt, const int p); -void CalcBound(out bool2 bIsMinValid, out bool2 bIsMaxValid, out float2 vMin, out float2 vMax, float4x4 InvProjection, float3 pos_view_space, float r); + const uint intraGroupLightIndex = t / THREADS_PER_LIGHT; + const uint globalLightIndex = g * LIGHTS_PER_GROUP + intraGroupLightIndex; + const uint firstVertexOffset = intraGroupLightIndex * NUM_VERTS; -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl" + const int eyeAdjustedInputOffset = GenerateLightCullDataIndex(globalLightIndex, g_iNrVisibLights, eyeIndex); + const SFiniteLightBound cullData = g_data[eyeAdjustedInputOffset]; -#endif // Z_BINNING + const float4x4 projMat = g_mProjectionArr[eyeIndex]; + const float4x4 invProjMat = g_mInvProjectionArr[eyeIndex]; -[numthreads(NR_THREADS, 1, 1)] -void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) -{ - uint groupID = u3GroupID.x; - uint eyeIndex = u3GroupID.y; // currently, can only be 0 or 1 - - // The g_ is preserved in order to make cross-pipeline (FPTL) updates easier - float4x4 g_mInvProjection = g_mInvProjectionArr[eyeIndex]; - float4x4 g_mProjection = g_mProjectionArr[eyeIndex]; - - //uint vindex = groupID * NR_THREADS + threadID; - unsigned int g = groupID; - unsigned int t = threadID; - - const int subLigt = (uint) (t/THREADS_PER_LIGHT); - const int lgtIndex = subLigt+(uint) g*LIGHTS_PER_GROUP; - const int sideIndex = (uint) (t%8); - - const int eyeAdjustedLgtIndex = GenerateLightCullDataIndex(lgtIndex, g_iNrVisibLights, eyeIndex); - SFiniteLightBound lgtDat = g_data[eyeAdjustedLgtIndex]; - -#ifdef Z_BINNING - //********************************************************************************************** - // The goal of this program is to compute the AABB of the light in the NDC space ([0, 1] range). - // The light is represented by a convex volume (a cuboid) with 6 faces (planar quads) and 8 vertices. - // - // Since a light volume may be partially off-screen, we must clip it before computing the AABB. - // Clipping the resulting AABB (rather than the light volume itself) may result in a loose AABB. - // - // To avoid having to deal with the "Moebius twist" property of the perspective transform, - // we perform clipping using the homogeneous (projective) post-perspective coordinates. - // This clipping method in described in Blinn's paper titled "Line Clipping". - // - // The algorithm processes a light on 4 threads. While all 6 faces may require clipping in the - // worst case, clipping more than 4 faces is very uncommon (typically, we clip 0, 3 or 4). - // Some faces may require culling rather than clipping (the former is simpler). - // - // It's important to realize that face culling may end up culling 5 (or even all 6) faces. - // This means that the clipped light volume may be reduced to a single polygon, or nothing at all. - // (Imagine a view volume completely or partially inside a light volume). - // Therefore, we must perform view-volume-corner-inside-light-volume tests. - // - // - // Notation: - // rbp - real (3D) coordinates before perspective - // hbp - hom. (4D) coordinates before perspective - // hap - hom. (4D) coordinates after perspective - // rap - real (3D) coordinates after perspective (after division by w) - // ********************************************************************************************* - - const uint groupLocalLightIndex = t / THREADS_PER_LIGHT; - const uint firstVertexOffset = NUM_VERTS * groupLocalLightIndex; - - const float scale = lgtDat.scaleXY; // scale.x = scale.y - const float3 rbpC = lgtDat.center.xyz; - // TODO: store X, Y, Scale - const float3 rbpX = lgtDat.boxAxisX.xyz; // Pre-scaled - const float3 rbpY = lgtDat.boxAxisY.xyz; // Pre-scaled - const float3 rbpZ = lgtDat.boxAxisZ.xyz; // Pre-scaled + const float scale = cullData.scaleXY; // scale.x = scale.y + const float3 rbpC = cullData.center.xyz; // View-space + const float3 rbpX = cullData.boxAxisX.xyz; // Pre-scaled + const float3 rbpY = cullData.boxAxisY.xyz; // Pre-scaled + const float3 rbpZ = cullData.boxAxisZ.xyz; // Pre-scaled #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // (0) Initialize the TGSM. if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts { - gs_CullClipFaceMasks[groupLocalLightIndex] = 0; // Initially inside - gs_NdcAaBbMinPtX[groupLocalLightIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtX[groupLocalLightIndex] = asuint(0.0f); - gs_NdcAaBbMinPtY[groupLocalLightIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtY[groupLocalLightIndex] = asuint(0.0f); - gs_NdcAaBbMinPtZ[groupLocalLightIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtZ[groupLocalLightIndex] = asuint(0.0f); - gs_NdcAaBbMinPtW[groupLocalLightIndex] = asuint(FLT_INF); - gs_NdcAaBbMaxPtW[groupLocalLightIndex] = asuint(0.0f); + gs_CullClipFaceMasks[intraGroupLightIndex] = 0; // Initially inside + gs_NdcAaBbMinPtX[intraGroupLightIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtX[intraGroupLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtY[intraGroupLightIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtY[intraGroupLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtZ[intraGroupLightIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtZ[intraGroupLightIndex] = asuint(0.0f); + gs_NdcAaBbMinPtW[intraGroupLightIndex] = asuint(FLT_INF); + gs_NdcAaBbMaxPtW[intraGroupLightIndex] = asuint(0.0f); } #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS @@ -511,7 +478,7 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) // Avoid generating (w = 0). rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; - float4 hapVert = mul(g_mProjection, float4(rbpVertVS, 1)); + float4 hapVert = mul(projMat, float4(rbpVertVS, 1)); // Warning: the W component may be negative. // Flipping the -W pyramid by negating all coordinates is incorrect @@ -571,11 +538,11 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, orMask, 0, xorMask); } #else - InterlockedOr(gs_CullClipFaceMasks[groupLocalLightIndex], cullClipFaceMask); + InterlockedOr(gs_CullClipFaceMasks[intraGroupLightIndex], cullClipFaceMask); GroupMemoryBarrierWithGroupSync(); - cullClipFaceMask = gs_CullClipFaceMasks[groupLocalLightIndex]; + cullClipFaceMask = gs_CullClipFaceMasks[intraGroupLightIndex]; #endif // (2) Test the corners of the view volume. @@ -615,8 +582,8 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) float3 rapVertCS = GenerateVertexOfStandardCube(v); rapVertCS.z = rapVertCS.z * 0.5 + 0.5; // View's projection matrix MUST map Z to [0, 1] - float4 hbpVertVS = mul(g_mInvProjection, float4(rapVertCS, 1)); // Clip to view space - float4 hapVertLS = mul(lightSpaceMatrix, hbpVertVS); // View to light space + float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space + float4 hapVertLS = mul(lightSpaceMatrix, hbpVertVS); // View to light space // Consider the vertex to be inside the light volume if: // -w < x < w @@ -680,11 +647,11 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, orMask, 0, xorMask); } #else - InterlockedAnd(gs_CullClipFaceMasks[groupLocalLightIndex], cullClipFaceMask); + InterlockedAnd(gs_CullClipFaceMasks[intraGroupLightIndex], cullClipFaceMask); GroupMemoryBarrierWithGroupSync(); - cullClipFaceMask = gs_CullClipFaceMasks[groupLocalLightIndex]; + cullClipFaceMask = gs_CullClipFaceMasks[intraGroupLightIndex]; #endif // (4) Clip the faces. @@ -704,7 +671,7 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) float4 vertRingBuffer[MAX_CLIP_VERTS]; ClipFaceAgainstViewVolume(f, behindMasksOfVerts, firstVertexOffset, srcBegin, srcSize, vertRingBuffer); - UpdateAaBb(srcBegin, srcSize, vertRingBuffer, g_isOrthographic != 0, g_mInvProjection, + UpdateAaBb(srcBegin, srcSize, vertRingBuffer, g_isOrthographic != 0, invProjMat, ndcAaBbMinPt, ndcAaBbMaxPt); } } @@ -729,510 +696,34 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. // We must take care of -0 ourselves. saturate() does not help. - InterlockedMin(gs_NdcAaBbMinPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); - InterlockedMax(gs_NdcAaBbMaxPtX[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); - InterlockedMin(gs_NdcAaBbMinPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); - InterlockedMax(gs_NdcAaBbMaxPtY[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); - InterlockedMin(gs_NdcAaBbMinPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.z))); - InterlockedMax(gs_NdcAaBbMaxPtZ[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.z))); - InterlockedMin(gs_NdcAaBbMinPtW[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); - InterlockedMax(gs_NdcAaBbMaxPtW[groupLocalLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); + InterlockedMin(gs_NdcAaBbMinPtX[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); + InterlockedMax(gs_NdcAaBbMaxPtX[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); + InterlockedMin(gs_NdcAaBbMinPtY[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); + InterlockedMax(gs_NdcAaBbMaxPtY[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); + InterlockedMin(gs_NdcAaBbMinPtZ[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.z))); + InterlockedMax(gs_NdcAaBbMaxPtZ[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.z))); + InterlockedMin(gs_NdcAaBbMinPtW[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); + InterlockedMax(gs_NdcAaBbMaxPtW[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); GroupMemoryBarrierWithGroupSync(); - ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[groupLocalLightIndex]); - ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[groupLocalLightIndex]); - ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[groupLocalLightIndex]); - ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[groupLocalLightIndex]); - ndcAaBbMinPt.z = asfloat(gs_NdcAaBbMinPtZ[groupLocalLightIndex]); - ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[groupLocalLightIndex]); - ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[groupLocalLightIndex]); - ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[groupLocalLightIndex]); + ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[intraGroupLightIndex]); + ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[intraGroupLightIndex]); + ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[intraGroupLightIndex]); + ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[intraGroupLightIndex]); + ndcAaBbMinPt.z = asfloat(gs_NdcAaBbMinPtZ[intraGroupLightIndex]); + ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[intraGroupLightIndex]); + ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupLightIndex]); + ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupLightIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts { - // Each light's AABB is represented by two float3s, the min and max of the box. - // And for stereo, we have two sets of lights. Therefore, each eye has a set of mins, followed by - // a set of maxs, and each set is equal to g_iNrVisibLights. - const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex); - - g_vBoundsBuffer[boundsIndices.min] = ndcAaBbMinPt; - g_vBoundsBuffer[boundsIndices.max] = ndcAaBbMaxPt; - } - -#else // !Z_BINNING - const float3 boxX = lgtDat.boxAxisX.xyz; - const float3 boxY = lgtDat.boxAxisY.xyz; - 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; - - { - if(sideIndex<6 && lgtIndex<(int) g_iNrVisibLights) // mask 2 out of 8 threads - { - float3 q0, q1, q2, q3; - GetHullQuad(q0, q1, q2, q3, boxX, boxY, boxZ, center, scaleXY, sideIndex); - - - const float4 vP0 = mul(g_mProjection, float4(q0, 1)); - const float4 vP1 = mul(g_mProjection, float4(q1, 1)); - const float4 vP2 = mul(g_mProjection, float4(q2, 1)); - const float4 vP3 = mul(g_mProjection, float4(q3, 1)); - - // test vertices of one quad (of the convex hull) for intersection - const unsigned int uFlag0 = GetClip(vP0); - const unsigned int uFlag1 = GetClip(vP1); - const unsigned int uFlag2 = GetClip(vP2); - const unsigned int uFlag3 = GetClip(vP3); - - const float4 vPnts[] = {vP0, vP1, vP2, vP3}; - - // screen-space AABB of one quad (assuming no intersection) - float3 vMin, vMax; - for(int k=0; k<4; k++) - { - float fW = vPnts[k].w; - float fS = fW<0 ? -1 : 1; - float fWabs = fW<0 ? (-fW) : fW; - fW = fS * (fWabs>(i*6))&0x3f; - uFlagAnd &= uClipBits; - uFlagOr |= uClipBits; - } - - uCollectiveAnd &= uFlagAnd; - uCollectiveOr |= uFlagOr; - } - - bool bSetBoundYet = false; - float3 vMin=0.0, vMax=0.0; - if(uCollectiveAnd!=0 || uCollectiveOr==0) // all invisible or all visible (early out) - { - if(uCollectiveOr==0) // all visible - { - for(f=0; f<6; f++) - { - const int sideIndex = f; - - float3 vFaceMi = float3(posX[subLigt*MAX_PNTS*2 + sideIndex + 0], posY[subLigt*MAX_PNTS*2 + sideIndex + 0], posZ[subLigt*MAX_PNTS*2 + sideIndex + 0]); - float3 vFaceMa = float3(posX[subLigt*MAX_PNTS*2 + sideIndex + 6], posY[subLigt*MAX_PNTS*2 + sideIndex + 6], posZ[subLigt*MAX_PNTS*2 + sideIndex + 6]); - - for(int k=0; k<2; k++) - { - float3 vP = k==0 ? vFaceMi : vFaceMa; - if(f==0 && k==0) { vMin=vP; vMax=vP; } - - vMax = max(vMax, vP); vMin = min(vMin, vP); - } - } - bSetBoundYet=true; - } - } - else // :( need true clipping - { - - for(f=0; f<6; f++) - { - float3 q0, q1, q2, q3; - GetHullQuad(q0, q1, q2, q3, boxX, boxY, boxZ, center, scaleXY, f); - - // 4 vertices to a quad of the convex hull in post projection space - const float4 vP0 = mul(g_mProjection, float4(q0, 1)); - const float4 vP1 = mul(g_mProjection, float4(q1, 1)); - const float4 vP2 = mul(g_mProjection, float4(q2, 1)); - const float4 vP3 = mul(g_mProjection, float4(q3, 1)); - - - int iSrcIndex = 0; - - int offs = iSrcIndex*MAX_PNTS+subLigt*MAX_PNTS*2; - - // fill up source clip buffer with the quad - posX[offs+0]=vP0.x; posX[offs+1]=vP1.x; posX[offs+2]=vP2.x; posX[offs+3]=vP3.x; - posY[offs+0]=vP0.y; posY[offs+1]=vP1.y; posY[offs+2]=vP2.y; posY[offs+3]=vP3.y; - posZ[offs+0]=vP0.z; posZ[offs+1]=vP1.z; posZ[offs+2]=vP2.z; posZ[offs+3]=vP3.z; - posW[offs+0]=vP0.w; posW[offs+1]=vP1.w; posW[offs+2]=vP2.w; posW[offs+3]=vP3.w; - - int iNrSrcVerts = 4; - - // do true clipping - for(int p=0; p<6; p++) - { - const int nrVertsDst = ClipAgainstPlane(iSrcIndex, iNrSrcVerts, subLigt, p); - - iSrcIndex = 1-iSrcIndex; - iNrSrcVerts = nrVertsDst; - - if(iNrSrcVerts<3 || iNrSrcVerts>=MAX_PNTS) break; - } - - // final clipped convex primitive is in src buffer - if(iNrSrcVerts>2) - { - int offs_src = iSrcIndex*MAX_PNTS+subLigt*MAX_PNTS*2; - for(int k=0; kradius) - { - float2 vMi, vMa; - bool2 bMi, bMa; - CalcBound(bMi, bMa, vMi, vMa, g_mInvProjection, center, radius); - - vMin.xy = bMi ? max(vMin.xy, vMi) : vMin.xy; - vMax.xy = bMa ? min(vMax.xy, vMa) : vMax.xy; - } - else if(g_isOrthographic!=0) - { - float2 vMi = mul(g_mProjection, float4(center.xyz-radius,1)).xy; // no division needed for ortho - float2 vMa = mul(g_mProjection, float4(center.xyz+radius,1)).xy; // no division needed for ortho - vMin.xy = max(vMin.xy, vMi); - vMax.xy = min(vMax.xy, vMa); - } -#ifndef USE_OBLIQUE_MODE -#if USE_LEFT_HAND_CAMERA_SPACE - if((center.z-radius)>0.0) - { - float4 vPosF = mul(g_mProjection, float4(0,0,center.z-radius,1)); - vMin.z = max(vMin.z, vPosF.z/vPosF.w); - } - if((center.z+radius)>0.0) - { - float4 vPosB = mul(g_mProjection, float4(0,0,center.z+radius,1)); - vMax.z = min(vMax.z, vPosB.z/vPosB.w); - } -#else - if((center.z+radius)<0.0) - { - float4 vPosF = mul(g_mProjection, float4(0,0,center.z+radius,1)); - vMin.z = max(vMin.z, vPosF.z/vPosF.w); - } - if((center.z-radius)<0.0) - { - float4 vPosB = mul(g_mProjection, float4(0,0,center.z-radius,1)); - vMax.z = min(vMax.z, vPosB.z/vPosB.w); - } -#endif - else - { - vMin = float3(-3,-3,-3); - vMax = float3(-2,-2,-2); - } -#endif - } - - - // we should consider doing a look-up here into a max depth mip chain - // to see if the light is occluded: vMin.z*VIEWPORT_SCALE_Z > MipTexelMaxDepth - //g_vBoundsBuffer[lgtIndex+0] = float3(0.5*vMin.x+0.5, -0.5*vMax.y+0.5, vMin.z*VIEWPORT_SCALE_Z); - //g_vBoundsBuffer[lgtIndex+g_iNrVisibLights] = float3(0.5*vMax.x+0.5, -0.5*vMin.y+0.5, vMax.z*VIEWPORT_SCALE_Z); - - // changed for unity - - // Each light's AABB is represented by two float3s, the min and max of the box. - // And for stereo, we have two sets of lights. Therefore, each eye has a set of mins, followed by - // a set of maxs, and each set is equal to g_iNrVisibLights. - const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(lgtIndex, g_iNrVisibLights, eyeIndex); - - // build a linear (in camera space) min/max Z for the aabb. This is needed for clustered when oblique is active - float linMiZ, linMaZ; -#ifndef USE_OBLIQUE_MODE - float2 vMiZW = mul(g_mInvProjection, float4(vMin,1)).zw; - float2 vMaZW = mul(g_mInvProjection, float4(vMax,1)).zw; - linMiZ = vMiZW.x/vMiZW.y; linMaZ = vMaZW.x/vMaZW.y; -#else - for(int i=0; i<8; i++) // establish 8 aabb points in camera space. - { - float3 vP = float3((i&1)!=0 ? vMax.x : vMin.x, (i&2)!=0 ? vMax.y : vMin.y, (i&4)!=0 ? vMax.z : vMin.z); - - float2 v2Pc = mul(g_mInvProjection, float4(vP,1)).zw; - float linZ = v2Pc.x/v2Pc.y; - - if(i==0) { linMiZ=linZ; linMaZ=linZ; } -#if USE_LEFT_HAND_CAMERA_SPACE - linMiZ = min(linMiZ, linZ); linMaZ = max(linMaZ, linZ); -#else - linMiZ = max(linMiZ, linZ); linMaZ = min(linMaZ, linZ); -#endif - } - - float z0 = center.z-radius, z1 = center.z+radius; -#if USE_LEFT_HAND_CAMERA_SPACE - linMiZ = max(linMiZ, z0); linMaZ = min(linMaZ, z1); -#else - linMiZ = min(linMiZ, z1); linMaZ = max(linMaZ, z0); -#endif - -#endif - - g_vBoundsBuffer[boundsIndices.min] = float4(0.5*vMin.x + 0.5, 0.5*vMin.y + 0.5, vMin.z*VIEWPORT_SCALE_Z, linMiZ); - g_vBoundsBuffer[boundsIndices.max] = float4(0.5*vMax.x + 0.5, 0.5*vMax.y + 0.5, vMax.z*VIEWPORT_SCALE_Z, linMaZ); - } - } -#endif // Z_BINNING -} - -#ifndef Z_BINNING - -float4 GenNewVert(const float4 vVisib, const float4 vInvisib, const int p); - -int ClipAgainstPlane(const int iSrcIndex, const int iNrSrcVerts, const int subLigt, const int p) -{ - int offs_src = iSrcIndex*MAX_PNTS+subLigt*MAX_PNTS*2; - int offs_dst = (1-iSrcIndex)*MAX_PNTS+subLigt*MAX_PNTS*2; - - float4 vPrev = float4(posX[offs_src+(iNrSrcVerts-1)], posY[offs_src+(iNrSrcVerts-1)], posZ[offs_src+(iNrSrcVerts-1)], posW[offs_src+(iNrSrcVerts-1)]); - - int nrVertsDst = 0; - - unsigned int uMask = (1<P.w)?2:0) | ((P.y<-P.w)?4:0) | ((P.y>P.w)?8:0) | ((P.z<0)?16:0) | ((P.z>P.w)?32:0)) & (bIsObliqueClipPlane ? 0x1f : 0x3f); -} - -float4 GenNewVert(const float4 vVisib, const float4 vInvisib, const int p) -{ - const float fS = p==4 ? 0 : ((p&1)==0 ? -1 : 1); - const int index = ((uint) p)/2; - float x1 = index==0 ? vVisib.x : (index==1 ? vVisib.y : vVisib.z); - float x0 = index==0 ? vInvisib.x : (index==1 ? vInvisib.y : vInvisib.z); - - //fS*((vVisib.w-vInvisib.w)*t + vInvisib.w) = (x1-x0)*t + x0; - - const float fT = (fS*vInvisib.w-x0)/((x1-x0) - fS*(vVisib.w-vInvisib.w)); - float4 vNew = vVisib*fT + vInvisib*(1-fT); - - // just to be really anal we make sure the clipped against coordinate is precise - if(index==0) vNew.x = fS*vNew.w; - else if(index==1) vNew.y = fS*vNew.w; - else vNew.z = fS*vNew.w; - - return vNew; -} - - -float4 TransformPlaneToPostSpace(float4x4 InvProjection, float4 plane) -{ - return mul(plane, InvProjection); -} - -float4 EvalPlanePair(out bool validPlanes, float2 posXY_in, float r) -{ - // rotate by 90 degrees to avoid potential division by zero - bool bMustFlip = abs(posXY_in.y)0.0; - - return res; } - -void CalcBound(out bool2 bIsMinValid, out bool2 bIsMaxValid, out float2 vMin, out float2 vMax, float4x4 InvProjection, float3 pos_view_space, float r) -{ - bool validX, validY; - float4 planeX = EvalPlanePair(validX, float2(pos_view_space.x, pos_view_space.z), r); - float4 planeY = EvalPlanePair(validY, float2(pos_view_space.y, pos_view_space.z), r); - - -#if USE_LEFT_HAND_CAMERA_SPACE - planeX = planeX.zwxy; // need to swap left/right and top/bottom planes when using left hand system - planeY = planeY.zwxy; -#endif - - bIsMinValid = bool2(planeX.z<0, planeY.z<0) && bool2(validX,validY); - bIsMaxValid = bool2((-planeX.x)<0, (-planeY.x)<0) && bool2(validX,validY); - - // hopefully the compiler takes zeros into account - // should be the case since the transformation in TransformPlaneToPostSpace() - // is done using multiply-adds and not dot product instructions. - float4 planeX0 = TransformPlaneToPostSpace(InvProjection, float4(planeX.x, 0, planeX.y, 0)); - float4 planeX1 = TransformPlaneToPostSpace(InvProjection, float4(planeX.z, 0, planeX.w, 0)); - float4 planeY0 = TransformPlaneToPostSpace(InvProjection, float4(0, planeY.x, planeY.y, 0)); - float4 planeY1 = TransformPlaneToPostSpace(InvProjection, float4(0, planeY.z, planeY.w, 0)); - - - // convert planes to the forms (1,0,0,D) and (0,1,0,D) - // 2D bound is given by -D components - float2 A = -float2(planeX0.w / planeX0.x, planeY0.w / planeY0.y); - float2 B = -float2(planeX1.w / planeX1.x, planeY1.w / planeY1.y); - - // Bound is complete - vMin = B; - vMax = A; -} - -#endif // !Z_BINNING From f1aeb3182125f1d5d01fd76f36f74537b84a7f9c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 17:25:46 -0700 Subject: [PATCH 016/209] Bounds check --- .../Lighting/LightLoop/LightCullUtils.hlsl | 16 ++++---- .../Lighting/LightLoop/scrbound.compute | 40 +++++++++---------- 2 files changed, 29 insertions(+), 27 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl index ea8d937ca7c..4a2a69df125 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl @@ -3,31 +3,33 @@ // Used to index into our SFiniteLightBound (g_data) and // LightVolumeData (_LightVolumeData) buffers. -int GenerateLightCullDataIndex(int lightIndex, uint numVisibleLights, uint eyeIndex) +uint GenerateLightCullDataIndex(uint lightIndex, uint numVisibleLights, uint eyeIndex) { + lightIndex = min(lightIndex, numVisibleLights - 1); // Stay within bounds + // For monoscopic, there is just one set of light cull data structs. // In stereo, all of the left eye structs are first, followed by the right eye structs. - const int perEyeBaseIndex = (int)eyeIndex * (int)numVisibleLights; + const uint perEyeBaseIndex = eyeIndex * numVisibleLights; return (perEyeBaseIndex + lightIndex); } struct ScreenSpaceBoundsIndices { - int min; - int max; + uint min; + uint max; }; // The returned values are used to index into our AABB screen space bounding box buffer // Usually named g_vBoundsBuffer. The two values represent the min/max indices. -ScreenSpaceBoundsIndices GenerateScreenSpaceBoundsIndices(int lightIndex, uint numVisibleLights, uint eyeIndex) +ScreenSpaceBoundsIndices GenerateScreenSpaceBoundsIndices(uint lightIndex, uint numVisibleLights, uint eyeIndex) { // In the monoscopic mode, there is one set of bounds (min,max -> 2 * g_iNrVisibLights) // In stereo, there are two sets of bounds (leftMin, leftMax, rightMin, rightMax -> 4 * g_iNrVisibLights) - const int eyeRelativeBase = (int)eyeIndex * 2 * (int)numVisibleLights; + const uint eyeRelativeBase = eyeIndex * 2 * numVisibleLights; ScreenSpaceBoundsIndices indices; indices.min = eyeRelativeBase + lightIndex; - indices.max = eyeRelativeBase + lightIndex + (int)numVisibleLights; + indices.max = indices.min + numVisibleLights; return indices; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 86144d43973..c804adad4dc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -13,8 +13,8 @@ /* ------------------------------ Inputs ------------------------------------ */ -uniform int g_isOrthographic; -uniform int g_iNrVisibLights; +uniform uint g_isOrthographic; +uniform uint g_iNrVisibLights; uniform float4x4 g_mInvProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; uniform float4x4 g_mProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; @@ -207,7 +207,7 @@ bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) uint cullMaskOfFace = FACE_MASK; // Initially behind uint vertListOfFace = GetVertexListOfFace(f); - for (int j = 0; j < 4; j++) + for (uint j = 0; j < 4; j++) { uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); // Non-zero if ALL the vertices are behind any of the planes. @@ -310,7 +310,7 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, } } -void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint firstVertexOffset, +void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint baseVertexOffset, out uint srcBegin, out uint srcSize, out float4 vertRingBuffer[MAX_CLIP_VERTS]) { @@ -320,7 +320,7 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint uint clipMaskOfFace = 0; // Initially in front uint vertListOfFace = GetVertexListOfFace(f); - for (int j = 0; j < 4; j++) + for (uint j = 0; j < 4; j++) { uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); // Non-zero if ANY of the vertices are behind any of the planes. @@ -328,10 +328,10 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint // Not all edges may require clipping. However, filtering the vertex list // is somewhat expensive, so we currently don't do it. - vertRingBuffer[j].x = gs_HapVertsX[firstVertexOffset + v]; - vertRingBuffer[j].y = gs_HapVertsY[firstVertexOffset + v]; - vertRingBuffer[j].z = gs_HapVertsZ[firstVertexOffset + v]; - vertRingBuffer[j].w = gs_HapVertsW[firstVertexOffset + v]; + vertRingBuffer[j].x = gs_HapVertsX[baseVertexOffset + v]; + vertRingBuffer[j].y = gs_HapVertsY[baseVertexOffset + v]; + vertRingBuffer[j].z = gs_HapVertsZ[baseVertexOffset + v]; + vertRingBuffer[j].w = gs_HapVertsW[baseVertexOffset + v]; } // Sutherland-Hodgeman polygon clipping algorithm. @@ -418,10 +418,10 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint intraGroupLightIndex = t / THREADS_PER_LIGHT; const uint globalLightIndex = g * LIGHTS_PER_GROUP + intraGroupLightIndex; - const uint firstVertexOffset = intraGroupLightIndex * NUM_VERTS; + const uint baseVertexOffset = intraGroupLightIndex * NUM_VERTS; - const int eyeAdjustedInputOffset = GenerateLightCullDataIndex(globalLightIndex, g_iNrVisibLights, eyeIndex); - const SFiniteLightBound cullData = g_data[eyeAdjustedInputOffset]; + const uint eyeAdjustedInputOffset = GenerateLightCullDataIndex(globalLightIndex, g_iNrVisibLights, eyeIndex); + const SFiniteLightBound cullData = g_data[eyeAdjustedInputOffset]; const float4x4 projMat = g_mProjectionArr[eyeIndex]; const float4x4 invProjMat = g_mInvProjectionArr[eyeIndex]; @@ -521,11 +521,11 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) cullClipFaceMask |= GetFaceMaskOfVertex(v); } - gs_HapVertsX[firstVertexOffset + v] = hapVert.x; - gs_HapVertsY[firstVertexOffset + v] = hapVert.y; - gs_HapVertsZ[firstVertexOffset + v] = hapVert.z; - gs_HapVertsW[firstVertexOffset + v] = hapVert.w; - gs_BehindMasksOfVerts[firstVertexOffset + v] = behindMask; + gs_HapVertsX[baseVertexOffset + v] = hapVert.x; + gs_HapVertsY[baseVertexOffset + v] = hapVert.y; + gs_HapVertsZ[baseVertexOffset + v] = hapVert.z; + gs_HapVertsW[baseVertexOffset + v] = hapVert.w; + gs_BehindMasksOfVerts[baseVertexOffset + v] = behindMask; } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS @@ -613,7 +613,7 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) for (uint i = 0; i < NUM_VERTS; i++) { - behindMasksOfVerts[i] = gs_BehindMasksOfVerts[firstVertexOffset + i]; + behindMasksOfVerts[i] = gs_BehindMasksOfVerts[baseVertexOffset + i]; } // (3) Cull the faces. @@ -669,7 +669,7 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint srcBegin, srcSize; float4 vertRingBuffer[MAX_CLIP_VERTS]; - ClipFaceAgainstViewVolume(f, behindMasksOfVerts, firstVertexOffset, + ClipFaceAgainstViewVolume(f, behindMasksOfVerts, baseVertexOffset, srcBegin, srcSize, vertRingBuffer); UpdateAaBb(srcBegin, srcSize, vertRingBuffer, g_isOrthographic != 0, invProjMat, ndcAaBbMinPt, ndcAaBbMaxPt); @@ -717,7 +717,7 @@ void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupLightIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts + if ((globalLightIndex < g_iNrVisibLights) && (t % THREADS_PER_LIGHT == 0)) // Avoid bank conflicts { // For stereo, we have two sets of lights. Therefore, each eye has a set of mins // followed by a set of maxs, and each set is equal to g_iNrVisibLights. From d2f3fdaf491a91aad220090dfc12a4599bdb9612 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 17:39:14 -0700 Subject: [PATCH 017/209] Add a profiling marker --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 19 +++++++++++-------- .../Lighting/LightLoop/scrbound.compute | 4 ++-- .../Runtime/RenderPipeline/HDProfileId.cs | 1 + 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index c1850bd6602..5ee6f7d067c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3074,18 +3074,21 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame { if (parameters.totalLightCount != 0) { - // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) - cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); - cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs))) + { + // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) + cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); + cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); - ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList); - const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int groupCount = HDUtils.DivRoundUp(parameters.totalLightCount * threadsPerLight, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(parameters.totalLightCount * threadsPerLight, threadsPerGroup); - cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); + cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); + } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index c804adad4dc..233876c830c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -9,7 +9,7 @@ // #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -#pragma kernel GenLightAABB +#pragma kernel main /* ------------------------------ Inputs ------------------------------------ */ @@ -410,7 +410,7 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT // ********************************************************************************************* [numthreads(THREADS_PER_GROUP, 1, 1)] -void GenLightAABB(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { const uint t = threadID; const uint g = groupID.x; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 2a743e973ef..54f95210d35 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -18,6 +18,7 @@ internal enum HDProfileId ScreenSpaceShadows, ScreenSpaceShadowsDebug, BuildLightList, + GenerateLightAABBs, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, From 6aefaf3ad8aa020e7a5b7e43bb3175805f3e9a49 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 17:58:14 -0700 Subject: [PATCH 018/209] Fix lane masks --- .../Lighting/LightLoop/scrbound.compute | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 233876c830c..585441e30c0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -535,7 +535,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB // TODO: Francesco - expose the right intrinsic. - cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, orMask, 0, xorMask); + cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else InterlockedOr(gs_CullClipFaceMasks[intraGroupLightIndex], cullClipFaceMask); @@ -644,7 +644,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB // TODO: Francesco - expose the right intrinsic. - cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, orMask, 0, xorMask); + cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else InterlockedAnd(gs_CullClipFaceMasks[intraGroupLightIndex], cullClipFaceMask); @@ -684,14 +684,14 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB // TODO: Francesco - expose the right intrinsic. - ndcAaBbMinPt.x = min(ndcAaBbMinPt.x, LaneSwizzle(ndcAaBbMinPt.x, orMask, 0, xorMask)); - ndcAaBbMaxPt.x = max(ndcAaBbMaxPt.x, LaneSwizzle(ndcAaBbMaxPt.x, orMask, 0, xorMask)); - ndcAaBbMinPt.y = min(ndcAaBbMinPt.y, LaneSwizzle(ndcAaBbMinPt.y, orMask, 0, xorMask)); - ndcAaBbMaxPt.y = max(ndcAaBbMaxPt.y, LaneSwizzle(ndcAaBbMaxPt.y, orMask, 0, xorMask)); - ndcAaBbMinPt.z = min(ndcAaBbMinPt.z, LaneSwizzle(ndcAaBbMinPt.z, orMask, 0, xorMask)); - ndcAaBbMaxPt.z = max(ndcAaBbMaxPt.z, LaneSwizzle(ndcAaBbMaxPt.z, orMask, 0, xorMask)); - ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, LaneSwizzle(ndcAaBbMinPt.w, orMask, 0, xorMask)); - ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, LaneSwizzle(ndcAaBbMaxPt.w, orMask, 0, xorMask)); + ndcAaBbMinPt.x = min(ndcAaBbMinPt.x, LaneSwizzle(ndcAaBbMinPt.x, andMask, orMask, xorMask)); + ndcAaBbMaxPt.x = max(ndcAaBbMaxPt.x, LaneSwizzle(ndcAaBbMaxPt.x, andMask, orMask, xorMask)); + ndcAaBbMinPt.y = min(ndcAaBbMinPt.y, LaneSwizzle(ndcAaBbMinPt.y, andMask, orMask, xorMask)); + ndcAaBbMaxPt.y = max(ndcAaBbMaxPt.y, LaneSwizzle(ndcAaBbMaxPt.y, andMask, orMask, xorMask)); + ndcAaBbMinPt.z = min(ndcAaBbMinPt.z, LaneSwizzle(ndcAaBbMinPt.z, andMask, orMask, xorMask)); + ndcAaBbMaxPt.z = max(ndcAaBbMaxPt.z, LaneSwizzle(ndcAaBbMaxPt.z, andMask, orMask, xorMask)); + ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, LaneSwizzle(ndcAaBbMinPt.w, andMask, orMask, xorMask)); + ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, LaneSwizzle(ndcAaBbMaxPt.w, andMask, orMask, xorMask)); } #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. From 157cd8eb936e358a53c87feb94667496cf55e827 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 18:44:10 -0700 Subject: [PATCH 019/209] Fix compiler warning --- .../Lighting/LightLoop/scrbound.compute | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 585441e30c0..7cdeab66b02 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -101,7 +101,7 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) /* ------------------------------ Implementation ---------------------------- */ -#define DUMB_COMPILER // Improve the quality of generated code +#define DUMB_COMPILER // Improve the quality of generated code at the expense of readability #define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) #define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks @@ -259,10 +259,10 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, uint modDstIdx = dstBegin % MAX_CLIP_VERTS; #endif - for (uint k = srcBegin; k < (srcBegin + srcSize); k++) + for (uint j = srcBegin; j < (srcBegin + srcSize); j++) { #ifndef DUMB_COMPILER - uint modSrcIdx = k % MAX_CLIP_VERTS; + uint modSrcIdx = j % MAX_CLIP_VERTS; #endif ClipVertex leadVert = CreateClipVertex(p, vertRingBuffer[modSrcIdx]); @@ -457,8 +457,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // any single plane, we can trivially reject (cull) that face. uint cullClipFaceMask = 0; // Initially inside + uint i; // Avoid multiply-declared variable warning + // (1) Compute the vertices of the light volume. - for (uint i = 0; i < VERTS_PER_THREAD; i++) + for (i = 0; i < VERTS_PER_THREAD; i++) { uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; @@ -529,7 +531,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - for (uint i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + for (i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) { uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role @@ -575,7 +577,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) lightSpaceMatrix = mul(mul(perspProjMatrix, invTranslateEye), lightSpaceMatrix); } - for (uint i = 0; i < VERTS_PER_THREAD; i++) + for (i = 0; i < VERTS_PER_THREAD; i++) { uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; @@ -611,7 +613,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint behindMasksOfVerts[NUM_VERTS]; - for (uint i = 0; i < NUM_VERTS; i++) + for (i = 0; i < NUM_VERTS; i++) { behindMasksOfVerts[i] = gs_BehindMasksOfVerts[baseVertexOffset + i]; } @@ -621,7 +623,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint cullFaceMask = cullClipFaceMask; const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] - for (uint i = 0; i < FACES_PER_THREAD; i++) + for (i = 0; i < FACES_PER_THREAD; i++) { uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; @@ -638,7 +640,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - for (uint i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + for (i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) { uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role @@ -659,7 +661,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint clipFaceMask = cullClipFaceMask; const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] - for (uint i = 0; i < FACES_PER_THREAD; i++) + for (i = 0; i < FACES_PER_THREAD; i++) { uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; @@ -678,7 +680,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - for (uint i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + for (i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) { uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role From a2da9243e15442f906a645a21663301d611fcceb Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 11 Aug 2020 18:56:38 -0700 Subject: [PATCH 020/209] Remove GPU Pro reference --- .../Runtime/Lighting/LightLoop/scrbound.compute | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 7cdeab66b02..26783afb163 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -1,16 +1,13 @@ -// The implementation is based on the demo on "fine pruned tiled lighting" published in GPU Pro 7. -// https://github.com/wolfgangfengel/GPU-Pro-7 +// #pragma enable_d3d11_debug_symbols +#pragma only_renderers d3d11 playstation xboxone vulkan metal switch + +#pragma kernel main #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" -// #pragma enable_d3d11_debug_symbols -#pragma only_renderers d3d11 playstation xboxone vulkan metal switch - -#pragma kernel main - /* ------------------------------ Inputs ------------------------------------ */ uniform uint g_isOrthographic; From 70859f772d85c17f665f535b5494e8feebcfdd54 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 16 Sep 2020 19:06:17 -0700 Subject: [PATCH 021/209] Be politically correct --- .../Lighting/LightLoop/scrbound.compute | 30 ++++++++----------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 26783afb163..7bbb2d44b97 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -10,12 +10,6 @@ /* ------------------------------ Inputs ------------------------------------ */ -uniform uint g_isOrthographic; -uniform uint g_iNrVisibLights; - -uniform float4x4 g_mInvProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; -uniform float4x4 g_mProjectionArr[SHADEROPTIONS_XR_MAX_VIEWS]; - StructuredBuffer g_data : register(t0); /* ------------------------------ Outputs ----------------------------------- */ @@ -50,7 +44,7 @@ uint NthBitLow(uint value, uint n) float4x4 Translation4x4(float3 d) { - float4x4 M = k_Identity4x4; + float4x4 M = k_identity4x4; M._14_24_34 = d; // Last column @@ -98,7 +92,7 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) /* ------------------------------ Implementation ---------------------------- */ -#define DUMB_COMPILER // Improve the quality of generated code at the expense of readability +#define OBTUSE_COMPILER // Improve the quality of generated code at the expense of readability #define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) #define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks @@ -251,14 +245,14 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, ClipVertex tailVert = CreateClipVertex(p, vertRingBuffer[(srcBegin + srcSize - 1) % MAX_CLIP_VERTS]); -#ifdef DUMB_COMPILER +#ifdef OBTUSE_COMPILER uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; uint modDstIdx = dstBegin % MAX_CLIP_VERTS; #endif for (uint j = srcBegin; j < (srcBegin + srcSize); j++) { - #ifndef DUMB_COMPILER + #ifndef OBTUSE_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif ClipVertex leadVert = CreateClipVertex(p, vertRingBuffer[modSrcIdx]); @@ -275,11 +269,11 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, { // The line segment is guaranteed to cross the plane. float4 clipVert = IntersectEdgeAgainstPlane(tailVert, leadVert); - #ifndef DUMB_COMPILER + #ifndef OBTUSE_COMPILER uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; #endif vertRingBuffer[modDstIdx] = clipVert; - #ifdef DUMB_COMPILER + #ifdef OBTUSE_COMPILER dstSize++; modDstIdx++; modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; @@ -288,18 +282,18 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, if (leadVert.bc >= 0) { - #ifndef DUMB_COMPILER + #ifndef OBTUSE_COMPILER uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; #endif vertRingBuffer[modDstIdx] = leadVert.pt; - #ifdef DUMB_COMPILER + #ifdef OBTUSE_COMPILER dstSize++; modDstIdx++; modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; #endif } - #ifdef DUMB_COMPILER + #ifdef OBTUSE_COMPILER modSrcIdx++; modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; #endif @@ -351,12 +345,12 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT bool isOrthoProj, float4x4 invProjMat, inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) { -#ifdef DUMB_COMPILER +#ifdef OBTUSE_COMPILER uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; #endif for (uint j = srcBegin; j < (srcBegin + srcSize); j++) { - #ifndef DUMB_COMPILER + #ifndef OBTUSE_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif float4 hapVert = vertRingBuffer[modSrcIdx]; @@ -371,7 +365,7 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVSz)); - #ifdef DUMB_COMPILER + #ifdef OBTUSE_COMPILER modSrcIdx++; modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; #endif From 6e8a605c943a31035d5c19c4c59073837a24e60f Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 26 Aug 2020 12:00:28 -0700 Subject: [PATCH 022/209] No instrinsics on Xbox --- .../Lighting/LightLoop/scrbound.compute | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 7bbb2d44b97..62ed317dad9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -92,7 +92,19 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) /* ------------------------------ Implementation ---------------------------- */ -#define OBTUSE_COMPILER // Improve the quality of generated code at the expense of readability +// Improve the quality of generated code at the expense of readability. +// Remove when the shader compiler is clever enough to perform this optimization for us. +#define OBTUSE_COMPILER + +#ifdef SHADER_API_XBOXONE +// The Xbox shader compiler expects the lane swizzle mask to be a compile-time constant. +// In our case, the mask is a compile-time constant, but it is defined inside a loop +// that is unrolled at the compile time, and the constants are generated during the +// constant propagation pass of the optimizer. This works fine on PlayStation, but does not work +// on Xbox. In order to avoid writing hideous code specifically for Xbox, we disable the support +// of wave intrinsics on Xbox until the Xbox compiler is fixed. +#undef PLATFORM_SUPPORTS_WAVE_INTRINSICS +#endif #define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) #define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks @@ -527,7 +539,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB - // TODO: Francesco - expose the right intrinsic. + cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else @@ -636,7 +648,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB - // TODO: Francesco - expose the right intrinsic. + cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else @@ -676,7 +688,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB - // TODO: Francesco - expose the right intrinsic. + ndcAaBbMinPt.x = min(ndcAaBbMinPt.x, LaneSwizzle(ndcAaBbMinPt.x, andMask, orMask, xorMask)); ndcAaBbMaxPt.x = max(ndcAaBbMaxPt.x, LaneSwizzle(ndcAaBbMaxPt.x, andMask, orMask, xorMask)); ndcAaBbMinPt.y = min(ndcAaBbMinPt.y, LaneSwizzle(ndcAaBbMinPt.y, andMask, orMask, xorMask)); From b50cded94b902167d80c5a6c01eac65c32505251 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 22 Sep 2020 17:38:01 -0700 Subject: [PATCH 023/209] Manually re-apply the changes (except for LightLoop.cs) --- .../Runtime/Common/CoreUnsafeUtils.cs | 15 ++++++++ .../ShaderLibrary/Common.hlsl | 3 +- .../Runtime/Debug/DebugDisplay.cs | 2 +- .../AtmosphericScattering.hlsl | 2 +- .../Lighting/Light/HDAdditionalLightData.cs | 2 +- .../Runtime/Lighting/LightDefinition.cs | 5 ++- .../Lighting/LightLoop/HDShadowLoop.hlsl | 2 +- .../Lighting/LightLoop/LightLoop.cs.hlsl | 2 +- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 8 ++--- .../Lighting/LightLoop/LightLoopDef.hlsl | 8 ++--- .../LightLoop/ShaderVariablesLightLoop.hlsl | 6 ++-- .../Lighting/Shadow/ContactShadows.compute | 8 ++--- .../Shadow/ScreenSpaceShadowManager.cs | 17 ++++++--- ...aceShadowManagerDirectional.RenderGraph.cs | 4 +-- .../ScreenSpaceShadowManagerDirectional.cs | 4 +-- .../Lighting/Shadow/ScreenSpaceShadows.shader | 4 +-- .../VolumetricLighting.compute | 8 ++--- .../VolumetricLighting/VolumetricLighting.cs | 7 ++-- .../Runtime/Material/Decal/DecalSystem.cs | 9 +++-- .../Material/Decal/DecalUtilities.hlsl | 6 ++-- .../Material/Decal/ShaderVariablesDecal.hlsl | 2 +- .../HDRenderPipeline.LightLoop.cs | 26 +++++++------- .../RenderPipeline/HDStringConstants.cs | 17 ++++++--- .../PathTracing/Shaders/PathTracingLight.hlsl | 8 ++--- .../Raytracing/HDRaytracingLightCluster.cs | 35 ++++++++++--------- .../Shaders/RaytracingLightLoop.hlsl | 18 +++++----- .../Shaders/Shadows/RaytracingShadow.compute | 30 ++++++++-------- .../ShaderPass/ShaderPassDecal.hlsl | 4 +-- .../PhysicallyBasedSky.shader | 6 ++-- 29 files changed, 152 insertions(+), 116 deletions(-) diff --git a/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs b/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs index 87ac634598a..8d5b7eda63e 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs @@ -119,6 +119,9 @@ internal struct DefaultKeyGetter : IKeyGetter internal struct UintKeyGetter : IKeyGetter { public uint Get(ref uint v) { return v; } } + // Note: this is a workaround needed to circumvent some AOT issues when building for xbox + internal struct UlongKeyGetter : IKeyGetter + { public ulong Get(ref ulong v) { return v; } } /// /// Extension method to copy elements of a list into a buffer. @@ -162,6 +165,18 @@ public static unsafe void QuickSort(uint[] arr, int left, int right) CoreUnsafeUtils.QuickSort(ptr, left, right); } + /// + /// Quick Sort + /// + /// ulong array. + /// Left boundary. + /// Left boundary. + public static unsafe void QuickSort(ulong[] arr, int left, int right) + { + fixed (ulong* ptr = arr) + CoreUnsafeUtils.QuickSort(ptr, left, right); + } + /// /// Quick sort. /// diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index eefe74e8c1b..6b697a594c3 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -530,6 +530,7 @@ real FastATan(real x) } #if (SHADER_TARGET >= 45) +// If 'x' is not a power-of-2, the result will be truncated (e.g. log2i(3) = 1). uint FastLog2(uint x) { return firstbithigh(x); @@ -558,7 +559,7 @@ TEMPLATE_2_REAL(PositivePow, base, power, return pow(abs(base), power)) // -As a replacement for pow(0,y) where y >= 1, the result of SafePositivePow(x,y) should be close enough to 0. // -For cases where we substitute for pow(0,y) where 0 < y < 1, SafePositivePow(x,y) will quickly reach 1 as y -> 0, while // normally pow(0,y) would give 0 instead of 1 for all 0 < y. -// eg: if we #define FLT_EPS 5.960464478e-8 (for fp32), +// eg: if we #define FLT_EPS 5.960464478e-8 (for fp32), // SafePositivePow(0, 0.1) = 0.1894646 // SafePositivePow(0, 0.01) = 0.8467453 // SafePositivePow(0, 0.001) = 0.9835021 diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index f36906f328b..6d14e383220 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -1312,7 +1312,7 @@ void RegisterLightingDebug() data.fullScreenContactShadowLightIndex = value; }, min = () => -1, // -1 will display all contact shadow - max = () => LightDefinitions.s_LightListMaxPrunedEntries - 1 + max = () => TiledLightingConstants.s_LightListMaxPrunedEntries - 1 }, } }); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/AtmosphericScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/AtmosphericScattering.hlsl index 7b4921dcff6..d605e24bb3e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/AtmosphericScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/AtmosphericScattering.hlsl @@ -123,7 +123,7 @@ void EvaluatePbrAtmosphere(float3 worldSpaceCameraPos, float3 V, float distAlong for (uint i = 0; i < _DirectionalLightCount; i++) { - DirectionalLightData light = _DirectionalLightDatas[i]; + DirectionalLightData light = _DirectionalLightData[i]; // Use scalar or integer cores (more efficient). bool interactsWithSky = asint(light.distanceFromCamera) >= 0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs index 76db7518757..4a192e8a381 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs @@ -1823,7 +1823,7 @@ internal void EvaluateShadowState(HDCamera hdCamera, in ProcessedLightData proce bool validShadow = false; if (processedLight.gpuLightType == GPULightType.Point || processedLight.gpuLightType == GPULightType.Rectangle - || (processedLight.gpuLightType == GPULightType.Spot && processedLight.lightVolumeType == LightVolumeType.Cone)) + || processedLight.gpuLightType == GPULightType.Spot) { validShadow = true; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs index 982e5bb923e..6583f5fad61 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs @@ -6,7 +6,7 @@ namespace UnityEngine.Rendering.HighDefinition // Caution: Order is important and is use for optimization in light loop [GenerateHLSL] - enum GPULightType + enum GPULightType // Rename to "LightType" { Directional, Point, @@ -20,6 +20,9 @@ enum GPULightType // Currently not supported in real time (just use for reference) Disc, // Sphere, + CubemapReflection, + PlanarReflection, + Count }; static class GPULightTypeExtension diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl index 9c3d88694fb..348faac2f18 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl @@ -30,7 +30,7 @@ void ShadowLoopMin(HDShadowContext shadowContext, PositionInputs posInput, float // Evaluate sun shadows. if (_DirectionalShadowIndex >= 0) { - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; // TODO: this will cause us to load from the normal buffer first. Does this cause a performance problem? float3 wi = -light.forward; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index dc8f41cf636..4c4eeacfcfc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -136,7 +136,7 @@ float3 GetCenter(SFiniteLightBound value) { return value.center; } -float2 GetScaleXY(SFiniteLightBound value) +float GetScaleXY(SFiniteLightBound value) { return value.scaleXY; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 38da98e9c1f..3c95fc626b1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -119,7 +119,7 @@ void ApplyDebug(LightLoopContext context, PositionInputs posInput, BSDFData bsdf SHADOW_TYPE shadow = 1.0; if (_DirectionalShadowIndex >= 0) { - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; #if defined(SCREEN_SPACE_SHADOWS_ON) && !defined(_SURFACE_TYPE_TRANSPARENT) if ((light.screenSpaceShadowIndex & SCREEN_SPACE_SHADOW_INDEX_MASK) != INVALID_SCREEN_SPACE_SHADOW) @@ -197,7 +197,7 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS // Evaluate sun shadows. if (_DirectionalShadowIndex >= 0) { - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; #if defined(SCREEN_SPACE_SHADOWS_ON) && !defined(_SURFACE_TYPE_TRANSPARENT) if ((light.screenSpaceShadowIndex & SCREEN_SPACE_SHADOW_INDEX_MASK) != INVALID_SCREEN_SPACE_SHADOW) @@ -425,9 +425,9 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS { for (i = 0; i < _DirectionalLightCount; ++i) { - if (IsMatchingLightLayer(_DirectionalLightDatas[i].lightLayers, builtinData.renderingLayers)) + if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, builtinData.renderingLayers)) { - DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightDatas[i], bsdfData, builtinData); + DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightData[i], bsdfData, builtinData); AccumulateDirectLighting(lighting, aggregateLighting); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 2cb84b578e9..329e2d4d82d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -284,24 +284,24 @@ LightData FetchLight(uint start, uint i) { uint j = FetchIndex(start, i); - return _LightDatas[j]; + return _LightData[j]; } LightData FetchLight(uint index) { - return _LightDatas[index]; + return _LightData[index]; } EnvLightData FetchEnvLight(uint start, uint i) { int j = FetchIndex(start, i); - return _EnvLightDatas[j]; + return _EnvLightData[j]; } EnvLightData FetchEnvLight(uint index) { - return _EnvLightDatas[index]; + return _EnvLightData[index]; } // In the first 8 bits of the target we store the max fade of the contact shadows as a byte diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index d7ed05ef52d..b8b24cad25a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -11,9 +11,9 @@ StructuredBuffer g_logBaseBuffer; StructuredBuffer g_TileFeatureFlags; #endif -StructuredBuffer _DirectionalLightDatas; -StructuredBuffer _LightDatas; -StructuredBuffer _EnvLightDatas; +StructuredBuffer _DirectionalLightData; +StructuredBuffer _LightData; +StructuredBuffer _EnvLightData; // Used by directional and spot lights TEXTURE2D(_CookieAtlas); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute index d50ea799f94..1592fbf0e9d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute @@ -33,7 +33,7 @@ float SampleDepth(float2 UV, bool HalfRes) pixelCoord.x *= 0.5f; pixelCoord.y = pixelCoord.y * 0.5f + _RenderTargetHeight; } - + return LoadCameraDepth(pixelCoord); } @@ -78,7 +78,7 @@ bool ScreenSpaceShadowRayCast(float3 positionWS, float3 rayDirWS, float rayLengt float occluded = 0.0f; - // From this point on, all the marching will be done in UV space + Z + // From this point on, all the marching will be done in UV space + Z float2 startUV = rayStartCS.xy * 0.5f + 0.5f; startUV.y = 1.0f - startUV.y; float3 rayStart = float3(startUV, rayStartCS.z); @@ -146,7 +146,7 @@ bool ComputeContactShadow(PositionInputs posInput, float3 direction, inout float { bool occluded = false; float fade; - + if (_ContactShadowLength > 0.0f) { //Here LightDirection is not the light direction but the light position @@ -202,7 +202,7 @@ void DeferredContactShadow(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId { if (_DirectionalShadowIndex >= 0) { - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; if (light.contactShadowMask != 0 && light.isRayTracedContactShadow == 0.0) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs index 0560a8a7ae3..a82a58ac78a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs @@ -238,7 +238,7 @@ void InitializeScreenSpaceShadows() default: s_ScreenSpaceShadowsMat.EnableKeyword("SHADOW_MEDIUM"); break; - } + } // Allocate the final result texture int numShadowTextures = Math.Max((int)Math.Ceiling(m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots / 4.0f), 1); @@ -286,7 +286,7 @@ void RenderScreenSpaceShadows(HDCamera hdCamera, CommandBuffer cmd) } } - + bool RenderLightScreenSpaceShadows(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingLightShadow))) @@ -299,10 +299,16 @@ bool RenderLightScreenSpaceShadows(HDCamera hdCamera, CommandBuffer cmd) // This matches the directional light if (!m_CurrentScreenSpaceShadowData[lightIdx].valid) continue; - // Fetch the light data and additional light data - LightData currentLight = m_lightList.lights[m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex]; - HDAdditionalLightData currentAdditionalLightData = m_CurrentScreenSpaceShadowData[lightIdx].additionalLightData; + HDAdditionalLightData extraLightData = m_CurrentScreenSpaceShadowData[lightIdx].additionalLightData; + int lightDataIndex = m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex; + + BoundedEntityCategory category = BoundedEntityCategory.Count; + GPULightType lightType = GPULightType.Point; + + EvaluateGPULightType(extraLightData.type, extraLightData.spotLightShape, extraLightData.areaLightShape, + ref category, ref lightType); + /* Broken in XR, fix later // Trigger the right algorithm based on the light type switch (currentLight.lightType) { @@ -318,6 +324,7 @@ bool RenderLightScreenSpaceShadows(HDCamera hdCamera, CommandBuffer cmd) } break; } + */ } } return true; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs index 4bada1fa650..8847078c6e0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs @@ -11,7 +11,7 @@ TextureHandle DenoiseDirectionalScreenSpaceShadow(RenderGraph renderGraph, HDCam TextureHandle noisyBuffer, TextureHandle velocityBuffer, TextureHandle distanceBuffer) { // Is the history still valid? - int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)LightDefinitions.s_ScreenSpaceShadowIndexMask; + int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)TiledLightingConstants.s_ScreenSpaceShadowIndexMask; float historyValidity = EvaluateHistoryValidityDirectionalShadow(hdCamera, dirShadowIndex, m_CurrentSunLightAdditionalLightData); // Grab the history buffers for shadows @@ -111,7 +111,7 @@ void RenderRayTracedDirectionalScreenSpaceShadow(RenderGraph renderGraph, HDCame directionalShadow, velocityBuffer, distanceBuffer); } - int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)LightDefinitions.s_ScreenSpaceShadowIndexMask; + int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)TiledLightingConstants.s_ScreenSpaceShadowIndexMask; ScreenSpaceShadowType shadowType = m_CurrentSunLightAdditionalLightData.colorShadow? ScreenSpaceShadowType.Color: ScreenSpaceShadowType.GrayScale; // Write the result texture to the screen space shadow buffer diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs index 4bf4697e72c..69ecdb6f6f4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs @@ -196,7 +196,7 @@ void DenoiseDirectionalScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera, R RTHandle intermediateBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); RTHandle intermediateDistanceBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.RG0); // Is the history still valid? - int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)LightDefinitions.s_ScreenSpaceShadowIndexMask; + int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)TiledLightingConstants.s_ScreenSpaceShadowIndexMask; float historyValidity = EvaluateHistoryValidityDirectionalShadow(hdCamera, dirShadowIndex, m_CurrentSunLightAdditionalLightData); // Grab the history buffers for shadows @@ -246,7 +246,7 @@ void RenderRayTracedDirectionalScreenSpaceShadow(CommandBuffer cmd, HDCamera hdC } // Write the result texture to the screen space shadow buffer - int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)LightDefinitions.s_ScreenSpaceShadowIndexMask; + int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)TiledLightingConstants.s_ScreenSpaceShadowIndexMask; WriteScreenSpaceShadowParameters wsssParams = PrepareWriteScreenSpaceShadowParameters(hdCamera, dirShadowIndex, m_CurrentSunLightAdditionalLightData.colorShadow ? ScreenSpaceShadowType.Color : ScreenSpaceShadowType.GrayScale); WriteScreenSpaceShadowResources wsssResources = PrepareWriteScreenSpaceShadowResources(outputShadowBuffer); ExecuteWriteScreenSpaceShadow(cmd, wsssParams, wsssResources); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader index 8f9544fa806..8634df027f4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader @@ -53,10 +53,10 @@ Shader "Hidden/HDRP/ScreenSpaceShadows" context.shadowContext = InitShadowContext(); // Get directional light data. By definition we only have one directional light casting shadow - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; float3 L = -light.forward; - // We also need the normal + // We also need the normal NormalData normalData; DecodeFromNormalBuffer(posInput.positionSS.xy, normalData); float3 normalWS = normalData.normalWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute index b9be1a26c11..0e00c04478c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute @@ -146,7 +146,7 @@ VoxelLighting EvaluateVoxelLightingDirectional(LightLoopContext context, uint fe // Evaluate sun shadows. if (_DirectionalShadowIndex >= 0) { - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; // Prep the light so that it works with non-volumetrics-aware code. light.contactShadowMask = 0; @@ -177,7 +177,7 @@ VoxelLighting EvaluateVoxelLightingDirectional(LightLoopContext context, uint fe for (uint i = 0; i < _DirectionalLightCount; ++i) { - DirectionalLightData light = _DirectionalLightDatas[i]; + DirectionalLightData light = _DirectionalLightData[i]; // Prep the light so that it works with non-volumetrics-aware code. light.contactShadowMask = 0; @@ -252,7 +252,7 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF for (; lightOffset < lightCount; lightOffset++) { uint lightIndex = FetchIndex(lightStart, lightOffset); - LightData light = _LightDatas[lightIndex]; + LightData light = _LightData[lightIndex]; if (light.lightType >= GPULIGHTTYPE_PROJECTOR_BOX) { break; } @@ -354,7 +354,7 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF for (; lightOffset < lightCount; lightOffset++) { uint lightIndex = FetchIndex(lightStart, lightOffset); - LightData light = _LightDatas[lightIndex]; + LightData light = _LightData[lightIndex]; if (light.lightType != GPULIGHTTYPE_PROJECTOR_BOX) { break; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index db409abb3da..e91bed9af51 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -47,7 +47,7 @@ unsafe struct ShaderVariablesVolumetric public fixed float _VBufferCoordToViewDirWS[ShaderConfig.k_XRMaxViewsForCBuffer * 16]; public float _VBufferUnitDepthTexelSpacing; - public uint _NumVisibleDensityVolumes; + public uint _DensityVolumeCount; public float _CornetteShanksConstant; public uint _VBufferHistoryIsValid; @@ -676,7 +676,7 @@ unsafe void UpdateShaderVariableslVolumetrics(ref ShaderVariablesVolumetric cb, for (int j = 0; j < 16; ++j) cb._VBufferCoordToViewDirWS[i * 16 + j] = m_PixelCoordToViewDirWS[i][j]; cb._VBufferUnitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, resolution.y); - cb._NumVisibleDensityVolumes = (uint)m_VisibleVolumeBounds.Count; + cb._DensityVolumeCount = (uint)m_VisibleVolumeBounds.Count; cb._CornetteShanksConstant = CornetteShanksPhasePartConstant(fog.anisotropy.value); cb._VBufferHistoryIsValid = hdCamera.volumetricHistoryIsValid ? 1u : 0u; @@ -740,7 +740,8 @@ VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCame var currParams = hdCamera.vBufferParams[currIdx]; parameters.viewCount = hdCamera.viewCount; - parameters.tiledLighting = HasLightToCull() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); + parameters.tiledLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass) && m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume) > 0; + bool optimal = currParams.voxelSize == 8; parameters.voxelizationCS = m_VolumeVoxelizationCS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs index ec262a398f7..b5223501c3d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs @@ -279,7 +279,7 @@ public Camera CurrentCamera // clustered draw data static public DecalData[] m_DecalDatas = new DecalData[kDecalBlockSize]; - static public SFiniteLightBound[] m_Bounds = new SFiniteLightBound[kDecalBlockSize]; + static public FiniteLightBound[] m_Bounds = new FiniteLightBound[kDecalBlockSize]; static public LightVolumeData[] m_LightVolumes = new LightVolumeData[kDecalBlockSize]; static public TextureScaleBias[] m_DiffuseTextureScaleBias = new TextureScaleBias[kDecalBlockSize]; static public TextureScaleBias[] m_NormalTextureScaleBias = new TextureScaleBias[kDecalBlockSize]; @@ -639,9 +639,8 @@ private void GetDecalVolumeDataAndBound(Matrix4x4 decalToWorld, Matrix4x4 worldT // The culling system culls pixels that are further // than a threshold to the box influence extents. // So we use an arbitrary threshold here (k_BoxCullingExtentOffset) - m_LightVolumes[m_DecalDatasCount].lightCategory = (uint)LightCategory.Decal; - m_LightVolumes[m_DecalDatasCount].lightVolume = (uint)LightVolumeType.Box; - m_LightVolumes[m_DecalDatasCount].featureFlags = (uint)LightFeatureFlags.Env; + m_LightVolumes[m_DecalDatasCount].lightCategory = (uint)BoundedEntityCategory.Decal; + m_LightVolumes[m_DecalDatasCount].featureFlags = (uint)LightFeatureFlags.Env; // WTF? m_LightVolumes[m_DecalDatasCount].lightPos = influencePositionVS; m_LightVolumes[m_DecalDatasCount].lightAxisX = influenceRightVS; m_LightVolumes[m_DecalDatasCount].lightAxisY = influenceUpVS; @@ -1160,7 +1159,7 @@ public void CreateDrawData() { int newDecalDatasSize = ((m_DecalsVisibleThisFrame + kDecalBlockSize - 1) / kDecalBlockSize) * kDecalBlockSize; m_DecalDatas = new DecalData[newDecalDatasSize]; - m_Bounds = new SFiniteLightBound[newDecalDatasSize]; + m_Bounds = new FiniteLightBound[newDecalDatasSize]; m_LightVolumes = new LightVolumeData[newDecalDatasSize]; m_DiffuseTextureScaleBias = new TextureScaleBias[newDecalDatasSize]; m_NormalTextureScaleBias = new TextureScaleBias[newDecalDatasSize]; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl index 865def30c91..168792b8c82 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl @@ -49,7 +49,7 @@ void EvalDecalMask( PositionInputs posInput, float3 positionRWSDdx, float3 posit float2 sampleDiffuseDdx = positionDSDdx.xz * decalData.diffuseScaleBias.xy; // factor in the atlas scale float2 sampleDiffuseDdy = positionDSDdy.xz * decalData.diffuseScaleBias.xy; float lodDiffuse = ComputeTextureLOD(sampleDiffuseDdx, sampleDiffuseDdy, _DecalAtlasResolution, 0.5); - + src *= SAMPLE_TEXTURE2D_LOD(_DecalAtlas2D, _trilinear_clamp_sampler_DecalAtlas2D, sampleDiffuse, lodDiffuse); } @@ -163,12 +163,12 @@ DecalData FetchDecal(uint start, uint i) #else int j = start + i; #endif - return _DecalDatas[j]; + return _DecalData[j]; } DecalData FetchDecal(uint index) { - return _DecalDatas[index]; + return _DecalData[index]; } #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl index f2fdfa622e7..ed5a9e6bdbd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderVariablesDecal.hlsl @@ -1,6 +1,6 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.cs.hlsl" -StructuredBuffer _DecalDatas; +StructuredBuffer _DecalData; TEXTURE2D(_DecalAtlas2D); SAMPLER(_trilinear_clamp_sampler_DecalAtlas2D); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 51bc4527a55..d817a086eef 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -143,8 +143,8 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend passData.globalLightListAtomic = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(1, sizeof(uint)) { name = "LightListAtomic"}); passData.AABBBoundsBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * 2 * tileAndClusterData.maxLightCount, 4 * sizeof(float)) { name = "AABBBoundBuffer" }); - var nrTilesX = (m_MaxCameraWidth + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl; - var nrTilesY = (m_MaxCameraHeight + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl; + var nrTilesX = (m_MaxCameraWidth + TiledLightingConstants.s_TileSizeFptl - 1) / TiledLightingConstants.s_TileSizeFptl; + var nrTilesY = (m_MaxCameraHeight + TiledLightingConstants.s_TileSizeFptl - 1) / TiledLightingConstants.s_TileSizeFptl; var nrTiles = nrTilesX * nrTilesY * m_MaxViewCount; const int capacityUShortsPerTile = 32; const int dwordsPerTile = (capacityUShortsPerTile + 1) >> 1; // room for 31 lights and a nrLights value. @@ -156,14 +156,14 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend passData.output.lightList = builder.WriteComputeBuffer( renderGraph.CreateComputeBuffer(new ComputeBufferDesc((int)LightCategory.Count * dwordsPerTile * nrTiles, sizeof(uint)) { name = "LightList" })); passData.output.tileList = builder.WriteComputeBuffer( - renderGraph.CreateComputeBuffer(new ComputeBufferDesc(LightDefinitions.s_NumFeatureVariants * nrTiles, sizeof(uint)) { name = "TileList" })); + renderGraph.CreateComputeBuffer(new ComputeBufferDesc(TiledLightingConstants.s_NumFeatureVariants * nrTiles, sizeof(uint)) { name = "TileList" })); passData.output.tileFeatureFlags = builder.WriteComputeBuffer( renderGraph.CreateComputeBuffer(new ComputeBufferDesc(nrTiles, sizeof(uint)) { name = "TileFeatureFlags" })); // DispatchIndirect: Buffer with arguments has to have three integer numbers at given argsOffset offset: number of work groups in X dimension, number of work groups in Y dimension, number of work groups in Z dimension. // DrawProceduralIndirect: Buffer with arguments has to have four integer numbers at given argsOffset offset: vertex count per instance, instance count, start vertex location, and start instance location // Use use max size of 4 unit for allocation passData.output.dispatchIndirectBuffer = builder.WriteComputeBuffer( - renderGraph.CreateComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * LightDefinitions.s_NumFeatureVariants * 4, sizeof(uint), ComputeBufferType.IndirectArguments) { name = "DispatchIndirectBuffer" })); + renderGraph.CreateComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * TiledLightingConstants.s_NumFeatureVariants * 4, sizeof(uint), ComputeBufferType.IndirectArguments) { name = "DispatchIndirectBuffer" })); } // Big Tile buffer @@ -174,12 +174,12 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend var nrBigTiles = nrBigTilesX * nrBigTilesY * m_MaxViewCount; // TODO: (Nick) In the case of Probe Volumes, this buffer could be trimmed down / tuned more specifically to probe volumes if we added a s_MaxNrBigTileProbeVolumesPlusOne value. passData.output.bigTileLightList = builder.WriteComputeBuffer( - renderGraph.CreateComputeBuffer(new ComputeBufferDesc(LightDefinitions.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint)) { name = "BigTiles" })); + renderGraph.CreateComputeBuffer(new ComputeBufferDesc(TiledLightingConstants.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint)) { name = "BigTiles" })); } // Cluster buffers - var nrClustersX = (m_MaxCameraWidth + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered; - var nrClustersY = (m_MaxCameraHeight + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered; + var nrClustersX = (m_MaxCameraWidth + TiledLightingConstants.s_TileSizeClustered - 1) / TiledLightingConstants.s_TileSizeClustered; + var nrClustersY = (m_MaxCameraHeight + TiledLightingConstants.s_TileSizeClustered - 1) / TiledLightingConstants.s_TileSizeClustered; var nrClusterTiles = nrClustersX * nrClustersY * m_MaxViewCount; passData.output.perVoxelOffset = builder.WriteComputeBuffer( @@ -200,12 +200,12 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend var buildLightListResources = PrepareBuildGPULightListResources(context, data); ClearLightLists(data.buildGPULightListParameters, buildLightListResources, context.cmd); - GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); + // GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd); - BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd); - VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd); + // BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd); + // VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd); - BuildDispatchIndirectArguments(data.buildGPULightListParameters, buildLightListResources, tileFlagsWritten, context.cmd); + // BuildDispatchIndirectArguments(data.buildGPULightListParameters, buildLightListResources, tileFlagsWritten, context.cmd); }); return passData.output; @@ -500,7 +500,6 @@ TextureHandle RenderSSR( RenderGraph renderGraph, class RenderContactShadowPassData { public ContactShadowsParameters parameters; - public LightLoopLightData lightLoopLightData; public TextureHandle depthTexture; public TextureHandle contactShadowsTexture; public ComputeBufferHandle lightList; @@ -520,7 +519,6 @@ TextureHandle RenderContactShadows(RenderGraph renderGraph, HDCamera hdCamera, T bool clearBuffer = m_CurrentDebugDisplaySettings.data.fullScreenDebugMode == FullScreenDebugMode.ContactShadows; passData.parameters = PrepareContactShadowsParameters(hdCamera, firstMipOffsetY); - passData.lightLoopLightData = m_LightLoopLightData; passData.lightList = builder.ReadComputeBuffer(lightLists.lightList); passData.depthTexture = builder.ReadTexture(depthTexture); passData.contactShadowsTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) @@ -531,7 +529,7 @@ TextureHandle RenderContactShadows(RenderGraph renderGraph, HDCamera hdCamera, T builder.SetRenderFunc( (RenderContactShadowPassData data, RenderGraphContext context) => { - RenderContactShadows(data.parameters, data.contactShadowsTexture, data.depthTexture, data.lightLoopLightData, data.lightList, context.cmd); + RenderContactShadows(data.parameters, data.contactShadowsTexture, data.depthTexture, data.lightList, context.cmd); }); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index defb3f22827..fc73761f637 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -113,9 +113,19 @@ static class HDShaderIDs public static readonly int _EnvCubemapTextures = Shader.PropertyToID("_EnvCubemapTextures"); public static readonly int _Env2DTextures = Shader.PropertyToID("_Env2DTextures"); - public static readonly int _DirectionalLightDatas = Shader.PropertyToID("_DirectionalLightDatas"); - public static readonly int _LightDatas = Shader.PropertyToID("_LightDatas"); - public static readonly int _EnvLightDatas = Shader.PropertyToID("_EnvLightDatas"); + + public static readonly int _DirectionalLightData = Shader.PropertyToID(nameof(_DirectionalLightData)); + public static readonly int _DirectionalLightCount = Shader.PropertyToID(nameof(_DirectionalLightCount)); + public static readonly int _PunctualLightData = Shader.PropertyToID(nameof(_PunctualLightData)); + public static readonly int _PunctualLightCount = Shader.PropertyToID(nameof(_PunctualLightCount)); + public static readonly int _AreaLightData = Shader.PropertyToID(nameof(_AreaLightData)); + public static readonly int _AreaLightCount = Shader.PropertyToID(nameof(_AreaLightCount)); + public static readonly int _EnvLightData = Shader.PropertyToID(nameof(_EnvLightData)); + public static readonly int _EnvLightCount = Shader.PropertyToID(nameof(_EnvLightCount)); + public static readonly int _DecalData = Shader.PropertyToID(nameof(_DecalData)); + public static readonly int _DecalCount = Shader.PropertyToID(nameof(_DecalCount)); + public static readonly int _DensityVolumeData = Shader.PropertyToID(nameof(_DensityVolumeData)); + public static readonly int _DensityVolumeCount = Shader.PropertyToID(nameof(_DensityVolumeCount)); public static readonly int _ProbeVolumeBounds = Shader.PropertyToID("_ProbeVolumeBounds"); public static readonly int _ProbeVolumeDatas = Shader.PropertyToID("_ProbeVolumeDatas"); @@ -197,7 +207,6 @@ static class HDShaderIDs public static readonly int _NormalToWorldID = Shader.PropertyToID("_NormalToWorld"); public static readonly int _DecalAtlas2DID = Shader.PropertyToID("_DecalAtlas2D"); public static readonly int _DecalHTileTexture = Shader.PropertyToID("_DecalHTileTexture"); - public static readonly int _DecalDatas = Shader.PropertyToID("_DecalDatas"); public static readonly int _DecalNormalBufferStencilReadMask = Shader.PropertyToID("_DecalNormalBufferStencilReadMask"); public static readonly int _DecalNormalBufferStencilRef = Shader.PropertyToID("_DecalNormalBufferStencilRef"); public static readonly int _DecalPrepassTexture = Shader.PropertyToID("_DecalPrepassTexture"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingLight.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingLight.hlsl index fb03efd30c0..9b0ac114192 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingLight.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingLight.hlsl @@ -140,9 +140,9 @@ LightList CreateLightList(float3 position, float3 normal, uint lightLayers) for (i = 0; i < _DirectionalLightCount && list.distantCount < MAX_DISTANT_LIGHT_COUNT; i++) { - if (IsMatchingLightLayer(_DirectionalLightDatas[i].lightLayers, lightLayers) + if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, lightLayers) #ifndef _SURFACE_TYPE_TRANSPARENT - && IsDistantLightActive(_DirectionalLightDatas[i], normal) + && IsDistantLightActive(_DirectionalLightData[i], normal) #endif ) list.distantIndex[list.distantCount++] = i; @@ -176,7 +176,7 @@ LightData GetLocalLightData(LightList list, float inputSample) DirectionalLightData GetDistantLightData(LightList list, uint i) { - return _DirectionalLightDatas[list.distantIndex[i]]; + return _DirectionalLightData[list.distantIndex[i]]; } DirectionalLightData GetDistantLightData(LightList list, float inputSample) @@ -327,7 +327,7 @@ bool SampleLights(LightList lightList, } else { - // DELTA_PDF represents 1 / area, where the area is infinitesimal + // DELTA_PDF represents 1 / area, where the area is infinitesimal pdf = DELTA_PDF; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs index 38b910ba49d..75c52d156e0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs @@ -300,10 +300,10 @@ void BuildGPULightVolumes(HDRayTracingLights rayTracingLights) // Reserve space in the cookie atlas m_RenderPipeline.ReserveCookieAtlasTexture(currentLight, light, currentLight.type); - + // Grab the light range float lightRange = light.range; - + if (currentLight.type != HDLightType.Area) { m_LightVolumesCPUArray[realIndex].range = new Vector3(lightRange, lightRange, lightRange); @@ -497,12 +497,10 @@ void BuildLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights ray continue; } - // Evaluate all the light type data that we need - LightCategory lightCategory = LightCategory.Count; - GPULightType gpuLightType = GPULightType.Point; - LightVolumeType lightVolumeType = LightVolumeType.Count; - HDLightType lightType = additionalLightData.type; - HDRenderPipeline.EvaluateGPULightType(lightType, additionalLightData.spotLightShape, additionalLightData.areaLightShape, ref lightCategory, ref gpuLightType, ref lightVolumeType); + BoundedEntityCategory lightCategory = BoundedEntityCategory.Count; + GPULightType gpuLightType = GPULightType.Point; + + HDRenderPipeline.EvaluateGPULightType(additionalLightData.type, additionalLightData.spotLightShape, additionalLightData.areaLightShape, ref lightCategory, ref gpuLightType); // Fetch the light component for this light additionalLightData.gameObject.TryGetComponent(out lightComponent); @@ -519,7 +517,7 @@ void BuildLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights ray processedData.lightDistanceFade = HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.fadeDistance); processedData.isBakedShadowMask = HDRenderPipeline.IsBakedShadowMaskLight(lightComponent); - // Build a visible light + // Build a visible light Color finalColor = lightComponent.color.linear * lightComponent.intensity; if (additionalLightData.useColorTemperature) finalColor *= Mathf.CorrelatedColorTemperatureToRGB(lightComponent.colorTemperature); @@ -539,7 +537,7 @@ void BuildLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights ray Vector3 lightDimensions = new Vector3(0.0f, 0.0f, 0.0f); // Use the shared code to build the light data - m_RenderPipeline.GetLightData(cmd, hdCamera, hdShadowSettings, visibleLight, lightComponent, in processedData, + m_RenderPipeline.GetLightData(cmd, hdCamera, hdShadowSettings, visibleLight, lightComponent, in processedData, shadowIndex, contactShadowScalableSetting, isRasterization: false, ref lightDimensions, ref screenSpaceShadowIndex, ref screenSpaceChannelSlot, ref lightData); // We make the light position camera-relative as late as possible in order @@ -587,10 +585,15 @@ void BuildEnvLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights var envLightData = new EnvLightData(); m_RenderPipeline.GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData); - // We make the light position camera-relative as late as possible in order - // to allow the preceding code to work with the absolute world space coordinates. - Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; - HDRenderPipeline.UpdateEnvLighCameraRelativetData(ref envLightData, camPosWS); + if (ShaderConfig.s_CameraRelativeRendering != 0) + { + Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; + + // Caution: 'EnvLightData.positionRWS' is camera-relative after this point. + envLightData.capturePositionRWS -= camPosWS; + envLightData.influencePositionRWS -= camPosWS; + envLightData.proxyPositionRWS -= camPosWS; + } m_EnvLightDataCPUArray.Add(envLightData); } @@ -729,14 +732,14 @@ public void BuildLightClusterBuffer(CommandBuffer cmd, HDCamera hdCamera, HDRayT // If there is no lights to process or no environment not the shader is missing if (totalLightCount == 0 || rayTracingLights.lightCount == 0 || !m_RenderPipeline.GetRayTracingState()) return; - + // Cull the lights within the evaluated cluster range CullLights(cmd); // Build the light Cluster BuildLightCluster(hdCamera, cmd); } - + public void ReserveCookieAtlasSlots( HDRayTracingLights rayTracingLights) { for (int lightIdx = 0; lightIdx < rayTracingLights.hdLightArray.Count; ++lightIdx) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl index 745d5075edc..3c266268de3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl @@ -1,8 +1,8 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingLightCluster.hlsl" -#define USE_LIGHT_CLUSTER +#define USE_LIGHT_CLUSTER -void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, BuiltinData builtinData, +void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, BuiltinData builtinData, float reflectionHierarchyWeight, float refractionHierarchyWeight, float3 reflection, float3 transmission, out LightLoopOutput lightLoopOutput) { @@ -17,11 +17,11 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS // Initialize the contactShadow and contactShadowFade fields InvalidateConctactShadow(posInput, context); - + // Evaluate sun shadows. if (_DirectionalShadowIndex >= 0) { - DirectionalLightData light = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData light = _DirectionalLightData[_DirectionalShadowIndex]; // TODO: this will cause us to load from the normal buffer first. Does this cause a performance problem? float3 L = -light.forward; @@ -43,7 +43,7 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS // Indices of the subranges to process uint lightStart = 0, lightEnd = 0; - // The light cluster is in actual world space coordinates, + // The light cluster is in actual world space coordinates, #ifdef USE_LIGHT_CLUSTER // Get the actual world space position float3 actualWSPos = GetAbsolutePositionWS(posInput.positionWS); @@ -99,7 +99,7 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS // Environment cubemap test lightlayers, sky don't test it #define EVALUATE_BSDF_ENV(envLightData, TYPE, type) if (IsMatchingLightLayer(envLightData.lightLayers, builtinData.renderingLayers)) { EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) } - + #ifdef USE_LIGHT_CLUSTER // Get the punctual light count GetLightCountAndStartCluster(actualWSPos, LIGHTCATEGORY_ENV, lightStart, lightEnd, cellIndex); @@ -157,16 +157,16 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS // We loop over all the directional lights given that there is no culling for them for (i = 0; i < _DirectionalLightCount; ++i) { - if (IsMatchingLightLayer(_DirectionalLightDatas[i].lightLayers, builtinData.renderingLayers)) + if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, builtinData.renderingLayers)) { - DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightDatas[i], bsdfData, builtinData); + DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightData[i], bsdfData, builtinData); AccumulateDirectLighting(lighting, aggregateLighting); } } #ifdef USE_LIGHT_CLUSTER - // Let's loop through all the + // Let's loop through all the GetLightCountAndStartCluster(actualWSPos, LIGHTCATEGORY_AREA, lightStart, lightEnd, cellIndex); #else lightStart = _PunctualLightCountRT; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute index 0754152f29a..1db8a9e4685 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute @@ -96,7 +96,7 @@ void RaytracingAreaShadowPrepass(uint3 dispatchThreadId : SV_DispatchThreadID, u float3 viewWS = normalize(_WorldSpaceCameraPos - positionWS); // Fetch the data of the area light - LightData lightData = _LightDatas[_RaytracingTargetAreaLight]; + LightData lightData = _LightData[_RaytracingTargetAreaLight]; // Compute the current sample index uint globalSampleIndex = _RaytracingFrameIndex * _RaytracingNumSamples; @@ -171,7 +171,7 @@ void RaytracingAreaShadowPrepass(uint3 dispatchThreadId : SV_DispatchThreadID, u // NOTE: Due to a VGPR optimisation in we need to restore the previous value (position, dimmer, and other thing are overriden) - lightData = _LightDatas[_RaytracingTargetAreaLight]; + lightData = _LightData[_RaytracingTargetAreaLight]; // Here we need to evaluate the diffuseProbablity and the unshadowed lighting if (!EvaluateMISProbabilties(lighting, bsdfData.perceptualRoughness, misInput.brdfProb)) @@ -192,7 +192,7 @@ void RaytracingAreaShadowPrepass(uint3 dispatchThreadId : SV_DispatchThreadID, u // Generate the right MIS Sample bool validity = GenerateMISSample(misInput, squad, viewWS, misOutput); outputPosition = misOutput.pos; - + // If we could not sample , or the sample is not in the hemisphere or the sample is on the backface of the light if (!validity || dot(misOutput.dir, bsdfData.normalWS) <= 0.0 || dot(misOutput.dir, lightData.forward) >= 0.0) { @@ -314,7 +314,7 @@ void RaytracingAreaShadowNewSample(uint3 dispatchThreadId : SV_DispatchThreadID, float3 viewWS = normalize(_WorldSpaceCameraPos - positionWS); // Fetch the data of the area light - LightData lightData = _LightDatas[_RaytracingTargetAreaLight]; + LightData lightData = _LightData[_RaytracingTargetAreaLight]; // Compute the current sample index uint globalSampleIndex = _RaytracingFrameIndex * _RaytracingNumSamples + _RaytracingSampleIndex; @@ -497,7 +497,7 @@ void RaytracingDirectionalShadowSample(uint3 dispatchThreadId : SV_DispatchThrea float3 positionWS = GetAbsolutePositionWS(posInput.positionWS); // Fetch the data of the area light - DirectionalLightData lightData = _DirectionalLightDatas[_DirectionalShadowIndex]; + DirectionalLightData lightData = _DirectionalLightData[_DirectionalShadowIndex]; // Compute the current sample index int globalSampleIndex = _RaytracingFrameIndex * _RaytracingNumSamples + _RaytracingSampleIndex; @@ -513,7 +513,7 @@ void RaytracingDirectionalShadowSample(uint3 dispatchThreadId : SV_DispatchThrea // We need to convert the diameter to a radius for our sampling float3 localDir = SampleConeUniform(noiseValue.x, noiseValue.y, cos(lightData.angularDiameter * 0.5)); - float3 wsDir = mul(localDir, localToWorld); + float3 wsDir = mul(localDir, localToWorld); // Output the direction to the target uav _RaytracingDirectionBuffer[COORD_TEXTURE2D_X(currentCoord)] = float4(wsDir, 1.0f); @@ -546,7 +546,7 @@ void RaytracingPointShadowSample(uint3 dispatchThreadId : SV_DispatchThreadID, u float3 positionWS = GetAbsolutePositionWS(posInput.positionWS); // Fetch the data of the area light - LightData lightData = _LightDatas[_RaytracingTargetAreaLight]; + LightData lightData = _LightData[_RaytracingTargetAreaLight]; float3 lightpositionWS = GetAbsolutePositionWS(lightData.positionRWS); // If the point is inside the sphere, it will be visible @@ -587,9 +587,9 @@ void RaytracingPointShadowSample(uint3 dispatchThreadId : SV_DispatchThreadID, u float lightRange2 = lightData.range * lightData.range; if (dot(normalData.normalWS, rayDirection) < 0.0 || dist2 > lightRange2) { - samplePDF = -1.0; + samplePDF = -1.0; } - + // Output the direction to the target uav _RaytracingDirectionBuffer[COORD_TEXTURE2D_X(currentCoord)] = float4(rayDirection, samplePDF); _RayTracingLengthBuffer[COORD_TEXTURE2D_X(currentCoord)] = rayLength; @@ -621,7 +621,7 @@ void RaytracingSpotShadowSample(uint3 dispatchThreadId : SV_DispatchThreadID, ui float3 positionWS = GetAbsolutePositionWS(posInput.positionWS); // Fetch the data of the area light - LightData lightData = _LightDatas[_RaytracingTargetAreaLight]; + LightData lightData = _LightData[_RaytracingTargetAreaLight]; float3 lightpositionWS = GetAbsolutePositionWS(lightData.positionRWS); // If the point is inside the sphere, it will be visible @@ -646,7 +646,7 @@ void RaytracingSpotShadowSample(uint3 dispatchThreadId : SV_DispatchThreadID, ui float samplePDF = 1.0; if (_RaytracingLightRadius > 0.001) { - SampleSphericalCone(lightpositionWS, _RaytracingLightRadius, lightData.forward, + SampleSphericalCone(lightpositionWS, _RaytracingLightRadius, lightData.forward, _RaytracingSpotAngle, noiseValue.x, noiseValue.y, positionWS, normalData.normalWS, lightPosition, samplePDF); @@ -665,12 +665,12 @@ void RaytracingSpotShadowSample(uint3 dispatchThreadId : SV_DispatchThreadID, ui float lightRange2 = lightData.range * lightData.range; if (dot(normalData.normalWS, rayDirection) < 0.0 || dist2 > lightRange2) { - samplePDF = -1.0; + samplePDF = -1.0; } // If the direction is going out of the cone, we invalidate this ray (to avoid casting useless rays) samplePDF = dot(-rayDirection, lightData.forward) > cos(_RaytracingSpotAngle * 0.5f) ? samplePDF : -1.0; - + // Output the direction to the target uav _RaytracingDirectionBuffer[COORD_TEXTURE2D_X(currentCoord)] = float4(rayDirection, samplePDF); _RayTracingLengthBuffer[COORD_TEXTURE2D_X(currentCoord)] = rayLength; @@ -704,7 +704,7 @@ void OUTPUT_SHADOW_TEXTURE(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 g // Offset shadow slot based on XR setup uint shadowSlot = INDEX_TEXTURE2D_ARRAY_X(_RaytracingShadowSlot); - // Fetch the previous stored values + // Fetch the previous stored values float4 previousShadowValues = _ScreenSpaceShadowsTextureRW[uint3(currentCoord, shadowSlot)]; #if defined(COLOR_SHADOW) @@ -713,7 +713,7 @@ void OUTPUT_SHADOW_TEXTURE(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 g _ScreenSpaceShadowsTextureRW[uint3(currentCoord, shadowSlot)] = previousShadowValues; #else // Otherwise we only override the channel we are interested in. We use a max with 0 to avoid using invalid values that may come from rthandle resizing - _ScreenSpaceShadowsTextureRW[uint3(currentCoord, shadowSlot)] = (1.0 - _RaytracingChannelMask) * max(0, previousShadowValues) + _ScreenSpaceShadowsTextureRW[uint3(currentCoord, shadowSlot)] = (1.0 - _RaytracingChannelMask) * max(0, previousShadowValues) + _RaytracingChannelMask * _RaytracedShadowIntegration[COORD_TEXTURE2D_X(currentCoord)].x; #endif } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl index ea039cb977a..2fa5cd5fcdd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl @@ -39,7 +39,7 @@ void Frag( PackedVaryingsToPS packedInput, DecalSurfaceData surfaceData; float clipValue = 1.0; -#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_PROJECTOR) +#if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_PROJECTOR) float depth = LoadCameraDepth(input.positionSS.xy); PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); @@ -114,7 +114,7 @@ void Frag( PackedVaryingsToPS packedInput, uint i; for (i = 0; i < _DirectionalLightCount; ++i) { - DirectionalLightData light = _DirectionalLightDatas[i]; + DirectionalLightData light = _DirectionalLightData[i]; outColor.rgb += surfaceData.baseColor.rgb * light.color * saturate(dot(surfaceData.normalWS.xyz, -light.forward.xyz)); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader index 7d0ccb09962..85aec5dc3e2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader @@ -95,7 +95,7 @@ Shader "Hidden/HDRP/Sky/PbrSky" // Unfortunately, they don't write depth. for (uint i = 0; i < _DirectionalLightCount; i++) { - DirectionalLightData light = _DirectionalLightDatas[i]; + DirectionalLightData light = _DirectionalLightData[i]; // Use scalar or integer cores (more efficient). bool interactsWithSky = asint(light.distanceFromCamera) >= 0; @@ -137,7 +137,7 @@ Shader "Hidden/HDRP/Sky/PbrSky" color *= SampleCookie2D(uv, light.surfaceTextureScaleOffset); // color *= SAMPLE_TEXTURE2D_ARRAY(_CookieTextures, s_linear_clamp_sampler, uv, light.surfaceTextureIndex).rgb; } - + color *= light.surfaceTint; } else // Flare region. @@ -188,7 +188,7 @@ Shader "Hidden/HDRP/Sky/PbrSky" // Shade the ground. for (uint i = 0; i < _DirectionalLightCount; i++) { - DirectionalLightData light = _DirectionalLightDatas[i]; + DirectionalLightData light = _DirectionalLightData[i]; // Use scalar or integer cores (more efficient). bool interactsWithSky = asint(light.distanceFromCamera) >= 0; From 8e912a5e040a43f7f545fa16ea478e1db40598f2 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 25 Sep 2020 18:23:59 -0700 Subject: [PATCH 024/209] Manually re-apply the changes to LightLoop.cs --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 1816 ++++++++++------- 1 file changed, 1133 insertions(+), 683 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 5ee6f7d067c..c92a85ca693 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using UnityEngine.Experimental.Rendering; +using System.Runtime.InteropServices; namespace UnityEngine.Rendering.HighDefinition { @@ -51,24 +52,302 @@ public static VisibleLightAxisAndPosition GetAxisAndPosition(this VisibleLight v //----------------------------------------------------------------------------- [GenerateHLSL] - internal enum LightVolumeType + internal enum BoundedEntityCategory // Defines the sorting order (takes priority over sorting by depth) { - Cone, - Sphere, - Box, - Count + PunctualLight, + AreaLight, + ReflectionProbe, + Decal, + DensityVolume, + ProbeVolume, // TODO + Count, + None = Count // Unbounded } - [GenerateHLSL] - internal enum LightCategory + internal class BoundedEntityCollection // Used for tiled lighting { - Punctual, - Area, - Env, - ProbeVolume, - Decal, - DensityVolume, // WARNING: Currently lightlistbuild.compute assumes density volume is the last element in the LightCategory enum. Do not append new LightCategory types after DensityVolume. TODO: Fix .compute code. - Count + // 'xrViewCount' and 'maxEntityCountPerCategory' control the size of the memory allocation. + public BoundedEntityCollection(int xrViewCount, int[] maxEntityCountPerCategory) + { + Debug.Assert(xrViewCount > 0); + Debug.Assert(maxEntityCountPerCategory.Length == (int)BoundedEntityCategory.Count); + + m_MaxEntityCount = 0; + + for (int i = 0, n = (int)BoundedEntityCategory.Count; i < n; i++) + { + m_EntityCountPerCategory[i] = 0; + + m_MaxEntityCount += maxEntityCountPerCategory[i]; + } + + m_TotalEntityCount = 0; + + m_Views = new ViewDependentData[xrViewCount]; + + for (int i = 0, n = xrViewCount; i < n; i++) + { + m_Views[i] = new ViewDependentData(); + + m_Views[i].punctualLightData = new List(); + m_Views[i].areaLightData = new List(); + m_Views[i].reflectionProbeData = new List(); + m_Views[i].decalData = new List(); + m_Views[i].densityVolumeData = new List(); + m_Views[i].entityBounds = new List(); + m_Views[i].entitySortKeys = new ulong[m_MaxEntityCount]; + } + + for (int i = 0, n = (int)BoundedEntityCategory.Count; i < n; i++) + { + m_EntityDataBufferPerCategory[i] = new ComputeBuffer(maxEntityCountPerCategory[i] * xrViewCount, s_EntityDataSizesPerCategory[i]); + } + + m_EntityBoundsBuffer = new ComputeBuffer(m_MaxEntityCount * xrViewCount, Marshal.SizeOf(typeof(FiniteLightBound))); + } + + // Reset the counters. + public void Reset() + { + for (int i = 0, n = (int)BoundedEntityCategory.Count; i < n; i++) + { + m_EntityCountPerCategory[i] = 0; + } + + m_TotalEntityCount = 0; + + for (int i = 0, n = m_Views.Length; i < n; i++) + { + m_Views[i].punctualLightData.Clear(); + m_Views[i].areaLightData.Clear(); + m_Views[i].reflectionProbeData.Clear(); + m_Views[i].decalData.Clear(); + m_Views[i].densityVolumeData.Clear(); + m_Views[i].entityBounds.Clear(); + + // Since we reset 'm_TotalEntityCount', we can leave 'entitySortKeys' alone. + } + + // No need to clear ComputeBuffers, we will just overwrite the contents. + } + + // Release the resources that are NOT automatically managed by C#. + // TODO: call this somewhere. + public void Release() + { + for (int i = 0, n = (int)BoundedEntityCategory.Count; i < n; i++) + { + CoreUtils.SafeRelease(m_EntityDataBufferPerCategory[i]); + } + + CoreUtils.SafeRelease(m_EntityBoundsBuffer); + } + + public int GetEntityCount(BoundedEntityCategory category) + { + return m_EntityCountPerCategory[(int)category]; + } + + // For all categories combined. + public int GetMaxEntityCount() + { + return m_MaxEntityCount; + } + + public void AddEntitySortKey(int viewIndex, BoundedEntityCategory category, ulong key) + { + Debug.Assert(0 <= viewIndex && viewIndex < m_Views.Length); + + // We could decode the category from the key, but it is probably not worth the effort. + m_Views[viewIndex].entitySortKeys[m_TotalEntityCount] = key; + m_EntityCountPerCategory[(int)category]++; + m_TotalEntityCount++; + } + + // For all categories combined. + public int GetTotalEntityCount() + { + Debug.Assert(GetEntitySortKeyArrayOffset(BoundedEntityCategory.Count) == m_TotalEntityCount); + + return m_TotalEntityCount; + } + + public ulong GetEntitySortKey(int viewIndex, int keyIndex) + { + return m_Views[viewIndex].entitySortKeys[keyIndex]; + } + + // Returns an offset for the 'entitySortKeys' array. + // Assumes the array has been sorted prior to making this call. + public int GetEntitySortKeyArrayOffset(BoundedEntityCategory category) + { + int s = 0; + + for (int i = 0, n = (int)category; i < n; i++) + { + s += m_EntityCountPerCategory[i]; + } + + return s; + } + + public void Sort() + { + Debug.Assert(GetEntitySortKeyArrayOffset(BoundedEntityCategory.Count) == m_TotalEntityCount); + + for (int i = 0, n = m_Views.Length; i < n; i++) + { + // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory. + CoreUnsafeUtils.QuickSort(m_Views[i].entitySortKeys, 0, m_TotalEntityCount - 1); + } + } + + // These must be added in the sorted order! TODO: how to enforce this? + public void AddEntityData(int viewIndex, BoundedEntityCategory category, LightData data) + { + if (category == BoundedEntityCategory.PunctualLight) + { + m_Views[viewIndex].punctualLightData.Add(data); + } + else if (category == BoundedEntityCategory.AreaLight) + { + m_Views[viewIndex].areaLightData.Add(data); + } + else + { + Debug.Assert(false); + } + } + + // These must be added in the sorted order! TODO: how to enforce this? + public void AddEntityData(int viewIndex, BoundedEntityCategory category, EnvLightData data) + { + Debug.Assert(category == BoundedEntityCategory.ReflectionProbe); + m_Views[viewIndex].reflectionProbeData.Add(data); + } + + // These must be added in the sorted order! TODO: how to enforce this? + public void AddEntityData(int viewIndex, BoundedEntityCategory category, DecalData data) + { + Debug.Assert(category == BoundedEntityCategory.Decal); + m_Views[viewIndex].decalData.Add(data); + } + + // These must be added in the sorted order! TODO: how to enforce this? + public void AddEntityData(int viewIndex, BoundedEntityCategory category, DensityVolumeEngineData data) + { + Debug.Assert(category == BoundedEntityCategory.DensityVolume); + m_Views[viewIndex].densityVolumeData.Add(data); + } + + // These must be added in the sorted order! TODO: how to enforce this? + public void AddEntityBounds(int viewIndex, BoundedEntityCategory category, FiniteLightBound bounds) + { + m_Views[viewIndex].entityBounds.Add(bounds); + } + + public ComputeBuffer GetEntityDataBuffer(BoundedEntityCategory category) + { + return m_EntityDataBufferPerCategory[(int)category]; + } + + public ComputeBuffer GetEntityBoundsBuffer() + { + return m_EntityBoundsBuffer; + } + + public void CopyEntityDataToComputeBuffers() + { + int totalCount = 0; + + for (int c = 0; c < (int)BoundedEntityCategory.Count; c++) + { + var category = (BoundedEntityCategory)c; + int count = GetEntityCount(category); + + totalCount += count; + + // For each category, concatenate lists of all views. + for (int i = 0, n = m_Views.Length; i < n; i++) + { + switch (category) + { + case BoundedEntityCategory.PunctualLight: + Debug.Assert(m_Views[i].punctualLightData.Count == count); + m_EntityDataBufferPerCategory[c].SetData(m_Views[i].punctualLightData, 0, i * count, count); + break; + case BoundedEntityCategory.AreaLight: + Debug.Assert(m_Views[i].areaLightData.Count == count); + m_EntityDataBufferPerCategory[c].SetData(m_Views[i].areaLightData, 0, i * count, count); + break; + case BoundedEntityCategory.ReflectionProbe: + Debug.Assert(m_Views[i].reflectionProbeData.Count == count); + m_EntityDataBufferPerCategory[c].SetData(m_Views[i].reflectionProbeData, 0, i * count, count); + break; + case BoundedEntityCategory.Decal: + Debug.Assert(m_Views[i].decalData.Count == count); + m_EntityDataBufferPerCategory[c].SetData(m_Views[i].decalData, 0, i * count, count); + break; + case BoundedEntityCategory.DensityVolume: + Debug.Assert(m_Views[i].densityVolumeData.Count == count); + m_EntityDataBufferPerCategory[c].SetData(m_Views[i].densityVolumeData, 0, i * count, count); + break; + default: + Debug.Assert(false); + break; + } + } + } + + for (int i = 0, n = m_Views.Length; i < n; i++) + { + Debug.Assert(m_Views[i].entityBounds.Count == totalCount); + m_EntityBoundsBuffer.SetData(m_Views[i].entityBounds, 0, i * totalCount, totalCount); + } + } + + /* ------------------------------ Private interface ------------------------------ */ + + static int[] s_EntityDataSizesPerCategory = new int[(int)BoundedEntityCategory.Count] // Can't make it const in C#... + { + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight + Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe + Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal + Marshal.SizeOf(typeof(DensityVolumeEngineData)) // BoundedEntityCategory.DensityVolume + }; + + // The entity count is the same for all views. + int[] m_EntityCountPerCategory = new int[(int)BoundedEntityCategory.Count]; + int m_TotalEntityCount; // Prefix sum of the array above + int m_MaxEntityCount; // For all categories combined + + + // We sort entities by depth, which makes the order of items in these lists view-dependent. + struct ViewDependentData + { + // 1x list per category. + public List punctualLightData; + public List areaLightData; + public List reflectionProbeData; + public List decalData; + public List densityVolumeData; + + // 1x list for all entites (sorted by category). + public List entityBounds; + + // 1x list for entites of all categories. We have to use a raw array for QuickSort. + // See also: BoundedEntitySortingKeyLayout. + public ulong[] entitySortKeys; + } + + ViewDependentData[] m_Views; // 1x view unless it is an XR application + + // 1x list per category (we concatenate lists of all views). + ComputeBuffer[] m_EntityDataBufferPerCategory = new ComputeBuffer[(int)BoundedEntityCategory.Count]; + + // 1x list for all entites (sorted by category, we concatenate lists of all views). + ComputeBuffer m_EntityBoundsBuffer; } [GenerateHLSL] @@ -87,7 +366,7 @@ internal enum LightFeatureFlags } [GenerateHLSL] - class LightDefinitions + class TiledLightingConstants { public static int s_MaxNrBigTileLightsPlusOne = 512; // may be overkill but the footprint is 2 bits per pixel using uint16. public static float s_ViewportScaleZ = 1.0f; @@ -124,37 +403,37 @@ class LightDefinitions } [GenerateHLSL] - struct SFiniteLightBound + struct FiniteLightBound { public Vector3 boxAxisX; // Scaled by the extents (half-size) public Vector3 boxAxisY; // Scaled by the extents (half-size) public Vector3 boxAxisZ; // Scaled by the extents (half-size) - public Vector3 center; // Center of the bounds (box) in camera space + public Vector3 center; // Center of the bounding box in the view space public float scaleXY; // Scale applied to the top of the box to turn it into a truncated pyramid (X = Y) - public float radius; // Circumscribed sphere for the bounds (box) - }; + public float radius; // Bounding sphere (may or may not be tighter than the bounding box) + } - [GenerateHLSL] - struct LightVolumeData - { - public Vector3 lightPos; // Of light's "origin" - public uint lightVolume; // Type index + // [GenerateHLSL] + // struct LightVolumeData + // { + // public Vector3 lightPos; // Of light's "origin" + // public uint lightVolume; // Type index - public Vector3 lightAxisX; // Normalized - public uint lightCategory; // Category index + // public Vector3 lightAxisX; // Normalized + // public uint lightCategory; // Category index - public Vector3 lightAxisY; // Normalized - public float radiusSq; // Cone and sphere: light range squared + // public Vector3 lightAxisY; // Normalized + // public float radiusSq; // Cone and sphere: light range squared - public Vector3 lightAxisZ; // Normalized - public float cotan; // Cone: cotan of the aperture (half-angle) + // public Vector3 lightAxisZ; // Normalized + // public float cotan; // Cone: cotan of the aperture (half-angle) - public Vector3 boxInnerDist; // Box: extents (half-size) of the inner box - public uint featureFlags; + // public Vector3 boxInnerDist; // Box: extents (half-size) of the inner box + // public uint featureFlags; - public Vector3 boxInvRange; // Box: 1 / (OuterBoxExtents - InnerBoxExtents) - public float unused2; - }; + // public Vector3 boxInvRange; // Box: 1 / (OuterBoxExtents - InnerBoxExtents) + // public float unused2; + // }; /// /// Tile and Cluster Debug Mode. @@ -254,7 +533,7 @@ internal struct ProcessedLightData { public HDAdditionalLightData additionalLightData; public HDLightType lightType; - public LightCategory lightCategory; + public BoundedEntityCategory lightCategory; public GPULightType gpuLightType; public LightVolumeType lightVolumeType; public float distanceToCamera; @@ -301,6 +580,8 @@ public partial class HDRenderPipeline int m_MaxPunctualLightsOnScreen; int m_MaxAreaLightsOnScreen; int m_MaxDecalsOnScreen; + int m_MaxDensityVolumesOnScreen = 1024; // TODO + int m_MaxProbeVolumesOnScreen = 1024; // TODO int m_MaxLightsOnScreen; int m_MaxEnvLightsOnScreen; int m_MaxPlanarReflectionOnScreen; @@ -376,36 +657,36 @@ public void NewFrame() } } - internal class LightLoopLightData - { - public ComputeBuffer directionalLightData { get; private set; } - public ComputeBuffer lightData { get; private set; } - public ComputeBuffer envLightData { get; private set; } - public ComputeBuffer decalData { get; private set; } - - public void Initialize(int directionalCount, int punctualCount, int areaLightCount, int envLightCount, int decalCount) - { - directionalLightData = new ComputeBuffer(directionalCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLightData))); - lightData = new ComputeBuffer(punctualCount + areaLightCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightData))); - envLightData = new ComputeBuffer(envLightCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(EnvLightData))); - decalData = new ComputeBuffer(decalCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DecalData))); - } - - public void Cleanup() - { - CoreUtils.SafeRelease(directionalLightData); - CoreUtils.SafeRelease(lightData); - CoreUtils.SafeRelease(envLightData); - CoreUtils.SafeRelease(decalData); - } - } + // internal class LightLoopLightData + // { + // public ComputeBuffer directionalLightData { get; private set; } + // public ComputeBuffer lightData { get; private set; } + // public ComputeBuffer envLightData { get; private set; } + // public ComputeBuffer decalData { get; private set; } + + // public void Initialize(int directionalCount, int punctualCount, int areaLightCount, int envLightCount, int decalCount) + // { + // directionalLightData = new ComputeBuffer(directionalCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLightData))); + // lightData = new ComputeBuffer(punctualCount + areaLightCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightData))); + // envLightData = new ComputeBuffer(envLightCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(EnvLightData))); + // decalData = new ComputeBuffer(decalCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DecalData))); + // } + + // public void Cleanup() + // { + // CoreUtils.SafeRelease(directionalLightData); + // CoreUtils.SafeRelease(lightData); + // CoreUtils.SafeRelease(envLightData); + // CoreUtils.SafeRelease(decalData); + // } + // } // TODO RENDERGRAPH: When we remove the old pass, we need to remove/refactor this class // With render graph it's only useful for 2 buffers and a boolean value. class TileAndClusterData { // Internal to light list building - public ComputeBuffer lightVolumeDataBuffer { get; private set; } + // public ComputeBuffer lightVolumeDataBuffer { get; private set; } public ComputeBuffer convexBoundsBuffer { get; private set; } public ComputeBuffer AABBBoundsBuffer { get; private set; } public ComputeBuffer globalLightListAtomic { get; private set; } @@ -437,34 +718,34 @@ public void Initialize(bool allocateTileBuffers, bool clusterNeedsDepth, int max globalLightListAtomic = new ComputeBuffer(1, sizeof(uint)); } - public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, int width, int height, int viewCount, int maxLightOnScreen) + public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, int width, int height, int viewCount, int maxBoundedEntityCount) { if (hasTileBuffers) { - var nrTilesX = (width + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl; - var nrTilesY = (height + LightDefinitions.s_TileSizeFptl - 1) / LightDefinitions.s_TileSizeFptl; + var nrTilesX = (width + TiledLightingConstants.s_TileSizeFptl - 1) / TiledLightingConstants.s_TileSizeFptl; + var nrTilesY = (height + TiledLightingConstants.s_TileSizeFptl - 1) / TiledLightingConstants.s_TileSizeFptl; var nrTiles = nrTilesX * nrTilesY * viewCount; const int capacityUShortsPerTile = 32; const int dwordsPerTile = (capacityUShortsPerTile + 1) >> 1; // room for 31 lights and a nrLights value. // note that nrTiles include the viewCount in allocation below - lightList = new ComputeBuffer((int)LightCategory.Count * dwordsPerTile * nrTiles, sizeof(uint)); // enough list memory for a 4k x 4k display - tileList = new ComputeBuffer((int)LightDefinitions.s_NumFeatureVariants * nrTiles, sizeof(uint)); + lightList = new ComputeBuffer((int)BoundedEntityCategory.Count * dwordsPerTile * nrTiles, sizeof(uint)); // enough list memory for a 4k x 4k display // WTF ??? + tileList = new ComputeBuffer((int)TiledLightingConstants.s_NumFeatureVariants * nrTiles, sizeof(uint)); tileFeatureFlags = new ComputeBuffer(nrTiles, sizeof(uint)); // DispatchIndirect: Buffer with arguments has to have three integer numbers at given argsOffset offset: number of work groups in X dimension, number of work groups in Y dimension, number of work groups in Z dimension. // DrawProceduralIndirect: Buffer with arguments has to have four integer numbers at given argsOffset offset: vertex count per instance, instance count, start vertex location, and start instance location // Use use max size of 4 unit for allocation - dispatchIndirectBuffer = new ComputeBuffer(viewCount * LightDefinitions.s_NumFeatureVariants * 4, sizeof(uint), ComputeBufferType.IndirectArguments); + dispatchIndirectBuffer = new ComputeBuffer(viewCount * TiledLightingConstants.s_NumFeatureVariants * 4, sizeof(uint), ComputeBufferType.IndirectArguments); } // Cluster { - var nrClustersX = (width + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered; - var nrClustersY = (height + LightDefinitions.s_TileSizeClustered - 1) / LightDefinitions.s_TileSizeClustered; + var nrClustersX = (width + TiledLightingConstants.s_TileSizeClustered - 1) / TiledLightingConstants.s_TileSizeClustered; + var nrClustersY = (height + TiledLightingConstants.s_TileSizeClustered - 1) / TiledLightingConstants.s_TileSizeClustered; var nrClusterTiles = nrClustersX * nrClustersY * viewCount; - perVoxelOffset = new ComputeBuffer((int)LightCategory.Count * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint)); + perVoxelOffset = new ComputeBuffer((int)BoundedEntityCategory.Count * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint)); perVoxelLightLists = new ComputeBuffer(NumLightIndicesPerClusteredTile() * nrClusterTiles, sizeof(uint)); if (clusterNeedsDepth) @@ -479,24 +760,24 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, var nrBigTilesY = (height + 63) / 64; var nrBigTiles = nrBigTilesX * nrBigTilesY * viewCount; // TODO: (Nick) In the case of Probe Volumes, this buffer could be trimmed down / tuned more specifically to probe volumes if we added a s_MaxNrBigTileProbeVolumesPlusOne value. - bigTileLightList = new ComputeBuffer(LightDefinitions.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint)); + bigTileLightList = new ComputeBuffer(TiledLightingConstants.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint)); } // The bounds and light volumes are view-dependent, and AABB is additionally projection dependent. - AABBBoundsBuffer = new ComputeBuffer(viewCount * 2 * maxLightOnScreen, 4 * sizeof(float)); + AABBBoundsBuffer = new ComputeBuffer((viewCount * maxBoundedEntityCount) * 2, 4 * sizeof(float)); // 2x float4 per AABB // Make sure to invalidate the content of the buffers listsAreClear = false; } - public void AllocateResolutionDependentBuffers(HDCamera hdCamera, int width, int height, int viewCount, int maxLightOnScreen, bool renderGraphEnabled) + public void AllocateResolutionDependentBuffers(HDCamera hdCamera, int width, int height, int viewCount, int maxBoundedEntityCount, bool renderGraphEnabled) { - convexBoundsBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound))); - lightVolumeDataBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightVolumeData))); + // convexBoundsBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(FiniteLightBound))); + // lightVolumeDataBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightVolumeData))); if (!renderGraphEnabled) - AllocateNonRenderGraphResolutionDependentBuffers(hdCamera, width, height, viewCount, maxLightOnScreen); + AllocateNonRenderGraphResolutionDependentBuffers(hdCamera, width, height, viewCount, maxBoundedEntityCount); // Make sure to invalidate the content of the buffers listsAreClear = false; @@ -532,10 +813,10 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() public void ReleaseResolutionDependentBuffers() { - CoreUtils.SafeRelease(convexBoundsBuffer); - CoreUtils.SafeRelease(lightVolumeDataBuffer); - convexBoundsBuffer = null; - lightVolumeDataBuffer = null; + // CoreUtils.SafeRelease(convexBoundsBuffer); + // CoreUtils.SafeRelease(lightVolumeDataBuffer); + // convexBoundsBuffer = null; + // lightVolumeDataBuffer = null; ReleaseNonRenderGraphResolutionDependentBuffers(); } @@ -551,7 +832,7 @@ public void Cleanup() // TODO: Remove the internal internal LightLoopTextureCaches m_TextureCaches = new LightLoopTextureCaches(); // TODO: Remove the internal - internal LightLoopLightData m_LightLoopLightData = new LightLoopLightData(); + // internal LightLoopLightData m_LightLoopLightData = new LightLoopLightData(); TileAndClusterData m_TileAndClusterData = new TileAndClusterData(); TileAndClusterData m_ProbeVolumeClusterData; @@ -564,22 +845,13 @@ public void Cleanup() static internal readonly bool s_UseCascadeBorders = true; // Keep sorting array around to avoid garbage - uint[] m_SortKeys = null; DynamicArray m_ProcessedLightData = new DynamicArray(); DynamicArray m_ProcessedReflectionProbeData = new DynamicArray(); DynamicArray m_ProcessedPlanarProbeData = new DynamicArray(); - void UpdateSortKeysArray(int count) - { - if (m_SortKeys == null ||count > m_SortKeys.Length) - { - m_SortKeys = new uint[count]; - } - } - static readonly Matrix4x4 s_FlipMatrixLHSRHS = Matrix4x4.Scale(new Vector3(1, 1, -1)); - Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) + static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) { var viewMatrix = (hdCamera.xr.enabled ? hdCamera.xr.GetViewMatrix(viewIndex) : hdCamera.camera.worldToCameraMatrix); @@ -597,59 +869,12 @@ Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) // Matrix used for LightList building, keep them around to avoid GC Matrix4x4[] m_LightListProjMatrices = new Matrix4x4[ShaderConfig.s_XrMaxViews]; - internal class LightList - { - public List directionalLights; - public List lights; - public List envLights; - public int punctualLightCount; - public int areaLightCount; - - public struct LightsPerView - { - public List bounds; - public List lightVolumes; - public List probeVolumesBounds; - public List probeVolumesLightVolumes; - } + internal List m_DirectionalLightData; // Global list + internal List m_DirectionalLightIndices; + internal ComputeBuffer m_DirectionalLightDataBuffer; - public List lightsPerView; + internal BoundedEntityCollection m_BoundedEntityCollection; // Per-tile (and per-view) lists - public void Clear() - { - directionalLights.Clear(); - lights.Clear(); - envLights.Clear(); - punctualLightCount = 0; - areaLightCount = 0; - - for (int i = 0; i < lightsPerView.Count; ++i) - { - lightsPerView[i].bounds.Clear(); - lightsPerView[i].lightVolumes.Clear(); - lightsPerView[i].probeVolumesBounds.Clear(); - lightsPerView[i].probeVolumesLightVolumes.Clear(); - } - } - - public void Allocate() - { - directionalLights = new List(); - lights = new List(); - envLights = new List(); - - lightsPerView = new List(); - for (int i = 0; i < TextureXR.slices; ++i) - { - lightsPerView.Add(new LightsPerView { bounds = new List(), lightVolumes = new List(), probeVolumesBounds = new List(), probeVolumesLightVolumes = new List() }); - } - } - } - - internal LightList m_lightList; - int m_TotalLightCount = 0; - int m_DensityVolumeCount = 0; - int m_ProbeVolumeCount = 0; bool m_EnableBakeShadowMask = false; // Track if any light require shadow mask. In this case we will need to enable the keyword shadow mask ComputeShader buildScreenAABBShader { get { return defaultResources.shaders.buildScreenAABBCS; } } @@ -711,7 +936,7 @@ enum ClusterDepthSource : int static int s_shadeOpaqueDirectShadowMaskFptlKernel; static int s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel; - static int[] s_shadeOpaqueIndirectFptlKernels = new int[LightDefinitions.s_NumFeatureVariants]; + static int[] s_shadeOpaqueIndirectFptlKernels = new int[TiledLightingConstants.s_NumFeatureVariants]; static int s_deferredContactShadowKernel; @@ -733,7 +958,7 @@ enum ClusterDepthSource : int static Material s_DeferredTileRegularLightingMat; // stencil-test set to touch regular pixels only static Material s_DeferredTileSplitLightingMat; // stencil-test set to touch split-lighting pixels only static Material s_DeferredTileMat; // fallback when regular and split-lighting pixels must be touch - static String[] s_variantNames = new String[LightDefinitions.s_NumFeatureVariants]; + static String[] s_variantNames = new String[TiledLightingConstants.s_NumFeatureVariants]; ContactShadows m_ContactShadows = null; bool m_EnableContactShadow = false; @@ -784,39 +1009,34 @@ struct ScreenSpaceShadowData static MaterialPropertyBlock m_LightLoopDebugMaterialProperties = new MaterialPropertyBlock(); - bool HasLightToCull() - { - return m_TotalLightCount > 0; - } - static int GetNumTileBigTileX(HDCamera hdCamera) { - return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, LightDefinitions.s_TileSizeBigTile); + return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_TileSizeBigTile); } static int GetNumTileBigTileY(HDCamera hdCamera) { - return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, LightDefinitions.s_TileSizeBigTile); + return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_TileSizeBigTile); } static int GetNumTileFtplX(HDCamera hdCamera) { - return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, LightDefinitions.s_TileSizeFptl); + return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_TileSizeFptl); } static int GetNumTileFtplY(HDCamera hdCamera) { - return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, LightDefinitions.s_TileSizeFptl); + return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_TileSizeFptl); } static int GetNumTileClusteredX(HDCamera hdCamera) { - return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, LightDefinitions.s_TileSizeClustered); + return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_TileSizeClustered); } static int GetNumTileClusteredY(HDCamera hdCamera) { - return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, LightDefinitions.s_TileSizeClustered); + return HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_TileSizeClustered); } void InitShadowSystem(HDRenderPipelineAsset hdAsset, RenderPipelineResources defaultResources) @@ -862,9 +1082,6 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) { var lightLoopSettings = asset.currentPlatformRenderPipelineSettings.lightLoopSettings; - m_lightList = new LightList(); - m_lightList.Allocate(); - m_DebugViewTilesMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugViewTilesPS); m_DebugHDShadowMapMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugHDShadowMapPS); m_DebugBlitMaterial = CoreUtils.CreateEngineMaterial(defaultResources.shaders.debugBlitQuad); @@ -908,16 +1125,30 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) s_deferredContactShadowKernel = contactShadowComputeShader.FindKernel("DeferredContactShadow"); - for (int variant = 0; variant < LightDefinitions.s_NumFeatureVariants; variant++) + for (int variant = 0; variant < TiledLightingConstants.s_NumFeatureVariants; variant++) { s_shadeOpaqueIndirectFptlKernels[variant] = deferredComputeShader.FindKernel("Deferred_Indirect_Fptl_Variant" + variant); } m_TextureCaches.Initialize(asset, defaultResources, iBLFilterBSDFArray); // All the allocation of the compute buffers need to happened after the kernel finding in order to avoid the leak loop when a shader does not compile or is not available - m_LightLoopLightData.Initialize(m_MaxDirectionalLightsOnScreen, m_MaxPunctualLightsOnScreen, m_MaxAreaLightsOnScreen, m_MaxEnvLightsOnScreen, m_MaxDecalsOnScreen); m_TileAndClusterData.Initialize(allocateTileBuffers: true, clusterNeedsDepth: k_UseDepthBuffer, maxLightCount: m_MaxLightsOnScreen); + + int xrViewCount = TextureXR.slices; + + int[] maxBoundedEntityCounts = new int[(int)BoundedEntityCategory.Count]; + maxBoundedEntityCounts[(int)BoundedEntityCategory.PunctualLight] = m_MaxPunctualLightsOnScreen; + maxBoundedEntityCounts[(int)BoundedEntityCategory.AreaLight] = m_MaxAreaLightsOnScreen; + maxBoundedEntityCounts[(int)BoundedEntityCategory.ReflectionProbe] = m_MaxEnvLightsOnScreen; + maxBoundedEntityCounts[(int)BoundedEntityCategory.Decal] = m_MaxDecalsOnScreen; + maxBoundedEntityCounts[(int)BoundedEntityCategory.DensityVolume] = m_MaxDensityVolumesOnScreen; + + m_DirectionalLightData = new List(); + m_DirectionalLightIndices = new List(); + m_DirectionalLightDataBuffer = new ComputeBuffer(m_MaxDirectionalLightsOnScreen, Marshal.SizeOf(typeof(DirectionalLightData))); + m_BoundedEntityCollection = new BoundedEntityCollection(xrViewCount, maxBoundedEntityCounts); + if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) { m_ProbeVolumeClusterData = new TileAndClusterData(); @@ -974,7 +1205,7 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) s_DeferredTileMat.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.Clear); s_DeferredTileMat.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.NotEqual); - for (int i = 0; i < LightDefinitions.s_NumFeatureVariants; ++i) + for (int i = 0; i < TiledLightingConstants.s_NumFeatureVariants; ++i) s_variantNames[i] = "VARIANT" + i; m_DefaultTexture2DArray = new Texture2DArray(1, 1, 1, TextureFormat.ARGB32, false); @@ -1030,8 +1261,11 @@ void CleanupLightLoop() CoreUtils.Destroy(m_DefaultTextureCube); m_TextureCaches.Cleanup(); - m_LightLoopLightData.Cleanup(); m_TileAndClusterData.Cleanup(); + + CoreUtils.SafeRelease(m_DirectionalLightDataBuffer); + m_BoundedEntityCollection.Release(); + if (m_ProbeVolumeClusterData != null) m_ProbeVolumeClusterData.Cleanup(); @@ -1098,7 +1332,7 @@ static int NumLightIndicesPerClusteredTile() void LightLoopAllocResolutionDependentBuffers(HDCamera hdCamera, int width, int height) { - m_TileAndClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, m_MaxLightsOnScreen, m_EnableRenderGraph); + m_TileAndClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, m_BoundedEntityCollection.GetMaxEntityCount(), m_EnableRenderGraph); if (m_ProbeVolumeClusterData != null) m_ProbeVolumeClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, k_MaxVisibleProbeVolumeCount, m_EnableRenderGraph); } @@ -1254,7 +1488,7 @@ static Vector3 EvaluateAtmosphericAttenuation(PhysicallyBasedSky skySettings, Ve } } - internal void GetDirectionalLightData(CommandBuffer cmd, HDCamera hdCamera, VisibleLight light, Light lightComponent, int lightIndex, int shadowIndex, + internal DirectionalLightData GetDirectionalLightData(CommandBuffer cmd, HDCamera hdCamera, VisibleLight light, Light lightComponent, int lightIndex, int shadowIndex, int sortedIndex, bool isPhysicallyBasedSkyActive, ref int screenSpaceShadowIndex, ref int screenSpaceShadowslot) { var processedData = m_ProcessedLightData[lightIndex]; @@ -1283,7 +1517,7 @@ internal void GetDirectionalLightData(CommandBuffer cmd, HDCamera hdCamera, Visi lightData.volumetricLightDimmer = additionalLightData.volumetricDimmer; lightData.shadowIndex = -1; - lightData.screenSpaceShadowIndex = (int)LightDefinitions.s_InvalidScreenSpaceShadow; + lightData.screenSpaceShadowIndex = (int)TiledLightingConstants.s_InvalidScreenSpaceShadow; lightData.isRayTracedContactShadow = 0.0f; if (lightComponent != null && lightComponent.cookie != null) @@ -1327,7 +1561,7 @@ internal void GetDirectionalLightData(CommandBuffer cmd, HDCamera hdCamera, Visi if (additionalLightData.colorShadow && additionalLightData.WillRenderRayTracedShadow()) { screenSpaceShadowslot += 3; - lightData.screenSpaceShadowIndex |= (int)LightDefinitions.s_ScreenSpaceColorShadowFlag; + lightData.screenSpaceShadowIndex |= (int)TiledLightingConstants.s_ScreenSpaceColorShadowFlag; } else { @@ -1389,7 +1623,7 @@ internal void GetDirectionalLightData(CommandBuffer cmd, HDCamera hdCamera, Visi // Fallback to the first non shadow casting directional light. m_CurrentSunLight = m_CurrentSunLight == null ? lightComponent : m_CurrentSunLight; - m_lightList.directionalLights.Add(lightData); + return lightData; } // This function evaluates if there is currently enough screen space sahdow slots of a given light based on its light type @@ -1406,13 +1640,15 @@ bool EnoughScreenSpaceShadowSlots(GPULightType gpuLightType, int screenSpaceChan } } - internal void GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSettings shadowSettings, VisibleLight light, Light lightComponent, - in ProcessedLightData processedData, int shadowIndex, BoolScalableSetting contactShadowsScalableSetting, bool isRasterization, ref Vector3 lightDimensions, ref int screenSpaceShadowIndex, ref int screenSpaceChannelSlot, ref LightData lightData) + internal LightData GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSettings shadowSettings, VisibleLight light, Light lightComponent, + in ProcessedLightData processedData, int shadowIndex, BoolScalableSetting contactShadowsScalableSetting, bool isRasterization, ref Vector3 lightDimensions, ref int screenSpaceShadowIndex, ref int screenSpaceChannelSlot) { var additionalLightData = processedData.additionalLightData; var gpuLightType = processedData.gpuLightType; var lightType = processedData.lightType; + var lightData = new LightData(); + var visibleLightAxisAndPosition = light.GetAxisAndPosition(); lightData.lightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? additionalLightData.GetLightLayers() : uint.MaxValue; @@ -1552,7 +1788,7 @@ internal void GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSetting lightData.cookieMode = CookieMode.None; lightData.shadowIndex = -1; - lightData.screenSpaceShadowIndex = (int)LightDefinitions.s_InvalidScreenSpaceShadow; + lightData.screenSpaceShadowIndex = (int)TiledLightingConstants.s_InvalidScreenSpaceShadow; lightData.isRayTracedContactShadow = 0.0f; if (lightComponent != null && additionalLightData != null && @@ -1651,7 +1887,7 @@ internal void GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSetting // Keep track of the screen space shadow data m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].additionalLightData = additionalLightData; - m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].lightDataIndex = m_lightList.lights.Count; + m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].lightDataIndex = -1; /* WILL NOT WORK IN XR */ m_CurrentScreenSpaceShadowData[screenSpaceShadowIndex].valid = true; m_ScreenSpaceShadowsUnion.Add(additionalLightData); @@ -1692,10 +1928,12 @@ internal void GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSetting lightData.shadowMaskSelector.x = -1.0f; lightData.nonLightMappedOnly = 0; } + + return lightData; } // TODO: we should be able to do this calculation only with LightData without VisibleLight light, but for now pass both - void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLightType, LightVolumeType lightVolumeType, + FiniteLightBound GetLightVolumeDataAndBound(BoundedEntityCategory lightCategory, GPULightType gpuLightType, LightVolumeType lightVolumeType, VisibleLight light, LightData lightData, Vector3 lightDimensions, Matrix4x4 worldToView, int viewIndex) { // Then Culling side @@ -1709,7 +1947,7 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig Vector3 zAxisVS = worldToView.MultiplyVector(lightToWorld.GetColumn(2)); // Fill bounds - var bound = new SFiniteLightBound(); + var bound = new FiniteLightBound(); var lightVolumeData = new LightVolumeData(); lightVolumeData.lightCategory = (uint)lightCategory; @@ -1868,8 +2106,7 @@ void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLig Debug.Assert(false, "TODO: encountered an unknown GPULightType."); } - m_lightList.lightsPerView[viewIndex].bounds.Add(bound); - m_lightList.lightsPerView[viewIndex].lightVolumes.Add(lightVolumeData); + return bound; } internal bool GetEnvLightData(CommandBuffer cmd, HDCamera hdCamera, in ProcessedProbeData processedProbe, ref EnvLightData envLightData) @@ -2018,9 +2255,9 @@ internal bool GetEnvLightData(CommandBuffer cmd, HDCamera hdCamera, in Processed return true; } - void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeType, Matrix4x4 worldToView, int viewIndex) + FiniteLightBound GetEnvLightVolumeDataAndBound(HDProbe probe, Matrix4x4 worldToView, int viewIndex) { - var bound = new SFiniteLightBound(); + var bound = new FiniteLightBound(); var lightVolumeData = new LightVolumeData(); // C is reflection volume center in world space (NOT same as cube map capture point) @@ -2034,13 +2271,13 @@ void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeTyp var influenceForwardVS = worldToView.MultiplyVector(influenceToWorld.GetColumn(2).normalized); var influencePositionVS = worldToView.MultiplyPoint(influenceToWorld.GetColumn(3)); - lightVolumeData.lightCategory = (uint)LightCategory.Env; + lightVolumeData.lightCategory = (uint)BoundedEntityCategory.ReflectionProbe; lightVolumeData.lightVolume = (uint)lightVolumeType; lightVolumeData.featureFlags = (uint)LightFeatureFlags.Env; - switch (lightVolumeType) + switch (probe.influenceVolume.shape) { - case LightVolumeType.Sphere: + case InfluenceShape.Sphere: { lightVolumeData.lightPos = influencePositionVS; lightVolumeData.radiusSq = influenceExtents.x * influenceExtents.x; @@ -2056,7 +2293,7 @@ void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeTyp bound.radius = influenceExtents.x; break; } - case LightVolumeType.Box: + case InfluenceShape.Box: { bound.center = influencePositionVS; bound.boxAxisX = influenceExtents.x * influenceRightVS; @@ -2076,16 +2313,20 @@ void GetEnvLightVolumeDataAndBound(HDProbe probe, LightVolumeType lightVolumeTyp lightVolumeData.boxInvRange.Set(1.0f / k_BoxCullingExtentThreshold.x, 1.0f / k_BoxCullingExtentThreshold.y, 1.0f / k_BoxCullingExtentThreshold.z); break; } + default: + { + Debug.Assert(false, "Encountered an unexpected case of a switch statement."); + break; + } } - m_lightList.lightsPerView[viewIndex].bounds.Add(bound); - m_lightList.lightsPerView[viewIndex].lightVolumes.Add(lightVolumeData); + return bound; } - void CreateBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView, float normalBiasDilation, out LightVolumeData volumeData, out SFiniteLightBound bound) + FiniteLightBound CreateBoxVolumeDataAndBound(OrientedBBox obb, BoundedEntityCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView, float normalBiasDilation) { volumeData = new LightVolumeData(); - bound = new SFiniteLightBound(); + bound = new FiniteLightBound(); // Used in Probe Volumes: // Conservatively dilate bounds used for tile / cluster assignment by normal bias. @@ -2122,6 +2363,8 @@ void CreateBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, Light volumeData.lightAxisZ = forwardVS; volumeData.boxInnerDist = extents - k_BoxCullingExtentThreshold; // We have no blend range, but the culling code needs a small EPS value for some reason??? volumeData.boxInvRange.Set(1.0f / k_BoxCullingExtentThreshold.x, 1.0f / k_BoxCullingExtentThreshold.y, 1.0f / k_BoxCullingExtentThreshold.z); + + return bound; } internal int GetCurrentShadowCount() @@ -2150,30 +2393,26 @@ internal static bool IsBakedShadowMaskLight(Light light) } internal static void EvaluateGPULightType(HDLightType lightType, SpotLightShape spotLightShape, AreaLightShape areaLightShape, - ref LightCategory lightCategory, ref GPULightType gpuLightType, ref LightVolumeType lightVolumeType) + ref BoundedEntityCategory lightCategory, ref GPULightType gpuLightType) { - lightCategory = LightCategory.Count; + lightCategory = BoundedEntityCategory.Count; gpuLightType = GPULightType.Point; - lightVolumeType = LightVolumeType.Count; switch (lightType) { case HDLightType.Spot: - lightCategory = LightCategory.Punctual; + lightCategory = BoundedEntityCategory.Punctual; switch (spotLightShape) { case SpotLightShape.Cone: gpuLightType = GPULightType.Spot; - lightVolumeType = LightVolumeType.Cone; break; case SpotLightShape.Pyramid: gpuLightType = GPULightType.ProjectorPyramid; - lightVolumeType = LightVolumeType.Cone; break; case SpotLightShape.Box: gpuLightType = GPULightType.ProjectorBox; - lightVolumeType = LightVolumeType.Box; break; default: Debug.Assert(false, "Encountered an unknown SpotLightShape."); @@ -2182,37 +2421,32 @@ internal static void EvaluateGPULightType(HDLightType lightType, SpotLightShape break; case HDLightType.Directional: - lightCategory = LightCategory.Punctual; + lightCategory = BoundedEntityCategory.None; // Unbounded gpuLightType = GPULightType.Directional; // No need to add volume, always visible - lightVolumeType = LightVolumeType.Count; // Count is none break; case HDLightType.Point: - lightCategory = LightCategory.Punctual; + lightCategory = BoundedEntityCategory.PunctualLight; gpuLightType = GPULightType.Point; - lightVolumeType = LightVolumeType.Sphere; break; case HDLightType.Area: - lightCategory = LightCategory.Area; + lightCategory = BoundedEntityCategory.AreaLight; switch (areaLightShape) { case AreaLightShape.Rectangle: gpuLightType = GPULightType.Rectangle; - lightVolumeType = LightVolumeType.Box; break; case AreaLightShape.Tube: gpuLightType = GPULightType.Tube; - lightVolumeType = LightVolumeType.Box; break; case AreaLightShape.Disc: //not used in real-time at the moment anyway gpuLightType = GPULightType.Disc; - lightVolumeType = LightVolumeType.Sphere; break; default: @@ -2227,6 +2461,134 @@ internal static void EvaluateGPULightType(HDLightType lightType, SpotLightShape } } + static float Log2f(float f) + { + return Mathf.Log(f, 2); // No way to directly emit the log2() instruction + } + + static int CeilLog2i(int i) + { + return Mathf.CeilToInt(Log2f(i)); // No integer log in our math library + } + + static void AssertUnitLength(Vector3 vec) + { + const float FLT_EPS = 5.960464478e-8f; + const float k = 32; // Empirical constant + + float sqMag = Vector3.SqrMagnitude(vec); + + Debug.Assert(Mathf.Abs(1 - sqMag) < k * FLT_EPS); + } + + static Vector3 ComputeWorldSpaceCentroidOfBoundedEntity(Light light) + { + // Most lights are "centered" by nature. + Vector3 centroidWS = light.transform.position; + + HDAdditionalLightData lightData = GetHDAdditionalLightData(light); + + HDLightType lightType = lightData.ComputeLightType(light); + Debug.Assert(lightType != HDLightType.Directional); + + if (lightType == HDLightType.Spot) + { + AssertUnitLength(light.transform.forward); + + Vector3 dirWS = light.transform.forward; + float range = lightData.range; + + centroidWS += (0.5f * range) * dirWS; + } + + return centroidWS; + } + + static Vector3 ComputeWorldSpaceCentroidOfBoundedEntity(HDProbe probe) + { + return (Vector3)probe.influenceToWorld.GetColumn(3); + } + + static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewIndex) + { + Matrix4x4 viewMatrix = GetWorldToViewMatrix(hdCamera, viewIndex); // Non-RWS + Vector3 positionVS = viewMatrix.MultiplyPoint(positionWS); + + return positionVS.z; + } + + // 'w' is the linear depth (Z coordinate of the view-space position). + // 'f' is the distance to the far plane. + // We consider the distance to the near plane n ≈ 0, since that plane may be oblique. + static int ComputeFixedPointLogDepth(float w, float f, int numBits = 16) + { + // z = Log[w/n] / Log[f/n] + // Undefined for (w < n, so we must clamp). This should not affect the efficiency of Z-binning. + // Still need the distance to the near plane in order for the math to work. + // Setting it too low will quickly consume the availabl bits. 0.1 is a safe value. + const float n = 0.1f; + + f = Math.Max(n, f); + + float x = Mathf.Max(1, w * (1/n)); + float z = Log2f(x) / Log2f(f * (1/n)); + + return Mathf.RoundToInt(z * ((1 << numBits) - 1)); + } + + internal struct BoundedEntitySortingKeyLayout + { + public const int k_EntityIndexBitCount = 16; + + public int categoryBitCount; + public int fixedPointLogDepthBitCount; + public int lightTypeBitCount; + public int indexBitCount; + public int totalBitCount; + + public int categoryOffset; + public int fixedPointLogDepthOffset; + public int lightTypeOffset; + public int indexOffset; + } + + internal static BoundedEntitySortingKeyLayout GeBoundedEntitySortingKeyLayoutLayout() + { + BoundedEntitySortingKeyLayout layout; + + layout.categoryBitCount = CeilLog2i((int)BoundedEntityCategory.Count); + layout.fixedPointLogDepthBitCount = 16; + layout.lightTypeBitCount = CeilLog2i((int)GPULightType.Count); + layout.indexBitCount = BoundedEntitySortingKeyLayout.k_EntityIndexBitCount; + layout.totalBitCount = layout.categoryBitCount + + layout.fixedPointLogDepthBitCount + + layout.lightTypeBitCount + + layout.indexBitCount; + // LSB -> MSB. + layout.indexOffset = 0; + layout.lightTypeOffset = layout.indexBitCount + layout.indexOffset; + layout.fixedPointLogDepthOffset = layout.lightTypeBitCount + layout.lightTypeOffset; + layout.categoryOffset = layout.fixedPointLogDepthBitCount + layout.fixedPointLogDepthOffset; + + return layout; + } + + // 'lightType' is optional in case the entity is not a light. + internal static ulong GenerateBoundedEntitySortingKey(int index, BoundedEntityCategory category, int fixedPointLogDepth, int lightType = 0) + { + BoundedEntitySortingKeyLayout layout = GeBoundedEntitySortingKeyLayoutLayout(); + + Debug.Assert(layout.totalBitCount <= 8 * sizeof(ulong)); + Debug.Assert(0 <= (int)category && (int)category < (int)BoundedEntityCategory.Count); + + ulong key = ((ulong)category << layout.categoryOffset) + | ((ulong)fixedPointLogDepth << layout.fixedPointLogDepthOffset) + | ((ulong)lightType << layout.lightTypeOffset) + | ((ulong)index << layout.indexOffset); + + return key; + } + bool TrivialRejectLight(VisibleLight light, HDCamera hdCamera, in AOVRequestData aovRequest) { // We can skip the processing of lights that are so small to not affect at least a pixel on screen. @@ -2253,12 +2615,11 @@ void PreprocessLightData(ref ProcessedLightData processedData, VisibleLight ligh processedData.lightType = additionalLightData.ComputeLightType(lightComponent); processedData.distanceToCamera = (additionalLightData.transform.position - hdCamera.camera.transform.position).magnitude; - // Evaluate the types that define the current light - processedData.lightCategory = LightCategory.Count; - processedData.gpuLightType = GPULightType.Point; - processedData.lightVolumeType = LightVolumeType.Count; - HDRenderPipeline.EvaluateGPULightType(processedData.lightType, processedData.additionalLightData.spotLightShape, processedData.additionalLightData.areaLightShape, - ref processedData.lightCategory, ref processedData.gpuLightType, ref processedData.lightVolumeType); + processedData.lightCategory = BoundedEntityCategory.Count; + processedData.gpuLightType = GPULightType.Count; + + EvaluateGPULightType(processedData.additionalLightData.type, processedData.additionalLightData.spotLightShape, processedData.additionalLightData.areaLightShape, + ref processedData.lightCategory, ref processedData.gpuLightType); processedData.lightDistanceFade = processedData.gpuLightType == GPULightType.Directional ? 1.0f : HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.fadeDistance); processedData.isBakedShadowMask = IsBakedShadowMaskLight(lightComponent); @@ -2277,16 +2638,13 @@ int PreprocessVisibleLights(HDCamera hdCamera, CullingResults cullResults, Debug // 1. Count the number of lights and sort all lights by category, type and volume - This is required for the fptl/cluster shader code // If we reach maximum of lights available on screen, then we discard the light. // Lights are processed in order, so we don't discards light based on their importance but based on their ordering in visible lights list. - int directionalLightcount = 0; - int punctualLightcount = 0; - int areaLightCount = 0; m_ProcessedLightData.Resize(cullResults.visibleLights.Length); - int lightCount = Math.Min(cullResults.visibleLights.Length, m_MaxLightsOnScreen); - UpdateSortKeysArray(lightCount); - int sortCount = 0; - for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; (lightIndex < numLights) && (sortCount < lightCount); ++lightIndex) + int maxLightCount = m_MaxDirectionalLightsOnScreen + m_MaxPunctualLightsOnScreen + m_MaxAreaLightsOnScreen; + int includedLightCount = 0; + + for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; (lightIndex < numLights) && (includedLightCount < maxLightCount); ++lightIndex) { var light = cullResults.visibleLights[lightIndex]; @@ -2314,19 +2672,15 @@ int PreprocessVisibleLights(HDCamera hdCamera, CullingResults cullResults, Debug // Do NOT process lights beyond the specified limit! switch (processedData.lightCategory) { - case LightCategory.Punctual: - if (processedData.gpuLightType == GPULightType.Directional) // Our directional lights are "punctual"... - { - if (!debugDisplaySettings.data.lightingDebugSettings.showDirectionalLight || directionalLightcount >= m_MaxDirectionalLightsOnScreen) continue; - directionalLightcount++; - break; - } - if (!debugDisplaySettings.data.lightingDebugSettings.showPunctualLight || punctualLightcount >= m_MaxPunctualLightsOnScreen) continue; - punctualLightcount++; + case BoundedEntityCategory.None: // Unbounded + Debug.Assert(processedData.gpuLightType == GPULightType.Directional); + if (!debugDisplaySettings.data.lightingDebugSettings.showDirectionalLight || m_DirectionalLightIndices.Count >= m_MaxDirectionalLightsOnScreen) continue; + break; + case BoundedEntityCategory.PunctualLight: + if (!debugDisplaySettings.data.lightingDebugSettings.showPunctualLight || m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight) >= m_MaxPunctualLightsOnScreen) continue; break; - case LightCategory.Area: - if (!debugDisplaySettings.data.lightingDebugSettings.showAreaLight || areaLightCount >= m_MaxAreaLightsOnScreen) continue; - areaLightCount++; + case BoundedEntityCategory.AreaLight: + if (!debugDisplaySettings.data.lightingDebugSettings.showAreaLight || m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight) >= m_MaxAreaLightsOnScreen) continue; break; default: break; @@ -2348,22 +2702,34 @@ int PreprocessVisibleLights(HDCamera hdCamera, CullingResults cullResults, Debug && !debugLightFilter.IsEnabledFor(processedData.gpuLightType, additionalData.spotLightShape)) continue; - // 5 bit (0x1F) light category, 5 bit (0x1F) GPULightType, 5 bit (0x1F) lightVolume, 1 bit for shadow casting, 16 bit index - m_SortKeys[sortCount++] = (uint)processedData.lightCategory << 27 | (uint)processedData.gpuLightType << 22 | (uint)processedData.lightVolumeType << 17 | (uint)lightIndex; + if (processedData.gpuLightType == GPULightType.Directional) + { + m_DirectionalLightIndices.Add(lightIndex); + } + else + { + int xrViewCount = hdCamera.viewCount; + + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) + { + float w = ComputeLinearDepth(ComputeWorldSpaceCentroidOfBoundedEntity(light.light), hdCamera, viewIndex); + int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views + ulong key = GenerateBoundedEntitySortingKey(lightIndex, processedData.lightCategory, d, (int)processedData.gpuLightType); + + m_BoundedEntityCollection.AddEntitySortKey(viewIndex, processedData.lightCategory, key); + } + } + + includedLightCount++; } - CoreUnsafeUtils.QuickSort(m_SortKeys, 0, sortCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call). - return sortCount; + return includedLightCount; } - void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, int processedLightCount) + void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults) { Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; - int directionalLightcount = 0; - int punctualLightcount = 0; - int areaLightCount = 0; - // Now that all the lights have requested a shadow resolution, we can layout them in the atlas // And if needed rescale the whole atlas m_ShadowManager.LayoutShadowMaps(m_CurrentDebugDisplaySettings.data.lightingDebugSettings); @@ -2392,16 +2758,11 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu var shadowFilteringQuality = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.shadowFilteringQuality; // 2. Go through all lights, convert them to GPU format. - // Simultaneously create data for culling (LightVolumeData and SFiniteLightBound) + // Simultaneously create data for culling for (int sortIndex = 0; sortIndex < processedLightCount; ++sortIndex) { - // In 1. we have already classify and sorted the light, we need to use this sorted order here - uint sortKey = m_SortKeys[sortIndex]; - LightCategory lightCategory = (LightCategory)((sortKey >> 27) & 0x1F); - GPULightType gpuLightType = (GPULightType)((sortKey >> 22) & 0x1F); - LightVolumeType lightVolumeType = (LightVolumeType)((sortKey >> 17) & 0x1F); - int lightIndex = (int)(sortKey & 0xFFFF); + int lightIndex = m_DirectionalLightIndices[sortIndex]; var light = cullResults.visibleLights[lightIndex]; var lightComponent = light.light; @@ -2409,7 +2770,6 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu m_EnableBakeShadowMask = m_EnableBakeShadowMask || processedData.isBakedShadowMask; - // Light should always have additional data, however preview light right don't have, so we must handle the case by assigning HDUtils.s_DefaultHDAdditionalLightData var additionalLightData = processedData.additionalLightData; int shadowIndex = -1; @@ -2431,75 +2791,94 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu #endif } - // Directional rendering side, it is separated as it is always visible so no volume to handle here - if (gpuLightType == GPULightType.Directional) - { - GetDirectionalLightData(cmd, hdCamera, light, lightComponent, lightIndex, shadowIndex, directionalLightcount, isPbrSkyActive, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot); + Debug.Assert(gpuLightType == GPULightType.Directional); - directionalLightcount++; + DirectionalLightData lightData = GetDirectionalLightData(cmd, hdCamera, light, lightComponent, lightIndex, shadowIndex, directionalLightcount, isPbrSkyActive, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot); - // We make the light position camera-relative as late as possible in order - // to allow the preceding code to work with the absolute world space coordinates. - if (ShaderConfig.s_CameraRelativeRendering != 0) - { - // Caution: 'DirectionalLightData.positionWS' is camera-relative after this point. - int last = m_lightList.directionalLights.Count - 1; - DirectionalLightData lightData = m_lightList.directionalLights[last]; - lightData.positionRWS -= camPosWS; - m_lightList.directionalLights[last] = lightData; - } + // We make the light position camera-relative as late as possible in order + // to allow the preceding code to work with the absolute world space coordinates. + if (ShaderConfig.s_CameraRelativeRendering != 0) + { + // Caution: 'DirectionalLightData.positionWS' is camera-relative after this point. + lightData.positionRWS -= camPosWS; } - else + + m_DirectionalLightData.Add(lightData); + } + + int xrViewCount = hdCamera.viewCount; + + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) + { + // Go through both categories at the same time (to make the existing code work). + int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.PunctualLight); + int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight) + + m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight); + + Debug.Assert(((int)BoundedEntityCategory.AreaLight - (int)BoundedEntityCategory.PunctualLight) == 1); + + for (int sortIndex = start; sortIndex < (start + count); ++sortIndex) { - Vector3 lightDimensions = new Vector3(); // X = length or width, Y = height, Z = range (depth) + BoundedEntitySortingKeyLayout layout = GeBoundedEntitySortingKeyLayoutLayout(); - // Allocate a light data - LightData lightData = new LightData(); + // In 1. we have already classify and sorted the light, we need to use this sorted order here + ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); - // Punctual, area, projector lights - the rendering side. - GetLightData(cmd, hdCamera, hdShadowSettings, light, lightComponent, in m_ProcessedLightData[lightIndex], shadowIndex, contactShadowScalableSetting, isRasterization: true, ref lightDimensions, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot, ref lightData); + var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); + var gpuLightType = (GPULightType) ((sortKey >> layout.lightTypeOffset) & ((1ul << layout.lightTypeBitCount) - 1)); + var lightIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); + + Debug.Assert(category == BoundedEntityCategory.PunctualLight || category == BoundedEntityCategory.AreaLight); + + var light = cullResults.visibleLights[lightIndex]; + var lightComponent = light.light; + ProcessedLightData processedData = m_ProcessedLightData[lightIndex]; - // Add the previously created light data - m_lightList.lights.Add(lightData); + m_EnableBakeShadowMask = m_EnableBakeShadowMask || processedData.isBakedShadowMask; - switch (lightCategory) + var additionalLightData = processedData.additionalLightData; + + int shadowIndex = -1; + + // Manage shadow requests + if (additionalLightData.WillRenderShadowMap()) { - case LightCategory.Punctual: - punctualLightcount++; - break; - case LightCategory.Area: - areaLightCount++; - break; - default: - Debug.Assert(false, "TODO: encountered an unknown LightCategory."); - break; + int shadowRequestCount; + shadowIndex = additionalLightData.UpdateShadowRequest(hdCamera, m_ShadowManager, hdShadowSettings, light, cullResults, lightIndex, m_CurrentDebugDisplaySettings.data.lightingDebugSettings, shadowFilteringQuality, out shadowRequestCount); + + #if UNITY_EDITOR + if ((m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugUseSelection + || m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) + && UnityEditor.Selection.activeGameObject == lightComponent.gameObject) + { + m_DebugSelectedLightShadowIndex = shadowIndex; + m_DebugSelectedLightShadowCount = shadowRequestCount; + } + #endif } + Debug.Assert(gpuLightType != GPULightType.Directional); + + Vector3 lightDimensions = new Vector3(); // X = length or width, Y = height, Z = range (depth) + + // Punctual, area, projector lights - the rendering side. + LightData lightData = GetLightData(cmd, hdCamera, hdShadowSettings, light, lightComponent, in m_ProcessedLightData[lightIndex], shadowIndex, contactShadowScalableSetting, isRasterization: true, ref lightDimensions, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot, ref lightData); + // Then culling side. Must be call in this order as we pass the created Light data to the function - for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) - { - GetLightVolumeDataAndBound(lightCategory, gpuLightType, lightVolumeType, light, m_lightList.lights[m_lightList.lights.Count - 1], lightDimensions, m_WorldToViewMatrices[viewIndex], viewIndex); - } + FiniteLightBound bounds = GetLightVolumeDataAndBound(lightCategory, gpuLightType, lightVolumeType, light, m_lightList.lights[m_lightList.lights.Count - 1], lightDimensions, m_WorldToViewMatrices[viewIndex], viewIndex); // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. if (ShaderConfig.s_CameraRelativeRendering != 0) { // Caution: 'LightData.positionWS' is camera-relative after this point. - int last = m_lightList.lights.Count - 1; - lightData = m_lightList.lights[last]; lightData.positionRWS -= camPosWS; - m_lightList.lights[last] = lightData; } + + m_BoundedEntityCollection.AddEntityData(viewIndex, category, lightData); + m_BoundedEntityCollection.AddEntityBounds(viewIndex, category, bounds); } } - - // Sanity check - Debug.Assert(m_lightList.directionalLights.Count == directionalLightcount); - Debug.Assert(m_lightList.lights.Count == areaLightCount + punctualLightcount); - - m_lightList.punctualLightCount = punctualLightcount; - m_lightList.areaLightCount = areaLightCount; } bool TrivialRejectProbe(in ProcessedProbeData processedProbe, HDCamera hdCamera) @@ -2557,15 +2936,13 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro // Redo everything but this time with envLights Debug.Assert(m_MaxEnvLightsOnScreen <= 256); //for key construction - int envLightCount = 0; - - var totalProbes = cullResults.visibleReflectionProbes.Length + hdProbeCullingResults.visibleProbes.Count; m_ProcessedReflectionProbeData.Resize(cullResults.visibleReflectionProbes.Length); m_ProcessedPlanarProbeData.Resize(hdProbeCullingResults.visibleProbes.Count); - int maxProbeCount = Math.Min(totalProbes, m_MaxEnvLightsOnScreen); - UpdateSortKeysArray(maxProbeCount); + var totalProbeCount = cullResults.visibleReflectionProbes.Length + hdProbeCullingResults.visibleProbes.Count; + int maxProbeCount = m_MaxEnvLightsOnScreen; + int includedProbeCount = 0; var enableReflectionProbes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReflectionProbe) && (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.ReflectionProbe)); @@ -2575,7 +2952,7 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro if (enableReflectionProbes) { - for (int probeIndex = 0; probeIndex < cullResults.visibleReflectionProbes.Length; probeIndex++) + for (int probeIndex = 0; (probeIndex < cullResults.visibleReflectionProbes.Length) && (includedProbeCount < maxProbeCount); probeIndex++) { var probe = cullResults.visibleReflectionProbes[probeIndex]; @@ -2597,23 +2974,27 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro continue; } - // This test needs to be the last one otherwise we may consume an available slot and then discard the probe. - if (envLightCount >= maxProbeCount) - continue; + // Sorting by volume is no longer possible + // var logVolume = CalculateProbeLogVolume(probe.bounds); - LightVolumeType lightVolumeType = LightVolumeType.Box; - if (processedData.hdProbe != null && processedData.hdProbe.influenceVolume.shape == InfluenceShape.Sphere) - lightVolumeType = LightVolumeType.Sphere; + int xrViewCount = hdCamera.viewCount; - var logVolume = CalculateProbeLogVolume(probe.bounds); + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) + { + float w = ComputeLinearDepth(ComputeWorldSpaceCentroidOfBoundedEntity(processedData.hdProbe), hdCamera, viewIndex); + int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views + ulong key = GenerateBoundedEntitySortingKey(probeIndex, BoundedEntityCategory.ReflectionProbe, d, (int)GPULightType.CubemapReflection); - m_SortKeys[envLightCount++] = PackProbeKey(logVolume, lightVolumeType, 0u, probeIndex); // Sort by volume + m_BoundedEntityCollection.AddEntitySortKey(viewIndex, BoundedEntityCategory.ReflectionProbe, key); + } + + includedProbeCount++; } } if (enablePlanarProbes) { - for (int planarProbeIndex = 0; planarProbeIndex < hdProbeCullingResults.visibleProbes.Count; planarProbeIndex++) + for (int planarProbeIndex = 0; (planarProbeIndex < hdProbeCullingResults.visibleProbes.Count) && (includedProbeCount < maxProbeCount); planarProbeIndex++) { var probe = hdProbeCullingResults.visibleProbes[planarProbeIndex]; @@ -2623,59 +3004,74 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro if (!aovRequest.IsLightEnabled(probe.gameObject)) continue; - // This test needs to be the last one otherwise we may consume an available slot and then discard the probe. - if (envLightCount >= maxProbeCount) - continue; + // Sorting by volume is no longer possible + // var logVolume = CalculateProbeLogVolume(probe.bounds); + + int xrViewCount = hdCamera.viewCount; - var lightVolumeType = LightVolumeType.Box; - if (probe.influenceVolume.shape == InfluenceShape.Sphere) - lightVolumeType = LightVolumeType.Sphere; + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) + { + float w = ComputeLinearDepth(ComputeWorldSpaceCentroidOfBoundedEntity(processedData.hdProbe), hdCamera, viewIndex); + int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views + ulong key = GenerateBoundedEntitySortingKey(planarProbeIndex, BoundedEntityCategory.ReflectionProbe, d, (int)GPULightType.PlanarReflection); - var logVolume = CalculateProbeLogVolume(probe.bounds); + m_BoundedEntityCollection.AddEntitySortKey(viewIndex, BoundedEntityCategory.ReflectionProbe, key); + } - m_SortKeys[envLightCount++] = PackProbeKey(logVolume, lightVolumeType, 1u, planarProbeIndex); // Sort by volume + includedProbeCount++; } } - // Not necessary yet but call it for future modification with sphere influence volume - CoreUnsafeUtils.QuickSort(m_SortKeys, 0, envLightCount - 1); // Call our own quicksort instead of Array.Sort(sortKeys, 0, sortCount) so we don't allocate memory (note the SortCount-1 that is different from original call). - return envLightCount; + return includedProbeCount; } - void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, HDProbeCullingResults hdProbeCullingResults, int processedLightCount) + void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, HDProbeCullingResults hdProbeCullingResults) { Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; for (int sortIndex = 0; sortIndex < processedLightCount; ++sortIndex) + int xrViewCount = hdCamera.viewCount; + + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) { - // In 1. we have already classify and sorted the light, we need to use this sorted order here - uint sortKey = m_SortKeys[sortIndex]; - LightVolumeType lightVolumeType; - int probeIndex; - int listType; - UnpackProbeSortKey(sortKey, out lightVolumeType, out probeIndex, out listType); + int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.ReflectionProbe); + int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe); + + for (int sortIndex = start; sortIndex < (start + count); ++sortIndex) + { + BoundedEntitySortingKeyLayout layout = GeBoundedEntitySortingKeyLayoutLayout(); - ProcessedProbeData processedProbe = (listType == 0) ? m_ProcessedReflectionProbeData[probeIndex] : m_ProcessedPlanarProbeData[probeIndex]; + // In 1. we have already classify and sorted the light, we need to use this sorted order here + ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); - EnvLightData envLightData = new EnvLightData(); + var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); + var gpuLightType = (GPULightType) ((sortKey >> layout.lightTypeOffset) & ((1ul << layout.lightTypeBitCount) - 1)); + var probeIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); - if (GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData)) - { - // it has been filled - m_lightList.envLights.Add(envLightData); + Debug.Assert(category == BoundedEntityCategory.ReflectionProbe); - for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) + ProcessedProbeData processedProbe = (gpuLightType == GPULightType.PlanarReflection) ? m_ProcessedPlanarProbeData[probeIndex] + : m_ProcessedReflectionProbeData[probeIndex]; + EnvLightData envLightData = new EnvLightData(); + + if (GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData)) { var worldToView = GetWorldToViewMatrix(hdCamera, viewIndex); - GetEnvLightVolumeDataAndBound(processedProbe.hdProbe, lightVolumeType, worldToView, viewIndex); - } + FiniteLightBound bounds = GetEnvLightVolumeDataAndBound(processedProbe.hdProbe, gpuLightType, worldToView, viewIndex); - // We make the light position camera-relative as late as possible in order - // to allow the preceding code to work with the absolute world space coordinates. - UpdateEnvLighCameraRelativetData(ref envLightData, camPosWS); + // We make the light position camera-relative as late as possible in order + // to allow the preceding code to work with the absolute world space coordinates. + if (ShaderConfig.s_CameraRelativeRendering != 0) + { + // Caution: 'EnvLightData.positionRWS' is camera-relative after this point. + envLightData.capturePositionRWS -= camPosWS; + envLightData.influencePositionRWS -= camPosWS; + envLightData.proxyPositionRWS -= camPosWS; + } - int last = m_lightList.envLights.Count - 1; - m_lightList.envLights[last] = envLightData; + m_BoundedEntityCollection.AddEntityData(viewIndex, BoundedEntityCategory.ReflectionProbe, envLightData); + m_BoundedEntityCollection.AddEntityBounds(viewIndex, BoundedEntityCategory.ReflectionProbe, bounds); + } } } } @@ -2696,8 +3092,6 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // If any light require it, we need to enabled bake shadow mask feature m_EnableBakeShadowMask = false; - m_lightList.Clear(); - // We need to properly reset this here otherwise if we go from 1 light to no visible light we would keep the old reference active. m_CurrentSunLight = null; m_CurrentSunLightAdditionalLightData = null; @@ -2705,7 +3099,15 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu m_DebugSelectedLightShadowIndex = -1; m_DebugSelectedLightShadowCount = 0; - int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); + int xrViewCount = hdCamera.viewCount; + + // Step 1: Fill m_BoundedEntityCollection.entitySortKeys and m_DirectionalLightIndices. + // Step 2: Sort m_BoundedEntityCollection. + // Step 3: Fill m_BoundedEntityCollection.*Data (in the sorted order!) and m_DirectionalLightData. + // Step 4: Upload the data to the GPU. + m_DirectionalLightData.Clear(); + m_DirectionalLightIndices.Clear(); + m_BoundedEntityCollection.Reset(); // We must clear the shadow requests before checking if they are any visible light because we would have requests from the last frame executed in the case where we don't see any lights m_ShadowManager.Clear(); @@ -2724,16 +3126,72 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu m_CurrentScreenSpaceShadowData[i].valid = false; } + /* ---------------------------- Step 1 ---------------------------- */ + // Do not pre-process per view... + // Note: Light with null intensity/Color are culled by the C++, no need to test it here if (cullResults.visibleLights.Length != 0) { - int processedLightCount = PreprocessVisibleLights(hdCamera, cullResults, debugDisplaySettings, aovRequest); + PreprocessVisibleLights(hdCamera, cullResults, debugDisplaySettings, aovRequest); + } + + if (cullResults.visibleReflectionProbes.Length != 0 || hdProbeCullingResults.visibleProbes.Count != 0) + { + PreprocessVisibleProbes(hdCamera, cullResults, hdProbeCullingResults, aovRequest); + } + + int decalCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); + + for (int decalIndex = 0; decalIndex < decalCount; decalIndex++) + { + Vector3 centroidVS = DecalSystem.m_Bounds[decalIndex].center; // Computed for the first eye, I guess? Confirm... + + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) + { + float w = centroidVS.z; + + if (viewIndex > 0) // This is quite suboptimal... + { + Matrix4x4 viewMatrixEye0 = GetWorldToViewMatrix(hdCamera, 0); // Non-RWS + Vector3 centroidWS = viewMatrixEye0.inverse.MultiplyPoint(centroidVS); + + w = ComputeLinearDepth(centroidWS, hdCamera, viewIndex); + } + + int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views + ulong key = GenerateBoundedEntitySortingKey(decalIndex, BoundedEntityCategory.Decal, d); + m_BoundedEntityCollection.AddEntitySortKey(viewIndex, BoundedEntityCategory.Decal, key); + } + } + + int densityVolumeCount = (densityVolumes.bounds != null) ? Math.Min(densityVolumes.bounds.Count, m_MaxDensityVolumesOnScreen) : 0; + + for (int densityVolumeIndex = 0; densityVolumeIndex < densityVolumeCount; densityVolumeIndex++) + { + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) + { + float w = ComputeLinearDepth(densityVolumes.bounds[densityVolumeIndex].center, hdCamera, viewIndex); + int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views + ulong key = GenerateBoundedEntitySortingKey(densityVolumeIndex, BoundedEntityCategory.DensityVolume, d); + + m_BoundedEntityCollection.AddEntitySortKey(viewIndex, BoundedEntityCategory.DensityVolume, key); + } + } + + /* ---------------------------- Step 2 ---------------------------- */ + m_BoundedEntityCollection.Sort(); + + /* ---------------------------- Step 3 ---------------------------- */ + + // Note: Light with null intensity/Color are culled by the C++, no need to test it here + if (cullResults.visibleLights.Length != 0) + { // In case ray tracing supported and a light cluster is built, we need to make sure to reserve all the cookie slots we need if (m_RayTracingSupported) ReserveRayTracingCookieAtlasSlots(); - PrepareGPULightdata(cmd, hdCamera, cullResults, processedLightCount); + PrepareGPULightdata(cmd, hdCamera, cullResults); // Update the compute buffer with the shadow request datas m_ShadowManager.PrepareGPUShadowDatas(cullResults, hdCamera); @@ -2747,106 +3205,134 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu if (cullResults.visibleReflectionProbes.Length != 0 || hdProbeCullingResults.visibleProbes.Count != 0) { - int processedProbesCount = PreprocessVisibleProbes(hdCamera, cullResults, hdProbeCullingResults, aovRequest); - PrepareGPUProbeData(cmd, hdCamera, cullResults, hdProbeCullingResults, processedProbesCount); + PrepareGPUProbeData(cmd, hdCamera, cullResults, hdProbeCullingResults); } - if (decalDatasCount > 0) + // Decals. + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) { for (int i = 0; i < decalDatasCount; i++) + int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.Decal); + int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal); + + for (int sortIndex = start; sortIndex < (start + count); ++sortIndex) { for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) - { - m_lightList.lightsPerView[viewIndex].bounds.Add(DecalSystem.m_Bounds[i]); - m_lightList.lightsPerView[viewIndex].lightVolumes.Add(DecalSystem.m_LightVolumes[i]); - } - } - } + BoundedEntitySortingKeyLayout layout = GeBoundedEntitySortingKeyLayoutLayout(); - // Inject density volumes into the clustered data structure for efficient look up. - m_DensityVolumeCount = densityVolumes.bounds != null ? densityVolumes.bounds.Count : 0; - m_ProbeVolumeCount = probeVolumes.bounds != null ? probeVolumes.bounds.Count : 0; + ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); - bool probeVolumeNormalBiasEnabled = false; - if (ShaderConfig.s_ProbeVolumesEvaluationMode != ProbeVolumesEvaluationModes.Disabled) - { - var settings = hdCamera.volumeStack.GetComponent(); - probeVolumeNormalBiasEnabled = !(settings == null || (settings.leakMitigationMode.value != LeakMitigationMode.NormalBias && settings.leakMitigationMode.value != LeakMitigationMode.OctahedralDepthOcclusionFilter)); - } + var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); + var decalIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); - for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) - { - Matrix4x4 worldToViewCR = GetWorldToViewMatrix(hdCamera, viewIndex); - - if (ShaderConfig.s_CameraRelativeRendering != 0) - { - // The OBBs are camera-relative, the matrix is not. Fix it. - worldToViewCR.SetColumn(3, new Vector4(0, 0, 0, 1)); - } + Debug.Assert(category == BoundedEntityCategory.Decal); - for (int i = 0, n = m_DensityVolumeCount; i < n; i++) - { - // Density volumes are not lights and therefore should not affect light classification. - LightFeatureFlags featureFlags = 0; - CreateBoxVolumeDataAndBound(densityVolumes.bounds[i], LightCategory.DensityVolume, featureFlags, worldToViewCR, 0.0f, out LightVolumeData volumeData, out SFiniteLightBound bound); - m_lightList.lightsPerView[viewIndex].lightVolumes.Add(volumeData); - m_lightList.lightsPerView[viewIndex].bounds.Add(bound); - } + FiniteLightBound bounds = DecalSystem.m_Bounds[decalIndex]; - for (int i = 0, n = m_ProbeVolumeCount; i < n; i++) - { - // Probe volumes are not lights and therefore should not affect light classification. - LightFeatureFlags featureFlags = 0; - float probeVolumeNormalBiasWS = probeVolumeNormalBiasEnabled ? probeVolumes.data[i].normalBiasWS : 0.0f; - CreateBoxVolumeDataAndBound(probeVolumes.bounds[i], LightCategory.ProbeVolume, featureFlags, worldToViewCR, probeVolumeNormalBiasWS, out LightVolumeData volumeData, out SFiniteLightBound bound); - if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + if (viewIndex > 0) { - // Only probe volume evaluation in the material pass use these custom probe volume specific lists. - // Probe volumes evaluated in the light loop, as well as other volume data such as Decals get folded into the standard list data. - m_lightList.lightsPerView[viewIndex].probeVolumesLightVolumes.Add(volumeData); - m_lightList.lightsPerView[viewIndex].probeVolumesBounds.Add(bound); + // This is quite suboptimal... + m_lightList.lightsPerView[viewIndex].bounds.Add(DecalSystem.m_Bounds[i]); + m_lightList.lightsPerView[viewIndex].lightVolumes.Add(DecalSystem.m_LightVolumes[i]); + Matrix4x4 viewMatrixEye0 = GetWorldToViewMatrix(hdCamera, 0); + Matrix4x4 viewMatrixEyeI = GetWorldToViewMatrix(hdCamera, viewIndex); + Matrix4x4 viewTransferMatrix = viewMatrixEyeI * viewMatrixEye0.inverse; + + bounds.boxAxisX = viewTransferMatrix.MultiplyVector(bounds.boxAxisX); + bounds.boxAxisY = viewTransferMatrix.MultiplyVector(bounds.boxAxisY); + bounds.boxAxisZ = viewTransferMatrix.MultiplyVector(bounds.boxAxisZ); + bounds.center = viewTransferMatrix.MultiplyPoint(bounds.center); } - else - { - m_lightList.lightsPerView[viewIndex].lightVolumes.Add(volumeData); - m_lightList.lightsPerView[viewIndex].bounds.Add(bound); - } + m_BoundedEntityCollection.AddEntityData(viewIndex, BoundedEntityCategory.Decal, DecalSystem.m_DecalDatas[decalIndex]); + m_BoundedEntityCollection.AddEntityBounds(viewIndex, BoundedEntityCategory.Decal, bounds); } } - m_TotalLightCount = m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_DensityVolumeCount; - if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.LightLoop) + // Density volumes. + for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) { - m_TotalLightCount += m_ProbeVolumeCount; - } + Matrix4x4 worldToViewCR = GetWorldToViewMatrix(hdCamera, viewIndex); - Debug.Assert(m_TotalLightCount == m_lightList.lightsPerView[0].bounds.Count); - Debug.Assert(m_TotalLightCount == m_lightList.lightsPerView[0].lightVolumes.Count); + int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.DensityVolume); + int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume); - // Aggregate the remaining views into the first entry of the list (view 0) - for (int viewIndex = 1; viewIndex < hdCamera.viewCount; ++viewIndex) - { - Debug.Assert(m_lightList.lightsPerView[viewIndex].bounds.Count == m_TotalLightCount); - m_lightList.lightsPerView[0].bounds.AddRange(m_lightList.lightsPerView[viewIndex].bounds); + for (int sortIndex = start; sortIndex < (start + count); ++sortIndex) + { + BoundedEntitySortingKeyLayout layout = GeBoundedEntitySortingKeyLayoutLayout(); - Debug.Assert(m_lightList.lightsPerView[viewIndex].lightVolumes.Count == m_TotalLightCount); - m_lightList.lightsPerView[0].lightVolumes.AddRange(m_lightList.lightsPerView[viewIndex].lightVolumes); - } + ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); - if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) - { - // Aggregate the remaining probe volume views into the first entry of the list (view 0) - for (int viewIndex = 1; viewIndex < hdCamera.viewCount; ++viewIndex) - { - Debug.Assert(m_lightList.lightsPerView[viewIndex].probeVolumesBounds.Count == m_ProbeVolumeCount); - m_lightList.lightsPerView[0].probeVolumesBounds.AddRange(m_lightList.lightsPerView[viewIndex].probeVolumesBounds); + var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); + var densityVolumeIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); + + Debug.Assert(category == BoundedEntityCategory.DensityVolume); + + // Density volumes are not lights and therefore should not affect light classification. + LightFeatureFlags featureFlags = 0; + FiniteLightBound bounds = AddBoxVolumeDataAndBound(densityVolumes.bounds[densityVolumeIndex], BoundedEntityCategory.DensityVolume, featureFlags, worldToViewCR, viewIndex); - Debug.Assert(m_lightList.lightsPerView[viewIndex].probeVolumesLightVolumes.Count == m_ProbeVolumeCount); - m_lightList.lightsPerView[0].probeVolumesLightVolumes.AddRange(m_lightList.lightsPerView[viewIndex].probeVolumesLightVolumes); + m_BoundedEntityCollection.AddEntityData(viewIndex, BoundedEntityCategory.DensityVolume, densityVolumes.density[densityVolumeIndex]); + m_BoundedEntityCollection.AddEntityBounds(viewIndex, BoundedEntityCategory.DensityVolume, bounds); } } + // I am not touching probe volumes... + m_ProbeVolumeCount = probeVolumes.bounds != null ? probeVolumes.bounds.Count : 0; + + // bool probeVolumeNormalBiasEnabled = false; + // if (ShaderConfig.s_ProbeVolumesEvaluationMode != ProbeVolumesEvaluationModes.Disabled) + // { + // var settings = hdCamera.volumeStack.GetComponent(); + // probeVolumeNormalBiasEnabled = !(settings == null || (settings.leakMitigationMode.value != LeakMitigationMode.NormalBias && settings.leakMitigationMode.value != LeakMitigationMode.OctahedralDepthOcclusionFilter)); + // } + + // for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) + // { + // Matrix4x4 worldToViewCR = GetWorldToViewMatrix(hdCamera, viewIndex); + + // if (ShaderConfig.s_CameraRelativeRendering != 0) + // { + // // The OBBs are camera-relative, the matrix is not. Fix it. + // worldToViewCR.SetColumn(3, new Vector4(0, 0, 0, 1)); + // } + + // for (int i = 0, n = m_ProbeVolumeCount; i < n; i++) + // { + // // Probe volumes are not lights and therefore should not affect light classification. + // LightFeatureFlags featureFlags = 0; + // float probeVolumeNormalBiasWS = probeVolumeNormalBiasEnabled ? probeVolumes.data[i].normalBiasWS : 0.0f; + // CreateBoxVolumeDataAndBound(probeVolumes.bounds[i], BoundedEntityCategory.ProbeVolume, featureFlags, worldToViewCR, probeVolumeNormalBiasWS, out LightVolumeData volumeData, out FiniteLightBound bound); + // if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + // { + // // Only probe volume evaluation in the material pass use these custom probe volume specific lists. + // // Probe volumes evaluated in the light loop, as well as other volume data such as Decals get folded into the standard list data. + // m_lightList.lightsPerView[viewIndex].probeVolumesLightVolumes.Add(volumeData); + // m_lightList.lightsPerView[viewIndex].probeVolumesBounds.Add(bound); + // } + // else + // { + + // m_lightList.lightsPerView[viewIndex].lightVolumes.Add(volumeData); + // m_lightList.lightsPerView[viewIndex].bounds.Add(bound); + // } + // } + // } + + // if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + // { + // // Aggregate the remaining probe volume views into the first entry of the list (view 0) + // for (int viewIndex = 1; viewIndex < hdCamera.viewCount; ++viewIndex) + // { + // Debug.Assert(m_lightList.lightsPerView[viewIndex].probeVolumesBounds.Count == m_ProbeVolumeCount); + // m_lightList.lightsPerView[0].probeVolumesBounds.AddRange(m_lightList.lightsPerView[viewIndex].probeVolumesBounds); + + // Debug.Assert(m_lightList.lightsPerView[viewIndex].probeVolumesLightVolumes.Count == m_ProbeVolumeCount); + // m_lightList.lightsPerView[0].probeVolumesLightVolumes.AddRange(m_lightList.lightsPerView[viewIndex].probeVolumesLightVolumes); + // } + // } + + /* ---------------------------- Step 4 ---------------------------- */ PushLightDataGlobalParams(cmd); PushShadowGlobalParams(cmd); } @@ -2899,54 +3385,12 @@ internal void ReserveCookieAtlasTexture(HDAdditionalLightData hdLightData, Light } } - internal static void UpdateLightCameraRelativetData(ref LightData lightData, Vector3 camPosWS) - { - if (ShaderConfig.s_CameraRelativeRendering != 0) - { - lightData.positionRWS -= camPosWS; - } - } - - internal static void UpdateEnvLighCameraRelativetData(ref EnvLightData envLightData, Vector3 camPosWS) - { - if (ShaderConfig.s_CameraRelativeRendering != 0) - { - // Caution: 'EnvLightData.positionRWS' is camera-relative after this point. - envLightData.capturePositionRWS -= camPosWS; - envLightData.influencePositionRWS -= camPosWS; - envLightData.proxyPositionRWS -= camPosWS; - } - } - - static float CalculateProbeLogVolume(Bounds bounds) - { - //Notes: - // - 1+ term is to prevent having negative values in the log result - // - 1000* is too keep 3 digit after the dot while we truncate the result later - // - 1048575 is 2^20-1 as we pack the result on 20bit later - float boxVolume = 8f* bounds.extents.x * bounds.extents.y * bounds.extents.z; - float logVolume = Mathf.Clamp(Mathf.Log(1 + boxVolume, 1.05f)*1000, 0, 1048575); - return logVolume; - } - - static void UnpackProbeSortKey(uint sortKey, out LightVolumeType lightVolumeType, out int probeIndex, out int listType) - { - lightVolumeType = (LightVolumeType)((sortKey >> 9) & 0x3); - probeIndex = (int)(sortKey & 0xFF); - listType = (int)((sortKey >> 8) & 1); - } - - static uint PackProbeKey(float logVolume, LightVolumeType lightVolumeType, uint listType, int probeIndex) - { - // 20 bit volume, 3 bit LightVolumeType, 1 bit list type, 8 bit index - return (uint)logVolume << 12 | (uint)lightVolumeType << 9 | listType << 8 | ((uint)probeIndex & 0xFF); - } - struct BuildGPULightListParameters { // Common - public int totalLightCount; // Regular + Env + Decal + Density Volumes - public int viewCount; + public bool hasDirectionalLights; + public int totalBoundedEntityCount; + public int viewCount; public bool runLightList; public bool clearLightLists; public bool enableFeatureVariants; @@ -2954,7 +3398,6 @@ struct BuildGPULightListParameters public bool computeLightVariants; public bool skyEnabled; public bool probeVolumeEnabled; - public LightList lightList; // Clear Light lists public ComputeShader clearLightListCS; @@ -3072,7 +3515,7 @@ static void ClearLightLists( in BuildGPULightListParameters parameters, // generate screen-space AABBs (used for both fptl and clustered). static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { - if (parameters.totalLightCount != 0) + if (parameters.totalBoundedEntityCount != 0) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs))) { @@ -3085,203 +3528,203 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int groupCount = HDUtils.DivRoundUp(parameters.totalLightCount * threadsPerLight, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(parameters.totalBoundedEntityCount * threadsPerLight, threadsPerGroup); cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); } } } - // enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered). - static void BigTilePrepass(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) - { - if (parameters.runLightList && parameters.runBigTilePrepass) - { - cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vLightList, resources.bigTileLightList); - cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); - cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); - cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); - - ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.bigTilePrepassShader, HDShaderIDs._ShaderVariablesLightList); - - cmd.DispatchCompute(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, parameters.numBigTilesX, parameters.numBigTilesY, parameters.viewCount); - } - } - - static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, ref bool tileFlagsWritten, CommandBuffer cmd) - { - // optimized for opaques only - if (parameters.runLightList && parameters.runFPTL) - { - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); - - cmd.SetComputeTextureParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vLightList, resources.lightList); - if (parameters.runBigTilePrepass) - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBigTileLightList, resources.bigTileLightList); - - var localLightListCB = parameters.lightListCB; - - if (parameters.enableFeatureVariants) - { - uint baseFeatureFlags = 0; - if (parameters.lightList.directionalLights.Count > 0) - { - baseFeatureFlags |= (uint)LightFeatureFlags.Directional; - } - if (parameters.skyEnabled) - { - baseFeatureFlags |= (uint)LightFeatureFlags.Sky; - } - if (!parameters.computeMaterialVariants) - { - baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; - } - - if (parameters.probeVolumeEnabled) - { - // If probe volume feature is enabled, we toggle this feature on for all tiles. - // This is necessary because all tiles must sample ambient probe fallback. - // It is possible we could save a little bit of work by having 2x feature flags for probe volumes: - // one specifiying which tiles contain probe volumes, - // and another triggered for all tiles to handle fallback. - baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; - } - - localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - - cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - tileFlagsWritten = true; - } - - ConstantBuffer.Push(cmd, localLightListCB, parameters.buildPerTileLightListShader, HDShaderIDs._ShaderVariablesLightList); - - cmd.DispatchCompute(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); - } - } - static void VoxelLightListGeneration(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) - { - if (parameters.runLightList) - { - // clear atomic offset index - cmd.SetComputeBufferParam(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); - cmd.DispatchCompute(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, 1, 1, 1); - - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); - cmd.SetComputeTextureParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vLayeredLightList, resources.perVoxelLightLists); - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredOffset, resources.perVoxelOffset); - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); - if (parameters.runBigTilePrepass) - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vBigTileLightList, resources.bigTileLightList); - - if (parameters.clusterNeedsDepth) - { - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_logBaseBuffer, resources.perTileLogBaseTweak); - } - - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); - cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); - - ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.buildPerVoxelLightListShader, HDShaderIDs._ShaderVariablesLightList); - - cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, parameters.numTilesClusterX, parameters.numTilesClusterY, parameters.viewCount); - } - } - - static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, bool tileFlagsWritten, CommandBuffer cmd) - { - if (parameters.enableFeatureVariants) - { - // We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen - bool needModifyingTileFeatures = !tileFlagsWritten || parameters.computeMaterialVariants; - if (needModifyingTileFeatures) - { - int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; - parameters.buildMaterialFlagsShader.shaderKeywords = null; - if (tileFlagsWritten && parameters.computeLightVariants) - { - parameters.buildMaterialFlagsShader.EnableKeyword("USE_OR"); - } - - uint baseFeatureFlags = 0; - if (!parameters.computeLightVariants) - { - baseFeatureFlags |= LightDefinitions.s_LightFeatureMaskFlags; - } - if (parameters.probeVolumeEnabled) - { - // TODO: Verify that we should be globally enabling ProbeVolume feature for all tiles here, or if we should be using per-tile culling. - baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; - } - - // If we haven't run the light list building, we are missing some basic lighting flags. - if (!tileFlagsWritten) - { - if (parameters.lightList.directionalLights.Count > 0) - { - baseFeatureFlags |= (uint)LightFeatureFlags.Directional; - } - if (parameters.skyEnabled) - { - baseFeatureFlags |= (uint)LightFeatureFlags.Sky; - } - if (!parameters.computeMaterialVariants) - { - baseFeatureFlags |= LightDefinitions.s_MaterialFeatureMaskFlags; - } - } - - var localLightListCB = parameters.lightListCB; - localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - - cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - - for (int i = 0; i < resources.gBuffer.Length; ++i) - cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); - - if(resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. - { - cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); - } - else - { - cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); - } - - ConstantBuffer.Push(cmd, localLightListCB, parameters.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList); - - cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); - } - - // clear dispatch indirect buffer - if (parameters.useComputeAsPixel) - { - cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); - cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); - - } - else - { - cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); - } - - // add tiles to indirect buffer - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); - // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel - cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); - } - } + // // enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered). + // static void BigTilePrepass(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + // { + // if (parameters.runLightList && parameters.runBigTilePrepass) + // { + // cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vLightList, resources.bigTileLightList); + // cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); + // cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); + // cmd.SetComputeBufferParam(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); + + // ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.bigTilePrepassShader, HDShaderIDs._ShaderVariablesLightList); + + // cmd.DispatchCompute(parameters.bigTilePrepassShader, parameters.bigTilePrepassKernel, parameters.numBigTilesX, parameters.numBigTilesY, parameters.viewCount); + // } + // } + + // static void BuildPerTileLightList(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, ref bool tileFlagsWritten, CommandBuffer cmd) + // { + // // optimized for opaques only + // if (parameters.runLightList && parameters.runFPTL) + // { + // cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); + // cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); + // cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); + + // cmd.SetComputeTextureParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); + // cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vLightList, resources.lightList); + // if (parameters.runBigTilePrepass) + // cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_vBigTileLightList, resources.bigTileLightList); + + // var localLightListCB = parameters.lightListCB; + + // if (parameters.enableFeatureVariants) + // { + // uint baseFeatureFlags = 0; + // if (parameters.lightList.directionalLights.Count > 0) + // { + // baseFeatureFlags |= (uint)LightFeatureFlags.Directional; + // } + // if (parameters.skyEnabled) + // { + // baseFeatureFlags |= (uint)LightFeatureFlags.Sky; + // } + // if (!parameters.computeMaterialVariants) + // { + // baseFeatureFlags |= TiledLightingConstants.s_MaterialFeatureMaskFlags; + // } + + // if (parameters.probeVolumeEnabled) + // { + // // If probe volume feature is enabled, we toggle this feature on for all tiles. + // // This is necessary because all tiles must sample ambient probe fallback. + // // It is possible we could save a little bit of work by having 2x feature flags for probe volumes: + // // one specifiying which tiles contain probe volumes, + // // and another triggered for all tiles to handle fallback. + // baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; + // } + + // localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; + + // cmd.SetComputeBufferParam(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + // tileFlagsWritten = true; + // } + + // ConstantBuffer.Push(cmd, localLightListCB, parameters.buildPerTileLightListShader, HDShaderIDs._ShaderVariablesLightList); + + // cmd.DispatchCompute(parameters.buildPerTileLightListShader, parameters.buildPerTileLightListKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); + // } + // } + // static void VoxelLightListGeneration(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + // { + // if (parameters.runLightList) + // { + // // clear atomic offset index + // cmd.SetComputeBufferParam(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); + // cmd.DispatchCompute(parameters.clearClusterAtomicIndexShader, s_ClearVoxelAtomicKernel, 1, 1, 1); + + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); + // cmd.SetComputeTextureParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_depth_tex, resources.depthBuffer); + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vLayeredLightList, resources.perVoxelLightLists); + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredOffset, resources.perVoxelOffset); + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, resources.globalLightListAtomic); + // if (parameters.runBigTilePrepass) + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vBigTileLightList, resources.bigTileLightList); + + // if (parameters.clusterNeedsDepth) + // { + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_logBaseBuffer, resources.perTileLogBaseTweak); + // } + + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs._LightVolumeData, resources.lightVolumeDataBuffer); + // cmd.SetComputeBufferParam(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); + + // ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.buildPerVoxelLightListShader, HDShaderIDs._ShaderVariablesLightList); + + // cmd.DispatchCompute(parameters.buildPerVoxelLightListShader, parameters.buildPerVoxelLightListKernel, parameters.numTilesClusterX, parameters.numTilesClusterY, parameters.viewCount); + // } + // } + + // static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, bool tileFlagsWritten, CommandBuffer cmd) + // { + // if (parameters.enableFeatureVariants) + // { + // // We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen + // bool needModifyingTileFeatures = !tileFlagsWritten || parameters.computeMaterialVariants; + // if (needModifyingTileFeatures) + // { + // int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; + // parameters.buildMaterialFlagsShader.shaderKeywords = null; + // if (tileFlagsWritten && parameters.computeLightVariants) + // { + // parameters.buildMaterialFlagsShader.EnableKeyword("USE_OR"); + // } + + // uint baseFeatureFlags = 0; + // if (!parameters.computeLightVariants) + // { + // baseFeatureFlags |= TiledLightingConstants.s_LightFeatureMaskFlags; + // } + // if (parameters.probeVolumeEnabled) + // { + // // TODO: Verify that we should be globally enabling ProbeVolume feature for all tiles here, or if we should be using per-tile culling. + // baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; + // } + + // // If we haven't run the light list building, we are missing some basic lighting flags. + // if (!tileFlagsWritten) + // { + // if (parameters.lightList.directionalLights.Count > 0) + // { + // baseFeatureFlags |= (uint)LightFeatureFlags.Directional; + // } + // if (parameters.skyEnabled) + // { + // baseFeatureFlags |= (uint)LightFeatureFlags.Sky; + // } + // if (!parameters.computeMaterialVariants) + // { + // baseFeatureFlags |= TiledLightingConstants.s_MaterialFeatureMaskFlags; + // } + // } + + // var localLightListCB = parameters.lightListCB; + // localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; + + // cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + + // for (int i = 0; i < resources.gBuffer.Length; ++i) + // cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); + + // if(resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. + // { + // cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); + // } + // else + // { + // cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); + // } + + // ConstantBuffer.Push(cmd, localLightListCB, parameters.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList); + + // cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); + // } + + // // clear dispatch indirect buffer + // if (parameters.useComputeAsPixel) + // { + // cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + // cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); + // cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); + // cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); + + // } + // else + // { + // cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + // cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); + // } + + // // add tiles to indirect buffer + // cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + // cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); + // cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + // cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); + // cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); + // // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel + // cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); + // } + // } static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) { @@ -3290,8 +3733,7 @@ static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera hdCamera, TileAndClusterData tileAndClusterData, - ref ShaderVariablesLightList constantBuffer, - int totalLightCount) + ref ShaderVariablesLightList constantBuffer) { BuildGPULightListParameters parameters = new BuildGPULightListParameters(); @@ -3343,7 +3785,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); - cb.g_iNrVisibLights = totalLightCount; + cb.g_iNrVisibLights = totalBoundedEntityCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; @@ -3361,8 +3803,10 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera // Copy the constant buffer into the parameter struct. parameters.lightListCB = cb; - parameters.totalLightCount = totalLightCount; - parameters.runLightList = parameters.totalLightCount > 0; + parameters.hasDirectionalLights = m_DirectionalLightData.Count != 0; + parameters.totalBoundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); + + parameters.runLightList = parameters.totalBoundedEntityCount != 0; parameters.clearLightLists = false; // TODO RENDERGRAPH: This logic is flawed with Render Graph. @@ -3390,7 +3834,6 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings) && tileAndClusterData.hasTileBuffers; parameters.computeMaterialVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeMaterialVariants); parameters.computeLightVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightVariants); - parameters.lightList = m_lightList; parameters.skyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera); parameters.useComputeAsPixel = DeferredUseComputeAsPixel(hdCamera.frameSettings); parameters.probeVolumeEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && m_ProbeVolumeCount > 0; @@ -3534,11 +3977,11 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) ClearLightLists(parameters, resources, cmd); GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); - BigTilePrepass(parameters, resources, cmd); - BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); - VoxelLightListGeneration(parameters, resources, cmd); + // BigTilePrepass(parameters, resources, cmd); + // BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); + // VoxelLightListGeneration(parameters, resources, cmd); - BuildDispatchIndirectArguments(parameters, resources, tileFlagsWritten, cmd); + // BuildDispatchIndirectArguments(parameters, resources, tileFlagsWritten, cmd); } } @@ -3636,29 +4079,36 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H void PushLightDataGlobalParams(CommandBuffer cmd) { - m_LightLoopLightData.directionalLightData.SetData(m_lightList.directionalLights); - m_LightLoopLightData.lightData.SetData(m_lightList.lights); - m_LightLoopLightData.envLightData.SetData(m_lightList.envLights); - m_LightLoopLightData.decalData.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen)); // don't add more than the size of the buffer - - // These two buffers have been set in Rebuild(). At this point, view 0 contains combined data from all views - m_TileAndClusterData.convexBoundsBuffer.SetData(m_lightList.lightsPerView[0].bounds); - m_TileAndClusterData.lightVolumeDataBuffer.SetData(m_lightList.lightsPerView[0].lightVolumes); - - if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) - { - m_ProbeVolumeClusterData.convexBoundsBuffer.SetData(m_lightList.lightsPerView[0].probeVolumesBounds); - m_ProbeVolumeClusterData.lightVolumeDataBuffer.SetData(m_lightList.lightsPerView[0].probeVolumesLightVolumes); - } + m_DirectionalLightDataBuffer.SetData(m_DirectionalLightData); + m_BoundedEntityCollection.CopyEntityDataToComputeBuffers(); + + // TODO: see if setting these not globally but, rather, per pass, is worth it. + cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightData, m_DirectionalLightDataBuffer); + cmd.SetGlobalBuffer(HDShaderIDs._PunctualLightData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.PunctualLight)); + cmd.SetGlobalBuffer(HDShaderIDs._AreaLightData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.AreaLight)); + cmd.SetGlobalBuffer(HDShaderIDs._EnvLightData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.ReflectionProbe)); + cmd.SetGlobalBuffer(HDShaderIDs._DecalData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.Decal)); + cmd.SetGlobalBuffer(HDShaderIDs._DensityVolumeData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.DensityVolume)); + + cmd.SetGlobalInt( HDShaderIDs._DirectionalLightCount, m_DirectionalLightData.Count); + cmd.SetGlobalInt( HDShaderIDs._PunctualLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight)); + cmd.SetGlobalInt( HDShaderIDs._AreaLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight)); + cmd.SetGlobalInt( HDShaderIDs._EnvLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe)); + cmd.SetGlobalInt( HDShaderIDs._DecalCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal)); + cmd.SetGlobalInt( HDShaderIDs._DensityVolumeCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume)); + + // Hand it over so it can be used to construct light lists. BEC still owns (and manages) the buffer. + m_TileAndClusterData.convexBoundsBuffer = m_BoundedEntityCollection.GetEntityBoundsBuffer(); + + // if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + // { + // m_ProbeVolumeClusterData.convexBoundsBuffer.SetData(m_lightList.lightsPerView[0].probeVolumesBounds); + // m_ProbeVolumeClusterData.lightVolumeDataBuffer.SetData(m_lightList.lightsPerView[0].probeVolumesLightVolumes); + // } cmd.SetGlobalTexture(HDShaderIDs._CookieAtlas, m_TextureCaches.lightCookieManager.atlasTexture); cmd.SetGlobalTexture(HDShaderIDs._EnvCubemapTextures, m_TextureCaches.reflectionProbeCache.GetTexCache()); cmd.SetGlobalTexture(HDShaderIDs._Env2DTextures, m_TextureCaches.reflectionPlanarProbeCache.GetTexCache()); - - cmd.SetGlobalBuffer(HDShaderIDs._LightDatas, m_LightLoopLightData.lightData); - cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, m_LightLoopLightData.envLightData); - cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, m_LightLoopLightData.decalData); - cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); } void PushShadowGlobalParams(CommandBuffer cmd) @@ -3722,7 +4172,7 @@ void GetContactShadowMask(HDAdditionalLightData hdAdditionalLightData, BoolScala // If contact shadows are not enabled or we already reached the manimal number of contact shadows // or this is not rasterization if ((!hdAdditionalLightData.useContactShadow.Value(contactShadowEnabled)) - || m_ContactShadowIndex >= LightDefinitions.s_LightListMaxPrunedEntries + || m_ContactShadowIndex >= TiledLightingConstants.s_LightListMaxPrunedEntries || !isRasterization) return; @@ -3897,7 +4347,7 @@ DeferredLightingParameters PrepareDeferredLightingParameters(HDCamera hdCamera, parameters.useComputeLightingEvaluation = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation); parameters.enableFeatureVariants = GetFeatureVariantsEnabled(hdCamera.frameSettings) && !debugDisplayOrSceneLightOff; parameters.enableShadowMasks = m_EnableBakeShadowMask; - parameters.numVariants = LightDefinitions.s_NumFeatureVariants; + parameters.numVariants = TiledLightingConstants.s_NumFeatureVariants; parameters.debugDisplaySettings = debugDisplaySettings; // Compute Lighting From 51a40204f8972722c10c17ffd9cea6f6dd68e2d7 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 28 Sep 2020 17:39:44 -0700 Subject: [PATCH 025/209] Make things compile --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 220 +++++++++--------- .../ScreenSpaceShadowManager.RenderGraph.cs | 42 ++-- .../Shadow/ScreenSpaceShadowManagerArea.cs | 8 +- .../Runtime/Material/Decal/DecalSystem.cs | 20 +- .../HDRenderPipeline.LightLoop.cs | 19 +- .../HDRenderPipeline.Prepass.cs | 8 +- .../HDRenderPipeline.RenderGraph.cs | 2 +- .../RenderPipeline/HDRenderPipeline.cs | 42 ++-- .../Raytracing/HDRaytracingLightCluster.cs | 13 +- 9 files changed, 187 insertions(+), 187 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index c92a85ca693..370fd2643a7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -59,7 +59,7 @@ internal enum BoundedEntityCategory // Defines the sorting order (takes priority ReflectionProbe, Decal, DensityVolume, - ProbeVolume, // TODO + // ProbeVolume, Count, None = Count // Unbounded } @@ -310,11 +310,12 @@ public void CopyEntityDataToComputeBuffers() static int[] s_EntityDataSizesPerCategory = new int[(int)BoundedEntityCategory.Count] // Can't make it const in C#... { - Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight - Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight - Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe - Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal - Marshal.SizeOf(typeof(DensityVolumeEngineData)) // BoundedEntityCategory.DensityVolume + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight + Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe + Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal + Marshal.SizeOf(typeof(DensityVolumeEngineData)), // BoundedEntityCategory.DensityVolume + // Marshal.SizeOf(typeof(ProbeVolumeEngineData)) // BoundedEntityCategory.ProbeVolume }; // The entity count is the same for all views. @@ -413,27 +414,27 @@ struct FiniteLightBound public float radius; // Bounding sphere (may or may not be tighter than the bounding box) } - // [GenerateHLSL] - // struct LightVolumeData - // { - // public Vector3 lightPos; // Of light's "origin" - // public uint lightVolume; // Type index + [GenerateHLSL] + struct LightVolumeData + { + public Vector3 lightPos; // Of light's "origin" + public uint lightVolume; // Type index - // public Vector3 lightAxisX; // Normalized - // public uint lightCategory; // Category index + public Vector3 lightAxisX; // Normalized + public uint lightCategory; // Category index - // public Vector3 lightAxisY; // Normalized - // public float radiusSq; // Cone and sphere: light range squared + public Vector3 lightAxisY; // Normalized + public float radiusSq; // Cone and sphere: light range squared - // public Vector3 lightAxisZ; // Normalized - // public float cotan; // Cone: cotan of the aperture (half-angle) + public Vector3 lightAxisZ; // Normalized + public float cotan; // Cone: cotan of the aperture (half-angle) - // public Vector3 boxInnerDist; // Box: extents (half-size) of the inner box - // public uint featureFlags; + public Vector3 boxInnerDist; // Box: extents (half-size) of the inner box + public uint featureFlags; - // public Vector3 boxInvRange; // Box: 1 / (OuterBoxExtents - InnerBoxExtents) - // public float unused2; - // }; + public Vector3 boxInvRange; // Box: 1 / (OuterBoxExtents - InnerBoxExtents) + public float unused2; + }; /// /// Tile and Cluster Debug Mode. @@ -533,9 +534,8 @@ internal struct ProcessedLightData { public HDAdditionalLightData additionalLightData; public HDLightType lightType; - public BoundedEntityCategory lightCategory; + public BoundedEntityCategory lightCategory; public GPULightType gpuLightType; - public LightVolumeType lightVolumeType; public float distanceToCamera; public float lightDistanceFade; public bool isBakedShadowMask; @@ -581,7 +581,6 @@ public partial class HDRenderPipeline int m_MaxAreaLightsOnScreen; int m_MaxDecalsOnScreen; int m_MaxDensityVolumesOnScreen = 1024; // TODO - int m_MaxProbeVolumesOnScreen = 1024; // TODO int m_MaxLightsOnScreen; int m_MaxEnvLightsOnScreen; int m_MaxPlanarReflectionOnScreen; @@ -687,7 +686,7 @@ class TileAndClusterData { // Internal to light list building // public ComputeBuffer lightVolumeDataBuffer { get; private set; } - public ComputeBuffer convexBoundsBuffer { get; private set; } + public ComputeBuffer convexBoundsBuffer { get; /*private*/ set; } public ComputeBuffer AABBBoundsBuffer { get; private set; } public ComputeBuffer globalLightListAtomic { get; private set; } @@ -834,7 +833,7 @@ public void Cleanup() // TODO: Remove the internal // internal LightLoopLightData m_LightLoopLightData = new LightLoopLightData(); TileAndClusterData m_TileAndClusterData = new TileAndClusterData(); - TileAndClusterData m_ProbeVolumeClusterData; + // TileAndClusterData m_ProbeVolumeClusterData; // HDRenderPipeline needs to cache m_ProbeVolumeList as a member variable, as it cannot be passed in directly into BuildGPULightListProbeVolumesCommon() async compute // due to the HDGPUAsyncTask API. We could have extended HDGPUAsyncTaskParams definition to contain a ProbeVolumeList, but this seems worse, as all other async compute @@ -892,7 +891,7 @@ static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) Shader deferredTilePixelShader { get { return defaultResources.shaders.deferredTilePS; } } ShaderVariablesLightList m_ShaderVariablesLightListCB = new ShaderVariablesLightList(); - ShaderVariablesLightList m_ShaderVariablesProbeVolumeLightListCB = new ShaderVariablesLightList(); + //ShaderVariablesLightList m_ShaderVariablesProbeVolumeLightListCB = new ShaderVariablesLightList(); enum ClusterPrepassSource : int @@ -1149,11 +1148,11 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) m_DirectionalLightDataBuffer = new ComputeBuffer(m_MaxDirectionalLightsOnScreen, Marshal.SizeOf(typeof(DirectionalLightData))); m_BoundedEntityCollection = new BoundedEntityCollection(xrViewCount, maxBoundedEntityCounts); - if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) - { - m_ProbeVolumeClusterData = new TileAndClusterData(); - m_ProbeVolumeClusterData.Initialize(allocateTileBuffers: false, clusterNeedsDepth: false, maxLightCount: k_MaxVisibleProbeVolumeCount); - } + //if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + //{ + // m_ProbeVolumeClusterData = new TileAndClusterData(); + // m_ProbeVolumeClusterData.Initialize(allocateTileBuffers: false, clusterNeedsDepth: false, maxLightCount: k_MaxVisibleProbeVolumeCount); + //} // OUTPUT_SPLIT_LIGHTING - SHADOWS_SHADOWMASK - DEBUG_DISPLAY m_deferredLightingMaterial = new Material[8]; @@ -1266,8 +1265,8 @@ void CleanupLightLoop() CoreUtils.SafeRelease(m_DirectionalLightDataBuffer); m_BoundedEntityCollection.Release(); - if (m_ProbeVolumeClusterData != null) - m_ProbeVolumeClusterData.Cleanup(); + //if (m_ProbeVolumeClusterData != null) + // m_ProbeVolumeClusterData.Cleanup(); LightLoopReleaseResolutionDependentBuffers(); @@ -1333,22 +1332,22 @@ static int NumLightIndicesPerClusteredTile() void LightLoopAllocResolutionDependentBuffers(HDCamera hdCamera, int width, int height) { m_TileAndClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, m_BoundedEntityCollection.GetMaxEntityCount(), m_EnableRenderGraph); - if (m_ProbeVolumeClusterData != null) - m_ProbeVolumeClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, k_MaxVisibleProbeVolumeCount, m_EnableRenderGraph); + //if (m_ProbeVolumeClusterData != null) + // m_ProbeVolumeClusterData.AllocateResolutionDependentBuffers(hdCamera, width, height, m_MaxViewCount, k_MaxVisibleProbeVolumeCount, m_EnableRenderGraph); } void LightLoopReleaseResolutionDependentBuffers() { m_TileAndClusterData.ReleaseResolutionDependentBuffers(); - if (m_ProbeVolumeClusterData != null) - m_ProbeVolumeClusterData.ReleaseResolutionDependentBuffers(); + //if (m_ProbeVolumeClusterData != null) + // m_ProbeVolumeClusterData.ReleaseResolutionDependentBuffers(); } void LightLoopCleanupNonRenderGraphResources() { m_TileAndClusterData.ReleaseNonRenderGraphResolutionDependentBuffers(); - if (m_ProbeVolumeClusterData != null) - m_ProbeVolumeClusterData.ReleaseNonRenderGraphResolutionDependentBuffers(); + //if (m_ProbeVolumeClusterData != null) + // m_ProbeVolumeClusterData.ReleaseNonRenderGraphResolutionDependentBuffers(); } internal static Matrix4x4 WorldToCamera(Camera camera) @@ -1933,7 +1932,7 @@ internal LightData GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSe } // TODO: we should be able to do this calculation only with LightData without VisibleLight light, but for now pass both - FiniteLightBound GetLightVolumeDataAndBound(BoundedEntityCategory lightCategory, GPULightType gpuLightType, LightVolumeType lightVolumeType, + FiniteLightBound GetLightVolumeDataAndBound(BoundedEntityCategory lightCategory, GPULightType gpuLightType, VisibleLight light, LightData lightData, Vector3 lightDimensions, Matrix4x4 worldToView, int viewIndex) { // Then Culling side @@ -1951,7 +1950,7 @@ FiniteLightBound GetLightVolumeDataAndBound(BoundedEntityCategory lightCategory, var lightVolumeData = new LightVolumeData(); lightVolumeData.lightCategory = (uint)lightCategory; - lightVolumeData.lightVolume = (uint)lightVolumeType; + //lightVolumeData.lightVolume = (uint)lightVolumeType; if (gpuLightType == GPULightType.Spot || gpuLightType == GPULightType.ProjectorPyramid) { @@ -2272,7 +2271,7 @@ FiniteLightBound GetEnvLightVolumeDataAndBound(HDProbe probe, Matrix4x4 worldToV var influencePositionVS = worldToView.MultiplyPoint(influenceToWorld.GetColumn(3)); lightVolumeData.lightCategory = (uint)BoundedEntityCategory.ReflectionProbe; - lightVolumeData.lightVolume = (uint)lightVolumeType; + //lightVolumeData.lightVolume = (uint)lightVolumeType; lightVolumeData.featureFlags = (uint)LightFeatureFlags.Env; switch (probe.influenceVolume.shape) @@ -2323,10 +2322,10 @@ FiniteLightBound GetEnvLightVolumeDataAndBound(HDProbe probe, Matrix4x4 worldToV return bound; } - FiniteLightBound CreateBoxVolumeDataAndBound(OrientedBBox obb, BoundedEntityCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView, float normalBiasDilation) + FiniteLightBound GetBoxVolumeDataAndBound(OrientedBBox obb, BoundedEntityCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView, float normalBiasDilation) { - volumeData = new LightVolumeData(); - bound = new FiniteLightBound(); + var volumeData = new LightVolumeData(); + var bound = new FiniteLightBound(); // Used in Probe Volumes: // Conservatively dilate bounds used for tile / cluster assignment by normal bias. @@ -2343,7 +2342,7 @@ FiniteLightBound CreateBoxVolumeDataAndBound(OrientedBBox obb, BoundedEntityCate var forwardVS = Vector3.Cross(upVS, rightVS); var extents = new Vector3(extentConservativeX, extentConservativeY, extentConservativeZ); - volumeData.lightVolume = (uint)LightVolumeType.Box; + //volumeData.lightVolume = (uint)LightVolumeType.Box; volumeData.lightCategory = (uint)category; volumeData.featureFlags = (uint)featureFlags; @@ -2401,7 +2400,7 @@ internal static void EvaluateGPULightType(HDLightType lightType, SpotLightShape switch (lightType) { case HDLightType.Spot: - lightCategory = BoundedEntityCategory.Punctual; + lightCategory = BoundedEntityCategory.PunctualLight; switch (spotLightShape) { @@ -2514,7 +2513,7 @@ static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewI Matrix4x4 viewMatrix = GetWorldToViewMatrix(hdCamera, viewIndex); // Non-RWS Vector3 positionVS = viewMatrix.MultiplyPoint(positionWS); - return positionVS.z; + return -positionVS.z; // The coordinate system of the view space is right-handed, Z pointing backwards } // 'w' is the linear depth (Z coordinate of the view-space position). @@ -2760,7 +2759,7 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // 2. Go through all lights, convert them to GPU format. // Simultaneously create data for culling - for (int sortIndex = 0; sortIndex < processedLightCount; ++sortIndex) + for (int sortIndex = 0, indexCount = m_DirectionalLightIndices.Count; sortIndex < indexCount; sortIndex++) { int lightIndex = m_DirectionalLightIndices[sortIndex]; @@ -2791,9 +2790,9 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu #endif } - Debug.Assert(gpuLightType == GPULightType.Directional); + Debug.Assert(processedData.gpuLightType == GPULightType.Directional); - DirectionalLightData lightData = GetDirectionalLightData(cmd, hdCamera, light, lightComponent, lightIndex, shadowIndex, directionalLightcount, isPbrSkyActive, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot); + DirectionalLightData lightData = GetDirectionalLightData(cmd, hdCamera, light, lightComponent, lightIndex, shadowIndex, sortIndex, isPbrSkyActive, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot); // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. @@ -2862,10 +2861,10 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu Vector3 lightDimensions = new Vector3(); // X = length or width, Y = height, Z = range (depth) // Punctual, area, projector lights - the rendering side. - LightData lightData = GetLightData(cmd, hdCamera, hdShadowSettings, light, lightComponent, in m_ProcessedLightData[lightIndex], shadowIndex, contactShadowScalableSetting, isRasterization: true, ref lightDimensions, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot, ref lightData); + LightData lightData = GetLightData(cmd, hdCamera, hdShadowSettings, light, lightComponent, in m_ProcessedLightData[lightIndex], shadowIndex, contactShadowScalableSetting, isRasterization: true, ref lightDimensions, ref m_ScreenSpaceShadowIndex, ref m_ScreenSpaceShadowChannelSlot); // Then culling side. Must be call in this order as we pass the created Light data to the function - FiniteLightBound bounds = GetLightVolumeDataAndBound(lightCategory, gpuLightType, lightVolumeType, light, m_lightList.lights[m_lightList.lights.Count - 1], lightDimensions, m_WorldToViewMatrices[viewIndex], viewIndex); + FiniteLightBound bounds = GetLightVolumeDataAndBound(category, gpuLightType, light, lightData, lightDimensions, m_WorldToViewMatrices[viewIndex], viewIndex); // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. @@ -3029,7 +3028,6 @@ void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu { Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; - for (int sortIndex = 0; sortIndex < processedLightCount; ++sortIndex) int xrViewCount = hdCamera.viewCount; for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) @@ -3057,7 +3055,7 @@ void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu if (GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData)) { var worldToView = GetWorldToViewMatrix(hdCamera, viewIndex); - FiniteLightBound bounds = GetEnvLightVolumeDataAndBound(processedProbe.hdProbe, gpuLightType, worldToView, viewIndex); + FiniteLightBound bounds = GetEnvLightVolumeDataAndBound(processedProbe.hdProbe, worldToView, viewIndex); // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. @@ -3211,13 +3209,11 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // Decals. for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) { - for (int i = 0; i < decalDatasCount; i++) int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.Decal); int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal); for (int sortIndex = start; sortIndex < (start + count); ++sortIndex) { - for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) BoundedEntitySortingKeyLayout layout = GeBoundedEntitySortingKeyLayoutLayout(); ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); @@ -3232,8 +3228,6 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu if (viewIndex > 0) { // This is quite suboptimal... - m_lightList.lightsPerView[viewIndex].bounds.Add(DecalSystem.m_Bounds[i]); - m_lightList.lightsPerView[viewIndex].lightVolumes.Add(DecalSystem.m_LightVolumes[i]); Matrix4x4 viewMatrixEye0 = GetWorldToViewMatrix(hdCamera, 0); Matrix4x4 viewMatrixEyeI = GetWorldToViewMatrix(hdCamera, viewIndex); Matrix4x4 viewTransferMatrix = viewMatrixEyeI * viewMatrixEye0.inverse; @@ -3270,7 +3264,7 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // Density volumes are not lights and therefore should not affect light classification. LightFeatureFlags featureFlags = 0; - FiniteLightBound bounds = AddBoxVolumeDataAndBound(densityVolumes.bounds[densityVolumeIndex], BoundedEntityCategory.DensityVolume, featureFlags, worldToViewCR, viewIndex); + FiniteLightBound bounds = GetBoxVolumeDataAndBound(densityVolumes.bounds[densityVolumeIndex], BoundedEntityCategory.DensityVolume, featureFlags, worldToViewCR, viewIndex); m_BoundedEntityCollection.AddEntityData(viewIndex, BoundedEntityCategory.DensityVolume, densityVolumes.density[densityVolumeIndex]); m_BoundedEntityCollection.AddEntityBounds(viewIndex, BoundedEntityCategory.DensityVolume, bounds); @@ -3278,7 +3272,7 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu } // I am not touching probe volumes... - m_ProbeVolumeCount = probeVolumes.bounds != null ? probeVolumes.bounds.Count : 0; + //m_ProbeVolumeCount = probeVolumes.bounds != null ? probeVolumes.bounds.Count : 0; // bool probeVolumeNormalBiasEnabled = false; // if (ShaderConfig.s_ProbeVolumesEvaluationMode != ProbeVolumesEvaluationModes.Disabled) @@ -3302,7 +3296,7 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // // Probe volumes are not lights and therefore should not affect light classification. // LightFeatureFlags featureFlags = 0; // float probeVolumeNormalBiasWS = probeVolumeNormalBiasEnabled ? probeVolumes.data[i].normalBiasWS : 0.0f; - // CreateBoxVolumeDataAndBound(probeVolumes.bounds[i], BoundedEntityCategory.ProbeVolume, featureFlags, worldToViewCR, probeVolumeNormalBiasWS, out LightVolumeData volumeData, out FiniteLightBound bound); + // GetBoxVolumeDataAndBound(probeVolumes.bounds[i], BoundedEntityCategory.ProbeVolume, featureFlags, worldToViewCR, probeVolumeNormalBiasWS, out LightVolumeData volumeData, out FiniteLightBound bound); // if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) // { // // Only probe volume evaluation in the material pass use these custom probe volume specific lists. @@ -3445,7 +3439,7 @@ struct BuildGPULightListResources public RTHandle[] gBuffer; // Internal to light list building - public ComputeBuffer lightVolumeDataBuffer; + //public ComputeBuffer lightVolumeDataBuffer; public ComputeBuffer convexBoundsBuffer; public ComputeBuffer AABBBoundsBuffer; public ComputeBuffer globalLightListAtomic; @@ -3475,7 +3469,7 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.perVoxelOffset = tileAndClusterData.perVoxelOffset; resources.convexBoundsBuffer = tileAndClusterData.convexBoundsBuffer; resources.AABBBoundsBuffer = tileAndClusterData.AABBBoundsBuffer; - resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; + //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; resources.perVoxelLightLists = tileAndClusterData.perVoxelLightLists; @@ -3785,20 +3779,21 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); - cb.g_iNrVisibLights = totalBoundedEntityCount; + cb.g_iNrVisibLights = -1; //m_BoundedEntityCollection.GetTotalEntityCount(); // TODO REMOVE cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; cb.g_BaseFeatureFlags = 0; // Filled for each individual pass. - cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; - cb._EnvLightIndexShift = (uint)m_lightList.lights.Count; - cb._DecalIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count); - cb._DensityVolumeIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount); + /* Will likely nuke these variables. */ + //cb.g_iNumSamplesMSAA = (int)hdCamera.msaaSamples; + //cb._EnvLightIndexShift = (uint)m_lightList.lights.Count; + //cb._DecalIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count); + //cb._DensityVolumeIndexShift = (uint)(m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount); - int probeVolumeIndexShift = (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.LightLoop) - ? (m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_DensityVolumeCount) - : 0; - cb._ProbeVolumeIndexShift = (uint)probeVolumeIndexShift; + //int probeVolumeIndexShift = (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.LightLoop) + // ? (m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount + m_DensityVolumeCount) + // : 0; + //cb._ProbeVolumeIndexShift = (uint)probeVolumeIndexShift; // Copy the constant buffer into the parameter struct. parameters.lightListCB = cb; @@ -3836,7 +3831,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.computeLightVariants = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightVariants); parameters.skyEnabled = m_SkyManager.IsLightingSkyValid(hdCamera); parameters.useComputeAsPixel = DeferredUseComputeAsPixel(hdCamera.frameSettings); - parameters.probeVolumeEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && m_ProbeVolumeCount > 0; + parameters.probeVolumeEnabled = false; // TODO: hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && m_ProbeVolumeCount > 0; bool isProjectionOblique = GeometryUtils.IsProjectionMatrixOblique(m_LightListProjMatrices[0]); @@ -3944,28 +3939,28 @@ void BuildGPULightListProbeVolumesCommon(HDCamera hdCamera, CommandBuffer cmd) if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume)) return; - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildGPULightListProbeVolumes))) - { - var parameters = PrepareBuildGPULightListParameters(hdCamera, m_ProbeVolumeClusterData, ref m_ShaderVariablesProbeVolumeLightListCB, m_ProbeVolumeCount); - var resources = PrepareBuildGPULightListResources( - m_ProbeVolumeClusterData, - m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), - m_SharedRTManager.GetStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), - isGBufferNeeded: false - ); + //using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildGPULightListProbeVolumes))) + //{ + // var parameters = PrepareBuildGPULightListParameters(hdCamera, m_ProbeVolumeClusterData, ref m_ShaderVariablesProbeVolumeLightListCB, m_ProbeVolumeCount); + // var resources = PrepareBuildGPULightListResources( + // m_ProbeVolumeClusterData, + // m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), + // m_SharedRTManager.GetStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), + // isGBufferNeeded: false + // ); - ClearLightLists(parameters, resources, cmd); - GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); - BigTilePrepass(parameters, resources, cmd); - VoxelLightListGeneration(parameters, resources, cmd); - } + // ClearLightLists(parameters, resources, cmd); + // GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); + // BigTilePrepass(parameters, resources, cmd); + // VoxelLightListGeneration(parameters, resources, cmd); + //} } void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildLightList))) { - var parameters = PrepareBuildGPULightListParameters(hdCamera, m_TileAndClusterData, ref m_ShaderVariablesLightListCB, m_TotalLightCount); + var parameters = PrepareBuildGPULightListParameters(hdCamera, m_TileAndClusterData, ref m_ShaderVariablesLightListCB); var resources = PrepareBuildGPULightListResources( m_TileAndClusterData, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), @@ -3973,7 +3968,7 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) isGBufferNeeded: true ); - bool tileFlagsWritten = false; + //bool tileFlagsWritten = false; ClearLightLists(parameters, resources, cmd); GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); @@ -3995,7 +3990,7 @@ void BuildGPULightLists(HDCamera hdCamera, CommandBuffer cmd) PushLightLoopGlobalParams(globalParams, cmd); } - HDAdditionalLightData GetHDAdditionalLightData(Light light) + static HDAdditionalLightData GetHDAdditionalLightData(Light light) { HDAdditionalLightData add = null; @@ -4046,11 +4041,13 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H } // Light info - cb._PunctualLightCount = (uint)m_lightList.punctualLightCount; - cb._AreaLightCount = (uint)m_lightList.areaLightCount; - cb._EnvLightCount = (uint)m_lightList.envLights.Count; - cb._DirectionalLightCount = (uint)m_lightList.directionalLights.Count; - cb._DecalCount = (uint)DecalSystem.m_DecalDatasCount; + cb._DirectionalLightCount = (uint)m_DirectionalLightData.Count; + cb._PunctualLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight); + cb._AreaLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight); + cb._EnvLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe); + cb._DecalCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal); + // cb._DensityVolumeCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume); + HDAdditionalLightData sunLightData = GetHDAdditionalLightData(m_CurrentSunLight); bool sunLightShadow = sunLightData != null && m_CurrentShadowSortedSunLightIndex >= 0; cb._DirectionalShadowIndex = sunLightShadow ? m_CurrentShadowSortedSunLightIndex : -1; @@ -4090,12 +4087,12 @@ void PushLightDataGlobalParams(CommandBuffer cmd) cmd.SetGlobalBuffer(HDShaderIDs._DecalData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.Decal)); cmd.SetGlobalBuffer(HDShaderIDs._DensityVolumeData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.DensityVolume)); - cmd.SetGlobalInt( HDShaderIDs._DirectionalLightCount, m_DirectionalLightData.Count); - cmd.SetGlobalInt( HDShaderIDs._PunctualLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight)); - cmd.SetGlobalInt( HDShaderIDs._AreaLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight)); - cmd.SetGlobalInt( HDShaderIDs._EnvLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe)); - cmd.SetGlobalInt( HDShaderIDs._DecalCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal)); - cmd.SetGlobalInt( HDShaderIDs._DensityVolumeCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume)); + //cmd.SetGlobalInt( HDShaderIDs._DirectionalLightCount, m_DirectionalLightData.Count); + //cmd.SetGlobalInt( HDShaderIDs._PunctualLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight)); + //cmd.SetGlobalInt( HDShaderIDs._AreaLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight)); + //cmd.SetGlobalInt( HDShaderIDs._EnvLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe)); + //cmd.SetGlobalInt( HDShaderIDs._DecalCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal)); + //cmd.SetGlobalInt( HDShaderIDs._DensityVolumeCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume)); // Hand it over so it can be used to construct light lists. BEC still owns (and manages) the buffer. m_TileAndClusterData.convexBoundsBuffer = m_BoundedEntityCollection.GetEntityBoundsBuffer(); @@ -4253,7 +4250,6 @@ ContactShadowsParameters PrepareContactShadowsParameters(HDCamera hdCamera, floa static void RenderContactShadows( in ContactShadowsParameters parameters, RTHandle contactShadowRT, RTHandle depthTexture, - LightLoopLightData lightLoopLightData, ComputeBuffer lightList, CommandBuffer cmd) { @@ -4261,11 +4257,11 @@ static void RenderContactShadows( in ContactShadowsParameters parameters, cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters, parameters.params1); cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters2, parameters.params2); cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters3, parameters.params3); - cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._DirectionalLightDatas, lightLoopLightData.directionalLightData); + //cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._DirectionalLightDatas, lightLoopLightData.directionalLightData); // Send light list to the compute - cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._LightDatas, lightLoopLightData.lightData); - cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs.g_vLightListGlobal, lightList); + //cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._LightDatas, lightLoopLightData.lightData); + //cmd.SetComputeBufferParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs.g_vLightListGlobal, lightList); cmd.SetComputeTextureParam(parameters.contactShadowsCS, parameters.kernel, parameters.depthTextureParameterName, depthTexture); cmd.SetComputeTextureParam(parameters.contactShadowsCS, parameters.kernel, HDShaderIDs._ContactShadowTextureUAV, contactShadowRT); @@ -4279,11 +4275,11 @@ static void RenderContactShadows( in ContactShadowsParameters parameters, cmd.SetRayTracingVectorParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowParamsParameters, parameters.params1); cmd.SetRayTracingVectorParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowParamsParameters2, parameters.params2); - cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs._DirectionalLightDatas, lightLoopLightData.directionalLightData); + //cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs._DirectionalLightDatas, lightLoopLightData.directionalLightData); // Send light list to the compute - cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs._LightDatas, lightLoopLightData.lightData); - cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs.g_vLightListGlobal, lightList); + //cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs._LightDatas, lightLoopLightData.lightData); + //cmd.SetRayTracingBufferParam(parameters.contactShadowsRTS, HDShaderIDs.g_vLightListGlobal, lightList); cmd.SetRayTracingTextureParam(parameters.contactShadowsRTS, HDShaderIDs._DepthTexture, depthTexture); cmd.SetRayTracingTextureParam(parameters.contactShadowsRTS, HDShaderIDs._ContactShadowTextureUAV, contactShadowRT); @@ -4305,7 +4301,7 @@ void RenderContactShadows(HDCamera hdCamera, CommandBuffer cmd) var depthTexture = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? m_SharedRTManager.GetDepthValuesTexture() : m_SharedRTManager.GetDepthTexture(); int firstMipOffsetY = m_SharedRTManager.GetDepthBufferMipChainInfo().mipLevelOffsets[1].y; var parameters = PrepareContactShadowsParameters(hdCamera, firstMipOffsetY); - RenderContactShadows(parameters, m_ContactShadowBuffer, depthTexture, m_LightLoopLightData, m_TileAndClusterData.lightList, cmd); + RenderContactShadows(parameters, m_ContactShadowBuffer, depthTexture, m_TileAndClusterData.lightList, cmd); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs index 88974134784..18ab72826a0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs @@ -90,27 +90,29 @@ bool RenderLightScreenSpaceShadows(RenderGraph renderGraph, HDCamera hdCamera, P // This matches the directional light if (!m_CurrentScreenSpaceShadowData[lightIdx].valid) continue; - // Fetch the light data and additional light data - LightData currentLight = m_lightList.lights[m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex]; - HDAdditionalLightData currentAdditionalLightData = m_CurrentScreenSpaceShadowData[lightIdx].additionalLightData; + // TODO. None of this works with Z-Binning. - // Trigger the right algorithm based on the light type - switch (currentLight.lightType) - { - case GPULightType.Rectangle: - { - RenderAreaScreenSpaceShadow(renderGraph, hdCamera, currentLight, currentAdditionalLightData, m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex, - prepassOutput, depthBuffer, normalBuffer, motionVectorsBuffer, rayCountTexture, screenSpaceShadowArray); - } - break; - case GPULightType.Point: - case GPULightType.Spot: - { - RenderPunctualScreenSpaceShadow(renderGraph, hdCamera, currentLight, currentAdditionalLightData, m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex, - prepassOutput, depthBuffer, normalBuffer, motionVectorsBuffer, rayCountTexture, screenSpaceShadowArray); - } - break; - } + // Fetch the light data and additional light data + //LightData currentLight = m_lightList.lights[m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex]; + //HDAdditionalLightData currentAdditionalLightData = m_CurrentScreenSpaceShadowData[lightIdx].additionalLightData; + + //// Trigger the right algorithm based on the light type + //switch (currentLight.lightType) + //{ + // case GPULightType.Rectangle: + // { + // RenderAreaScreenSpaceShadow(renderGraph, hdCamera, currentLight, currentAdditionalLightData, m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex, + // prepassOutput, depthBuffer, normalBuffer, motionVectorsBuffer, rayCountTexture, screenSpaceShadowArray); + // } + // break; + // case GPULightType.Point: + // case GPULightType.Spot: + // { + // RenderPunctualScreenSpaceShadow(renderGraph, hdCamera, currentLight, currentAdditionalLightData, m_CurrentScreenSpaceShadowData[lightIdx].lightDataIndex, + // prepassOutput, depthBuffer, normalBuffer, motionVectorsBuffer, rayCountTexture, screenSpaceShadowArray); + // } + // break; + //} } return true; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs index 78ff62ca0e8..57c35b377b7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs @@ -70,7 +70,7 @@ RTSAreaRayTraceParameters PrepareRTSAreaRayTraceParameters(HDCamera hdCamera, HD rtsartParams.worldToLocalMatrix = m_WorldToLocalArea.inverse; rtsartParams.historyValidity = EvaluateHistoryValidity(hdCamera); rtsartParams.filterTracedShadow = additionalLightData.filterTracedShadow; - rtsartParams.areaShadowSlot = m_lightList.lights[lightIndex].screenSpaceShadowIndex; + rtsartParams.areaShadowSlot = -1; // m_lightList.lights[lightIndex].screenSpaceShadowIndex; // TODO FIX ME rtsartParams.filterSize = additionalLightData.filterSizeTraced; // Kernels @@ -364,7 +364,7 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera shadowHistoryArray, analyticHistoryArray); ExecuteSSSAreaRayTrace(cmd, sssartParams, sssartResources); - int areaShadowSlot = m_lightList.lights[lightIndex].screenSpaceShadowIndex; + int areaShadowSlot = -1; // m_lightList.lights[lightIndex].screenSpaceShadowIndex; // TODO FIX ME // Write the result texture to the screen space shadow buffer WriteScreenSpaceShadowParameters wsssParams = PrepareWriteScreenSpaceShadowParameters(hdCamera, areaShadowSlot, ScreenSpaceShadowType.Area); WriteScreenSpaceShadowResources wsssResources = PrepareWriteScreenSpaceShadowResources(intermediateBufferRGBA0); @@ -374,7 +374,7 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera if (additionalLightData.filterTracedShadow) { // Do not forget to update the identification of shadow history usage - hdCamera.PropagateShadowHistory(additionalLightData, areaShadowSlot, GPULightType.Rectangle); + // hdCamera.PropagateShadowHistory(additionalLightData, areaShadowSlot, GPULightType.Rectangle); // TODO FIX ME } } @@ -481,7 +481,7 @@ void RenderAreaScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera areaShadow = passData.outputShadowTexture; } - int areaShadowSlot = m_lightList.lights[lightIndex].screenSpaceShadowIndex; + int areaShadowSlot = -1; // m_lightList.lights[lightIndex].screenSpaceShadowIndex; // TOOD FIX ME WriteScreenSpaceShadow(renderGraph, hdCamera, areaShadow, screenSpaceShadowArray, areaShadowSlot, ScreenSpaceShadowType.Area); if (additionalLightData.filterTracedShadow) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs index b5223501c3d..128b5e49a31 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs @@ -280,7 +280,7 @@ public Camera CurrentCamera // clustered draw data static public DecalData[] m_DecalDatas = new DecalData[kDecalBlockSize]; static public FiniteLightBound[] m_Bounds = new FiniteLightBound[kDecalBlockSize]; - static public LightVolumeData[] m_LightVolumes = new LightVolumeData[kDecalBlockSize]; + //static public LightVolumeData[] m_LightVolumes = new LightVolumeData[kDecalBlockSize]; static public TextureScaleBias[] m_DiffuseTextureScaleBias = new TextureScaleBias[kDecalBlockSize]; static public TextureScaleBias[] m_NormalTextureScaleBias = new TextureScaleBias[kDecalBlockSize]; static public TextureScaleBias[] m_MaskTextureScaleBias = new TextureScaleBias[kDecalBlockSize]; @@ -639,14 +639,14 @@ private void GetDecalVolumeDataAndBound(Matrix4x4 decalToWorld, Matrix4x4 worldT // The culling system culls pixels that are further // than a threshold to the box influence extents. // So we use an arbitrary threshold here (k_BoxCullingExtentOffset) - m_LightVolumes[m_DecalDatasCount].lightCategory = (uint)BoundedEntityCategory.Decal; - m_LightVolumes[m_DecalDatasCount].featureFlags = (uint)LightFeatureFlags.Env; // WTF? - m_LightVolumes[m_DecalDatasCount].lightPos = influencePositionVS; - m_LightVolumes[m_DecalDatasCount].lightAxisX = influenceRightVS; - m_LightVolumes[m_DecalDatasCount].lightAxisY = influenceUpVS; - m_LightVolumes[m_DecalDatasCount].lightAxisZ = influenceForwardVS; - m_LightVolumes[m_DecalDatasCount].boxInnerDist = influenceExtents - HDRenderPipeline.k_BoxCullingExtentThreshold; - m_LightVolumes[m_DecalDatasCount].boxInvRange.Set(1.0f / HDRenderPipeline.k_BoxCullingExtentThreshold.x, 1.0f / HDRenderPipeline.k_BoxCullingExtentThreshold.y, 1.0f / HDRenderPipeline.k_BoxCullingExtentThreshold.z); + //m_LightVolumes[m_DecalDatasCount].lightCategory = (uint)BoundedEntityCategory.Decal; + //m_LightVolumes[m_DecalDatasCount].featureFlags = (uint)LightFeatureFlags.Env; // WTF? + //m_LightVolumes[m_DecalDatasCount].lightPos = influencePositionVS; + //m_LightVolumes[m_DecalDatasCount].lightAxisX = influenceRightVS; + //m_LightVolumes[m_DecalDatasCount].lightAxisY = influenceUpVS; + //m_LightVolumes[m_DecalDatasCount].lightAxisZ = influenceForwardVS; + //m_LightVolumes[m_DecalDatasCount].boxInnerDist = influenceExtents - HDRenderPipeline.k_BoxCullingExtentThreshold; + //m_LightVolumes[m_DecalDatasCount].boxInvRange.Set(1.0f / HDRenderPipeline.k_BoxCullingExtentThreshold.x, 1.0f / HDRenderPipeline.k_BoxCullingExtentThreshold.y, 1.0f / HDRenderPipeline.k_BoxCullingExtentThreshold.z); } private void AssignCurrentBatches(ref Matrix4x4[] decalToWorldBatch, ref Matrix4x4[] normalToWorldBatch, ref float[] decalLayerMaskBatch, int batchCount) @@ -1160,7 +1160,7 @@ public void CreateDrawData() int newDecalDatasSize = ((m_DecalsVisibleThisFrame + kDecalBlockSize - 1) / kDecalBlockSize) * kDecalBlockSize; m_DecalDatas = new DecalData[newDecalDatasSize]; m_Bounds = new FiniteLightBound[newDecalDatasSize]; - m_LightVolumes = new LightVolumeData[newDecalDatasSize]; + //m_LightVolumes = new LightVolumeData[newDecalDatasSize]; m_DiffuseTextureScaleBias = new TextureScaleBias[newDecalDatasSize]; m_NormalTextureScaleBias = new TextureScaleBias[newDecalDatasSize]; m_MaskTextureScaleBias = new TextureScaleBias[newDecalDatasSize]; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index d817a086eef..f701764300c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -58,7 +58,7 @@ class BuildGPULightListPassData // Transient buffers that are not used outside of BuildGPULight list so they don't need to go outside the pass. public ComputeBufferHandle globalLightListAtomic; - public ComputeBufferHandle lightVolumeDataBuffer; + //public ComputeBufferHandle lightVolumeDataBuffer; public BuildGPULightListOutput output = new BuildGPULightListOutput(); } @@ -93,7 +93,7 @@ static BuildGPULightListResources PrepareBuildGPULightListResources(RenderGraphC buildLightListResources.gBuffer[i] = data.gBuffer[i]; } - buildLightListResources.lightVolumeDataBuffer = data.lightVolumeDataBuffer; + //buildLightListResources.lightVolumeDataBuffer = data.lightVolumeDataBuffer; buildLightListResources.convexBoundsBuffer = data.convexBoundsBuffer; buildLightListResources.AABBBoundsBuffer = data.AABBBoundsBuffer; buildLightListResources.globalLightListAtomic = data.globalLightListAtomic; @@ -113,7 +113,6 @@ static BuildGPULightListResources PrepareBuildGPULightListResources(RenderGraphC BuildGPULightListOutput BuildGPULightList( RenderGraph renderGraph, HDCamera hdCamera, TileAndClusterData tileAndClusterData, - int totalLightCount, ref ShaderVariablesLightList constantBuffer, TextureHandle depthStencilBuffer, TextureHandle stencilBufferCopy, @@ -123,7 +122,7 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend { builder.EnableAsyncCompute(hdCamera.frameSettings.BuildLightListRunsAsync()); - passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera, tileAndClusterData, ref constantBuffer, totalLightCount); + passData.buildGPULightListParameters = PrepareBuildGPULightListParameters(hdCamera, tileAndClusterData, ref constantBuffer); passData.depthBuffer = builder.ReadTexture(depthStencilBuffer); passData.stencilTexture = builder.ReadTexture(stencilBufferCopy); if (passData.buildGPULightListParameters.computeMaterialVariants && passData.buildGPULightListParameters.enableFeatureVariants) @@ -138,7 +137,7 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend // Those buffer are filled with the CPU outside of the render graph. passData.convexBoundsBuffer = builder.ReadComputeBuffer(renderGraph.ImportComputeBuffer(tileAndClusterData.convexBoundsBuffer)); - passData.lightVolumeDataBuffer = builder.ReadComputeBuffer(renderGraph.ImportComputeBuffer(tileAndClusterData.lightVolumeDataBuffer)); + // passData.lightVolumeDataBuffer = builder.ReadComputeBuffer(renderGraph.ImportComputeBuffer(tileAndClusterData.lightVolumeDataBuffer)); passData.globalLightListAtomic = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(1, sizeof(uint)) { name = "LightListAtomic"}); passData.AABBBoundsBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * 2 * tileAndClusterData.maxLightCount, 4 * sizeof(float)) { name = "AABBBoundBuffer" }); @@ -154,7 +153,7 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend // note that nrTiles include the viewCount in allocation below // Tile buffers passData.output.lightList = builder.WriteComputeBuffer( - renderGraph.CreateComputeBuffer(new ComputeBufferDesc((int)LightCategory.Count * dwordsPerTile * nrTiles, sizeof(uint)) { name = "LightList" })); + renderGraph.CreateComputeBuffer(new ComputeBufferDesc(/*(int)LightCategory.Count*/ 0 * dwordsPerTile * nrTiles, sizeof(uint)) { name = "LightList" })); passData.output.tileList = builder.WriteComputeBuffer( renderGraph.CreateComputeBuffer(new ComputeBufferDesc(TiledLightingConstants.s_NumFeatureVariants * nrTiles, sizeof(uint)) { name = "TileList" })); passData.output.tileFeatureFlags = builder.WriteComputeBuffer( @@ -183,7 +182,7 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend var nrClusterTiles = nrClustersX * nrClustersY * m_MaxViewCount; passData.output.perVoxelOffset = builder.WriteComputeBuffer( - renderGraph.CreateComputeBuffer(new ComputeBufferDesc((int)LightCategory.Count * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint)) { name = "PerVoxelOffset" })); + renderGraph.CreateComputeBuffer(new ComputeBufferDesc(/*(int)LightCategory.Count*/ 0 * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint)) { name = "PerVoxelOffset" })); passData.output.perVoxelLightLists = builder.WriteComputeBuffer( renderGraph.CreateComputeBuffer(new ComputeBufferDesc(NumLightIndicesPerClusteredTile() * nrClusterTiles, sizeof(uint)) { name = "PerVoxelLightList" })); if (tileAndClusterData.clusterNeedsDepth) @@ -195,13 +194,13 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend builder.SetRenderFunc( (BuildGPULightListPassData data, RenderGraphContext context) => { - bool tileFlagsWritten = false; - var buildLightListResources = PrepareBuildGPULightListResources(context, data); + //bool tileFlagsWritten = false; + ClearLightLists(data.buildGPULightListParameters, buildLightListResources, context.cmd); // GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); - BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd); + //BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd); // BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd); // VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 3de5a4b0e3e..6aba373a526 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -213,10 +213,10 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, // The probe volume light lists do not depend on any of the framebuffer RTs being cleared - do they depend on anything in PushGlobalParams()? // Do they depend on hdCamera.xr.StartSinglePass()? BuildGPULightListOutput probeVolumeListOutput = new BuildGPULightListOutput(); - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) - { - probeVolumeListOutput = BuildGPULightList(m_RenderGraph, hdCamera, m_ProbeVolumeClusterData, m_ProbeVolumeCount, ref m_ShaderVariablesProbeVolumeLightListCB, result.depthBuffer, result.stencilBuffer, result.gbuffer); - } + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + //{ + // probeVolumeListOutput = BuildGPULightList(m_RenderGraph, hdCamera, m_ProbeVolumeClusterData, m_ProbeVolumeCount, ref m_ShaderVariablesProbeVolumeLightListCB, result.depthBuffer, result.stencilBuffer, result.gbuffer); + //} bool shouldRenderMotionVectorAfterGBuffer = RenderDepthPrepass(renderGraph, cullingResults, hdCamera, ref result, out var decalBuffer); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index c33b4c03a48..687d4e69afd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -88,7 +88,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, } else { - gpuLightListOutput = BuildGPULightList(m_RenderGraph, hdCamera, m_TileAndClusterData, m_TotalLightCount, ref m_ShaderVariablesLightListCB, prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.gbuffer); + gpuLightListOutput = BuildGPULightList(m_RenderGraph, hdCamera, m_TileAndClusterData, ref m_ShaderVariablesLightListCB, prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.gbuffer); lightingBuffers.ambientOcclusionBuffer = m_AmbientOcclusionSystem.Render(m_RenderGraph, hdCamera, prepassOutput.depthPyramidTexture, prepassOutput.normalBuffer, prepassOutput.motionVectorsBuffer, m_FrameCount, m_DepthBufferMipChainInfo, m_ShaderVariablesRayTracingCB, rayCountTexture); // Should probably be inside the AO render function but since it's a separate class it's currently not super clean to do. diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index e3e972fb1cd..d7bec6ca4b1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -2527,27 +2527,27 @@ void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) // When evaluating probe volumes in material pass, we build a custom probe volume light list. // When evaluating probe volumes in light loop, probe volumes are folded into the standard light loop data. - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) - { - if (hdCamera.frameSettings.BuildLightListRunsAsync()) - { - buildProbeVolumeLightListTask.EndWithPostWork(cmd, hdCamera, Callback); - - void Callback(CommandBuffer c, HDCamera cam) - { - var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); - var globalParams = hdrp.PrepareLightLoopGlobalParameters(cam, m_ProbeVolumeClusterData); - PushProbeVolumeLightListGlobalParams(globalParams, c); - } - } - else - { - BuildGPULightListProbeVolumesCommon(hdCamera, cmd); - var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); - var globalParams = hdrp.PrepareLightLoopGlobalParameters(hdCamera, m_ProbeVolumeClusterData); - PushProbeVolumeLightListGlobalParams(globalParams, cmd); - } - } + //if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass) + //{ + // if (hdCamera.frameSettings.BuildLightListRunsAsync()) + // { + // buildProbeVolumeLightListTask.EndWithPostWork(cmd, hdCamera, Callback); + + // void Callback(CommandBuffer c, HDCamera cam) + // { + // var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); + // var globalParams = hdrp.PrepareLightLoopGlobalParameters(cam, m_ProbeVolumeClusterData); + // PushProbeVolumeLightListGlobalParams(globalParams, c); + // } + // } + // else + // { + // BuildGPULightListProbeVolumesCommon(hdCamera, cmd); + // var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); + // var globalParams = hdrp.PrepareLightLoopGlobalParameters(hdCamera, m_ProbeVolumeClusterData); + // PushProbeVolumeLightListGlobalParams(globalParams, cmd); + // } + //} RenderGBuffer(cullingResults, hdCamera, renderContext, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs index 75c52d156e0..a180a954ca9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs @@ -511,7 +511,6 @@ void BuildLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights ray processedData.lightType = additionalLightData.type; processedData.lightCategory = lightCategory; processedData.gpuLightType = gpuLightType; - processedData.lightVolumeType = lightVolumeType; // Both of these positions are non-camera-relative. processedData.distanceToCamera = (additionalLightData.gameObject.transform.position - hdCamera.camera.transform.position).magnitude; processedData.lightDistanceFade = HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.fadeDistance); @@ -537,13 +536,17 @@ void BuildLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights ray Vector3 lightDimensions = new Vector3(0.0f, 0.0f, 0.0f); // Use the shared code to build the light data - m_RenderPipeline.GetLightData(cmd, hdCamera, hdShadowSettings, visibleLight, lightComponent, in processedData, - shadowIndex, contactShadowScalableSetting, isRasterization: false, ref lightDimensions, ref screenSpaceShadowIndex, ref screenSpaceChannelSlot, ref lightData); + lightData = m_RenderPipeline.GetLightData(cmd, hdCamera, hdShadowSettings, visibleLight, lightComponent, in processedData, + shadowIndex, contactShadowScalableSetting, isRasterization: false, ref lightDimensions, ref screenSpaceShadowIndex, ref screenSpaceChannelSlot); // We make the light position camera-relative as late as possible in order // to allow the preceding code to work with the absolute world space coordinates. - Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; - HDRenderPipeline.UpdateLightCameraRelativetData(ref lightData, camPosWS); + if (ShaderConfig.s_CameraRelativeRendering != 0) + { + Vector3 camPosWS = hdCamera.mainViewConstants.worldSpaceCameraPos; + // Caution: 'LightData.positionWS' is camera-relative after this point. + lightData.positionRWS -= camPosWS; + } // Set the data for this light m_LightDataCPUArray.Add(lightData); From 9b0f90f0c724caf27ce34dbf250a34e215f7d22e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 28 Sep 2020 19:47:14 -0700 Subject: [PATCH 026/209] Update the naming convention --- .../Lighting/LightLoop/LightCullUtils.hlsl | 6 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 61 +++--- .../Lighting/LightLoop/LightLoop.cs.hlsl | 20 +- .../LightLoop/lightlistbuild-bigtile.compute | 18 +- .../lightlistbuild-clustered.compute | 26 +-- .../Lighting/LightLoop/lightlistbuild.compute | 16 +- .../Lighting/LightLoop/scrbound.compute | 177 +++++++++--------- .../HDRenderPipeline.LightLoop.cs | 2 +- 8 files changed, 168 insertions(+), 158 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl index 4a2a69df125..5a9994e6e7d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl @@ -1,7 +1,7 @@ #ifndef __LIGHTCULLUTILS_H__ #define __LIGHTCULLUTILS_H__ -// Used to index into our SFiniteLightBound (g_data) and +// Used to index into our FiniteLightBound (g_data) and // LightVolumeData (_LightVolumeData) buffers. uint GenerateLightCullDataIndex(uint lightIndex, uint numVisibleLights, uint eyeIndex) { @@ -23,8 +23,8 @@ struct ScreenSpaceBoundsIndices // Usually named g_vBoundsBuffer. The two values represent the min/max indices. ScreenSpaceBoundsIndices GenerateScreenSpaceBoundsIndices(uint lightIndex, uint numVisibleLights, uint eyeIndex) { - // In the monoscopic mode, there is one set of bounds (min,max -> 2 * g_iNrVisibLights) - // In stereo, there are two sets of bounds (leftMin, leftMax, rightMin, rightMax -> 4 * g_iNrVisibLights) + // In the monoscopic mode, there is one set of bounds (min,max -> 2 * _BoundedEntityCount) + // In stereo, there are two sets of bounds (leftMin, leftMax, rightMin, rightMax -> 4 * _BoundedEntityCount) const uint eyeRelativeBase = eyeIndex * 2 * numVisibleLights; ScreenSpaceBoundsIndices indices; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 370fd2643a7..2f1429ef79d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -516,7 +516,7 @@ unsafe struct ShaderVariablesLightList public Vector4 g_screenSize; public Vector2Int g_viDimensions; - public int g_iNrVisibLights; + public int _BoundedEntityCount; public uint g_isOrthographic; public uint g_BaseFeatureFlags; @@ -3383,7 +3383,7 @@ struct BuildGPULightListParameters { // Common public bool hasDirectionalLights; - public int totalBoundedEntityCount; + public int boundedEntityCount; public int viewCount; public bool runLightList; public bool clearLightLists; @@ -3480,36 +3480,40 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData return resources; } - static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuffer cmd, ComputeBuffer bufferToClear) - { - cmd.SetComputeBufferParam(parameters.clearLightListCS, parameters.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear); - cmd.SetComputeIntParam(parameters.clearLightListCS, HDShaderIDs._LightListEntries, bufferToClear.count); + //static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuffer cmd, ComputeBuffer bufferToClear) + //{ + // cmd.SetComputeBufferParam(parameters.clearLightListCS, parameters.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear); + // cmd.SetComputeIntParam(parameters.clearLightListCS, HDShaderIDs._LightListEntries, bufferToClear.count); - int groupSize = 64; - cmd.DispatchCompute(parameters.clearLightListCS, parameters.clearLightListKernel, (bufferToClear.count + groupSize - 1) / groupSize, 1, 1); - } + // int groupSize = 64; + // cmd.DispatchCompute(parameters.clearLightListCS, parameters.clearLightListKernel, (bufferToClear.count + groupSize - 1) / groupSize, 1, 1); + //} static void ClearLightLists( in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { - if (parameters.clearLightLists) - { - // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust - // to changes to the inner workings of the lists. - // Also, we clear all the lists and to be resilient to changes in pipeline. - if (parameters.runBigTilePrepass) - ClearLightList(parameters, cmd, resources.bigTileLightList); - if (resources.lightList != null) // This can happen for probe volume light list build where we only generate clusters. - ClearLightList(parameters, cmd, resources.lightList); - ClearLightList(parameters, cmd, resources.perVoxelOffset); - } + // We should not have to clear anything. That consumes GPU time and creates GPU bubbles. + // We should, however, discard the contents of the resource. For more information, see + // https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#5.7%20Resource%20Discard + + //if (parameters.clearLightLists) + //{ + // // Note we clear the whole content and not just the header since it is fast enough, happens only in one frame and is a bit more robust + // // to changes to the inner workings of the lists. + // // Also, we clear all the lists and to be resilient to changes in pipeline. + // if (parameters.runBigTilePrepass) + // ClearLightList(parameters, cmd, resources.bigTileLightList); + // if (resources.lightList != null) // This can happen for probe volume light list build where we only generate clusters. + // ClearLightList(parameters, cmd, resources.lightList); + // ClearLightList(parameters, cmd, resources.perVoxelOffset); + //} } // generate screen-space AABBs (used for both fptl and clustered). static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { - if (parameters.totalBoundedEntityCount != 0) + if (parameters.boundedEntityCount > 0) // Do not perform a dispatch with 0 groups { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs))) { @@ -3522,7 +3526,7 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int groupCount = HDUtils.DivRoundUp(parameters.totalBoundedEntityCount * threadsPerLight, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount * threadsPerLight, threadsPerGroup); cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); } @@ -3779,7 +3783,9 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); - cb.g_iNrVisibLights = -1; //m_BoundedEntityCollection.GetTotalEntityCount(); // TODO REMOVE + int boundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); + + cb._BoundedEntityCount = boundedEntityCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; @@ -3798,10 +3804,10 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera // Copy the constant buffer into the parameter struct. parameters.lightListCB = cb; - parameters.hasDirectionalLights = m_DirectionalLightData.Count != 0; - parameters.totalBoundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); + parameters.hasDirectionalLights = m_DirectionalLightData.Count != 0; + parameters.boundedEntityCount = boundedEntityCount; - parameters.runLightList = parameters.totalBoundedEntityCount != 0; + parameters.runLightList = boundedEntityCount != 0; parameters.clearLightLists = false; // TODO RENDERGRAPH: This logic is flawed with Render Graph. @@ -3810,6 +3816,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera // because for now buffers are pooled based on their parameters. When we do proper aliasing though, we might end up with any random chunk of memory. // Always build the light list in XR mode to avoid issues with multi-pass + // TODO: ????????????????? if (hdCamera.xr.enabled) { parameters.runLightList = true; @@ -3970,6 +3977,8 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) //bool tileFlagsWritten = false; + // The algorithm (below) works even if the bounded entity count is 0. + // That is fairly efficient, and allows us to avoid weird special cases. ClearLightLists(parameters, resources, cmd); GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); // BigTilePrepass(parameters, resources, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 4c4eeacfcfc..0fe935b2e83 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -66,9 +66,9 @@ #define CLUSTERDEBUGMODE_VISUALIZE_OPAQUE (0) #define CLUSTERDEBUGMODE_VISUALIZE_SLICE (1) -// Generated from UnityEngine.Rendering.HighDefinition.SFiniteLightBound +// Generated from UnityEngine.Rendering.HighDefinition.FiniteLightBound // PackingRules = Exact -struct SFiniteLightBound +struct FiniteLightBound { float3 boxAxisX; float3 boxAxisY; @@ -105,7 +105,7 @@ CBUFFER_START(ShaderVariablesLightList) float4x4 g_mProjectionArr[2]; float4 g_screenSize; int2 g_viDimensions; - int g_iNrVisibLights; + int _BoundedEntityCount; uint g_isOrthographic; uint g_BaseFeatureFlags; int g_iNumSamplesMSAA; @@ -118,29 +118,29 @@ CBUFFER_START(ShaderVariablesLightList) CBUFFER_END // -// Accessors for UnityEngine.Rendering.HighDefinition.SFiniteLightBound +// Accessors for UnityEngine.Rendering.HighDefinition.FiniteLightBound // -float3 GetBoxAxisX(SFiniteLightBound value) +float3 GetBoxAxisX(FiniteLightBound value) { return value.boxAxisX; } -float3 GetBoxAxisY(SFiniteLightBound value) +float3 GetBoxAxisY(FiniteLightBound value) { return value.boxAxisY; } -float3 GetBoxAxisZ(SFiniteLightBound value) +float3 GetBoxAxisZ(FiniteLightBound value) { return value.boxAxisZ; } -float3 GetCenter(SFiniteLightBound value) +float3 GetCenter(FiniteLightBound value) { return value.center; } -float GetScaleXY(SFiniteLightBound value) +float GetScaleXY(FiniteLightBound value) { return value.scaleXY; } -float GetRadius(SFiniteLightBound value) +float GetRadius(FiniteLightBound value) { return value.radius; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute index aa9b402db5d..41b471c1851 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute @@ -20,7 +20,7 @@ StructuredBuffer g_vBoundsBuffer : register( t1 ); StructuredBuffer _LightVolumeData : register(t2); -StructuredBuffer g_data : register( t3 ); +StructuredBuffer g_data : register( t3 ); #ifdef PLATFORM_LANE_COUNT // We can infer the size of a wave. This is currently not possible on non-consoles, so we have to fallback to a sensible default in those cases. @@ -128,9 +128,9 @@ void BigTileLightListGen(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_Gro float2 vTileUR = float2(viTilUR.x/(float) iWidth, viTilUR.y/(float) iHeight); // build coarse list using AABB - for(int l=(int) t; l<(int) g_iNrVisibLights; l += NR_THREADS) + for(int l=(int) t; l<(int) _BoundedEntityCount; l += NR_THREADS) { - const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, g_iNrVisibLights, eyeIndex); + const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, _BoundedEntityCount, eyeIndex); const float2 vMi = g_vBoundsBuffer[boundsIndices.min].xy; const float2 vMa = g_vBoundsBuffer[boundsIndices.max].xy; @@ -165,7 +165,7 @@ void BigTileLightListGen(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_Gro if(t==0) lightOffs = 0; GroupMemoryBarrierWithGroupSync(); int i; - for(i=t; i g_vBoundsBuffer : register( t1 ); StructuredBuffer _LightVolumeData : register(t2); -StructuredBuffer g_data : register( t3 ); +StructuredBuffer g_data : register( t3 ); #ifdef USE_TWO_PASS_TILED_LIGHTING StructuredBuffer g_vBigTileLightList : register( t4 ); // don't support Buffer yet in unity @@ -47,7 +47,7 @@ StructuredBuffer g_vBigTileLightList : register( t4 ); // don't sup #ifdef PLATFORM_LANE_COUNT // We can infer the size of a wave. This is currently not possible on non-consoles, so we have to fallback to a sensible default in those cases. -#define NR_THREADS PLATFORM_LANE_COUNT +#define NR_THREADS PLATFORM_LANE_COUNT #else #define NR_THREADS 64 // default to 64 threads per group on other platforms.. #endif @@ -284,10 +284,10 @@ void LIGHTLISTGEN(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) { int l = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*bigTileIdx+l0+1]; #else - for(int l=(int) t; l<(int) g_iNrVisibLights; l += NR_THREADS) + for(int l=(int) t; l<(int) _BoundedEntityCount; l += NR_THREADS) { #endif - const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, g_iNrVisibLights, eyeIndex); + const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, _BoundedEntityCount, eyeIndex); const float2 vMi = g_vBoundsBuffer[boundsIndices.min].xy; const float2 vMa = g_vBoundsBuffer[boundsIndices.max].xy; @@ -333,8 +333,8 @@ void LIGHTLISTGEN(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) for(int l=(int) t; l<((iNrCoarseLights+1)>>1); l += NR_THREADS) { const int l0 = coarseList[2*l+0], l1 = coarseList[min(2*l+1,iNrCoarseLights-1)]; - const ScreenSpaceBoundsIndices l0Bounds = GenerateScreenSpaceBoundsIndices(l0, g_iNrVisibLights, eyeIndex); - const ScreenSpaceBoundsIndices l1Bounds = GenerateScreenSpaceBoundsIndices(l1, g_iNrVisibLights, eyeIndex); + const ScreenSpaceBoundsIndices l0Bounds = GenerateScreenSpaceBoundsIndices(l0, _BoundedEntityCount, eyeIndex); + const ScreenSpaceBoundsIndices l1Bounds = GenerateScreenSpaceBoundsIndices(l1, _BoundedEntityCount, eyeIndex); const unsigned int clustIdxMi0 = (const unsigned int)min(255, SnapToClusterIdx(g_vBoundsBuffer[l0Bounds.min].w, suggestedBase)); const unsigned int clustIdxMa0 = (const unsigned int)min(255, SnapToClusterIdx(g_vBoundsBuffer[l0Bounds.max].w, suggestedBase)); @@ -400,7 +400,7 @@ void LIGHTLISTGEN(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) { if(offs<(start+iSpaceAvail) && i PLATFORM_LANE_COUNT GroupMemoryBarrierWithGroupSync(); #endif - const int lightCullIndex = GenerateLightCullDataIndex(coarseList[l], g_iNrVisibLights, eyeIndex); + const int lightCullIndex = GenerateLightCullDataIndex(coarseList[l], _BoundedEntityCount, eyeIndex); UNITY_BRANCH if (_LightVolumeData[lightCullIndex].lightVolume != LIGHTVOLUMETYPE_SPHERE) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes. { - SFiniteLightBound lgtDat = g_data[lightCullIndex]; + FiniteLightBound lgtDat = g_data[lightCullIndex]; const float3 boxX = lgtDat.boxAxisX.xyz; const float3 boxY = lgtDat.boxAxisY.xyz; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute index 49a88c59d47..85c598b9163 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute @@ -31,7 +31,7 @@ StructuredBuffer g_vBoundsBuffer : register( t1 ); StructuredBuffer _LightVolumeData : register(t2); -StructuredBuffer g_data : register( t3 ); +StructuredBuffer g_data : register( t3 ); #ifdef USE_TWO_PASS_TILED_LIGHTING StructuredBuffer g_vBigTileLightList : register( t4 ); // don't support Buffer yet in unity @@ -42,7 +42,7 @@ StructuredBuffer g_vBigTileLightList : register( t4 ); // don't sup #endif #ifdef PLATFORM_LANE_COUNT // We can infer the size of a wave. This is currently not possible on non-consoles, so we have to fallback to a sensible default in those cases. -#define NR_THREADS PLATFORM_LANE_COUNT +#define NR_THREADS PLATFORM_LANE_COUNT #else #define NR_THREADS 64 // default to 64 threads per group on other platforms.. #endif @@ -220,13 +220,13 @@ void TileLightListGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadI { int l = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE*bigTileIdx+l0+1]; #else - for(int l=(int) t; l<(int) g_iNrVisibLights; l += NR_THREADS) + for(int l=(int) t; l<(int) _BoundedEntityCount; l += NR_THREADS) { #endif // Skip density volumes (lights are sorted by category). TODO: improve data locality if (_LightVolumeData[l].lightCategory == LIGHTCATEGORY_DENSITY_VOLUME) { break; } - const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, g_iNrVisibLights, unity_StereoEyeIndex); + const ScreenSpaceBoundsIndices boundsIndices = GenerateScreenSpaceBoundsIndices(l, _BoundedEntityCount, unity_StereoEyeIndex); const float3 vMi = g_vBoundsBuffer[boundsIndices.min].xyz; const float3 vMa = g_vBoundsBuffer[boundsIndices.max].xyz; @@ -279,7 +279,7 @@ void TileLightListGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadI int nrLightsCombinedList = min(ldsNrLightsFinal,LIGHT_LIST_MAX_COARSE_ENTRIES); for(int i=t; i g_data : register(t0); +StructuredBuffer g_data : register(t0); /* ------------------------------ Outputs ----------------------------------- */ @@ -111,16 +111,16 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) // Clipping a plane by a cube may produce a hexagon (6-gon). // Clipping a hexagon by 4 planes may produce a decagon (10-gon). -#define MAX_CLIP_VERTS (10) -#define NUM_VERTS (8) -#define NUM_FACES (6) -#define NUM_PLANES (6) -#define THREADS_PER_GROUP (64) -#define THREADS_PER_LIGHT (4) // Set to 1 for debugging -#define LIGHTS_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_LIGHT) -#define VERTS_PER_GROUP (NUM_VERTS * LIGHTS_PER_GROUP) -#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_LIGHT) -#define FACES_PER_THREAD DIV_ROUND_UP(NUM_FACES, THREADS_PER_LIGHT) +#define MAX_CLIP_VERTS (10) +#define NUM_VERTS (8) +#define NUM_FACES (6) +#define NUM_PLANES (6) +#define THREADS_PER_GROUP (64) +#define THREADS_PER_ENTITY (4) // Set to 1 for debugging +#define ENTITIES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_ENTITY) +#define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) +#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) +#define FACES_PER_THREAD DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY) // All planes and faces are always in the standard order (see below). // Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. @@ -188,20 +188,20 @@ groupshared float gs_HapVertsW[VERTS_PER_GROUP]; groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS -// 1 array * 16 elements * 4 bytes each = 64 bytes. -groupshared uint gs_CullClipFaceMasks[LIGHTS_PER_GROUP]; // 6 faces each (HLSL does not support small data types) +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_CullClipFaceMasks[ENTITIES_PER_GROUP]; // 6 faces each (HLSL does not support small data types) // 8 arrays * 16 elements * 4 bytes each = 512 bytes. // These are actually floats reinterpreted as uints. // The reason is because floating-point atomic operations are not supported. -groupshared uint gs_NdcAaBbMinPtX[LIGHTS_PER_GROUP]; -groupshared uint gs_NdcAaBbMaxPtX[LIGHTS_PER_GROUP]; -groupshared uint gs_NdcAaBbMinPtY[LIGHTS_PER_GROUP]; -groupshared uint gs_NdcAaBbMaxPtY[LIGHTS_PER_GROUP]; -groupshared uint gs_NdcAaBbMinPtZ[LIGHTS_PER_GROUP]; // Note that min-max Z cannot be trivially reconstructed -groupshared uint gs_NdcAaBbMaxPtZ[LIGHTS_PER_GROUP]; // from min-max W if the projection is oblique. -groupshared uint gs_NdcAaBbMinPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate -groupshared uint gs_NdcAaBbMaxPtW[LIGHTS_PER_GROUP]; // View-space Z coordinate +groupshared uint gs_NdcAaBbMinPtX[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMaxPtX[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMinPtY[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMaxPtY[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMinPtZ[ENTITIES_PER_GROUP]; // Note that min-max Z cannot be trivially reconstructed +groupshared uint gs_NdcAaBbMaxPtZ[ENTITIES_PER_GROUP]; // from min-max W if the projection is oblique. +groupshared uint gs_NdcAaBbMinPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate +groupshared uint gs_NdcAaBbMaxPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS // Returns 'true' if it manages to cull the face. @@ -385,24 +385,24 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT } //********************************************************************************************** -// The goal of this program is to compute the AABB of the light in the NDC space ([0, 1] range). -// The light is represented by a convex volume (a cuboid) with 6 faces (planar quads) and 8 vertices. +// The goal of this program is to compute the AABB of the entity in the NDC space ([0, 1] range). +// The entity is represented by a convex volume (a frustum) with 6 faces (planar quads) and 8 vertices. // -// Since a light volume may be partially off-screen, we must clip it before computing the AABB. -// Clipping the resulting AABB (rather than the light volume itself) may result in a loose AABB. +// Since an entity's bounding volume may be partially off-screen, we must clip it before computing the AABB. +// Clipping the resulting AABB (rather than the bounding volume) may result in a loose AABB. // // To avoid having to deal with the "Moebius twist" property of the perspective transform, // we perform clipping using the homogeneous (projective) post-perspective coordinates. // This clipping method in described in Blinn's paper titled "Line Clipping". // -// The algorithm processes a light on 4 threads. While all 6 faces may require clipping in the +// The algorithm processes an entity on 4 threads. While all 6 faces may require clipping in the // worst case, clipping more than 4 faces is very uncommon (typically, we clip 0, 3 or 4). // Some faces may require culling rather than clipping (the former is simpler). // // It's important to realize that face culling may end up culling 5 (or even all 6) faces. -// This means that the clipped light volume may be reduced to a single polygon, or nothing at all. -// (Imagine a view volume completely or partially inside a light volume). -// Therefore, we must perform view-volume-corner-inside-light-volume tests. +// This means that the clipped volume may be reduced to a single polygon, or nothing at all. +// (Imagine a view volume completely or partially inside a bounding volume). +// Therefore, we must perform view-volume-corner-inside-bounding-volume tests. // // // Notation: @@ -419,12 +419,13 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint g = groupID.x; const uint eyeIndex = groupID.y; // Currently, can only be 0 or 1 - const uint intraGroupLightIndex = t / THREADS_PER_LIGHT; - const uint globalLightIndex = g * LIGHTS_PER_GROUP + intraGroupLightIndex; - const uint baseVertexOffset = intraGroupLightIndex * NUM_VERTS; + const uint intraGroupEntityIndex = t / THREADS_PER_ENTITY; + const uint globalEntityIndex = g * ENTITIES_PER_GROUP + intraGroupEntityIndex; + const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; - const uint eyeAdjustedInputOffset = GenerateLightCullDataIndex(globalLightIndex, g_iNrVisibLights, eyeIndex); - const SFiniteLightBound cullData = g_data[eyeAdjustedInputOffset]; + // The function call below will not generate an out-of-bounds index. + const uint eyeAdjustedInputOffset = GenerateLightCullDataIndex(globalEntityIndex, _BoundedEntityCount, eyeIndex); + const FiniteLightBound cullData = g_data[eyeAdjustedInputOffset]; const float4x4 projMat = g_mProjectionArr[eyeIndex]; const float4x4 invProjMat = g_mInvProjectionArr[eyeIndex]; @@ -437,17 +438,17 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // (0) Initialize the TGSM. - if (t % THREADS_PER_LIGHT == 0) // Avoid bank conflicts + if (t % THREADS_PER_ENTITY == 0) // Avoid bank conflicts { - gs_CullClipFaceMasks[intraGroupLightIndex] = 0; // Initially inside - gs_NdcAaBbMinPtX[intraGroupLightIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtX[intraGroupLightIndex] = asuint(0.0f); - gs_NdcAaBbMinPtY[intraGroupLightIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtY[intraGroupLightIndex] = asuint(0.0f); - gs_NdcAaBbMinPtZ[intraGroupLightIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtZ[intraGroupLightIndex] = asuint(0.0f); - gs_NdcAaBbMinPtW[intraGroupLightIndex] = asuint(FLT_INF); - gs_NdcAaBbMaxPtW[intraGroupLightIndex] = asuint(0.0f); + gs_CullClipFaceMasks[intraGroupEntityIndex] = 0; // Initially inside + gs_NdcAaBbMinPtX[intraGroupEntityIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtX[intraGroupEntityIndex] = asuint(0.0f); + gs_NdcAaBbMinPtY[intraGroupEntityIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtY[intraGroupEntityIndex] = asuint(0.0f); + gs_NdcAaBbMinPtZ[intraGroupEntityIndex] = asuint(1.0f); + gs_NdcAaBbMaxPtZ[intraGroupEntityIndex] = asuint(0.0f); + gs_NdcAaBbMinPtW[intraGroupEntityIndex] = asuint(FLT_INF); + gs_NdcAaBbMaxPtW[intraGroupEntityIndex] = asuint(0.0f); } #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS @@ -462,10 +463,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint i; // Avoid multiply-declared variable warning - // (1) Compute the vertices of the light volume. + // (1) Compute the vertices of the bounding volume. for (i = 0; i < VERTS_PER_THREAD; i++) { - uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + uint v = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; // rbpVerts[0] = rbpC - rbpX * scale - rbpY * scale - rbpZ; (-s, -s, -1) // rbpVerts[1] = rbpC + rbpX * scale - rbpY * scale - rbpZ; (+s, -s, -1) @@ -534,7 +535,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - for (i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + for (i = 0; i < FastLog2(THREADS_PER_ENTITY); i++) { uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role @@ -543,29 +544,29 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else - InterlockedOr(gs_CullClipFaceMasks[intraGroupLightIndex], cullClipFaceMask); + InterlockedOr(gs_CullClipFaceMasks[intraGroupEntityIndex], cullClipFaceMask); GroupMemoryBarrierWithGroupSync(); - cullClipFaceMask = gs_CullClipFaceMasks[intraGroupLightIndex]; + cullClipFaceMask = gs_CullClipFaceMasks[intraGroupEntityIndex]; #endif // (2) Test the corners of the view volume. if (cullClipFaceMask != 0) { - // The light is partially outside the view volume. - // Therefore, some of the corners of the view volume may be inside the light volume. + // The entity is partially outside the view volume. + // Therefore, some of the corners of the view volume may be inside the entity's bounding volume. // We perform aggressive culling, so we must make sure they are accounted for. - // The light volume is a special type of cuboid - a right frustum. - // We can exploit this fact by building a light-space projection matrix. - float4x4 invTranslateToLightSpace = Translation4x4(-rbpC); - float4x4 invRotateAndScaleInLightSpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); + // The bounding volume is a special type of cuboid - a right frustum. + // We can exploit this fact by building a entity-space projection matrix. + float4x4 invTranslateToEntitySpace = Translation4x4(-rbpC); + float4x4 invRotateAndScaleInEntitySpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); // TODO: avoid full inversion by using unit vectors and passing magnitudes explicitly. - // This (orthographic) projection matrix maps a view-space point to a light-space [-1, 1]^3 cube. - float4x4 lightSpaceMatrix = mul(invRotateAndScaleInLightSpace, invTranslateToLightSpace); + // This (orthographic) projection matrix maps a view-space point to a entity-space [-1, 1]^3 cube. + float4x4 entitySpaceMatrix = mul(invRotateAndScaleInEntitySpace, invTranslateToEntitySpace); - if (scale != 1) // Perspective light space? + if (scale != 1) // Perspective entity space? { // Compute the parameters of the perspective projection. float s = scale; @@ -577,20 +578,20 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) float4x4 invTranslateEye = Translation4x4(float3(0, 0, -e)); float4x4 perspProjMatrix = PerspectiveProjection4x4(1, g, n, f); - lightSpaceMatrix = mul(mul(perspProjMatrix, invTranslateEye), lightSpaceMatrix); + entitySpaceMatrix = mul(mul(perspProjMatrix, invTranslateEye), entitySpaceMatrix); } for (i = 0; i < VERTS_PER_THREAD; i++) { - uint v = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + uint v = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; float3 rapVertCS = GenerateVertexOfStandardCube(v); rapVertCS.z = rapVertCS.z * 0.5 + 0.5; // View's projection matrix MUST map Z to [0, 1] float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space - float4 hapVertLS = mul(lightSpaceMatrix, hbpVertVS); // View to light space + float4 hapVertLS = mul(entitySpaceMatrix, hbpVertVS); // View to entity space - // Consider the vertex to be inside the light volume if: + // Consider the vertex to be inside the entity's bounding volume if: // -w < x < w // -w < y < w <-- exclude boundary points, as we will not clip using these vertices // -w < z < w <-- assume that Z-precision is not very important here @@ -628,7 +629,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) for (i = 0; i < FACES_PER_THREAD; i++) { - uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + uint n = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; if (n < numFacesToCull) { @@ -643,7 +644,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - for (i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + for (i = 0; i < FastLog2(THREADS_PER_ENTITY); i++) { uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role @@ -652,11 +653,11 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else - InterlockedAnd(gs_CullClipFaceMasks[intraGroupLightIndex], cullClipFaceMask); + InterlockedAnd(gs_CullClipFaceMasks[intraGroupEntityIndex], cullClipFaceMask); GroupMemoryBarrierWithGroupSync(); - cullClipFaceMask = gs_CullClipFaceMasks[intraGroupLightIndex]; + cullClipFaceMask = gs_CullClipFaceMasks[intraGroupEntityIndex]; #endif // (4) Clip the faces. @@ -666,7 +667,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) for (i = 0; i < FACES_PER_THREAD; i++) { - uint n = i * THREADS_PER_LIGHT + t % THREADS_PER_LIGHT; + uint n = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; if (n < numFacesToClip) { @@ -683,7 +684,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - for (i = 0; i < FastLog2(THREADS_PER_LIGHT); i++) + for (i = 0; i < FastLog2(THREADS_PER_ENTITY); i++) { uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes uint orMask = 0; // Plays no role @@ -701,32 +702,32 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. // We must take care of -0 ourselves. saturate() does not help. - InterlockedMin(gs_NdcAaBbMinPtX[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); - InterlockedMax(gs_NdcAaBbMaxPtX[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); - InterlockedMin(gs_NdcAaBbMinPtY[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); - InterlockedMax(gs_NdcAaBbMaxPtY[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); - InterlockedMin(gs_NdcAaBbMinPtZ[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.z))); - InterlockedMax(gs_NdcAaBbMaxPtZ[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.z))); - InterlockedMin(gs_NdcAaBbMinPtW[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); - InterlockedMax(gs_NdcAaBbMaxPtW[intraGroupLightIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); + InterlockedMin(gs_NdcAaBbMinPtX[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); + InterlockedMax(gs_NdcAaBbMaxPtX[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); + InterlockedMin(gs_NdcAaBbMinPtY[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); + InterlockedMax(gs_NdcAaBbMaxPtY[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); + InterlockedMin(gs_NdcAaBbMinPtZ[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.z))); + InterlockedMax(gs_NdcAaBbMaxPtZ[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.z))); + InterlockedMin(gs_NdcAaBbMinPtW[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); + InterlockedMax(gs_NdcAaBbMaxPtW[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); GroupMemoryBarrierWithGroupSync(); - ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[intraGroupLightIndex]); - ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[intraGroupLightIndex]); - ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[intraGroupLightIndex]); - ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[intraGroupLightIndex]); - ndcAaBbMinPt.z = asfloat(gs_NdcAaBbMinPtZ[intraGroupLightIndex]); - ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[intraGroupLightIndex]); - ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupLightIndex]); - ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupLightIndex]); + ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[intraGroupEntityIndex]); + ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[intraGroupEntityIndex]); + ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[intraGroupEntityIndex]); + ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[intraGroupEntityIndex]); + ndcAaBbMinPt.z = asfloat(gs_NdcAaBbMinPtZ[intraGroupEntityIndex]); + ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[intraGroupEntityIndex]); + ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupEntityIndex]); + ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - if ((globalLightIndex < g_iNrVisibLights) && (t % THREADS_PER_LIGHT == 0)) // Avoid bank conflicts + if ((globalEntityIndex < _BoundedEntityCount) && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { - // For stereo, we have two sets of lights. Therefore, each eye has a set of mins - // followed by a set of maxs, and each set is equal to g_iNrVisibLights. - const ScreenSpaceBoundsIndices eyeAdjustedOutputOffsets = GenerateScreenSpaceBoundsIndices(globalLightIndex, g_iNrVisibLights, eyeIndex); + // For stereo, we have two sets of entities. Therefore, each eye has a set of mins + // followed by a set of maxs, and each set is equal to _BoundedEntityCount. + const ScreenSpaceBoundsIndices eyeAdjustedOutputOffsets = GenerateScreenSpaceBoundsIndices(globalEntityIndex, _BoundedEntityCount, eyeIndex); g_vBoundsBuffer[eyeAdjustedOutputOffsets.min] = ndcAaBbMinPt; g_vBoundsBuffer[eyeAdjustedOutputOffsets.max] = ndcAaBbMaxPt; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index f701764300c..61bd7735260 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -199,7 +199,7 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend //bool tileFlagsWritten = false; ClearLightLists(data.buildGPULightListParameters, buildLightListResources, context.cmd); - // GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); + GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); //BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd); // BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd); // VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd); From 2b52e449648d508d2ae174439ce28ef982268e5e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 29 Sep 2020 19:50:00 -0700 Subject: [PATCH 027/209] Split the output of the AABB pass into XY and W buffers --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 29 ++++++++------ .../Lighting/LightLoop/scrbound.compute | 39 ++++++++----------- .../HDRenderPipeline.LightLoop.cs | 9 +++-- .../RenderPipeline/HDStringConstants.cs | 3 +- 4 files changed, 42 insertions(+), 38 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 2f1429ef79d..78f7943e304 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -687,7 +687,8 @@ class TileAndClusterData // Internal to light list building // public ComputeBuffer lightVolumeDataBuffer { get; private set; } public ComputeBuffer convexBoundsBuffer { get; /*private*/ set; } - public ComputeBuffer AABBBoundsBuffer { get; private set; } + public ComputeBuffer xyBoundsBuffer { get; private set; } + public ComputeBuffer wBoundsBuffer { get; private set; } public ComputeBuffer globalLightListAtomic { get; private set; } // Tile Output @@ -763,7 +764,8 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, } // The bounds and light volumes are view-dependent, and AABB is additionally projection dependent. - AABBBoundsBuffer = new ComputeBuffer((viewCount * maxBoundedEntityCount) * 2, 4 * sizeof(float)); // 2x float4 per AABB + xyBoundsBuffer = new ComputeBuffer(viewCount * maxBoundedEntityCount, 4 * sizeof(float)); // {x_min, y_min, x_max, y_max} + wBoundsBuffer = new ComputeBuffer(viewCount * maxBoundedEntityCount, 2 * sizeof(float)); // {w_min, w_max} // Make sure to invalidate the content of the buffers listsAreClear = false; @@ -804,9 +806,11 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() bigTileLightList = null; // LightList building - CoreUtils.SafeRelease(AABBBoundsBuffer); + CoreUtils.SafeRelease(xyBoundsBuffer); + xyBoundsBuffer = null; + CoreUtils.SafeRelease(wBoundsBuffer); + wBoundsBuffer = null; CoreUtils.SafeRelease(dispatchIndirectBuffer); - AABBBoundsBuffer = null; dispatchIndirectBuffer = null; } @@ -3441,7 +3445,8 @@ struct BuildGPULightListResources // Internal to light list building //public ComputeBuffer lightVolumeDataBuffer; public ComputeBuffer convexBoundsBuffer; - public ComputeBuffer AABBBoundsBuffer; + public ComputeBuffer xyBoundsBuffer; + public ComputeBuffer wBoundsBuffer; public ComputeBuffer globalLightListAtomic; // Output @@ -3468,7 +3473,8 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.lightList = tileAndClusterData.lightList; resources.perVoxelOffset = tileAndClusterData.perVoxelOffset; resources.convexBoundsBuffer = tileAndClusterData.convexBoundsBuffer; - resources.AABBBoundsBuffer = tileAndClusterData.AABBBoundsBuffer; + resources.xyBoundsBuffer = tileAndClusterData.xyBoundsBuffer; + resources.wBoundsBuffer = tileAndClusterData.wBoundsBuffer; //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; @@ -3513,20 +3519,21 @@ static void ClearLightLists( in BuildGPULightListParameters parameters, // generate screen-space AABBs (used for both fptl and clustered). static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { - if (parameters.boundedEntityCount > 0) // Do not perform a dispatch with 0 groups + if (parameters.boundedEntityCount > 0) // Do not perform a dispatch with 0 groups; this will leave the output buffer in an uninitialized state { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs))) { // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); - cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_vBoundsBuffer, resources.AABBBoundsBuffer); + cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); + cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs._wBoundsBuffer, resources.wBoundsBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList); - const int threadsPerLight = 4; // Shader: THREADS_PER_LIGHT (4) - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerEntity = 4; // Shader: THREADS_PER_ENTITY (4) - int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount * threadsPerLight, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount * threadsPerEntity, threadsPerGroup); cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 3b645e6126e..96f85b26e87 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -1,4 +1,4 @@ -// #pragma enable_d3d11_debug_symbols +#pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch #pragma kernel main @@ -14,7 +14,8 @@ StructuredBuffer g_data : register(t0); /* ------------------------------ Outputs ----------------------------------- */ -RWStructuredBuffer g_vBoundsBuffer : register(u0); +RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, y_min, x_max, y_max} +RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} /* ------------------------------ Utilities --------------------------------- */ @@ -198,8 +199,7 @@ groupshared uint gs_NdcAaBbMinPtX[ENTITIES_PER_GROUP]; groupshared uint gs_NdcAaBbMaxPtX[ENTITIES_PER_GROUP]; groupshared uint gs_NdcAaBbMinPtY[ENTITIES_PER_GROUP]; groupshared uint gs_NdcAaBbMaxPtY[ENTITIES_PER_GROUP]; -groupshared uint gs_NdcAaBbMinPtZ[ENTITIES_PER_GROUP]; // Note that min-max Z cannot be trivially reconstructed -groupshared uint gs_NdcAaBbMaxPtZ[ENTITIES_PER_GROUP]; // from min-max W if the projection is oblique. +// Skip Z, we do not need it. groupshared uint gs_NdcAaBbMinPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate groupshared uint gs_NdcAaBbMaxPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS @@ -385,8 +385,8 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT } //********************************************************************************************** -// The goal of this program is to compute the AABB of the entity in the NDC space ([0, 1] range). -// The entity is represented by a convex volume (a frustum) with 6 faces (planar quads) and 8 vertices. +// The goal of this program is to compute the AABB of the bounded entity in the NDC space ([0, 1] range). +// The entity is represented by a convex volume (a right frustum) with 6 faces (planar quads) and 8 vertices. // // Since an entity's bounding volume may be partially off-screen, we must clip it before computing the AABB. // Clipping the resulting AABB (rather than the bounding volume) may result in a loose AABB. @@ -424,8 +424,8 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; // The function call below will not generate an out-of-bounds index. - const uint eyeAdjustedInputOffset = GenerateLightCullDataIndex(globalEntityIndex, _BoundedEntityCount, eyeIndex); - const FiniteLightBound cullData = g_data[eyeAdjustedInputOffset]; + const uint eyeAdjustedDataOffset = GenerateLightCullDataIndex(globalEntityIndex, _BoundedEntityCount, eyeIndex); + const FiniteLightBound cullData = g_data[eyeAdjustedDataOffset]; const float4x4 projMat = g_mProjectionArr[eyeIndex]; const float4x4 invProjMat = g_mInvProjectionArr[eyeIndex]; @@ -445,8 +445,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) gs_NdcAaBbMaxPtX[intraGroupEntityIndex] = asuint(0.0f); gs_NdcAaBbMinPtY[intraGroupEntityIndex] = asuint(1.0f); gs_NdcAaBbMaxPtY[intraGroupEntityIndex] = asuint(0.0f); - gs_NdcAaBbMinPtZ[intraGroupEntityIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtZ[intraGroupEntityIndex] = asuint(0.0f); + // Skip Z, we do not need it. gs_NdcAaBbMinPtW[intraGroupEntityIndex] = asuint(FLT_INF); gs_NdcAaBbMaxPtW[intraGroupEntityIndex] = asuint(0.0f); } @@ -557,7 +556,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // The entity is partially outside the view volume. // Therefore, some of the corners of the view volume may be inside the entity's bounding volume. // We perform aggressive culling, so we must make sure they are accounted for. - // The bounding volume is a special type of cuboid - a right frustum. + // The bounding volume is a special type of a rectangular prism - a right frustum. // We can exploit this fact by building a entity-space projection matrix. float4x4 invTranslateToEntitySpace = Translation4x4(-rbpC); float4x4 invRotateAndScaleInEntitySpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); @@ -694,8 +693,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) ndcAaBbMaxPt.x = max(ndcAaBbMaxPt.x, LaneSwizzle(ndcAaBbMaxPt.x, andMask, orMask, xorMask)); ndcAaBbMinPt.y = min(ndcAaBbMinPt.y, LaneSwizzle(ndcAaBbMinPt.y, andMask, orMask, xorMask)); ndcAaBbMaxPt.y = max(ndcAaBbMaxPt.y, LaneSwizzle(ndcAaBbMaxPt.y, andMask, orMask, xorMask)); - ndcAaBbMinPt.z = min(ndcAaBbMinPt.z, LaneSwizzle(ndcAaBbMinPt.z, andMask, orMask, xorMask)); - ndcAaBbMaxPt.z = max(ndcAaBbMaxPt.z, LaneSwizzle(ndcAaBbMaxPt.z, andMask, orMask, xorMask)); + // Skip Z, we do not need it. ndcAaBbMinPt.w = min(ndcAaBbMinPt.w, LaneSwizzle(ndcAaBbMinPt.w, andMask, orMask, xorMask)); ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, LaneSwizzle(ndcAaBbMaxPt.w, andMask, orMask, xorMask)); } @@ -706,8 +704,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) InterlockedMax(gs_NdcAaBbMaxPtX[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); InterlockedMin(gs_NdcAaBbMinPtY[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); InterlockedMax(gs_NdcAaBbMaxPtY[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); - InterlockedMin(gs_NdcAaBbMinPtZ[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.z))); - InterlockedMax(gs_NdcAaBbMaxPtZ[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.z))); + // Skip Z, we do not need it. InterlockedMin(gs_NdcAaBbMinPtW[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); InterlockedMax(gs_NdcAaBbMaxPtW[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); @@ -717,19 +714,15 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[intraGroupEntityIndex]); ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[intraGroupEntityIndex]); ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[intraGroupEntityIndex]); - ndcAaBbMinPt.z = asfloat(gs_NdcAaBbMinPtZ[intraGroupEntityIndex]); - ndcAaBbMaxPt.z = asfloat(gs_NdcAaBbMaxPtZ[intraGroupEntityIndex]); + // Skip Z, we do not need it. ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupEntityIndex]); ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - if ((globalEntityIndex < _BoundedEntityCount) && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts + if ((globalEntityIndex < (uint)_BoundedEntityCount) && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { - // For stereo, we have two sets of entities. Therefore, each eye has a set of mins - // followed by a set of maxs, and each set is equal to _BoundedEntityCount. - const ScreenSpaceBoundsIndices eyeAdjustedOutputOffsets = GenerateScreenSpaceBoundsIndices(globalEntityIndex, _BoundedEntityCount, eyeIndex); - g_vBoundsBuffer[eyeAdjustedOutputOffsets.min] = ndcAaBbMinPt; - g_vBoundsBuffer[eyeAdjustedOutputOffsets.max] = ndcAaBbMaxPt; + _xyBoundsBuffer[eyeAdjustedDataOffset] = float4(ndcAaBbMinPt.xy, ndcAaBbMaxPt.xy); + _wBoundsBuffer[eyeAdjustedDataOffset] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 61bd7735260..72456fad409 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -54,7 +54,8 @@ class BuildGPULightListPassData // Buffers filled with the CPU outside of render graph. public ComputeBufferHandle convexBoundsBuffer; - public ComputeBufferHandle AABBBoundsBuffer; + public ComputeBufferHandle xyBoundsBuffer; + public ComputeBufferHandle wBoundsBuffer; // Transient buffers that are not used outside of BuildGPULight list so they don't need to go outside the pass. public ComputeBufferHandle globalLightListAtomic; @@ -95,7 +96,8 @@ static BuildGPULightListResources PrepareBuildGPULightListResources(RenderGraphC //buildLightListResources.lightVolumeDataBuffer = data.lightVolumeDataBuffer; buildLightListResources.convexBoundsBuffer = data.convexBoundsBuffer; - buildLightListResources.AABBBoundsBuffer = data.AABBBoundsBuffer; + buildLightListResources.xyBoundsBuffer = data.xyBoundsBuffer; + buildLightListResources.wBoundsBuffer = data.wBoundsBuffer; buildLightListResources.globalLightListAtomic = data.globalLightListAtomic; buildLightListResources.tileFeatureFlags = data.output.tileFeatureFlags; @@ -140,7 +142,8 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend // passData.lightVolumeDataBuffer = builder.ReadComputeBuffer(renderGraph.ImportComputeBuffer(tileAndClusterData.lightVolumeDataBuffer)); passData.globalLightListAtomic = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(1, sizeof(uint)) { name = "LightListAtomic"}); - passData.AABBBoundsBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * 2 * tileAndClusterData.maxLightCount, 4 * sizeof(float)) { name = "AABBBoundBuffer" }); + passData.xyBoundsBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * tileAndClusterData.maxLightCount, 4 * sizeof(float)) { name = "xyBoundsBuffer" }); + passData.wBoundsBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(m_MaxViewCount * tileAndClusterData.maxLightCount, 2 * sizeof(float)) { name = "wBoundsBuffer" }); var nrTilesX = (m_MaxCameraWidth + TiledLightingConstants.s_TileSizeFptl - 1) / TiledLightingConstants.s_TileSizeFptl; var nrTilesY = (m_MaxCameraHeight + TiledLightingConstants.s_TileSizeFptl - 1) / TiledLightingConstants.s_TileSizeFptl; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index fc73761f637..23eb056f93c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -94,7 +94,8 @@ static class HDShaderIDs public static readonly int g_vBigTileLightList = Shader.PropertyToID("g_vBigTileLightList"); public static readonly int g_vLightListGlobal = Shader.PropertyToID("g_vLightListGlobal"); public static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer"); - public static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer"); + public static readonly int _xyBoundsBuffer = Shader.PropertyToID("_xyBoundsBuffer"); + public static readonly int _wBoundsBuffer = Shader.PropertyToID("_wBoundsBuffer"); public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); public static readonly int g_data = Shader.PropertyToID("g_data"); public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList"); From 536013436335e57f212fc99003bec4897ef9ae7c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 1 Oct 2020 18:34:09 -0700 Subject: [PATCH 028/209] Implement the Z-binning pass --- .../Runtime/Lighting/LightDefinition.cs.hlsl | 3 + .../Lighting/LightLoop/LightCullUtils.hlsl | 2 - .../Runtime/Lighting/LightLoop/LightLoop.cs | 98 ++++++++++++--- .../Lighting/LightLoop/LightLoop.cs.hlsl | 16 ++- .../Lighting/LightLoop/scrbound.compute | 20 +-- .../Runtime/Lighting/LightLoop/zbin.compute | 114 ++++++++++++++++++ .../Lighting/LightLoop/zbin.compute.meta | 9 ++ .../VolumeVoxelization.compute | 2 +- .../VolumetricLighting.cs.hlsl | 2 +- .../Runtime/RenderPipeline/HDProfileId.cs | 1 + .../RenderPipeline/HDStringConstants.cs | 3 +- .../RenderPipeline/RenderPipelineResources.cs | 2 + .../ShaderLibrary/ShaderVariablesGlobal.cs | 8 +- .../ShaderVariablesGlobal.cs.hlsl | 2 + 14 files changed, 247 insertions(+), 35 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl index 907299c3b15..3f5a6053f73 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl @@ -15,6 +15,9 @@ #define GPULIGHTTYPE_TUBE (5) #define GPULIGHTTYPE_RECTANGLE (6) #define GPULIGHTTYPE_DISC (7) +#define GPULIGHTTYPE_CUBEMAP_REFLECTION (8) +#define GPULIGHTTYPE_PLANAR_REFLECTION (9) +#define GPULIGHTTYPE_COUNT (10) // // UnityEngine.Rendering.HighDefinition.GPUImageBasedLightingType: static fields diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl index 5a9994e6e7d..b4867b98802 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl @@ -5,8 +5,6 @@ // LightVolumeData (_LightVolumeData) buffers. uint GenerateLightCullDataIndex(uint lightIndex, uint numVisibleLights, uint eyeIndex) { - lightIndex = min(lightIndex, numVisibleLights - 1); // Stay within bounds - // For monoscopic, there is just one set of light cull data structs. // In stereo, all of the left eye structs are first, followed by the right eye structs. const uint perEyeBaseIndex = eyeIndex * numVisibleLights; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 78f7943e304..c036d10c1a3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -377,6 +377,8 @@ class TiledLightingConstants public static int s_TileSizeClustered = 32; public static int s_TileSizeBigTile = 64; + public static int s_ZBinCount = 8192; + // Tile indexing constants for indirect dispatch deferred pass : [2 bits for eye index | 15 bits for tileX | 15 bits for tileY] public static int s_TileIndexMask = 0x7FFF; public static int s_TileIndexShiftX = 0; @@ -516,7 +518,7 @@ unsafe struct ShaderVariablesLightList public Vector4 g_screenSize; public Vector2Int g_viDimensions; - public int _BoundedEntityCount; + public uint _BoundedEntityCount; public uint g_isOrthographic; public uint g_BaseFeatureFlags; @@ -689,6 +691,7 @@ class TileAndClusterData public ComputeBuffer convexBoundsBuffer { get; /*private*/ set; } public ComputeBuffer xyBoundsBuffer { get; private set; } public ComputeBuffer wBoundsBuffer { get; private set; } + public ComputeBuffer zBinBuffer { get; private set; } public ComputeBuffer globalLightListAtomic { get; private set; } // Tile Output @@ -764,8 +767,9 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, } // The bounds and light volumes are view-dependent, and AABB is additionally projection dependent. - xyBoundsBuffer = new ComputeBuffer(viewCount * maxBoundedEntityCount, 4 * sizeof(float)); // {x_min, y_min, x_max, y_max} - wBoundsBuffer = new ComputeBuffer(viewCount * maxBoundedEntityCount, 2 * sizeof(float)); // {w_min, w_max} + xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, y_min, x_max, y_max} + wBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 2 * sizeof(float)); // {w_min, w_max} + zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_ZBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | count} // Make sure to invalidate the content of the buffers listsAreClear = false; @@ -809,7 +813,9 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() CoreUtils.SafeRelease(xyBoundsBuffer); xyBoundsBuffer = null; CoreUtils.SafeRelease(wBoundsBuffer); - wBoundsBuffer = null; + wBoundsBuffer = null; + CoreUtils.SafeRelease(zBinBuffer); + zBinBuffer = null; CoreUtils.SafeRelease(dispatchIndirectBuffer); dispatchIndirectBuffer = null; } @@ -881,6 +887,7 @@ static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) bool m_EnableBakeShadowMask = false; // Track if any light require shadow mask. In this case we will need to enable the keyword shadow mask ComputeShader buildScreenAABBShader { get { return defaultResources.shaders.buildScreenAABBCS; } } + ComputeShader zBinShader { get { return defaultResources.shaders.zBinCS; } } ComputeShader buildPerTileLightListShader { get { return defaultResources.shaders.buildPerTileLightListCS; } } ComputeShader buildPerBigTileLightListShader { get { return defaultResources.shaders.buildPerBigTileLightListCS; } } ComputeShader buildPerVoxelLightListShader { get { return defaultResources.shaders.buildPerVoxelLightListCS; } } @@ -1012,6 +1019,21 @@ struct ScreenSpaceShadowData static MaterialPropertyBlock m_LightLoopDebugMaterialProperties = new MaterialPropertyBlock(); + static Vector4 GetZBinBufferEncodingParams(HDCamera hdCamera) + { + // encodingParams = { n, log2(f/n), 1/n, 1/log2(f/n) } + // n = 0.1. See ComputeFixedPointLogDepth. + float n = 0.1f; + float f = hdCamera.camera.farClipPlane; // Assume XR uses the same far plane for all views + + float x = n; + float z = 1 / x; + float y = Log2f(f * z); + float w = 1 / y; + + return new Vector4(x, y, z, w); + } + static int GetNumTileBigTileX(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_TileSizeBigTile); @@ -2526,9 +2548,10 @@ static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewI static int ComputeFixedPointLogDepth(float w, float f, int numBits = 16) { // z = Log[w/n] / Log[f/n] - // Undefined for (w < n, so we must clamp). This should not affect the efficiency of Z-binning. + // Undefined for (w < n, so we must clamp). This should not significantly affect the efficiency of Z-binning. // Still need the distance to the near plane in order for the math to work. - // Setting it too low will quickly consume the availabl bits. 0.1 is a safe value. + // Setting it too low will quickly consume the available bits. 0.1 is a safe value. + // See https://zero-radiance.github.io/post/z-buffer/ const float n = 0.1f; f = Math.Max(n, f); @@ -3403,7 +3426,9 @@ struct BuildGPULightListParameters // Screen Space AABBs public ComputeShader screenSpaceAABBShader; - public int screenSpaceAABBKernel; + + // Z-binning + public ComputeShader zBinShader; // Big Tile public ComputeShader bigTilePrepassShader; @@ -3447,6 +3472,7 @@ struct BuildGPULightListResources public ComputeBuffer convexBoundsBuffer; public ComputeBuffer xyBoundsBuffer; public ComputeBuffer wBoundsBuffer; + public ComputeBuffer zBinBuffer; public ComputeBuffer globalLightListAtomic; // Output @@ -3475,6 +3501,7 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.convexBoundsBuffer = tileAndClusterData.convexBoundsBuffer; resources.xyBoundsBuffer = tileAndClusterData.xyBoundsBuffer; resources.wBoundsBuffer = tileAndClusterData.wBoundsBuffer; + resources.zBinBuffer = tileAndClusterData.zBinBuffer; //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; @@ -3516,30 +3543,51 @@ static void ClearLightLists( in BuildGPULightListParameters parameters, //} } - // generate screen-space AABBs (used for both fptl and clustered). static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { if (parameters.boundedEntityCount > 0) // Do not perform a dispatch with 0 groups; this will leave the output buffer in an uninitialized state { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.GenerateLightAABBs))) { - // With XR single-pass, we have one set of light bounds per view to iterate over (bounds are in view space for each view) - cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs.g_data, resources.convexBoundsBuffer); - cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); - cmd.SetComputeBufferParam(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, HDShaderIDs._wBoundsBuffer, resources.wBoundsBuffer); + var shader = parameters.screenSpaceAABBShader; + int kernel = 0; - ConstantBuffer.Push(cmd, parameters.lightListCB, parameters.screenSpaceAABBShader, HDShaderIDs._ShaderVariablesLightList); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._EntityBoundsBuffer, resources.convexBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._wBoundsBuffer, resources.wBoundsBuffer); - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - const int threadsPerEntity = 4; // Shader: THREADS_PER_ENTITY (4) + ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); + + int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + int threadsPerEntity = 4; // Shader: THREADS_PER_ENTITY (4) int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount * threadsPerEntity, threadsPerGroup); - cmd.DispatchCompute(parameters.screenSpaceAABBShader, parameters.screenSpaceAABBKernel, groupCount, parameters.viewCount, 1); + cmd.DispatchCompute(shader, kernel, groupCount, parameters.viewCount, 1); } } } + static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + { + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformZBinning))) + { + var shader = parameters.zBinShader; + int kernel = 0; + + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._wBoundsBuffer, resources.wBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._zBinBuffer, resources.zBinBuffer); + + ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); + + int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + + int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); + + cmd.DispatchCompute(shader, kernel, groupCount, parameters.viewCount, 1); + } + } + // // enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered). // static void BigTilePrepass(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) // { @@ -3792,7 +3840,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera int boundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); - cb._BoundedEntityCount = boundedEntityCount; + cb._BoundedEntityCount = (uint)boundedEntityCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; @@ -3855,7 +3903,9 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera // Screen space AABB parameters.screenSpaceAABBShader = buildScreenAABBShader; - parameters.screenSpaceAABBKernel = 0; + + // Screen space AABB + parameters.zBinShader = zBinShader; // Big tile prepass parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); @@ -3988,6 +4038,10 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) // That is fairly efficient, and allows us to avoid weird special cases. ClearLightLists(parameters, resources, cmd); GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); + // Both Z-binning and XY-binning can be executed concurrently. + // This should improve GPU utilization. + PerformZBinning(parameters, resources, cmd); + // BigTilePrepass(parameters, resources, cmd); // BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); // VoxelLightListGeneration(parameters, resources, cmd); @@ -4075,6 +4129,14 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H var geomSeries = (1.0 - Mathf.Pow(k_ClustLogBase, C)) / (1 - k_ClustLogBase); // geometric series: sum_k=0^{C-1} base^k // Tile/Cluster + for (int i = 0; i < (int)BoundedEntityCategory.Count; i++) + { + cb._BoundedEntityCountPerCategory[i] = (uint)m_BoundedEntityCollection.GetEntityCount((BoundedEntityCategory)i); + } + + cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); + + // Old stuff below... cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); cb._NumTileFtplY = (uint)GetNumTileFtplY(hdCamera); cb.g_fClustScale = (float)(geomSeries / (hdCamera.camera.farClipPlane - hdCamera.camera.nearClipPlane)); ; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 0fe935b2e83..35170b14cad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -23,6 +23,17 @@ #define LIGHTCATEGORY_DENSITY_VOLUME (5) #define LIGHTCATEGORY_COUNT (6) +// +// UnityEngine.Rendering.HighDefinition.BoundedEntityCategory: static fields +// +#define BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT (0) +#define BOUNDEDENTITYCATEGORY_AREA_LIGHT (1) +#define BOUNDEDENTITYCATEGORY_REFLECTION_PROBE (2) +#define BOUNDEDENTITYCATEGORY_DECAL (3) +#define BOUNDEDENTITYCATEGORY_DENSITY_VOLUME (4) +#define BOUNDEDENTITYCATEGORY_COUNT (5) +#define BOUNDEDENTITYCATEGORY_NONE (5) + // // UnityEngine.Rendering.HighDefinition.LightFeatureFlags: static fields // @@ -36,7 +47,7 @@ #define LIGHTFEATUREFLAGS_PROBE_VOLUME (524288) // -// UnityEngine.Rendering.HighDefinition.LightDefinitions: static fields +// UnityEngine.Rendering.HighDefinition.TiledLightingConstants: static fields // #define MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE (512) #define VIEWPORT_SCALE_Z (1) @@ -44,6 +55,7 @@ #define TILE_SIZE_FPTL (16) #define TILE_SIZE_CLUSTERED (32) #define TILE_SIZE_BIG_TILE (64) +#define ZBIN_COUNT (8192) #define TILE_INDEX_MASK (32767) #define TILE_INDEX_SHIFT_X (0) #define TILE_INDEX_SHIFT_Y (15) @@ -105,7 +117,7 @@ CBUFFER_START(ShaderVariablesLightList) float4x4 g_mProjectionArr[2]; float4 g_screenSize; int2 g_viDimensions; - int _BoundedEntityCount; + uint _BoundedEntityCount; uint g_isOrthographic; uint g_BaseFeatureFlags; int g_iNumSamplesMSAA; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 96f85b26e87..997329467cf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -10,10 +10,12 @@ /* ------------------------------ Inputs ------------------------------------ */ -StructuredBuffer g_data : register(t0); +// 1x list for all entites (sorted by category, we concatenate lists of all views). +StructuredBuffer _EntityBoundsBuffer : register(t0); /* ------------------------------ Outputs ----------------------------------- */ +// 1x list for all entites (sorted by category, we concatenate lists of all views). RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, y_min, x_max, y_max} RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} @@ -415,20 +417,20 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT [numthreads(THREADS_PER_GROUP, 1, 1)] void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { - const uint t = threadID; - const uint g = groupID.x; - const uint eyeIndex = groupID.y; // Currently, can only be 0 or 1 + const uint t = threadID; + const uint g = groupID.x; + const uint eye = groupID.y; const uint intraGroupEntityIndex = t / THREADS_PER_ENTITY; const uint globalEntityIndex = g * ENTITIES_PER_GROUP + intraGroupEntityIndex; const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; + const uint clampedEntityIndex = min(globalEntityIndex, _BoundedEntityCount - 1); // Stay within bounds - // The function call below will not generate an out-of-bounds index. - const uint eyeAdjustedDataOffset = GenerateLightCullDataIndex(globalEntityIndex, _BoundedEntityCount, eyeIndex); - const FiniteLightBound cullData = g_data[eyeAdjustedDataOffset]; + const uint eyeAdjustedDataOffset = GenerateLightCullDataIndex(clampedEntityIndex, _BoundedEntityCount, eye); + const FiniteLightBound cullData = _EntityBoundsBuffer[eyeAdjustedDataOffset]; - const float4x4 projMat = g_mProjectionArr[eyeIndex]; - const float4x4 invProjMat = g_mInvProjectionArr[eyeIndex]; + const float4x4 projMat = g_mProjectionArr[eye]; + const float4x4 invProjMat = g_mInvProjectionArr[eye]; const float scale = cullData.scaleXY; // scale.x = scale.y const float3 rbpC = cullData.center.xyz; // View-space diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute new file mode 100644 index 00000000000..babe8cecf49 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -0,0 +1,114 @@ +#pragma enable_d3d11_debug_symbols +#pragma only_renderers d3d11 playstation xboxone vulkan metal switch + +#pragma kernel main + +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" + +/* ------------------------------ Inputs ------------------------------------ */ + +// 1x list for all entites (sorted by category, we concatenate lists of all views). +StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} + +// Repackage to work around ridiculous constant buffer limitations of HLSL. +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; + +/* ------------------------------ Outputs ----------------------------------- */ + +// 1x list for all entites (sorted by category, we concatenate lists of all views). +RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | count} + +/* ------------------------------ Utilities --------------------------------- */ + +uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) +{ + float z = EncodeLogarithmicDepth(w, encodingParams); + z = saturate(z); // Clamp to the region between the near and the far planes + + return min((uint)(z * ZBIN_COUNT), ZBIN_COUNT - 1); +} + +float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) +{ + float2 bBounds = float2(bin, bin + 1); + float2 zBounds = saturate(bBounds * rcp(ZBIN_COUNT)); + + return float2(DecodeLogarithmicDepth(zBounds.x, encodingParams), + DecodeLogarithmicDepth(zBounds.y, encodingParams)); +} + +uint Convert3DCoordinateTo1DIndex(uint3 coord, uint2 size) +{ + return coord.x + + coord.y * (size.x) + + coord.z * (size.x * size.y); +} + +uint GenerateZBinBufferOffset(uint bin, uint category, uint eye) +{ + // The Z-bin buffer is effectively 3-dimensional. + return Convert3DCoordinateTo1DIndex(uint3(bin, category, eye), + uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + +// The intervals must be defined s.t. +// the 'x' component holds the lower bound and +// the 'y' component holds the upper bound. +bool IntervalsOverlap(float2 i1, float2 i2) +{ + float l = max(i1.x, i2.x); // Lower bound of intersection interval + float u = min(i1.y, i2.y); // Upper bound of intersection interval + + return l <= u; // Is the interval non-empty? +} + +/* ------------------------------ Implementation ---------------------------- */ + +#define THREADS_PER_GROUP (64) + +[numthreads(THREADS_PER_GROUP, 1, 1)] +void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +{ + const uint t = threadID; + const uint g = groupID.x; + const uint eye = groupID.y; + const uint bin = t + g * THREADS_PER_GROUP; + + // ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP. + const float2 wBounds = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); + + uint inputIndex = GenerateLightCullDataIndex(0, _BoundedEntityCount, eye); + + for (uint cat = 0; cat < BOUNDEDENTITYCATEGORY_COUNT; cat++) + { + uint first = (1 << 16), last = 0; + + uint n = s_BoundedEntityCountPerCategory[cat]; + + // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. + // Therefore, it will be slow if 'n' is large. + // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). + // TODO: unroll. + for (uint i = 0; i < n; i++, inputIndex++) + { + float2 wMinMax = _wBoundsBuffer[inputIndex]; // Sorted by category + + // TODO: flatten. + if (IntervalsOverlap(wBounds, wMinMax)) + { + first = min(i, first); + last = max(i, last); + } + } + + // The compiler should be able to move most of the calculation outside the loop. + uint outputIndex = GenerateZBinBufferOffset(bin, cat, eye); + uint outputRange = (first > last) ? 0 : (first << 16) | (last - first + 1); + + _zBinBuffer[outputIndex] = outputRange; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute.meta new file mode 100644 index 00000000000..d005afb5710 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 313c8dc48c577184997e1c10638c6499 +ComputeShaderImporter: + externalObjects: {} + currentAPIMask: 2097156 + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index 69ba1f5a640..d23f6c17774 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -144,7 +144,7 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, Jitter #else // USE_BIG_TILE_LIGHTLIST - volumeCount = _NumVisibleDensityVolumes; + volumeCount = _DensityVolumeCount; volumeStart = 0; #endif // USE_BIG_TILE_LIGHTLIST diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl index 82ab856b1de..8525fb172f5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl @@ -25,7 +25,7 @@ struct DensityVolumeEngineData CBUFFER_START(ShaderVariablesVolumetric) float4x4 _VBufferCoordToViewDirWS[2]; float _VBufferUnitDepthTexelSpacing; - uint _NumVisibleDensityVolumes; + uint _DensityVolumeCount; float _CornetteShanksConstant; uint _VBufferHistoryIsValid; float4 _VBufferSampleOffset; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 54f95210d35..06d5c77d7f5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -19,6 +19,7 @@ internal enum HDProfileId ScreenSpaceShadowsDebug, BuildLightList, GenerateLightAABBs, + PerformZBinning, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 23eb056f93c..48a6b85be1b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -96,8 +96,9 @@ static class HDShaderIDs public static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer"); public static readonly int _xyBoundsBuffer = Shader.PropertyToID("_xyBoundsBuffer"); public static readonly int _wBoundsBuffer = Shader.PropertyToID("_wBoundsBuffer"); + public static readonly int _zBinBuffer = Shader.PropertyToID("_zBinBuffer"); public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); - public static readonly int g_data = Shader.PropertyToID("g_data"); + public static readonly int _EntityBoundsBuffer = Shader.PropertyToID("_EntityBoundsBuffer"); public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList"); public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs index 360d058375d..f0e80af0c2d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs @@ -59,6 +59,8 @@ public sealed class ShaderResources public ComputeShader buildDispatchIndirectCS; [Reload("Runtime/Lighting/LightLoop/scrbound.compute")] public ComputeShader buildScreenAABBCS; + [Reload("Runtime/Lighting/LightLoop/zbin.compute")] + public ComputeShader zBinCS; [Reload("Runtime/Lighting/LightLoop/lightlistbuild.compute")] public ComputeShader buildPerTileLightListCS; // FPTL [Reload("Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute")] diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 2deeaac0eee..0475fc8dac7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -146,7 +146,8 @@ unsafe struct ShaderVariablesGlobal public float _VBufferLastSliceDist; // The distance to the middle of the last slice // Light Loop - public const int s_MaxEnv2DLight = 32; + public const int s_MaxEnv2DLight = 32; // WTF? + public Vector4 _ShadowAtlasSize; public Vector4 _CascadeShadowAtlasSize; @@ -198,6 +199,11 @@ unsafe struct ShaderVariablesGlobal public Vector4 _PlanarAtlasData; // Tile/Cluster + [HLSLArray(((int)BoundedEntityCategory.Count + 3) / 4, typeof(ShaderGenUInt4))] + public fixed uint _BoundedEntityCountPerCategory[(((int)BoundedEntityCategory.Count + 3) / 4) * 4]; + + public Vector4 _ZBinBufferEncodingParams; + public uint _NumTileFtplX; public uint _NumTileFtplY; public float g_fClustScale; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 38cdd93a601..092a065a643 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -109,6 +109,8 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) float4 _CookieAtlasSize; float4 _CookieAtlasData; float4 _PlanarAtlasData; + uint4 _BoundedEntityCountPerCategory[2]; + float4 _ZBinBufferEncodingParams; uint _NumTileFtplX; uint _NumTileFtplY; float g_fClustScale; From 4bc512a302bd852c5e0ced0912e81f43b61941ca Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 2 Oct 2020 15:26:18 -0700 Subject: [PATCH 029/209] Store {start, end} rather than {start, count} --- .../Runtime/Lighting/LightLoop/zbin.compute | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index babe8cecf49..d2cbb5a6539 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -20,7 +20,7 @@ static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint /* ------------------------------ Outputs ----------------------------------- */ // 1x list for all entites (sorted by category, we concatenate lists of all views). -RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | count} +RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} /* ------------------------------ Utilities --------------------------------- */ @@ -48,7 +48,7 @@ uint Convert3DCoordinateTo1DIndex(uint3 coord, uint2 size) + coord.z * (size.x * size.y); } -uint GenerateZBinBufferOffset(uint bin, uint category, uint eye) +uint GenerateZBinBufferIndex(uint bin, uint category, uint eye) { // The Z-bin buffer is effectively 3-dimensional. return Convert3DCoordinateTo1DIndex(uint3(bin, category, eye), @@ -106,8 +106,8 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } // The compiler should be able to move most of the calculation outside the loop. - uint outputIndex = GenerateZBinBufferOffset(bin, cat, eye); - uint outputRange = (first > last) ? 0 : (first << 16) | (last - first + 1); + uint outputIndex = GenerateZBinBufferIndex(bin, cat, eye); + uint outputRange = (first > last) ? 0 : (first << 16) | (last + 1); _zBinBuffer[outputIndex] = outputRange; } From 9f9ef7df8f225f1102392025aafd055fa0cf1ba8 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 5 Oct 2020 15:47:31 -0700 Subject: [PATCH 030/209] Assert --- .../Runtime/Lighting/LightLoop/zbin.compute | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index d2cbb5a6539..3904444473f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -12,10 +12,7 @@ /* ------------------------------ Inputs ------------------------------------ */ // 1x list for all entites (sorted by category, we concatenate lists of all views). -StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} - -// Repackage to work around ridiculous constant buffer limitations of HLSL. -static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; +StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} /* ------------------------------ Outputs ----------------------------------- */ @@ -24,6 +21,12 @@ RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} /* ------------------------------ Utilities --------------------------------- */ +// The preprocessor does not support the '%' operator. +#define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) + +// Repackage to work around ridiculous constant buffer limitations of HLSL. +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; + uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) { float z = EncodeLogarithmicDepth(w, encodingParams); @@ -78,7 +81,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint eye = groupID.y; const uint bin = t + g * THREADS_PER_GROUP; - // ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP. +#if (REMAINDER(ZBIN_COUNT, THREADS_PER_GROUP) != 0) + #error "ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP." +#endif + const float2 wBounds = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); uint inputIndex = GenerateLightCullDataIndex(0, _BoundedEntityCount, eye); From 283b83f5f41c6edefc81b730285aa73b02cbd23b Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 5 Oct 2020 17:20:29 -0700 Subject: [PATCH 031/209] IndexFromCoordinate, CoordinateFromIndex --- .../ShaderLibrary/Common.hlsl | 45 +++++++++++++++++++ .../Runtime/Lighting/LightLoop/zbin.compute | 15 +++---- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index 6b697a594c3..649334a5083 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1276,4 +1276,49 @@ float SharpenAlpha(float alpha, float alphaClipTreshold) // These clamping function to max of floating point 16 bit are use to prevent INF in code in case of extreme value TEMPLATE_1_REAL(ClampToFloat16Max, value, return min(value, HALF_MAX)) +uint IndexFromCoordinate(uint4 coord, uint3 size) +{ + return coord.x + + coord.y * (size.x) + + coord.z * (size.x * size.y) + + coord.w * (size.x * size.y * size.z); +} + +uint IndexFromCoordinate(uint3 coord, uint2 size) +{ + return IndexFromCoordinate(uint4(coord, 0), uint3(size, 1)); +} + +uint IndexFromCoordinate(uint2 coord, uint size) +{ + return IndexFromCoordinate(uint4(coord, 0, 0), uint3(size, 1, 1)); +} + +uint4 CoordinateFromIndex(uint index, uint3 size) +{ + uint cube = (index ) / (size.x * size.y * size.z); + uint plane = (index % (size.x * size.y * size.z)) / (size.x * size.y); + uint row = (index % (size.x * size.y) ) / (size.x); + uint column = (index % (size.x)); + + return uint4(column, row, plane, cube); +} + +uint3 CoordinateFromIndex(uint index, uint2 size) +{ + uint plane = (index ) / (size.x * size.y); + uint row = (index % (size.x * size.y)) / (size.x); + uint column = (index % (size.x)); + + return uint3(column, row, plane); +} + +uint2 CoordinateFromIndex(uint index, uint size) +{ + uint row = index / size.x; + uint column = index % size.x; + + return uint2(column, row); +} + #endif // UNITY_COMMON_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 3904444473f..454a51d0268 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -17,6 +17,9 @@ StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} /* ------------------------------ Outputs ----------------------------------- */ // 1x list for all entites (sorted by category, we concatenate lists of all views). +// The size of the buffer can be computed as follows: +// ZBIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * 4 bytes per range. +// For example (1080p): 8192 * 5 * 1 * 4 = 160 KiB. RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} /* ------------------------------ Utilities --------------------------------- */ @@ -44,18 +47,10 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) DecodeLogarithmicDepth(zBounds.y, encodingParams)); } -uint Convert3DCoordinateTo1DIndex(uint3 coord, uint2 size) -{ - return coord.x - + coord.y * (size.x) - + coord.z * (size.x * size.y); -} - uint GenerateZBinBufferIndex(uint bin, uint category, uint eye) { - // The Z-bin buffer is effectively 3-dimensional. - return Convert3DCoordinateTo1DIndex(uint3(bin, category, eye), - uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + return IndexFromCoordinate(uint3(bin, category, eye), + uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } // The intervals must be defined s.t. From 7e11c2dc8fdef5b9d5a6ee2edeba62578efda595 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 5 Oct 2020 20:02:44 -0700 Subject: [PATCH 032/209] Dispatch a group per category --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 20 ++++- .../Lighting/LightLoop/LightLoop.cs.hlsl | 5 +- .../Lighting/LightLoop/scrbound.compute | 14 ++-- .../Runtime/Lighting/LightLoop/zbin.compute | 75 ++++++++++--------- .../ShaderLibrary/ShaderVariablesGlobal.cs | 2 + .../ShaderVariablesGlobal.cs.hlsl | 1 + 6 files changed, 73 insertions(+), 44 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index c036d10c1a3..0d8016aa741 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -377,8 +377,6 @@ class TiledLightingConstants public static int s_TileSizeClustered = 32; public static int s_TileSizeBigTile = 64; - public static int s_ZBinCount = 8192; - // Tile indexing constants for indirect dispatch deferred pass : [2 bits for eye index | 15 bits for tileX | 15 bits for tileY] public static int s_TileIndexMask = 0x7FFF; public static int s_TileIndexShiftX = 0; @@ -403,6 +401,12 @@ class TiledLightingConstants public static uint s_ScreenSpaceColorShadowFlag = 0x100; public static uint s_InvalidScreenSpaceShadow = 0xff; public static uint s_ScreenSpaceShadowIndexMask = 0xff; + + // Z-binning + public static int s_CoarseTileEntityLimit = 64; // Before pruning, so, in practice, the number is lower + public static int s_CoarseTileSize = 64; + public static int s_FineTileSize = 8; + public static int s_ZBinCount = 8192; } [GenerateHLSL] @@ -3570,6 +3574,7 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { + // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformZBinning))) { var shader = parameters.zBinShader; @@ -3584,7 +3589,9 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); - cmd.DispatchCompute(shader, kernel, groupCount, parameters.viewCount, 1); + cmd.DispatchCompute(shader, kernel, groupCount, parameters.viewCount, (int)BoundedEntityCategory.Count); + } + } } } @@ -4134,6 +4141,13 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H cb._BoundedEntityCountPerCategory[i] = (uint)m_BoundedEntityCollection.GetEntityCount((BoundedEntityCategory)i); } + cb._BoundedEntityOffsetPerCategory[0] = 0; + + for (int i = 1; i < (int)BoundedEntityCategory.Count; i++) + { + cb._BoundedEntityOffsetPerCategory[i] = cb._BoundedEntityOffsetPerCategory[i - 1] + cb._BoundedEntityCountPerCategory[i - 1]; + } + cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); // Old stuff below... diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 35170b14cad..19e0e37c97f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -55,7 +55,6 @@ #define TILE_SIZE_FPTL (16) #define TILE_SIZE_CLUSTERED (32) #define TILE_SIZE_BIG_TILE (64) -#define ZBIN_COUNT (8192) #define TILE_INDEX_MASK (32767) #define TILE_INDEX_SHIFT_X (0) #define TILE_INDEX_SHIFT_Y (15) @@ -71,6 +70,10 @@ #define SCREEN_SPACE_COLOR_SHADOW_FLAG (256) #define INVALID_SCREEN_SPACE_SHADOW (255) #define SCREEN_SPACE_SHADOW_INDEX_MASK (255) +#define COARSE_TILE_ENTITY_LIMIT (64) +#define COARSE_TILE_SIZE (64) +#define FINE_TILE_SIZE (8) +#define ZBIN_COUNT (8192) // // UnityEngine.Rendering.HighDefinition.ClusterDebugMode: static fields diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 997329467cf..66916dfee59 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -6,7 +6,6 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -93,6 +92,11 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) 0, 0, 1, 0); } +uint ComputeEntityBoundsBufferOffset(uint entityIndex, uint eye) +{ + return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); +} + /* ------------------------------ Implementation ---------------------------- */ // Improve the quality of generated code at the expense of readability. @@ -426,8 +430,8 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; const uint clampedEntityIndex = min(globalEntityIndex, _BoundedEntityCount - 1); // Stay within bounds - const uint eyeAdjustedDataOffset = GenerateLightCullDataIndex(clampedEntityIndex, _BoundedEntityCount, eye); - const FiniteLightBound cullData = _EntityBoundsBuffer[eyeAdjustedDataOffset]; + const uint bufferOffset = ComputeEntityBoundsBufferOffset(clampedEntityIndex, _BoundedEntityCount); + const FiniteLightBound cullData = _EntityBoundsBuffer[bufferOffset]; const float4x4 projMat = g_mProjectionArr[eye]; const float4x4 invProjMat = g_mInvProjectionArr[eye]; @@ -724,7 +728,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if ((globalEntityIndex < (uint)_BoundedEntityCount) && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { - _xyBoundsBuffer[eyeAdjustedDataOffset] = float4(ndcAaBbMinPt.xy, ndcAaBbMaxPt.xy); - _wBoundsBuffer[eyeAdjustedDataOffset] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); + _xyBoundsBuffer[bufferOffset] = float4(ndcAaBbMinPt.xy, ndcAaBbMaxPt.xy); + _wBoundsBuffer[bufferOffset] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 454a51d0268..45608ba925d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -6,7 +6,6 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -18,17 +17,29 @@ StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: -// ZBIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * 4 bytes per range. +// ZBIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (4 bytes per range). // For example (1080p): 8192 * 5 * 1 * 4 = 160 KiB. RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} /* ------------------------------ Utilities --------------------------------- */ -// The preprocessor does not support the '%' operator. +// The HLSL preprocessor does not support the '%' operator. #define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) // Repackage to work around ridiculous constant buffer limitations of HLSL. -static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; +static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; + +uint ComputeEntityBoundsBufferOffset(uint entityIndex, uint eye) +{ + return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); +} + +uint GenerateZBinBufferOffset(uint bin, uint category, uint eye) +{ + return IndexFromCoordinate(uint3(bin, category, eye), + uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) { @@ -47,12 +58,6 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) DecodeLogarithmicDepth(zBounds.y, encodingParams)); } -uint GenerateZBinBufferIndex(uint bin, uint category, uint eye) -{ - return IndexFromCoordinate(uint3(bin, category, eye), - uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); -} - // The intervals must be defined s.t. // the 'x' component holds the lower bound and // the 'y' component holds the upper bound. @@ -74,42 +79,42 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint t = threadID; const uint g = groupID.x; const uint eye = groupID.y; - const uint bin = t + g * THREADS_PER_GROUP; + const uint cat = groupID.z; + const uint bin = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); + + // Entities are sorted by category. + const uint entityIndex = s_BoundedEntityOffsetPerCategory[cat]; + const uint entityCount = s_BoundedEntityCountPerCategory[cat]; #if (REMAINDER(ZBIN_COUNT, THREADS_PER_GROUP) != 0) #error "ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP." #endif - const float2 wBounds = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); - uint inputIndex = GenerateLightCullDataIndex(0, _BoundedEntityCount, eye); + uint first = (1 << 16), last = 0; - for (uint cat = 0; cat < BOUNDEDENTITYCATEGORY_COUNT; cat++) - { - uint first = (1 << 16), last = 0; + uint inputOffset = ComputeEntityBoundsBufferOffset(entityIndex, _BoundedEntityCount); - uint n = s_BoundedEntityCountPerCategory[cat]; + // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. + // Therefore, it will be slow if 'n' is large. + // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). + // TODO: unroll. + for (uint i = 0; i < entityCount; i++, inputOffset++) + { + float2 wMinMax = _wBoundsBuffer[inputOffset]; - // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. - // Therefore, it will be slow if 'n' is large. - // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). - // TODO: unroll. - for (uint i = 0; i < n; i++, inputIndex++) + // TODO: flatten. + if (IntervalsOverlap(wBounds, wMinMax)) { - float2 wMinMax = _wBoundsBuffer[inputIndex]; // Sorted by category - - // TODO: flatten. - if (IntervalsOverlap(wBounds, wMinMax)) - { - first = min(i, first); - last = max(i, last); - } + // We store intra-category indices. + first = min(i, first); + last = max(i, last); } + } - // The compiler should be able to move most of the calculation outside the loop. - uint outputIndex = GenerateZBinBufferIndex(bin, cat, eye); - uint outputRange = (first > last) ? 0 : (first << 16) | (last + 1); + // The compiler should be able to move most of the calculation outside the loop. + uint outputOffset = GenerateZBinBufferOffset(bin, cat, eye); + uint outputRange = (first > last) ? 0 : (first << 16) | (last + 1); - _zBinBuffer[outputIndex] = outputRange; - } + _zBinBuffer[outputOffset] = outputRange; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 0475fc8dac7..3d73c6fe0e2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -201,6 +201,8 @@ unsafe struct ShaderVariablesGlobal // Tile/Cluster [HLSLArray(((int)BoundedEntityCategory.Count + 3) / 4, typeof(ShaderGenUInt4))] public fixed uint _BoundedEntityCountPerCategory[(((int)BoundedEntityCategory.Count + 3) / 4) * 4]; + [HLSLArray(((int)BoundedEntityCategory.Count + 3) / 4, typeof(ShaderGenUInt4))] + public fixed uint _BoundedEntityOffsetPerCategory[(((int)BoundedEntityCategory.Count + 3) / 4) * 4]; public Vector4 _ZBinBufferEncodingParams; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 092a065a643..6c6c0d2b24c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -110,6 +110,7 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) float4 _CookieAtlasData; float4 _PlanarAtlasData; uint4 _BoundedEntityCountPerCategory[2]; + uint4 _BoundedEntityOffsetPerCategory[2]; float4 _ZBinBufferEncodingParams; uint _NumTileFtplX; uint _NumTileFtplY; From 856f5c40dddc40cbf3e270a5bc6f9079100f7d8b Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 6 Oct 2020 18:01:12 -0700 Subject: [PATCH 033/209] Dimensions --- .../ShaderLibrary/Common.hlsl | 40 ++++----- .../Runtime/Lighting/LightLoop/xybin.compute | 83 +++++++++++++++++++ .../Lighting/LightLoop/xybin.compute.meta | 9 ++ 3 files changed, 112 insertions(+), 20 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index 649334a5083..8a81fe0f108 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1276,47 +1276,47 @@ float SharpenAlpha(float alpha, float alphaClipTreshold) // These clamping function to max of floating point 16 bit are use to prevent INF in code in case of extreme value TEMPLATE_1_REAL(ClampToFloat16Max, value, return min(value, HALF_MAX)) -uint IndexFromCoordinate(uint4 coord, uint3 size) +uint IndexFromCoordinate(uint4 coord, uint3 dimensions) { return coord.x - + coord.y * (size.x) - + coord.z * (size.x * size.y) - + coord.w * (size.x * size.y * size.z); + + coord.y * (dimensions.x) + + coord.z * (dimensions.x * dimensions.y) + + coord.w * (dimensions.x * dimensions.y * dimensions.z); } -uint IndexFromCoordinate(uint3 coord, uint2 size) +uint IndexFromCoordinate(uint3 coord, uint2 dimensions) { - return IndexFromCoordinate(uint4(coord, 0), uint3(size, 1)); + return IndexFromCoordinate(uint4(coord, 0), uint3(dimensions, 1)); } -uint IndexFromCoordinate(uint2 coord, uint size) +uint IndexFromCoordinate(uint2 coord, uint dimensions) { - return IndexFromCoordinate(uint4(coord, 0, 0), uint3(size, 1, 1)); + return IndexFromCoordinate(uint4(coord, 0, 0), uint3(dimensions, 1, 1)); } -uint4 CoordinateFromIndex(uint index, uint3 size) +uint4 CoordinateFromIndex(uint index, uint3 dimensions) { - uint cube = (index ) / (size.x * size.y * size.z); - uint plane = (index % (size.x * size.y * size.z)) / (size.x * size.y); - uint row = (index % (size.x * size.y) ) / (size.x); - uint column = (index % (size.x)); + uint cube = (index ) / (dimensions.x * dimensions.y * dimensions.z); + uint plane = (index % (dimensions.x * dimensions.y * dimensions.z)) / (dimensions.x * dimensions.y); + uint row = (index % (dimensions.x * dimensions.y) ) / (dimensions.x); + uint column = (index % (dimensions.x)); return uint4(column, row, plane, cube); } -uint3 CoordinateFromIndex(uint index, uint2 size) +uint3 CoordinateFromIndex(uint index, uint2 dimensions) { - uint plane = (index ) / (size.x * size.y); - uint row = (index % (size.x * size.y)) / (size.x); - uint column = (index % (size.x)); + uint plane = (index ) / (dimensions.x * dimensions.y); + uint row = (index % (dimensions.x * dimensions.y)) / (dimensions.x); + uint column = (index % (dimensions.x)); return uint3(column, row, plane); } -uint2 CoordinateFromIndex(uint index, uint size) +uint2 CoordinateFromIndex(uint index, uint dimensions) { - uint row = index / size.x; - uint column = index % size.x; + uint row = index / dimensions.x; + uint column = index % dimensions.x; return uint2(column, row); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute new file mode 100644 index 00000000000..c6980215a52 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -0,0 +1,83 @@ +#pragma enable_d3d11_debug_symbols +#pragma only_renderers d3d11 playstation xboxone vulkan metal switch + +// Generates large screen tiles in a fast, conservative manner +#pragma kernel BinCoarseXY PASS = BIN_COARSE_XY +// Removes certain entities from the coarse buffer at a large cost +#pragma kernel PruneCoarseXY PASS = PRUNE_COARSE_XY +// Generates small screen tiles in an accurate manner +#pragma kernel BinFineXY PASS = BIN_FINE_XY + +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" + +/* ------------------------------ Inputs ------------------------------------ */ + +#if (PASS == BIN_COARSE_XY) + // 1x list for all entites (sorted by category, we concatenate lists of all views). + RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, y_min, x_max, y_max} +#endif + +/* ------------------------------ Outputs ----------------------------------- */ + +#if (PASS == BIN_COARSE_XY) + // 1x list for all entites (sorted by category, we concatenate lists of all views). + // The size of the buffer can be computed as follows: + // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_TILE_ENTITY_LIMIT * 2 bytes per entry). + // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. + RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 1-based indices +#endif + +/* ------------------------------ Utilities --------------------------------- */ + +// Repackage to work around ridiculous constant buffer limitations of HLSL. +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; +static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; + +uint ComputeEntityBoundsBufferOffset(uint entityIndex, uint eye) +{ + return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); +} + +uint GenerateCoarseTileBufferOffset(uint tile, uint category, uint eye) +{ + return IndexFromCoordinate(uint3(tile, category, eye), + uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + +/* ------------------------------ Implementation ---------------------------- */ + +#define THREADS_PER_GROUP (64) + +[numthreads(THREADS_PER_GROUP, 1, 1)] +void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) +{ + // TODO: it may be worth processing a single bin on multiple threads. + const uint2 t = threadID.xy; // 8x8 block for locality (reduce divergence) + const uint g = groupID.x; + const uint eye = groupID.y; + const uint bin = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); + + // TODO: copy=paste BigTile Code. +} + +[numthreads(THREADS_PER_GROUP, 1, 1)] +void PruneCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +{ + const uint t = threadID; + const uint g = groupID.x; + const uint eye = groupID.y; + const uint bin = t + g * THREADS_PER_GROUP; +} + +[numthreads(THREADS_PER_GROUP, 1, 1)] +void BinFineXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +{ + const uint t = threadID; + const uint g = groupID.x; + const uint eye = groupID.y; + const uint bin = t + g * THREADS_PER_GROUP; +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta new file mode 100644 index 00000000000..5d94f12a2aa --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 8ccaf15991ce0ec48a2adfc5c8d930de +ComputeShaderImporter: + externalObjects: {} + currentAPIMask: 2097156 + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: From 913b4734a708fab99920406c511e5689bf7977f9 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 7 Oct 2020 19:36:01 -0700 Subject: [PATCH 034/209] BinCoarseXY prototype --- .../ShaderLibrary/Macros.hlsl | 1 + .../Runtime/Lighting/LightLoop/LightLoop.cs | 34 ++++- .../Lighting/LightLoop/scrbound.compute | 18 ++- .../Runtime/Lighting/LightLoop/xybin.compute | 134 +++++++++++++++--- .../Runtime/Lighting/LightLoop/zbin.compute | 60 ++++---- 5 files changed, 187 insertions(+), 60 deletions(-) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl index 3981ef50a88..f96b7f4238d 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl @@ -46,6 +46,7 @@ #define HALF_MIN_SQRT 0.0078125 // 2^-7 == sqrt(HALF_MIN), useful for ensuring HALF_MIN after x^2 #define HALF_MAX 65504.0 #define UINT_MAX 0xFFFFFFFFu +#define UINT16_MAX 0xFFFFu #define INT_MAX 0x7FFFFFFF diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 0d8016aa741..27c004392e9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -771,7 +771,7 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, } // The bounds and light volumes are view-dependent, and AABB is additionally projection dependent. - xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, y_min, x_max, y_max} + xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, x_max, y_min, y_max} wBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 2 * sizeof(float)); // {w_min, w_max} zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_ZBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | count} @@ -3589,9 +3589,38 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); - cmd.DispatchCompute(shader, kernel, groupCount, parameters.viewCount, (int)BoundedEntityCategory.Count); + cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); } } + + static void PerformXYBinning(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + { + // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformZBinning))) + { + var shader = parameters.zBinShader; + int kernel; + + kernel = 0; // BinCoarseXY + + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._wBoundsBuffer, resources.wBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._zBinBuffer, resources.zBinBuffer); + + ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); + + int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + + int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); + + // cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); + + kernel = 1; // PruneCoarseXY + + // ... + + kernel = 2; // BinFineXY + + // ... } } @@ -4048,6 +4077,7 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) // Both Z-binning and XY-binning can be executed concurrently. // This should improve GPU utilization. PerformZBinning(parameters, resources, cmd); + PerformXYBinning(parameters, resources, cmd); // BigTilePrepass(parameters, resources, cmd); // BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 66916dfee59..4720a700062 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -15,7 +15,7 @@ StructuredBuffer _EntityBoundsBuffer : register(t0); /* ------------------------------ Outputs ----------------------------------- */ // 1x list for all entites (sorted by category, we concatenate lists of all views). -RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, y_min, x_max, y_max} +RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, x_max, y_min, y_max} RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} /* ------------------------------ Utilities --------------------------------- */ @@ -92,7 +92,7 @@ float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) 0, 0, 1, 0); } -uint ComputeEntityBoundsBufferOffset(uint entityIndex, uint eye) +uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) { return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); } @@ -430,8 +430,12 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; const uint clampedEntityIndex = min(globalEntityIndex, _BoundedEntityCount - 1); // Stay within bounds - const uint bufferOffset = ComputeEntityBoundsBufferOffset(clampedEntityIndex, _BoundedEntityCount); - const FiniteLightBound cullData = _EntityBoundsBuffer[bufferOffset]; + // Helper threads may perform the same computation on valid data, + // but do not store the results of the computation to memory. + const bool isHelperThread = globalEntityIndex != clampedEntityIndex; + + const uint bufferIndex = ComputeEntityBoundsBufferIndex(clampedEntityIndex, _BoundedEntityCount); + const FiniteLightBound cullData = _EntityBoundsBuffer[bufferIndex]; const float4x4 projMat = g_mProjectionArr[eye]; const float4x4 invProjMat = g_mInvProjectionArr[eye]; @@ -725,10 +729,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - if ((globalEntityIndex < (uint)_BoundedEntityCount) && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts + if (!isHelperThread && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { - _xyBoundsBuffer[bufferOffset] = float4(ndcAaBbMinPt.xy, ndcAaBbMaxPt.xy); - _wBoundsBuffer[bufferOffset] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); + _xyBoundsBuffer[bufferIndex] = float4(ndcAaBbMinPt.x, ndcAaBbMaxPt.x, ndcAaBbMinPt.y, ndcAaBbMaxPt.y); + _wBoundsBuffer[bufferIndex] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index c6980215a52..ba531730997 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -17,7 +17,7 @@ #if (PASS == BIN_COARSE_XY) // 1x list for all entites (sorted by category, we concatenate lists of all views). - RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, y_min, x_max, y_max} + RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, x_max, y_min, y_max} #endif /* ------------------------------ Outputs ----------------------------------- */ @@ -28,56 +28,146 @@ // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_TILE_ENTITY_LIMIT * 2 bytes per entry). // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. - RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 1-based indices + RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 16-bit indices #endif /* ------------------------------ Utilities --------------------------------- */ +// The HLSL preprocessor does not support the '%' operator. +#define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) + // Repackage to work around ridiculous constant buffer limitations of HLSL. static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; -uint ComputeEntityBoundsBufferOffset(uint entityIndex, uint eye) +uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) { return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); } -uint GenerateCoarseTileBufferOffset(uint tile, uint category, uint eye) +uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint tileRowSize, uint category, uint eye) { - return IndexFromCoordinate(uint3(tile, category, eye), - uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + uint stride = COARSE_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + return stride * IndexFromCoordinate(uint4(tileCoord, category, eye), + uint3(tileRowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + +// The intervals must be defined s.t. +// the 'x' component holds the lower bound and +// the 'y' component holds the upper bound. +bool IntervalsOverlap(float2 i1, float2 i2) +{ + float l = max(i1.x, i2.x); // Lower bound of the intersection interval + float u = min(i1.y, i2.y); // Upper bound of the intersection interval + + return l <= u; // Is the interval non-empty? } /* ------------------------------ Implementation ---------------------------- */ -#define THREADS_PER_GROUP (64) +#if (REMAINDER(COARSE_TILE_ENTITY_LIMIT, 2) != 0) + #error "COARSE_TILE_ENTITY_LIMIT must be an integer multiple of 2." +#endif + +#define GROUP_SIZE (8) +#define THREADS_PER_GROUP (GROUP_SIZE * GROUP_SIZE) [numthreads(THREADS_PER_GROUP, 1, 1)] void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { - // TODO: it may be worth processing a single bin on multiple threads. - const uint2 t = threadID.xy; // 8x8 block for locality (reduce divergence) - const uint g = groupID.x; - const uint eye = groupID.y; - const uint bin = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); - - // TODO: copy=paste BigTile Code. + const uint2 t = threadID.xy; // 8x8 block for locality (reduce divergence) + const uint g = groupID.x; + const uint eye = groupID.y; + const uint cat = groupID.z; + + const uint2 groupCount = uint2(DIV_ROUND_UP(_ScreenSize.x, GROUP_SIZE * COARSE_TILE_SIZE), + DIV_ROUND_UP(_ScreenSize.y, GROUP_SIZE * COARSE_TILE_SIZE)); + + const uint2 coarseTileBufferDimensions = 0; + + const uint2 groupCoord = CoordinateFromIndex(g, groupCount.x); + const uint2 tileCoord = groupCoord * GROUP_SIZE + t; + const uint2 clampedTileCoord = min(clampedTileCoord, coarseTileBufferDimensions - 1); // Stay within bounds + + // Helper threads may perform the same computation on valid data, + // but do not store the results of the computation to memory. + const bool isHelperThread = any(tileCoord != clampedTileCoord); + + if (isHelperThread) return; // Avoid adding too many checks or branches below + + // Entities are sorted by category. + const uint entityIndex = s_BoundedEntityOffsetPerCategory[cat]; + const uint entityCount = s_BoundedEntityCountPerCategory[cat]; + + if (entityCount > 0) // Avoid wasted work + { + // Compute 2-D the AABB of the tile. + const uint2 tileAaBbMinPtSS = clampedTileCoord * COARSE_TILE_SIZE; + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_TILE_SIZE + const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide + const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float3 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); + const float3 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); + + const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, _BoundedEntityCount); + const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, coarseTileBufferDimensions.x, cat, eye); + + // Define inputs and outputs. + uint i = 0, j = 0; + uint indexPair = 0; + + // The algorithm is O(n * m) where 'n' is the entity count and 'm' is tile count. + // Therefore, it will be slow if 'n' is large. + // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). + // TODO: unroll. + while ((i < entityCount) && (j < COARSE_TILE_ENTITY_LIMIT)) + { + float2 entityBoundsX = _xyBoundsBuffer[inputStart + i].xy; + float2 entityBoundsY = _xyBoundsBuffer[inputStart + i].zw; + + if (IntervalsOverlap(entityBoundsX, tileBoundsX) && + IntervalsOverlap(entityBoundsY, tileBoundsY)) + { + // We store intra-category indices. + // 2x 16-bit indices per uint. + indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits + + if ((j & 1) != 0) // Is the pair complete & ready to be stored? + { + _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; + + indexPair = 0; // In order to use bitwise OR above + } + + j++; + } + + i++; + } + + if (j < COARSE_TILE_ENTITY_LIMIT) + { + // Add a terminator. + indexPair |= UINT16_MAX << (16 * (j & 1)); // Order: first Lo, then Hi bits + + _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; + } + } + else + { + // We do not clear the buffer, so we must add a terminator. + _CoarseTileBuffer[outputStart] = UINT16_MAX; + } } [numthreads(THREADS_PER_GROUP, 1, 1)] void PruneCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { - const uint t = threadID; - const uint g = groupID.x; - const uint eye = groupID.y; - const uint bin = t + g * THREADS_PER_GROUP; + } [numthreads(THREADS_PER_GROUP, 1, 1)] void BinFineXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { - const uint t = threadID; - const uint g = groupID.x; - const uint eye = groupID.y; - const uint bin = t + g * THREADS_PER_GROUP; + } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 45608ba925d..4cd686fe401 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -30,12 +30,12 @@ RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; -uint ComputeEntityBoundsBufferOffset(uint entityIndex, uint eye) +uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) { return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); } -uint GenerateZBinBufferOffset(uint bin, uint category, uint eye) +uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) { return IndexFromCoordinate(uint3(bin, category, eye), uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); @@ -63,8 +63,8 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) // the 'y' component holds the upper bound. bool IntervalsOverlap(float2 i1, float2 i2) { - float l = max(i1.x, i2.x); // Lower bound of intersection interval - float u = min(i1.y, i2.y); // Upper bound of intersection interval + float l = max(i1.x, i2.x); // Lower bound of the intersection interval + float u = min(i1.y, i2.y); // Upper bound of the intersection interval return l <= u; // Is the interval non-empty? } @@ -73,48 +73,50 @@ bool IntervalsOverlap(float2 i1, float2 i2) #define THREADS_PER_GROUP (64) +#if (REMAINDER(ZBIN_COUNT, THREADS_PER_GROUP) != 0) + #error "ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP." +#endif + [numthreads(THREADS_PER_GROUP, 1, 1)] void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { const uint t = threadID; const uint g = groupID.x; - const uint eye = groupID.y; - const uint cat = groupID.z; + const uint cat = groupID.y; + const uint eye = groupID.z; const uint bin = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); // Entities are sorted by category. const uint entityIndex = s_BoundedEntityOffsetPerCategory[cat]; const uint entityCount = s_BoundedEntityCountPerCategory[cat]; -#if (REMAINDER(ZBIN_COUNT, THREADS_PER_GROUP) != 0) - #error "ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP." -#endif - const float2 wBounds = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); - uint first = (1 << 16), last = 0; - uint inputOffset = ComputeEntityBoundsBufferOffset(entityIndex, _BoundedEntityCount); - - // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. - // Therefore, it will be slow if 'n' is large. - // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). - // TODO: unroll. - for (uint i = 0; i < entityCount; i++, inputOffset++) + if (entityCount > 0) // Avoid wasted work { - float2 wMinMax = _wBoundsBuffer[inputOffset]; - - // TODO: flatten. - if (IntervalsOverlap(wBounds, wMinMax)) + const float2 binBoundsW = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); + const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, _BoundedEntityCount); + + // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. + // Therefore, it will be slow if 'n' is large. + // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). + // TODO: unroll. + for (uint i = 0; i < entityCount; i++) { - // We store intra-category indices. - first = min(i, first); - last = max(i, last); + float2 entityBoundsW = _wBoundsBuffer[inputStart + i]; + + // TODO: flatten. + if (IntervalsOverlap(entityBoundsW, binBoundsW)) + { + // We store intra-category indices. + first = min(i, first); + last = max(i, last); + } } } - // The compiler should be able to move most of the calculation outside the loop. - uint outputOffset = GenerateZBinBufferOffset(bin, cat, eye); - uint outputRange = (first > last) ? 0 : (first << 16) | (last + 1); + uint outputIndex = ComputeZBinBufferIndex(bin, cat, eye); + uint outputRange = (first > last) ? 0 : (first << 16) | (last + 1); - _zBinBuffer[outputOffset] = outputRange; + _zBinBuffer[outputIndex] = outputRange; } From a6c1ccba014f669b372eb5eb797057e18dcbf510 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 7 Oct 2020 20:07:28 -0700 Subject: [PATCH 035/209] Feed shader constants --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 26 +++++++++++++++++-- .../Lighting/LightLoop/LightLoop.cs.hlsl | 2 +- .../Runtime/Lighting/LightLoop/xybin.compute | 17 +++++------- .../ShaderLibrary/ShaderVariablesGlobal.cs | 7 +++-- .../ShaderVariablesGlobal.cs.hlsl | 2 ++ 5 files changed, 39 insertions(+), 15 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 27c004392e9..9f6b5906e3d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -532,7 +532,7 @@ unsafe struct ShaderVariablesLightList public uint _DensityVolumeIndexShift; public uint _ProbeVolumeIndexShift; - public uint _Pad0_SVLL; + public uint _BinCoarseXYDispatchGroupCountX; public uint _Pad1_SVLL; } @@ -1038,6 +1038,22 @@ static Vector4 GetZBinBufferEncodingParams(HDCamera hdCamera) return new Vector4(x, y, z, w); } + static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) + { + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseTileSize); + + return new Vector2Int(w, h); + } + + static Vector2Int GetFineTileBufferDimensions(HDCamera hdCamera) + { + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineTileSize); + + return new Vector2Int(w, h); + } + static int GetNumTileBigTileX(HDCamera hdCamera) { return HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_TileSizeBigTile); @@ -3875,8 +3891,12 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); int boundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); + int coarseTileBufferWidth = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); + int coarseTileBufferHeight = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseTileSize); + int binCoarseXYDispatchGroupSize = 8; // GROUP_SIZE in the shader cb._BoundedEntityCount = (uint)boundedEntityCount; + cb._BinCoarseXYDispatchGroupCountX = (uint)HDUtils.DivRoundUp(coarseTileBufferWidth, binCoarseXYDispatchGroupSize); cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; @@ -4178,7 +4198,9 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H cb._BoundedEntityOffsetPerCategory[i] = cb._BoundedEntityOffsetPerCategory[i - 1] + cb._BoundedEntityCountPerCategory[i - 1]; } - cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); + cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); + cb._CoarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + cb._FineTileBufferDimensions = GetFineTileBufferDimensions(hdCamera); // Old stuff below... cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 19e0e37c97f..bc8eb5bf957 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -128,7 +128,7 @@ CBUFFER_START(ShaderVariablesLightList) uint _DecalIndexShift; uint _DensityVolumeIndexShift; uint _ProbeVolumeIndexShift; - uint _Pad0_SVLL; + uint _BinCoarseXYDispatchGroupCountX; uint _Pad1_SVLL; CBUFFER_END diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index ba531730997..c3166938d7f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -80,14 +80,9 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) const uint eye = groupID.y; const uint cat = groupID.z; - const uint2 groupCount = uint2(DIV_ROUND_UP(_ScreenSize.x, GROUP_SIZE * COARSE_TILE_SIZE), - DIV_ROUND_UP(_ScreenSize.y, GROUP_SIZE * COARSE_TILE_SIZE)); - - const uint2 coarseTileBufferDimensions = 0; - - const uint2 groupCoord = CoordinateFromIndex(g, groupCount.x); + const uint2 groupCoord = CoordinateFromIndex(g, _BinCoarseXYDispatchGroupCountX); const uint2 tileCoord = groupCoord * GROUP_SIZE + t; - const uint2 clampedTileCoord = min(clampedTileCoord, coarseTileBufferDimensions - 1); // Stay within bounds + const uint2 clampedTileCoord = min(clampedTileCoord, (uint2)_CoarseTileBufferDimensions - 1); // Stay within bounds // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -106,11 +101,11 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge - const float3 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); - const float3 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); + const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); + const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, _BoundedEntityCount); - const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, coarseTileBufferDimensions.x, cat, eye); + const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, (uint)_CoarseTileBufferDimensions.x, cat, eye); // Define inputs and outputs. uint i = 0, j = 0; @@ -155,6 +150,8 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } else { + const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, (uint)_CoarseTileBufferDimensions.x, cat, eye); + // We do not clear the buffer, so we must add a terminator. _CoarseTileBuffer[outputStart] = UINT16_MAX; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 3d73c6fe0e2..2f3c821f302 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -33,7 +33,7 @@ unsafe struct ShaderVariablesGlobal public const int RenderingLightLayersMaskShift = 0; public const int RenderingDecalLayersMask = 0x0000FF00; public const int RenderingDecalLayersMaskShift = 8; - public const int DefaultRenderingLayerMask = 0x0101; + public const int DefaultRenderingLayerMask = 0x0101; // TODO: put commonly used vars together (below), and then sort them by the frequency of use (descending). // Note: a matrix is 4 * 4 * 4 = 64 bytes (1x cache line), so no need to sort those. @@ -204,7 +204,10 @@ unsafe struct ShaderVariablesGlobal [HLSLArray(((int)BoundedEntityCategory.Count + 3) / 4, typeof(ShaderGenUInt4))] public fixed uint _BoundedEntityOffsetPerCategory[(((int)BoundedEntityCategory.Count + 3) / 4) * 4]; - public Vector4 _ZBinBufferEncodingParams; + public Vector4 _ZBinBufferEncodingParams; + + public Vector2Int _CoarseTileBufferDimensions; + public Vector2Int _FineTileBufferDimensions; public uint _NumTileFtplX; public uint _NumTileFtplY; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 6c6c0d2b24c..6d61a71f78d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -112,6 +112,8 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) uint4 _BoundedEntityCountPerCategory[2]; uint4 _BoundedEntityOffsetPerCategory[2]; float4 _ZBinBufferEncodingParams; + int2 _CoarseTileBufferDimensions; + int2 _FineTileBufferDimensions; uint _NumTileFtplX; uint _NumTileFtplY; float g_fClustScale; From 5e051dcf11e8178c022fa1920df4e2b029f93182 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 8 Oct 2020 12:02:50 -0700 Subject: [PATCH 036/209] Fix near plane issues --- .../Runtime/Lighting/LightLoop/scrbound.compute | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 4720a700062..893816a051e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -729,9 +729,14 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + // Reminder: Z-binning uses n=0.1 as the near plane. + // Therefore, we must make sure the entities behind the near plane + // are assigned to the first bin. + ndcAaBbMinPt.w = max(ndcAaBbMinPt.w, 0.1); + ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, 0.1); + if (!isHelperThread && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { - _xyBoundsBuffer[bufferIndex] = float4(ndcAaBbMinPt.x, ndcAaBbMaxPt.x, ndcAaBbMinPt.y, ndcAaBbMaxPt.y); _wBoundsBuffer[bufferIndex] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); } From dbacfd56e0e77c5e7f548db6682e9d6cae375efc Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 8 Oct 2020 16:57:12 -0700 Subject: [PATCH 037/209] Feed the shader --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 76 ++++++++++++------- .../Runtime/Lighting/LightLoop/xybin.compute | 8 +- .../RenderPipeline/HDStringConstants.cs | 2 + .../RenderPipeline/RenderPipelineResources.cs | 2 + 4 files changed, 55 insertions(+), 33 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 9f6b5906e3d..a11cb5c7818 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -711,6 +711,9 @@ class TileAndClusterData public ComputeBuffer bigTileLightList { get; private set; } // Volumetric public ComputeBuffer perVoxelLightLists { get; private set; } // Cluster + // Z-Binning + public ComputeBuffer coarseTileBuffer { get; private set; } + public bool listsAreClear = false; public bool clusterNeedsDepth { get; private set; } @@ -770,10 +773,19 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, bigTileLightList = new ComputeBuffer(TiledLightingConstants.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint)); } - // The bounds and light volumes are view-dependent, and AABB is additionally projection dependent. + // These are not resolution-dependent at all, but the old code allocated them here... xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, x_max, y_min, y_max} wBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 2 * sizeof(float)); // {w_min, w_max} - zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_ZBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | count} + zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_ZBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | end} + + Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + + int coarseTileBufferElementCount = coarseTileBufferDimensions.x * coarseTileBufferDimensions.y * + (int)BoundedEntityCategory.Count * viewCount * + (TiledLightingConstants.s_CoarseTileEntityLimit / 2); + + // Actually resolution-dependent buffers below. + coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // List of 16-bit indices // Make sure to invalidate the content of the buffers listsAreClear = false; @@ -813,13 +825,15 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() CoreUtils.SafeRelease(bigTileLightList); bigTileLightList = null; - // LightList building + // Z-binning CoreUtils.SafeRelease(xyBoundsBuffer); xyBoundsBuffer = null; CoreUtils.SafeRelease(wBoundsBuffer); wBoundsBuffer = null; CoreUtils.SafeRelease(zBinBuffer); zBinBuffer = null; + CoreUtils.SafeRelease(coarseTileBuffer); + coarseTileBuffer = null; CoreUtils.SafeRelease(dispatchIndirectBuffer); dispatchIndirectBuffer = null; } @@ -892,6 +906,7 @@ static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) ComputeShader buildScreenAABBShader { get { return defaultResources.shaders.buildScreenAABBCS; } } ComputeShader zBinShader { get { return defaultResources.shaders.zBinCS; } } + ComputeShader xyBinShader { get { return defaultResources.shaders.xyBinCS; } } ComputeShader buildPerTileLightListShader { get { return defaultResources.shaders.buildPerTileLightListCS; } } ComputeShader buildPerBigTileLightListShader { get { return defaultResources.shaders.buildPerBigTileLightListCS; } } ComputeShader buildPerVoxelLightListShader { get { return defaultResources.shaders.buildPerVoxelLightListCS; } } @@ -1040,7 +1055,7 @@ static Vector4 GetZBinBufferEncodingParams(HDCamera hdCamera) static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseTileSize); return new Vector2Int(w, h); @@ -1048,7 +1063,7 @@ static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) static Vector2Int GetFineTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineTileSize); return new Vector2Int(w, h); @@ -3444,11 +3459,11 @@ struct BuildGPULightListParameters public ComputeShader clearLightListCS; public int clearLightListKernel; - // Screen Space AABBs - public ComputeShader screenSpaceAABBShader; - // Z-binning + public ComputeShader screenSpaceAABBShader; public ComputeShader zBinShader; + public ComputeShader xyBinShader; + public Vector2Int coarseTileBufferDimensions; // Big Tile public ComputeShader bigTilePrepassShader; @@ -3493,6 +3508,7 @@ struct BuildGPULightListResources public ComputeBuffer xyBoundsBuffer; public ComputeBuffer wBoundsBuffer; public ComputeBuffer zBinBuffer; + public ComputeBuffer coarseTileBuffer; public ComputeBuffer globalLightListAtomic; // Output @@ -3522,6 +3538,7 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.xyBoundsBuffer = tileAndClusterData.xyBoundsBuffer; resources.wBoundsBuffer = tileAndClusterData.wBoundsBuffer; resources.zBinBuffer = tileAndClusterData.zBinBuffer; + resources.coarseTileBuffer = tileAndClusterData.coarseTileBuffer; //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; @@ -3578,12 +3595,12 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); - int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int threadsPerEntity = 4; // Shader: THREADS_PER_ENTITY (4) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerEntity = 4; // Shader: THREADS_PER_ENTITY (4) int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount * threadsPerEntity, threadsPerGroup); - cmd.DispatchCompute(shader, kernel, groupCount, parameters.viewCount, 1); + cmd.DispatchCompute(shader, kernel, groupCount, 1, parameters.viewCount); } } } @@ -3601,7 +3618,7 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); - int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); @@ -3614,21 +3631,22 @@ static void PerformXYBinning(in BuildGPULightListParameters parameters, in Build // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformZBinning))) { - var shader = parameters.zBinShader; + var shader = parameters.xyBinShader; int kernel; kernel = 0; // BinCoarseXY - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._wBoundsBuffer, resources.wBoundsBuffer); - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._zBinBuffer, resources.zBinBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); - int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int groupSize = 8; // Shader: GROUP_SIZE (8) - int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(parameters.coarseTileBufferDimensions.x, groupSize) + * HDUtils.DivRoundUp(parameters.coarseTileBufferDimensions.y, groupSize); - // cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); + cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); kernel = 1; // PruneCoarseXY @@ -3888,15 +3906,15 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera } } - var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); - + var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); int boundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); - int coarseTileBufferWidth = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); - int coarseTileBufferHeight = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseTileSize); - int binCoarseXYDispatchGroupSize = 8; // GROUP_SIZE in the shader + + Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + + const int binCoarseXYDispatchGroupSize = 8; // GROUP_SIZE in the shader cb._BoundedEntityCount = (uint)boundedEntityCount; - cb._BinCoarseXYDispatchGroupCountX = (uint)HDUtils.DivRoundUp(coarseTileBufferWidth, binCoarseXYDispatchGroupSize); + cb._BinCoarseXYDispatchGroupCountX = (uint)HDUtils.DivRoundUp(coarseTileBufferDimensions.x, binCoarseXYDispatchGroupSize); cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; @@ -3957,11 +3975,11 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.clearLightListCS = defaultResources.shaders.clearLightListsCS; parameters.clearLightListKernel = parameters.clearLightListCS.FindKernel("ClearList"); - // Screen space AABB - parameters.screenSpaceAABBShader = buildScreenAABBShader; - - // Screen space AABB - parameters.zBinShader = zBinShader; + // Z-binning + parameters.screenSpaceAABBShader = buildScreenAABBShader; + parameters.zBinShader = zBinShader; + parameters.xyBinShader = xyBinShader; + parameters.coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); // Big tile prepass parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index c3166938d7f..5ce34e8fb75 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -17,7 +17,7 @@ #if (PASS == BIN_COARSE_XY) // 1x list for all entites (sorted by category, we concatenate lists of all views). - RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, x_max, y_min, y_max} + StructuredBuffer _xyBoundsBuffer : register(t0); // {x_min, x_max, y_min, y_max} #endif /* ------------------------------ Outputs ----------------------------------- */ @@ -77,12 +77,12 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { const uint2 t = threadID.xy; // 8x8 block for locality (reduce divergence) const uint g = groupID.x; - const uint eye = groupID.y; - const uint cat = groupID.z; + const uint cat = groupID.y; + const uint eye = groupID.z; const uint2 groupCoord = CoordinateFromIndex(g, _BinCoarseXYDispatchGroupCountX); const uint2 tileCoord = groupCoord * GROUP_SIZE + t; - const uint2 clampedTileCoord = min(clampedTileCoord, (uint2)_CoarseTileBufferDimensions - 1); // Stay within bounds + const uint2 clampedTileCoord = min(tileCoord, (uint2)_CoarseTileBufferDimensions - 1); // Stay within bounds // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 48a6b85be1b..124591e0eee 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -97,6 +97,8 @@ static class HDShaderIDs public static readonly int _xyBoundsBuffer = Shader.PropertyToID("_xyBoundsBuffer"); public static readonly int _wBoundsBuffer = Shader.PropertyToID("_wBoundsBuffer"); public static readonly int _zBinBuffer = Shader.PropertyToID("_zBinBuffer"); + public static readonly int _CoarseTileBuffer = Shader.PropertyToID("_CoarseTileBuffer"); + public static readonly int _FineTileBuffer = Shader.PropertyToID("_FineTileBuffer"); public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); public static readonly int _EntityBoundsBuffer = Shader.PropertyToID("_EntityBoundsBuffer"); public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs index f0e80af0c2d..596e6ad623d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs @@ -61,6 +61,8 @@ public sealed class ShaderResources public ComputeShader buildScreenAABBCS; [Reload("Runtime/Lighting/LightLoop/zbin.compute")] public ComputeShader zBinCS; + [Reload("Runtime/Lighting/LightLoop/xybin.compute")] + public ComputeShader xyBinCS; [Reload("Runtime/Lighting/LightLoop/lightlistbuild.compute")] public ComputeShader buildPerTileLightListCS; // FPTL [Reload("Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute")] From 1eeecabe6a0e957a838fe1e98c4f68362ff59990 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 8 Oct 2020 18:09:01 -0700 Subject: [PATCH 038/209] Add the right marker --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 2 +- .../Runtime/RenderPipeline/HDProfileId.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index a11cb5c7818..5382ae11317 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3629,7 +3629,7 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG static void PerformXYBinning(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformZBinning))) + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformXYBinning))) { var shader = parameters.xyBinShader; int kernel; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 06d5c77d7f5..09aac9b2580 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -20,6 +20,7 @@ internal enum HDProfileId BuildLightList, GenerateLightAABBs, PerformZBinning, + PerformXYBinning, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, From 1a28ade3fdfb84dbf6e3457ba65308c535d7f73d Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 8 Oct 2020 18:14:40 -0700 Subject: [PATCH 039/209] Bugfix --- .../Lighting/LightLoop/scrbound.compute | 6 ++--- .../Runtime/Lighting/LightLoop/xybin.compute | 23 ++++++++++--------- .../Runtime/Lighting/LightLoop/zbin.compute | 4 ++-- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 893816a051e..eccb91daf4f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -423,10 +423,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { const uint t = threadID; const uint g = groupID.x; - const uint eye = groupID.y; + const uint eye = groupID.z; const uint intraGroupEntityIndex = t / THREADS_PER_ENTITY; - const uint globalEntityIndex = g * ENTITIES_PER_GROUP + intraGroupEntityIndex; + const uint globalEntityIndex = IndexFromCoordinate(uint2(intraGroupEntityIndex, g), ENTITIES_PER_GROUP); const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; const uint clampedEntityIndex = min(globalEntityIndex, _BoundedEntityCount - 1); // Stay within bounds @@ -434,7 +434,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // but do not store the results of the computation to memory. const bool isHelperThread = globalEntityIndex != clampedEntityIndex; - const uint bufferIndex = ComputeEntityBoundsBufferIndex(clampedEntityIndex, _BoundedEntityCount); + const uint bufferIndex = ComputeEntityBoundsBufferIndex(clampedEntityIndex, eye); const FiniteLightBound cullData = _EntityBoundsBuffer[bufferIndex]; const float4x4 projMat = g_mProjectionArr[eye]; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index 5ce34e8fb75..4d4c64f3236 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -45,11 +45,13 @@ uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); } -uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint tileRowSize, uint category, uint eye) +uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint category, uint eye) { - uint stride = COARSE_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + uint rowSize = _CoarseTileBufferDimensions.x; + uint stride = COARSE_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + return stride * IndexFromCoordinate(uint4(tileCoord, category, eye), - uint3(tileRowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(rowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } // The intervals must be defined s.t. @@ -69,10 +71,9 @@ bool IntervalsOverlap(float2 i1, float2 i2) #error "COARSE_TILE_ENTITY_LIMIT must be an integer multiple of 2." #endif -#define GROUP_SIZE (8) -#define THREADS_PER_GROUP (GROUP_SIZE * GROUP_SIZE) +#define GROUP_SIZE (8) -[numthreads(THREADS_PER_GROUP, 1, 1)] +[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { const uint2 t = threadID.xy; // 8x8 block for locality (reduce divergence) @@ -104,8 +105,8 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); - const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, _BoundedEntityCount); - const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, (uint)_CoarseTileBufferDimensions.x, cat, eye); + const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); + const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, cat, eye); // Define inputs and outputs. uint i = 0, j = 0; @@ -150,20 +151,20 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } else { - const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, (uint)_CoarseTileBufferDimensions.x, cat, eye); + const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, cat, eye); // We do not clear the buffer, so we must add a terminator. _CoarseTileBuffer[outputStart] = UINT16_MAX; } } -[numthreads(THREADS_PER_GROUP, 1, 1)] +[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] void PruneCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } -[numthreads(THREADS_PER_GROUP, 1, 1)] +[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] void BinFineXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 4cd686fe401..d455d0884f5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -90,12 +90,12 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint entityIndex = s_BoundedEntityOffsetPerCategory[cat]; const uint entityCount = s_BoundedEntityCountPerCategory[cat]; - uint first = (1 << 16), last = 0; + uint first = UINT16_MAX, last = 0; if (entityCount > 0) // Avoid wasted work { const float2 binBoundsW = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); - const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, _BoundedEntityCount); + const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. // Therefore, it will be slow if 'n' is large. From f66809706ceaa30ab1b4bed560e4785c2cacac57 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 9 Oct 2020 00:41:12 -0700 Subject: [PATCH 040/209] Better fix --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 4 +++- .../Runtime/Lighting/LightLoop/scrbound.compute | 6 ------ .../Runtime/Lighting/LightLoop/zbin.compute | 14 ++++++++++++-- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 5382ae11317..e5f12286ec6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -1045,6 +1045,8 @@ static Vector4 GetZBinBufferEncodingParams(HDCamera hdCamera) float n = 0.1f; float f = hdCamera.camera.farClipPlane; // Assume XR uses the same far plane for all views + f = Mathf.Max(f, 0.11f); // Avoid degenerate configurations + float x = n; float z = 1 / x; float y = Log2f(f * z); @@ -2589,7 +2591,7 @@ static int ComputeFixedPointLogDepth(float w, float f, int numBits = 16) // See https://zero-radiance.github.io/post/z-buffer/ const float n = 0.1f; - f = Math.Max(n, f); + f = Mathf.Max(f, 0.11f); // Avoid degenerate configurations float x = Mathf.Max(1, w * (1/n)); float z = Log2f(x) / Log2f(f * (1/n)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index eccb91daf4f..d9cc20d5b1c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -729,12 +729,6 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - // Reminder: Z-binning uses n=0.1 as the near plane. - // Therefore, we must make sure the entities behind the near plane - // are assigned to the first bin. - ndcAaBbMinPt.w = max(ndcAaBbMinPt.w, 0.1); - ndcAaBbMaxPt.w = max(ndcAaBbMaxPt.w, 0.1); - if (!isHelperThread && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { _xyBoundsBuffer[bufferIndex] = float4(ndcAaBbMinPt.x, ndcAaBbMaxPt.x, ndcAaBbMinPt.y, ndcAaBbMaxPt.y); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index d455d0884f5..6501ae4da2d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -54,8 +54,18 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) float2 bBounds = float2(bin, bin + 1); float2 zBounds = saturate(bBounds * rcp(ZBIN_COUNT)); - return float2(DecodeLogarithmicDepth(zBounds.x, encodingParams), - DecodeLogarithmicDepth(zBounds.y, encodingParams)); + float2 wBounds = float2(DecodeLogarithmicDepth(zBounds.x, encodingParams), + DecodeLogarithmicDepth(zBounds.y, encodingParams)); + + // Reminder: Z-binning uses n=0.1 as the near plane. + // In case the actual near plane is closer (or is oblique), + // we must extend the first bin to include the lights + // that are very close to the camera. + // Note that this will not cause the lights behind the near plane + // to be included, since they have invalid AABBs. + wBounds.x = (bin == 0) ? 0 : wBounds.x; + + return wBounds; } // The intervals must be defined s.t. From 6bf4f74a45067838c3f16057267e043b8494492a Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 12 Oct 2020 17:42:26 -0700 Subject: [PATCH 041/209] Remove thread block grouping --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 9 +++--- .../Runtime/Lighting/LightLoop/xybin.compute | 31 ++++++++++--------- .../Runtime/Lighting/LightLoop/zbin.compute | 1 + 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index e5f12286ec6..d091d250a18 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -532,7 +532,7 @@ unsafe struct ShaderVariablesLightList public uint _DensityVolumeIndexShift; public uint _ProbeVolumeIndexShift; - public uint _BinCoarseXYDispatchGroupCountX; + public uint _Pad0_SVLL; public uint _Pad1_SVLL; } @@ -3643,10 +3643,10 @@ static void PerformXYBinning(in BuildGPULightListParameters parameters, in Build ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); - const int groupSize = 8; // Shader: GROUP_SIZE (8) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int groupCount = HDUtils.DivRoundUp(parameters.coarseTileBufferDimensions.x, groupSize) - * HDUtils.DivRoundUp(parameters.coarseTileBufferDimensions.y, groupSize); + int bufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; + int groupCount = HDUtils.DivRoundUp(bufferSize, threadsPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); @@ -3916,7 +3916,6 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera const int binCoarseXYDispatchGroupSize = 8; // GROUP_SIZE in the shader cb._BoundedEntityCount = (uint)boundedEntityCount; - cb._BinCoarseXYDispatchGroupCountX = (uint)HDUtils.DivRoundUp(coarseTileBufferDimensions.x, binCoarseXYDispatchGroupSize); cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); cb.g_isOrthographic = camera.orthographic ? 1u : 0u; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index 4d4c64f3236..4062f6350d9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -71,23 +71,26 @@ bool IntervalsOverlap(float2 i1, float2 i2) #error "COARSE_TILE_ENTITY_LIMIT must be an integer multiple of 2." #endif -#define GROUP_SIZE (8) +#define THREADS_PER_GROUP (64) -[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] -void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) +[numthreads(THREADS_PER_GROUP, 1, 1)] +void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { - const uint2 t = threadID.xy; // 8x8 block for locality (reduce divergence) - const uint g = groupID.x; - const uint cat = groupID.y; - const uint eye = groupID.z; - - const uint2 groupCoord = CoordinateFromIndex(g, _BinCoarseXYDispatchGroupCountX); - const uint2 tileCoord = groupCoord * GROUP_SIZE + t; - const uint2 clampedTileCoord = min(tileCoord, (uint2)_CoarseTileBufferDimensions - 1); // Stay within bounds + // We could tile the threads in 8x8 blocks. The problem is, + // the size of the buffer is already quite small. The extra padding + // (helper threads) required outweights the benefits (reduced divergence). + const uint t = threadID; + const uint g = groupID.x; + const uint cat = groupID.y; + const uint eye = groupID.z; + + const uint tileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); + const uint clampedTileIndex = min(tileIndex, (uint)(_CoarseTileBufferDimensions.x * _CoarseTileBufferDimensions.y - 1)); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, (uint)_CoarseTileBufferDimensions.x); // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. - const bool isHelperThread = any(tileCoord != clampedTileCoord); + const bool isHelperThread = tileIndex != clampedTileIndex; if (isHelperThread) return; // Avoid adding too many checks or branches below @@ -158,13 +161,13 @@ void BinCoarseXY(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } } -[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] +[numthreads(THREADS_PER_GROUP, 1, 1)] void PruneCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } -[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] +[numthreads(THREADS_PER_GROUP, 1, 1)] void BinFineXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 6501ae4da2d..8016518906e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -94,6 +94,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint g = groupID.x; const uint cat = groupID.y; const uint eye = groupID.z; + const uint bin = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); // Entities are sorted by category. From 42f2cbad0271bae59ea1612d48e90ffdf3f13945 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 12 Oct 2020 17:48:19 -0700 Subject: [PATCH 042/209] Manually edit the HLSL file... --- .../Runtime/Lighting/LightLoop/LightLoop.cs.hlsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index bc8eb5bf957..19e0e37c97f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -128,7 +128,7 @@ CBUFFER_START(ShaderVariablesLightList) uint _DecalIndexShift; uint _DensityVolumeIndexShift; uint _ProbeVolumeIndexShift; - uint _BinCoarseXYDispatchGroupCountX; + uint _Pad0_SVLL; uint _Pad1_SVLL; CBUFFER_END From 7891197daa18889f81e33299a235677da14a4b2a Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 12 Oct 2020 18:06:45 -0700 Subject: [PATCH 043/209] Delete --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index d091d250a18..1dad084f641 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3913,8 +3913,6 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); - const int binCoarseXYDispatchGroupSize = 8; // GROUP_SIZE in the shader - cb._BoundedEntityCount = (uint)boundedEntityCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. cb.g_viDimensions = new Vector2Int((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y); From 38a29e8078891bf86afef4f248a071bf91169605 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 12 Oct 2020 18:31:14 -0700 Subject: [PATCH 044/209] Share more code --- .../LightLoop/TilingAndBinningUtilities.hlsl | 123 ++++++++++++++++++ .../TilingAndBinningUtilities.hlsl.meta | 10 ++ .../Lighting/LightLoop/scrbound.compute | 80 +----------- .../Runtime/Lighting/LightLoop/xybin.compute | 31 +---- .../Runtime/Lighting/LightLoop/zbin.compute | 38 +----- 5 files changed, 141 insertions(+), 141 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl new file mode 100644 index 00000000000..96980273868 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -0,0 +1,123 @@ +#ifndef UNITY_TILINGANDBINNINGUTILITIES_INCLUDED +#define UNITY_TILINGANDBINNINGUTILITIES_INCLUDED + +// The HLSL preprocessor does not support the '%' operator. +#define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) + +// Returns the location of the N-th set bit starting from the lowest order bit and working upward. +// Slow implementation - do not use for large bit sets. +// Could be optimized - see https://graphics.stanford.edu/~seander/bithacks.html +uint NthBitLow(uint value, uint n) +{ + uint b = -1; // Consistent with the behavior of firstbitlow() + uint c = countbits(value); + + if (n < c) // Validate inputs + { + uint r = n + 1; // Compute the number of remaining bits + + do + { + uint f = firstbitlow(value >> (b + 1)); // Find the next set bit + b += f + r; // Make a guess (assume all [b+f+1,b+f+r] bits are set) + c = countbits(value << (32 - (b + 1))); // Count the number of bits actually set + r = (n + 1) - c; // Compute the number of remaining bits + } while (r > 0); + } + + return b; +} + +float4x4 Translation4x4(float3 d) +{ + float4x4 M = k_identity4x4; + + M._14_24_34 = d; // Last column + + return M; +} + +// Scale followed by rotation (scaled axes). +float3x3 ScaledRotation3x3(float3 xAxis, float3 yAxis, float3 zAxis) +{ + float3x3 R = float3x3(xAxis, yAxis, zAxis); + float3x3 C = transpose(R); // Row to column + + return C; +} + +float3x3 Invert3x3(float3x3 R) +{ + float3x3 C = transpose(R); // Row to column + float det = dot(C[0], cross(C[1], C[2])); + float3x3 adj = float3x3(cross(C[1], C[2]), + cross(C[2], C[0]), + cross(C[0], C[1])); + return rcp(det) * adj; +} + +float4x4 Homogenize3x3(float3x3 R) +{ + float4x4 M = float4x4(float4(R[0], 0), + float4(R[1], 0), + float4(R[2], 0), + float4(0,0,0,1)); + return M; +} + +float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) +{ + float b = (f + n) * rcp(f - n); // Z in [-1, 1] + float c = -2 * f * n * rcp(f - n); // No Z-reversal + + return float4x4(g/a, 0, 0, 0, + 0, g, 0, 0, + 0, 0, b, c, + 0, 0, 1, 0); +} + +// The intervals must be defined s.t. +// the 'x' component holds the lower bound and +// the 'y' component holds the upper bound. +bool IntervalsOverlap(float2 i1, float2 i2) +{ + float l = max(i1.x, i2.x); // Lower bound of the intersection interval + float u = min(i1.y, i2.y); // Upper bound of the intersection interval + + return l <= u; // Is the interval non-empty? +} + +uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) +{ + return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); +} + +// TODO: should we move '_CoarseTileBufferDimensions' to 'LightLoop.cs.hlsl'? +#ifndef NO_SHADERVARIABLESGLOBAL_HLSL + +uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint category, uint eye) +{ + uint rowSize = (uint)_CoarseTileBufferDimensions.x; + uint stride = COARSE_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + + return stride * IndexFromCoordinate(uint4(tileCoord, category, eye), + uint3(rowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + +uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) +{ + return IndexFromCoordinate(uint3(bin, category, eye), + uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + +uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) +{ + float z = EncodeLogarithmicDepth(w, encodingParams); + z = saturate(z); // Clamp to the region between the near and the far planes + + return min((uint)(z * ZBIN_COUNT), ZBIN_COUNT - 1); +} + +#endif // NO_SHADERVARIABLESGLOBAL_HLSL + +#endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED \ No newline at end of file diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl.meta new file mode 100644 index 00000000000..222698b99d9 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: edd1049f42df45e4791840dd443e6a03 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index d9cc20d5b1c..f047581e0e3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -6,6 +6,9 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" +#define NO_SHADERVARIABLESGLOBAL_HLSL +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" +#undef NO_SHADERVARIABLESGLOBAL_HLSL /* ------------------------------ Inputs ------------------------------------ */ @@ -20,83 +23,6 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} /* ------------------------------ Utilities --------------------------------- */ -// Returns the location of the N-th set bit starting from the lowest order bit and working upward. -// Slow implementation - do not use for large bit sets. -// Could be optimized - see https://graphics.stanford.edu/~seander/bithacks.html -uint NthBitLow(uint value, uint n) -{ - uint b = -1; // Consistent with the behavior of firstbitlow() - uint c = countbits(value); - - if (n < c) // Validate inputs - { - uint r = n + 1; // Compute the number of remaining bits - - do - { - uint f = firstbitlow(value >> (b + 1)); // Find the next set bit - b += f + r; // Make a guess (assume all [b+f+1,b+f+r] bits are set) - c = countbits(value << (32 - (b + 1))); // Count the number of bits actually set - r = (n + 1) - c; // Compute the number of remaining bits - } while (r > 0); - } - - return b; -} - -float4x4 Translation4x4(float3 d) -{ - float4x4 M = k_identity4x4; - - M._14_24_34 = d; // Last column - - return M; -} - -// Scale followed by rotation (scaled axes). -float3x3 ScaledRotation3x3(float3 xAxis, float3 yAxis, float3 zAxis) -{ - float3x3 R = float3x3(xAxis, yAxis, zAxis); - float3x3 C = transpose(R); // Row to column - - return C; -} - -float3x3 Invert3x3(float3x3 R) -{ - float3x3 C = transpose(R); // Row to column - float det = dot(C[0], cross(C[1], C[2])); - float3x3 adj = float3x3(cross(C[1], C[2]), - cross(C[2], C[0]), - cross(C[0], C[1])); - return rcp(det) * adj; -} - -float4x4 Homogenize3x3(float3x3 R) -{ - float4x4 M = float4x4(float4(R[0], 0), - float4(R[1], 0), - float4(R[2], 0), - float4(0,0,0,1)); - return M; -} - -float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) -{ - float b = (f + n) * rcp(f - n); // Z in [-1, 1] - float c = -2 * f * n * rcp(f - n); // No Z-reversal - - return float4x4(g/a, 0, 0, 0, - 0, g, 0, 0, - 0, 0, b, c, - 0, 0, 1, 0); -} - -uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) -{ - return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); -} - /* ------------------------------ Implementation ---------------------------- */ // Improve the quality of generated code at the expense of readability. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index 4062f6350d9..ce9cf1b2c37 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -10,8 +10,9 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -33,38 +34,10 @@ /* ------------------------------ Utilities --------------------------------- */ -// The HLSL preprocessor does not support the '%' operator. -#define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) - // Repackage to work around ridiculous constant buffer limitations of HLSL. static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; -uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) -{ - return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); -} - -uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint category, uint eye) -{ - uint rowSize = _CoarseTileBufferDimensions.x; - uint stride = COARSE_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' - - return stride * IndexFromCoordinate(uint4(tileCoord, category, eye), - uint3(rowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); -} - -// The intervals must be defined s.t. -// the 'x' component holds the lower bound and -// the 'y' component holds the upper bound. -bool IntervalsOverlap(float2 i1, float2 i2) -{ - float l = max(i1.x, i2.x); // Lower bound of the intersection interval - float u = min(i1.y, i2.y); // Upper bound of the intersection interval - - return l <= u; // Is the interval non-empty? -} - /* ------------------------------ Implementation ---------------------------- */ #if (REMAINDER(COARSE_TILE_ENTITY_LIMIT, 2) != 0) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 8016518906e..b396d08f9ab 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -5,8 +5,9 @@ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -23,31 +24,11 @@ RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} /* ------------------------------ Utilities --------------------------------- */ -// The HLSL preprocessor does not support the '%' operator. -#define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) - // Repackage to work around ridiculous constant buffer limitations of HLSL. static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; -uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) -{ - return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); -} - -uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) -{ - return IndexFromCoordinate(uint3(bin, category, eye), - uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); -} - -uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) -{ - float z = EncodeLogarithmicDepth(w, encodingParams); - z = saturate(z); // Clamp to the region between the near and the far planes - - return min((uint)(z * ZBIN_COUNT), ZBIN_COUNT - 1); -} +/* ------------------------------ Implementation ---------------------------- */ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) { @@ -68,19 +49,6 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) return wBounds; } -// The intervals must be defined s.t. -// the 'x' component holds the lower bound and -// the 'y' component holds the upper bound. -bool IntervalsOverlap(float2 i1, float2 i2) -{ - float l = max(i1.x, i2.x); // Lower bound of the intersection interval - float u = min(i1.y, i2.y); // Upper bound of the intersection interval - - return l <= u; // Is the interval non-empty? -} - -/* ------------------------------ Implementation ---------------------------- */ - #define THREADS_PER_GROUP (64) #if (REMAINDER(ZBIN_COUNT, THREADS_PER_GROUP) != 0) From 3861d9aa68971ab90bd1d55eb4c63e69f6f2cf34 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 12 Oct 2020 18:42:38 -0700 Subject: [PATCH 045/209] Comment --- .../Runtime/Lighting/LightLoop/scrbound.compute | 4 ++-- .../Runtime/Lighting/LightLoop/xybin.compute | 10 +++++----- .../Runtime/Lighting/LightLoop/zbin.compute | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index f047581e0e3..d36c7550cd9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -439,7 +439,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // 0 <= y <= w <-- include boundary points to avoid clipping them later // 0 <= z <= w // w is always valid - // TODO: epsilon for numerical robustness? + // TODO: add epsilon for numerical robustness? for (uint j = 0; j < (NUM_PLANES / 2); j++) { @@ -531,7 +531,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // -w < y < w <-- exclude boundary points, as we will not clip using these vertices // -w < z < w <-- assume that Z-precision is not very important here // 0 < w - // TODO: epsilon for numerical robustness? + // TODO: add epsilon for numerical robustness? bool inside = Max3(abs(hapVertLS.x), abs(hapVertLS.y), abs(hapVertLS.z)) < hapVertLS.w; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute index ce9cf1b2c37..a594cceeb56 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute @@ -75,11 +75,11 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // Compute 2-D the AABB of the tile. const uint2 tileAaBbMinPtSS = clampedTileCoord * COARSE_TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_TILE_SIZE - const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide - const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge - const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); - const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_TILE_SIZE + const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide + const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? + const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); // TODO: add epsilon for numerical robustness? const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, cat, eye); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index b396d08f9ab..5bc21c1fb39 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -46,7 +46,7 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) // to be included, since they have invalid AABBs. wBounds.x = (bin == 0) ? 0 : wBounds.x; - return wBounds; + return wBounds; // TODO: add epsilon for numerical robustness? } #define THREADS_PER_GROUP (64) @@ -73,7 +73,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if (entityCount > 0) // Avoid wasted work { - const float2 binBoundsW = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); + const float2 binBounds = ComputeZBinLinearDepthBounds(bin, _ZBinBufferEncodingParams); const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. @@ -82,10 +82,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // TODO: unroll. for (uint i = 0; i < entityCount; i++) { - float2 entityBoundsW = _wBoundsBuffer[inputStart + i]; + float2 entityBounds = _wBoundsBuffer[inputStart + i]; // TODO: flatten. - if (IntervalsOverlap(entityBoundsW, binBoundsW)) + if (IntervalsOverlap(entityBounds, binBounds)) { // We store intra-category indices. first = min(i, first); From aa988272112f239e8f6ae607f3bb4c34528143a2 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 13 Oct 2020 18:04:14 -0700 Subject: [PATCH 046/209] Start working on the binned lighting API --- .../ShaderLibrary/Common.hlsl | 3 + .../Runtime/Lighting/LightLoop/LightLoop.cs | 4 +- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 558 ++++++++---------- .../Lighting/LightLoop/LightLoopDef.hlsl | 178 ++---- .../LightLoop/ShaderVariablesLightLoop.hlsl | 14 +- .../LightLoop/TilingAndBinningUtilities.hlsl | 24 +- .../VolumeVoxelization.compute | 24 +- .../RenderPipeline/HDStringConstants.cs | 2 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 2 +- .../ShaderVariablesGlobal.cs.hlsl | 2 +- 10 files changed, 353 insertions(+), 458 deletions(-) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index 8a81fe0f108..7e91661ebd2 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1039,6 +1039,9 @@ struct PositionInputs uint2 tileCoord; // Screen tile coordinates : [0, NumTiles) float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed) float linearDepth; // View space Z coordinate : [Near, Far] + + uint xyTile; + uint zBin; }; // This function is use to provide an easy way to sample into a screen texture, either from a pixel or a compute shaders. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 1dad084f641..d9f8ace1daa 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -4188,7 +4188,7 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H cb._DirectionalLightCount = (uint)m_DirectionalLightData.Count; cb._PunctualLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight); cb._AreaLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight); - cb._EnvLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe); + cb._ReflectionProbeCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe); cb._DecalCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal); // cb._DensityVolumeCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume); @@ -4244,7 +4244,7 @@ void PushLightDataGlobalParams(CommandBuffer cmd) cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightData, m_DirectionalLightDataBuffer); cmd.SetGlobalBuffer(HDShaderIDs._PunctualLightData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.PunctualLight)); cmd.SetGlobalBuffer(HDShaderIDs._AreaLightData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.AreaLight)); - cmd.SetGlobalBuffer(HDShaderIDs._EnvLightData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.ReflectionProbe)); + cmd.SetGlobalBuffer(HDShaderIDs._ReflectionProbeData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.ReflectionProbe)); cmd.SetGlobalBuffer(HDShaderIDs._DecalData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.Decal)); cmd.SetGlobalBuffer(HDShaderIDs._DensityVolumeData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.DensityVolume)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 3c95fc626b1..32f705f787d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -223,6 +223,8 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS } } + uint i; // Declare once to avoid the D3D11 compiler warning. + // This struct is define in the material. the Lightloop must not access it // PostEvaluateBSDF call at the end will convert Lighting to diffuse and specular lighting AggregateLighting aggregateLighting; @@ -230,323 +232,265 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS if (featureFlags & LIGHTFEATUREFLAGS_PUNCTUAL) { - uint lightCount, lightStart; - -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - GetCountAndStart(posInput, LIGHTCATEGORY_PUNCTUAL, lightStart, lightCount); -#else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - lightCount = _PunctualLightCount; - lightStart = 0; -#endif - - bool fastPath = false; - #if SCALARIZE_LIGHT_LOOP - uint lightStartLane0; - fastPath = IsFastPath(lightStart, lightStartLane0); - - if (fastPath) - { - lightStart = lightStartLane0; - } - #endif - - // Scalarized loop. All lights that are in a tile/cluster touched by any pixel in the wave are loaded (scalar load), only the one relevant to current thread/pixel are processed. - // For clarity, the following code will follow the convention: variables starting with s_ are meant to be wave uniform (meant for scalar register), - // v_ are variables that might have different value for each thread in the wave (meant for vector registers). - // This will perform more loads than it is supposed to, however, the benefits should offset the downside, especially given that light data accessed should be largely coherent. - // Note that the above is valid only if wave intriniscs are supported. - uint v_lightListOffset = 0; - uint v_lightIdx = lightStart; - - while (v_lightListOffset < lightCount) - { - v_lightIdx = FetchIndex(lightStart, v_lightListOffset); -#if SCALARIZE_LIGHT_LOOP - uint s_lightIdx = ScalarizeElementIndex(v_lightIdx, fastPath); -#else - uint s_lightIdx = v_lightIdx; -#endif - if (s_lightIdx == -1) - break; - - LightData s_lightData = FetchLight(s_lightIdx); - - // If current scalar and vector light index match, we process the light. The v_lightListOffset for current thread is increased. - // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could - // end up with a unique v_lightIdx value that is smaller than s_lightIdx hence being stuck in a loop. All the active lanes will not have this problem. - if (s_lightIdx >= v_lightIdx) - { - v_lightListOffset++; - if (IsMatchingLightLayer(s_lightData.lightLayers, builtinData.renderingLayers)) - { - DirectLighting lighting = EvaluateBSDF_Punctual(context, V, posInput, preLightData, s_lightData, bsdfData, builtinData); - AccumulateDirectLighting(lighting, aggregateLighting); - } - } - } - } - - - // Define macro for a better understanding of the loop - // TODO: this code is now much harder to understand... -#define EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) \ - IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightData, bsdfData, envLightData.influenceShapeType, MERGE_NAME(GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), MERGE_NAME(type, HierarchyWeight)); \ - AccumulateIndirectLighting(lighting, aggregateLighting); - -// Environment cubemap test lightlayers, sky don't test it -#define EVALUATE_BSDF_ENV(envLightData, TYPE, type) if (IsMatchingLightLayer(envLightData.lightLayers, builtinData.renderingLayers)) { EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) } - - // First loop iteration - if (featureFlags & (LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_SSREFRACTION | LIGHTFEATUREFLAGS_SSREFLECTION)) - { - float reflectionHierarchyWeight = 0.0; // Max: 1.0 - float refractionHierarchyWeight = _EnableSSRefraction ? 0.0 : 1.0; // Max: 1.0 - - uint envLightStart, envLightCount; - - // Fetch first env light to provide the scene proxy for screen space computation -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - GetCountAndStart(posInput, LIGHTCATEGORY_ENV, envLightStart, envLightCount); -#else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - envLightCount = _EnvLightCount; - envLightStart = 0; -#endif - - bool fastPath = false; - #if SCALARIZE_LIGHT_LOOP - uint envStartFirstLane; - fastPath = IsFastPath(envLightStart, envStartFirstLane); - #endif - - // Reflection / Refraction hierarchy is - // 1. Screen Space Refraction / Reflection - // 2. Environment Reflection / Refraction - // 3. Sky Reflection / Refraction - - // Apply SSR. - #if (defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR_TRANSPARENT)) || (!defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR)) - { - IndirectLighting indirect = EvaluateBSDF_ScreenSpaceReflection(posInput, preLightData, bsdfData, - reflectionHierarchyWeight); - AccumulateIndirectLighting(indirect, aggregateLighting); - } - #endif - - EnvLightData envLightData; - if (envLightCount > 0) - { - envLightData = FetchEnvLight(envLightStart, 0); - } - else - { - envLightData = InitSkyEnvLightData(0); - } - - if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (_EnableSSRefraction > 0)) - { - IndirectLighting lighting = EvaluateBSDF_ScreenspaceRefraction(context, V, posInput, preLightData, bsdfData, envLightData, refractionHierarchyWeight); - AccumulateIndirectLighting(lighting, aggregateLighting); - } - - // Reflection probes are sorted by volume (in the increasing order). - if (featureFlags & LIGHTFEATUREFLAGS_ENV) - { - context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES; - - #if SCALARIZE_LIGHT_LOOP - if (fastPath) - { - envLightStart = envStartFirstLane; - } - #endif - - // Scalarized loop, same rationale of the punctual light version - uint v_envLightListOffset = 0; - uint v_envLightIdx = envLightStart; - while (v_envLightListOffset < envLightCount) - { - v_envLightIdx = FetchIndex(envLightStart, v_envLightListOffset); - uint s_envLightIdx = ScalarizeElementIndex(v_envLightIdx, fastPath); - if (s_envLightIdx == -1) - break; - - EnvLightData s_envLightData = FetchEnvLight(s_envLightIdx); // Scalar load. - - // If current scalar and vector light index match, we process the light. The v_envLightListOffset for current thread is increased. - // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could - // end up with a unique v_envLightIdx value that is smaller than s_envLightIdx hence being stuck in a loop. All the active lanes will not have this problem. - if (s_envLightIdx >= v_envLightIdx) - { - v_envLightListOffset++; - if (reflectionHierarchyWeight < 1.0) - { - EVALUATE_BSDF_ENV(s_envLightData, REFLECTION, reflection); - } - // Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation - // However it is hard to deal with the fact that reflectionHierarchyWeight and refractionHierarchyWeight have not the same values, they are independent - // The refraction probe is rarely used and happen only with sphere shape and high IOR. So we accept the slow path that use more simple code and - // doesn't affect the performance of the reflection which is more important. - // We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be a waste to not use screen and only cubemap. - if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) - { - EVALUATE_BSDF_ENV(s_envLightData, REFRACTION, refraction); - } - } + LightData lightData; - } - } - - // Only apply the sky IBL if the sky texture is available - if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled) - { - // The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression) - context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY; - - // The sky data are generated on the fly so the compiler can optimize the code - EnvLightData envLightSky = InitSkyEnvLightData(0); - - // Only apply the sky if we haven't yet accumulated enough IBL lighting. - if (reflectionHierarchyWeight < 1.0) - { - EVALUATE_BSDF_ENV_SKY(envLightSky, REFLECTION, reflection); - } + i = 0; - if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) - { - EVALUATE_BSDF_ENV_SKY(envLightSky, REFRACTION, refraction); - } - } - } -#undef EVALUATE_BSDF_ENV -#undef EVALUATE_BSDF_ENV_SKY - - uint i = 0; // Declare once to avoid the D3D11 compiler warning. - if (featureFlags & LIGHTFEATUREFLAGS_DIRECTIONAL) - { - for (i = 0; i < _DirectionalLightCount; ++i) + while (TryLoadPunctualLightData(i, posInput.xyTile, posInput.zBin, lightData)) { - if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, builtinData.renderingLayers)) + if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) { - DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightData[i], bsdfData, builtinData); + DirectLighting lighting = EvaluateBSDF_Punctual(context, V, posInput, preLightData, lightData, bsdfData, builtinData); AccumulateDirectLighting(lighting, aggregateLighting); } - } - } - -#if SHADEROPTIONS_AREA_LIGHTS - if (featureFlags & LIGHTFEATUREFLAGS_AREA) - { - uint lightCount, lightStart; - - #ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - GetCountAndStart(posInput, LIGHTCATEGORY_AREA, lightStart, lightCount); - #else - lightCount = _AreaLightCount; - lightStart = _PunctualLightCount; - #endif - - // COMPILER BEHAVIOR WARNING! - // If rectangle lights are before line lights, the compiler will duplicate light matrices in VGPR because they are used differently between the two types of lights. - // By keeping line lights first we avoid this behavior and save substantial register pressure. - // TODO: This is based on the current Lit.shader and can be different for any other way of implementing area lights, how to be generic and ensure performance ? - - if (lightCount > 0) - { - i = 0; - - uint last = lightCount - 1; - LightData lightData = FetchLight(lightStart, i); - - while (i <= last && lightData.lightType == GPULIGHTTYPE_TUBE) - { - lightData.lightType = GPULIGHTTYPE_TUBE; // Enforce constant propagation - lightData.cookieMode = COOKIEMODE_NONE; // Enforce constant propagation - - if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) - { - DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); - AccumulateDirectLighting(lighting, aggregateLighting); - } - - lightData = FetchLight(lightStart, min(++i, last)); - } - - while (i <= last) // GPULIGHTTYPE_RECTANGLE - { - lightData.lightType = GPULIGHTTYPE_RECTANGLE; // Enforce constant propagation - - if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) - { - DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); - AccumulateDirectLighting(lighting, aggregateLighting); - } - lightData = FetchLight(lightStart, min(++i, last)); - } + i++; } } -#endif - -#if SHADEROPTIONS_PROBE_VOLUMES_EVALUATION_MODE == PROBEVOLUMESEVALUATIONMODES_LIGHT_LOOP - bool uninitialized = IsUninitializedGI(builtinData.bakeDiffuseLighting); - builtinData.bakeDiffuseLighting = uninitialized ? float3(0.0, 0.0, 0.0) : builtinData.bakeDiffuseLighting; - - // If probe volume feature is enabled, this bit is enabled for all tiles to handle ambient probe fallback. - // No need to branch internally on _EnableProbeVolumes uniform. - if (featureFlags & LIGHTFEATUREFLAGS_PROBE_VOLUME) - { -#if !SHADEROPTIONS_PROBE_VOLUMES_ADDITIVE_BLENDING - if (uninitialized) -#endif - { - // Need to make sure not to apply ModifyBakedDiffuseLighting() twice to our bakeDiffuseLighting data, which could happen if we are dealing with initialized data (light maps). - // Create a local BuiltinData variable here, and then add results to builtinData.bakeDiffuseLighting at the end. - BuiltinData builtinDataProbeVolumes; - ZERO_INITIALIZE(BuiltinData, builtinDataProbeVolumes); - - float probeVolumeHierarchyWeight = uninitialized ? 0.0f : 1.0f; - - // Note: we aren't suppose to access normalWS in lightloop, but bsdfData.normalWS is always define for any material. So this is safe. - ProbeVolumeEvaluateSphericalHarmonics( - posInput, - bsdfData.normalWS, - -bsdfData.normalWS, - builtinData.renderingLayers, - probeVolumeHierarchyWeight, - builtinDataProbeVolumes.bakeDiffuseLighting, - builtinDataProbeVolumes.backBakeDiffuseLighting - ); - - // Apply control from the indirect lighting volume settings (Remember there is no emissive here at this step) - float indirectDiffuseMultiplier = GetIndirectDiffuseMultiplier(builtinData.renderingLayers); - builtinDataProbeVolumes.bakeDiffuseLighting *= indirectDiffuseMultiplier; - builtinDataProbeVolumes.backBakeDiffuseLighting *= indirectDiffuseMultiplier; - -#ifdef MODIFY_BAKED_DIFFUSE_LIGHTING -#ifdef DEBUG_DISPLAY - // When the lux meter is enabled, we don't want the albedo of the material to modify the diffuse baked lighting - if (_DebugLightingMode != DEBUGLIGHTINGMODE_LUX_METER) -#endif - ModifyBakedDiffuseLighting(V, posInput, preLightData, bsdfData, builtinDataProbeVolumes); - -#endif - -#if (SHADERPASS == SHADERPASS_DEFERRED_LIGHTING) - // If we are deferred we should apply baked AO here as it was already apply for lightmap. - // But in deferred ambientOcclusion is white so we should use specularOcclusion instead. It is the - // same case than for Microshadow so we can reuse this function. It should not be apply in forward - // as in this case the baked AO is correctly apply in PostBSDF() - // This is apply only on bakeDiffuseLighting as ModifyBakedDiffuseLighting combine both bakeDiffuseLighting and backBakeDiffuseLighting - builtinDataProbeVolumes.bakeDiffuseLighting *= GetAmbientOcclusionForMicroShadowing(bsdfData); -#endif - - ApplyDebugToBuiltinData(builtinDataProbeVolumes); - // Note: builtinDataProbeVolumes.bakeDiffuseLighting and builtinDataProbeVolumes.backBakeDiffuseLighting were combine inside of ModifyBakedDiffuseLighting(). - builtinData.bakeDiffuseLighting += builtinDataProbeVolumes.bakeDiffuseLighting; - } - } -#endif +// // Define macro for a better understanding of the loop +// // TODO: this code is now much harder to understand... +// #define EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) \ +// IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightData, bsdfData, envLightData.influenceShapeType, MERGE_NAME(GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), MERGE_NAME(type, HierarchyWeight)); \ +// AccumulateIndirectLighting(lighting, aggregateLighting); + +// // Environment cubemap test lightlayers, sky don't test it +// #define EVALUATE_BSDF_ENV(envLightData, TYPE, type) if (IsMatchingLightLayer(envLightData.lightLayers, builtinData.renderingLayers)) { EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) } + +// // First loop iteration +// if (featureFlags & (LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_SSREFRACTION | LIGHTFEATUREFLAGS_SSREFLECTION)) +// { +// float reflectionHierarchyWeight = 0.0; // Max: 1.0 +// float refractionHierarchyWeight = _EnableSSRefraction ? 0.0 : 1.0; // Max: 1.0 + +// // Reflection / Refraction hierarchy is +// // 1. Screen Space Refraction / Reflection +// // 2. Environment Reflection / Refraction +// // 3. Sky Reflection / Refraction + +// // Apply SSR. +// #if (defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR_TRANSPARENT)) || (!defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR)) +// { +// IndirectLighting indirect = EvaluateBSDF_ScreenSpaceReflection(posInput, preLightData, bsdfData, +// reflectionHierarchyWeight); +// AccumulateIndirectLighting(indirect, aggregateLighting); +// } +// #endif + +// EnvLightData envLightData; +// if (envLightCount > 0) +// { +// envLightData = FetchEnvLight(envLightStart, 0); +// } +// else +// { +// envLightData = InitSkyEnvLightData(0); +// } + +// if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (_EnableSSRefraction > 0)) +// { +// IndirectLighting lighting = EvaluateBSDF_ScreenspaceRefraction(context, V, posInput, preLightData, bsdfData, envLightData, refractionHierarchyWeight); +// AccumulateIndirectLighting(lighting, aggregateLighting); +// } + +// // Reflection probes are sorted by volume (in the increasing order). +// if (featureFlags & LIGHTFEATUREFLAGS_ENV) +// { +// context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES; + +// #if SCALARIZE_LIGHT_LOOP +// if (fastPath) +// { +// envLightStart = envStartFirstLane; +// } +// #endif + +// // Scalarized loop, same rationale of the punctual light version +// uint v_envLightListOffset = 0; +// uint v_envLightIdx = envLightStart; +// while (v_envLightListOffset < envLightCount) +// { +// v_envLightIdx = FetchIndex(envLightStart, v_envLightListOffset); +// uint s_envLightIdx = ScalarizeElementIndex(v_envLightIdx, fastPath); +// if (s_envLightIdx == -1) +// break; + +// EnvLightData s_envLightData = FetchEnvLight(s_envLightIdx); // Scalar load. + +// // If current scalar and vector light index match, we process the light. The v_envLightListOffset for current thread is increased. +// // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could +// // end up with a unique v_envLightIdx value that is smaller than s_envLightIdx hence being stuck in a loop. All the active lanes will not have this problem. +// if (s_envLightIdx >= v_envLightIdx) +// { +// v_envLightListOffset++; +// if (reflectionHierarchyWeight < 1.0) +// { +// EVALUATE_BSDF_ENV(s_envLightData, REFLECTION, reflection); +// } +// // Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation +// // However it is hard to deal with the fact that reflectionHierarchyWeight and refractionHierarchyWeight have not the same values, they are independent +// // The refraction probe is rarely used and happen only with sphere shape and high IOR. So we accept the slow path that use more simple code and +// // doesn't affect the performance of the reflection which is more important. +// // We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be a waste to not use screen and only cubemap. +// if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) +// { +// EVALUATE_BSDF_ENV(s_envLightData, REFRACTION, refraction); +// } +// } + +// } +// } + +// // Only apply the sky IBL if the sky texture is available +// if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled) +// { +// // The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression) +// context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY; + +// // The sky data are generated on the fly so the compiler can optimize the code +// EnvLightData envLightSky = InitSkyEnvLightData(0); + +// // Only apply the sky if we haven't yet accumulated enough IBL lighting. +// if (reflectionHierarchyWeight < 1.0) +// { +// EVALUATE_BSDF_ENV_SKY(envLightSky, REFLECTION, reflection); +// } + +// if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) +// { +// EVALUATE_BSDF_ENV_SKY(envLightSky, REFRACTION, refraction); +// } +// } +// } +// #undef EVALUATE_BSDF_ENV +// #undef EVALUATE_BSDF_ENV_SKY + +// if (featureFlags & LIGHTFEATUREFLAGS_DIRECTIONAL) +// { +// for (i = 0; i < _DirectionalLightCount; ++i) +// { +// if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, builtinData.renderingLayers)) +// { +// DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightData[i], bsdfData, builtinData); +// AccumulateDirectLighting(lighting, aggregateLighting); +// } +// } +// } + +// #if SHADEROPTIONS_AREA_LIGHTS +// if (featureFlags & LIGHTFEATUREFLAGS_AREA) +// { +// uint lightCount, lightStart; + +// #ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER +// GetCountAndStart(posInput, LIGHTCATEGORY_AREA, lightStart, lightCount); +// #else +// lightCount = _AreaLightCount; +// lightStart = _PunctualLightCount; +// #endif + +// // COMPILER BEHAVIOR WARNING! +// // If rectangle lights are before line lights, the compiler will duplicate light matrices in VGPR because they are used differently between the two types of lights. +// // By keeping line lights first we avoid this behavior and save substantial register pressure. +// // TODO: This is based on the current Lit.shader and can be different for any other way of implementing area lights, how to be generic and ensure performance ? + +// if (lightCount > 0) +// { +// i = 0; + +// uint last = lightCount - 1; +// LightData lightData = FetchLight(lightStart, i); + +// while (i <= last && lightData.lightType == GPULIGHTTYPE_TUBE) +// { +// lightData.lightType = GPULIGHTTYPE_TUBE; // Enforce constant propagation +// lightData.cookieMode = COOKIEMODE_NONE; // Enforce constant propagation + +// if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) +// { +// DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); +// AccumulateDirectLighting(lighting, aggregateLighting); +// } + +// lightData = FetchLight(lightStart, min(++i, last)); +// } + +// while (i <= last) // GPULIGHTTYPE_RECTANGLE +// { +// lightData.lightType = GPULIGHTTYPE_RECTANGLE; // Enforce constant propagation + +// if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) +// { +// DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); +// AccumulateDirectLighting(lighting, aggregateLighting); +// } + +// lightData = FetchLight(lightStart, min(++i, last)); +// } +// } +// } +// #endif + +// #if SHADEROPTIONS_PROBE_VOLUMES_EVALUATION_MODE == PROBEVOLUMESEVALUATIONMODES_LIGHT_LOOP +// bool uninitialized = IsUninitializedGI(builtinData.bakeDiffuseLighting); +// builtinData.bakeDiffuseLighting = uninitialized ? float3(0.0, 0.0, 0.0) : builtinData.bakeDiffuseLighting; + +// // If probe volume feature is enabled, this bit is enabled for all tiles to handle ambient probe fallback. +// // No need to branch internally on _EnableProbeVolumes uniform. +// if (featureFlags & LIGHTFEATUREFLAGS_PROBE_VOLUME) +// { +// #if !SHADEROPTIONS_PROBE_VOLUMES_ADDITIVE_BLENDING +// if (uninitialized) +// #endif +// { +// // Need to make sure not to apply ModifyBakedDiffuseLighting() twice to our bakeDiffuseLighting data, which could happen if we are dealing with initialized data (light maps). +// // Create a local BuiltinData variable here, and then add results to builtinData.bakeDiffuseLighting at the end. +// BuiltinData builtinDataProbeVolumes; +// ZERO_INITIALIZE(BuiltinData, builtinDataProbeVolumes); + +// float probeVolumeHierarchyWeight = uninitialized ? 0.0f : 1.0f; + +// // Note: we aren't suppose to access normalWS in lightloop, but bsdfData.normalWS is always define for any material. So this is safe. +// ProbeVolumeEvaluateSphericalHarmonics( +// posInput, +// bsdfData.normalWS, +// -bsdfData.normalWS, +// builtinData.renderingLayers, +// probeVolumeHierarchyWeight, +// builtinDataProbeVolumes.bakeDiffuseLighting, +// builtinDataProbeVolumes.backBakeDiffuseLighting +// ); + +// // Apply control from the indirect lighting volume settings (Remember there is no emissive here at this step) +// float indirectDiffuseMultiplier = GetIndirectDiffuseMultiplier(builtinData.renderingLayers); +// builtinDataProbeVolumes.bakeDiffuseLighting *= indirectDiffuseMultiplier; +// builtinDataProbeVolumes.backBakeDiffuseLighting *= indirectDiffuseMultiplier; + +// #ifdef MODIFY_BAKED_DIFFUSE_LIGHTING +// #ifdef DEBUG_DISPLAY +// // When the lux meter is enabled, we don't want the albedo of the material to modify the diffuse baked lighting +// if (_DebugLightingMode != DEBUGLIGHTINGMODE_LUX_METER) +// #endif +// ModifyBakedDiffuseLighting(V, posInput, preLightData, bsdfData, builtinDataProbeVolumes); + +// #endif + +// #if (SHADERPASS == SHADERPASS_DEFERRED_LIGHTING) +// // If we are deferred we should apply baked AO here as it was already apply for lightmap. +// // But in deferred ambientOcclusion is white so we should use specularOcclusion instead. It is the +// // same case than for Microshadow so we can reuse this function. It should not be apply in forward +// // as in this case the baked AO is correctly apply in PostBSDF() +// // This is apply only on bakeDiffuseLighting as ModifyBakedDiffuseLighting combine both bakeDiffuseLighting and backBakeDiffuseLighting +// builtinDataProbeVolumes.bakeDiffuseLighting *= GetAmbientOcclusionForMicroShadowing(bsdfData); +// #endif + +// ApplyDebugToBuiltinData(builtinDataProbeVolumes); + +// // Note: builtinDataProbeVolumes.bakeDiffuseLighting and builtinDataProbeVolumes.backBakeDiffuseLighting were combine inside of ModifyBakedDiffuseLighting(). +// builtinData.bakeDiffuseLighting += builtinDataProbeVolumes.bakeDiffuseLighting; +// } +// } +// #endif #if !defined(_SURFACE_TYPE_TRANSPARENT) // If we use the texture ssgi for ssgi or rtgi, we want to combine it with the value in the bake diffuse lighting value diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 329e2d4d82d..8d80cf19ee6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -144,165 +144,99 @@ float4 SampleEnv(LightLoopContext lightLoopContext, int index, float3 texCoord, // Single Pass and Tile Pass // ---------------------------------------------------------------------------- -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" -// Calculate the offset in global light index light for current light category -int GetTileOffset(PositionInputs posInput, uint lightCategory) +// Careful, this may not work if 'TextureXR.hlsl' has not already been included. +uint GetEyeIndex() { - uint2 tileIndex = posInput.tileCoord; - return (tileIndex.y + lightCategory * _NumTileFtplY) * _NumTileFtplX + tileIndex.x; -} - -void GetCountAndStartTile(PositionInputs posInput, uint lightCategory, out uint start, out uint lightCount) -{ - int tileOffset = GetTileOffset(posInput, lightCategory); - #if defined(UNITY_STEREO_INSTANCING_ENABLED) - // Eye base offset must match code in lightlistbuild.compute - tileOffset += unity_StereoEyeIndex * _NumTileFtplX * _NumTileFtplY * LIGHTCATEGORY_COUNT; + return unity_StereoEyeIndex; +#else + return 0; #endif - - // The first entry inside a tile is the number of light for lightCategory (thus the +0) - lightCount = g_vLightListGlobal[DWORD_PER_TILE * tileOffset + 0] & 0xffff; - start = tileOffset; } -#ifdef USE_FPTL_LIGHTLIST +#ifdef LIGHTLOOP_COARSE_BINNED_LIGHTING -uint GetTileSize() -{ - return TILE_SIZE_FPTL; -} - -void GetCountAndStart(PositionInputs posInput, uint lightCategory, out uint start, out uint lightCount) -{ - GetCountAndStartTile(posInput, lightCategory, start, lightCount); -} - -uint FetchIndex(uint tileOffset, uint lightOffset) -{ - const uint lightOffsetPlusOne = lightOffset + 1; // Add +1 as first slot is reserved to store number of light - // Light index are store on 16bit - return (g_vLightListGlobal[DWORD_PER_TILE * tileOffset + (lightOffsetPlusOne >> 1)] >> ((lightOffsetPlusOne & 1) * DWORD_PER_TILE)) & 0xffff; -} +#elif defined(LIGHTLOOP_FINE_BINNED_LIGHTING) -#elif defined(USE_CLUSTERED_LIGHTLIST) +/* ... */ -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClusteredUtils.hlsl" +#else // !(defined(LIGHTLOOP_COARSE_BINNED_LIGHTING) || defined(LIGHTLOOP_FINE_BINNED_LIGHTING)) -uint GetTileSize() +bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data) { - return TILE_SIZE_CLUSTERED; -} + bool b = false; + uint n = _PunctualLightCount; -uint GetLightClusterIndex(uint2 tileIndex, float linearDepth) -{ - float logBase = g_fClustBase; - if (g_isLogBaseBufferEnabled) + if (i < n) { - const uint logBaseIndex = GenerateLogBaseBufferIndex(tileIndex, _NumTileClusteredX, _NumTileClusteredY, unity_StereoEyeIndex); - logBase = g_logBaseBuffer[logBaseIndex]; + data = _PunctualLightData[i]; + b = true; } - return SnapToClusterIdxFlex(linearDepth, logBase, g_isLogBaseBufferEnabled != 0); -} - -void GetCountAndStartCluster(uint2 tileIndex, uint clusterIndex, uint lightCategory, out uint start, out uint lightCount) -{ - int nrClusters = (1 << g_iLog2NumClusters); - - const int idx = GenerateLayeredOffsetBufferIndex(lightCategory, tileIndex, clusterIndex, _NumTileClusteredX, _NumTileClusteredY, nrClusters, unity_StereoEyeIndex); - - uint dataPair = g_vLayeredOffsetsBuffer[idx]; - start = dataPair & 0x7ffffff; - lightCount = (dataPair >> 27) & 31; + return b; } -void GetCountAndStartCluster(PositionInputs posInput, uint lightCategory, out uint start, out uint lightCount) +bool TryLoadAreaLightData(uint i, uint xyTile, uint zBin, out LightData data) { - // Note: XR depends on unity_StereoEyeIndex already being defined, - // which means ShaderVariables.hlsl needs to be defined ahead of this! - - uint2 tileIndex = posInput.tileCoord; - uint clusterIndex = GetLightClusterIndex(tileIndex, posInput.linearDepth); - - GetCountAndStartCluster(tileIndex, clusterIndex, lightCategory, start, lightCount); -} - -void GetCountAndStart(PositionInputs posInput, uint lightCategory, out uint start, out uint lightCount) -{ - GetCountAndStartCluster(posInput, lightCategory, start, lightCount); -} + bool b = false; + uint n = _AreaLightCount; -uint FetchIndex(uint lightStart, uint lightOffset) -{ - return g_vLightListGlobal[lightStart + lightOffset]; -} - -#elif defined(USE_BIG_TILE_LIGHTLIST) + if (i < n) + { + data = _AreaLightData[i]; + b = true; + } -uint FetchIndex(uint lightStart, uint lightOffset) -{ - return g_vBigTileLightList[lightStart + lightOffset]; + return b; } -#else -// Fallback case (mainly for raytracing right now) -uint FetchIndex(uint lightStart, uint lightOffset) +bool TryLoadReflectionProbeData(uint i, uint xyTile, uint zBin, out EnvLightData data) { - return 0; -} -#endif // USE_FPTL_LIGHTLIST + bool b = false; + uint n = _ReflectionProbeCount; -#else + if (i < n) + { + data = _ReflectionProbeData[i]; + b = true; + } -uint GetTileSize() -{ - return 1; + return b; } -uint FetchIndex(uint lightStart, uint lightOffset) +bool TryLoadDecalData(uint i, uint xyTile, uint zBin, out DecalData data) { - return lightStart + lightOffset; -} + bool b = false; + uint n = _DecalCount; -#endif // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - -uint FetchIndexWithBoundsCheck(uint start, uint count, uint i) -{ - if (i < count) - { - return FetchIndex(start, i); - } - else + if (i < n) { - return UINT_MAX; + data = _DecalData[i]; + b = true; } -} - -LightData FetchLight(uint start, uint i) -{ - uint j = FetchIndex(start, i); - return _LightData[j]; + return b; } -LightData FetchLight(uint index) -{ - return _LightData[index]; -} +// bool TryLoadDensityVolumeDataDataAndBounds(uint i, uint xyTile, uint zBin, +// out DensityVolumeEngineData data, out OrientedBBox bounds) +// { +// bool b = false; +// uint n = _DensityVolumeCount; -EnvLightData FetchEnvLight(uint start, uint i) -{ - int j = FetchIndex(start, i); +// if (i < n) +// { +// data = _DensityVolumeData[i]; +// bounds = _DensityVolumeBounds[i]; +// b = true; +// } - return _EnvLightData[j]; -} +// return b; +// } -EnvLightData FetchEnvLight(uint index) -{ - return _EnvLightData[index]; -} +#endif // !(defined(LIGHTLOOP_COARSE_BINNED_LIGHTING) || defined(LIGHTLOOP_FINE_BINNED_LIGHTING)) // In the first 8 bits of the target we store the max fade of the contact shadows as a byte void UnpackContactShadowData(uint contactShadowData, out float fade, out uint mask) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index b8b24cad25a..9c6330d65e8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -11,9 +11,17 @@ StructuredBuffer g_logBaseBuffer; StructuredBuffer g_TileFeatureFlags; #endif -StructuredBuffer _DirectionalLightData; -StructuredBuffer _LightData; -StructuredBuffer _EnvLightData; +// Directional lights + 1x list per BoundedEntityCategory. +StructuredBuffer _DirectionalLightData; + +// NEVER ACCESS THESE DIRECTLY. +StructuredBuffer _PunctualLightData; +StructuredBuffer _AreaLightData; +StructuredBuffer _ReflectionProbeData; +// Defined elsewhere: +// StructuredBuffer _DecalData; +// StructuredBuffer _DensityVolumeData; +// StructuredBuffer _DensityVolumeBounds; // Used by directional and spot lights TEXTURE2D(_CookieAtlas); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 96980273868..0e151d0475e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -1,6 +1,12 @@ #ifndef UNITY_TILINGANDBINNINGUTILITIES_INCLUDED #define UNITY_TILINGANDBINNINGUTILITIES_INCLUDED +// REMOVE!!! +uint GetTileSize() +{ + return 16; +} + // The HLSL preprocessor does not support the '%' operator. #define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) @@ -92,6 +98,12 @@ uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); } +uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) +{ + return IndexFromCoordinate(uint3(bin, category, eye), + uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + // TODO: should we move '_CoarseTileBufferDimensions' to 'LightLoop.cs.hlsl'? #ifndef NO_SHADERVARIABLESGLOBAL_HLSL @@ -104,15 +116,9 @@ uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint category, uint eye) uint3(rowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } -uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) -{ - return IndexFromCoordinate(uint3(bin, category, eye), - uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); -} - -uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) +uint ComputeZBinFromLinearDepth(float w) { - float z = EncodeLogarithmicDepth(w, encodingParams); + float z = EncodeLogarithmicDepth(w, _ZBinBufferEncodingParams); z = saturate(z); // Clamp to the region between the near and the far planes return min((uint)(z * ZBIN_COUNT), ZBIN_COUNT - 1); @@ -120,4 +126,4 @@ uint ComputeZBinFromLinearDepth(float w, float4 encodingParams) #endif // NO_SHADERVARIABLESGLOBAL_HLSL -#endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED \ No newline at end of file +#endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index d23f6c17774..f38c14d21a7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -38,8 +38,8 @@ // Inputs & outputs //-------------------------------------------------------------------------------------------------- -StructuredBuffer _VolumeBounds; -StructuredBuffer _VolumeData; +StructuredBuffer _DensityVolumeBounds; +StructuredBuffer _DensityVolumeData; TEXTURE3D(_VolumeMaskAtlas); @@ -180,7 +180,7 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, Jitter uint volumeIndex = FetchIndex(volumeStart, volumeOffset); #endif - const OrientedBBox obb = _VolumeBounds[volumeIndex]; + const OrientedBBox obb = _DensityVolumeBounds[volumeIndex]; const float3x3 obbFrame = float3x3(obb.right, obb.up, cross(obb.up, obb.right)); const float3 obbExtents = float3(obb.extentX, obb.extentY, obb.extentZ); @@ -269,25 +269,25 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, Jitter float dist = t; overlapFraction *= ComputeFadeFactor(voxelCenterNDC, dist, - _VolumeData[volumeIndex].rcpPosFaceFade, - _VolumeData[volumeIndex].rcpNegFaceFade, - _VolumeData[volumeIndex].invertFade, - _VolumeData[volumeIndex].rcpDistFadeLen, - _VolumeData[volumeIndex].endTimesRcpDistFadeLen); + _DensityVolumeData[volumeIndex].rcpPosFaceFade, + _DensityVolumeData[volumeIndex].rcpNegFaceFade, + _DensityVolumeData[volumeIndex].invertFade, + _DensityVolumeData[volumeIndex].rcpDistFadeLen, + _DensityVolumeData[volumeIndex].endTimesRcpDistFadeLen); // Sample the volumeMask. - if (_VolumeData[volumeIndex].textureIndex != -1) + if (_DensityVolumeData[volumeIndex].textureIndex != -1) { float3 xDerivUVW = (0.5 * t) * voxelAxisRightBS * rcp(obbExtents); float3 yDerivUVW = (0.5 * t) * voxelAxisUpBS * rcp(obbExtents); float3 zDerivUVW = (0.5 * dt) * voxelAxisForwardBS * rcp(obbExtents); - overlapFraction *= SampleVolumeMask(_VolumeData[volumeIndex], voxelCenterNDC, xDerivUVW, yDerivUVW, zDerivUVW); + overlapFraction *= SampleVolumeMask(_DensityVolumeData[volumeIndex], voxelCenterNDC, xDerivUVW, yDerivUVW, zDerivUVW); } // There is an overlap. Sample the 3D texture, or load the constant value. - voxelScattering += overlapFraction * _VolumeData[volumeIndex].scattering; - voxelExtinction += overlapFraction * _VolumeData[volumeIndex].extinction; + voxelScattering += overlapFraction * _DensityVolumeData[volumeIndex].scattering; + voxelExtinction += overlapFraction * _DensityVolumeData[volumeIndex].extinction; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 124591e0eee..8b11ac35796 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -124,7 +124,7 @@ static class HDShaderIDs public static readonly int _PunctualLightCount = Shader.PropertyToID(nameof(_PunctualLightCount)); public static readonly int _AreaLightData = Shader.PropertyToID(nameof(_AreaLightData)); public static readonly int _AreaLightCount = Shader.PropertyToID(nameof(_AreaLightCount)); - public static readonly int _EnvLightData = Shader.PropertyToID(nameof(_EnvLightData)); + public static readonly int _ReflectionProbeData = Shader.PropertyToID(nameof(_ReflectionProbeData)); public static readonly int _EnvLightCount = Shader.PropertyToID(nameof(_EnvLightCount)); public static readonly int _DecalData = Shader.PropertyToID(nameof(_DecalData)); public static readonly int _DecalCount = Shader.PropertyToID(nameof(_DecalCount)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 2f3c821f302..e2711a41c8e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -165,7 +165,7 @@ unsafe struct ShaderVariablesGlobal public uint _DirectionalLightCount; public uint _PunctualLightCount; public uint _AreaLightCount; - public uint _EnvLightCount; + public uint _ReflectionProbeCount; public int _EnvLightSkyEnabled; public uint _CascadeShadowCount; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 6d61a71f78d..9a714e8bc94 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -84,7 +84,7 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) uint _DirectionalLightCount; uint _PunctualLightCount; uint _AreaLightCount; - uint _EnvLightCount; + uint _ReflectionProbeCount; int _EnvLightSkyEnabled; uint _CascadeShadowCount; int _DirectionalShadowIndex; From 34cdfd0204cf68fefe14761b5e3f821d229afe2a Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 13 Oct 2020 18:40:30 -0700 Subject: [PATCH 047/209] Rename: 'tile' -> 'xyTile' --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 91 ++++++++++--------- .../Lighting/LightLoop/LightLoop.cs.hlsl | 8 +- .../LightLoop/TilingAndBinningUtilities.hlsl | 11 +-- .../{xybin.compute => xyTile.compute} | 44 ++++----- ...xybin.compute.meta => xyTile.compute.meta} | 2 +- .../Runtime/Lighting/LightLoop/zbin.compute | 8 +- .../RenderPipeline/HDStringConstants.cs | 15 +-- .../RenderPipeline/RenderPipelineResources.cs | 6 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 4 +- .../ShaderVariablesGlobal.cs.hlsl | 4 +- 10 files changed, 97 insertions(+), 96 deletions(-) rename com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/{xybin.compute => xyTile.compute} (79%) rename com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/{xybin.compute.meta => xyTile.compute.meta} (81%) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index d9f8ace1daa..fbb2bc326ae 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -402,11 +402,11 @@ class TiledLightingConstants public static uint s_InvalidScreenSpaceShadow = 0xff; public static uint s_ScreenSpaceShadowIndexMask = 0xff; - // Z-binning - public static int s_CoarseTileEntityLimit = 64; // Before pruning, so, in practice, the number is lower - public static int s_CoarseTileSize = 64; - public static int s_FineTileSize = 8; - public static int s_ZBinCount = 8192; + // Binned lighting + public static int s_CoarseXyTileEntityLimit = 64; // Before pruning, so, in practice, the number is lower + public static int s_CoarseXyTileSize = 64; + public static int s_FineXyTileSize = 8; + public static int s_zBinCount = 8192; } [GenerateHLSL] @@ -711,8 +711,8 @@ class TileAndClusterData public ComputeBuffer bigTileLightList { get; private set; } // Volumetric public ComputeBuffer perVoxelLightLists { get; private set; } // Cluster - // Z-Binning - public ComputeBuffer coarseTileBuffer { get; private set; } + // Binned lighting + public ComputeBuffer coarseXyTileBuffer { get; private set; } public bool listsAreClear = false; @@ -776,16 +776,16 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, // These are not resolution-dependent at all, but the old code allocated them here... xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, x_max, y_min, y_max} wBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 2 * sizeof(float)); // {w_min, w_max} - zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_ZBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | end} + zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_zBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | end} - Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + Vector2Int coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); - int coarseTileBufferElementCount = coarseTileBufferDimensions.x * coarseTileBufferDimensions.y * - (int)BoundedEntityCategory.Count * viewCount * - (TiledLightingConstants.s_CoarseTileEntityLimit / 2); + int coarseXyTileBufferElementCount = coarseXyTileBufferDimensions.x * coarseXyTileBufferDimensions.y * + (int)BoundedEntityCategory.Count * viewCount * + (TiledLightingConstants.s_CoarseXyTileEntityLimit / 2); // Actually resolution-dependent buffers below. - coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // List of 16-bit indices + coarseXyTileBuffer = new ComputeBuffer(coarseXyTileBufferElementCount, sizeof(uint)); // List of 16-bit indices // Make sure to invalidate the content of the buffers listsAreClear = false; @@ -825,15 +825,15 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() CoreUtils.SafeRelease(bigTileLightList); bigTileLightList = null; - // Z-binning + // Binned lighting CoreUtils.SafeRelease(xyBoundsBuffer); xyBoundsBuffer = null; CoreUtils.SafeRelease(wBoundsBuffer); wBoundsBuffer = null; CoreUtils.SafeRelease(zBinBuffer); zBinBuffer = null; - CoreUtils.SafeRelease(coarseTileBuffer); - coarseTileBuffer = null; + CoreUtils.SafeRelease(coarseXyTileBuffer); + coarseXyTileBuffer = null; CoreUtils.SafeRelease(dispatchIndirectBuffer); dispatchIndirectBuffer = null; } @@ -906,7 +906,7 @@ static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) ComputeShader buildScreenAABBShader { get { return defaultResources.shaders.buildScreenAABBCS; } } ComputeShader zBinShader { get { return defaultResources.shaders.zBinCS; } } - ComputeShader xyBinShader { get { return defaultResources.shaders.xyBinCS; } } + ComputeShader xyTileShader { get { return defaultResources.shaders.xyTileCS; } } ComputeShader buildPerTileLightListShader { get { return defaultResources.shaders.buildPerTileLightListCS; } } ComputeShader buildPerBigTileLightListShader { get { return defaultResources.shaders.buildPerBigTileLightListCS; } } ComputeShader buildPerVoxelLightListShader { get { return defaultResources.shaders.buildPerVoxelLightListCS; } } @@ -1055,18 +1055,18 @@ static Vector4 GetZBinBufferEncodingParams(HDCamera hdCamera) return new Vector4(x, y, z, w); } - static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) + static Vector2Int GetCoarseXyTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); - int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseTileSize); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseXyTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseXyTileSize); return new Vector2Int(w, h); } - static Vector2Int GetFineTileBufferDimensions(HDCamera hdCamera) + static Vector2Int GetFineXyTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); - int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineTileSize); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineXyTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineXyTileSize); return new Vector2Int(w, h); } @@ -3461,11 +3461,11 @@ struct BuildGPULightListParameters public ComputeShader clearLightListCS; public int clearLightListKernel; - // Z-binning + // Binned lighting public ComputeShader screenSpaceAABBShader; public ComputeShader zBinShader; - public ComputeShader xyBinShader; - public Vector2Int coarseTileBufferDimensions; + public ComputeShader xyTileShader; + public Vector2Int coarseXyTileBufferDimensions; // Big Tile public ComputeShader bigTilePrepassShader; @@ -3510,7 +3510,7 @@ struct BuildGPULightListResources public ComputeBuffer xyBoundsBuffer; public ComputeBuffer wBoundsBuffer; public ComputeBuffer zBinBuffer; - public ComputeBuffer coarseTileBuffer; + public ComputeBuffer coarseXyTileBuffer; public ComputeBuffer globalLightListAtomic; // Output @@ -3540,7 +3540,7 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.xyBoundsBuffer = tileAndClusterData.xyBoundsBuffer; resources.wBoundsBuffer = tileAndClusterData.wBoundsBuffer; resources.zBinBuffer = tileAndClusterData.zBinBuffer; - resources.coarseTileBuffer = tileAndClusterData.coarseTileBuffer; + resources.coarseXyTileBuffer = tileAndClusterData.coarseXyTileBuffer; //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; @@ -3622,7 +3622,7 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_ZBinCount, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_zBinCount, threadsPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); } @@ -3633,28 +3633,28 @@ static void PerformXYBinning(in BuildGPULightListParameters parameters, in Build // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformXYBinning))) { - var shader = parameters.xyBinShader; + var shader = parameters.xyTileShader; int kernel; - kernel = 0; // BinCoarseXY + kernel = 0; // FillCoarseXyTile - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseXyTileBuffer, resources.coarseXyTileBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int bufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; + int bufferSize = parameters.coarseXyTileBufferDimensions.x * parameters.coarseXyTileBufferDimensions.y; int groupCount = HDUtils.DivRoundUp(bufferSize, threadsPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); - kernel = 1; // PruneCoarseXY + kernel = 1; // PruneCoarseXyTile // ... - kernel = 2; // BinFineXY + kernel = 2; // BuildFineXyTile // ... } @@ -3911,7 +3911,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); int boundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); - Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + Vector2Int coarseTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); cb._BoundedEntityCount = (uint)boundedEntityCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. @@ -3974,11 +3974,11 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.clearLightListCS = defaultResources.shaders.clearLightListsCS; parameters.clearLightListKernel = parameters.clearLightListCS.FindKernel("ClearList"); - // Z-binning - parameters.screenSpaceAABBShader = buildScreenAABBShader; - parameters.zBinShader = zBinShader; - parameters.xyBinShader = xyBinShader; - parameters.coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + // Binned lighting + parameters.screenSpaceAABBShader = buildScreenAABBShader; + parameters.zBinShader = zBinShader; + parameters.xyTileShader = xyTileShader; + parameters.coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); // Big tile prepass parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); @@ -4215,9 +4215,10 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H cb._BoundedEntityOffsetPerCategory[i] = cb._BoundedEntityOffsetPerCategory[i - 1] + cb._BoundedEntityCountPerCategory[i - 1]; } - cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); - cb._CoarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); - cb._FineTileBufferDimensions = GetFineTileBufferDimensions(hdCamera); + // Binned lighting + cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); + cb._CoarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); + cb._FineXyTileBufferDimensions = GetFineXyTileBufferDimensions(hdCamera); // Old stuff below... cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 19e0e37c97f..d87bdda381f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -70,10 +70,10 @@ #define SCREEN_SPACE_COLOR_SHADOW_FLAG (256) #define INVALID_SCREEN_SPACE_SHADOW (255) #define SCREEN_SPACE_SHADOW_INDEX_MASK (255) -#define COARSE_TILE_ENTITY_LIMIT (64) -#define COARSE_TILE_SIZE (64) -#define FINE_TILE_SIZE (8) -#define ZBIN_COUNT (8192) +#define COARSE_XY_TILE_ENTITY_LIMIT (64) +#define COARSE_XY_TILE_SIZE (64) +#define FINE_XY_TILE_SIZE (8) +#define Z_BIN_COUNT (8192) // // UnityEngine.Rendering.HighDefinition.ClusterDebugMode: static fields diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 0e151d0475e..90bec310ba5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -101,19 +101,18 @@ uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) { return IndexFromCoordinate(uint3(bin, category, eye), - uint2(ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + uint2(Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } -// TODO: should we move '_CoarseTileBufferDimensions' to 'LightLoop.cs.hlsl'? #ifndef NO_SHADERVARIABLESGLOBAL_HLSL uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint category, uint eye) { - uint rowSize = (uint)_CoarseTileBufferDimensions.x; - uint stride = COARSE_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + uint rowSize = (uint)_CoarseXyTileBufferDimensions.x; + uint stride = COARSE_XY_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' return stride * IndexFromCoordinate(uint4(tileCoord, category, eye), - uint3(rowSize, ZBIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(rowSize, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } uint ComputeZBinFromLinearDepth(float w) @@ -121,7 +120,7 @@ uint ComputeZBinFromLinearDepth(float w) float z = EncodeLogarithmicDepth(w, _ZBinBufferEncodingParams); z = saturate(z); // Clamp to the region between the near and the far planes - return min((uint)(z * ZBIN_COUNT), ZBIN_COUNT - 1); + return min((uint)(z * Z_BIN_COUNT), Z_BIN_COUNT - 1); } #endif // NO_SHADERVARIABLESGLOBAL_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute similarity index 79% rename from com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute rename to com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute index a594cceeb56..2f802059bc9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute @@ -2,11 +2,11 @@ #pragma only_renderers d3d11 playstation xboxone vulkan metal switch // Generates large screen tiles in a fast, conservative manner -#pragma kernel BinCoarseXY PASS = BIN_COARSE_XY +#pragma kernel FillCoarseXyTile PASS = FILL_COARSE_XY_TILE // Removes certain entities from the coarse buffer at a large cost -#pragma kernel PruneCoarseXY PASS = PRUNE_COARSE_XY +#pragma kernel PruneCoarseXyTile PASS = PRUNE_COARSE_XY_TILE // Generates small screen tiles in an accurate manner -#pragma kernel BinFineXY PASS = BIN_FINE_XY +#pragma kernel BuildFineXyTile PASS = BUILD_FINE_XY_TILE #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" @@ -16,20 +16,20 @@ /* ------------------------------ Inputs ------------------------------------ */ -#if (PASS == BIN_COARSE_XY) +#if (PASS == FILL_COARSE_XY_TILE) // 1x list for all entites (sorted by category, we concatenate lists of all views). StructuredBuffer _xyBoundsBuffer : register(t0); // {x_min, x_max, y_min, y_max} #endif /* ------------------------------ Outputs ----------------------------------- */ -#if (PASS == BIN_COARSE_XY) +#if (PASS == FILL_COARSE_XY_TILE) // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: - // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_TILE_ENTITY_LIMIT * 2 bytes per entry). + // DIV_ROUND_UP(RES_X, COARSE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_XY_TILE_SIZE) * + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_XY_TILE_ENTITY_LIMIT * 2 bytes per entry). // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. - RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 16-bit indices + RWStructuredBuffer _CoarseXyTileBuffer : register(u0); // List of 16-bit indices #endif /* ------------------------------ Utilities --------------------------------- */ @@ -40,14 +40,14 @@ static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin /* ------------------------------ Implementation ---------------------------- */ -#if (REMAINDER(COARSE_TILE_ENTITY_LIMIT, 2) != 0) - #error "COARSE_TILE_ENTITY_LIMIT must be an integer multiple of 2." +#if (REMAINDER(COARSE_XY_TILE_ENTITY_LIMIT, 2) != 0) + #error "COARSE_XY_TILE_ENTITY_LIMIT must be an integer multiple of 2." #endif #define THREADS_PER_GROUP (64) [numthreads(THREADS_PER_GROUP, 1, 1)] -void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // We could tile the threads in 8x8 blocks. The problem is, // the size of the buffer is already quite small. The extra padding @@ -58,8 +58,8 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint eye = groupID.z; const uint tileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); - const uint clampedTileIndex = min(tileIndex, (uint)(_CoarseTileBufferDimensions.x * _CoarseTileBufferDimensions.y - 1)); - const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, (uint)_CoarseTileBufferDimensions.x); + const uint clampedTileIndex = min(tileIndex, (uint)(_CoarseXyTileBufferDimensions.x * _CoarseXyTileBufferDimensions.y - 1)); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, (uint)_CoarseXyTileBufferDimensions.x); // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -74,8 +74,8 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if (entityCount > 0) // Avoid wasted work { // Compute 2-D the AABB of the tile. - const uint2 tileAaBbMinPtSS = clampedTileCoord * COARSE_TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_TILE_SIZE + const uint2 tileAaBbMinPtSS = clampedTileCoord * COARSE_XY_TILE_SIZE; + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_XY_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_XY_TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? @@ -92,7 +92,7 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // Therefore, it will be slow if 'n' is large. // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). // TODO: unroll. - while ((i < entityCount) && (j < COARSE_TILE_ENTITY_LIMIT)) + while ((i < entityCount) && (j < COARSE_XY_TILE_ENTITY_LIMIT)) { float2 entityBoundsX = _xyBoundsBuffer[inputStart + i].xy; float2 entityBoundsY = _xyBoundsBuffer[inputStart + i].zw; @@ -106,7 +106,7 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if ((j & 1) != 0) // Is the pair complete & ready to be stored? { - _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; + _CoarseXyTileBuffer[outputStart + (j / 2)] = indexPair; indexPair = 0; // In order to use bitwise OR above } @@ -117,12 +117,12 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) i++; } - if (j < COARSE_TILE_ENTITY_LIMIT) + if (j < COARSE_XY_TILE_ENTITY_LIMIT) { // Add a terminator. indexPair |= UINT16_MAX << (16 * (j & 1)); // Order: first Lo, then Hi bits - _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; + _CoarseXyTileBuffer[outputStart + (j / 2)] = indexPair; } } else @@ -130,18 +130,18 @@ void BinCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, cat, eye); // We do not clear the buffer, so we must add a terminator. - _CoarseTileBuffer[outputStart] = UINT16_MAX; + _CoarseXyTileBuffer[outputStart] = UINT16_MAX; } } [numthreads(THREADS_PER_GROUP, 1, 1)] -void PruneCoarseXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void PruneCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } [numthreads(THREADS_PER_GROUP, 1, 1)] -void BinFineXY(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void BuildFineXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute.meta similarity index 81% rename from com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta rename to com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute.meta index 5d94f12a2aa..ac5cc8d5ac2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xybin.compute.meta +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 8ccaf15991ce0ec48a2adfc5c8d930de +guid: ecd07937befe9614d90276f5d8609b3e ComputeShaderImporter: externalObjects: {} currentAPIMask: 2097156 diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 5bc21c1fb39..d599b6ca649 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -18,7 +18,7 @@ StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: -// ZBIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (4 bytes per range). +// Z_BIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (4 bytes per range). // For example (1080p): 8192 * 5 * 1 * 4 = 160 KiB. RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} @@ -33,7 +33,7 @@ static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) { float2 bBounds = float2(bin, bin + 1); - float2 zBounds = saturate(bBounds * rcp(ZBIN_COUNT)); + float2 zBounds = saturate(bBounds * rcp(Z_BIN_COUNT)); float2 wBounds = float2(DecodeLogarithmicDepth(zBounds.x, encodingParams), DecodeLogarithmicDepth(zBounds.y, encodingParams)); @@ -51,8 +51,8 @@ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) #define THREADS_PER_GROUP (64) -#if (REMAINDER(ZBIN_COUNT, THREADS_PER_GROUP) != 0) - #error "ZBIN_COUNT must be an integer multiple of THREADS_PER_GROUP." +#if (REMAINDER(Z_BIN_COUNT, THREADS_PER_GROUP) != 0) + #error "Z_BIN_COUNT must be an integer multiple of THREADS_PER_GROUP." #endif [numthreads(THREADS_PER_GROUP, 1, 1)] diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 8b11ac35796..5e7af1bff10 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -94,14 +94,15 @@ static class HDShaderIDs public static readonly int g_vBigTileLightList = Shader.PropertyToID("g_vBigTileLightList"); public static readonly int g_vLightListGlobal = Shader.PropertyToID("g_vLightListGlobal"); public static readonly int g_logBaseBuffer = Shader.PropertyToID("g_logBaseBuffer"); - public static readonly int _xyBoundsBuffer = Shader.PropertyToID("_xyBoundsBuffer"); - public static readonly int _wBoundsBuffer = Shader.PropertyToID("_wBoundsBuffer"); - public static readonly int _zBinBuffer = Shader.PropertyToID("_zBinBuffer"); - public static readonly int _CoarseTileBuffer = Shader.PropertyToID("_CoarseTileBuffer"); - public static readonly int _FineTileBuffer = Shader.PropertyToID("_FineTileBuffer"); - public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); - public static readonly int _EntityBoundsBuffer = Shader.PropertyToID("_EntityBoundsBuffer"); public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList"); + public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); + + public static readonly int _EntityBoundsBuffer = Shader.PropertyToID(nameof(_EntityBoundsBuffer)); + public static readonly int _xyBoundsBuffer = Shader.PropertyToID(nameof(_xyBoundsBuffer)); + public static readonly int _wBoundsBuffer = Shader.PropertyToID(nameof(_wBoundsBuffer)); + public static readonly int _zBinBuffer = Shader.PropertyToID(nameof(_zBinBuffer)); + public static readonly int _CoarseXyTileBuffer = Shader.PropertyToID(nameof(_CoarseXyTileBuffer)); + public static readonly int _FineXyTileBuffer = Shader.PropertyToID(nameof(_FineXyTileBuffer)); public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs index 596e6ad623d..a32f513d22d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs @@ -59,10 +59,10 @@ public sealed class ShaderResources public ComputeShader buildDispatchIndirectCS; [Reload("Runtime/Lighting/LightLoop/scrbound.compute")] public ComputeShader buildScreenAABBCS; - [Reload("Runtime/Lighting/LightLoop/zbin.compute")] + [Reload("Runtime/Lighting/LightLoop/zBin.compute")] public ComputeShader zBinCS; - [Reload("Runtime/Lighting/LightLoop/xybin.compute")] - public ComputeShader xyBinCS; + [Reload("Runtime/Lighting/LightLoop/xyTile.compute")] + public ComputeShader xyTileCS; [Reload("Runtime/Lighting/LightLoop/lightlistbuild.compute")] public ComputeShader buildPerTileLightListCS; // FPTL [Reload("Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute")] diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index e2711a41c8e..99fc1100ad8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -206,8 +206,8 @@ unsafe struct ShaderVariablesGlobal public Vector4 _ZBinBufferEncodingParams; - public Vector2Int _CoarseTileBufferDimensions; - public Vector2Int _FineTileBufferDimensions; + public Vector2Int _CoarseXyTileBufferDimensions; + public Vector2Int _FineXyTileBufferDimensions; public uint _NumTileFtplX; public uint _NumTileFtplY; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 9a714e8bc94..bae91ccc8f3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -112,8 +112,8 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) uint4 _BoundedEntityCountPerCategory[2]; uint4 _BoundedEntityOffsetPerCategory[2]; float4 _ZBinBufferEncodingParams; - int2 _CoarseTileBufferDimensions; - int2 _FineTileBufferDimensions; + int2 _CoarseXyTileBufferDimensions; + int2 _FineXyTileBufferDimensions; uint _NumTileFtplX; uint _NumTileFtplY; float g_fClustScale; From 102685258f61f84fcfdf943d1a9bb6cf459e16db Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 14 Oct 2020 16:51:47 -0700 Subject: [PATCH 048/209] Bruteforce lighting works --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 165 +++++++++--------- 1 file changed, 84 insertions(+), 81 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index fbb2bc326ae..dcc3225dd3a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3760,96 +3760,99 @@ static void PerformXYBinning(in BuildGPULightListParameters parameters, in Build // } // } - // static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, bool tileFlagsWritten, CommandBuffer cmd) - // { - // if (parameters.enableFeatureVariants) - // { - // // We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen - // bool needModifyingTileFeatures = !tileFlagsWritten || parameters.computeMaterialVariants; - // if (needModifyingTileFeatures) - // { - // int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; - // parameters.buildMaterialFlagsShader.shaderKeywords = null; - // if (tileFlagsWritten && parameters.computeLightVariants) - // { - // parameters.buildMaterialFlagsShader.EnableKeyword("USE_OR"); - // } + static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, bool tileFlagsWritten, CommandBuffer cmd) + { + var parameters_computeLightVariants = false; // REMOVE - // uint baseFeatureFlags = 0; - // if (!parameters.computeLightVariants) - // { - // baseFeatureFlags |= TiledLightingConstants.s_LightFeatureMaskFlags; - // } - // if (parameters.probeVolumeEnabled) - // { - // // TODO: Verify that we should be globally enabling ProbeVolume feature for all tiles here, or if we should be using per-tile culling. - // baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; - // } + if (parameters.enableFeatureVariants) + { + // We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen + bool needModifyingTileFeatures = !tileFlagsWritten || parameters.computeMaterialVariants; + if (needModifyingTileFeatures) + { + int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; + parameters.buildMaterialFlagsShader.shaderKeywords = null; - // // If we haven't run the light list building, we are missing some basic lighting flags. - // if (!tileFlagsWritten) - // { - // if (parameters.lightList.directionalLights.Count > 0) - // { - // baseFeatureFlags |= (uint)LightFeatureFlags.Directional; - // } - // if (parameters.skyEnabled) - // { - // baseFeatureFlags |= (uint)LightFeatureFlags.Sky; - // } - // if (!parameters.computeMaterialVariants) - // { - // baseFeatureFlags |= TiledLightingConstants.s_MaterialFeatureMaskFlags; - // } - // } + if (tileFlagsWritten && parameters_computeLightVariants) + { + parameters.buildMaterialFlagsShader.EnableKeyword("USE_OR"); + } - // var localLightListCB = parameters.lightListCB; - // localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; + uint baseFeatureFlags = 0; + if (!parameters_computeLightVariants) + { + baseFeatureFlags |= TiledLightingConstants.s_LightFeatureMaskFlags; + } + if (parameters.probeVolumeEnabled) + { + // TODO: Verify that we should be globally enabling ProbeVolume feature for all tiles here, or if we should be using per-tile culling. + baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; + } - // cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + // If we haven't run the light list building, we are missing some basic lighting flags. + if (!tileFlagsWritten) + { + if (parameters.hasDirectionalLights) + { + baseFeatureFlags |= (uint)LightFeatureFlags.Directional; + } + if (parameters.skyEnabled) + { + baseFeatureFlags |= (uint)LightFeatureFlags.Sky; + } + if (!parameters.computeMaterialVariants) + { + baseFeatureFlags |= TiledLightingConstants.s_MaterialFeatureMaskFlags; + } + } - // for (int i = 0; i < resources.gBuffer.Length; ++i) - // cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); + var localLightListCB = parameters.lightListCB; + localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - // if(resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. - // { - // cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); - // } - // else - // { - // cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); - // } + cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - // ConstantBuffer.Push(cmd, localLightListCB, parameters.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList); + for (int i = 0; i < resources.gBuffer.Length; ++i) + cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); - // cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); - // } + if (resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. + { + cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); + } + else + { + cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); + } - // // clear dispatch indirect buffer - // if (parameters.useComputeAsPixel) - // { - // cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - // cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - // cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); - // cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); + ConstantBuffer.Push(cmd, localLightListCB, parameters.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList); - // } - // else - // { - // cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - // cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); - // } + cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); + } - // // add tiles to indirect buffer - // cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - // cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); - // cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - // cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - // cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); - // // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel - // cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); - // } - // } + // clear dispatch indirect buffer + if (parameters.useComputeAsPixel) + { + cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); + cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); + cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); + + } + else + { + cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); + } + + // add tiles to indirect buffer + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); + cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); + // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel + cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); + } + } static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) { @@ -4105,7 +4108,6 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) isGBufferNeeded: true ); - //bool tileFlagsWritten = false; // The algorithm (below) works even if the bounded entity count is 0. // That is fairly efficient, and allows us to avoid weird special cases. @@ -4120,7 +4122,8 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) // BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); // VoxelLightListGeneration(parameters, resources, cmd); - // BuildDispatchIndirectArguments(parameters, resources, tileFlagsWritten, cmd); + bool tileFlagsWritten = false; // ??? + BuildDispatchIndirectArguments(parameters, resources, tileFlagsWritten, cmd); } } From f20a1a2fa333006d8b1f12a3044da53fff1544cd Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 14 Oct 2020 17:31:55 -0700 Subject: [PATCH 049/209] More efficient tile indexing --- .../LightLoop/TilingAndBinningUtilities.hlsl | 30 +++++++++++++------ .../Runtime/Lighting/LightLoop/xyTile.compute | 4 +-- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 90bec310ba5..b28fdba9b3c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -106,15 +106,6 @@ uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) #ifndef NO_SHADERVARIABLESGLOBAL_HLSL -uint ComputeCoarseTileBufferIndex(uint2 tileCoord, uint category, uint eye) -{ - uint rowSize = (uint)_CoarseXyTileBufferDimensions.x; - uint stride = COARSE_XY_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' - - return stride * IndexFromCoordinate(uint4(tileCoord, category, eye), - uint3(rowSize, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); -} - uint ComputeZBinFromLinearDepth(float w) { float z = EncodeLogarithmicDepth(w, _ZBinBufferEncodingParams); @@ -123,6 +114,27 @@ uint ComputeZBinFromLinearDepth(float w) return min((uint)(z * Z_BIN_COUNT), Z_BIN_COUNT - 1); } +// Cannot be used to index directly into the buffer. +// Use ComputeCoarseXyTileBufferIndex for that purpose. +uint ComputeCoarseXyTileIndex(uint2 pixelCoord) +{ + const uint rowSize = (uint)_CoarseXyTileBufferDimensions.x; + const uint2 tileCoord = pixelCoord / COARSE_XY_TILE_SIZE; + + return IndexFromCoordinate(uint4(tileCoord, 0, 0), + uint3(rowSize, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); +} + +// 'tileIndex' may be computed by invoking ComputeCoarseXyTileIndex. +uint ComputeCoarseXyTileBufferIndex(uint tileIndex, uint category, uint eye) +{ + const uint rowSize = (uint)_CoarseXyTileBufferDimensions.x; + const uint stride = COARSE_XY_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + + return stride * (tileIndex + IndexFromCoordinate(uint4(0, 0, category, eye), + uint3(rowSize, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT))); +} + #endif // NO_SHADERVARIABLESGLOBAL_HLSL #endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute index 2f802059bc9..704bed7a47b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute @@ -82,7 +82,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); // TODO: add epsilon for numerical robustness? const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); - const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, cat, eye); + const uint outputStart = ComputeCoarseXyTileBufferIndex(clampedTileIndex, cat, eye); // Define inputs and outputs. uint i = 0, j = 0; @@ -127,7 +127,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } else { - const uint outputStart = ComputeCoarseTileBufferIndex(clampedTileCoord, cat, eye); + const uint outputStart = ComputeCoarseXyTileBufferIndex(clampedTileIndex, cat, eye); // We do not clear the buffer, so we must add a terminator. _CoarseXyTileBuffer[outputStart] = UINT16_MAX; From 8b56147ed8a7f4380cb8d2b405e097be3f42e6b6 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 14 Oct 2020 18:07:15 -0700 Subject: [PATCH 050/209] Share code between coarse and fine tiles --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 11 +++--- .../Lighting/LightLoop/LightLoop.cs.hlsl | 3 +- .../Lighting/LightLoop/LightLoopDef.hlsl | 22 +++++++++--- .../LightLoop/TilingAndBinningUtilities.hlsl | 32 +++++++++++------ .../Runtime/Lighting/LightLoop/xyTile.compute | 36 +++++++++++-------- 5 files changed, 70 insertions(+), 34 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index dcc3225dd3a..a4bf5c7cb3e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -403,10 +403,11 @@ class TiledLightingConstants public static uint s_ScreenSpaceShadowIndexMask = 0xff; // Binned lighting - public static int s_CoarseXyTileEntityLimit = 64; // Before pruning, so, in practice, the number is lower - public static int s_CoarseXyTileSize = 64; - public static int s_FineXyTileSize = 8; - public static int s_zBinCount = 8192; + public static int s_CoarseXyTileEntryLimit = 64; // Per category; before pruning, so, in practice, the number is lower + public static int s_FineXyTileEntryLimit = 16; // Per category; after pruning, so the number is exact + public static int s_CoarseXyTileSize = 64; + public static int s_FineXyTileSize = 8; + public static int s_zBinCount = 8192; } [GenerateHLSL] @@ -782,7 +783,7 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, int coarseXyTileBufferElementCount = coarseXyTileBufferDimensions.x * coarseXyTileBufferDimensions.y * (int)BoundedEntityCategory.Count * viewCount * - (TiledLightingConstants.s_CoarseXyTileEntityLimit / 2); + (TiledLightingConstants.s_CoarseXyTileEntryLimit / 2); // Actually resolution-dependent buffers below. coarseXyTileBuffer = new ComputeBuffer(coarseXyTileBufferElementCount, sizeof(uint)); // List of 16-bit indices diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index d87bdda381f..20d1eb2dcd8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -70,7 +70,8 @@ #define SCREEN_SPACE_COLOR_SHADOW_FLAG (256) #define INVALID_SCREEN_SPACE_SHADOW (255) #define SCREEN_SPACE_SHADOW_INDEX_MASK (255) -#define COARSE_XY_TILE_ENTITY_LIMIT (64) +#define COARSE_XY_TILE_ENTRY_LIMIT (64) +#define FINE_XY_TILE_ENTRY_LIMIT (16) #define COARSE_XY_TILE_SIZE (64) #define FINE_XY_TILE_SIZE (8) #define Z_BIN_COUNT (8192) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 8d80cf19ee6..dfaa99c716f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -156,13 +156,27 @@ uint GetEyeIndex() #endif } -#ifdef LIGHTLOOP_COARSE_BINNED_LIGHTING +#if defined(COARSE_BINNING) -#elif defined(LIGHTLOOP_FINE_BINNED_LIGHTING) +bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data) +{ + bool b = false; + uint n = _PunctualLightCount; + + if (i < n) + { + data = _PunctualLightData[i]; + b = true; + } + + return b; +} + +#elif defined(FINE_BINNING) /* ... */ -#else // !(defined(LIGHTLOOP_COARSE_BINNED_LIGHTING) || defined(LIGHTLOOP_FINE_BINNED_LIGHTING)) +#else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data) { @@ -236,7 +250,7 @@ bool TryLoadDecalData(uint i, uint xyTile, uint zBin, out DecalData data) // return b; // } -#endif // !(defined(LIGHTLOOP_COARSE_BINNED_LIGHTING) || defined(LIGHTLOOP_FINE_BINNED_LIGHTING)) +#endif // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) // In the first 8 bits of the target we store the max fade of the contact shadows as a byte void UnpackContactShadowData(uint contactShadowData, out float fade, out uint mask) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index b28fdba9b3c..e84ac5cde10 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -114,25 +114,37 @@ uint ComputeZBinFromLinearDepth(float w) return min((uint)(z * Z_BIN_COUNT), Z_BIN_COUNT - 1); } +#if defined(COARSE_BINNING) + #define XY_TILE_SIZE COARSE_XY_TILE_SIZE + #define XY_TILE_BUFFER_DIMS uint2(_CoarseXyTileBufferDimensions.xy) + #define XY_TILE_ENTRY_LIMIT COARSE_XY_TILE_ENTRY_LIMIT +#elif defined(FINE_BINNING) + #define XY_TILE_SIZE FINE_XY_TILE_SIZE + #define XY_TILE_BUFFER_DIMS uint2(_FineXyTileBufferDimensions.xy) + #define XY_TILE_ENTRY_LIMIT FINE_XY_TILE_ENTRY_LIMIT +#else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) + #define XY_TILE_SIZE 0 + #define XY_TILE_BUFFER_DIMS 0 + #define XY_TILE_ENTRY_LIMIT 0 +#endif + // Cannot be used to index directly into the buffer. -// Use ComputeCoarseXyTileBufferIndex for that purpose. -uint ComputeCoarseXyTileIndex(uint2 pixelCoord) +// Use ComputXyTileBufferIndex for that purpose. +uint ComputeXyTileIndex(uint2 pixelCoord) { - const uint rowSize = (uint)_CoarseXyTileBufferDimensions.x; - const uint2 tileCoord = pixelCoord / COARSE_XY_TILE_SIZE; + uint2 tileCoord = pixelCoord / XY_TILE_SIZE; return IndexFromCoordinate(uint4(tileCoord, 0, 0), - uint3(rowSize, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(XY_TILE_BUFFER_DIMS.x, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } -// 'tileIndex' may be computed by invoking ComputeCoarseXyTileIndex. -uint ComputeCoarseXyTileBufferIndex(uint tileIndex, uint category, uint eye) +// 'tileIndex' may be computed by invoking ComputeXyTileIndex. +uint ComputeXyTileBufferIndex(uint tileIndex, uint category, uint eye) { - const uint rowSize = (uint)_CoarseXyTileBufferDimensions.x; - const uint stride = COARSE_XY_TILE_ENTITY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + const uint stride = XY_TILE_ENTRY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' return stride * (tileIndex + IndexFromCoordinate(uint4(0, 0, category, eye), - uint3(rowSize, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT))); + uint3(XY_TILE_BUFFER_DIMS.x, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT))); } #endif // NO_SHADERVARIABLESGLOBAL_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute index 704bed7a47b..c6c1e2a22a8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute @@ -2,11 +2,11 @@ #pragma only_renderers d3d11 playstation xboxone vulkan metal switch // Generates large screen tiles in a fast, conservative manner -#pragma kernel FillCoarseXyTile PASS = FILL_COARSE_XY_TILE +#pragma kernel FillCoarseXyTile COARSE_BINNING PASS = FILL_COARSE_XY_TILE // Removes certain entities from the coarse buffer at a large cost -#pragma kernel PruneCoarseXyTile PASS = PRUNE_COARSE_XY_TILE +#pragma kernel PruneCoarseXyTile COARSE_BINNING PASS = PRUNE_COARSE_XY_TILE // Generates small screen tiles in an accurate manner -#pragma kernel BuildFineXyTile PASS = BUILD_FINE_XY_TILE +#pragma kernel BuildFineXyTile FINE_BINNING PASS = BUILD_FINE_XY_TILE #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" @@ -27,11 +27,19 @@ // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, COARSE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_XY_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_XY_TILE_ENTITY_LIMIT * 2 bytes per entry). + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_XY_TILE_ENTRY_LIMIT * 2 bytes per entry). // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. RWStructuredBuffer _CoarseXyTileBuffer : register(u0); // List of 16-bit indices #endif +#if (PASS == BUILD_FINE_XY_TILE) + // 1x list for all entites (sorted by category, we concatenate lists of all views). + // The size of the buffer can be computed as follows: + // DIV_ROUND_UP(RES_X, FINE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_XY_TILE_SIZE) * + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (FINE_XY_TILE_ENTRY_LIMIT * 2 bytes per entry). + // For example (1080p): 240 * 165 * 5 * 1 * (16 * 2) = 6.04 MiB. +#endif + /* ------------------------------ Utilities --------------------------------- */ // Repackage to work around ridiculous constant buffer limitations of HLSL. @@ -40,8 +48,8 @@ static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin /* ------------------------------ Implementation ---------------------------- */ -#if (REMAINDER(COARSE_XY_TILE_ENTITY_LIMIT, 2) != 0) - #error "COARSE_XY_TILE_ENTITY_LIMIT must be an integer multiple of 2." +#if (REMAINDER(XY_TILE_ENTRY_LIMIT, 2) != 0) + #error "XY_TILE_ENTRY_LIMIT must be an integer multiple of 2." #endif #define THREADS_PER_GROUP (64) @@ -58,8 +66,8 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint eye = groupID.z; const uint tileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); - const uint clampedTileIndex = min(tileIndex, (uint)(_CoarseXyTileBufferDimensions.x * _CoarseXyTileBufferDimensions.y - 1)); - const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, (uint)_CoarseXyTileBufferDimensions.x); + const uint clampedTileIndex = min(tileIndex, XY_TILE_BUFFER_DIMS.x * XY_TILE_BUFFER_DIMS.y - 1); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, XY_TILE_BUFFER_DIMS.x); // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -74,15 +82,15 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if (entityCount > 0) // Avoid wasted work { // Compute 2-D the AABB of the tile. - const uint2 tileAaBbMinPtSS = clampedTileCoord * COARSE_XY_TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + COARSE_XY_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_XY_TILE_SIZE + const uint2 tileAaBbMinPtSS = clampedTileCoord * XY_TILE_SIZE; + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + XY_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_XY_TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); // TODO: add epsilon for numerical robustness? const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); - const uint outputStart = ComputeCoarseXyTileBufferIndex(clampedTileIndex, cat, eye); + const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); // Define inputs and outputs. uint i = 0, j = 0; @@ -92,7 +100,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // Therefore, it will be slow if 'n' is large. // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). // TODO: unroll. - while ((i < entityCount) && (j < COARSE_XY_TILE_ENTITY_LIMIT)) + while ((i < entityCount) && (j < XY_TILE_ENTRY_LIMIT)) { float2 entityBoundsX = _xyBoundsBuffer[inputStart + i].xy; float2 entityBoundsY = _xyBoundsBuffer[inputStart + i].zw; @@ -117,7 +125,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) i++; } - if (j < COARSE_XY_TILE_ENTITY_LIMIT) + if (j < XY_TILE_ENTRY_LIMIT) { // Add a terminator. indexPair |= UINT16_MAX << (16 * (j & 1)); // Order: first Lo, then Hi bits @@ -127,7 +135,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } else { - const uint outputStart = ComputeCoarseXyTileBufferIndex(clampedTileIndex, cat, eye); + const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); // We do not clear the buffer, so we must add a terminator. _CoarseXyTileBuffer[outputStart] = UINT16_MAX; From fc54793d0050a4c36e7be3dbaa5ec783e445208b Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 15 Oct 2020 19:31:37 -0700 Subject: [PATCH 051/209] TODOs --- .../Runtime/Lighting/LightLoop/scrbound.compute | 4 ++++ .../Runtime/Lighting/LightLoop/xyTile.compute | 2 +- .../Runtime/Lighting/LightLoop/zbin.compute | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index d36c7550cd9..809e4824136 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -653,6 +653,10 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // Skip Z, we do not need it. ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupEntityIndex]); ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); + + // TODO: for point and spot lights, compute the intersection of AABBs + // of the bounding frustum and the bounding sphere. + #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS if (!isHelperThread && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute index c6c1e2a22a8..e3fef737122 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute @@ -94,7 +94,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // Define inputs and outputs. uint i = 0, j = 0; - uint indexPair = 0; + uint indexPair = 0; // TODO: store not just the indices themselves, but also their min-max for early out // The algorithm is O(n * m) where 'n' is the entity count and 'm' is tile count. // Therefore, it will be slow if 'n' is large. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index d599b6ca649..e9193d9a546 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -78,7 +78,8 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // The algorithm is O(n * m) where 'n' is the entity count and 'm' is bin count. // Therefore, it will be slow if 'n' is large. - // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). + // TODO: we should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). + // TODO: should Z-binning be two-pass as well (coarse bins, fine bins)? This would improve performance for large entity counts. // TODO: unroll. for (uint i = 0; i < entityCount; i++) { From b90ea9519b2ca6365af48de125c13bf161091a62 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 22 Oct 2020 14:11:29 -0700 Subject: [PATCH 052/209] Port the bounding sphere code --- .../LightLoop/TilingAndBinningUtilities.hlsl | 20 +- .../Lighting/LightLoop/scrbound.compute | 225 ++++++++++++++---- 2 files changed, 195 insertions(+), 50 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index e84ac5cde10..497cb3c3b48 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -55,7 +55,7 @@ float3x3 ScaledRotation3x3(float3 xAxis, float3 yAxis, float3 zAxis) float3x3 Invert3x3(float3x3 R) { float3x3 C = transpose(R); // Row to column - float det = dot(C[0], cross(C[1], C[2])); + float det = dot(C[0],cross(C[1], C[2])); float3x3 adj = float3x3(cross(C[1], C[2]), cross(C[2], C[0]), cross(C[0], C[1])); @@ -71,15 +71,19 @@ float4x4 Homogenize3x3(float3x3 R) return M; } -float4x4 PerspectiveProjection4x4(float a, float g, float n, float f) +// a: aspect ratio. +// p: distance to the projection plane. +// n: distance to the near plane. +// f: distance to the far plane. +float4x4 PerspectiveProjection4x4(float a, float p, float n, float f) { - float b = (f + n) * rcp(f - n); // Z in [-1, 1] - float c = -2 * f * n * rcp(f - n); // No Z-reversal + float b = (f + n) * rcp(f - n); + float c = -2 * f * n * rcp(f - n); - return float4x4(g/a, 0, 0, 0, - 0, g, 0, 0, - 0, 0, b, c, - 0, 0, 1, 0); + return float4x4(p/a, 0, 0, 0, + 0, p, 0, 0, // No Y-flip + 0, 0, b, c, // Z in [-1, 1], no Z-reversal + 0, 0, 1, 0); // No W-flip } // The intervals must be defined s.t. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 809e4824136..bac9ac19b83 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -19,12 +19,23 @@ StructuredBuffer _EntityBoundsBuffer : register(t0); // 1x list for all entites (sorted by category, we concatenate lists of all views). RWStructuredBuffer _xyBoundsBuffer : register(u0); // {x_min, x_max, y_min, y_max} -RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} +RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} /* ------------------------------ Utilities --------------------------------- */ /* ------------------------------ Implementation ---------------------------- */ +// !!! IMPORTANT !!! +// The legacy code from Morten provides us special projection matrices (and their inverses). +// These matrices are different from the matrices the HDRP uses. +// There is no reversed-Z buffering (effectively, forced UNITY_REVERSED_Z = 0). +// Additionally, there is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). +// Therefore, all coordinate systems are left-handed, Y-up, without W-flip. +// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. +// y z +// | / +// 0 -- x + // Improve the quality of generated code at the expense of readability. // Remove when the shader compiler is clever enough to perform this optimization for us. #define OBTUSE_COMPILER @@ -57,37 +68,37 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} // All planes and faces are always in the standard order (see below). // Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. -#define FACE_LEFT (1 << 0) // -X z -#define FACE_RIGHT (1 << 1) // +X / -#define FACE_TOP (1 << 2) // -Y 0 -- x -#define FACE_BOTTOM (1 << 3) // +Y | -#define FACE_FRONT (1 << 4) // -Z y +#define FACE_LEFT (1 << 0) // -X +#define FACE_RIGHT (1 << 1) // +X +#define FACE_BOTTOM (1 << 2) // -Y +#define FACE_TOP (1 << 3) // +Y +#define FACE_FRONT (1 << 4) // -Z #define FACE_BACK (1 << 5) // +Z #define FACE_MASK ((1 << NUM_FACES) - 1) // A list of vertices for each face (CCW order w.r.t. its normal, starting from the LSB). -#define VERT_LIST_LEFT ((2) << 9 | (6) << 6 | (4) << 3 | (0) << 0) -#define VERT_LIST_RIGHT ((5) << 9 | (7) << 6 | (3) << 3 | (1) << 0) -#define VERT_LIST_TOP ((1) << 9 | (3) << 6 | (2) << 3 | (0) << 0) -#define VERT_LIST_BOTTOM ((6) << 9 | (7) << 6 | (5) << 3 | (4) << 0) -#define VERT_LIST_FRONT ((4) << 9 | (5) << 6 | (1) << 3 | (0) << 0) -#define VERT_LIST_BACK ((3) << 9 | (7) << 6 | (6) << 3 | (2) << 0) +#define VERT_LIST_LEFT ((4) << 9 | (6) << 6 | (2) << 3 | (0) << 0) +#define VERT_LIST_RIGHT ((3) << 9 | (7) << 6 | (5) << 3 | (1) << 0) +#define VERT_LIST_BOTTOM ((1) << 9 | (5) << 6 | (4) << 3 | (0) << 0) +#define VERT_LIST_TOP ((6) << 9 | (7) << 6 | (3) << 3 | (2) << 0) +#define VERT_LIST_FRONT ((2) << 9 | (3) << 6 | (1) << 3 | (0) << 0) +#define VERT_LIST_BACK ((5) << 9 | (7) << 6 | (6) << 3 | (4) << 0) // All vertices are always in the standard order (see below). uint GetFaceMaskOfVertex(uint v) { - // 0: (-1, -1, -1) -> { FACE_LEFT | FACE_TOP | FACE_FRONT } - // 1: (+1, -1, -1) -> { FACE_RIGHT | FACE_TOP | FACE_FRONT } - // 2: (-1, +1, -1) -> { FACE_LEFT | FACE_BOTTOM | FACE_FRONT } - // 3: (+1, +1, -1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_FRONT } - // 4: (-1, -1, +1) -> { FACE_LEFT | FACE_TOP | FACE_BACK } - // 5: (+1, -1, +1) -> { FACE_RIGHT | FACE_TOP | FACE_BACK } - // 6: (-1, +1, +1) -> { FACE_LEFT | FACE_BOTTOM | FACE_BACK } - // 7: (+1, +1, +1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_BACK } + // 0: (-1, -1, -1) -> { FACE_LEFT | FACE_BOTTOM | FACE_FRONT } + // 1: (+1, -1, -1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_FRONT } + // 2: (-1, +1, -1) -> { FACE_LEFT | FACE_TOP | FACE_FRONT } + // 3: (+1, +1, -1) -> { FACE_RIGHT | FACE_TOP | FACE_FRONT } + // 4: (-1, -1, +1) -> { FACE_LEFT | FACE_BOTTOM | FACE_BACK } + // 5: (+1, -1, +1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_BACK } + // 6: (-1, +1, +1) -> { FACE_LEFT | FACE_TOP | FACE_BACK } + // 7: (+1, +1, +1) -> { FACE_RIGHT | FACE_TOP | FACE_BACK } // ((v & 1) == 0) ? 1 : 2) | ((v & 2) == 0) ? 4 : 8) | ((v & 4) == 0) ? 16 : 32) - uint f = (FACE_LEFT << BitFieldExtract(v, 0, 1)) - | (FACE_TOP << BitFieldExtract(v, 1, 1)) - | (FACE_FRONT << BitFieldExtract(v, 2, 1)); + uint f = (FACE_LEFT << BitFieldExtract(v, 0, 1)) + | (FACE_BOTTOM << BitFieldExtract(v, 1, 1)) + | (FACE_FRONT << BitFieldExtract(v, 2, 1)); return f; }; @@ -96,9 +107,9 @@ float3 GenerateVertexOfStandardCube(uint v) { float3 p; - p.x = ((v & 1) == 0) ? -1 : 1; - p.y = ((v & 2) == 0) ? -1 : 1; - p.z = ((v & 4) == 0) ? -1 : 1; + p.x = ((v & 1) == 0) ? -1 : 1; // FACE_LEFT : FACE_RIGHT + p.y = ((v & 2) == 0) ? -1 : 1; // FACE_BOTTOM : FACE_TOP + p.z = ((v & 4) == 0) ? -1 : 1; // FACE_FRONT : FACE_BACK return p; } @@ -106,9 +117,9 @@ float3 GenerateVertexOfStandardCube(uint v) uint GetVertexListOfFace(uint f) { // Warning: don't add 'static' here unless you want really bad code gen. - const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, - (VERT_LIST_BOTTOM << 12) | VERT_LIST_TOP, - (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); + const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, + (VERT_LIST_TOP << 12) | VERT_LIST_BOTTOM, + (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); return BitFieldExtract(allVertLists[f >> 1], 12 * (f & 1), 12); } @@ -316,12 +327,96 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT } } +// Given: 'C' is the center of the sphere in the view space, 'r' is its radius; +// 'projScale' and 'projOffset' are used to perform projection of the X (or Y) component of a vector. +float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float projOffset) +{ + float xMin, xMax; + + // See sec. 8.2.1 of https://foundationsofgameenginedev.com/#fged2 for an alternative derivation. + // Goal: find the planes that pass through the origin O, bound the sphere, and form + // an axis-aligned rectangle at the intersection with the projection plane. + // Solution (for the X-coordinate): + // The intersection of the bounding planes and the projection plane must be vertical lines, + // which means that the bounding planes must be tangent to the Y-axis. + // The bounding planes must be also tangent to the sphere. + // Call the intersection points of the two vertical bounding planes and the bounding + // sphere B and D. Assume that B is on the left of C; D is on the right of C. + // Note that C may be behind the origin, so the same generally goes for B and D. + // BC is normal w.r.t. the bounding plane, so it is normal w.r.t. the Y-axis; |BC| = r. + // As a consequence, it lies in a plane parallel to the the O-X-Z plane. + // Consider B'C', which is an orthogonal projection of BC onto the actual O-X-Z plane. + // (Imagine sliding the sphere up or down between the bounding planes). + // We then consider a triangle OB'C' that lies entirely in the O-X-Z plane. + // The coordinates are: OB' = (b.x, 0, b.z), OC' = (c.x, 0, c.z). + float3 B, D; + // OBC is a right triangle. So is OB'C'. + // |BC| = |B'C'| = r. + // |OB'|^2 = |OC'|^2 - |B'C'|^2. + float lenSqOC = dot(C.xz, C.xz); + float lenSqOB = lenSqOC - r * r; + // If |OB'| = 0 or |OC'| = 0, the bounding planes tangent to the sphere do not exist. + if (lenSqOB > 0) + { + float lenOB = sqrt(lenSqOB); + // |OB' x OC'| = |OB'| * |OC'| * Sin[a']. + // OB' . OC' = |OB'| * |OC'| * Cos[a']. + // We can determine Sin[a'] = |B'C'| / |OC'| = R / |OC'|. + // Cos[a'] = Sqrt[1 - Sin[a']^2]. + // (OB' x OC') points along Y. + // (OB' x OC').y = b.z * c.x - b.x * c.z. + // Therefore, b.z * c.x - b.x * c.z = |OB'| * |OC'| * Sin[a']. + // OB' . OC' = b.x * c.x + b.z * c.z = |OB'| * |OC'| * Cos[a']. + // Since we don't care about the scale, and |OB'| != 0 and |OC'| != 0, + // we can equivalently solve + // z * c.x - x * c.z = |OC'|^3 * Sin[a']. + // x * c.x + z * c.z = |OC'|^3 * Cos[a']. + // With 2 equations and 2 unknowns, we can easily solve this linear system. + // The solutions is + // x = -c.z * r + c.x * |OB'|. + // z = c.x * r + c.z * |OB'|. + B.x = C.x * lenOB - (C.z * r); + B.z = C.z * lenOB + (C.x * r); + // (OD' x OC') points along Y. + // (OD' x OC').y = d.z * c.x - d.x * c.z. + // We must solve + // z * c.x - x * c.z = -|OC'|^3 * Sin[a']. + // x * c.x + z * c.z = |OC'|^3 * Cos[a']. + // The solution is + // x = c.z * r + c.x * |OB'|. + // z = -c.x * r + c.z * |OB'|. + D.x = C.x * lenOB + (C.z * r); + D.z = C.z * lenOB - (C.x * r); + // We can transform OB and OD as direction vectors. + // For the simplification below, see OptimizeProjectionMatrix. + float rapBx = (B.x * rcp(B.z)) * projScale + projOffset; + float rapDx = (D.x * rcp(D.z)) * projScale + projOffset; + // One problem with the above is that this direction may, for certain spheres, + // point behind the origin (B.z <= 0 or D.z <= 0). + // At this point we know that the sphere at least *partially* in front of the origin, + // and that it is we are not inside the sphere, so there is at least one valid + // plane (and one valid direction). We just need the second direction to go "in front" + // of the first one to extend the bounding box. + xMin = (B.z > 0) ? rapBx : -FLT_INF; + xMax = (D.z > 0) ? rapDx : FLT_INF; + } + else + { + // Conservative estimate (we do not cull the bounding sphere using the view frustum). + xMin = -1; + xMax = 1; + } + + return float2(xMin, xMax); +} + //********************************************************************************************** -// The goal of this program is to compute the AABB of the bounded entity in the NDC space ([0, 1] range). -// The entity is represented by a convex volume (a right frustum) with 6 faces (planar quads) and 8 vertices. +// The goal of this program is to compute the AABB of a bounded entity in the NDC space ([0, 1] range). +// The entity is represented by a bounding sphere and a right bounding frustum with 6 faces and 8 vertices. +// The resulting bounding volume is defined by the the intersection of the sphere and the frustum. // // Since an entity's bounding volume may be partially off-screen, we must clip it before computing the AABB. -// Clipping the resulting AABB (rather than the bounding volume) may result in a loose AABB. +// Clipping the resulting AABB (rather than the bounding volume itself) may result in a loose AABB. // // To avoid having to deal with the "Moebius twist" property of the perspective transform, // we perform clipping using the homogeneous (projective) post-perspective coordinates. @@ -336,7 +431,6 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT // (Imagine a view volume completely or partially inside a bounding volume). // Therefore, we must perform view-volume-corner-inside-bounding-volume tests. // -// // Notation: // rbp - real (3D) coordinates before perspective // hbp - hom. (4D) coordinates before perspective @@ -366,11 +460,14 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const float4x4 projMat = g_mProjectionArr[eye]; const float4x4 invProjMat = g_mInvProjectionArr[eye]; - const float scale = cullData.scaleXY; // scale.x = scale.y + // Bounding frustum. const float3 rbpC = cullData.center.xyz; // View-space const float3 rbpX = cullData.boxAxisX.xyz; // Pre-scaled const float3 rbpY = cullData.boxAxisY.xyz; // Pre-scaled const float3 rbpZ = cullData.boxAxisZ.xyz; // Pre-scaled + const float scale = cullData.scaleXY; // scale.x = scale.y + // Bounding sphere. + const float radius = cullData.radius; #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // (0) Initialize the TGSM. @@ -398,7 +495,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint i; // Avoid multiply-declared variable warning - // (1) Compute the vertices of the bounding volume. + // (1) Compute the vertices of the bounding frustum. for (i = 0; i < VERTS_PER_THREAD; i++) { uint v = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; @@ -459,6 +556,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } else // Outside { + // Mark all the faces of the bounding frustum associated with this vertex. cullClipFaceMask |= GetFaceMaskOfVertex(v); } @@ -490,10 +588,11 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if (cullClipFaceMask != 0) { // The entity is partially outside the view volume. - // Therefore, some of the corners of the view volume may be inside the entity's bounding volume. + // Therefore, some of the corners of the view volume may be inside the entity's bounding frustum. // We perform aggressive culling, so we must make sure they are accounted for. - // The bounding volume is a special type of a rectangular prism - a right frustum. - // We can exploit this fact by building a entity-space projection matrix. + // We can exploit the properties of the frustum by building an entity-space projection matrix. + // P_v = T * (R * S) * P_l + // P_l = (R * S)^{-1} * T^{-1} * P_v float4x4 invTranslateToEntitySpace = Translation4x4(-rbpC); float4x4 invRotateAndScaleInEntitySpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); // TODO: avoid full inversion by using unit vectors and passing magnitudes explicitly. @@ -526,7 +625,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space float4 hapVertLS = mul(entitySpaceMatrix, hbpVertVS); // View to entity space - // Consider the vertex to be inside the entity's bounding volume if: + // Consider the vertex to be inside the entity's bounding frustum if: // -w < x < w // -w < y < w <-- exclude boundary points, as we will not clip using these vertices // -w < z < w <-- assume that Z-precision is not very important here @@ -653,11 +752,53 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // Skip Z, we do not need it. ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupEntityIndex]); ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - // TODO: for point and spot lights, compute the intersection of AABBs - // of the bounding frustum and the bounding sphere. + // (5) Compute the AABB of the bounding sphere. + if (radius > 0) + { + // Occasionally, an intersection of AABBs of a bounding sphere and a bounding frustum + // results in a tighter AABB when compared to using the AABB of the frustum alone. + // That is the case (mostly) for sphere-capped spot lights with very wide angles. + // Note that, unfortunately, it is not quite as tight as an AABB of a CSG intersection + // of a sphere and frustum. Also note that the algorithm below doesn't clip the bounding + // sphere against the view frustum before computing the bounding box, simply because it is + // too hard/expensive. I will leave it as a TODO in case someone wants to tackle this problem. + if ((rbpC.z + radius) > 0) // Is the sphere at least *partially* in front of the origin? + { + float2 rectMin, rectMax; -#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + // For the 'x' and 'y' components, the solution is given below. + if (g_isOrthographic) + { + // Compute the center and the extents (half-diagonal) of the bounding box. + float2 center = mul(projMat, float4(rbpC.xyz, 1)).xy; + float2 extents = mul(projMat, float4(radius.xx, 0, 0)).xy; + + rectMin = center - extents; + rectMax = center + extents; + } + else // Perspective + { + float2 xBounds = ComputeBoundsOfProjectedSphere(rbpC.xxz, radius, projMat._m00, projMat._m02); // X-Z plane + float2 yBounds = ComputeBoundsOfProjectedSphere(rbpC.yyz, radius, projMat._m11, projMat._m12); // Y-Z plane + + rectMin = float2(xBounds.r, yBounds.r); + rectMax = float2(xBounds.g, yBounds.g); + } + + // Transform to the NDC coordinates. + rectMin = rectMin * 0.5 + 0.5; + rectMax = rectMax * 0.5 + 0.5; + + // Note: separating the X- and Y-computations across 2 threads is not worth it. + ndcAaBbMinPt.xy = max(ndcAaBbMinPt.xy, rectMin); + ndcAaBbMaxPt.xy = min(ndcAaBbMaxPt.xy, rectMax); + // Skip Z, we do not need it. + ndcAaBbMinPt.w = max(ndcAaBbMinPt.w, rbpC.z - radius); + ndcAaBbMaxPt.w = min(ndcAaBbMaxPt.w, rbpC.z + radius); + } + } if (!isHelperThread && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts { From d292b7808308b52ad49cd7b59a9c30733f0135d0 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 22 Oct 2020 18:38:45 -0700 Subject: [PATCH 053/209] Use z-binning for punctual lights during the deferred lighting pass --- .../ShaderLibrary/Common.hlsl | 37 ++++------- .../Runtime/Lighting/Deferred.shader | 2 +- .../Lighting/LightLoop/Deferred.compute | 24 ++++--- .../Lighting/LightLoop/DeferredTile.shader | 2 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 56 ++++++++-------- .../Lighting/LightLoop/LightLoopDef.hlsl | 64 +++++++++++++------ .../LightLoop/ShaderVariablesLightLoop.hlsl | 11 ++-- .../LightLoop/TilingAndBinningUtilities.hlsl | 42 ++++++------ .../Runtime/Lighting/LightLoop/xyTile.compute | 28 ++++---- .../Runtime/Lighting/LightLoop/zbin.compute | 6 +- .../VolumetricLighting/VolumetricLighting.cs | 4 +- .../Shaders/DepthOfFieldMipSafe.compute | 2 +- .../Shaders/DoFCircleOfConfusion.compute | 2 +- .../PostProcessing/Shaders/Exposure.compute | 4 +- .../PostProcessing/Shaders/UberPost.compute | 4 +- .../HDRenderPipeline.LightLoop.cs | 2 +- .../HDRenderPipeline.Prepass.cs | 4 +- .../Shaders/Shadows/RaytracingShadow.compute | 2 +- .../Settings/FrameSettings.Migration.cs | 4 +- .../RenderPipeline/Settings/FrameSettings.cs | 12 ++-- .../ShaderPass/ShaderPassDecal.hlsl | 2 +- .../ShaderPass/ShaderPassForward.hlsl | 4 +- .../HDRenderPipelineResources.asset | 4 +- .../Tests/Editor/FrameSettingsTest.cs | 4 +- 24 files changed, 172 insertions(+), 154 deletions(-) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index 7e91661ebd2..3ebbb2a0d2b 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1036,19 +1036,18 @@ struct PositionInputs float3 positionWS; // World space position (could be camera-relative) float2 positionNDC; // Normalized screen coordinates within the viewport : [0, 1) (with the half-pixel offset) uint2 positionSS; // Screen space pixel coordinates : [0, NumPixels) - uint2 tileCoord; // Screen tile coordinates : [0, NumTiles) float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed) float linearDepth; // View space Z coordinate : [Near, Far] - uint xyTile; - uint zBin; + uint xyTile; // Screen tile index + uint zBin; // Depth bin index }; // This function is use to provide an easy way to sample into a screen texture, either from a pixel or a compute shaders. // This allow to easily share code. // If a compute shader call this function positionSS is an integer usually calculate like: uint2 positionSS = groupId.xy * BLOCK_SIZE + groupThreadId.xy // else it is current unormalized screen coordinate like return by SV_Position -PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, uint2 tileCoord) // Specify explicit tile coordinates so that we can easily make it lane invariant for compute evaluation. +PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize) { PositionInputs posInput; ZERO_INITIALIZE(PositionInputs, posInput); @@ -1060,21 +1059,19 @@ PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, uint2 t #endif posInput.positionNDC *= invScreenSize; posInput.positionSS = uint2(positionSS); - posInput.tileCoord = tileCoord; - return posInput; -} + // These two are only used by certain (binned lighting) passes, + // so they must be initialized explicitly (only when necessary). + posInput.xyTile = posInput.zBin = 0; -PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize) -{ - return GetPositionInput(positionSS, invScreenSize, uint2(0, 0)); + return posInput; } // From forward // deviceDepth and linearDepth come directly from .zw of SV_Position -PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float deviceDepth, float linearDepth, float3 positionWS, uint2 tileCoord) +PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float deviceDepth, float linearDepth, float3 positionWS) { - PositionInputs posInput = GetPositionInput(positionSS, invScreenSize, tileCoord); + PositionInputs posInput = GetPositionInput(positionSS, invScreenSize); posInput.positionWS = positionWS; posInput.deviceDepth = deviceDepth; posInput.linearDepth = linearDepth; @@ -1082,19 +1079,13 @@ PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float d return posInput; } -PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float deviceDepth, float linearDepth, float3 positionWS) -{ - return GetPositionInput(positionSS, invScreenSize, deviceDepth, linearDepth, positionWS, uint2(0, 0)); -} - // From deferred or compute shader // depth must be the depth from the raw depth buffer. This allow to handle all kind of depth automatically with the inverse view projection matrix. // For information. In Unity Depth is always in range 0..1 (even on OpenGL) but can be reversed. PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float deviceDepth, - float4x4 invViewProjMatrix, float4x4 viewMatrix, - uint2 tileCoord) + float4x4 invViewProjMatrix, float4x4 viewMatrix) { - PositionInputs posInput = GetPositionInput(positionSS, invScreenSize, tileCoord); + PositionInputs posInput = GetPositionInput(positionSS, invScreenSize); posInput.positionWS = ComputeWorldSpacePosition(posInput.positionNDC, deviceDepth, invViewProjMatrix); posInput.deviceDepth = deviceDepth; posInput.linearDepth = LinearEyeDepth(posInput.positionWS, viewMatrix); @@ -1102,12 +1093,6 @@ PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float d return posInput; } -PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize, float deviceDepth, - float4x4 invViewProjMatrix, float4x4 viewMatrix) -{ - return GetPositionInput(positionSS, invScreenSize, deviceDepth, invViewProjMatrix, viewMatrix, uint2(0, 0)); -} - // The view direction 'V' points towards the camera. // 'depthOffsetVS' is always applied in the opposite direction (-V). void ApplyDepthOffsetPositionInput(float3 V, float depthOffsetVS, float3 viewForwardDir, float4x4 viewProjMatrix, inout PositionInputs posInput) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader index 93336d39e82..7dcdd51dbed 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader @@ -128,7 +128,7 @@ Shader "Hidden/HDRP/Deferred" // input.positionCS is SV_Position float depth = LoadCameraDepth(input.positionCS.xy); - PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, uint2(input.positionCS.xy) / GetTileSize()); + PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); BSDFData bsdfData; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index ff8f1b39077..d5270ffaa4b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -1,3 +1,5 @@ +#pragma enable_d3d11_debug_symbols + #pragma kernel Deferred_Direct_Fptl SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl #pragma kernel Deferred_Direct_Fptl_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl_DebugDisplay DEBUG_DISPLAY @@ -45,7 +47,7 @@ // deferred opaque always use FPTL #define USE_FPTL_LIGHTLIST 1 -// #pragma enable_d3d11_debug_symbols +#define COARSE_BINNING // Comment out the line to loop over all lights (for debugging purposes) //------------------------------------------------------------------------------------- // Include @@ -78,7 +80,6 @@ CBUFFER_END #define HAS_LIGHTLOOP - // Note: We have fix as guidelines that we have only one deferred material (with control of GBuffer enabled). Mean a users that add a new // deferred material must replace the old one here. If in the future we want to support multiple layout (cause a lot of consistency problem), // the deferred shader will require to use multicompile. @@ -97,12 +98,12 @@ TEXTURE2D_X_UINT2(_StencilTexture); RW_TEXTURE2D_X(float3, diffuseLightingUAV); RW_TEXTURE2D_X(float4, specularLightingUAV); -#define GROUP_SIZE (TILE_SIZE_FPTL / 2) // 4x 8x8 groups per a 16x16 tile +#define GROUP_SIZE (8) #ifdef USE_INDIRECT StructuredBuffer g_TileList; -// Indirect + [numthreads(GROUP_SIZE, GROUP_SIZE, 1)] void SHADE_OPAQUE_ENTRY(uint2 groupThreadId : SV_GroupThreadID, uint groupId : SV_GroupID) { @@ -118,6 +119,8 @@ void SHADE_OPAQUE_ENTRY(uint2 groupThreadId : SV_GroupThreadID, uint groupId : S uint numTilesX = (screenWidth + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL; uint tileVariantIndex = tileCoord.x + tileCoord.y * numTilesX; + uint xyTile = 0; + #if defined(UNITY_STEREO_INSTANCING_ENABLED) uint screenHeight = (uint)_ScreenSize.y; uint numTilesY = (screenHeight + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL; @@ -125,15 +128,16 @@ void SHADE_OPAQUE_ENTRY(uint2 groupThreadId : SV_GroupThreadID, uint groupId : S #endif uint featureFlags = TileVariantToFeatureFlags(VARIANT, tileVariantIndex); -#else -// Direct +#else // !USE_INDIRECT + [numthreads(GROUP_SIZE, GROUP_SIZE, 1)] void SHADE_OPAQUE_ENTRY(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupId : SV_GroupID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - uint2 tileCoord = (GROUP_SIZE * groupId) / GetTileSize(); + uint2 tileCoord = (GROUP_SIZE * groupId) / XY_TILE_SIZE; + uint xyTile = ComputeXyTileIndex(tileCoord); uint2 pixelCoord = dispatchThreadId.xy; uint featureFlags = UINT_MAX; @@ -142,7 +146,9 @@ void SHADE_OPAQUE_ENTRY(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 grou // This need to stay in sync with deferred.shader float depth = LoadCameraDepth(pixelCoord.xy); - PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, tileCoord); + PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); + posInput.xyTile = xyTile; + posInput.zBin = ComputeZBinIndex(posInput.linearDepth); // For indirect case: we can still overlap inside a tile with the sky/background, reject it // Can't rely on stencil as we are in compute shader @@ -150,7 +156,7 @@ void SHADE_OPAQUE_ENTRY(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 grou { return; } - + // This is required for camera stacking and other cases where we might have a valid depth value in the depth buffer, but the pixel was not covered by this camera uint stencilVal = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, pixelCoord.xy)); if ((stencilVal & STENCILUSAGE_REQUIRES_DEFERRED_LIGHTING) == 0) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader index 832bd083d08..59bb287b177 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader @@ -399,7 +399,7 @@ Shader "Hidden/HDRP/DeferredTile" // input.positionCS is SV_Position float depth = LoadCameraDepth(input.positionCS.xy).x; - PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, uint2(input.positionCS.xy) / GetTileSize()); + PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index a4bf5c7cb3e..d2affde8a1b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -696,9 +696,12 @@ class TileAndClusterData public ComputeBuffer convexBoundsBuffer { get; /*private*/ set; } public ComputeBuffer xyBoundsBuffer { get; private set; } public ComputeBuffer wBoundsBuffer { get; private set; } - public ComputeBuffer zBinBuffer { get; private set; } public ComputeBuffer globalLightListAtomic { get; private set; } + // Binned lighting + public ComputeBuffer coarseXyTileBuffer { get; private set; } + public ComputeBuffer zBinBuffer { get; private set; } + // Tile Output public ComputeBuffer tileFeatureFlags { get; private set; } // Deferred public ComputeBuffer dispatchIndirectBuffer { get; private set; } // Deferred @@ -712,8 +715,6 @@ class TileAndClusterData public ComputeBuffer bigTileLightList { get; private set; } // Volumetric public ComputeBuffer perVoxelLightLists { get; private set; } // Cluster - // Binned lighting - public ComputeBuffer coarseXyTileBuffer { get; private set; } public bool listsAreClear = false; @@ -765,28 +766,22 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, } } - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) { - var nrBigTilesX = (width + 63) / 64; - var nrBigTilesY = (height + 63) / 64; - var nrBigTiles = nrBigTilesX * nrBigTilesY * viewCount; - // TODO: (Nick) In the case of Probe Volumes, this buffer could be trimmed down / tuned more specifically to probe volumes if we added a s_MaxNrBigTileProbeVolumesPlusOne value. - bigTileLightList = new ComputeBuffer(TiledLightingConstants.s_MaxNrBigTileLightsPlusOne * nrBigTiles, sizeof(uint)); - } + /* These are not resolution-dependent at all, but the old code allocated them here... */ + xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, x_max, y_min, y_max} + wBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 2 * sizeof(float)); // {w_min, w_max} + zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_zBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {last << 16 | first} - // These are not resolution-dependent at all, but the old code allocated them here... - xyBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 4 * sizeof(float)); // {x_min, x_max, y_min, y_max} - wBoundsBuffer = new ComputeBuffer(maxBoundedEntityCount * viewCount, 2 * sizeof(float)); // {w_min, w_max} - zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_zBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {start << 16 | end} + /* Actually resolution-dependent buffers below. */ + Vector2Int coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); - Vector2Int coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); + int coarseXyTileBufferElementCount = coarseXyTileBufferDimensions.x * coarseXyTileBufferDimensions.y * + (int)BoundedEntityCategory.Count * viewCount * + (TiledLightingConstants.s_CoarseXyTileEntryLimit / 2); - int coarseXyTileBufferElementCount = coarseXyTileBufferDimensions.x * coarseXyTileBufferDimensions.y * - (int)BoundedEntityCategory.Count * viewCount * - (TiledLightingConstants.s_CoarseXyTileEntryLimit / 2); - - // Actually resolution-dependent buffers below. - coarseXyTileBuffer = new ComputeBuffer(coarseXyTileBufferElementCount, sizeof(uint)); // List of 16-bit indices + coarseXyTileBuffer = new ComputeBuffer(coarseXyTileBufferElementCount, sizeof(uint)); // List of 16-bit indices + } // Make sure to invalidate the content of the buffers listsAreClear = false; @@ -3463,6 +3458,7 @@ struct BuildGPULightListParameters public int clearLightListKernel; // Binned lighting + public bool binEntities; public ComputeShader screenSpaceAABBShader; public ComputeShader zBinShader; public ComputeShader xyTileShader; @@ -3471,7 +3467,6 @@ struct BuildGPULightListParameters // Big Tile public ComputeShader bigTilePrepassShader; public int bigTilePrepassKernel; - public bool runBigTilePrepass; public int numBigTilesX, numBigTilesY; // FPTL @@ -3979,13 +3974,13 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.clearLightListKernel = parameters.clearLightListCS.FindKernel("ClearList"); // Binned lighting + parameters.binEntities = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting); parameters.screenSpaceAABBShader = buildScreenAABBShader; parameters.zBinShader = zBinShader; parameters.xyTileShader = xyTileShader; parameters.coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); // Big tile prepass - parameters.runBigTilePrepass = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); parameters.bigTilePrepassShader = buildPerBigTileLightListShader; parameters.bigTilePrepassKernel = s_GenListPerBigTileKernel; parameters.numBigTilesX = (w + 63) / 64; @@ -3995,7 +3990,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.runFPTL = hdCamera.frameSettings.fptl && tileAndClusterData.hasTileBuffers; parameters.buildPerTileLightListShader = buildPerTileLightListShader; parameters.buildPerTileLightListShader.shaderKeywords = null; - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) { parameters.buildPerTileLightListShader.EnableKeyword("USE_TWO_PASS_TILED_LIGHTING"); } @@ -4015,7 +4010,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera // Cluster bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); - var clustPrepassSourceIdx = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass) ? ClusterPrepassSource.BigTile : ClusterPrepassSource.None; + var clustPrepassSourceIdx = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting) ? ClusterPrepassSource.BigTile : ClusterPrepassSource.None; var clustDepthSourceIdx = ClusterDepthSource.NoDepth; if (tileAndClusterData.clusterNeedsDepth) clustDepthSourceIdx = msaa ? ClusterDepthSource.MSAA_Depth : ClusterDepthSource.Depth; @@ -4060,7 +4055,7 @@ static void PushProbeVolumeLightListGlobalParams(in LightLoopGlobalParameters pa { Camera camera = param.hdCamera.camera; - if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) + if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, param.tileAndClusterData.bigTileLightList); // int useDepthBuffer = 0; @@ -4283,8 +4278,12 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PushGlobalParameters))) { - if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) - cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, param.tileAndClusterData.bigTileLightList); + if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) + { + cmd.SetGlobalBuffer(HDShaderIDs._CoarseXyTileBuffer, param.tileAndClusterData.coarseXyTileBuffer); + //cmd.SetGlobalBuffer(HDShaderIDs._FineXyTileBuffer, param.tileAndClusterData.fine); + cmd.SetGlobalBuffer(HDShaderIDs._zBinBuffer, param.tileAndClusterData.zBinBuffer); + } // Cluster { @@ -4636,6 +4635,7 @@ static void RenderComputeDeferredLighting(in DeferredLightingParameters paramete { // 4x 8x8 groups per a 16x16 tile. cmd.DispatchCompute(parameters.deferredComputeShader, kernel, parameters.numTilesX * 2, parameters.numTilesY * 2, parameters.viewCount); + break; // There's only one variant. Don't render the same thing 30 times! } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index dfaa99c716f..816839fd782 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -146,36 +146,60 @@ float4 SampleEnv(LightLoopContext lightLoopContext, int index, float3 texCoord, #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" -// Careful, this may not work if 'TextureXR.hlsl' has not already been included. -uint GetEyeIndex() -{ -#if defined(UNITY_STEREO_INSTANCING_ENABLED) - return unity_StereoEyeIndex; -#else - return 0; -#endif -} - -#if defined(COARSE_BINNING) +#if (defined(COARSE_BINNING) || defined(FINE_BINNING)) -bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data) +bool TryLoadPunctualLightData(inout uint i, uint xyTile, uint zBin, out LightData data) { bool b = false; - uint n = _PunctualLightCount; + uint n = XY_TILE_ENTRY_LIMIT; - if (i < n) + // These values are loop-invariant. They do not depend on the value of 'i'. + // They will only be computed once per category, not once per function call. + const uint xyTileBufferIndex = ComputeXyTileBufferIndex(xyTile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint firstTileEntry = XY_TILE_BUFFER[xyTileBufferIndex]; + + const uint zBinBufferIndex = ComputeZBinBufferIndex( zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint packedIndexRange = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + + // TODO: add a range check for the tile here. + const bool isTileEmpty = firstTileEntry == UINT16_MAX; + const bool isBinEmpty = packedIndexRange == UINT16_MAX; + + if (!isTileEmpty && !isBinEmpty) { - data = _PunctualLightData[i]; - b = true; + const uint firstEntityIndex = packedIndexRange & UINT16_MAX; + const uint lastEntityIndex = packedIndexRange >> 16; + + // The part below will be actually executed during every function call. + while (i < n) + { + // This is a valid buffer index. + uint entityIndexPair = XY_TILE_BUFFER[xyTileBufferIndex + (i / 2)]; // 16-bit indices + uint entityIndex = BitFieldExtract(entityIndexPair, 16 * (i & 1), 16); // Order: first Lo, then Hi bits + + // Entity indices are stored in the ascending order. + // We can distinguish 3 cases: + if (entityIndex < firstEntityIndex) + { + i++; // Skip this entity; continue the search + } + else if (entityIndex <= lastEntityIndex) + { + data = _PunctualLightData[entityIndex]; + + b = true; // Found a valid index + break; // Avoid incrementing 'i' further + } + else // if (lastEntityIndex < entityIndex) + { + break; // Avoid incrementing 'i' further + } + } } return b; } -#elif defined(FINE_BINNING) - -/* ... */ - #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index 9c6330d65e8..c433e7f783c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -1,11 +1,12 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs.hlsl" -// don't support Buffer yet in unity -StructuredBuffer g_vBigTileLightList; -StructuredBuffer g_vLightListGlobal; -StructuredBuffer g_vLayeredOffsetsBuffer; -StructuredBuffer g_logBaseBuffer; +#if (defined(COARSE_BINNING) || defined(FINE_BINNING)) + // TODO: we don't need both at the same time, so perhaps just declare one? + StructuredBuffer _CoarseXyTileBuffer; + StructuredBuffer _FineXyTileBuffer; + StructuredBuffer _zBinBuffer; +#endif #ifdef USE_INDIRECT StructuredBuffer g_TileFeatureFlags; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 497cb3c3b48..663d8ce3b9d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -59,7 +59,7 @@ float3x3 Invert3x3(float3x3 R) float3x3 adj = float3x3(cross(C[1], C[2]), cross(C[2], C[0]), cross(C[0], C[1])); - return rcp(det) * adj; + return rcp(det) * adj; // Adjugate / Determinant } float4x4 Homogenize3x3(float3x3 R) @@ -102,17 +102,19 @@ uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); } -uint ComputeZBinBufferIndex(uint bin, uint category, uint eye) +uint ComputeZBinBufferIndex(uint zBin, uint category, uint eye) { - return IndexFromCoordinate(uint3(bin, category, eye), + return IndexFromCoordinate(uint3(zBin, category, eye), uint2(Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); } #ifndef NO_SHADERVARIABLESGLOBAL_HLSL -uint ComputeZBinFromLinearDepth(float w) +// Cannot be used to index directly into the buffer. +// Use ComputeZBinBufferIndex for that purpose. +uint ComputeZBinIndex(float linearDepth) { - float z = EncodeLogarithmicDepth(w, _ZBinBufferEncodingParams); + float z = EncodeLogarithmicDepth(linearDepth, _ZBinBufferEncodingParams); z = saturate(z); // Clamp to the region between the near and the far planes return min((uint)(z * Z_BIN_COUNT), Z_BIN_COUNT - 1); @@ -120,35 +122,37 @@ uint ComputeZBinFromLinearDepth(float w) #if defined(COARSE_BINNING) #define XY_TILE_SIZE COARSE_XY_TILE_SIZE - #define XY_TILE_BUFFER_DIMS uint2(_CoarseXyTileBufferDimensions.xy) #define XY_TILE_ENTRY_LIMIT COARSE_XY_TILE_ENTRY_LIMIT + #define XY_TILE_BUFFER _CoarseXyTileBuffer + #define XY_TILE_BUFFER_DIMS uint2(_CoarseXyTileBufferDimensions.xy) #elif defined(FINE_BINNING) #define XY_TILE_SIZE FINE_XY_TILE_SIZE - #define XY_TILE_BUFFER_DIMS uint2(_FineXyTileBufferDimensions.xy) #define XY_TILE_ENTRY_LIMIT FINE_XY_TILE_ENTRY_LIMIT + #define XY_TILE_BUFFER _FineXyTileBuffer + #define XY_TILE_BUFFER_DIMS uint2(_FineXyTileBufferDimensions.xy) #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) - #define XY_TILE_SIZE 0 - #define XY_TILE_BUFFER_DIMS 0 + // These must be defined so the compiler does not complain. + #define XY_TILE_SIZE 1 #define XY_TILE_ENTRY_LIMIT 0 + #define XY_TILE_BUFFER_DIMS uint2(0, 0) #endif // Cannot be used to index directly into the buffer. -// Use ComputXyTileBufferIndex for that purpose. -uint ComputeXyTileIndex(uint2 pixelCoord) +// Use ComputeXyTileBufferIndex for that purpose. +uint ComputeXyTileIndex(uint2 tileCoord) { - uint2 tileCoord = pixelCoord / XY_TILE_SIZE; - return IndexFromCoordinate(uint4(tileCoord, 0, 0), - uint3(XY_TILE_BUFFER_DIMS.x, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(XY_TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); } -// 'tileIndex' may be computed by invoking ComputeXyTileIndex. -uint ComputeXyTileBufferIndex(uint tileIndex, uint category, uint eye) +// xyTile: output of ComputeXyTileIndex. +uint ComputeXyTileBufferIndex(uint xyTile, uint category, uint eye) { - const uint stride = XY_TILE_ENTRY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + uint stride = XY_TILE_ENTRY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + uint offset = IndexFromCoordinate(uint4(0, 0, category, eye), + uint3(XY_TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); - return stride * (tileIndex + IndexFromCoordinate(uint4(0, 0, category, eye), - uint3(XY_TILE_BUFFER_DIMS.x, Z_BIN_COUNT, BOUNDEDENTITYCATEGORY_COUNT))); + return stride * (offset + xyTile); } #endif // NO_SHADERVARIABLESGLOBAL_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute index e3fef737122..d7e2268e69f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute @@ -1,12 +1,12 @@ #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -// Generates large screen tiles in a fast, conservative manner -#pragma kernel FillCoarseXyTile COARSE_BINNING PASS = FILL_COARSE_XY_TILE -// Removes certain entities from the coarse buffer at a large cost -#pragma kernel PruneCoarseXyTile COARSE_BINNING PASS = PRUNE_COARSE_XY_TILE -// Generates small screen tiles in an accurate manner -#pragma kernel BuildFineXyTile FINE_BINNING PASS = BUILD_FINE_XY_TILE +// Generates large screen tiles in a fast, conservative manner. +#pragma kernel FillCoarseXyTile PASS = FILL_COARSE_XY_TILE COARSE_BINNING +// Removes certain entities from the coarse buffer at a large cost. +#pragma kernel PruneCoarseXyTile PASS = PRUNE_COARSE_XY_TILE COARSE_BINNING +// Generates small screen tiles in an accurate manner. +#pragma kernel BuildFineXyTile PASS = BUILD_FINE_XY_TILE FINE_BINNING #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" @@ -43,8 +43,8 @@ /* ------------------------------ Utilities --------------------------------- */ // Repackage to work around ridiculous constant buffer limitations of HLSL. -static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; /* ------------------------------ Implementation ---------------------------- */ @@ -58,8 +58,8 @@ static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // We could tile the threads in 8x8 blocks. The problem is, - // the size of the buffer is already quite small. The extra padding - // (helper threads) required outweights the benefits (reduced divergence). + // the dimensions of the buffer are already quite small. The extra padding + // (helper threads) required outweighs the benefits (reduced divergence). const uint t = threadID; const uint g = groupID.x; const uint cat = groupID.y; @@ -83,7 +83,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // Compute 2-D the AABB of the tile. const uint2 tileAaBbMinPtSS = clampedTileCoord * XY_TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + XY_TILE_SIZE; // (clampedTileCoord + 1) * COARSE_XY_TILE_SIZE + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + XY_TILE_SIZE; // (clampedTileCoord + 1) * XY_TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? @@ -127,8 +127,9 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if (j < XY_TILE_ENTRY_LIMIT) { - // Add a terminator. - indexPair |= UINT16_MAX << (16 * (j & 1)); // Order: first Lo, then Hi bits + i = UINT16_MAX; // Add a terminator + + indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits _CoarseXyTileBuffer[outputStart + (j / 2)] = indexPair; } @@ -137,8 +138,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); - // We do not clear the buffer, so we must add a terminator. - _CoarseXyTileBuffer[outputStart] = UINT16_MAX; + _CoarseXyTileBuffer[outputStart] = UINT16_MAX; // Add a terminator } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index e9193d9a546..0a12f513189 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -20,13 +20,13 @@ StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} // The size of the buffer can be computed as follows: // Z_BIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (4 bytes per range). // For example (1080p): 8192 * 5 * 1 * 4 = 160 KiB. -RWStructuredBuffer _zBinBuffer : register(u0); // {start << 16 | end} +RWStructuredBuffer _zBinBuffer : register(u0); // {last << 16 | first} /* ------------------------------ Utilities --------------------------------- */ // Repackage to work around ridiculous constant buffer limitations of HLSL. -static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; /* ------------------------------ Implementation ---------------------------- */ @@ -96,7 +96,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } uint outputIndex = ComputeZBinBufferIndex(bin, cat, eye); - uint outputRange = (first > last) ? 0 : (first << 16) | (last + 1); + uint outputRange = (last << 16) | first; _zBinBuffer[outputIndex] = outputRange; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index e91bed9af51..f5f233240e4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -740,7 +740,7 @@ VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCame var currParams = hdCamera.vBufferParams[currIdx]; parameters.viewCount = hdCamera.viewCount; - parameters.tiledLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass) && m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume) > 0; + parameters.tiledLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting) && m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume) > 0; bool optimal = currParams.voxelSize == 8; @@ -863,7 +863,7 @@ VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCame var fog = hdCamera.volumeStack.GetComponent(); // Only available in the Play Mode because all the frame counters in the Edit Mode are broken. - parameters.tiledLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass); + parameters.tiledLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting); parameters.enableReprojection = hdCamera.IsVolumetricReprojectionEnabled(); bool enableAnisotropy = fog.anisotropy.value != 0; bool optimal = currParams.voxelSize == 8; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute index ecc1053a3c2..9ce1c21add3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute @@ -26,7 +26,7 @@ void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw); float2 uv =ClampAndScaleUVForBilinear(posInputs.positionNDC); _OutputTexture[COORD_TEXTURE2D_X(posInputs.positionSS)] = SAMPLE_TEXTURE2D_X_LOD(_InputTexture, sampler_LinearClamp, uv, 0.0).CTYPE_SWIZZLE; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute index 8981d33ab2f..7ed40bd20ab 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute @@ -30,7 +30,7 @@ RW_TEXTURE2D_X(float, _OutputTexture); void KMainCoCPhysical(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(GROUP_RES, GROUP_RES)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); float depth = LoadCameraDepth(posInputs.positionSS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute index 3d313dab02c..fa6b4060743 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute @@ -48,7 +48,7 @@ void KPrePass(uint2 dispatchThreadId : SV_DispatchThreadID) // For XR, interleave single-pass views in a checkerboard pattern UNITY_XR_ASSIGN_VIEW_INDEX((dispatchThreadId.x + dispatchThreadId.y) % _XRViewCount) - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId), rcp(PREPASS_TEX_SIZE), uint2(8u, 8u)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId), rcp(PREPASS_TEX_SIZE)); float2 uv = ClampAndScaleUVForBilinear(posInputs.positionNDC); float luma = SampleLuminance(uv); @@ -112,7 +112,7 @@ void KReduction(uint2 groupId : SV_GroupID, uint2 groupThreadId : SV_GroupThread if (gs_weights[0] > 0.0) avgLuminance /= (gs_weights[0] * 0.25); - + UNITY_BRANCH switch (ParamEvaluateMode) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute index 8a0b252c5a1..90a5a480450 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute @@ -109,13 +109,13 @@ float2 DistortUV(float2 uv) void Uber(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); float2 uv = posInputs.positionNDC; float2 uvDistorted = DistortUV(uv); CTYPE color = 0.0; CTYPE inputColor = 0.0; - // Chromatic aberration + // Chromatic aberration // Inspired by the method described in "Rendering Inside" [Playdead 2016] // https://twitter.com/pixelmager/status/717019757766123520 #ifdef CHROMATIC_ABERRATION diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 72456fad409..a4e9514a4b6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -169,7 +169,7 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend } // Big Tile buffer - if (passData.buildGPULightListParameters.runBigTilePrepass) + if (passData.buildGPULightListParameters.binEntities) { var nrBigTilesX = (m_MaxCameraWidth + 63) / 64; var nrBigTilesY = (m_MaxCameraHeight + 63) / 64; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index 6aba373a526..dcad3ab2fd7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -509,7 +509,7 @@ static void BindProbeVolumeGlobalData(in FrameSettings frameSettings, GBufferPas if (!data.needProbeVolumeLightLists) return; - if (frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) + if (frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) ctx.cmd.SetGlobalBuffer(HDShaderIDs.g_vBigTileLightList, data.probeVolumeBigTile); ctx.cmd.SetGlobalBuffer(HDShaderIDs.g_vProbeVolumesLayeredOffsetsBuffer, data.probeVolumePerVoxelOffset); ctx.cmd.SetGlobalBuffer(HDShaderIDs.g_vProbeVolumesLightListGlobal, data.probeVolumePerVoxelLightList); @@ -541,7 +541,7 @@ void RenderGBuffer(RenderGraph renderGraph, TextureHandle sssBuffer, TextureHand passData.needProbeVolumeLightLists = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.MaterialPass; if (passData.needProbeVolumeLightLists) { - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BigTilePrepass)) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) passData.probeVolumeBigTile = builder.ReadComputeBuffer(probeVolumeLightList.bigTileLightList); passData.probeVolumePerVoxelLightList = builder.ReadComputeBuffer(probeVolumeLightList.perVoxelLightLists); passData.probeVolumePerVoxelOffset = builder.ReadComputeBuffer(probeVolumeLightList.perVoxelOffset); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute index 1db8a9e4685..7ad407836f6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute @@ -87,7 +87,7 @@ void RaytracingAreaShadowPrepass(uint3 dispatchThreadId : SV_DispatchThreadID, u return; // Compute the position input structure - PositionInputs posInput = GetPositionInput(currentCoord, _ScreenSize.zw, depthValue, UNITY_MATRIX_I_VP, GetWorldToViewMatrix(), 0); + PositionInputs posInput = GetPositionInput(currentCoord, _ScreenSize.zw, depthValue, UNITY_MATRIX_I_VP, GetWorldToViewMatrix()); // Convert this to a world space position float3 positionWS = GetAbsolutePositionWS(posInput.positionWS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs index 405a76fcf0b..26527103817 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs @@ -196,7 +196,7 @@ internal static void MigrateFromClassVersion(ref ObsoleteFrameSettings oldFrameS newFrameSettingsFormat.SetEnabled(FrameSettingsField.ComputeLightVariants, oldFrameSettingsFormat.lightLoopSettings.enableComputeLightVariants); newFrameSettingsFormat.SetEnabled(FrameSettingsField.ComputeMaterialVariants, oldFrameSettingsFormat.lightLoopSettings.enableComputeMaterialVariants); newFrameSettingsFormat.SetEnabled(FrameSettingsField.FPTLForForwardOpaque, oldFrameSettingsFormat.lightLoopSettings.enableFptlForForwardOpaque); - newFrameSettingsFormat.SetEnabled(FrameSettingsField.BigTilePrepass, oldFrameSettingsFormat.lightLoopSettings.enableBigTilePrepass); + newFrameSettingsFormat.SetEnabled(FrameSettingsField.BinnedLighting, oldFrameSettingsFormat.lightLoopSettings.enableBigTilePrepass); } // OverrideMask @@ -320,7 +320,7 @@ internal static void MigrateFromClassVersion(ref ObsoleteFrameSettings oldFrameS newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.DeferredTile] = true; break; case ObsoleteLightLoopSettingsOverrides.BigTilePrepass: - newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.BigTilePrepass] = true; + newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.BinnedLighting] = true; break; case ObsoleteLightLoopSettingsOverrides.ComputeLightEvaluation: newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ComputeLightEvaluation] = true; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs index b9950eedb66..5546087bf79 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs @@ -329,9 +329,9 @@ public enum FrameSettingsField /// When enabled, HDRP uses FPTL for forward opaque. [FrameSettingsField(3, autoName: FPTLForForwardOpaque)] FPTLForForwardOpaque = 120, - /// When enabled, HDRP uses a big tile prepass for light visibility. - [FrameSettingsField(3, autoName: BigTilePrepass)] - BigTilePrepass = 121, + /// When enabled, HDRP performs binning to determine the set of visible lights. + [FrameSettingsField(3, autoName: BinnedLighting)] + BinnedLighting = 121, /// When enabled, HDRP uses tiles to compute deferred lighting. [FrameSettingsField(3, autoName: DeferredTile)] DeferredTile = 122, @@ -428,7 +428,7 @@ partial struct FrameSettings (uint)FrameSettingsField.ComputeLightVariants, (uint)FrameSettingsField.ComputeMaterialVariants, (uint)FrameSettingsField.FPTLForForwardOpaque, - (uint)FrameSettingsField.BigTilePrepass, + (uint)FrameSettingsField.BinnedLighting, (uint)FrameSettingsField.TransparentsWriteMotionVector, (uint)FrameSettingsField.ReflectionProbe, (uint)FrameSettingsField.PlanarProbe, @@ -487,7 +487,7 @@ partial struct FrameSettings (uint)FrameSettingsField.ComputeLightVariants, (uint)FrameSettingsField.ComputeMaterialVariants, (uint)FrameSettingsField.FPTLForForwardOpaque, - (uint)FrameSettingsField.BigTilePrepass, + (uint)FrameSettingsField.BinnedLighting, (uint)FrameSettingsField.ReflectionProbe, (uint)FrameSettingsField.RayTracing, // (uint)FrameSettingsField.EnableSkyReflection, @@ -541,7 +541,7 @@ partial struct FrameSettings (uint)FrameSettingsField.ComputeLightVariants, (uint)FrameSettingsField.ComputeMaterialVariants, (uint)FrameSettingsField.FPTLForForwardOpaque, - (uint)FrameSettingsField.BigTilePrepass, + (uint)FrameSettingsField.BinnedLighting, (uint)FrameSettingsField.ReplaceDiffuseForIndirect, // (uint)FrameSettingsField.EnableSkyReflection, // (uint)FrameSettingsField.DirectSpecularLighting, diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl index 2fa5cd5fcdd..57a7c4e4d96 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl @@ -88,7 +88,7 @@ void Frag( PackedVaryingsToPS packedInput, float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); #else // Decal mesh // input.positionSS is SV_Position - PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz, uint2(0, 0)); + PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz); #ifdef VARYINGS_NEED_POSITION_WS float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl index 4a392bdfc40..b2d13122ea6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl @@ -115,10 +115,8 @@ void Frag(PackedVaryingsToPS packedInput, // We need to readapt the SS position as our screen space positions are for a low res buffer, but we try to access a full res buffer. input.positionSS.xy = _OffScreenRendering > 0 ? (input.positionSS.xy * _OffScreenDownsampleFactor) : input.positionSS.xy; - uint2 tileIndex = uint2(input.positionSS.xy) / GetTileSize(); - // input.positionSS is SV_Position - PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz, tileIndex); + PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz); #ifdef VARYINGS_NEED_POSITION_WS float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/HDRenderPipelineResources.asset b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/HDRenderPipelineResources.asset index 7ea01347b1e..8def6ba7bf3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/HDRenderPipelineResources.asset +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/HDRenderPipelineResources.asset @@ -35,8 +35,8 @@ MonoBehaviour: clearLightListsCS: {fileID: 7200000, guid: 743eb3491795b9545955695d591195a1, type: 3} buildDispatchIndirectCS: {fileID: 7200000, guid: 4eb1b418be7044c40bb5200496c50f14, type: 3} buildScreenAABBCS: {fileID: 7200000, guid: 728dce960f8a9c44bbc3abb3b851d8f6, type: 3} - buildPerTileLightListCS: {fileID: 7200000, guid: 65af3444cbf4b3747a4dead7ee00cfee, type: 3} - buildPerBigTileLightListCS: {fileID: 7200000, guid: 5ee1f9d6e09abe045b2f5e0b784b9072, type: 3} + zBinCS: {fileID: 7200000, guid: 313c8dc48c577184997e1c10638c6499, type: 3} + xyTileCS: {fileID: 7200000, guid: ecd07937befe9614d90276f5d8609b3e, type: 3} buildPerVoxelLightListCS: {fileID: 7200000, guid: 0bb1b7e0ddcd5c44baf3ddc7456eb196, type: 3} lightListClusterClearAtomicIndexCS: {fileID: 7200000, guid: 1e3472a94b14a334a93230bbc700d7b2, type: 3} buildMaterialFlagsCS: {fileID: 7200000, guid: fb3eda953cd6e634e877fb777be2cd08, type: 3} diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs index 61e1d2db53d..5148f8ca2d0 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs @@ -445,7 +445,7 @@ out GameObject prefab Assert.AreEqual(legacyFrameSettingsData.runContactShadowsAsync, frameSettingsData.IsEnabled(FrameSettingsField.ContactShadowsAsync)); Assert.AreEqual(legacyFrameSettingsData.runVolumeVoxelizationAsync, frameSettingsData.IsEnabled(FrameSettingsField.VolumeVoxelizationsAsync)); - Assert.AreEqual(legacyFrameSettingsData.lightLoopSettings.enableBigTilePrepass, frameSettingsData.IsEnabled(FrameSettingsField.BigTilePrepass)); + Assert.AreEqual(legacyFrameSettingsData.lightLoopSettings.enableBigTilePrepass, frameSettingsData.IsEnabled(FrameSettingsField.BinnedLighting)); Assert.AreEqual(legacyFrameSettingsData.lightLoopSettings.enableComputeLightEvaluation, frameSettingsData.IsEnabled(FrameSettingsField.ComputeLightEvaluation)); Assert.AreEqual(legacyFrameSettingsData.lightLoopSettings.enableComputeLightVariants, frameSettingsData.IsEnabled(FrameSettingsField.ComputeLightVariants)); Assert.AreEqual(legacyFrameSettingsData.lightLoopSettings.enableComputeMaterialVariants, frameSettingsData.IsEnabled(FrameSettingsField.ComputeMaterialVariants)); @@ -484,7 +484,7 @@ out GameObject prefab Assert.AreEqual((legacyFrameSettingsData.overrides & LegacyFrameSettingsOverrides.ContactShadowsAsync) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.ContactShadowsAsync]); Assert.AreEqual((legacyFrameSettingsData.overrides & LegacyFrameSettingsOverrides.VolumeVoxelizationsAsync) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.VolumeVoxelizationsAsync]); - Assert.AreEqual((legacyFrameSettingsData.lightLoopSettings.overrides & LegacyLightLoopSettingsOverrides.BigTilePrepass) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.BigTilePrepass]); + Assert.AreEqual((legacyFrameSettingsData.lightLoopSettings.overrides & LegacyLightLoopSettingsOverrides.BigTilePrepass) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.BinnedLighting]); Assert.AreEqual((legacyFrameSettingsData.lightLoopSettings.overrides & LegacyLightLoopSettingsOverrides.ComputeLightEvaluation) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.ComputeLightEvaluation]); Assert.AreEqual((legacyFrameSettingsData.lightLoopSettings.overrides & LegacyLightLoopSettingsOverrides.ComputeLightVariants) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.ComputeLightVariants]); Assert.AreEqual((legacyFrameSettingsData.lightLoopSettings.overrides & LegacyLightLoopSettingsOverrides.ComputeMaterialVariants) > 0, frameSettingsMask.mask[(uint)FrameSettingsField.ComputeMaterialVariants]); From 1fdea752eea06e6a2eb9beda810f68a2b3aea867 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 23 Oct 2020 15:56:51 -0700 Subject: [PATCH 054/209] Store metadata per tile --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 20 +++--- .../Lighting/LightLoop/LightLoop.cs.hlsl | 4 +- .../Lighting/LightLoop/LightLoopDef.hlsl | 66 +++++++++---------- .../LightLoop/TilingAndBinningUtilities.hlsl | 16 ++++- .../Runtime/Lighting/LightLoop/xyTile.compute | 44 ++++++++----- 5 files changed, 89 insertions(+), 61 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index d2affde8a1b..07892c28192 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -403,8 +403,10 @@ class TiledLightingConstants public static uint s_ScreenSpaceShadowIndexMask = 0xff; // Binned lighting - public static int s_CoarseXyTileEntryLimit = 64; // Per category; before pruning, so, in practice, the number is lower - public static int s_FineXyTileEntryLimit = 16; // Per category; after pruning, so the number is exact + // For performance reasons, keep all sizes in powers of 2. + // The first 2 entries are reserved for the metadata. + public static int s_CoarseXyTileEntryLimit = 64 - 2; // Per category; before pruning, so the number is lower in practice + public static int s_FineXyTileEntryLimit = 16 - 2; // Per category; after pruning, so the number is exact public static int s_CoarseXyTileSize = 64; public static int s_FineXyTileSize = 8; public static int s_zBinCount = 8192; @@ -3548,14 +3550,14 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData return resources; } - //static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuffer cmd, ComputeBuffer bufferToClear) - //{ - // cmd.SetComputeBufferParam(parameters.clearLightListCS, parameters.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear); - // cmd.SetComputeIntParam(parameters.clearLightListCS, HDShaderIDs._LightListEntries, bufferToClear.count); + static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuffer cmd, ComputeBuffer bufferToClear) + { + cmd.SetComputeBufferParam(parameters.clearLightListCS, parameters.clearLightListKernel, HDShaderIDs._LightListToClear, bufferToClear); + cmd.SetComputeIntParam(parameters.clearLightListCS, HDShaderIDs._LightListEntries, bufferToClear.count); - // int groupSize = 64; - // cmd.DispatchCompute(parameters.clearLightListCS, parameters.clearLightListKernel, (bufferToClear.count + groupSize - 1) / groupSize, 1, 1); - //} + int groupSize = 64; + cmd.DispatchCompute(parameters.clearLightListCS, parameters.clearLightListKernel, (bufferToClear.count + groupSize - 1) / groupSize, 1, 1); + } static void ClearLightLists( in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 20d1eb2dcd8..e1d5cbade74 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -70,8 +70,8 @@ #define SCREEN_SPACE_COLOR_SHADOW_FLAG (256) #define INVALID_SCREEN_SPACE_SHADOW (255) #define SCREEN_SPACE_SHADOW_INDEX_MASK (255) -#define COARSE_XY_TILE_ENTRY_LIMIT (64) -#define FINE_XY_TILE_ENTRY_LIMIT (16) +#define COARSE_XY_TILE_ENTRY_LIMIT (62) +#define FINE_XY_TILE_ENTRY_LIMIT (14) #define COARSE_XY_TILE_SIZE (64) #define FINE_XY_TILE_SIZE (8) #define Z_BIN_COUNT (8192) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 816839fd782..7e0cc389625 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -153,46 +153,46 @@ bool TryLoadPunctualLightData(inout uint i, uint xyTile, uint zBin, out LightDat bool b = false; uint n = XY_TILE_ENTRY_LIMIT; - // These values are loop-invariant. They do not depend on the value of 'i'. + // This part (1) is loop-invariant. These values do not depend on the value of 'i'. // They will only be computed once per category, not once per function call. const uint xyTileBufferIndex = ComputeXyTileBufferIndex(xyTile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); - const uint firstTileEntry = XY_TILE_BUFFER[xyTileBufferIndex]; + const uint xyTilePackedRange = XY_TILE_BUFFER[xyTileBufferIndex]; // {last << 16 | first} + const bool isTileEmpty = xyTilePackedRange == UINT16_MAX; - const uint zBinBufferIndex = ComputeZBinBufferIndex( zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); - const uint packedIndexRange = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} - - // TODO: add a range check for the tile here. - const bool isTileEmpty = firstTileEntry == UINT16_MAX; - const bool isBinEmpty = packedIndexRange == UINT16_MAX; - - if (!isTileEmpty && !isBinEmpty) + if (!isTileEmpty) { - const uint firstEntityIndex = packedIndexRange & UINT16_MAX; - const uint lastEntityIndex = packedIndexRange >> 16; + const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint zBinPackedRange = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} - // The part below will be actually executed during every function call. - while (i < n) - { - // This is a valid buffer index. - uint entityIndexPair = XY_TILE_BUFFER[xyTileBufferIndex + (i / 2)]; // 16-bit indices - uint entityIndex = BitFieldExtract(entityIndexPair, 16 * (i & 1), 16); // Order: first Lo, then Hi bits + const uint2 xyTileRange = uint2(xyTilePackedRange & UINT16_MAX, xyTilePackedRange >> 16); + const uint2 zBinRange = uint2( zBinPackedRange & UINT16_MAX, zBinPackedRange >> 16); - // Entity indices are stored in the ascending order. - // We can distinguish 3 cases: - if (entityIndex < firstEntityIndex) - { - i++; // Skip this entity; continue the search - } - else if (entityIndex <= lastEntityIndex) - { - data = _PunctualLightData[entityIndex]; - - b = true; // Found a valid index - break; // Avoid incrementing 'i' further - } - else // if (lastEntityIndex < entityIndex) + if (IntervalsOverlap(xyTileRange, zBinRange)) + { + // The part (2) below will be actually executed during every function call. + while (i < n) { - break; // Avoid incrementing 'i' further + // This is a valid buffer index. +1 because the first uint is reserved for the metadata. + uint entityIndexPair = XY_TILE_BUFFER[(xyTileBufferIndex + 1) + (i / 2)]; // 16-bit indices + uint entityIndex = BitFieldExtract(entityIndexPair, 16 * (i & 1), 16); // Order: first Lo, then Hi bits + + // Entity indices are stored in the ascending order. + // We can distinguish 3 cases: + if (entityIndex < zBinRange.x) + { + i++; // Skip this entity; continue the (linear) search + } + else if (entityIndex <= zBinRange.y) + { + data = _PunctualLightData[entityIndex]; + + b = true; // Found a valid index + break; // Avoid incrementing 'i' further + } + else // if (zBinRange.y < entityIndex) + { + break; // Avoid incrementing 'i' further + } } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 663d8ce3b9d..ae61b45f08b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -94,7 +94,18 @@ bool IntervalsOverlap(float2 i1, float2 i2) float l = max(i1.x, i2.x); // Lower bound of the intersection interval float u = min(i1.y, i2.y); // Upper bound of the intersection interval - return l <= u; // Is the interval non-empty? + return l <= u; // Is the intersection non-empty? +} + +// The intervals must be defined s.t. +// the 'x' component holds the lower bound and +// the 'y' component holds the upper bound. +bool IntervalsOverlap(uint2 i1, uint2 i2) +{ + uint l = max(i1.x, i2.x); // Lower bound of the intersection interval + uint u = min(i1.y, i2.y); // Upper bound of the intersection interval + + return l <= u; // Is the intersection non-empty? } uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) @@ -148,7 +159,8 @@ uint ComputeXyTileIndex(uint2 tileCoord) // xyTile: output of ComputeXyTileIndex. uint ComputeXyTileBufferIndex(uint xyTile, uint category, uint eye) { - uint stride = XY_TILE_ENTRY_LIMIT / 2; // We use 'uint' buffer rather than a 'uint16_t[n]' + // We use 'uint' buffer rather than a 'uint16_t[n]'. + uint stride = (XY_TILE_ENTRY_LIMIT + 2) / 2; // The first 2 entries are reserved for the metadata uint offset = IndexFromCoordinate(uint4(0, 0, category, eye), uint3(XY_TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute index d7e2268e69f..d8fc8047936 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute @@ -27,7 +27,7 @@ // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, COARSE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_XY_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (COARSE_XY_TILE_ENTRY_LIMIT * 2 bytes per entry). + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((COARSE_XY_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. RWStructuredBuffer _CoarseXyTileBuffer : register(u0); // List of 16-bit indices #endif @@ -36,7 +36,7 @@ // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, FINE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_XY_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (FINE_XY_TILE_ENTRY_LIMIT * 2 bytes per entry). + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((FINE_XY_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). // For example (1080p): 240 * 165 * 5 * 1 * (16 * 2) = 6.04 MiB. #endif @@ -48,8 +48,8 @@ static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin /* ------------------------------ Implementation ---------------------------- */ -#if (REMAINDER(XY_TILE_ENTRY_LIMIT, 2) != 0) - #error "XY_TILE_ENTRY_LIMIT must be an integer multiple of 2." +#if (REMAINDER(XY_TILE_ENTRY_LIMIT + 2, 2) != 0) + #error "(XY_TILE_ENTRY_LIMIT + 2) must be an integer multiple of 2." #endif #define THREADS_PER_GROUP (64) @@ -79,6 +79,11 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint entityIndex = s_BoundedEntityOffsetPerCategory[cat]; const uint entityCount = s_BoundedEntityCountPerCategory[cat]; + const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); + const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); + + uint first = UINT16_MAX, last = 0; + if (entityCount > 0) // Avoid wasted work { // Compute 2-D the AABB of the tile. @@ -89,12 +94,9 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); // TODO: add epsilon for numerical robustness? - const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); - const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); - // Define inputs and outputs. uint i = 0, j = 0; - uint indexPair = 0; // TODO: store not just the indices themselves, but also their min-max for early out + uint indexPair = 0; // The algorithm is O(n * m) where 'n' is the entity count and 'm' is tile count. // Therefore, it will be slow if 'n' is large. @@ -109,12 +111,16 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) IntervalsOverlap(entityBoundsY, tileBoundsY)) { // We store intra-category indices. + first = min(i, first); + last = max(i, last); + // 2x 16-bit indices per uint. indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits if ((j & 1) != 0) // Is the pair complete & ready to be stored? { - _CoarseXyTileBuffer[outputStart + (j / 2)] = indexPair; + // +1 because the first uint is reserved for the metadata. + _CoarseXyTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; indexPair = 0; // In order to use bitwise OR above } @@ -131,15 +137,23 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits - _CoarseXyTileBuffer[outputStart + (j / 2)] = indexPair; + _CoarseXyTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; + + j++; } - } - else - { - const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); - _CoarseXyTileBuffer[outputStart] = UINT16_MAX; // Add a terminator + // You can clear the buffer for debugging purposes. + // while (j < XY_TILE_ENTRY_LIMIT) + // { + // _CoarseXyTileBuffer[(outputStart + 1) + (j / 2)] = 0; + // j += 2; + // } } + + uint outputRange = (last << 16) | first; + + // Store the metadata. + _CoarseXyTileBuffer[outputStart] = outputRange; } [numthreads(THREADS_PER_GROUP, 1, 1)] From b72b6e6518466c5eba2e3dcdb4264f6cb9cfe8d9 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 23 Oct 2020 16:46:09 -0700 Subject: [PATCH 055/209] Rename 'xyTile' -> 'tile' --- .../ShaderLibrary/Common.hlsl | 4 +- .../Lighting/LightLoop/Deferred.compute | 11 +-- .../Runtime/Lighting/LightLoop/LightLoop.cs | 88 +++++++++---------- .../Lighting/LightLoop/LightLoop.cs.hlsl | 8 +- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 2 +- .../Lighting/LightLoop/LightLoopDef.hlsl | 28 +++--- .../LightLoop/ShaderVariablesLightLoop.hlsl | 4 +- .../LightLoop/TilingAndBinningUtilities.hlsl | 38 ++++---- .../{xyTile.compute => tile.compute} | 56 ++++++------ ...{xyTile.compute.meta => tile.compute.meta} | 2 +- .../RenderPipeline/HDStringConstants.cs | 4 +- .../RenderPipeline/RenderPipelineResources.cs | 4 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 4 +- .../ShaderVariablesGlobal.cs.hlsl | 4 +- 14 files changed, 129 insertions(+), 128 deletions(-) rename com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/{xyTile.compute => tile.compute} (73%) rename com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/{xyTile.compute.meta => tile.compute.meta} (81%) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index 3ebbb2a0d2b..0e1ecc2cc95 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1039,7 +1039,7 @@ struct PositionInputs float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed) float linearDepth; // View space Z coordinate : [Near, Far] - uint xyTile; // Screen tile index + uint tile; // Screen tile index uint zBin; // Depth bin index }; @@ -1062,7 +1062,7 @@ PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize) // These two are only used by certain (binned lighting) passes, // so they must be initialized explicitly (only when necessary). - posInput.xyTile = posInput.zBin = 0; + posInput.tile = posInput.zBin = 0; return posInput; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index d5270ffaa4b..70227618042 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -119,7 +119,7 @@ void SHADE_OPAQUE_ENTRY(uint2 groupThreadId : SV_GroupThreadID, uint groupId : S uint numTilesX = (screenWidth + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL; uint tileVariantIndex = tileCoord.x + tileCoord.y * numTilesX; - uint xyTile = 0; + uint tile = 0; #if defined(UNITY_STEREO_INSTANCING_ENABLED) uint screenHeight = (uint)_ScreenSize.y; @@ -136,8 +136,8 @@ void SHADE_OPAQUE_ENTRY(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 grou { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - uint2 tileCoord = (GROUP_SIZE * groupId) / XY_TILE_SIZE; - uint xyTile = ComputeXyTileIndex(tileCoord); + uint2 tileCoord = (GROUP_SIZE * groupId) / TILE_SIZE; + uint tile = ComputeTileIndex(tileCoord); uint2 pixelCoord = dispatchThreadId.xy; uint featureFlags = UINT_MAX; @@ -147,8 +147,9 @@ void SHADE_OPAQUE_ENTRY(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 grou float depth = LoadCameraDepth(pixelCoord.xy); PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); - posInput.xyTile = xyTile; - posInput.zBin = ComputeZBinIndex(posInput.linearDepth); + + posInput.tile = tile; + posInput.zBin = ComputeZBinIndex(posInput.linearDepth); // For indirect case: we can still overlap inside a tile with the sky/background, reject it // Can't rely on stencil as we are in compute shader diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 07892c28192..4621409fb62 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -405,11 +405,11 @@ class TiledLightingConstants // Binned lighting // For performance reasons, keep all sizes in powers of 2. // The first 2 entries are reserved for the metadata. - public static int s_CoarseXyTileEntryLimit = 64 - 2; // Per category; before pruning, so the number is lower in practice - public static int s_FineXyTileEntryLimit = 16 - 2; // Per category; after pruning, so the number is exact - public static int s_CoarseXyTileSize = 64; - public static int s_FineXyTileSize = 8; - public static int s_zBinCount = 8192; + public static int s_CoarseTileEntryLimit = 64 - 2; // Per category; before pruning, so the number is lower in practice + public static int s_FineTileEntryLimit = 16 - 2; // Per category; after pruning, so the number is exact + public static int s_CoarseTileSize = 64; + public static int s_FineTileSize = 8; + public static int s_zBinCount = 8192; } [GenerateHLSL] @@ -701,8 +701,8 @@ class TileAndClusterData public ComputeBuffer globalLightListAtomic { get; private set; } // Binned lighting - public ComputeBuffer coarseXyTileBuffer { get; private set; } - public ComputeBuffer zBinBuffer { get; private set; } + public ComputeBuffer coarseTileBuffer { get; private set; } + public ComputeBuffer zBinBuffer { get; private set; } // Tile Output public ComputeBuffer tileFeatureFlags { get; private set; } // Deferred @@ -776,13 +776,13 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, zBinBuffer = new ComputeBuffer(TiledLightingConstants.s_zBinCount * (int)BoundedEntityCategory.Count * viewCount, sizeof(uint)); // {last << 16 | first} /* Actually resolution-dependent buffers below. */ - Vector2Int coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); + Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); - int coarseXyTileBufferElementCount = coarseXyTileBufferDimensions.x * coarseXyTileBufferDimensions.y * - (int)BoundedEntityCategory.Count * viewCount * - (TiledLightingConstants.s_CoarseXyTileEntryLimit / 2); + int coarseTileBufferElementCount = coarseTileBufferDimensions.x * coarseTileBufferDimensions.y * + (int)BoundedEntityCategory.Count * viewCount * + (TiledLightingConstants.s_CoarseTileEntryLimit / 2); - coarseXyTileBuffer = new ComputeBuffer(coarseXyTileBufferElementCount, sizeof(uint)); // List of 16-bit indices + coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // List of 16-bit indices } // Make sure to invalidate the content of the buffers @@ -830,8 +830,8 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() wBoundsBuffer = null; CoreUtils.SafeRelease(zBinBuffer); zBinBuffer = null; - CoreUtils.SafeRelease(coarseXyTileBuffer); - coarseXyTileBuffer = null; + CoreUtils.SafeRelease(coarseTileBuffer); + coarseTileBuffer = null; CoreUtils.SafeRelease(dispatchIndirectBuffer); dispatchIndirectBuffer = null; } @@ -904,7 +904,7 @@ static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) ComputeShader buildScreenAABBShader { get { return defaultResources.shaders.buildScreenAABBCS; } } ComputeShader zBinShader { get { return defaultResources.shaders.zBinCS; } } - ComputeShader xyTileShader { get { return defaultResources.shaders.xyTileCS; } } + ComputeShader tileShader { get { return defaultResources.shaders.tileCS; } } ComputeShader buildPerTileLightListShader { get { return defaultResources.shaders.buildPerTileLightListCS; } } ComputeShader buildPerBigTileLightListShader { get { return defaultResources.shaders.buildPerBigTileLightListCS; } } ComputeShader buildPerVoxelLightListShader { get { return defaultResources.shaders.buildPerVoxelLightListCS; } } @@ -1053,18 +1053,18 @@ static Vector4 GetZBinBufferEncodingParams(HDCamera hdCamera) return new Vector4(x, y, z, w); } - static Vector2Int GetCoarseXyTileBufferDimensions(HDCamera hdCamera) + static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseXyTileSize); - int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseXyTileSize); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_CoarseTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_CoarseTileSize); return new Vector2Int(w, h); } - static Vector2Int GetFineXyTileBufferDimensions(HDCamera hdCamera) + static Vector2Int GetFineTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineXyTileSize); - int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineXyTileSize); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineTileSize); return new Vector2Int(w, h); } @@ -3463,8 +3463,8 @@ struct BuildGPULightListParameters public bool binEntities; public ComputeShader screenSpaceAABBShader; public ComputeShader zBinShader; - public ComputeShader xyTileShader; - public Vector2Int coarseXyTileBufferDimensions; + public ComputeShader tileShader; + public Vector2Int coarseTileBufferDimensions; // Big Tile public ComputeShader bigTilePrepassShader; @@ -3508,7 +3508,7 @@ struct BuildGPULightListResources public ComputeBuffer xyBoundsBuffer; public ComputeBuffer wBoundsBuffer; public ComputeBuffer zBinBuffer; - public ComputeBuffer coarseXyTileBuffer; + public ComputeBuffer coarseTileBuffer; public ComputeBuffer globalLightListAtomic; // Output @@ -3538,7 +3538,7 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.xyBoundsBuffer = tileAndClusterData.xyBoundsBuffer; resources.wBoundsBuffer = tileAndClusterData.wBoundsBuffer; resources.zBinBuffer = tileAndClusterData.zBinBuffer; - resources.coarseXyTileBuffer = tileAndClusterData.coarseXyTileBuffer; + resources.coarseTileBuffer = tileAndClusterData.coarseTileBuffer; //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; @@ -3631,28 +3631,28 @@ static void PerformXYBinning(in BuildGPULightListParameters parameters, in Build // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformXYBinning))) { - var shader = parameters.xyTileShader; + var shader = parameters.tileShader; int kernel; - kernel = 0; // FillCoarseXyTile + kernel = 0; // FillCoarseTile - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseXyTileBuffer, resources.coarseXyTileBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - int bufferSize = parameters.coarseXyTileBufferDimensions.x * parameters.coarseXyTileBufferDimensions.y; + int bufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; int groupCount = HDUtils.DivRoundUp(bufferSize, threadsPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); - kernel = 1; // PruneCoarseXyTile + kernel = 1; // PruneCoarseTile // ... - kernel = 2; // BuildFineXyTile + kernel = 2; // BuildFineTile // ... } @@ -3912,7 +3912,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera var decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, m_MaxDecalsOnScreen); int boundedEntityCount = m_BoundedEntityCollection.GetTotalEntityCount(); - Vector2Int coarseTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); + Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); cb._BoundedEntityCount = (uint)boundedEntityCount; cb.g_screenSize = hdCamera.screenSize; // TODO remove and use global one. @@ -3976,11 +3976,11 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.clearLightListKernel = parameters.clearLightListCS.FindKernel("ClearList"); // Binned lighting - parameters.binEntities = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting); - parameters.screenSpaceAABBShader = buildScreenAABBShader; - parameters.zBinShader = zBinShader; - parameters.xyTileShader = xyTileShader; - parameters.coarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); + parameters.binEntities = hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting); + parameters.screenSpaceAABBShader = buildScreenAABBShader; + parameters.zBinShader = zBinShader; + parameters.tileShader = tileShader; + parameters.coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); // Big tile prepass parameters.bigTilePrepassShader = buildPerBigTileLightListShader; @@ -4217,9 +4217,9 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H } // Binned lighting - cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); - cb._CoarseXyTileBufferDimensions = GetCoarseXyTileBufferDimensions(hdCamera); - cb._FineXyTileBufferDimensions = GetFineXyTileBufferDimensions(hdCamera); + cb._ZBinBufferEncodingParams = GetZBinBufferEncodingParams(hdCamera); + cb._CoarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + cb._FineTileBufferDimensions = GetFineTileBufferDimensions(hdCamera); // Old stuff below... cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); @@ -4282,9 +4282,9 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman { if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) { - cmd.SetGlobalBuffer(HDShaderIDs._CoarseXyTileBuffer, param.tileAndClusterData.coarseXyTileBuffer); - //cmd.SetGlobalBuffer(HDShaderIDs._FineXyTileBuffer, param.tileAndClusterData.fine); - cmd.SetGlobalBuffer(HDShaderIDs._zBinBuffer, param.tileAndClusterData.zBinBuffer); + cmd.SetGlobalBuffer(HDShaderIDs._CoarseTileBuffer, param.tileAndClusterData.coarseTileBuffer); + //cmd.SetGlobalBuffer(HDShaderIDs._FineTileBuffer, param.tileAndClusterData.fine); + cmd.SetGlobalBuffer(HDShaderIDs._zBinBuffer, param.tileAndClusterData.zBinBuffer); } // Cluster diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index e1d5cbade74..382c33b1967 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -70,10 +70,10 @@ #define SCREEN_SPACE_COLOR_SHADOW_FLAG (256) #define INVALID_SCREEN_SPACE_SHADOW (255) #define SCREEN_SPACE_SHADOW_INDEX_MASK (255) -#define COARSE_XY_TILE_ENTRY_LIMIT (62) -#define FINE_XY_TILE_ENTRY_LIMIT (14) -#define COARSE_XY_TILE_SIZE (64) -#define FINE_XY_TILE_SIZE (8) +#define COARSE_TILE_ENTRY_LIMIT (62) +#define FINE_TILE_ENTRY_LIMIT (14) +#define COARSE_TILE_SIZE (64) +#define FINE_TILE_SIZE (8) #define Z_BIN_COUNT (8192) // diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 32f705f787d..684b2f6b27a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -236,7 +236,7 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS i = 0; - while (TryLoadPunctualLightData(i, posInput.xyTile, posInput.zBin, lightData)) + while (TryLoadPunctualLightData(i, posInput.tile, posInput.zBin, lightData)) { if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 7e0cc389625..a5ea40d9e8a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -148,32 +148,32 @@ float4 SampleEnv(LightLoopContext lightLoopContext, int index, float3 texCoord, #if (defined(COARSE_BINNING) || defined(FINE_BINNING)) -bool TryLoadPunctualLightData(inout uint i, uint xyTile, uint zBin, out LightData data) +bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData data) { bool b = false; - uint n = XY_TILE_ENTRY_LIMIT; + uint n = TILE_ENTRY_LIMIT; // This part (1) is loop-invariant. These values do not depend on the value of 'i'. // They will only be computed once per category, not once per function call. - const uint xyTileBufferIndex = ComputeXyTileBufferIndex(xyTile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); - const uint xyTilePackedRange = XY_TILE_BUFFER[xyTileBufferIndex]; // {last << 16 | first} - const bool isTileEmpty = xyTilePackedRange == UINT16_MAX; + const uint tileBufferIndex = ComputeTileBufferIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint tilePackedRange = TILE_BUFFER[tileBufferIndex]; // {last << 16 | first} + const bool isTileEmpty = tilePackedRange == UINT16_MAX; if (!isTileEmpty) { const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); const uint zBinPackedRange = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} - const uint2 xyTileRange = uint2(xyTilePackedRange & UINT16_MAX, xyTilePackedRange >> 16); - const uint2 zBinRange = uint2( zBinPackedRange & UINT16_MAX, zBinPackedRange >> 16); + const uint2 tileRange = uint2(tilePackedRange & UINT16_MAX, tilePackedRange >> 16); + const uint2 zBinRange = uint2(zBinPackedRange & UINT16_MAX, zBinPackedRange >> 16); - if (IntervalsOverlap(xyTileRange, zBinRange)) + if (IntervalsOverlap(tileRange, zBinRange)) { // The part (2) below will be actually executed during every function call. while (i < n) { // This is a valid buffer index. +1 because the first uint is reserved for the metadata. - uint entityIndexPair = XY_TILE_BUFFER[(xyTileBufferIndex + 1) + (i / 2)]; // 16-bit indices + uint entityIndexPair = TILE_BUFFER[(tileBufferIndex + 1) + (i / 2)]; // 16-bit indices uint entityIndex = BitFieldExtract(entityIndexPair, 16 * (i & 1), 16); // Order: first Lo, then Hi bits // Entity indices are stored in the ascending order. @@ -202,7 +202,7 @@ bool TryLoadPunctualLightData(inout uint i, uint xyTile, uint zBin, out LightDat #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) -bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data) +bool TryLoadPunctualLightData(uint i, uint tile, uint zBin, out LightData data) { bool b = false; uint n = _PunctualLightCount; @@ -216,7 +216,7 @@ bool TryLoadPunctualLightData(uint i, uint xyTile, uint zBin, out LightData data return b; } -bool TryLoadAreaLightData(uint i, uint xyTile, uint zBin, out LightData data) +bool TryLoadAreaLightData(uint i, uint tile, uint zBin, out LightData data) { bool b = false; uint n = _AreaLightCount; @@ -230,7 +230,7 @@ bool TryLoadAreaLightData(uint i, uint xyTile, uint zBin, out LightData data) return b; } -bool TryLoadReflectionProbeData(uint i, uint xyTile, uint zBin, out EnvLightData data) +bool TryLoadReflectionProbeData(uint i, uint tile, uint zBin, out EnvLightData data) { bool b = false; uint n = _ReflectionProbeCount; @@ -244,7 +244,7 @@ bool TryLoadReflectionProbeData(uint i, uint xyTile, uint zBin, out EnvLightData return b; } -bool TryLoadDecalData(uint i, uint xyTile, uint zBin, out DecalData data) +bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) { bool b = false; uint n = _DecalCount; @@ -258,7 +258,7 @@ bool TryLoadDecalData(uint i, uint xyTile, uint zBin, out DecalData data) return b; } -// bool TryLoadDensityVolumeDataDataAndBounds(uint i, uint xyTile, uint zBin, +// bool TryLoadDensityVolumeDataDataAndBounds(uint i, uint tile, uint zBin, // out DensityVolumeEngineData data, out OrientedBBox bounds) // { // bool b = false; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index c433e7f783c..52d12ba1a3f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -3,8 +3,8 @@ #if (defined(COARSE_BINNING) || defined(FINE_BINNING)) // TODO: we don't need both at the same time, so perhaps just declare one? - StructuredBuffer _CoarseXyTileBuffer; - StructuredBuffer _FineXyTileBuffer; + StructuredBuffer _CoarseTileBuffer; + StructuredBuffer _FineTileBuffer; StructuredBuffer _zBinBuffer; #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index ae61b45f08b..3812731624b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -132,39 +132,39 @@ uint ComputeZBinIndex(float linearDepth) } #if defined(COARSE_BINNING) - #define XY_TILE_SIZE COARSE_XY_TILE_SIZE - #define XY_TILE_ENTRY_LIMIT COARSE_XY_TILE_ENTRY_LIMIT - #define XY_TILE_BUFFER _CoarseXyTileBuffer - #define XY_TILE_BUFFER_DIMS uint2(_CoarseXyTileBufferDimensions.xy) + #define TILE_SIZE COARSE_TILE_SIZE + #define TILE_ENTRY_LIMIT COARSE_TILE_ENTRY_LIMIT + #define TILE_BUFFER _CoarseTileBuffer + #define TILE_BUFFER_DIMS uint2(_CoarseTileBufferDimensions.xy) #elif defined(FINE_BINNING) - #define XY_TILE_SIZE FINE_XY_TILE_SIZE - #define XY_TILE_ENTRY_LIMIT FINE_XY_TILE_ENTRY_LIMIT - #define XY_TILE_BUFFER _FineXyTileBuffer - #define XY_TILE_BUFFER_DIMS uint2(_FineXyTileBufferDimensions.xy) + #define TILE_SIZE FINE_TILE_SIZE + #define TILE_ENTRY_LIMIT FINE_TILE_ENTRY_LIMIT + #define TILE_BUFFER _FineTileBuffer + #define TILE_BUFFER_DIMS uint2(_FineTileBufferDimensions.xy) #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) // These must be defined so the compiler does not complain. - #define XY_TILE_SIZE 1 - #define XY_TILE_ENTRY_LIMIT 0 - #define XY_TILE_BUFFER_DIMS uint2(0, 0) + #define TILE_SIZE 1 + #define TILE_ENTRY_LIMIT 0 + #define TILE_BUFFER_DIMS uint2(0, 0) #endif // Cannot be used to index directly into the buffer. -// Use ComputeXyTileBufferIndex for that purpose. -uint ComputeXyTileIndex(uint2 tileCoord) +// Use ComputeTileBufferIndex for that purpose. +uint ComputeTileIndex(uint2 tileCoord) { return IndexFromCoordinate(uint4(tileCoord, 0, 0), - uint3(XY_TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); } -// xyTile: output of ComputeXyTileIndex. -uint ComputeXyTileBufferIndex(uint xyTile, uint category, uint eye) +// tile: output of ComputeTileIndex. +uint ComputeTileBufferIndex(uint tile, uint category, uint eye) { // We use 'uint' buffer rather than a 'uint16_t[n]'. - uint stride = (XY_TILE_ENTRY_LIMIT + 2) / 2; // The first 2 entries are reserved for the metadata + uint stride = (TILE_ENTRY_LIMIT + 2) / 2; // The first 2 entries are reserved for the metadata uint offset = IndexFromCoordinate(uint4(0, 0, category, eye), - uint3(XY_TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); - return stride * (offset + xyTile); + return stride * (offset + tile); } #endif // NO_SHADERVARIABLESGLOBAL_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute similarity index 73% rename from com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute rename to com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index d8fc8047936..5c1daf65d3c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -2,11 +2,11 @@ #pragma only_renderers d3d11 playstation xboxone vulkan metal switch // Generates large screen tiles in a fast, conservative manner. -#pragma kernel FillCoarseXyTile PASS = FILL_COARSE_XY_TILE COARSE_BINNING +#pragma kernel FillCoarseTile PASS = FILL_COARSE_TILE COARSE_BINNING // Removes certain entities from the coarse buffer at a large cost. -#pragma kernel PruneCoarseXyTile PASS = PRUNE_COARSE_XY_TILE COARSE_BINNING +#pragma kernel PruneCoarseTile PASS = PRUNE_COARSE_TILE COARSE_BINNING // Generates small screen tiles in an accurate manner. -#pragma kernel BuildFineXyTile PASS = BUILD_FINE_XY_TILE FINE_BINNING +#pragma kernel BuildFineTile PASS = BUILD_FINE_TILE FINE_BINNING #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" @@ -16,27 +16,27 @@ /* ------------------------------ Inputs ------------------------------------ */ -#if (PASS == FILL_COARSE_XY_TILE) +#if (PASS == FILL_COARSE_TILE) // 1x list for all entites (sorted by category, we concatenate lists of all views). StructuredBuffer _xyBoundsBuffer : register(t0); // {x_min, x_max, y_min, y_max} #endif /* ------------------------------ Outputs ----------------------------------- */ -#if (PASS == FILL_COARSE_XY_TILE) +#if (PASS == FILL_COARSE_TILE) // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: - // DIV_ROUND_UP(RES_X, COARSE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_XY_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((COARSE_XY_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). + // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((COARSE_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. - RWStructuredBuffer _CoarseXyTileBuffer : register(u0); // List of 16-bit indices + RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 16-bit indices #endif -#if (PASS == BUILD_FINE_XY_TILE) +#if (PASS == BUILD_FINE_TILE) // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: - // DIV_ROUND_UP(RES_X, FINE_XY_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_XY_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((FINE_XY_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). + // DIV_ROUND_UP(RES_X, FINE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_TILE_SIZE) * + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((FINE_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). // For example (1080p): 240 * 165 * 5 * 1 * (16 * 2) = 6.04 MiB. #endif @@ -48,14 +48,14 @@ static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin /* ------------------------------ Implementation ---------------------------- */ -#if (REMAINDER(XY_TILE_ENTRY_LIMIT + 2, 2) != 0) - #error "(XY_TILE_ENTRY_LIMIT + 2) must be an integer multiple of 2." +#if (REMAINDER(TILE_ENTRY_LIMIT + 2, 2) != 0) + #error "(TILE_ENTRY_LIMIT + 2) must be an integer multiple of 2." #endif #define THREADS_PER_GROUP (64) [numthreads(THREADS_PER_GROUP, 1, 1)] -void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void FillCoarseTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // We could tile the threads in 8x8 blocks. The problem is, // the dimensions of the buffer are already quite small. The extra padding @@ -66,8 +66,8 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint eye = groupID.z; const uint tileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); - const uint clampedTileIndex = min(tileIndex, XY_TILE_BUFFER_DIMS.x * XY_TILE_BUFFER_DIMS.y - 1); - const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, XY_TILE_BUFFER_DIMS.x); + const uint clampedTileIndex = min(tileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -80,15 +80,15 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint entityCount = s_BoundedEntityCountPerCategory[cat]; const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); - const uint outputStart = ComputeXyTileBufferIndex(clampedTileIndex, cat, eye); + const uint outputStart = ComputeTileBufferIndex(clampedTileIndex, cat, eye); uint first = UINT16_MAX, last = 0; if (entityCount > 0) // Avoid wasted work { // Compute 2-D the AABB of the tile. - const uint2 tileAaBbMinPtSS = clampedTileCoord * XY_TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + XY_TILE_SIZE; // (clampedTileCoord + 1) * XY_TILE_SIZE + const uint2 tileAaBbMinPtSS = clampedTileCoord * TILE_SIZE; + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (clampedTileCoord + 1) * TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? @@ -102,7 +102,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // Therefore, it will be slow if 'n' is large. // We should consider a sorting-based algorithm, which could be closer to O((n + m) * log(n)). // TODO: unroll. - while ((i < entityCount) && (j < XY_TILE_ENTRY_LIMIT)) + while ((i < entityCount) && (j < TILE_ENTRY_LIMIT)) { float2 entityBoundsX = _xyBoundsBuffer[inputStart + i].xy; float2 entityBoundsY = _xyBoundsBuffer[inputStart + i].zw; @@ -120,7 +120,7 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if ((j & 1) != 0) // Is the pair complete & ready to be stored? { // +1 because the first uint is reserved for the metadata. - _CoarseXyTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; + _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; indexPair = 0; // In order to use bitwise OR above } @@ -131,21 +131,21 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) i++; } - if (j < XY_TILE_ENTRY_LIMIT) + if (j < TILE_ENTRY_LIMIT) { i = UINT16_MAX; // Add a terminator indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits - _CoarseXyTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; + _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; j++; } // You can clear the buffer for debugging purposes. - // while (j < XY_TILE_ENTRY_LIMIT) + // while (j < TILE_ENTRY_LIMIT) // { - // _CoarseXyTileBuffer[(outputStart + 1) + (j / 2)] = 0; + // _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = 0; // j += 2; // } } @@ -153,17 +153,17 @@ void FillCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) uint outputRange = (last << 16) | first; // Store the metadata. - _CoarseXyTileBuffer[outputStart] = outputRange; + _CoarseTileBuffer[outputStart] = outputRange; } [numthreads(THREADS_PER_GROUP, 1, 1)] -void PruneCoarseXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void PruneCoarseTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } [numthreads(THREADS_PER_GROUP, 1, 1)] -void BuildFineXyTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void BuildFineTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute.meta similarity index 81% rename from com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute.meta rename to com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute.meta index ac5cc8d5ac2..b411db6ecd4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/xyTile.compute.meta +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ecd07937befe9614d90276f5d8609b3e +guid: 3a8709910066b4d4186b56721cdc36aa ComputeShaderImporter: externalObjects: {} currentAPIMask: 2097156 diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 5e7af1bff10..9c62c94e1bc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -101,8 +101,8 @@ static class HDShaderIDs public static readonly int _xyBoundsBuffer = Shader.PropertyToID(nameof(_xyBoundsBuffer)); public static readonly int _wBoundsBuffer = Shader.PropertyToID(nameof(_wBoundsBuffer)); public static readonly int _zBinBuffer = Shader.PropertyToID(nameof(_zBinBuffer)); - public static readonly int _CoarseXyTileBuffer = Shader.PropertyToID(nameof(_CoarseXyTileBuffer)); - public static readonly int _FineXyTileBuffer = Shader.PropertyToID(nameof(_FineXyTileBuffer)); + public static readonly int _CoarseTileBuffer = Shader.PropertyToID(nameof(_CoarseTileBuffer)); + public static readonly int _FineTileBuffer = Shader.PropertyToID(nameof(_FineTileBuffer)); public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs index a32f513d22d..1f78da31739 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs @@ -61,8 +61,8 @@ public sealed class ShaderResources public ComputeShader buildScreenAABBCS; [Reload("Runtime/Lighting/LightLoop/zBin.compute")] public ComputeShader zBinCS; - [Reload("Runtime/Lighting/LightLoop/xyTile.compute")] - public ComputeShader xyTileCS; + [Reload("Runtime/Lighting/LightLoop/tile.compute")] + public ComputeShader tileCS; [Reload("Runtime/Lighting/LightLoop/lightlistbuild.compute")] public ComputeShader buildPerTileLightListCS; // FPTL [Reload("Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute")] diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 99fc1100ad8..e2711a41c8e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -206,8 +206,8 @@ unsafe struct ShaderVariablesGlobal public Vector4 _ZBinBufferEncodingParams; - public Vector2Int _CoarseXyTileBufferDimensions; - public Vector2Int _FineXyTileBufferDimensions; + public Vector2Int _CoarseTileBufferDimensions; + public Vector2Int _FineTileBufferDimensions; public uint _NumTileFtplX; public uint _NumTileFtplY; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index bae91ccc8f3..9a714e8bc94 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -112,8 +112,8 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) uint4 _BoundedEntityCountPerCategory[2]; uint4 _BoundedEntityOffsetPerCategory[2]; float4 _ZBinBufferEncodingParams; - int2 _CoarseXyTileBufferDimensions; - int2 _FineXyTileBufferDimensions; + int2 _CoarseTileBufferDimensions; + int2 _FineTileBufferDimensions; uint _NumTileFtplX; uint _NumTileFtplY; float g_fClustScale; From 3b98d96dda74e84d7d45998f003e6feba7b2b09c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 23 Oct 2020 17:59:19 -0700 Subject: [PATCH 056/209] Fill coarse tiles --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 14 +++++++------- .../Runtime/Lighting/LightLoop/tile.compute | 18 +++++++++--------- .../Runtime/RenderPipeline/HDProfileId.cs | 2 +- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 4621409fb62..da21bfe9538 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3626,15 +3626,15 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG } } - static void PerformXYBinning(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformXYBinning))) + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.FillCoarseTiles))) { var shader = parameters.tileShader; int kernel; - kernel = 0; // FillCoarseTile + kernel = 0; // FillCoarseTiles cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); @@ -3648,11 +3648,11 @@ static void PerformXYBinning(in BuildGPULightListParameters parameters, in Build cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); - kernel = 1; // PruneCoarseTile + kernel = 1; // PruneCoarseTiles // ... - kernel = 2; // BuildFineTile + kernel = 2; // FillFineTiles // ... } @@ -4111,10 +4111,10 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) // That is fairly efficient, and allows us to avoid weird special cases. ClearLightLists(parameters, resources, cmd); GenerateLightsScreenSpaceAABBs(parameters, resources, cmd); - // Both Z-binning and XY-binning can be executed concurrently. + // Both Z-binning and tile filling can be executed concurrently. // This should improve GPU utilization. PerformZBinning(parameters, resources, cmd); - PerformXYBinning(parameters, resources, cmd); + FillCoarseTiles(parameters, resources, cmd); // BigTilePrepass(parameters, resources, cmd); // BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 5c1daf65d3c..a7e892663e6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -2,11 +2,11 @@ #pragma only_renderers d3d11 playstation xboxone vulkan metal switch // Generates large screen tiles in a fast, conservative manner. -#pragma kernel FillCoarseTile PASS = FILL_COARSE_TILE COARSE_BINNING +#pragma kernel FillCoarseTiles PASS = FILL_COARSE_TILES COARSE_BINNING // Removes certain entities from the coarse buffer at a large cost. -#pragma kernel PruneCoarseTile PASS = PRUNE_COARSE_TILE COARSE_BINNING +#pragma kernel PruneCoarseTiles PASS = PRUNE_COARSE_TILES COARSE_BINNING // Generates small screen tiles in an accurate manner. -#pragma kernel BuildFineTile PASS = BUILD_FINE_TILE FINE_BINNING +#pragma kernel FillFineTiles PASS = FILL_FINE_TILES FINE_BINNING #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" @@ -16,14 +16,14 @@ /* ------------------------------ Inputs ------------------------------------ */ -#if (PASS == FILL_COARSE_TILE) +#if (PASS == FILL_COARSE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). StructuredBuffer _xyBoundsBuffer : register(t0); // {x_min, x_max, y_min, y_max} #endif /* ------------------------------ Outputs ----------------------------------- */ -#if (PASS == FILL_COARSE_TILE) +#if (PASS == FILL_COARSE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * @@ -32,7 +32,7 @@ RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 16-bit indices #endif -#if (PASS == BUILD_FINE_TILE) +#if (PASS == BUILD_FINE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, FINE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_TILE_SIZE) * @@ -55,7 +55,7 @@ static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin #define THREADS_PER_GROUP (64) [numthreads(THREADS_PER_GROUP, 1, 1)] -void FillCoarseTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // We could tile the threads in 8x8 blocks. The problem is, // the dimensions of the buffer are already quite small. The extra padding @@ -157,13 +157,13 @@ void FillCoarseTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } [numthreads(THREADS_PER_GROUP, 1, 1)] -void PruneCoarseTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void PruneCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } [numthreads(THREADS_PER_GROUP, 1, 1)] -void BuildFineTile(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +void FillFineTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 09aac9b2580..0021a3f5153 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -20,7 +20,7 @@ internal enum HDProfileId BuildLightList, GenerateLightAABBs, PerformZBinning, - PerformXYBinning, + FillCoarseTiles, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, From b4d515df3be0db42fdc303d51bcd73c746bd7ee9 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 23 Oct 2020 18:28:31 -0700 Subject: [PATCH 057/209] Clean up --- .../Lighting/LightLoop/LightLoopDef.hlsl | 1 + .../LightLoop/TilingAndBinningUtilities.hlsl | 4 +- .../Lighting/LightLoop/scrbound.compute | 81 +++++++++---------- .../Runtime/Lighting/LightLoop/tile.compute | 22 ++--- 4 files changed, 49 insertions(+), 59 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index a5ea40d9e8a..45bf72ff637 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -155,6 +155,7 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData // This part (1) is loop-invariant. These values do not depend on the value of 'i'. // They will only be computed once per category, not once per function call. + // TODO: we may want to store tile buffer ranges in a separate buffer for cache locality. const uint tileBufferIndex = ComputeTileBufferIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); const uint tilePackedRange = TILE_BUFFER[tileBufferIndex]; // {last << 16 | first} const bool isTileEmpty = tilePackedRange == UINT16_MAX; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 3812731624b..8e5ac981850 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -8,7 +8,9 @@ uint GetTileSize() } // The HLSL preprocessor does not support the '%' operator. -#define REMAINDER(a, n) ((a) - (n) * ((a) / (n))) +#define REMAINDER(A, N) ((A) - (N) * ((A) / (N))) +#define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) +#define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks // Returns the location of the N-th set bit starting from the lowest order bit and working upward. // Slow implementation - do not use for large bit sets. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index bac9ac19b83..da1e8bd5a68 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -50,9 +50,6 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} #undef PLATFORM_SUPPORTS_WAVE_INTRINSICS #endif -#define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) -#define DIV_ROUND_UP(N, D) (((N) + (D) - 1) / (D)) // No division by 0 checks - // Clipping a plane by a cube may produce a hexagon (6-gon). // Clipping a hexagon by 4 planes may produce a decagon (10-gon). #define MAX_CLIP_VERTS (10) @@ -64,7 +61,7 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} #define ENTITIES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_ENTITY) #define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) #define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) -#define FACES_PER_THREAD DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY) +#define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) // All planes and faces are always in the standard order (see below). // Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. @@ -438,17 +435,17 @@ float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float // rap - real (3D) coordinates after perspective (after division by w) // ********************************************************************************************* -[numthreads(THREADS_PER_GROUP, 1, 1)] -void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +[numthreads(THREADS_PER_ENTITY, ENTITIES_PER_GROUP, 1)] +void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { - const uint t = threadID; - const uint g = groupID.x; - const uint eye = groupID.z; + const uint t = threadID.x; + const uint entity = threadID.y; + const uint g = groupID.x; + const uint eye = groupID.z; - const uint intraGroupEntityIndex = t / THREADS_PER_ENTITY; - const uint globalEntityIndex = IndexFromCoordinate(uint2(intraGroupEntityIndex, g), ENTITIES_PER_GROUP); - const uint baseVertexOffset = intraGroupEntityIndex * NUM_VERTS; - const uint clampedEntityIndex = min(globalEntityIndex, _BoundedEntityCount - 1); // Stay within bounds + const uint baseVertexOffset = entity * NUM_VERTS; + const uint globalEntityIndex = IndexFromCoordinate(uint2(entity, g), ENTITIES_PER_GROUP); + const uint clampedEntityIndex = min(globalEntityIndex, _BoundedEntityCount - 1); // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -471,16 +468,16 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // (0) Initialize the TGSM. - if (t % THREADS_PER_ENTITY == 0) // Avoid bank conflicts + if (t == 0) // Avoid bank conflicts { - gs_CullClipFaceMasks[intraGroupEntityIndex] = 0; // Initially inside - gs_NdcAaBbMinPtX[intraGroupEntityIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtX[intraGroupEntityIndex] = asuint(0.0f); - gs_NdcAaBbMinPtY[intraGroupEntityIndex] = asuint(1.0f); - gs_NdcAaBbMaxPtY[intraGroupEntityIndex] = asuint(0.0f); + gs_CullClipFaceMasks[entity] = 0; // Initially inside + gs_NdcAaBbMinPtX[entity] = asuint(1.0f); + gs_NdcAaBbMaxPtX[entity] = asuint(0.0f); + gs_NdcAaBbMinPtY[entity] = asuint(1.0f); + gs_NdcAaBbMaxPtY[entity] = asuint(0.0f); // Skip Z, we do not need it. - gs_NdcAaBbMinPtW[intraGroupEntityIndex] = asuint(FLT_INF); - gs_NdcAaBbMaxPtW[intraGroupEntityIndex] = asuint(0.0f); + gs_NdcAaBbMinPtW[entity] = asuint(FLT_INF); + gs_NdcAaBbMaxPtW[entity] = asuint(0.0f); } #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS @@ -498,7 +495,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // (1) Compute the vertices of the bounding frustum. for (i = 0; i < VERTS_PER_THREAD; i++) { - uint v = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; + uint v = t + i * THREADS_PER_ENTITY; // rbpVerts[0] = rbpC - rbpX * scale - rbpY * scale - rbpZ; (-s, -s, -1) // rbpVerts[1] = rbpC + rbpX * scale - rbpY * scale - rbpZ; (+s, -s, -1) @@ -577,11 +574,11 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else - InterlockedOr(gs_CullClipFaceMasks[intraGroupEntityIndex], cullClipFaceMask); + InterlockedOr(gs_CullClipFaceMasks[entity], cullClipFaceMask); GroupMemoryBarrierWithGroupSync(); - cullClipFaceMask = gs_CullClipFaceMasks[intraGroupEntityIndex]; + cullClipFaceMask = gs_CullClipFaceMasks[entity]; #endif // (2) Test the corners of the view volume. @@ -617,7 +614,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) for (i = 0; i < VERTS_PER_THREAD; i++) { - uint v = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; + uint v = t + i * THREADS_PER_ENTITY; float3 rapVertCS = GenerateVertexOfStandardCube(v); rapVertCS.z = rapVertCS.z * 0.5 + 0.5; // View's projection matrix MUST map Z to [0, 1] @@ -663,7 +660,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) for (i = 0; i < FACES_PER_THREAD; i++) { - uint n = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; + uint n = t + i * THREADS_PER_ENTITY; if (n < numFacesToCull) { @@ -687,11 +684,11 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } #else - InterlockedAnd(gs_CullClipFaceMasks[intraGroupEntityIndex], cullClipFaceMask); + InterlockedAnd(gs_CullClipFaceMasks[entity], cullClipFaceMask); GroupMemoryBarrierWithGroupSync(); - cullClipFaceMask = gs_CullClipFaceMasks[intraGroupEntityIndex]; + cullClipFaceMask = gs_CullClipFaceMasks[entity]; #endif // (4) Clip the faces. @@ -701,7 +698,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) for (i = 0; i < FACES_PER_THREAD; i++) { - uint n = i * THREADS_PER_ENTITY + t % THREADS_PER_ENTITY; + uint n = t + i * THREADS_PER_ENTITY; if (n < numFacesToClip) { @@ -735,23 +732,23 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) #else // Integer comparison works for floating-point numbers as long as the sign bit is 0. // We must take care of -0 ourselves. saturate() does not help. - InterlockedMin(gs_NdcAaBbMinPtX[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); - InterlockedMax(gs_NdcAaBbMaxPtX[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); - InterlockedMin(gs_NdcAaBbMinPtY[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); - InterlockedMax(gs_NdcAaBbMaxPtY[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); + InterlockedMin(gs_NdcAaBbMinPtX[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.x))); + InterlockedMax(gs_NdcAaBbMaxPtX[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.x))); + InterlockedMin(gs_NdcAaBbMinPtY[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.y))); + InterlockedMax(gs_NdcAaBbMaxPtY[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.y))); // Skip Z, we do not need it. - InterlockedMin(gs_NdcAaBbMinPtW[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); - InterlockedMax(gs_NdcAaBbMaxPtW[intraGroupEntityIndex], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); + InterlockedMin(gs_NdcAaBbMinPtW[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); + InterlockedMax(gs_NdcAaBbMaxPtW[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); GroupMemoryBarrierWithGroupSync(); - ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[intraGroupEntityIndex]); - ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[intraGroupEntityIndex]); - ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[intraGroupEntityIndex]); - ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[intraGroupEntityIndex]); + ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[entity]); + ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[entity]); + ndcAaBbMinPt.y = asfloat(gs_NdcAaBbMinPtY[entity]); + ndcAaBbMaxPt.y = asfloat(gs_NdcAaBbMaxPtY[entity]); // Skip Z, we do not need it. - ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[intraGroupEntityIndex]); - ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[intraGroupEntityIndex]); + ndcAaBbMinPt.w = asfloat(gs_NdcAaBbMinPtW[entity]); + ndcAaBbMaxPt.w = asfloat(gs_NdcAaBbMaxPtW[entity]); #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS // (5) Compute the AABB of the bounding sphere. @@ -800,7 +797,7 @@ void main(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) } } - if (!isHelperThread && (t % THREADS_PER_ENTITY == 0)) // Avoid bank conflicts + if (!isHelperThread && (t == 0)) // Avoid bank conflicts { _xyBoundsBuffer[bufferIndex] = float4(ndcAaBbMinPt.x, ndcAaBbMaxPt.x, ndcAaBbMinPt.y, ndcAaBbMaxPt.y); _wBoundsBuffer[bufferIndex] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a7e892663e6..a4298d9b633 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -59,19 +59,19 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // We could tile the threads in 8x8 blocks. The problem is, // the dimensions of the buffer are already quite small. The extra padding - // (helper threads) required outweighs the benefits (reduced divergence). + // (helper threads) required outweighs the benefits (improved locality, reduced divergence). const uint t = threadID; const uint g = groupID.x; const uint cat = groupID.y; const uint eye = groupID.z; - const uint tileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); - const uint clampedTileIndex = min(tileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); + const uint globalTileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); + const uint clampedTileIndex = min(globalTileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. - const bool isHelperThread = tileIndex != clampedTileIndex; + const bool isHelperThread = globalTileIndex != clampedTileIndex; if (isHelperThread) return; // Avoid adding too many checks or branches below @@ -119,8 +119,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if ((j & 1) != 0) // Is the pair complete & ready to be stored? { - // +1 because the first uint is reserved for the metadata. - _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; + _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; // +1 for the metadata indexPair = 0; // In order to use bitwise OR above } @@ -137,17 +136,8 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits - _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; - - j++; + _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; // +1 for the metadata } - - // You can clear the buffer for debugging purposes. - // while (j < TILE_ENTRY_LIMIT) - // { - // _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = 0; - // j += 2; - // } } uint outputRange = (last << 16) | first; From 1929a83efce34dc1216c2ed47715e322875039ad Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 23 Oct 2020 21:27:37 -0700 Subject: [PATCH 058/209] TODO --- .../Runtime/Lighting/LightLoop/materialflags.compute | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute index 4ac95c5b265..433eda440ad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute @@ -19,11 +19,14 @@ #define USE_MATERIAL_FEATURE_FLAGS #ifdef PLATFORM_LANE_COUNT // We can infer the size of a wave. This is currently not possible on non-consoles, so we have to fallback to a sensible default in those cases. -#define NR_THREADS PLATFORM_LANE_COUNT +#define NR_THREADS PLATFORM_LANE_COUNT #else #define NR_THREADS 64 // default to 64 threads per group on other platforms.. #endif +// TODO: MUST DO LIGHT CLASSIFICATION HERE +// LIGHT CLASSIFICATION NEEDS MIN-MAX Z OF THE TILE TO USE Z-BINNING WHICH WILL COMPENSATE FOR THE LOSS OF FPTL + groupshared uint ldsFeatureFlags; RWStructuredBuffer g_TileFeatureFlags; @@ -58,7 +61,7 @@ void MaterialFlagsGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadI { int idx = i * NR_THREADS + threadID; uint2 uCrd = min(uint2(viTilLL.x + (idx & 0xf), viTilLL.y + (idx >> 4)), uint2(iWidth - 1, iHeight - 1)); - + // Unlit object, sky/background and forward opaque tag don't tag the StencilUsage.RequiresDeferredLighting bit uint stencilVal = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, uCrd)); if ((stencilVal & STENCILUSAGE_REQUIRES_DEFERRED_LIGHTING) > 0) From 54b1e3facc9959c802f75e63c232098fe38fdc75 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 23 Oct 2020 21:35:22 -0700 Subject: [PATCH 059/209] Naming --- .../Lighting/LightLoop/LightLoopDef.hlsl | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 45bf72ff637..f9ba8e1061f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -157,40 +157,40 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData // They will only be computed once per category, not once per function call. // TODO: we may want to store tile buffer ranges in a separate buffer for cache locality. const uint tileBufferIndex = ComputeTileBufferIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); - const uint tilePackedRange = TILE_BUFFER[tileBufferIndex]; // {last << 16 | first} - const bool isTileEmpty = tilePackedRange == UINT16_MAX; + const uint tileRangeData = TILE_BUFFER[tileBufferIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; if (!isTileEmpty) { const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); - const uint zBinPackedRange = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} - const uint2 tileRange = uint2(tilePackedRange & UINT16_MAX, tilePackedRange >> 16); - const uint2 zBinRange = uint2(zBinPackedRange & UINT16_MAX, zBinPackedRange >> 16); + const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); + const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); - if (IntervalsOverlap(tileRange, zBinRange)) + if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) { // The part (2) below will be actually executed during every function call. while (i < n) { // This is a valid buffer index. +1 because the first uint is reserved for the metadata. - uint entityIndexPair = TILE_BUFFER[(tileBufferIndex + 1) + (i / 2)]; // 16-bit indices - uint entityIndex = BitFieldExtract(entityIndexPair, 16 * (i & 1), 16); // Order: first Lo, then Hi bits + uint tileEntityPair = TILE_BUFFER[(tileBufferIndex + 1) + (i / 2)]; // 16-bit indices + uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); // Entity indices are stored in the ascending order. // We can distinguish 3 cases: - if (entityIndex < zBinRange.x) + if (tileEntityIndex < zBinEntityIndexRange.x) { i++; // Skip this entity; continue the (linear) search } - else if (entityIndex <= zBinRange.y) + else if (tileEntityIndex <= zBinEntityIndexRange.y) { - data = _PunctualLightData[entityIndex]; + data = _PunctualLightData[tileEntityIndex]; b = true; // Found a valid index break; // Avoid incrementing 'i' further } - else // if (zBinRange.y < entityIndex) + else // if (zBinEntityIndexRange.y < tileEntityIndex) { break; // Avoid incrementing 'i' further } From 3dbd648c48e0912e3aff6c4b0b05595212f148c4 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 26 Oct 2020 16:57:02 -0700 Subject: [PATCH 060/209] Split the tile buffer into header + body --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 16 +++++----- .../Lighting/LightLoop/LightLoop.cs.hlsl | 4 +-- .../Lighting/LightLoop/LightLoopDef.hlsl | 13 ++++---- .../LightLoop/ShaderVariablesLightLoop.hlsl | 2 +- .../LightLoop/TilingAndBinningUtilities.hlsl | 23 ++++++++++---- .../Runtime/Lighting/LightLoop/tile.compute | 30 +++++++++++++------ 6 files changed, 57 insertions(+), 31 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index da21bfe9538..84bc9fbc0d5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -404,9 +404,8 @@ class TiledLightingConstants // Binned lighting // For performance reasons, keep all sizes in powers of 2. - // The first 2 entries are reserved for the metadata. - public static int s_CoarseTileEntryLimit = 64 - 2; // Per category; before pruning, so the number is lower in practice - public static int s_FineTileEntryLimit = 16 - 2; // Per category; after pruning, so the number is exact + public static int s_CoarseTileEntryLimit = 64; // Per category; before pruning, so the number is lower in practice + public static int s_FineTileEntryLimit = 16; // Per category; after pruning, so the number is exact public static int s_CoarseTileSize = 64; public static int s_FineTileSize = 8; public static int s_zBinCount = 8192; @@ -778,11 +777,14 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, /* Actually resolution-dependent buffers below. */ Vector2Int coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); - int coarseTileBufferElementCount = coarseTileBufferDimensions.x * coarseTileBufferDimensions.y * - (int)BoundedEntityCategory.Count * viewCount * - (TiledLightingConstants.s_CoarseTileEntryLimit / 2); + // The tile buffer is composed of two parts: + // the header (containing index ranges, 2 * sizeof(uint16)) and + // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). + int coarseTileBufferElementCount = coarseTileBufferDimensions.x * coarseTileBufferDimensions.y + * (int)BoundedEntityCategory.Count * viewCount + * (2 + TiledLightingConstants.s_CoarseTileEntryLimit) / 2; - coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // List of 16-bit indices + coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // Index range + index list } // Make sure to invalidate the content of the buffers diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 382c33b1967..087e04caa77 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -70,8 +70,8 @@ #define SCREEN_SPACE_COLOR_SHADOW_FLAG (256) #define INVALID_SCREEN_SPACE_SHADOW (255) #define SCREEN_SPACE_SHADOW_INDEX_MASK (255) -#define COARSE_TILE_ENTRY_LIMIT (62) -#define FINE_TILE_ENTRY_LIMIT (14) +#define COARSE_TILE_ENTRY_LIMIT (64) +#define FINE_TILE_ENTRY_LIMIT (16) #define COARSE_TILE_SIZE (64) #define FINE_TILE_SIZE (8) #define Z_BIN_COUNT (8192) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index f9ba8e1061f..89b30655fc0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -155,10 +155,9 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData // This part (1) is loop-invariant. These values do not depend on the value of 'i'. // They will only be computed once per category, not once per function call. - // TODO: we may want to store tile buffer ranges in a separate buffer for cache locality. - const uint tileBufferIndex = ComputeTileBufferIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); - const uint tileRangeData = TILE_BUFFER[tileBufferIndex]; // {last << 16 | first} - const bool isTileEmpty = tileRangeData == UINT16_MAX; + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; if (!isTileEmpty) { @@ -170,11 +169,13 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) { + const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + // The part (2) below will be actually executed during every function call. while (i < n) { - // This is a valid buffer index. +1 because the first uint is reserved for the metadata. - uint tileEntityPair = TILE_BUFFER[(tileBufferIndex + 1) + (i / 2)]; // 16-bit indices + // This is a valid buffer index. + uint tileEntityPair = TILE_BUFFER[tileBufferBodyIndex + (i / 2)]; // 16-bit indices uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); // Entity indices are stored in the ascending order. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index 52d12ba1a3f..f236b45191b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -2,7 +2,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs.hlsl" #if (defined(COARSE_BINNING) || defined(FINE_BINNING)) - // TODO: we don't need both at the same time, so perhaps just declare one? + // TODO: we don't need both tile buffers in the same shader, so perhaps just declare one? StructuredBuffer _CoarseTileBuffer; StructuredBuffer _FineTileBuffer; StructuredBuffer _zBinBuffer; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 8e5ac981850..851d8ec41cf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -158,15 +158,26 @@ uint ComputeTileIndex(uint2 tileCoord) uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); } +// Contains index ranges. // tile: output of ComputeTileIndex. -uint ComputeTileBufferIndex(uint tile, uint category, uint eye) +uint ComputeTileBufferHeaderIndex(uint tile, uint category, uint eye) { - // We use 'uint' buffer rather than a 'uint16_t[n]'. - uint stride = (TILE_ENTRY_LIMIT + 2) / 2; // The first 2 entries are reserved for the metadata - uint offset = IndexFromCoordinate(uint4(0, 0, category, eye), - uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); + uint eyeCatOffset = IndexFromCoordinate(uint4(0, 0, category, eye), + uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); - return stride * (offset + tile); + return eyeCatOffset + tile; +} + +// Contains index lists. +uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye) +{ + // TODO: may want to precompute this. + uint headerOffset = TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y * BOUNDEDENTITYCATEGORY_COUNT * _XRViewCount; + uint eyeCatOffset = IndexFromCoordinate(uint4(0, 0, category, eye), + uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); + uint stride = TILE_ENTRY_LIMIT / 2; // 16-bit index list + + return headerOffset + stride * (eyeCatOffset + tile); } #endif // NO_SHADERVARIABLESGLOBAL_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a4298d9b633..2bb2cdd9978 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -24,20 +24,31 @@ /* ------------------------------ Outputs ----------------------------------- */ #if (PASS == FILL_COARSE_TILES) + // The tile buffer is composed of two parts: + // the header (containing index ranges, 2 * sizeof(uint16)) and + // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((COARSE_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). - // For example (1080p): 30 * 17 * 5 * 1 * (64 * 2) = 318.75 KiB. - RWStructuredBuffer _CoarseTileBuffer : register(u0); // List of 16-bit indices + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + COARSE_TILE_ENTRY_LIMIT) * 2 bytes per entry. + // For example (1080p): 30 * 17 * 5 * 1 * (2 + 64) * 2 = 328.7 KiB. + RWStructuredBuffer _CoarseTileBuffer : register(u0); // Index range + index list +#endif + +#if (PASS == PRUNE_COARSE_TILES) + // 1x list for all entites (sorted by category, we concatenate lists of all views). + RWStructuredBuffer _DstCoarseTileBuffer : register(u0); // Index range + index list #endif #if (PASS == BUILD_FINE_TILES) + // The tile buffer is composed of two parts: + // the header (containing index ranges, 2 * sizeof(uint16)) and + // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, FINE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_TILE_SIZE) * - // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * ((FINE_TILE_ENTRY_LIMIT + 2) * 2 bytes per entry). - // For example (1080p): 240 * 165 * 5 * 1 * (16 * 2) = 6.04 MiB. + // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + FINE_TILE_ENTRY_LIMIT) * 2 bytes per entry. + // For example (1080p): 240 * 165 * 5 * 1 * (2 + 16) * 2 = 6.8 MiB. #endif /* ------------------------------ Utilities --------------------------------- */ @@ -80,7 +91,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint entityCount = s_BoundedEntityCountPerCategory[cat]; const uint inputStart = ComputeEntityBoundsBufferIndex(entityIndex, eye); - const uint outputStart = ComputeTileBufferIndex(clampedTileIndex, cat, eye); + const uint outputStart = ComputeTileBufferBodyIndex(clampedTileIndex, cat, eye); uint first = UINT16_MAX, last = 0; @@ -119,7 +130,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) if ((j & 1) != 0) // Is the pair complete & ready to be stored? { - _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; // +1 for the metadata + _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; indexPair = 0; // In order to use bitwise OR above } @@ -136,14 +147,15 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits - _CoarseTileBuffer[(outputStart + 1) + (j / 2)] = indexPair; // +1 for the metadata + _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; } } uint outputRange = (last << 16) | first; // Store the metadata. - _CoarseTileBuffer[outputStart] = outputRange; + uint headerIndex = ComputeTileBufferHeaderIndex(clampedTileIndex, cat, eye); + _CoarseTileBuffer[headerIndex] = outputRange; } [numthreads(THREADS_PER_GROUP, 1, 1)] From 065828e6ce72268073e9d59cbed407cf63efcfa5 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 26 Oct 2020 18:41:50 -0700 Subject: [PATCH 061/209] Add VERTS_PER_FACE --- .../Runtime/Lighting/LightLoop/scrbound.compute | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index da1e8bd5a68..31a6ac33b12 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -62,6 +62,7 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} #define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) #define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) #define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) +#define VERTS_PER_FACE (4) // All planes and faces are always in the standard order (see below). // Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. @@ -150,7 +151,7 @@ bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) uint cullMaskOfFace = FACE_MASK; // Initially behind uint vertListOfFace = GetVertexListOfFace(f); - for (uint j = 0; j < 4; j++) + for (uint j = 0; j < VERTS_PER_FACE; j++) { uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); // Non-zero if ALL the vertices are behind any of the planes. @@ -258,12 +259,12 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint out float4 vertRingBuffer[MAX_CLIP_VERTS]) { srcBegin = 0; - srcSize = 4; + srcSize = VERTS_PER_FACE; uint clipMaskOfFace = 0; // Initially in front uint vertListOfFace = GetVertexListOfFace(f); - for (uint j = 0; j < 4; j++) + for (uint j = 0; j < VERTS_PER_FACE; j++) { uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); // Non-zero if ANY of the vertices are behind any of the planes. From 55130894649d40e7d4829909914e2b249619aa04 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 26 Oct 2020 18:52:20 -0700 Subject: [PATCH 062/209] Add 'ClippingUtilities.hlsl' --- .../Lighting/LightLoop/ClippingUtilities.hlsl | 102 ++++++++++++++++++ .../Lighting/LightLoop/scrbound.compute | 100 +---------------- 2 files changed, 104 insertions(+), 98 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl new file mode 100644 index 00000000000..64098db508f --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl @@ -0,0 +1,102 @@ +#ifndef UNITY_CLIPPINGUTILITIES_INCLUDED +#define UNITY_CLIPPINGUTILITIES_INCLUDED + +// (Sep 16, 2020) +// Improve the quality of generated code at the expense of readability. +// Remove when the shader compiler is clever enough to perform this optimization for us. +#define OBTUSE_COMPILER + +struct ClipVertex +{ + float4 pt; // Homogeneous coordinate after perspective + float bc; // Boundary coordinate with respect to the plane 'p' +}; + +ClipVertex CreateClipVertex(uint p, float4 v) +{ + bool evenPlane = (p & 1) == 0; + + float c = v[p >> 1]; + float w = v.w; + + ClipVertex cv; + + cv.pt = v; + cv.bc = evenPlane ? c : w - c; // dot(PlaneEquation, HapVertex); + + return cv; +} + +float4 IntersectEdgeAgainstPlane(ClipVertex v0, ClipVertex v1) +{ + float alpha = saturate(v0.bc * rcp(v0.bc - v1.bc)); // Guaranteed to lie between 0 and 1 + + return lerp(v0.pt, v1.pt, alpha); +} + +void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, + inout float4 vertRingBuffer[MAX_CLIP_VERTS], + out uint dstBegin, out uint dstSize) +{ + dstBegin = srcBegin + srcSize; // Start at the end; we don't use modular arithmetic here + dstSize = 0; + + ClipVertex tailVert = CreateClipVertex(p, vertRingBuffer[(srcBegin + srcSize - 1) % MAX_CLIP_VERTS]); + +#ifdef OBTUSE_COMPILER + uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; + uint modDstIdx = dstBegin % MAX_CLIP_VERTS; +#endif + + for (uint j = srcBegin; j < (srcBegin + srcSize); j++) + { + #ifndef OBTUSE_COMPILER + uint modSrcIdx = j % MAX_CLIP_VERTS; + #endif + ClipVertex leadVert = CreateClipVertex(p, vertRingBuffer[modSrcIdx]); + + // Execute Blinn's line clipping algorithm. + // Classify the line segment. 4 cases: + // 0. v0 out, v1 out -> add nothing + // 1. v0 in, v1 out -> add intersection + // 2. v0 out, v1 in -> add intersection, add v1 + // 3. v0 in, v1 in -> add v1 + // (bc >= 0) <-> in, (bc < 0) <-> out. Beware of -0. + + if ((tailVert.bc >= 0) != (leadVert.bc >= 0)) + { + // The line segment is guaranteed to cross the plane. + float4 clipVert = IntersectEdgeAgainstPlane(tailVert, leadVert); + #ifndef OBTUSE_COMPILER + uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; + #endif + vertRingBuffer[modDstIdx] = clipVert; + #ifdef OBTUSE_COMPILER + dstSize++; + modDstIdx++; + modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; + #endif + } + + if (leadVert.bc >= 0) + { + #ifndef OBTUSE_COMPILER + uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; + #endif + vertRingBuffer[modDstIdx] = leadVert.pt; + #ifdef OBTUSE_COMPILER + dstSize++; + modDstIdx++; + modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; + #endif + } + + #ifdef OBTUSE_COMPILER + modSrcIdx++; + modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; + #endif + tailVert = leadVert; // Avoid recomputation and overwriting the vertex in the ring buffer + } +} + +#endif // UNITY_CLIPPINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 31a6ac33b12..a2ae18defff 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -9,6 +9,7 @@ #define NO_SHADERVARIABLESGLOBAL_HLSL #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" #undef NO_SHADERVARIABLESGLOBAL_HLSL +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -36,10 +37,6 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} // | / // 0 -- x -// Improve the quality of generated code at the expense of readability. -// Remove when the shader compiler is clever enough to perform this optimization for us. -#define OBTUSE_COMPILER - #ifdef SHADER_API_XBOXONE // The Xbox shader compiler expects the lane swizzle mask to be a compile-time constant. // In our case, the mask is a compile-time constant, but it is defined inside a loop @@ -51,7 +48,7 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} #endif // Clipping a plane by a cube may produce a hexagon (6-gon). -// Clipping a hexagon by 4 planes may produce a decagon (10-gon). +// Clipping a hexagon by 4 planes (substitute a quad for the plane) may produce a decagon (10-gon). #define MAX_CLIP_VERTS (10) #define NUM_VERTS (8) #define NUM_FACES (6) @@ -161,99 +158,6 @@ bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) return (cullMaskOfFace != 0); } -struct ClipVertex -{ - float4 pt; // Homogeneous coordinate after perspective - float bc; // Boundary coordinate with respect to the plane 'p' -}; - -ClipVertex CreateClipVertex(uint p, float4 v) -{ - bool evenPlane = (p & 1) == 0; - - float c = v[p >> 1]; - float w = v.w; - - ClipVertex cv; - - cv.pt = v; - cv.bc = evenPlane ? c : w - c; // dot(PlaneEquation, HapVertex); - - return cv; -} - -float4 IntersectEdgeAgainstPlane(ClipVertex v0, ClipVertex v1) -{ - float alpha = saturate(v0.bc * rcp(v0.bc - v1.bc)); // Guaranteed to lie between 0 and 1 - - return lerp(v0.pt, v1.pt, alpha); -} - -void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, - inout float4 vertRingBuffer[MAX_CLIP_VERTS], - out uint dstBegin, out uint dstSize) -{ - dstBegin = srcBegin + srcSize; // Start at the end; we don't use modular arithmetic here - dstSize = 0; - - ClipVertex tailVert = CreateClipVertex(p, vertRingBuffer[(srcBegin + srcSize - 1) % MAX_CLIP_VERTS]); - -#ifdef OBTUSE_COMPILER - uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; - uint modDstIdx = dstBegin % MAX_CLIP_VERTS; -#endif - - for (uint j = srcBegin; j < (srcBegin + srcSize); j++) - { - #ifndef OBTUSE_COMPILER - uint modSrcIdx = j % MAX_CLIP_VERTS; - #endif - ClipVertex leadVert = CreateClipVertex(p, vertRingBuffer[modSrcIdx]); - - // Execute Blinn's line clipping algorithm. - // Classify the line segment. 4 cases: - // 0. v0 out, v1 out -> add nothing - // 1. v0 in, v1 out -> add intersection - // 2. v0 out, v1 in -> add intersection, add v1 - // 3. v0 in, v1 in -> add v1 - // (bc >= 0) <-> in, (bc < 0) <-> out. Beware of -0. - - if ((tailVert.bc >= 0) != (leadVert.bc >= 0)) - { - // The line segment is guaranteed to cross the plane. - float4 clipVert = IntersectEdgeAgainstPlane(tailVert, leadVert); - #ifndef OBTUSE_COMPILER - uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; - #endif - vertRingBuffer[modDstIdx] = clipVert; - #ifdef OBTUSE_COMPILER - dstSize++; - modDstIdx++; - modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; - #endif - } - - if (leadVert.bc >= 0) - { - #ifndef OBTUSE_COMPILER - uint modDstIdx = (dstBegin + dstSize++) % MAX_CLIP_VERTS; - #endif - vertRingBuffer[modDstIdx] = leadVert.pt; - #ifdef OBTUSE_COMPILER - dstSize++; - modDstIdx++; - modDstIdx = (modDstIdx == MAX_CLIP_VERTS) ? 0 : modDstIdx; - #endif - } - - #ifdef OBTUSE_COMPILER - modSrcIdx++; - modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; - #endif - tailVert = leadVert; // Avoid recomputation and overwriting the vertex in the ring buffer - } -} - void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint baseVertexOffset, out uint srcBegin, out uint srcSize, out float4 vertRingBuffer[MAX_CLIP_VERTS]) From 0f7ed4877358b736739ad25111bfce99ecc54b49 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 26 Oct 2020 19:57:46 -0700 Subject: [PATCH 063/209] Comment --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 2 +- .../Runtime/Lighting/LightLoop/scrbound.compute | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 84bc9fbc0d5..13b030f2fd2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -404,7 +404,7 @@ class TiledLightingConstants // Binned lighting // For performance reasons, keep all sizes in powers of 2. - public static int s_CoarseTileEntryLimit = 64; // Per category; before pruning, so the number is lower in practice + public static int s_CoarseTileEntryLimit = 64; // Per category; before pruning, so the number is lower in practice; the number could be made (almost always) exact at the cost of making the 'FillCoarseTiles' pass more complicated public static int s_FineTileEntryLimit = 16; // Per category; after pruning, so the number is exact public static int s_CoarseTileSize = 64; public static int s_FineTileSize = 8; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index a2ae18defff..1c2baad827d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -312,7 +312,7 @@ float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float return float2(xMin, xMax); } -//********************************************************************************************** +// ************************************************************************************************* // The goal of this program is to compute the AABB of a bounded entity in the NDC space ([0, 1] range). // The entity is represented by a bounding sphere and a right bounding frustum with 6 faces and 8 vertices. // The resulting bounding volume is defined by the the intersection of the sphere and the frustum. @@ -338,7 +338,7 @@ float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float // hbp - hom. (4D) coordinates before perspective // hap - hom. (4D) coordinates after perspective // rap - real (3D) coordinates after perspective (after division by w) -// ********************************************************************************************* +// ************************************************************************************************* [numthreads(THREADS_PER_ENTITY, ENTITIES_PER_GROUP, 1)] void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) From 8fd1c016f7340443a5f7a9b5c1cc317be8f88b1c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 28 Oct 2020 16:08:30 -0700 Subject: [PATCH 064/209] Add a prototype for PruneCoarseTiles --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 60 +++++-- .../Lighting/LightLoop/LightLoopDef.hlsl | 5 +- .../Lighting/LightLoop/scrbound.compute | 4 +- .../Runtime/Lighting/LightLoop/tile.compute | 147 +++++++++++++++++- .../RenderPipeline/HDStringConstants.cs | 14 +- 5 files changed, 195 insertions(+), 35 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 13b030f2fd2..5686fe13677 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -701,6 +701,7 @@ class TileAndClusterData // Binned lighting public ComputeBuffer coarseTileBuffer { get; private set; } + public ComputeBuffer fineTileBuffer { get; private set; } public ComputeBuffer zBinBuffer { get; private set; } // Tile Output @@ -785,6 +786,17 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, * (2 + TiledLightingConstants.s_CoarseTileEntryLimit) / 2; coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // Index range + index list + + Vector2Int fineTileBufferDimensions = GetFineTileBufferDimensions(hdCamera); + + // The tile buffer is composed of two parts: + // the header (containing index ranges, 2 * sizeof(uint16)) and + // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). + int fineTileBufferElementCount = fineTileBufferDimensions.x * fineTileBufferDimensions.y + * (int)BoundedEntityCategory.Count * viewCount + * (2 + TiledLightingConstants.s_FineTileEntryLimit) / 2; + + fineTileBuffer = new ComputeBuffer(fineTileBufferElementCount, sizeof(uint)); // Index range + index list } // Make sure to invalidate the content of the buffers @@ -830,10 +842,12 @@ public void ReleaseNonRenderGraphResolutionDependentBuffers() xyBoundsBuffer = null; CoreUtils.SafeRelease(wBoundsBuffer); wBoundsBuffer = null; - CoreUtils.SafeRelease(zBinBuffer); - zBinBuffer = null; CoreUtils.SafeRelease(coarseTileBuffer); coarseTileBuffer = null; + CoreUtils.SafeRelease(fineTileBuffer); + fineTileBuffer = null; + CoreUtils.SafeRelease(zBinBuffer); + zBinBuffer = null; CoreUtils.SafeRelease(dispatchIndirectBuffer); dispatchIndirectBuffer = null; } @@ -3509,8 +3523,9 @@ struct BuildGPULightListResources public ComputeBuffer convexBoundsBuffer; public ComputeBuffer xyBoundsBuffer; public ComputeBuffer wBoundsBuffer; - public ComputeBuffer zBinBuffer; public ComputeBuffer coarseTileBuffer; + public ComputeBuffer fineTileBuffer; + public ComputeBuffer zBinBuffer; public ComputeBuffer globalLightListAtomic; // Output @@ -3539,8 +3554,9 @@ BuildGPULightListResources PrepareBuildGPULightListResources(TileAndClusterData resources.convexBoundsBuffer = tileAndClusterData.convexBoundsBuffer; resources.xyBoundsBuffer = tileAndClusterData.xyBoundsBuffer; resources.wBoundsBuffer = tileAndClusterData.wBoundsBuffer; - resources.zBinBuffer = tileAndClusterData.zBinBuffer; resources.coarseTileBuffer = tileAndClusterData.coarseTileBuffer; + resources.fineTileBuffer = tileAndClusterData.fineTileBuffer; + resources.zBinBuffer = tileAndClusterData.zBinBuffer; //resources.lightVolumeDataBuffer = tileAndClusterData.lightVolumeDataBuffer; resources.tileFeatureFlags = tileAndClusterData.tileFeatureFlags; resources.globalLightListAtomic = tileAndClusterData.globalLightListAtomic; @@ -3597,10 +3613,9 @@ static void GenerateLightsScreenSpaceAABBs(in BuildGPULightListParameters parame ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) - const int threadsPerEntity = 4; // Shader: THREADS_PER_ENTITY (4) + const int entitiesPerGroup = 16; // Shader: ENTITIES_PER_GROUP - int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount * threadsPerEntity, threadsPerGroup); + int groupCount = HDUtils.DivRoundUp(parameters.boundedEntityCount, entitiesPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, 1, parameters.viewCount); } @@ -3620,7 +3635,7 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP int groupCount = HDUtils.DivRoundUp(TiledLightingConstants.s_zBinCount, threadsPerGroup); @@ -3634,25 +3649,36 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.FillCoarseTiles))) { var shader = parameters.tileShader; - int kernel; + + ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); + + int kernel, groupCount; kernel = 0; // FillCoarseTiles cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._xyBoundsBuffer, resources.xyBoundsBuffer); - cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); - - ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); + // This is not an accident. We alias the fine tile buffer memory. + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.fineTileBuffer); - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP (64) + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP - int bufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; - int groupCount = HDUtils.DivRoundUp(bufferSize, threadsPerGroup); + int coarseBufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; + groupCount = HDUtils.DivRoundUp(coarseBufferSize, threadsPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); kernel = 1; // PruneCoarseTiles - // ... + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._EntityBoundsBuffer, resources.convexBoundsBuffer); + // This is not an accident. We alias the fine tile buffer memory. + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._SrcCoarseTileBuffer, resources.fineTileBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._DstCoarseTileBuffer, resources.coarseTileBuffer); + + const int tilesPerGroup = 16; // Shader: TILES_PER_GROUP + + groupCount = HDUtils.DivRoundUp(coarseBufferSize, tilesPerGroup); + + cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); kernel = 2; // FillFineTiles @@ -4285,7 +4311,7 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman if (param.hdCamera.frameSettings.IsEnabled(FrameSettingsField.BinnedLighting)) { cmd.SetGlobalBuffer(HDShaderIDs._CoarseTileBuffer, param.tileAndClusterData.coarseTileBuffer); - //cmd.SetGlobalBuffer(HDShaderIDs._FineTileBuffer, param.tileAndClusterData.fine); + cmd.SetGlobalBuffer(HDShaderIDs._FineTileBuffer, param.tileAndClusterData.fineTileBuffer); cmd.SetGlobalBuffer(HDShaderIDs._zBinBuffer, param.tileAndClusterData.zBinBuffer); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 89b30655fc0..5c9bd3a479b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -174,9 +174,8 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData // The part (2) below will be actually executed during every function call. while (i < n) { - // This is a valid buffer index. - uint tileEntityPair = TILE_BUFFER[tileBufferBodyIndex + (i / 2)]; // 16-bit indices - uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); + uint tileEntityPair = TILE_BUFFER[tileBufferBodyIndex + (i / 2)]; // 16-bit indices + uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); // First Lo, then Hi bits // Entity indices are stored in the ascending order. // We can distinguish 3 cases: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 1c2baad827d..43f0d6b1edf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -9,7 +9,6 @@ #define NO_SHADERVARIABLESGLOBAL_HLSL #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" #undef NO_SHADERVARIABLESGLOBAL_HLSL -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -61,6 +60,9 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} #define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) #define VERTS_PER_FACE (4) +// Needs the defines above. +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" + // All planes and faces are always in the standard order (see below). // Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. #define FACE_LEFT (1 << 0) // -X diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 2bb2cdd9978..0b3969fadb9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -21,6 +21,13 @@ StructuredBuffer _xyBoundsBuffer : register(t0); // {x_min, x_max, y_min, y_max} #endif +#if (PASS == PRUNE_COARSE_TILES) + // 1x list for all entites (sorted by category, we concatenate lists of all views). + StructuredBuffer _EntityBoundsBuffer : register(t0); + // 1x list for all entites (sorted by category, we concatenate lists of all views). + StructuredBuffer _SrcCoarseTileBuffer : register(t1); // Index range + index list +#endif + /* ------------------------------ Outputs ----------------------------------- */ #if (PASS == FILL_COARSE_TILES) @@ -59,12 +66,24 @@ static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uin /* ------------------------------ Implementation ---------------------------- */ -#if (REMAINDER(TILE_ENTRY_LIMIT + 2, 2) != 0) - #error "(TILE_ENTRY_LIMIT + 2) must be an integer multiple of 2." +// !!! IMPORTANT !!! +// The legacy code from Morten provides us special projection matrices (and their inverses). +// These matrices are different from the matrices the HDRP uses. +// There is no reversed-Z buffering (effectively, forced UNITY_REVERSED_Z = 0). +// Additionally, there is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). +// Therefore, all coordinate systems are left-handed, Y-up, without W-flip. +// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. +// y z +// | / +// 0 -- x + +#if (REMAINDER(TILE_ENTRY_LIMIT, 2) != 0) + #error "TILE_ENTRY_LIMIT must be an integer multiple of 2." #endif #define THREADS_PER_GROUP (64) +// 1x thread per tile. [numthreads(THREADS_PER_GROUP, 1, 1)] void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { @@ -99,13 +118,13 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { // Compute 2-D the AABB of the tile. const uint2 tileAaBbMinPtSS = clampedTileCoord * TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (clampedTileCoord + 1) * TILE_SIZE + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (clampedTileCoord + 1) * TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 tileBoundsX = float2(tileAaBbMinPtNDC.x, tileAaBbMaxPtNDC.x); // TODO: add epsilon for numerical robustness? const float2 tileBoundsY = float2(tileAaBbMinPtNDC.y, tileAaBbMaxPtNDC.y); // TODO: add epsilon for numerical robustness? - // Define inputs and outputs. + // Define inputs (i) and outputs (j). uint i = 0, j = 0; uint indexPair = 0; @@ -126,7 +145,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) last = max(i, last); // 2x 16-bit indices per uint. - indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits + indexPair |= i << (16 * (j & 1)); // First Lo, then Hi bits if ((j & 1) != 0) // Is the pair complete & ready to be stored? { @@ -145,7 +164,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) { i = UINT16_MAX; // Add a terminator - indexPair |= i << (16 * (j & 1)); // Order: first Lo, then Hi bits + indexPair |= i << (16 * (j & 1)); // First Lo, then Hi bits _CoarseTileBuffer[outputStart + (j / 2)] = indexPair; } @@ -158,10 +177,122 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) _CoarseTileBuffer[headerIndex] = outputRange; } -[numthreads(THREADS_PER_GROUP, 1, 1)] -void PruneCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +// Below is copy-pasted from 'scrbound.compute'. +// Clipping a plane by a cube may produce a hexagon (6-gon). +// Clipping a hexagon by 4 planes (substitute a quad for the plane) may produce a decagon (10-gon). +#define MAX_CLIP_VERTS (10) +#define NUM_VERTS (8) +#define NUM_FACES (6) +#define NUM_PLANES (6) +#define THREADS_PER_GROUP (64) +#define THREADS_PER_ENTITY (4) // Set to 1 for debugging +#define ENTITIES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_ENTITY) +#define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) +#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) +#define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) +#define VERTS_PER_FACE (4) + +// Needs the defines above. +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" + +// 5 arrays * 128 elements * 4 bytes each = 2560 bytes. +groupshared float gs_HapVertsX[VERTS_PER_GROUP]; +groupshared float gs_HapVertsY[VERTS_PER_GROUP]; +groupshared float gs_HapVertsZ[VERTS_PER_GROUP]; +groupshared float gs_HapVertsW[VERTS_PER_GROUP]; +groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) + +#define THREADS_PER_TILE (THREADS_PER_ENTITY) // Helps with naming +#define TILES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_TILE) + +// ************************************************************************************************* +// At this point, each tile has a list of conservatively selected entities. +// The idea it to spend a few more clock cycles to remove entities that do not belong to the tile. +// We use roughly the same idea as in 'scrbound.compute': +// we test the bounding volume of the entity against the mini-frustum of the tile. +// The difference is that we do not need to compute the AABB. +// Thus, there is a "slow" path and a "fast" path. The latter includes "trivial" accept or reject. +// "trivial" accept or reject .......... +// ************************************************************************************************* + +bool TryCullEntity(uint a, uint2 b) { + return false; +} + +[numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] +void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) +{ + // TODO: swizzle blocks of tiles to improve locality & reduce divergence at the cost of padding? + const uint t = threadID.x; + const uint tile = threadID.y; + const uint g = groupID.x; + const uint cat = groupID.y; + const uint eye = groupID.z; + + const uint globalTileIndex = IndexFromCoordinate(uint2(tile, g), TILES_PER_GROUP); + const uint clampedTileIndex = min(globalTileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); + + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(clampedTileIndex, cat, eye); + uint tileRangeData = _SrcCoarseTileBuffer[tileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; + + if (!isTileEmpty) + { + const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(clampedTileIndex, cat, eye); + + // Define inputs (i) and outputs (j). + uint i = 0, j = 0; + uint indexPair = 0; + + uint first = UINT16_MAX, last = 0; + + while (i < TILE_ENTRY_LIMIT) + { + uint entityPair = _SrcCoarseTileBuffer[tileBufferBodyIndex + (i / 2)]; // 16-bit indices + uint entityIndex = BitFieldExtract(entityPair, 16 * (i & 1), 16); // First Lo, then Hi bits + + if (entityIndex == UINT16_MAX) + { + break; // Reached the terminator + } + + if (!TryCullEntity(entityIndex, clampedTileCoord)) + { + // The entity was not culled, so transfer it over. + first = min(entityIndex, first); + last = max(entityIndex, last); + + // 2x 16-bit indices per uint. + indexPair |= entityIndex << (16 * (j & 1)); // First Lo, then Hi bits + + if ((j & 1) != 0) // Is the pair complete & ready to be stored? + { + _DstCoarseTileBuffer[tileBufferBodyIndex + (j / 2)] = indexPair; + + indexPair = 0; // In order to use bitwise OR above + } + + j++; + } + + i++; + } + + if (j < TILE_ENTRY_LIMIT) + { + uint entityIndex = UINT16_MAX; // Add a terminator + + indexPair |= entityIndex << (16 * (j & 1)); // First Lo, then Hi bits + + _DstCoarseTileBuffer[tileBufferBodyIndex + (j / 2)] = indexPair; + } + + tileRangeData = (last << 16) | first; + } + _DstCoarseTileBuffer[tileBufferHeaderIndex] = tileRangeData; } [numthreads(THREADS_PER_GROUP, 1, 1)] diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index 9c62c94e1bc..4eac0e19bec 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -97,12 +97,14 @@ static class HDShaderIDs public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList"); public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData"); - public static readonly int _EntityBoundsBuffer = Shader.PropertyToID(nameof(_EntityBoundsBuffer)); - public static readonly int _xyBoundsBuffer = Shader.PropertyToID(nameof(_xyBoundsBuffer)); - public static readonly int _wBoundsBuffer = Shader.PropertyToID(nameof(_wBoundsBuffer)); - public static readonly int _zBinBuffer = Shader.PropertyToID(nameof(_zBinBuffer)); - public static readonly int _CoarseTileBuffer = Shader.PropertyToID(nameof(_CoarseTileBuffer)); - public static readonly int _FineTileBuffer = Shader.PropertyToID(nameof(_FineTileBuffer)); + public static readonly int _EntityBoundsBuffer = Shader.PropertyToID(nameof(_EntityBoundsBuffer)); + public static readonly int _xyBoundsBuffer = Shader.PropertyToID(nameof(_xyBoundsBuffer)); + public static readonly int _wBoundsBuffer = Shader.PropertyToID(nameof(_wBoundsBuffer)); + public static readonly int _CoarseTileBuffer = Shader.PropertyToID(nameof(_CoarseTileBuffer)); + public static readonly int _SrcCoarseTileBuffer = Shader.PropertyToID(nameof(_SrcCoarseTileBuffer)); + public static readonly int _DstCoarseTileBuffer = Shader.PropertyToID(nameof(_DstCoarseTileBuffer)); + public static readonly int _FineTileBuffer = Shader.PropertyToID(nameof(_FineTileBuffer)); + public static readonly int _zBinBuffer = Shader.PropertyToID(nameof(_zBinBuffer)); public static readonly int g_TileFeatureFlags = Shader.PropertyToID("g_TileFeatureFlags"); From bc1f01f0e9c9f26fc2b6cc2d4fed2c439c3a387c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 28 Oct 2020 18:45:15 -0700 Subject: [PATCH 065/209] TryCullEntity WIP --- .../LightLoop/TilingAndBinningUtilities.hlsl | 24 +++++- .../Lighting/LightLoop/scrbound.compute | 2 +- .../Runtime/Lighting/LightLoop/tile.compute | 78 ++++++++++++++++--- .../Runtime/Lighting/LightLoop/zbin.compute | 4 - 4 files changed, 91 insertions(+), 17 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 851d8ec41cf..d78c1362e94 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -73,6 +73,16 @@ float4x4 Homogenize3x3(float3x3 R) return M; } +float SqDistPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +{ + float sqDist = 0; + + sqDist += Sq(Max3(pt.x - aaBbMaxPt.x, aaBbMinPt.x - pt.x, 0.0f)); + sqDist += Sq(Max3(pt.y - aaBbMaxPt.y, aaBbMinPt.y - pt.y, 0.0f)); + + return sqDist; +} + // a: aspect ratio. // p: distance to the projection plane. // n: distance to the near plane. @@ -110,9 +120,9 @@ bool IntervalsOverlap(uint2 i1, uint2 i2) return l <= u; // Is the intersection non-empty? } -uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint eye) +uint ComputeEntityBoundsBufferIndex(uint globalEntityIndex, uint eye) { - return IndexFromCoordinate(uint2(entityIndex, eye), _BoundedEntityCount); + return IndexFromCoordinate(uint2(globalEntityIndex, eye), _BoundedEntityCount); } uint ComputeZBinBufferIndex(uint zBin, uint category, uint eye) @@ -123,6 +133,16 @@ uint ComputeZBinBufferIndex(uint zBin, uint category, uint eye) #ifndef NO_SHADERVARIABLESGLOBAL_HLSL +// Repackage to work around ridiculous constant buffer limitations of HLSL. +static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; +static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; + +uint ComputeEntityBoundsBufferIndex(uint entityIndex, uint category, uint eye) +{ + uint offset = s_BoundedEntityOffsetPerCategory[category]; + return IndexFromCoordinate(uint2(offset + entityIndex, eye), _BoundedEntityCount); +} + // Cannot be used to index directly into the buffer. // Use ComputeZBinBufferIndex for that purpose. uint ComputeZBinIndex(float linearDepth) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 43f0d6b1edf..19543b75cd2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -677,7 +677,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { // Compute the center and the extents (half-diagonal) of the bounding box. float2 center = mul(projMat, float4(rbpC.xyz, 1)).xy; - float2 extents = mul(projMat, float4(radius.xx, 0, 0)).xy; + float2 extents = mul(projMat, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse rectMin = center - extents; rectMax = center + extents; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 0b3969fadb9..e1d7819c521 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -60,10 +60,6 @@ /* ------------------------------ Utilities --------------------------------- */ -// Repackage to work around ridiculous constant buffer limitations of HLSL. -static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; -static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; - /* ------------------------------ Implementation ---------------------------- */ // !!! IMPORTANT !!! @@ -205,6 +201,73 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL #define THREADS_PER_TILE (THREADS_PER_ENTITY) // Helps with naming #define TILES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_TILE) +bool TryCullSphere(float3 center, float radius, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat) +{ + bool isCulled; + + // We do not consider the near and the far plane (as as in 'scrbound.compute'). + if (g_isOrthographic) + { + // Compute the center and the extents (half-diagonal) of the bounding box. + float2 sphereCenterCS = mul(projMat, float4(center, 1)).xy; + float2 sphereExtentsCS = mul(projMat, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse + + // Convert to clip-space coordinates. + float2 aaBbMinPtCS = aaBbMinPtNDC * 2 - 1; + float2 aaBbMaxPtCS = aaBbMaxPtNDC * 2 - 1; + + // Make them relative to the ellipse. + aaBbMinPtCS -= sphereCenterCS; + aaBbMaxPtCS -= sphereCenterCS; + + // Transform the ellipse into a unit circle. + aaBbMinPtCS *= rcp(sphereExtentsCS); + aaBbMaxPtCS *= rcp(sphereExtentsCS); + + // Compute the distance from the center of the sphere (at the origin) to the AABB. + float sqDist = SqDistPointAaBb(0, aaBbMinPtCS, aaBbMaxPtCS); + + isCulled = sqDist > 1; + } + else // Perspective + { + // Extract the frustum planes? IDK... + isCulled = false; + } + + return isCulled; +} + +bool TryCullEntity(uint entityIndex, uint category, uint eye, uint2 tileCoord, uint t /* thread */) +{ + const uint2 tileAaBbMinPtSS = tileCoord * TILE_SIZE; + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE + const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide + const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + + const uint bufferIndex = ComputeEntityBoundsBufferIndex(entityIndex, category, eye); + const FiniteLightBound cullData = _EntityBoundsBuffer[bufferIndex]; + + const float4x4 projMat = g_mProjectionArr[eye]; // For the entire view frustum + const float4x4 invProjMat = g_mInvProjectionArr[eye]; // For the entire view frustum + + // Bounding frustum. + const float3 rbpC = cullData.center.xyz; // View-space + const float3 rbpX = cullData.boxAxisX.xyz; // Pre-scaled + const float3 rbpY = cullData.boxAxisY.xyz; // Pre-scaled + const float3 rbpZ = cullData.boxAxisZ.xyz; // Pre-scaled + const float scale = cullData.scaleXY; // scale.x = scale.y + // Bounding sphere. + const float radius = cullData.radius; + + bool trivialReject = false, trivialAccept = false; + + // 1. Attempt to trivially reject the entity by considering its bounding sphere. + trivialReject = TryCullSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat); + + return trivialReject; +} + // ************************************************************************************************* // At this point, each tile has a list of conservatively selected entities. // The idea it to spend a few more clock cycles to remove entities that do not belong to the tile. @@ -215,11 +278,6 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL // "trivial" accept or reject .......... // ************************************************************************************************* -bool TryCullEntity(uint a, uint2 b) -{ - return false; -} - [numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { @@ -258,7 +316,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou break; // Reached the terminator } - if (!TryCullEntity(entityIndex, clampedTileCoord)) + if (!TryCullEntity(entityIndex, cat, eye, clampedTileCoord, t)) { // The entity was not culled, so transfer it over. first = min(entityIndex, first); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 0a12f513189..bf7434ede12 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -24,10 +24,6 @@ RWStructuredBuffer _zBinBuffer : register(u0); // {last << 16 | first} /* ------------------------------ Utilities --------------------------------- */ -// Repackage to work around ridiculous constant buffer limitations of HLSL. -static uint s_BoundedEntityOffsetPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityOffsetPerCategory; -static uint s_BoundedEntityCountPerCategory[BOUNDEDENTITYCATEGORY_COUNT] = (uint[BOUNDEDENTITYCATEGORY_COUNT])_BoundedEntityCountPerCategory; - /* ------------------------------ Implementation ---------------------------- */ float2 ComputeZBinLinearDepthBounds(uint bin, float4 encodingParams) From 63743080d558fac6d85386178ae7f713dbabfebc Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 29 Oct 2020 17:00:09 -0700 Subject: [PATCH 066/209] OptimizeOrthographicMatrix --- .../LightLoop/TilingAndBinningUtilities.hlsl | 14 ++++++++++++++ .../Runtime/Lighting/LightLoop/scrbound.compute | 6 ++++-- .../Runtime/Lighting/LightLoop/tile.compute | 6 ++++-- .../Runtime/ShaderLibrary/ShaderVariables.hlsl | 1 + 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index d78c1362e94..14067895d71 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -73,6 +73,20 @@ float4x4 Homogenize3x3(float3x3 R) return M; } +float4x4 OptimizeOrthographicMatrix(float4x4 M) +{ + // | x 0 0 x | + // | 0 x 0 x | + // | x x x x | + // | 0 0 0 1 | + + M._12_13 = 0; + M._21_23 = 0; + M._41_42_43 = 0; M._44 = 1; + + return M; +} + float SqDistPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) { float sqDist = 0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 19543b75cd2..6671d5b4aaf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -675,9 +675,11 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // For the 'x' and 'y' components, the solution is given below. if (g_isOrthographic) { + float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); + // Compute the center and the extents (half-diagonal) of the bounding box. - float2 center = mul(projMat, float4(rbpC.xyz, 1)).xy; - float2 extents = mul(projMat, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse + float2 center = mul(orthoProj, float4(rbpC.xyz, 1)).xy; + float2 extents = mul(orthoProj, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse rectMin = center - extents; rectMax = center + extents; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index e1d7819c521..d81c1a91ec4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -208,9 +208,11 @@ bool TryCullSphere(float3 center, float radius, float2 aaBbMinPtNDC, float2 aaBb // We do not consider the near and the far plane (as as in 'scrbound.compute'). if (g_isOrthographic) { + float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); + // Compute the center and the extents (half-diagonal) of the bounding box. - float2 sphereCenterCS = mul(projMat, float4(center, 1)).xy; - float2 sphereExtentsCS = mul(projMat, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse + float2 sphereCenterCS = mul(orthoProj, float4(center.xyz, 1)).xy; + float2 sphereExtentsCS = mul(orthoProj, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse // Convert to clip-space coordinates. float2 aaBbMinPtCS = aaBbMinPtNDC * 2 - 1; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl index ccc952522eb..cecf9d93ea2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl @@ -215,6 +215,7 @@ float4x4 OptimizeProjectionMatrix(float4x4 M) // We can avoid loading and doing math with constants. M._21_41 = 0; M._12_42 = 0; + return M; } From 5f47615c07b270c02a5bd16332547742e6389496 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 29 Oct 2020 17:13:50 -0700 Subject: [PATCH 067/209] Fix broken shaders --- .../ScreenSpaceLighting/GTAOTemporalDenoise.compute | 2 +- .../ScreenSpaceGlobalIllumination.compute | 6 +++--- .../Runtime/PostProcessing/Shaders/BloomPrefilter.compute | 2 +- .../Runtime/PostProcessing/Shaders/BloomUpsample.compute | 2 +- .../PostProcessing/Shaders/DepthOfFieldCoCReproject.compute | 2 +- .../PostProcessing/Shaders/DepthOfFieldCombine.compute | 2 +- .../PostProcessing/Shaders/DepthOfFieldGather.compute | 2 +- .../PostProcessing/Shaders/DepthOfFieldPrefilter.compute | 2 +- .../Runtime/PostProcessing/Shaders/DoFGather.compute | 2 +- .../Runtime/PostProcessing/Shaders/PaniniProjection.compute | 2 +- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute index e2e18913a50..2adf4155364 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute @@ -62,7 +62,7 @@ void TemporalDenoise(uint3 dispatchThreadId : SV_DispatchThreadID) float currDepth, currAO; UnpackData(currFrameData, currAO, currDepth); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(8, 8)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); #if HALF_RES float2 closest = posInputs.positionSS * 2; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute index ae91a4eb037..720188a067c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute @@ -238,10 +238,10 @@ void TRACE_GLOBAL_ILLUMINATION(uint3 dispatchThreadId : SV_DispatchThreadID, uin bool killRay = deviceDepth == UNITY_RAW_FAR_CLIP_VALUE; // Convert this to a world space position (camera relative) #if HALF_RES - PositionInputs posInput = GetPositionInput(fullResCoord, _ScreenSize.zw, deviceDepth, UNITY_MATRIX_I_VP, GetWorldToViewMatrix(), 0); + PositionInputs posInput = GetPositionInput(fullResCoord, _ScreenSize.zw, deviceDepth, UNITY_MATRIX_I_VP, GetWorldToViewMatrix()); #else - PositionInputs posInput = GetPositionInput(currentCoord, _ScreenSize.zw, deviceDepth, UNITY_MATRIX_I_VP, GetWorldToViewMatrix(), 0); -#endif + PositionInputs posInput = GetPositionInput(currentCoord, _ScreenSize.zw, deviceDepth, UNITY_MATRIX_I_VP, GetWorldToViewMatrix()); +#endif // Compute the view direction (world space) float3 viewWS = GetWorldSpaceNormalizeViewDir(posInput.positionWS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute index 627a1294a87..85a5c548a38 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute @@ -24,7 +24,7 @@ CBUFFER_END void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw); float2 uv = posInputs.positionNDC; // Use a rotated grid to minimize artifacts coming from horizontal and vertical boundaries diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute index dba4a7cbe48..c7372d856b0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute @@ -29,7 +29,7 @@ CBUFFER_END void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw); float2 uv = ClampAndScaleUVForBilinear(posInputs.positionNDC, _TexelSize.zw) ; float3 highRes = LOAD_TEXTURE2D_X(_InputHighTexture, posInputs.positionSS).xyz; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute index 4ddecbfbe11..cc7b0a6428e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute @@ -40,7 +40,7 @@ void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); float2 uv = posInputs.positionNDC; #if 0 diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute index e837e088c3e..ed8b5251893 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute @@ -34,7 +34,7 @@ void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); float2 uv = posInputs.positionNDC * _RTHandleScale.xy; CTYPE outColor = LOAD_TEXTURE2D_X(_InputTexture, posInputs.positionSS).CTYPE_SWIZZLE; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute index fc7f62c8c4d..44bec00839b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute @@ -77,7 +77,7 @@ void MAIN(uint3 dispatchThreadId : SV_DispatchThreadID) if (any(dispatchThreadId.xy >= uint2(_TexelSize.xy))) return; // Out of bounds, discard - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw, uint2(GROUP_RES, GROUP_RES)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _TexelSize.zw); float2 uv = posInputs.positionNDC; float2 barrelUV = (uv * 2.0 - 1.0) * BarrelClipping; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute index 32a92351a79..0bf0600e44a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute @@ -37,7 +37,7 @@ void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); float2 texelSize = _ScreenSize.zw * _TargetScale.x; - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), texelSize, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), texelSize); float2 uv = posInputs.positionNDC; #if FULL_RES diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute index bce710f195f..f6e8c25c96b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute @@ -181,7 +181,7 @@ float GetRingWeight(int index, float dR) [numthreads(GROUP_RES, GROUP_RES, 1)] void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(GROUP_RES, GROUP_RES)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); int bucketIndex = 0; // Bucket 0 : far focus region diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute index 080736d0106..f47907317b5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute @@ -107,7 +107,7 @@ void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw, uint2(GROUP_SIZE, GROUP_SIZE)); + PositionInputs posInputs = GetPositionInput(float2(dispatchThreadId.xy), _ScreenSize.zw); float2 uv = posInputs.positionNDC; #if GENERIC From e663fd5f4358a76b50e599f04358c4502767387f Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 29 Oct 2020 19:05:34 -0700 Subject: [PATCH 068/209] Assert --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 5686fe13677..5c14040fadf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -4134,6 +4134,23 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) isGBufferNeeded: true ); + unsafe + { + int row, col; + + if (parameters.lightListCB.g_isOrthographic != 0) + { + row = 4; col = 4; + } + else + { + row = 4; col = 3; + } + + float flip = parameters.lightListCB.g_mProjectionArr[4 * (col - 1) + (row - 1)]; // Transposed + + Debug.Assert(flip == 1.0f, "View space with the z-axis pointing backwards is not supported!"); + } // The algorithm (below) works even if the bounded entity count is 0. // That is fairly efficient, and allows us to avoid weird special cases. From a7802ac333c0f7227088cc1339c233ca6271810a Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 29 Oct 2020 20:12:51 -0700 Subject: [PATCH 069/209] Fix z-flip --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 5c14040fadf..ce73ede064b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -2590,7 +2590,7 @@ static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewI Matrix4x4 viewMatrix = GetWorldToViewMatrix(hdCamera, viewIndex); // Non-RWS Vector3 positionVS = viewMatrix.MultiplyPoint(positionWS); - return -positionVS.z; // The coordinate system of the view space is right-handed, Z pointing backwards + return positionVS.z; // Assume the z-axis actually points forwards and is not flipped... } // 'w' is the linear depth (Z coordinate of the view-space position). From d900d8e89990ab0fe1947658ef6d52d6b49cdb34 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 29 Oct 2020 20:18:59 -0700 Subject: [PATCH 070/209] Don't hope; assert --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index ce73ede064b..79c6cf6a35b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -2590,7 +2590,9 @@ static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewI Matrix4x4 viewMatrix = GetWorldToViewMatrix(hdCamera, viewIndex); // Non-RWS Vector3 positionVS = viewMatrix.MultiplyPoint(positionWS); - return positionVS.z; // Assume the z-axis actually points forwards and is not flipped... + Debug.Assert(viewMatrix.MultiplyVector(hdCamera.camera.transform.forward).z > 0, "The view space z-axis must point forward!"); + + return positionVS.z; } // 'w' is the linear depth (Z coordinate of the view-space position). From 433e23f842c37f5314cb0bfe2ad43b3669b2f426 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 30 Oct 2020 18:05:02 -0700 Subject: [PATCH 071/209] Implement sphere culling --- .../Lighting/LightLoop/ClippingUtilities.hlsl | 12 +++ .../Lighting/LightLoop/LightLoopDef.hlsl | 4 +- .../LightLoop/TilingAndBinningUtilities.hlsl | 10 --- .../Lighting/LightLoop/scrbound.compute | 8 +- .../Runtime/Lighting/LightLoop/tile.compute | 88 +++++++++++++------ 5 files changed, 81 insertions(+), 41 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl index 64098db508f..ca7bc5ff795 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl @@ -99,4 +99,16 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, } } +float2 ClosestPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +{ + return clamp(pt, aaBbMinPt, aaBbMaxPt); +} + +float SqDistToClosestPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +{ + float2 qt = ClosestPointAaBb(pt, aaBbMinPt, aaBbMaxPt); + + return dot(pt - qt, pt - qt); +} + #endif // UNITY_CLIPPINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 5c9bd3a479b..34b4b9495a4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -159,7 +159,7 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} const bool isTileEmpty = tileRangeData == UINT16_MAX; - if (!isTileEmpty) + if (!isTileEmpty) // Avoid wasted work { const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} @@ -167,7 +167,7 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); - if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) + if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) // Avoid wasted work { const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 14067895d71..b4bc1839c5e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -87,16 +87,6 @@ float4x4 OptimizeOrthographicMatrix(float4x4 M) return M; } -float SqDistPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) -{ - float sqDist = 0; - - sqDist += Sq(Max3(pt.x - aaBbMaxPt.x, aaBbMinPt.x - pt.x, 0.0f)); - sqDist += Sq(Max3(pt.y - aaBbMaxPt.y, aaBbMinPt.y - pt.y, 0.0f)); - - return sqDist; -} - // a: aspect ratio. // p: distance to the projection plane. // n: distance to the near plane. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 6671d5b4aaf..949d9654154 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -260,7 +260,7 @@ float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float float lenSqOC = dot(C.xz, C.xz); float lenSqOB = lenSqOC - r * r; // If |OB'| = 0 or |OC'| = 0, the bounding planes tangent to the sphere do not exist. - if (lenSqOB > 0) + if (lenSqOB > 0) // The sphere does not contain the origin { float lenOB = sqrt(lenSqOB); // |OB' x OC'| = |OB'| * |OC'| * Sin[a']. @@ -292,7 +292,7 @@ float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float D.x = C.x * lenOB + (C.z * r); D.z = C.z * lenOB - (C.x * r); // We can transform OB and OD as direction vectors. - // For the simplification below, see OptimizeProjectionMatrix. + // Manually optimize the perspective projection (see OptimizeProjectionMatrix). float rapBx = (B.x * rcp(B.z)) * projScale + projOffset; float rapDx = (D.x * rcp(D.z)) * projScale + projOffset; // One problem with the above is that this direction may, for certain spheres, @@ -686,8 +686,8 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } else // Perspective { - float2 xBounds = ComputeBoundsOfProjectedSphere(rbpC.xxz, radius, projMat._m00, projMat._m02); // X-Z plane - float2 yBounds = ComputeBoundsOfProjectedSphere(rbpC.yyz, radius, projMat._m11, projMat._m12); // Y-Z plane + float2 xBounds = ComputeBoundsOfProjectedSphere(rbpC.xxz, radius, projMat._11, projMat._13); // X-Z plane + float2 yBounds = ComputeBoundsOfProjectedSphere(rbpC.yyz, radius, projMat._22, projMat._23); // Y-Z plane rectMin = float2(xBounds.r, yBounds.r); rectMax = float2(xBounds.g, yBounds.g); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index d81c1a91ec4..a80a64562d2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -201,40 +201,78 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL #define THREADS_PER_TILE (THREADS_PER_ENTITY) // Helps with naming #define TILES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_TILE) -bool TryCullSphere(float3 center, float radius, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat) +bool TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat) { - bool isCulled; + bool isCulled = false; - // We do not consider the near and the far plane (as as in 'scrbound.compute'). - if (g_isOrthographic) + if ((C.z + r) > 0) // Is the sphere at least *partially* in front of the origin? { - float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); - - // Compute the center and the extents (half-diagonal) of the bounding box. - float2 sphereCenterCS = mul(orthoProj, float4(center.xyz, 1)).xy; - float2 sphereExtentsCS = mul(orthoProj, float4(radius.xx, 0, 0)).xy; // Axis-aligned ellipse - // Convert to clip-space coordinates. float2 aaBbMinPtCS = aaBbMinPtNDC * 2 - 1; float2 aaBbMaxPtCS = aaBbMaxPtNDC * 2 - 1; - // Make them relative to the ellipse. - aaBbMinPtCS -= sphereCenterCS; - aaBbMaxPtCS -= sphereCenterCS; + // We do not clip the sphere against the near and the far plane (same as in 'scrbound.compute'). + if (g_isOrthographic) + { + float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); - // Transform the ellipse into a unit circle. - aaBbMinPtCS *= rcp(sphereExtentsCS); - aaBbMaxPtCS *= rcp(sphereExtentsCS); + // Compute the center and the extents (half-diagonal) of the bounding box. + float2 sphereCenterCS = mul(orthoProj, float4(C.xyz, 1)).xy; + float2 sphereExtentsCS = mul(orthoProj, float4(r.xx, 0, 0)).xy; // Axis-aligned ellipse - // Compute the distance from the center of the sphere (at the origin) to the AABB. - float sqDist = SqDistPointAaBb(0, aaBbMinPtCS, aaBbMaxPtCS); + // Make them relative to the ellipse. + aaBbMinPtCS -= sphereCenterCS; + aaBbMaxPtCS -= sphereCenterCS; - isCulled = sqDist > 1; - } - else // Perspective - { - // Extract the frustum planes? IDK... - isCulled = false; + // Transform the ellipse into a unit circle. + aaBbMinPtCS *= rcp(sphereExtentsCS); + aaBbMaxPtCS *= rcp(sphereExtentsCS); + + // Compute the distance from the center of the sphere (at the origin) to the AABB. + float sqDist = SqDistToClosestPointAaBb(0, aaBbMinPtCS, aaBbMaxPtCS); + + isCulled = sqDist > 1; + } + else if ((C.z > 0) && ((dot(C, C) - r * r) > 0)) // Perspective; the sphere does not contain the origin + { + // Project the center of the bounding sphere (ellipse). + float2 projC; + // Manually optimize the perspective projection (see OptimizeProjectionMatrix). + projC.x = (C.x * rcp(C.z)) * projMat._11 + projMat._13; + projC.y = (C.y * rcp(C.z)) * projMat._22 + projMat._23; + + // Find the closest point inside the AABB. + float2 projQ = ClosestPointAaBb(projC, aaBbMinPtCS, aaBbMaxPtCS); + + // Unproject the closest point (Q') into the view space (Q). + // Inverse of an arbitrary perspective projection matrix looks like this: + // | x 0 0 x | + // | 0 x 0 x | + // | 0 0 0 1 | + // | x x x x | + // Q.x = (InvProj._11 * Q'.x + InvProj._14) / Q.w + // Q.y = (InvProj._22 * Q'.y + InvProj._24) / Q.w + // Q.z = 1 / Q.w + // We don't need to normalize. + + float3 Q; + Q.x = (invProjMat._11 * projQ.x + invProjMat._14); + Q.y = (invProjMat._22 * projQ.y + invProjMat._24); + Q.z = 1; // Near plane + + #if 0 + // Compute the angle of the bounding cone. + float sinAlpha = r * rsqrt(dot(C, C)); + float cosAlpha = sqrt(1 - sinAlpha * sinAlpha); + // Compute the angle between OC and OQ. + float cosBeta = dot(C, Q) * rsqrt(dot(C, C) * dot(Q, Q)); + + isCulled = cosBeta < cosAlpha; + #else + // Same, but faster. + isCulled = dot(C, Q) < sqrt(dot(Q, Q) * (dot(C, C) - r * r)); + #endif + } } return isCulled; @@ -298,7 +336,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou uint tileRangeData = _SrcCoarseTileBuffer[tileBufferHeaderIndex]; // {last << 16 | first} const bool isTileEmpty = tileRangeData == UINT16_MAX; - if (!isTileEmpty) + if (!isTileEmpty) // Avoid wasted work { const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(clampedTileIndex, cat, eye); From e95e700ecd11feafa3dce55fa0ff08dded31a327 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 30 Oct 2020 18:34:38 -0700 Subject: [PATCH 072/209] Update warning --- .../Runtime/Lighting/LightLoop/scrbound.compute | 6 ++---- .../Runtime/Lighting/LightLoop/tile.compute | 10 ++++------ 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 949d9654154..0b45ad4fe57 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -28,10 +28,8 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} // !!! IMPORTANT !!! // The legacy code from Morten provides us special projection matrices (and their inverses). // These matrices are different from the matrices the HDRP uses. -// There is no reversed-Z buffering (effectively, forced UNITY_REVERSED_Z = 0). -// Additionally, there is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). -// Therefore, all coordinate systems are left-handed, Y-up, without W-flip. -// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. +// There is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). +// All coordinate systems are left-handed, Y-up, Z-forward. // y z // | / // 0 -- x diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a80a64562d2..7d60d895095 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -65,10 +65,8 @@ // !!! IMPORTANT !!! // The legacy code from Morten provides us special projection matrices (and their inverses). // These matrices are different from the matrices the HDRP uses. -// There is no reversed-Z buffering (effectively, forced UNITY_REVERSED_Z = 0). -// Additionally, there is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). -// Therefore, all coordinate systems are left-handed, Y-up, without W-flip. -// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. +// There is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). +// All coordinate systems are left-handed, Y-up, Z-forward. // y z // | / // 0 -- x @@ -201,17 +199,17 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL #define THREADS_PER_TILE (THREADS_PER_ENTITY) // Helps with naming #define TILES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_TILE) +// We do not clip the sphere against the near and the far plane (same as in 'scrbound.compute'). bool TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat) { bool isCulled = false; if ((C.z + r) > 0) // Is the sphere at least *partially* in front of the origin? { - // Convert to clip-space coordinates. + // Transform to clip-space coordinates. float2 aaBbMinPtCS = aaBbMinPtNDC * 2 - 1; float2 aaBbMaxPtCS = aaBbMaxPtNDC * 2 - 1; - // We do not clip the sphere against the near and the far plane (same as in 'scrbound.compute'). if (g_isOrthographic) { float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); From c8301f5f1c445a27ebafbe7487a98478450978a6 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 30 Oct 2020 18:47:01 -0700 Subject: [PATCH 073/209] Comment --- .../Runtime/Lighting/LightLoop/tile.compute | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 7d60d895095..61f9a6cbd49 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -298,12 +298,12 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, uint2 tileCoord, u // Bounding sphere. const float radius = cullData.radius; - bool trivialReject = false, trivialAccept = false; + bool isCulled = false; // 1. Attempt to trivially reject the entity by considering its bounding sphere. - trivialReject = TryCullSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat); + isCulled = TryCullSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat); - return trivialReject; + return isCulled; } // ************************************************************************************************* @@ -312,8 +312,8 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, uint2 tileCoord, u // We use roughly the same idea as in 'scrbound.compute': // we test the bounding volume of the entity against the mini-frustum of the tile. // The difference is that we do not need to compute the AABB. -// Thus, there is a "slow" path and a "fast" path. The latter includes "trivial" accept or reject. -// "trivial" accept or reject .......... +// Thus, there is a "slow" path and a "fast" path. The "fast" path means we try to find a way +// to "trivial" reject the entity if its bounding volume clearly does not overlap the tile. // ************************************************************************************************* [numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] From 6a48ee4749715dc64c941035b0345e865afdbd5c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 30 Oct 2020 20:58:06 -0700 Subject: [PATCH 074/209] Optimize FiniteLightBound --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 8 +++++--- .../Runtime/Lighting/LightLoop/LightLoop.cs.hlsl | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 79c6cf6a35b..ed1ee09e364 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -414,12 +414,14 @@ class TiledLightingConstants [GenerateHLSL] struct FiniteLightBound { + public Vector3 center; // Center (in the view space) shared by the bounding box and the bounding sphere + public float radius; // Of the bounding sphere public Vector3 boxAxisX; // Scaled by the extents (half-size) + public float scaleXY; // Scale applied to the top of the box to turn it into a truncated pyramid (X = Y) public Vector3 boxAxisY; // Scaled by the extents (half-size) + public float __pad0__; public Vector3 boxAxisZ; // Scaled by the extents (half-size) - public Vector3 center; // Center of the bounding box in the view space - public float scaleXY; // Scale applied to the top of the box to turn it into a truncated pyramid (X = Y) - public float radius; // Bounding sphere (may or may not be tighter than the bounding box) + public float __pad1__; } [GenerateHLSL] diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 087e04caa77..7a4dd513e44 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -86,12 +86,14 @@ // PackingRules = Exact struct FiniteLightBound { + float3 center; + float radius; float3 boxAxisX; + float scaleXY; float3 boxAxisY; + float __pad0__; float3 boxAxisZ; - float3 center; - float scaleXY; - float radius; + float __pad1__; }; // Generated from UnityEngine.Rendering.HighDefinition.LightVolumeData From d621d7fac5a1f4866c174eeb1ee83669b20794c3 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 30 Oct 2020 21:04:47 -0700 Subject: [PATCH 075/209] Early out --- .../Runtime/Lighting/LightLoop/scrbound.compute | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 0b45ad4fe57..a9cff7954e0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -184,7 +184,7 @@ void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint // Sutherland-Hodgeman polygon clipping algorithm. // It works by clipping the entire polygon against one clipping plane at a time. - while (clipMaskOfFace != 0) + while ((clipMaskOfFace != 0) && (srcSize != 0)) { uint p = firstbitlow(clipMaskOfFace); From 917a6b032a191572e7559d7fbb51a293948a814c Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 2 Nov 2020 16:30:42 -0800 Subject: [PATCH 076/209] Allow TryCullSphere to trivially accept --- .../LightLoop/TilingAndBinningUtilities.hlsl | 14 ++ .../Runtime/Lighting/LightLoop/tile.compute | 150 ++++++++++-------- 2 files changed, 95 insertions(+), 69 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index b4bc1839c5e..2b0051c74cc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -87,6 +87,20 @@ float4x4 OptimizeOrthographicMatrix(float4x4 M) return M; } +float4x4 OptimizePerspectiveMatrix(float4x4 M) +{ + // | x 0 x 0 | + // | 0 x x 0 | + // | x x x x | + // | 0 0 x 0 | + + M._12_14 = 0; + M._21_24 = 0; + M._41_42_44 = 0; // Unity sometimes sets M._43 = -1 :( + + return M; +} + // a: aspect ratio. // p: distance to the projection plane. // n: distance to the near plane. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 61f9a6cbd49..51124366476 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -200,9 +200,10 @@ groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL #define TILES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_TILE) // We do not clip the sphere against the near and the far plane (same as in 'scrbound.compute'). -bool TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat) +void TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat, + out bool trivialAccept, out bool trivialReject) { - bool isCulled = false; + trivialAccept = trivialReject = false; if ((C.z + r) > 0) // Is the sphere at least *partially* in front of the origin? { @@ -214,81 +215,86 @@ bool TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, { float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); - // Compute the center and the extents (half-diagonal) of the bounding box. - float2 sphereCenterCS = mul(orthoProj, float4(C.xyz, 1)).xy; - float2 sphereExtentsCS = mul(orthoProj, float4(r.xx, 0, 0)).xy; // Axis-aligned ellipse + // Project the center of the bounding sphere (ellipse). + float3 projC = mul(orthoProj, float4(C.xyz, 1)).xyz; + trivialAccept = all(aaBbMinPtCS <= projC.xy && projC.xy <= aaBbMaxPtCS.xy) && (0 <= projC.z <= 1); + + if (!trivialAccept) + { + float2 projDims = mul(orthoProj, float4(r.xx, 0, 0)).xy; // Axis-aligned ellipse - // Make them relative to the ellipse. - aaBbMinPtCS -= sphereCenterCS; - aaBbMaxPtCS -= sphereCenterCS; + // Make them relative to the ellipse. + aaBbMinPtCS -= projC.xy; + aaBbMaxPtCS -= projC.xy; - // Transform the ellipse into a unit circle. - aaBbMinPtCS *= rcp(sphereExtentsCS); - aaBbMaxPtCS *= rcp(sphereExtentsCS); + // Transform the ellipse into a unit circle. + aaBbMinPtCS *= rcp(projDims); + aaBbMaxPtCS *= rcp(projDims); - // Compute the distance from the center of the sphere (at the origin) to the AABB. - float sqDist = SqDistToClosestPointAaBb(0, aaBbMinPtCS, aaBbMaxPtCS); + // Compute the distance from the center of the sphere (at the origin) to the AABB. + float sqDist = SqDistToClosestPointAaBb(0, aaBbMinPtCS, aaBbMaxPtCS); - isCulled = sqDist > 1; + trivialReject = sqDist > 1; + } } - else if ((C.z > 0) && ((dot(C, C) - r * r) > 0)) // Perspective; the sphere does not contain the origin + else if (C.z > 0) // Perspective; the sphere is in front of the origin { + float4x4 perspProj = OptimizePerspectiveMatrix(projMat); + // Project the center of the bounding sphere (ellipse). - float2 projC; - // Manually optimize the perspective projection (see OptimizeProjectionMatrix). - projC.x = (C.x * rcp(C.z)) * projMat._11 + projMat._13; - projC.y = (C.y * rcp(C.z)) * projMat._22 + projMat._23; - - // Find the closest point inside the AABB. - float2 projQ = ClosestPointAaBb(projC, aaBbMinPtCS, aaBbMaxPtCS); - - // Unproject the closest point (Q') into the view space (Q). - // Inverse of an arbitrary perspective projection matrix looks like this: - // | x 0 0 x | - // | 0 x 0 x | - // | 0 0 0 1 | - // | x x x x | - // Q.x = (InvProj._11 * Q'.x + InvProj._14) / Q.w - // Q.y = (InvProj._22 * Q'.y + InvProj._24) / Q.w - // Q.z = 1 / Q.w - // We don't need to normalize. - - float3 Q; - Q.x = (invProjMat._11 * projQ.x + invProjMat._14); - Q.y = (invProjMat._22 * projQ.y + invProjMat._24); - Q.z = 1; // Near plane - - #if 0 - // Compute the angle of the bounding cone. - float sinAlpha = r * rsqrt(dot(C, C)); - float cosAlpha = sqrt(1 - sinAlpha * sinAlpha); - // Compute the angle between OC and OQ. - float cosBeta = dot(C, Q) * rsqrt(dot(C, C) * dot(Q, Q)); - - isCulled = cosBeta < cosAlpha; - #else - // Same, but faster. - isCulled = dot(C, Q) < sqrt(dot(Q, Q) * (dot(C, C) - r * r)); - #endif + float3 projC = mul(perspProj, float4(C.xyz, 1)).xyz * rcp(C.z); // Assume M[3] = (0,0,1,0) + trivialAccept = all(aaBbMinPtCS <= projC.xy && projC.xy <= aaBbMaxPtCS.xy) && (0 <= projC.z <= 1); + + if (!trivialAccept && (dot(C, C) - r * r) > 0) + { + // Find the closest point inside the AABB. + float2 projQ = ClosestPointAaBb(projC.xy, aaBbMinPtCS, aaBbMaxPtCS); + + // Unproject the closest point (Q') into the view space (Q). + // Inverse of an arbitrary perspective projection matrix looks like this: + // | x 0 0 x | + // | 0 x 0 x | + // | 0 0 0 1 | + // | x x x x | + // Q.x = (InvProj._11 * Q'.x + InvProj._14) / Q.w + // Q.y = (InvProj._22 * Q'.y + InvProj._24) / Q.w + // Q.z = 1 / Q.w + // We don't need to normalize. + + float3 Q; + Q.x = (invProjMat._11 * projQ.x + invProjMat._14); + Q.y = (invProjMat._22 * projQ.y + invProjMat._24); + Q.z = 1; // Near plane with reversed Z-buffering + + #if 0 + // Compute the angle of the bounding cone. + float sinAlpha = r * rsqrt(dot(C, C)); + float cosAlpha = sqrt(1 - sinAlpha * sinAlpha); + // Compute the angle between OC and OQ. + float cosBeta = dot(C, Q) * rsqrt(dot(C, C) * dot(Q, Q)); + + trivialReject = cosBeta < cosAlpha; + #else + // Same, but faster. + trivialReject = dot(C, Q) < sqrt(dot(Q, Q) * (dot(C, C) - r * r)); + #endif + } } } - - return isCulled; + else // if ((C.z + r) <= 0) + { + trivialReject = true; + } } -bool TryCullEntity(uint entityIndex, uint category, uint eye, uint2 tileCoord, uint t /* thread */) +bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMinPtNDC, float2 tileAaBbMaxPtNDC , uint t /* thread */) { - const uint2 tileAaBbMinPtSS = tileCoord * TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE - const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide - const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float4x4 projMat = g_mProjectionArr[eye]; // For the entire view frustum + const float4x4 invProjMat = g_mInvProjectionArr[eye]; // For the entire view frustum const uint bufferIndex = ComputeEntityBoundsBufferIndex(entityIndex, category, eye); const FiniteLightBound cullData = _EntityBoundsBuffer[bufferIndex]; - const float4x4 projMat = g_mProjectionArr[eye]; // For the entire view frustum - const float4x4 invProjMat = g_mInvProjectionArr[eye]; // For the entire view frustum - // Bounding frustum. const float3 rbpC = cullData.center.xyz; // View-space const float3 rbpX = cullData.boxAxisX.xyz; // Pre-scaled @@ -298,12 +304,13 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, uint2 tileCoord, u // Bounding sphere. const float radius = cullData.radius; - bool isCulled = false; + // 1. Attempt to trivially accept/reject the entity by considering its bounding sphere. + bool trivialAccept, trivialReject; + TryCullSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat, + trivialAccept, trivialReject); - // 1. Attempt to trivially reject the entity by considering its bounding sphere. - isCulled = TryCullSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat); - return isCulled; + return trivialReject; } // ************************************************************************************************* @@ -311,9 +318,9 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, uint2 tileCoord, u // The idea it to spend a few more clock cycles to remove entities that do not belong to the tile. // We use roughly the same idea as in 'scrbound.compute': // we test the bounding volume of the entity against the mini-frustum of the tile. -// The difference is that we do not need to compute the AABB. -// Thus, there is a "slow" path and a "fast" path. The "fast" path means we try to find a way -// to "trivial" reject the entity if its bounding volume clearly does not overlap the tile. +// The difference is that this time we do not need to compute the AABB. +// Thus, there is a "slow" path and a "fast" path. The fast path includes "trivial" accept and reject. +// If we cannot find a way to accept or reject a tile with certainty, we must conservatively keep it. // ************************************************************************************************* [numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] @@ -330,6 +337,11 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou const uint clampedTileIndex = min(globalTileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); + const uint2 tileAaBbMinPtSS = clampedTileCoord * TILE_SIZE; + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE + const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide + const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(clampedTileIndex, cat, eye); uint tileRangeData = _SrcCoarseTileBuffer[tileBufferHeaderIndex]; // {last << 16 | first} const bool isTileEmpty = tileRangeData == UINT16_MAX; @@ -354,7 +366,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou break; // Reached the terminator } - if (!TryCullEntity(entityIndex, cat, eye, clampedTileCoord, t)) + if (!TryCullEntity(entityIndex, cat, eye, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, t)) { // The entity was not culled, so transfer it over. first = min(entityIndex, first); From deb2550193ce782a2e711ce0f94215ef014e4aac Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 5 Nov 2020 18:08:34 -0800 Subject: [PATCH 077/209] TryCullBoundingFrustum works --- .../Lighting/LightLoop/ClippingUtilities.hlsl | 228 ++++++++++- .../Lighting/LightLoop/scrbound.compute | 284 +++----------- .../Runtime/Lighting/LightLoop/tile.compute | 363 ++++++++++++++++-- 3 files changed, 589 insertions(+), 286 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl index ca7bc5ff795..eadbd0f3b72 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl @@ -1,10 +1,17 @@ #ifndef UNITY_CLIPPINGUTILITIES_INCLUDED #define UNITY_CLIPPINGUTILITIES_INCLUDED -// (Sep 16, 2020) -// Improve the quality of generated code at the expense of readability. -// Remove when the shader compiler is clever enough to perform this optimization for us. -#define OBTUSE_COMPILER +float2 ClosestPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +{ + return clamp(pt, aaBbMinPt, aaBbMaxPt); +} + +float SqDistToClosestPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +{ + float2 qt = ClosestPointAaBb(pt, aaBbMinPt, aaBbMaxPt); + + return dot(pt - qt, pt - qt); +} struct ClipVertex { @@ -12,17 +19,32 @@ struct ClipVertex float bc; // Boundary coordinate with respect to the plane 'p' }; -ClipVertex CreateClipVertex(uint p, float4 v) +float4 CreateClipPlane(uint p, float3 cubeMin, float3 cubeMax) { - bool evenPlane = (p & 1) == 0; + bool evenPlane = (p & 1) == 0; + float s = evenPlane ? 1 : -1; + float3 distances = evenPlane ? cubeMin : cubeMax; + float d = distances[p / 2]; + + float3 n; +#if 0 + n = 0; + n[p / 2] = s; // Doesn't compile... +#else + n.x = (0 == (p / 2)) ? s : 0; + n.y = (1 == (p / 2)) ? s : 0; + n.z = (2 == (p / 2)) ? s : 0; +#endif - float c = v[p >> 1]; - float w = v.w; + return float4(n, -s * d); // Normal points inwards +} +ClipVertex CreateClipVertex(float4 vert, float4 plane) +{ ClipVertex cv; - cv.pt = v; - cv.bc = evenPlane ? c : w - c; // dot(PlaneEquation, HapVertex); + cv.pt = vert; + cv.bc = dot(vert, plane); return cv; } @@ -34,14 +56,113 @@ float4 IntersectEdgeAgainstPlane(ClipVertex v0, ClipVertex v1) return lerp(v0.pt, v1.pt, alpha); } -void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, +#ifdef INCLUDE_SPECIFIC_CLIPPING_CODE +// The code below is specific to binned lighting. + +// (Sep 16, 2020) +// Improve the quality of generated code at the expense of readability. +// Remove when the shader compiler is clever enough to perform this optimization for us. +#define OBTUSE_COMPILER + +// Clipping a plane by a cube may produce a hexagon (6-gon). +// Clipping a hexagon by 4 planes (substitute a quad for the plane) may produce a decagon (10-gon). +#define MAX_CLIP_VERTS (10) +#define NUM_VERTS (8) +#define NUM_FACES (6) +#define NUM_PLANES (6) +#define THREADS_PER_GROUP (64) +#define THREADS_PER_ENTITY (4) // Set to 1 for debugging +#define ENTITIES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_ENTITY) +#define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) +#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) +#define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) +#define VERTS_PER_FACE (4) + +// All planes and faces are always in the standard order (see below). +// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. +#define FACE_LEFT (1 << 0) // -X +#define FACE_RIGHT (1 << 1) // +X +#define FACE_BOTTOM (1 << 2) // -Y +#define FACE_TOP (1 << 3) // +Y +#define FACE_FRONT (1 << 4) // -Z +#define FACE_BACK (1 << 5) // +Z +#define FACE_MASK ((1 << NUM_FACES) - 1) +#define PLANE_MASK FACE_MASK // 6 culling planes, the same order + +float3 GenerateVertexOfStandardCube(uint v) +{ + float3 p; + + p.x = ((v & 1) == 0) ? -1 : 1; // FACE_LEFT : FACE_RIGHT + p.y = ((v & 2) == 0) ? -1 : 1; // FACE_BOTTOM : FACE_TOP + p.z = ((v & 4) == 0) ? -1 : 1; // FACE_FRONT : FACE_BACK + + return p; +} + +// All vertices are always in the standard order (see below). +uint GetFaceMaskOfVertex(uint v) +{ + // 0: (-1, -1, -1) -> { FACE_LEFT | FACE_BOTTOM | FACE_FRONT } + // 1: (+1, -1, -1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_FRONT } + // 2: (-1, +1, -1) -> { FACE_LEFT | FACE_TOP | FACE_FRONT } + // 3: (+1, +1, -1) -> { FACE_RIGHT | FACE_TOP | FACE_FRONT } + // 4: (-1, -1, +1) -> { FACE_LEFT | FACE_BOTTOM | FACE_BACK } + // 5: (+1, -1, +1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_BACK } + // 6: (-1, +1, +1) -> { FACE_LEFT | FACE_TOP | FACE_BACK } + // 7: (+1, +1, +1) -> { FACE_RIGHT | FACE_TOP | FACE_BACK } + // ((v & 1) == 0) ? 1 : 2) | ((v & 2) == 0) ? 4 : 8) | ((v & 4) == 0) ? 16 : 32) + uint f = (FACE_LEFT << BitFieldExtract(v, 0, 1)) + | (FACE_BOTTOM << BitFieldExtract(v, 1, 1)) + | (FACE_FRONT << BitFieldExtract(v, 2, 1)); + + return f; +}; + +// A list of vertices for each face (CCW order w.r.t. its normal, starting from the LSB). +#define VERT_LIST_LEFT ((4) << 9 | (6) << 6 | (2) << 3 | (0) << 0) +#define VERT_LIST_RIGHT ((3) << 9 | (7) << 6 | (5) << 3 | (1) << 0) +#define VERT_LIST_BOTTOM ((1) << 9 | (5) << 6 | (4) << 3 | (0) << 0) +#define VERT_LIST_TOP ((6) << 9 | (7) << 6 | (3) << 3 | (2) << 0) +#define VERT_LIST_FRONT ((2) << 9 | (3) << 6 | (1) << 3 | (0) << 0) +#define VERT_LIST_BACK ((5) << 9 | (7) << 6 | (6) << 3 | (4) << 0) + +uint GetVertexListOfFace(uint f) +{ + // Warning: don't add 'static' here unless you want really bad code gen. + const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, + (VERT_LIST_TOP << 12) | VERT_LIST_BOTTOM, + (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); + + return BitFieldExtract(allVertLists[f >> 1], 12 * (f & 1), 12); +} + +groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) + +// Returns 'true' if it manages to cull the face. +uint TryCullFace(uint f, uint baseVertexOffset) +{ + uint cullMaskOfFace = PLANE_MASK; // Initially behind + uint vertListOfFace = GetVertexListOfFace(f); + + for (uint j = 0; j < VERTS_PER_FACE; j++) + { + uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); + // Non-zero if ALL the vertices are behind the same plane(s). + cullMaskOfFace &= gs_BehindMasksOfVerts[baseVertexOffset + v]; + } + + return (cullMaskOfFace != 0); +} + +void ClipPolygonAgainstPlane(float4 clipPlane, uint srcBegin, uint srcSize, inout float4 vertRingBuffer[MAX_CLIP_VERTS], out uint dstBegin, out uint dstSize) { dstBegin = srcBegin + srcSize; // Start at the end; we don't use modular arithmetic here dstSize = 0; - ClipVertex tailVert = CreateClipVertex(p, vertRingBuffer[(srcBegin + srcSize - 1) % MAX_CLIP_VERTS]); + ClipVertex tailVert = CreateClipVertex(vertRingBuffer[(srcBegin + srcSize - 1) % MAX_CLIP_VERTS], clipPlane); #ifdef OBTUSE_COMPILER uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; @@ -53,7 +174,7 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, #ifndef OBTUSE_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif - ClipVertex leadVert = CreateClipVertex(p, vertRingBuffer[modSrcIdx]); + ClipVertex leadVert = CreateClipVertex(vertRingBuffer[modSrcIdx], clipPlane); // Execute Blinn's line clipping algorithm. // Classify the line segment. 4 cases: @@ -99,16 +220,87 @@ void ClipPolygonAgainstPlane(uint p, uint srcBegin, uint srcSize, } } -float2 ClosestPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +// 5 arrays * 128 elements * 4 bytes each = 2560 bytes. +groupshared float gs_HapVertsX[VERTS_PER_GROUP]; +groupshared float gs_HapVertsY[VERTS_PER_GROUP]; +groupshared float gs_HapVertsZ[VERTS_PER_GROUP]; +groupshared float gs_HapVertsW[VERTS_PER_GROUP]; + +// Returns 'true' if the face has been entirely clipped. +bool ClipFaceAgainstCube(uint f, float3 cubeMin, float3 cubeMax, uint baseVertexOffset, + out uint srcBegin, out uint srcSize, + out float4 vertRingBuffer[MAX_CLIP_VERTS]) { - return clamp(pt, aaBbMinPt, aaBbMaxPt); + srcBegin = 0; + srcSize = VERTS_PER_FACE; + + uint clipMaskOfFace = 0; // Initially in front + uint vertListOfFace = GetVertexListOfFace(f); + + for (uint j = 0; j < VERTS_PER_FACE; j++) + { + uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); + // Non-zero if ANY of the vertices are behind the same plane(s). + clipMaskOfFace |= gs_BehindMasksOfVerts[baseVertexOffset + v]; + + // Not all edges may require clipping. However, filtering the vertex list + // is somewhat expensive, so we currently don't do it. + vertRingBuffer[j].x = gs_HapVertsX[baseVertexOffset + v]; + vertRingBuffer[j].y = gs_HapVertsY[baseVertexOffset + v]; + vertRingBuffer[j].z = gs_HapVertsZ[baseVertexOffset + v]; + vertRingBuffer[j].w = gs_HapVertsW[baseVertexOffset + v]; + } + + // Sutherland-Hodgeman polygon clipping algorithm. + // It works by clipping the entire polygon against one clipping plane at a time. + while ((clipMaskOfFace != 0) && (srcSize != 0)) + { + uint p = firstbitlow(clipMaskOfFace); + + float4 clipPlane = CreateClipPlane(p, cubeMin, cubeMax); + + uint dstBegin, dstSize; + ClipPolygonAgainstPlane(clipPlane, srcBegin, srcSize, vertRingBuffer, dstBegin, dstSize); + + srcBegin = dstBegin; + srcSize = dstSize; + + clipMaskOfFace ^= 1 << p; // Clear the bit to continue using firstbitlow() + } + + return srcSize == 0; } -float SqDistToClosestPointAaBb(float2 pt, float2 aaBbMinPt, float2 aaBbMaxPt) +void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERTS], + bool isOrthoProj, float4x4 invProjMat, + inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) { - float2 qt = ClosestPointAaBb(pt, aaBbMinPt, aaBbMaxPt); +#ifdef OBTUSE_COMPILER + uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; +#endif + for (uint j = srcBegin; j < (srcBegin + srcSize); j++) + { + #ifndef OBTUSE_COMPILER + uint modSrcIdx = j % MAX_CLIP_VERTS; + #endif + float4 hapVert = vertRingBuffer[modSrcIdx]; + // Clamp to the bounds in case of numerical errors (may still generate -0). + float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); + float rbpVertVSz = hapVert.w; - return dot(pt - qt, pt - qt); + if (isOrthoProj) // Must replace (w = 1) + { + rbpVertVSz = dot(invProjMat[2], hapVert); + } + + ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); + ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVSz)); + #ifdef OBTUSE_COMPILER + modSrcIdx++; + modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; + #endif + } } +#endif // INCLUDE_SPECIFIC_CLIPPING_CODE #endif // UNITY_CLIPPINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index a9cff7954e0..5d2a58d3100 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -9,6 +9,9 @@ #define NO_SHADERVARIABLESGLOBAL_HLSL #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" #undef NO_SHADERVARIABLESGLOBAL_HLSL +#define INCLUDE_SPECIFIC_CLIPPING_CODE +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" +#undef INCLUDE_SPECIFIC_CLIPPING_CODE /* ------------------------------ Inputs ------------------------------------ */ @@ -23,212 +26,6 @@ RWStructuredBuffer _wBoundsBuffer : register(u1); // {w_min, w_max} /* ------------------------------ Utilities --------------------------------- */ -/* ------------------------------ Implementation ---------------------------- */ - -// !!! IMPORTANT !!! -// The legacy code from Morten provides us special projection matrices (and their inverses). -// These matrices are different from the matrices the HDRP uses. -// There is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). -// All coordinate systems are left-handed, Y-up, Z-forward. -// y z -// | / -// 0 -- x - -#ifdef SHADER_API_XBOXONE -// The Xbox shader compiler expects the lane swizzle mask to be a compile-time constant. -// In our case, the mask is a compile-time constant, but it is defined inside a loop -// that is unrolled at the compile time, and the constants are generated during the -// constant propagation pass of the optimizer. This works fine on PlayStation, but does not work -// on Xbox. In order to avoid writing hideous code specifically for Xbox, we disable the support -// of wave intrinsics on Xbox until the Xbox compiler is fixed. -#undef PLATFORM_SUPPORTS_WAVE_INTRINSICS -#endif - -// Clipping a plane by a cube may produce a hexagon (6-gon). -// Clipping a hexagon by 4 planes (substitute a quad for the plane) may produce a decagon (10-gon). -#define MAX_CLIP_VERTS (10) -#define NUM_VERTS (8) -#define NUM_FACES (6) -#define NUM_PLANES (6) -#define THREADS_PER_GROUP (64) -#define THREADS_PER_ENTITY (4) // Set to 1 for debugging -#define ENTITIES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_ENTITY) -#define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) -#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) -#define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) -#define VERTS_PER_FACE (4) - -// Needs the defines above. -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" - -// All planes and faces are always in the standard order (see below). -// Near and far planes are swapped in the case of Z-reversal, but it does not change the algorithm. -#define FACE_LEFT (1 << 0) // -X -#define FACE_RIGHT (1 << 1) // +X -#define FACE_BOTTOM (1 << 2) // -Y -#define FACE_TOP (1 << 3) // +Y -#define FACE_FRONT (1 << 4) // -Z -#define FACE_BACK (1 << 5) // +Z -#define FACE_MASK ((1 << NUM_FACES) - 1) - -// A list of vertices for each face (CCW order w.r.t. its normal, starting from the LSB). -#define VERT_LIST_LEFT ((4) << 9 | (6) << 6 | (2) << 3 | (0) << 0) -#define VERT_LIST_RIGHT ((3) << 9 | (7) << 6 | (5) << 3 | (1) << 0) -#define VERT_LIST_BOTTOM ((1) << 9 | (5) << 6 | (4) << 3 | (0) << 0) -#define VERT_LIST_TOP ((6) << 9 | (7) << 6 | (3) << 3 | (2) << 0) -#define VERT_LIST_FRONT ((2) << 9 | (3) << 6 | (1) << 3 | (0) << 0) -#define VERT_LIST_BACK ((5) << 9 | (7) << 6 | (6) << 3 | (4) << 0) - -// All vertices are always in the standard order (see below). -uint GetFaceMaskOfVertex(uint v) -{ - // 0: (-1, -1, -1) -> { FACE_LEFT | FACE_BOTTOM | FACE_FRONT } - // 1: (+1, -1, -1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_FRONT } - // 2: (-1, +1, -1) -> { FACE_LEFT | FACE_TOP | FACE_FRONT } - // 3: (+1, +1, -1) -> { FACE_RIGHT | FACE_TOP | FACE_FRONT } - // 4: (-1, -1, +1) -> { FACE_LEFT | FACE_BOTTOM | FACE_BACK } - // 5: (+1, -1, +1) -> { FACE_RIGHT | FACE_BOTTOM | FACE_BACK } - // 6: (-1, +1, +1) -> { FACE_LEFT | FACE_TOP | FACE_BACK } - // 7: (+1, +1, +1) -> { FACE_RIGHT | FACE_TOP | FACE_BACK } - // ((v & 1) == 0) ? 1 : 2) | ((v & 2) == 0) ? 4 : 8) | ((v & 4) == 0) ? 16 : 32) - uint f = (FACE_LEFT << BitFieldExtract(v, 0, 1)) - | (FACE_BOTTOM << BitFieldExtract(v, 1, 1)) - | (FACE_FRONT << BitFieldExtract(v, 2, 1)); - - return f; -}; - -float3 GenerateVertexOfStandardCube(uint v) -{ - float3 p; - - p.x = ((v & 1) == 0) ? -1 : 1; // FACE_LEFT : FACE_RIGHT - p.y = ((v & 2) == 0) ? -1 : 1; // FACE_BOTTOM : FACE_TOP - p.z = ((v & 4) == 0) ? -1 : 1; // FACE_FRONT : FACE_BACK - - return p; -} - -uint GetVertexListOfFace(uint f) -{ - // Warning: don't add 'static' here unless you want really bad code gen. - const uint3 allVertLists = uint3((VERT_LIST_RIGHT << 12) | VERT_LIST_LEFT, - (VERT_LIST_TOP << 12) | VERT_LIST_BOTTOM, - (VERT_LIST_BACK << 12) | VERT_LIST_FRONT); - - return BitFieldExtract(allVertLists[f >> 1], 12 * (f & 1), 12); -} - -// 5 arrays * 128 elements * 4 bytes each = 2560 bytes. -groupshared float gs_HapVertsX[VERTS_PER_GROUP]; -groupshared float gs_HapVertsY[VERTS_PER_GROUP]; -groupshared float gs_HapVertsZ[VERTS_PER_GROUP]; -groupshared float gs_HapVertsW[VERTS_PER_GROUP]; -groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) - -#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS -// 1 array * 16 elements * 4 bytes each = 64 bytes. -groupshared uint gs_CullClipFaceMasks[ENTITIES_PER_GROUP]; // 6 faces each (HLSL does not support small data types) - -// 8 arrays * 16 elements * 4 bytes each = 512 bytes. -// These are actually floats reinterpreted as uints. -// The reason is because floating-point atomic operations are not supported. -groupshared uint gs_NdcAaBbMinPtX[ENTITIES_PER_GROUP]; -groupshared uint gs_NdcAaBbMaxPtX[ENTITIES_PER_GROUP]; -groupshared uint gs_NdcAaBbMinPtY[ENTITIES_PER_GROUP]; -groupshared uint gs_NdcAaBbMaxPtY[ENTITIES_PER_GROUP]; -// Skip Z, we do not need it. -groupshared uint gs_NdcAaBbMinPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate -groupshared uint gs_NdcAaBbMaxPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate -#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - -// Returns 'true' if it manages to cull the face. -bool TryCullFace(uint f, uint behindMasksOfVerts[NUM_VERTS]) -{ - uint cullMaskOfFace = FACE_MASK; // Initially behind - uint vertListOfFace = GetVertexListOfFace(f); - - for (uint j = 0; j < VERTS_PER_FACE; j++) - { - uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); - // Non-zero if ALL the vertices are behind any of the planes. - cullMaskOfFace &= behindMasksOfVerts[v]; - } - - return (cullMaskOfFace != 0); -} - -void ClipFaceAgainstViewVolume(uint f, uint behindMasksOfVerts[NUM_VERTS], uint baseVertexOffset, - out uint srcBegin, out uint srcSize, - out float4 vertRingBuffer[MAX_CLIP_VERTS]) -{ - srcBegin = 0; - srcSize = VERTS_PER_FACE; - - uint clipMaskOfFace = 0; // Initially in front - uint vertListOfFace = GetVertexListOfFace(f); - - for (uint j = 0; j < VERTS_PER_FACE; j++) - { - uint v = BitFieldExtract(vertListOfFace, 3 * j, 3); - // Non-zero if ANY of the vertices are behind any of the planes. - clipMaskOfFace |= behindMasksOfVerts[v]; - - // Not all edges may require clipping. However, filtering the vertex list - // is somewhat expensive, so we currently don't do it. - vertRingBuffer[j].x = gs_HapVertsX[baseVertexOffset + v]; - vertRingBuffer[j].y = gs_HapVertsY[baseVertexOffset + v]; - vertRingBuffer[j].z = gs_HapVertsZ[baseVertexOffset + v]; - vertRingBuffer[j].w = gs_HapVertsW[baseVertexOffset + v]; - } - - // Sutherland-Hodgeman polygon clipping algorithm. - // It works by clipping the entire polygon against one clipping plane at a time. - while ((clipMaskOfFace != 0) && (srcSize != 0)) - { - uint p = firstbitlow(clipMaskOfFace); - - uint dstBegin, dstSize; - ClipPolygonAgainstPlane(p, srcBegin, srcSize, vertRingBuffer, dstBegin, dstSize); - - srcBegin = dstBegin; - srcSize = dstSize; - - clipMaskOfFace ^= 1 << p; // Clear the bit to continue using firstbitlow() - } -} - -void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERTS], - bool isOrthoProj, float4x4 invProjMat, - inout float4 ndcAaBbMinPt, inout float4 ndcAaBbMaxPt) -{ -#ifdef OBTUSE_COMPILER - uint modSrcIdx = srcBegin % MAX_CLIP_VERTS; -#endif - for (uint j = srcBegin; j < (srcBegin + srcSize); j++) - { - #ifndef OBTUSE_COMPILER - uint modSrcIdx = j % MAX_CLIP_VERTS; - #endif - float4 hapVert = vertRingBuffer[modSrcIdx]; - // Clamp to the bounds in case of numerical errors (may still generate -0). - float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); - float rbpVertVSz = hapVert.w; - - if (isOrthoProj) // Must replace (w = 1) - { - rbpVertVSz = dot(invProjMat[2], hapVert); - } - - ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); - ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVSz)); - #ifdef OBTUSE_COMPILER - modSrcIdx++; - modSrcIdx = (modSrcIdx == MAX_CLIP_VERTS) ? 0 : modSrcIdx; - #endif - } -} - // Given: 'C' is the center of the sphere in the view space, 'r' is its radius; // 'projScale' and 'projOffset' are used to perform projection of the X (or Y) component of a vector. float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float projOffset) @@ -312,6 +109,43 @@ float2 ComputeBoundsOfProjectedSphere(float3 C, float r, float projScale, float return float2(xMin, xMax); } +/* ------------------------------ Implementation ---------------------------- */ + +// !!! IMPORTANT !!! +// The legacy code from Morten provides us special projection matrices (and their inverses). +// These matrices are different from the matrices the HDRP uses. +// There is no clip-space flip (effectively, forced UNITY_UV_STARTS_AT_TOP = 0). +// All coordinate systems are left-handed, Y-up, Z-forward. +// y z +// | / +// 0 -- x + +#ifdef SHADER_API_XBOXONE +// (Sep 16, 2020) +// The Xbox shader compiler expects the lane swizzle mask to be a compile-time constant. +// In our case, the mask is a compile-time constant, but it is defined inside a loop +// that is unrolled at the compile time, and the constants are generated during the +// constant propagation pass of the optimizer. This works fine on PlayStation, but does not work +// on Xbox. In order to avoid writing hideous code specifically for Xbox, we disable the support +// of wave intrinsics on Xbox until the Xbox compiler is fixed. +#undef PLATFORM_SUPPORTS_WAVE_INTRINSICS +#endif + +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_CullClipFaceMasks[ENTITIES_PER_GROUP]; // 6 faces each (HLSL does not support small data types) +// 8 arrays * 16 elements * 4 bytes each = 512 bytes. +// These are actually floats reinterpreted as uints. +// The reason is because floating-point atomic operations are not supported. +groupshared uint gs_NdcAaBbMinPtX[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMaxPtX[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMinPtY[ENTITIES_PER_GROUP]; +groupshared uint gs_NdcAaBbMaxPtY[ENTITIES_PER_GROUP]; +// Skip Z, we do not need it. +groupshared uint gs_NdcAaBbMinPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate +groupshared uint gs_NdcAaBbMaxPtW[ENTITIES_PER_GROUP]; // View-space Z coordinate +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + // ************************************************************************************************* // The goal of this program is to compute the AABB of a bounded entity in the NDC space ([0, 1] range). // The entity is represented by a bounding sphere and a right bounding frustum with 6 faces and 8 vertices. @@ -375,7 +209,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // (0) Initialize the TGSM. if (t == 0) // Avoid bank conflicts { - gs_CullClipFaceMasks[entity] = 0; // Initially inside + gs_CullClipFaceMasks[entity] = 0; // Initially all faces are assumed to be inside gs_NdcAaBbMinPtX[entity] = asuint(1.0f); gs_NdcAaBbMaxPtX[entity] = asuint(0.0f); gs_NdcAaBbMinPtY[entity] = asuint(1.0f); @@ -395,7 +229,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // any single plane, we can trivially reject (cull) that face. uint cullClipFaceMask = 0; // Initially inside - uint i; // Avoid multiply-declared variable warning + uint i; // Avoid the multiply-declared variable warning // (1) Compute the vertices of the bounding frustum. for (i = 0; i < VERTS_PER_THREAD; i++) @@ -414,7 +248,8 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) float3 m = GenerateVertexOfStandardCube(v); m.xy *= ((v & 4) == 0) ? scale : 1; // X, Y in [-scale, scale] - float3 rbpVertVS = rbpC + m.x * rbpX + m.y * rbpY + m.z * rbpZ; + float3 rbpVertRVS = m.x * rbpX + m.y * rbpY + m.z * rbpZ; + float3 rbpVertVS = rbpC + rbpVertRVS; // Avoid generating (w = 0). rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; @@ -423,6 +258,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // Warning: the W component may be negative. // Flipping the -W pyramid by negating all coordinates is incorrect // and will break both classification and clipping. + // We are allowed to change the magnitude of the vector, but not its direction! // For the orthographic projection, (w = 1). // Transform the X and Y components: [-w, w] -> [0, w]. @@ -478,13 +314,15 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); } + + GroupMemoryBarrier(); // Wait for writes to gs_BehindMasksOfVerts, gs_HapVertsX #else InterlockedOr(gs_CullClipFaceMasks[entity], cullClipFaceMask); - GroupMemoryBarrierWithGroupSync(); + GroupMemoryBarrier(); // Wait for writes to gs_CullClipFaceMasks, gs_BehindMasksOfVerts, gs_HapVertsX cullClipFaceMask = gs_CullClipFaceMasks[entity]; -#endif +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS // (2) Test the corners of the view volume. if (cullClipFaceMask != 0) @@ -497,7 +335,6 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // P_l = (R * S)^{-1} * T^{-1} * P_v float4x4 invTranslateToEntitySpace = Translation4x4(-rbpC); float4x4 invRotateAndScaleInEntitySpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); - // TODO: avoid full inversion by using unit vectors and passing magnitudes explicitly. // This (orthographic) projection matrix maps a view-space point to a entity-space [-1, 1]^3 cube. float4x4 entitySpaceMatrix = mul(invRotateAndScaleInEntitySpace, invTranslateToEntitySpace); @@ -547,17 +384,6 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } } -#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS - GroupMemoryBarrierWithGroupSync(); -#endif - - uint behindMasksOfVerts[NUM_VERTS]; - - for (i = 0; i < NUM_VERTS; i++) - { - behindMasksOfVerts[i] = gs_BehindMasksOfVerts[baseVertexOffset + i]; - } - // (3) Cull the faces. { const uint cullFaceMask = cullClipFaceMask; @@ -571,9 +397,9 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { uint f = NthBitLow(cullFaceMask, n); - if (TryCullFace(f, behindMasksOfVerts)) + if (TryCullFace(f, baseVertexOffset)) { - cullClipFaceMask ^= 1 << f; // Clear the bit + cullClipFaceMask ^= 1 << f; } } } @@ -591,7 +417,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) #else InterlockedAnd(gs_CullClipFaceMasks[entity], cullClipFaceMask); - GroupMemoryBarrierWithGroupSync(); + GroupMemoryBarrier(); // Wait for writes to gs_CullClipFaceMasks cullClipFaceMask = gs_CullClipFaceMasks[entity]; #endif @@ -611,8 +437,8 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) uint srcBegin, srcSize; float4 vertRingBuffer[MAX_CLIP_VERTS]; - ClipFaceAgainstViewVolume(f, behindMasksOfVerts, baseVertexOffset, - srcBegin, srcSize, vertRingBuffer); + ClipFaceAgainstCube(f, 0, 1, baseVertexOffset, + srcBegin, srcSize, vertRingBuffer); UpdateAaBb(srcBegin, srcSize, vertRingBuffer, g_isOrthographic != 0, invProjMat, ndcAaBbMinPt, ndcAaBbMaxPt); } @@ -645,7 +471,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) InterlockedMin(gs_NdcAaBbMinPtW[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMinPt.w))); InterlockedMax(gs_NdcAaBbMaxPtW[entity], asuint(CLEAR_SIGN_BIT(ndcAaBbMaxPt.w))); - GroupMemoryBarrierWithGroupSync(); + GroupMemoryBarrier(); // Wait for writes to gs_NdcAaBbMinPtX ndcAaBbMinPt.x = asfloat(gs_NdcAaBbMinPtX[entity]); ndcAaBbMaxPt.x = asfloat(gs_NdcAaBbMaxPtX[entity]); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 51124366476..687e99b9ca4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -13,6 +13,23 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" +#define INCLUDE_SPECIFIC_CLIPPING_CODE +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" +#undef INCLUDE_SPECIFIC_CLIPPING_CODE + +#ifdef SHADER_API_XBOXONE +// (Sep 16, 2020) +// The Xbox shader compiler expects the lane swizzle mask to be a compile-time constant. +// In our case, the mask is a compile-time constant, but it is defined inside a loop +// that is unrolled at the compile time, and the constants are generated during the +// constant propagation pass of the optimizer. This works fine on PlayStation, but does not work +// on Xbox. In order to avoid writing hideous code specifically for Xbox, we disable the support +// of wave intrinsics on Xbox until the Xbox compiler is fixed. +#undef PLATFORM_SUPPORTS_WAVE_INTRINSICS +#endif + +// Requires the define above. +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" /* ------------------------------ Inputs ------------------------------------ */ @@ -71,12 +88,31 @@ // | / // 0 -- x +#ifdef SHADER_API_XBOXONE +// (Sep 16, 2020) +// The Xbox shader compiler expects the lane swizzle mask to be a compile-time constant. +// In our case, the mask is a compile-time constant, but it is defined inside a loop +// that is unrolled at the compile time, and the constants are generated during the +// constant propagation pass of the optimizer. This works fine on PlayStation, but does not work +// on Xbox. In order to avoid writing hideous code specifically for Xbox, we disable the support +// of wave intrinsics on Xbox until the Xbox compiler is fixed. +#undef PLATFORM_SUPPORTS_WAVE_INTRINSICS +#endif + +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS +// Booleans are stored in 2x consecutive SGPRs on GCN. +// So using LaneSwizzle is probably inefficient in this case... +// TODO: reimplement this using 'ballot'. +bool LaneSwizzle(bool x, uint andMask, uint orMask, uint xorMask) +{ + return (bool)LaneSwizzle((uint)x, uint andMask, uint orMask, uint xorMask) +} +#endif + #if (REMAINDER(TILE_ENTRY_LIMIT, 2) != 0) #error "TILE_ENTRY_LIMIT must be an integer multiple of 2." #endif -#define THREADS_PER_GROUP (64) - // 1x thread per tile. [numthreads(THREADS_PER_GROUP, 1, 1)] void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) @@ -171,37 +207,25 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) _CoarseTileBuffer[headerIndex] = outputRange; } -// Below is copy-pasted from 'scrbound.compute'. -// Clipping a plane by a cube may produce a hexagon (6-gon). -// Clipping a hexagon by 4 planes (substitute a quad for the plane) may produce a decagon (10-gon). -#define MAX_CLIP_VERTS (10) -#define NUM_VERTS (8) -#define NUM_FACES (6) -#define NUM_PLANES (6) -#define THREADS_PER_GROUP (64) -#define THREADS_PER_ENTITY (4) // Set to 1 for debugging -#define ENTITIES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_ENTITY) -#define VERTS_PER_GROUP (NUM_VERTS * ENTITIES_PER_GROUP) -#define VERTS_PER_THREAD (NUM_VERTS / THREADS_PER_ENTITY) -#define FACES_PER_THREAD (DIV_ROUND_UP(NUM_FACES, THREADS_PER_ENTITY)) -#define VERTS_PER_FACE (4) - -// Needs the defines above. -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl" - -// 5 arrays * 128 elements * 4 bytes each = 2560 bytes. -groupshared float gs_HapVertsX[VERTS_PER_GROUP]; -groupshared float gs_HapVertsY[VERTS_PER_GROUP]; -groupshared float gs_HapVertsZ[VERTS_PER_GROUP]; -groupshared float gs_HapVertsW[VERTS_PER_GROUP]; -groupshared uint gs_BehindMasksOfVerts[VERTS_PER_GROUP]; // 6 planes each (HLSL does not support small data types) - -#define THREADS_PER_TILE (THREADS_PER_ENTITY) // Helps with naming -#define TILES_PER_GROUP (THREADS_PER_GROUP / THREADS_PER_TILE) +// Improve naming by using the definitions below. +#define THREADS_PER_TILE (THREADS_PER_ENTITY) +#define TILES_PER_GROUP (ENTITIES_PER_GROUP) + +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_CullClipFaceMasks[TILES_PER_GROUP]; // 6 faces each (HLSL does not support small data types) +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_CulledFaceCounts[TILES_PER_GROUP]; // [0, 6] +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_CullMasksOfAllFaces[TILES_PER_GROUP]; // 6 planes each (HLSL does not support small data types) +// 1 array * 16 elements * 4 bytes each = 64 bytes. +groupshared uint gs_TrivialAcceptFlags[TILES_PER_GROUP]; // Just a boolean +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS // We do not clip the sphere against the near and the far plane (same as in 'scrbound.compute'). -void TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat, - out bool trivialAccept, out bool trivialReject) +void TryCullBoundingSphere(float3 C, float r, + float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat, + out bool trivialAccept, out bool trivialReject) { trivialAccept = trivialReject = false; @@ -221,15 +245,15 @@ void TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, if (!trivialAccept) { - float2 projDims = mul(orthoProj, float4(r.xx, 0, 0)).xy; // Axis-aligned ellipse + float2 projExtents = mul(orthoProj, float4(r.xx, 0, 0)).xy; // Axis-aligned ellipse // Make them relative to the ellipse. aaBbMinPtCS -= projC.xy; aaBbMaxPtCS -= projC.xy; // Transform the ellipse into a unit circle. - aaBbMinPtCS *= rcp(projDims); - aaBbMaxPtCS *= rcp(projDims); + aaBbMinPtCS *= rcp(projExtents); + aaBbMaxPtCS *= rcp(projExtents); // Compute the distance from the center of the sphere (at the origin) to the AABB. float sqDist = SqDistToClosestPointAaBb(0, aaBbMinPtCS, aaBbMaxPtCS); @@ -287,7 +311,256 @@ void TryCullSphere(float3 C, float r, float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, } } -bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMinPtNDC, float2 tileAaBbMaxPtNDC , uint t /* thread */) +void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, float scale, float radius, uint tile, uint t /* thread */, + float3 cubeMin, float3 cubeMax, float4x4 projMat, + out bool trivialAccept, out bool trivialReject) +{ + trivialAccept = trivialReject = false; + + const uint baseVertexOffset = tile * NUM_VERTS; + +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS + // (0) Initialize the TGSM. + if (t == 0) // Avoid bank conflicts + { + gs_CullClipFaceMasks[tile] = 0; // Initially all faces are assumed to be inside + gs_CulledFaceCounts[tile] = 0; // Initially none + gs_TrivialAcceptFlags[tile] = (uint)false; // Initially false + } +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + + // We must determine whether we have to clip or cull any of the faces. + // If all vertices of a face are inside with respect to all the culling planes, + // we can trivially accept that face. If all vertices of a face are behind + // any single plane, we can trivially reject (cull) that face. + uint cullClipFaceMask = 0; // Initially inside + + uint i; // Avoid the multiply-declared variable warning + + // (1) Compute the vertices of the bounding frustum. + for (i = 0; i < VERTS_PER_THREAD; i++) + { + uint v = t + i * THREADS_PER_TILE; + + // rbpVerts[0] = rbpC - rbpX * scale - rbpY * scale - rbpZ; (-s, -s, -1) + // rbpVerts[1] = rbpC + rbpX * scale - rbpY * scale - rbpZ; (+s, -s, -1) + // rbpVerts[2] = rbpC - rbpX * scale + rbpY * scale - rbpZ; (-s, +s, -1) + // rbpVerts[3] = rbpC + rbpX * scale + rbpY * scale - rbpZ; (+s, +s, -1) + // rbpVerts[4] = rbpC - rbpX - rbpY + rbpZ; (-1, -1, +1) + // rbpVerts[5] = rbpC + rbpX - rbpY + rbpZ; (+1, -1, +1) + // rbpVerts[6] = rbpC - rbpX + rbpY + rbpZ; (-1, +1, +1) + // rbpVerts[7] = rbpC + rbpX + rbpY + rbpZ; (+1, +1, +1) + + float3 m = GenerateVertexOfStandardCube(v); + m.xy *= ((v & 4) == 0) ? scale : 1; // X, Y in [-scale, scale] + + float3 rbpVertRVS = m.x * rbpX + m.y * rbpY + m.z * rbpZ; + float3 rbpVertVS = rbpC + rbpVertRVS; + // Avoid generating (w = 0). + rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; + + float4 hapVert = mul(projMat, float4(rbpVertVS, 1)); + + // Warning: the W component may be negative. + // Flipping the -W pyramid by negating all coordinates is incorrect + // and will break both classification and clipping. + // We are allowed to change the magnitude of the vector, but not its direction! + // For the orthographic projection, (w = 1). + + // Transform the X and Y components: [-w, w] -> [0, w]. + hapVert.xy = 0.5 * hapVert.xy + (0.5 * hapVert.w); + + // For each vertex, we must determine whether it is within the bounds. + // For culling and clipping, we must know, per culling plane, whether the vertex + // is in the positive or the negative half-space. + uint behindMask = 0; // Initially in front + + // Consider the vertex to be inside the view volume if: + // min_x <= x <= max_x + // min_y <= y <= max_y <-- include boundary points to avoid clipping them later + // min_z <= z <= max_z + // w is always valid + const float3 hapAaBbMinPT = cubeMin * abs(hapVert.w); + const float3 hapAaBbMaxPT = cubeMax * abs(hapVert.w); + // TODO: add epsilon for numerical robustness? + + for (uint j = 0; j < (NUM_PLANES / 2); j++) + { + float w = hapVert.w; + + behindMask |= (hapVert[j] < hapAaBbMinPT[j] ? 1 : 0) << (2 * j + 0); + behindMask |= (hapVert[j] > hapAaBbMaxPT[j] ? 1 : 0) << (2 * j + 1); + } + + if (behindMask == 0) // Inside? + { + // The vertex of the bounding frustum is inside the viewing frustum. + // But is it also inside the bounding sphere? + trivialAccept = trivialAccept || (dot(rbpVertRVS, rbpVertRVS) <= (radius * radius)); + } + else // Outside + { + // Mark all the faces of the bounding frustum associated with this vertex. + cullClipFaceMask |= GetFaceMaskOfVertex(v); + } + + gs_HapVertsX[baseVertexOffset + v] = hapVert.x; + gs_HapVertsY[baseVertexOffset + v] = hapVert.y; + gs_HapVertsZ[baseVertexOffset + v] = hapVert.z; + gs_HapVertsW[baseVertexOffset + v] = hapVert.w; + gs_BehindMasksOfVerts[baseVertexOffset + v] = behindMask; + } + +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (i = 0; i < FastLog2(THREADS_PER_TILE); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + + cullClipFaceMask |= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); + trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); + } + + GroupMemoryBarrier(); // Wait for writes to gs_BehindMasksOfVerts, gs_HapVerts +#else + InterlockedOr(gs_CullClipFaceMasks[tile], cullClipFaceMask); + InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); + + GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags, gs_CullClipFaceMasks, gs_BehindMasksOfVerts, gs_HapVerts + + cullClipFaceMask = gs_CullClipFaceMasks[tile]; + trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + + if (trivialAccept || trivialReject) return; + + // (2) Test the corners of the view volume. + // Skipped - pointless in this case. + + uint culledFaceCount = 0; // Potentially, by different planes + + // (3) Cull the faces. + { + const uint cullFaceMask = cullClipFaceMask; + const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] + + for (i = 0; i < FACES_PER_THREAD; i++) + { + uint n = t + i * THREADS_PER_TILE; + + if (n < numFacesToCull) + { + uint f = NthBitLow(cullFaceMask, n); + + if (TryCullFace(f, baseVertexOffset)) + { + culledFaceCount++; + cullClipFaceMask ^= 1 << f; + } + } + } + } + +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (i = 0; i < FastLog2(THREADS_PER_TILE); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + + cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); + culledFaceCount += LaneSwizzle(culledFaceCount, andMask, orMask, xorMask); + } +#else + InterlockedAnd(gs_CullClipFaceMasks[tile], cullClipFaceMask); + InterlockedAdd(gs_CulledFaceCounts[tile], culledFaceCount); + + GroupMemoryBarrier(); // Wait for writes to gs_CulledFaceCounts, gs_CullClipFaceMasks + + cullClipFaceMask = gs_CullClipFaceMasks[tile]; + culledFaceCount = gs_CulledFaceCounts[tile]; +#endif + + if (culledFaceCount == NUM_FACES) + { + // If we culled all the faces, there are 2 possibilities: + // 1. The bounding frustum is entirely outside the view frustum. + // -> We can safely reject this entity. + // 2. The bounding frustum is entirely inside the view frustum. + // -> We can safely accept this entity. + // Case 2 can only occur if the center of the bounding frustum is inside the view frustum. + // But, we already trivially accept using this condition inside TryCullBoundingSphere. + // So the only remaining possibility is Case 1. + trivialReject = true; + } + + if (trivialAccept || trivialReject) return; + + // (4) Clip the faces. + { + const uint clipFaceMask = cullClipFaceMask; + const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] + + for (i = 0; i < FACES_PER_THREAD; i++) + { + uint n = t + i * THREADS_PER_TILE; + + if (n < numFacesToClip) + { + uint f = NthBitLow(clipFaceMask, n); + + uint srcBegin, srcSize; + float4 vertRingBuffer[MAX_CLIP_VERTS]; + if (ClipFaceAgainstCube(f, cubeMin, cubeMax, baseVertexOffset, + srcBegin, srcSize, vertRingBuffer)) + { + culledFaceCount++; // Clipped completely + } + else + { + trivialAccept = true; + } + } + } + } + +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (i = 0; i < FastLog2(THREADS_PER_TILE); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + + culledFaceCount += LaneSwizzle(culledFaceCount, andMask, orMask, xorMask); + trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); + } +#else + InterlockedAdd(gs_CulledFaceCounts[tile], culledFaceCount); + InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); + + GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags, gs_CulledFaceCounts + + culledFaceCount = gs_CulledFaceCounts[tile]; + trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; +#endif + + if (trivialAccept || trivialReject) return; + + if (culledFaceCount == NUM_FACES) + { + // If we culled all the faces, there are 2 possibilities: + // 1. The bounding frustum is entirely outside the view frustum. + // -> We can safely reject this entity. + // 2. The bounding frustum is entirely inside the view frustum. + // -> We can safely accept this entity. + // Case 2 can only occur if the center of the bounding frustum is inside the view frustum. + // But, we already trivially accept using this condition inside TryCullBoundingSphere. + // So the only remaining possibility is Case 1. + trivialReject = true; + } +} +bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMinPtNDC, float2 tileAaBbMaxPtNDC, uint tile, uint t /* thread */) { const float4x4 projMat = g_mProjectionArr[eye]; // For the entire view frustum const float4x4 invProjMat = g_mInvProjectionArr[eye]; // For the entire view frustum @@ -304,11 +577,17 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMin // Bounding sphere. const float radius = cullData.radius; - // 1. Attempt to trivially accept/reject the entity by considering its bounding sphere. bool trivialAccept, trivialReject; - TryCullSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat, - trivialAccept, trivialReject); + TryCullBoundingSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat, + trivialAccept, trivialReject); + if (!(trivialAccept || trivialReject)) + { + const float3 cubeMin = float3(tileAaBbMinPtNDC, 0); + const float3 cubeMax = float3(tileAaBbMaxPtNDC, 1); + TryCullBoundingFrustum(rbpC, rbpX, rbpY, rbpZ, scale, radius, tile, t, cubeMin, cubeMax, projMat, + trivialAccept, trivialReject); + } return trivialReject; } @@ -337,6 +616,12 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou const uint clampedTileIndex = min(globalTileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); + // Helper threads may perform the same computation on valid data, + // but do not store the results of the computation to memory. + const bool isHelperThread = globalTileIndex != clampedTileIndex; + + if (isHelperThread) return; // Avoid adding too many checks or branches below + const uint2 tileAaBbMinPtSS = clampedTileCoord * TILE_SIZE; const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide @@ -366,7 +651,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou break; // Reached the terminator } - if (!TryCullEntity(entityIndex, cat, eye, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, t)) + if (!TryCullEntity(entityIndex, cat, eye, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, tile, t)) { // The entity was not culled, so transfer it over. first = min(entityIndex, first); From b64bcd68f69a2a2116f3d19e38783da12dc2e708 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 5 Nov 2020 18:41:30 -0800 Subject: [PATCH 078/209] Optimize --- .../Runtime/Lighting/LightLoop/tile.compute | 49 ++++++++----------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 687e99b9ca4..fda6bb1192b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -102,7 +102,7 @@ #ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS // Booleans are stored in 2x consecutive SGPRs on GCN. // So using LaneSwizzle is probably inefficient in this case... -// TODO: reimplement this using 'ballot'. +// TODO: reimplement this using 'ballot' to save VGPRs and VALUs. bool LaneSwizzle(bool x, uint andMask, uint orMask, uint xorMask) { return (bool)LaneSwizzle((uint)x, uint andMask, uint orMask, uint xorMask) @@ -215,7 +215,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) // 1 array * 16 elements * 4 bytes each = 64 bytes. groupshared uint gs_CullClipFaceMasks[TILES_PER_GROUP]; // 6 faces each (HLSL does not support small data types) // 1 array * 16 elements * 4 bytes each = 64 bytes. -groupshared uint gs_CulledFaceCounts[TILES_PER_GROUP]; // [0, 6] +groupshared uint gs_CulledFaceMasks[TILES_PER_GROUP]; // 6 faces each (HLSL does not support small data types) // 1 array * 16 elements * 4 bytes each = 64 bytes. groupshared uint gs_CullMasksOfAllFaces[TILES_PER_GROUP]; // 6 planes each (HLSL does not support small data types) // 1 array * 16 elements * 4 bytes each = 64 bytes. @@ -324,7 +324,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, if (t == 0) // Avoid bank conflicts { gs_CullClipFaceMasks[tile] = 0; // Initially all faces are assumed to be inside - gs_CulledFaceCounts[tile] = 0; // Initially none + gs_CulledFaceMasks[tile] = 0; // Initially none gs_TrivialAcceptFlags[tile] = (uint)false; // Initially false } #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS @@ -334,6 +334,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // we can trivially accept that face. If all vertices of a face are behind // any single plane, we can trivially reject (cull) that face. uint cullClipFaceMask = 0; // Initially inside + uint culledFaceMask = 0; // Initially none uint i; // Avoid the multiply-declared variable warning @@ -438,8 +439,6 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // (2) Test the corners of the view volume. // Skipped - pointless in this case. - uint culledFaceCount = 0; // Potentially, by different planes - // (3) Cull the faces. { const uint cullFaceMask = cullClipFaceMask; @@ -455,8 +454,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, if (TryCullFace(f, baseVertexOffset)) { - culledFaceCount++; - cullClipFaceMask ^= 1 << f; + culledFaceMask |= 1 << f; } } } @@ -469,20 +467,17 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB - cullClipFaceMask &= LaneSwizzle(cullClipFaceMask, andMask, orMask, xorMask); - culledFaceCount += LaneSwizzle(culledFaceCount, andMask, orMask, xorMask); + culledFaceMask |= LaneSwizzle(culledFaceMask, andMask, orMask, xorMask); } #else - InterlockedAnd(gs_CullClipFaceMasks[tile], cullClipFaceMask); - InterlockedAdd(gs_CulledFaceCounts[tile], culledFaceCount); + InterlockedOr(gs_CulledFaceMasks[tile], culledFaceMask); - GroupMemoryBarrier(); // Wait for writes to gs_CulledFaceCounts, gs_CullClipFaceMasks + GroupMemoryBarrier(); // Wait for writes to gs_CulledFaceMasks - cullClipFaceMask = gs_CullClipFaceMasks[tile]; - culledFaceCount = gs_CulledFaceCounts[tile]; + culledFaceMask = gs_CulledFaceMasks[tile]; #endif - if (culledFaceCount == NUM_FACES) + if (culledFaceMask == FACE_MASK) { // If we culled all the faces, there are 2 possibilities: // 1. The bounding frustum is entirely outside the view frustum. @@ -499,7 +494,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // (4) Clip the faces. { - const uint clipFaceMask = cullClipFaceMask; + const uint clipFaceMask = cullClipFaceMask & ~culledFaceMask; const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] for (i = 0; i < FACES_PER_THREAD; i++) @@ -515,11 +510,11 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, if (ClipFaceAgainstCube(f, cubeMin, cubeMax, baseVertexOffset, srcBegin, srcSize, vertRingBuffer)) { - culledFaceCount++; // Clipped completely + culledFaceMask |= 1 << f; } else { - trivialAccept = true; + // trivialAccept = true; } } } @@ -532,22 +527,20 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB - culledFaceCount += LaneSwizzle(culledFaceCount, andMask, orMask, xorMask); - trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); + culledFaceMask |= LaneSwizzle(culledFaceMask, andMask, orMask, xorMask); + // trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); } #else - InterlockedAdd(gs_CulledFaceCounts[tile], culledFaceCount); - InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); + InterlockedOr(gs_CulledFaceMasks[tile], culledFaceMask); + // InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); - GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags, gs_CulledFaceCounts + GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags, gs_CulledFaceMasks - culledFaceCount = gs_CulledFaceCounts[tile]; - trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; + culledFaceMask = gs_CulledFaceMasks[tile]; + // trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; #endif - if (trivialAccept || trivialReject) return; - - if (culledFaceCount == NUM_FACES) + if (culledFaceMask == FACE_MASK) { // If we culled all the faces, there are 2 possibilities: // 1. The bounding frustum is entirely outside the view frustum. From d98a85a688de86b64f1072db9d2f30a139bd8a3e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 6 Nov 2020 20:08:18 -0800 Subject: [PATCH 079/209] Do not use the shifted clip space of Blinn --- .../Lighting/LightLoop/ClippingUtilities.hlsl | 21 ++- .../Lighting/LightLoop/scrbound.compute | 43 ++--- .../Runtime/Lighting/LightLoop/tile.compute | 152 +++++++++++++----- 3 files changed, 153 insertions(+), 63 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl index eadbd0f3b72..31883eb0875 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl @@ -100,6 +100,17 @@ float3 GenerateVertexOfStandardCube(uint v) return p; } +float3 GenerateVertexOfCustomCube(uint v, float3 cubeMin, float3 cubeMax) +{ + float3 p; + + p.x = ((v & 1) == 0) ? cubeMin.x : cubeMax.x; // FACE_LEFT : FACE_RIGHT + p.y = ((v & 2) == 0) ? cubeMin.y : cubeMax.y; // FACE_BOTTOM : FACE_TOP + p.z = ((v & 4) == 0) ? cubeMin.z : cubeMax.z; // FACE_FRONT : FACE_BACK + + return p; +} + // All vertices are always in the standard order (see below). uint GetFaceMaskOfVertex(uint v) { @@ -283,14 +294,14 @@ void UpdateAaBb(uint srcBegin, uint srcSize, float4 vertRingBuffer[MAX_CLIP_VERT #ifndef OBTUSE_COMPILER uint modSrcIdx = j % MAX_CLIP_VERTS; #endif - float4 hapVert = vertRingBuffer[modSrcIdx]; - // Clamp to the bounds in case of numerical errors (may still generate -0). - float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); - float rbpVertVSz = hapVert.w; + float4 hapVertCS = vertRingBuffer[modSrcIdx]; + float3 rapVertCS = hapVertCS.xyz * rcp(hapVertCS.w); + float3 rapVertNDC = float3(rapVertCS.xy * 0.5 + 0.5, rapVertCS.z); + float rbpVertVSz = hapVertCS.w; if (isOrthoProj) // Must replace (w = 1) { - rbpVertVSz = dot(invProjMat[2], hapVert); + rbpVertVSz = dot(invProjMat[2], hapVertCS); } ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVSz)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 5d2a58d3100..ec5dcf5e432 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -205,6 +205,10 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // Bounding sphere. const float radius = cullData.radius; + // This cube defines the view frustum. + const float3 cubeMinCS = float3(-1, -1, 0); + const float3 cubeMaxCS = float3( 1, 1, 1); + #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS // (0) Initialize the TGSM. if (t == 0) // Avoid bank conflicts @@ -253,7 +257,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // Avoid generating (w = 0). rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; - float4 hapVert = mul(projMat, float4(rbpVertVS, 1)); + float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); // Warning: the W component may be negative. // Flipping the -W pyramid by negating all coordinates is incorrect @@ -261,9 +265,6 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // We are allowed to change the magnitude of the vector, but not its direction! // For the orthographic projection, (w = 1). - // Transform the X and Y components: [-w, w] -> [0, w]. - hapVert.xy = 0.5 * hapVert.xy + (0.5 * hapVert.w); - // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex // is in the positive or the negative half-space. @@ -278,16 +279,16 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) for (uint j = 0; j < (NUM_PLANES / 2); j++) { - float w = hapVert.w; + float w = hapVertCS.w; - behindMask |= (hapVert[j] < 0 ? 1 : 0) << (2 * j + 0); // Planes crossing '0' - behindMask |= (hapVert[j] > w ? 1 : 0) << (2 * j + 1); // Planes crossing 'w' + behindMask |= ((hapVertCS[j] < -w) ? 1 : 0) << (2 * j + 0); // Planes crossing -w + behindMask |= ((hapVertCS[j] > w) ? 1 : 0) << (2 * j + 1); // Planes crossing +w } if (behindMask == 0) // Inside? { - // Clamp to the bounds in case of numerical errors (may still generate -0). - float3 rapVertNDC = saturate(hapVert.xyz * rcp(hapVert.w)); + float3 rapVertCS = hapVertCS.xyz * rcp(hapVertCS.w); + float3 rapVertNDC = float3(rapVertCS.xy * 0.5 + 0.5, rapVertCS.z); ndcAaBbMinPt = min(ndcAaBbMinPt, float4(rapVertNDC, rbpVertVS.z)); ndcAaBbMaxPt = max(ndcAaBbMaxPt, float4(rapVertNDC, rbpVertVS.z)); @@ -298,10 +299,10 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) cullClipFaceMask |= GetFaceMaskOfVertex(v); } - gs_HapVertsX[baseVertexOffset + v] = hapVert.x; - gs_HapVertsY[baseVertexOffset + v] = hapVert.y; - gs_HapVertsZ[baseVertexOffset + v] = hapVert.z; - gs_HapVertsW[baseVertexOffset + v] = hapVert.w; + gs_HapVertsX[baseVertexOffset + v] = hapVertCS.x; + gs_HapVertsY[baseVertexOffset + v] = hapVertCS.y; + gs_HapVertsZ[baseVertexOffset + v] = hapVertCS.z; + gs_HapVertsW[baseVertexOffset + v] = hapVertCS.w; gs_BehindMasksOfVerts[baseVertexOffset + v] = behindMask; } @@ -343,10 +344,10 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { // Compute the parameters of the perspective projection. float s = scale; - float e = -1 - 2 * (s * rcp(1 - s)); // Signed distance from the origin to the eye - float n = -e - 1; // Distance from the eye to the near plane - float f = -e + 1; // Distance from the eye to the far plane - float g = f; // Distance from the eye to the projection plane + float n = 2 * (s * rcp(1 - s)); // Distance from the eye to the near plane + float f = 2 + n; // Distance from the eye to the far plane + float g = f; // Distance from the eye to the projection plane + float e = -1 - n; // Signed distance from the origin to the eye float4x4 invTranslateEye = Translation4x4(float3(0, 0, -e)); float4x4 perspProjMatrix = PerspectiveProjection4x4(1, g, n, f); @@ -358,9 +359,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { uint v = t + i * THREADS_PER_ENTITY; - float3 rapVertCS = GenerateVertexOfStandardCube(v); - rapVertCS.z = rapVertCS.z * 0.5 + 0.5; // View's projection matrix MUST map Z to [0, 1] - + float3 rapVertCS = GenerateVertexOfCustomCube(v, cubeMinCS, cubeMaxCS); float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space float4 hapVertLS = mul(entitySpaceMatrix, hbpVertVS); // View to entity space @@ -385,6 +384,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } // (3) Cull the faces. + if (cullClipFaceMask != 0) { const uint cullFaceMask = cullClipFaceMask; const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] @@ -423,6 +423,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) #endif // (4) Clip the faces. + if (cullClipFaceMask != 0) { const uint clipFaceMask = cullClipFaceMask; const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] @@ -437,7 +438,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) uint srcBegin, srcSize; float4 vertRingBuffer[MAX_CLIP_VERTS]; - ClipFaceAgainstCube(f, 0, 1, baseVertexOffset, + ClipFaceAgainstCube(f, cubeMinCS, cubeMaxCS, baseVertexOffset, srcBegin, srcSize, vertRingBuffer); UpdateAaBb(srcBegin, srcSize, vertRingBuffer, g_isOrthographic != 0, invProjMat, ndcAaBbMinPt, ndcAaBbMaxPt); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index fda6bb1192b..cea57558187 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -224,23 +224,20 @@ groupshared uint gs_TrivialAcceptFlags[TILES_PER_GROUP]; // Just a boolean // We do not clip the sphere against the near and the far plane (same as in 'scrbound.compute'). void TryCullBoundingSphere(float3 C, float r, - float2 aaBbMinPtNDC, float2 aaBbMaxPtNDC, float4x4 projMat, float4x4 invProjMat, + float2 aaBbMinPtCS, float2 aaBbMaxPtCS, float4x4 projMat, float4x4 invProjMat, out bool trivialAccept, out bool trivialReject) { trivialAccept = trivialReject = false; if ((C.z + r) > 0) // Is the sphere at least *partially* in front of the origin? { - // Transform to clip-space coordinates. - float2 aaBbMinPtCS = aaBbMinPtNDC * 2 - 1; - float2 aaBbMaxPtCS = aaBbMaxPtNDC * 2 - 1; - if (g_isOrthographic) { float4x4 orthoProj = OptimizeOrthographicMatrix(projMat); // Project the center of the bounding sphere (ellipse). float3 projC = mul(orthoProj, float4(C.xyz, 1)).xyz; + // Test whether the light's center is inside the view volume. trivialAccept = all(aaBbMinPtCS <= projC.xy && projC.xy <= aaBbMaxPtCS.xy) && (0 <= projC.z <= 1); if (!trivialAccept) @@ -267,6 +264,7 @@ void TryCullBoundingSphere(float3 C, float r, // Project the center of the bounding sphere (ellipse). float3 projC = mul(perspProj, float4(C.xyz, 1)).xyz * rcp(C.z); // Assume M[3] = (0,0,1,0) + // Test whether the light's center is inside the view volume. trivialAccept = all(aaBbMinPtCS <= projC.xy && projC.xy <= aaBbMaxPtCS.xy) && (0 <= projC.z <= 1); if (!trivialAccept && (dot(C, C) - r * r) > 0) @@ -312,7 +310,7 @@ void TryCullBoundingSphere(float3 C, float r, } void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, float scale, float radius, uint tile, uint t /* thread */, - float3 cubeMin, float3 cubeMax, float4x4 projMat, + float3 cubeMinCS, float3 cubeMaxCS, float4x4 projMat, float4x4 invProjMat, out bool trivialAccept, out bool trivialReject) { trivialAccept = trivialReject = false; @@ -334,7 +332,6 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // we can trivially accept that face. If all vertices of a face are behind // any single plane, we can trivially reject (cull) that face. uint cullClipFaceMask = 0; // Initially inside - uint culledFaceMask = 0; // Initially none uint i; // Avoid the multiply-declared variable warning @@ -360,7 +357,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // Avoid generating (w = 0). rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; - float4 hapVert = mul(projMat, float4(rbpVertVS, 1)); + float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); // Warning: the W component may be negative. // Flipping the -W pyramid by negating all coordinates is incorrect @@ -368,9 +365,6 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // We are allowed to change the magnitude of the vector, but not its direction! // For the orthographic projection, (w = 1). - // Transform the X and Y components: [-w, w] -> [0, w]. - hapVert.xy = 0.5 * hapVert.xy + (0.5 * hapVert.w); - // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex // is in the positive or the negative half-space. @@ -381,16 +375,14 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // min_y <= y <= max_y <-- include boundary points to avoid clipping them later // min_z <= z <= max_z // w is always valid - const float3 hapAaBbMinPT = cubeMin * abs(hapVert.w); - const float3 hapAaBbMaxPT = cubeMax * abs(hapVert.w); + const float3 hapAaBbMinPt = cubeMinCS * abs(hapVertCS.w); + const float3 hapAaBbMaxPt = cubeMaxCS * abs(hapVertCS.w); // TODO: add epsilon for numerical robustness? for (uint j = 0; j < (NUM_PLANES / 2); j++) { - float w = hapVert.w; - - behindMask |= (hapVert[j] < hapAaBbMinPT[j] ? 1 : 0) << (2 * j + 0); - behindMask |= (hapVert[j] > hapAaBbMaxPT[j] ? 1 : 0) << (2 * j + 1); + behindMask |= ((hapVertCS[j] < hapAaBbMinPt[j]) ? 1 : 0) << (2 * j + 0); + behindMask |= ((hapVertCS[j] > hapAaBbMaxPt[j]) ? 1 : 0) << (2 * j + 1); } if (behindMask == 0) // Inside? @@ -405,10 +397,10 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, cullClipFaceMask |= GetFaceMaskOfVertex(v); } - gs_HapVertsX[baseVertexOffset + v] = hapVert.x; - gs_HapVertsY[baseVertexOffset + v] = hapVert.y; - gs_HapVertsZ[baseVertexOffset + v] = hapVert.z; - gs_HapVertsW[baseVertexOffset + v] = hapVert.w; + gs_HapVertsX[baseVertexOffset + v] = hapVertCS.x; + gs_HapVertsY[baseVertexOffset + v] = hapVertCS.y; + gs_HapVertsZ[baseVertexOffset + v] = hapVertCS.z; + gs_HapVertsW[baseVertexOffset + v] = hapVertCS.w; gs_BehindMasksOfVerts[baseVertexOffset + v] = behindMask; } @@ -437,9 +429,85 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, if (trivialAccept || trivialReject) return; // (2) Test the corners of the view volume. - // Skipped - pointless in this case. + if (cullClipFaceMask != 0) + { + // The entity is partially outside the view volume. + // Therefore, some of the corners of the view volume may be inside the entity's bounding frustum. + // We perform aggressive culling, so we must make sure they are accounted for. + // We can exploit the properties of the frustum by building an entity-space projection matrix. + // P_v = T * (R * S) * P_l + // P_l = (R * S)^{-1} * T^{-1} * P_v + float4x4 invTranslateToEntitySpace = Translation4x4(-rbpC); + float4x4 invRotateAndScaleInEntitySpace = Homogenize3x3(Invert3x3(ScaledRotation3x3(rbpX, rbpY, rbpZ))); + + // This (orthographic) projection matrix maps a view-space point to a entity-space [-1, 1]^3 cube. + float4x4 entitySpaceMatrix = mul(invRotateAndScaleInEntitySpace, invTranslateToEntitySpace); + + if (scale != 1) // Perspective entity space? + { + // Compute the parameters of the perspective projection. + float s = scale; + float n = 2 * (s * rcp(1 - s)); // Distance from the eye to the near plane + float f = 2 + n; // Distance from the eye to the far plane + float g = f; // Distance from the eye to the projection plane + float e = -1 - n; // Signed distance from the origin to the eye + + float4x4 invTranslateEye = Translation4x4(float3(0, 0, -e)); + float4x4 perspProjMatrix = PerspectiveProjection4x4(1, g, n, f); + + entitySpaceMatrix = mul(mul(perspProjMatrix, invTranslateEye), entitySpaceMatrix); + } + + for (i = 0; i < VERTS_PER_THREAD; i++) + { + uint v = t + i * THREADS_PER_TILE; + + float3 rapVertCS = GenerateVertexOfCustomCube(v, cubeMinCS, cubeMaxCS); + float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space + float4 hapVertLS = mul(entitySpaceMatrix, hbpVertVS); // View to entity space + + // Consider the vertex to be inside the entity's bounding frustum if: + // -w < x < w + // -w < y < w <-- exclude boundary points, as we will not clip using these vertices + // -w < z < w <-- assume that Z-precision is not very important here + // 0 < w + // TODO: add epsilon for numerical robustness? + + bool inside = Max3(abs(hapVertLS.x), abs(hapVertLS.y), abs(hapVertLS.z)) < hapVertLS.w; + + if (inside) + { + float3 rbpVertRVS = hbpVertVS.xyz * rcp(hbpVertVS.w) - rbpC; + // The vertex of the viewing frustum is inside the bounding frustum. + // But is it also inside the bounding sphere? + trivialAccept = trivialAccept || (dot(rbpVertRVS, rbpVertRVS) <= (radius * radius)); + } + } + } + +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS + for (i = 0; i < FastLog2(THREADS_PER_TILE); i++) + { + uint andMask = PLATFORM_LANE_COUNT - 1; // All lanes + uint orMask = 0; // Plays no role + uint xorMask = 1 << i; // Flip bits one by one starting from the LSB + + trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); + } +#else + InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); + + GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags + + trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + + if (trivialAccept || trivialReject) return; // (3) Cull the faces. + uint culledFaceMask = 0; // Initially none + + if (cullClipFaceMask != 0) { const uint cullFaceMask = cullClipFaceMask; const uint numFacesToCull = countbits(cullFaceMask); // [0, 6] @@ -483,18 +551,22 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // 1. The bounding frustum is entirely outside the view frustum. // -> We can safely reject this entity. // 2. The bounding frustum is entirely inside the view frustum. + // 3. The view frustum is entirely inside the bounding frustum. // -> We can safely accept this entity. - // Case 2 can only occur if the center of the bounding frustum is inside the view frustum. - // But, we already trivially accept using this condition inside TryCullBoundingSphere. + // Case 2 has been handled inside TryCullBoundingFrustum. + // Case 3 has been handled in this function, above. // So the only remaining possibility is Case 1. trivialReject = true; } if (trivialAccept || trivialReject) return; + cullClipFaceMask &= ~culledFaceMask; + // (4) Clip the faces. + if (cullClipFaceMask != 0) { - const uint clipFaceMask = cullClipFaceMask & ~culledFaceMask; + const uint clipFaceMask = cullClipFaceMask; const uint numFacesToClip = countbits(clipFaceMask); // [0, 6] for (i = 0; i < FACES_PER_THREAD; i++) @@ -507,13 +579,14 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, uint srcBegin, srcSize; float4 vertRingBuffer[MAX_CLIP_VERTS]; - if (ClipFaceAgainstCube(f, cubeMin, cubeMax, baseVertexOffset, + if (ClipFaceAgainstCube(f, cubeMinCS, cubeMaxCS, baseVertexOffset, srcBegin, srcSize, vertRingBuffer)) { culledFaceMask |= 1 << f; } else { + // Early out no longer serves a purpose, so the code has been commented out. // trivialAccept = true; } } @@ -527,17 +600,17 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, uint orMask = 0; // Plays no role uint xorMask = 1 << i; // Flip bits one by one starting from the LSB - culledFaceMask |= LaneSwizzle(culledFaceMask, andMask, orMask, xorMask); + culledFaceMask |= LaneSwizzle(culledFaceMask, andMask, orMask, xorMask); // trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); } #else - InterlockedOr(gs_CulledFaceMasks[tile], culledFaceMask); + InterlockedOr(gs_CulledFaceMasks[tile], culledFaceMask); // InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags, gs_CulledFaceMasks culledFaceMask = gs_CulledFaceMasks[tile]; - // trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; + // trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; #endif if (culledFaceMask == FACE_MASK) @@ -546,14 +619,16 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // 1. The bounding frustum is entirely outside the view frustum. // -> We can safely reject this entity. // 2. The bounding frustum is entirely inside the view frustum. + // 3. The view frustum is entirely inside the bounding frustum. // -> We can safely accept this entity. - // Case 2 can only occur if the center of the bounding frustum is inside the view frustum. - // But, we already trivially accept using this condition inside TryCullBoundingSphere. + // Case 2 has been handled inside TryCullBoundingFrustum. + // Case 3 has been handled in this function, above. // So the only remaining possibility is Case 1. trivialReject = true; } } -bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMinPtNDC, float2 tileAaBbMaxPtNDC, uint tile, uint t /* thread */) + +bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMinPtCS, float2 tileAaBbMaxPtCS, uint tile, uint t /* thread */) { const float4x4 projMat = g_mProjectionArr[eye]; // For the entire view frustum const float4x4 invProjMat = g_mInvProjectionArr[eye]; // For the entire view frustum @@ -571,14 +646,15 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMin const float radius = cullData.radius; bool trivialAccept, trivialReject; - TryCullBoundingSphere(rbpC, radius, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, projMat, invProjMat, + TryCullBoundingSphere(rbpC, radius, tileAaBbMinPtCS, tileAaBbMaxPtCS, projMat, invProjMat, trivialAccept, trivialReject); if (!(trivialAccept || trivialReject)) { - const float3 cubeMin = float3(tileAaBbMinPtNDC, 0); - const float3 cubeMax = float3(tileAaBbMaxPtNDC, 1); - TryCullBoundingFrustum(rbpC, rbpX, rbpY, rbpZ, scale, radius, tile, t, cubeMin, cubeMax, projMat, + const float3 cubeMinCS = float3(tileAaBbMinPtCS, 0); + const float3 cubeMaxCS = float3(tileAaBbMaxPtCS, 1); + TryCullBoundingFrustum(rbpC, rbpX, rbpY, rbpZ, scale, radius, tile, t, + cubeMinCS, cubeMaxCS, projMat, invProjMat, trivialAccept, trivialReject); } @@ -619,6 +695,8 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float2 tileAaBbMinPtCS = tileAaBbMinPtNDC * 2 - 1; + const float2 tileAaBbMaxPtCS = tileAaBbMaxPtNDC * 2 - 1; const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(clampedTileIndex, cat, eye); uint tileRangeData = _SrcCoarseTileBuffer[tileBufferHeaderIndex]; // {last << 16 | first} @@ -644,7 +722,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou break; // Reached the terminator } - if (!TryCullEntity(entityIndex, cat, eye, tileAaBbMinPtNDC, tileAaBbMaxPtNDC, tile, t)) + if (!TryCullEntity(entityIndex, cat, eye, tileAaBbMinPtCS, tileAaBbMaxPtCS, tile, t)) { // The entity was not culled, so transfer it over. first = min(entityIndex, first); From 11a57a6620ad0d8874e5cc0ff3cbcd4e7e0178a6 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 6 Nov 2020 22:17:36 -0800 Subject: [PATCH 080/209] TMI --- .../Lighting/LightLoop/scrbound.compute | 19 +------------- .../Runtime/Lighting/LightLoop/tile.compute | 26 +++++-------------- 2 files changed, 7 insertions(+), 38 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index ec5dcf5e432..2682030ba61 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -257,26 +257,15 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // Avoid generating (w = 0). rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; + // For the orthographic projection, the resulting (w = 1). float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); - // Warning: the W component may be negative. - // Flipping the -W pyramid by negating all coordinates is incorrect - // and will break both classification and clipping. - // We are allowed to change the magnitude of the vector, but not its direction! - // For the orthographic projection, (w = 1). - // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex // is in the positive or the negative half-space. uint behindMask = 0; // Initially in front - // Consider the vertex to be inside the view volume if: - // 0 <= x <= w - // 0 <= y <= w <-- include boundary points to avoid clipping them later - // 0 <= z <= w - // w is always valid // TODO: add epsilon for numerical robustness? - for (uint j = 0; j < (NUM_PLANES / 2); j++) { float w = hapVertCS.w; @@ -363,13 +352,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space float4 hapVertLS = mul(entitySpaceMatrix, hbpVertVS); // View to entity space - // Consider the vertex to be inside the entity's bounding frustum if: - // -w < x < w - // -w < y < w <-- exclude boundary points, as we will not clip using these vertices - // -w < z < w <-- assume that Z-precision is not very important here - // 0 < w // TODO: add epsilon for numerical robustness? - bool inside = Max3(abs(hapVertLS.x), abs(hapVertLS.y), abs(hapVertLS.z)) < hapVertLS.w; if (inside) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index cea57558187..a001a5967ba 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -359,26 +359,18 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); - // Warning: the W component may be negative. - // Flipping the -W pyramid by negating all coordinates is incorrect - // and will break both classification and clipping. - // We are allowed to change the magnitude of the vector, but not its direction! - // For the orthographic projection, (w = 1). + // For the orthographic projection, the resulting (w = 1). + float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); + + const float3 hapAaBbMinPt = cubeMinCS * abs(hapVertCS.w); + const float3 hapAaBbMaxPt = cubeMaxCS * abs(hapVertCS.w); // For each vertex, we must determine whether it is within the bounds. // For culling and clipping, we must know, per culling plane, whether the vertex // is in the positive or the negative half-space. uint behindMask = 0; // Initially in front - // Consider the vertex to be inside the view volume if: - // min_x <= x <= max_x - // min_y <= y <= max_y <-- include boundary points to avoid clipping them later - // min_z <= z <= max_z - // w is always valid - const float3 hapAaBbMinPt = cubeMinCS * abs(hapVertCS.w); - const float3 hapAaBbMaxPt = cubeMaxCS * abs(hapVertCS.w); // TODO: add epsilon for numerical robustness? - for (uint j = 0; j < (NUM_PLANES / 2); j++) { behindMask |= ((hapVertCS[j] < hapAaBbMinPt[j]) ? 1 : 0) << (2 * j + 0); @@ -466,13 +458,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, float4 hbpVertVS = mul(invProjMat, float4(rapVertCS, 1)); // Clip to view space float4 hapVertLS = mul(entitySpaceMatrix, hbpVertVS); // View to entity space - // Consider the vertex to be inside the entity's bounding frustum if: - // -w < x < w - // -w < y < w <-- exclude boundary points, as we will not clip using these vertices - // -w < z < w <-- assume that Z-precision is not very important here - // 0 < w // TODO: add epsilon for numerical robustness? - bool inside = Max3(abs(hapVertLS.x), abs(hapVertLS.y), abs(hapVertLS.z)) < hapVertLS.w; if (inside) @@ -692,7 +678,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou if (isHelperThread) return; // Avoid adding too many checks or branches below const uint2 tileAaBbMinPtSS = clampedTileCoord * TILE_SIZE; - const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE + const uint2 tileAaBbMaxPtSS = tileAaBbMinPtSS + TILE_SIZE; // (tileCoord + 1) * TILE_SIZE const float2 tileAaBbMinPtNDC = tileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 tileAaBbMaxPtNDC = saturate(tileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 tileAaBbMinPtCS = tileAaBbMinPtNDC * 2 - 1; From b01810e2ff532bbed82804219ade0b2f6fb6a49e Mon Sep 17 00:00:00 2001 From: Evgenii Date: Sat, 7 Nov 2020 10:43:43 -0800 Subject: [PATCH 081/209] Allow the bounding sphere to be disabled --- .../Runtime/Lighting/LightLoop/tile.compute | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a001a5967ba..8b5ddfcc62e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -357,8 +357,6 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, // Avoid generating (w = 0). rbpVertVS.z = (abs(rbpVertVS.z) > FLT_MIN) ? rbpVertVS.z : FLT_MIN; - float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); - // For the orthographic projection, the resulting (w = 1). float4 hapVertCS = mul(projMat, float4(rbpVertVS, 1)); @@ -631,9 +629,13 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMin // Bounding sphere. const float radius = cullData.radius; - bool trivialAccept, trivialReject; - TryCullBoundingSphere(rbpC, radius, tileAaBbMinPtCS, tileAaBbMaxPtCS, projMat, invProjMat, - trivialAccept, trivialReject); + bool trivialAccept = false, trivialReject = false; + + if (radius > 0) + { + TryCullBoundingSphere(rbpC, radius, tileAaBbMinPtCS, tileAaBbMaxPtCS, projMat, invProjMat, + trivialAccept, trivialReject); + } if (!(trivialAccept || trivialReject)) { From 603549a0d787608b4c2666d59e51bfff5ddd77f1 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Sun, 8 Nov 2020 10:22:52 -0800 Subject: [PATCH 082/209] Comment --- .../Runtime/Lighting/LightLoop/tile.compute | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index 8b5ddfcc62e..a09e0d9fd1f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -570,8 +570,7 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, } else { - // Early out no longer serves a purpose, so the code has been commented out. - // trivialAccept = true; + // May not trivially accept here unless it also lies within the bounding sphere. } } } @@ -585,16 +584,13 @@ void TryCullBoundingFrustum(float3 rbpC, float3 rbpX, float3 rbpY, float3 rbpZ, uint xorMask = 1 << i; // Flip bits one by one starting from the LSB culledFaceMask |= LaneSwizzle(culledFaceMask, andMask, orMask, xorMask); - // trivialAccept = trivialAccept || LaneSwizzle(trivialAccept, andMask, orMask, xorMask); } #else InterlockedOr(gs_CulledFaceMasks[tile], culledFaceMask); - // InterlockedOr(gs_TrivialAcceptFlags[tile], (uint)trivialAccept); GroupMemoryBarrier(); // Wait for writes to gs_TrivialAcceptFlags, gs_CulledFaceMasks culledFaceMask = gs_CulledFaceMasks[tile]; - // trivialAccept = (bool)gs_TrivialAcceptFlags[tile]; #endif if (culledFaceMask == FACE_MASK) From f2ba62b110595ad4f23340cf5f0ebf2773debc9d Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 9 Nov 2020 19:36:37 -0800 Subject: [PATCH 083/209] Fine tile binning works --- .../Lighting/LightLoop/Deferred.compute | 2 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 27 ++-- .../LightLoop/TilingAndBinningUtilities.hlsl | 50 +++--- .../Runtime/Lighting/LightLoop/tile.compute | 143 ++++++++++++++++-- 4 files changed, 185 insertions(+), 37 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index 70227618042..e84f5c58a78 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -47,7 +47,7 @@ // deferred opaque always use FPTL #define USE_FPTL_LIGHTLIST 1 -#define COARSE_BINNING // Comment out the line to loop over all lights (for debugging purposes) +#define FINE_BINNING // Comment out the line to loop over all lights (for debugging purposes) //------------------------------------------------------------------------------------- // Include diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index ed1ee09e364..afaefe664ca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -1081,10 +1081,10 @@ static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) static Vector2Int GetFineTileBufferDimensions(HDCamera hdCamera) { - int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); - int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineTileSize); + Vector2Int coarseBufferDims = GetCoarseTileBufferDimensions(hdCamera); - return new Vector2Int(w, h); + // For each coarse tile, we have several fine tiles. + return coarseBufferDims * (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize); } static int GetNumTileBigTileX(HDCamera hdCamera) @@ -3485,6 +3485,7 @@ struct BuildGPULightListParameters public ComputeShader zBinShader; public ComputeShader tileShader; public Vector2Int coarseTileBufferDimensions; + public Vector2Int fineTileBufferDimensions; // Big Tile public ComputeShader bigTilePrepassShader; @@ -3656,6 +3657,12 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG ConstantBuffer.Push(cmd, parameters.lightListCB, shader, HDShaderIDs._ShaderVariablesLightList); + const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP + const int tilesPerGroup = 16; // Shader: TILES_PER_GROUP + + int coarseBufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; + int fineBufferSize = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; + int kernel, groupCount; kernel = 0; // FillCoarseTiles @@ -3664,9 +3671,6 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG // This is not an accident. We alias the fine tile buffer memory. cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.fineTileBuffer); - const int threadsPerGroup = 64; // Shader: THREADS_PER_GROUP - - int coarseBufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; groupCount = HDUtils.DivRoundUp(coarseBufferSize, threadsPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); @@ -3678,15 +3682,19 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._SrcCoarseTileBuffer, resources.fineTileBuffer); cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._DstCoarseTileBuffer, resources.coarseTileBuffer); - const int tilesPerGroup = 16; // Shader: TILES_PER_GROUP - groupCount = HDUtils.DivRoundUp(coarseBufferSize, tilesPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); kernel = 2; // FillFineTiles - // ... + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._EntityBoundsBuffer, resources.convexBoundsBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); + cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._FineTileBuffer, resources.fineTileBuffer); + + groupCount = HDUtils.DivRoundUp(fineBufferSize, tilesPerGroup); + + cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); } } @@ -4013,6 +4021,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.zBinShader = zBinShader; parameters.tileShader = tileShader; parameters.coarseTileBufferDimensions = GetCoarseTileBufferDimensions(hdCamera); + parameters.fineTileBufferDimensions = GetFineTileBufferDimensions(hdCamera); // Big tile prepass parameters.bigTilePrepassShader = buildPerBigTileLightListShader; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 2b0051c74cc..daa5b607e2f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -171,53 +171,69 @@ uint ComputeZBinIndex(float linearDepth) return min((uint)(z * Z_BIN_COUNT), Z_BIN_COUNT - 1); } +#define COARSE_TILE_BUFFER_DIMS uint2(_CoarseTileBufferDimensions.xy) +#define FINE_TILE_BUFFER_DIMS uint2( _FineTileBufferDimensions.xy) + #if defined(COARSE_BINNING) - #define TILE_SIZE COARSE_TILE_SIZE - #define TILE_ENTRY_LIMIT COARSE_TILE_ENTRY_LIMIT #define TILE_BUFFER _CoarseTileBuffer - #define TILE_BUFFER_DIMS uint2(_CoarseTileBufferDimensions.xy) + #define TILE_BUFFER_DIMS COARSE_TILE_BUFFER_DIMS + #define TILE_ENTRY_LIMIT COARSE_TILE_ENTRY_LIMIT + #define TILE_SIZE COARSE_TILE_SIZE #elif defined(FINE_BINNING) - #define TILE_SIZE FINE_TILE_SIZE - #define TILE_ENTRY_LIMIT FINE_TILE_ENTRY_LIMIT #define TILE_BUFFER _FineTileBuffer - #define TILE_BUFFER_DIMS uint2(_FineTileBufferDimensions.xy) + #define TILE_BUFFER_DIMS FINE_TILE_BUFFER_DIMS + #define TILE_ENTRY_LIMIT FINE_TILE_ENTRY_LIMIT + #define TILE_SIZE FINE_TILE_SIZE #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) // These must be defined so the compiler does not complain. - #define TILE_SIZE 1 - #define TILE_ENTRY_LIMIT 0 #define TILE_BUFFER_DIMS uint2(0, 0) + #define TILE_ENTRY_LIMIT 0 + #define TILE_SIZE 1 #endif // Cannot be used to index directly into the buffer. // Use ComputeTileBufferIndex for that purpose. +// tileCoord = pixelCoord / TILE_SIZE. uint ComputeTileIndex(uint2 tileCoord) { return IndexFromCoordinate(uint4(tileCoord, 0, 0), uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); } -// Contains index ranges. -// tile: output of ComputeTileIndex. -uint ComputeTileBufferHeaderIndex(uint tile, uint category, uint eye) +// Internal. Do not use. +uint ComputeTileBufferHeaderIndex(uint tile, uint category, uint eye, uint2 tileBufferDims) { uint eyeCatOffset = IndexFromCoordinate(uint4(0, 0, category, eye), - uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); + uint3(tileBufferDims, BOUNDEDENTITYCATEGORY_COUNT)); return eyeCatOffset + tile; } -// Contains index lists. -uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye) +// Contains index ranges. +// tile: output of ComputeTileIndex. +uint ComputeTileBufferHeaderIndex(uint tile, uint category, uint eye) +{ + return ComputeTileBufferHeaderIndex(tile, category, eye, TILE_BUFFER_DIMS); +} + +// Internal. Do not use. +uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye, uint2 tileBufferDims, uint tileEntryLimit) { // TODO: may want to precompute this. - uint headerOffset = TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y * BOUNDEDENTITYCATEGORY_COUNT * _XRViewCount; + uint headerOffset = tileBufferDims.x * tileBufferDims.y * BOUNDEDENTITYCATEGORY_COUNT * _XRViewCount; uint eyeCatOffset = IndexFromCoordinate(uint4(0, 0, category, eye), - uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); - uint stride = TILE_ENTRY_LIMIT / 2; // 16-bit index list + uint3(tileBufferDims, BOUNDEDENTITYCATEGORY_COUNT)); + uint stride = tileEntryLimit / 2; // 16-bit index list return headerOffset + stride * (eyeCatOffset + tile); } +// Contains index lists. +uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye) +{ + return ComputeTileBufferBodyIndex(tile, category, eye, TILE_BUFFER_DIMS, TILE_ENTRY_LIMIT); +} + #endif // NO_SHADERVARIABLESGLOBAL_HLSL #endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a09e0d9fd1f..a8b5b055519 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -1,14 +1,19 @@ #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch +#define FILL_COARSE_TILES 0 +#define PRUNE_COARSE_TILES 1 +#define FILL_FINE_TILES 2 + // Generates large screen tiles in a fast, conservative manner. #pragma kernel FillCoarseTiles PASS = FILL_COARSE_TILES COARSE_BINNING // Removes certain entities from the coarse buffer at a large cost. #pragma kernel PruneCoarseTiles PASS = PRUNE_COARSE_TILES COARSE_BINNING // Generates small screen tiles in an accurate manner. -#pragma kernel FillFineTiles PASS = FILL_FINE_TILES FINE_BINNING +#pragma kernel FillFineTiles PASS = FILL_FINE_TILES COARSE_BINNING #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceFillingCurves.hlsl" #include "Packages/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" @@ -45,12 +50,19 @@ StructuredBuffer _SrcCoarseTileBuffer : register(t1); // Index range + index list #endif +#if (PASS == FILL_FINE_TILES) + // 1x list for all entites (sorted by category, we concatenate lists of all views). + StructuredBuffer _EntityBoundsBuffer : register(t0); + // 1x list for all entites (sorted by category, we concatenate lists of all views). + StructuredBuffer _CoarseTileBuffer : register(t1); // Index range + index list +#endif + /* ------------------------------ Outputs ----------------------------------- */ #if (PASS == FILL_COARSE_TILES) // The tile buffer is composed of two parts: // the header (containing index ranges, 2 * sizeof(uint16)) and - // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). + // the body (containing index lists, COARSE_TILE_ENTRY_LIMIT * sizeof(uint16)). // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * @@ -64,15 +76,17 @@ RWStructuredBuffer _DstCoarseTileBuffer : register(u0); // Index range + index list #endif -#if (PASS == BUILD_FINE_TILES) +#if (PASS == FILL_FINE_TILES) // The tile buffer is composed of two parts: // the header (containing index ranges, 2 * sizeof(uint16)) and - // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). + // the body (containing index lists, FINE_TILE_ENTRY_LIMIT * sizeof(uint16)). // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: - // DIV_ROUND_UP(RES_X, FINE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_TILE_SIZE) * + // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * + // (COARSE_TILE_SIZE / FINE_TILE_SIZE)^2 * // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + FINE_TILE_ENTRY_LIMIT) * 2 bytes per entry. - // For example (1080p): 240 * 165 * 5 * 1 * (2 + 16) * 2 = 6.8 MiB. + // For example (1080p): 30 * 17 * 8^2 * 5 * 1 * (2 + 16) * 2 = 5.6 MiB. + RWStructuredBuffer _FineTileBuffer : register(u0); // Index range + index list #endif /* ------------------------------ Utilities --------------------------------- */ @@ -113,6 +127,8 @@ bool LaneSwizzle(bool x, uint andMask, uint orMask, uint xorMask) #error "TILE_ENTRY_LIMIT must be an integer multiple of 2." #endif +#if (PASS == FILL_COARSE_TILES) + // 1x thread per tile. [numthreads(THREADS_PER_GROUP, 1, 1)] void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) @@ -207,6 +223,8 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) _CoarseTileBuffer[headerIndex] = outputRange; } +#else // (PASS != FILL_COARSE_TILES) + // Improve naming by using the definitions below. #define THREADS_PER_TILE (THREADS_PER_ENTITY) #define TILES_PER_GROUP (ENTITIES_PER_GROUP) @@ -645,6 +663,8 @@ bool TryCullEntity(uint entityIndex, uint category, uint eye, float2 tileAaBbMin return trivialReject; } +#if (PASS == PRUNE_COARSE_TILES) + // ************************************************************************************************* // At this point, each tile has a list of conservatively selected entities. // The idea it to spend a few more clock cycles to remove entities that do not belong to the tile. @@ -683,8 +703,9 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou const float2 tileAaBbMaxPtCS = tileAaBbMaxPtNDC * 2 - 1; const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(clampedTileIndex, cat, eye); - uint tileRangeData = _SrcCoarseTileBuffer[tileBufferHeaderIndex]; // {last << 16 | first} - const bool isTileEmpty = tileRangeData == UINT16_MAX; + + uint tileRangeData = _SrcCoarseTileBuffer[tileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; if (!isTileEmpty) // Avoid wasted work { @@ -743,8 +764,110 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou _DstCoarseTileBuffer[tileBufferHeaderIndex] = tileRangeData; } -[numthreads(THREADS_PER_GROUP, 1, 1)] -void FillFineTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) +#endif // (PASS == PRUNE_COARSE_TILES) + +#if (PASS == FILL_FINE_TILES) + +[numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] +void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { + const uint t = threadID.x; + const uint tile = threadID.y; + const uint g = groupID.x; + const uint cat = groupID.y; + const uint eye = groupID.z; + + // Caution: tile macros and functions used below correspond to COARSE_BINNING. + const uint coarseToFineSizeRatio = COARSE_TILE_SIZE / FINE_TILE_SIZE; + const uint fineTilesPerCoarseTile = Sq(coarseToFineSizeRatio); + const uint globalCoarseTileIndex = (g * TILES_PER_GROUP) / fineTilesPerCoarseTile; + const uint clampedCoarseTileIndex = min(globalCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x * COARSE_TILE_BUFFER_DIMS.y - 1); // Wave-uniform + const uint2 clampedCoarseTileCoord = CoordinateFromIndex(clampedCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x); + + // Helper threads may perform the same computation on valid data, + // but do not store the results of the computation to memory. + const bool isHelperThread = globalCoarseTileIndex != clampedCoarseTileIndex; + + if (isHelperThread) return; // Avoid adding too many checks or branches below + + // Within the coarse tile, we process fine tiles in the Morton order. + // Of course, both coarse and fine tiles are arranged linearly in memory. + const uint localFineTileIndex = (g * TILES_PER_GROUP) % fineTilesPerCoarseTile + tile; + const uint2 localFineTileCoord = DecodeMorton2D(localFineTileIndex & (fineTilesPerCoarseTile - 1)); // Use AND to inform the compiler + const uint2 globalFineTileCoord = clampedCoarseTileCoord * coarseToFineSizeRatio + localFineTileCoord; + const uint globalFineTileIndex = IndexFromCoordinate(globalFineTileCoord, FINE_TILE_BUFFER_DIMS.x); + + const uint2 fineTileAaBbMinPtSS = globalFineTileCoord * FINE_TILE_SIZE; + const uint2 fineTileAaBbMaxPtSS = fineTileAaBbMinPtSS + FINE_TILE_SIZE; // (tileCoord + 1) * TILE_SIZE + const float2 fineTileAaBbMinPtNDC = saturate(fineTileAaBbMinPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float2 fineTileAaBbMaxPtNDC = saturate(fineTileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float2 fineTileAaBbMinPtCS = fineTileAaBbMinPtNDC * 2 - 1; + const float2 fineTileAaBbMaxPtCS = fineTileAaBbMaxPtNDC * 2 - 1; + + const uint coarseTileBufferHeaderIndex = ComputeTileBufferHeaderIndex(clampedCoarseTileIndex, cat, eye, COARSE_TILE_BUFFER_DIMS); + const uint fineTileBufferHeaderIndex = ComputeTileBufferHeaderIndex( globalFineTileIndex, cat, eye, FINE_TILE_BUFFER_DIMS); + + uint tileRangeData = _CoarseTileBuffer[coarseTileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; + + if (!isTileEmpty) // Avoid wasted work + { + const uint coarseTileBufferBodyIndex = ComputeTileBufferBodyIndex(clampedCoarseTileIndex, cat, eye, COARSE_TILE_BUFFER_DIMS, COARSE_TILE_ENTRY_LIMIT); + const uint fineTileBufferBodyIndex = ComputeTileBufferBodyIndex( globalFineTileIndex, cat, eye, FINE_TILE_BUFFER_DIMS, FINE_TILE_ENTRY_LIMIT); + + // Define inputs (i) and outputs (j). + uint i = 0, j = 0; + uint indexPair = 0; + + uint first = UINT16_MAX, last = 0; + + while ((i < COARSE_TILE_ENTRY_LIMIT) && (j < FINE_TILE_ENTRY_LIMIT)) + { + uint entityPair = _CoarseTileBuffer[coarseTileBufferBodyIndex + (i / 2)]; // 16-bit indices + uint entityIndex = BitFieldExtract(entityPair, 16 * (i & 1), 16); // First Lo, then Hi bits + + if (entityIndex == UINT16_MAX) + { + break; // Reached the terminator + } + + if (!TryCullEntity(entityIndex, cat, eye, fineTileAaBbMinPtCS, fineTileAaBbMaxPtCS, tile, t)) + { + // The entity was not culled, so transfer it over. + first = min(entityIndex, first); + last = max(entityIndex, last); + + // 2x 16-bit indices per uint. + indexPair |= entityIndex << (16 * (j & 1)); // First Lo, then Hi bits + + if ((j & 1) != 0) // Is the pair complete & ready to be stored? + { + _FineTileBuffer[fineTileBufferBodyIndex + (j / 2)] = indexPair; + + indexPair = 0; // In order to use bitwise OR above + } + + j++; + } + + i++; + } + + if (j < FINE_TILE_ENTRY_LIMIT) + { + uint entityIndex = UINT16_MAX; // Add a terminator + + indexPair |= entityIndex << (16 * (j & 1)); // First Lo, then Hi bits + + _FineTileBuffer[fineTileBufferBodyIndex + (j / 2)] = indexPair; + } + tileRangeData = (last << 16) | first; + } + + _FineTileBuffer[fineTileBufferHeaderIndex] = tileRangeData; } + +#endif // (PASS == FILL_FINE_TILES) + +#endif // (PASS != FILL_COARSE_TILES) \ No newline at end of file From a54890efae0aa6628e8f0899b2914c1082b5cbbe Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 9 Nov 2020 19:38:37 -0800 Subject: [PATCH 084/209] Rename profiling marker --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 2 +- .../Runtime/RenderPipeline/HDProfileId.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index afaefe664ca..1e0da35f455 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3651,7 +3651,7 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.FillCoarseTiles))) + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.FillScreenTiles))) { var shader = parameters.tileShader; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 0021a3f5153..883ef3b6894 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -20,7 +20,7 @@ internal enum HDProfileId BuildLightList, GenerateLightAABBs, PerformZBinning, - FillCoarseTiles, + FillScreenTiles, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, From f5cb659c2661f8f8576fadabbaeefab1e5f307aa Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 9 Nov 2020 19:42:35 -0800 Subject: [PATCH 085/209] Remove debug symbols --- .../Runtime/Lighting/LightLoop/scrbound.compute | 2 +- .../Runtime/Lighting/LightLoop/tile.compute | 3 ++- .../Runtime/Lighting/LightLoop/zbin.compute | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 2682030ba61..701f6976e66 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -1,4 +1,4 @@ -#pragma enable_d3d11_debug_symbols +// #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch #pragma kernel main diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a8b5b055519..c35e591a184 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -1,4 +1,4 @@ -#pragma enable_d3d11_debug_symbols +// #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch #define FILL_COARSE_TILES 0 @@ -183,6 +183,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) float2 entityBoundsX = _xyBoundsBuffer[inputStart + i].xy; float2 entityBoundsY = _xyBoundsBuffer[inputStart + i].zw; + [branch] // This hint is required to avoid an internal compiler error. if (IntervalsOverlap(entityBoundsX, tileBoundsX) && IntervalsOverlap(entityBoundsY, tileBoundsY)) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index bf7434ede12..644314190b8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -1,4 +1,4 @@ -#pragma enable_d3d11_debug_symbols +// #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch #pragma kernel main From d7d6f317ff2d453c5420309d489873657cf595b0 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 10 Nov 2020 08:19:39 -0800 Subject: [PATCH 086/209] Assert --- .../Runtime/Lighting/LightLoop/tile.compute | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index c35e591a184..faff3c9defc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -769,6 +769,10 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou #if (PASS == FILL_FINE_TILES) +#if (REMAINDER(COARSE_TILE_SIZE, FINE_TILE_SIZE) != 0) + #error "COARSE_TILE_SIZE must be an integer multiple of FINE_TILE_SIZE." +#endif + [numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { From 176b160aa162877d1fb3fa04d4b4272f7c0c986f Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 10 Nov 2020 18:02:37 -0800 Subject: [PATCH 087/209] Reduce the size of the fine tile buffer --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 11 ++--- .../Runtime/Lighting/LightLoop/tile.compute | 41 +++++++++++-------- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 1e0da35f455..fab7b020796 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -1081,10 +1081,10 @@ static Vector2Int GetCoarseTileBufferDimensions(HDCamera hdCamera) static Vector2Int GetFineTileBufferDimensions(HDCamera hdCamera) { - Vector2Int coarseBufferDims = GetCoarseTileBufferDimensions(hdCamera); + int w = HDUtils.DivRoundUp((int)hdCamera.screenSize.x, TiledLightingConstants.s_FineTileSize); + int h = HDUtils.DivRoundUp((int)hdCamera.screenSize.y, TiledLightingConstants.s_FineTileSize); - // For each coarse tile, we have several fine tiles. - return coarseBufferDims * (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize); + return new Vector2Int(w, h); } static int GetNumTileBigTileX(HDCamera hdCamera) @@ -3661,7 +3661,8 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG const int tilesPerGroup = 16; // Shader: TILES_PER_GROUP int coarseBufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; - int fineBufferSize = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; + int fineTilesPerCoarseTile = (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize) + * (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize); int kernel, groupCount; @@ -3692,7 +3693,7 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._CoarseTileBuffer, resources.coarseTileBuffer); cmd.SetComputeBufferParam(shader, kernel, HDShaderIDs._FineTileBuffer, resources.fineTileBuffer); - groupCount = HDUtils.DivRoundUp(fineBufferSize, tilesPerGroup); + groupCount = HDUtils.DivRoundUp(coarseBufferSize * fineTilesPerCoarseTile, tilesPerGroup); cmd.DispatchCompute(shader, kernel, groupCount, (int)BoundedEntityCategory.Count, parameters.viewCount); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index faff3c9defc..a34053dc7ca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -67,7 +67,7 @@ // The size of the buffer can be computed as follows: // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + COARSE_TILE_ENTRY_LIMIT) * 2 bytes per entry. - // For example (1080p): 30 * 17 * 5 * 1 * (2 + 64) * 2 = 328.7 KiB. + // For example (1080p): 30 * 17 * 5 * 1 * (2 + 64) * 2 = 328.71 KiB. RWStructuredBuffer _CoarseTileBuffer : register(u0); // Index range + index list #endif @@ -82,10 +82,9 @@ // the body (containing index lists, FINE_TILE_ENTRY_LIMIT * sizeof(uint16)). // 1x list for all entites (sorted by category, we concatenate lists of all views). // The size of the buffer can be computed as follows: - // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * - // (COARSE_TILE_SIZE / FINE_TILE_SIZE)^2 * + // DIV_ROUND_UP(RES_X, FINE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_TILE_SIZE) * // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + FINE_TILE_ENTRY_LIMIT) * 2 bytes per entry. - // For example (1080p): 30 * 17 * 8^2 * 5 * 1 * (2 + 16) * 2 = 5.6 MiB. + // For example (1080p): 240 * 135 * 5 * 1 * (2 + 16) * 2 = 5.56 MiB. RWStructuredBuffer _FineTileBuffer : register(u0); // Index range + index list #endif @@ -773,6 +772,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou #error "COARSE_TILE_SIZE must be an integer multiple of FINE_TILE_SIZE." #endif +// TILES_PER_GROUP corresponds to fine tiles. [numthreads(THREADS_PER_TILE, TILES_PER_GROUP, 1)] void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { @@ -785,32 +785,37 @@ void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID // Caution: tile macros and functions used below correspond to COARSE_BINNING. const uint coarseToFineSizeRatio = COARSE_TILE_SIZE / FINE_TILE_SIZE; const uint fineTilesPerCoarseTile = Sq(coarseToFineSizeRatio); - const uint globalCoarseTileIndex = (g * TILES_PER_GROUP) / fineTilesPerCoarseTile; - const uint clampedCoarseTileIndex = min(globalCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x * COARSE_TILE_BUFFER_DIMS.y - 1); // Wave-uniform + const uint globalCoarseTileIndex = (g * TILES_PER_GROUP) / fineTilesPerCoarseTile; // Wave-uniform + const uint clampedCoarseTileIndex = min(globalCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x * COARSE_TILE_BUFFER_DIMS.y - 1); const uint2 clampedCoarseTileCoord = CoordinateFromIndex(clampedCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x); + // Within the coarse tile, we process fine tiles in the Morton order. + // Of course, both coarse and fine tiles are arranged linearly in memory. + const uint localFineTileIndex = (g * TILES_PER_GROUP) % fineTilesPerCoarseTile + tile; + const uint2 localFineTileCoord = DecodeMorton2D(localFineTileIndex & (fineTilesPerCoarseTile - 1)); // Use AND to inform the compiler + const uint2 globalFineTileCoord = clampedCoarseTileCoord * coarseToFineSizeRatio + localFineTileCoord; + const uint clampedFineTileCoord = min(globalFineTileCoord, FINE_TILE_BUFFER_DIMS - 1); + const uint clampedFineTileIndex = IndexFromCoordinate(clampedFineTileCoord, FINE_TILE_BUFFER_DIMS.x); + + // We dispatch 'fineTilesPerCoarseTile' threads per coarse tile. + // However, certain portions of the coarse tile may extend past the edge of the screen (due to the size of the tile). + // This is a little wasteful. TODO: reduce padding to 4x4 blocks rather than 8x8. + // In this case, these "phantom" fine tiles (that do not exist in memory) correspond to helper threads. // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. - const bool isHelperThread = globalCoarseTileIndex != clampedCoarseTileIndex; + const bool isHelperThread = (globalCoarseTileIndex != clampedCoarseTileIndex) || any(globalFineTileCoord != clampedFineTileCoord); if (isHelperThread) return; // Avoid adding too many checks or branches below - // Within the coarse tile, we process fine tiles in the Morton order. - // Of course, both coarse and fine tiles are arranged linearly in memory. - const uint localFineTileIndex = (g * TILES_PER_GROUP) % fineTilesPerCoarseTile + tile; - const uint2 localFineTileCoord = DecodeMorton2D(localFineTileIndex & (fineTilesPerCoarseTile - 1)); // Use AND to inform the compiler - const uint2 globalFineTileCoord = clampedCoarseTileCoord * coarseToFineSizeRatio + localFineTileCoord; - const uint globalFineTileIndex = IndexFromCoordinate(globalFineTileCoord, FINE_TILE_BUFFER_DIMS.x); - - const uint2 fineTileAaBbMinPtSS = globalFineTileCoord * FINE_TILE_SIZE; - const uint2 fineTileAaBbMaxPtSS = fineTileAaBbMinPtSS + FINE_TILE_SIZE; // (tileCoord + 1) * TILE_SIZE + const uint2 fineTileAaBbMinPtSS = clampedFineTileCoord * FINE_TILE_SIZE; + const uint2 fineTileAaBbMaxPtSS = fineTileAaBbMinPtSS + FINE_TILE_SIZE; // (tileCoord + 1) * TILE_SIZE const float2 fineTileAaBbMinPtNDC = saturate(fineTileAaBbMinPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 fineTileAaBbMaxPtNDC = saturate(fineTileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 fineTileAaBbMinPtCS = fineTileAaBbMinPtNDC * 2 - 1; const float2 fineTileAaBbMaxPtCS = fineTileAaBbMaxPtNDC * 2 - 1; const uint coarseTileBufferHeaderIndex = ComputeTileBufferHeaderIndex(clampedCoarseTileIndex, cat, eye, COARSE_TILE_BUFFER_DIMS); - const uint fineTileBufferHeaderIndex = ComputeTileBufferHeaderIndex( globalFineTileIndex, cat, eye, FINE_TILE_BUFFER_DIMS); + const uint fineTileBufferHeaderIndex = ComputeTileBufferHeaderIndex( clampedFineTileIndex, cat, eye, FINE_TILE_BUFFER_DIMS); uint tileRangeData = _CoarseTileBuffer[coarseTileBufferHeaderIndex]; // {last << 16 | first} const bool isTileEmpty = tileRangeData == UINT16_MAX; @@ -818,7 +823,7 @@ void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID if (!isTileEmpty) // Avoid wasted work { const uint coarseTileBufferBodyIndex = ComputeTileBufferBodyIndex(clampedCoarseTileIndex, cat, eye, COARSE_TILE_BUFFER_DIMS, COARSE_TILE_ENTRY_LIMIT); - const uint fineTileBufferBodyIndex = ComputeTileBufferBodyIndex( globalFineTileIndex, cat, eye, FINE_TILE_BUFFER_DIMS, FINE_TILE_ENTRY_LIMIT); + const uint fineTileBufferBodyIndex = ComputeTileBufferBodyIndex( clampedFineTileIndex, cat, eye, FINE_TILE_BUFFER_DIMS, FINE_TILE_ENTRY_LIMIT); // Define inputs (i) and outputs (j). uint i = 0, j = 0; From 4f3191340b4301414a0c053d5b78b9020bfbc699 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 10 Nov 2020 19:33:59 -0800 Subject: [PATCH 088/209] Add 'classification.compute' --- .../LightLoop/ClippingUtilities.hlsl.meta | 10 ++ .../Lighting/LightLoop/Deferred.compute | 3 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 22 ++--- .../LightLoop/TilingAndBinningUtilities.hlsl | 22 +++++ .../Lighting/LightLoop/classification.compute | 98 +++++++++++++++++++ .../LightLoop/classification.compute.meta | 9 ++ .../Lighting/LightLoop/materialflags.compute | 92 ----------------- .../LightLoop/materialflags.compute.meta | 9 -- .../Runtime/Lighting/LightLoop/tile.compute | 4 +- 9 files changed, 154 insertions(+), 115 deletions(-) create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl.meta create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute create mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute.meta delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute delete mode 100644 com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute.meta diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl.meta new file mode 100644 index 00000000000..72b58230efd --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClippingUtilities.hlsl.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 50063c1e82edca84d9d1dbfe85e93b7e +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index e84f5c58a78..324e4ac1d69 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -47,7 +47,8 @@ // deferred opaque always use FPTL #define USE_FPTL_LIGHTLIST 1 -#define FINE_BINNING // Comment out the line to loop over all lights (for debugging purposes) +// Comment out the line to loop over all lights (for debugging purposes) +#define FINE_BINNING // Keep in sync with 'classification.compute' //------------------------------------------------------------------------------------- // Include diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index fab7b020796..6c55f108d6c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -927,7 +927,7 @@ static Matrix4x4 GetWorldToViewMatrix(HDCamera hdCamera, int viewIndex) ComputeShader buildPerBigTileLightListShader { get { return defaultResources.shaders.buildPerBigTileLightListCS; } } ComputeShader buildPerVoxelLightListShader { get { return defaultResources.shaders.buildPerVoxelLightListCS; } } ComputeShader clearClusterAtomicIndexShader { get { return defaultResources.shaders.lightListClusterClearAtomicIndexCS; } } - ComputeShader buildMaterialFlagsShader { get { return defaultResources.shaders.buildMaterialFlagsCS; } } + ComputeShader classificationShader { get { return defaultResources.shaders.classificationCS; } } ComputeShader buildDispatchIndirectShader { get { return defaultResources.shaders.buildDispatchIndirectCS; } } ComputeShader clearDispatchIndirectShader { get { return defaultResources.shaders.clearDispatchIndirectCS; } } ComputeShader deferredComputeShader { get { return defaultResources.shaders.deferredCS; } } @@ -3509,7 +3509,7 @@ struct BuildGPULightListParameters public bool clusterNeedsDepth; // Build dispatch indirect - public ComputeShader buildMaterialFlagsShader; + public ComputeShader classificationShader; public ComputeShader clearDispatchIndirectShader; public ComputeShader buildDispatchIndirectShader; public bool useComputeAsPixel; @@ -3810,11 +3810,11 @@ static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parame if (needModifyingTileFeatures) { int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; - parameters.buildMaterialFlagsShader.shaderKeywords = null; + parameters.classificationShader.shaderKeywords = null; if (tileFlagsWritten && parameters_computeLightVariants) { - parameters.buildMaterialFlagsShader.EnableKeyword("USE_OR"); + parameters.classificationShader.EnableKeyword("USE_OR"); } uint baseFeatureFlags = 0; @@ -3848,23 +3848,23 @@ static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parame var localLightListCB = parameters.lightListCB; localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - cmd.SetComputeBufferParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + cmd.SetComputeBufferParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); for (int i = 0; i < resources.gBuffer.Length; ++i) - cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); + cmd.SetComputeTextureParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); if (resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. { - cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); + cmd.SetComputeTextureParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); } else { - cmd.SetComputeTextureParam(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); + cmd.SetComputeTextureParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); } - ConstantBuffer.Push(cmd, localLightListCB, parameters.buildMaterialFlagsShader, HDShaderIDs._ShaderVariablesLightList); + ConstantBuffer.Push(cmd, localLightListCB, parameters.classificationShader, HDShaderIDs._ShaderVariablesLightList); - cmd.DispatchCompute(parameters.buildMaterialFlagsShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); + cmd.DispatchCompute(parameters.classificationShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); } // clear dispatch indirect buffer @@ -4067,7 +4067,7 @@ unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera parameters.clusterNeedsDepth = tileAndClusterData.clusterNeedsDepth; // Build dispatch indirect - parameters.buildMaterialFlagsShader = buildMaterialFlagsShader; + parameters.classificationShader = classificationShader; parameters.clearDispatchIndirectShader = clearDispatchIndirectShader; parameters.buildDispatchIndirectShader = buildDispatchIndirectShader; parameters.buildDispatchIndirectShader.shaderKeywords = null; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index daa5b607e2f..dae16ddc4e3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -234,6 +234,28 @@ uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye) return ComputeTileBufferBodyIndex(tile, category, eye, TILE_BUFFER_DIMS, TILE_ENTRY_LIMIT); } +bool IsBinEmpty(uint tile, uint zBin, uint category, uint eye) +{ + bool b = true; + + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, category, eye); + const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; + + if (!isTileEmpty) // Avoid wasted work + { + const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, category, eye); + const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + + const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); + const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); + + b = !IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange); + } + + return b; +} + #endif // NO_SHADERVARIABLESGLOBAL_HLSL #endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute new file mode 100644 index 00000000000..0340824eec5 --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -0,0 +1,98 @@ +// #pragma enable_d3d11_debug_symbols +#pragma only_renderers d3d11 playstation xboxone vulkan metal switch + +#pragma kernel main + +#pragma multi_compile_local _ LIGHT_CLASSIFICATION +#pragma multi_compile_local _ MATERIAL_CLASSIFICATION + +#define FINE_BINNING // Keep in sync with 'deferred.compute' + +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" +#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceFillingCurves.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" + +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderBase.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" + +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs.hlsl" + +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" + +RWStructuredBuffer g_TileFeatureFlags; + +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS + groupshared uint gs_TileFeatureFlags; +#endif + +TEXTURE2D_X_UINT2(_StencilTexture); + +[numthreads(TILE_SIZE * TILE_SIZE, 1, 1)] +void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) +{ + const uint t = threadID.x; + const uint tile = groupID.x; + const uint eye = groupID.z; + + const uint2 tileCoord = CoordinateFromIndex(tile, TILE_BUFFER_DIMS.x); + const uint2 localPixelCoord = DecodeMorton2D(t & (TILE_SIZE * TILE_SIZE - 1)); // Use AND to inform the compiler + const uint2 globalPixelCoord = tileCoord * TILE_SIZE + localPixelCoord; + const uint2 clampedPixelCoord = min(globalPixelCoord, uint2(_ScreenSize.xy) - 1); + +#ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS + if (t == 0) // Avoid bank conflicts + { + gs_TileFeatureFlags = 0; + } +#endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS + + uint featureFlags = g_BaseFeatureFlags; // Contain all lightFeatures or 0 (depends if we enable light classification or not) + +#ifdef LIGHT_CLASSIFICATION + float depth = LoadCameraDepth(clampedPixelCoord); + PositionInputs posInput = GetPositionInput(clampedPixelCoord, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + + if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, eye)) + { + featureFlags |= LIGHTFEATUREFLAGS_PUNCTUAL; + } + + if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_AREA_LIGHT, eye)) + { + featureFlags |= LIGHTFEATUREFLAGS_AREA; + } + + if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_REFLECTION_PROBE, eye)) + { + featureFlags |= LIGHTFEATUREFLAGS_ENV; + } +#endif // LIGHT_CLASSIFICATION + +#ifdef MATERIAL_CLASSIFICATION + // Unlit object, sky/background and forward opaque tag don't tag the StencilUsage.RequiresDeferredLighting bit + uint stencilVal = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, clampedPixelCoord)); + if ((stencilVal & STENCILUSAGE_REQUIRES_DEFERRED_LIGHTING) != 0) + { + featureFlags |= MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(clampedPixelCoord); + } +#endif // MATERIAL_CLASSIFICATION + +#if (defined(PLATFORM_SUPPORTS_WAVE_INTRINSICS) && (PLATFORM_LANE_COUNT >= (TILE_SIZE * TILE_SIZE))) + featureFlags = WaveActiveBitOr(featureFlags); +#else + InterlockedOr(gs_TileFeatureFlags, featureFlags); + + GroupMemoryBarrierWithGroupSync(); // Wait for writes to gs_TileFeatureFlags + + featureFlags = gs_TileFeatureFlags; +#endif + + if (t == 0) // Avoid bank conflicts + { + uint bufferIndex = tile + IndexFromCoordinate(uint2(0, 0, eye), TILE_BUFFER_DIMS); + g_TileFeatureFlags[bufferIndex] = featureFlags; + } +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute.meta new file mode 100644 index 00000000000..467cc737ccc --- /dev/null +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2f62649560ae64f4da8e8234a88ba2e2 +ComputeShaderImporter: + externalObjects: {} + currentAPIMask: 2097156 + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute deleted file mode 100644 index 433eda440ad..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute +++ /dev/null @@ -1,92 +0,0 @@ -#pragma kernel MaterialFlagsGen - -#pragma multi_compile _ USE_OR - -// #pragma enable_d3d11_debug_symbols - -#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderBase.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" - -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs.hlsl" - -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" - -#pragma only_renderers d3d11 playstation xboxone vulkan metal switch - -#define USE_MATERIAL_FEATURE_FLAGS - -#ifdef PLATFORM_LANE_COUNT // We can infer the size of a wave. This is currently not possible on non-consoles, so we have to fallback to a sensible default in those cases. -#define NR_THREADS PLATFORM_LANE_COUNT -#else -#define NR_THREADS 64 // default to 64 threads per group on other platforms.. -#endif - -// TODO: MUST DO LIGHT CLASSIFICATION HERE -// LIGHT CLASSIFICATION NEEDS MIN-MAX Z OF THE TILE TO USE Z-BINNING WHICH WILL COMPENSATE FOR THE LOSS OF FPTL - -groupshared uint ldsFeatureFlags; -RWStructuredBuffer g_TileFeatureFlags; - -TEXTURE2D_X_UINT2(_StencilTexture); - -[numthreads(NR_THREADS, 1, 1)] -void MaterialFlagsGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) -{ - UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - - uint2 tileIDX = u3GroupID.xy; - - uint iWidth = g_viDimensions.x; - uint iHeight = g_viDimensions.y; - uint nrTilesX = (iWidth + (TILE_SIZE_FPTL - 1)) / TILE_SIZE_FPTL; - uint nrTilesY = (iHeight + (TILE_SIZE_FPTL - 1)) / TILE_SIZE_FPTL; - - // 16 * 4 = 64. We process data by group of 4 pixel - uint2 viTilLL = 16 * tileIDX; - - float2 invScreenSize = float2(1.0 / iWidth, 1.0 / iHeight); - - if (threadID == 0) - { - ldsFeatureFlags = 0; - } - GroupMemoryBarrierWithGroupSync(); - - uint materialFeatureFlags = g_BaseFeatureFlags; // Contain all lightFeatures or 0 (depends if we enable light classification or not) - UNITY_UNROLL - for (int i = 0; i < 4; i++) - { - int idx = i * NR_THREADS + threadID; - uint2 uCrd = min(uint2(viTilLL.x + (idx & 0xf), viTilLL.y + (idx >> 4)), uint2(iWidth - 1, iHeight - 1)); - - // Unlit object, sky/background and forward opaque tag don't tag the StencilUsage.RequiresDeferredLighting bit - uint stencilVal = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, uCrd)); - if ((stencilVal & STENCILUSAGE_REQUIRES_DEFERRED_LIGHTING) > 0) - { - PositionInputs posInput = GetPositionInput(uCrd, invScreenSize); - materialFeatureFlags |= MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(posInput.positionSS); - } - } - - InterlockedOr(ldsFeatureFlags, materialFeatureFlags); //TODO: driver might optimize this or we might have to do a manual reduction - GroupMemoryBarrierWithGroupSync(); - - if (threadID == 0) - { - uint tileIndex = tileIDX.y * nrTilesX + tileIDX.x; - - // TODO: shouldn't this always enabled? -#if defined(UNITY_STEREO_INSTANCING_ENABLED) - tileIndex += unity_StereoEyeIndex * nrTilesX * nrTilesY; -#endif - -#ifdef USE_OR - g_TileFeatureFlags[tileIndex] |= ldsFeatureFlags; -#else // Use in case we have disabled light classification - g_TileFeatureFlags[tileIndex] = ldsFeatureFlags; -#endif - } -} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute.meta b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute.meta deleted file mode 100644 index 0a12debd800..00000000000 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: fb3eda953cd6e634e877fb777be2cd08 -timeCreated: 1496923318 -licenseType: Pro -ComputeShaderImporter: - currentAPIMask: 4 - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index a34053dc7ca..b882fdf40c9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -794,7 +794,7 @@ void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID const uint localFineTileIndex = (g * TILES_PER_GROUP) % fineTilesPerCoarseTile + tile; const uint2 localFineTileCoord = DecodeMorton2D(localFineTileIndex & (fineTilesPerCoarseTile - 1)); // Use AND to inform the compiler const uint2 globalFineTileCoord = clampedCoarseTileCoord * coarseToFineSizeRatio + localFineTileCoord; - const uint clampedFineTileCoord = min(globalFineTileCoord, FINE_TILE_BUFFER_DIMS - 1); + const uint2 clampedFineTileCoord = min(globalFineTileCoord, FINE_TILE_BUFFER_DIMS - 1); const uint clampedFineTileIndex = IndexFromCoordinate(clampedFineTileCoord, FINE_TILE_BUFFER_DIMS.x); // We dispatch 'fineTilesPerCoarseTile' threads per coarse tile. @@ -809,7 +809,7 @@ void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID const uint2 fineTileAaBbMinPtSS = clampedFineTileCoord * FINE_TILE_SIZE; const uint2 fineTileAaBbMaxPtSS = fineTileAaBbMinPtSS + FINE_TILE_SIZE; // (tileCoord + 1) * TILE_SIZE - const float2 fineTileAaBbMinPtNDC = saturate(fineTileAaBbMinPtSS * _ScreenSize.zw); // Divide and clamp to the edge + const float2 fineTileAaBbMinPtNDC = fineTileAaBbMinPtSS * _ScreenSize.zw; // Divide const float2 fineTileAaBbMaxPtNDC = saturate(fineTileAaBbMaxPtSS * _ScreenSize.zw); // Divide and clamp to the edge const float2 fineTileAaBbMinPtCS = fineTileAaBbMinPtNDC * 2 - 1; const float2 fineTileAaBbMaxPtCS = fineTileAaBbMaxPtNDC * 2 - 1; From ee3720cb5611b3e880c45ad3ca87e04db29943e8 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 11 Nov 2020 10:19:21 -0800 Subject: [PATCH 089/209] Optimize --- .../Lighting/LightLoop/classification.compute | 52 ++++++++++--------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index 0340824eec5..aa9ef910cb0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -48,37 +48,41 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) } #endif // PLATFORM_SUPPORTS_WAVE_INTRINSICS - uint featureFlags = g_BaseFeatureFlags; // Contain all lightFeatures or 0 (depends if we enable light classification or not) + uint featureFlags = 0; -#ifdef LIGHT_CLASSIFICATION - float depth = LoadCameraDepth(clampedPixelCoord); - PositionInputs posInput = GetPositionInput(clampedPixelCoord, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); - uint zBin = ComputeZBinIndex(posInput.linearDepth); - - if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, eye)) - { - featureFlags |= LIGHTFEATUREFLAGS_PUNCTUAL; - } - - if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_AREA_LIGHT, eye)) - { - featureFlags |= LIGHTFEATUREFLAGS_AREA; - } - - if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_REFLECTION_PROBE, eye)) - { - featureFlags |= LIGHTFEATUREFLAGS_ENV; - } -#endif // LIGHT_CLASSIFICATION - -#ifdef MATERIAL_CLASSIFICATION // Unlit object, sky/background and forward opaque tag don't tag the StencilUsage.RequiresDeferredLighting bit uint stencilVal = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, clampedPixelCoord)); + if ((stencilVal & STENCILUSAGE_REQUIRES_DEFERRED_LIGHTING) != 0) { + featureFlags = g_BaseFeatureFlags; // Contain all lightFeatures or 0 (depends if we enable light classification or not) + + #ifdef LIGHT_CLASSIFICATION + // TODO: optimize using LinearEyeDepth(float2 positionNDC, float deviceDepth, float4 invProjParam). + float depth = LoadCameraDepth(clampedPixelCoord); + PositionInputs posInput = GetPositionInput(clampedPixelCoord, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + + if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, eye)) + { + featureFlags |= LIGHTFEATUREFLAGS_PUNCTUAL; + } + + if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_AREA_LIGHT, eye)) + { + featureFlags |= LIGHTFEATUREFLAGS_AREA; + } + + if (!IsBinEmpty(tile, zBin, BOUNDEDENTITYCATEGORY_REFLECTION_PROBE, eye)) + { + featureFlags |= LIGHTFEATUREFLAGS_ENV; + } + #endif // LIGHT_CLASSIFICATION + + #ifdef MATERIAL_CLASSIFICATION featureFlags |= MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(clampedPixelCoord); + #endif // MATERIAL_CLASSIFICATION } -#endif // MATERIAL_CLASSIFICATION #if (defined(PLATFORM_SUPPORTS_WAVE_INTRINSICS) && (PLATFORM_LANE_COUNT >= (TILE_SIZE * TILE_SIZE))) featureFlags = WaveActiveBitOr(featureFlags); From 9653936c0e4babd23a37b18052a1542e0bfe9b6b Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 12 Nov 2020 17:29:39 -0800 Subject: [PATCH 090/209] Fix classification scripts --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 148 ++++++++---------- .../LightLoop/TilingAndBinningUtilities.hlsl | 22 --- .../Lighting/LightLoop/classification.compute | 36 ++++- .../Runtime/RenderPipeline/HDProfileId.cs | 1 + 4 files changed, 99 insertions(+), 108 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 6c55f108d6c..98fc81114fe 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -973,7 +973,6 @@ enum ClusterDepthSource : int static int s_ClearDispatchIndirectKernel; static int s_BuildIndirectKernel; static int s_ClearDrawProceduralIndirectKernel; - static int s_BuildMaterialFlagsWriteKernel; static int s_BuildMaterialFlagsOrKernel; static int s_shadeOpaqueDirectFptlKernel; @@ -1196,8 +1195,6 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) s_ClearDrawProceduralIndirectKernel = clearDispatchIndirectShader.FindKernel("ClearDrawProceduralIndirect"); - s_BuildMaterialFlagsWriteKernel = buildMaterialFlagsShader.FindKernel("MaterialFlagsGen"); - s_shadeOpaqueDirectFptlKernel = deferredComputeShader.FindKernel("Deferred_Direct_Fptl"); s_shadeOpaqueDirectFptlDebugDisplayKernel = deferredComputeShader.FindKernel("Deferred_Direct_Fptl_DebugDisplay"); @@ -3648,7 +3645,7 @@ static void PerformZBinning(in BuildGPULightListParameters parameters, in BuildG } } - static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + static void FillScreenTiles(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { // If (boundedEntityCount == 0), we still perform a dispatch that will initialize bins as empty. using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.FillScreenTiles))) @@ -3799,97 +3796,82 @@ static void FillCoarseTiles(in BuildGPULightListParameters parameters, in BuildG // } // } - static void BuildDispatchIndirectArguments(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, bool tileFlagsWritten, CommandBuffer cmd) + static void PerformClassification(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) { - var parameters_computeLightVariants = false; // REMOVE + if (!parameters.enableFeatureVariants) return; - if (parameters.enableFeatureVariants) + Debug.Assert(parameters.computeLightVariants || parameters.computeMaterialVariants); + + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.PerformClassification))) { - // We need to touch up the tile flags if we need material classification or, if disabled, to patch up for missing flags during the skipped light tile gen - bool needModifyingTileFeatures = !tileFlagsWritten || parameters.computeMaterialVariants; - if (needModifyingTileFeatures) - { - int buildMaterialFlagsKernel = s_BuildMaterialFlagsWriteKernel; - parameters.classificationShader.shaderKeywords = null; + uint baseFeatureFlags = 0; - if (tileFlagsWritten && parameters_computeLightVariants) - { - parameters.classificationShader.EnableKeyword("USE_OR"); - } + if (parameters.computeLightVariants) + { + parameters.classificationShader.EnableKeyword("LIGHT_CLASSIFICATION"); + } - uint baseFeatureFlags = 0; - if (!parameters_computeLightVariants) - { - baseFeatureFlags |= TiledLightingConstants.s_LightFeatureMaskFlags; - } - if (parameters.probeVolumeEnabled) - { - // TODO: Verify that we should be globally enabling ProbeVolume feature for all tiles here, or if we should be using per-tile culling. - baseFeatureFlags |= (uint)LightFeatureFlags.ProbeVolume; - } + if (parameters.computeMaterialVariants) + { + parameters.classificationShader.EnableKeyword("MATERIAL_CLASSIFICATION"); + } + else + { + baseFeatureFlags |= TiledLightingConstants.s_MaterialFeatureMaskFlags; + } - // If we haven't run the light list building, we are missing some basic lighting flags. - if (!tileFlagsWritten) - { - if (parameters.hasDirectionalLights) - { - baseFeatureFlags |= (uint)LightFeatureFlags.Directional; - } - if (parameters.skyEnabled) - { - baseFeatureFlags |= (uint)LightFeatureFlags.Sky; - } - if (!parameters.computeMaterialVariants) - { - baseFeatureFlags |= TiledLightingConstants.s_MaterialFeatureMaskFlags; - } - } + if (parameters.hasDirectionalLights) + { + baseFeatureFlags |= (uint)LightFeatureFlags.Directional; + } + if (parameters.skyEnabled) + { + baseFeatureFlags |= (uint)LightFeatureFlags.Sky; + } - var localLightListCB = parameters.lightListCB; - localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; + var localLightListCB = parameters.lightListCB; + localLightListCB.g_BaseFeatureFlags = baseFeatureFlags; - cmd.SetComputeBufferParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + ConstantBuffer.Push(cmd, localLightListCB, parameters.classificationShader, HDShaderIDs._ShaderVariablesLightList); - for (int i = 0; i < resources.gBuffer.Length; ++i) - cmd.SetComputeTextureParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture[i], resources.gBuffer[i]); + // Note that all material feature flag bellow are in the same GBuffer (inGBuffer2) and thus material classification only sample one Gbuffer + cmd.SetComputeTextureParam(parameters.classificationShader, 0, HDShaderIDs._GBufferTexture[2], resources.gBuffer[2]); + cmd.SetComputeBufferParam( parameters.classificationShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - if (resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. - { - cmd.SetComputeTextureParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture); - } - else - { - cmd.SetComputeTextureParam(parameters.classificationShader, buildMaterialFlagsKernel, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); - } + // Assume that we use fine (and not coarse) tiles in the shader. + int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; - ConstantBuffer.Push(cmd, localLightListCB, parameters.classificationShader, HDShaderIDs._ShaderVariablesLightList); + cmd.DispatchCompute(parameters.classificationShader, 0, numTiles, 1, parameters.viewCount); + } + } - cmd.DispatchCompute(parameters.classificationShader, buildMaterialFlagsKernel, parameters.numTilesFPTLX, parameters.numTilesFPTLY, parameters.viewCount); - } + static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in BuildGPULightListResources resources, CommandBuffer cmd) + { + if (!parameters.enableFeatureVariants) return; - // clear dispatch indirect buffer - if (parameters.useComputeAsPixel) - { - cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); - cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); + // clear dispatch indirect buffer + if (parameters.useComputeAsPixel) + { + cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); + cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); + cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); - } - else - { - cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); - } + } + else + { + cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); + } - // add tiles to indirect buffer - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); - // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel - cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); + // add tiles to indirect buffer + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); + cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); + // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel + cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); } } @@ -4173,14 +4155,14 @@ void BuildGPULightListsCommon(HDCamera hdCamera, CommandBuffer cmd) // Both Z-binning and tile filling can be executed concurrently. // This should improve GPU utilization. PerformZBinning(parameters, resources, cmd); - FillCoarseTiles(parameters, resources, cmd); + FillScreenTiles(parameters, resources, cmd); // BigTilePrepass(parameters, resources, cmd); // BuildPerTileLightList(parameters, resources, ref tileFlagsWritten, cmd); // VoxelLightListGeneration(parameters, resources, cmd); - bool tileFlagsWritten = false; // ??? - BuildDispatchIndirectArguments(parameters, resources, tileFlagsWritten, cmd); + PerformClassification(parameters, resources, cmd); + BuildDispatchIndirect(parameters, resources, cmd); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index dae16ddc4e3..daa5b607e2f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -234,28 +234,6 @@ uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye) return ComputeTileBufferBodyIndex(tile, category, eye, TILE_BUFFER_DIMS, TILE_ENTRY_LIMIT); } -bool IsBinEmpty(uint tile, uint zBin, uint category, uint eye) -{ - bool b = true; - - const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, category, eye); - const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} - const bool isTileEmpty = tileRangeData == UINT16_MAX; - - if (!isTileEmpty) // Avoid wasted work - { - const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, category, eye); - const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} - - const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); - const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); - - b = !IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange); - } - - return b; -} - #endif // NO_SHADERVARIABLESGLOBAL_HLSL #endif // UNITY_TILINGANDBINNINGUTILITIES_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index aa9ef910cb0..077d9f4ff0c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -21,14 +21,44 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" +/* ------------------------------ Inputs ------------------------------------ */ + +TEXTURE2D_X_UINT2(_StencilTexture); + +/* ------------------------------ Outputs ----------------------------------- */ + RWStructuredBuffer g_TileFeatureFlags; +/* ------------------------------ Utilities --------------------------------- */ + +bool IsBinEmpty(uint tile, uint zBin, uint category, uint eye) +{ + bool b = true; + + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, category, eye); + const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; + + if (!isTileEmpty) // Avoid wasted work + { + const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, category, eye); + const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + + const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); + const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); + + b = !IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange); + } + + return b; +} + +/* ------------------------------ Implementation ---------------------------- */ + #ifndef PLATFORM_SUPPORTS_WAVE_INTRINSICS groupshared uint gs_TileFeatureFlags; #endif -TEXTURE2D_X_UINT2(_StencilTexture); - [numthreads(TILE_SIZE * TILE_SIZE, 1, 1)] void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { @@ -96,7 +126,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) if (t == 0) // Avoid bank conflicts { - uint bufferIndex = tile + IndexFromCoordinate(uint2(0, 0, eye), TILE_BUFFER_DIMS); + uint bufferIndex = tile + IndexFromCoordinate(uint3(0, 0, eye), TILE_BUFFER_DIMS); g_TileFeatureFlags[bufferIndex] = featureFlags; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 883ef3b6894..37f1f615ea7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -21,6 +21,7 @@ internal enum HDProfileId GenerateLightAABBs, PerformZBinning, FillScreenTiles, + PerformClassification, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, From f259602b5ae14db04693710d0c03223ad2a85774 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 12 Nov 2020 17:37:48 -0800 Subject: [PATCH 091/209] Remove all the 'register' crap --- .../Runtime/Lighting/LightLoop/Deferred.compute | 2 +- .../Lighting/LightLoop/classification.compute | 2 +- .../Runtime/Lighting/LightLoop/scrbound.compute | 2 +- .../Runtime/Lighting/LightLoop/tile.compute | 16 ++++++++-------- .../Runtime/Lighting/LightLoop/zbin.compute | 4 ++-- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index 324e4ac1d69..c7e53f834f2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -48,7 +48,7 @@ #define USE_FPTL_LIGHTLIST 1 // Comment out the line to loop over all lights (for debugging purposes) -#define FINE_BINNING // Keep in sync with 'classification.compute' +#define FINE_BINNING // Keep in sync with 'classification.compute' and 'builddispatchindirect.compute' //------------------------------------------------------------------------------------- // Include diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index 077d9f4ff0c..77969c20fa6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -6,7 +6,7 @@ #pragma multi_compile_local _ LIGHT_CLASSIFICATION #pragma multi_compile_local _ MATERIAL_CLASSIFICATION -#define FINE_BINNING // Keep in sync with 'deferred.compute' +#define FINE_BINNING // Keep in sync with 'deferred.compute' and 'builddispatchindirect.compute' #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceFillingCurves.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index 701f6976e66..b9d9ae1ee20 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -16,7 +16,7 @@ /* ------------------------------ Inputs ------------------------------------ */ // 1x list for all entites (sorted by category, we concatenate lists of all views). -StructuredBuffer _EntityBoundsBuffer : register(t0); +StructuredBuffer _EntityBoundsBuffer; /* ------------------------------ Outputs ----------------------------------- */ diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index b882fdf40c9..e99c5f92adf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -40,21 +40,21 @@ #if (PASS == FILL_COARSE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). - StructuredBuffer _xyBoundsBuffer : register(t0); // {x_min, x_max, y_min, y_max} + StructuredBuffer _xyBoundsBuffer; // {x_min, x_max, y_min, y_max} #endif #if (PASS == PRUNE_COARSE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). - StructuredBuffer _EntityBoundsBuffer : register(t0); + StructuredBuffer _EntityBoundsBuffer; // 1x list for all entites (sorted by category, we concatenate lists of all views). - StructuredBuffer _SrcCoarseTileBuffer : register(t1); // Index range + index list + StructuredBuffer _SrcCoarseTileBuffer; // Index range + index list #endif #if (PASS == FILL_FINE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). - StructuredBuffer _EntityBoundsBuffer : register(t0); + StructuredBuffer _EntityBoundsBuffer; // 1x list for all entites (sorted by category, we concatenate lists of all views). - StructuredBuffer _CoarseTileBuffer : register(t1); // Index range + index list + StructuredBuffer _CoarseTileBuffer; // Index range + index list #endif /* ------------------------------ Outputs ----------------------------------- */ @@ -68,12 +68,12 @@ // DIV_ROUND_UP(RES_X, COARSE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, COARSE_TILE_SIZE) * // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + COARSE_TILE_ENTRY_LIMIT) * 2 bytes per entry. // For example (1080p): 30 * 17 * 5 * 1 * (2 + 64) * 2 = 328.71 KiB. - RWStructuredBuffer _CoarseTileBuffer : register(u0); // Index range + index list + RWStructuredBuffer _CoarseTileBuffer; // Index range + index list #endif #if (PASS == PRUNE_COARSE_TILES) // 1x list for all entites (sorted by category, we concatenate lists of all views). - RWStructuredBuffer _DstCoarseTileBuffer : register(u0); // Index range + index list + RWStructuredBuffer _DstCoarseTileBuffer; // Index range + index list #endif #if (PASS == FILL_FINE_TILES) @@ -85,7 +85,7 @@ // DIV_ROUND_UP(RES_X, FINE_TILE_SIZE) * DIV_ROUND_UP(RES_Y, FINE_TILE_SIZE) * // BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (2 + FINE_TILE_ENTRY_LIMIT) * 2 bytes per entry. // For example (1080p): 240 * 135 * 5 * 1 * (2 + 16) * 2 = 5.56 MiB. - RWStructuredBuffer _FineTileBuffer : register(u0); // Index range + index list + RWStructuredBuffer _FineTileBuffer; // Index range + index list #endif /* ------------------------------ Utilities --------------------------------- */ diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute index 644314190b8..e87c98cd0c5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/zbin.compute @@ -12,7 +12,7 @@ /* ------------------------------ Inputs ------------------------------------ */ // 1x list for all entites (sorted by category, we concatenate lists of all views). -StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} +StructuredBuffer _wBoundsBuffer; // {w_min, w_max} /* ------------------------------ Outputs ----------------------------------- */ @@ -20,7 +20,7 @@ StructuredBuffer _wBoundsBuffer : register(t0); // {w_min, w_max} // The size of the buffer can be computed as follows: // Z_BIN_COUNT * BOUNDEDENTITYCATEGORY_COUNT * EYE_COUNT * (4 bytes per range). // For example (1080p): 8192 * 5 * 1 * 4 = 160 KiB. -RWStructuredBuffer _zBinBuffer : register(u0); // {last << 16 | first} +RWStructuredBuffer _zBinBuffer; // {last << 16 | first} /* ------------------------------ Utilities --------------------------------- */ From 20021ee09b0c2045c6a2710c1d26c795eede4692 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 12 Nov 2020 19:10:17 -0800 Subject: [PATCH 092/209] Build Dispatch Indirect is done (still need to fix Deferred.compute) --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 44 ++++++---- .../LightLoop/builddispatchindirect.compute | 82 +++++++++++-------- .../Lighting/LightLoop/classification.compute | 4 +- .../RenderPipeline/RenderPipelineResources.cs | 4 +- 4 files changed, 79 insertions(+), 55 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 98fc81114fe..008162a6ff1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -746,13 +746,13 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, // note that nrTiles include the viewCount in allocation below lightList = new ComputeBuffer((int)BoundedEntityCategory.Count * dwordsPerTile * nrTiles, sizeof(uint)); // enough list memory for a 4k x 4k display // WTF ??? - tileList = new ComputeBuffer((int)TiledLightingConstants.s_NumFeatureVariants * nrTiles, sizeof(uint)); - tileFeatureFlags = new ComputeBuffer(nrTiles, sizeof(uint)); + //tileList = new ComputeBuffer((int)TiledLightingConstants.s_NumFeatureVariants * nrTiles, sizeof(uint)); + //tileFeatureFlags = new ComputeBuffer(nrTiles, sizeof(uint)); - // DispatchIndirect: Buffer with arguments has to have three integer numbers at given argsOffset offset: number of work groups in X dimension, number of work groups in Y dimension, number of work groups in Z dimension. - // DrawProceduralIndirect: Buffer with arguments has to have four integer numbers at given argsOffset offset: vertex count per instance, instance count, start vertex location, and start instance location - // Use use max size of 4 unit for allocation - dispatchIndirectBuffer = new ComputeBuffer(viewCount * TiledLightingConstants.s_NumFeatureVariants * 4, sizeof(uint), ComputeBufferType.IndirectArguments); + //// DispatchIndirect: Buffer with arguments has to have three integer numbers at given argsOffset offset: number of work groups in X dimension, number of work groups in Y dimension, number of work groups in Z dimension. + //// DrawProceduralIndirect: Buffer with arguments has to have four integer numbers at given argsOffset offset: vertex count per instance, instance count, start vertex location, and start instance location + //// Use use max size of 4 unit for allocation + //dispatchIndirectBuffer = new ComputeBuffer(viewCount * TiledLightingConstants.s_NumFeatureVariants * 4, sizeof(uint), ComputeBufferType.IndirectArguments); } // Cluster @@ -799,6 +799,18 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, * (2 + TiledLightingConstants.s_FineTileEntryLimit) / 2; fineTileBuffer = new ComputeBuffer(fineTileBufferElementCount, sizeof(uint)); // Index range + index list + + // Assume the deferred lighting CS uses fine tiles. + int numTiles = fineTileBufferDimensions.x * fineTileBufferDimensions.y; + + tileFeatureFlags = new ComputeBuffer(numTiles * viewCount, sizeof(uint)); + + // DispatchIndirect: Buffer with arguments has to have three integer numbers at given argsOffset offset: number of work groups in X dimension, number of work groups in Y dimension, number of work groups in Z dimension. + // DrawProceduralIndirect: Buffer with arguments has to have four integer numbers at given argsOffset offset: vertex count per instance, instance count, start vertex location, and start instance location + // Use use max size of 4 unit for allocation + dispatchIndirectBuffer = new ComputeBuffer(TiledLightingConstants.s_NumFeatureVariants * viewCount, 4 * sizeof(uint), ComputeBufferType.IndirectArguments); + + tileList = new ComputeBuffer(numTiles * viewCount * TiledLightingConstants.s_NumFeatureVariants, sizeof(uint)); } // Make sure to invalidate the content of the buffers @@ -971,7 +983,6 @@ enum ClusterDepthSource : int static int[,] s_ClusterObliqueKernels = new int[(int)ClusterPrepassSource.Count, (int)ClusterDepthSource.Count]; static int s_ClearVoxelAtomicKernel; static int s_ClearDispatchIndirectKernel; - static int s_BuildIndirectKernel; static int s_ClearDrawProceduralIndirectKernel; static int s_BuildMaterialFlagsOrKernel; @@ -1190,7 +1201,6 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) s_GenListPerBigTileKernel = buildPerBigTileLightListShader.FindKernel("BigTileLightListGen"); - s_BuildIndirectKernel = buildDispatchIndirectShader.FindKernel("BuildIndirect"); s_ClearDispatchIndirectKernel = clearDispatchIndirectShader.FindKernel("ClearDispatchIndirect"); s_ClearDrawProceduralIndirectKernel = clearDispatchIndirectShader.FindKernel("ClearDrawProceduralIndirect"); @@ -3853,7 +3863,6 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in if (parameters.useComputeAsPixel) { cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); @@ -3865,14 +3874,15 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in } // add tiles to indirect buffer - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileList, resources.tileList); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTiles, parameters.numTilesFPTL); - cmd.SetComputeIntParam(parameters.buildDispatchIndirectShader, HDShaderIDs.g_NumTilesX, parameters.numTilesFPTLX); - // Round on k_ThreadGroupOptimalSize so we have optimal thread for buildDispatchIndirectShader kernel - cmd.DispatchCompute(parameters.buildDispatchIndirectShader, s_BuildIndirectKernel, (parameters.numTilesFPTL + k_ThreadGroupOptimalSize - 1) / k_ThreadGroupOptimalSize, 1, parameters.viewCount); - } + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileList, resources.tileList); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + + // Assume that we use fine (and not coarse) tiles in the shader. + int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; + int groupCount = HDUtils.DivRoundUp(numTiles, k_ThreadGroupOptimalSize); + + cmd.DispatchCompute(parameters.buildDispatchIndirectShader, 0, groupCount, 1, parameters.viewCount); } static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute index 0afe7a4306c..528e1fac28d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute @@ -1,66 +1,80 @@ -#pragma kernel BuildIndirect +// #pragma enable_d3d11_debug_symbols +#pragma only_renderers d3d11 playstation xboxone vulkan metal switch #pragma multi_compile _ IS_DRAWPROCEDURALINDIRECT -#pragma only_renderers d3d11 playstation xboxone vulkan metal switch +#pragma kernel main + +#define FINE_BINNING // Keep in sync with 'deferred.compute' and 'classification.compute' #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" -#ifdef PLATFORM_LANE_COUNT // We can infer the size of a wave. This is currently not possible on non-consoles, so we have to fallback to a sensible default in those cases. +/* ------------------------------ Inputs ------------------------------------ */ + +StructuredBuffer g_TileFeatureFlags; + +/* ------------------------------ Outputs ----------------------------------- */ + +RWBuffer g_DispatchIndirectBuffer; // Indirect arguments have to be in a _buffer_, not a structured buffer +RWStructuredBuffer g_TileList; + +/* ------------------------------ Utilities --------------------------------- */ + + +/* ------------------------------ Implementation ---------------------------- */ + +#ifdef PLATFORM_LANE_COUNT #define NR_THREADS PLATFORM_LANE_COUNT #else #define NR_THREADS 64 // default to 64 threads per group on other platforms.. #endif -RWBuffer g_DispatchIndirectBuffer : register( u0 ); // Indirect arguments have to be in a _buffer_, not a structured buffer -RWStructuredBuffer g_TileList; -StructuredBuffer g_TileFeatureFlags; - -uniform uint g_NumTiles; -uniform uint g_NumTilesX; - [numthreads(NR_THREADS, 1, 1)] -void BuildIndirect(uint3 dispatchThreadId : SV_DispatchThreadID) +void main(uint3 threadID : SV_DispatchThreadID, uint3 groupID : SV_GroupID) { - if (dispatchThreadId.x >= g_NumTiles) - return; + const uint tile = threadID.x; + const uint eye = groupID.z; + + const uint clampedTile = min(tile, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); - UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); + // Helper threads may perform the same computation on valid data, + // but do not store the results of the computation to memory. + const bool isHelperThread = tile != clampedTile; - uint featureFlags = g_TileFeatureFlags[dispatchThreadId.x + unity_StereoEyeIndex * g_NumTiles]; + if (isHelperThread) return; // Avoid adding too many checks or branches below - uint tileY = (dispatchThreadId.x + 0.5f) / (float)g_NumTilesX; // Integer division is extremely expensive, so we better avoid it - uint tileX = dispatchThreadId.x - tileY * g_NumTilesX; + uint bufferIndex = clampedTile + IndexFromCoordinate(uint3(0, 0, eye), TILE_BUFFER_DIMS); + uint featureFlags = g_TileFeatureFlags[bufferIndex]; // Check if there is no material (means it is a sky/background pixel). - // Note that we can have no lights, yet we still need to render geometry with precomputed illumination. + // Note that a tile may have no lights, and yet we still need to render geometry with precomputed illumination. if ((featureFlags & MATERIAL_FEATURE_MASK_FLAGS) != 0) { uint variant = FeatureFlagsToTileVariant(featureFlags); - uint tileOffset; -#ifdef IS_DRAWPROCEDURALINDIRECT - // We are filling up an indirect argument buffer for DrawProceduralIndirect. - // The buffer contains {vertex count per instance, instance count, start vertex location, and start instance location} = {0, instance count, 0, 0, 0} + uint tileOffset; // This includes the eye index for XR + + // TODO: optimize this using TGSM or wave intrinsics! + // We really shouldn't spam the atomic counter located in the global memory... + #ifdef IS_DRAWPROCEDURALINDIRECT + // We are filling up an indirect argument (uint4) buffer for DrawProceduralIndirect. + // The buffer contains {vertex count per instance, instance count, start vertex location, and start instance location}. InterlockedAdd(g_DispatchIndirectBuffer[variant * 4 + 1], 1, tileOffset); -#else - uint prevGroupCnt; + #else + // We are filling up an indirect argument (uint3) buffer for DispatchIndirect. + // The buffer contains {groupCntX, groupCntY, groupCntZ} = {groupCnt, 1, 1}. + InterlockedAdd(g_DispatchIndirectBuffer[variant * 3 + 0], 1, tileOffset); + #endif - // We are filling up an indirect argument buffer for DispatchIndirect. - // The buffer contains {groupCntX, groupCntY, groupCntZ} = {groupCnt, 0, 0}. - InterlockedAdd(g_DispatchIndirectBuffer[variant * 3 + 0], 4, prevGroupCnt); - tileOffset = prevGroupCnt / 4; // 4x 8x8 groups per a 16x16 tile -#endif + uint listIndex = tileOffset + IndexFromCoordinate(uint4(0, 0, 0, variant), uint3(TILE_BUFFER_DIMS, _XRViewCount)); - // See LightDefinitions class in LightLoop.cs - uint tileIndex = (unity_StereoEyeIndex << TILE_INDEX_SHIFT_EYE) | (tileY << TILE_INDEX_SHIFT_Y) | (tileX << TILE_INDEX_SHIFT_X); - // For g_TileList each VR eye is interlaced instead of one eye and then the other. Thus why we use _XRViewCount here - g_TileList[variant * g_NumTiles * _XRViewCount + tileOffset] = tileIndex; + g_TileList[listIndex] = (eye << TILE_INDEX_SHIFT_EYE) | clampedTile; // Must retain the eye index } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index 77969c20fa6..03203928ac5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -1,11 +1,11 @@ // #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -#pragma kernel main - #pragma multi_compile_local _ LIGHT_CLASSIFICATION #pragma multi_compile_local _ MATERIAL_CLASSIFICATION +#pragma kernel main + #define FINE_BINNING // Keep in sync with 'deferred.compute' and 'builddispatchindirect.compute' #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs index 1f78da31739..8892a86dae0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPipelineResources.cs @@ -71,8 +71,8 @@ public sealed class ShaderResources public ComputeShader buildPerVoxelLightListCS; // clustered [Reload("Runtime/Lighting/LightLoop/lightlistbuild-clearatomic.compute")] public ComputeShader lightListClusterClearAtomicIndexCS; - [Reload("Runtime/Lighting/LightLoop/materialflags.compute")] - public ComputeShader buildMaterialFlagsCS; + [Reload("Runtime/Lighting/LightLoop/classification.compute")] + public ComputeShader classificationCS; [Reload("Runtime/Lighting/LightLoop/Deferred.compute")] public ComputeShader deferredCS; [Reload("Runtime/Lighting/Shadow/ContactShadows.compute")] From 6cf6bd32cb3d1297e67470dcf1c2d209e11f0bfc Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 13 Nov 2020 09:25:43 -0800 Subject: [PATCH 093/209] TODO --- .../Runtime/Lighting/LightLoop/scrbound.compute | 1 + 1 file changed, 1 insertion(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute index b9d9ae1ee20..c58498e09ef 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute @@ -516,6 +516,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) if (!isHelperThread && (t == 0)) // Avoid bank conflicts { + // TODO: double-check to make sure that off-screen entities get assigned invalid AABBs. _xyBoundsBuffer[bufferIndex] = float4(ndcAaBbMinPt.x, ndcAaBbMaxPt.x, ndcAaBbMinPt.y, ndcAaBbMaxPt.y); _wBoundsBuffer[bufferIndex] = float2(ndcAaBbMinPt.w, ndcAaBbMaxPt.w); } From d7afe6708be940f66e0e412f966ed0df9fea40b3 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 13 Nov 2020 14:08:04 -0800 Subject: [PATCH 094/209] Bind the stencil texture for the classification pass --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 008162a6ff1..108beaef19e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3848,6 +3848,15 @@ static void PerformClassification(in BuildGPULightListParameters parameters, in cmd.SetComputeTextureParam(parameters.classificationShader, 0, HDShaderIDs._GBufferTexture[2], resources.gBuffer[2]); cmd.SetComputeBufferParam( parameters.classificationShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + if (resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. + { + cmd.SetComputeTextureParam(parameters.classificationShader, 0, HDShaderIDs._StencilTexture, resources.stencilTexture); + } + else + { + cmd.SetComputeTextureParam(parameters.classificationShader, 0, HDShaderIDs._StencilTexture, resources.stencilTexture, 0, RenderTextureSubElement.Stencil); + } + // Assume that we use fine (and not coarse) tiles in the shader. int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; @@ -4525,8 +4534,6 @@ void RenderContactShadows(HDCamera hdCamera, CommandBuffer cmd) struct DeferredLightingParameters { - public int numTilesX; - public int numTilesY; public int numTiles; public bool enableTile; public bool outputSplitLighting; @@ -4551,11 +4558,10 @@ DeferredLightingParameters PrepareDeferredLightingParameters(HDCamera hdCamera, bool debugDisplayOrSceneLightOff = CoreUtils.IsSceneLightingDisabled(hdCamera.camera) || debugDisplaySettings.IsDebugDisplayEnabled(); - int w = hdCamera.actualWidth; - int h = hdCamera.actualHeight; - parameters.numTilesX = (w + 15) / 16; - parameters.numTilesY = (h + 15) / 16; - parameters.numTiles = parameters.numTilesX * parameters.numTilesY; + // Assume the deferred lighting CS uses fine tiles. + Vector2Int fineTileBufferDimensions = GetFineTileBufferDimensions(hdCamera); + parameters.numTiles = fineTileBufferDimensions.x * fineTileBufferDimensions.y; + parameters.enableTile = hdCamera.frameSettings.IsEnabled(FrameSettingsField.DeferredTile); parameters.outputSplitLighting = hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering); parameters.useComputeLightingEvaluation = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation); @@ -4676,18 +4682,16 @@ static void RenderComputeDeferredLighting(in DeferredLightingParameters paramete cmd.SetComputeTextureParam(parameters.deferredComputeShader, kernel, HDShaderIDs._StencilTexture, resources.depthStencilBuffer, 0, RenderTextureSubElement.Stencil); - // always do deferred lighting in blocks of 16x16 (not same as tiled light size) if (parameters.enableFeatureVariants) { cmd.SetComputeBufferParam(parameters.deferredComputeShader, kernel, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlagsBuffer); cmd.SetComputeIntParam(parameters.deferredComputeShader, HDShaderIDs.g_TileListOffset, variant * parameters.numTiles * parameters.viewCount); cmd.SetComputeBufferParam(parameters.deferredComputeShader, kernel, HDShaderIDs.g_TileList, resources.tileListBuffer); - cmd.DispatchCompute(parameters.deferredComputeShader, kernel, resources.dispatchIndirectBuffer, (uint)variant * 3 * sizeof(uint)); + cmd.DispatchCompute(parameters.deferredComputeShader, kernel, resources.dispatchIndirectBuffer, (uint)(variant * 3 * sizeof(uint))); } else { - // 4x 8x8 groups per a 16x16 tile. - cmd.DispatchCompute(parameters.deferredComputeShader, kernel, parameters.numTilesX * 2, parameters.numTilesY * 2, parameters.viewCount); + cmd.DispatchCompute(parameters.deferredComputeShader, kernel, parameters.numTiles, 1, parameters.viewCount); break; // There's only one variant. Don't render the same thing 30 times! } } @@ -4708,7 +4712,7 @@ static void RenderComputeAsPixelDeferredLighting(in DeferredLightingParameters p for (int variant = 0; variant < parameters.numVariants; variant++) { - cmd.SetGlobalInt(HDShaderIDs.g_TileListOffset, variant * parameters.numTiles); + cmd.SetGlobalInt(HDShaderIDs.g_TileListOffset, variant * parameters.numTiles * parameters.viewCount); cmd.EnableShaderKeyword(s_variantNames[variant]); From 9c468605fb10422867004a935fec878e08d05a2a Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 13 Nov 2020 14:12:45 -0800 Subject: [PATCH 095/209] Classification + dispatch indirect + compute deferred lighting works --- .../Runtime/Debug/DebugViewTiles.shader | 2 +- .../Lighting/LightLoop/Deferred.compute | 52 +++++++------------ .../Lighting/LightLoop/DeferredTile.shader | 4 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 1 + .../LightLoop/builddispatchindirect.compute | 6 +-- .../Lighting/LightLoop/classification.compute | 2 +- .../Runtime/Lighting/LightLoop/tile.compute | 6 +-- .../Runtime/Material/Lit/Lit.hlsl | 7 ++- 8 files changed, 34 insertions(+), 46 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewTiles.shader b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewTiles.shader index 455e67dd8e1..75b6c041d1f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewTiles.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugViewTiles.shader @@ -201,7 +201,7 @@ Shader "Hidden/HDRP/DebugViewTiles" float depth = GetTileDepth(pixelCoord); - PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, pixelCoord / GetTileSize()); + PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); int2 tileCoord = (float2)pixelCoord / GetTileSize(); int2 mouseTileCoord = _MousePixelCoord.xy / GetTileSize(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index c7e53f834f2..a35ce91425c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -99,51 +99,35 @@ TEXTURE2D_X_UINT2(_StencilTexture); RW_TEXTURE2D_X(float3, diffuseLightingUAV); RW_TEXTURE2D_X(float4, specularLightingUAV); -#define GROUP_SIZE (8) - #ifdef USE_INDIRECT - StructuredBuffer g_TileList; +#endif -[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] -void SHADE_OPAQUE_ENTRY(uint2 groupThreadId : SV_GroupThreadID, uint groupId : SV_GroupID) +[numthreads(TILE_SIZE, TILE_SIZE, 1)] +void SHADE_OPAQUE_ENTRY(uint3 groupThreadId : SV_GroupThreadID, uint3 groupId : SV_GroupID) { - uint tileIndex = g_TileList[g_TileListOffset + (groupId / 4)]; - uint2 tileCoord = uint2((tileIndex >> TILE_INDEX_SHIFT_X) & TILE_INDEX_MASK, (tileIndex >> TILE_INDEX_SHIFT_Y) & TILE_INDEX_MASK); // see builddispatchindirect.compute - uint2 pixelCoord = tileCoord * GetTileSize() - + uint2(groupId & 1, (groupId >> 1) & 1) * GROUP_SIZE - + groupThreadId; - - UNITY_XR_ASSIGN_VIEW_INDEX(tileIndex >> TILE_INDEX_SHIFT_EYE); - - uint screenWidth = (uint)_ScreenSize.x; - uint numTilesX = (screenWidth + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL; - uint tileVariantIndex = tileCoord.x + tileCoord.y * numTilesX; - - uint tile = 0; - -#if defined(UNITY_STEREO_INSTANCING_ENABLED) - uint screenHeight = (uint)_ScreenSize.y; - uint numTilesY = (screenHeight + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL; - tileVariantIndex += unity_StereoEyeIndex * numTilesX * numTilesY; -#endif +#ifdef USE_INDIRECT + uint variantOffset = g_TileListOffset; + uint tileOffset = groupId.x; // Includes the eye index for XR + uint tileAndEye = g_TileList[variantOffset + tileOffset]; + uint eye = tileAndEye >> TILE_INDEX_SHIFT_EYE; + uint tile = tileAndEye ^ (eye << TILE_INDEX_SHIFT_EYE); - uint featureFlags = TileVariantToFeatureFlags(VARIANT, tileVariantIndex); + UNITY_XR_ASSIGN_VIEW_INDEX(eye); // Sets 'unity_StereoEyeIndex' + uint featureFlags = TileVariantToFeatureFlags(VARIANT, tile, unity_StereoEyeIndex); #else // !USE_INDIRECT + uint tile = groupId.x; + uint eye = groupId.z; -[numthreads(GROUP_SIZE, GROUP_SIZE, 1)] -void SHADE_OPAQUE_ENTRY(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupId : SV_GroupID) -{ - UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - - uint2 tileCoord = (GROUP_SIZE * groupId) / TILE_SIZE; - uint tile = ComputeTileIndex(tileCoord); - uint2 pixelCoord = dispatchThreadId.xy; - uint featureFlags = UINT_MAX; + UNITY_XR_ASSIGN_VIEW_INDEX(eye); + uint featureFlags = UINT_MAX; #endif + uint2 tileCoord = CoordinateFromIndex(tile, TILE_BUFFER_DIMS.x); // TODO: avoid integer division + uint2 pixelCoord = tileCoord * TILE_SIZE + groupThreadId.xy; // TODO: Morton order? + // This need to stay in sync with deferred.shader float depth = LoadCameraDepth(pixelCoord.xy); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader index 59bb287b177..888dd32e4db 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader @@ -230,10 +230,10 @@ Shader "Hidden/HDRP/DeferredTile" uint tileIndex = input.tileIndexAndCoord.x; uint2 tileCoord = input.tileIndexAndCoord.yz; - uint featureFlags = TileVariantToFeatureFlags(VARIANT, tileIndex); + uint featureFlags = TileVariantToFeatureFlags(VARIANT, tileIndex, unity_StereoEyeIndex); float depth = LoadCameraDepth(input.positionCS.xy).x; - PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V, tileCoord); + PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 108beaef19e..dd5e7c0c56b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3819,6 +3819,7 @@ static void PerformClassification(in BuildGPULightListParameters parameters, in if (parameters.computeLightVariants) { parameters.classificationShader.EnableKeyword("LIGHT_CLASSIFICATION"); + cmd.SetComputeBufferParam(parameters.classificationShader, 0, HDShaderIDs._FineTileBuffer, resources.fineTileBuffer); } if (parameters.computeMaterialVariants) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute index 528e1fac28d..aca0e2b4694 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute @@ -59,7 +59,7 @@ void main(uint3 threadID : SV_DispatchThreadID, uint3 groupID : SV_GroupID) { uint variant = FeatureFlagsToTileVariant(featureFlags); - uint tileOffset; // This includes the eye index for XR + uint tileOffset; // Includes the eye index for XR // TODO: optimize this using TGSM or wave intrinsics! // We really shouldn't spam the atomic counter located in the global memory... @@ -73,8 +73,8 @@ void main(uint3 threadID : SV_DispatchThreadID, uint3 groupID : SV_GroupID) InterlockedAdd(g_DispatchIndirectBuffer[variant * 3 + 0], 1, tileOffset); #endif - uint listIndex = tileOffset + IndexFromCoordinate(uint4(0, 0, 0, variant), uint3(TILE_BUFFER_DIMS, _XRViewCount)); + uint variantOffset = IndexFromCoordinate(uint4(0, 0, 0, variant), uint3(TILE_BUFFER_DIMS, _XRViewCount)); // g_TileListOffset - g_TileList[listIndex] = (eye << TILE_INDEX_SHIFT_EYE) | clampedTile; // Must retain the eye index + g_TileList[variantOffset + tileOffset] = (eye << TILE_INDEX_SHIFT_EYE) | clampedTile; // Must retain the eye index } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index 03203928ac5..f6ce78706a6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -66,7 +66,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) const uint tile = groupID.x; const uint eye = groupID.z; - const uint2 tileCoord = CoordinateFromIndex(tile, TILE_BUFFER_DIMS.x); + const uint2 tileCoord = CoordinateFromIndex(tile, TILE_BUFFER_DIMS.x); // TODO: avoid integer division const uint2 localPixelCoord = DecodeMorton2D(t & (TILE_SIZE * TILE_SIZE - 1)); // Use AND to inform the compiler const uint2 globalPixelCoord = tileCoord * TILE_SIZE + localPixelCoord; const uint2 clampedPixelCoord = min(globalPixelCoord, uint2(_ScreenSize.xy) - 1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute index e99c5f92adf..6cc6a68af9d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/tile.compute @@ -142,7 +142,7 @@ void FillCoarseTiles(uint threadID : SV_GroupIndex, uint3 groupID : SV_GroupID) const uint globalTileIndex = IndexFromCoordinate(uint2(t, g), THREADS_PER_GROUP); const uint clampedTileIndex = min(globalTileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); - const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); // TODO: avoid integer division // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -687,7 +687,7 @@ void PruneCoarseTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_Grou const uint globalTileIndex = IndexFromCoordinate(uint2(tile, g), TILES_PER_GROUP); const uint clampedTileIndex = min(globalTileIndex, TILE_BUFFER_DIMS.x * TILE_BUFFER_DIMS.y - 1); - const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); + const uint2 clampedTileCoord = CoordinateFromIndex(clampedTileIndex, TILE_BUFFER_DIMS.x); // TODO: avoid integer division // Helper threads may perform the same computation on valid data, // but do not store the results of the computation to memory. @@ -787,7 +787,7 @@ void FillFineTiles(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID const uint fineTilesPerCoarseTile = Sq(coarseToFineSizeRatio); const uint globalCoarseTileIndex = (g * TILES_PER_GROUP) / fineTilesPerCoarseTile; // Wave-uniform const uint clampedCoarseTileIndex = min(globalCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x * COARSE_TILE_BUFFER_DIMS.y - 1); - const uint2 clampedCoarseTileCoord = CoordinateFromIndex(clampedCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x); + const uint2 clampedCoarseTileCoord = CoordinateFromIndex(clampedCoarseTileIndex, COARSE_TILE_BUFFER_DIMS.x); // TODO: avoid integer division // Within the coarse tile, we process fine tiles in the Morton order. // Of course, both coarse and fine tiles are arranged linearly in memory. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl index 801a2bd824e..92465aca492 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl @@ -151,14 +151,17 @@ uint FeatureFlagsToTileVariant(uint featureFlags) #ifdef USE_INDIRECT -uint TileVariantToFeatureFlags(uint variant, uint tileIndex) +uint TileVariantToFeatureFlags(uint variant, uint tile, uint eye) { if (variant == NUM_FEATURE_VARIANTS - 1) { + // Same as in 'classification.compute'. + uint bufferIndex = tile + IndexFromCoordinate(uint3(0, 0, eye), TILE_BUFFER_DIMS); + // We don't have any compile-time feature information. // Therefore, we load the feature classification data at runtime to avoid // entering every single branch based on feature flags. - return g_TileFeatureFlags[tileIndex]; + return g_TileFeatureFlags[bufferIndex]; } else { From 1a30c03f163e1b33e85b461f074ad48a1d9c7dda Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 13 Nov 2020 14:26:12 -0800 Subject: [PATCH 096/209] Add a profiling scope --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 41 ++++++++++--------- .../Runtime/RenderPipeline/HDProfileId.cs | 1 + 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index dd5e7c0c56b..05f0317563c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3869,30 +3869,33 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in { if (!parameters.enableFeatureVariants) return; - // clear dispatch indirect buffer - if (parameters.useComputeAsPixel) + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildDispatchIndirect))) { - cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); - cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); + // clear dispatch indirect buffer + if (parameters.useComputeAsPixel) + { + cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); + cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); - } - else - { - cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); - } + } + else + { + cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDispatchIndirectKernel, 1, 1, 1); + } - // add tiles to indirect buffer - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileList, resources.tileList); - cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + // add tiles to indirect buffer + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileList, resources.tileList); + cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - // Assume that we use fine (and not coarse) tiles in the shader. - int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; - int groupCount = HDUtils.DivRoundUp(numTiles, k_ThreadGroupOptimalSize); + // Assume that we use fine (and not coarse) tiles in the shader. + int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; + int groupCount = HDUtils.DivRoundUp(numTiles, k_ThreadGroupOptimalSize); - cmd.DispatchCompute(parameters.buildDispatchIndirectShader, 0, groupCount, 1, parameters.viewCount); + cmd.DispatchCompute(parameters.buildDispatchIndirectShader, 0, groupCount, 1, parameters.viewCount); + } } static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs index 37f1f615ea7..dadd48c9f14 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDProfileId.cs @@ -22,6 +22,7 @@ internal enum HDProfileId PerformZBinning, FillScreenTiles, PerformClassification, + BuildDispatchIndirect, ContactShadows, BlitToFinalRTDevBuildOnly, Distortion, From cd86a2ec2642cd6f81632bda73c73496e3ca75d2 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 13 Nov 2020 14:56:25 -0800 Subject: [PATCH 097/209] TODO --- .../Runtime/Lighting/LightLoop/classification.compute | 1 + 1 file changed, 1 insertion(+) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index f6ce78706a6..0f2c05ca8bd 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -83,6 +83,7 @@ void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) // Unlit object, sky/background and forward opaque tag don't tag the StencilUsage.RequiresDeferredLighting bit uint stencilVal = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, clampedPixelCoord)); + // TODO: use coarse stencil here. if ((stencilVal & STENCILUSAGE_REQUIRES_DEFERRED_LIGHTING) != 0) { featureFlags = g_BaseFeatureFlags; // Contain all lightFeatures or 0 (depends if we enable light classification or not) From a3576b4d4bb22326c8de77e05ea373c6f9ecedf1 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 13 Nov 2020 17:57:57 -0800 Subject: [PATCH 098/209] Try to fix deferred pixel shaders --- .../ShaderLibrary/Common.hlsl | 7 ---- .../Runtime/Lighting/Deferred.shader | 10 ++++-- .../Lighting/LightLoop/Deferred.compute | 8 ++--- .../Lighting/LightLoop/DeferredTile.shader | 34 ++++++++++++------- .../Runtime/Lighting/LightLoop/LightLoop.cs | 1 + .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 4 +-- .../LightLoop/TilingAndBinningUtilities.hlsl | 4 +-- 7 files changed, 35 insertions(+), 33 deletions(-) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl index 0e1ecc2cc95..0a912c8c95e 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl @@ -1038,9 +1038,6 @@ struct PositionInputs uint2 positionSS; // Screen space pixel coordinates : [0, NumPixels) float deviceDepth; // Depth from the depth buffer : [0, 1] (typically reversed) float linearDepth; // View space Z coordinate : [Near, Far] - - uint tile; // Screen tile index - uint zBin; // Depth bin index }; // This function is use to provide an easy way to sample into a screen texture, either from a pixel or a compute shaders. @@ -1060,10 +1057,6 @@ PositionInputs GetPositionInput(float2 positionSS, float2 invScreenSize) posInput.positionNDC *= invScreenSize; posInput.positionSS = uint2(positionSS); - // These two are only used by certain (binned lighting) passes, - // so they must be initialized explicitly (only when necessary). - posInput.tile = posInput.zBin = 0; - return posInput; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader index 7dcdd51dbed..725e17af231 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader @@ -41,7 +41,8 @@ Shader "Hidden/HDRP/Deferred" #pragma multi_compile _ DEBUG_DISPLAY #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #define USE_FPTL_LIGHTLIST // deferred opaque always use FPTL + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING //------------------------------------------------------------------------------------- // Include @@ -131,6 +132,9 @@ Shader "Hidden/HDRP/Deferred" PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); + uint tile = ComputeTileIndex(posInput.positionSS); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + BSDFData bsdfData; BuiltinData builtinData; DECODE_FROM_GBUFFER(posInput.positionSS, UINT_MAX, bsdfData, builtinData); @@ -138,12 +142,12 @@ Shader "Hidden/HDRP/Deferred" PreLightData preLightData = GetPreLightData(V, posInput, bsdfData); LightLoopOutput lightLoopOutput; - LightLoop(V, posInput, preLightData, bsdfData, builtinData, LIGHT_FEATURE_MASK_FLAGS_OPAQUE, lightLoopOutput); + LightLoop(V, posInput, tile, zBin, preLightData, bsdfData, builtinData, LIGHT_FEATURE_MASK_FLAGS_OPAQUE, lightLoopOutput); // Alias float3 diffuseLighting = lightLoopOutput.diffuseLighting; float3 specularLighting = lightLoopOutput.specularLighting; - + diffuseLighting *= GetCurrentExposureMultiplier(); specularLighting *= GetCurrentExposureMultiplier(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index a35ce91425c..4b8b12fd50c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -44,9 +44,6 @@ # pragma warning( disable : 4714 ) // sum of temp registers and indexable temp registers times 256 threads exceeds the recommended total 16384. Performance may be reduced at kernel #endif -// deferred opaque always use FPTL -#define USE_FPTL_LIGHTLIST 1 - // Comment out the line to loop over all lights (for debugging purposes) #define FINE_BINNING // Keep in sync with 'classification.compute' and 'builddispatchindirect.compute' @@ -133,8 +130,7 @@ void SHADE_OPAQUE_ENTRY(uint3 groupThreadId : SV_GroupThreadID, uint3 groupId : float depth = LoadCameraDepth(pixelCoord.xy); PositionInputs posInput = GetPositionInput(pixelCoord.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); - posInput.tile = tile; - posInput.zBin = ComputeZBinIndex(posInput.linearDepth); + uint zBin = ComputeZBinIndex(posInput.linearDepth); // For indirect case: we can still overlap inside a tile with the sky/background, reject it // Can't rely on stencil as we are in compute shader @@ -159,7 +155,7 @@ void SHADE_OPAQUE_ENTRY(uint3 groupThreadId : SV_GroupThreadID, uint3 groupId : PreLightData preLightData = GetPreLightData(V, posInput, bsdfData); LightLoopOutput lightLoopOutput; - LightLoop(V, posInput, preLightData, bsdfData, builtinData, featureFlags, lightLoopOutput); + LightLoop(V, posInput, tile, zBin, preLightData, bsdfData, builtinData, featureFlags, lightLoopOutput); // Alias float3 diffuseLighting = lightLoopOutput.diffuseLighting; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader index 888dd32e4db..1a987305837 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader @@ -43,7 +43,8 @@ Shader "Hidden/HDRP/DeferredTile" #define USE_INDIRECT // otherwise TileVariantToFeatureFlags() will not be defined in Lit.hlsl!!! - #define USE_FPTL_LIGHTLIST 1 // deferred opaque always use FPTL + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING // Keep in sync with 'classification.compute' and 'builddispatchindirect.compute' #ifdef VARIANT0 #define VARIANT 0 @@ -201,13 +202,14 @@ Shader "Hidden/HDRP/DeferredTile" Varyings Vert(Attributes input) { - uint tilePackIndex = g_TileList[g_TileListOffset + input.instID]; - uint2 tileCoord = uint2((tilePackIndex >> TILE_INDEX_SHIFT_X) & TILE_INDEX_MASK, (tilePackIndex >> TILE_INDEX_SHIFT_Y) & TILE_INDEX_MASK); // see builddispatchindirect.compute - uint2 pixelCoord = tileCoord * GetTileSize(); + uint variantOffset = g_TileListOffset; + uint tileOffset = input.instID; // Includes the eye index for XR + uint tileAndEye = g_TileList[variantOffset + tileOffset]; + uint eye = tileAndEye >> TILE_INDEX_SHIFT_EYE; + uint tile = tileAndEye ^ (eye << TILE_INDEX_SHIFT_EYE); - uint screenWidth = (uint)_ScreenSize.x; - uint numTilesX = (screenWidth + (TILE_SIZE_FPTL) - 1) / TILE_SIZE_FPTL; - uint tileIndex = tileCoord.x + tileCoord.y * numTilesX; + uint2 tileCoord = CoordinateFromIndex(tile, TILE_BUFFER_DIMS.x); // TODO: avoid integer division + uint2 pixelCoord = tileCoord * TILE_SIZE; // This handles both "real quad" and "2 triangles" cases: remaps {0, 1, 2, 3, 4, 5} into {0, 1, 2, 3, 0, 2}. uint quadIndex = (input.vertexID & 0x03) + (input.vertexID >> 2) * (input.vertexID & 0x01); @@ -219,7 +221,7 @@ Shader "Hidden/HDRP/DeferredTile" // Tiles coordinates always start at upper-left corner of the screen (y axis down). // Clip-space coordinatea always have y axis up. Hence, we must always flip y. output.positionCS.y *= -1.0; - output.tileIndexAndCoord = uint3(tileIndex, tileCoord); + output.tileIndexAndCoord = uint3(tile, tileCoord); return output; } @@ -228,13 +230,15 @@ Shader "Hidden/HDRP/DeferredTile" { // This need to stay in sync with deferred.compute - uint tileIndex = input.tileIndexAndCoord.x; + uint tile = input.tileIndexAndCoord.x; uint2 tileCoord = input.tileIndexAndCoord.yz; - uint featureFlags = TileVariantToFeatureFlags(VARIANT, tileIndex, unity_StereoEyeIndex); + uint featureFlags = TileVariantToFeatureFlags(VARIANT, tile, unity_StereoEyeIndex); float depth = LoadCameraDepth(input.positionCS.xy).x; PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); BSDFData bsdfData; @@ -244,7 +248,7 @@ Shader "Hidden/HDRP/DeferredTile" PreLightData preLightData = GetPreLightData(V, posInput, bsdfData); LightLoopOutput lightLoopOutput; - LightLoop(V, posInput, preLightData, bsdfData, builtinData, featureFlags, lightLoopOutput); + LightLoop(V, posInput, tile, zBin, preLightData, bsdfData, builtinData, featureFlags, lightLoopOutput); // Alias float3 diffuseLighting = lightLoopOutput.diffuseLighting; @@ -308,7 +312,8 @@ Shader "Hidden/HDRP/DeferredTile" #pragma multi_compile SCREEN_SPACE_SHADOWS_OFF SCREEN_SPACE_SHADOWS_ON #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #define USE_FPTL_LIGHTLIST 1 // deferred opaque always use FPTL + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING // Keep in sync with 'classification.compute' and 'builddispatchindirect.compute' #ifdef DEBUG_DISPLAY // Don't care about this warning in debug @@ -401,6 +406,9 @@ Shader "Hidden/HDRP/DeferredTile" float depth = LoadCameraDepth(input.positionCS.xy).x; PositionInputs posInput = GetPositionInput(input.positionCS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); + uint tile = ComputeTileIndex(posInput.positionSS); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS); BSDFData bsdfData; @@ -410,7 +418,7 @@ Shader "Hidden/HDRP/DeferredTile" PreLightData preLightData = GetPreLightData(V, posInput, bsdfData); LightLoopOutput lightLoopOutput; - LightLoop(V, posInput, preLightData, bsdfData, builtinData, LIGHT_FEATURE_MASK_FLAGS_OPAQUE, lightLoopOutput); + LightLoop(V, posInput, tile, zBin, preLightData, bsdfData, builtinData, LIGHT_FEATURE_MASK_FLAGS_OPAQUE, lightLoopOutput); // Alias float3 diffuseLighting = lightLoopOutput.diffuseLighting; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 05f0317563c..33f31cc09d4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3820,6 +3820,7 @@ static void PerformClassification(in BuildGPULightListParameters parameters, in { parameters.classificationShader.EnableKeyword("LIGHT_CLASSIFICATION"); cmd.SetComputeBufferParam(parameters.classificationShader, 0, HDShaderIDs._FineTileBuffer, resources.fineTileBuffer); + cmd.SetComputeBufferParam(parameters.classificationShader, 0, HDShaderIDs._zBinBuffer, resources.zBinBuffer); } if (parameters.computeMaterialVariants) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 684b2f6b27a..017746b6925 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -172,7 +172,7 @@ void ApplyDebug(LightLoopContext context, PositionInputs posInput, BSDFData bsdf #endif } -void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, BuiltinData builtinData, uint featureFlags, +void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLightData preLightData, BSDFData bsdfData, BuiltinData builtinData, uint featureFlags, out LightLoopOutput lightLoopOutput) { // Init LightLoop output structure @@ -236,7 +236,7 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BS i = 0; - while (TryLoadPunctualLightData(i, posInput.tile, posInput.zBin, lightData)) + while (TryLoadPunctualLightData(i, tile, zBin, lightData)) { if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index daa5b607e2f..af7bfcc5849 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -193,9 +193,9 @@ uint ComputeZBinIndex(float linearDepth) // Cannot be used to index directly into the buffer. // Use ComputeTileBufferIndex for that purpose. -// tileCoord = pixelCoord / TILE_SIZE. -uint ComputeTileIndex(uint2 tileCoord) +uint ComputeTileIndex(uint2 pixelCoord) { + uint2 tileCoord = pixelCoord / TILE_SIZE; return IndexFromCoordinate(uint4(tileCoord, 0, 0), uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); } From c1cb95c38675f30ddfa391c3cb193b0979af13ec Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 16 Nov 2020 16:27:28 -0800 Subject: [PATCH 099/209] Optimize --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 4 +--- .../Runtime/Lighting/LightLoop/classification.compute | 8 ++++---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 33f31cc09d4..43b69e20a8b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3860,9 +3860,7 @@ static void PerformClassification(in BuildGPULightListParameters parameters, in } // Assume that we use fine (and not coarse) tiles in the shader. - int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; - - cmd.DispatchCompute(parameters.classificationShader, 0, numTiles, 1, parameters.viewCount); + cmd.DispatchCompute(parameters.classificationShader, 0, parameters.fineTileBufferDimensions.x, parameters.fineTileBufferDimensions.y, parameters.viewCount); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute index 0f2c05ca8bd..58be81bf993 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/classification.compute @@ -62,11 +62,11 @@ bool IsBinEmpty(uint tile, uint zBin, uint category, uint eye) [numthreads(TILE_SIZE * TILE_SIZE, 1, 1)] void main(uint3 threadID : SV_GroupThreadID, uint3 groupID : SV_GroupID) { - const uint t = threadID.x; - const uint tile = groupID.x; - const uint eye = groupID.z; + const uint t = threadID.x; + const uint2 tileCoord = groupID.xy; + const uint eye = groupID.z; - const uint2 tileCoord = CoordinateFromIndex(tile, TILE_BUFFER_DIMS.x); // TODO: avoid integer division + const uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); const uint2 localPixelCoord = DecodeMorton2D(t & (TILE_SIZE * TILE_SIZE - 1)); // Use AND to inform the compiler const uint2 globalPixelCoord = tileCoord * TILE_SIZE + localPixelCoord; const uint2 clampedPixelCoord = min(globalPixelCoord, uint2(_ScreenSize.xy) - 1); From 929ea35a3e1e31474bbb897c3b9f9702350be85b Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 16 Nov 2020 16:52:13 -0800 Subject: [PATCH 100/209] Another attempted fix... --- .../Runtime/Lighting/LightLoop/DeferredTile.shader | 11 ++++++----- .../Runtime/Lighting/LightLoop/LightLoop.cs | 7 +++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader index 1a987305837..cae90086333 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/DeferredTile.shader @@ -187,7 +187,7 @@ Shader "Hidden/HDRP/DeferredTile" struct Varyings { float4 positionCS : SV_POSITION; - nointerpolation uint3 tileIndexAndCoord : TEXCOORD0; + nointerpolation uint2 tileCoord : TEXCOORD0; }; struct Outputs @@ -214,14 +214,14 @@ Shader "Hidden/HDRP/DeferredTile" // This handles both "real quad" and "2 triangles" cases: remaps {0, 1, 2, 3, 4, 5} into {0, 1, 2, 3, 0, 2}. uint quadIndex = (input.vertexID & 0x03) + (input.vertexID >> 2) * (input.vertexID & 0x01); float2 pp = GetQuadVertexPosition(quadIndex).xy; - pixelCoord += uint2(pp.xy * TILE_SIZE_FPTL); + pixelCoord += uint2(pp.xy * TILE_SIZE); Varyings output; output.positionCS = float4((pixelCoord * _ScreenSize.zw) * 2.0 - 1.0, 0, 1); // Tiles coordinates always start at upper-left corner of the screen (y axis down). // Clip-space coordinatea always have y axis up. Hence, we must always flip y. output.positionCS.y *= -1.0; - output.tileIndexAndCoord = uint3(tile, tileCoord); + output.tileCoord = tileCoord; return output; } @@ -230,8 +230,9 @@ Shader "Hidden/HDRP/DeferredTile" { // This need to stay in sync with deferred.compute - uint tile = input.tileIndexAndCoord.x; - uint2 tileCoord = input.tileIndexAndCoord.yz; + uint2 tileCoord = input.tileCoord; + + uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); uint featureFlags = TileVariantToFeatureFlags(VARIANT, tile, unity_StereoEyeIndex); float depth = LoadCameraDepth(input.positionCS.xy).x; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 43b69e20a8b..7f94801ebd2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -3870,10 +3870,15 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildDispatchIndirect))) { + + // Assume that we use fine (and not coarse) tiles in the shader. + int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; + // clear dispatch indirect buffer if (parameters.useComputeAsPixel) { cmd.SetComputeBufferParam(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, HDShaderIDs.g_DispatchIndirectBuffer, resources.dispatchIndirectBuffer); + cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, numTiles); cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); @@ -3889,8 +3894,6 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileList, resources.tileList); cmd.SetComputeBufferParam(parameters.buildDispatchIndirectShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); - // Assume that we use fine (and not coarse) tiles in the shader. - int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; int groupCount = HDUtils.DivRoundUp(numTiles, k_ThreadGroupOptimalSize); cmd.DispatchCompute(parameters.buildDispatchIndirectShader, 0, groupCount, 1, parameters.viewCount); From 1635bf19f88f65bb56d693673ba767881b90834d Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 17 Nov 2020 17:48:44 -0800 Subject: [PATCH 101/209] Simplify --- .../Runtime/Lighting/Deferred.shader | 2 -- .../Runtime/Lighting/LightLoop/builddispatchindirect.compute | 4 +--- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader index 725e17af231..32b256c4165 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Deferred.shader @@ -32,8 +32,6 @@ Shader "Hidden/HDRP/Deferred" #pragma vertex Vert #pragma fragment Frag - #define LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - // Split lighting is utilized during the SSS pass. #pragma multi_compile _ OUTPUT_SPLIT_LIGHTING #pragma multi_compile _ SHADOWS_SHADOWMASK diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute index aca0e2b4694..a08cf4b2249 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/builddispatchindirect.compute @@ -48,14 +48,12 @@ void main(uint3 threadID : SV_DispatchThreadID, uint3 groupID : SV_GroupID) // but do not store the results of the computation to memory. const bool isHelperThread = tile != clampedTile; - if (isHelperThread) return; // Avoid adding too many checks or branches below - uint bufferIndex = clampedTile + IndexFromCoordinate(uint3(0, 0, eye), TILE_BUFFER_DIMS); uint featureFlags = g_TileFeatureFlags[bufferIndex]; // Check if there is no material (means it is a sky/background pixel). // Note that a tile may have no lights, and yet we still need to render geometry with precomputed illumination. - if ((featureFlags & MATERIAL_FEATURE_MASK_FLAGS) != 0) + if (!isHelperThread && ((featureFlags & MATERIAL_FEATURE_MASK_FLAGS) != 0)) { uint variant = FeatureFlagsToTileVariant(featureFlags); From 0a3bb4f46fed90114465f79abf180b09a6c558b1 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 17 Nov 2020 18:26:49 -0800 Subject: [PATCH 102/209] Z-bin the lit shader --- .../Lighting/LightLoop/ShaderVariablesLightLoop.hlsl | 10 ++++------ .../Runtime/Material/LayeredLit/LayeredLit.shader | 3 ++- .../Material/LayeredLit/LayeredLitTessellation.shader | 3 ++- .../Runtime/Material/Lit/Lit.shader | 6 ++++-- .../Runtime/Material/Lit/LitTessellation.shader | 6 ++++-- .../RenderPipeline/ShaderPass/ShaderPassForward.hlsl | 5 ++++- 6 files changed, 20 insertions(+), 13 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index f236b45191b..0f8100406d9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -1,12 +1,10 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs.hlsl" -#if (defined(COARSE_BINNING) || defined(FINE_BINNING)) - // TODO: we don't need both tile buffers in the same shader, so perhaps just declare one? - StructuredBuffer _CoarseTileBuffer; - StructuredBuffer _FineTileBuffer; - StructuredBuffer _zBinBuffer; -#endif +// It appears that, due to our include structure, we have to always declare these. +StructuredBuffer _CoarseTileBuffer; +StructuredBuffer _FineTileBuffer; +StructuredBuffer _zBinBuffer; #ifdef USE_INDIRECT StructuredBuffer g_TileFeatureFlags; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader index 3a322d992ff..6f9b1273888 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader @@ -816,7 +816,8 @@ Shader "HDRP/LayeredLit" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader index 585db9520ab..162b1bd4ae4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader @@ -804,7 +804,8 @@ Shader "HDRP/LayeredLitTessellation" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader index d83743bdb8d..8b737f657ca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader @@ -746,7 +746,8 @@ Shader "HDRP/Lit" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #define USE_CLUSTERED_LIGHTLIST // There is not FPTL lighting when using transparent + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" @@ -821,7 +822,8 @@ Shader "HDRP/Lit" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader index 8163e8398b9..a850b93b600 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader @@ -674,7 +674,8 @@ Shader "HDRP/LitTessellation" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #define USE_CLUSTERED_LIGHTLIST // There is not FPTL lighting when using transparent + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl" @@ -741,7 +742,8 @@ Shader "HDRP/LitTessellation" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl index b2d13122ea6..f1294e3d2ee 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl @@ -125,6 +125,9 @@ void Frag(PackedVaryingsToPS packedInput, float3 V = float3(1.0, 1.0, 1.0); // Avoid the division by 0 #endif + uint tile = ComputeTileIndex(posInput.positionSS); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + SurfaceData surfaceData; BuiltinData builtinData; GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData); @@ -212,7 +215,7 @@ void Frag(PackedVaryingsToPS packedInput, uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_OPAQUE; #endif LightLoopOutput lightLoopOutput; - LightLoop(V, posInput, preLightData, bsdfData, builtinData, featureFlags, lightLoopOutput); + LightLoop(V, posInput, tile, zBin, preLightData, bsdfData, builtinData, featureFlags, lightLoopOutput); // Alias float3 diffuseLighting = lightLoopOutput.diffuseLighting; From c2cdc77430e978ed70928848c5c6b5fa78a0b3da Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 17 Nov 2020 19:08:20 -0800 Subject: [PATCH 103/209] Add area light support --- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 66 +++++-------------- .../Lighting/LightLoop/LightLoopDef.hlsl | 53 +++++++++++++++ 2 files changed, 69 insertions(+), 50 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 017746b6925..131d6e3e220 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -377,59 +377,25 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh // } // } -// #if SHADEROPTIONS_AREA_LIGHTS -// if (featureFlags & LIGHTFEATUREFLAGS_AREA) -// { -// uint lightCount, lightStart; - -// #ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER -// GetCountAndStart(posInput, LIGHTCATEGORY_AREA, lightStart, lightCount); -// #else -// lightCount = _AreaLightCount; -// lightStart = _PunctualLightCount; -// #endif - -// // COMPILER BEHAVIOR WARNING! -// // If rectangle lights are before line lights, the compiler will duplicate light matrices in VGPR because they are used differently between the two types of lights. -// // By keeping line lights first we avoid this behavior and save substantial register pressure. -// // TODO: This is based on the current Lit.shader and can be different for any other way of implementing area lights, how to be generic and ensure performance ? - -// if (lightCount > 0) -// { -// i = 0; - -// uint last = lightCount - 1; -// LightData lightData = FetchLight(lightStart, i); - -// while (i <= last && lightData.lightType == GPULIGHTTYPE_TUBE) -// { -// lightData.lightType = GPULIGHTTYPE_TUBE; // Enforce constant propagation -// lightData.cookieMode = COOKIEMODE_NONE; // Enforce constant propagation - -// if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) -// { -// DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); -// AccumulateDirectLighting(lighting, aggregateLighting); -// } - -// lightData = FetchLight(lightStart, min(++i, last)); -// } +#if SHADEROPTIONS_AREA_LIGHTS + if (featureFlags & LIGHTFEATUREFLAGS_AREA) + { + LightData lightData; -// while (i <= last) // GPULIGHTTYPE_RECTANGLE -// { -// lightData.lightType = GPULIGHTTYPE_RECTANGLE; // Enforce constant propagation + i = 0; -// if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) -// { -// DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); -// AccumulateDirectLighting(lighting, aggregateLighting); -// } + while (TryLoadAreaLightData(i, tile, zBin, lightData)) + { + if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) + { + DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, lightData, bsdfData, builtinData); + AccumulateDirectLighting(lighting, aggregateLighting); + } -// lightData = FetchLight(lightStart, min(++i, last)); -// } -// } -// } -// #endif + i++; + } + } +#endif // #if SHADEROPTIONS_PROBE_VOLUMES_EVALUATION_MODE == PROBEVOLUMESEVALUATIONMODES_LIGHT_LOOP // bool uninitialized = IsUninitializedGI(builtinData.bakeDiffuseLighting); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 34b4b9495a4..03883177b65 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -201,6 +201,59 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData return b; } +bool TryLoadAreaLightData(inout uint i, uint tile, uint zBin, out LightData data) +{ + bool b = false; + uint n = TILE_ENTRY_LIMIT; + + // This part (1) is loop-invariant. These values do not depend on the value of 'i'. + // They will only be computed once per category, not once per function call. + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, BOUNDEDENTITYCATEGORY_AREA_LIGHT, unity_StereoEyeIndex); + const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} + const bool isTileEmpty = tileRangeData == UINT16_MAX; + + if (!isTileEmpty) // Avoid wasted work + { + const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_AREA_LIGHT, unity_StereoEyeIndex); + const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + + const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); + const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); + + if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) // Avoid wasted work + { + const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(tile, BOUNDEDENTITYCATEGORY_AREA_LIGHT, unity_StereoEyeIndex); + + // The part (2) below will be actually executed during every function call. + while (i < n) + { + uint tileEntityPair = TILE_BUFFER[tileBufferBodyIndex + (i / 2)]; // 16-bit indices + uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); // First Lo, then Hi bits + + // Entity indices are stored in the ascending order. + // We can distinguish 3 cases: + if (tileEntityIndex < zBinEntityIndexRange.x) + { + i++; // Skip this entity; continue the (linear) search + } + else if (tileEntityIndex <= zBinEntityIndexRange.y) + { + data = _AreaLightData[tileEntityIndex]; + + b = true; // Found a valid index + break; // Avoid incrementing 'i' further + } + else // if (zBinEntityIndexRange.y < tileEntityIndex) + { + break; // Avoid incrementing 'i' further + } + } + } + } + + return b; +} + #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) bool TryLoadPunctualLightData(uint i, uint tile, uint zBin, out LightData data) From 303566a1ff95a340e847bb5fc7ff406701a20c8d Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 18 Nov 2020 17:35:13 -0800 Subject: [PATCH 104/209] Add decal support --- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 6 +- .../Lighting/LightLoop/LightLoopDef.hlsl | 84 +++++++++---------- .../LightLoop/TilingAndBinningUtilities.hlsl | 4 +- .../Material/Decal/DecalUtilities.hlsl | 65 ++------------ 4 files changed, 51 insertions(+), 108 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 131d6e3e220..fab6b386103 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -232,10 +232,9 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh if (featureFlags & LIGHTFEATUREFLAGS_PUNCTUAL) { - LightData lightData; - i = 0; + LightData lightData; while (TryLoadPunctualLightData(i, tile, zBin, lightData)) { if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) @@ -380,10 +379,9 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh #if SHADEROPTIONS_AREA_LIGHTS if (featureFlags & LIGHTFEATUREFLAGS_AREA) { - LightData lightData; - i = 0; + LightData lightData; while (TryLoadAreaLightData(i, tile, zBin, lightData)) { if (IsMatchingLightLayer(lightData.lightLayers, builtinData.renderingLayers)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 03883177b65..0141821387e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -148,20 +148,23 @@ float4 SampleEnv(LightLoopContext lightLoopContext, int index, float3 texCoord, #if (defined(COARSE_BINNING) || defined(FINE_BINNING)) -bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData data) +// Internal. Do not call directly. +uint TryFindEntityIndex(inout uint i, uint tile, uint zBin, uint category, out uint entityIndex) { + entityIndex = UINT16_MAX; + bool b = false; uint n = TILE_ENTRY_LIMIT; // This part (1) is loop-invariant. These values do not depend on the value of 'i'. // They will only be computed once per category, not once per function call. - const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, category, unity_StereoEyeIndex); const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} const bool isTileEmpty = tileRangeData == UINT16_MAX; if (!isTileEmpty) // Avoid wasted work { - const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, category, unity_StereoEyeIndex); const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); @@ -169,7 +172,7 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) // Avoid wasted work { - const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(tile, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, unity_StereoEyeIndex); + const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(tile, category, unity_StereoEyeIndex); // The part (2) below will be actually executed during every function call. while (i < n) @@ -185,7 +188,7 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData } else if (tileEntityIndex <= zBinEntityIndexRange.y) { - data = _PunctualLightData[tileEntityIndex]; + entityIndex = tileEntityIndex; b = true; // Found a valid index break; // Avoid incrementing 'i' further @@ -201,57 +204,46 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData return b; } -bool TryLoadAreaLightData(inout uint i, uint tile, uint zBin, out LightData data) +bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData data) { - bool b = false; - uint n = TILE_ENTRY_LIMIT; + bool success = false; - // This part (1) is loop-invariant. These values do not depend on the value of 'i'. - // They will only be computed once per category, not once per function call. - const uint tileBufferHeaderIndex = ComputeTileBufferHeaderIndex(tile, BOUNDEDENTITYCATEGORY_AREA_LIGHT, unity_StereoEyeIndex); - const uint tileRangeData = TILE_BUFFER[tileBufferHeaderIndex]; // {last << 16 | first} - const bool isTileEmpty = tileRangeData == UINT16_MAX; - - if (!isTileEmpty) // Avoid wasted work + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBin, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, entityIndex)) { - const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, BOUNDEDENTITYCATEGORY_AREA_LIGHT, unity_StereoEyeIndex); - const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + success = true; + data = _PunctualLightData[entityIndex]; + } - const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); - const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); + return success; +} - if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) // Avoid wasted work - { - const uint tileBufferBodyIndex = ComputeTileBufferBodyIndex(tile, BOUNDEDENTITYCATEGORY_AREA_LIGHT, unity_StereoEyeIndex); +bool TryLoadAreaLightData(inout uint i, uint tile, uint zBin, out LightData data) +{ + bool success = false; - // The part (2) below will be actually executed during every function call. - while (i < n) - { - uint tileEntityPair = TILE_BUFFER[tileBufferBodyIndex + (i / 2)]; // 16-bit indices - uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); // First Lo, then Hi bits + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBin, BOUNDEDENTITYCATEGORY_AREA_LIGHT, entityIndex)) + { + success = true; + data = _AreaLightData[entityIndex]; + } - // Entity indices are stored in the ascending order. - // We can distinguish 3 cases: - if (tileEntityIndex < zBinEntityIndexRange.x) - { - i++; // Skip this entity; continue the (linear) search - } - else if (tileEntityIndex <= zBinEntityIndexRange.y) - { - data = _AreaLightData[tileEntityIndex]; + return success; +} - b = true; // Found a valid index - break; // Avoid incrementing 'i' further - } - else // if (zBinEntityIndexRange.y < tileEntityIndex) - { - break; // Avoid incrementing 'i' further - } - } - } +bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) +{ + bool success = false; + + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBin, BOUNDEDENTITYCATEGORY_DECAL, entityIndex)) + { + success = true; + data = _DecalData[entityIndex]; } - return b; + return success; } #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index af7bfcc5849..538f670e569 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -200,7 +200,7 @@ uint ComputeTileIndex(uint2 pixelCoord) uint3(TILE_BUFFER_DIMS, BOUNDEDENTITYCATEGORY_COUNT)); } -// Internal. Do not use. +// Internal. Do not call directly. uint ComputeTileBufferHeaderIndex(uint tile, uint category, uint eye, uint2 tileBufferDims) { uint eyeCatOffset = IndexFromCoordinate(uint4(0, 0, category, eye), @@ -216,7 +216,7 @@ uint ComputeTileBufferHeaderIndex(uint tile, uint category, uint eye) return ComputeTileBufferHeaderIndex(tile, category, eye, TILE_BUFFER_DIMS); } -// Internal. Do not use. +// Internal. Do not call directly. uint ComputeTileBufferBodyIndex(uint tile, uint category, uint eye, uint2 tileBufferDims, uint tileEntryLimit) { // TODO: may want to precompute this. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl index 168792b8c82..cc460d188ae 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl @@ -155,27 +155,9 @@ void EvalDecalMask( PositionInputs posInput, float3 positionRWSDdx, float3 posit } } -#if defined(_SURFACE_TYPE_TRANSPARENT) && defined(HAS_LIGHTLOOP) // forward transparent using clustered decals -DecalData FetchDecal(uint start, uint i) -{ -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - int j = FetchIndex(start, i); -#else - int j = start + i; -#endif - return _DecalData[j]; -} - -DecalData FetchDecal(uint index) -{ - return _DecalData[index]; -} -#endif - DecalSurfaceData GetDecalSurfaceData(PositionInputs posInput, inout float alpha) { #if defined(_SURFACE_TYPE_TRANSPARENT) && defined(HAS_LIGHTLOOP) // forward transparent using clustered decals - uint decalCount, decalStart; DBufferType0 DBuffer0 = float4(0.0, 0.0, 0.0, 1.0); DBufferType1 DBuffer1 = float4(0.5, 0.5, 0.5, 1.0); DBufferType2 DBuffer2 = float4(0.0, 0.0, 0.0, 1.0); @@ -185,17 +167,8 @@ DecalSurfaceData GetDecalSurfaceData(PositionInputs posInput, inout float alpha) float2 DBuffer3 = float2(1.0, 1.0); #endif -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - GetCountAndStart(posInput, LIGHTCATEGORY_DECAL, decalStart, decalCount); - - // Fast path is when we all pixels in a wave are accessing same tile or cluster. - uint decalStartLane0; - bool fastPath = IsFastPath(decalStart, decalStartLane0); - -#else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - decalCount = _DecalCount; - decalStart = 0; -#endif + uint tile = ComputeTileIndex(posInput.positionSS); + uint zBin = ComputeZBinIndex(posInput.linearDepth); float3 positionRWS = posInput.positionWS; @@ -205,38 +178,18 @@ DecalSurfaceData GetDecalSurfaceData(PositionInputs posInput, inout float alpha) uint decalLayerMask = GetMeshRenderingDecalLayer(); - // Scalarized loop. All decals that are in a tile/cluster touched by any pixel in the wave are loaded (scalar load), only the ones relevant to current thread/pixel are processed. - // For clarity, the following code will follow the convention: variables starting with s_ are wave uniform (meant for scalar register), - // v_ are variables that might have different value for each thread in the wave (meant for vector registers). - // This will perform more loads than it is supposed to, however, the benefits should offset the downside, especially given that decal data accessed should be largely coherent - // Note that the above is valid only if wave intriniscs are supported. - uint v_decalListOffset = 0; - uint v_decalIdx = decalStart; - while (v_decalListOffset < decalCount) - { -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - v_decalIdx = FetchIndex(decalStart, v_decalListOffset); -#else - v_decalIdx = decalStart + v_decalListOffset; -#endif // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER + DecalData decalData; - uint s_decalIdx = ScalarizeElementIndex(v_decalIdx, fastPath); - if (s_decalIdx == -1) - break; + uint i = 0; - DecalData s_decalData = FetchDecal(s_decalIdx); - bool isRejected = (s_decalData.decalLayerMask & decalLayerMask) == 0; - - // If current scalar and vector decal index match, we process the decal. The v_decalListOffset for current thread is increased. - // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could - // end up with a unique v_decalIdx value that is smaller than s_decalIdx hence being stuck in a loop. All the active lanes will not have this problem. - if (s_decalIdx >= v_decalIdx) + while (TryLoadDecalData(i, tile, zBin, decalData)) + { + if ((decalData.decalLayerMask & decalLayerMask) != 0) { - v_decalListOffset++; - if (!isRejected) - EvalDecalMask(posInput, positionRWSDdx, positionRWSDdy, s_decalData, DBuffer0, DBuffer1, DBuffer2, DBuffer3, alpha); + EvalDecalMask(posInput, positionRWSDdx, positionRWSDdy, decalData, DBuffer0, DBuffer1, DBuffer2, DBuffer3, alpha); } + i++; } #else // Opaque - used DBuffer FETCH_DBUFFER(DBuffer, _DBufferTexture, int2(posInput.positionSS.xy)); From f132dd7fd37097a428cb442cdd91bc1363d2bb57 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 18 Nov 2020 20:26:45 -0800 Subject: [PATCH 105/209] Enable directional lights --- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index fab6b386103..889732ac68d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -364,17 +364,17 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh // #undef EVALUATE_BSDF_ENV // #undef EVALUATE_BSDF_ENV_SKY -// if (featureFlags & LIGHTFEATUREFLAGS_DIRECTIONAL) -// { -// for (i = 0; i < _DirectionalLightCount; ++i) -// { -// if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, builtinData.renderingLayers)) -// { -// DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightData[i], bsdfData, builtinData); -// AccumulateDirectLighting(lighting, aggregateLighting); -// } -// } -// } + if (featureFlags & LIGHTFEATUREFLAGS_DIRECTIONAL) + { + for (i = 0; i < _DirectionalLightCount; ++i) + { + if (IsMatchingLightLayer(_DirectionalLightData[i].lightLayers, builtinData.renderingLayers)) + { + DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightData[i], bsdfData, builtinData); + AccumulateDirectLighting(lighting, aggregateLighting); + } + } + } #if SHADEROPTIONS_AREA_LIGHTS if (featureFlags & LIGHTFEATUREFLAGS_AREA) From 6b83df2741d4acf4149457a06e03385df3827e90 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 19 Nov 2020 15:15:27 -0800 Subject: [PATCH 106/209] Fix HDShadowLoop.hlsl (ShadowLoopMin) --- .../Lighting/LightLoop/HDShadowLoop.hlsl | 135 ++++++------------ 1 file changed, 43 insertions(+), 92 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl index 348faac2f18..7c8ed933f2b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/HDShadowLoop.hlsl @@ -18,6 +18,10 @@ void ShadowLoopMin(HDShadowContext shadowContext, PositionInputs posInput, float shadow = float3(1, 1, 1); #endif + // TODO: may want to make 'tile' wave-uniform. + uint tile = ComputeTileIndex(posInput.positionSS); + uint zBin = ComputeZBinIndex(posInput.linearDepth); + // With XR single-pass and camera-relative: offset position to do lighting computations from the combined center view (original camera matrix). // This is required because there is only one list of lights generated on the CPU. Shadows are also generated once and shared between the instanced views. ApplyCameraRelativeXR(posInput.positionWS); @@ -54,116 +58,59 @@ void ShadowLoopMin(HDShadowContext shadowContext, PositionInputs posInput, float } } + uint i; // Declare once to avoid the D3D11 compiler warning. + if (featureFlags & LIGHTFEATUREFLAGS_PUNCTUAL) { - uint lightCount, lightStart; - -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - GetCountAndStart(posInput, LIGHTCATEGORY_PUNCTUAL, lightStart, lightCount); -#else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - lightCount = _PunctualLightCount; - lightStart = 0; -#endif + i = 0; - bool fastPath = false; - uint lightStartLane0; - fastPath = IsFastPath(lightStart, lightStartLane0); - - if (fastPath) + LightData lightData; + while (TryLoadPunctualLightData(i, tile, zBin, lightData)) { - lightStart = lightStartLane0; - } - - // Scalarized loop. All lights that are in a tile/cluster touched by any pixel in the wave are loaded (scalar load), only the one relevant to current thread/pixel are processed. - // For clarity, the following code will follow the convention: variables starting with s_ are meant to be wave uniform (meant for scalar register), - // v_ are variables that might have different value for each thread in the wave (meant for vector registers). - // This will perform more loads than it is supposed to, however, the benefits should offset the downside, especially given that light data accessed should be largely coherent. - // Note that the above is valid only if wave intriniscs are supported. - uint v_lightListOffset = 0; - uint v_lightIdx = lightStart; - - while (v_lightListOffset < lightCount) - { - v_lightIdx = FetchIndex(lightStart, v_lightListOffset); - uint s_lightIdx = ScalarizeElementIndex(v_lightIdx, fastPath); - if (s_lightIdx == -1) - break; - - LightData s_lightData = FetchLight(s_lightIdx); - - // If current scalar and vector light index match, we process the light. The v_lightListOffset for current thread is increased. - // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could - // end up with a unique v_lightIdx value that is smaller than s_lightIdx hence being stuck in a loop. All the active lanes will not have this problem. - if (s_lightIdx >= v_lightIdx) + if (IsMatchingLightLayer(lightData.lightLayers, renderLayer) && + lightData.shadowIndex >= 0 && + lightData.shadowDimmer > 0) { - v_lightListOffset++; - if (IsMatchingLightLayer(s_lightData.lightLayers, renderLayer) && - s_lightData.shadowIndex >= 0 && - s_lightData.shadowDimmer > 0) + float shadowP; + float3 L; + float4 distances; // {d, d^2, 1/d, d_proj} + GetPunctualLightVectors(posInput.positionWS, lightData, L, distances); + float distToLight = (lightData.lightType == GPULIGHTTYPE_PROJECTOR_BOX) ? distances.w : distances.x; + float lightRadSqr = lightData.size.x; + if (distances.x < lightData.range && + PunctualLightAttenuation(distances, lightData.rangeAttenuationScale, lightData.rangeAttenuationBias, + lightData.angleScale, lightData.angleOffset) > 0.0 && + L.y > 0.0) { - float shadowP; - float3 L; - float4 distances; // {d, d^2, 1/d, d_proj} - GetPunctualLightVectors(posInput.positionWS, s_lightData, L, distances); - float distToLight = (s_lightData.lightType == GPULIGHTTYPE_PROJECTOR_BOX) ? distances.w : distances.x; - float lightRadSqr = s_lightData.size.x; - if (distances.x < s_lightData.range && - PunctualLightAttenuation(distances, s_lightData.rangeAttenuationScale, s_lightData.rangeAttenuationBias, - s_lightData.angleScale, s_lightData.angleOffset) > 0.0 && - L.y > 0.0) - { - shadowP = GetPunctualShadowAttenuation(shadowContext, posInput.positionSS, posInput.positionWS, normalWS, s_lightData.shadowIndex, L, distances.x, s_lightData.lightType == GPULIGHTTYPE_POINT, s_lightData.lightType != GPULIGHTTYPE_PROJECTOR_BOX); - shadowP = s_lightData.nonLightMappedOnly ? min(1.0f, shadowP) : shadowP; - shadowP = lerp(1.0f, shadowP, s_lightData.shadowDimmer); + shadowP = GetPunctualShadowAttenuation(shadowContext, posInput.positionSS, posInput.positionWS, normalWS, lightData.shadowIndex, L, distances.x, lightData.lightType == GPULIGHTTYPE_POINT, lightData.lightType != GPULIGHTTYPE_PROJECTOR_BOX); + shadowP = lightData.nonLightMappedOnly ? min(1.0f, shadowP) : shadowP; + shadowP = lerp(1.0f, shadowP, lightData.shadowDimmer); #ifdef SHADOW_LOOP_MULTIPLY - shadow *= lerp(s_lightData.shadowTint, float3(1, 1, 1), shadowP); + shadow *= lerp(lightData.shadowTint, float3(1, 1, 1), shadowP); #elif defined(SHADOW_LOOP_AVERAGE) - shadow += lerp(s_lightData.shadowTint, float3(1, 1, 1), shadowP); + shadow += lerp(lightData.shadowTint, float3(1, 1, 1), shadowP); #else - shadow = min(shadow, shadowP.xxx); + shadow = min(shadow, shadowP.xxx); #endif - shadowCount += 1.0f; - weight += 1.0f - shadowP; - } + shadowCount += 1.0f; + weight += 1.0f - shadowP; } } + + i++; } } if (featureFlags & LIGHTFEATUREFLAGS_AREA) { - uint lightCount, lightStart; - - #ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - GetCountAndStart(posInput, LIGHTCATEGORY_AREA, lightStart, lightCount); - #else - lightCount = _AreaLightCount; - lightStart = _PunctualLightCount; - #endif - - // COMPILER BEHAVIOR WARNING! - // If rectangle lights are before line lights, the compiler will duplicate light matrices in VGPR because they are used differently between the two types of lights. - // By keeping line lights first we avoid this behavior and save substantial register pressure. - // TODO: This is based on the current Lit.shader and can be different for any other way of implementing area lights, how to be generic and ensure performance ? - - uint i; - if (lightCount > 0) - { - i = 0; - - uint last = lightCount - 1; - LightData lightData = FetchLight(lightStart, i); - - while (i <= last && lightData.lightType == GPULIGHTTYPE_TUBE) - { - lightData = FetchLight(lightStart, min(++i, last)); - } + i = 0; - while (i <= last) // GPULIGHTTYPE_RECTANGLE + LightData lightData; + while (TryLoadAreaLightData(i, tile, zBin, lightData)) + { + if (lightData.lightType == GPULIGHTTYPE_RECTANGLE) { - lightData.lightType = GPULIGHTTYPE_RECTANGLE; // Enforce constant propagation - if (IsMatchingLightLayer(lightData.lightLayers, renderLayer)) { float3 L; @@ -208,9 +155,13 @@ void ShadowLoopMin(HDShadowContext shadowContext, PositionInputs posInput, float weight += 1.0f - shadowA; } } - - lightData = FetchLight(lightStart, min(++i, last)); } + else // GPULIGHTTYPE_TUBE + { + /* ??? */ + } + + i++; } } #ifdef SHADOW_LOOP_MULTIPLY From 1aa1e271418b301ffef3dd1e8a001b8b070ec9bc Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 19 Nov 2020 19:07:51 -0800 Subject: [PATCH 107/209] Add reflection probe support --- .../Runtime/Lighting/LightDefinition.cs | 1 + .../Runtime/Lighting/LightDefinition.cs.hlsl | 1 + .../Runtime/Lighting/LightLoop/LightLoop.cs | 31 ++- .../Lighting/LightLoop/LightLoop.cs.hlsl | 29 ++- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 225 +++++++++--------- .../Lighting/LightLoop/LightLoopDef.hlsl | 27 ++- .../Raytracing/HDRaytracingLightCluster.cs | 7 +- 7 files changed, 190 insertions(+), 131 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs index 6583f5fad61..50bd0adf466 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs @@ -204,6 +204,7 @@ enum EnvConstants struct EnvLightData { // Packing order depends on chronological access to avoid cache misses + public uint logVolume; public uint lightLayers; // Proxy properties diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl index 3f5a6053f73..b3f767ba574 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl @@ -132,6 +132,7 @@ struct LightData // PackingRules = Exact struct EnvLightData { + uint logVolume; uint lightLayers; float3 capturePositionRWS; int influenceShapeType; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 7f94801ebd2..7962f97c8d9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -409,6 +409,7 @@ class TiledLightingConstants public static int s_CoarseTileSize = 64; public static int s_FineTileSize = 8; public static int s_zBinCount = 8192; + public static int s_MaxReflectionProbesPerPixel = 4; } [GenerateHLSL] @@ -555,6 +556,7 @@ internal struct ProcessedProbeData { public HDProbe hdProbe; public float weight; + public uint logVolume; // Used for sorting in the shader } public partial class HDRenderPipeline @@ -2297,6 +2299,7 @@ internal bool GetEnvLightData(CommandBuffer cmd, HDCamera hdCamera, in Processed InfluenceVolume influence = probe.influenceVolume; envLightData.lightLayers = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers) ? probe.lightLayersAsUInt : uint.MaxValue; + envLightData.logVolume = processedProbe.logVolume; envLightData.influenceShapeType = influence.envShape; envLightData.weight = processedProbe.weight; envLightData.multiplier = probe.multiplier * m_indirectLightingController.reflectionProbeIntensityMultiplier.value; @@ -2996,6 +2999,17 @@ bool TrivialRejectProbe(in ProcessedProbeData processedProbe, HDCamera hdCamera) return false; } + static uint CalculateProbeLogVolume(Bounds bounds) + { + //Notes: + // - 1+ term is to prevent having negative values in the log result + // - 1000* is too keep 3 digit after the dot while we truncate the result later + // - 1048575 is 2^20-1 as we pack the result on 20bit later + float boxVolume = 8f* bounds.extents.x * bounds.extents.y * bounds.extents.z; + uint logVolume = (uint)Math.Max(0, Math.Min((int)(1000 * Mathf.Log(1 + boxVolume, 1.05f)), 1048575)); + return logVolume; + } + internal static void PreprocessReflectionProbeData(ref ProcessedProbeData processedData, VisibleReflectionProbe probe, HDCamera hdCamera) { var add = probe.reflectionProbe.GetComponent(); @@ -3008,13 +3022,14 @@ internal static void PreprocessReflectionProbeData(ref ProcessedProbeData proces add.influenceVolume.shape = InfluenceShape.Box; } - PreprocessProbeData(ref processedData, add, hdCamera); + PreprocessProbeData(ref processedData, add, probe.bounds, hdCamera); } - internal static void PreprocessProbeData(ref ProcessedProbeData processedData, HDProbe probe, HDCamera hdCamera) + internal static void PreprocessProbeData(ref ProcessedProbeData processedData, HDProbe probe, Bounds bounds, HDCamera hdCamera) { - processedData.hdProbe = probe; - processedData.weight = HDUtils.ComputeWeightedLinearFadeDistance(processedData.hdProbe.transform.position, hdCamera.camera.transform.position, processedData.hdProbe.weight, processedData.hdProbe.fadeDistance); + processedData.hdProbe = probe; + processedData.weight = HDUtils.ComputeWeightedLinearFadeDistance(processedData.hdProbe.transform.position, hdCamera.camera.transform.position, processedData.hdProbe.weight, processedData.hdProbe.fadeDistance); + processedData.logVolume = CalculateProbeLogVolume(bounds); } int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDProbeCullingResults hdProbeCullingResults, in AOVRequestData aovRequest) @@ -3062,9 +3077,6 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro continue; } - // Sorting by volume is no longer possible - // var logVolume = CalculateProbeLogVolume(probe.bounds); - int xrViewCount = hdCamera.viewCount; for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) @@ -3087,14 +3099,11 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro var probe = hdProbeCullingResults.visibleProbes[planarProbeIndex]; ref ProcessedProbeData processedData = ref m_ProcessedPlanarProbeData[planarProbeIndex]; - PreprocessProbeData(ref processedData, probe, hdCamera); + PreprocessProbeData(ref processedData, probe, probe.bounds, hdCamera); if (!aovRequest.IsLightEnabled(probe.gameObject)) continue; - // Sorting by volume is no longer possible - // var logVolume = CalculateProbeLogVolume(probe.bounds); - int xrViewCount = hdCamera.viewCount; for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl index 7a4dd513e44..d9b8a08d318 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl @@ -75,6 +75,7 @@ #define COARSE_TILE_SIZE (64) #define FINE_TILE_SIZE (8) #define Z_BIN_COUNT (8192) +#define MAX_REFLECTION_PROBES_PER_PIXEL (4) // // UnityEngine.Rendering.HighDefinition.ClusterDebugMode: static fields @@ -138,29 +139,37 @@ CBUFFER_END // // Accessors for UnityEngine.Rendering.HighDefinition.FiniteLightBound // +float3 GetCenter(FiniteLightBound value) +{ + return value.center; +} +float GetRadius(FiniteLightBound value) +{ + return value.radius; +} float3 GetBoxAxisX(FiniteLightBound value) { return value.boxAxisX; } -float3 GetBoxAxisY(FiniteLightBound value) +float GetScaleXY(FiniteLightBound value) { - return value.boxAxisY; + return value.scaleXY; } -float3 GetBoxAxisZ(FiniteLightBound value) +float3 GetBoxAxisY(FiniteLightBound value) { - return value.boxAxisZ; + return value.boxAxisY; } -float3 GetCenter(FiniteLightBound value) +float Get__pad0__(FiniteLightBound value) { - return value.center; + return value.__pad0__; } -float GetScaleXY(FiniteLightBound value) +float3 GetBoxAxisZ(FiniteLightBound value) { - return value.scaleXY; + return value.boxAxisZ; } -float GetRadius(FiniteLightBound value) +float Get__pad1__(FiniteLightBound value) { - return value.radius; + return value.__pad1__; } // // Accessors for UnityEngine.Rendering.HighDefinition.LightVolumeData diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 889732ac68d..4b1e09a82cf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -247,122 +247,131 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh } } -// // Define macro for a better understanding of the loop -// // TODO: this code is now much harder to understand... -// #define EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) \ -// IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightData, bsdfData, envLightData.influenceShapeType, MERGE_NAME(GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), MERGE_NAME(type, HierarchyWeight)); \ -// AccumulateIndirectLighting(lighting, aggregateLighting); + // Define macro for a better understanding of the loop + // TODO: this code is now much harder to understand... +#define EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) \ + IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightData, bsdfData, envLightData.influenceShapeType, MERGE_NAME(GPUIMAGEBASEDLIGHTINGTYPE_, TYPE), MERGE_NAME(type, HierarchyWeight)); \ + AccumulateIndirectLighting(lighting, aggregateLighting); -// // Environment cubemap test lightlayers, sky don't test it -// #define EVALUATE_BSDF_ENV(envLightData, TYPE, type) if (IsMatchingLightLayer(envLightData.lightLayers, builtinData.renderingLayers)) { EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) } +// Environment cubemap test lightlayers, sky don't test it +#define EVALUATE_BSDF_ENV(envLightData, TYPE, type) if (IsMatchingLightLayer(envLightData.lightLayers, builtinData.renderingLayers)) { EVALUATE_BSDF_ENV_SKY(envLightData, TYPE, type) } -// // First loop iteration -// if (featureFlags & (LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_SSREFRACTION | LIGHTFEATUREFLAGS_SSREFLECTION)) -// { -// float reflectionHierarchyWeight = 0.0; // Max: 1.0 -// float refractionHierarchyWeight = _EnableSSRefraction ? 0.0 : 1.0; // Max: 1.0 + // First loop iteration + if (featureFlags & (LIGHTFEATUREFLAGS_ENV | LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_SSREFRACTION | LIGHTFEATUREFLAGS_SSREFLECTION)) + { + float reflectionHierarchyWeight = 0.0; // Max: 1.0 + float refractionHierarchyWeight = _EnableSSRefraction ? 0.0 : 1.0; // Max: 1.0 -// // Reflection / Refraction hierarchy is -// // 1. Screen Space Refraction / Reflection -// // 2. Environment Reflection / Refraction -// // 3. Sky Reflection / Refraction + // Reflection / Refraction hierarchy is + // 1. Screen Space Refraction / Reflection + // 2. Environment Reflection / Refraction + // 3. Sky Reflection / Refraction -// // Apply SSR. -// #if (defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR_TRANSPARENT)) || (!defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR)) -// { -// IndirectLighting indirect = EvaluateBSDF_ScreenSpaceReflection(posInput, preLightData, bsdfData, -// reflectionHierarchyWeight); -// AccumulateIndirectLighting(indirect, aggregateLighting); -// } -// #endif + // Apply SSR. + #if (defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR_TRANSPARENT)) || (!defined(_SURFACE_TYPE_TRANSPARENT) && !defined(_DISABLE_SSR)) + { + IndirectLighting indirect = EvaluateBSDF_ScreenSpaceReflection(posInput, preLightData, bsdfData, + reflectionHierarchyWeight); + AccumulateIndirectLighting(indirect, aggregateLighting); + } + #endif -// EnvLightData envLightData; -// if (envLightCount > 0) -// { -// envLightData = FetchEnvLight(envLightStart, 0); -// } -// else -// { -// envLightData = InitSkyEnvLightData(0); -// } + // Weight in the upper 20 bits, index in the lower 12 bits. + uint envLightWeightsAndIndices[MAX_REFLECTION_PROBES_PER_PIXEL]; + ZERO_INITIALIZE_ARRAY(uint, envLightWeightsAndIndices, MAX_REFLECTION_PROBES_PER_PIXEL); -// if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (_EnableSSRefraction > 0)) -// { -// IndirectLighting lighting = EvaluateBSDF_ScreenspaceRefraction(context, V, posInput, preLightData, bsdfData, envLightData, refractionHierarchyWeight); -// AccumulateIndirectLighting(lighting, aggregateLighting); -// } + i = 0; -// // Reflection probes are sorted by volume (in the increasing order). -// if (featureFlags & LIGHTFEATUREFLAGS_ENV) -// { -// context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES; - -// #if SCALARIZE_LIGHT_LOOP -// if (fastPath) -// { -// envLightStart = envStartFirstLane; -// } -// #endif - -// // Scalarized loop, same rationale of the punctual light version -// uint v_envLightListOffset = 0; -// uint v_envLightIdx = envLightStart; -// while (v_envLightListOffset < envLightCount) -// { -// v_envLightIdx = FetchIndex(envLightStart, v_envLightListOffset); -// uint s_envLightIdx = ScalarizeElementIndex(v_envLightIdx, fastPath); -// if (s_envLightIdx == -1) -// break; - -// EnvLightData s_envLightData = FetchEnvLight(s_envLightIdx); // Scalar load. - -// // If current scalar and vector light index match, we process the light. The v_envLightListOffset for current thread is increased. -// // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could -// // end up with a unique v_envLightIdx value that is smaller than s_envLightIdx hence being stuck in a loop. All the active lanes will not have this problem. -// if (s_envLightIdx >= v_envLightIdx) -// { -// v_envLightListOffset++; -// if (reflectionHierarchyWeight < 1.0) -// { -// EVALUATE_BSDF_ENV(s_envLightData, REFLECTION, reflection); -// } -// // Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation -// // However it is hard to deal with the fact that reflectionHierarchyWeight and refractionHierarchyWeight have not the same values, they are independent -// // The refraction probe is rarely used and happen only with sphere shape and high IOR. So we accept the slow path that use more simple code and -// // doesn't affect the performance of the reflection which is more important. -// // We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be a waste to not use screen and only cubemap. -// if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) -// { -// EVALUATE_BSDF_ENV(s_envLightData, REFRACTION, refraction); -// } -// } - -// } -// } + EnvLightData envLightData; + uint envLightIndex; + while (TryLoadReflectionProbeData(i, tile, zBin, envLightData, envLightIndex)) + { + uint weight = 1048575 - envLightData.logVolume; // Small volume -> high weight + uint indexAndWeight = (weight << 12) | envLightIndex; -// // Only apply the sky IBL if the sky texture is available -// if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled) -// { -// // The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression) -// context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY; - -// // The sky data are generated on the fly so the compiler can optimize the code -// EnvLightData envLightSky = InitSkyEnvLightData(0); - -// // Only apply the sky if we haven't yet accumulated enough IBL lighting. -// if (reflectionHierarchyWeight < 1.0) -// { -// EVALUATE_BSDF_ENV_SKY(envLightSky, REFLECTION, reflection); -// } - -// if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) -// { -// EVALUATE_BSDF_ENV_SKY(envLightSky, REFRACTION, refraction); -// } -// } -// } -// #undef EVALUATE_BSDF_ENV -// #undef EVALUATE_BSDF_ENV_SKY + // Insertion sort. We retain at most MAX_REFLECTION_PROBES_PER_PIXEL probes (based on their weight). + for (uint j = 0; j < MAX_REFLECTION_PROBES_PER_PIXEL; j++) + { + if ((envLightWeightsAndIndices[j] >> 12) < weight) + { + envLightWeightsAndIndices[j] = indexAndWeight; + break; + } + } + + i++; + } + + // Do not index out of bounds. + uint envLightCount = min(i, MAX_REFLECTION_PROBES_PER_PIXEL); + + if (envLightCount > 0) + { + uint firstIndex = envLightWeightsAndIndices[0] & ((1 << 12) - 1); + + envLightData = LoadReflectionProbeDataUnsafe(firstIndex); + } + else + { + envLightData = InitSkyEnvLightData(0); + } + + if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (_EnableSSRefraction > 0)) + { + IndirectLighting lighting = EvaluateBSDF_ScreenspaceRefraction(context, V, posInput, preLightData, bsdfData, envLightData, refractionHierarchyWeight); + AccumulateIndirectLighting(lighting, aggregateLighting); + } + + // Reflection probes are sorted by volume (in the increasing order). + if (featureFlags & LIGHTFEATUREFLAGS_ENV) + { + context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES; + + for (i = 0; i < envLightCount; i++) + { + uint envLightIndex = envLightWeightsAndIndices[i] & ((1 << 12) - 1); + + envLightData = LoadReflectionProbeDataUnsafe(envLightIndex); + + if (reflectionHierarchyWeight < 1.0) + { + EVALUATE_BSDF_ENV(envLightData, REFLECTION, reflection); + } + // Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation + // However it is hard to deal with the fact that reflectionHierarchyWeight and refractionHierarchyWeight have not the same values, they are independent + // The refraction probe is rarely used and happen only with sphere shape and high IOR. So we accept the slow path that use more simple code and + // doesn't affect the performance of the reflection which is more important. + // We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be a waste to not use screen and only cubemap. + if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) + { + EVALUATE_BSDF_ENV(envLightData, REFRACTION, refraction); + } + } + } + + // Only apply the sky IBL if the sky texture is available + if ((featureFlags & LIGHTFEATUREFLAGS_SKY) && _EnvLightSkyEnabled) + { + // The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression) + context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY; + + // The sky data are generated on the fly so the compiler can optimize the code + EnvLightData envLightSky = InitSkyEnvLightData(0); + + // Only apply the sky if we haven't yet accumulated enough IBL lighting. + if (reflectionHierarchyWeight < 1.0) + { + EVALUATE_BSDF_ENV_SKY(envLightSky, REFLECTION, reflection); + } + + if ((featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION) && (refractionHierarchyWeight < 1.0)) + { + EVALUATE_BSDF_ENV_SKY(envLightSky, REFRACTION, refraction); + } + } + } +#undef EVALUATE_BSDF_ENV +#undef EVALUATE_BSDF_ENV_SKY if (featureFlags & LIGHTFEATUREFLAGS_DIRECTIONAL) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 0141821387e..abb5ef146a1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -232,6 +232,19 @@ bool TryLoadAreaLightData(inout uint i, uint tile, uint zBin, out LightData data return success; } +bool TryLoadReflectionProbeData(inout uint i, uint tile, uint zBin, out EnvLightData data, out uint entityIndex) +{ + bool success = false; + + if (TryFindEntityIndex(i, tile, zBin, BOUNDEDENTITYCATEGORY_REFLECTION_PROBE, entityIndex)) + { + success = true; + data = _ReflectionProbeData[entityIndex]; + } + + return success; +} + bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) { bool success = false; @@ -276,13 +289,17 @@ bool TryLoadAreaLightData(uint i, uint tile, uint zBin, out LightData data) return b; } -bool TryLoadReflectionProbeData(uint i, uint tile, uint zBin, out EnvLightData data) +bool TryLoadReflectionProbeData(uint i, uint tile, uint zBin, out EnvLightData data, out uint entityIndex) { + entityIndex = UINT16_MAX; + bool b = false; uint n = _ReflectionProbeCount; if (i < n) { + entityIndex = i; + data = _ReflectionProbeData[i]; b = true; } @@ -322,6 +339,14 @@ bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) #endif // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) +// This call performs no bounds-checking. +// Only call this using the 'entityIndex' returned by TryLoadReflectionProbeData, and +// only if the call to TryLoadReflectionProbeData succeeded. +EnvLightData LoadReflectionProbeDataUnsafe(uint entityIndex) +{ + return _ReflectionProbeData[entityIndex]; +} + // In the first 8 bits of the target we store the max fade of the contact shadows as a byte void UnpackContactShadowData(uint contactShadowData, out float fade, out uint mask) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs index a180a954ca9..682d40e3049 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs @@ -583,7 +583,12 @@ void BuildEnvLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights // Skip the probe if the probe has never rendered (in realtime cases) or if texture is null if (!probeData.HasValidRenderedData()) continue; - HDRenderPipeline.PreprocessProbeData(ref processedProbe, probeData, hdCamera); + // 'probeBounds' are required to compute the volume of the probe (for sorting in the shader). + // The existing ray tracing code does not appear to have any bounds. Below is a workaround. + // TODO: we should probably use the influence volume of the probe for sorting. + Bounds probeBounds = new Bounds(Vector3.zero, Vector3.one); + + HDRenderPipeline.PreprocessProbeData(ref processedProbe, probeData, probeBounds, hdCamera); var envLightData = new EnvLightData(); m_RenderPipeline.GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData); From a653fa4f25b440979e51a791ff4626b7532b31af Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 19 Nov 2020 19:12:11 -0800 Subject: [PATCH 108/209] Fix TerrainLit --- .../Runtime/Material/TerrainLit/TerrainLit.shader | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader index 55098176b9c..53b951cebce 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader @@ -257,7 +257,8 @@ Shader "HDRP/TerrainLit" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl" From c3b17710fb197fbae7461eaad41119a33d3869d5 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 20 Nov 2020 16:53:09 -0800 Subject: [PATCH 109/209] Update the HDRI sky to use binned lighting --- .../Runtime/Sky/HDRISky/HDRISky.shader | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader index 8960eebf36b..1aa551bedc3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader @@ -8,15 +8,14 @@ Shader "Hidden/HDRP/Sky/HDRISky" #pragma target 4.5 #pragma only_renderers d3d11 playstation xboxone vulkan metal switch - #define LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - #pragma multi_compile_local _ SKY_MOTION #pragma multi_compile_local _ USE_FLOWMAP #pragma multi_compile _ DEBUG_DISPLAY #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define ATTRIBUTES_NEED_NORMAL #define ATTRIBUTES_NEED_TANGENT From adcc75238535a6c142d0b3645ce347061f31265f Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 20 Nov 2020 17:10:28 -0800 Subject: [PATCH 110/209] Fix the AxF shader --- .../Runtime/Material/AxF/AxF.shader | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader index 4a50d27ff0b..3434f32ceee 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader @@ -407,7 +407,8 @@ Shader "HDRP/AxF" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) From a60769b377db0acbcc294540b2f4c30b030393a6 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 20 Nov 2020 17:10:43 -0800 Subject: [PATCH 111/209] Remove GetTileSize() --- .../Lighting/LightLoop/TilingAndBinningUtilities.hlsl | 6 ------ 1 file changed, 6 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl index 538f670e569..ace64385c8d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/TilingAndBinningUtilities.hlsl @@ -1,12 +1,6 @@ #ifndef UNITY_TILINGANDBINNINGUTILITIES_INCLUDED #define UNITY_TILINGANDBINNINGUTILITIES_INCLUDED -// REMOVE!!! -uint GetTileSize() -{ - return 16; -} - // The HLSL preprocessor does not support the '%' operator. #define REMAINDER(A, N) ((A) - (N) * ((A) / (N))) #define CLEAR_SIGN_BIT(X) (asint(X) & INT_MAX) From 21be3e2203a7c8236188b9208ce932980291b8a8 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 20 Nov 2020 18:29:30 -0800 Subject: [PATCH 112/209] Fix insertion sort --- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 4b1e09a82cf..2e24d201638 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -292,8 +292,17 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh // Insertion sort. We retain at most MAX_REFLECTION_PROBES_PER_PIXEL probes (based on their weight). for (uint j = 0; j < MAX_REFLECTION_PROBES_PER_PIXEL; j++) { - if ((envLightWeightsAndIndices[j] >> 12) < weight) + uint arrayElementWeight = envLightWeightsAndIndices[j] >> 12; + + if (arrayElementWeight < weight) { + // Rotate the sub-array [j, last] to the right. + for (uint k = MAX_REFLECTION_PROBES_PER_PIXEL - 1; k > j; k--) + { + envLightWeightsAndIndices[k] = envLightWeightsAndIndices[k - 1]; + } + + // Perform the insertion. envLightWeightsAndIndices[j] = indexAndWeight; break; } From f50b5bab934a1730bb2c5ef266f149a79d1dd8ff Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 20 Nov 2020 18:43:34 -0800 Subject: [PATCH 113/209] Fix TerrainLit_Basemap (test fails???) --- .../Runtime/Material/TerrainLit/TerrainLit_Basemap.shader | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader index e87dbbbef17..b3882f1c813 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader @@ -209,7 +209,8 @@ Shader "Hidden/HDRP/TerrainLit_Basemap" // Supported shadow modes per light type #pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH - #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST + // Comment out the line to loop over all lights (for debugging purposes) + #define FINE_BINNING #define SHADERPASS SHADERPASS_FORWARD #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl" From 641b553b3f2d75d9c4486baa773faa3122a43678 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 20 Nov 2020 19:30:16 -0800 Subject: [PATCH 114/209] Const --- .../Runtime/Lighting/LightLoop/LightLoop.hlsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl index 2e24d201638..36f8ad0beb4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl @@ -312,7 +312,7 @@ void LightLoop( float3 V, PositionInputs posInput, uint tile, uint zBin, PreLigh } // Do not index out of bounds. - uint envLightCount = min(i, MAX_REFLECTION_PROBES_PER_PIXEL); + const uint envLightCount = min(i, MAX_REFLECTION_PROBES_PER_PIXEL); if (envLightCount > 0) { From c91c8587d8790e1ac7caf2b431fcca55d54be411 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Mon, 23 Nov 2020 19:04:16 -0800 Subject: [PATCH 115/209] Support ranged queries --- .../Lighting/LightLoop/LightLoopDef.hlsl | 137 +++++++++++++++++- 1 file changed, 132 insertions(+), 5 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index abb5ef146a1..bf167b6d8c9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -149,7 +149,7 @@ float4 SampleEnv(LightLoopContext lightLoopContext, int index, float3 texCoord, #if (defined(COARSE_BINNING) || defined(FINE_BINNING)) // Internal. Do not call directly. -uint TryFindEntityIndex(inout uint i, uint tile, uint zBin, uint category, out uint entityIndex) +uint TryFindEntityIndex(inout uint i, uint tile, uint2 zBinRange, uint category, out uint entityIndex) { entityIndex = UINT16_MAX; @@ -164,11 +164,15 @@ uint TryFindEntityIndex(inout uint i, uint tile, uint zBin, uint category, out u if (!isTileEmpty) // Avoid wasted work { - const uint zBinBufferIndex = ComputeZBinBufferIndex(zBin, category, unity_StereoEyeIndex); - const uint zBinRangeData = _zBinBuffer[zBinBufferIndex]; // {last << 16 | first} + const uint zBinBufferIndex0 = ComputeZBinBufferIndex(zBinRange[0], category, unity_StereoEyeIndex); + const uint zBinBufferIndex1 = ComputeZBinBufferIndex(zBinRange[1], category, unity_StereoEyeIndex); + const uint zBinRangeData0 = _zBinBuffer[zBinBufferIndex0]; // {last << 16 | first} + const uint zBinRangeData1 = _zBinBuffer[zBinBufferIndex1]; // {last << 16 | first} - const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); - const uint2 zBinEntityIndexRange = uint2(zBinRangeData & UINT16_MAX, zBinRangeData >> 16); + // Recall that entities are sorted by the z-coordinate. + // So we can take the smallest index from the first bin and the largest index from the last bin. + const uint2 tileEntityIndexRange = uint2(tileRangeData & UINT16_MAX, tileRangeData >> 16); + const uint2 zBinEntityIndexRange = uint2(zBinRangeData0 & UINT16_MAX, zBinRangeData1 >> 16); if (IntervalsOverlap(tileEntityIndexRange, zBinEntityIndexRange)) // Avoid wasted work { @@ -204,6 +208,14 @@ uint TryFindEntityIndex(inout uint i, uint tile, uint zBin, uint category, out u return b; } +// Internal. Do not call directly. +uint TryFindEntityIndex(inout uint i, uint tile, uint zBin, uint category, out uint entityIndex) +{ + uint2 zBinRange = uint2(zBin, zBin); + + return TryFindEntityIndex(i, tile, zBinRange, category, entityIndex); +} + bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData data) { bool success = false; @@ -218,6 +230,20 @@ bool TryLoadPunctualLightData(inout uint i, uint tile, uint zBin, out LightData return success; } +bool TryLoadPunctualLightData(inout uint i, uint tile, uint2 zBinRange, out LightData data) +{ + bool success = false; + + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBinRange, BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT, entityIndex)) + { + success = true; + data = _PunctualLightData[entityIndex]; + } + + return success; +} + bool TryLoadAreaLightData(inout uint i, uint tile, uint zBin, out LightData data) { bool success = false; @@ -232,6 +258,20 @@ bool TryLoadAreaLightData(inout uint i, uint tile, uint zBin, out LightData data return success; } +bool TryLoadAreaLightData(inout uint i, uint tile, uint2 zBinRange, out LightData data) +{ + bool success = false; + + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBinRange, BOUNDEDENTITYCATEGORY_AREA_LIGHT, entityIndex)) + { + success = true; + data = _AreaLightData[entityIndex]; + } + + return success; +} + bool TryLoadReflectionProbeData(inout uint i, uint tile, uint zBin, out EnvLightData data, out uint entityIndex) { bool success = false; @@ -245,6 +285,19 @@ bool TryLoadReflectionProbeData(inout uint i, uint tile, uint zBin, out EnvLight return success; } +bool TryLoadReflectionProbeData(inout uint i, uint tile, uint2 zBinRange, out EnvLightData data, out uint entityIndex) +{ + bool success = false; + + if (TryFindEntityIndex(i, tile, zBinRange, BOUNDEDENTITYCATEGORY_REFLECTION_PROBE, entityIndex)) + { + success = true; + data = _ReflectionProbeData[entityIndex]; + } + + return success; +} + bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) { bool success = false; @@ -259,6 +312,20 @@ bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) return success; } +bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) +{ + bool success = false; + + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBinRange, BOUNDEDENTITYCATEGORY_DECAL, entityIndex)) + { + success = true; + data = _DecalData[entityIndex]; + } + + return success; +} + #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) bool TryLoadPunctualLightData(uint i, uint tile, uint zBin, out LightData data) @@ -275,6 +342,20 @@ bool TryLoadPunctualLightData(uint i, uint tile, uint zBin, out LightData data) return b; } +bool TryLoadPunctualLightData(uint i, uint tile, uint2 zBinRange, out LightData data) +{ + bool b = false; + uint n = _PunctualLightCount; + + if (i < n) + { + data = _PunctualLightData[i]; + b = true; + } + + return b; +} + bool TryLoadAreaLightData(uint i, uint tile, uint zBin, out LightData data) { bool b = false; @@ -289,6 +370,20 @@ bool TryLoadAreaLightData(uint i, uint tile, uint zBin, out LightData data) return b; } +bool TryLoadAreaLightData(uint i, uint tile, uint2 zBinRange, out LightData data) +{ + bool b = false; + uint n = _AreaLightCount; + + if (i < n) + { + data = _AreaLightData[i]; + b = true; + } + + return b; +} + bool TryLoadReflectionProbeData(uint i, uint tile, uint zBin, out EnvLightData data, out uint entityIndex) { entityIndex = UINT16_MAX; @@ -307,6 +402,24 @@ bool TryLoadReflectionProbeData(uint i, uint tile, uint zBin, out EnvLightData d return b; } +bool TryLoadReflectionProbeData(uint i, uint tile, uint2 zBinRange, out EnvLightData data, out uint entityIndex) +{ + entityIndex = UINT16_MAX; + + bool b = false; + uint n = _ReflectionProbeCount; + + if (i < n) + { + entityIndex = i; + + data = _ReflectionProbeData[i]; + b = true; + } + + return b; +} + bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) { bool b = false; @@ -321,6 +434,20 @@ bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) return b; } +bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) +{ + bool b = false; + uint n = _DecalCount; + + if (i < n) + { + data = _DecalData[i]; + b = true; + } + + return b; +} + // bool TryLoadDensityVolumeDataDataAndBounds(uint i, uint tile, uint zBin, // out DensityVolumeEngineData data, out OrientedBBox bounds) // { From c70446cb02f11b9a3736d0111fdf569f7bb394af Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 24 Nov 2020 17:28:49 -0800 Subject: [PATCH 116/209] Add density volume support (merge DensityVolumeEngineData and OrientedBBox into DensityVolumeData) --- .../Lighting/AtmosphericScattering/Fog.cs | 5 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 73 ++++++++-------- .../Lighting/LightLoop/LightLoopDef.hlsl | 66 ++++++++++++--- .../LightLoop/ShaderVariablesLightLoop.hlsl | 15 ++-- .../VolumetricLighting/DensityVolume.cs | 11 ++- .../VolumeVoxelization.compute | 3 - .../VolumetricLighting/VolumetricLighting.cs | 84 ++++++------------- .../VolumetricLighting.cs.hlsl | 58 +++++++++---- .../HDRenderPipeline.LightLoop.cs | 8 -- .../HDRenderPipeline.RenderGraph.cs | 2 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 2 +- .../ShaderVariablesGlobal.cs.hlsl | 2 +- 12 files changed, 182 insertions(+), 147 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs index 167bc8930e8..982bce950ed 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs @@ -147,7 +147,10 @@ void UpdateShaderVariablesGlobalCBFogParameters(ref ShaderVariablesGlobal cb, HD cb._MipFogParameters = new Vector4(mipFogNear.value, mipFogFar.value, mipFogMaxMip.value, 0.0f); DensityVolumeArtistParameters param = new DensityVolumeArtistParameters(albedo.value, meanFreePath.value, anisotropy.value); - DensityVolumeEngineData data = param.ConvertToEngineData(); + + // What's this? There is no density volume here. + OrientedBBox invalidOBB = new OrientedBBox(); + DensityVolumeData data = param.ConvertToEngineData(invalidOBB); cb._HeightFogBaseScattering = data.scattering; cb._HeightFogBaseExtinction = data.extinction; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 7962f97c8d9..b2436bd89cb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -93,7 +93,7 @@ public BoundedEntityCollection(int xrViewCount, int[] maxEntityCountPerCategory) m_Views[i].areaLightData = new List(); m_Views[i].reflectionProbeData = new List(); m_Views[i].decalData = new List(); - m_Views[i].densityVolumeData = new List(); + m_Views[i].densityVolumeData = new List(); m_Views[i].entityBounds = new List(); m_Views[i].entitySortKeys = new ulong[m_MaxEntityCount]; } @@ -234,7 +234,7 @@ public void AddEntityData(int viewIndex, BoundedEntityCategory category, DecalDa } // These must be added in the sorted order! TODO: how to enforce this? - public void AddEntityData(int viewIndex, BoundedEntityCategory category, DensityVolumeEngineData data) + public void AddEntityData(int viewIndex, BoundedEntityCategory category, DensityVolumeData data) { Debug.Assert(category == BoundedEntityCategory.DensityVolume); m_Views[viewIndex].densityVolumeData.Add(data); @@ -310,12 +310,12 @@ public void CopyEntityDataToComputeBuffers() static int[] s_EntityDataSizesPerCategory = new int[(int)BoundedEntityCategory.Count] // Can't make it const in C#... { - Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight - Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight - Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe - Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal - Marshal.SizeOf(typeof(DensityVolumeEngineData)), // BoundedEntityCategory.DensityVolume - // Marshal.SizeOf(typeof(ProbeVolumeEngineData)) // BoundedEntityCategory.ProbeVolume + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight + Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe + Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal + Marshal.SizeOf(typeof(DensityVolumeData)), // BoundedEntityCategory.DensityVolume + // Marshal.SizeOf(typeof(ProbeVolumeEngineData)) // BoundedEntityCategory.ProbeVolume }; // The entity count is the same for all views. @@ -328,11 +328,11 @@ public void CopyEntityDataToComputeBuffers() struct ViewDependentData { // 1x list per category. - public List punctualLightData; - public List areaLightData; - public List reflectionProbeData; - public List decalData; - public List densityVolumeData; + public List punctualLightData; + public List areaLightData; + public List reflectionProbeData; + public List decalData; + public List densityVolumeData; // 1x list for all entites (sorted by category). public List entityBounds; @@ -2999,15 +2999,15 @@ bool TrivialRejectProbe(in ProcessedProbeData processedProbe, HDCamera hdCamera) return false; } - static uint CalculateProbeLogVolume(Bounds bounds) - { - //Notes: - // - 1+ term is to prevent having negative values in the log result - // - 1000* is too keep 3 digit after the dot while we truncate the result later - // - 1048575 is 2^20-1 as we pack the result on 20bit later - float boxVolume = 8f* bounds.extents.x * bounds.extents.y * bounds.extents.z; - uint logVolume = (uint)Math.Max(0, Math.Min((int)(1000 * Mathf.Log(1 + boxVolume, 1.05f)), 1048575)); - return logVolume; + static uint CalculateProbeLogVolume(Bounds bounds) + { + //Notes: + // - 1+ term is to prevent having negative values in the log result + // - 1000* is too keep 3 digit after the dot while we truncate the result later + // - 1048575 is 2^20-1 as we pack the result on 20bit later + float boxVolume = 8f* bounds.extents.x * bounds.extents.y * bounds.extents.z; + uint logVolume = (uint)Math.Max(0, Math.Min((int)(1000 * Mathf.Log(1 + boxVolume, 1.05f)), 1048575)); + return logVolume; } internal static void PreprocessReflectionProbeData(ref ProcessedProbeData processedData, VisibleReflectionProbe probe, HDCamera hdCamera) @@ -3261,13 +3261,13 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu } } - int densityVolumeCount = (densityVolumes.bounds != null) ? Math.Min(densityVolumes.bounds.Count, m_MaxDensityVolumesOnScreen) : 0; + int densityVolumeCount = (densityVolumes.data != null) ? Math.Min(densityVolumes.data.Count, m_MaxDensityVolumesOnScreen) : 0; for (int densityVolumeIndex = 0; densityVolumeIndex < densityVolumeCount; densityVolumeIndex++) { for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) { - float w = ComputeLinearDepth(densityVolumes.bounds[densityVolumeIndex].center, hdCamera, viewIndex); + float w = ComputeLinearDepth(densityVolumes.data[densityVolumeIndex].center, hdCamera, viewIndex); int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views ulong key = GenerateBoundedEntitySortingKey(densityVolumeIndex, BoundedEntityCategory.DensityVolume, d); @@ -3362,9 +3362,19 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // Density volumes are not lights and therefore should not affect light classification. LightFeatureFlags featureFlags = 0; - FiniteLightBound bounds = GetBoxVolumeDataAndBound(densityVolumes.bounds[densityVolumeIndex], BoundedEntityCategory.DensityVolume, featureFlags, worldToViewCR, viewIndex); - m_BoundedEntityCollection.AddEntityData(viewIndex, BoundedEntityCategory.DensityVolume, densityVolumes.density[densityVolumeIndex]); + OrientedBBox obb = new OrientedBBox(); + + obb.right = densityVolumes.data[densityVolumeIndex].right; + obb.extentX = densityVolumes.data[densityVolumeIndex].extentX; + obb.up = densityVolumes.data[densityVolumeIndex].up; + obb.extentY = densityVolumes.data[densityVolumeIndex].extentY; + obb.center = densityVolumes.data[densityVolumeIndex].center; + obb.extentZ = densityVolumes.data[densityVolumeIndex].extentZ; + + FiniteLightBound bounds = GetBoxVolumeDataAndBound(obb, BoundedEntityCategory.DensityVolume, featureFlags, worldToViewCR, viewIndex); + + m_BoundedEntityCollection.AddEntityData(viewIndex, BoundedEntityCategory.DensityVolume, densityVolumes.data[densityVolumeIndex]); m_BoundedEntityCollection.AddEntityBounds(viewIndex, BoundedEntityCategory.DensityVolume, bounds); } } @@ -4260,13 +4270,13 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H cb._Env2DAtlasScaleOffset[i * 4 + j] = m_TextureCaches.env2DAtlasScaleOffset[i][j]; } - // Light info + // Entity info cb._DirectionalLightCount = (uint)m_DirectionalLightData.Count; cb._PunctualLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight); cb._AreaLightCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight); cb._ReflectionProbeCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe); cb._DecalCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal); - // cb._DensityVolumeCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume); + cb._DensityVolumeCount = (uint)m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume); HDAdditionalLightData sunLightData = GetHDAdditionalLightData(m_CurrentSunLight); bool sunLightShadow = sunLightData != null && m_CurrentShadowSortedSunLightIndex >= 0; @@ -4325,13 +4335,6 @@ void PushLightDataGlobalParams(CommandBuffer cmd) cmd.SetGlobalBuffer(HDShaderIDs._DecalData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.Decal)); cmd.SetGlobalBuffer(HDShaderIDs._DensityVolumeData, m_BoundedEntityCollection.GetEntityDataBuffer(BoundedEntityCategory.DensityVolume)); - //cmd.SetGlobalInt( HDShaderIDs._DirectionalLightCount, m_DirectionalLightData.Count); - //cmd.SetGlobalInt( HDShaderIDs._PunctualLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight)); - //cmd.SetGlobalInt( HDShaderIDs._AreaLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight)); - //cmd.SetGlobalInt( HDShaderIDs._EnvLightCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.ReflectionProbe)); - //cmd.SetGlobalInt( HDShaderIDs._DecalCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.Decal)); - //cmd.SetGlobalInt( HDShaderIDs._DensityVolumeCount, m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume)); - // Hand it over so it can be used to construct light lists. BEC still owns (and manages) the buffer. m_TileAndClusterData.convexBoundsBuffer = m_BoundedEntityCollection.GetEntityBoundsBuffer(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index bf167b6d8c9..e1ccc32298f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -326,6 +326,34 @@ bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) return success; } +bool TryLoadDensityVolumeData(uint i, uint tile, uint zBin, out DensityVolumeData data) +{ + bool success = false; + + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBin, BOUNDEDENTITYCATEGORY_DENSITY_VOLUME, entityIndex)) + { + success = true; + data = _DensityVolumeData[i]; + } + + return success; +} + +bool TryLoadDensityVolumeData(uint i, uint tile, uint2 zBinRange, out DensityVolumeData data) +{ + bool success = false; + + uint entityIndex; + if (TryFindEntityIndex(i, tile, zBinRange, BOUNDEDENTITYCATEGORY_DENSITY_VOLUME, entityIndex)) + { + success = true; + data = _DensityVolumeData[i]; + } + + return success; +} + #else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) bool TryLoadPunctualLightData(uint i, uint tile, uint zBin, out LightData data) @@ -448,21 +476,33 @@ bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) return b; } -// bool TryLoadDensityVolumeDataDataAndBounds(uint i, uint tile, uint zBin, -// out DensityVolumeEngineData data, out OrientedBBox bounds) -// { -// bool b = false; -// uint n = _DensityVolumeCount; +bool TryLoadDensityVolumeData(uint i, uint tile, uint zBin, out DensityVolumeData data) +{ + bool b = false; + uint n = _DensityVolumeCount; + + if (i < n) + { + data = _DensityVolumeData[i]; + b = true; + } + + return b; +} + +bool TryLoadDensityVolumeData(uint i, uint tile, uint2 zBinRange, out DensityVolumeData data) +{ + bool b = false; + uint n = _DensityVolumeCount; -// if (i < n) -// { -// data = _DensityVolumeData[i]; -// bounds = _DensityVolumeBounds[i]; -// b = true; -// } + if (i < n) + { + data = _DensityVolumeData[i]; + b = true; + } -// return b; -// } + return b; +} #endif // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index 0f8100406d9..5bd90de1e74 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -1,5 +1,6 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightDefinition.cs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs.hlsl" +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl" // For 'DensityVolumeData' // It appears that, due to our include structure, we have to always declare these. StructuredBuffer _CoarseTileBuffer; @@ -11,16 +12,14 @@ StructuredBuffer _zBinBuffer; #endif // Directional lights + 1x list per BoundedEntityCategory. -StructuredBuffer _DirectionalLightData; +StructuredBuffer _DirectionalLightData; // NEVER ACCESS THESE DIRECTLY. -StructuredBuffer _PunctualLightData; -StructuredBuffer _AreaLightData; -StructuredBuffer _ReflectionProbeData; -// Defined elsewhere: -// StructuredBuffer _DecalData; -// StructuredBuffer _DensityVolumeData; -// StructuredBuffer _DensityVolumeBounds; +StructuredBuffer _PunctualLightData; +StructuredBuffer _AreaLightData; +StructuredBuffer _ReflectionProbeData; +// StructuredBuffer _DecalData; // Defined elsewhere +StructuredBuffer _DensityVolumeData; // Used by directional and spot lights TEXTURE2D(_CookieAtlas); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs index 6f7f75102ce..2e9c0a6f86c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs @@ -114,9 +114,16 @@ internal void Constrain() distanceFadeEnd = Mathf.Max(distanceFadeStart, distanceFadeEnd); } - internal DensityVolumeEngineData ConvertToEngineData() + internal DensityVolumeData ConvertToEngineData(OrientedBBox bounds) { - DensityVolumeEngineData data = new DensityVolumeEngineData(); + DensityVolumeData data = new DensityVolumeData(); + + data.right = bounds.right; + data.extentX = bounds.extentX; + data.up = bounds.up; + data.extentY = bounds.extentY; + data.center = bounds.center; + data.extentZ = bounds.extentZ; data.extinction = VolumeRenderingUtils.ExtinctionFromMeanFreePath(meanFreePath); data.scattering = VolumeRenderingUtils.ScatteringFromExtinctionAndAlbedo(data.extinction, (Vector3)(Vector4)albedo); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index f38c14d21a7..094eb779e30 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -38,9 +38,6 @@ // Inputs & outputs //-------------------------------------------------------------------------------------------------- -StructuredBuffer _DensityVolumeBounds; -StructuredBuffer _DensityVolumeData; - TEXTURE3D(_VolumeMaskAtlas); RW_TEXTURE3D(float4, _VBufferDensity); // RGB = sqrt(scattering), A = sqrt(extinction) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index f5f233240e4..50c71b3d74d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -8,8 +8,15 @@ namespace UnityEngine.Rendering.HighDefinition // Optimized version of 'DensityVolumeArtistParameters'. // TODO: pack better. This data structure contains a bunch of UNORMs. [GenerateHLSL] - struct DensityVolumeEngineData + struct DensityVolumeData { + public Vector3 right; + public float extentX; + public Vector3 up; + public float extentY; + public Vector3 center; + public float extentZ; + public Vector3 scattering; // [0, 1] public float extinction; // [0, 1] public Vector3 textureTiling; @@ -20,24 +27,6 @@ struct DensityVolumeEngineData public float rcpDistFadeLen; public Vector3 rcpNegFaceFade; public float endTimesRcpDistFadeLen; - - public static DensityVolumeEngineData GetNeutralValues() - { - DensityVolumeEngineData data; - - data.scattering = Vector3.zero; - data.extinction = 0; - data.textureIndex = -1; - data.textureTiling = Vector3.one; - data.textureScroll = Vector3.zero; - data.rcpPosFaceFade = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); - data.rcpNegFaceFade = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); - data.invertFade = 0; - data.rcpDistFadeLen = 0; - data.endTimesRcpDistFadeLen = 1; - - return data; - } } // struct VolumeProperties [GenerateHLSL(needAccessors = false, generateCBuffer = true)] @@ -47,7 +36,7 @@ unsafe struct ShaderVariablesVolumetric public fixed float _VBufferCoordToViewDirWS[ShaderConfig.k_XRMaxViewsForCBuffer * 16]; public float _VBufferUnitDepthTexelSpacing; - public uint _DensityVolumeCount; + public uint _Pad2_SVV; public float _CornetteShanksConstant; public uint _VBufferHistoryIsValid; @@ -74,7 +63,6 @@ unsafe struct ShaderVariablesVolumetric public uint _Pad1_SVV; } - class VolumeRenderingUtils { public static float MeanFreePathFromExtinction(float extinction) @@ -105,8 +93,7 @@ public static Vector3 AlbedoFromMeanFreePathAndScattering(float meanFreePath, Ve struct DensityVolumeList { - public List bounds; - public List density; + public List data; } struct VBufferParameters @@ -199,24 +186,19 @@ static Vector4 ComputeLogarithmicDepthDecodingParams(float nearPlane, float farP public partial class HDRenderPipeline { - ComputeShader m_VolumeVoxelizationCS = null; - ComputeShader m_VolumetricLightingCS = null; - ComputeShader m_VolumetricLightingFilteringCS = null; - - List m_VisibleVolumeBounds = null; - List m_VisibleVolumeData = null; - const int k_MaxVisibleVolumeCount = 512; + ComputeShader m_VolumeVoxelizationCS = null; + ComputeShader m_VolumetricLightingCS = null; + ComputeShader m_VolumetricLightingFilteringCS = null; - // Static keyword is required here else we get a "DestroyBuffer can only be called from the main thread" - ComputeBuffer m_VisibleVolumeBoundsBuffer = null; - ComputeBuffer m_VisibleVolumeDataBuffer = null; + List m_VisibleVolumeData = null; + const int k_MaxVisibleVolumeCount = 512; // These two buffers do not depend on the frameID and are therefore shared by all views. - RTHandle m_DensityBuffer; - RTHandle m_LightingBuffer; - Vector3Int m_CurrentVolumetricBufferSize; + RTHandle m_DensityBuffer; + RTHandle m_LightingBuffer; + Vector3Int m_CurrentVolumetricBufferSize; - ShaderVariablesVolumetric m_ShaderVariablesVolumetricCB = new ShaderVariablesVolumetric(); + ShaderVariablesVolumetric m_ShaderVariablesVolumetricCB = new ShaderVariablesVolumetric(); // Is the feature globally disabled? bool m_SupportVolumetrics = false; @@ -442,10 +424,7 @@ internal void CreateVolumetricLightingBuffers() Debug.Assert(m_DensityBuffer == null); Debug.Assert(m_LightingBuffer == null); - m_VisibleVolumeBounds = new List(); - m_VisibleVolumeData = new List(); - m_VisibleVolumeBoundsBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, Marshal.SizeOf(typeof(OrientedBBox))); - m_VisibleVolumeDataBuffer = new ComputeBuffer(k_MaxVisibleVolumeCount, Marshal.SizeOf(typeof(DensityVolumeEngineData))); + m_VisibleVolumeData = new List(); // Allocate the smallest possible 3D texture. // We will perform rescaling manually, in a custom manner, based on volume parameters. @@ -463,11 +442,7 @@ internal void DestroyVolumetricLightingBuffers() RTHandles.Release(m_LightingBuffer); RTHandles.Release(m_DensityBuffer); - CoreUtils.SafeRelease(m_VisibleVolumeDataBuffer); - CoreUtils.SafeRelease(m_VisibleVolumeBoundsBuffer); - - m_VisibleVolumeData = null; // free() - m_VisibleVolumeBounds = null; // free() + m_VisibleVolumeData = null; // free() } // Must be called AFTER UpdateVolumetricBufferParams. @@ -595,7 +570,6 @@ DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuff camOffset = camPosition; // Camera-relative } - m_VisibleVolumeBounds.Clear(); m_VisibleVolumeData.Clear(); // Collect all visible finite volume data, and upload it to the GPU. @@ -617,19 +591,14 @@ DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuff if (GeometryUtils.Overlap(obb, hdCamera.frustum, 6, 8)) { // TODO: cache these? - var data = volume.parameters.ConvertToEngineData(); + var data = volume.parameters.ConvertToEngineData(obb); - m_VisibleVolumeBounds.Add(obb); m_VisibleVolumeData.Add(data); } } - m_VisibleVolumeBoundsBuffer.SetData(m_VisibleVolumeBounds); - m_VisibleVolumeDataBuffer.SetData(m_VisibleVolumeData); - // Fill the struct with pointers in order to share the data with the light loop. - densityVolumes.bounds = m_VisibleVolumeBounds; - densityVolumes.density = m_VisibleVolumeData; + densityVolumes.data = m_VisibleVolumeData; return densityVolumes; } @@ -676,7 +645,6 @@ unsafe void UpdateShaderVariableslVolumetrics(ref ShaderVariablesVolumetric cb, for (int j = 0; j < 16; ++j) cb._VBufferCoordToViewDirWS[i * 16 + j] = m_PixelCoordToViewDirWS[i][j]; cb._VBufferUnitDepthTexelSpacing = HDUtils.ComputZPlaneTexelSpacing(1.0f, vFoV, resolution.y); - cb._DensityVolumeCount = (uint)m_VisibleVolumeBounds.Count; cb._CornetteShanksConstant = CornetteShanksPhasePartConstant(fog.anisotropy.value); cb._VBufferHistoryIsValid = hdCamera.volumetricHistoryIsValid ? 1u : 0u; @@ -766,8 +734,6 @@ VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCame static void VolumeVoxelizationPass( in VolumeVoxelizationParameters parameters, RTHandle densityBuffer, - ComputeBuffer visibleVolumeBoundsBuffer, - ComputeBuffer visibleVolumeDataBuffer, ComputeBuffer bigTileLightList, CommandBuffer cmd) { @@ -775,8 +741,6 @@ static void VolumeVoxelizationPass( in VolumeVoxelizationParameters parameters, cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList); cmd.SetComputeTextureParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VBufferDensity, densityBuffer); - cmd.SetComputeBufferParam( parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeBounds, visibleVolumeBoundsBuffer); - cmd.SetComputeBufferParam( parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeData, visibleVolumeDataBuffer); cmd.SetComputeTextureParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs._VolumeMaskAtlas, parameters.volumeAtlas); ConstantBuffer.Push(cmd, parameters.volumetricCB, parameters.voxelizationCS, HDShaderIDs._ShaderVariablesVolumetric); @@ -794,7 +758,7 @@ void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.VolumeVoxelization))) { var parameters = PrepareVolumeVoxelizationParameters(hdCamera, frameIndex); - VolumeVoxelizationPass(parameters, m_DensityBuffer, m_VisibleVolumeBoundsBuffer, m_VisibleVolumeDataBuffer, m_TileAndClusterData.bigTileLightList, cmd); + VolumeVoxelizationPass(parameters, m_DensityBuffer, m_TileAndClusterData.bigTileLightList, cmd); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl index 8525fb172f5..f3cf82d81f9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs.hlsl @@ -4,10 +4,16 @@ #ifndef VOLUMETRICLIGHTING_CS_HLSL #define VOLUMETRICLIGHTING_CS_HLSL -// Generated from UnityEngine.Rendering.HighDefinition.DensityVolumeEngineData +// Generated from UnityEngine.Rendering.HighDefinition.DensityVolumeData // PackingRules = Exact -struct DensityVolumeEngineData +struct DensityVolumeData { + float3 right; + float extentX; + float3 up; + float extentY; + float3 center; + float extentZ; float3 scattering; float extinction; float3 textureTiling; @@ -25,7 +31,7 @@ struct DensityVolumeEngineData CBUFFER_START(ShaderVariablesVolumetric) float4x4 _VBufferCoordToViewDirWS[2]; float _VBufferUnitDepthTexelSpacing; - uint _DensityVolumeCount; + uint _Pad2_SVV; float _CornetteShanksConstant; uint _VBufferHistoryIsValid; float4 _VBufferSampleOffset; @@ -47,45 +53,69 @@ CBUFFER_START(ShaderVariablesVolumetric) CBUFFER_END // -// Accessors for UnityEngine.Rendering.HighDefinition.DensityVolumeEngineData +// Accessors for UnityEngine.Rendering.HighDefinition.DensityVolumeData // -float3 GetScattering(DensityVolumeEngineData value) +float3 GetRight(DensityVolumeData value) +{ + return value.right; +} +float GetExtentX(DensityVolumeData value) +{ + return value.extentX; +} +float3 GetUp(DensityVolumeData value) +{ + return value.up; +} +float GetExtentY(DensityVolumeData value) +{ + return value.extentY; +} +float3 GetCenter(DensityVolumeData value) +{ + return value.center; +} +float GetExtentZ(DensityVolumeData value) +{ + return value.extentZ; +} +float3 GetScattering(DensityVolumeData value) { return value.scattering; } -float GetExtinction(DensityVolumeEngineData value) +float GetExtinction(DensityVolumeData value) { return value.extinction; } -float3 GetTextureTiling(DensityVolumeEngineData value) +float3 GetTextureTiling(DensityVolumeData value) { return value.textureTiling; } -int GetTextureIndex(DensityVolumeEngineData value) +int GetTextureIndex(DensityVolumeData value) { return value.textureIndex; } -float3 GetTextureScroll(DensityVolumeEngineData value) +float3 GetTextureScroll(DensityVolumeData value) { return value.textureScroll; } -int GetInvertFade(DensityVolumeEngineData value) +int GetInvertFade(DensityVolumeData value) { return value.invertFade; } -float3 GetRcpPosFaceFade(DensityVolumeEngineData value) +float3 GetRcpPosFaceFade(DensityVolumeData value) { return value.rcpPosFaceFade; } -float GetRcpDistFadeLen(DensityVolumeEngineData value) +float GetRcpDistFadeLen(DensityVolumeData value) { return value.rcpDistFadeLen; } -float3 GetRcpNegFaceFade(DensityVolumeEngineData value) +float3 GetRcpNegFaceFade(DensityVolumeData value) { return value.rcpNegFaceFade; } -float GetEndTimesRcpDistFadeLen(DensityVolumeEngineData value) +float GetEndTimesRcpDistFadeLen(DensityVolumeData value) { return value.endTimesRcpDistFadeLen; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index a4e9514a4b6..75e1cb276de 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -544,14 +544,10 @@ class VolumeVoxelizationPassData public VolumeVoxelizationParameters parameters; public TextureHandle densityBuffer; public ComputeBufferHandle bigTileLightListBuffer; - public ComputeBuffer visibleVolumeBoundsBuffer; - public ComputeBuffer visibleVolumeDataBuffer; } TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, HDCamera hdCamera, - ComputeBuffer visibleVolumeBoundsBuffer, - ComputeBuffer visibleVolumeDataBuffer, ComputeBufferHandle bigTileLightList, int frameIndex) { @@ -562,8 +558,6 @@ TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, builder.EnableAsyncCompute(hdCamera.frameSettings.VolumeVoxelizationRunsAsync()); passData.parameters = PrepareVolumeVoxelizationParameters(hdCamera, frameIndex); - passData.visibleVolumeBoundsBuffer = visibleVolumeBoundsBuffer; - passData.visibleVolumeDataBuffer = visibleVolumeDataBuffer; passData.bigTileLightListBuffer = builder.ReadComputeBuffer(bigTileLightList); float tileSize = 0; @@ -576,8 +570,6 @@ TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, { VolumeVoxelizationPass( data.parameters, data.densityBuffer, - data.visibleVolumeBoundsBuffer, - data.visibleVolumeDataBuffer, data.bigTileLightListBuffer, ctx.cmd); }); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 687d4e69afd..6c17c490954 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -96,7 +96,7 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, lightingBuffers.contactShadowsBuffer = RenderContactShadows(m_RenderGraph, hdCamera, msaa ? prepassOutput.depthValuesMSAA : prepassOutput.depthPyramidTexture, gpuLightListOutput, GetDepthBufferMipChainInfo().mipLevelOffsets[1].y); - var volumetricDensityBuffer = VolumeVoxelizationPass(m_RenderGraph, hdCamera, m_VisibleVolumeBoundsBuffer, m_VisibleVolumeDataBuffer, gpuLightListOutput.bigTileLightList, m_FrameCount); + var volumetricDensityBuffer = VolumeVoxelizationPass(m_RenderGraph, hdCamera, gpuLightListOutput.bigTileLightList, m_FrameCount); shadowResult = RenderShadows(m_RenderGraph, hdCamera, cullingResults); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index e2711a41c8e..55c841f72ad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -121,7 +121,7 @@ unsafe struct ShaderVariablesGlobal public float _MaxFogDistance; public Vector4 _FogColor; // color in rgb public float _FogColorMode; - public float _Pad0; + public float _DensityVolumeCount; public float _Pad1; public float _Pad2; public Vector4 _MipFogParameters; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 9a714e8bc94..017edc07bd9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -52,7 +52,7 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) float _MaxFogDistance; float4 _FogColor; float _FogColorMode; - float _Pad0; + float _DensityVolumeCount; float _Pad1; float _Pad2; float4 _MipFogParameters; From 1dd8fc3e32565cd87cf0ebb0b62b88d6b13841c9 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 24 Nov 2020 18:30:21 -0800 Subject: [PATCH 117/209] Fix volume voxelization pass --- .../VolumeVoxelization.compute | 113 +++++++----------- 1 file changed, 40 insertions(+), 73 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index 094eb779e30..e34c2013e24 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -10,9 +10,8 @@ #pragma kernel VolumeVoxelizationBruteforce VolumeVoxelization=VolumeVoxelizationBruteforce LIGHTLOOP_DISABLE_TILE_AND_CLUSTER #pragma kernel VolumeVoxelizationTiled VolumeVoxelization=VolumeVoxelizationTiled -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - #define USE_BIG_TILE_LIGHTLIST -#endif +// Comment out the line to loop over all lights (for debugging purposes) +#define COARSE_BINNING #ifdef VL_PRESET_OPTIMAL // E.g. for 1080p: (1920/8)x(1080/8)x(64) = 2,073,600 voxels @@ -71,7 +70,7 @@ float ComputeFadeFactor(float3 coordNDC, float dist, return dstF * (invertFade ? (1 - fade) : fade); } -float SampleVolumeMask(DensityVolumeEngineData volumeData, float3 voxelCenterNDC, float3 duvw_dx, float3 duvw_dy, float3 duvw_dz) +float SampleVolumeMask(DensityVolumeData volumeData, float3 voxelCenterNDC, float3 duvw_dx, float3 duvw_dy, float3 duvw_dz) { // Scale and bias the UVWs and then take fractional part, will be in [0,1] range. float3 voxelCenterUVW = frac(voxelCenterNDC * volumeData.textureTiling + volumeData.textureScroll); @@ -105,50 +104,14 @@ float SampleVolumeMask(DensityVolumeEngineData volumeData, float3 voxelCenterNDC return SAMPLE_TEXTURE3D_LOD(_VolumeMaskAtlas, s_trilinear_repeat_sampler, voxelCenterUVW, lod).a; } -void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, JitteredRay ray) +void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay ray, float cosTheta) { - uint volumeCount, volumeStart; - -#ifdef USE_BIG_TILE_LIGHTLIST - // Offset for stereo rendering - tileIndex += unity_StereoEyeIndex * _NumTileBigTileX * _NumTileBigTileY; - - // The "big tile" list contains the number of objects contained within the tile followed by the - // list of object indices. Note that while objects are already sorted by type, we don't know the - // number of each type of objects (e.g. lights), so we should remember to break out of the loop. - volumeCount = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE * tileIndex]; - volumeStart = MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE * tileIndex + 1; - - // For now, iterate through all the objects to determine the correct range. - // TODO: precompute this, of course. - { - uint offset = 0; - - for (; offset < volumeCount; offset++) - { - uint objectIndex = FetchIndex(volumeStart, offset); - - if (objectIndex >= _DensityVolumeIndexShift) - { - // We have found the first density volume. - break; - } - } - - volumeStart += offset; - volumeCount -= offset; - } - -#else // USE_BIG_TILE_LIGHTLIST - - volumeCount = _DensityVolumeCount; - volumeStart = 0; - -#endif // USE_BIG_TILE_LIGHTLIST - float t0 = DecodeLogarithmicDepthGeneralized(0, _VBufferDistanceDecodingParams); float de = _VBufferRcpSliceCount; // Log-encoded distance between slices + float z0 = t0 * cosTheta; // Distance to linear depth + uint zBin0 = ComputeZBinIndex(z0); + for (uint slice = 0; slice < _VBufferSliceCount; slice++) { uint3 voxelCoord = uint3(posInput.positionSS, slice + _VBufferSliceCount * unity_StereoEyeIndex); @@ -158,6 +121,9 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, Jitter float dt = t1 - t0; float t = t0 + 0.5 * dt; + float z1 = t1 * cosTheta; // Distance to linear depth + uint zBin1 = ComputeZBinIndex(z1); + float3 voxelCenterWS = ray.originWS + t * ray.centerDirWS; // TODO: the fog value at the center is likely different from the average value across the voxel. @@ -167,23 +133,18 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, Jitter // Start by sampling the height fog. float3 voxelScattering = _HeightFogBaseScattering.xyz * heightMultiplier; - float voxelExtinction = _HeightFogBaseExtinction * heightMultiplier; - - for (uint volumeOffset = 0; volumeOffset < volumeCount; volumeOffset++) - { - #ifdef USE_BIG_TILE_LIGHTLIST - uint volumeIndex = FetchIndex(volumeStart, volumeOffset) - _DensityVolumeIndexShift; - #else - uint volumeIndex = FetchIndex(volumeStart, volumeOffset); - #endif + float voxelExtinction = _HeightFogBaseExtinction * heightMultiplier; - const OrientedBBox obb = _DensityVolumeBounds[volumeIndex]; + uint i = 0; - const float3x3 obbFrame = float3x3(obb.right, obb.up, cross(obb.up, obb.right)); - const float3 obbExtents = float3(obb.extentX, obb.extentY, obb.extentZ); + DensityVolumeData volumeData; + while (TryLoadDensityVolumeData(i, tile, uint2(zBin0, zBin1), volumeData)) + { + const float3x3 obbFrame = float3x3(volumeData.right, volumeData.up, cross(volumeData.up, volumeData.right)); + const float3 obbExtents = float3(volumeData.extentX, volumeData.extentY, volumeData.extentZ); // Express the voxel center in the local coordinate system of the box. - const float3 voxelCenterBS = mul(voxelCenterWS - obb.center, transpose(obbFrame)); + const float3 voxelCenterBS = mul(voxelCenterWS - volumeData.center, transpose(obbFrame)); const float3 voxelCenterCS = (voxelCenterBS * rcp(obbExtents)); const float3 voxelAxisRightBS = mul(ray.xDirDerivWS, transpose(obbFrame)); @@ -266,31 +227,34 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tileIndex, Jitter float dist = t; overlapFraction *= ComputeFadeFactor(voxelCenterNDC, dist, - _DensityVolumeData[volumeIndex].rcpPosFaceFade, - _DensityVolumeData[volumeIndex].rcpNegFaceFade, - _DensityVolumeData[volumeIndex].invertFade, - _DensityVolumeData[volumeIndex].rcpDistFadeLen, - _DensityVolumeData[volumeIndex].endTimesRcpDistFadeLen); + volumeData.rcpPosFaceFade, + volumeData.rcpNegFaceFade, + volumeData.invertFade, + volumeData.rcpDistFadeLen, + volumeData.endTimesRcpDistFadeLen); // Sample the volumeMask. - if (_DensityVolumeData[volumeIndex].textureIndex != -1) + if (volumeData.textureIndex != -1) { float3 xDerivUVW = (0.5 * t) * voxelAxisRightBS * rcp(obbExtents); float3 yDerivUVW = (0.5 * t) * voxelAxisUpBS * rcp(obbExtents); float3 zDerivUVW = (0.5 * dt) * voxelAxisForwardBS * rcp(obbExtents); - overlapFraction *= SampleVolumeMask(_DensityVolumeData[volumeIndex], voxelCenterNDC, xDerivUVW, yDerivUVW, zDerivUVW); + overlapFraction *= SampleVolumeMask(volumeData, voxelCenterNDC, xDerivUVW, yDerivUVW, zDerivUVW); } // There is an overlap. Sample the 3D texture, or load the constant value. - voxelScattering += overlapFraction * _DensityVolumeData[volumeIndex].scattering; - voxelExtinction += overlapFraction * _DensityVolumeData[volumeIndex].extinction; + voxelScattering += overlapFraction * volumeData.scattering; + voxelExtinction += overlapFraction * volumeData.extinction; } + + i++; } _VBufferDensity[voxelCoord] = float4(voxelScattering, voxelExtinction); - t0 = t1; + t0 = t1; + zBin0 = zBin1; } } @@ -305,15 +269,15 @@ void VolumeVoxelization(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 voxelCoord = groupOffset + groupThreadId; #ifdef VL_PRESET_OPTIMAL // The entire thread group is within the same light tile. - uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE_BIG_TILE; + uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE; #else // No compile-time optimizations, no scalarization. - // If _VBufferVoxelSize is not a power of 2 or > TILE_SIZE_BIG_TILE, a voxel may straddle + // If _VBufferVoxelSize is not a power of 2 or > TILE_SIZE, a voxel may straddle // a tile boundary. This means different voxel subsamples may belong to different tiles. // We accept this error, and simply use the coordinates of the center of the voxel. - uint2 tileCoord = (uint2)((voxelCoord + 0.5) * _VBufferVoxelSize / TILE_SIZE_BIG_TILE); + uint2 tileCoord = (uint2)((voxelCoord + 0.5) * _VBufferVoxelSize / TILE_SIZE); #endif - uint tileIndex = tileCoord.x + _NumTileBigTileX * tileCoord.y; + uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); // Reminder: our voxels are sphere-capped right frustums (truncated right pyramids). // The curvature of the front and back faces is quite gentle, so we can use @@ -345,9 +309,12 @@ void VolumeVoxelization(uint3 dispatchThreadId : SV_DispatchThreadID, ray.yDirDerivWS = cross(ray.xDirDerivWS, ray.centerDirWS); // Will have the length of 'unitDistFaceSize' by construction ray.jitterDirWS = ray.centerDirWS; // TODO - PositionInputs posInput = GetPositionInput(voxelCoord, _VBufferViewportSize.zw, tileCoord); + // We will use the value of the cosine to convert distances from the camera to linear depth values. + float cosTheta = dot(F, ray.jitterDirWS); + + PositionInputs posInput = GetPositionInput(voxelCoord, _VBufferViewportSize.zw); ApplyCameraRelativeXR(ray.originWS); - FillVolumetricDensityBuffer(posInput, tileIndex, ray); + FillVolumetricDensityBuffer(posInput, tile, ray, cosTheta); } From 81c39b8b4c4f666370d14c4b0b61cca4943047b0 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 24 Nov 2020 18:43:51 -0800 Subject: [PATCH 118/209] Share more code --- .../Lighting/LightLoop/LightLoopDef.hlsl | 195 ++++-------------- 1 file changed, 43 insertions(+), 152 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index e1ccc32298f..4840656851f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -208,6 +208,49 @@ uint TryFindEntityIndex(inout uint i, uint tile, uint2 zBinRange, uint category, return b; } +#else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) + +// Internal. Do not call directly. +uint TryFindEntityIndex(inout uint i, uint tile, uint2 zBinRange, uint category, out uint entityIndex) +{ + entityIndex = UINT16_MAX; + + bool b = false; + uint n; + + switch (category) + { + case BOUNDEDENTITYCATEGORY_PUNCTUAL_LIGHT: + n = _PunctualLightCount; + break; + case BOUNDEDENTITYCATEGORY_AREA_LIGHT: + n = _AreaLightCount; + break; + case BOUNDEDENTITYCATEGORY_REFLECTION_PROBE: + n = _ReflectionProbeCount; + break; + case BOUNDEDENTITYCATEGORY_DECAL: + n = _DecalCount; + break; + case BOUNDEDENTITYCATEGORY_DENSITY_VOLUME: + n = _DensityVolumeCount; + break; + default: + n = 0; + break; + } + + if (i < n) + { + entityIndex = i; + b = true; + } + + return b; +} + +#endif // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) + // Internal. Do not call directly. uint TryFindEntityIndex(inout uint i, uint tile, uint zBin, uint category, out uint entityIndex) { @@ -354,158 +397,6 @@ bool TryLoadDensityVolumeData(uint i, uint tile, uint2 zBinRange, out DensityVol return success; } -#else // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) - -bool TryLoadPunctualLightData(uint i, uint tile, uint zBin, out LightData data) -{ - bool b = false; - uint n = _PunctualLightCount; - - if (i < n) - { - data = _PunctualLightData[i]; - b = true; - } - - return b; -} - -bool TryLoadPunctualLightData(uint i, uint tile, uint2 zBinRange, out LightData data) -{ - bool b = false; - uint n = _PunctualLightCount; - - if (i < n) - { - data = _PunctualLightData[i]; - b = true; - } - - return b; -} - -bool TryLoadAreaLightData(uint i, uint tile, uint zBin, out LightData data) -{ - bool b = false; - uint n = _AreaLightCount; - - if (i < n) - { - data = _AreaLightData[i]; - b = true; - } - - return b; -} - -bool TryLoadAreaLightData(uint i, uint tile, uint2 zBinRange, out LightData data) -{ - bool b = false; - uint n = _AreaLightCount; - - if (i < n) - { - data = _AreaLightData[i]; - b = true; - } - - return b; -} - -bool TryLoadReflectionProbeData(uint i, uint tile, uint zBin, out EnvLightData data, out uint entityIndex) -{ - entityIndex = UINT16_MAX; - - bool b = false; - uint n = _ReflectionProbeCount; - - if (i < n) - { - entityIndex = i; - - data = _ReflectionProbeData[i]; - b = true; - } - - return b; -} - -bool TryLoadReflectionProbeData(uint i, uint tile, uint2 zBinRange, out EnvLightData data, out uint entityIndex) -{ - entityIndex = UINT16_MAX; - - bool b = false; - uint n = _ReflectionProbeCount; - - if (i < n) - { - entityIndex = i; - - data = _ReflectionProbeData[i]; - b = true; - } - - return b; -} - -bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) -{ - bool b = false; - uint n = _DecalCount; - - if (i < n) - { - data = _DecalData[i]; - b = true; - } - - return b; -} - -bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) -{ - bool b = false; - uint n = _DecalCount; - - if (i < n) - { - data = _DecalData[i]; - b = true; - } - - return b; -} - -bool TryLoadDensityVolumeData(uint i, uint tile, uint zBin, out DensityVolumeData data) -{ - bool b = false; - uint n = _DensityVolumeCount; - - if (i < n) - { - data = _DensityVolumeData[i]; - b = true; - } - - return b; -} - -bool TryLoadDensityVolumeData(uint i, uint tile, uint2 zBinRange, out DensityVolumeData data) -{ - bool b = false; - uint n = _DensityVolumeCount; - - if (i < n) - { - data = _DensityVolumeData[i]; - b = true; - } - - return b; -} - -#endif // !(defined(COARSE_BINNING) || defined(FINE_BINNING)) - // This call performs no bounds-checking. // Only call this using the 'entityIndex' returned by TryLoadReflectionProbeData, and // only if the call to TryLoadReflectionProbeData succeeded. From ddb5206635e3a5f14446df743b1bcda9739bab04 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Tue, 24 Nov 2020 19:13:52 -0800 Subject: [PATCH 119/209] Fix volume voxelization pass (2) --- .../VolumeVoxelization.compute | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index e34c2013e24..bf12c76f3c8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -5,13 +5,10 @@ // #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -#pragma kernel VolumeVoxelizationBruteforceOptimal VolumeVoxelization=VolumeVoxelizationBruteforceOptimal LIGHTLOOP_DISABLE_TILE_AND_CLUSTER VL_PRESET_OPTIMAL -#pragma kernel VolumeVoxelizationTiledOptimal VolumeVoxelization=VolumeVoxelizationTiledOptimal VL_PRESET_OPTIMAL -#pragma kernel VolumeVoxelizationBruteforce VolumeVoxelization=VolumeVoxelizationBruteforce LIGHTLOOP_DISABLE_TILE_AND_CLUSTER -#pragma kernel VolumeVoxelizationTiled VolumeVoxelization=VolumeVoxelizationTiled - -// Comment out the line to loop over all lights (for debugging purposes) -#define COARSE_BINNING +#pragma kernel VolumeVoxelizationBruteforceOptimal VolumeVoxelization=VolumeVoxelizationBruteforceOptimal VL_PRESET_OPTIMAL +#pragma kernel VolumeVoxelizationTiledOptimal VolumeVoxelization=VolumeVoxelizationTiledOptimal COARSE_BINNING VL_PRESET_OPTIMAL +#pragma kernel VolumeVoxelizationBruteforce VolumeVoxelization=VolumeVoxelizationBruteforce +#pragma kernel VolumeVoxelizationTiled VolumeVoxelization=VolumeVoxelizationTiled COARSE_BINNING #ifdef VL_PRESET_OPTIMAL // E.g. for 1080p: (1920/8)x(1080/8)x(64) = 2,073,600 voxels @@ -104,12 +101,12 @@ float SampleVolumeMask(DensityVolumeData volumeData, float3 voxelCenterNDC, floa return SAMPLE_TEXTURE3D_LOD(_VolumeMaskAtlas, s_trilinear_repeat_sampler, voxelCenterUVW, lod).a; } -void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay ray, float cosTheta) +void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay ray, float cosRay) { float t0 = DecodeLogarithmicDepthGeneralized(0, _VBufferDistanceDecodingParams); float de = _VBufferRcpSliceCount; // Log-encoded distance between slices - float z0 = t0 * cosTheta; // Distance to linear depth + float z0 = t0 * cosRay; // Distance to linear depth uint zBin0 = ComputeZBinIndex(z0); for (uint slice = 0; slice < _VBufferSliceCount; slice++) @@ -121,7 +118,7 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay float dt = t1 - t0; float t = t0 + 0.5 * dt; - float z1 = t1 * cosTheta; // Distance to linear depth + float z1 = t1 * cosRay; // Distance to linear depth uint zBin1 = ComputeZBinIndex(z1); float3 voxelCenterWS = ray.originWS + t * ray.centerDirWS; @@ -267,17 +264,20 @@ void VolumeVoxelization(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupOffset = groupId * GROUP_SIZE_1D; uint2 voxelCoord = groupOffset + groupThreadId; + // We would like to determine the screen pixel (at the full resolution) which + // the jittered ray corresponds to. The exact solution can be obtained by intersecting + // the ray with the screen plane, e.i. (ViewSpace(jitterDirWS).z = 1). That's a little expensive. + // So, as an approximation, we ignore the curvature of the frustum. + uint2 pixelCoord = (uint2)((voxelCoord + 0.5) * _VBufferVoxelSize); + #ifdef VL_PRESET_OPTIMAL // The entire thread group is within the same light tile. uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE; + uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); #else // No compile-time optimizations, no scalarization. - // If _VBufferVoxelSize is not a power of 2 or > TILE_SIZE, a voxel may straddle - // a tile boundary. This means different voxel subsamples may belong to different tiles. - // We accept this error, and simply use the coordinates of the center of the voxel. - uint2 tileCoord = (uint2)((voxelCoord + 0.5) * _VBufferVoxelSize / TILE_SIZE); + uint tile = ComputeTileIndex(pixelCoord); #endif - uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); // Reminder: our voxels are sphere-capped right frustums (truncated right pyramids). // The curvature of the front and back faces is quite gentle, so we can use @@ -310,11 +310,11 @@ void VolumeVoxelization(uint3 dispatchThreadId : SV_DispatchThreadID, ray.jitterDirWS = ray.centerDirWS; // TODO // We will use the value of the cosine to convert distances from the camera to linear depth values. - float cosTheta = dot(F, ray.jitterDirWS); + float cosRay = dot(F, ray.jitterDirWS); PositionInputs posInput = GetPositionInput(voxelCoord, _VBufferViewportSize.zw); ApplyCameraRelativeXR(ray.originWS); - FillVolumetricDensityBuffer(posInput, tile, ray, cosTheta); + FillVolumetricDensityBuffer(posInput, tile, ray, cosRay); } From f0d5703f025067a799cd05320179f56ddb6d3652 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Wed, 25 Nov 2020 17:06:07 -0800 Subject: [PATCH 120/209] Fix a camera-relative bug --- .../Runtime/Lighting/LightLoop/LightLoop.cs | 19 ++++++++++++++++--- .../VolumetricLighting/VolumetricLighting.cs | 2 +- .../ShaderLibrary/ShaderVariablesGlobal.cs | 2 +- .../ShaderVariablesGlobal.cs.hlsl | 2 +- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index b2436bd89cb..3af0cb89490 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -2597,10 +2597,16 @@ static Vector3 ComputeWorldSpaceCentroidOfBoundedEntity(HDProbe probe) return (Vector3)probe.influenceToWorld.GetColumn(3); } - static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewIndex) + static float ComputeLinearDepth(Vector3 positionWS, HDCamera hdCamera, int viewIndex, bool forceRWS = false) { Matrix4x4 viewMatrix = GetWorldToViewMatrix(hdCamera, viewIndex); // Non-RWS - Vector3 positionVS = viewMatrix.MultiplyPoint(positionWS); + + if (forceRWS && (ShaderConfig.s_CameraRelativeRendering != 0)) + { + viewMatrix.SetColumn(3, new Vector4(0, 0, 0, 1)); + } + + Vector3 positionVS = viewMatrix.MultiplyPoint(positionWS); Debug.Assert(viewMatrix.MultiplyVector(hdCamera.camera.transform.forward).z > 0, "The view space z-axis must point forward!"); @@ -3267,7 +3273,8 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu { for (int viewIndex = 0; viewIndex < xrViewCount; viewIndex++) { - float w = ComputeLinearDepth(densityVolumes.data[densityVolumeIndex].center, hdCamera, viewIndex); + // The OBB is RWS. + float w = ComputeLinearDepth(densityVolumes.data[densityVolumeIndex].center, hdCamera, viewIndex, forceRWS: true); int d = ComputeFixedPointLogDepth(w, hdCamera.camera.farClipPlane); // Assume XR uses the same far plane for all views ulong key = GenerateBoundedEntitySortingKey(densityVolumeIndex, BoundedEntityCategory.DensityVolume, d); @@ -3346,6 +3353,12 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu { Matrix4x4 worldToViewCR = GetWorldToViewMatrix(hdCamera, viewIndex); + if (ShaderConfig.s_CameraRelativeRendering != 0) + { + // The OBBs are camera-relative, the matrix is not. Fix it. + worldToViewCR.SetColumn(3, new Vector4(0, 0, 0, 1)); + } + int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.DensityVolume); int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.DensityVolume); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 50c71b3d74d..0b797892376 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -582,7 +582,7 @@ DensityVolumeList PrepareVisibleDensityVolumeList(HDCamera hdCamera, CommandBuff // TODO: cache these? var obb = new OrientedBBox(Matrix4x4.TRS(volume.transform.position, volume.transform.rotation, volume.parameters.size)); - // Handle camera-relative rendering. + // Make the OBB camera-relative. obb.center -= camOffset; // Frustum cull on the CPU for now. TODO: do it on the GPU. diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs index 55c841f72ad..e905b2f081e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs @@ -121,7 +121,7 @@ unsafe struct ShaderVariablesGlobal public float _MaxFogDistance; public Vector4 _FogColor; // color in rgb public float _FogColorMode; - public float _DensityVolumeCount; + public uint _DensityVolumeCount; public float _Pad1; public float _Pad2; public Vector4 _MipFogParameters; diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl index 017edc07bd9..4baa00ffbff 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesGlobal.cs.hlsl @@ -52,7 +52,7 @@ GLOBAL_CBUFFER_START(ShaderVariablesGlobal, b0) float _MaxFogDistance; float4 _FogColor; float _FogColorMode; - float _DensityVolumeCount; + uint _DensityVolumeCount; float _Pad1; float _Pad2; float4 _MipFogParameters; From 3e034ec3c9e410d827fda5749ae27100f7431831 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 26 Nov 2020 18:38:03 -0800 Subject: [PATCH 121/209] Fix copy-paste fail --- .../Runtime/Lighting/LightLoop/LightLoopDef.hlsl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index 4840656851f..c00e62db89e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -377,7 +377,7 @@ bool TryLoadDensityVolumeData(uint i, uint tile, uint zBin, out DensityVolumeDat if (TryFindEntityIndex(i, tile, zBin, BOUNDEDENTITYCATEGORY_DENSITY_VOLUME, entityIndex)) { success = true; - data = _DensityVolumeData[i]; + data = _DensityVolumeData[entityIndex]; } return success; @@ -391,7 +391,7 @@ bool TryLoadDensityVolumeData(uint i, uint tile, uint2 zBinRange, out DensityVol if (TryFindEntityIndex(i, tile, zBinRange, BOUNDEDENTITYCATEGORY_DENSITY_VOLUME, entityIndex)) { success = true; - data = _DensityVolumeData[i]; + data = _DensityVolumeData[entityIndex]; } return success; From e78c2e408d1b1b2f32f8b9dc51624301aa9bbe3d Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 26 Nov 2020 18:40:50 -0800 Subject: [PATCH 122/209] Fix volumetric lighting --- .../Lighting/LightLoop/LightLoopDef.hlsl | 10 +- .../VolumetricLighting.compute | 288 +++++++----------- .../VolumetricLighting/VolumetricLighting.cs | 4 +- 3 files changed, 110 insertions(+), 192 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl index c00e62db89e..19853eefea6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl @@ -181,6 +181,7 @@ uint TryFindEntityIndex(inout uint i, uint tile, uint2 zBinRange, uint category, // The part (2) below will be actually executed during every function call. while (i < n) { + // Walk the list of entity indices of the tile. uint tileEntityPair = TILE_BUFFER[tileBufferBodyIndex + (i / 2)]; // 16-bit indices uint tileEntityIndex = BitFieldExtract(tileEntityPair, 16 * (i & 1), 16); // First Lo, then Hi bits @@ -199,6 +200,7 @@ uint TryFindEntityIndex(inout uint i, uint tile, uint2 zBinRange, uint category, } else // if (zBinEntityIndexRange.y < tileEntityIndex) { + // (tileEntityIndex == UINT16_MAX) signifies a terminator. break; // Avoid incrementing 'i' further } } @@ -341,7 +343,7 @@ bool TryLoadReflectionProbeData(inout uint i, uint tile, uint2 zBinRange, out En return success; } -bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) +bool TryLoadDecalData(inout uint i, uint tile, uint zBin, out DecalData data) { bool success = false; @@ -355,7 +357,7 @@ bool TryLoadDecalData(uint i, uint tile, uint zBin, out DecalData data) return success; } -bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) +bool TryLoadDecalData(inout uint i, uint tile, uint2 zBinRange, out DecalData data) { bool success = false; @@ -369,7 +371,7 @@ bool TryLoadDecalData(uint i, uint tile, uint2 zBinRange, out DecalData data) return success; } -bool TryLoadDensityVolumeData(uint i, uint tile, uint zBin, out DensityVolumeData data) +bool TryLoadDensityVolumeData(inout uint i, uint tile, uint zBin, out DensityVolumeData data) { bool success = false; @@ -383,7 +385,7 @@ bool TryLoadDensityVolumeData(uint i, uint tile, uint zBin, out DensityVolumeDat return success; } -bool TryLoadDensityVolumeData(uint i, uint tile, uint2 zBinRange, out DensityVolumeData data) +bool TryLoadDensityVolumeData(inout uint i, uint tile, uint2 zBinRange, out DensityVolumeData data) { bool success = false; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute index 0e00c04478c..fa03042d060 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute @@ -7,22 +7,14 @@ #pragma kernel VolumetricLighting -#pragma multi_compile _ LIGHTLOOP_DISABLE_TILE_AND_CLUSTER +#pragma multi_compile _ COARSE_BINNING #pragma multi_compile _ ENABLE_REPROJECTION #pragma multi_compile _ ENABLE_ANISOTROPY #pragma multi_compile _ VL_PRESET_OPTIMAL -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - #define USE_BIG_TILE_LIGHTLIST -#endif - // Don't want contact shadows #define LIGHT_EVALUATION_NO_CONTACT_SHADOWS // To define before LightEvaluation.hlsl -#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER - #define USE_BIG_TILE_LIGHTLIST -#endif - #ifdef VL_PRESET_OPTIMAL // E.g. for 1080p: (1920/8)x(1080/8)x(64) = 2,073,600 voxels #define VBUFFER_VOXEL_SIZE 8 @@ -233,7 +225,7 @@ VoxelLighting EvaluateVoxelLightingDirectional(LightLoopContext context, uint fe // Computes the light integral (in-scattered radiance) within the voxel. // Multiplication by the scattering coefficient and the phase function is performed outside. VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureFlags, PositionInputs posInput, - uint lightCount, uint lightStart, float3 centerWS, + uint tile, uint2 zBinRange, float3 centerWS, JitteredRay ray, float t0, float t1, float dt, float rndVal, float extinction, float anisotropy) { VoxelLighting lighting; @@ -246,153 +238,104 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF if (featureFlags & LIGHTFEATUREFLAGS_PUNCTUAL) { - uint lightOffset = 0; // This is used by two subsequent loops + uint i = 0; - // This loop does not process box lights. - for (; lightOffset < lightCount; lightOffset++) + LightData light; + while (TryLoadPunctualLightData(i, tile, zBinRange, light)) { - uint lightIndex = FetchIndex(lightStart, lightOffset); - LightData light = _LightData[lightIndex]; - - if (light.lightType >= GPULIGHTTYPE_PROJECTOR_BOX) { break; } - // Prep the light so that it works with non-volumetrics-aware code. light.contactShadowMask = 0; light.shadowDimmer = light.volumetricShadowDimmer; - bool sampleLight = (light.volumetricLightDimmer > 0); + float weight = 0; // Monte Carlo weight - float tEntr = t0; - float tExit = t1; - - // Perform ray-cone intersection for pyramid and spot lights. - if (light.lightType != GPULIGHTTYPE_POINT) + if (light.lightType == GPULIGHTTYPE_PROJECTOR_BOX) { - float lenMul = 1; - - if (light.lightType == GPULIGHTTYPE_PROJECTOR_PYRAMID) - { - // 'light.right' and 'light.up' vectors are pre-scaled on the CPU - // s.t. if you were to place them at the distance of 1 directly in front - // of the light, they would give you the "footprint" of the light. - // For spot lights, the cone fit is exact. - // For pyramid lights, however, this is the "inscribed" cone - // (contained within the pyramid), and we want to intersect - // the "escribed" cone (which contains the pyramid). - // Therefore, we have to scale the radii by the sqrt(2). - lenMul = rsqrt(2); - } - - float3 coneAxisX = lenMul * light.right; - float3 coneAxisY = lenMul * light.up; - - sampleLight = sampleLight && IntersectRayCone(ray.originWS, ray.jitterDirWS, - light.positionRWS, light.forward, - coneAxisX, coneAxisY, - t0, t1, tEntr, tExit); - } + bool sampleLight = (light.volumetricLightDimmer > 0); - // Is it worth evaluating the light? - if (sampleLight) - { - float lightSqRadius = light.size.x; + // Convert the box light from OBB to AABB. + // 'light.right' and 'light.up' vectors are pre-scaled on the CPU by (2/w) and (2/h). + float3x3 rotMat = float3x3(light.right, light.up, light.forward); - float t, distSq, rcpPdf; - ImportanceSamplePunctualLight(rndVal, light.positionRWS, lightSqRadius, - ray.originWS, ray.jitterDirWS, - tEntr, tExit, - t, distSq, rcpPdf); + float3 o = mul(rotMat, ray.originWS - light.positionRWS); + float3 d = mul(rotMat, ray.jitterDirWS); - posInput.positionWS = ray.originWS + t * ray.jitterDirWS; + float3 boxPt0 = float3(-1, -1, 0); + float3 boxPt1 = float3( 1, 1, light.range); - float3 L; - float4 distances; // {d, d^2, 1/d, d_proj} - GetPunctualLightVectors(posInput.positionWS, light, L, distances); + float tEntr, tExit; + sampleLight = sampleLight && IntersectRayAABB(o, d, boxPt0, boxPt1, t0, t1, tEntr, tExit); - float4 lightColor = EvaluateLight_Punctual(context, posInput, light, L, distances); - // The volumetric light dimmer, unlike the regular light dimmer, is not pre-multiplied. - lightColor.a *= light.volumetricLightDimmer; - lightColor.rgb *= lightColor.a; // Composite + // Is it worth evaluating the light? + if (sampleLight) + { + float tOffset; + ImportanceSampleHomogeneousMedium(rndVal, extinction, tExit - tEntr, tOffset, weight); - #if SHADOW_VIEW_BIAS - // Our shadows only support normal bias. Volumetrics has no access to the surface normal. - // We fake view bias by invoking the normal bias code with the view direction. - float3 shadowN = -ray.jitterDirWS; - #else - float3 shadowN = 0; // No bias - #endif // SHADOW_VIEW_BIAS + // Compute transmittance from 't0' to 'tEntr'. + weight *= TransmittanceHomogeneousMedium(extinction, tEntr - t0); - SHADOW_TYPE shadow = EvaluateShadow_Punctual(context, posInput, light, unused, shadowN, L, distances); - lightColor.rgb *= ComputeShadowColor(shadow, light.shadowTint, light.penumbraTint); - - - // Important: - // Ideally, all scattering calculations should use the jittered versions - // of the sample position and the ray direction. However, correct reprojection - // of asymmetrically scattered lighting (affected by an anisotropic phase - // function) is not possible. We work around this issue by reprojecting - // lighting not affected by the phase function. This basically removes - // the phase function from the temporal integration process. It is a hack. - // The downside is that anisotropy no longer benefits from temporal averaging, - // and any temporal instability of anisotropy causes causes visible jitter. - // In order to stabilize the image, we use the voxel center for all - // anisotropy-related calculations. - float3 centerL = light.positionRWS - centerWS; - float cosTheta = dot(centerL, ray.centerDirWS) * rsqrt(dot(centerL, centerL)); - float phase = CornetteShanksPhasePartVarying(anisotropy, cosTheta); - - // Compute transmittance from 't0' to 't'. - float weight = TransmittanceHomogeneousMedium(extinction, t - t0) * rcpPdf; - - // Compute the amount of in-scattered radiance. - lighting.radianceNoPhase += (weight * lightColor.rgb); - lighting.radianceComplete += (weight * lightColor.rgb) * phase; + float t = tEntr + tOffset; + posInput.positionWS = ray.originWS + t * ray.jitterDirWS; + } } - } - - // This loop only processes box lights. - for (; lightOffset < lightCount; lightOffset++) - { - uint lightIndex = FetchIndex(lightStart, lightOffset); - LightData light = _LightData[lightIndex]; - - if (light.lightType != GPULIGHTTYPE_PROJECTOR_BOX) { break; } - - // Prep the light so that it works with non-volumetrics-aware code. - light.contactShadowMask = 0; - light.shadowDimmer = light.volumetricShadowDimmer; - - bool sampleLight = (light.volumetricLightDimmer > 0); - - // Convert the box light from OBB to AABB. - // 'light.right' and 'light.up' vectors are pre-scaled on the CPU by (2/w) and (2/h). - float3x3 rotMat = float3x3(light.right, light.up, light.forward); - - float3 o = mul(rotMat, ray.originWS - light.positionRWS); - float3 d = mul(rotMat, ray.jitterDirWS); - - float3 boxPt0 = float3(-1, -1, 0); - float3 boxPt1 = float3( 1, 1, light.range); - - float tEntr, tExit; - sampleLight = sampleLight && IntersectRayAABB(o, d, boxPt0, boxPt1, t0, t1, tEntr, tExit); - - // Is it worth evaluating the light? - if (sampleLight) + else // (light.lightType != GPULIGHTTYPE_PROJECTOR_BOX) { - float tOffset, weight; - ImportanceSampleHomogeneousMedium(rndVal, extinction, tExit - tEntr, tOffset, weight); - - // Compute transmittance from 't0' to 'tEntr'. - weight *= TransmittanceHomogeneousMedium(extinction, tEntr - t0); - - float t = tEntr + tOffset; - posInput.positionWS = ray.originWS + t * ray.jitterDirWS; + bool sampleLight = (light.volumetricLightDimmer > 0); + + float tEntr = t0; + float tExit = t1; + + // Perform ray-cone intersection for pyramid and spot lights. + if (light.lightType != GPULIGHTTYPE_POINT) + { + float lenMul = 1; + + if (light.lightType == GPULIGHTTYPE_PROJECTOR_PYRAMID) + { + // 'light.right' and 'light.up' vectors are pre-scaled on the CPU + // s.t. if you were to place them at the distance of 1 directly in front + // of the light, they would give you the "footprint" of the light. + // For spot lights, the cone fit is exact. + // For pyramid lights, however, this is the "inscribed" cone + // (contained within the pyramid), and we want to intersect + // the "escribed" cone (which contains the pyramid). + // Therefore, we have to scale the radii by the sqrt(2). + lenMul = rsqrt(2); + } + + float3 coneAxisX = lenMul * light.right; + float3 coneAxisY = lenMul * light.up; + + sampleLight = sampleLight && IntersectRayCone(ray.originWS, ray.jitterDirWS, + light.positionRWS, light.forward, + coneAxisX, coneAxisY, + t0, t1, tEntr, tExit); + } + + // Is it worth evaluating the light? + if (sampleLight) + { + float lightSqRadius = light.size.x; + + float t, distSq, rcpPdf; + ImportanceSamplePunctualLight(rndVal, light.positionRWS, lightSqRadius, + ray.originWS, ray.jitterDirWS, + tEntr, tExit, + t, distSq, rcpPdf); + + // Compute transmittance from 't0' to 't'. + weight = TransmittanceHomogeneousMedium(extinction, t - t0) * rcpPdf; + + posInput.positionWS = ray.originWS + t * ray.jitterDirWS; + } + } - float3 L = -light.forward; - float3 lightToSample = posInput.positionWS - light.positionRWS; - float distProj = dot(lightToSample, light.forward); - float4 distances = float4(1, 1, 1, distProj); + if (weight > 0) + { + float3 L; + float4 distances; // {d, d^2, 1/d, d_proj} + GetPunctualLightVectors(posInput.positionWS, light, L, distances); float4 lightColor = EvaluateLight_Punctual(context, posInput, light, L, distances); // The volumetric light dimmer, unlike the regular light dimmer, is not pre-multiplied. @@ -410,7 +353,6 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF SHADOW_TYPE shadow = EvaluateShadow_Punctual(context, posInput, light, unused, shadowN, L, distances); lightColor.rgb *= ComputeShadowColor(shadow, light.shadowTint, light.penumbraTint); - // Important: // Ideally, all scattering calculations should use the jittered versions // of the sample position and the ray direction. However, correct reprojection @@ -431,6 +373,8 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF lighting.radianceNoPhase += (weight * lightColor.rgb); lighting.radianceComplete += (weight * lightColor.rgb) * phase; } + + i++; } } @@ -439,49 +383,14 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF // Computes the in-scattered radiance along the ray. void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, - PositionInputs posInput, uint tileIndex, JitteredRay ray) + PositionInputs posInput, uint tile, JitteredRay ray, float cosRay) { - uint lightCount, lightStart; - -#ifdef USE_BIG_TILE_LIGHTLIST - // Offset for stereo rendering - tileIndex += unity_StereoEyeIndex * _NumTileBigTileX * _NumTileBigTileY; - - // The "big tile" list contains the number of objects contained within the tile followed by the - // list of object indices. Note that while objects are already sorted by type, we don't know the - // number of each type of objects (e.g. lights), so we should remember to break out of the loop. - lightCount = g_vBigTileLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE * tileIndex]; - lightStart = MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE * tileIndex + 1; - - // For now, iterate through all the objects to determine the correct range. - // TODO: precompute this, of course. - { - uint offset = 0; - - for (; offset < lightCount; offset++) - { - uint objectIndex = FetchIndex(lightStart, offset); - - if (objectIndex >= _EnvLightIndexShift) - { - // We have found the last local analytical light. - break; - } - } - - lightCount = offset; - } - -#else // USE_BIG_TILE_LIGHTLIST - - lightCount = _PunctualLightCount; - lightStart = 0; - -#endif // USE_BIG_TILE_LIGHTLIST - float t0 = DecodeLogarithmicDepthGeneralized(0, _VBufferDistanceDecodingParams); float de = _VBufferRcpSliceCount; // Log-encoded distance between slices + float z0 = t0 * cosRay; // Distance to linear depth + uint zBin0 = ComputeZBinIndex(z0); + // The contribution of the ambient probe does not depend on the position, // only on the direction and the length of the interval. // SampleSH9() evaluates the 3-band SH in a given direction. @@ -513,6 +422,9 @@ void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, } #endif + float z1 = t1 * cosRay; // Distance to linear depth + uint zBin1 = ComputeZBinIndex(z1); + float dt = t1 - t0; // Is geometry-aware // Accurately compute the center of the voxel in the log space. It's important to perform @@ -561,7 +473,7 @@ void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, #if (SUPPORT_LOCAL_LIGHTS != 0) { VoxelLighting lighting = EvaluateVoxelLightingLocal(context, featureFlags, posInput, - lightCount, lightStart, + tile, uint2(zBin0, zBin1), centerWS, ray, t0, t1, dt, rndVal, extinction, anisotropy); @@ -670,7 +582,8 @@ void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, // Compute the optical depth up to the end of the interval. opticalDepth += 0.5 * blendValue.a; - t0 = tNext; + t0 = tNext; + zBin0 = zBin1; // TODO: maybe not a good idea with the "stop ray at geometry" feature active } } @@ -723,6 +636,9 @@ void VolumetricLighting(uint3 dispatchThreadId : SV_DispatchThreadID, ray.jitterDirWS = normalize(ray.centerDirWS + sampleOffset.x * ray.xDirDerivWS + sampleOffset.y * ray.yDirDerivWS); + // We will use the value of the cosine to convert distances from the camera to linear depth values. + float cosRay = dot(F, ray.jitterDirWS); + // We would like to determine the screen pixel (at the full resolution) which // the jittered ray corresponds to. The exact solution can be obtained by intersecting // the ray with the screen plane, e.i. (ViewSpace(jitterDirWS).z = 1). That's a little expensive. @@ -731,15 +647,15 @@ void VolumetricLighting(uint3 dispatchThreadId : SV_DispatchThreadID, #ifdef VL_PRESET_OPTIMAL // The entire thread group is within the same light tile. - uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE_BIG_TILE; + uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE; + uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); #else // No compile-time optimizations, no scalarization. - uint2 tileCoord = pixelCoord / TILE_SIZE_BIG_TILE; + uint tile = ComputeTileIndex(pixelCoord); #endif - uint tileIndex = tileCoord.x + _NumTileBigTileX * tileCoord.y; // Do not jitter 'voxelCoord' else. It's expected to correspond to the center of the voxel. - PositionInputs posInput = GetPositionInput(voxelCoord, _VBufferViewportSize.zw, tileCoord); + PositionInputs posInput = GetPositionInput(voxelCoord, _VBufferViewportSize.zw); ray.geomDist = FLT_INF; @@ -761,5 +677,5 @@ void VolumetricLighting(uint3 dispatchThreadId : SV_DispatchThreadID, ApplyCameraRelativeXR(ray.originWS); - FillVolumetricLightingBuffer(context, featureFlags, posInput, tileIndex, ray); + FillVolumetricLightingBuffer(context, featureFlags, posInput, tile, ray, cosRay); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 0b797892376..7e9ecabb143 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -835,9 +835,9 @@ VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCame parameters.volumetricLightingCS = m_VolumetricLightingCS; parameters.volumetricLightingCS.shaderKeywords = null; - if(!parameters.tiledLighting) + if(parameters.tiledLighting) { - parameters.volumetricLightingCS.EnableKeyword("LIGHTLOOP_DISABLE_TILE_AND_CLUSTER"); + parameters.volumetricLightingCS.EnableKeyword("COARSE_BINNING"); } if(parameters.enableReprojection) From db54bf78b46e78139ec8c047ae0deac854974ffa Mon Sep 17 00:00:00 2001 From: Evgenii Date: Fri, 27 Nov 2020 15:21:34 -0800 Subject: [PATCH 123/209] Symbols --- .../Runtime/Lighting/LightLoop/Deferred.compute | 2 +- .../Runtime/Material/Decal/DecalUtilities.hlsl | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute index 4b8b12fd50c..f68b2c5d7dc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute @@ -1,4 +1,4 @@ -#pragma enable_d3d11_debug_symbols +// #pragma enable_d3d11_debug_symbols #pragma kernel Deferred_Direct_Fptl SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl #pragma kernel Deferred_Direct_Fptl_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl_DebugDisplay DEBUG_DISPLAY diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl index cc460d188ae..d799c3d5763 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalUtilities.hlsl @@ -178,10 +178,9 @@ DecalSurfaceData GetDecalSurfaceData(PositionInputs posInput, inout float alpha) uint decalLayerMask = GetMeshRenderingDecalLayer(); - DecalData decalData; - uint i = 0; + DecalData decalData; while (TryLoadDecalData(i, tile, zBin, decalData)) { if ((decalData.decalLayerMask & decalLayerMask) != 0) From ae8cc57d0cab254a9cd65e31cf387329009123b3 Mon Sep 17 00:00:00 2001 From: Sebastien Lagarde Date: Tue, 1 Dec 2020 14:52:15 +0100 Subject: [PATCH 124/209] formatting --- .../Editor/CameraEditorUtils.cs | 1 + .../Editor/ContextualMenuDispatcher.cs | 16 +- .../Editor/CoreEditorDrawers.cs | 10 +- .../Editor/CoreEditorUtils.cs | 33 +- .../Editor/Debugging/DebugState.cs | 2 +- .../Debugging/DebugUIDrawer.Builtins.cs | 2 +- .../Debugging/DebugUIHandlerCanvasEditor.cs | 40 +- .../Editor/Debugging/DebugWindow.cs | 6 +- .../Editor/EditorPrefBoolFlags.cs | 8 +- .../Editor/Gizmo/HierarchicalBox.cs | 39 +- .../Editor/Gizmo/HierarchicalSphere.cs | 6 +- .../Editor/Gizmo/UnlitGizmo.shader | 6 +- .../Editor/InspectorCurveEditor.cs | 2 +- .../Lighting/CoreLightEditorUtilities.cs | 34 +- .../Editor/Lighting/IESImporterEditor.cs | 8 +- .../Editor/Lighting/IESReader.cs | 1 - .../Editor/LookDev/CameraController.cs | 4 +- .../Editor/LookDev/CameraState.cs | 8 +- .../LookDev/ComparisonGizmoController.cs | 8 +- .../Editor/LookDev/Compositor.cs | 5 +- .../LookDev/DisplayWindow.DebugSidePanel.cs | 61 +- ...splayWindow.EnvironmentLibrarySidePanel.cs | 26 +- .../Editor/LookDev/DisplayWindow.cs | 58 +- .../Editor/LookDev/DisplayWindow.uss | 10 +- .../Editor/LookDev/Environment.cs | 18 +- .../Editor/LookDev/EnvironmentLibrary.cs | 2 +- .../Editor/LookDev/Stage.cs | 4 +- .../Editor/LookDev/ToolbarRadio.cs | 9 +- .../Editor/MaterialUpgrader.cs | 6 +- .../Editor/QuaternionPropertyDrawer.cs | 1 - .../Editor/RenderGraph/RenderGraphViewer.cs | 5 +- .../Editor/ShaderGenerator/CSharpToHLSL.cs | 10 +- .../ShaderGenerator/ShaderTypeGeneration.cs | 17 +- .../Editor/Utilities/EditorMaterialQuality.cs | 2 +- .../Editor/Utilities/SerializedBitArray.cs | 16 +- .../Editor/Volume/VolumeComponentEditor.cs | 5 +- .../Volume/VolumeComponentListEditor.cs | 27 +- .../Editor/Volume/VolumeParameterDrawer.cs | 4 +- .../Editor/Volume/VolumeProfileFactory.cs | 4 +- .../Runtime/Camera/FreeCamera.cs | 2 +- .../Runtime/Common/CommonStructs.cs | 2 +- .../Runtime/Common/CoreUnsafeUtils.cs | 9 +- .../Runtime/Common/DynamicArray.cs | 3 +- .../Common/DynamicResolutionHandler.cs | 23 +- .../Runtime/Common/ListBuffer.cs | 8 +- .../Runtime/Debugging/DebugManager.Actions.cs | 6 +- .../Runtime/Debugging/DebugShapes.cs | 104 +- .../Runtime/Debugging/DebugUI.Containers.cs | 2 +- .../Runtime/Debugging/DebugUI.Fields.cs | 2 +- .../Runtime/Debugging/MousePositionDebug.cs | 16 +- .../Prefabs/Scripts/DebugUIHandlerBitField.cs | 3 +- .../Scripts/DebugUIHandlerEnumField.cs | 6 +- .../Prefabs/Scripts/DebugUIHandlerPanel.cs | 8 +- .../Runtime/Debugging/ProfilingScope.cs | 7 +- .../Runtime/RenderGraph/RenderGraph.cs | 23 +- .../Runtime/RenderGraph/RenderGraphBuilder.cs | 2 + .../RenderGraphDefaultResources.cs | 2 - .../RenderGraph/RenderGraphObjectPool.cs | 6 +- .../Runtime/RenderGraph/RenderGraphPass.cs | 2 +- .../RenderGraph/RenderGraphResourcePool.cs | 6 +- .../RenderGraphResourceRegistry.cs | 10 +- .../RenderGraph/RenderGraphResources.cs | 1 - .../ShaderGeneratorAttributes.cs | 3 +- .../Textures/BufferedRTHandleSystem.cs | 3 +- .../Runtime/Textures/RTHandle.cs | 10 +- .../Runtime/Textures/RTHandleSystem.cs | 111 +- .../Runtime/Textures/RTHandles.cs | 20 +- .../Runtime/Utilities/BitArray.cs | 76 +- .../Runtime/Utilities/CameraCaptureBridge.cs | 4 +- .../Runtime/Utilities/ColorUtils.cs | 6 +- .../Runtime/Utilities/CoreMatrixUtils.cs | 11 +- .../Runtime/Utilities/CoreUtils.cs | 2 + .../Runtime/Utilities/DelegateUtility.cs | 2 +- .../Runtime/Utilities/MaterialQuality.cs | 8 +- .../Runtime/Utilities/ResourceReloader.cs | 8 +- .../Runtime/Utilities/TextureCurve.cs | 4 +- .../Runtime/Utilities/XRUtils.cs | 1 - .../Runtime/Volume/Volume.cs | 1 + .../Runtime/Volume/VolumeComponent.cs | 7 +- .../Runtime/Volume/VolumeManager.cs | 2 +- .../Runtime/Volume/VolumeParameter.cs | 16 +- .../Runtime/Volume/VolumeProfile.cs | 1 - .../ShaderLibrary/API/GLCore.hlsl | 1 - .../ShaderLibrary/API/GLES3.hlsl | 1 - .../ShaderLibrary/AreaLighting.hlsl | 16 +- .../ShaderLibrary/Color.hlsl | 4 +- .../ShaderLibrary/CommonLighting.hlsl | 8 +- .../ShaderLibrary/CommonMaterial.hlsl | 4 +- .../ShaderLibrary/DummyShaderLibrary.cs | 1 - .../ShaderLibrary/GeometricTools.hlsl | 6 +- .../ShaderLibrary/GraniteShaderLibBase.hlsl | 922 ++++---- .../ShaderLibrary/Packing.hlsl | 4 +- .../ShaderLibrary/ParallaxMapping.hlsl | 2 +- .../ShaderLibrary/PhysicalCamera.hlsl | 2 +- .../ShaderLibrary/TextureStack.hlsl | 42 +- .../ShaderLibrary/UnityDOTSInstancing.hlsl | 3 +- .../ShaderLibrary/Version.hlsl | 1 - .../ShaderLibrary/VirtualTexturing.hlsl | 70 +- .../Tests/Editor/BitArrayTests.cs | 2 +- .../Tests/Editor/CoreUnsafeUtilsTests.cs | 34 +- .../Tests/Editor/EditorExampleTest.cs | 32 +- .../Tests/Editor/RenderGraphTests.cs | 73 +- .../Tests/Runtime/RuntimeExampleTest.cs | 32 +- .../Runtime/ShaderConfig.cs | 2 +- .../AutodeskInteractiveMaterialImport.cs | 5 +- ...dSurfaceMaterialDescriptionPreprocessor.cs | 21 +- .../FBXMaterialDescriptionPostprocessor.cs | 6 +- .../AssetProcessors/HDIESImporterEditor.cs | 42 +- .../AssetProcessors/MaterialPostProcessor.cs | 44 +- .../NormalMapFilteringTexturePostprocessor.cs | 2 +- .../PhysicalMaterial3DsMaxPreprocessor.cs | 6 +- .../ShaderGraphMaterialsUpdater.cs | 4 +- ...ketchupMaterialDescriptionPostprocessor.cs | 13 +- ...ThreeDSMaterialDescriptionPostprocessor.cs | 1 - .../BuildProcessors/HDRPPreprocessBuild.cs | 2 +- .../BuildProcessors/HDRPPreprocessShaders.cs | 49 +- .../Compositor/CompositionLayerUI.Drawers.cs | 14 +- .../CompositionManagerEditor.Styles.cs | 2 +- .../Compositor/CompositionManagerEditor.cs | 15 +- .../Editor/Compositor/CompositionUtils.cs | 10 +- .../Editor/Compositor/CompositorWindow.cs | 7 +- .../Compositor/SerializedCompositionLayer.cs | 20 +- .../Compositor/ShaderPropertyUI.Drawers.cs | 72 +- .../Editor/HDAnalytics.cs | 3 +- .../Editor/Lighting/AmbientOcclusionEditor.cs | 2 +- .../DiffusionProfileOverrideEditor.cs | 2 +- .../Lighting/HDLightExplorerExtension.cs | 753 +++--- .../Editor/Lighting/HDLightUI.Handles.cs | 14 +- .../Editor/Lighting/HDLightUI.cs | 61 +- .../Lighting/LightUnit/LightUnitSlider.cs | 2 +- .../LightUnit/LightUnitSliderSettings.cs | 20 +- .../Lighting/ProbeVolume/ProbeVolumeEditor.cs | 5 +- .../ProbeVolume/ProbeVolumeUI.Drawer.cs | 20 +- .../Lighting/ProbeVolumeControllerEditor.cs | 2 +- .../Reflection/HDBakedReflectionSystem.cs | 189 +- .../Lighting/Reflection/HDProbeEditor.cs | 17 +- .../Lighting/Reflection/HDProbeUI.Drawers.cs | 150 +- .../Lighting/Reflection/HDProbeUI.Handles.cs | 58 +- .../Lighting/Reflection/HDProbeUI.Skin.cs | 2 +- .../HDReflectionProbeEditor.Gizmos.cs | 4 +- .../Reflection/HDReflectionProbeEditor.cs | 1 + .../HDScreenSpaceReflectionEditor.cs | 4 +- .../Reflection/PlanarReflectionProbeEditor.cs | 24 +- .../Reflection/ProbeSettingsUI.Drawers.cs | 5 +- .../Reflection/SerializedCameraSettings.cs | 2 +- .../Lighting/Reflection/SerializedHDProbe.cs | 4 +- .../Volume/InfluenceVolumeUI.Drawers.cs | 4 +- .../Volume/InfluenceVolumeUI.Handles.cs | 2 +- .../Volume/InfluenceVolumeUI.Skin.cs | 1 - .../ReflectionProxyVolumeComponentEditor.cs | 1 - .../Volume/SerializedInfluenceVolume.cs | 6 +- .../Editor/Lighting/SerializedHDLight.cs | 12 +- .../Lighting/Shadow/ContactShadowsEditor.cs | 1 + .../Lighting/Shadow/HDShadowSettingsEditor.cs | 3 +- .../VolumetricLighting/DensityVolumeEditor.cs | 18 +- .../DensityVolumeUI.Drawer.cs | 26 +- .../DensityVolumeUI.Skin.cs | 2 +- .../SerializedDensityVolume.cs | 2 +- .../Editor/Material/AxF/AxFGUI.cs | 15 +- .../Decal/DecalProjectorEditor.Skin.cs | 3 +- .../Material/Decal/DecalProjectorEditor.cs | 12 +- .../ShaderGraph/CreateDecalShaderGraph.cs | 6 +- .../ShaderGraph/DecalSubTarget.Migration.cs | 10 +- .../Decal/ShaderGraph/DecalSubTarget.cs | 34 +- .../DiffusionProfileSettingsEditor.Styles.cs | 2 +- .../DiffusionProfileSettingsEditor.cs | 2 +- .../Eye/ShaderGraph/CreateEyeShaderGraph.cs | 12 +- .../Material/Eye/ShaderGraph/EyeData.cs | 2 +- .../Eye/ShaderGraph/EyeSubTarget.Migration.cs | 26 +- .../Material/Eye/ShaderGraph/EyeSubTarget.cs | 4 +- .../ShaderGraph/Node/CirclePupilAnimation.cs | 2 +- .../Eye/ShaderGraph/Node/CorneaRefraction.cs | 2 +- .../ShaderGraph/Node/EyeSurfaceTypeDebug.cs | 2 +- .../Eye/ShaderGraph/Node/IrisLimbalRing.cs | 2 +- .../Eye/ShaderGraph/Node/IrisOffset.cs | 2 +- .../Node/IrisOutOfBoundColorClamp.cs | 2 +- .../Eye/ShaderGraph/Node/IrisUVLocation.cs | 2 +- .../Eye/ShaderGraph/Node/ScleraIrisBlend.cs | 2 +- .../Eye/ShaderGraph/Node/ScleraLimbalRing.cs | 2 +- .../Eye/ShaderGraph/Node/ScleraUVLocation.cs | 2 +- .../Eye/ShaderGraph/ShaderPass.template.hlsl | 4 +- .../ShaderGraph/CreateFabricShaderGraph.cs | 8 +- .../Material/Fabric/ShaderGraph/FabricData.cs | 2 +- .../ShaderGraph/FabricSubTarget.Migration.cs | 18 +- .../Fabric/ShaderGraph/FabricSubTarget.cs | 8 +- .../ShaderGraph/ShaderPass.template.hlsl | 2 +- .../Hair/ShaderGraph/CreateHairShaderGraph.cs | 8 +- .../Material/Hair/ShaderGraph/HairData.cs | 2 +- .../ShaderGraph/HairSubTarget.Migration.cs | 22 +- .../Hair/ShaderGraph/HairSubTarget.cs | 4 +- .../Hair/ShaderGraph/ShaderPass.template.hlsl | 2 +- .../Material/LayeredLit/LayeredLitGUI.cs | 3 +- .../Editor/Material/Lit/LitGUI.cs | 2 +- .../Material/Lit/LitShaderPreprocessor.cs | 2 +- .../Lit/ShaderGraph/CreateHDLitShaderGraph.cs | 6 +- .../Material/Lit/ShaderGraph/HDLitData.cs | 2 +- .../ShaderGraph/HDLitSubTarget.Migration.cs | 32 +- .../Lit/ShaderGraph/HDLitSubTarget.cs | 17 +- .../LitSurfaceOptionPropertyBlock.cs | 2 +- .../Lit/StandardsToHDLitMaterialUpgrader.cs | 26 +- .../Material/MaterialEditorExtension.cs | 2 +- .../DiffusionProfileMaterialPropertyDrawer.cs | 2 +- .../DiffusionProfilePropertyDrawer.cs | 4 +- .../DiffusionProfileShaderProperty.cs | 2 +- .../ShaderGraph/DistortionPropertyBlock.cs | 2 +- .../Material/ShaderGraph/HDBlockFields.cs | 84 +- .../Editor/Material/ShaderGraph/HDFields.cs | 8 +- .../ShaderGraph/HDPropertiesHeader.cs | 3 +- .../Material/ShaderGraph/HDShaderPasses.cs | 146 +- .../Material/ShaderGraph/HDStructFields.cs | 62 +- .../ShaderGraph/HDSubShaderUtilities.cs | 31 +- .../Material/ShaderGraph/HDSubTarget.cs | 12 +- .../Editor/Material/ShaderGraph/HDTarget.cs | 115 +- .../ShaderGraph/Legacy/DecalMasterNode1.cs | 4 +- .../ShaderGraph/Legacy/EyeMasterNode1.cs | 2 +- .../ShaderGraph/Legacy/HDLitMasterNode1.cs | 2 +- .../ShaderGraph/Legacy/HDUnlitMasterNode1.cs | 2 +- .../ShaderGraph/Legacy/HairMasterNode1.cs | 6 +- .../ShaderGraph/Nodes/DiffusionProfileNode.cs | 4 +- .../ShaderGraph/Nodes/EmissionNode.cs | 37 +- .../ShaderGraph/Nodes/ExposureNode.cs | 3 +- .../ShaderGraph/Nodes/HDSceneColorNode.cs | 37 +- .../ShaderGraph/Slots/DefaultMaterialSlot.cs | 2 +- .../DiffusionProfileInputMaterialSlot.cs | 5 +- .../ShaderGraph/SubTargetPropertiesGUI.cs | 4 +- .../ShaderGraph/SubTargetPropertyBlock.cs | 4 +- .../ShaderGraph/SurfaceOptionPropertyBlock.cs | 4 +- .../Material/ShaderGraph/SurfaceSubTarget.cs | 23 +- .../ShaderGraph/TargetData/BuiltinData.cs | 2 +- .../ShaderGraph/TargetData/HDTargetData.cs | 2 +- .../ShaderGraph/TargetData/IRequiresData.cs | 2 +- .../ShaderGraph/TargetData/LightingData.cs | 2 +- .../ShaderGraph/TargetData/SystemData.cs | 5 +- .../Templates/VertexAnimation.template.hlsl | 2 +- .../ShaderGraph/CreateStackLitShaderGraph.cs | 6 +- .../ShaderGraph/ShaderPass.template.hlsl | 2 +- .../StackLit/ShaderGraph/StackLitData.cs | 2 +- .../StackLitSubTarget.Migration.cs | 6 +- .../StackLit/ShaderGraph/StackLitSubTarget.cs | 64 +- .../StackLitSurfaceOptionPropertyBlock.cs | 6 +- .../StandardsTerrainToHDTerrainLitUpgrader.cs | 1 - .../Material/TerrainLit/TerrainLitGUI.cs | 10 +- .../UIBlocks/AdvancedOptionsUIBlock.cs | 5 +- .../UIBlocks/AxfMainSurfaceInputsUIBlock.cs | 2 +- .../UIBlocks/AxfSurfaceInputsUIBlock.cs | 27 +- .../UIBlocks/DecalSortingInputsUIBlock.cs | 4 +- .../UIBlocks/DecalSurfaceInputsUIBlock.cs | 4 +- .../UIBlocks/DecalSurfaceOptionsUIBlock.cs | 2 +- .../Material/UIBlocks/EmissionUIBlock.cs | 6 +- .../Editor/Material/UIBlocks/HDShaderGUI.cs | 5 +- .../Material/UIBlocks/LayerListUIBlock.cs | 2 +- .../UIBlocks/LightingShaderGraphGUI.cs | 2 +- .../Material/UIBlocks/LitShaderGraphGUI.cs | 2 +- .../UIBlocks/LitSurfaceInputsUIBlock.cs | 4 +- .../Material/UIBlocks/MaterialUIBlock.cs | 16 +- .../Material/UIBlocks/MaterialUIBlockList.cs | 2 +- .../Material/UIBlocks/RefractionUIBlock.cs | 2 +- .../Material/UIBlocks/SurfaceOptionUIBlock.cs | 4 +- .../UIBlocks/TessellationOptionsUIBlock.cs | 2 +- .../Material/UIBlocks/TransparencyUIBlock.cs | 2 +- .../Editor/Material/Unlit/BaseUnlitGUI.cs | 5 +- .../ShaderGraph/CreateHDUnlitShaderGraph.cs | 8 +- .../Material/Unlit/ShaderGraph/HDUnlitData.cs | 2 +- .../HDUnlitDistortionPropertyBlock.cs | 2 +- .../ShaderGraph/HDUnlitSubTarget.Migration.cs | 2 +- .../Unlit/ShaderGraph/HDUnlitSubTarget.cs | 4 +- .../Editor/Material/Unlit/UnlitGUI.cs | 1 - .../Editor/PackageInfo.cs | 2 +- .../Editor/PostProcessing/BloomEditor.cs | 1 + .../ChromaticAberrationEditor.cs | 2 +- .../Editor/PostProcessing/ExposureEditor.cs | 8 +- .../Editor/PostProcessing/MotionBlurEditor.cs | 12 +- .../SerializedGlobalPostProcessSettings.cs | 1 - .../PostProcessing/TrackballUIDrawer.cs | 4 +- .../RayTracing/ReflectionKernelGenerator.cs | 16 +- .../RayTracing/SolidAngleKernelGenerator.cs | 8 +- .../RenderPipeline/Camera/HDCameraEditor.cs | 2 +- .../Camera/HDCameraUI.Drawers.cs | 25 +- .../Camera/SerializedHDCamera.cs | 4 +- .../CustomPass/CustomPassDrawer.cs | 500 ++-- .../CustomPass/CustomPassDrawerAttribute.cs | 28 +- .../CustomPass/CustomPassVolumeEditor.cs | 10 +- .../DrawRenderersCustomPassDrawer.cs | 20 +- .../CustomPass/FullScreenCustomPassDrawer.cs | 112 +- .../Editor/RenderPipeline/HDEditorUtils.cs | 21 +- .../HDRenderPipelineMenuItems.cs | 8 +- .../RenderPipeline/HDRenderPipelineUI.Skin.cs | 2 +- .../RenderPipeline/HDRenderPipelineUI.cs | 26 +- .../Editor/RenderPipeline/HDShaderUtils.cs | 25 +- .../Raytracing/GlobalIlluminationEditor.cs | 9 +- .../ScalableSettingLevelParameterEditor.cs | 2 +- .../Settings/DefaultSettingsPanel.cs | 2 +- .../DiffusionProfileSettingsListUI.cs | 2 +- .../Settings/FrameSettingsUI.Drawers.cs | 106 +- .../Settings/OverridableFrameSettingsArea.cs | 9 +- .../Settings/SerializedFrameSettings.cs | 4 +- .../SerializedHDRenderPipelineAsset.cs | 1 - .../SerializedLowResTransparencySettings.cs | 2 +- ...SerializedPostProcessingQualitySettings.cs | 2 +- .../Settings/SerializedScalableSetting.cs | 16 +- .../SerializedScalableSettingValue.cs | 8 +- .../VirtualTexturingSettingsUI.cs | 15 +- .../VolumeComponentWithQualityEditor.cs | 10 +- .../HDRPBasicDxrScenePipeline.cs | 4 +- .../SceneTemplates/HDRPBasicScenePipeline.cs | 4 +- .../Sky/AtmosphericScattering/FogEditor.cs | 4 +- .../Editor/Sky/HDRISky/HDRISkyEditor.cs | 2 +- .../PhysicallyBasedSkyEditor.cs | 98 +- .../Editor/Sky/SkySettingsEditor.cs | 2 +- .../Editor/USS/QualitySettingsDark.uss | 2 +- .../Editor/USS/QualitySettingsLight.uss | 2 +- .../UpgradeStandardShaderMaterials.cs | 44 +- .../Outputs/VFXAbstractDistortionOutput.cs | 4 +- .../VFXAbstractParticleHDRPLitOutput.cs | 16 +- .../VFXDistortionPlanarPrimitiveOutput.cs | 2 +- .../Outputs/VFXDistortionQuadStripOutput.cs | 2 +- .../VFXGraph/Outputs/VFXLitQuadStripOutput.cs | 2 +- .../Editor/VFXGraph/VFXHDRPBinder.cs | 2 +- .../Editor/VFXGraph/VFXHDRPSubOutput.cs | 20 +- .../Editor/Wizard/HDWizard.Configuration.cs | 42 +- .../Editor/Wizard/HDWizard.UIElement.cs | 29 +- .../Editor/Wizard/HDWizard.Window.cs | 36 +- .../Runtime/AssemblyInfo.cs | 1 - .../Compositor/AdditionalCompositorData.cs | 2 +- .../Runtime/Compositor/AlphaInjection.cs | 3 +- .../Runtime/Compositor/CompositionLayer.cs | 30 +- .../Runtime/Compositor/CompositionManager.cs | 27 +- .../Runtime/Compositor/CompositionProfile.cs | 4 +- .../Runtime/Compositor/CustomClear.cs | 2 +- .../Compositor/Shaders/AlphaInjection.shader | 2 +- .../Compositor/Shaders/ChromaKeying.shader | 108 +- .../ClearUIntTextureArray.compute | 2 +- .../Runtime/Core/CoreResources/GPUCopy.cs | 1 + .../Debugging/FrameSettingsFieldAttribute.cs | 2 +- .../Runtime/Core/Textures/EncodeBC6H.cs | 4 +- .../Runtime/Core/Textures/TextureCache.cs | 1 + .../Runtime/Core/Textures/TextureCache2D.cs | 8 +- .../Core/Textures/TextureCacheCubemap.cs | 4 +- .../Runtime/Core/Utilities/GeometryUtils.cs | 11 +- .../Runtime/Debug/DebugDisplay.cs | 174 +- .../Runtime/Debug/DebugExposure.shader | 22 +- .../Runtime/Debug/DebugLightVolumes.compute | 34 +- .../Runtime/Debug/DebugLightVolumes.cs | 19 +- .../Runtime/Debug/LightingDebug.cs | 22 +- .../Runtime/Debug/MaterialDebug.cs | 9 +- .../Runtime/Debug/MaterialError.shader | 2 +- .../Runtime/Debug/RayCountManager.cs | 7 +- .../Runtime/Debug/VolumeDebug.cs | 7 +- .../Lighting/AtmosphericScattering/Fog.cs | 10 +- .../ShaderVariablesAtmosphericScattering.hlsl | 1 - .../Lighting/DiffusionProfileOverride.cs | 2 +- .../Lighting/GlobalIlluminationUtils.cs | 138 +- .../Lighting/IndirectLightingController.cs | 2 +- .../Light/HDAdditionalLightData.Migration.cs | 212 +- .../Lighting/Light/HDAdditionalLightData.cs | 71 +- .../Runtime/Lighting/LightCookieManager.cs | 19 +- .../Runtime/Lighting/LightLoop/LightLoop.cs | 307 ++- .../LightLoop/ShaderVariablesLightLoop.hlsl | 2 +- .../LightLoop/cleardispatchindirect.compute | 6 +- .../LightLoop/lightlistbuild-bigtile.compute | 8 +- .../lightlistbuild-clustered.compute | 22 +- .../Lighting/LightLoop/lightlistbuild.compute | 6 +- .../Runtime/Lighting/LightLoop/tile.compute | 2 +- .../Runtime/Lighting/LightUtils.cs | 13 +- .../PlanarReflectionFiltering.compute | 12 +- .../DebugDisplayProbeVolume.shader | 2 +- .../Lighting/ProbeVolume/ProbeVolume.cs | 9 +- .../Lighting/ProbeVolume/ProbeVolume.hlsl | 10 +- .../ProbeVolume/ProbeVolumeAccumulate.hlsl | 4 +- .../Lighting/ProbeVolume/ProbeVolumeAsset.cs | 40 +- .../ProbeVolume/ProbeVolumeAtlas.hlsl | 4 +- .../ProbeVolume/ProbeVolumeAtlasBlit.compute | 4 +- .../ProbeVolume/ProbeVolumeLighting.cs | 23 +- .../ProbeVolume/ProbeVolumeManager.cs | 2 + .../HDAdditionalReflectionData.Legacy.cs | 2 +- .../HDAdditionalReflectionData.Migration.cs | 124 +- .../Runtime/Lighting/Reflection/HDProbe.cs | 9 +- .../Lighting/Reflection/HDProbeSystem.cs | 70 +- .../Reflection/HDRuntimeReflectionSystem.cs | 1 + .../Reflection/PlanarReflectionProbeCache.cs | 7 +- .../Reflection/ReflectionProbeCache.cs | 4 +- .../Volume/InfluenceVolume.Migration.cs | 2 +- .../Reflection/Volume/InfluenceVolume.cs | 20 +- .../Volume/ProxyVolume.Migration.cs | 2 +- .../Lighting/Reflection/Volume/ProxyVolume.cs | 12 +- .../AmbientOcclusion.RenderGraph.cs | 56 +- .../ScreenSpaceLighting/AmbientOcclusion.cs | 45 +- .../Lighting/ScreenSpaceLighting/GTAO.compute | 2 +- .../GTAOBlurAndUpsample.compute | 8 +- .../ScreenSpaceLighting/SSGIDenoiser.compute | 10 +- .../ScreenSpaceLighting/SSGIDenoiser.cs | 48 +- ...reenSpaceGlobalIllumination.RenderGraph.cs | 76 +- .../ScreenSpaceGlobalIllumination.compute | 18 +- .../ScreenSpaceGlobalIllumination.cs | 4 +- .../ScreenSpaceLighting.hlsl | 2 +- .../ScreenSpaceReflection.cs | 2 +- .../ScreenSpaceTracing.hlsl | 1 - .../Runtime/Lighting/Shadow/EVSMBlur.compute | 8 +- .../Lighting/Shadow/HDCachedShadowAtlas.cs | 38 +- .../Lighting/Shadow/HDCachedShadowManager.cs | 22 +- .../Lighting/Shadow/HDDynamicShadowAtlas.cs | 9 +- .../Runtime/Lighting/Shadow/HDIMS.hlsl | 28 +- .../Runtime/Lighting/Shadow/HDPCSS.hlsl | 2 +- .../Runtime/Lighting/Shadow/HDShadowAtlas.cs | 48 +- .../Shadow/HDShadowManager.RenderGraph.cs | 83 +- .../Lighting/Shadow/HDShadowManager.cs | 63 +- .../Lighting/Shadow/HDShadowSampling.hlsl | 2 +- .../Runtime/Lighting/Shadow/HDShadowUtils.cs | 10 +- .../Lighting/Shadow/MomentShadows.compute | 34 +- .../ScreenSpaceShadowManager.RenderGraph.cs | 31 +- .../Shadow/ScreenSpaceShadowManager.cs | 72 +- .../Shadow/ScreenSpaceShadowManagerArea.cs | 70 +- ...aceShadowManagerDirectional.RenderGraph.cs | 68 +- .../ScreenSpaceShadowManagerDirectional.cs | 16 +- ...nSpaceShadowManagerPunctual.RenderGraph.cs | 72 +- .../ScreenSpaceShadowManagerPunctual.cs | 18 +- .../Runtime/Lighting/Shadow/ShadowBlit.shader | 2 +- .../Lighting/Shadow/ShadowMoments.hlsl | 2 +- .../Runtime/Lighting/SphericalHarmonics.cs | 18 +- .../Runtime/Lighting/SurfaceShading.hlsl | 2 - .../VolumetricLighting/DensityVolume.cs | 1 + .../VolumetricLighting/Texture3DAtlas.cs | 4 +- .../VolumeVoxelization.compute | 14 +- .../VolumetricLighting.compute | 160 +- .../VolumetricLighting/VolumetricLighting.cs | 88 +- .../VolumetricLightingFiltering.compute | 2 +- .../Runtime/Material/AxF/AxF.hlsl | 28 +- .../Runtime/Material/AxF/AxFData.hlsl | 20 +- .../AxF/AxFLTCAreaLight/LtcData.GGX2.cs | 3 +- .../AxF/PreIntegratedFGD_CookTorrance.shader | 2 +- .../Material/AxF/ShaderPass/AxFDepthPass.hlsl | 2 +- .../Material/AxF/ShaderPass/AxFSharePass.hlsl | 2 +- .../Runtime/Material/Builtin/BuiltinData.hlsl | 2 +- .../Runtime/Material/BuiltinGIUtilities.hlsl | 12 +- .../Runtime/Material/Decal/DBufferManager.cs | 2 - .../Runtime/Material/Decal/Decal.hlsl | 64 +- .../Runtime/Material/Decal/Decal.shader | 96 +- .../Runtime/Material/Decal/DecalData.hlsl | 30 +- .../Material/Decal/DecalNormalBuffer.shader | 4 +- .../Runtime/Material/Decal/DecalProjector.cs | 4 +- .../Runtime/Material/Decal/DecalSystem.cs | 26 +- .../DiffusionProfileSettings.Migration.cs | 6 +- .../DiffusionProfileSettings.cs | 27 +- .../Runtime/Material/Eye/Eye.hlsl | 4 +- .../Runtime/Material/Eye/EyeRaytracing.hlsl | 2 +- .../Runtime/Material/Eye/EyeUtils.hlsl | 6 +- .../Material/Fabric/FabricRaytracing.hlsl | 2 +- .../Material/Fabric/FabricReference.hlsl | 6 +- .../Runtime/Material/GBufferManager.cs | 6 +- .../Material/GGXConvolution/IBLFilterGGX.cs | 4 +- .../Runtime/Material/Hair/Hair.hlsl | 2 +- .../Runtime/Material/Hair/HairRayTracing.hlsl | 2 +- .../Material/LTCAreaLight/LTCAreaLight.cs | 6 +- .../Material/LayeredLit/LayeredLit.shader | 20 +- .../LayeredLit/LayeredLitTessellation.shader | 30 +- .../Runtime/Material/Lit/Lit.cs | 13 +- .../Runtime/Material/Lit/Lit.hlsl | 2 +- .../Material/Lit/LitDataIndividualLayer.hlsl | 6 +- .../Runtime/Material/Lit/LitProperties.hlsl | 1 - .../Lit/ShaderPass/LitConstantPass.hlsl | 2 +- .../Material/Lit/ShaderPass/LitDepthPass.hlsl | 2 +- .../Runtime/Material/Material.hlsl | 4 +- .../PreIntegratedFGD/PreIntegratedFGD.cs | 2 +- .../PreIntegratedFGD/PreIntegratedFGD.hlsl | 2 +- .../preIntegratedFGD_GGXDisneyDiffuse.shader | 2 +- .../Runtime/Material/SharedRTManager.cs | 10 +- .../SphericalCapPivot/SPTDistribution.hlsl | 51 +- .../Runtime/Material/StackLit/StackLit.hlsl | 38 +- .../Material/StackLit/StackLitRayTracing.hlsl | 2 +- .../Material/StandardLit/StandardLit.hlsl | 6 +- .../CombineLighting.shader | 4 +- .../SubsurfaceScatteringManager.cs | 8 +- .../SubsurfaceScatteringManagerRT.cs | 89 +- .../Material/TerrainLit/TerrainLit.shader | 4 +- .../Material/TerrainLit/TerrainLitData.hlsl | 8 +- .../TerrainLit/TerrainLitTemplate.hlsl | 6 +- .../TerrainLit/TerrainLit_Basemap.shader | 4 +- .../TerrainLit/TerrainLit_Splatmap.hlsl | 4 +- .../Runtime/Material/Unlit/Unlit.shader | 24 +- .../Runtime/Material/Unlit/UnlitData.hlsl | 2 +- .../Material/Unlit/UnlitRaytracing.hlsl | 2 +- .../Runtime/Material/VTBufferManager.cs | 13 +- .../Runtime/PackageInfo.cs | 2 +- .../PostProcessing/Components/Bloom.cs | 2 +- .../PostProcessing/Components/DepthOfField.cs | 4 +- .../PostProcessing/Components/Exposure.cs | 6 +- .../PostProcessing/Components/FilmGrain.cs | 2 +- .../PostProcessing/Components/MotionBlur.cs | 5 +- .../PostProcessing/Components/Tonemapping.cs | 8 +- .../PostProcessing/Components/Vignette.cs | 2 +- .../CustomPostProcessInjectionPoint.cs | 2 +- .../PostProcessSystem.RenderGraph.cs | 357 ++- .../PostProcessing/PostProcessSystem.cs | 138 +- .../Shaders/BloomPrefilter.compute | 2 +- .../Shaders/ContrastAdaptiveSharpen.compute | 58 +- .../Shaders/DepthOfFieldCoCDilate.compute | 1 - .../Shaders/DepthOfFieldGather.compute | 2 +- .../Shaders/DepthOfFieldPreCombineFar.compute | 2 +- .../Shaders/DoFCoCPyramid.compute | 2 +- .../PostProcessing/Shaders/DoFGather.compute | 2 +- .../Shaders/ExposureCommon.hlsl | 2 +- .../PostProcessing/Shaders/FXAA.compute | 2 +- .../PostProcessing/Shaders/FinalPass.shader | 6 +- .../Shaders/HistogramExposure.compute | 14 +- .../Shaders/LutBuilder3D.compute | 2 +- .../PostProcessing/Shaders/MotionBlur.compute | 8 +- .../Shaders/MotionBlurCommon.hlsl | 2 +- .../Shaders/MotionBlurGenTilePass.compute | 4 +- .../Shaders/MotionBlurMotionVecPrep.compute | 10 +- .../MotionBlurNeighborhoodTilePass.compute | 2 +- .../Shaders/PaniniProjection.compute | 2 +- .../SubpixelMorphologicalAntialiasing.hlsl | 6 +- .../SubpixelMorphologicalAntialiasing.shader | 2 +- .../Shaders/TemporalAntiAliasing.shader | 12 +- .../Shaders/TemporalAntialiasing.hlsl | 6 +- .../PostProcessing/Shaders/UberPost.compute | 2 +- .../Runtime/PostProcessing/Shaders/ffx_a.hlsl | 29 +- .../PostProcessing/Shaders/ffx_cas.hlsl | 22 +- .../PostProcessing/Shaders/ffx_lpm.hlsl | 40 +- .../Accumulation/SubFrameManager.cs | 8 +- .../HDAdditionalCameraData.Migration.cs | 2 +- .../Camera/HDAdditionalCameraData.cs | 24 +- .../Runtime/RenderPipeline/Camera/HDCamera.cs | 61 +- .../RenderPipeline/CullingGroupManager.cs | 5 +- .../GlobalLightingQualitySettings.cs | 2 - .../GlobalPostProcessingQualitySettings.cs | 3 +- .../Runtime/RenderPipeline/HDGPUAsyncTask.cs | 3 +- .../RenderPipeline/HDRenderPipeline.Debug.cs | 288 ++- .../HDRenderPipeline.LightLoop.cs | 299 +-- .../HDRenderPipeline.LookDev.cs | 19 +- .../HDRenderPipeline.PostProcess.cs | 22 +- .../HDRenderPipeline.Prepass.cs | 297 +-- .../HDRenderPipeline.RenderGraph.cs | 569 +++-- .../HDRenderPipeline.RenderGraphUtils.cs | 44 +- .../HDRenderPipeline.SubsurfaceScattering.cs | 28 +- .../RenderPipeline/HDRenderPipeline.cs | 1529 +++++++------ .../HDRenderPipelineAsset.Migration.cs | 2 +- .../RenderPipeline/HDRenderPipelineAsset.cs | 4 +- .../HDRenderPipelineEditorResources.cs | 2 +- .../Runtime/RenderPipeline/HDRenderQueue.cs | 5 +- .../Runtime/RenderPipeline/HDStencilUsage.cs | 1 - .../RenderPipeline/HDStringConstants.cs | 4 +- .../RenderPipeline/PathTracing/PathTracing.cs | 35 +- .../Shaders/PathTracingIntersection.hlsl | 22 +- .../Shaders/PathTracingVolume.hlsl | 4 +- .../Raytracing/HDDiffuseDenoiser.cs | 20 +- .../Raytracing/HDDiffuseShadowDenoiser.cs | 80 +- ...DRaytracingAmbientOcclusion.RenderGraph.cs | 34 +- .../HDRaytracingAmbientOcclusion.cs | 7 +- ...RaytracingDeferredLightLoop.RenderGraph.cs | 46 +- .../HDRaytracingDeferredLightLoop.cs | 28 +- ...HDRaytracingIndirectDiffuse.RenderGraph.cs | 100 +- .../Raytracing/HDRaytracingIndirectDiffuse.cs | 10 +- .../Raytracing/HDRaytracingLightCluster.cs | 37 +- .../Raytracing/HDRaytracingManager.cs | 64 +- .../HDRaytracingRecursiveRenderer.cs | 22 +- .../HDRaytracingReflection.RenderGraph.cs | 100 +- .../Raytracing/HDRaytracingReflection.cs | 8 +- .../Raytracing/HDReflectionDenoiser.cs | 39 +- .../Raytracing/HDSimpleDenoiser.cs | 35 +- .../HDTemporalFilter.RenderGraph.cs | 74 +- .../Raytracing/HDTemporalFilter.cs | 10 +- .../Raytracing/RayTracingMode.cs | 2 +- .../Raytracing/RayTracingSettings.cs | 1 - .../Shaders/Common/RayBinning.compute | 2 +- .../Shaders/DebugLightCluster.shader | 8 +- .../Deferred/RaytracingDeferred.compute | 4 +- .../RaytracingIntersectonGBuffer.hlsl | 2 +- .../Shaders/Denoising/DiffuseDenoiser.compute | 2 +- .../Denoising/DiffuseShadowDenoiser.compute | 4 +- .../Shaders/Denoising/TemporalFilter.compute | 14 +- .../Raytracing/Shaders/OnlineVariance.hlsl | 2 +- .../Raytracing/Shaders/RayTracingCommon.hlsl | 2 +- .../Shaders/RayTracingLightCluster.hlsl | 12 +- .../Shaders/RaytracingFragInputs.hlsl | 22 +- .../Shaders/RaytracingIntersection.hlsl | 216 +- .../Shaders/RaytracingLightCluster.compute | 6 +- .../Shaders/RaytracingLightLoop.hlsl | 2 +- .../Raytracing/Shaders/RaytracingMacros.hlsl | 4 +- .../Shaders/Shadows/RaytracingMIS.hlsl | 4 +- .../Shaders/Shadows/RaytracingShadow.compute | 2 +- .../Shadows/RaytracingShadowFilter.compute | 8 +- .../Shaders/Shadows/SphericalCone.hlsl | 2 +- .../Shaders/Shadows/SphericalQuad.hlsl | 20 +- .../Shaders/Shadows/SphericalSphere.hlsl | 10 +- .../SubSurface/RayTracingSubSurface.compute | 6 +- .../RenderPass/AOV/AOVRequest.cs | 5 +- .../RenderPass/AOV/AOVRequestData.cs | 23 +- .../AOV/AOVRequestDataCollection.cs | 2 +- .../RenderPass/AOV/RenderOutputProperties.cs | 6 +- .../RenderPass/CustomPass/CustomPass.cs | 86 +- .../CustomPass/CustomPassCommon.hlsl | 2 +- .../CustomPass/CustomPassContext.cs | 2 +- .../CustomPass/CustomPassInjectionPoint.cs | 2 +- .../CustomPass/CustomPassRenderers.hlsl | 2 +- .../CustomPassRenderersUtils.shader | 2 +- .../RenderPass/CustomPass/CustomPassUtils.cs | 42 +- .../RenderPass/CustomPass/CustomPassVolume.cs | 4 +- .../Distortion/ApplyDistortion.shader | 2 +- .../RenderPass/DrawRenderersCustomPass.cs | 6 +- .../RenderPass/FullScreenCustomPass.cs | 2 +- .../RenderPass/GenerateMaxZ.compute | 8 +- .../RenderPipeline/RenderPass/MipGenerator.cs | 26 +- .../MotionVectors/CameraMotionVectors.shader | 2 +- .../RenderPipeline/SceneViewDrawMode.cs | 6 +- .../Settings/FrameSettings.Migration.cs | 5 +- .../RenderPipeline/Settings/FrameSettings.cs | 46 +- .../Settings/FrameSettingsHistory.cs | 13 +- .../Settings/RenderPipelineSettings.cs | 11 +- .../Settings/ScalableSetting.cs | 8 +- .../Settings/ScalableSettingSchema.cs | 6 +- .../Settings/ScalableSettingSchemaId.cs | 3 +- .../Settings/ScalableSettingValue.cs | 8 +- .../ShaderPass/ShaderPassDecal.hlsl | 8 +- .../ShaderPass/ShaderPassMotionVectors.hlsl | 2 +- .../ShaderPassRayTracingSubSurface.hlsl | 2 +- .../ShaderPassRaytracingForward.hlsl | 6 +- .../ShaderPassRaytracingGBuffer.hlsl | 2 +- .../ShaderPassRaytracingIndirect.hlsl | 8 +- .../ShaderPassRaytracingVisibility.hlsl | 4 +- .../RenderPipeline/Utility/BlueNoise.cs | 1 - .../Runtime/RenderPipeline/Utility/HDUtils.cs | 67 +- .../RenderPipeline/Utility/Texture2DAtlas.cs | 23 +- .../Utility/Texture2DAtlasDynamic.cs | 4 +- .../Utility/Texture3DAtlasDynamic.cs | 2 +- .../Runtime/RenderPipeline/XR/XRPass.cs | 2 + .../Runtime/RenderPipeline/XR/XRSystem.cs | 7 +- .../Runtime/Scripting/GameObjectExtension.cs | 6 +- .../ShaderLibrary/CopyStencilBuffer.shader | 6 +- .../ResolveStencilBuffer.compute | 6 +- .../ShaderLibrary/ShaderGraphFunctions.hlsl | 2 +- .../ShaderLibrary/ShaderGraphHeader.hlsl | 2 +- .../ShaderVariablesFunctions.hlsl | 4 +- .../ShaderLibrary/XROcclusionMesh.shader | 4 +- .../Sky/GradientSky/GradientSky.shader | 2 +- .../Runtime/Sky/HDRISky/HDRISky.cs | 2 +- .../Runtime/Sky/HDRISky/HDRISky.shader | 4 +- .../Runtime/Sky/HDRISky/HDRISkyRenderer.cs | 10 +- .../Sky/HDRISky/IntegrateHDRISky.shader | 2 +- .../PhysicallyBasedSky/PhysicallyBasedSky.cs | 8 +- .../PhysicallyBasedSkyCommon.hlsl | 14 +- .../PhysicallyBasedSkyRenderer.cs | 39 +- .../Runtime/Sky/SkyManager.cs | 68 +- .../Runtime/Sky/SkyRenderer.cs | 5 +- .../Runtime/Sky/SkySettings.cs | 2 +- .../Runtime/Sky/VisualEnvironment.cs | 2 +- .../Runtime/Utilities/CameraCache.cs | 4 +- .../Runtime/Utilities/CameraSettings.cs | 68 +- .../HDAdditionalSceneViewSettings.cs | 2 +- .../Runtime/Utilities/HDBakingUtilities.cs | 2 +- .../Utilities/HDRenderPipelinePreferences.cs | 2 +- .../Runtime/Utilities/HDRenderUtilities.cs | 114 +- .../Runtime/Utilities/HDTextureUtilities.cs | 48 +- .../Utilities/ProbeCapturePositionSettings.cs | 2 +- .../Runtime/Utilities/ProbeSettings.cs | 4 +- .../Utilities/ProbeSettingsUtilities.cs | 50 +- .../Runtime/Utilities/SceneObjectIDMap.cs | 6 +- .../Runtime/Utilities/TypeInfo.cs | 2 +- .../Utilities/VolumeComponentWithQuality.cs | 3 +- .../Runtime/VFXGraph/Shaders/VFXCommon.hlsl | 6 +- .../Runtime/VFXGraph/Shaders/VFXDefines.hlsl | 8 +- .../Runtime/VFXGraph/Shaders/VFXLit.hlsl | 6 +- .../VFXGraph/Shaders/VFXLitPixelOutput.hlsl | 10 +- .../PropertyBinders/HDRPCameraBinder.cs | 2 - .../Shaders/TMP_SDF-Mobile_Ztest.shader | 448 ++-- .../Resources/Shaders/TMPro.cginc | 87 +- .../Resources/Shaders/TMPro_Properties.cginc | 136 +- .../Resources/Shaders/TMPro_Surface.cginc | 154 +- .../Tests/Editor/FrameSettingsTest.cs | 8 +- .../Tests/Editor/HDRenderUtilitiesTests.cs | 12 +- .../Editor/ProbeSettingsUtilitiesTests.cs | 2 +- .../Editor/SerializedScalableSettingTests.cs | 2 +- .../SerializedScalableSettingValueTests.cs | 10 +- .../Editor/TestFramework/RandomUtilities.cs | 1 + .../Tests/Runtime/RuntimeExampleTest.cs | 32 +- .../Tests/Runtime/SampleRuntimeTests.cs | 2 +- .../ShaderLibrary/Core.hlsl | 2 +- .../ShaderLibrary/Input.hlsl | 2 +- .../ShaderLibrary/Lighting.hlsl | 2 +- .../ShaderLibrary/Particles.hlsl | 2 +- .../ShaderLibrary/ShaderGraphFunctions.hlsl | 2 +- .../ShaderLibrary/Shadows.hlsl | 2 +- .../ShaderLibrary/SurfaceInput.hlsl | 2 +- .../ShaderLibrary/UnityInput.hlsl | 2 +- .../ShaderLibrary/Version.hlsl | 2 +- .../Shaders/2D/Include/LightingUtility.hlsl | 2 +- .../2D/Include/NormalsRenderingShared.hlsl | 2 +- .../Shaders/BakedLitMetaPass.hlsl | 2 +- .../Shaders/DepthOnlyPass.hlsl | 2 +- .../Shaders/LitInput.hlsl | 2 +- .../Shaders/LitMetaPass.hlsl | 2 +- .../Nature/SpeedTree7BillboardInput.hlsl | 2 +- .../Nature/SpeedTree7BillboardPasses.hlsl | 2 +- .../Shaders/Nature/SpeedTree7CommonInput.hlsl | 2 +- .../Nature/SpeedTree7CommonPasses.hlsl | 2 +- .../Shaders/Nature/SpeedTree7Input.hlsl | 2 +- .../Shaders/Nature/SpeedTree7Passes.hlsl | 2 +- .../Shaders/Nature/SpeedTree8Input.hlsl | 2 +- .../Shaders/Nature/SpeedTree8Passes.hlsl | 2 +- .../Particles/ParticlesLitForwardPass.hlsl | 2 +- .../Shaders/Particles/ParticlesLitInput.hlsl | 2 +- .../ParticlesSimpleLitForwardPass.hlsl | 2 +- .../Particles/ParticlesSimpleLitInput.hlsl | 2 +- .../Particles/ParticlesUnlitForwardPass.hlsl | 2 +- .../Particles/ParticlesUnlitInput.hlsl | 2 +- .../Shaders/ShadowCasterPass.hlsl | 2 +- .../Shaders/SimpleLitForwardPass.hlsl | 2 +- .../Shaders/SimpleLitInput.hlsl | 2 +- .../Shaders/SimpleLitMetaPass.hlsl | 2 +- .../Shaders/Terrain/TerrainLitInput.hlsl | 2 +- .../Shaders/Terrain/TerrainLitMetaPass.hlsl | 2 +- .../Shaders/Terrain/TerrainLitPasses.hlsl | 2 +- .../Shaders/Terrain/WavingGrassInput.hlsl | 2 +- .../Shaders/Terrain/WavingGrassPasses.hlsl | 2 +- .../Shaders/UnlitInput.hlsl | 2 +- .../Shaders/UnlitMetaPass.hlsl | 2 +- .../Shaders/Utils/CopyDepthPass.hlsl | 2 +- .../Shaders/Utils/Lightweight2D.hlsl | 2 +- .../Tests/Editor/LightweightEditorTests.cs | 2 +- .../2D/CompositeShadowCaster2DEditor.cs | 1 - .../Editor/2D/FreeformPathPresets.cs | 12 +- .../Editor/2D/Light2DEditor.cs | 148 +- .../Editor/2D/Light2DEditorUtility.cs | 46 +- .../Editor/2D/Renderer2DAnalytics.cs | 2 +- .../Editor/2D/Renderer2DMenus.cs | 5 +- .../Editor/2D/Renderer2DUpgrader.cs | 13 +- .../Editor/2D/ShadowCaster2DEditor.cs | 10 +- .../Editor/2D/ShadowCaster2DShapeTool.cs | 2 +- .../ShapeEditor/EditablePath/EditablePath.cs | 6 +- .../EditablePath/EditablePathController.cs | 10 +- .../EditablePath/EditablePathExtensions.cs | 30 +- .../MultipleEditablePathController.cs | 4 +- .../EditorTool/GenericScriptablePath.cs | 6 +- .../GenericScriptablePathInspector.cs | 18 +- .../EditorTool/PathComponentEditor.cs | 2 +- .../ShapeEditor/EditorTool/PathEditorTool.cs | 14 +- .../EditorTool/PathEditorToolExtensions.cs | 9 +- .../ShapeEditor/EditorTool/ScriptablePath.cs | 2 +- .../EditorTool/ScriptablePathInspector.cs | 30 +- .../ShapeEditor/GUIFramework/ClickAction.cs | 2 +- .../ShapeEditor/GUIFramework/CommandAction.cs | 4 +- .../2D/ShapeEditor/GUIFramework/Control.cs | 2 - .../GUIFramework/DefaultControl.cs | 2 +- .../2D/ShapeEditor/GUIFramework/GUIAction.cs | 5 +- .../2D/ShapeEditor/GUIFramework/GUIState.cs | 2 +- .../2D/ShapeEditor/GUIFramework/GUISystem.cs | 2 +- .../GUIFramework/GenericControl.cs | 12 +- .../GUIFramework/GenericDefaultControl.cs | 2 +- .../ShapeEditor/GUIFramework/SliderAction.cs | 1 - .../2D/ShapeEditor/Selection/RectSelector.cs | 4 +- .../Selection/SerializableSelection.cs | 14 +- .../2D/ShapeEditor/Shapes/ShapeExtensions.cs | 16 +- .../Editor/2D/ShapeEditor/Shapes/Spline.cs | 16 +- .../Editor/2D/ShapeEditor/View/Drawer.cs | 1 - .../2D/ShapeEditor/View/EditablePathView.cs | 41 +- .../Editor/2D/SortingLayerDropDown.cs | 5 +- .../AutodeskInteractiveMaterialImport.cs | 7 +- ...dSurfaceMaterialDescriptionPreprocessor.cs | 4 +- .../FBXMaterialDescriptionPreprocessor.cs | 6 +- .../MaterialPostprocessor.cs | 15 +- .../PhysicalMaterial3DsMaxPreprocessor.cs | 14 +- ...ketchupMaterialDescriptionPostprocessor.cs | 3 +- ...ThreeDSMaterialDescriptionPostprocessor.cs | 1 - .../Editor/AssetVersion.cs | 2 +- .../Editor/Deprecated.cs | 6 +- .../Editor/LightExplorer.cs | 88 +- .../Editor/Overrides/MotionBlurEditor.cs | 6 +- .../Editor/RenderStateDataEditor.cs | 4 +- .../RenderObjectsPassFeatureEditor.cs | 394 ++-- .../ScreenSpaceAmbientOcclusionEditor.cs | 10 +- .../Editor/SavedParameter.cs | 8 +- .../Editor/ScriptableRendererDataEditor.cs | 2 +- .../Editor/ShaderGUI/BaseShaderGUI.cs | 43 +- .../Editor/ShaderGUI/ParticleGUI.cs | 8 +- .../Editor/ShaderGUI/Shaders/LitShader.cs | 2 +- .../ShaderGUI/ShadingModels/BakedLitGUI.cs | 2 +- .../Editor/ShaderGUI/ShadingModels/LitGUI.cs | 43 +- .../ShaderGUI/ShadingModels/SimpleLitGUI.cs | 16 +- .../Editor/ShaderGUI/TerrainLitShaderGUI.cs | 9 +- .../AssetCallbacks/CreateLitShaderGraph.cs | 12 +- .../CreateSpriteLitShaderGraph.cs | 10 +- .../CreateSpriteUnlitShaderGraph.cs | 8 +- .../AssetCallbacks/CreateUnlitShaderGraph.cs | 8 +- .../Includes/DepthNormalsOnlyPass.hlsl | 2 +- .../ShaderGraph/Includes/DepthOnlyPass.hlsl | 4 +- .../Includes/LightingMetaPass.hlsl | 4 +- .../ShaderGraph/Includes/PBR2DPass.hlsl | 6 +- .../ShaderGraph/Includes/PBRGBufferPass.hlsl | 6 +- .../Includes/ShadowCasterPass.hlsl | 4 +- .../Includes/SpriteForwardPass.hlsl | 6 +- .../ShaderGraph/Includes/SpriteLitPass.hlsl | 4 +- .../Includes/SpriteNormalPass.hlsl | 4 +- .../ShaderGraph/Includes/SpriteUnlitPass.hlsl | 4 +- .../ShaderGraph/Includes/UnlitPass.hlsl | 6 +- .../Editor/ShaderGraph/Includes/Varyings.hlsl | 7 +- .../Targets/UniversalLitSubTarget.cs | 86 +- .../Targets/UniversalSpriteLitSubTarget.cs | 26 +- .../Targets/UniversalSpriteUnlitSubTarget.cs | 14 +- .../ShaderGraph/Targets/UniversalTarget.cs | 106 +- .../Targets/UniversalUnlitSubTarget.cs | 20 +- .../Editor/ShaderGraph/UniversalFields.cs | 12 +- .../ShaderGraph/UniversalStructFields.cs | 10 +- .../Editor/ShaderGraph/UniversalStructs.cs | 2 +- .../Editor/ShaderPreprocessor.cs | 23 +- .../Editor/Shadow/ShadowCascadeSplitGUI.cs | 8 +- .../UniversalAdditionalCameraDataEditor.cs | 1 + .../Editor/UniversalAnalytics.cs | 2 +- .../UniversalRenderPipelineAssetEditor.cs | 8 +- .../UniversalRenderPipelineCameraEditor.cs | 32 +- .../UniversalRenderPipelineLightEditor.cs | 10 +- ...UniversalRenderPipelineMaterialUpgrader.cs | 4 +- .../Runtime/2D/Clipper.cs | 43 +- .../Runtime/2D/Light2D.cs | 8 +- .../Runtime/2D/Light2DAuthoring.cs | 5 +- .../Runtime/2D/Light2DBlendStyle.cs | 1 - .../Runtime/2D/Light2DCullResult.cs | 1 + .../Runtime/2D/Light2DManager.cs | 9 +- .../Runtime/2D/Light2DStub.cs | 2 +- .../Runtime/2D/LightUtility.cs | 25 +- .../Runtime/2D/Passes/Render2DLightingPass.cs | 5 +- .../Runtime/2D/Passes/Utility/LayerUtility.cs | 14 +- .../2D/Passes/Utility/RendererLighting.cs | 8 +- .../Runtime/2D/PixelPerfectCamera.cs | 2 + .../Runtime/2D/PixelPerfectCameraInternal.cs | 6 +- .../Runtime/2D/Renderer2DData.cs | 4 +- .../Runtime/2D/Renderer2DDataAuthoring.cs | 1 + .../2D/Shadows/CompositeShadowCaster2D.cs | 1 - .../Runtime/2D/Shadows/ShadowCaster2D.cs | 13 +- .../2D/Shadows/ShadowCasterGroup2DManager.cs | 1 + .../Runtime/2D/Shadows/ShadowUtility.cs | 16 +- .../Runtime/AssemblyInfo.cs | 2 +- .../Runtime/Data/PostProcessData.cs | 1 + .../Runtime/Data/RenderStateData.cs | 2 +- .../Data/UniversalRenderPipelineAsset.cs | 15 +- .../Runtime/Data/XRSystemData.cs | 1 + .../Runtime/DeferredLights.cs | 169 +- .../Runtime/DeferredShaderData.cs | 1 - .../Runtime/DeferredTiler.cs | 49 +- .../Runtime/Deprecated.cs | 5 +- .../Runtime/External/LibTessDotNet/Dict.cs | 136 +- .../Runtime/External/LibTessDotNet/Geom.cs | 426 ++-- .../Runtime/External/LibTessDotNet/Mesh.cs | 773 +++---- .../External/LibTessDotNet/MeshUtils.cs | 691 +++--- .../External/LibTessDotNet/PriorityHeap.cs | 322 ++- .../External/LibTessDotNet/PriorityQueue.cs | 310 +-- .../Runtime/External/LibTessDotNet/Sweep.cs | 2020 +++++++++-------- .../Runtime/External/LibTessDotNet/Tess.cs | 1114 ++++----- .../Runtime/ForwardLights.cs | 24 +- .../Runtime/ForwardRenderer.cs | 31 +- .../Runtime/ForwardRendererData.cs | 1 + .../Runtime/Overrides/ColorCurves.cs | 8 +- .../Runtime/Overrides/ColorLookup.cs | 6 +- .../Runtime/Overrides/DepthOfField.cs | 2 +- .../Runtime/Overrides/FilmGrain.cs | 2 +- .../Runtime/Overrides/MotionBlur.cs | 4 +- .../Runtime/Overrides/Tonemapping.cs | 2 +- .../AdditionalLightsShadowCasterPass.cs | 8 +- .../Runtime/Passes/ColorGradingLutPass.cs | 6 +- .../Runtime/Passes/DepthNormalOnlyPass.cs | 3 +- .../Runtime/Passes/DepthOnlyPass.cs | 1 - .../Runtime/Passes/DrawObjectsPass.cs | 4 +- .../Runtime/Passes/FinalBlitPass.cs | 1 - .../Passes/MainLightShadowCasterPass.cs | 4 +- .../Runtime/Passes/PostProcessPass.cs | 11 +- .../Runtime/Passes/RenderObjectsPass.cs | 5 +- .../Runtime/Passes/ScriptableRenderPass.cs | 11 +- .../Runtime/Passes/TransparentSettingsPass.cs | 2 - .../DisallowMultipleRendererFeature.cs | 2 +- .../Runtime/RendererFeatures/RenderObjects.cs | 5 +- .../ScreenSpaceAmbientOcclusion.cs | 8 +- .../Runtime/RenderingUtils.cs | 12 +- .../Runtime/SceneViewDrawMode.cs | 4 +- .../Runtime/ScriptableRenderer.cs | 31 +- .../Runtime/ScriptableRendererData.cs | 8 +- .../Runtime/ShaderUtils.cs | 1 + .../Runtime/StencilUsage.cs | 3 +- .../Runtime/UniversalAdditionalCameraData.cs | 6 +- .../Runtime/UniversalRenderPipeline.cs | 152 +- .../Runtime/UniversalRenderPipelineCore.cs | 4 +- .../Runtime/XR/XRPass.cs | 14 +- .../Runtime/XR/XRSystem.cs | 18 +- .../ShaderLibrary/ShaderGraphFunctions.hlsl | 2 +- .../UniversalDOTSInstancing.hlsl | 3 +- .../2D/Include/CombinedShapeLightShared.hlsl | 4 +- .../Shaders/2D/Include/LightingUtility.hlsl | 17 +- .../2D/Include/NormalsRenderingShared.hlsl | 2 +- .../2D/Light2D-Point-Volumetric.shader | 14 +- .../Shaders/2D/Light2D-Point.shader | 12 +- .../2D/Light2D-Shape-Volumetric.shader | 2 +- .../Shaders/2D/Light2D-Shape.shader | 2 +- .../Shaders/2D/ShadowGroup2D.shader | 4 +- .../Shaders/2D/Sprite-Lit-Default.shader | 30 +- .../Shaders/Particles/ParticlesLit.shader | 2 +- .../Shaders/PostProcessing/FinalPost.shader | 4 +- .../PostProcessing/LutBuilderHdr.shader | 4 +- .../PostProcessing/LutBuilderLdr.shader | 2 +- .../PostProcessing/PaniniProjection.shader | 2 +- .../SubpixelMorphologicalAntialiasing.hlsl | 6 +- .../SubpixelMorphologicalAntialiasing.shader | 2 +- ...bpixelMorphologicalAntialiasingBridge.hlsl | 6 +- .../Shaders/Shaders.cs | 2 +- .../Shaders/Terrain/TerrainLit.shader | 8 +- .../Shaders/Terrain/TerrainLitAdd.shader | 8 +- .../Shaders/Terrain/TerrainLitBase.shader | 8 +- .../Shaders/Terrain/TerrainLitPasses.hlsl | 20 +- .../Shaders/Utils/MaterialError.shader | 2 +- .../Tests/Runtime/Light2DTests.cs | 6 +- .../Tests/Runtime/RuntimeTests.cs | 3 +- .../Editor/API/AsyncBuildReportJob.cs | 2 +- .../Editor/API/AsyncJob.cs | 6 +- .../Editor/API/BuildReportFeature.cs | 2 +- .../Editor/API/EditorShaderTools.cs | 4 +- .../Editor/API/Export/ExportFormat.cs | 4 +- .../Editor/API/Export/IReportDiffExport.cs | 2 +- .../Editor/API/Export/IReportExport.cs | 2 +- .../API/Export/ReportDiffExportAttribute.cs | 2 +- .../API/Export/ReportDiffExporterIndex.cs | 2 +- .../API/Export/ReportExportAttribute.cs | 2 +- .../Editor/API/Export/ReportExporterIndex.cs | 2 +- .../API/Export/ShaderBuildReportDiff.cs | 2 +- .../Editor/API/IAsyncJob.cs | 2 +- .../Editor/API/IPlatformJobFactory.cs | 2 +- .../Editor/API/PlatformJob.cs | 2 +- .../Editor/API/ShaderAnalysisReport.cs | 28 +- .../Editor/API/ShaderBuildReport.cs | 2 +- .../Editor/API/ShaderCompilationUtility.cs | 2 +- .../Editor/API/ShaderCompilerOptions.cs | 2 +- .../Editor/API/ShaderProfile.cs | 2 +- .../Editor/API/ShaderProgramFilter.cs | 3 +- .../Editor/Internal/AssemblyProperties.cs | 2 +- .../Editor/Internal/AssetMetadata.cs | 2 +- .../Editor/Internal/EditorUpdateManager.cs | 2 +- .../Internal/Export/CSV/CSVReportExport.cs | 2 +- .../Editor/Internal/ExporterUtilities.cs | 2 +- .../Editor/Internal/PackagesUtilities.cs | 2 +- .../Editor/Internal/ProcessManager.cs | 4 +- .../Editor/Internal/ProcessOperationBase.cs | 2 +- .../Internal/ShaderAnalysisInspectorWindow.cs | 10 +- .../Editor/Internal/ShaderAnalysisMenu.cs | 2 +- .../Editor/Internal/ShaderAnalysisReport.cs | 2 +- .../Editor/Internal/ShaderAnalysisUtils.cs | 13 +- .../Editor/Internal/SimpleDataCache.cs | 2 +- .../Editor/Internal/SymbolicLinkUtilities.cs | 2 +- .../Editor/Internal/UIUtils.cs | 2 +- .../Editor/Platforms/BuildReportJobAsync.cs | 2 +- .../Platforms/ComputeShaderReportBuildData.cs | 2 +- .../Editor/Platforms/Internal/Utility.cs | 2 +- .../Editor/Platforms/ProgressWrapper.cs | 4 +- .../Editor/Platforms/ReportBuildData.cs | 4 +- .../Editor/Platforms/ShaderCompiler.cs | 4 +- .../Editor/Platforms/ShaderReportBuildData.cs | 4 +- .../EditMode/SymbolicLinkUtilitiesTests.cs | 2 +- .../AssetCallbacks/CreateVFXShaderGraph.cs | 6 +- .../Data/Attributes/InspectableAttribute.cs | 2 +- .../Attributes/SGPropertyDrawerAttribute.cs | 2 +- .../Editor/Data/ContextData.cs | 2 +- .../Data/Graphs/AbstractShaderProperty.cs | 26 +- .../Editor/Data/Graphs/BooleanMaterialSlot.cs | 1 - .../Editor/Data/Graphs/ColorShaderProperty.cs | 11 +- .../Data/Graphs/DynamicVectorMaterialSlot.cs | 1 - .../Editor/Data/Graphs/GraphConcretization.cs | 2 + .../Editor/Data/Graphs/GraphData.cs | 132 +- .../Editor/Data/Graphs/GraphSetup.cs | 6 +- .../Editor/Data/Graphs/GraphValidation.cs | 2 +- .../Editor/Data/Graphs/GroupData.cs | 10 +- .../Graphs/LightmappingShaderProperties.cs | 18 +- .../Editor/Data/Graphs/MaterialSlot.cs | 4 +- .../Editor/Data/Graphs/Matrix2MaterialSlot.cs | 1 - .../Data/Graphs/Matrix4ShaderProperty.cs | 2 +- .../Editor/Data/Graphs/MinimalGraphData.cs | 2 +- .../Editor/Data/Graphs/ParentGroupChange.cs | 1 - .../Editor/Data/Graphs/PreviewProperty.cs | 1 - .../Data/Graphs/SamplerStateMaterialSlot.cs | 3 +- .../Data/Graphs/SerializableVirtualTexture.cs | 1 - .../Editor/Data/Graphs/ShaderKeyword.cs | 22 +- .../Editor/Data/Graphs/StickyNoteData.cs | 3 - .../Data/Graphs/Texture2DArrayMaterialSlot.cs | 1 - .../Editor/Data/Graphs/Vector1MaterialSlot.cs | 1 + .../Data/Graphs/Vector1ShaderProperty.cs | 14 +- .../Data/Graphs/Vector4ShaderProperty.cs | 4 +- .../Graphs/VirtualTextureShaderProperty.cs | 1 + .../Editor/Data/Implementation/NodeUtils.cs | 47 +- .../Interfaces/IMayRequireVertexSkinning.cs | 2 +- .../Editor/Data/Interfaces/IPropertyDrawer.cs | 2 +- .../Editor/Data/Legacy/ILegacyTarget.cs | 2 +- .../Editor/Data/Legacy/IMasterNode1.cs | 2 +- .../Data/Legacy/SpriteLitMasterNode1.cs | 2 +- .../Data/Legacy/SpriteUnlitMasterNode1.cs | 2 +- .../Data/Legacy/VisualEffectMasterNode1.cs | 2 +- .../Editor/Data/Nodes/AbstractMaterialNode.cs | 35 +- .../Artistic/Adjustment/ChannelMixerNode.cs | 18 +- .../Nodes/Artistic/Adjustment/ContrastNode.cs | 2 +- .../Data/Nodes/Artistic/Adjustment/HueNode.cs | 4 +- .../Artistic/Adjustment/InvertColorsNode.cs | 20 +- .../Artistic/Adjustment/ReplaceColorNode.cs | 2 +- .../Data/Nodes/Artistic/Blend/BlendNode.cs | 44 +- .../Data/Nodes/Artistic/Filter/DitherNode.cs | 2 +- .../Nodes/Artistic/Mask/ChannelMaskNode.cs | 68 +- .../Data/Nodes/Artistic/Mask/ColorMaskNode.cs | 2 +- .../Artistic/Normal/NormalFromHeightNode.cs | 54 +- .../Artistic/Normal/NormalFromTextureNode.cs | 40 +- .../Artistic/Normal/NormalReconstructZNode.cs | 4 +- .../Artistic/Normal/NormalStrengthNode.cs | 3 +- .../Nodes/Artistic/Normal/NormalUnpackNode.cs | 5 +- .../Artistic/Utility/ColorspaceConversion.cs | 19 +- .../Editor/Data/Nodes/BlockNode.cs | 52 +- .../Editor/Data/Nodes/Channel/CombineNode.cs | 1 - .../Editor/Data/Nodes/Channel/FlipNode.cs | 21 +- .../Editor/Data/Nodes/Channel/SplitNode.cs | 1 - .../Editor/Data/Nodes/Channel/SwizzleNode.cs | 15 +- .../Editor/Data/Nodes/CodeFunctionNode.cs | 28 +- .../Editor/Data/Nodes/GeometryNode.cs | 4 +- .../Data/Nodes/Input/Basic/BooleanNode.cs | 3 +- .../Data/Nodes/Input/Basic/ColorNode.cs | 5 +- .../Data/Nodes/Input/Basic/IntegerNode.cs | 1 - .../Data/Nodes/Input/Basic/SliderNode.cs | 3 +- .../Editor/Data/Nodes/Input/Basic/TimeNode.cs | 1 - .../Data/Nodes/Input/Basic/Vector1Node.cs | 3 +- .../Data/Nodes/Input/Basic/Vector2Node.cs | 7 +- .../Data/Nodes/Input/Basic/Vector3Node.cs | 9 +- .../Data/Nodes/Input/Basic/Vector4Node.cs | 11 +- .../Input/Geometry/BitangentVectorNode.cs | 1 - .../Nodes/Input/Geometry/NormalVectorNode.cs | 1 - .../Data/Nodes/Input/Geometry/PositionNode.cs | 13 +- .../Input/Geometry/ScreenPositionNode.cs | 1 - .../Nodes/Input/Geometry/TangentVectorNode.cs | 1 - .../Data/Nodes/Input/Geometry/UVNode.cs | 1 - .../Nodes/Input/Geometry/VertexColorNode.cs | 1 - .../Nodes/Input/Geometry/ViewDirectionNode.cs | 11 +- .../Data/Nodes/Input/Gradient/GradientNode.cs | 2 +- .../Input/Gradient/SampleGradientNode.cs | 2 +- .../Data/Nodes/Input/Lighting/AmbientNode.cs | 1 - .../Data/Nodes/Input/Lighting/BakedGINode.cs | 27 +- .../Input/Lighting/ReflectionProbeNode.cs | 3 +- .../Data/Nodes/Input/Matrix/Matrix2Node.cs | 1 - .../Data/Nodes/Input/Matrix/Matrix3Node.cs | 1 - .../Data/Nodes/Input/Matrix/Matrix4Node.cs | 1 - .../Input/Matrix/TransformationMatrixNode.cs | 3 +- .../Nodes/Input/PBR/DielectricSpecularNode.cs | 1 - .../Nodes/Input/PBR/MetalReflectanceNode.cs | 1 - .../Editor/Data/Nodes/Input/PropertyNode.cs | 7 +- .../Data/Nodes/Input/Scene/CameraNode.cs | 1 - .../Editor/Data/Nodes/Input/Scene/FogNode.cs | 3 +- .../Data/Nodes/Input/Scene/ObjectNode.cs | 1 - .../Data/Nodes/Input/Scene/SceneColorNode.cs | 2 +- .../Data/Nodes/Input/Scene/SceneDepthNode.cs | 8 +- .../Data/Nodes/Input/Scene/ScreenNode.cs | 1 - .../Nodes/Input/Texture/CubemapAssetNode.cs | 1 - .../Texture/ProceduralVirtualTextureNode.cs | 1 - .../Nodes/Input/Texture/SampleCubemapNode.cs | 13 +- .../Input/Texture/SampleRawCubemapNode.cs | 11 +- .../Input/Texture/SampleTexture2DArrayNode.cs | 11 +- .../Input/Texture/SampleTexture2DLODNode.cs | 11 +- .../Input/Texture/SampleTexture2DNode.cs | 9 +- .../Input/Texture/SampleTexture3DNode.cs | 9 +- .../Input/Texture/SampleVirtualTextureNode.cs | 2 +- .../Nodes/Input/Texture/SamplerStateNode.cs | 9 +- .../Data/Nodes/Input/Texture/TexelSizeNode.cs | 8 +- .../Input/Texture/Texture2DArrayAssetNode.cs | 1 - .../Nodes/Input/Texture/Texture2DAssetNode.cs | 1 - .../Nodes/Input/Texture/Texture3DAssetNode.cs | 1 - .../Data/Nodes/LegacyUnknownTypeNode.cs | 3 +- .../Data/Nodes/Math/Advanced/AbsoluteNode.cs | 3 +- .../Nodes/Math/Advanced/ExponentialNode.cs | 5 +- .../Data/Nodes/Math/Advanced/LengthNode.cs | 3 +- .../Data/Nodes/Math/Advanced/LogNode.cs | 7 +- .../Data/Nodes/Math/Advanced/ModuloNode.cs | 3 +- .../Data/Nodes/Math/Advanced/NegateNode.cs | 3 +- .../Data/Nodes/Math/Advanced/NormalizeNode.cs | 3 +- .../Data/Nodes/Math/Advanced/PosterizeNode.cs | 3 +- .../Nodes/Math/Advanced/ReciprocalNode.cs | 5 +- .../Math/Advanced/ReciprocalSquareRootNode.cs | 3 +- .../Editor/Data/Nodes/Math/Basic/AddNode.cs | 2 +- .../Data/Nodes/Math/Basic/DivideNode.cs | 1 - .../Data/Nodes/Math/Basic/MultiplyNode.cs | 36 +- .../Editor/Data/Nodes/Math/Basic/PowerNode.cs | 3 +- .../Data/Nodes/Math/Basic/SquareRootNode.cs | 3 +- .../Data/Nodes/Math/Basic/SubtractNode.cs | 3 +- .../Data/Nodes/Math/Derivative/DDXNode.cs | 3 +- .../Data/Nodes/Math/Derivative/DDXYNode.cs | 3 +- .../Data/Nodes/Math/Derivative/DDYNode.cs | 3 +- .../Math/Interpolation/InverseLerpNode.cs | 3 +- .../Data/Nodes/Math/Interpolation/LerpNode.cs | 3 +- .../Math/Interpolation/SmoothstepNode.cs | 3 +- .../Math/Matrix/MatrixConstructionNode.cs | 43 +- .../Math/Matrix/MatrixDeterminantNode.cs | 2 +- .../Data/Nodes/Math/Matrix/MatrixSplitNode.cs | 3 +- .../Nodes/Math/Matrix/MatrixTransposeNode.cs | 3 +- .../Editor/Data/Nodes/Math/Range/ClampNode.cs | 3 +- .../Data/Nodes/Math/Range/FractionNode.cs | 3 +- .../Data/Nodes/Math/Range/MaximumNode.cs | 3 +- .../Data/Nodes/Math/Range/MinimumNode.cs | 3 +- .../Data/Nodes/Math/Range/OneMinusNode.cs | 3 +- .../Data/Nodes/Math/Range/RandomRangeNode.cs | 3 +- .../Editor/Data/Nodes/Math/Range/RemapNode.cs | 3 +- .../Data/Nodes/Math/Range/SaturateNode.cs | 3 +- .../Data/Nodes/Math/Round/CeilingNode.cs | 3 +- .../Editor/Data/Nodes/Math/Round/FloorNode.cs | 3 +- .../Editor/Data/Nodes/Math/Round/RoundNode.cs | 3 +- .../Editor/Data/Nodes/Math/Round/SignNode.cs | 3 +- .../Editor/Data/Nodes/Math/Round/StepNode.cs | 3 +- .../Data/Nodes/Math/Round/TruncateNode.cs | 3 +- .../Nodes/Math/Trigonometry/ArccosineNode.cs | 3 +- .../Nodes/Math/Trigonometry/ArcsineNode.cs | 3 +- .../Math/Trigonometry/Arctangent2Node.cs | 3 +- .../Nodes/Math/Trigonometry/ArctangentNode.cs | 3 +- .../Nodes/Math/Trigonometry/CosineNode.cs | 3 +- .../Math/Trigonometry/DegreesToRadiansNode.cs | 3 +- .../Math/Trigonometry/HyperbolicCosineNode.cs | 3 +- .../Math/Trigonometry/HyperbolicSineNode.cs | 3 +- .../Trigonometry/HyperbolicTangentNode.cs | 3 +- .../Math/Trigonometry/RadiansToDegreesNode.cs | 3 +- .../Data/Nodes/Math/Trigonometry/SineNode.cs | 3 +- .../Nodes/Math/Trigonometry/TangentNode.cs | 3 +- .../Nodes/Math/Vector/CrossProductNode.cs | 3 +- .../Data/Nodes/Math/Vector/DistanceNode.cs | 3 +- .../Data/Nodes/Math/Vector/DotProductNode.cs | 3 +- .../Nodes/Math/Vector/FresnelEffectNode.cs | 3 +- .../Data/Nodes/Math/Vector/ProjectionNode.cs | 3 +- .../Data/Nodes/Math/Vector/ReflectionNode.cs | 1 - .../Data/Nodes/Math/Vector/RejectionNode.cs | 3 +- .../Nodes/Math/Vector/RotateAboutAxisNode.cs | 9 +- .../Data/Nodes/Math/Vector/TransformNode.cs | 7 +- .../Data/Nodes/Math/Wave/NoiseSineWaveNode.cs | 5 +- .../Data/Nodes/Math/Wave/SawtoothWaveNode.cs | 5 +- .../Data/Nodes/Math/Wave/SquareWaveNode.cs | 5 +- .../Data/Nodes/Math/Wave/TriangleWaveNode.cs | 5 +- .../MeshDeformation/ComputeDeformNode.cs | 16 +- .../LinearBlendSkinningNode.cs | 34 +- .../Editor/Data/Nodes/NodeClassCache.cs | 38 +- .../Data/Nodes/Procedural/CheckerboardNode.cs | 3 +- .../Procedural/Noise/GradientNoiseNode.cs | 5 +- .../Nodes/Procedural/Noise/SimpleNoiseNode.cs | 3 +- .../Nodes/Procedural/Noise/VoronoiNode.cs | 2 +- .../Nodes/Procedural/Shape/EllipseNode.cs | 3 +- .../Nodes/Procedural/Shape/PolygonNode.cs | 3 +- .../Nodes/Procedural/Shape/RectangleNode.cs | 3 +- .../Procedural/Shape/RoundedRectangleNode.cs | 3 +- .../Editor/Data/Nodes/SlotValue.cs | 8 +- .../Editor/Data/Nodes/UV/FlipbookNode.cs | 58 +- .../Data/Nodes/UV/ParallaxMappingNode.cs | 5 +- .../Nodes/UV/ParallaxOcclusionMappingNode.cs | 41 +- .../Data/Nodes/UV/PolarCoordinatesNode.cs | 3 +- .../Editor/Data/Nodes/UV/RadialShearNode.cs | 3 +- .../Editor/Data/Nodes/UV/RotateNode.cs | 3 +- .../Editor/Data/Nodes/UV/SpherizeNode.cs | 3 +- .../Data/Nodes/UV/TilingAndOffsetNode.cs | 3 +- .../Editor/Data/Nodes/UV/TriplanarNode.cs | 3 +- .../Editor/Data/Nodes/UV/TwirlNode.cs | 3 +- .../Data/Nodes/Utility/CustomFunctionNode.cs | 26 +- .../Editor/Data/Nodes/Utility/KeywordNode.cs | 20 +- .../Data/Nodes/Utility/Logic/AllNode.cs | 3 +- .../Data/Nodes/Utility/Logic/AndNode.cs | 3 +- .../Data/Nodes/Utility/Logic/AnyNode.cs | 3 +- .../Data/Nodes/Utility/Logic/BranchNode.cs | 3 +- .../Nodes/Utility/Logic/ComparisonNode.cs | 13 +- .../Nodes/Utility/Logic/IsFrontFaceNode.cs | 34 +- .../Nodes/Utility/Logic/IsInfiniteNode.cs | 3 +- .../Data/Nodes/Utility/Logic/IsNanNode.cs | 3 +- .../Data/Nodes/Utility/Logic/NandNode.cs | 3 +- .../Data/Nodes/Utility/Logic/NotNode.cs | 3 +- .../Editor/Data/Nodes/Utility/Logic/OrNode.cs | 3 +- .../Editor/Data/Nodes/Utility/PreviewNode.cs | 3 +- .../Data/Nodes/Utility/RedirectNodeData.cs | 4 +- .../Data/Nodes/Utility/RedirectNodeView.cs | 5 +- .../Editor/Data/Nodes/Utility/SubGraphNode.cs | 190 +- .../Editor/Data/SubGraph/SubGraphAsset.cs | 13 +- .../Data/SubGraph/SubGraphOutputNode.cs | 14 +- .../Editor/Data/Util/GradientUtil.cs | 28 +- .../Editor/Data/Util/GraphUtil.cs | 6 +- .../Editor/Data/Util/KeywordCollector.cs | 18 +- .../Data/Util/KeywordDependentCollection.cs | 18 +- .../Editor/Data/Util/KeywordUtil.cs | 38 +- .../Editor/Data/Util/PooledHashSet.cs | 1 + .../Editor/Data/Util/PooledList.cs | 1 + .../Editor/Data/Util/PrecisionUtil.cs | 4 +- .../Editor/Data/Util/SerializationHelper.cs | 6 +- .../Util/ShaderGraphRequirementsPerKeyword.cs | 10 +- .../Editor/Data/Util/SlotValueTypeUtil.cs | 2 +- .../Editor/Data/Util/TextUtil.cs | 2 +- .../Drawing/Blackboard/BlackboardFieldView.cs | 62 +- .../Drawing/Blackboard/BlackboardProvider.cs | 19 +- .../Editor/Drawing/Colors/ColorManager.cs | 18 +- .../Editor/Drawing/Colors/CustomColorData.cs | 6 +- .../Editor/Drawing/Colors/PrecisionColors.cs | 2 +- .../Editor/Drawing/Colors/UserColors.cs | 2 +- .../Controls/DielectricSpecularControl.cs | 34 +- .../Editor/Drawing/Controls/VectorControl.cs | 58 +- .../Editor/Drawing/EdgeConnectorListener.cs | 2 +- .../Editor/Drawing/Inspector/InspectorView.cs | 10 +- .../Drawing/Inspector/PropertyDrawerUtils.cs | 2 +- .../AbstractMaterialNodePropertyDrawer.cs | 7 +- .../PropertyDrawers/BoolPropertyDrawer.cs | 6 +- .../PropertyDrawers/ColorPropertyDrawer.cs | 6 +- .../PropertyDrawers/CubemapPropertyDrawer.cs | 6 +- .../CustomFunctionNodePropertyDrawer.cs | 4 +- .../PropertyDrawers/DropdownPropertyDrawer.cs | 6 +- .../PropertyDrawers/EnumPropertyDrawer.cs | 10 +- .../PropertyDrawers/FloatPropertyDrawer.cs | 6 +- .../PropertyDrawers/GradientPropertyDrawer.cs | 6 +- .../GraphDataPropertyDrawer.cs | 26 +- .../PropertyDrawers/IShaderPropertyDrawer.cs | 2 +- .../PropertyDrawers/IntegerPropertyDrawer.cs | 4 +- .../PropertyDrawers/MatrixPropertyDrawer.cs | 10 +- .../SampleVirtualTextureNodePropertyDrawer.cs | 50 +- .../ShaderInputPropertyDrawer.cs | 229 +- .../SubGraphOutputNodePropertyDrawer.cs | 2 +- .../PropertyDrawers/TextPropertyDrawer.cs | 6 +- .../Texture2DArrayPropertyDrawer.cs | 6 +- .../Texture2DPropertyDrawer.cs | 6 +- .../Texture3DPropertyDrawer.cs | 6 +- .../ToggleDataPropertyDrawer.cs | 6 +- .../PropertyDrawers/Vector2PropertyDrawer.cs | 5 +- .../PropertyDrawers/Vector3PropertyDrawer.cs | 5 +- .../PropertyDrawers/Vector4PropertyDrawer.cs | 5 +- .../Drawing/Inspector/TabbedView/TabButton.cs | 18 +- .../Inspector/TabbedView/TabbedView.cs | 27 +- .../Drawing/Manipulators/ResizeSideHandle.cs | 1 + .../Editor/Drawing/MaterialGraphEditWindow.cs | 15 +- .../Editor/Drawing/PreviewManager.cs | 270 +-- .../Editor/Drawing/SearchWindowAdapter.cs | 11 +- .../Editor/Drawing/SearchWindowProvider.cs | 100 +- .../Editor/Drawing/Views/ContextView.cs | 16 +- .../Editor/Drawing/Views/GradientEdge.cs | 1 - .../Editor/Drawing/Views/GraphEditorView.cs | 127 +- .../Editor/Drawing/Views/GraphSubWindow.cs | 14 +- .../Editor/Drawing/Views/HelpBoxRow.cs | 4 +- .../Editor/Drawing/Views/HlslFunctionView.cs | 24 +- .../Editor/Drawing/Views/IdentifierField.cs | 6 +- .../Editor/Drawing/Views/MaterialGraphView.cs | 59 +- .../Editor/Drawing/Views/MaterialNodeView.cs | 22 +- .../Editor/Drawing/Views/PropertyNodeView.cs | 42 +- .../Editor/Drawing/Views/PropertyRow.cs | 4 +- .../Drawing/Views/ReorderableSlotListView.cs | 28 +- .../Drawing/Views/ReorderableTextListView.cs | 1 - .../Editor/Drawing/Views/ShaderGroup.cs | 3 +- .../Editor/Drawing/Views/ShaderPort.cs | 2 +- .../Views/Slots/GradientSlotControlView.cs | 2 +- .../Views/Slots/MultiFloatSlotControlView.cs | 62 +- .../Editor/Drawing/Views/StickyNote.cs | 6 +- .../Editor/Extensions/FieldExtensions.cs | 6 +- .../Extensions/IConditionalExtensions.cs | 10 +- .../Attributes/GenerateBlocksAttribute.cs | 2 +- .../Collections/DefineCollection.cs | 6 +- .../Collections/DependencyCollection.cs | 4 +- .../Generation/Collections/FieldCollection.cs | 4 +- .../Collections/IncludeCollection.cs | 6 +- .../Collections/KeywordCollection.cs | 6 +- .../Generation/Collections/PassCollection.cs | 6 +- .../Collections/PragmaCollection.cs | 6 +- .../Collections/RenderStateCollection.cs | 6 +- .../Collections/StructCollection.cs | 6 +- .../Contexts/TargetActiveBlockContext.cs | 4 +- .../Contexts/TargetPropertyGUIContext.cs | 7 +- .../Generation/Data/ConditionalField.cs | 2 +- .../Editor/Generation/Data/FieldCondition.cs | 2 +- .../Editor/Generation/Data/FieldDependency.cs | 2 +- .../Editor/Generation/Data/KeywordEntry.cs | 2 +- .../Descriptors/BlockFieldDescriptor.cs | 8 +- .../Generation/Descriptors/FieldDescriptor.cs | 6 +- .../Descriptors/IncludeDescriptor.cs | 2 +- .../Descriptors/KeywordDescriptor.cs | 2 +- .../Descriptors/PragmaDescriptor.cs | 2 +- .../Descriptors/RenderStateDescriptor.cs | 2 +- .../Descriptors/StructDescriptor.cs | 2 +- .../Editor/Generation/Enumerations/Blend.cs | 2 +- .../Editor/Generation/Enumerations/BlendOp.cs | 2 +- .../Editor/Generation/Enumerations/Cull.cs | 2 +- .../Enumerations/IncludeLocation.cs | 2 +- .../Enumerations/InstancingOptions.cs | 4 +- .../Enumerations/KeywordDefinition.cs | 2 +- .../Generation/Enumerations/KeywordScope.cs | 2 +- .../Generation/Enumerations/KeywordType.cs | 2 +- .../Generation/Enumerations/Platform.cs | 2 +- .../Generation/Enumerations/RenderQueue.cs | 2 +- .../Generation/Enumerations/RenderType.cs | 2 +- .../Generation/Enumerations/ShaderModel.cs | 4 +- .../Enumerations/ShaderValueType.cs | 2 +- .../Enumerations/StructFieldOptions.cs | 2 +- .../Editor/Generation/Enumerations/ZTest.cs | 2 +- .../Editor/Generation/Enumerations/ZWrite.cs | 2 +- .../Editor/Generation/OutputMetadata.cs | 2 +- .../Generation/Processors/ActiveFields.cs | 16 +- .../Generation/Processors/GenerationUtils.cs | 99 +- .../Editor/Generation/Processors/Generator.cs | 120 +- .../Processors/GraphCompilationResult.cs | 2 +- .../Processors/PropertyCollector.cs | 8 +- .../Generation/Processors/ShaderSpliceUtil.cs | 18 +- .../Processors/ShaderStringBuilder.cs | 8 +- .../Editor/Generation/ShaderGraphVfxAsset.cs | 9 +- .../Editor/Generation/SubTarget.cs | 4 +- .../Editor/Generation/Target.cs | 5 +- .../Generation/TargetResources/BlockFields.cs | 2 +- .../Generation/TargetResources/Fields.cs | 8 +- .../TargetResources/StructFields.cs | 156 +- .../Generation/Targets/PreviewTarget.cs | 2 +- .../Editor/Generation/Targets/VFXTarget.cs | 8 +- ...uildSurfaceDescriptionInputs.template.hlsl | 18 +- ...BuildVertexDescriptionInputs.template.hlsl | 2 +- .../Editor/Generation/Utils/TargetUtils.cs | 6 +- .../ShaderGraphAssetPostProcessor.cs | 4 +- .../Editor/Importers/ShaderGraphImporter.cs | 30 +- .../Importers/ShaderGraphImporterEditor.cs | 1 - .../Importers/ShaderSubGraphImporter.cs | 4 +- .../Editor/Interface/IConditional.cs | 2 +- .../Editor/Interface/IShaderString.cs | 2 +- .../Resources/Shaders/FallbackError.shader | 2 +- .../Styles/Controls/ColorControlView.uss | 2 +- .../Styles/Controls/EnumControlView.uss | 2 +- .../Controls/EnumConversionControlView.uss | 6 +- .../Styles/Controls/GradientControlView.uss | 2 +- .../Styles/Controls/IntegerControlView.uss | 1 - .../Styles/Controls/ToggleControlView.uss | 2 +- .../Resources/Styles/GraphSubWindow.uss | 3 +- .../Resources/Styles/MaterialNodeView.uss | 2 +- .../Editor/Resources/Styles/PropertyRow.uss | 2 +- .../Editor/Resources/Styles/RedirectNode.uss | 2 +- .../Styles/ReorderableSlotListView.uss | 2 +- .../Styles/ShaderGraphBlackboard.uss | 2 +- .../Resources/Styles/TabButtonStyles.uss | 32 +- .../Editor/Resources/Styles/TabbedView.uss | 12 +- .../Editor/Resources/UXML/GraphInspector.uxml | 2 +- .../Editor/Resources/UXML/GraphSubWindow.uxml | 2 +- .../Editor/Resources/UXML/NodeSettings.uxml | 7 +- .../Editor/Resources/UXML/StickyNote.uxml | 1 - .../Editor/Resources/UXML/TabButton.uxml | 11 +- .../Editor/Serialization/JsonData.cs | 20 +- .../Editor/Serialization/JsonObject.cs | 14 +- .../Editor/Serialization/JsonRef.cs | 12 +- .../Editor/Serialization/MultiJsonInternal.cs | 44 +- .../Editor/Serialization/RefDataEnumerable.cs | 2 +- .../Editor/ShaderGUI/PBRMasterGUI.cs | 6 +- .../Editor/ShaderGraphPreferences.cs | 18 +- .../Editor/Util/CompatibilityExtensions.cs | 2 + .../Editor/Util/CopyPasteGraph.cs | 2 +- .../Editor/Util/MessageManager.cs | 8 +- .../Editor/Util/UIUtilities.cs | 1 - .../Editor/Util/ValueUtilities.cs | 10 +- .../Utilities/GenerationAPIAttribute.cs | 4 +- .../DummyShaderGraphLibrary.cs | 1 - .../ShaderGraphLibrary/Functions.hlsl | 2 +- .../ShaderGraphLibrary/PreviewPass.hlsl | 6 +- .../Editor/IntegrationTests/NamespaceTests.cs | 5 +- .../IntegrationTests/SerializationTests.cs | 4 +- .../Editor/UnitTests/MessageManagerTests.cs | 2 - .../Editor/UnitTests/SerializedGraphTests.cs | 40 +- .../Tests/Editor/UnitTests/StackTests.cs | 6 +- .../Tests/Editor/UnitTests/TargetTests.cs | 15 +- .../Tests/Editor/UnitTests/UtilityTests.cs | 2 - .../Assets/Scripts/LookWithMouse.cs | 2 +- .../Assets/Scripts/PlayerMovement.cs | 10 +- .../Assets/Scripts/SimpleCameraController.cs | 32 +- .../Scripts/Editor/ReadmeEditor.cs | 294 ++- .../Assets/TutorialInfo/Scripts/Readme.cs | 24 +- .../Editor/InternalTests/ExpectedSettings.cs | 4 +- .../Assets/Scripts/SimpleCameraController.cs | 32 +- .../Scripts/Editor/ReadmeEditor.cs | 294 ++- .../Assets/TutorialInfo/Scripts/Readme.cs | 24 +- .../Tests/Editor/EditorExampleTest.cs | 29 +- .../Editor/InternalTests/ExpectedSettings.cs | 2 +- .../Tests/Runtime/RuntimeExampleTest.cs | 8 +- .../Editor/Compiler/VFXGraphCompiledData.cs | 4 +- .../Editor/Compiler/VFXShaderWriter.cs | 1 - .../Editor/Compiler/VFXUniformMapper.cs | 6 +- .../Editor/Controls/VFXEnumField.cs | 2 +- .../Editor/Controls/VFXEnumValuePopup.cs | 6 +- .../Editor/Controls/VFXLabeledField.cs | 2 +- .../Editor/Controls/VFXReorderableList.cs | 2 +- .../Editor/Controls/VFXSliderField.cs | 8 +- .../Editor/Core/VFXSerializer.cs | 2 +- .../Editor/Data/VFXDataParticle.cs | 12 +- .../Expressions/VFXExpressionAbstract.cs | 5 +- .../Editor/Expressions/VFXExpressionFlow.cs | 2 +- .../Expressions/VFXExpressionSampleSDF.cs | 9 +- .../Editor/Expressions/VFXExpressionStrips.cs | 4 +- .../Expressions/VFXExpressionTextureDim.cs | 8 +- .../Expressions/VFXExpressionTransform.cs | 1 + .../GraphView/Blackboard/VFXBlackboard.cs | 6 +- .../Blackboard/VFXBlackboardField.cs | 2 +- .../Blackboard/VFXBlackboardPropertyView.cs | 13 +- .../Elements/Controllers/VFXNodeController.cs | 2 +- .../Controllers/VFXParameterController.cs | 17 +- .../Controllers/VFXParameterNodeController.cs | 5 +- .../Controllers/VFXSettingController.cs | 3 +- .../Editor/GraphView/Elements/VFXContextUI.cs | 2 +- .../GraphView/Elements/VFXDataAnchor.cs | 6 +- .../GraphView/Elements/VFXEdgeConnector.cs | 9 +- .../GraphView/Elements/VFXEdgeDragInfo.cs | 6 +- .../Editor/GraphView/VFXViewWindow.cs | 4 +- .../Views/Controller/VFXViewController.cs | 15 +- .../Views/Properties/ListPropertiesRM.cs | 16 +- .../Views/Properties/NumericPropertiesRM.cs | 6 +- .../Views/Properties/ObjectPropertyRM.cs | 1 - .../GraphView/Views/Properties/PropertyRM.cs | 5 +- .../Views/Properties/StringPropertyRM.cs | 5 +- .../VFXParameterEnumValuePropertyRM.cs | 3 +- .../Views/Properties/Vector3PropertyRM.cs | 1 - .../Views/Properties/VectorPropertiesRM.cs | 5 +- .../Editor/GraphView/Views/VFXNodeProvider.cs | 2 +- .../Editor/GraphView/Views/VFXPaste.cs | 2 +- .../Editor/GraphView/Views/VFXView.cs | 54 +- .../Editor/Inspector/VFXAssetEditor.cs | 22 +- .../Inspector/VFXSlotContainerEditor.cs | 12 +- .../Editor/Inspector/VisualEffectEditor.cs | 12 +- .../Implementations/Collision/CollisionSDF.cs | 4 +- .../Implementations/Forces/ConformToSDF.cs | 3 +- .../Implementations/Orientation/Orient.cs | 2 +- .../Implementations/Position/PositionAABox.cs | 6 +- .../Implementations/Position/PositionBase.cs | 2 +- .../Position/PositionCircle.cs | 4 +- .../Implementations/Position/PositionDepth.cs | 78 +- .../Implementations/Position/PositionMesh.cs | 3 +- .../Implementations/Position/PositionSDF.cs | 6 +- .../Position/PositionSequential.cs | 15 +- .../Implementations/Position/PositionTorus.cs | 2 +- .../VFXAbstractRenderedOutput.cs | 2 +- .../Implementations/VFXBasicInitialize.cs | 3 +- .../Implementations/VFXBasicUpdate.cs | 2 +- .../Implementations/VFXQuadStripOutput.cs | 2 +- .../Implementations/VFXStaticMeshOutput.cs | 2 +- .../Editor/Models/Contexts/VFXContext.cs | 2 +- .../Models/Contexts/VFXMultiMeshHelper.cs | 4 +- .../Editor/Models/Contexts/VFXOutputUpdate.cs | 6 +- .../Operators/Implementations/SampleSDF.cs | 6 +- .../Implementations/TextureDimensions.cs | 6 +- .../Implementations/WorldToViewportPoint.cs | 10 +- .../Models/Operators/VFXOperatorUtility.cs | 6 +- .../Models/Operators/VFXSubgraphOperator.cs | 8 +- .../Parameters/VFXDynamicBuiltInParameter.cs | 20 +- .../Editor/Models/Parameters/VFXParameter.cs | 4 +- .../Editor/Models/Slots/VFXSlot.cs | 4 +- .../Editor/Models/VFXErrorManager.cs | 15 +- .../Editor/Models/VFXGraph.cs | 10 +- .../Editor/Models/VFXModel.cs | 11 +- .../Editor/Models/VFXParameterInfo.cs | 2 +- .../Editor/Models/VFXSlotContainerModel.cs | 8 +- .../VFXShaderGraphParticleOutput.cs | 2 +- .../Editor/Types/VFXProperty.cs | 2 +- .../Editor/Types/VFXPropertyAttribute.cs | 7 +- .../Editor/UIResources/uss/VFXBlackboard.uss | 2 +- .../UIResources/uss/VFXComponentBoard.uss | 2 +- .../UIResources/uss/VFXEdgeDragInfo.uss | 2 +- .../EventTester/VFXEventTesterWindow.cs | 2 +- .../Editor/Utils/VFXResources.cs | 25 +- .../Editor/VFXAssetEditorUtility.cs | 4 +- .../Implementation/VFXMouseEventBinder.cs | 10 +- .../VFXOutputEventAbstractHandler.cs | 3 +- .../Implementation/VFXInputMouseBinder.cs | 2 +- .../Implementation/VFXInputTouchBinder.cs | 6 +- .../PropertyBinding/VFXPropertyBinder.cs | 1 + ...OutputEventCinemachineCameraShakeEditor.cs | 2 +- .../Editor/VFXOutputEventPlayAudioEditor.cs | 2 +- .../Editor/VFXOutputEventRigidBodyEditor.cs | 2 +- .../Runtime/VFXOutputEventPrefabSpawn.cs | 1 + .../Shaders/VFXCommon.hlsl | 4 +- 1455 files changed, 15797 insertions(+), 16115 deletions(-) diff --git a/com.unity.render-pipelines.core/Editor/CameraEditorUtils.cs b/com.unity.render-pipelines.core/Editor/CameraEditorUtils.cs index 37b941c9849..61d890b25aa 100644 --- a/com.unity.render-pipelines.core/Editor/CameraEditorUtils.cs +++ b/com.unity.render-pipelines.core/Editor/CameraEditorUtils.cs @@ -103,6 +103,7 @@ public static void DrawCameraSceneViewOverlay(Object target, SceneView sceneView previewCamera.targetTexture = null; } } + /// /// Check if the view port rect have a positive size /// diff --git a/com.unity.render-pipelines.core/Editor/ContextualMenuDispatcher.cs b/com.unity.render-pipelines.core/Editor/ContextualMenuDispatcher.cs index 37dde2c699c..5134b3ec652 100644 --- a/com.unity.render-pipelines.core/Editor/ContextualMenuDispatcher.cs +++ b/com.unity.render-pipelines.core/Editor/ContextualMenuDispatcher.cs @@ -39,14 +39,14 @@ static bool DispatchRemoveComponent(T component) static IEnumerable ComponentDependencies(Component component) => component.gameObject - .GetComponents() - .Where(c => c != component - && c.GetType() - .GetCustomAttributes(typeof(RequireComponent), true) - .Count(att => att is RequireComponent rc - && (rc.m_Type0 == component.GetType() - || rc.m_Type1 == component.GetType() - || rc.m_Type2 == component.GetType())) > 0); + .GetComponents() + .Where(c => c != component + && c.GetType() + .GetCustomAttributes(typeof(RequireComponent), true) + .Count(att => att is RequireComponent rc + && (rc.m_Type0 == component.GetType() + || rc.m_Type1 == component.GetType() + || rc.m_Type2 == component.GetType())) > 0); static bool CanRemoveComponent(Component component, out string error) { diff --git a/com.unity.render-pipelines.core/Editor/CoreEditorDrawers.cs b/com.unity.render-pipelines.core/Editor/CoreEditorDrawers.cs index ef2791151e1..559646ddd24 100644 --- a/com.unity.render-pipelines.core/Editor/CoreEditorDrawers.cs +++ b/com.unity.render-pipelines.core/Editor/CoreEditorDrawers.cs @@ -57,7 +57,7 @@ public interface IDrawer /// The data used /// The editor rendering public delegate void SwitchEnabler(TData data, Editor owner); - + /// Delegate that must be used to select sub object for data for drawing /// The type of the sub object used for data /// The data used @@ -74,7 +74,7 @@ public interface IDrawer public static readonly IDrawer space = Group((data, owner) => EditorGUILayout.Space()); /// Use it when IDrawer required but no operation should be done - public static readonly IDrawer noop = Group((data, owner) => { }); + public static readonly IDrawer noop = Group((data, owner) => {}); /// /// Conditioned drawer that will only be drawn if its enabler function is null or return true @@ -308,7 +308,7 @@ class SelectDrawerInternal : IDrawer CoreEditorDrawer.ActionDrawer[] m_SourceDrawers; public SelectDrawerInternal(DataSelect dataSelect, - params CoreEditorDrawer.ActionDrawer[] otherDrawers) + params CoreEditorDrawer.ActionDrawer[] otherDrawers) { m_SourceDrawers = otherDrawers; m_DataSelect = dataSelect; @@ -355,7 +355,7 @@ public static IDrawer FoldoutGroup(string title, TEnum mask, Expa { return FoldoutGroup(EditorGUIUtility.TrTextContent(title), mask, state, contentDrawers); } - + /// Create an IDrawer foldout header using an ExpandedState /// Type of the mask used /// Type of the persistent state @@ -563,7 +563,7 @@ public static IDrawer AdvancedFoldoutGroup(GUIContent foldoutTitl return FoldoutGroup(foldoutTitle, foldoutMask, foldoutState, options, isAdvanced, switchAdvanced, normalContent, Conditional((serialized, owner) => isAdvanced(serialized, owner) && foldoutState[foldoutMask], advancedContent).Draw - ); + ); } } diff --git a/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs b/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs index bae3bdf72d6..cf99affa5c2 100644 --- a/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs +++ b/com.unity.render-pipelines.core/Editor/CoreEditorUtils.cs @@ -460,7 +460,7 @@ public static bool DrawHeaderToggle(string title, SerializedProperty group, Seri /// Callback called when the MoreOptions is toggled /// return the state of the foldout header public static bool DrawHeaderToggle(GUIContent title, SerializedProperty group, SerializedProperty activeField, Action contextAction = null, Func hasMoreOptions = null, Action toggleMoreOptions = null) - => DrawHeaderToggle(title, group, activeField, contextAction, hasMoreOptions, toggleMoreOptions, null); + => DrawHeaderToggle(title, group, activeField, contextAction, hasMoreOptions, toggleMoreOptions, null); /// Draw a header toggle like in Volumes /// The title of the header @@ -596,12 +596,14 @@ public static bool DrawHeaderToggle(GUIContent title, SerializedProperty group, static readonly GUIContent[][] k_DrawVector6_Label = { - new[] { + new[] + { new GUIContent(" X"), new GUIContent(" Y"), new GUIContent(" Z"), }, - new[] { + new[] + { new GUIContent("-X"), new GUIContent("-Y"), new GUIContent("-Z"), @@ -624,13 +626,13 @@ public static bool DrawHeaderToggle(GUIContent title, SerializedProperty group, public static void DrawVector6(GUIContent label, SerializedProperty positive, SerializedProperty negative, Vector3 min, Vector3 max, Color[] colors = null, SerializedProperty multiplicator = null, bool allowIntersection = true) { if (colors != null && (colors.Length != 6)) - throw new System.ArgumentException("Colors must be a 6 element array. [+X, +Y, +X, -X, -Y, -Z]"); + throw new System.ArgumentException("Colors must be a 6 element array. [+X, +Y, +X, -X, -Y, -Z]"); GUILayout.BeginVertical(); const int interline = 2; const int fixAlignSubVector3Labels = -1; - Rect wholeArea = EditorGUILayout.GetControlRect(true, 2*EditorGUIUtility.singleLineHeight + interline); + Rect wholeArea = EditorGUILayout.GetControlRect(true, 2 * EditorGUIUtility.singleLineHeight + interline); Rect firstLineRect = wholeArea; firstLineRect.height = EditorGUIUtility.singleLineHeight; Rect secondLineRect = firstLineRect; @@ -679,7 +681,7 @@ static void DrawVector3(Rect rect, GUIContent[] labels, SerializedProperty value { float[] multifloat = multiplicator == null ? new float[] { value.vector3Value.x, value.vector3Value.y, value.vector3Value.z } - : new float[] { value.vector3Value.x * multiplicator.vector3Value.x, value.vector3Value.y * multiplicator.vector3Value.y, value.vector3Value.z * multiplicator.vector3Value.z }; + : new float[] { value.vector3Value.x * multiplicator.vector3Value.x, value.vector3Value.y * multiplicator.vector3Value.y, value.vector3Value.z * multiplicator.vector3Value.z }; float fieldWidth = rect.width / 3f; const int subLabelWidth = 13; @@ -754,7 +756,7 @@ static void DrawVector3_(Rect rect, GUIContent[] labels, SerializedProperty valu { float[] multifloat = multiplicator == null ? new float[] { value.vector3Value.x, value.vector3Value.y, value.vector3Value.z } - : new float[] { value.vector3Value.x * multiplicator.vector3Value.x, value.vector3Value.y * multiplicator.vector3Value.y, value.vector3Value.z * multiplicator.vector3Value.z }; + : new float[] { value.vector3Value.x * multiplicator.vector3Value.x, value.vector3Value.y * multiplicator.vector3Value.y, value.vector3Value.z * multiplicator.vector3Value.z }; float fieldWidth = rect.width / 3f; EditorGUI.showMixedValue = value.hasMultipleDifferentValues; @@ -764,15 +766,15 @@ static void DrawVector3_(Rect rect, GUIContent[] labels, SerializedProperty valu { value.vector3Value = multiplicator == null ? new Vector3( - Mathf.Clamp(multifloat[0], min.x, max.x), - Mathf.Clamp(multifloat[1], min.y, max.y), - Mathf.Clamp(multifloat[2], min.z, max.z) - ) + Mathf.Clamp(multifloat[0], min.x, max.x), + Mathf.Clamp(multifloat[1], min.y, max.y), + Mathf.Clamp(multifloat[2], min.z, max.z) + ) : new Vector3( - Mathf.Clamp((multiplicator.vector3Value.x < -0.00001 || 0.00001 < multiplicator.vector3Value.x) ? multifloat[0] / multiplicator.vector3Value.x : 0f, min.x, max.x), - Mathf.Clamp((multiplicator.vector3Value.y < -0.00001 || 0.00001 < multiplicator.vector3Value.y) ? multifloat[1] / multiplicator.vector3Value.y : 0f, min.y, max.y), - Mathf.Clamp((multiplicator.vector3Value.z < -0.00001 || 0.00001 < multiplicator.vector3Value.z) ? multifloat[2] / multiplicator.vector3Value.z : 0f, min.z, max.z) - ); + Mathf.Clamp((multiplicator.vector3Value.x < -0.00001 || 0.00001 < multiplicator.vector3Value.x) ? multifloat[0] / multiplicator.vector3Value.x : 0f, min.x, max.x), + Mathf.Clamp((multiplicator.vector3Value.y < -0.00001 || 0.00001 < multiplicator.vector3Value.y) ? multifloat[1] / multiplicator.vector3Value.y : 0f, min.y, max.y), + Mathf.Clamp((multiplicator.vector3Value.z < -0.00001 || 0.00001 < multiplicator.vector3Value.z) ? multifloat[2] / multiplicator.vector3Value.z : 0f, min.z, max.z) + ); } EditorGUI.showMixedValue = false; @@ -933,7 +935,6 @@ static public void CheckOutFile(bool VCSEnabled, UnityObject mat) } } - #region IconAndSkin internal enum Skin diff --git a/com.unity.render-pipelines.core/Editor/Debugging/DebugState.cs b/com.unity.render-pipelines.core/Editor/Debugging/DebugState.cs index e20e00807bd..f70b0162df5 100644 --- a/com.unity.render-pipelines.core/Editor/Debugging/DebugState.cs +++ b/com.unity.render-pipelines.core/Editor/Debugging/DebugState.cs @@ -144,7 +144,7 @@ public sealed class DebugStateInt : DebugState {} /// Flags Debug State. /// [Serializable, DebugState(typeof(DebugUI.BitField))] - public sealed class DebugStateFlags : DebugState { } + public sealed class DebugStateFlags : DebugState {} /// /// Unsigned Integer Debug State. diff --git a/com.unity.render-pipelines.core/Editor/Debugging/DebugUIDrawer.Builtins.cs b/com.unity.render-pipelines.core/Editor/Debugging/DebugUIDrawer.Builtins.cs index bb724c6aa50..b2b04c655d4 100644 --- a/com.unity.render-pipelines.core/Editor/Debugging/DebugUIDrawer.Builtins.cs +++ b/com.unity.render-pipelines.core/Editor/Debugging/DebugUIDrawer.Builtins.cs @@ -105,7 +105,7 @@ public override bool OnGUI(DebugUI.Widget widget, DebugState state) labelRect.width = EditorGUIUtility.labelWidth; const int oneValueWidth = 70; var valueRects = new Rect[w.historyDepth + 1]; - for(int i = 0; i < w.historyDepth + 1; i++) + for (int i = 0; i < w.historyDepth + 1; i++) { valueRects[i] = rect; valueRects[i].x += EditorGUIUtility.labelWidth + i * oneValueWidth; diff --git a/com.unity.render-pipelines.core/Editor/Debugging/DebugUIHandlerCanvasEditor.cs b/com.unity.render-pipelines.core/Editor/Debugging/DebugUIHandlerCanvasEditor.cs index e19753630a7..5e2c2b21ec4 100644 --- a/com.unity.render-pipelines.core/Editor/Debugging/DebugUIHandlerCanvasEditor.cs +++ b/com.unity.render-pipelines.core/Editor/Debugging/DebugUIHandlerCanvasEditor.cs @@ -39,29 +39,29 @@ void OnEnable() { drawHeaderCallback = rect => EditorGUI.LabelField(rect, "Widget Prefabs"), drawElementCallback = (rect, index, isActive, isFocused) => - { - var element = m_PrefabList.serializedProperty.GetArrayElementAtIndex(index); - rect.y += 2f; - const float kTypeWidth = 100f; + { + var element = m_PrefabList.serializedProperty.GetArrayElementAtIndex(index); + rect.y += 2f; + const float kTypeWidth = 100f; - // Type selector - var typeProp = element.FindPropertyRelative("type"); - int typeIndex = ArrayUtility.IndexOf(s_Types, typeProp.stringValue); - typeIndex = Mathf.Max(typeIndex, 0); - typeIndex = EditorGUI.Popup(new Rect(rect.x, rect.y, kTypeWidth, EditorGUIUtility.singleLineHeight), typeIndex, s_DisplayTypes); - typeProp.stringValue = s_Types[typeIndex]; + // Type selector + var typeProp = element.FindPropertyRelative("type"); + int typeIndex = ArrayUtility.IndexOf(s_Types, typeProp.stringValue); + typeIndex = Mathf.Max(typeIndex, 0); + typeIndex = EditorGUI.Popup(new Rect(rect.x, rect.y, kTypeWidth, EditorGUIUtility.singleLineHeight), typeIndex, s_DisplayTypes); + typeProp.stringValue = s_Types[typeIndex]; - // Prefab - EditorGUI.PropertyField( - new Rect(rect.x + kTypeWidth + 2f, rect.y, rect.width - kTypeWidth - 2f, EditorGUIUtility.singleLineHeight), - element.FindPropertyRelative("prefab"), GUIContent.none); - }, + // Prefab + EditorGUI.PropertyField( + new Rect(rect.x + kTypeWidth + 2f, rect.y, rect.width - kTypeWidth - 2f, EditorGUIUtility.singleLineHeight), + element.FindPropertyRelative("prefab"), GUIContent.none); + }, onSelectCallback = list => - { - var prefab = list.serializedProperty.GetArrayElementAtIndex(list.index).FindPropertyRelative("prefab").objectReferenceValue as GameObject; - if (prefab) - EditorGUIUtility.PingObject(prefab.gameObject); - } + { + var prefab = list.serializedProperty.GetArrayElementAtIndex(list.index).FindPropertyRelative("prefab").objectReferenceValue as GameObject; + if (prefab) + EditorGUIUtility.PingObject(prefab.gameObject); + } }; } diff --git a/com.unity.render-pipelines.core/Editor/Debugging/DebugWindow.cs b/com.unity.render-pipelines.core/Editor/Debugging/DebugWindow.cs index b5fca6ec32f..5e3f33744b7 100644 --- a/com.unity.render-pipelines.core/Editor/Debugging/DebugWindow.cs +++ b/com.unity.render-pipelines.core/Editor/Debugging/DebugWindow.cs @@ -97,7 +97,7 @@ static void RebuildTypeMaps() .Where( t => t.IsDefined(attrType, false) && !t.IsAbstract - ); + ); s_WidgetStateMap = new Dictionary(); @@ -115,7 +115,7 @@ static void RebuildTypeMaps() .Where( t => t.IsDefined(attrType, false) && !t.IsAbstract - ); + ); s_WidgetDrawerMap = new Dictionary(); @@ -135,7 +135,7 @@ static void Init() { var window = GetWindow(); window.titleContent = new GUIContent("Debug"); - if(OnDebugWindowToggled == null) + if (OnDebugWindowToggled == null) OnDebugWindowToggled += DebugManager.instance.ToggleEditorUI; open = true; } diff --git a/com.unity.render-pipelines.core/Editor/EditorPrefBoolFlags.cs b/com.unity.render-pipelines.core/Editor/EditorPrefBoolFlags.cs index 463e76b6b58..740301ef597 100644 --- a/com.unity.render-pipelines.core/Editor/EditorPrefBoolFlags.cs +++ b/com.unity.render-pipelines.core/Editor/EditorPrefBoolFlags.cs @@ -52,25 +52,27 @@ public void SetFlag(T f, bool v) /// The EditorPrefBoolFlags /// The value /// A EditorPrefBoolFlags with OR operator performed - public static EditorPrefBoolFlags operator |(EditorPrefBoolFlags l, T r) + public static EditorPrefBoolFlags operator|(EditorPrefBoolFlags l, T r) { l.rawValue |= (uint)(int)(object)r; return l; } + /// And operator between a EditorPrefBoolFlags and a value /// The EditorPrefBoolFlags /// The value /// A EditorPrefBoolFlags with AND operator performed - public static EditorPrefBoolFlags operator &(EditorPrefBoolFlags l, T r) + public static EditorPrefBoolFlags operator&(EditorPrefBoolFlags l, T r) { l.rawValue &= (uint)(int)(object)r; return l; } + /// Xor operator between a EditorPrefBoolFlags and a value /// The EditorPrefBoolFlags /// The value /// A EditorPrefBoolFlags with XOR operator performed - public static EditorPrefBoolFlags operator ^(EditorPrefBoolFlags l, T r) + public static EditorPrefBoolFlags operator^(EditorPrefBoolFlags l, T r) { l.rawValue ^= (uint)(int)(object)r; return l; diff --git a/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalBox.cs b/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalBox.cs index 26b9250d279..e0dbb33c4e8 100644 --- a/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalBox.cs +++ b/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalBox.cs @@ -91,7 +91,7 @@ Material material if (m_Material == null || m_Material.Equals(null)) m_Material = new Material(k_Material); //material can be lost when exiting play mode so gather the color again when reconstructing it - m_Material.color = m_MonochromeFillColor; + m_Material.color = m_MonochromeFillColor; return m_Material; } } @@ -130,26 +130,26 @@ public Color baseColor //Thus Slider1D is used (with reflection) static Type k_Slider1D = Type.GetType("UnityEditorInternal.Slider1D, UnityEditor"); static MethodInfo k_Slider1D_Do = k_Slider1D - .GetMethod( - "Do", - BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, - null, - CallingConventions.Any, - new[] { typeof(int), typeof(Vector3), typeof(Vector3), typeof(float), typeof(Handles.CapFunction), typeof(float) }, - null); + .GetMethod( + "Do", + BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, + null, + CallingConventions.Any, + new[] { typeof(int), typeof(Vector3), typeof(Vector3), typeof(float), typeof(Handles.CapFunction), typeof(float) }, + null); static void Slider1D(int controlID, ref Vector3 handlePosition, Vector3 handleOrientation, float snapScale, Color color) { using (new Handles.DrawingScope(color)) { handlePosition = (Vector3)k_Slider1D_Do.Invoke(null, new object[] - { - controlID, - handlePosition, - handleOrientation, - HandleUtility.GetHandleSize(handlePosition) * k_HandleSizeCoef, - new Handles.CapFunction(Handles.DotHandleCap), - snapScale - }); + { + controlID, + handlePosition, + handleOrientation, + HandleUtility.GetHandleSize(handlePosition) * k_HandleSizeCoef, + new Handles.CapFunction(Handles.DotHandleCap), + snapScale + }); } } @@ -244,7 +244,7 @@ public void DrawHandle() for (int i = 0, count = m_ControlIDs.Length; i < count; ++i) m_ControlIDs[i] = GUIUtility.GetControlID("HierarchicalBox".GetHashCode() + i, FocusType.Passive); - + var leftPosition = center + size.x * .5f * Vector3.left; var rightPosition = center + size.x * .5f * Vector3.right; var topPosition = center + size.y * .5f * Vector3.up; @@ -338,7 +338,7 @@ public void DrawHandle() case NamedFace.Front: backPosition.z += delta; break; case NamedFace.Back: frontPosition.z -= delta; break; } - + //ensure that the box face are still facing outside switch (theChangedFace) { @@ -358,7 +358,6 @@ public void DrawHandle() frontPosition.z = backPosition.z = center.z; break; } - } if (useHomothety) @@ -388,7 +387,7 @@ public void DrawHandle() topPosition.y -= halfDelta; break; } - + //ensure that the box face are still facing outside switch (theChangedFace) { diff --git a/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalSphere.cs b/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalSphere.cs index f6e71293dce..75bb33fb7c9 100644 --- a/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalSphere.cs +++ b/com.unity.render-pipelines.core/Editor/Gizmo/HierarchicalSphere.cs @@ -78,8 +78,8 @@ public class HierarchicalSphere Color m_WireframeColorBehind; Material material => m_Material == null || m_Material.Equals(null) - ? (m_Material = new Material(k_Material)) - : m_Material; + ? (m_Material = new Material(k_Material)) + : m_Material; /// The position of the center of the box in Handle.matrix space. public Vector3 center { get; set; } @@ -168,7 +168,7 @@ public void DrawHandle() using (new Handles.DrawingScope(m_HandleColor)) { radius = Handles.RadiusHandle(Quaternion.identity, center, radius, handlesOnly: true); - if(m_Parent != null) + if (m_Parent != null) radius = Mathf.Min(radius, m_Parent.radius - Vector3.Distance(center, m_Parent.center)); } } diff --git a/com.unity.render-pipelines.core/Editor/Gizmo/UnlitGizmo.shader b/com.unity.render-pipelines.core/Editor/Gizmo/UnlitGizmo.shader index 6b7acf0ac8c..9f03db071d6 100644 --- a/com.unity.render-pipelines.core/Editor/Gizmo/UnlitGizmo.shader +++ b/com.unity.render-pipelines.core/Editor/Gizmo/UnlitGizmo.shader @@ -5,13 +5,13 @@ Shader "Hidden/UnlitTransparentColored" { SubShader { Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"} - + ZWrite Off Lighting Off Fog { Mode Off } - Cull Off + Cull Off - Blend SrcAlpha OneMinusSrcAlpha + Blend SrcAlpha OneMinusSrcAlpha Pass { Color [_Color] diff --git a/com.unity.render-pipelines.core/Editor/InspectorCurveEditor.cs b/com.unity.render-pipelines.core/Editor/InspectorCurveEditor.cs index d0ea92e9f5e..0dc98d97393 100644 --- a/com.unity.render-pipelines.core/Editor/InspectorCurveEditor.cs +++ b/com.unity.render-pipelines.core/Editor/InspectorCurveEditor.cs @@ -238,7 +238,7 @@ internal MenuAction(SerializedProperty curve, Vector3 position) /// /// public InspectorCurveEditor() - : this(Settings.defaultSettings) { } + : this(Settings.defaultSettings) {} /// /// Creates a curve editor with the given settings. diff --git a/com.unity.render-pipelines.core/Editor/Lighting/CoreLightEditorUtilities.cs b/com.unity.render-pipelines.core/Editor/Lighting/CoreLightEditorUtilities.cs index fe50c0906aa..67dd0950b16 100644 --- a/com.unity.render-pipelines.core/Editor/Lighting/CoreLightEditorUtilities.cs +++ b/com.unity.render-pipelines.core/Editor/Lighting/CoreLightEditorUtilities.cs @@ -94,7 +94,7 @@ static void DrawPointLight(Light light, Color outerColor) static void DrawPointHandlesAndLabels(Light light) { // Getting the first control on point handle - var firstControl = GUIUtility.GetControlID(s_PointLightHandle.GetHashCode(), FocusType.Passive) -6; // BoxBoundsHandle allocates 6 control IDs + var firstControl = GUIUtility.GetControlID(s_PointLightHandle.GetHashCode(), FocusType.Passive) - 6; // BoxBoundsHandle allocates 6 control IDs if (Event.current.type != EventType.Repaint) return; // var firstControl = GUIUtility.GetControlID(k_RadiusHandleHash, FocusType.Passive) - 6; @@ -174,7 +174,7 @@ static void DrawRectangleLight(Light light, Color outerColor) static void DrawRectangleHandlesAndLabels(Light light) { // Getting the first control on radius handle - var firstControl = GUIUtility.GetControlID(s_AreaLightHandle.GetHashCode(), FocusType.Passive) -6; // BoxBoundsHandle allocates 6 control IDs + var firstControl = GUIUtility.GetControlID(s_AreaLightHandle.GetHashCode(), FocusType.Passive) - 6; // BoxBoundsHandle allocates 6 control IDs if (Event.current.type != EventType.Repaint) return; @@ -244,7 +244,7 @@ static void DrawDiscLight(Light light, Color outerColor) static void DrawDiscHandlesAndLabels(Light light) { // Getting the first control on radius handle - var firstControl = GUIUtility.GetControlID(s_DiscLightHandle.GetHashCode(), FocusType.Passive) -6; // BoxBoundsHandle allocates 6 control IDs + var firstControl = GUIUtility.GetControlID(s_DiscLightHandle.GetHashCode(), FocusType.Passive) - 6; // BoxBoundsHandle allocates 6 control IDs if (Event.current.type != EventType.Repaint) return; @@ -312,7 +312,7 @@ static void DrawHandleLabel(Vector3 handlePosition, string labelText, float offs { Vector3 labelPosition = Vector3.zero; - var style = new GUIStyle{normal = {background = Texture2D.whiteTexture}}; + var style = new GUIStyle {normal = {background = Texture2D.whiteTexture}}; GUI.color = new Color(0.82f, 0.82f, 0.82f, 1); labelPosition = handlePosition + Handles.inverseMatrix.MultiplyVector(Vector3.up) * HandleUtility.GetHandleSize(handlePosition) * offsetFromHandle; @@ -332,7 +332,7 @@ static Vector2 DoRectHandles(Vector2 size) } static readonly SphereBoundsHandle s_DiscLightHandle = - new SphereBoundsHandle { axes = PrimitiveBoundsHandle.Axes.X | PrimitiveBoundsHandle.Axes.Y } ; + new SphereBoundsHandle { axes = PrimitiveBoundsHandle.Axes.X | PrimitiveBoundsHandle.Axes.Y }; static float DoDiscHandles(float radius) { s_DiscLightHandle.center = Vector3.zero; @@ -447,7 +447,7 @@ static void DrawHandlesAndLabels(Light light, Color color) // Draw Near Plane Handle float nearPlaneRange = light.shadowNearPlane; - if(light.shadows != LightShadows.None && light.lightmapBakeType != LightmapBakeType.Baked) + if (light.shadows != LightShadows.None && light.lightmapBakeType != LightmapBakeType.Baked) { EditorGUI.BeginChangeCheck(); nearPlaneRange = SliderLineHandle(GUIUtility.GetControlID(FocusType.Passive), Vector3.zero, Vector3.forward, nearPlaneRange, "Near Plane: "); @@ -479,7 +479,7 @@ static Color GetLightAboveObjectWireframeColor(Color wireframeColor) { Color color = wireframeColor; color.a = 1f; - return RemapLightColor(CoreUtils.ConvertLinearToActiveColorSpace(color.linear)); + return RemapLightColor(CoreUtils.ConvertLinearToActiveColorSpace(color.linear)); } static Color GetLightBehindObjectWireframeColor(Color wireframeColor) @@ -492,7 +492,7 @@ static Color GetLightBehindObjectWireframeColor(Color wireframeColor) static Color RemapLightColor(Color src) { Color color = src; - float max = Mathf.Max( Mathf.Max(color.r, color.g), color.b); + float max = Mathf.Max(Mathf.Max(color.r, color.g), color.b); if (max > 0f) { float mult = 1f / max; @@ -524,7 +524,7 @@ static void DrawSpotlightWireframe(Light spotlight, Color outerColor, Color inne // Need to check if we need to draw inner angle // Need to disable this for now until we get all the inner angle baking working. - if(innerAngle > 0f && drawInnerConeAngle) + if (innerAngle > 0f && drawInnerConeAngle) { DrawHandleDirections = HandleDirections.Up | HandleDirections.Down; var innerDiscRadius = range * Mathf.Sin(innerAngle * Mathf.Deg2Rad * 0.5f); @@ -551,7 +551,7 @@ static void DrawSpotlightWireframe(Light spotlight, Color outerColor, Color inne Handles.DrawWireArc(Vector3.zero, Vector3.up, vectorLineLeft, outerAngle, range); // If we are using shadows we draw the near plane for shadows - if(spotlight.shadows != LightShadows.None && spotlight.lightmapBakeType != LightmapBakeType.Baked) + if (spotlight.shadows != LightShadows.None && spotlight.lightmapBakeType != LightmapBakeType.Baked) { DrawShadowNearPlane(spotlight, innerColor); } @@ -563,7 +563,7 @@ static void DrawShadowNearPlane(Light spotlight, Color color) Handles.color = color; var shadowDiscRadius = Mathf.Tan(spotlight.spotAngle * Mathf.Deg2Rad * 0.5f) * spotlight.shadowNearPlane; - var shadowDiscDistance = spotlight.shadowNearPlane ; + var shadowDiscDistance = spotlight.shadowNearPlane; Handles.DrawWireDisc(Vector3.forward * shadowDiscDistance, Vector3.forward, shadowDiscRadius); Handles.DrawLine(Vector3.forward * shadowDiscDistance, (Vector3.right * shadowDiscRadius) + (Vector3.forward * shadowDiscDistance)); Handles.DrawLine(Vector3.forward * shadowDiscDistance, (-Vector3.right * shadowDiscRadius) + (Vector3.forward * shadowDiscDistance)); @@ -604,25 +604,25 @@ static void DrawConeWireframe(float radius, float height, HandleDirections handl static float DrawConeHandles(Vector3 position, float angle, float range, HandleDirections handleDirections, string controlName) { - if(handleDirections.HasFlag(HandleDirections.Left)) + if (handleDirections.HasFlag(HandleDirections.Left)) { angle = SizeSliderSpotAngle(position, Vector3.forward, -Vector3.right, range, angle, controlName); } - if(handleDirections.HasFlag(HandleDirections.Up)) + if (handleDirections.HasFlag(HandleDirections.Up)) { angle = SizeSliderSpotAngle(position, Vector3.forward, Vector3.up, range, angle, controlName); } - if(handleDirections.HasFlag(HandleDirections.Right)) + if (handleDirections.HasFlag(HandleDirections.Right)) { angle = SizeSliderSpotAngle(position, Vector3.forward, Vector3.right, range, angle, controlName); } - if(handleDirections.HasFlag(HandleDirections.Down)) + if (handleDirections.HasFlag(HandleDirections.Down)) { angle = SizeSliderSpotAngle(position, Vector3.forward, -Vector3.up, range, angle, controlName); } return angle; } - + static float SliderLineHandle(int id, Vector3 position, Vector3 direction, float value, string labelText = "") { Vector3 pos = position + direction * value; @@ -644,7 +644,7 @@ static float SliderLineHandle(int id, Vector3 position, Vector3 direction, float return value; } - + static float SizeSliderSpotAngle(Vector3 position, Vector3 forward, Vector3 axis, float range, float spotAngle, string controlName) { if (Math.Abs(spotAngle) <= 0.05f) diff --git a/com.unity.render-pipelines.core/Editor/Lighting/IESImporterEditor.cs b/com.unity.render-pipelines.core/Editor/Lighting/IESImporterEditor.cs index 942a5c84e0e..fbe18f7ae2c 100644 --- a/com.unity.render-pipelines.core/Editor/Lighting/IESImporterEditor.cs +++ b/com.unity.render-pipelines.core/Editor/Lighting/IESImporterEditor.cs @@ -176,9 +176,9 @@ public void CommonApply() /// Delegate provided by the Render pipeline to setup the Preview Floor /// true to specified IES has a Preview public bool CommonHasPreviewGUI(SetupRenderPipelinePreviewCamera setupRenderPipelinePreviewCamera, - SetupRenderPipelinePreviewLight setupRenderPipelinePreviewLight, - SetupRenderPipelinePreviewWallRenderer setupRenderPipelinePreviewWallRenderer, - SetupRenderPipelinePreviewFloorRenderer setupRenderPipelinePreviewFloorRenderer) + SetupRenderPipelinePreviewLight setupRenderPipelinePreviewLight, + SetupRenderPipelinePreviewWallRenderer setupRenderPipelinePreviewWallRenderer, + SetupRenderPipelinePreviewFloorRenderer setupRenderPipelinePreviewFloorRenderer) { if (m_PreviewRenderUtility == null) { @@ -257,7 +257,7 @@ public GUIContent CommonGetPreviewTitle() /// ScriptedImporter targeted /// Delegate provided by the Rendering Pipeline to setup the Light Intensity public void CommonOnPreviewGUI(Rect r, GUIStyle background, ScriptedImporter target, - SetupRenderPipelinePreviewLightIntensity setupRenderPipelinePreviewLightIntensity) + SetupRenderPipelinePreviewLightIntensity setupRenderPipelinePreviewLightIntensity) { if (Event.current.type == EventType.Repaint) { diff --git a/com.unity.render-pipelines.core/Editor/Lighting/IESReader.cs b/com.unity.render-pipelines.core/Editor/Lighting/IESReader.cs index 909fc2c03b0..97d9bf9cfd7 100644 --- a/com.unity.render-pipelines.core/Editor/Lighting/IESReader.cs +++ b/com.unity.render-pipelines.core/Editor/Lighting/IESReader.cs @@ -73,7 +73,6 @@ public int PhotometricType /// Return the error during the import otherwise null if no error public string ReadFile(string iesFilePath) { - using (var iesReader = File.OpenText(iesFilePath)) { string versionLine = iesReader.ReadLine(); diff --git a/com.unity.render-pipelines.core/Editor/LookDev/CameraController.cs b/com.unity.render-pipelines.core/Editor/LookDev/CameraController.cs index c4d7fb0a31e..129dbeebc51 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/CameraController.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/CameraController.cs @@ -261,7 +261,7 @@ void OnKeyUpOrDownFPS(KeyboardEventBase evt) if (GetKeyCombinationByID("3D Viewport/Fly Mode Down", out combination) && combination.Match(evt)) RegisterMotionChange(Direction.Down, evt); } - + void RegisterMotionChange(Direction direction, KeyboardEventBase evt) where T : KeyboardEventBase, new() { @@ -318,7 +318,7 @@ bool GetKeyCombinationByID(string ID, out KeyCombination combination) return false; } } - + void OnMouseUp(MouseUpEvent evt) { ResetCameraControl(); diff --git a/com.unity.render-pipelines.core/Editor/LookDev/CameraState.cs b/com.unity.render-pipelines.core/Editor/LookDev/CameraState.cs index 4f75204df32..e813437b9ae 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/CameraState.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/CameraState.cs @@ -37,12 +37,12 @@ public class CameraState : ICameraUpdater /// The size of the view [field: SerializeField] public float viewSize { get; set; } = k_DefaultViewSize; - + /// The distance from pivot public float distanceFromPivot - // distance coeficient from vertical FOV should be - // 1f / Mathf.Tan(kDefaultFoV * 0.5f * Mathf.Deg2Rad) - // but with fixed FoV of 90, this coef is always equal to 1f + // distance coeficient from vertical FOV should be + // 1f / Mathf.Tan(kDefaultFoV * 0.5f * Mathf.Deg2Rad) + // but with fixed FoV of 90, this coef is always equal to 1f => viewSize; /// The position of the camera diff --git a/com.unity.render-pipelines.core/Editor/LookDev/ComparisonGizmoController.cs b/com.unity.render-pipelines.core/Editor/LookDev/ComparisonGizmoController.cs index d89e2ea59bc..645fea46e53 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/ComparisonGizmoController.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/ComparisonGizmoController.cs @@ -90,7 +90,7 @@ void OnMouseDown(MouseDownEvent evt) m_SavedRelativePositionOnMouseDown = GetNormalizedCoordinates(evt.localMousePosition, displayRect) - m_State.center; isDragging = true; //We do not want to move camera and gizmo at the same time. - evt.StopImmediatePropagation(); + evt.StopImmediatePropagation(); } else { @@ -99,7 +99,7 @@ void OnMouseDown(MouseDownEvent evt) m_Switcher.SwitchUntilNextEndOfDrag(); } } - + void OnMouseUp(MouseUpEvent evt) { if (LookDev.currentContext.layout.viewLayout != Layout.CustomSplit @@ -126,7 +126,7 @@ void OnMouseDrag(MouseMoveEvent evt) switch (m_Selected) { case Selected.PlaneSeparator: OnDragPlaneSeparator(evt); break; - case Selected.NodeFirstView: + case Selected.NodeFirstView: case Selected.NodeSecondView: OnDragPlaneNodeExtremity(evt); break; case Selected.Fader: OnDragFader(evt); break; default: throw new ArgumentException("Unknown kind of Selected"); @@ -148,7 +148,7 @@ void OnDragPlaneSeparator(MouseMoveEvent evt) //We do not want to move camera and gizmo at the same time. evt.StopImmediatePropagation(); } - + void OnDragPlaneNodeExtremity(MouseMoveEvent evt) { Vector2 normalizedCoord = GetNormalizedCoordinates(evt.localMousePosition, target.contentRect); diff --git a/com.unity.render-pipelines.core/Editor/LookDev/Compositor.cs b/com.unity.render-pipelines.core/Editor/LookDev/Compositor.cs index 454b554ce01..153bf14c329 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/Compositor.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/Compositor.cs @@ -46,7 +46,7 @@ public RenderTexture this[CompositionFinal index] int computeIndex(ViewIndex index, ShadowCompositionPass passIndex) => (int)index * k_PassPerViewCount + (int)(passIndex); int computeIndex(CompositionFinal index) - => (k_PassPerViewCount-1) + (int)(index) * k_PassPerViewCount; + => (k_PassPerViewCount - 1) + (int)(index) * k_PassPerViewCount; void UpdateSize(int index, Rect rect, bool pixelPerfect, Camera renderingCamera, string renderDocName = "LookDevRT") { @@ -93,7 +93,6 @@ public void UpdateSize(Rect rect, ViewIndex index, bool pixelPerfect, Camera ren UpdateSize(computeIndex(index, ShadowCompositionPass.ShadowMask), rect, pixelPerfect, renderingCamera, $"LookDevRT-{index}-ShadowMask"); } - public void UpdateSize(Rect rect, CompositionFinal index, bool pixelPerfect, Camera renderingCamera) => UpdateSize(computeIndex(index), rect, pixelPerfect, renderingCamera, $"LookDevRT-Final-{index}"); @@ -184,6 +183,7 @@ void CleanUp() m_Displayer.OnRenderDocAcquisitionTriggered -= RenderDocAcquisitionRequested; m_Displayer.OnUpdateRequested -= Render; } + public void Dispose() { if (m_Disposed) @@ -192,6 +192,7 @@ public void Dispose() CleanUp(); GC.SuppressFinalize(this); } + ~Compositer() => CleanUp(); public void Render() diff --git a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.DebugSidePanel.cs b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.DebugSidePanel.cs index 244360f9192..85f0a4d00b4 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.DebugSidePanel.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.DebugSidePanel.cs @@ -6,7 +6,7 @@ using UnityEngine.UIElements; namespace UnityEditor.Rendering.LookDev -{ +{ partial class DisplayWindow { static partial class Style @@ -22,7 +22,6 @@ static partial class Style //The following const are used in the uss. //If you change them, update the uss file too. internal const string k_DebugToolbarName = "debugToolbar"; - } MultipleSourceToggle m_Shadow; @@ -71,7 +70,7 @@ T GetInFilteredViewsContext(Func getter, out bool multipleDif multipleDifferentValue = false; bool view1 = debugView1SidePanel; bool view2 = debugView2SidePanel; - + if (view1) res1 = getter.Invoke(LookDev.currentContext.GetViewContent(ViewIndex.First)); if (view2) @@ -96,16 +95,16 @@ void ReadValueFromSourcesWithoutNotify(K element, Func fro element.inMultipleValueState = multipleDifferentValue; } -#region Hack_Support_UIElement_MixedValueState + #region Hack_Support_UIElement_MixedValueState class MultipleDifferentValue : TextElement { - public new class UxmlFactory : UxmlFactory { } + public new class UxmlFactory : UxmlFactory {} - public new class UxmlTraits : TextElement.UxmlTraits { } + public new class UxmlTraits : TextElement.UxmlTraits {} public new static readonly string ussClassName = "unity-multipledifferentevalue"; - + public MultipleDifferentValue() { AddToClassList(ussClassName); @@ -136,7 +135,7 @@ public bool inMultipleValueState } } - public MultipleSourceToggle() : base () + public MultipleSourceToggle() : base() { m_MultipleOverlay = new MultipleDifferentValue(); this.Q(name: "unity-checkmark").Add(m_MultipleOverlay); @@ -160,12 +159,12 @@ public override void SetValueWithoutNotify(bool newValue) public override bool value { get => inMultipleValueState ? default : base.value; - set - { - if (inMultipleValueState) - inMultipleValueState = false; - base.value = value; - } + set + { + if (inMultipleValueState) + inMultipleValueState = false; + base.value = value; + } } } @@ -190,11 +189,11 @@ public bool inMultipleValueState public MultipleSourcePopupField(string label, List choices, int defaultIndex = 0) : base( - label, - choices, - defaultIndex, - null, - null) + label, + choices, + defaultIndex, + null, + null) { count = choices.Count; m_MultipleOverlay = new MultipleDifferentValue(); @@ -212,17 +211,17 @@ public override void SetValueWithoutNotify(string newValue) public override string value { get => inMultipleValueState ? default : base.value; - set - { - //when actively changing in the drop down, quit mixed value state - if (inMultipleValueState) - inMultipleValueState = false; - base.value = value; - } + set + { + //when actively changing in the drop down, quit mixed value state + if (inMultipleValueState) + inMultipleValueState = false; + base.value = value; + } } } -#endregion + #endregion void CreateDebug() { @@ -234,8 +233,8 @@ void CreateDebug() if (sidePanel == SidePanel.Debug) m_MainContainer.AddToClassList(Style.k_ShowDebugPanelClass); - AddDebugViewSelector(); - + AddDebugViewSelector(); + AddDebugShadow(); AddDebugViewMode(); @@ -250,7 +249,7 @@ void CreateDebug() //[TODO: debug why list sometimes empty on resource reloading] //[TODO: display only per view] - + if (sidePanel == SidePanel.Debug) UpdateSideDebugPanelProperties(); } @@ -308,7 +307,7 @@ void AddDebugViewMode(int pos = -1) else m_DebugContainer.Insert(pos, m_DebugView); } - + void UpdateSideDebugPanelProperties() { ReadValueFromSourcesWithoutNotify(m_Shadow, view => view.debug.shadow); diff --git a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.EnvironmentLibrarySidePanel.cs b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.EnvironmentLibrarySidePanel.cs index e546030ec7e..4cf26c45afe 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.EnvironmentLibrarySidePanel.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.EnvironmentLibrarySidePanel.cs @@ -125,12 +125,12 @@ void CreateEnvironment() #if UNITY_2020_1_OR_NEWER m_EnvironmentList.onItemsChosen += objCollection => { - foreach(var obj in objCollection) - EditorGUIUtility.PingObject(LookDev.currentContext.environmentLibrary?[(int)obj]); + foreach (var obj in objCollection) + EditorGUIUtility.PingObject(LookDev.currentContext.environmentLibrary ? [(int)obj]); }; #else m_EnvironmentList.onItemChosen += obj => - EditorGUIUtility.PingObject(LookDev.currentContext.environmentLibrary?[(int)obj]); + EditorGUIUtility.PingObject(LookDev.currentContext.environmentLibrary ? [(int)obj]); #endif m_NoEnvironmentList = new Label(Style.k_DragAndDropLibrary); m_NoEnvironmentList.style.flexGrow = 1; @@ -195,7 +195,7 @@ void CreateEnvironment() listContainer.AddToClassList("list-environment"); listContainer.Add(m_EnvironmentList); listContainer.Add(m_EnvironmentListToolbar); - + m_LibraryField = new ObjectField("Library") { tooltip = "The currently used library" @@ -217,10 +217,10 @@ void CreateEnvironment() environmentListCreationToolbar.Add(m_LibraryField); environmentListCreationToolbar.Add(new ToolbarButton(() => EnvironmentLibraryCreator.CreateAndAssignTo(m_LibraryField)) - { - text = "New", - tooltip = "Create a new EnvironmentLibrary" - }); + { + text = "New", + tooltip = "Create a new EnvironmentLibrary" + }); m_EnvironmentContainer.Add(listContainer); m_EnvironmentContainer.Add(m_NoEnvironmentList); @@ -286,8 +286,8 @@ void RefreshLibraryDisplay() .Q(className: "unity-scroll-view__vertical-scroller") .Q("unity-dragger") .style.visibility = itemMax == 0 - ? Visibility.Hidden - : Visibility.Visible; + ? Visibility.Hidden + : Visibility.Visible; m_EnvironmentListToolbar.style.visibility = Visibility.Visible; m_NoEnvironmentList.style.display = DisplayStyle.None; } @@ -305,7 +305,7 @@ DraggingContext StartDragging(VisualElement item, Vector2 worldPosition) void EndDragging(DraggingContext context, Vector2 mouseWorldPosition) { - Environment environment = LookDev.currentContext.environmentLibrary?[context.draggedIndex]; + Environment environment = LookDev.currentContext.environmentLibrary ? [context.draggedIndex]; if (environment == null) return; @@ -435,7 +435,7 @@ void IEnvironmentDisplayer.Repaint() RefreshLibraryDisplay(); } - + void OnFocus() { //OnFocus is called before OnEnable that open backend if not already opened, so only sync if backend is open @@ -475,7 +475,7 @@ void FullRefreshEnvironmentList() { if (LookDev.currentContext.environmentLibrary != null) LookDev.currentContext.FullReimportEnvironmentLibrary(); - + ((IEnvironmentDisplayer)this).Repaint(); } } diff --git a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.cs b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.cs index c1a53ef8bf1..3f482e01847 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.cs @@ -54,21 +54,21 @@ static partial class Style internal static readonly GUIContent k_WindowTitleAndIcon = EditorGUIUtility.TrTextContentWithIcon("Look Dev", CoreEditorUtils.LoadIcon(k_IconFolder, "LookDev", forceLowRes: true)); - internal static readonly (Texture2D icon, string tooltip) k_Layout1Icon = + internal static readonly (Texture2D icon, string tooltip)k_Layout1Icon = (CoreEditorUtils.LoadIcon(Style.k_IconFolder, "Layout1", forceLowRes: true), - "First view"); - internal static readonly (Texture2D icon, string tooltip) k_Layout2Icon = + "First view"); + internal static readonly (Texture2D icon, string tooltip)k_Layout2Icon = (CoreEditorUtils.LoadIcon(Style.k_IconFolder, "Layout2", forceLowRes: true), - "Second view"); - internal static readonly (Texture2D icon, string tooltip) k_LayoutVerticalIcon = + "Second view"); + internal static readonly (Texture2D icon, string tooltip)k_LayoutVerticalIcon = (CoreEditorUtils.LoadIcon(Style.k_IconFolder, "LayoutVertical", forceLowRes: true), - "Both views split vertically"); - internal static readonly (Texture2D icon, string tooltip) k_LayoutHorizontalIcon = + "Both views split vertically"); + internal static readonly (Texture2D icon, string tooltip)k_LayoutHorizontalIcon = (CoreEditorUtils.LoadIcon(Style.k_IconFolder, "LayoutHorizontal", forceLowRes: true), - "Both views split horizontally"); - internal static readonly (Texture2D icon, string tooltip) k_LayoutStackIcon = + "Both views split horizontally"); + internal static readonly (Texture2D icon, string tooltip)k_LayoutStackIcon = (CoreEditorUtils.LoadIcon(Style.k_IconFolder, "LayoutCustom", forceLowRes: true), - "Both views stacked"); + "Both views stacked"); internal static readonly Texture2D k_Camera1Icon = CoreEditorUtils.LoadIcon(Style.k_IconFolder, "Camera1", forceLowRes: true); internal static readonly Texture2D k_Camera2Icon = CoreEditorUtils.LoadIcon(Style.k_IconFolder, "Camera2", forceLowRes: true); @@ -219,37 +219,37 @@ event Action IViewDisplayer.OnUpdateRequested void ReloadStyleSheets() { - if(styleSheet == null || styleSheet.Equals(null)) + if (styleSheet == null || styleSheet.Equals(null)) { styleSheet = AssetDatabase.LoadAssetAtPath(Style.k_uss); - if(styleSheet == null || styleSheet.Equals(null)) + if (styleSheet == null || styleSheet.Equals(null)) { //Debug.LogWarning("[LookDev] Could not load Stylesheet."); return; } } - if(!rootVisualElement.styleSheets.Contains(styleSheet)) + if (!rootVisualElement.styleSheets.Contains(styleSheet)) rootVisualElement.styleSheets.Add(styleSheet); //Additively load Light Skin - if(!EditorGUIUtility.isProSkin) + if (!EditorGUIUtility.isProSkin) { - if(styleSheetLight == null || styleSheetLight.Equals(null)) + if (styleSheetLight == null || styleSheetLight.Equals(null)) { styleSheetLight = AssetDatabase.LoadAssetAtPath(Style.k_uss_personal_overload); - if(styleSheetLight == null || styleSheetLight.Equals(null)) + if (styleSheetLight == null || styleSheetLight.Equals(null)) { //Debug.LogWarning("[LookDev] Could not load Light skin."); return; } } - - if(!rootVisualElement.styleSheets.Contains(styleSheetLight)) + + if (!rootVisualElement.styleSheets.Contains(styleSheetLight)) rootVisualElement.styleSheets.Add(styleSheetLight); } } - + void CreateGUI() { ReloadStyleSheets(); @@ -281,7 +281,7 @@ void CreateGUI() } void OnEnable() - { + { Undo.undoRedoPerformed += FullRefreshEnvironmentList; } @@ -295,13 +295,14 @@ void CreateToolbar() { // Layout swapper part var layoutRadio = new ToolbarRadio() { name = Style.k_ToolbarRadioName }; - layoutRadio.AddRadios(new[] { + layoutRadio.AddRadios(new[] + { Style.k_Layout1Icon, Style.k_Layout2Icon, Style.k_LayoutVerticalIcon, Style.k_LayoutHorizontalIcon, Style.k_LayoutStackIcon, - }); + }); layoutRadio.RegisterCallback((ChangeEvent evt) => viewLayout = (Layout)evt.newValue); layoutRadio.SetValueWithoutNotify((int)viewLayout); @@ -345,10 +346,11 @@ void CreateToolbar() { name = Style.k_TabsRadioName }; - sideRadio.AddRadios(new[] { + sideRadio.AddRadios(new[] + { Style.k_EnvironmentSidePanelName, Style.k_DebugSidePanelName, - }); + }); sideRadio.SetValueWithoutNotify((int)sidePanel); sideRadio.RegisterCallback((ChangeEvent evt) => sidePanel = (SidePanel)evt.newValue); @@ -524,7 +526,7 @@ void IViewDisplayer.SetTexture(ViewCompositionIndex index, Texture texture) if (updated |= m_Views[(int)ViewIndex.First].image != texture) m_Views[(int)ViewIndex.First].image = texture; else if (updated |= (m_LastFirstViewSize.x != texture.width - || m_LastFirstViewSize.y != texture.height)) + || m_LastFirstViewSize.y != texture.height)) { m_Views[(int)ViewIndex.First].image = null; //force refresh else it will appear zoomed m_Views[(int)ViewIndex.First].image = texture; @@ -539,7 +541,7 @@ void IViewDisplayer.SetTexture(ViewCompositionIndex index, Texture texture) if (m_Views[(int)ViewIndex.Second].image != texture) m_Views[(int)ViewIndex.Second].image = texture; else if (updated |= (m_LastSecondViewSize.x != texture.width - || m_LastSecondViewSize.y != texture.height)) + || m_LastSecondViewSize.y != texture.height)) { m_Views[(int)ViewIndex.Second].image = null; //force refresh else it will appear zoomed m_Views[(int)ViewIndex.Second].image = texture; @@ -669,9 +671,9 @@ void Update() void OnGUI() { - if(EditorApplication.isUpdating) + if (EditorApplication.isUpdating) return; - + //deal with missing style on domain reload... ReloadStyleSheets(); diff --git a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.uss b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.uss index 04cdd7e6368..58fea9f2a1c 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.uss +++ b/com.unity.render-pipelines.core/Editor/LookDev/DisplayWindow.uss @@ -40,7 +40,7 @@ #environmentContainer { - width: 0px; + width: 0px; visibility: hidden; flex-direction: column-reverse; border-color: #232323; @@ -49,7 +49,7 @@ #debugContainer { - width: 0px; + width: 0px; visibility: hidden; border-color: #232323; border-left-width: 1px; @@ -63,13 +63,13 @@ .showEnvironmentPanel > #environmentContainer { - width: 255px; + width: 255px; visibility: visible; } .showDebugPanel > #debugContainer { - width: 256px; /*219px;*/ + width: 256px; /*219px;*/ visibility: visible; } @@ -320,7 +320,7 @@ MultipleSourcePopupField > MultipleDifferentValue:hover padding: 2px; } -#tabsRadio +#tabsRadio { width: 256px; min-width: 256px; diff --git a/com.unity.render-pipelines.core/Editor/LookDev/Environment.cs b/com.unity.render-pipelines.core/Editor/LookDev/Environment.cs index 8d533c8f445..9ab965699db 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/Environment.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/Environment.cs @@ -74,7 +74,7 @@ public float sunLongitude } internal static float ClampLatitude(float value) => Mathf.Clamp(value, -90, 90); - + internal static float ClampLongitude(float value) { value = value % 360f; @@ -85,7 +85,7 @@ internal static float ClampLongitude(float value) internal void UpdateSunPosition(Light sun) => sun.transform.rotation = Quaternion.Euler(sunLatitude, rotation + sunLongitude, 0f); - + /// /// Compute sun position to be brightest spot of the sky /// @@ -122,11 +122,11 @@ internal void CopyTo(Environment other) /// Editor version of the datas public UnityEngine.Rendering.LookDev.Sky sky => new UnityEngine.Rendering.LookDev.Sky() - { - cubemap = cubemap, - longitudeOffset = rotation, - exposure = exposure - }; + { + cubemap = cubemap, + longitudeOffset = rotation, + exposure = exposure + }; internal static Environment GetTemporaryEnvironmentForCubemap(Cubemap cubemap) { @@ -152,7 +152,7 @@ class EnvironmentEditor : Editor public sealed override VisualElement CreateInspectorGUI() => null; // Don't use ImGUI - public sealed override void OnInspectorGUI() { } + public sealed override void OnInspectorGUI() {} //but make preview in Project window override public Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) @@ -196,7 +196,7 @@ static Material cubeToLatlongMaterial public Environment target => environment; - public EnvironmentElement() => Create(withPreview: true); + public EnvironmentElement() => Create(withPreview : true); public EnvironmentElement(bool withPreview, Action OnChangeCallback = null) { this.OnChangeCallback = OnChangeCallback; diff --git a/com.unity.render-pipelines.core/Editor/LookDev/EnvironmentLibrary.cs b/com.unity.render-pipelines.core/Editor/LookDev/EnvironmentLibrary.cs index d641038553a..03edd2af2c1 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/EnvironmentLibrary.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/EnvironmentLibrary.cs @@ -140,7 +140,7 @@ public sealed override VisualElement CreateInspectorGUI() } // Don't use ImGUI - public sealed override void OnInspectorGUI() { } + public sealed override void OnInspectorGUI() {} } class EnvironmentLibraryCreator : ProjectWindowCallback.EndNameEditAction diff --git a/com.unity.render-pipelines.core/Editor/LookDev/Stage.cs b/com.unity.render-pipelines.core/Editor/LookDev/Stage.cs index 0f121b9bcbd..08551be06b2 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/Stage.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/Stage.cs @@ -218,7 +218,7 @@ void SetGameObjectVisible(bool visible) continue; foreach (UnityEngine.Renderer renderer in go.GetComponentsInChildren()) { - if((renderer.hideFlags & HideFlags.HideInInspector) == 0 && ((renderer.hideFlags & HideFlags.HideAndDontSave) == 0)) + if ((renderer.hideFlags & HideFlags.HideInInspector) == 0 && ((renderer.hideFlags & HideFlags.HideAndDontSave) == 0)) renderer.enabled = visible; } foreach (Light light in go.GetComponentsInChildren()) @@ -350,7 +350,7 @@ public void UpdateSceneLighting(ViewIndex index, IDataProvider provider) Environment environment = m_Contexts.GetViewContent(index).environment; provider.UpdateSky(stage.camera, environment == null ? default : environment.sky, - stage.runtimeInterface); + stage.runtimeInterface); } private bool disposedValue = false; // To detect redundant calls diff --git a/com.unity.render-pipelines.core/Editor/LookDev/ToolbarRadio.cs b/com.unity.render-pipelines.core/Editor/LookDev/ToolbarRadio.cs index 0d985d18e7d..c218c24c004 100644 --- a/com.unity.render-pipelines.core/Editor/LookDev/ToolbarRadio.cs +++ b/com.unity.render-pipelines.core/Editor/LookDev/ToolbarRadio.cs @@ -7,8 +7,8 @@ namespace UnityEditor.Rendering.LookDev { class ToolbarRadio : UIElements.Toolbar, INotifyValueChanged { - public new class UxmlFactory : UxmlFactory { } - public new class UxmlTraits : Button.UxmlTraits { } + public new class UxmlFactory : UxmlFactory {} + public new class UxmlTraits : Button.UxmlTraits {} List radios = new List(); @@ -43,7 +43,7 @@ public int value } } - public ToolbarRadio() : this(null, false) { } + public ToolbarRadio() : this(null, false) {} public ToolbarRadio(string label = null, bool canDeselectAll = false) { @@ -84,6 +84,7 @@ public void AddRadios(string[] labels) foreach (var label in labels) AddRadio(label); } + public void AddRadios((string text, string tooltip)[] labels) { foreach (var label in labels) @@ -101,7 +102,7 @@ public void AddRadios((string text, Texture2D icon)[] labels) foreach (var label in labels) AddRadio(label.text, label.icon); } - + public void AddRadios((Texture2D icon, string tooltip)[] labels) { foreach (var label in labels) diff --git a/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs b/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs index bde4ad17ae6..e499e33cb0d 100644 --- a/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs +++ b/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs @@ -340,7 +340,7 @@ public static void UpgradeProjectFolder(List upgraders, HashSe if (IsMaterialPath(s)) totalMaterialCount++; } - + int materialIndex = 0; foreach (string path in UnityEditor.AssetDatabase.GetAllAssetPaths()) { @@ -354,7 +354,7 @@ public static void UpgradeProjectFolder(List upgraders, HashSe if (!ShouldUpgradeShader(m, shaderNamesToIgnore)) continue; - + Upgrade(m, upgraders, flags); //SaveAssetsAndFreeMemory(); @@ -448,7 +448,7 @@ public static void UpgradeSelection(List upgraders, HashSet 1 ? "s" : "") + - DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel)) + DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel)) return; string lastMaterialName = ""; diff --git a/com.unity.render-pipelines.core/Editor/QuaternionPropertyDrawer.cs b/com.unity.render-pipelines.core/Editor/QuaternionPropertyDrawer.cs index 3bbe0fb103a..ebaaef784e8 100644 --- a/com.unity.render-pipelines.core/Editor/QuaternionPropertyDrawer.cs +++ b/com.unity.render-pipelines.core/Editor/QuaternionPropertyDrawer.cs @@ -17,5 +17,4 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten property.quaternionValue = Quaternion.Euler(euler); } } - } diff --git a/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs b/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs index 3281ffa1a3a..69deb154187 100644 --- a/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs +++ b/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs @@ -23,7 +23,7 @@ public CellElement(int idxStart, int idxEnd) style.borderBottomLeftRadius = style.borderTopLeftRadius = style.borderBottomRightRadius = style.borderTopRightRadius = 5; style.borderBottomWidth = style.borderTopWidth = style.borderLeftWidth = style.borderRightWidth = 1f; style.borderBottomColor = style.borderTopColor = style.borderLeftColor = style.borderRightColor = new Color(0f, 0f, 0f, 1f); - style.backgroundColor = (Color)new Color32(88, 88, 88, 255); + style.backgroundColor = (Color) new Color32(88, 88, 88, 255); style.height = kResourceHeight; style.left = idxStart * kRenderPassWidth; style.width = (idxEnd - idxStart + 1) * kRenderPassWidth; @@ -111,7 +111,6 @@ void RenderPassLabelChanged(GeometryChangedEvent evt) var topRowElement = m_GraphViewerElement.Q("GraphViewer.TopRowElement"); topRowElement.style.minHeight = passNamesContainerHeight; - } void LastRenderPassLabelChanged(GeometryChangedEvent evt) @@ -220,7 +219,7 @@ void MouseLeaveResourceCallback(MouseLeaveEvent evt, (int index, int resourceTyp var resource = m_CurrentRenderGraph.GetDebugData().resourceLists[info.resourceType][info.index]; UpdatePassColor(info, m_OriginalPassColor, m_OriginalPassColor); - UpdateResourceLabelColor(info, resource.imported ? m_ImportedResourceColor : m_OriginalResourceColor); ; + UpdateResourceLabelColor(info, resource.imported ? m_ImportedResourceColor : m_OriginalResourceColor);; } VisualElement CreateRenderPass(string name, int index, bool culled) diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/CSharpToHLSL.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/CSharpToHLSL.cs index 76391051c57..2f8a0b2e677 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/CSharpToHLSL.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/CSharpToHLSL.cs @@ -92,16 +92,12 @@ public static void GenerateAll() { info = new FileInfo(fileName); } - - catch (UnauthorizedAccessException ) - + catch (UnauthorizedAccessException) { Debug.Log("Access to " + fileName + " is denied. Skipping it."); skipFile = true; } - - catch (System.Security.SecurityException ) - + catch (System.Security.SecurityException) { Debug.Log("You do not have permission to access " + fileName + ". Skipping it."); skipFile = true; @@ -169,7 +165,7 @@ public static void GenerateAll() foreach (var gen in it.Value) { - if(gen.hasPackedInfo) + if (gen.hasPackedInfo) { writer.WriteLine(gen.EmitPackedInfo().Replace("\n", writer.NewLine)); } diff --git a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs index 86d87306a08..18bf34e0814 100644 --- a/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs +++ b/com.unity.render-pipelines.core/Editor/ShaderGenerator/ShaderTypeGeneration.cs @@ -470,9 +470,9 @@ public string EmitSetters(bool generatingInitFunc = false) } shaderText += - //"\t" - " " // unity convention use space instead of tab... - + "dest." + acc.name + arrayAccess + " = newValue;\n"; + //"\t" + " " // unity convention use space instead of tab... + + "dest." + acc.name + arrayAccess + " = newValue;\n"; shaderText += "}\n"; } } @@ -520,9 +520,9 @@ public string EmitAccessors() } shaderText += - //"\t" - " " // unity convention use space instead of tab... - + "return value." + acc.name + swizzle + arrayAccess + ";\n"; + //"\t" + " " // unity convention use space instead of tab... + + "return value." + acc.name + swizzle + arrayAccess + ";\n"; shaderText += "}\n"; } } @@ -589,8 +589,7 @@ public string EmitFunctions() { if (debugField.checkIsNormalized) { - shaderText += " result = IsNormalized(" + lowerStructName + "." + debugField.fieldName +")? " + lowerStructName + "." + debugField.fieldName + " * 0.5 + 0.5 : float3(1.0, 0.0, 0.0);\n"; - + shaderText += " result = IsNormalized(" + lowerStructName + "." + debugField.fieldName + ")? " + lowerStructName + "." + debugField.fieldName + " * 0.5 + 0.5 : float3(1.0, 0.0, 0.0);\n"; } else { @@ -802,6 +801,7 @@ private string EmitPackedGetters() } return gettersString; } + private string EmitPackedSetters() { string settersString = ""; @@ -895,6 +895,7 @@ private string EmitPackedSetters() } return settersString; } + private string EmitPackedInit() { string initString = ""; diff --git a/com.unity.render-pipelines.core/Editor/Utilities/EditorMaterialQuality.cs b/com.unity.render-pipelines.core/Editor/Utilities/EditorMaterialQuality.cs index 28c3c31ae9b..ac0e307f00d 100644 --- a/com.unity.render-pipelines.core/Editor/Utilities/EditorMaterialQuality.cs +++ b/com.unity.render-pipelines.core/Editor/Utilities/EditorMaterialQuality.cs @@ -18,7 +18,7 @@ public static MaterialQuality GetMaterialQuality(this ShaderKeywordSet keywordSe for (var i = 0; i < MaterialQualityUtilities.Keywords.Length; ++i) { if (keywordSet.IsEnabled(MaterialQualityUtilities.Keywords[i])) - result |= (MaterialQuality) (1 << i); + result |= (MaterialQuality)(1 << i); } return result; diff --git a/com.unity.render-pipelines.core/Editor/Utilities/SerializedBitArray.cs b/com.unity.render-pipelines.core/Editor/Utilities/SerializedBitArray.cs index 10c6aeec619..38407b01d79 100644 --- a/com.unity.render-pipelines.core/Editor/Utilities/SerializedBitArray.cs +++ b/com.unity.render-pipelines.core/Editor/Utilities/SerializedBitArray.cs @@ -507,8 +507,8 @@ public SerializedBitArray128(SerializedProperty serializedProperty) : base(seria /// True: properties have different value protected override bool HasBitMultipleDifferentValue_Internal(uint bitIndex) => bitIndex < 64u - ? HasBitMultipleDifferentValue_For64Bits("data1", m_Data1, bitIndex) - : HasBitMultipleDifferentValue_For64Bits("data2", m_Data2, bitIndex - 64u); + ? HasBitMultipleDifferentValue_For64Bits("data1", m_Data1, bitIndex) + : HasBitMultipleDifferentValue_For64Bits("data2", m_Data2, bitIndex - 64u); /// Get the value at index @@ -572,12 +572,12 @@ public SerializedBitArray256(SerializedProperty serializedProperty) : base(seria /// True: properties have different value protected override bool HasBitMultipleDifferentValue_Internal(uint bitIndex) => bitIndex < 128u - ? bitIndex < 64u - ? HasBitMultipleDifferentValue_For64Bits("data1", m_Data1, bitIndex) - : HasBitMultipleDifferentValue_For64Bits("data2", m_Data2, bitIndex - 64u) - : bitIndex < 192u - ? HasBitMultipleDifferentValue_For64Bits("data3", m_Data3, bitIndex - 128u) - : HasBitMultipleDifferentValue_For64Bits("data4", m_Data4, bitIndex - 192u); + ? bitIndex < 64u + ? HasBitMultipleDifferentValue_For64Bits("data1", m_Data1, bitIndex) + : HasBitMultipleDifferentValue_For64Bits("data2", m_Data2, bitIndex - 64u) + : bitIndex < 192u + ? HasBitMultipleDifferentValue_For64Bits("data3", m_Data3, bitIndex - 128u) + : HasBitMultipleDifferentValue_For64Bits("data4", m_Data4, bitIndex - 192u); /// Get the value at index /// The index diff --git a/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs b/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs index 49d9c310abd..97619523824 100644 --- a/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs +++ b/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs @@ -150,7 +150,7 @@ static void ReloadDecoratorTypes() .Where( t => t.IsDefined(typeof(VolumeParameterDrawerAttribute), false) && !t.IsAbstract - ); + ); // Store them foreach (var type in types) @@ -179,7 +179,6 @@ internal void Init(VolumeComponent target, Editor inspector) OnEnable(); } - class ParameterSorter : Comparer<(GUIContent displayName, int displayOrder, SerializedDataParameter param)> { public override int Compare((GUIContent displayName, int displayOrder, SerializedDataParameter param) x, (GUIContent displayName, int displayOrder, SerializedDataParameter param) y) @@ -212,7 +211,7 @@ public virtual void OnEnable() .Where(t => (t.IsPublic && t.GetCustomAttributes(typeof(NonSerializedAttribute), false).Length == 0) || (t.GetCustomAttributes(typeof(SerializeField), false).Length > 0) - ) + ) .Where(t => t.GetCustomAttributes(typeof(HideInInspector), false).Length == 0) .ToList(); diff --git a/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs b/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs index 6c27dcf5da9..d7bbea08b39 100644 --- a/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs +++ b/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs @@ -102,7 +102,7 @@ public void Init(VolumeProfile asset, SerializedObject serializedObject) .Where( t => t.IsDefined(typeof(VolumeComponentEditorAttribute), false) && !t.IsAbstract - ); + ); // Map them to their corresponding component type foreach (var editorType in editorTypes) @@ -127,9 +127,9 @@ void OnUndoRedoPerformed() // Dumb hack to make sure the serialized object is up to date on undo (else there'll be // a state mismatch when this class is used in a GameObject inspector). if (m_SerializedObject != null - && !m_SerializedObject.Equals(null) - && m_SerializedObject.targetObject != null - && !m_SerializedObject.targetObject.Equals(null)) + && !m_SerializedObject.Equals(null) + && m_SerializedObject.targetObject != null + && !m_SerializedObject.targetObject.Equals(null)) { m_SerializedObject.Update(); m_SerializedObject.ApplyModifiedProperties(); @@ -235,14 +235,14 @@ public void OnGUI() CoreEditorUtils.DrawSplitter(); bool displayContent = CoreEditorUtils.DrawHeaderToggle( - title, - editor.baseProperty, - editor.activeProperty, - pos => OnContextClick(pos, editor.target, id), - editor.hasAdvancedMode ? () => editor.isInAdvancedMode : (Func)null, - () => editor.isInAdvancedMode ^= true, - documentationURL - ); + title, + editor.baseProperty, + editor.activeProperty, + pos => OnContextClick(pos, editor.target, id), + editor.hasAdvancedMode ? () => editor.isInAdvancedMode : (Func)null, + () => editor.isInAdvancedMode ^= true, + documentationURL + ); if (displayContent) { @@ -292,7 +292,7 @@ void OnContextClick(Vector2 position, VolumeComponent targetComponent, int id) } else { - menu.AddItem(EditorGUIUtility.TrTextContent("Move to Bottom"), false, () => MoveComponent(id, (m_Editors.Count -1) - id)); + menu.AddItem(EditorGUIUtility.TrTextContent("Move to Bottom"), false, () => MoveComponent(id, (m_Editors.Count - 1) - id)); menu.AddItem(EditorGUIUtility.TrTextContent("Move Down"), false, () => MoveComponent(id, 1)); } @@ -482,7 +482,6 @@ internal void ExpandComponents() m_SerializedObject.ApplyModifiedProperties(); } - static bool CanPaste(VolumeComponent targetComponent) { if (string.IsNullOrWhiteSpace(EditorGUIUtility.systemCopyBuffer)) diff --git a/com.unity.render-pipelines.core/Editor/Volume/VolumeParameterDrawer.cs b/com.unity.render-pipelines.core/Editor/Volume/VolumeParameterDrawer.cs index 5636f800678..40a6d6fce67 100644 --- a/com.unity.render-pipelines.core/Editor/Volume/VolumeParameterDrawer.cs +++ b/com.unity.render-pipelines.core/Editor/Volume/VolumeParameterDrawer.cs @@ -47,10 +47,10 @@ public VolumeParameterDrawerAttribute(Type parameterType) /// public override bool OnGUI(SerializedDataParameter parameter, GUIContent title) /// { /// var value = parameter.value; - /// + /// /// if (value.propertyType != SerializedPropertyType.Float) /// return false; - /// + /// /// var o = parameter.GetObjectRef<ClampedFloatParameter>(); /// EditorGUILayout.Slider(value, o.min, o.max, title); /// value.floatValue = Mathf.Clamp(value.floatValue, o.min, o.max); diff --git a/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileFactory.cs b/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileFactory.cs index cf00102a263..26a1d7ecf7e 100644 --- a/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileFactory.cs +++ b/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileFactory.cs @@ -20,7 +20,7 @@ static void CreateVolumeProfile() "New Volume Profile.asset", null, null - ); + ); } /// @@ -69,7 +69,7 @@ public static VolumeProfile CreateVolumeProfile(Scene scene, string targetName) AssetDatabase.CreateFolder(rootPath.TrimEnd(Path.DirectorySeparatorChar), directory); rootPath = newPath + Path.DirectorySeparatorChar; } - } + } path = profilePath + Path.DirectorySeparatorChar; } diff --git a/com.unity.render-pipelines.core/Runtime/Camera/FreeCamera.cs b/com.unity.render-pipelines.core/Runtime/Camera/FreeCamera.cs index 675439767c2..293aa382062 100644 --- a/com.unity.render-pipelines.core/Runtime/Camera/FreeCamera.cs +++ b/com.unity.render-pipelines.core/Runtime/Camera/FreeCamera.cs @@ -1,6 +1,6 @@ #if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE #define USE_INPUT_SYSTEM - using UnityEngine.InputSystem; +using UnityEngine.InputSystem; #endif using System.Collections.Generic; diff --git a/com.unity.render-pipelines.core/Runtime/Common/CommonStructs.cs b/com.unity.render-pipelines.core/Runtime/Common/CommonStructs.cs index b2930e73561..2b38f5f79e4 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/CommonStructs.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/CommonStructs.cs @@ -5,7 +5,7 @@ namespace UnityEngine.Rendering /// /// Render Textures clear flag. /// - [Flags] + [Flags] public enum ClearFlag { /// Don't clear. diff --git a/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs b/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs index 8d5b7eda63e..172687451a1 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/CoreUnsafeUtils.cs @@ -161,8 +161,8 @@ public static void CopyTo(this T[] list, void* dest, int count) /// Left boundary. public static unsafe void QuickSort(uint[] arr, int left, int right) { - fixed (uint* ptr = arr) - CoreUnsafeUtils.QuickSort(ptr, left, right); + fixed(uint* ptr = arr) + CoreUnsafeUtils.QuickSort(ptr, left, right); } /// @@ -173,8 +173,8 @@ public static unsafe void QuickSort(uint[] arr, int left, int right) /// Left boundary. public static unsafe void QuickSort(ulong[] arr, int left, int right) { - fixed (ulong* ptr = arr) - CoreUnsafeUtils.QuickSort(ptr, left, right); + fixed(ulong* ptr = arr) + CoreUnsafeUtils.QuickSort(ptr, left, right); } /// @@ -417,7 +417,6 @@ public static void CombineHashes(int count, void* hashes, Hash1 var h = getter.Get(ref v); HashUtilities.AppendHash(ref h, ref *outHash); } - } /// diff --git a/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs b/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs index 66fe1a3ede2..99d20d0b11e 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/DynamicArray.cs @@ -6,7 +6,7 @@ namespace UnityEngine.Rendering /// Generic growable array. /// /// Type of the array. - public class DynamicArray where T: new() + public class DynamicArray where T : new() { T[] m_Array = null; @@ -112,5 +112,4 @@ public ref T this[int index] } } } - } diff --git a/com.unity.render-pipelines.core/Runtime/Common/DynamicResolutionHandler.cs b/com.unity.render-pipelines.core/Runtime/Common/DynamicResolutionHandler.cs index 964f85edeed..342e6f33466 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/DynamicResolutionHandler.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/DynamicResolutionHandler.cs @@ -3,12 +3,12 @@ namespace UnityEngine.Rendering { /// - /// The format of the delegate used to perofrm dynamic resolution. + /// The format of the delegate used to perofrm dynamic resolution. /// public delegate float PerformDynamicRes(); /// - /// The type of dynamic resolution scaler. It essentially defines what the output of the scaler is expected to be. + /// The type of dynamic resolution scaler. It essentially defines what the output of the scaler is expected to be. /// public enum DynamicResScalePolicyType { @@ -19,14 +19,14 @@ public enum DynamicResScalePolicyType ReturnsPercentage, /// /// If is the option, DynamicResolutionHandler expects the scaler to return a factor t in the [0..1] such that the final resolution percentage - /// is determined by lerp(minimumPercentage, maximumPercentage, t), where the minimum and maximum percentages are the one set in the GlobalDynamicResolutionSettings. + /// is determined by lerp(minimumPercentage, maximumPercentage, t), where the minimum and maximum percentages are the one set in the GlobalDynamicResolutionSettings. /// ReturnsMinMaxLerpFactor } /// - /// The class responsible to handle dynamic resolution. + /// The class responsible to handle dynamic resolution. /// public class DynamicResolutionHandler { @@ -49,13 +49,13 @@ public class DynamicResolutionHandler private Vector2Int cachedOriginalSize; /// - /// The filter that is used to upscale the rendering result to the native resolution. + /// The filter that is used to upscale the rendering result to the native resolution. /// public DynamicResUpscaleFilter filter { get; set; } /// /// The viewport of the final buffer. This is likely the resolution the dynamic resolution starts from before any scaling. Note this is NOT the target resolution the rendering will happen in - /// but the resolution the scaled rendered result will be upscaled to. + /// but the resolution the scaled rendered result will be upscaled to. /// public Vector2Int finalViewport { get; set; } @@ -66,7 +66,7 @@ public class DynamicResolutionHandler private static DynamicResolutionHandler s_Instance = new DynamicResolutionHandler(); /// - /// Get the instance of the global dynamic resolution handler. + /// Get the instance of the global dynamic resolution handler. /// public static DynamicResolutionHandler instance { get { return s_Instance; } } @@ -75,7 +75,6 @@ private DynamicResolutionHandler() { m_DynamicResMethod = DefaultDynamicResMethod; filter = DynamicResUpscaleFilter.Bilinear; - } // TODO: Eventually we will need to provide a good default implementation for this. @@ -143,13 +142,13 @@ public void Update(GlobalDynamicResolutionSettings settings, Action OnResolution if (!m_ForcingRes) { - if(m_ScalerType == DynamicResScalePolicyType.ReturnsMinMaxLerpFactor) + if (m_ScalerType == DynamicResScalePolicyType.ReturnsMinMaxLerpFactor) { float currLerp = m_DynamicResMethod(); float lerpFactor = Mathf.Clamp(currLerp, 0.0f, 1.0f); m_CurrentFraction = Mathf.Lerp(m_MinScreenFraction, m_MaxScreenFraction, lerpFactor); } - else if(m_ScalerType == DynamicResScalePolicyType.ReturnsPercentage) + else if (m_ScalerType == DynamicResScalePolicyType.ReturnsPercentage) { float percentageRequested = Mathf.Max(m_DynamicResMethod(), 5.0f); m_CurrentFraction = Mathf.Clamp(percentageRequested / 100.0f, m_MinScreenFraction, m_MaxScreenFraction); @@ -165,7 +164,7 @@ public void Update(GlobalDynamicResolutionSettings settings, Action OnResolution ScalableBufferManager.ResizeBuffers(m_CurrentFraction, m_CurrentFraction); } - if(OnResolutionChange != null) + if (OnResolutionChange != null) OnResolutionChange(); } else @@ -173,7 +172,7 @@ public void Update(GlobalDynamicResolutionSettings settings, Action OnResolution // Unity can change the scale factor by itself so we need to trigger the Action if that happens as well. if (!m_ForceSoftwareFallback && type == DynamicResolutionType.Hardware) { - if(ScalableBufferManager.widthScaleFactor != m_PrevHWScaleWidth || + if (ScalableBufferManager.widthScaleFactor != m_PrevHWScaleWidth || ScalableBufferManager.heightScaleFactor != m_PrevHWScaleHeight) { if (OnResolutionChange != null) diff --git a/com.unity.render-pipelines.core/Runtime/Common/ListBuffer.cs b/com.unity.render-pipelines.core/Runtime/Common/ListBuffer.cs index 594313c44f8..d43c91544b9 100644 --- a/com.unity.render-pipelines.core/Runtime/Common/ListBuffer.cs +++ b/com.unity.render-pipelines.core/Runtime/Common/ListBuffer.cs @@ -10,7 +10,7 @@ namespace UnityEngine.Rendering /// /// The type of the data stored in the list. public unsafe struct ListBuffer - where T: unmanaged + where T : unmanaged { private T* m_BufferPtr; private int m_Capacity; @@ -99,7 +99,7 @@ public bool TryAdd(in T value) /// The number of item to copy. public unsafe void CopyTo(T* dstBuffer, int startDstIndex, int copyCount) { - UnsafeUtility.MemCpy( dstBuffer + startDstIndex, m_BufferPtr, + UnsafeUtility.MemCpy(dstBuffer + startDstIndex, m_BufferPtr, UnsafeUtility.SizeOf() * copyCount); } @@ -116,7 +116,7 @@ public bool TryCopyTo(ListBuffer other) if (other.Count + Count >= other.m_Capacity) return false; - UnsafeUtility.MemCpy( other.m_BufferPtr + other.Count, m_BufferPtr, UnsafeUtility.SizeOf() * Count); + UnsafeUtility.MemCpy(other.m_BufferPtr + other.Count, m_BufferPtr, UnsafeUtility.SizeOf() * Count); *other.m_CountPtr += Count; return true; } @@ -135,7 +135,7 @@ public bool TryCopyFrom(T* srcPtr, int count) if (count + Count > m_Capacity) return false; - UnsafeUtility.MemCpy( m_BufferPtr + Count, srcPtr, UnsafeUtility.SizeOf() * count); + UnsafeUtility.MemCpy(m_BufferPtr + Count, srcPtr, UnsafeUtility.SizeOf() * count); *m_CountPtr += count; return true; } diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.Actions.cs b/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.Actions.cs index d515df034f3..14c65746f34 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.Actions.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.Actions.cs @@ -1,7 +1,7 @@ #if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE #define USE_INPUT_SYSTEM - using UnityEngine.InputSystem; - using UnityEngine.InputSystem.Controls; +using UnityEngine.InputSystem; +using UnityEngine.InputSystem.Controls; #endif using System.Collections.Generic; @@ -378,6 +378,7 @@ public void TriggerWithButton(InputAction action, float state) inputAction = action; Trigger(action.bindings.Count, state); } + #else public void TriggerWithButton(string[] buttons, float state) { @@ -401,6 +402,7 @@ public void TriggerWithKey(KeyCode[] keys, float state) m_PressedAxis = ""; Trigger(keys.Length, state); } + #endif void Reset() diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/DebugShapes.cs b/com.unity.render-pipelines.core/Runtime/Debugging/DebugShapes.cs index f556c9a7a05..e1407069f33 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/DebugShapes.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/DebugShapes.cs @@ -139,18 +139,18 @@ void BuildBox(ref Mesh outputMesh, float length, float width, float height) Vector3[] vertices = new Vector3[] { - // Bottom - p0, p1, p2, p3, - // Left - p7, p4, p0, p3, - // Front - p4, p5, p1, p0, - // Back - p6, p7, p3, p2, - // Right - p5, p6, p2, p1, - // Top - p7, p6, p5, p4 + // Bottom + p0, p1, p2, p3, + // Left + p7, p4, p0, p3, + // Front + p4, p5, p1, p0, + // Back + p6, p7, p3, p2, + // Right + p5, p6, p2, p1, + // Top + p7, p6, p5, p4 }; Vector3 up = Vector3.up; @@ -162,18 +162,18 @@ void BuildBox(ref Mesh outputMesh, float length, float width, float height) Vector3[] normales = new Vector3[] { - // Bottom - down, down, down, down, - // Left - left, left, left, left, - // Front - front, front, front, front, - // Back - back, back, back, back, - // Right - right, right, right, right, - // Top - up, up, up, up + // Bottom + down, down, down, down, + // Left + left, left, left, left, + // Front + front, front, front, front, + // Back + back, back, back, back, + // Right + right, right, right, right, + // Top + up, up, up, up }; Vector2 _00 = new Vector2(0f, 0f); @@ -183,39 +183,39 @@ void BuildBox(ref Mesh outputMesh, float length, float width, float height) Vector2[] uvs = new Vector2[] { - // Bottom - _11, _01, _00, _10, - // Left - _11, _01, _00, _10, - // Front - _11, _01, _00, _10, - // Back - _11, _01, _00, _10, - // Right - _11, _01, _00, _10, - // Top - _11, _01, _00, _10, + // Bottom + _11, _01, _00, _10, + // Left + _11, _01, _00, _10, + // Front + _11, _01, _00, _10, + // Back + _11, _01, _00, _10, + // Right + _11, _01, _00, _10, + // Top + _11, _01, _00, _10, }; int[] triangles = new int[] { - // Bottom - 3, 1, 0, + // Bottom + 3, 1, 0, 3, 2, 1, - // Left - 3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1, + // Left + 3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1, 3 + 4 * 1, 2 + 4 * 1, 1 + 4 * 1, - // Front - 3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2, + // Front + 3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2, 3 + 4 * 2, 2 + 4 * 2, 1 + 4 * 2, - // Back - 3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3, + // Back + 3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3, 3 + 4 * 3, 2 + 4 * 3, 1 + 4 * 3, - // Right - 3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4, + // Right + 3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4, 3 + 4 * 4, 2 + 4 * 4, 1 + 4 * 4, - // Top - 3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5, + // Top + 3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5, 3 + 4 * 5, 2 + 4 * 5, 1 + 4 * 5, }; @@ -407,8 +407,8 @@ void BuildPyramid(ref Mesh outputMesh, float width, float height, float depth) // Top Face vertices[0] = new Vector3(0f, 0f, 0f); - vertices[1] = new Vector3(-width/2.0f, height / 2.0f, depth); - vertices[2] = new Vector3( width / 2.0f, height / 2.0f, depth); + vertices[1] = new Vector3(-width / 2.0f, height / 2.0f, depth); + vertices[2] = new Vector3(width / 2.0f, height / 2.0f, depth); // Left Face vertices[3] = new Vector3(0f, 0f, 0f); @@ -437,7 +437,7 @@ void BuildPyramid(ref Mesh outputMesh, float width, float height, float depth) // The indexes for the side part is simple int[] triangles = new int[18]; - for(int idx = 0; idx < 12; ++idx) + for (int idx = 0; idx < 12; ++idx) { triangles[idx] = idx; } @@ -472,7 +472,7 @@ void BuildShapes() m_pyramidMesh = new Mesh(); BuildPyramid(ref m_pyramidMesh, 1.0f, 1.0f, 1.0f); } - + void RebuildResources() { if (m_sphereMesh == null || m_boxMesh == null || m_coneMesh == null || m_pyramidMesh == null) diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Containers.cs b/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Containers.cs index ce2aad6b1bd..d5727cb2b6e 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Containers.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Containers.cs @@ -133,7 +133,7 @@ public class Foldout : Container, IValueField /// /// Constructor. /// - public Foldout() : base() { } + public Foldout() : base() {} /// /// Constructor. /// diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs b/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs index d2005a63f8a..064c491ac81 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs @@ -98,7 +98,7 @@ public void SetValue(T value) /// /// Boolean field. /// - public class BoolField : Field { } + public class BoolField : Field {} /// /// Boolean field with history. /// diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/MousePositionDebug.cs b/com.unity.render-pipelines.core/Runtime/Debugging/MousePositionDebug.cs index 7e2c9dc2450..18704267d1a 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/MousePositionDebug.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/MousePositionDebug.cs @@ -1,7 +1,7 @@ #if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE #define USE_INPUT_SYSTEM - using UnityEngine.InputSystem; - using UnityEngine.InputSystem.Controls; +using UnityEngine.InputSystem; +using UnityEngine.InputSystem.Controls; #endif using UnityEditor; @@ -140,12 +140,12 @@ public void Cleanup() #endif } - /// - /// Get the mouse position in the scene or game view. - /// - /// Window height. - /// Get position in the scene view? - /// Coordinates of the mouse in the specified window. + /// + /// Get the mouse position in the scene or game view. + /// + /// Window height. + /// Get position in the scene view? + /// Coordinates of the mouse in the specified window. public Vector2 GetMousePosition(float ScreenHeight, bool sceneView) { #if UNITY_EDITOR diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerBitField.cs b/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerBitField.cs index 23fdb5088bf..faba2cbe0a5 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerBitField.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerBitField.cs @@ -42,7 +42,8 @@ internal override void SetWidget(DebugUI.Widget widget) toggle.nameLabel.text = enumName.text; toggle.Init(); toggleIndex++; - }; + } + ; for (; toggleIndex < toggles.Count; ++toggleIndex) { diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerEnumField.cs b/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerEnumField.cs index e6698d5030a..bf1b2d0d0f6 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerEnumField.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerEnumField.cs @@ -75,7 +75,7 @@ public override void OnIncrement(bool fast) //check if quickSeparators have not been constructed //it is the case when not constructed with autoenum var separators = m_Field.quickSeparators; - if(separators == null) + if (separators == null) { m_Field.InitQuickSeparators(); separators = m_Field.quickSeparators; @@ -83,7 +83,7 @@ public override void OnIncrement(bool fast) int idxSup = 0; for (; idxSup < separators.Length && index + 1 > separators[idxSup]; ++idxSup) ; - if(idxSup == separators.Length) + if (idxSup == separators.Length) { index = 0; } @@ -117,7 +117,7 @@ public override void OnDecrement(bool fast) if (index == 0) { - if(fast) + if (fast) { //check if quickSeparators have not been constructed //it is thecase when not constructed with autoenum diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerPanel.cs b/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerPanel.cs index dbd5a3b68e8..ae583069602 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerPanel.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerPanel.cs @@ -57,10 +57,10 @@ internal void ScrollTo(DebugUIHandlerWidget target) float GetYPosInScroll(RectTransform target) { var pivotOffset = new Vector3( - (0.5f - target.pivot.x) * target.rect.size.x, - (0.5f - target.pivot.y) * target.rect.size.y, - 0f - ); + (0.5f - target.pivot.x) * target.rect.size.x, + (0.5f - target.pivot.y) * target.rect.size.y, + 0f + ); var localPos = target.localPosition + pivotOffset; var worldPos = target.parent.TransformPoint(localPos); return m_ScrollTransform.TransformPoint(worldPos).y; diff --git a/com.unity.render-pipelines.core/Runtime/Debugging/ProfilingScope.cs b/com.unity.render-pipelines.core/Runtime/Debugging/ProfilingScope.cs index 4df457d9c97..91b85ed7ca0 100644 --- a/com.unity.render-pipelines.core/Runtime/Debugging/ProfilingScope.cs +++ b/com.unity.render-pipelines.core/Runtime/Debugging/ProfilingScope.cs @@ -129,7 +129,7 @@ public void End(CommandBuffer cmd) else cmd.EndSample(name); #else - m_Cmd.EndSample(name); + m_Cmd.EndSample(name); #endif inlineSampler?.End(); } @@ -214,7 +214,7 @@ public bool enableRecording public int inlineCpuSampleCount => 0; #endif // Keep the constructor private - ProfilingSampler() { } + ProfilingSampler() {} } #if DEVELOPMENT_BUILD || UNITY_EDITOR @@ -271,7 +271,7 @@ void Dispose(bool disposing) m_Disposed = true; } -} + } #else /// /// Scoped Profiling markers @@ -285,7 +285,6 @@ public struct ProfilingScope : IDisposable /// Profiling Sampler to be used for this scope. public ProfilingScope(CommandBuffer cmd, ProfilingSampler sampler) { - } /// diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs index c8ecc61700e..f2c7f3d5226 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs @@ -61,10 +61,12 @@ public void RegisterDebug(string name) var list = new List(); list.Add(new DebugUI.BoolField { displayName = "Clear Render Targets at creation", getter = () => clearRenderTargetsAtCreation, setter = value => clearRenderTargetsAtCreation = value }); // We cannot expose this option as it will change the active render target and the debug menu won't know where to render itself anymore. - // list.Add(new DebugUI.BoolField { displayName = "Clear Render Targets at release", getter = () => clearRenderTargetsAtRelease, setter = value => clearRenderTargetsAtRelease = value }); + // list.Add(new DebugUI.BoolField { displayName = "Clear Render Targets at release", getter = () => clearRenderTargetsAtRelease, setter = value => clearRenderTargetsAtRelease = value }); list.Add(new DebugUI.BoolField { displayName = "Disable Pass Culling", getter = () => disablePassCulling, setter = value => disablePassCulling = value }); list.Add(new DebugUI.BoolField { displayName = "Immediate Mode", getter = () => immediateMode, setter = value => immediateMode = value }); - list.Add(new DebugUI.Button { displayName = "Log Frame Information", + list.Add(new DebugUI.Button + { + displayName = "Log Frame Information", action = () => { logFrameInformation = true; @@ -73,7 +75,9 @@ public void RegisterDebug(string name) #endif } }); - list.Add(new DebugUI.Button { displayName = "Log Resources", + list.Add(new DebugUI.Button + { + displayName = "Log Resources", action = () => { logResources = true; @@ -394,7 +398,6 @@ public void CreateTextureIfInvalid(in TextureDesc desc, ref TextureHandle textur texture = m_Resources.CreateTexture(desc); } - /// /// Gets the descriptor of the specified Texture resource. /// @@ -517,7 +520,7 @@ public void Begin(in RenderGraphParameters parameters) m_CompiledPassInfos.Resize(m_CompiledPassInfos.capacity); m_CurrentImmediatePassIndex = 0; - for(int i = 0; i < (int)RenderGraphResourceType.Count; ++i) + for (int i = 0; i < (int)RenderGraphResourceType.Count; ++i) { if (m_ImmediateModeResourceList[i] == null) m_ImmediateModeResourceList[i] = new List(); @@ -573,7 +576,6 @@ public void Execute() } } - class ProfilingScopePassData { public ProfilingSampler sampler; @@ -614,6 +616,7 @@ public void EndProfilingSampler(ProfilingSampler sampler) }); } } + #endregion #region Internal Interface @@ -743,7 +746,6 @@ void CullOutputlessPasses() foreach (var index in passInfo.pass.resourceReadLists[type]) { m_CompiledResourcesInfos[type][index].refCount--; - } } } @@ -915,7 +917,6 @@ int GetLatestValidWriteIndex(in CompiledResourceInfo info) return -1; } - void UpdateResourceAllocationAndSynchronization() { int lastGraphicsPipeSync = -1; @@ -944,7 +945,6 @@ void UpdateResourceAllocationAndSynchronization() { UpdateResourceSynchronization(ref lastGraphicsPipeSync, ref lastComputePipeSync, passIndex, resourcesInfo[resource]); } - } // Gather all renderer lists @@ -1073,7 +1073,7 @@ ref CompiledPassInfo CompilePassImmediatly(RenderGraphPass pass) } // Create the necessary renderer lists - foreach(var rl in pass.usedRendererListList) + foreach (var rl in pass.usedRendererListList) { if (!m_Resources.IsRendererListCreated(rl)) m_RendererLists.Add(rl); @@ -1169,7 +1169,6 @@ void PreRenderPassSetRenderTargets(in CompiledPassInfo passInfo, RenderGraphCont { CoreUtils.SetRenderTarget(rgContext.cmd, m_Resources.GetTexture(pass.colorBuffers[0])); } - } } } @@ -1328,7 +1327,6 @@ void UpdateImportedResourceLifeTime(ref RenderGraphDebugData.ResourceDebugData d } } - void GenerateDebugData() { m_RenderGraphDebugData.Clear(); @@ -1452,4 +1450,3 @@ void Dispose(bool disposing) } } } - diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs index 49ea12e577b..ea45a58bef2 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs @@ -194,6 +194,7 @@ public void Dispose() { Dispose(true); } + #endregion #region Internal Interface @@ -241,6 +242,7 @@ internal void GenerateDebugData(bool value) { m_RenderPass.GenerateDebugData(value); } + #endregion } } diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphDefaultResources.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphDefaultResources.cs index 58b9809c074..da84c8468c9 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphDefaultResources.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphDefaultResources.cs @@ -57,7 +57,5 @@ internal void InitializeForRendering(RenderGraph renderGraph) blackTexture3DXR = renderGraph.ImportTexture(TextureXR.GetBlackTexture3D()); whiteTextureXR = renderGraph.ImportTexture(TextureXR.GetWhiteTexture()); } - } } - diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphObjectPool.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphObjectPool.cs index a69920a053c..c30f3911517 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphObjectPool.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphObjectPool.cs @@ -32,7 +32,7 @@ public void Release(T value) List<(object, (Type, int))> m_AllocatedArrays = new List<(object, (Type, int))>(); List m_AllocatedMaterialPropertyBlocks = new List(); - internal RenderGraphObjectPool() { } + internal RenderGraphObjectPool() {} /// /// Allocate a temporary typed array of a specific size. @@ -68,7 +68,7 @@ public MaterialPropertyBlock GetTempMaterialPropertyBlock() internal void ReleaseAllTempAlloc() { - foreach(var arrayDesc in m_AllocatedArrays) + foreach (var arrayDesc in m_AllocatedArrays) { bool result = m_ArrayPool.TryGetValue(arrayDesc.Item2, out var stack); Debug.Assert(result, "Correct stack type should always be allocated."); @@ -77,7 +77,7 @@ internal void ReleaseAllTempAlloc() m_AllocatedArrays.Clear(); - foreach(var mpb in m_AllocatedMaterialPropertyBlocks) + foreach (var mpb in m_AllocatedMaterialPropertyBlocks) { SharedObjectPool.sharedPool.Release(mpb); } diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs index 1ee14536848..5ad920a3bb8 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs @@ -9,7 +9,7 @@ namespace UnityEngine.Experimental.Rendering.RenderGraphModule abstract class RenderGraphPass { public RenderFunc GetExecuteDelegate() - where PassData : class, new() => ((RenderGraphPass)this).renderFunc; + where PassData : class, new() => ((RenderGraphPass) this).renderFunc; public abstract void Execute(RenderGraphContext renderGraphContext); public abstract void Release(RenderGraphObjectPool pool); diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs index 05b936e2c79..9b502fb440a 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs @@ -3,11 +3,10 @@ namespace UnityEngine.Experimental.Rendering.RenderGraphModule { - abstract class RenderGraphResourcePool where Type : class { // Dictionary tracks resources by hash and stores resources with same hash in a List (list instead of a stack because we need to be able to remove stale allocations, potentially in the middle of the stack). - protected Dictionary> m_ResourcePool = new Dictionary>(); + protected Dictionary> m_ResourcePool = new Dictionary>(); // This list allows us to determine if all resources were correctly released in the frame. // This is useful to warn in case of user error or avoid leaks when a render graph execution errors occurs for example. @@ -94,7 +93,6 @@ public void CheckFrameAllocation(bool onException, int frameIndex) m_FrameAllocatedResources.Clear(); } - struct ResourceLogInfo { public string name; @@ -108,7 +106,7 @@ public void LogResources(RenderGraphLogger logger) { foreach (var res in kvp.Value) { - allocationList.Add(new ResourceLogInfo { name = GetResourceName(res.resource), size = GetResourceSize(res.resource) } ); + allocationList.Add(new ResourceLogInfo { name = GetResourceName(res.resource), size = GetResourceSize(res.resource) }); } } diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs index b48ed33f270..e8d515a86d2 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceRegistry.cs @@ -67,7 +67,6 @@ class RenderGraphResource protected RenderGraphResource() { - } public override void Reset() @@ -159,7 +158,6 @@ internal ComputeBuffer GetComputeBuffer(in ComputeBufferHandle handle) #region Internal Interface private RenderGraphResourceRegistry() { - } internal RenderGraphResourceRegistry(RenderGraphDebugParams renderGraphDebug, RenderGraphLogger logger) @@ -364,15 +362,15 @@ internal void CreateAndClearTexture(RenderGraphContext rgContext, int index) { case TextureSizeMode.Explicit: resource.resource = RTHandles.Alloc(desc.width, desc.height, desc.slices, desc.depthBufferBits, desc.colorFormat, desc.filterMode, desc.wrapMode, desc.dimension, desc.enableRandomWrite, - desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.msaaSamples, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, name); + desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.msaaSamples, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, name); break; case TextureSizeMode.Scale: resource.resource = RTHandles.Alloc(desc.scale, desc.slices, desc.depthBufferBits, desc.colorFormat, desc.filterMode, desc.wrapMode, desc.dimension, desc.enableRandomWrite, - desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.enableMSAA, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, name); + desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.enableMSAA, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, name); break; case TextureSizeMode.Functor: resource.resource = RTHandles.Alloc(desc.func, desc.slices, desc.depthBufferBits, desc.colorFormat, desc.filterMode, desc.wrapMode, desc.dimension, desc.enableRandomWrite, - desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.enableMSAA, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, name); + desc.useMipMap, desc.autoGenerateMips, desc.isShadowMap, desc.anisoLevel, desc.mipMapBias, desc.enableMSAA, desc.bindTextureMS, desc.useDynamicScale, desc.memoryless, name); break; } } @@ -381,7 +379,7 @@ internal void CreateAndClearTexture(RenderGraphContext rgContext, int index) #if UNITY_2020_2_OR_NEWER var fastMemDesc = resource.desc.fastMemoryDesc; - if(fastMemDesc.inFastMemory) + if (fastMemDesc.inFastMemory) { resource.resource.SwitchToFastMemory(rgContext.cmd, fastMemDesc.residencyFraction, fastMemDesc.flags); } diff --git a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResources.cs b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResources.cs index 824f43ce28b..f1b55b5c4ef 100644 --- a/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResources.cs +++ b/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResources.cs @@ -445,5 +445,4 @@ public override int GetHashCode() return hashCode; } } - } diff --git a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs index 9cc0767e1ff..b630bbb6eff 100644 --- a/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs +++ b/com.unity.render-pipelines.core/Runtime/ShaderGenerator/ShaderGeneratorAttributes.cs @@ -116,7 +116,7 @@ public class GenerateHLSL : System.Attribute /// Generate a constant buffer. /// When generating a constant buffer, specify the optional constant register. public GenerateHLSL(PackingRules rules = PackingRules.Exact, bool needAccessors = true, bool needSetters = false, bool needParamDebug = false, int paramDefinesStart = 1, - bool omitStructDeclaration = false, bool containsPackedFields = false, bool generateCBuffer = false, int constantRegister = -1) + bool omitStructDeclaration = false, bool containsPackedFields = false, bool generateCBuffer = false, int constantRegister = -1) { packingRules = rules; this.needAccessors = needAccessors; @@ -312,6 +312,5 @@ public PackingAttribute(string displayName = "", FieldPacking packingScheme = Fi /// public struct ShaderGenUInt4 { - } } diff --git a/com.unity.render-pipelines.core/Runtime/Textures/BufferedRTHandleSystem.cs b/com.unity.render-pipelines.core/Runtime/Textures/BufferedRTHandleSystem.cs index 51888e2e4aa..c9d74c83573 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/BufferedRTHandleSystem.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/BufferedRTHandleSystem.cs @@ -91,7 +91,7 @@ public void AllocBuffer( int bufferId, Func allocator, int bufferCount - ) + ) { var buffer = new RTHandle[bufferCount]; m_RTHandles.Add(bufferId, buffer); @@ -144,7 +144,6 @@ public void ResetReferenceSize(int width, int height) m_RTHandleSystem.ResetReferenceSize(width, height); } - void Swap() { foreach (var item in m_RTHandles) diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs index e66b7b515cb..10d84198c55 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs @@ -103,7 +103,7 @@ public static implicit operator RenderTargetIdentifier(RTHandle handle) internal void SetRenderTexture(RenderTexture rt) { - m_RT= rt; + m_RT = rt; m_ExternalTexture = null; m_NameID = new RenderTargetIdentifier(rt); } @@ -150,7 +150,7 @@ public Vector2Int GetScaledSize(Vector2Int refSize) return new Vector2Int( x: Mathf.RoundToInt(scaleFactor.x * refSize.x), y: Mathf.RoundToInt(scaleFactor.y * refSize.y) - ); + ); } } @@ -167,7 +167,7 @@ public void SwitchToFastMemory(CommandBuffer cmd, float residencyFraction = 1.0f, FastMemoryFlags flags = FastMemoryFlags.SpillTop, bool copyContents = false - ) + ) { residencyFraction = Mathf.Clamp01(residencyFraction); cmd.SwitchIntoFastMemory(m_RT, flags, residencyFraction, copyContents); @@ -182,7 +182,7 @@ public void SwitchToFastMemory(CommandBuffer cmd, public void CopyToFastMemory(CommandBuffer cmd, float residencyFraction = 1.0f, FastMemoryFlags flags = FastMemoryFlags.SpillTop - ) + ) { SwitchToFastMemory(cmd, residencyFraction, flags, copyContents: true); } @@ -196,7 +196,7 @@ public void SwitchOutFastMemory(CommandBuffer cmd, bool copyContents = true) { cmd.SwitchOutOfFastMemory(m_RT, copyContents); } -#endif +#endif } } diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs index 9647a87c1bc..3daec6b6f5f 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandleSystem.cs @@ -68,7 +68,7 @@ internal enum ResizeMode int m_MaxWidths = 0; int m_MaxHeights = 0; #if UNITY_EDITOR - // In editor every now and then we must reset the size of the rthandle system if it was set very high and then switched back to a much smaller scale. + // In editor every now and then we must reset the size of the rthandle system if it was set very high and then switched back to a much smaller scale. int m_FramesSinceLastReset = 0; #endif @@ -238,7 +238,7 @@ public void SetReferenceSize(int width, int height, MSAASamples msaaSamples, boo /// State of hardware dynamic resolution. public void SetHardwareDynamicResolutionState(bool enableHWDynamicRes) { - if(enableHWDynamicRes != m_HardwareDynamicResRequested) + if (enableHWDynamicRes != m_HardwareDynamicResRequested) { m_HardwareDynamicResRequested = enableHWDynamicRes; @@ -250,7 +250,7 @@ public void SetHardwareDynamicResolutionState(bool enableHWDynamicRes) // Grab the render texture var renderTexture = rth.m_RT; - if(renderTexture) + if (renderTexture) { // Free the previous version renderTexture.Release(); @@ -317,15 +317,15 @@ void DemandResize(RTHandle rth) // Generate a new name rt.name = CoreUtils.GetRenderTargetAutoName( - rt.width, - rt.height, - rt.volumeDepth, - rt.format, - rth.m_Name, - mips: rt.useMipMap, - enableMSAA: rth.m_EnableMSAA, - msaaSamples: m_ScaledRTCurrentMSAASamples - ); + rt.width, + rt.height, + rt.volumeDepth, + rt.format, + rth.m_Name, + mips: rt.useMipMap, + enableMSAA: rth.m_EnableMSAA, + msaaSamples: m_ScaledRTCurrentMSAASamples + ); // Create the new texture rt.Create(); @@ -462,7 +462,7 @@ public RTHandle Alloc( bool useDynamicScale = false, RenderTextureMemoryless memoryless = RenderTextureMemoryless.None, string name = "" - ) + ) { bool enableMSAA = msaaSamples != MSAASamples.None; if (!enableMSAA && bindTextureMS == true) @@ -494,11 +494,9 @@ public RTHandle Alloc( memorylessMode = memoryless, name = CoreUtils.GetRenderTargetAutoName(width, height, slices, format, name, mips: useMipMap, enableMSAA: enableMSAA, msaaSamples: msaaSamples) }; - } else { - rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat) { hideFlags = HideFlags.HideAndDontSave, @@ -580,7 +578,7 @@ public RTHandle Alloc( bool useDynamicScale = false, RenderTextureMemoryless memoryless = RenderTextureMemoryless.None, string name = "" - ) + ) { // If an MSAA target is requested, make sure the support was on if (enableMSAA) @@ -590,25 +588,25 @@ public RTHandle Alloc( int height = Mathf.Max(Mathf.RoundToInt(scaleFactor.y * GetMaxHeight()), 1); var rth = AllocAutoSizedRenderTexture(width, - height, - slices, - depthBufferBits, - colorFormat, - filterMode, - wrapMode, - dimension, - enableRandomWrite, - useMipMap, - autoGenerateMips, - isShadowMap, - anisoLevel, - mipMapBias, - enableMSAA, - bindTextureMS, - useDynamicScale, - memoryless, - name - ); + height, + slices, + depthBufferBits, + colorFormat, + filterMode, + wrapMode, + dimension, + enableRandomWrite, + useMipMap, + autoGenerateMips, + isShadowMap, + anisoLevel, + mipMapBias, + enableMSAA, + bindTextureMS, + useDynamicScale, + memoryless, + name + ); rth.referenceSize = new Vector2Int(width, height); @@ -668,32 +666,32 @@ public RTHandle Alloc( bool useDynamicScale = false, RenderTextureMemoryless memoryless = RenderTextureMemoryless.None, string name = "" - ) + ) { var scaleFactor = scaleFunc(new Vector2Int(GetMaxWidth(), GetMaxHeight())); int width = Mathf.Max(scaleFactor.x, 1); int height = Mathf.Max(scaleFactor.y, 1); var rth = AllocAutoSizedRenderTexture(width, - height, - slices, - depthBufferBits, - colorFormat, - filterMode, - wrapMode, - dimension, - enableRandomWrite, - useMipMap, - autoGenerateMips, - isShadowMap, - anisoLevel, - mipMapBias, - enableMSAA, - bindTextureMS, - useDynamicScale, - memoryless, - name - ); + height, + slices, + depthBufferBits, + colorFormat, + filterMode, + wrapMode, + dimension, + enableRandomWrite, + useMipMap, + autoGenerateMips, + isShadowMap, + anisoLevel, + mipMapBias, + enableMSAA, + bindTextureMS, + useDynamicScale, + memoryless, + name + ); rth.referenceSize = new Vector2Int(width, height); @@ -722,7 +720,7 @@ RTHandle AllocAutoSizedRenderTexture( bool useDynamicScale, RenderTextureMemoryless memoryless, string name - ) + ) { // Here user made a mistake in setting up msaa/bindMS, hence the warning if (!enableMSAA && bindTextureMS == true) @@ -877,7 +875,6 @@ private static RTHandle Alloc(RTHandle tex) return null; } - internal string DumpRTInfo() { string result = ""; diff --git a/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs b/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs index 342ce9c58a8..eb0eda0154a 100644 --- a/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs +++ b/com.unity.render-pipelines.core/Runtime/Textures/RTHandles.cs @@ -65,7 +65,7 @@ public static RTHandle Alloc( bool useDynamicScale = false, RenderTextureMemoryless memoryless = RenderTextureMemoryless.None, string name = "" - ) + ) { return s_DefaultInstance.Alloc( width, @@ -87,7 +87,7 @@ public static RTHandle Alloc( useDynamicScale, memoryless, name - ); + ); } /// @@ -131,7 +131,7 @@ public static RTHandle Alloc( bool useDynamicScale = false, RenderTextureMemoryless memoryless = RenderTextureMemoryless.None, string name = "" - ) + ) { return s_DefaultInstance.Alloc( scaleFactor, @@ -152,7 +152,7 @@ public static RTHandle Alloc( useDynamicScale, memoryless, name - ); + ); } /// @@ -196,7 +196,7 @@ public static RTHandle Alloc( bool useDynamicScale = false, RenderTextureMemoryless memoryless = RenderTextureMemoryless.None, string name = "" - ) + ) { return s_DefaultInstance.Alloc( scaleFunc, @@ -217,7 +217,7 @@ public static RTHandle Alloc( useDynamicScale, memoryless, name - ); + ); } /// @@ -279,14 +279,14 @@ public static void Initialize( int height, bool scaledRTsupportsMSAA, MSAASamples scaledRTMSAASamples - ) + ) { s_DefaultInstance.Initialize( width, height, scaledRTsupportsMSAA, scaledRTMSAASamples - ); + ); } /// @@ -317,13 +317,13 @@ public static void SetReferenceSize( int width, int height, MSAASamples msaaSamples - ) + ) { s_DefaultInstance.SetReferenceSize( width, height, msaaSamples - ); + ); } /// diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/BitArray.cs b/com.unity.render-pipelines.core/Runtime/Utilities/BitArray.cs index ad773481f85..0632f5972d2 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/BitArray.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/BitArray.cs @@ -104,21 +104,21 @@ public BitArray8(IEnumerable bitIndexTrue) /// /// Bit array with which to do the operation. /// The resulting bit array. - public static BitArray8 operator ~(BitArray8 a) => new BitArray8((byte)~a.data); + public static BitArray8 operator~(BitArray8 a) => new BitArray8((byte)~a.data); /// /// Bit-wise Or operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray8 operator |(BitArray8 a, BitArray8 b) => new BitArray8((byte)(a.data | b.data)); + public static BitArray8 operator|(BitArray8 a, BitArray8 b) => new BitArray8((byte)(a.data | b.data)); /// /// Bit-wise And operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray8 operator &(BitArray8 a, BitArray8 b) => new BitArray8((byte)(a.data & b.data)); + public static BitArray8 operator&(BitArray8 a, BitArray8 b) => new BitArray8((byte)(a.data & b.data)); /// /// Bit-wise And @@ -144,14 +144,14 @@ public BitArray8(IEnumerable bitIndexTrue) /// First bit array. /// Second bit array. /// True if both bit arrays are equals. - public static bool operator ==(BitArray8 a, BitArray8 b) => a.data == b.data; + public static bool operator==(BitArray8 a, BitArray8 b) => a.data == b.data; /// /// Inequality operator. /// /// First bit array. /// Second bit array. /// True if the bit arrays are not equals. - public static bool operator !=(BitArray8 a, BitArray8 b) => a.data != b.data; + public static bool operator!=(BitArray8 a, BitArray8 b) => a.data != b.data; /// /// Equality operator. /// @@ -223,21 +223,21 @@ public BitArray16(IEnumerable bitIndexTrue) /// /// Bit array with which to do the operation. /// The resulting bit array. - public static BitArray16 operator ~(BitArray16 a) => new BitArray16((ushort)~a.data); + public static BitArray16 operator~(BitArray16 a) => new BitArray16((ushort)~a.data); /// /// Bit-wise Or operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray16 operator |(BitArray16 a, BitArray16 b) => new BitArray16((ushort)(a.data | b.data)); + public static BitArray16 operator|(BitArray16 a, BitArray16 b) => new BitArray16((ushort)(a.data | b.data)); /// /// Bit-wise And operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray16 operator &(BitArray16 a, BitArray16 b) => new BitArray16((ushort)(a.data & b.data)); + public static BitArray16 operator&(BitArray16 a, BitArray16 b) => new BitArray16((ushort)(a.data & b.data)); /// /// Bit-wise And @@ -263,14 +263,14 @@ public BitArray16(IEnumerable bitIndexTrue) /// First bit array. /// Second bit array. /// True if both bit arrays are equals. - public static bool operator ==(BitArray16 a, BitArray16 b) => a.data == b.data; + public static bool operator==(BitArray16 a, BitArray16 b) => a.data == b.data; /// /// Inequality operator. /// /// First bit array. /// Second bit array. /// True if the bit arrays are not equals. - public static bool operator !=(BitArray16 a, BitArray16 b) => a.data != b.data; + public static bool operator!=(BitArray16 a, BitArray16 b) => a.data != b.data; /// /// Equality operator. /// @@ -361,21 +361,21 @@ public BitArray32(IEnumerable bitIndexTrue) /// /// Bit array with which to do the operation. /// The resulting bit array. - public static BitArray32 operator ~(BitArray32 a) => new BitArray32(~a.data); + public static BitArray32 operator~(BitArray32 a) => new BitArray32(~a.data); /// /// Bit-wise Or operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray32 operator |(BitArray32 a, BitArray32 b) => new BitArray32(a.data | b.data); + public static BitArray32 operator|(BitArray32 a, BitArray32 b) => new BitArray32(a.data | b.data); /// /// Bit-wise And operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray32 operator &(BitArray32 a, BitArray32 b) => new BitArray32(a.data & b.data); + public static BitArray32 operator&(BitArray32 a, BitArray32 b) => new BitArray32(a.data & b.data); /// /// Equality operator. @@ -383,14 +383,14 @@ public BitArray32(IEnumerable bitIndexTrue) /// First bit array. /// Second bit array. /// True if both bit arrays are equals. - public static bool operator ==(BitArray32 a, BitArray32 b) => a.data == b.data; + public static bool operator==(BitArray32 a, BitArray32 b) => a.data == b.data; /// /// Inequality operator. /// /// First bit array. /// Second bit array. /// True if the bit arrays are not equals. - public static bool operator !=(BitArray32 a, BitArray32 b) => a.data != b.data; + public static bool operator!=(BitArray32 a, BitArray32 b) => a.data != b.data; /// /// Equality operator. /// @@ -462,21 +462,21 @@ public BitArray64(IEnumerable bitIndexTrue) /// /// Bit array with which to do the operation. /// The resulting bit array. - public static BitArray64 operator ~(BitArray64 a) => new BitArray64(~a.data); + public static BitArray64 operator~(BitArray64 a) => new BitArray64(~a.data); /// /// Bit-wise Or operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray64 operator |(BitArray64 a, BitArray64 b) => new BitArray64(a.data | b.data); + public static BitArray64 operator|(BitArray64 a, BitArray64 b) => new BitArray64(a.data | b.data); /// /// Bit-wise And operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray64 operator &(BitArray64 a, BitArray64 b) => new BitArray64(a.data & b.data); + public static BitArray64 operator&(BitArray64 a, BitArray64 b) => new BitArray64(a.data & b.data); /// /// Bit-wise And @@ -502,14 +502,14 @@ public BitArray64(IEnumerable bitIndexTrue) /// First bit array. /// Second bit array. /// True if both bit arrays are equals. - public static bool operator ==(BitArray64 a, BitArray64 b) => a.data == b.data; + public static bool operator==(BitArray64 a, BitArray64 b) => a.data == b.data; /// /// Inequality operator. /// /// First bit array. /// Second bit array. /// True if the bit arrays are not equals. - public static bool operator !=(BitArray64 a, BitArray64 b) => a.data != b.data; + public static bool operator!=(BitArray64 a, BitArray64 b) => a.data != b.data; /// /// Equality operator. /// @@ -567,6 +567,7 @@ public BitArray128(ulong initValue1, ulong initValue2) data1 = initValue1; data2 = initValue2; } + /// /// Constructor. /// @@ -592,21 +593,21 @@ public BitArray128(IEnumerable bitIndexTrue) /// /// First bit array. /// The resulting bit array. - public static BitArray128 operator ~(BitArray128 a) => new BitArray128(~a.data1, ~a.data2); + public static BitArray128 operator~(BitArray128 a) => new BitArray128(~a.data1, ~a.data2); /// /// Bit-wise Or operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray128 operator |(BitArray128 a, BitArray128 b) => new BitArray128(a.data1 | b.data1, a.data2 | b.data2); + public static BitArray128 operator|(BitArray128 a, BitArray128 b) => new BitArray128(a.data1 | b.data1, a.data2 | b.data2); /// /// Bit-wise And operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray128 operator &(BitArray128 a, BitArray128 b) => new BitArray128(a.data1 & b.data1, a.data2 & b.data2); + public static BitArray128 operator&(BitArray128 a, BitArray128 b) => new BitArray128(a.data1 & b.data1, a.data2 & b.data2); /// /// Bit-wise And @@ -632,14 +633,14 @@ public BitArray128(IEnumerable bitIndexTrue) /// First bit array. /// Second bit array. /// True if both bit arrays are equals. - public static bool operator ==(BitArray128 a, BitArray128 b) => a.data1 == b.data1 && a.data2 == b.data2; + public static bool operator==(BitArray128 a, BitArray128 b) => a.data1 == b.data1 && a.data2 == b.data2; /// /// Inequality operator. /// /// First bit array. /// Second bit array. /// True if the bit arrays are not equals. - public static bool operator !=(BitArray128 a, BitArray128 b) => a.data1 != b.data1 || a.data2 != b.data2; + public static bool operator!=(BitArray128 a, BitArray128 b) => a.data1 != b.data1 || a.data2 != b.data2; /// /// Equality operator. /// @@ -685,8 +686,8 @@ public struct BitArray256 : IBitArray public string humanizedData => System.Text.RegularExpressions.Regex.Replace(String.Format("{0, " + 64u + "}", Convert.ToString((long)data4, 2)).Replace(' ', '0'), ".{8}", "$0.") + System.Text.RegularExpressions.Regex.Replace(String.Format("{0, " + 64u + "}", Convert.ToString((long)data3, 2)).Replace(' ', '0'), ".{8}", "$0.") - + System.Text.RegularExpressions.Regex.Replace(String.Format("{0, " + 64u + "}", Convert.ToString((long) data2, 2)).Replace(' ', '0'), ".{8}", "$0.") - + System.Text.RegularExpressions.Regex.Replace(String.Format("{0, " + 64u + "}", Convert.ToString((long) data1, 2)).Replace(' ', '0'), ".{8}", "$0.").TrimEnd('.'); + + System.Text.RegularExpressions.Regex.Replace(String.Format("{0, " + 64u + "}", Convert.ToString((long)data2, 2)).Replace(' ', '0'), ".{8}", "$0.") + + System.Text.RegularExpressions.Regex.Replace(String.Format("{0, " + 64u + "}", Convert.ToString((long)data1, 2)).Replace(' ', '0'), ".{8}", "$0.").TrimEnd('.'); /// /// Returns the state of the bit at a specific index. @@ -713,6 +714,7 @@ public BitArray256(ulong initValue1, ulong initValue2, ulong initValue3, ulong i data3 = initValue3; data4 = initValue4; } + /// /// Constructor. /// @@ -741,21 +743,21 @@ public BitArray256(IEnumerable bitIndexTrue) /// /// Bit array with which to do the operation. /// The resulting bit array. - public static BitArray256 operator ~(BitArray256 a) => new BitArray256(~a.data1, ~a.data2, ~a.data3, ~a.data4); + public static BitArray256 operator~(BitArray256 a) => new BitArray256(~a.data1, ~a.data2, ~a.data3, ~a.data4); /// /// Bit-wise Or operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray256 operator |(BitArray256 a, BitArray256 b) => new BitArray256(a.data1 | b.data1, a.data2 | b.data2, a.data3 | b.data3, a.data4 | b.data4); + public static BitArray256 operator|(BitArray256 a, BitArray256 b) => new BitArray256(a.data1 | b.data1, a.data2 | b.data2, a.data3 | b.data3, a.data4 | b.data4); /// /// Bit-wise And operator /// /// First bit array. /// Second bit array. /// The resulting bit array. - public static BitArray256 operator &(BitArray256 a, BitArray256 b) => new BitArray256(a.data1 & b.data1, a.data2 & b.data2, a.data3 & b.data3, a.data4 & b.data4); + public static BitArray256 operator&(BitArray256 a, BitArray256 b) => new BitArray256(a.data1 & b.data1, a.data2 & b.data2, a.data3 & b.data3, a.data4 & b.data4); /// /// Bit-wise And @@ -781,14 +783,14 @@ public BitArray256(IEnumerable bitIndexTrue) /// First bit array. /// Second bit array. /// True if both bit arrays are equals. - public static bool operator ==(BitArray256 a, BitArray256 b) => a.data1 == b.data1 && a.data2 == b.data2 && a.data3 == b.data3 && a.data4 == b.data4; + public static bool operator==(BitArray256 a, BitArray256 b) => a.data1 == b.data1 && a.data2 == b.data2 && a.data3 == b.data3 && a.data4 == b.data4; /// /// Inequality operator. /// /// First bit array. /// Second bit array. /// True if the bit arrays are not equals. - public static bool operator !=(BitArray256 a, BitArray256 b) => a.data1 != b.data1 || a.data2 != b.data2 || a.data3 != b.data3 || a.data4 != b.data4; + public static bool operator!=(BitArray256 a, BitArray256 b) => a.data1 != b.data1 || a.data2 != b.data2 || a.data3 != b.data3 || a.data4 != b.data4; /// /// Equality operator. /// @@ -873,11 +875,11 @@ public static bool Get128(uint index, ulong data1, ulong data2) public static bool Get256(uint index, ulong data1, ulong data2, ulong data3, ulong data4) => index < 128u ? index < 64u - ? (data1 & (1uL << (int)index)) != 0uL - : (data2 & (1uL << (int)(index - 64u))) != 0uL + ? (data1 & (1uL << (int)index)) != 0uL + : (data2 & (1uL << (int)(index - 64u))) != 0uL : index < 192u - ? (data3 & (1uL << (int)(index - 128u))) != 0uL - : (data4 & (1uL << (int)(index - 192u))) != 0uL; + ? (data3 & (1uL << (int)(index - 128u))) != 0uL + : (data4 & (1uL << (int)(index - 192u))) != 0uL; /// /// Set a bit at a specific index. @@ -915,13 +917,13 @@ public static bool Get256(uint index, ulong data1, ulong data2, ulong data3, ulo /// Bit array data 2. /// Value to set the bit to. public static void Set128(uint index, ref ulong data1, ref ulong data2, bool value) - { if (index < 64u) data1 = (value ? (data1 | (1uL << (int)index)) : (data1 & ~(1uL << (int)index))); else data2 = (value ? (data2 | (1uL << (int)(index - 64u))) : (data2 & ~(1uL << (int)(index - 64u)))); } + /// /// Set a bit at a specific index. /// diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/CameraCaptureBridge.cs b/com.unity.render-pipelines.core/Runtime/Utilities/CameraCaptureBridge.cs index e65f83c342b..2e8018a9178 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/CameraCaptureBridge.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/CameraCaptureBridge.cs @@ -79,7 +79,7 @@ public static bool enabled #else _enabled #endif - ; + ; } set { @@ -109,7 +109,7 @@ public static IEnumerator> GetCapt #elif UNITY_EDITOR var recorderActions = UnityEditor.Recorder.Input.CameraCapture.GetActions(camera); if (recorderActions != null) - return recorderActions; + return recorderActions; #endif if (!actionDict.TryGetValue(camera, out var actions)) diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/ColorUtils.cs b/com.unity.render-pipelines.core/Runtime/Utilities/ColorUtils.cs index 01920973d81..0512031e645 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/ColorUtils.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/ColorUtils.cs @@ -9,14 +9,14 @@ public static class ColorUtils { /// /// Calibration constant (K) used for our virtual reflected light meter. Modifying this will lead to a change on how average scene luminance - /// gets mapped to exposure. + /// gets mapped to exposure. /// static public float s_LightMeterCalibrationConstant = 12.5f; /// /// Factor used for our lens system w.r.t. exposure calculation. Modifying this will lead to a change on how linear exposure /// multipliers are computed from EV100 values (and viceversa). s_LensAttenuation models transmission attenuation and lens vignetting. - /// Note that according to the standard ISO 12232, a lens saturates at s_LensAttenuation = 0.78f (under ISO 100). + /// Note that according to the standard ISO 12232, a lens saturates at s_LensAttenuation = 0.78f (under ISO 100). /// static public float s_LensAttenuation = 0.65f; @@ -272,7 +272,7 @@ public static float ComputeEV100FromAvgLuminance(float avgLuminance) // The default is 12.5% as it is the closest to 12.7% in order to have // a middle gray at 18% with a sqrt(2) room for specular highlights // Note that this gives equivalent results as using an incident light meter - // with a calibration constant of C=314. + // with a calibration constant of C=314. float K = s_LightMeterCalibrationConstant; return Mathf.Log(avgLuminance * 100f / K, 2f); } diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/CoreMatrixUtils.cs b/com.unity.render-pipelines.core/Runtime/Utilities/CoreMatrixUtils.cs index 21f4f2f06e1..65967b0d505 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/CoreMatrixUtils.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/CoreMatrixUtils.cs @@ -14,7 +14,7 @@ public static class CoreMatrixUtils { /// /// This function provides the equivalent of multiplying matrix parameter inOutMatrix with a translation matrix defined by the parameter translation. - /// The order of the equivalent multiplication is inOutMatrix * translation. + /// The order of the equivalent multiplication is inOutMatrix * translation. /// /// Matrix to multiply with translation. /// Translation component to multiply to the matrix. @@ -27,7 +27,7 @@ public static void MatrixTimesTranslation(ref Matrix4x4 inOutMatrix, Vector3 tra /// /// This function provides the equivalent of multiplying a translation matrix defined by the parameter translation with the matrix specified by the parameter inOutMatrix. - /// The order of the equivalent multiplication is translation * inOutMatrix. + /// The order of the equivalent multiplication is translation * inOutMatrix. /// /// Matrix to multiply with translation. /// Translation component to multiply to the matrix. @@ -51,7 +51,7 @@ public static void TranslationTimesMatrix(ref Matrix4x4 inOutMatrix, Vector3 tra /// /// Multiplies a matrix with a perspective matrix. This function is faster than performing the full matrix multiplication. - /// The operation order is perspective * rhs. + /// The operation order is perspective * rhs. /// /// The perspective matrix to multiply with rhs. /// A matrix to be multiply to perspective. @@ -137,7 +137,7 @@ private static Matrix4x4 MultiplyGenericOrthoMatrix(Matrix4x4 ortho, Matrix4x4 r /// /// Multiplies a matrix with an orthographic matrix. This function is faster than performing the full matrix multiplication. - /// The operation order is ortho * rhs. + /// The operation order is ortho * rhs. /// /// The ortho matrix to multiply with rhs. /// A matrix to be multiply to perspective. @@ -148,10 +148,9 @@ public static Matrix4x4 MultiplyOrthoMatrix(Matrix4x4 ortho, Matrix4x4 rhs, bool return centered ? MultiplyGenericOrthoMatrix(ortho, rhs) : MultiplyOrthoMatrixCentered(ortho, rhs); } - /// /// Multiplies a matrix with a projection matrix. This function is faster than performing the full matrix multiplication. - /// The operation order is projMatrix * rhs. + /// The operation order is projMatrix * rhs. /// /// The projection matrix to multiply with rhs. /// A matrix to be multiply to perspective. diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs b/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs index a686d086c8b..4287f1d7357 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs @@ -225,6 +225,7 @@ public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buf cmd.SetRenderTarget(buffer, miplevel, cubemapFace, depthSlice); ClearRenderTarget(cmd, clearFlag, clearColor); } + /// /// Set the current render texture. /// @@ -1161,6 +1162,7 @@ static CoreUtils() var lambda = System.Linq.Expressions.Expression.Lambda>>(fieldExpression); materialEditors = lambda.Compile(); } + #endif /// diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/DelegateUtility.cs b/com.unity.render-pipelines.core/Runtime/Utilities/DelegateUtility.cs index 1a18beda81f..2d3298e3898 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/DelegateUtility.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/DelegateUtility.cs @@ -24,7 +24,7 @@ public static Delegate Cast(Delegate source, Type type) Delegate[] delegatesDest = new Delegate[delegates.Length]; for (int nDelegate = 0; nDelegate < delegates.Length; nDelegate++) delegatesDest[nDelegate] = Delegate.CreateDelegate(type, - delegates[nDelegate].Target, delegates[nDelegate].Method); + delegates[nDelegate].Target, delegates[nDelegate].Method); return Delegate.Combine(delegatesDest); } } diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/MaterialQuality.cs b/com.unity.render-pipelines.core/Runtime/Utilities/MaterialQuality.cs index 879ac777aaf..998adac6d64 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/MaterialQuality.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/MaterialQuality.cs @@ -58,7 +58,7 @@ public static MaterialQuality GetHighestQuality(this MaterialQuality levels) { for (var i = Keywords.Length - 1; i >= 0; --i) { - var level = (MaterialQuality) (1 << i); + var level = (MaterialQuality)(1 << i); if ((levels & level) != 0) return level; } @@ -118,7 +118,7 @@ public static void SetGlobalShaderKeywords(this MaterialQuality level) { for (var i = 0; i < KeywordNames.Length; ++i) { - if ((level & (MaterialQuality) (1 << i)) != 0) + if ((level & (MaterialQuality)(1 << i)) != 0) Shader.EnableKeyword(KeywordNames[i]); else Shader.DisableKeyword(KeywordNames[i]); @@ -150,7 +150,7 @@ public static int ToFirstIndex(this MaterialQuality level) { for (var i = 0; i < KeywordNames.Length; ++i) { - if ((level & (MaterialQuality) (1 << i)) != 0) + if ((level & (MaterialQuality)(1 << i)) != 0) return i; } @@ -162,6 +162,6 @@ public static int ToFirstIndex(this MaterialQuality level) /// /// Index of the material quality. /// The equivalent enum. - public static MaterialQuality FromIndex(int index) => (MaterialQuality) (1 << index); + public static MaterialQuality FromIndex(int index) => (MaterialQuality)(1 << index); } } diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/ResourceReloader.cs b/com.unity.render-pipelines.core/Runtime/Utilities/ResourceReloader.cs index 50d04978cdb..f74440bdd67 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/ResourceReloader.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/ResourceReloader.cs @@ -42,7 +42,6 @@ public static (bool hasChange, bool assetDatabaseNotReady) TryReloadAllNullIn(Sy } } - /// /// Looks for resources in the given object and reload the ones /// that are missing or broken. @@ -204,7 +203,6 @@ static UnityEngine.Object Load(string path, Type type, bool builtin) return result; } - static bool SetAndLoadIfNull(System.Object container, FieldInfo info, string path, bool builtin) { @@ -307,7 +305,7 @@ public ReloadAttribute(string[] paths, Package package = Package.Root) /// The lookup method public ReloadAttribute(string path, Package package = Package.Root) : this(new[] { path }, package) - { } + {} /// /// Creates a new for an array using automatic path name @@ -318,7 +316,7 @@ public ReloadAttribute(string path, Package package = Package.Root) /// The array end index (exclusive) /// The lookup method public ReloadAttribute(string pathFormat, int rangeMin, int rangeMax, - Package package = Package.Root) + Package package = Package.Root) { #if UNITY_EDITOR this.package = package; @@ -338,5 +336,5 @@ public ReloadAttribute(string pathFormat, int rangeMin, int rangeMax, /// [AttributeUsage(AttributeTargets.Class)] public sealed class ReloadGroupAttribute : Attribute - { } + {} } diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs b/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs index 17d1db6de13..f78bccd2ebc 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/TextureCurve.cs @@ -58,7 +58,7 @@ public class TextureCurve : IDisposable /// Should the curve automatically loop in the given ? /// The boundaries of the curve. public TextureCurve(AnimationCurve baseCurve, float zeroValue, bool loop, in Vector2 bounds) - : this(baseCurve.keys, zeroValue, loop, bounds) { } + : this(baseCurve.keys, zeroValue, loop, bounds) {} /// /// Creates a new from an arbitrary number of keyframes. @@ -250,7 +250,7 @@ public class TextureCurveParameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. public TextureCurveParameter(TextureCurve value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} /// /// Release implementation. diff --git a/com.unity.render-pipelines.core/Runtime/Utilities/XRUtils.cs b/com.unity.render-pipelines.core/Runtime/Utilities/XRUtils.cs index f894b3b403f..8420422455d 100644 --- a/com.unity.render-pipelines.core/Runtime/Utilities/XRUtils.cs +++ b/com.unity.render-pipelines.core/Runtime/Utilities/XRUtils.cs @@ -18,6 +18,5 @@ public static class XRUtils UnityEngine.RectInt normalizedCamViewport = new UnityEngine.RectInt(0, 0, camera.pixelWidth, camera.pixelHeight); cmd.DrawOcclusionMesh(normalizedCamViewport); } - } } diff --git a/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs b/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs index 8d6c6283802..c653f90b576 100644 --- a/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs +++ b/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs @@ -197,6 +197,7 @@ void OnDrawGizmos() colliders.Clear(); } + #endif } } diff --git a/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs b/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs index 683b01e921a..3546971477e 100644 --- a/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs +++ b/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs @@ -97,7 +97,7 @@ protected virtual void OnEnable() foreach (var parameter in parameters) { - if(parameter != null) + if (parameter != null) parameter.OnEnable(); else Debug.LogWarning("Volume Component " + GetType().Name + " contains a null parameter; please make sure all parameters are initialized to a default value. Until this is fixed the null parameters will not be considered by the system."); @@ -118,6 +118,7 @@ protected virtual void OnDisable() parameter.OnDisable(); } } + /// /// Interpolates a with this component by an interpolation /// factor and puts the result back into the given . @@ -192,7 +193,7 @@ void SetAllOverridesTo(IEnumerable enumerable, bool state) // This method won't be called a lot but this is sub-optimal, fix me var innerParams = (ReadOnlyCollection) t.GetProperty("parameters", BindingFlags.NonPublic | BindingFlags.Instance) - .GetValue(prop, null); + .GetValue(prop, null); if (innerParams != null) SetAllOverridesTo(innerParams, state); @@ -231,7 +232,7 @@ public void Release() { for (int i = 0; i < parameters.Count; i++) { - if(parameters[i] != null) + if (parameters[i] != null) parameters[i].Release(); } } diff --git a/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs b/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs index cec5e48e5a8..c1852ce553e 100644 --- a/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs +++ b/com.unity.render-pipelines.core/Runtime/Volume/VolumeManager.cs @@ -227,7 +227,7 @@ void ReplaceData(VolumeStack stack, List components) for (int i = 0; i < count; i++) { - if(target.parameters[i] != null) + if (target.parameters[i] != null) { target.parameters[i].overrideState = false; target.parameters[i].SetValue(component.parameters[i]); diff --git a/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs b/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs index 074e00306ee..15f7ec5f63a 100644 --- a/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs +++ b/com.unity.render-pipelines.core/Runtime/Volume/VolumeParameter.cs @@ -126,13 +126,13 @@ public virtual void Release() {} /// This sample code shows how to make a custom parameter holding a float: /// /// using UnityEngine.Rendering; - /// + /// /// [Serializable] /// public sealed class MyFloatParameter : VolumeParameter<float> /// { /// public MyFloatParameter(float value, bool overrideState = false) /// : base(value, overrideState) { } - /// + /// /// public sealed override void Interp(float from, float to, float t) /// { /// m_Value = from + (to - from) * t; @@ -449,7 +449,7 @@ public MinIntParameter(int value, int min, bool overrideState = false) } /// - /// A that holds a non-interpolating int value that + /// A that holds a non-interpolating int value that /// clamped to a minimum value. /// /// @@ -537,7 +537,7 @@ public MaxIntParameter(int value, int max, bool overrideState = false) } /// - /// A that holds a non-interpolating int value that + /// A that holds a non-interpolating int value that /// clamped to a maximum value. /// /// @@ -632,7 +632,7 @@ public ClampedIntParameter(int value, int min, int max, bool overrideState = fal } /// - /// A that holds a non-interpolating int value + /// A that holds a non-interpolating int value /// clamped between a minimum and a maximum value. /// /// @@ -1285,7 +1285,7 @@ public class Vector2Parameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. public Vector2Parameter(Vector2 value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} /// /// Interpolates between two Vector2 values. @@ -1329,7 +1329,7 @@ public class Vector3Parameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. public Vector3Parameter(Vector3 value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} /// /// Interpolates between two Vector3 values. @@ -1374,7 +1374,7 @@ public class Vector4Parameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. public Vector4Parameter(Vector4 value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} /// /// Interpolates between two Vector4 values. diff --git a/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs b/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs index 4e97e2f1f92..371f95b078f 100644 --- a/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs +++ b/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs @@ -284,7 +284,6 @@ public bool TryGetAllSubclassOf(Type type, List result) return count != result.Count; } - /// /// A custom hashing function that Unity uses to compare the state of parameters. /// diff --git a/com.unity.render-pipelines.core/ShaderLibrary/API/GLCore.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/API/GLCore.hlsl index 45de79471dd..b48a9f93ea5 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/API/GLCore.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/API/GLCore.hlsl @@ -149,4 +149,3 @@ #define GATHER_TEXTURECUBE(textureName, samplerName, coord3) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_TEXTURECUBE) #define GATHER_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_TEXTURECUBE_ARRAY) #endif - diff --git a/com.unity.render-pipelines.core/ShaderLibrary/API/GLES3.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/API/GLES3.hlsl index 401ba9ee37f..32820c2ee5d 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/API/GLES3.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/API/GLES3.hlsl @@ -166,4 +166,3 @@ #define GATHER_BLUE_TEXTURE2D(textureName, samplerName, coord2) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_BLUE_TEXTURE2D) #define GATHER_ALPHA_TEXTURE2D(textureName, samplerName, coord2) ERROR_ON_UNSUPPORTED_FUNCTION(GATHER_ALPHA_TEXTURE2D) #endif - diff --git a/com.unity.render-pipelines.core/ShaderLibrary/AreaLighting.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/AreaLighting.hlsl index 8b7032786ba..368095cdaa1 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/AreaLighting.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/AreaLighting.hlsl @@ -373,41 +373,41 @@ real LTCEvaluate(real3 P1, real3 P2, real3 B, real3x3 invM) if (!(P1.z <= 0.0 && P2.z <= 0.0)) { real width = ComputeLineWidthFactor(invM, B); - + if (P1.z > P2.z) { // Convention: 'P2' is above 'P1', with the tangent pointing upwards. Swap(P1, P2); } - + // Recompute the length and the tangent in the new coordinate system. real len = length(P2 - P1); real3 T = normalize(P2 - P1); - + // Clip the part of the light below the horizon. if (P1.z <= 0.0) { // P = P1 + t * T; P.z == 0. real t = -P1.z / T.z; P1 = real3(P1.xy + t * T.xy, 0.0); - + // Set the length of the visible part of the light. len -= t; } - + // Compute the normal direction to the line, s.t. it is the shortest vector // between the shaded point and the line, pointing away from the shaded point. // Can be interpreted as a point on the line, since the shaded point is at the origin. real proj = dot(P1, T); real3 P0 = P1 - proj * T; - + // Compute the parameterization: distances from 'P1' and 'P2' to 'P0'. real l1 = proj; real l2 = l1 + len; - + // Integrate the clamped cosine over the line segment. real irradiance = LineIrradiance(l1, l2, P0, T); - + // Guard against numerical precision issues. result = max(INV_PI * width * irradiance, 0.0); } diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl index 75516014b10..8c295a4d491 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl @@ -547,7 +547,7 @@ real3 NeutralCurve(real3 x, real a, real b, real c, real d, real e, real f) return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f; } -#define TONEMAPPING_CLAMP_MAX 435.18712 //(-b + sqrt(b * b - 4 * a * (HALF_MAX - d * f))) / (2 * a * whiteScale) +#define TONEMAPPING_CLAMP_MAX 435.18712 //(-b + sqrt(b * b - 4 * a * (HALF_MAX - d * f))) / (2 * a * whiteScale) //Extremely high values cause NaN output when using fp16, we clamp to avoid the performace hit of switching to fp32 //The overflow happens in (x * (a * x + b) + d * f) of the NeutralCurve, highest value that avoids fp16 precision errors is ~571.56873 //Since whiteScale is constant (~1.31338) max input is ~435.18712 @@ -564,7 +564,7 @@ real3 NeutralTonemap(real3 x) const real whiteLevel = 5.3; const real whiteClip = 1.0; -#if defined(SHADER_API_MOBILE) +#if defined(SHADER_API_MOBILE) x = min(x, TONEMAPPING_CLAMP_MAX); #endif diff --git a/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl index 02cf0a902ce..cb7e9064bce 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl @@ -301,9 +301,9 @@ real ComputeWrappedPowerDiffuseLighting(real NdotL, real w, real p) // Ref: The Technical Art of Uncharted 4 - Brinck and Maximov 2016 real ComputeMicroShadowing(real AO, real NdotL, real opacity) { - real aperture = 2.0 * AO * AO; - real microshadow = saturate(NdotL + aperture - 1.0); - return lerp(1.0, microshadow, opacity); + real aperture = 2.0 * AO * AO; + real microshadow = saturate(NdotL + aperture - 1.0); + return lerp(1.0, microshadow, opacity); } real3 ComputeShadowColor(real shadow, real3 shadowTint, real penumbraFlag) @@ -437,7 +437,7 @@ real3x3 GetOrthoBasisViewNormal(real3 V, real3 N, real unclampedNdotV, bool test if (testSingularity && (abs(1.0 - unclampedNdotV) <= FLT_EPS)) { // In this case N == V, and azimuth orientation around N shouldn't matter for the caller, - // we can use any quaternion-based method, like Frisvad or Reynold's (Pixar): + // we can use any quaternion-based method, like Frisvad or Reynold's (Pixar): orthoBasisViewNormal = GetLocalFrame(N); } else diff --git a/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl index 86e0eaa8015..9307f64d2c9 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl @@ -58,9 +58,9 @@ real PerceptualSmoothnessToPerceptualRoughness(real perceptualSmoothness) // but chopping the far tails of GGX and keeping 94% of the mass yields a distribution with a defined variance where // we can then relate the roughness of GGX to a variance (see Ray Tracing Gems p153 - the reference is wrong though, // the Conty paper doesn't mention this at all, but it can be found in stats using quantiles): -// +// // roughnessGGX^2 = variance / 2 -// +// // From the two previous, if we want roughly comparable variances of slopes between a Beckmann and a GGX NDF, we can // equate the variances and get a conversion of their roughnesses: // diff --git a/com.unity.render-pipelines.core/ShaderLibrary/DummyShaderLibrary.cs b/com.unity.render-pipelines.core/ShaderLibrary/DummyShaderLibrary.cs index e11a749ab5c..ee0a9ce23f8 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/DummyShaderLibrary.cs +++ b/com.unity.render-pipelines.core/ShaderLibrary/DummyShaderLibrary.cs @@ -1,5 +1,4 @@ // This file is only to force Unity to load the ShaderLibrary's hlsl files in visual studio project via asmdef file, so they can be browse. class DummyShaderLibrary { - } diff --git a/com.unity.render-pipelines.core/ShaderLibrary/GeometricTools.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/GeometricTools.hlsl index a84aeda1098..c873955a6cf 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/GeometricTools.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/GeometricTools.hlsl @@ -138,15 +138,15 @@ bool IntersectRayPlane(float3 rayOrigin, float3 rayDirection, float3 planePositi bool res = false; t = -1.0; - float denom = dot(planeNormal, rayDirection); + float denom = dot(planeNormal, rayDirection); if (abs(denom) > 1e-5) - { + { float3 d = planePosition - rayOrigin; t = dot(d, planeNormal) / denom; res = (t >= 0); } - return res; + return res; } // Can support cones with an elliptic base: pre-scale 'coneAxisX' and 'coneAxisY' by (h/r_x) and (h/r_y). diff --git a/com.unity.render-pipelines.core/ShaderLibrary/GraniteShaderLibBase.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/GraniteShaderLibBase.hlsl index c8646ad823a..bae79ffe18f 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/GraniteShaderLibBase.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/GraniteShaderLibBase.hlsl @@ -68,174 +68,174 @@ // Temp workaround for some platforms's lack of unorm. #ifdef GRA_NO_UNORM - #define GRA_UNORM -#else - #define GRA_UNORM unorm + #define GRA_UNORM +#else + #define GRA_UNORM unorm #endif #ifndef GRA_TEXTURE_ARRAY_SUPPORT - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) || (GRA_GLSL_330 == 1) - #define GRA_TEXTURE_ARRAY_SUPPORT 1 - #else - #define GRA_TEXTURE_ARRAY_SUPPORT 0 - #endif + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) || (GRA_GLSL_330 == 1) + #define GRA_TEXTURE_ARRAY_SUPPORT 1 + #else + #define GRA_TEXTURE_ARRAY_SUPPORT 0 + #endif #endif #define GRA_HLSL_FAMILY ((GRA_HLSL_3 == 1) || (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1)) #define GRA_GLSL_FAMILY ((GRA_GLSL_120 == 1) || (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1)) #if GRA_HLSL_FAMILY - #define gra_Float2 float2 - #define gra_Float3 float3 - #define gra_Float4 float4 - #define gra_Int3 int3 - #define gra_Float4x4 float4x4 - #define gra_Unroll [unroll] - #define gra_Branch [branch] + #define gra_Float2 float2 + #define gra_Float3 float3 + #define gra_Float4 float4 + #define gra_Int3 int3 + #define gra_Float4x4 float4x4 + #define gra_Unroll [unroll] + #define gra_Branch [branch] #elif GRA_GLSL_FAMILY - #if (GRA_VERTEX_SHADER == 0) && (GRA_PIXEL_SHADER ==0) - #error GLSL requires knowledge of the shader stage! Neither GRA_VERTEX_SHADER or GRA_PIXEL_SHADER are defined! - #else - #define gra_Float2 vec2 - #define gra_Float3 vec3 - #define gra_Float4 vec4 - #define gra_Int3 ivec3 - #define gra_Float4x4 mat4 - #define gra_Unroll - #define gra_Branch - #if (GRA_VERTEX_SHADER == 1) - #define ddx - #define ddy - #elif (GRA_PIXEL_SHADER == 1) - #define ddx dFdx - #define ddy dFdy - #endif - #define frac fract - #define lerp mix - /** This is not correct (http://stackoverflow.com/questions/7610631/glsl-mod-vs-hlsl-fmod) but it is for our case */ - #define fmod mod - #endif + #if (GRA_VERTEX_SHADER == 0) && (GRA_PIXEL_SHADER ==0) + #error GLSL requires knowledge of the shader stage! Neither GRA_VERTEX_SHADER or GRA_PIXEL_SHADER are defined! + #else + #define gra_Float2 vec2 + #define gra_Float3 vec3 + #define gra_Float4 vec4 + #define gra_Int3 ivec3 + #define gra_Float4x4 mat4 + #define gra_Unroll + #define gra_Branch + #if (GRA_VERTEX_SHADER == 1) + #define ddx + #define ddy + #elif (GRA_PIXEL_SHADER == 1) + #define ddx dFdx + #define ddy dFdy + #endif + #define frac fract + #define lerp mix + /** This is not correct (http://stackoverflow.com/questions/7610631/glsl-mod-vs-hlsl-fmod) but it is for our case */ + #define fmod mod + #endif #else - #error unknown shader architecture + #error unknown shader architecture #endif #if (GRA_DISABLE_TEX_LOAD!=1) - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) || (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) - #define GRA_LOAD_INSTR 1 - #else - #define GRA_LOAD_INSTR 0 - #endif + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) || (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) + #define GRA_LOAD_INSTR 1 + #else + #define GRA_LOAD_INSTR 0 + #endif #else - #define GRA_LOAD_INSTR 0 + #define GRA_LOAD_INSTR 0 #endif /** - a cross API texture handle + a cross API texture handle */ #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - struct GraniteTranslationTexture - { - SamplerState Sampler; - Texture2D Texture; - }; - struct GraniteCacheTexture - { - SamplerState Sampler; - - #if GRA_TEXTURE_ARRAY_SUPPORT - Texture2DArray TextureArray; - #else - Texture2D Texture; - #endif - }; + struct GraniteTranslationTexture + { + SamplerState Sampler; + Texture2D Texture; + }; + struct GraniteCacheTexture + { + SamplerState Sampler; + + #if GRA_TEXTURE_ARRAY_SUPPORT + Texture2DArray TextureArray; + #else + Texture2D Texture; + #endif + }; #elif (GRA_HLSL_3 == 1) || (GRA_GLSL_120 == 1) || (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) - #define GraniteTranslationTexture sampler2D - - #if GRA_TEXTURE_ARRAY_SUPPORT - #define GraniteCacheTexture sampler2DArray - #else - #define GraniteCacheTexture sampler2D - #endif - + #define GraniteTranslationTexture sampler2D + + #if GRA_TEXTURE_ARRAY_SUPPORT + #define GraniteCacheTexture sampler2DArray + #else + #define GraniteCacheTexture sampler2D + #endif + #else - #error unknow shader archtecture + #error unknow shader archtecture #endif /** - Struct defining the constant buffer for each streaming texture. - Use IStreamingTexture::GetConstantBuffer to fill this struct. + Struct defining the constant buffer for each streaming texture. + Use IStreamingTexture::GetConstantBuffer to fill this struct. */ struct GraniteStreamingTextureConstantBuffer { - #define _grStreamingTextureCBSize 2 - gra_Float4 data[_grStreamingTextureCBSize]; + #define _grStreamingTextureCBSize 2 + gra_Float4 data[_grStreamingTextureCBSize]; }; /** - Struct defining the constant buffer for each cube streaming texture. - Use multiple calls to IStreamingTexture::GetConstantBuffer this struct (one call for each face). - */ + Struct defining the constant buffer for each cube streaming texture. + Use multiple calls to IStreamingTexture::GetConstantBuffer this struct (one call for each face). + */ struct GraniteStreamingTextureCubeConstantBuffer { - #define _grStreamingTextureCubeCBSize 6 - GraniteStreamingTextureConstantBuffer data[_grStreamingTextureCubeCBSize]; + #define _grStreamingTextureCubeCBSize 6 + GraniteStreamingTextureConstantBuffer data[_grStreamingTextureCubeCBSize]; }; /** - Struct defining the constant buffer for each tileset. - Use ITileSet::GetConstantBuffer to fill this struct. + Struct defining the constant buffer for each tileset. + Use ITileSet::GetConstantBuffer to fill this struct. */ struct GraniteTilesetConstantBuffer { - #define _grTilesetCBSize 2 - gra_Float4x4 data[_grTilesetCBSize]; + #define _grTilesetCBSize 2 + gra_Float4x4 data[_grTilesetCBSize]; }; /** - Utility struct used by the shaderlib to wrap up all required constant buffers needed to perform a VT lookup/sample. - */ + Utility struct used by the shaderlib to wrap up all required constant buffers needed to perform a VT lookup/sample. + */ struct GraniteConstantBuffers { - GraniteTilesetConstantBuffer tilesetBuffer; - GraniteStreamingTextureConstantBuffer streamingTextureBuffer; + GraniteTilesetConstantBuffer tilesetBuffer; + GraniteStreamingTextureConstantBuffer streamingTextureBuffer; }; /** - Utility struct used by the shaderlib to wrap up all required constant buffers needed to perform a Cube VT lookup/sample. - */ + Utility struct used by the shaderlib to wrap up all required constant buffers needed to perform a Cube VT lookup/sample. + */ struct GraniteCubeConstantBuffers { - GraniteTilesetConstantBuffer tilesetBuffer; - GraniteStreamingTextureCubeConstantBuffer streamingTextureCubeBuffer; + GraniteTilesetConstantBuffer tilesetBuffer; + GraniteStreamingTextureCubeConstantBuffer streamingTextureCubeBuffer; }; /** - The Granite lookup data for the different sampling functions. + The Granite lookup data for the different sampling functions. */ // Granite lookup data for automatic mip level selecting sampling struct GraniteLookupData { - gra_Float4 translationTableData; - gra_Float2 textureCoordinates; - gra_Float2 dX; - gra_Float2 dY; + gra_Float4 translationTableData; + gra_Float2 textureCoordinates; + gra_Float2 dX; + gra_Float2 dY; }; // Granite lookup data for explicit level-of-detail sampling struct GraniteLODLookupData { - gra_Float4 translationTableData; - gra_Float2 textureCoordinates; - float cacheLevel; + gra_Float4 translationTableData; + gra_Float2 textureCoordinates; + float cacheLevel; }; //@IGNORE_END // public interface /* - END OF PUBLIC INTERFACE - Everything below this point should be treated as private to GraniteShaderLib.h + END OF PUBLIC INTERFACE + Everything below this point should be treated as private to GraniteShaderLib.h */ //@INSERT_DEFINES @@ -258,135 +258,135 @@ struct GraniteLODLookupData #if GRA_ROW_MAJOR == 1 - #define gra_TranslationTableBias gra_TilesetBufferInternal[0][0] - #define gra_MaxAnisotropyLog2 gra_TilesetBufferInternal[1][0] - #define gra_CalcMiplevelDeltaScale gra_Float2(gra_TilesetBufferInternal[2][0], gra_TilesetBufferInternal[3][0]) - #define gra_CalcMiplevelDeltaScaleX gra_TilesetBufferInternal[2][0] - #define gra_CalcMiplevelDeltaScaleY gra_TilesetBufferInternal[3][0] - #define gra_LodBiasPow2 gra_TilesetBufferInternal[0][1] - #define gra_TrilinearOffset gra_TilesetBufferInternal[0][2] - #define gra_TileContentInTiles gra_Float2(gra_TilesetBufferInternal[0][2], gra_TilesetBufferInternal[1][2]) - #define gra_Level0NumTilesX gra_TilesetBufferInternal[0][3] - #define gra_NumTilesYScale gra_TilesetBufferInternal[1][3] - #define gra_TextureMagic gra_TilesetBufferInternal[2][3] - #define gra_TextureId gra_TilesetBufferInternal[3][3] - - #define gra_RcpCacheInTiles(l) gra_Float2(gra_TilesetCacheBuffer[0][l], gra_TilesetCacheBuffer[1][l]) - #define gra_BorderPixelsRcpCache(l) gra_Float2(gra_TilesetCacheBuffer[2][l], gra_TilesetCacheBuffer[3][l]) + #define gra_TranslationTableBias gra_TilesetBufferInternal[0][0] + #define gra_MaxAnisotropyLog2 gra_TilesetBufferInternal[1][0] + #define gra_CalcMiplevelDeltaScale gra_Float2(gra_TilesetBufferInternal[2][0], gra_TilesetBufferInternal[3][0]) + #define gra_CalcMiplevelDeltaScaleX gra_TilesetBufferInternal[2][0] + #define gra_CalcMiplevelDeltaScaleY gra_TilesetBufferInternal[3][0] + #define gra_LodBiasPow2 gra_TilesetBufferInternal[0][1] + #define gra_TrilinearOffset gra_TilesetBufferInternal[0][2] + #define gra_TileContentInTiles gra_Float2(gra_TilesetBufferInternal[0][2], gra_TilesetBufferInternal[1][2]) + #define gra_Level0NumTilesX gra_TilesetBufferInternal[0][3] + #define gra_NumTilesYScale gra_TilesetBufferInternal[1][3] + #define gra_TextureMagic gra_TilesetBufferInternal[2][3] + #define gra_TextureId gra_TilesetBufferInternal[3][3] + + #define gra_RcpCacheInTiles(l) gra_Float2(gra_TilesetCacheBuffer[0][l], gra_TilesetCacheBuffer[1][l]) + #define gra_BorderPixelsRcpCache(l) gra_Float2(gra_TilesetCacheBuffer[2][l], gra_TilesetCacheBuffer[3][l]) #else - #define gra_TranslationTableBias gra_TilesetBufferInternal[0][0] - #define gra_MaxAnisotropyLog2 gra_TilesetBufferInternal[0][1] - #define gra_CalcMiplevelDeltaScale gra_Float2(gra_TilesetBufferInternal[0][2], gra_TilesetBufferInternal[0][3]) - #define gra_CalcMiplevelDeltaScaleX gra_TilesetBufferInternal[0][2] - #define gra_CalcMiplevelDeltaScaleY gra_TilesetBufferInternal[0][3] - #define gra_LodBiasPow2 gra_TilesetBufferInternal[1][0] - #define gra_TrilinearOffset gra_TilesetBufferInternal[2][0] - #define gra_TileContentInTiles gra_Float2(gra_TilesetBufferInternal[2][0], gra_TilesetBufferInternal[2][1]) - #define gra_Level0NumTilesX gra_TilesetBufferInternal[3][0] - #define gra_NumTilesYScale gra_TilesetBufferInternal[3][1] - #define gra_TextureMagic gra_TilesetBufferInternal[3][2] - #define gra_TextureId gra_TilesetBufferInternal[3][3] + #define gra_TranslationTableBias gra_TilesetBufferInternal[0][0] + #define gra_MaxAnisotropyLog2 gra_TilesetBufferInternal[0][1] + #define gra_CalcMiplevelDeltaScale gra_Float2(gra_TilesetBufferInternal[0][2], gra_TilesetBufferInternal[0][3]) + #define gra_CalcMiplevelDeltaScaleX gra_TilesetBufferInternal[0][2] + #define gra_CalcMiplevelDeltaScaleY gra_TilesetBufferInternal[0][3] + #define gra_LodBiasPow2 gra_TilesetBufferInternal[1][0] + #define gra_TrilinearOffset gra_TilesetBufferInternal[2][0] + #define gra_TileContentInTiles gra_Float2(gra_TilesetBufferInternal[2][0], gra_TilesetBufferInternal[2][1]) + #define gra_Level0NumTilesX gra_TilesetBufferInternal[3][0] + #define gra_NumTilesYScale gra_TilesetBufferInternal[3][1] + #define gra_TextureMagic gra_TilesetBufferInternal[3][2] + #define gra_TextureId gra_TilesetBufferInternal[3][3] - #define gra_RcpCacheInTiles(l) gra_Float2(gra_TilesetCacheBuffer[l][0], gra_TilesetCacheBuffer[l][1]) - #define gra_BorderPixelsRcpCache(l) gra_Float2(gra_TilesetCacheBuffer[l][2], gra_TilesetCacheBuffer[l][3]) + #define gra_RcpCacheInTiles(l) gra_Float2(gra_TilesetCacheBuffer[l][0], gra_TilesetCacheBuffer[l][1]) + #define gra_BorderPixelsRcpCache(l) gra_Float2(gra_TilesetCacheBuffer[l][2], gra_TilesetCacheBuffer[l][3]) #endif #if (GRA_GLSL_120==1) - // Extension needed for texture2DLod - //extension GL_ARB_shader_texture_lod : enable - // Extensions needed fot texture2DGrad - //extension GL_EXT_gpu_shader4 : enable - // Extensions needed for bit manipulation - //extension GL_ARB_shader_bit_encoding : enable + // Extension needed for texture2DLod + //extension GL_ARB_shader_texture_lod : enable + // Extensions needed fot texture2DGrad + //extension GL_EXT_gpu_shader4 : enable + // Extensions needed for bit manipulation + //extension GL_ARB_shader_bit_encoding : enable #endif #if (GRA_TEXTURE_ARRAY_SUPPORT==1) - gra_Float4 GranitePrivate_SampleArray(in GraniteCacheTexture tex, in gra_Float3 texCoord) - { - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.TextureArray.Sample(tex.Sampler, texCoord); - #elif (GRA_GLSL_330 == 1) - return texture(tex, texCoord); - #else - #error using unsupported function - #endif - } - - gra_Float4 GranitePrivate_SampleGradArray(in GraniteCacheTexture tex, in gra_Float3 texCoord, in gra_Float2 dX, in gra_Float2 dY) - { - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.TextureArray.SampleGrad(tex.Sampler,texCoord,dX,dY); - #elif (GRA_GLSL_330 == 1) - return textureGrad(tex, texCoord, dX, dY); - #else - #error using unsupported function - #endif - } - - gra_Float4 GranitePrivate_SampleLevelArray(in GraniteCacheTexture tex, in gra_Float3 texCoord, in float level) - { - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.TextureArray.SampleLevel(tex.Sampler, texCoord, level); - #elif (GRA_GLSL_330 == 1) - return textureLod(tex, texCoord, level); - #else - #error using unsupported function - #endif - } + gra_Float4 GranitePrivate_SampleArray(in GraniteCacheTexture tex, in gra_Float3 texCoord) + { + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) + return tex.TextureArray.Sample(tex.Sampler, texCoord); + #elif (GRA_GLSL_330 == 1) + return texture(tex, texCoord); + #else + #error using unsupported function + #endif + } + + gra_Float4 GranitePrivate_SampleGradArray(in GraniteCacheTexture tex, in gra_Float3 texCoord, in gra_Float2 dX, in gra_Float2 dY) + { + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) + return tex.TextureArray.SampleGrad(tex.Sampler,texCoord,dX,dY); + #elif (GRA_GLSL_330 == 1) + return textureGrad(tex, texCoord, dX, dY); + #else + #error using unsupported function + #endif + } + + gra_Float4 GranitePrivate_SampleLevelArray(in GraniteCacheTexture tex, in gra_Float3 texCoord, in float level) + { + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) + return tex.TextureArray.SampleLevel(tex.Sampler, texCoord, level); + #elif (GRA_GLSL_330 == 1) + return textureLod(tex, texCoord, level); + #else + #error using unsupported function + #endif + } #else - gra_Float4 GranitePrivate_Sample(in GraniteCacheTexture tex, in gra_Float2 texCoord) - { - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.Texture.Sample(tex.Sampler,texCoord); - #elif (GRA_HLSL_3 == 1) - return tex2D(tex,texCoord); - #elif (GRA_GLSL_120 == 1) || (GRA_GLSL_130 == 1) - return texture2D(tex, texCoord); - #elif (GRA_GLSL_330 == 1) - return texture(tex, texCoord); - #endif - } - - gra_Float4 GranitePrivate_SampleLevel(in GraniteCacheTexture tex, in gra_Float2 texCoord, in float level) - { - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.Texture.SampleLevel(tex.Sampler, texCoord, level); - #elif (GRA_HLSL_3 == 1) - return tex2Dlod(tex,gra_Float4(texCoord,0.0,level)); - #elif (GRA_GLSL_120 == 1) - return texture2DLod(tex, texCoord, level); - #elif (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) - return textureLod(tex, texCoord, level); - #endif - } - - gra_Float4 GranitePrivate_SampleGrad(in GraniteCacheTexture tex, in gra_Float2 texCoord, in gra_Float2 dX, in gra_Float2 dY) - { - #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.Texture.SampleGrad(tex.Sampler,texCoord,dX,dY); - #elif (GRA_HLSL_3 == 1) - return tex2D(tex,texCoord,dX,dY); - #elif (GRA_GLSL_120 == 1) - return texture2DGrad(tex, texCoord, dX, dY); - #elif (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) - return textureGrad(tex, texCoord, dX, dY); - #endif - } + gra_Float4 GranitePrivate_Sample(in GraniteCacheTexture tex, in gra_Float2 texCoord) + { + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) + return tex.Texture.Sample(tex.Sampler,texCoord); + #elif (GRA_HLSL_3 == 1) + return tex2D(tex,texCoord); + #elif (GRA_GLSL_120 == 1) || (GRA_GLSL_130 == 1) + return texture2D(tex, texCoord); + #elif (GRA_GLSL_330 == 1) + return texture(tex, texCoord); + #endif + } + + gra_Float4 GranitePrivate_SampleLevel(in GraniteCacheTexture tex, in gra_Float2 texCoord, in float level) + { + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) + return tex.Texture.SampleLevel(tex.Sampler, texCoord, level); + #elif (GRA_HLSL_3 == 1) + return tex2Dlod(tex,gra_Float4(texCoord,0.0,level)); + #elif (GRA_GLSL_120 == 1) + return texture2DLod(tex, texCoord, level); + #elif (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) + return textureLod(tex, texCoord, level); + #endif + } + + gra_Float4 GranitePrivate_SampleGrad(in GraniteCacheTexture tex, in gra_Float2 texCoord, in gra_Float2 dX, in gra_Float2 dY) + { + #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) + return tex.Texture.SampleGrad(tex.Sampler,texCoord,dX,dY); + #elif (GRA_HLSL_3 == 1) + return tex2D(tex,texCoord,dX,dY); + #elif (GRA_GLSL_120 == 1) + return texture2DGrad(tex, texCoord, dX, dY); + #elif (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) + return textureGrad(tex, texCoord, dX, dY); + #endif + } #endif //#if (GRA_TEXTURE_ARRAY_SUPPORT==1) #if (GRA_LOAD_INSTR==1) gra_Float4 GranitePrivate_Load(in GraniteTranslationTexture tex, in gra_Int3 location) { #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.Texture.Load(location); + return tex.Texture.Load(location); #elif (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) - return texelFetch(tex, location.xy, location.z); + return texelFetch(tex, location.xy, location.z); #elif (GRA_HLSL_3 == 1) || (GRA_GLSL_120 == 1) - #error using unsupported function + #error using unsupported function #endif } #endif @@ -398,22 +398,22 @@ gra_Float4 GranitePrivate_Load(in GraniteTranslationTexture tex, in gra_Int3 loc gra_Float4 GranitePrivate_SampleLevel_Translation(in GraniteTranslationTexture tex, in gra_Float2 texCoord, in float level) { #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return tex.Texture.SampleLevel(tex.Sampler, texCoord, level); + return tex.Texture.SampleLevel(tex.Sampler, texCoord, level); #elif (GRA_HLSL_3 == 1) - return tex2Dlod(tex,gra_Float4(texCoord,0.0,level)); + return tex2Dlod(tex,gra_Float4(texCoord,0.0,level)); #elif (GRA_GLSL_120 == 1) - return texture2DLod(tex, texCoord, level); + return texture2DLod(tex, texCoord, level); #elif (GRA_GLSL_130 == 1) || (GRA_GLSL_330 == 1) - return textureLod(tex, texCoord, level); + return textureLod(tex, texCoord, level); #endif } float GranitePrivate_Saturate(in float value) { #if GRA_HLSL_FAMILY - return saturate(value); + return saturate(value); #elif GRA_GLSL_FAMILY - return clamp(value, 0.0f, 1.0f); + return clamp(value, 0.0f, 1.0f); #endif } @@ -421,9 +421,9 @@ float GranitePrivate_Saturate(in float value) uint GranitePrivate_FloatAsUint(float value) { #if (GRA_HLSL_5 == 1) || (GRA_HLSL_4 == 1) - return asuint(value); + return asuint(value); #elif (GRA_GLSL_330 == 1) - return floatBitsToUint(value); + return floatBitsToUint(value); #endif } #endif @@ -431,9 +431,9 @@ uint GranitePrivate_FloatAsUint(float value) float GranitePrivate_Pow2(uint exponent) { #if GRA_HLSL_FAMILY - return pow(2.0, exponent); + return pow(2.0, exponent); #else - return pow(2.0, float(exponent)); + return pow(2.0, float(exponent)); #endif } @@ -466,399 +466,399 @@ gra_Float4 GranitePrivate_PackTileId(in gra_Float2 tileXY, in float level, in fl gra_Float4 Granite_DebugPackedTileId64(in gra_Float4 PackedTile) { #if GRA_64BIT_RESOLVER - gra_Float4 output; - - const float scale = 1.0f / 65535.0f; - gra_Float4 temp = PackedTile / scale; - - output.x = fmod(temp.x, 256.0f); - output.y = floor(temp.x / 256.0f) + fmod(temp.y, 16.0f) * 16.0f; - output.z = floor(temp.y / 16.0f); - output.w = temp.z + temp.a * 16.0f; - - return gra_Float4 - ( - (float)output.x / 255.0f, - (float)output.y / 255.0f, - (float)output.z / 255.0f, - (float)output.w / 255.0f + gra_Float4 output; + + const float scale = 1.0f / 65535.0f; + gra_Float4 temp = PackedTile / scale; + + output.x = fmod(temp.x, 256.0f); + output.y = floor(temp.x / 256.0f) + fmod(temp.y, 16.0f) * 16.0f; + output.z = floor(temp.y / 16.0f); + output.w = temp.z + temp.a * 16.0f; + + return gra_Float4 + ( + (float)output.x / 255.0f, + (float)output.y / 255.0f, + (float)output.z / 255.0f, + (float)output.w / 255.0f ); #else - return PackedTile; + return PackedTile; #endif } gra_Float3 Granite_UnpackNormal(in gra_Float4 PackedNormal, float scale) { - gra_Float2 reconstructed = gra_Float2(PackedNormal.x * PackedNormal.a, PackedNormal.y) * 2.0f - 1.0f; - reconstructed *= scale; - float z = sqrt(1.0f - GranitePrivate_Saturate(dot(reconstructed, reconstructed))); - return gra_Float3(reconstructed, z); + gra_Float2 reconstructed = gra_Float2(PackedNormal.x * PackedNormal.a, PackedNormal.y) * 2.0f - 1.0f; + reconstructed *= scale; + float z = sqrt(1.0f - GranitePrivate_Saturate(dot(reconstructed, reconstructed))); + return gra_Float3(reconstructed, z); } gra_Float3 Granite_UnpackNormal(in gra_Float4 PackedNormal) { - return Granite_UnpackNormal(PackedNormal, 1.0); + return Granite_UnpackNormal(PackedNormal, 1.0); } #if GRA_HLSL_FAMILY GraniteTilesetConstantBuffer Granite_ApplyResolutionOffset(in GraniteTilesetConstantBuffer INtsCB, in float resolutionOffsetPow2) { - GraniteTilesetConstantBuffer tsCB = INtsCB; - gra_LodBiasPow2 *= resolutionOffsetPow2; - //resolutionOffsetPow2 *= resolutionOffsetPow2; //Square it before multiplying it in below - gra_CalcMiplevelDeltaScaleX *= resolutionOffsetPow2; - gra_CalcMiplevelDeltaScaleY *= resolutionOffsetPow2; - return tsCB; + GraniteTilesetConstantBuffer tsCB = INtsCB; + gra_LodBiasPow2 *= resolutionOffsetPow2; + //resolutionOffsetPow2 *= resolutionOffsetPow2; //Square it before multiplying it in below + gra_CalcMiplevelDeltaScaleX *= resolutionOffsetPow2; + gra_CalcMiplevelDeltaScaleY *= resolutionOffsetPow2; + return tsCB; } GraniteTilesetConstantBuffer Granite_SetMaxAnisotropy(in GraniteTilesetConstantBuffer INtsCB, in float maxAnisotropyLog2) { - GraniteTilesetConstantBuffer tsCB = INtsCB; - gra_MaxAnisotropyLog2 = min(gra_MaxAnisotropyLog2, maxAnisotropyLog2); - return tsCB; + GraniteTilesetConstantBuffer tsCB = INtsCB; + gra_MaxAnisotropyLog2 = min(gra_MaxAnisotropyLog2, maxAnisotropyLog2); + return tsCB; } #else void Granite_ApplyResolutionOffset(inout GraniteTilesetConstantBuffer tsCB, in float resolutionOffsetPow2) { - gra_LodBiasPow2 *= resolutionOffsetPow2; - //resolutionOffsetPow2 *= resolutionOffsetPow2; //Square it before multiplying it in below - gra_CalcMiplevelDeltaScaleX *= resolutionOffsetPow2; - gra_CalcMiplevelDeltaScaleY *= resolutionOffsetPow2; + gra_LodBiasPow2 *= resolutionOffsetPow2; + //resolutionOffsetPow2 *= resolutionOffsetPow2; //Square it before multiplying it in below + gra_CalcMiplevelDeltaScaleX *= resolutionOffsetPow2; + gra_CalcMiplevelDeltaScaleY *= resolutionOffsetPow2; } void Granite_SetMaxAnisotropy(inout GraniteTilesetConstantBuffer tsCB, in float maxAnisotropyLog2) { - gra_MaxAnisotropyLog2 = min(gra_MaxAnisotropyLog2, maxAnisotropyLog2); + gra_MaxAnisotropyLog2 = min(gra_MaxAnisotropyLog2, maxAnisotropyLog2); } #endif gra_Float2 Granite_Transform(in GraniteStreamingTextureConstantBuffer grSTCB, in gra_Float2 textureCoord) { - return textureCoord * gra_StreamingTextureTransform.zw + gra_StreamingTextureTransform.xy; + return textureCoord * gra_StreamingTextureTransform.zw + gra_StreamingTextureTransform.xy; } gra_Float4 Granite_MergeResolveOutputs(in gra_Float4 resolve0, in gra_Float4 resolve1, in gra_Float2 pixelLocation) { - gra_Float2 screenPos = frac(pixelLocation * 0.5f); - bool dither = (screenPos.x != screenPos.y); - return (dither) ? resolve0 : resolve1; + gra_Float2 screenPos = frac(pixelLocation * 0.5f); + bool dither = (screenPos.x != screenPos.y); + return (dither) ? resolve0 : resolve1; } gra_Float4 Granite_PackTileId(in gra_Float4 unpackedTileID) { - return GranitePrivate_PackTileId(unpackedTileID.xy, unpackedTileID.z, unpackedTileID.w); + return GranitePrivate_PackTileId(unpackedTileID.xy, unpackedTileID.z, unpackedTileID.w); } #if (GRA_HLSL_5 == 1) void Granite_DitherResolveOutput(in gra_Float4 resolve, in RWTexture2D resolveTexture, in gra_Float2 screenPos, in float alpha) { - const uint2 pixelPos = int2(screenPos); - const uint2 pixelLocation = pixelPos % GRA_RWTEXTURE2D_SCALE; - bool dither = (pixelLocation.x == 0) && (pixelLocation.y == 0); - uint2 writePos = pixelPos / GRA_RWTEXTURE2D_SCALE; - - if ( alpha == 0 ) - { - dither = false; - } - else if (alpha != 1.0) - { - // Do a 4x4 dither patern so alternating pixels resolve to the first or the second texture - gra_Float2 pixelLocationAlpha = frac(screenPos * 0.25f); // We don't scale after the frac so this will give coords 0, 0.25, 0.5, 0.75 - int pixelId = (int)(pixelLocationAlpha.y * 16 + pixelLocationAlpha.x * 4); //faster as a dot2 ? - - // Clamp - // This ensures that for example alpha=0.95 still resolves some tiles of the surfaces behind it - // and alpha=0.05 still resolves some tiles of this surface - alpha = min(max(alpha, 0.0625), 0.9375); - - // Modern hardware supports array indexing with per pixel varying indexes - // on old hardware this will be expanded to a conditional tree by the compiler - const float thresholdMaxtrix[16] = { 1.0f / 17.0f, 9.0f / 17.0f, 3.0f / 17.0f, 11.0f / 17.0f, - 13.0f / 17.0f, 5.0f / 17.0f, 15.0f / 17.0f, 7.0f / 17.0f, - 4.0f / 17.0f, 12.0f / 17.0f, 2.0f / 17.0f, 10.0f / 17.0f, - 16.0f / 17.0f, 8.0f / 17.0f, 14.0f / 17.0f, 6.0f / 17.0f}; - float threshold = thresholdMaxtrix[pixelId]; - - if (alpha < threshold) - { - dither = false; - } - } - - gra_Branch if (dither) - { + const uint2 pixelPos = int2(screenPos); + const uint2 pixelLocation = pixelPos % GRA_RWTEXTURE2D_SCALE; + bool dither = (pixelLocation.x == 0) && (pixelLocation.y == 0); + uint2 writePos = pixelPos / GRA_RWTEXTURE2D_SCALE; + + if ( alpha == 0 ) + { + dither = false; + } + else if (alpha != 1.0) + { + // Do a 4x4 dither patern so alternating pixels resolve to the first or the second texture + gra_Float2 pixelLocationAlpha = frac(screenPos * 0.25f); // We don't scale after the frac so this will give coords 0, 0.25, 0.5, 0.75 + int pixelId = (int)(pixelLocationAlpha.y * 16 + pixelLocationAlpha.x * 4); //faster as a dot2 ? + + // Clamp + // This ensures that for example alpha=0.95 still resolves some tiles of the surfaces behind it + // and alpha=0.05 still resolves some tiles of this surface + alpha = min(max(alpha, 0.0625), 0.9375); + + // Modern hardware supports array indexing with per pixel varying indexes + // on old hardware this will be expanded to a conditional tree by the compiler + const float thresholdMaxtrix[16] = { 1.0f / 17.0f, 9.0f / 17.0f, 3.0f / 17.0f, 11.0f / 17.0f, + 13.0f / 17.0f, 5.0f / 17.0f, 15.0f / 17.0f, 7.0f / 17.0f, + 4.0f / 17.0f, 12.0f / 17.0f, 2.0f / 17.0f, 10.0f / 17.0f, + 16.0f / 17.0f, 8.0f / 17.0f, 14.0f / 17.0f, 6.0f / 17.0f}; + float threshold = thresholdMaxtrix[pixelId]; + + if (alpha < threshold) + { + dither = false; + } + } + + gra_Branch if (dither) + { #if (GRA_PACK_RESOLVE_OUTPUT==0) - resolveTexture[writePos] = Granite_PackTileId(resolve); + resolveTexture[writePos] = Granite_PackTileId(resolve); #else - resolveTexture[writePos] = resolve; + resolveTexture[writePos] = resolve; #endif - } + } } #endif float GranitePrivate_CalcMiplevelAnisotropic(in GraniteTilesetConstantBuffer tsCB, in GraniteStreamingTextureConstantBuffer grSTCB, in gra_Float2 ddxTc, in gra_Float2 ddyTc) { - // Calculate the required mipmap level, this uses a similar - // formula as the GL spec. - // To reduce sqrt's and log2's we do some stuff in squared space here and further below in log space - // i.e. we wait with the sqrt untill we can do it for 'free' later during the log2 + // Calculate the required mipmap level, this uses a similar + // formula as the GL spec. + // To reduce sqrt's and log2's we do some stuff in squared space here and further below in log space + // i.e. we wait with the sqrt untill we can do it for 'free' later during the log2 ddxTc *= gra_CalcMiplevelDeltaScale; ddyTc *= gra_CalcMiplevelDeltaScale; float lenDxSqr = dot(ddxTc, ddxTc); - float lenDySqr = dot(ddyTc, ddyTc); - float dMaxSqr = max(lenDxSqr, lenDySqr); - float dMinSqr = min(lenDxSqr, lenDySqr); + float lenDySqr = dot(ddyTc, ddyTc); + float dMaxSqr = max(lenDxSqr, lenDySqr); + float dMinSqr = min(lenDxSqr, lenDySqr); - // Calculate mipmap levels directly from sqared distances. This uses log2(sqrt(x)) = 0.5 * log2(x) to save some sqrt's - float maxLevel = 0.5 * log2( dMaxSqr ); - float minLevel = 0.5 * log2( dMinSqr ); + // Calculate mipmap levels directly from sqared distances. This uses log2(sqrt(x)) = 0.5 * log2(x) to save some sqrt's + float maxLevel = 0.5 * log2( dMaxSqr ); + float minLevel = 0.5 * log2( dMinSqr ); - // Calculate the log2 of the anisotropy and clamp it by the max supported. This uses log2(a/b) = log2(a)-log2(b) and min(log(a),log(b)) = log(min(a,b)) - float anisoLog2 = maxLevel - minLevel; - anisoLog2 = min( anisoLog2, gra_MaxAnisotropyLog2 ); + // Calculate the log2 of the anisotropy and clamp it by the max supported. This uses log2(a/b) = log2(a)-log2(b) and min(log(a),log(b)) = log(min(a,b)) + float anisoLog2 = maxLevel - minLevel; + anisoLog2 = min( anisoLog2, gra_MaxAnisotropyLog2 ); - // Adjust for anisotropy & clamp to level 0 - float result = max(maxLevel - anisoLog2 - 0.5f, 0.0f); //Subtract 0.5 to compensate for trilinear mipmapping + // Adjust for anisotropy & clamp to level 0 + float result = max(maxLevel - anisoLog2 - 0.5f, 0.0f); //Subtract 0.5 to compensate for trilinear mipmapping - // Added clamping to avoid "hot pink" on small tilesets that try to sample past the 1x1 tile miplevel - // This happens if you for example import a relatively small texture and zoom out - return min(result, gra_NumLevels); + // Added clamping to avoid "hot pink" on small tilesets that try to sample past the 1x1 tile miplevel + // This happens if you for example import a relatively small texture and zoom out + return min(result, gra_NumLevels); } float GranitePrivate_CalcMiplevelLinear(in GraniteTilesetConstantBuffer tsCB, in GraniteStreamingTextureConstantBuffer grSTCB, in gra_Float2 ddxTc, in gra_Float2 ddyTc) { - // Calculate the required mipmap level, this uses a similar - // formula as the GL spec. - // To reduce sqrt's and log2's we do some stuff in squared space here and further below in log space - // i.e. we wait with the sqrt untill we can do it for 'free' later during the log2 + // Calculate the required mipmap level, this uses a similar + // formula as the GL spec. + // To reduce sqrt's and log2's we do some stuff in squared space here and further below in log space + // i.e. we wait with the sqrt untill we can do it for 'free' later during the log2 ddxTc *= gra_CalcMiplevelDeltaScale; ddyTc *= gra_CalcMiplevelDeltaScale; - float lenDxSqr = dot(ddxTc, ddxTc); - float lenDySqr = dot(ddyTc, ddyTc); - float dMaxSqr = max(lenDxSqr, lenDySqr); + float lenDxSqr = dot(ddxTc, ddxTc); + float lenDySqr = dot(ddyTc, ddyTc); + float dMaxSqr = max(lenDxSqr, lenDySqr); - // Calculate mipmap levels directly from squared distances. This uses log2(sqrt(x)) = 0.5 * log2(x) to save some sqrt's - float maxLevel = 0.5 * log2(dMaxSqr) - 0.5f; //Subtract 0.5 to compensate for trilinear mipmapping + // Calculate mipmap levels directly from squared distances. This uses log2(sqrt(x)) = 0.5 * log2(x) to save some sqrt's + float maxLevel = 0.5 * log2(dMaxSqr) - 0.5f; //Subtract 0.5 to compensate for trilinear mipmapping - return clamp(maxLevel, 0.0f, gra_NumLevels); + return clamp(maxLevel, 0.0f, gra_NumLevels); } gra_Float4 GranitePrivate_PackTileId(in gra_Float2 tileXY, in float level, in float textureID) { #if GRA_64BIT_RESOLVER == 0 - gra_Float4 resultBits; - - resultBits.x = fmod(tileXY.x, 256.0f); - resultBits.y = floor(tileXY.x / 256.0f) + fmod(tileXY.y, 32.0f) * 8.0f; - resultBits.z = floor(tileXY.y / 32.0f) + fmod(level, 4.0f) * 64.0f; - resultBits.w = floor(level / 4.0f) + textureID * 4.0f; + gra_Float4 resultBits; + + resultBits.x = fmod(tileXY.x, 256.0f); + resultBits.y = floor(tileXY.x / 256.0f) + fmod(tileXY.y, 32.0f) * 8.0f; + resultBits.z = floor(tileXY.y / 32.0f) + fmod(level, 4.0f) * 64.0f; + resultBits.w = floor(level / 4.0f) + textureID * 4.0f; - const float scale = 1.0f / 255.0f; + const float scale = 1.0f / 255.0f; #if GRA_BGRA == 0 return scale * gra_Float4 - ( - float(resultBits.x), - float(resultBits.y), - float(resultBits.z), - float(resultBits.w) + ( + float(resultBits.x), + float(resultBits.y), + float(resultBits.z), + float(resultBits.w) ); #else return scale * gra_Float4 - ( - float(resultBits.z), - float(resultBits.y), - float(resultBits.x), - float(resultBits.w) + ( + float(resultBits.z), + float(resultBits.y), + float(resultBits.x), + float(resultBits.w) ); #endif #else - const float scale = 1.0f / 65535.0f; - return gra_Float4(tileXY.x, tileXY.y, level, textureID) * scale; + const float scale = 1.0f / 65535.0f; + return gra_Float4(tileXY.x, tileXY.y, level, textureID) * scale; #endif } gra_Float4 GranitePrivate_UnpackTileId(in gra_Float4 packedTile) { - gra_Float4 swiz; + gra_Float4 swiz; #if GRA_BGRA == 0 - swiz = packedTile; + swiz = packedTile; #else - swiz = packedTile.zyxw; + swiz = packedTile.zyxw; #endif - swiz *= 255.0f; + swiz *= 255.0f; - float tileX = swiz.x + fmod(swiz.y, 16.0f) * 256.0f; - float tileY = floor(swiz.y / 16.0f) + swiz.z * 16.0f; - float level = fmod(swiz.w, 16.0f); - float tex = floor(swiz.w / 16.0f); + float tileX = swiz.x + fmod(swiz.y, 16.0f) * 256.0f; + float tileY = floor(swiz.y / 16.0f) + swiz.z * 16.0f; + float level = fmod(swiz.w, 16.0f); + float tex = floor(swiz.w / 16.0f); - return gra_Float4(tileX, tileY, level, tex); + return gra_Float4(tileX, tileY, level, tex); } gra_Float3 GranitePrivate_TranslateCoord(in GraniteTilesetConstantBuffer tsCB, in gra_Float2 inputTexCoord, in gra_Float4 translationData, in int layer, out gra_Float2 numPagesOnLevel) { - // The translation table contains uint32_t values so we have to get to the individual bits of the float data - uint data = GranitePrivate_FloatAsUint(translationData[layer]); + // The translation table contains uint32_t values so we have to get to the individual bits of the float data + uint data = GranitePrivate_FloatAsUint(translationData[layer]); - // Slice Index: 7 bits, Cache X: 10 bits, Cache Y: 10 bits, Tile Level: 4 bits - uint slice = (data >> 24u) & 0x7Fu; - uint cacheX = (data >> 14u) & 0x3FFu; - uint cacheY = (data >> 4u) & 0x3FFu; - uint revLevel = data & 0xFu; + // Slice Index: 7 bits, Cache X: 10 bits, Cache Y: 10 bits, Tile Level: 4 bits + uint slice = (data >> 24u) & 0x7Fu; + uint cacheX = (data >> 14u) & 0x3FFu; + uint cacheY = (data >> 4u) & 0x3FFu; + uint revLevel = data & 0xFu; - gra_Float2 numTilesOnLevel; - numTilesOnLevel.x = GranitePrivate_Pow2(revLevel); - numTilesOnLevel.y = numTilesOnLevel.x * gra_NumTilesYScale; + gra_Float2 numTilesOnLevel; + numTilesOnLevel.x = GranitePrivate_Pow2(revLevel); + numTilesOnLevel.y = numTilesOnLevel.x * gra_NumTilesYScale; - gra_Float2 tileTexCoord = frac(inputTexCoord * numTilesOnLevel); + gra_Float2 tileTexCoord = frac(inputTexCoord * numTilesOnLevel); - gra_Float2 tileTexCoordCache = tileTexCoord * gra_TileContentInTiles + gra_Float2(cacheX, cacheY); - gra_Float3 final = gra_Float3(tileTexCoordCache * gra_RcpCacheInTiles(layer) + gra_BorderPixelsRcpCache(layer), slice); + gra_Float2 tileTexCoordCache = tileTexCoord * gra_TileContentInTiles + gra_Float2(cacheX, cacheY); + gra_Float3 final = gra_Float3(tileTexCoordCache * gra_RcpCacheInTiles(layer) + gra_BorderPixelsRcpCache(layer), slice); - numPagesOnLevel = numTilesOnLevel * gra_TileContentInTiles * gra_RcpCacheInTiles(layer); + numPagesOnLevel = numTilesOnLevel * gra_TileContentInTiles * gra_RcpCacheInTiles(layer); - return final; + return final; } gra_Float4 GranitePrivate_DrawDebugTiles(in gra_Float4 sourceColor, in gra_Float2 textureCoord, in gra_Float2 numPagesOnLevel) { - // Calculate the border values - gra_Float2 cacheOffs = frac(textureCoord * numPagesOnLevel); - float borderTemp = max(cacheOffs.x, 1.0-cacheOffs.x); - borderTemp = max(max(cacheOffs.y, 1.0-cacheOffs.y), borderTemp); - float border = smoothstep(0.98, 0.99, borderTemp); + // Calculate the border values + gra_Float2 cacheOffs = frac(textureCoord * numPagesOnLevel); + float borderTemp = max(cacheOffs.x, 1.0-cacheOffs.x); + borderTemp = max(max(cacheOffs.y, 1.0-cacheOffs.y), borderTemp); + float border = smoothstep(0.98, 0.99, borderTemp); - // White - gra_Float4 borderColor = gra_Float4(1,1,1,1); + // White + gra_Float4 borderColor = gra_Float4(1,1,1,1); - //Lerp it over the source color - return lerp(sourceColor, borderColor, border); + //Lerp it over the source color + return lerp(sourceColor, borderColor, border); } gra_Float4 GranitePrivate_MakeResolveOutput(in GraniteTilesetConstantBuffer tsCB, in gra_Float2 tileXY, in float level) { #if GRA_PACK_RESOLVE_OUTPUT - return GranitePrivate_PackTileId(tileXY, level, gra_TextureId); + return GranitePrivate_PackTileId(tileXY, level, gra_TextureId); #else - return gra_Float4(tileXY, level, gra_TextureId); + return gra_Float4(tileXY, level, gra_TextureId); #endif } gra_Float4 GranitePrivate_ResolverPixel(in GraniteTilesetConstantBuffer tsCB, in gra_Float2 inputTexCoord, in float LOD) { - float level = floor(LOD + 0.5f); + float level = floor(LOD + 0.5f); - // Number of tiles on level zero - gra_Float2 level0NumTiles; - level0NumTiles.x = gra_Level0NumTilesX; - level0NumTiles.y = gra_Level0NumTilesX * gra_NumTilesYScale; + // Number of tiles on level zero + gra_Float2 level0NumTiles; + level0NumTiles.x = gra_Level0NumTilesX; + level0NumTiles.y = gra_Level0NumTilesX * gra_NumTilesYScale; - // Calculate xy of the tiles to load - gra_Float2 virtualTilesUv = floor(inputTexCoord * level0NumTiles * pow(0.5, level)); + // Calculate xy of the tiles to load + gra_Float2 virtualTilesUv = floor(inputTexCoord * level0NumTiles * pow(0.5, level)); - return GranitePrivate_MakeResolveOutput(tsCB, virtualTilesUv, level); + return GranitePrivate_MakeResolveOutput(tsCB, virtualTilesUv, level); } void GranitePrivate_CalculateCubemapCoordinates(in gra_Float3 inputTexCoord, in gra_Float3 dVx, in gra_Float3 dVy, in GraniteStreamingTextureCubeConstantBuffer transforms, out int faceIdx, out gra_Float2 texCoord, out gra_Float2 dX, out gra_Float2 dY) { - gra_Float2 contTexCoord; - gra_Float3 derivX; - gra_Float3 derivY; + gra_Float2 contTexCoord; + gra_Float3 derivX; + gra_Float3 derivY; - float majorAxis; - if (abs(inputTexCoord.z) >= abs(inputTexCoord.x) && abs(inputTexCoord.z) >= abs(inputTexCoord.y)) - { + float majorAxis; + if (abs(inputTexCoord.z) >= abs(inputTexCoord.x) && abs(inputTexCoord.z) >= abs(inputTexCoord.y)) + { // Z major axis - if(inputTexCoord.z < 0.0) - { - faceIdx = 5; - texCoord.x = -inputTexCoord.x; - } - else - { - faceIdx = 4; - texCoord.x = inputTexCoord.x; - } - texCoord.y = -inputTexCoord.y; - majorAxis = inputTexCoord.z; - - contTexCoord = gra_Float2(inputTexCoord.x, inputTexCoord.y); - derivX = gra_Float3(dVx.x, dVx.y, dVx.z); - derivY = gra_Float3(dVy.x, dVy.y, dVy.z); - } - else if (abs(inputTexCoord.y) >= abs(inputTexCoord.x)) - { + if(inputTexCoord.z < 0.0) + { + faceIdx = 5; + texCoord.x = -inputTexCoord.x; + } + else + { + faceIdx = 4; + texCoord.x = inputTexCoord.x; + } + texCoord.y = -inputTexCoord.y; + majorAxis = inputTexCoord.z; + + contTexCoord = gra_Float2(inputTexCoord.x, inputTexCoord.y); + derivX = gra_Float3(dVx.x, dVx.y, dVx.z); + derivY = gra_Float3(dVy.x, dVy.y, dVy.z); + } + else if (abs(inputTexCoord.y) >= abs(inputTexCoord.x)) + { // Y major axis - if(inputTexCoord.y < 0.0) - { - faceIdx = 3; - texCoord.y = -inputTexCoord.z; - } - else - { - faceIdx = 2; - texCoord.y = inputTexCoord.z; - } - texCoord.x = inputTexCoord.x; - majorAxis = inputTexCoord.y; - - contTexCoord = gra_Float2(inputTexCoord.x, inputTexCoord.z); - derivX = gra_Float3(dVx.x, dVx.z, dVx.y); - derivY = gra_Float3(dVy.x, dVy.z, dVy.y); - } - else - { + if(inputTexCoord.y < 0.0) + { + faceIdx = 3; + texCoord.y = -inputTexCoord.z; + } + else + { + faceIdx = 2; + texCoord.y = inputTexCoord.z; + } + texCoord.x = inputTexCoord.x; + majorAxis = inputTexCoord.y; + + contTexCoord = gra_Float2(inputTexCoord.x, inputTexCoord.z); + derivX = gra_Float3(dVx.x, dVx.z, dVx.y); + derivY = gra_Float3(dVy.x, dVy.z, dVy.y); + } + else + { // X major axis - if(inputTexCoord.x < 0.0) - { - faceIdx = 1; - texCoord.x = inputTexCoord.z; - } - else - { - faceIdx = 0; - texCoord.x = -inputTexCoord.z; - } - texCoord.y = -inputTexCoord.y; - majorAxis = inputTexCoord.x; - - contTexCoord = gra_Float2(inputTexCoord.z, inputTexCoord.y); - derivX = gra_Float3(dVx.z, dVx.y, dVx.x); - derivY = gra_Float3(dVy.z, dVy.y, dVy.x); - } - texCoord = (texCoord + majorAxis) / (2.0 * abs(majorAxis)); + if(inputTexCoord.x < 0.0) + { + faceIdx = 1; + texCoord.x = inputTexCoord.z; + } + else + { + faceIdx = 0; + texCoord.x = -inputTexCoord.z; + } + texCoord.y = -inputTexCoord.y; + majorAxis = inputTexCoord.x; + + contTexCoord = gra_Float2(inputTexCoord.z, inputTexCoord.y); + derivX = gra_Float3(dVx.z, dVx.y, dVx.x); + derivY = gra_Float3(dVy.z, dVy.y, dVy.x); + } + texCoord = (texCoord + majorAxis) / (2.0 * abs(majorAxis)); #if GRA_HQ_CUBEMAPPING - dX = /*contTexCoord **/ ((contTexCoord + derivX.xy) / ( 2.0 * (majorAxis + derivX.z)) - (contTexCoord / (2.0 * majorAxis))); - dY = /*contTexCoord **/ ((contTexCoord + derivY.xy) / ( 2.0 * (majorAxis + derivY.z)) - (contTexCoord / (2.0 * majorAxis))); + dX = /*contTexCoord **/ ((contTexCoord + derivX.xy) / ( 2.0 * (majorAxis + derivX.z)) - (contTexCoord / (2.0 * majorAxis))); + dY = /*contTexCoord **/ ((contTexCoord + derivY.xy) / ( 2.0 * (majorAxis + derivY.z)) - (contTexCoord / (2.0 * majorAxis))); #else - dX = ((/*contTexCoord **/ derivX.xy) / (2.0 * abs(majorAxis))); - dY = ((/*contTexCoord **/ derivY.xy) / (2.0 * abs(majorAxis))); + dX = ((/*contTexCoord **/ derivX.xy) / (2.0 * abs(majorAxis))); + dY = ((/*contTexCoord **/ derivY.xy) / (2.0 * abs(majorAxis))); #endif - // Now scale the derivatives with the texture transform scale - dX *= transforms.data[faceIdx].data[0].zw; - dY *= transforms.data[faceIdx].data[0].zw; + // Now scale the derivatives with the texture transform scale + dX *= transforms.data[faceIdx].data[0].zw; + dY *= transforms.data[faceIdx].data[0].zw; } // Auto-level void GranitePrivate_CalculateCubemapCoordinates(in gra_Float3 inputTexCoord, in GraniteStreamingTextureCubeConstantBuffer transforms, out int faceIdx, out gra_Float2 texCoord, out gra_Float2 dX, out gra_Float2 dY) { - gra_Float3 dVx = ddx(inputTexCoord); - gra_Float3 dVy = ddy(inputTexCoord); + gra_Float3 dVx = ddx(inputTexCoord); + gra_Float3 dVy = ddy(inputTexCoord); - GranitePrivate_CalculateCubemapCoordinates(inputTexCoord, dVx, dVy, transforms, faceIdx, texCoord, dX, dY); + GranitePrivate_CalculateCubemapCoordinates(inputTexCoord, dVx, dVy, transforms, faceIdx, texCoord, dX, dY); } gra_Float2 Granite_GetTextureDimensions(in GraniteStreamingTextureConstantBuffer grSTCB) { - return gra_Float2(1.0 / gra_AssetWidthRcp, 1.0 / gra_AssetHeightRcp); //TODO(ddebaets) use HLSL rcp here + return gra_Float2(1.0 / gra_AssetWidthRcp, 1.0 / gra_AssetHeightRcp); //TODO(ddebaets) use HLSL rcp here } diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl index 882aa4d3cc3..ef6802d9b30 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl @@ -548,7 +548,7 @@ float3 PackFloat2To888(float2 f) // Unpack 2 float of 12bit packed into a 888 float2 Unpack888ToFloat2(float3 x) { - uint3 i = (uint3)(x * 255.5); // +0.5 to fix precision error on iOS + uint3 i = (uint3)(x * 255.5); // +0.5 to fix precision error on iOS // 8 bit in lo, 4 bit in hi uint hi = i.z >> 4; uint lo = i.z & 15; @@ -567,7 +567,7 @@ float PackFloat2To8(float2 f) return x_y_expanded / 255.0; // above 4 lines equivalent to: - //return (16.0 * f.x + f.y) / 17.0; + //return (16.0 * f.x + f.y) / 17.0; } // Unpack 2 float values from the [0, 1] range, packed in an 8 bits float from the [0, 1] range diff --git a/com.unity.render-pipelines.core/ShaderLibrary/ParallaxMapping.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/ParallaxMapping.hlsl index d6494d02e93..c90437bef4c 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/ParallaxMapping.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/ParallaxMapping.hlsl @@ -13,7 +13,7 @@ half3 GetViewDirectionTangentSpace(half4 tangentWS, half3 normalWS, half3 viewDi half crossSign = (tangentWS.w > 0.0 ? 1.0 : -1.0); // we do not need to multiple GetOddNegativeScale() here, as it is done in vertex shader half3 bitang = crossSign * cross(normalWS.xyz, tangentWS.xyz); - half3 WorldSpaceNormal = renormFactor * normalWS.xyz; // we want a unit length Normal Vector node in shader graph + half3 WorldSpaceNormal = renormFactor * normalWS.xyz; // we want a unit length Normal Vector node in shader graph // to preserve mikktspace compliance we use same scale renormFactor as was used on the normal. // This is explained in section 2.2 in "surface gradient based bump mapping framework" diff --git a/com.unity.render-pipelines.core/ShaderLibrary/PhysicalCamera.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/PhysicalCamera.hlsl index 93f08de59ac..5263fce312f 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/PhysicalCamera.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/PhysicalCamera.hlsl @@ -67,7 +67,7 @@ float ComputeLuminanceAdaptation(float previousLuminance, float currentLuminance { float delta = currentLuminance - previousLuminance; float speed = delta > 0.0 ? speedDarkToLight : speedLightToDark; - + // Exponential decay return previousLuminance + delta * (1.0 - exp2(-deltaTime * speed)); } diff --git a/com.unity.render-pipelines.core/ShaderLibrary/TextureStack.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/TextureStack.hlsl index 461af12fb84..9417d835733 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/TextureStack.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/TextureStack.hlsl @@ -70,7 +70,7 @@ struct StackInfo { GraniteLookupData lookupData; GraniteLODLookupData lookupDataLod; - float4 resolveOutput; + float4 resolveOutput; }; struct VTProperty @@ -211,30 +211,30 @@ float4 SampleVT_##layerSamplerName(StackInfo info, int lodCalculation, int quali } #define DECLARE_STACK(stackName, layer0SamplerName)\ - DECLARE_STACK_BASE(stackName)\ - DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ - DECLARE_BUILD_PROPERTIES(stackName, 1, 0, 0, 0, 0) + DECLARE_STACK_BASE(stackName)\ + DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ + DECLARE_BUILD_PROPERTIES(stackName, 1, 0, 0, 0, 0) #define DECLARE_STACK2(stackName, layer0SamplerName, layer1SamplerName)\ - DECLARE_STACK_BASE(stackName)\ - DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ - DECLARE_STACK_LAYER(stackName, layer1SamplerName, 1)\ - DECLARE_BUILD_PROPERTIES(stackName, 2, 0, 1, 1, 1) + DECLARE_STACK_BASE(stackName)\ + DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ + DECLARE_STACK_LAYER(stackName, layer1SamplerName, 1)\ + DECLARE_BUILD_PROPERTIES(stackName, 2, 0, 1, 1, 1) #define DECLARE_STACK3(stackName, layer0SamplerName, layer1SamplerName, layer2SamplerName)\ - DECLARE_STACK_BASE(stackName)\ - DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ - DECLARE_STACK_LAYER(stackName, layer1SamplerName, 1)\ - DECLARE_STACK_LAYER(stackName, layer2SamplerName, 2)\ - DECLARE_BUILD_PROPERTIES(stackName, 3, 0, 1, 2, 2) + DECLARE_STACK_BASE(stackName)\ + DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ + DECLARE_STACK_LAYER(stackName, layer1SamplerName, 1)\ + DECLARE_STACK_LAYER(stackName, layer2SamplerName, 2)\ + DECLARE_BUILD_PROPERTIES(stackName, 3, 0, 1, 2, 2) #define DECLARE_STACK4(stackName, layer0SamplerName, layer1SamplerName, layer2SamplerName, layer3SamplerName)\ - DECLARE_STACK_BASE(stackName)\ - DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ - DECLARE_STACK_LAYER(stackName, layer1SamplerName, 1)\ - DECLARE_STACK_LAYER(stackName, layer2SamplerName, 2)\ - DECLARE_STACK_LAYER(stackName, layer3SamplerName, 3)\ - DECLARE_BUILD_PROPERTIES(stackName, 4, 0, 1, 2, 3) + DECLARE_STACK_BASE(stackName)\ + DECLARE_STACK_LAYER(stackName, layer0SamplerName, 0)\ + DECLARE_STACK_LAYER(stackName, layer1SamplerName, 1)\ + DECLARE_STACK_LAYER(stackName, layer2SamplerName, 2)\ + DECLARE_STACK_LAYER(stackName, layer3SamplerName, 3)\ + DECLARE_BUILD_PROPERTIES(stackName, 4, 0, 1, 2, 3) #define PrepareStack(inputParams, stackName) PrepareVT_##stackName(inputParams) #define SampleStack(info, lodMode, quality, textureName) SampleVT_##textureName(info, lodMode, quality) @@ -316,12 +316,12 @@ struct VTProperty TEXTURE2D(Layer1); TEXTURE2D(Layer2); TEXTURE2D(Layer3); -#ifndef SHADER_API_GLES +#ifndef SHADER_API_GLES SAMPLER(samplerLayer0); SAMPLER(samplerLayer1); SAMPLER(samplerLayer2); SAMPLER(samplerLayer3); -#endif +#endif }; StackInfo MakeStackInfo(VtInputParameters vt) diff --git a/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl index 5e0c1bcf4f1..a8d3949b637 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/UnityDOTSInstancing.hlsl @@ -133,7 +133,7 @@ ByteAddressBuffer unity_DOTSInstanceData; // on some platforms does not trigger. struct DOTSVisibleData { - uint4 VisibleData; + uint4 VisibleData; }; // The name of this cbuffer has to start with "UnityInstancing" and a struct so it's @@ -236,4 +236,3 @@ float2x4 LoadDOTSInstancedData(float2x4 dummy, uint metadata) { return LoadDOTSI #endif // UNITY_DOTS_INSTANCING_ENABLED #endif // UNITY_DOTS_INSTANCING_INCLUDED - diff --git a/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl index 3e07515e608..1b438bd8b4b 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/Version.hlsl @@ -4,4 +4,3 @@ #define VERSION_GREATER_EQUAL(major, minor) ((SHADER_LIBRARY_VERSION_MAJOR > major) || ((SHADER_LIBRARY_VERSION_MAJOR == major) && (SHADER_LIBRARY_VERSION_MINOR >= minor))) #define VERSION_LOWER(major, minor) ((SHADER_LIBRARY_VERSION_MAJOR < major) || ((SHADER_LIBRARY_VERSION_MAJOR == major) && (SHADER_LIBRARY_VERSION_MINOR < minor))) #define VERSION_EQUAL(major, minor) ((SHADER_LIBRARY_VERSION_MAJOR == major) && (SHADER_LIBRARY_VERSION_MINOR == minor)) - diff --git a/com.unity.render-pipelines.core/ShaderLibrary/VirtualTexturing.hlsl b/com.unity.render-pipelines.core/ShaderLibrary/VirtualTexturing.hlsl index 576fa67b1b9..3739546ecb1 100644 --- a/com.unity.render-pipelines.core/ShaderLibrary/VirtualTexturing.hlsl +++ b/com.unity.render-pipelines.core/ShaderLibrary/VirtualTexturing.hlsl @@ -32,9 +32,9 @@ struct VtInputParameters int VirtualTexturingLookup( in GraniteConstantBuffers grCB, - in GraniteTranslationTexture translationTable, + in GraniteTranslationTexture translationTable, in VtInputParameters input, - out GraniteLookupData graniteLookupData, + out GraniteLookupData graniteLookupData, out float4 resolveResult ) { @@ -48,8 +48,8 @@ int VirtualTexturingLookup( if (input.levelMode == VtLevel_Automatic) { - dx = ddx(texCoord); - dy = ddy(texCoord); + dx = ddx(texCoord); + dy = ddy(texCoord); } else if (input.levelMode == VtLevel_Bias) { @@ -65,34 +65,34 @@ int VirtualTexturingLookup( else { dx = ddx(texCoord); - dy = ddy(texCoord); + dy = ddy(texCoord); } - } + } else if (input.levelMode == VtLevel_Derivatives) { - dx = input.dx; - dy = input.dy; + dx = input.dx; + dy = input.dy; } else /*input.levelMode == VtLevel_Lod*/ { - //gra_TrilinearOffset ensures we do round-nearest for no-trilinear and + //gra_TrilinearOffset ensures we do round-nearest for no-trilinear and //round-floor for trilinear. - float clampedLevel = clamp(input.lodOrOffset + gra_TrilinearOffset, 0.0f, gra_NumLevels); + float clampedLevel = clamp(input.lodOrOffset + gra_TrilinearOffset, 0.0f, gra_NumLevels); mipLevel = floor(clampedLevel); - dx = float2(frac(clampedLevel), 0.0f); // trilinear blend ratio - dy = float2(0.0f,0.0f); + dx = float2(frac(clampedLevel), 0.0f); // trilinear blend ratio + dy = float2(0.0f,0.0f); } - + // Transform the derivatives to atlas space if needed if (input.uvMode == VtUvSpace_Regular && input.levelMode != VtLevel_Lod) { - dx = gra_Transform.zw * dx; - dy = gra_Transform.zw * dy; + dx = gra_Transform.zw * dx; + dy = gra_Transform.zw * dy; } if (input.levelMode != VtLevel_Lod) { - mipLevel = GranitePrivate_CalcMiplevelAnisotropic(grCB.tilesetBuffer, grCB.streamingTextureBuffer, dx, dy); + mipLevel = GranitePrivate_CalcMiplevelAnisotropic(grCB.tilesetBuffer, grCB.streamingTextureBuffer, dx, dy); // Simply add it here derivatives are wrong from this point onwards but not used anymore if ( input.sampleQuality == VtSampleQuality_Low && input.levelMode == VtLevel_Bias) @@ -127,13 +127,13 @@ int VirtualTexturingLookup( texCoord = input.uv; } - texCoord = Granite_Transform(gra_StreamingTextureCB, texCoord); + texCoord = Granite_Transform(gra_StreamingTextureCB, texCoord); } - // calculate resolver data - float2 level0NumTiles = float2(gra_Level0NumTilesX, gra_Level0NumTilesX*gra_NumTilesYScale); - float2 virtualTilesUv = floor(texCoord * level0NumTiles * pow(0.5, mipLevel)); - resolveResult = GranitePrivate_MakeResolveOutput(tsCB, virtualTilesUv, mipLevel); + // calculate resolver data + float2 level0NumTiles = float2(gra_Level0NumTilesX, gra_Level0NumTilesX*gra_NumTilesYScale); + float2 virtualTilesUv = floor(texCoord * level0NumTiles * pow(0.5, mipLevel)); + resolveResult = GranitePrivate_MakeResolveOutput(tsCB, virtualTilesUv, mipLevel); float4 translationTableData; if (input.levelMode != VtLevel_Lod) @@ -155,18 +155,18 @@ int VirtualTexturingLookup( // Note: this is equal for both anisotropic and linear sampling // We could use a sample bias here for 'auto' mip level detection #if (GRA_LOAD_INSTR==0) - translationTableData = GranitePrivate_SampleLevel_Translation(translationTable, texCoord, mipLevel); + translationTableData = GranitePrivate_SampleLevel_Translation(translationTable, texCoord, mipLevel); #else - translationTableData = GranitePrivate_Load(translationTable, gra_Int3(virtualTilesUv, mipLevel)); -#endif + translationTableData = GranitePrivate_Load(translationTable, gra_Int3(virtualTilesUv, mipLevel)); +#endif } - graniteLookupData.translationTableData = translationTableData; - graniteLookupData.textureCoordinates = texCoord; - graniteLookupData.dX = dx; - graniteLookupData.dY = dy; + graniteLookupData.translationTableData = translationTableData; + graniteLookupData.textureCoordinates = texCoord; + graniteLookupData.dX = dx; + graniteLookupData.dY = dy; - return 1; + return 1; } int VirtualTexturingSample( @@ -178,9 +178,9 @@ int VirtualTexturingSample( in int quality, out float4 result) { - // Convert from pixels to [0-1] and look up in the physical page texture - float2 deltaScale; - float3 cacheCoord = GranitePrivate_TranslateCoord(tsCB, graniteLookupData.textureCoordinates, graniteLookupData.translationTableData, layer, deltaScale); + // Convert from pixels to [0-1] and look up in the physical page texture + float2 deltaScale; + float3 cacheCoord = GranitePrivate_TranslateCoord(tsCB, graniteLookupData.textureCoordinates, graniteLookupData.translationTableData, layer, deltaScale); if ( levelMode != VtLevel_Lod ) { @@ -199,13 +199,13 @@ int VirtualTexturingSample( float2 sampDeltaX = graniteLookupData.dX*deltaScale; float2 sampDeltaY = graniteLookupData.dY*deltaScale; - result = GranitePrivate_SampleGradArray(cacheTexture, cacheCoord, sampDeltaX, sampDeltaY); + result = GranitePrivate_SampleGradArray(cacheTexture, cacheCoord, sampDeltaX, sampDeltaY); } } else { - result = GranitePrivate_SampleLevelArray(cacheTexture, cacheCoord, graniteLookupData.dX.x); + result = GranitePrivate_SampleLevelArray(cacheTexture, cacheCoord, graniteLookupData.dX.x); } - return 1; + return 1; } diff --git a/com.unity.render-pipelines.core/Tests/Editor/BitArrayTests.cs b/com.unity.render-pipelines.core/Tests/Editor/BitArrayTests.cs index ce007cff0f2..12785a2e68b 100644 --- a/com.unity.render-pipelines.core/Tests/Editor/BitArrayTests.cs +++ b/com.unity.render-pipelines.core/Tests/Editor/BitArrayTests.cs @@ -100,7 +100,7 @@ void TestBitArrayOperator(T[] ba) Assert.AreEqual(notA.humanizedData, GetLastHumanizedBits(notAHumanized, ba[0].capacity)); //test indexer - foreach(uint index in getSetTestedIndexes.Where(i => i < ba[0].capacity)) + foreach (uint index in getSetTestedIndexes.Where(i => i < ba[0].capacity)) { //test get Assert.AreEqual(ba[1][index], (index & 1) == 0); //on a, odd value are false and even true diff --git a/com.unity.render-pipelines.core/Tests/Editor/CoreUnsafeUtilsTests.cs b/com.unity.render-pipelines.core/Tests/Editor/CoreUnsafeUtilsTests.cs index 24905fd3347..accde5f90d1 100644 --- a/com.unity.render-pipelines.core/Tests/Editor/CoreUnsafeUtilsTests.cs +++ b/com.unity.render-pipelines.core/Tests/Editor/CoreUnsafeUtilsTests.cs @@ -27,7 +27,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - fixed (float* fptr = &floatValue) + fixed(float* fptr = &floatValue) return intValue ^ *(int*)fptr; } } @@ -35,13 +35,13 @@ public override int GetHashCode() static object[][] s_CopyToList = new object[][] { new object[] { new List - { - new TestData { floatValue = 2, intValue = 1 }, - new TestData { floatValue = 3, intValue = 2 }, - new TestData { floatValue = 4, intValue = 3 }, - new TestData { floatValue = 5, intValue = 4 }, - new TestData { floatValue = 6, intValue = 5 }, - } } + { + new TestData { floatValue = 2, intValue = 1 }, + new TestData { floatValue = 3, intValue = 2 }, + new TestData { floatValue = 4, intValue = 3 }, + new TestData { floatValue = 5, intValue = 4 }, + new TestData { floatValue = 6, intValue = 5 }, + } } }; [Test] @@ -55,18 +55,16 @@ public void CopyToList(List datas) Assert.AreEqual(datas[i], dest[i]); } - - static object[][] s_CopyToArray = new object[][] { new object[] { new TestData[] - { - new TestData { floatValue = 2, intValue = 1 }, - new TestData { floatValue = 3, intValue = 2 }, - new TestData { floatValue = 4, intValue = 3 }, - new TestData { floatValue = 5, intValue = 4 }, - new TestData { floatValue = 6, intValue = 5 }, - } } + { + new TestData { floatValue = 2, intValue = 1 }, + new TestData { floatValue = 3, intValue = 2 }, + new TestData { floatValue = 4, intValue = 3 }, + new TestData { floatValue = 5, intValue = 4 }, + new TestData { floatValue = 6, intValue = 5 }, + } } }; [Test] @@ -98,7 +96,7 @@ public void QuickSort(int[] values) CoreUnsafeUtils.QuickSort(values.Length, ptrValues); - for (int i = 0; i< values.Length - 1; ++i) + for (int i = 0; i < values.Length - 1; ++i) Assert.LessOrEqual(ptrValues[i], ptrValues[i + 1]); } diff --git a/com.unity.render-pipelines.core/Tests/Editor/EditorExampleTest.cs b/com.unity.render-pipelines.core/Tests/Editor/EditorExampleTest.cs index 06dd0a117fc..a2d55421ede 100644 --- a/com.unity.render-pipelines.core/Tests/Editor/EditorExampleTest.cs +++ b/com.unity.render-pipelines.core/Tests/Editor/EditorExampleTest.cs @@ -1,22 +1,24 @@ -using UnityEngine; +using UnityEngine; using UnityEditor; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections; -class EditorExampleTest { +class EditorExampleTest +{ + [Test] + public void EditorSampleTestSimplePasses() + { + // Use the Assert class to test conditions. + } - [Test] - public void EditorSampleTestSimplePasses() { - // Use the Assert class to test conditions. - } - - // A UnityTest behaves like a coroutine in PlayMode - // and allows you to yield null to skip a frame in EditMode - [UnityTest] - public IEnumerator EditorSampleTestWithEnumeratorPasses() { - // Use the Assert class to test conditions. - // yield to skip a frame - yield return null; - } + // A UnityTest behaves like a coroutine in PlayMode + // and allows you to yield null to skip a frame in EditMode + [UnityTest] + public IEnumerator EditorSampleTestWithEnumeratorPasses() + { + // Use the Assert class to test conditions. + // yield to skip a frame + yield return null; + } } diff --git a/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs b/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs index 5de013d578a..b02b863b884 100644 --- a/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs +++ b/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs @@ -27,7 +27,7 @@ public void WriteToBackBufferNotCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -44,7 +44,7 @@ public void NoWriteToBackBufferCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -61,7 +61,7 @@ public void WriteToImportedTextureNotCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { builder.WriteTexture(m_RenderGraph.ImportTexture(null)); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -77,7 +77,7 @@ public void WriteToImportedComputeBufferNotCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { builder.WriteComputeBuffer(m_RenderGraph.ImportComputeBuffer(null)); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -171,7 +171,7 @@ public void PassWriteResourcePartialNotReadAfterNotCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } TextureHandle texture1; @@ -179,7 +179,7 @@ public void PassWriteResourcePartialNotReadAfterNotCulled() { builder.ReadTexture(texture0); texture1 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // This pass writes to texture0 which is used so will not be culled out. @@ -189,14 +189,14 @@ public void PassWriteResourcePartialNotReadAfterNotCulled() { builder.WriteTexture(texture0); builder.WriteTexture(texture1); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass3", out var passData)) { builder.ReadTexture(texture1); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -216,7 +216,7 @@ public void PassDisallowCullingNotCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { builder.AllowPassCulling(false); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -235,14 +235,14 @@ public void PartialUnusedProductNotCulled() { texture = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass1", out var passData)) { builder.ReadTexture(texture); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -261,7 +261,7 @@ public void SimpleCreateReleaseTexture() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { texture = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // Add dummy passes @@ -269,7 +269,7 @@ public void SimpleCreateReleaseTexture() { using (var builder = m_RenderGraph.AddRenderPass("TestPass1", out var passData)) { - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } } @@ -277,7 +277,7 @@ public void SimpleCreateReleaseTexture() { builder.ReadTexture(texture); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -297,14 +297,14 @@ public void UseTransientOutsidePassRaiseException() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { texture = builder.CreateTransientTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm }); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass1", out var passData)) { builder.ReadTexture(texture); // This is illegal (transient resource was created in previous pass) builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -319,7 +319,7 @@ public void TransientCreateReleaseInSamePass() { texture = builder.CreateTransientTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm }); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -345,7 +345,7 @@ public void AsyncPassReleaseTextureOnGraphicsPipe() texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); texture1 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // Second pass creates a transient texture => Create/Release should happen in this pass but we want to delay the release until the first graphics pipe pass that sync with async queue. @@ -354,7 +354,7 @@ public void AsyncPassReleaseTextureOnGraphicsPipe() texture2 = builder.CreateTransientTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm }); builder.WriteTexture(texture0); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // This pass is the last to read texture0 => Release should happen in this pass but we want to delay the release until the first graphics pipe pass that sync with async queue. @@ -363,7 +363,7 @@ public void AsyncPassReleaseTextureOnGraphicsPipe() texture0 = builder.ReadTexture(texture0); builder.WriteTexture(texture1); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // Just here to add "padding" to the number of passes to ensure resources are not released right at the first sync pass. @@ -371,7 +371,7 @@ public void AsyncPassReleaseTextureOnGraphicsPipe() { texture3 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); builder.EnableAsyncCompute(false); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // Pass prior to synchronization should be where textures are released. @@ -379,7 +379,7 @@ public void AsyncPassReleaseTextureOnGraphicsPipe() { builder.WriteTexture(texture3); builder.EnableAsyncCompute(false); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // Graphics pass that reads texture1. This will request a sync with compute pipe. The previous pass should be the one releasing async textures. @@ -389,7 +389,7 @@ public void AsyncPassReleaseTextureOnGraphicsPipe() builder.ReadTexture(texture3); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled builder.EnableAsyncCompute(false); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -407,14 +407,14 @@ public void TransientResourceNotCulled() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass1", out var passData)) { builder.CreateTransientTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm }); builder.WriteTexture(texture0); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } // Graphics pass that reads texture1. This will request a sync with compute pipe. The previous pass should be the one releasing async textures. @@ -423,7 +423,7 @@ public void TransientResourceNotCulled() builder.ReadTexture(texture0); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled builder.EnableAsyncCompute(false); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -440,21 +440,21 @@ public void AsyncPassWriteWaitOnGraphcisPipe() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("Async_TestPass1", out var passData)) { texture0 = builder.WriteTexture(texture0); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass2", out var passData)) { builder.ReadTexture(texture0); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -473,7 +473,7 @@ public void AsyncPassReadWaitOnGraphcisPipe() using (var builder = m_RenderGraph.AddRenderPass("TestPass0", out var passData)) { texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("Async_TestPass1", out var passData)) @@ -481,14 +481,14 @@ public void AsyncPassReadWaitOnGraphcisPipe() builder.ReadTexture(texture0); texture1 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass2", out var passData)) { builder.ReadTexture(texture1); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -507,14 +507,14 @@ public void GraphicsPassWriteWaitOnAsyncPipe() { texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass1", out var passData)) { builder.WriteTexture(texture0); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); @@ -524,7 +524,6 @@ public void GraphicsPassWriteWaitOnAsyncPipe() Assert.AreEqual(0, compiledPasses[1].syncToPassIndex); } - [Test] public void GraphicsPassReadWaitOnAsyncPipe() { @@ -533,14 +532,14 @@ public void GraphicsPassReadWaitOnAsyncPipe() { texture0 = builder.WriteTexture(m_RenderGraph.CreateTexture(new TextureDesc(Vector2.one) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm })); builder.EnableAsyncCompute(true); - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } using (var builder = m_RenderGraph.AddRenderPass("TestPass1", out var passData)) { builder.ReadTexture(texture0); builder.WriteTexture(m_RenderGraph.ImportBackbuffer(0)); // Needed for the passes to not be culled - builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => { }); + builder.SetRenderFunc((RenderGraphTestPassData data, RenderGraphContext context) => {}); } m_RenderGraph.CompileRenderGraph(); diff --git a/com.unity.render-pipelines.core/Tests/Runtime/RuntimeExampleTest.cs b/com.unity.render-pipelines.core/Tests/Runtime/RuntimeExampleTest.cs index ed3e28d0bd1..e08ffec278f 100644 --- a/com.unity.render-pipelines.core/Tests/Runtime/RuntimeExampleTest.cs +++ b/com.unity.render-pipelines.core/Tests/Runtime/RuntimeExampleTest.cs @@ -1,21 +1,23 @@ -using UnityEngine; +using UnityEngine; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections; -class RuntimeExampleTest { +class RuntimeExampleTest +{ + [Test] + public void PlayModeSampleTestSimplePasses() + { + // Use the Assert class to test conditions. + } - [Test] - public void PlayModeSampleTestSimplePasses() { - // Use the Assert class to test conditions. - } - - // A UnityTest behaves like a coroutine in PlayMode - // and allows you to yield null to skip a frame in EditMode - [UnityTest] - public IEnumerator PlayModeSampleTestWithEnumeratorPasses() { - // Use the Assert class to test conditions. - // yield to skip a frame - yield return null; - } + // A UnityTest behaves like a coroutine in PlayMode + // and allows you to yield null to skip a frame in EditMode + [UnityTest] + public IEnumerator PlayModeSampleTestWithEnumeratorPasses() + { + // Use the Assert class to test conditions. + // yield to skip a frame + yield return null; + } } diff --git a/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs b/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs index 79721c240d2..cd9945c4d57 100644 --- a/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs +++ b/com.unity.render-pipelines.high-definition-config/Runtime/ShaderConfig.cs @@ -69,7 +69,7 @@ public enum ShaderOptions // Also uncomment in the HDRP package all ".../Experimental/Probe Volume" menu /// Whether probe volumes are enabled. - EnableProbeVolumes = 0, + EnableProbeVolumes = 0, /// Probe volume supports additive blending. ProbeVolumesAdditiveBlending = 1, /// The probe volume filtering mode. diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/AutodeskInteractiveMaterialImport.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/AutodeskInteractiveMaterialImport.cs index 36caf3be80d..911a5e4382a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/AutodeskInteractiveMaterialImport.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/AutodeskInteractiveMaterialImport.cs @@ -13,6 +13,7 @@ public override uint GetVersion() { return k_Version; } + public override int GetPostprocessOrder() { return k_Order; @@ -30,8 +31,8 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat Vector4 vectorProperty; TexturePropertyDescription textureProperty; - bool isMasked = description.TryGetProperty("mask_threshold",out floatProperty); - bool isTransparent = description.TryGetProperty("opacity",out floatProperty); + bool isMasked = description.TryGetProperty("mask_threshold", out floatProperty); + bool isTransparent = description.TryGetProperty("opacity", out floatProperty); Shader shader; if (isMasked) diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs index d8a9134f523..4594225cddb 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs @@ -10,7 +10,7 @@ namespace UnityEditor.Rendering.HighDefinition -{ +{ class FBXArnoldSurfaceMaterialDescriptionPreprocessor : AssetPostprocessor { static readonly uint k_Version = 2; @@ -21,6 +21,7 @@ public override uint GetVersion() { return k_Version; } + public override int GetPostprocessOrder() { return k_Order; @@ -32,6 +33,7 @@ static bool IsMayaArnoldStandardSurfaceMaterial(MaterialDescription description) description.TryGetProperty("TypeId", out typeId); return typeId == 1138001; } + static bool Is3DsMaxArnoldStandardSurfaceMaterial(MaterialDescription description) { float classIdA; @@ -63,7 +65,7 @@ void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description Vector4 vectorProperty; TexturePropertyDescription textureProperty; - + var shader = AssetDatabase.LoadAssetAtPath(k_ShaderPath); if (shader == null) @@ -94,14 +96,14 @@ void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description { if (hasOpacityMap) { - material.SetTexture("_OPACITY_MAP",opacityMap.texture); + material.SetTexture("_OPACITY_MAP", opacityMap.texture); material.SetFloat("_OPACITY", 1.0f); } else { material.SetFloat("_OPACITY", opacity); } - + material.SetInt("_SrcBlend", 1); material.SetInt("_DstBlend", 10); material.SetFloat("_BlendMode", (float)BlendMode.Alpha); @@ -153,7 +155,7 @@ void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description remapPropertyFloatOrTexture(description, material, "specularRotation", "_SPECULAR_ROTATION"); remapPropertyTexture(description, material, "normalCamera", "_NORMAL_MAP"); - + remapPropertyFloat(description, material, "coat", "_COAT_WEIGHT"); remapPropertyColorOrTexture(description, material, "coatColor", "_COAT_COLOR"); remapPropertyFloatOrTexture(description, material, "coatRoughness", "_COAT_ROUGHNESS"); @@ -161,8 +163,6 @@ void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description remapPropertyTexture(description, material, "coatNormal", "_COAT_NORMAL"); } - - void CreateFrom3DsMaxArnoldStandardSurfaceMaterial(MaterialDescription description, Material material, AnimationClip[] clips) { float floatProperty; @@ -170,7 +170,7 @@ void CreateFrom3DsMaxArnoldStandardSurfaceMaterial(MaterialDescription descripti TexturePropertyDescription textureProperty; var shader = AssetDatabase.LoadAssetAtPath(k_ShaderPath); - + if (shader == null) return; @@ -289,7 +289,7 @@ static void remapPropertyTexture(MaterialDescription description, Material mater } } - static void remapPropertyColorOrTexture3DsMax(MaterialDescription description, Material material, string inPropName, string outPropName,float multiplier = 1.0f) + static void remapPropertyColorOrTexture3DsMax(MaterialDescription description, Material material, string inPropName, string outPropName, float multiplier = 1.0f) { if (description.TryGetProperty(inPropName + ".shader", out TexturePropertyDescription textureProperty)) { @@ -317,7 +317,7 @@ static void remapPropertyFloatOrTexture3DsMax(MaterialDescription description, M } } - static void remapPropertyColorOrTexture(MaterialDescription description, Material material, string inPropName, string outPropName,float multiplier = 1.0f) + static void remapPropertyColorOrTexture(MaterialDescription description, Material material, string inPropName, string outPropName, float multiplier = 1.0f) { if (description.TryGetProperty(inPropName, out TexturePropertyDescription textureProperty)) { @@ -330,6 +330,7 @@ static void remapPropertyColorOrTexture(MaterialDescription description, Materia material.SetColor(outPropName, vectorProperty * multiplier); } } + static void remapPropertyFloatOrTexture(MaterialDescription description, Material material, string inPropName, string outPropName) { if (description.TryGetProperty(inPropName, out TexturePropertyDescription textureProperty)) diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXMaterialDescriptionPostprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXMaterialDescriptionPostprocessor.cs index 090b039d360..fca7bd7c7e5 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXMaterialDescriptionPostprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/FBXMaterialDescriptionPostprocessor.cs @@ -96,7 +96,7 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat material.renderQueue = -1; } - if (description.TryGetProperty("DiffuseColor", out textureProperty) && textureProperty.texture!=null) + if (description.TryGetProperty("DiffuseColor", out textureProperty) && textureProperty.texture != null) { Color diffuseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); if (description.TryGetProperty("DiffuseFactor", out floatProperty)) @@ -150,8 +150,8 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive; } } - else if ( description.TryGetProperty("EmissiveColor", out vectorProperty) && vectorProperty.magnitude > vectorProperty.w - || description.HasAnimationCurve("EmissiveColor.x")) + else if (description.TryGetProperty("EmissiveColor", out vectorProperty) && vectorProperty.magnitude > vectorProperty.w + || description.HasAnimationCurve("EmissiveColor.x")) { if (description.TryGetProperty("EmissiveFactor", out floatProperty)) vectorProperty *= floatProperty; diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/HDIESImporterEditor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/HDIESImporterEditor.cs index c39ce8c59ad..9997b04ebb6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/HDIESImporterEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/HDIESImporterEditor.cs @@ -111,23 +111,23 @@ protected override void Apply() public override bool HasPreviewGUI() { return iesImporterEditor.CommonHasPreviewGUI( - delegate (Camera camera) - { - SetupRenderPipelinePreviewCamera(camera); - }, - delegate (Light light) - { - SetupRenderPipelinePreviewLight(light); - }, - delegate (MeshRenderer wallRenderer) - { - SetupRenderPipelinePreviewWallRenderer(wallRenderer); - }, - delegate (MeshRenderer floorRenderer) - { - SetupRenderPipelinePreviewFloorRenderer(floorRenderer); - } - ); + delegate(Camera camera) + { + SetupRenderPipelinePreviewCamera(camera); + }, + delegate(Light light) + { + SetupRenderPipelinePreviewLight(light); + }, + delegate(MeshRenderer wallRenderer) + { + SetupRenderPipelinePreviewWallRenderer(wallRenderer); + }, + delegate(MeshRenderer floorRenderer) + { + SetupRenderPipelinePreviewFloorRenderer(floorRenderer); + } + ); } /// @@ -147,10 +147,10 @@ public override GUIContent GetPreviewTitle() public override void OnPreviewGUI(Rect r, GUIStyle background) { iesImporterEditor.CommonOnPreviewGUI(r, background, target as IESImporter, - delegate (Light light, SerializedProperty useIESMaximumIntensityProp, SerializedProperty iesMaximumIntensityUnitProp, SerializedProperty iesMaximumIntensityProp) - { - SetupRenderPipelinePreviewLightIntensity(light, useIESMaximumIntensityProp, iesMaximumIntensityUnitProp, iesMaximumIntensityProp); - }); + delegate(Light light, SerializedProperty useIESMaximumIntensityProp, SerializedProperty iesMaximumIntensityUnitProp, SerializedProperty iesMaximumIntensityProp) + { + SetupRenderPipelinePreviewLightIntensity(light, useIESMaximumIntensityProp, iesMaximumIntensityUnitProp, iesMaximumIntensityProp); + }); } /// diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs index aca9bca460b..c02a6a3a649 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs @@ -56,7 +56,7 @@ static void RegisterUpgraderReimport() { bool fileExist = true; // We check the file existence only once to avoid IO operations every frame. - if(s_NeedToCheckProjSettingExistence) + if (s_NeedToCheckProjSettingExistence) { fileExist = System.IO.File.Exists("ProjectSettings/HDRPProjectSettings.asset"); s_NeedToCheckProjSettingExistence = false; @@ -72,9 +72,9 @@ static void RegisterUpgraderReimport() if (!inTestSuite && fileExist && !Application.isBatchMode) { EditorUtility.DisplayDialog("HDRP Material upgrade", "The Materials in your Project were created using an older version of the High Definition Render Pipeline (HDRP)." + - " Unity must upgrade them to be compatible with your current version of HDRP. \n" + - " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n"+ - " Please see the Material upgrade guide in the HDRP documentation for more information.", "Ok"); + " Unity must upgrade them to be compatible with your current version of HDRP. \n" + + " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + + " Please see the Material upgrade guide in the HDRP documentation for more information.", "Ok"); } // When we open a project from scratch all the material have been converted and we don't need to do it two time. @@ -192,17 +192,17 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse // to bump all materials version... static internal Action[] k_Migrations = new Action[] { - StencilRefactor, - ZWriteForTransparent, - RenderQueueUpgrade, - ShaderGraphStack, - MoreMaterialSurfaceOptionFromShaderGraph, - AlphaToMaskUIFix, - MigrateDecalRenderQueue, - ExposedDecalInputsFromShaderGraph, - FixIncorrectEmissiveColorSpace, - ExposeRefraction, - MetallicRemapping, + StencilRefactor, + ZWriteForTransparent, + RenderQueueUpgrade, + ShaderGraphStack, + MoreMaterialSurfaceOptionFromShaderGraph, + AlphaToMaskUIFix, + MigrateDecalRenderQueue, + ExposedDecalInputsFromShaderGraph, + FixIncorrectEmissiveColorSpace, + ExposeRefraction, + MetallicRemapping, }; #region Migrations @@ -310,7 +310,8 @@ static void RenderQueueUpgrade(Material material, HDShaderUtils.ShaderID id) // properties in this tab should be properties from Unlit or PBR cross pipeline shader // that are suppose to be synchronize with the Material during upgrade - readonly static string[] s_ShadergraphStackFloatPropertiesToSynchronize = { + readonly static string[] s_ShadergraphStackFloatPropertiesToSynchronize = + { "_SurfaceType", "_BlendMode", "_DstBlend", @@ -350,11 +351,10 @@ static void ShaderGraphStack(Material material, HDShaderUtils.ShaderID id) bool alphaTest = material.HasProperty("_AlphaCutoffEnable") && material.GetFloat("_AlphaCutoffEnable") > 0.0f; material.renderQueue = isTransparent ? (int)HDRenderQueue.Priority.Transparent : - alphaTest ? (int)HDRenderQueue.Priority.OpaqueAlphaTest : (int)HDRenderQueue.Priority.Opaque; + alphaTest ? (int)HDRenderQueue.Priority.OpaqueAlphaTest : (int)HDRenderQueue.Priority.Opaque; material.SetFloat("_RenderQueueType", isTransparent ? (float)HDRenderQueue.RenderQueueType.Transparent : (float)HDRenderQueue.RenderQueueType.Opaque); } - } } @@ -402,7 +402,7 @@ static void MigrateDecalRenderQueue(Material material, HDShaderUtils.ShaderID id // Take the opportunity to remove _SupportDecals from Unlit as it is not suppose to be here if (HDShaderUtils.IsUnlitHDRPShader(material.shader)) - { + { var serializedMaterial = new SerializedObject(material); if (TryFindProperty(serializedMaterial, kSupportDecals, SerializedType.Integer, out var property, out _, out _)) { @@ -536,7 +536,7 @@ static void ExposedDecalInputsFromShaderGraph(Material material, HDShaderUtils.S const string s_MeshDecalsMAOSStr = "DBufferMesh_MAOS"; const string s_MeshDecals3RTStr = "DBufferMesh_3RT"; const string s_MeshDecalsForwardEmissive = "Mesh_Emissive"; - + material.SetShaderPassEnabled(s_MeshDecalsMStr, true); material.SetShaderPassEnabled(s_MeshDecalsSStr, true); material.SetShaderPassEnabled(s_MeshDecalsMSStr, true); @@ -564,7 +564,7 @@ static void ExposedDecalInputsFromShaderGraph(Material material, HDShaderUtils.S { HDShaderUtils.ResetMaterialKeywords(material); } - } + } static void FixIncorrectEmissiveColorSpace(Material material, HDShaderUtils.ShaderID id) { @@ -615,7 +615,7 @@ static void MetallicRemapping(Material material, HDShaderUtils.ShaderID id) // Lit shaders now have metallic remapping for the mask map if (id == HDShaderUtils.ShaderID.Lit || id == HDShaderUtils.ShaderID.LitTesselation - || id == HDShaderUtils.ShaderID.LayeredLit || id == HDShaderUtils.ShaderID.LayeredLitTesselation) + || id == HDShaderUtils.ShaderID.LayeredLit || id == HDShaderUtils.ShaderID.LayeredLitTesselation) { const string kMetallic = "_Metallic"; if (material.HasProperty(kMetallic) && material.HasProperty(kMetallicRemapMax)) diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/NormalMapFilteringTexturePostprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/NormalMapFilteringTexturePostprocessor.cs index f597a2d1af7..858e47ae84b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/NormalMapFilteringTexturePostprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/NormalMapFilteringTexturePostprocessor.cs @@ -203,7 +203,7 @@ void OnPostprocessTexture(Texture2D texture) for (int x = 0; x < mipWidth; ++x) { Vector3 averageNormal = GetAverageNormal(source, x * texelFootprintW, y * texelFootprintH, - texture.width, texture.height, texelFootprintW, texelFootprintH); + texture.width, texture.height, texelFootprintW, texelFootprintH); int outputPosition = y * mipWidth + x; diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/PhysicalMaterial3DsMaxPreprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/PhysicalMaterial3DsMaxPreprocessor.cs index c55eb7be046..5b43f6fef15 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/PhysicalMaterial3DsMaxPreprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/PhysicalMaterial3DsMaxPreprocessor.cs @@ -181,7 +181,7 @@ void CreateFrom3DsPhysicalMaterial(MaterialDescription description, Material mat Vector4 vectorProperty; TexturePropertyDescription textureProperty; - + var shader = AssetDatabase.LoadAssetAtPath(k_ShaderPath); if (shader == null) return; @@ -290,7 +290,7 @@ static void RemapPropertyTextureOrColor(MaterialDescription description, Materia material.SetTexture(outPropName + "_MAP", textureProperty.texture); material.SetColor(outPropName, Color.white); } - else if(description.TryGetProperty(inPropName, out Vector4 color)) + else if (description.TryGetProperty(inPropName, out Vector4 color)) { material.SetColor(outPropName, color); } @@ -304,7 +304,7 @@ static void RemapPropertyTextureOrFloat(MaterialDescription description, Materia material.SetTexture(outPropName + "_MAP", textureProperty.texture); material.SetFloat(outPropName, 1.0f); } - else if(description.TryGetProperty(inPropName, out float floatProperty)) + else if (description.TryGetProperty(inPropName, out float floatProperty)) { material.SetFloat(outPropName, floatProperty); } diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs index e8ea081b829..9f9295cfac6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ShaderGraphMaterialsUpdater.cs @@ -46,11 +46,11 @@ static void OnShaderGraphSaved(Shader shader, object saveContext) i / (float)(length - 1)); } - // Get Material object + // Get Material object string materialPath = AssetDatabase.GUIDToAssetPath(materialGuids[i]); Material material = AssetDatabase.LoadAssetAtPath(materialPath); - // Reset keywords + // Reset keywords if (material.shader.name == shader.name) HDShaderUtils.ResetMaterialKeywords(material); diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/SketchupMaterialDescriptionPostprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/SketchupMaterialDescriptionPostprocessor.cs index 3c3481b3c9a..fa3f72ddad1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/SketchupMaterialDescriptionPostprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/SketchupMaterialDescriptionPostprocessor.cs @@ -41,23 +41,23 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat TexturePropertyDescription textureProperty; material.SetShaderPassEnabled("DistortionVectors", false); - material.SetShaderPassEnabled("TransparentDepthPrepass",false); + material.SetShaderPassEnabled("TransparentDepthPrepass", false); material.SetShaderPassEnabled("TransparentDepthPostpass", false); material.SetShaderPassEnabled("TransparentBackface", false); material.SetShaderPassEnabled("MOTIONVECTORS", false); - if (description.TryGetProperty("DiffuseMap", out textureProperty) && textureProperty.texture!=null) + if (description.TryGetProperty("DiffuseMap", out textureProperty) && textureProperty.texture != null) { SetMaterialTextureProperty("_BaseColorMap", material, textureProperty); SetMaterialTextureProperty("_MainTex", material, textureProperty); - var color = new Color(1.0f, 1.0f, 1.0f, 1.0f); + var color = new Color(1.0f, 1.0f, 1.0f, 1.0f); material.SetColor("_BaseColor", color); material.SetColor("_Color", color); } - else if (description.TryGetProperty("DiffuseColor", out vectorProperty)) + else if (description.TryGetProperty("DiffuseColor", out vectorProperty)) { - Color diffuseColor = vectorProperty; - diffuseColor = PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor; + Color diffuseColor = vectorProperty; + diffuseColor = PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor; material.SetColor("_BaseColor", diffuseColor); material.SetColor("_Color", diffuseColor); } @@ -90,4 +90,3 @@ static void SetMaterialTextureProperty(string propertyName, Material material, T } } } - diff --git a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ThreeDSMaterialDescriptionPostprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ThreeDSMaterialDescriptionPostprocessor.cs index 862f18a132b..7798419788e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ThreeDSMaterialDescriptionPostprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/ThreeDSMaterialDescriptionPostprocessor.cs @@ -113,4 +113,3 @@ static void SetMaterialTextureProperty(string propertyName, Material material, T } } } - diff --git a/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs b/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs index 5dd02bd5e59..d430005fc9d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs +++ b/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs @@ -35,7 +35,7 @@ public void OnPreprocessBuild(BuildReport report) if (!Application.isBatchMode) { if (!EditorUtility.DisplayDialog("Build Player", - "There is no HDRP Asset provided in GraphicsSettings.\nAre you sure you want to continue?\n Build time can be extremely long without it.", "Ok", "Cancel")) + "There is no HDRP Asset provided in GraphicsSettings.\nAre you sure you want to continue?\n Build time can be extremely long without it.", "Ok", "Cancel")) { throw new BuildFailedException("Stop build on request."); } diff --git a/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs b/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs index b82ee87e056..cc34e397ced 100644 --- a/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs +++ b/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs @@ -15,7 +15,7 @@ class CommonShaderPreprocessor : BaseShaderPreprocessor { public override int Priority => 100; - public CommonShaderPreprocessor() { } + public CommonShaderPreprocessor() {} protected override bool DoShadersStripper(HDRenderPipelineAsset hdrpAsset, Shader shader, ShaderSnippetData snippet, ShaderCompilerData inputData) { @@ -59,11 +59,11 @@ protected override bool DoShadersStripper(HDRenderPipelineAsset hdrpAsset, Shade return true; // If requested by the render pipeline settings, or if we are in a release build, - // don't compile fullscreen debug display variant + // don't compile fullscreen debug display variant bool isFullScreenDebugPass = snippet.passName == "FullScreenDebug"; - if (isFullScreenDebugPass && (!Debug.isDebugBuild || !hdrpAsset.currentPlatformRenderPipelineSettings.supportRuntimeDebugDisplay)) + if (isFullScreenDebugPass && (!Debug.isDebugBuild || !hdrpAsset.currentPlatformRenderPipelineSettings.supportRuntimeDebugDisplay)) return true; - + // Debug Display shader is currently the longest shader to compile, so we allow users to disable it at runtime. // We also don't want it in release build. // However our AOV API rely on several debug display shader. In case AOV API is requested at runtime (like for the Graphics Compositor) @@ -136,7 +136,7 @@ protected override bool DoShadersStripper(HDRenderPipelineAsset hdrpAsset, Shade // Strip the decal prepass variant when decals are disabled if (inputData.shaderKeywordSet.IsEnabled(m_WriteDecalBuffer) && - !(hdrpAsset.currentPlatformRenderPipelineSettings.supportDecals && hdrpAsset.currentPlatformRenderPipelineSettings.supportDecalLayers)) + !(hdrpAsset.currentPlatformRenderPipelineSettings.supportDecals && hdrpAsset.currentPlatformRenderPipelineSettings.supportDecalLayers)) return true; // If decal support, remove unused variant @@ -241,17 +241,17 @@ public void Dispose() void LogShaderVariants(ComputeShader shader, string kernelName, ShaderVariantLogLevel logLevel, uint prevVariantsCount, uint currVariantsCount) { - // We cannot yet differentiate whether a compute shader is HDRP specific or not. + // We cannot yet differentiate whether a compute shader is HDRP specific or not. if (logLevel == ShaderVariantLogLevel.AllShaders || logLevel == ShaderVariantLogLevel.OnlyHDRPShaders) { float percentageCurrent = ((float)currVariantsCount / prevVariantsCount) * 100.0f; float percentageTotal = ((float)m_TotalVariantsOutputCount / m_TotalVariantsInputCount) * 100.0f; string result = string.Format("STRIPPING: {0} (kernel: {1}) -" + - " Remaining shader variants = {2}/{3} = {4}% - Total = {5}/{6} = {7}%", - shader.name, kernelName, currVariantsCount, - prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount, - percentageTotal); + " Remaining shader variants = {2}/{3} = {4}% - Total = {5}/{6} = {7}%", + shader.name, kernelName, currVariantsCount, + prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount, + percentageTotal); Debug.Log(result); } } @@ -385,15 +385,15 @@ void LogShaderVariants(Shader shader, ShaderSnippetData snippetData, ShaderVaria float percentageTotal = ((float)m_TotalVariantsOutputCount / m_TotalVariantsInputCount) * 100.0f; string result = string.Format("STRIPPING: {0} ({1} pass) ({2}) -" + - " Remaining shader variants = {3}/{4} = {5}% - Total = {6}/{7} = {8}%", - shader.name, snippetData.passName, snippetData.shaderType.ToString(), currVariantsCount, - prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount, - percentageTotal); + " Remaining shader variants = {3}/{4} = {5}% - Total = {6}/{7} = {8}%", + shader.name, snippetData.passName, snippetData.shaderType.ToString(), currVariantsCount, + prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount, + percentageTotal); Debug.Log(result); } } - struct ExportShaderStrip: System.IDisposable + struct ExportShaderStrip : System.IDisposable { bool m_ExportLog; string m_OutFile; @@ -432,7 +432,7 @@ public void Dispose() if (m_ExportLog) { try - { + { System.IO.File.AppendAllText( m_OutFile, $"{{ \"shader\": \"{m_Shader?.name}\", \"pass\": \"{m_Snippet.passName ?? string.Empty}\", \"passType\": \"{m_Snippet.passType}\", \"shaderType\": \"{m_Snippet.shaderType}\", \"variantOut\": \"{m_InputData.Count}\", \"totalVariantIn\": \"{m_PreProcess?.m_TotalVariantsInputCount}\", \"totalVariantOut\": \"{m_PreProcess?.m_TotalVariantsOutputCount}\" }}\r\n" @@ -460,7 +460,6 @@ public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList a.allowShaderVariantStripping) ) + if (hdPipelineAssets.Count == 0 || !hdPipelineAssets.Any(a => a.allowShaderVariantStripping)) return; var inputShaderVariantCount = inputData.Count; - for (int i = 0; i < inputShaderVariantCount; ) + for (int i = 0; i < inputShaderVariantCount;) { ShaderCompilerData input = inputData[i]; @@ -489,7 +488,7 @@ public void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList inputDataList) + if (inputData is List inputDataList) inputDataList.RemoveRange(inputShaderVariantCount, inputDataList.Count - inputShaderVariantCount); else for (int i = inputData.Count - 1; i >= inputShaderVariantCount; --i) @@ -602,7 +601,7 @@ static void GetAllValidHDRPAssets() { var curGUID = guidRenderPipelineAssets[i]; var curPath = AssetDatabase.GUIDToAssetPath(curGUID); - if(depsHash.Contains(curPath)) + if (depsHash.Contains(curPath)) { _hdrpAssets.Add(AssetDatabase.LoadAssetAtPath(curPath)); } @@ -611,14 +610,14 @@ static void GetAllValidHDRPAssets() // Add the HDRP assets that are in the Resources folders. _hdrpAssets.AddRange( Resources.FindObjectsOfTypeAll() - .Where( a => !_hdrpAssets.Contains(a) ) - ); + .Where(a => !_hdrpAssets.Contains(a)) + ); // Add the HDRP assets that are labeled to be included _hdrpAssets.AddRange( AssetDatabase.FindAssets("t:HDRenderPipelineAsset l:" + HDEditorUtils.HDRPAssetBuildLabel) .Select(s => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(s))) - ); + ); // Discard duplicate entries using (HashSetPool.Get(out var uniques)) diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionLayerUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionLayerUI.Drawers.cs index b05b2cd3d38..7fa245af7a0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionLayerUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionLayerUI.Drawers.cs @@ -39,14 +39,14 @@ static partial class Styles static public float infoBoxIconWidth = 100; } - static bool s_AsyncCompileState = false; - static bool s_HasStartedCompiling = false; + static bool s_AsyncCompileState = false; + static bool s_HasStartedCompiling = false; public static void DrawItemInList(Rect rect, SerializedCompositionLayer serialized, RenderTexture thumbnail, float aspectRatio, bool isAlphaEnbaled) { bool isCameraStack = serialized.outTarget.intValue == (int)CompositorLayer.OutputTarget.CameraStack; - // Compute the desired indentation + // Compute the desired indentation { const float listBorder = 2.0f; rect.x = isCameraStack ? rect.x + CompositorStyle.k_ListItemStackPading + listBorder : rect.x + listBorder; @@ -71,8 +71,8 @@ public static void DrawItemInList(Rect rect, SerializedCompositionLayer serializ if (isAlphaEnbaled && (thumbnail.format == RenderTextureFormat.ARGBHalf - || thumbnail.format == RenderTextureFormat.ARGBFloat - || thumbnail.format == RenderTextureFormat.ARGB64)) + || thumbnail.format == RenderTextureFormat.ARGBFloat + || thumbnail.format == RenderTextureFormat.ARGB64)) { EditorGUI.DrawTextureAlpha(previewRect, thumbnail); rect.x += previewRect.width + CompositorStyle.k_ThumbnailSpacing; @@ -139,7 +139,7 @@ public static void DrawOutputLayerProperties(Rect rect, SerializedCompositionLay EditorGUI.PropertyField(rect, serializedProperties.outputRenderer, Styles.k_OutputRenderer); rect.y += CompositorStyle.k_Spacing; - EditorGUI.PropertyField(rect, serializedProperties.aovBitmask, Styles.k_AOVs); + EditorGUI.PropertyField(rect, serializedProperties.aovBitmask, Styles.k_AOVs); rect.y += CompositorStyle.k_Spacing; if (serializedProperties.aovBitmask.intValue != 0) @@ -233,7 +233,7 @@ public static void DrawStackedLayerProperties(Rect rect, SerializedCompositionLa EditorGUI.PropertyField(rect, serializedProperties.clearAlpha, Styles.k_ClearAlpha); rect.y += 1.0f * CompositorStyle.k_Spacing; - // Draw a min/max slider for tha alpha range + // Draw a min/max slider for tha alpha range { const float spacing = 5; var labelRect = new Rect(rect.x, rect.y, EditorGUIUtility.labelWidth, rect.height); diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.Styles.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.Styles.cs index fb4a5f1afa9..3f91497af2a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.Styles.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.Styles.cs @@ -16,7 +16,7 @@ static internal class CompositorStyle internal static readonly int k_IconVerticalOffset = 5; // used to center the icons vertically internal static readonly int k_LabelVerticalOffset = 6; // used to center the labels vertically - + internal static readonly int k_IconSize = 28; internal static readonly int k_ListItemPading = 4; diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.cs index 016392ee526..e2fe265363a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionManagerEditor.cs @@ -80,7 +80,7 @@ public bool CacheSerializedObjects() { return false; } - + m_SerializedLayerProperties = new List(); m_SerializedShaderProperties = new List(); @@ -193,10 +193,10 @@ public override void OnInspectorGUI() var serializedLayerList = m_SerializedProperties.layerList; m_layerList = new ReorderableList(m_SerializedProperties.compositorSO, serializedLayerList, true, false, true, true); - // Pre-select the "default" item in the list (used to remember the last selected item when re-creating the Editor) + // Pre-select the "default" item in the list (used to remember the last selected item when re-creating the Editor) if (defaultSelection >= 0) { - m_layerList.index = Math.Min(defaultSelection, m_layerList.count-1); + m_layerList.index = Math.Min(defaultSelection, m_layerList.count - 1); } m_layerList.drawHeaderCallback = (Rect rect) => @@ -221,7 +221,7 @@ public override void OnInspectorGUI() if (!m_compositionManager.ValidateLayerListOrder(oldIndex, newIndex)) { // The new position is invalid, so set the currently selected layer to the old/starting position s - m_layerList.index = oldIndex; + m_layerList.index = oldIndex; } }; @@ -335,7 +335,7 @@ public override void OnInspectorGUI() m_compositionManager.UpdateLayerSetup(); } } - + void DrawLayerProperties(Rect rect, SerializedCompositionLayer serializedProperties, int layerIndex, RenderTexture preview = null) { if (serializedProperties == null) @@ -366,7 +366,7 @@ void DrawLayerProperties(Rect rect, SerializedCompositionLayer serializedPropert m_filterList.drawElementCallback = (Rect r, int index, bool isActive, bool isFocused) => { if (index < m_SerializedLayerProperties[m_layerList.index].filterList.Count) - { + { var serializedFilter = m_SerializedLayerProperties[m_layerList.index].filterList[index]; CompositionFilterUI.Draw(r, serializedFilter); } @@ -399,8 +399,5 @@ void DrawLayerProperties(Rect rect, SerializedCompositionLayer serializedPropert CompositionLayerUI.DrawStackedLayerProperties(rect, serializedProperties, m_filterList); } } - } } - - diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionUtils.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionUtils.cs index 3ea545e1d62..0be987b2a8f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionUtils.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositionUtils.cs @@ -47,7 +47,7 @@ static public void LoadDefaultCompositionGraph(CompositionManager compositor) profilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(fullpath), System.IO.Path.GetFileNameWithoutExtension(compositor.shader.name)) + ".asset"; profilePath = AssetDatabase.GenerateUniqueAssetPath(profilePath); } - + bool ret2 = AssetDatabase.CopyAsset(HDUtils.GetHDRenderPipelinePath() + "Runtime/Compositor/ShaderGraphs/DefaultCompositionGraph.asset", profilePath); if (ret2 == false) { @@ -82,11 +82,11 @@ static public void SetDefaultCamera(CompositionManager compositor) static public void SetDefaultLayers(CompositionManager compositor) { - for (int i = compositor.numLayers - 1; i>=0; --i) + for (int i = compositor.numLayers - 1; i >= 0; --i) { if (compositor.layers[i].outputTarget == CompositorLayer.OutputTarget.CompositorLayer) { - if ((i+i < compositor.numLayers - 1) && (compositor.layers[i+1].outputTarget == CompositorLayer.OutputTarget.CameraStack)) + if ((i + i < compositor.numLayers - 1) && (compositor.layers[i + 1].outputTarget == CompositorLayer.OutputTarget.CameraStack)) { continue; } @@ -99,7 +99,7 @@ static public void LoadOrCreateCompositionProfileAsset(CompositionManager compos { var shader = compositor.shader; - if(shader == null) + if (shader == null) { compositor.profile = null; return; @@ -127,7 +127,7 @@ static public void LoadOrCreateCompositionProfileAsset(CompositionManager compos } compositor.profile = newProfile; - // [case 1265631] The profile asset is auto-generated by the compositor, so do not allow the users to manually edit/reset the values in the asset because it might break things. + // [case 1265631] The profile asset is auto-generated by the compositor, so do not allow the users to manually edit/reset the values in the asset because it might break things. compositor.profile.hideFlags = HideFlags.NotEditable; } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositorWindow.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositorWindow.cs index 6db97847a12..f027d2fced5 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositorWindow.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/CompositorWindow.cs @@ -54,7 +54,7 @@ void Update() Repaint(); // [case 1266216] Ensure the game view gets repainted a few times per second even when we are not in play mode. - // This ensures that we will not always display the first frame, which might have some artifacts for effects that require temporal data + // This ensures that we will not always display the first frame, which might have some artifacts for effects that require temporal data if (!Application.isPlaying) { CompositionManager compositor = CompositionManager.GetInstance(); @@ -68,7 +68,6 @@ void Update() compositor.Repaint(); } } - } } } @@ -128,7 +127,7 @@ void OnGUI() { if (compositor.outputCamera) { - if(compositor.outputCamera.name == CompositionUtils.k_DefaultCameraName) + if (compositor.outputCamera.name == CompositionUtils.k_DefaultCameraName) { var cameraData = compositor.outputCamera.GetComponent(); if (cameraData != null) @@ -140,7 +139,7 @@ void OnGUI() EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); } } - + CoreUtils.Destroy(compositor); return; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/SerializedCompositionLayer.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/SerializedCompositionLayer.cs index 1f08919219f..2c398d9e43e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/SerializedCompositionLayer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/SerializedCompositionLayer.cs @@ -76,7 +76,7 @@ public float GetPropertiesHeight() { if (outTarget.intValue != (int)CompositorLayer.OutputTarget.CameraStack) { - return + return EditorGUI.GetPropertyHeight(outputRenderer, null) + EditorGUI.GetPropertyHeight(colorFormat, null) + EditorGUI.GetPropertyHeight(aovBitmask, null) + @@ -110,15 +110,15 @@ public float GetPropertiesHeight() public float GetListItemHeight() { - int pading = 10; - if (outTarget.intValue != (int)CompositorLayer.OutputTarget.CameraStack) - { - return CompositorStyle.k_ThumbnailSize + pading; - } - else - { - return EditorGUIUtility.singleLineHeight + pading; - } + int pading = 10; + if (outTarget.intValue != (int)CompositorLayer.OutputTarget.CameraStack) + { + return CompositorStyle.k_ThumbnailSize + pading; + } + else + { + return EditorGUIUtility.singleLineHeight + pading; } } + } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Compositor/ShaderPropertyUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/Compositor/ShaderPropertyUI.Drawers.cs index 7689f700e34..73478e17746 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Compositor/ShaderPropertyUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Compositor/ShaderPropertyUI.Drawers.cs @@ -24,52 +24,52 @@ public static void Draw(List propertyList) Draw(property); } } - + public static void Draw(SerializedShaderProperty prop) { - int columnWidth = (int)EditorGUIUtility.labelWidth; // Set a fixed length for all labels, so everything in the UI is nicely aligned + int columnWidth = (int)EditorGUIUtility.labelWidth; // Set a fixed length for all labels, so everything in the UI is nicely aligned var propertNameWithTooltip = new GUIContent(prop.propertyName.stringValue, prop.propertyName.stringValue); switch ((ShaderPropertyType)prop.propertyType.intValue) { case ShaderPropertyType.Range: - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); - Vector2 rangeLimits = prop.rangeLimits.vector2Value; - float val = EditorGUILayout.Slider(prop.propertyValue.vector4Value.x, rangeLimits.x, rangeLimits.y); - prop.propertyValue.vector4Value = new Vector4(val, 0, 0, 0); - EditorGUILayout.EndHorizontal(); - } - break; + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); + Vector2 rangeLimits = prop.rangeLimits.vector2Value; + float val = EditorGUILayout.Slider(prop.propertyValue.vector4Value.x, rangeLimits.x, rangeLimits.y); + prop.propertyValue.vector4Value = new Vector4(val, 0, 0, 0); + EditorGUILayout.EndHorizontal(); + } + break; case ShaderPropertyType.Float: - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); - float val = EditorGUILayout.FloatField(prop.propertyValue.vector4Value.x); - prop.propertyValue.vector4Value = new Vector4(val, 0, 0, 0); - EditorGUILayout.EndHorizontal(); - } - break; + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); + float val = EditorGUILayout.FloatField(prop.propertyValue.vector4Value.x); + prop.propertyValue.vector4Value = new Vector4(val, 0, 0, 0); + EditorGUILayout.EndHorizontal(); + } + break; case ShaderPropertyType.Vector: - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); - Vector4 val = EditorGUILayout.Vector4Field(GUIContent.none, prop.propertyValue.vector4Value); - prop.propertyValue.vector4Value = val; - EditorGUILayout.EndHorizontal(); - } - break; + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); + Vector4 val = EditorGUILayout.Vector4Field(GUIContent.none, prop.propertyValue.vector4Value); + prop.propertyValue.vector4Value = val; + EditorGUILayout.EndHorizontal(); + } + break; case ShaderPropertyType.Color: - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); - Color val = prop.propertyValue.vector4Value; - val = EditorGUILayout.ColorField(GUIContent.none, val); - prop.propertyValue.vector4Value = val; - EditorGUILayout.EndHorizontal(); - } - break; + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.LabelField(propertNameWithTooltip, GUILayout.Width(columnWidth)); + Color val = prop.propertyValue.vector4Value; + val = EditorGUILayout.ColorField(GUIContent.none, val); + prop.propertyValue.vector4Value = val; + EditorGUILayout.EndHorizontal(); + } + break; } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/HDAnalytics.cs b/com.unity.render-pipelines.high-definition/Editor/HDAnalytics.cs index b67680d7672..974b86337c5 100644 --- a/com.unity.render-pipelines.high-definition/Editor/HDAnalytics.cs +++ b/com.unity.render-pipelines.high-definition/Editor/HDAnalytics.cs @@ -15,7 +15,7 @@ class HDAnalytics : IPostprocessBuildWithReport const int k_MaxNumberOfElements = 1000; const string k_VendorKey = "unity.hdrp"; const string k_EventName = "uHDRPUsage"; - + public int callbackOrder { get; } struct EventData @@ -58,7 +58,6 @@ public static void SendEvent() EditorAnalytics.SendEventWithLimit(k_EventName, data); } - // Helpers to get changed settings as JSON static Dictionary DiffSettings(object a, object b) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/AmbientOcclusionEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/AmbientOcclusionEditor.cs index 9f82f0998b7..b37cb1d76c9 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/AmbientOcclusionEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/AmbientOcclusionEditor.cs @@ -117,7 +117,7 @@ public override void OnInspectorGUI() using (new HDEditorUtils.IndentScope()) { - if(!m_TemporalAccumulation.value.boolValue) + if (!m_TemporalAccumulation.value.boolValue) { PropertyField(m_DirectionCount, EditorGUIUtility.TrTextContent("Direction Count", "Number of directions searched for occlusion at each each pixel.")); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileOverrideEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileOverrideEditor.cs index 4f0ee67a00b..0adb288ce13 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileOverrideEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileOverrideEditor.cs @@ -70,7 +70,7 @@ void FillProfileListWithScene() var profile = GetMaterialDiffusionProfile(mat); if (profiles.Count == DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT - 1) - break ; + break; if (profile != null) profiles.Add(profile); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightExplorerExtension.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightExplorerExtension.cs index dbe1f3ae163..27f04b9b5ac 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightExplorerExtension.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightExplorerExtension.cs @@ -124,9 +124,9 @@ public override LightingExplorerTab[] GetContentTabs() protected virtual UnityEngine.Object[] GetHDLights() { #if UNITY_2020_1_OR_NEWER - var lights = Resources.FindObjectsOfTypeAll(); + var lights = Resources.FindObjectsOfTypeAll(); #else - var lights = UnityEngine.Object.FindObjectsOfType(); + var lights = UnityEngine.Object.FindObjectsOfType(); #endif foreach (Light light in lights) @@ -146,9 +146,9 @@ protected virtual UnityEngine.Object[] GetHDLights() protected virtual UnityEngine.Object[] GetHDReflectionProbes() { #if UNITY_2020_1_OR_NEWER - var reflectionProbes = Resources.FindObjectsOfTypeAll(); + var reflectionProbes = Resources.FindObjectsOfTypeAll(); #else - var reflectionProbes = UnityEngine.Object.FindObjectsOfType(); + var reflectionProbes = UnityEngine.Object.FindObjectsOfType(); #endif foreach (ReflectionProbe probe in reflectionProbes) @@ -162,18 +162,18 @@ protected virtual UnityEngine.Object[] GetHDReflectionProbes() protected virtual UnityEngine.Object[] GetPlanarReflections() { #if UNITY_2020_1_OR_NEWER - return Resources.FindObjectsOfTypeAll(); + return Resources.FindObjectsOfTypeAll(); #else - return UnityEngine.Object.FindObjectsOfType(); + return UnityEngine.Object.FindObjectsOfType(); #endif } protected virtual UnityEngine.Object[] GetVolumes() { #if UNITY_2020_1_OR_NEWER - var volumes = Resources.FindObjectsOfTypeAll(); + var volumes = Resources.FindObjectsOfTypeAll(); #else - var volumes = UnityEngine.Object.FindObjectsOfType(); + var volumes = UnityEngine.Object.FindObjectsOfType(); #endif foreach (var volume in volumes) @@ -198,7 +198,7 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, HDStyles.Name, null, 200), // 1: Name new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.Type, "m_Type", 100, (r, prop, dep) => // 2: Type { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -217,42 +217,42 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() } EditorGUI.EndProperty(); }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return ((int)lLightData.type).CompareTo((int)rLightData.type); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return ((int)lLightData.type).CompareTo((int)rLightData.type); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObjects(new Object[] { target.serializedObject.targetObject, tLightData }, "Changed light type"); - tLightData.type = sLightData.type; - }), + Undo.RecordObjects(new Object[] { target.serializedObject.targetObject, tLightData }, "Changed light type"); + tLightData.type = sLightData.type; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.Mode, "m_Lightmapping", 90), // 3: Mixed mode new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.Range, "m_Range", 60), // 4: Range new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Color, HDStyles.Color, "m_Color", 60), // 5: Color new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.ColorTemperatureMode, "m_UseColorTemperature", 150), // 6: Color Temperature Mode new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.ColorTemperature, "m_ColorTemperature", 120, (r, prop, dep) => // 7: Color Temperature { - using(new EditorGUI.DisabledScope(!prop.serializedObject.FindProperty("m_UseColorTemperature").boolValue)) + using (new EditorGUI.DisabledScope(!prop.serializedObject.FindProperty("m_UseColorTemperature").boolValue)) { EditorGUI.PropertyField(r, prop, GUIContent.none); } }, (lprop, rprop) => - { - float lTemp = lprop.serializedObject.FindProperty("m_UseColorTemperature").boolValue ? lprop.floatValue : 0.0f; - float rTemp = rprop.serializedObject.FindProperty("m_UseColorTemperature").boolValue ? rprop.floatValue : 0.0f; + { + float lTemp = lprop.serializedObject.FindProperty("m_UseColorTemperature").boolValue ? lprop.floatValue : 0.0f; + float rTemp = rprop.serializedObject.FindProperty("m_UseColorTemperature").boolValue ? rprop.floatValue : 0.0f; - return lTemp.CompareTo(rTemp); - }), + return lTemp.CompareTo(rTemp); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.Intensity, "m_Intensity", 60, (r, prop, dep) => // 8: Intensity { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -270,25 +270,25 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() } EditorGUI.EndProperty(); }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return ((float)lLightData.intensity).CompareTo((float)rLightData.intensity); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return ((float)lLightData.intensity).CompareTo((float)rLightData.intensity); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObjects(new Object[] { target.serializedObject.targetObject, tLightData }, "Changed light intensity"); - tLightData.intensity = sLightData.intensity; - }), + Undo.RecordObjects(new Object[] { target.serializedObject.targetObject, tLightData }, "Changed light intensity"); + tLightData.intensity = sLightData.intensity; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.Unit, "m_Intensity", 70, (r, prop, dep) => // 9: Unit { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -304,22 +304,22 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() lightData.lightUnit = unit; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return ((int)lLightData.lightUnit).CompareTo((int)rLightData.lightUnit); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return ((int)lLightData.lightUnit).CompareTo((int)rLightData.lightUnit); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed light unit"); - tLightData.lightUnit = sLightData.lightUnit; - }), + Undo.RecordObject(tLightData, "Changed light unit"); + tLightData.lightUnit = sLightData.lightUnit; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.IndirectMultiplier, "m_BounceIntensity", 115), // 10: Indirect multiplier new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.Shadows, "m_Shadows.m_Type", 60, (r, prop, dep) => // 11: Shadows { @@ -332,7 +332,7 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.ContactShadowsLevel, "m_Shadows.m_Type", 115, (r, prop, dep) => // 12: Contact Shadows level { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -340,7 +340,7 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() var useContactShadow = lightData.useContactShadow; EditorGUI.BeginChangeCheck(); - var (level, useOverride) = SerializedScalableSettingValueUI.LevelFieldGUI(r, GUIContent.none, ScalableSettingSchema.GetSchemaOrNull(ScalableSettingSchemaId.With3Levels), useContactShadow.level, useContactShadow.useOverride); + var(level, useOverride) = SerializedScalableSettingValueUI.LevelFieldGUI(r, GUIContent.none, ScalableSettingSchema.GetSchemaOrNull(ScalableSettingSchemaId.With3Levels), useContactShadow.level, useContactShadow.useOverride); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(lightData, "Changed contact shadows"); @@ -348,26 +348,26 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() useContactShadow.useOverride = useOverride; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return (lLightData.useContactShadow.useOverride ? -1 : (int)lLightData.useContactShadow.level).CompareTo(rLightData.useContactShadow.useOverride ? -1 : (int)rLightData.useContactShadow.level); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return (lLightData.useContactShadow.useOverride ? -1 : (int)lLightData.useContactShadow.level).CompareTo(rLightData.useContactShadow.useOverride ? -1 : (int)rLightData.useContactShadow.level); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed contact shadows"); - tLightData.useContactShadow.level = sLightData.useContactShadow.level; - tLightData.useContactShadow.useOverride = sLightData.useContactShadow.useOverride; - }), + Undo.RecordObject(tLightData, "Changed contact shadows"); + tLightData.useContactShadow.level = sLightData.useContactShadow.level; + tLightData.useContactShadow.useOverride = sLightData.useContactShadow.useOverride; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.ContactShadowsValue, "m_Shadows.m_Type", 115, (r, prop, dep) => // 13: Contact Shadows override { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -398,39 +398,39 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() } } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; - var lUseContactShadow = lLightData.useContactShadow; - var rUseContactShadow = rLightData.useContactShadow; + var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; + var lUseContactShadow = lLightData.useContactShadow; + var rUseContactShadow = rLightData.useContactShadow; - bool lEnabled = lUseContactShadow.useOverride ? lUseContactShadow.@override : HDAdditionalLightData.ScalableSettings.UseContactShadow(hdrp)[lUseContactShadow.level]; - bool rEnabled = rUseContactShadow.useOverride ? rUseContactShadow.@override : HDAdditionalLightData.ScalableSettings.UseContactShadow(hdrp)[rUseContactShadow.level]; + bool lEnabled = lUseContactShadow.useOverride ? lUseContactShadow.@override : HDAdditionalLightData.ScalableSettings.UseContactShadow(hdrp)[lUseContactShadow.level]; + bool rEnabled = rUseContactShadow.useOverride ? rUseContactShadow.@override : HDAdditionalLightData.ScalableSettings.UseContactShadow(hdrp)[rUseContactShadow.level]; - return lEnabled.CompareTo(rEnabled); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return lEnabled.CompareTo(rEnabled); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; - var tUseContactShadow = tLightData.useContactShadow; - var sUseContactShadow = sLightData.useContactShadow; + var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; + var tUseContactShadow = tLightData.useContactShadow; + var sUseContactShadow = sLightData.useContactShadow; - if (tUseContactShadow.useOverride) - { - Undo.RecordObject(tLightData, "Changed contact shadow override"); - tUseContactShadow.@override = sUseContactShadow.@override; - } - }), + if (tUseContactShadow.useOverride) + { + Undo.RecordObject(tLightData, "Changed contact shadow override"); + tUseContactShadow.@override = sUseContactShadow.@override; + } + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.ShadowResolutionLevel, "m_Intensity", 130, (r, prop, dep) => // 14: Shadow Resolution level { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -439,7 +439,7 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() var shadowResolution = lightData.shadowResolution; EditorGUI.BeginChangeCheck(); - var (level, useOverride) = SerializedScalableSettingValueUI.LevelFieldGUI(r, GUIContent.none, ScalableSettingSchema.GetSchemaOrNull(ScalableSettingSchemaId.With4Levels), shadowResolution.level, shadowResolution.useOverride); + var(level, useOverride) = SerializedScalableSettingValueUI.LevelFieldGUI(r, GUIContent.none, ScalableSettingSchema.GetSchemaOrNull(ScalableSettingSchemaId.With4Levels), shadowResolution.level, shadowResolution.useOverride); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(lightData, "Changed contact shadow resolution"); @@ -447,28 +447,28 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() shadowResolution.useOverride = useOverride; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return ((int)lLightData.shadowResolution.level).CompareTo((int)rLightData.shadowResolution.level); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return ((int)lLightData.shadowResolution.level).CompareTo((int)rLightData.shadowResolution.level); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed contact shadow resolution"); - tLightData.shadowResolution.level = sLightData.shadowResolution.level; - tLightData.shadowResolution.useOverride = sLightData.shadowResolution.useOverride; - }), + Undo.RecordObject(tLightData, "Changed contact shadow resolution"); + tLightData.shadowResolution.level = sLightData.shadowResolution.level; + tLightData.shadowResolution.useOverride = sLightData.shadowResolution.useOverride; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, HDStyles.ShadowResolutionValue, "m_Intensity", 130, (r, prop, dep) => // 15: Shadow resolution override { var hdrp = HDRenderPipeline.currentAsset; - if(!TryGetAdditionalLightData(prop, out var lightData, out var light) || hdrp == null) + if (!TryGetAdditionalLightData(prop, out var lightData, out var light) || hdrp == null) { EditorGUI.LabelField(r, "--"); return; @@ -498,41 +498,41 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() } } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData, out var lLight); - TryGetAdditionalLightData(rprop, out var rLightData, out var rLight); + { + TryGetAdditionalLightData(lprop, out var lLightData, out var lLight); + TryGetAdditionalLightData(rprop, out var rLightData, out var rLight); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; - var lShadowResolution = lLightData.shadowResolution; - var rShadowResolution = rLightData.shadowResolution; - var lLightShape = lLightData.type; - var rLightShape = rLightData.type; + var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; + var lShadowResolution = lLightData.shadowResolution; + var rShadowResolution = rLightData.shadowResolution; + var lLightShape = lLightData.type; + var rLightShape = rLightData.type; - int lResolution = lShadowResolution.useOverride ? lShadowResolution.@override : (hdrp == null ? -1 : HDLightUI.ScalableSettings.ShadowResolution(lLightShape, hdrp)[lShadowResolution.level]); - int rResolution = rShadowResolution.useOverride ? rShadowResolution.@override : (hdrp == null ? -1 : HDLightUI.ScalableSettings.ShadowResolution(rLightShape, hdrp)[rShadowResolution.level]); + int lResolution = lShadowResolution.useOverride ? lShadowResolution.@override : (hdrp == null ? -1 : HDLightUI.ScalableSettings.ShadowResolution(lLightShape, hdrp)[lShadowResolution.level]); + int rResolution = rShadowResolution.useOverride ? rShadowResolution.@override : (hdrp == null ? -1 : HDLightUI.ScalableSettings.ShadowResolution(rLightShape, hdrp)[rShadowResolution.level]); - return lResolution.CompareTo(rResolution); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return lResolution.CompareTo(rResolution); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; - var tShadowResolution = tLightData.shadowResolution; - var sShadowResolution = sLightData.shadowResolution; + var hdrp = GraphicsSettings.currentRenderPipeline as HDRenderPipelineAsset; + var tShadowResolution = tLightData.shadowResolution; + var sShadowResolution = sLightData.shadowResolution; - if (tShadowResolution.useOverride) - { - Undo.RecordObject(tLightData, "Changed shadow resolution override"); - tShadowResolution.@override = sShadowResolution.@override; - } - }), + if (tShadowResolution.useOverride) + { + Undo.RecordObject(tLightData, "Changed shadow resolution override"); + tShadowResolution.@override = sShadowResolution.@override; + } + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.AffectDiffuse, "m_Intensity", 95, (r, prop, dep) => // 16: Affect Diffuse { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -548,25 +548,25 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() lightData.affectDiffuse = affectDiffuse; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return lLightData.affectDiffuse.CompareTo(rLightData.affectDiffuse); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return lLightData.affectDiffuse.CompareTo(rLightData.affectDiffuse); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed affects diffuse"); - tLightData.affectDiffuse = sLightData.affectDiffuse; - }), + Undo.RecordObject(tLightData, "Changed affects diffuse"); + tLightData.affectDiffuse = sLightData.affectDiffuse; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.AffectSpecular, "m_Intensity", 100, (r, prop, dep) => // 17: Affect Specular { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -582,25 +582,25 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() lightData.affectSpecular = affectSpecular; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return lLightData.affectSpecular.CompareTo(rLightData.affectSpecular); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return lLightData.affectSpecular.CompareTo(rLightData.affectSpecular); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed affects specular"); - tLightData.affectSpecular = sLightData.affectSpecular; - }), + Undo.RecordObject(tLightData, "Changed affects specular"); + tLightData.affectSpecular = sLightData.affectSpecular; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.FadeDistance, "m_Intensity", 95, (r, prop, dep) => // 18: Fade Distance { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -616,25 +616,25 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() lightData.fadeDistance = fadeDistance; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return lLightData.fadeDistance.CompareTo(rLightData.fadeDistance); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return lLightData.fadeDistance.CompareTo(rLightData.fadeDistance); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed light fade distance"); - tLightData.fadeDistance = sLightData.fadeDistance; - }), + Undo.RecordObject(tLightData, "Changed light fade distance"); + tLightData.fadeDistance = sLightData.fadeDistance; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.ShadowFadeDistance, "m_Intensity", 145, (r, prop, dep) => // 19: Shadow Fade Distance { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -650,27 +650,27 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() lightData.shadowFadeDistance = shadowFadeDistance; } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return lLightData.shadowFadeDistance.CompareTo(rLightData.shadowFadeDistance); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return lLightData.shadowFadeDistance.CompareTo(rLightData.shadowFadeDistance); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed light shadow fade distance"); - tLightData.shadowFadeDistance = sLightData.shadowFadeDistance; - }), + Undo.RecordObject(tLightData, "Changed light shadow fade distance"); + tLightData.shadowFadeDistance = sLightData.shadowFadeDistance; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Custom, HDStyles.LightLayer, "m_RenderingLayerMask", 145, (r, prop, dep) => // 20: Light Layer { using (new EditorGUI.DisabledScope(!HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.supportLightLayers)) { - if(!TryGetAdditionalLightData(prop, out var lightData)) + if (!TryGetAdditionalLightData(prop, out var lightData)) { EditorGUI.LabelField(r, "--"); return; @@ -687,22 +687,22 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() } } }, (lprop, rprop) => - { - TryGetAdditionalLightData(lprop, out var lLightData); - TryGetAdditionalLightData(rprop, out var rLightData); + { + TryGetAdditionalLightData(lprop, out var lLightData); + TryGetAdditionalLightData(rprop, out var rLightData); - if (IsNullComparison(lLightData, rLightData, out var order)) - return order; + if (IsNullComparison(lLightData, rLightData, out var order)) + return order; - return ((int)lLightData.lightlayersMask).CompareTo((int)rLightData.lightlayersMask); - }, (target, source) => - { - if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) - return; + return ((int)lLightData.lightlayersMask).CompareTo((int)rLightData.lightlayersMask); + }, (target, source) => + { + if (!TryGetAdditionalLightData(target, out var tLightData) || !TryGetAdditionalLightData(source, out var sLightData)) + return; - Undo.RecordObject(tLightData, "Changed light layer"); - tLightData.lightlayersMask = sLightData.lightlayersMask; - }), + Undo.RecordObject(tLightData, "Changed light layer"); + tLightData.lightlayersMask = sLightData.lightlayersMask; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Custom, HDStyles.IsPrefab, "m_Intensity", 120, (r, prop, dep) => // 21: Prefab { if (!TryGetLightPrefabData(prop, out var isPrefab, out var prefabRoot)) @@ -716,15 +716,15 @@ protected virtual LightingExplorerTableColumn[] GetHDLightColumns() } } }, (lprop, rprop) => - { - TryGetLightPrefabData(lprop, out var lIsPrefab, out var lPrefabRoot); - TryGetLightPrefabData(rprop, out var rIsPrefab, out var rPrefabRoot); + { + TryGetLightPrefabData(lprop, out var lIsPrefab, out var lPrefabRoot); + TryGetLightPrefabData(rprop, out var rIsPrefab, out var rPrefabRoot); - if (IsNullComparison(lPrefabRoot, rPrefabRoot, out var order)) - return order; + if (IsNullComparison(lPrefabRoot, rPrefabRoot, out var order)) + return order; - return EditorUtility.NaturalCompare(lPrefabRoot.name, rPrefabRoot.name); - }), + return EditorUtility.NaturalCompare(lPrefabRoot.name, rPrefabRoot.name); + }), }; } @@ -747,22 +747,21 @@ protected virtual LightingExplorerTableColumn[] GetVolumeColumns() isGlobal = EditorGUI.Popup(r, isGlobal, HDStyles.globalModes); if (EditorGUI.EndChangeCheck()) prop.boolValue = isGlobal == 0; - }, (lprop, rprop) => - { - bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); - bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); + { + bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); + bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); - return (lHasVolume ? lVolumeData.isGlobal : false).CompareTo((rHasVolume ? rVolumeData.isGlobal : false)); - }), + return (lHasVolume ? lVolumeData.isGlobal : false).CompareTo((rHasVolume ? rVolumeData.isGlobal : false)); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.Priority, "priority", 60), // 3: Priority new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Custom, HDStyles.VolumeProfile, "sharedProfile", 200, (r, prop, dep) => // 4: Profile { EditorGUI.PropertyField(r, prop, GUIContent.none); }, (lprop, rprop) => - { - return EditorUtility.NaturalCompare(((lprop == null || lprop.objectReferenceValue == null) ? "--" : lprop.objectReferenceValue.name), ((rprop == null || rprop.objectReferenceValue == null) ? "--" : rprop.objectReferenceValue.name)); - }), + { + return EditorUtility.NaturalCompare(((lprop == null || lprop.objectReferenceValue == null) ? "--" : lprop.objectReferenceValue.name), ((rprop == null || rprop.objectReferenceValue == null) ? "--" : rprop.objectReferenceValue.name)); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.HasVisualEnvironment, "sharedProfile", 150, (r, prop, dep) => // 5: Has Visual environment { if (!TryGetAdditionalVolumeData(prop, out var volumeData)) @@ -776,12 +775,12 @@ protected virtual LightingExplorerTableColumn[] GetVolumeColumns() EditorGUI.Toggle(r, volumeData.hasVisualEnvironment); } }, (lprop, rprop) => - { - bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); - bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); + { + bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); + bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); - return (lHasVolume ? System.Convert.ToInt32(lVolumeData.hasVisualEnvironment) : -1).CompareTo((rHasVolume ? System.Convert.ToInt32(rVolumeData.hasVisualEnvironment) : -1)); - }), + return (lHasVolume ? System.Convert.ToInt32(lVolumeData.hasVisualEnvironment) : -1).CompareTo((rHasVolume ? System.Convert.ToInt32(rVolumeData.hasVisualEnvironment) : -1)); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.SkyType, "sharedProfile", 75, (r, prop, dep) => // 6: Sky type { if (!TryGetAdditionalVolumeData(prop, out var volumeData)) @@ -795,12 +794,12 @@ protected virtual LightingExplorerTableColumn[] GetVolumeColumns() EditorGUI.IntPopup(r, volumeData.skyType, VisualEnvironmentEditor.skyClassNames.ToArray(), VisualEnvironmentEditor.skyUniqueIDs.ToArray()); } }, (lprop, rprop) => - { - bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); - bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); + { + bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); + bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); - return (lHasVolume ? (int)lVolumeData.skyType : -1).CompareTo((rHasVolume ? (int)rVolumeData.skyType : -1)); - }), + return (lHasVolume ? (int)lVolumeData.skyType : -1).CompareTo((rHasVolume ? (int)rVolumeData.skyType : -1)); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.Fog, "sharedProfile", 50, (r, prop, dep) => // 8: Fog enabled { if (!TryGetAdditionalVolumeData(prop, out var volumeData)) @@ -814,12 +813,12 @@ protected virtual LightingExplorerTableColumn[] GetVolumeColumns() EditorGUI.Toggle(r, volumeData.fogEnabled); } }, (lprop, rprop) => - { - bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); - bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); + { + bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); + bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); - return (lHasVolume ? lVolumeData.fogEnabled : false).CompareTo((rHasVolume ? rVolumeData.fogEnabled : false)); - }), + return (lHasVolume ? lVolumeData.fogEnabled : false).CompareTo((rHasVolume ? rVolumeData.fogEnabled : false)); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.Volumetric, "sharedProfile", 95, (r, prop, dep) => // 9: Volumetric enabled { if (!TryGetAdditionalVolumeData(prop, out var volumeData)) @@ -833,12 +832,12 @@ protected virtual LightingExplorerTableColumn[] GetVolumeColumns() EditorGUI.Toggle(r, volumeData.volumetricEnabled); } }, (lprop, rprop) => - { - bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); - bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); + { + bool lHasVolume = TryGetAdditionalVolumeData(lprop, out var lVolumeData); + bool rHasVolume = TryGetAdditionalVolumeData(rprop, out var rVolumeData); - return (lHasVolume ? lVolumeData.volumetricEnabled : false).CompareTo((rHasVolume ? rVolumeData.volumetricEnabled : false)); - }) + return (lHasVolume ? lVolumeData.volumetricEnabled : false).CompareTo((rHasVolume ? rVolumeData.volumetricEnabled : false)); + }) }; } @@ -860,23 +859,23 @@ protected virtual LightingExplorerTableColumn[] GetHDReflectionProbeColumns() EditorGUI.PropertyField(r, reflectionData.FindProperty("m_ProbeSettings.mode"), GUIContent.none); reflectionData.ApplyModifiedProperties(); }, (lprop, rprop) => - { - TryGetAdditionalReflectionData(lprop, out var lReflectionData); - TryGetAdditionalReflectionData(rprop, out var rReflectionData); + { + TryGetAdditionalReflectionData(lprop, out var lReflectionData); + TryGetAdditionalReflectionData(rprop, out var rReflectionData); - if (IsNullComparison(lReflectionData, rReflectionData, out var order)) - return order; + if (IsNullComparison(lReflectionData, rReflectionData, out var order)) + return order; - return lReflectionData.FindProperty("m_ProbeSettings.mode").intValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.mode").intValue); - }, (target, source) => - { - if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) - return; + return lReflectionData.FindProperty("m_ProbeSettings.mode").intValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.mode").intValue); + }, (target, source) => + { + if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) + return; - tReflectionData.Update(); - tReflectionData.FindProperty("m_ProbeSettings.mode").intValue = sReflectionData.FindProperty("m_ProbeSettings.mode").intValue; - tReflectionData.ApplyModifiedProperties(); - }), + tReflectionData.Update(); + tReflectionData.FindProperty("m_ProbeSettings.mode").intValue = sReflectionData.FindProperty("m_ProbeSettings.mode").intValue; + tReflectionData.ApplyModifiedProperties(); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, HDStyles.Shape, "m_Mode", 70, (r, prop, dep) => // 3: Shape { if (!TryGetAdditionalReflectionData(prop, out var reflectionData)) @@ -889,23 +888,23 @@ protected virtual LightingExplorerTableColumn[] GetHDReflectionProbeColumns() EditorGUI.PropertyField(r, reflectionData.FindProperty("m_ProbeSettings.influence.m_Shape"), GUIContent.none); reflectionData.ApplyModifiedProperties(); }, (lprop, rprop) => - { - TryGetAdditionalReflectionData(lprop, out var lReflectionData); - TryGetAdditionalReflectionData(rprop, out var rReflectionData); + { + TryGetAdditionalReflectionData(lprop, out var lReflectionData); + TryGetAdditionalReflectionData(rprop, out var rReflectionData); - if (IsNullComparison(lReflectionData, rReflectionData, out var order)) - return order; + if (IsNullComparison(lReflectionData, rReflectionData, out var order)) + return order; - return lReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue); - }, (target, source) => - { - if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) - return; + return lReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue); + }, (target, source) => + { + if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) + return; - tReflectionData.Update(); - tReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue = sReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue; - tReflectionData.ApplyModifiedProperties(); - }), + tReflectionData.Update(); + tReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue = sReflectionData.FindProperty("m_ProbeSettings.influence.m_Shape").intValue; + tReflectionData.ApplyModifiedProperties(); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.NearClip, "m_NearClip", 65, (r, prop, dep) => // 4: Near clip { if (!TryGetAdditionalReflectionData(prop, out var reflectionData)) @@ -918,23 +917,23 @@ protected virtual LightingExplorerTableColumn[] GetHDReflectionProbeColumns() EditorGUI.PropertyField(r, reflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw"), GUIContent.none); reflectionData.ApplyModifiedProperties(); }, (lprop, rprop) => - { - TryGetAdditionalReflectionData(lprop, out var lReflectionData); - TryGetAdditionalReflectionData(rprop, out var rReflectionData); + { + TryGetAdditionalReflectionData(lprop, out var lReflectionData); + TryGetAdditionalReflectionData(rprop, out var rReflectionData); - if (IsNullComparison(lReflectionData, rReflectionData, out var order)) - return order; + if (IsNullComparison(lReflectionData, rReflectionData, out var order)) + return order; - return lReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue); - }, (target, source) => - { - if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) - return; + return lReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue); + }, (target, source) => + { + if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) + return; - tReflectionData.Update(); - tReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue = sReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue; - tReflectionData.ApplyModifiedProperties(); - }), + tReflectionData.Update(); + tReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue = sReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.nearClipPlaneRaw").floatValue; + tReflectionData.ApplyModifiedProperties(); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.FarClip, "m_FarClip", 60, (r, prop, dep) => // 5: Far clip { if (!TryGetAdditionalReflectionData(prop, out var reflectionData)) @@ -947,23 +946,23 @@ protected virtual LightingExplorerTableColumn[] GetHDReflectionProbeColumns() EditorGUI.PropertyField(r, reflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw"), GUIContent.none); reflectionData.ApplyModifiedProperties(); }, (lprop, rprop) => - { - TryGetAdditionalReflectionData(lprop, out var lReflectionData); - TryGetAdditionalReflectionData(rprop, out var rReflectionData); + { + TryGetAdditionalReflectionData(lprop, out var lReflectionData); + TryGetAdditionalReflectionData(rprop, out var rReflectionData); - if (IsNullComparison(lReflectionData, rReflectionData, out var order)) - return order; + if (IsNullComparison(lReflectionData, rReflectionData, out var order)) + return order; - return lReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue); - }, (target, source) => - { - if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) - return; + return lReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue); + }, (target, source) => + { + if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) + return; - tReflectionData.Update(); - tReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue = sReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue; - tReflectionData.ApplyModifiedProperties(); - }), + tReflectionData.Update(); + tReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue = sReflectionData.FindProperty("m_ProbeSettings.cameraSettings.frustum.farClipPlaneRaw").floatValue; + tReflectionData.ApplyModifiedProperties(); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, HDStyles.ParallaxCorrection, "m_BoxProjection", 215, (r, prop, dep) => // 6. Use Influence volume as proxy { if (!TryGetAdditionalReflectionData(prop, out var reflectionData)) @@ -976,23 +975,23 @@ protected virtual LightingExplorerTableColumn[] GetHDReflectionProbeColumns() EditorGUI.PropertyField(r, reflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume"), GUIContent.none); reflectionData.ApplyModifiedProperties(); }, (lprop, rprop) => - { - TryGetAdditionalReflectionData(lprop, out var lReflectionData); - TryGetAdditionalReflectionData(rprop, out var rReflectionData); + { + TryGetAdditionalReflectionData(lprop, out var lReflectionData); + TryGetAdditionalReflectionData(rprop, out var rReflectionData); - if (IsNullComparison(lReflectionData, rReflectionData, out var order)) - return order; + if (IsNullComparison(lReflectionData, rReflectionData, out var order)) + return order; - return lReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue); - }, (target, source) => - { - if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) - return; + return lReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue); + }, (target, source) => + { + if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) + return; - tReflectionData.Update(); - tReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue = sReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue; - tReflectionData.ApplyModifiedProperties(); - }), + tReflectionData.Update(); + tReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue = sReflectionData.FindProperty("m_ProbeSettings.proxySettings.useInfluenceVolumeAsProxyVolume").boolValue; + tReflectionData.ApplyModifiedProperties(); + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.Weight, "m_Mode", 60, (r, prop, dep) => // 7: Weight { if (!TryGetAdditionalReflectionData(prop, out var reflectionData)) @@ -1005,23 +1004,23 @@ protected virtual LightingExplorerTableColumn[] GetHDReflectionProbeColumns() EditorGUI.PropertyField(r, reflectionData.FindProperty("m_ProbeSettings.lighting.weight"), GUIContent.none); reflectionData.ApplyModifiedProperties(); }, (lprop, rprop) => - { - TryGetAdditionalReflectionData(lprop, out var lReflectionData); - TryGetAdditionalReflectionData(rprop, out var rReflectionData); + { + TryGetAdditionalReflectionData(lprop, out var lReflectionData); + TryGetAdditionalReflectionData(rprop, out var rReflectionData); - if (IsNullComparison(lReflectionData, rReflectionData, out var order)) - return order; + if (IsNullComparison(lReflectionData, rReflectionData, out var order)) + return order; - return lReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue); - }, (target, source) => - { - if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) - return; + return lReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue.CompareTo(rReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue); + }, (target, source) => + { + if (!TryGetAdditionalReflectionData(target, out var tReflectionData) || !TryGetAdditionalReflectionData(source, out var sReflectionData)) + return; - tReflectionData.Update(); - tReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue = sReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue; - tReflectionData.ApplyModifiedProperties(); - }), + tReflectionData.Update(); + tReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue = sReflectionData.FindProperty("m_ProbeSettings.lighting.weight").floatValue; + tReflectionData.ApplyModifiedProperties(); + }), }; } @@ -1045,26 +1044,26 @@ protected internal virtual LightingExplorerTableColumn[] GetProbeVolumeColumns() SerializedProperty drawProbes = prop.FindPropertyRelative("drawProbes"); EditorGUI.PropertyField(r, drawProbes, GUIContent.none); }, (lhs, rhs) => - { - return lhs.FindPropertyRelative("drawProbes").boolValue.CompareTo(rhs.FindPropertyRelative("drawProbes").boolValue); - }, (target, source) => - { - target.FindPropertyRelative("drawProbes").boolValue = source.FindPropertyRelative("drawProbes").boolValue; - }), + { + return lhs.FindPropertyRelative("drawProbes").boolValue.CompareTo(rhs.FindPropertyRelative("drawProbes").boolValue); + }, (target, source) => + { + target.FindPropertyRelative("drawProbes").boolValue = source.FindPropertyRelative("drawProbes").boolValue; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Color, HDStyles.DebugColor, "parameters", 75, (r, prop, dep) => // 2: Debug Color { SerializedProperty debugColor = prop.FindPropertyRelative("debugColor"); EditorGUI.PropertyField(r, debugColor, GUIContent.none); }, (lhs, rhs) => - { - float lh, ls, lv, rh, rs, rv; - Color.RGBToHSV(lhs.FindPropertyRelative("debugColor").colorValue, out lh, out ls, out lv); - Color.RGBToHSV(rhs.FindPropertyRelative("debugColor").colorValue, out rh, out rs, out rv); - return lh.CompareTo(rh); - }, (target, source) => - { - target.FindPropertyRelative("debugColor").colorValue = source.FindPropertyRelative("debugColor").colorValue; - }), + { + float lh, ls, lv, rh, rs, rv; + Color.RGBToHSV(lhs.FindPropertyRelative("debugColor").colorValue, out lh, out ls, out lv); + Color.RGBToHSV(rhs.FindPropertyRelative("debugColor").colorValue, out rh, out rs, out rv); + return lh.CompareTo(rh); + }, (target, source) => + { + target.FindPropertyRelative("debugColor").colorValue = source.FindPropertyRelative("debugColor").colorValue; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, HDStyles.ResolutionX, "parameters", 75, (r, prop, dep) => // 3: Resolution X { SerializedProperty resolutionX = prop.FindPropertyRelative("resolutionX"); @@ -1077,12 +1076,12 @@ protected internal virtual LightingExplorerTableColumn[] GetProbeVolumeColumns() resolutionX.intValue = Mathf.Max(1, resolutionX.intValue); } }, (lhs, rhs) => - { - return lhs.FindPropertyRelative("resolutionX").intValue.CompareTo(rhs.FindPropertyRelative("resolutionX").intValue); - }, (target, source) => - { - target.FindPropertyRelative("resolutionX").intValue = source.FindPropertyRelative("resolutionX").intValue; - }), + { + return lhs.FindPropertyRelative("resolutionX").intValue.CompareTo(rhs.FindPropertyRelative("resolutionX").intValue); + }, (target, source) => + { + target.FindPropertyRelative("resolutionX").intValue = source.FindPropertyRelative("resolutionX").intValue; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, HDStyles.ResolutionY, "parameters", 75, (r, prop, dep) => // 4: Resolution Y { SerializedProperty resolutionY = prop.FindPropertyRelative("resolutionY"); @@ -1096,12 +1095,12 @@ protected internal virtual LightingExplorerTableColumn[] GetProbeVolumeColumns() resolutionY.intValue = Mathf.Max(1, resolutionY.intValue); } }, (lhs, rhs) => - { - return lhs.FindPropertyRelative("resolutionY").intValue.CompareTo(rhs.FindPropertyRelative("resolutionY").intValue); - }, (target, source) => - { - target.FindPropertyRelative("resolutionY").intValue = source.FindPropertyRelative("resolutionY").intValue; - }), + { + return lhs.FindPropertyRelative("resolutionY").intValue.CompareTo(rhs.FindPropertyRelative("resolutionY").intValue); + }, (target, source) => + { + target.FindPropertyRelative("resolutionY").intValue = source.FindPropertyRelative("resolutionY").intValue; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, HDStyles.ResolutionZ, "parameters", 75, (r, prop, dep) => // 5: Resolution Z { SerializedProperty resolutionZ = prop.FindPropertyRelative("resolutionZ"); @@ -1115,34 +1114,34 @@ protected internal virtual LightingExplorerTableColumn[] GetProbeVolumeColumns() resolutionZ.intValue = Mathf.Max(1, resolutionZ.intValue); } }, (lhs, rhs) => - { - return lhs.FindPropertyRelative("resolutionZ").intValue.CompareTo(rhs.FindPropertyRelative("resolutionZ").intValue); - }, (target, source) => - { - target.FindPropertyRelative("resolutionZ").intValue = source.FindPropertyRelative("resolutionZ").intValue; - }), + { + return lhs.FindPropertyRelative("resolutionZ").intValue.CompareTo(rhs.FindPropertyRelative("resolutionZ").intValue); + }, (target, source) => + { + target.FindPropertyRelative("resolutionZ").intValue = source.FindPropertyRelative("resolutionZ").intValue; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.FadeStart, "parameters", 65, (r, prop, dep) => // 6: Distance Fade Start { SerializedProperty distanceFadeStart = prop.FindPropertyRelative("distanceFadeStart"); EditorGUI.PropertyField(r, distanceFadeStart, GUIContent.none); }, (lhs, rhs) => - { - return lhs.FindPropertyRelative("distanceFadeStart").floatValue.CompareTo(rhs.FindPropertyRelative("distanceFadeStart").floatValue); - }, (target, source) => - { - target.FindPropertyRelative("distanceFadeStart").floatValue = source.FindPropertyRelative("distanceFadeStart").floatValue; - }), + { + return lhs.FindPropertyRelative("distanceFadeStart").floatValue.CompareTo(rhs.FindPropertyRelative("distanceFadeStart").floatValue); + }, (target, source) => + { + target.FindPropertyRelative("distanceFadeStart").floatValue = source.FindPropertyRelative("distanceFadeStart").floatValue; + }), new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, HDStyles.FadeEnd, "parameters", 65, (r, prop, dep) => // 7: Distance Fade End { SerializedProperty distanceFadeEnd = prop.FindPropertyRelative("distanceFadeEnd"); EditorGUI.PropertyField(r, distanceFadeEnd, GUIContent.none); }, (lhs, rhs) => - { - return lhs.FindPropertyRelative("distanceFadeEnd").floatValue.CompareTo(rhs.FindPropertyRelative("distanceFadeEnd").floatValue); - }, (target, source) => - { - target.FindPropertyRelative("distanceFadeEnd").floatValue = source.FindPropertyRelative("distanceFadeEnd").floatValue; - }) + { + return lhs.FindPropertyRelative("distanceFadeEnd").floatValue.CompareTo(rhs.FindPropertyRelative("distanceFadeEnd").floatValue); + }, (target, source) => + { + target.FindPropertyRelative("distanceFadeEnd").floatValue = source.FindPropertyRelative("distanceFadeEnd").floatValue; + }) }; } @@ -1174,7 +1173,7 @@ private bool TryGetLightPrefabData(SerializedProperty prop, out bool isPrefab, o { Light light = prop.serializedObject.targetObject as Light; - if(light == null || !lightDataPairing.ContainsKey(light)) + if (light == null || !lightDataPairing.ContainsKey(light)) { isPrefab = false; prefabRoot = null; @@ -1191,7 +1190,7 @@ private bool TryGetAdditionalVolumeData(SerializedProperty prop, out VolumeData { Volume volume = prop.serializedObject.targetObject as Volume; - if(volume == null || !volumeDataPairing.ContainsKey(volume)) + if (volume == null || !volumeDataPairing.ContainsKey(volume)) { volumeData = new VolumeData(); return false; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.Handles.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.Handles.cs index 72c1b4fc0d5..5a449df82d8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.Handles.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.Handles.cs @@ -192,7 +192,7 @@ static void DrawSpotlightWireframe(Vector3 outerAngleInnerAngleRange, float shad Handles.DrawWireDisc(Vector3.forward * shadowDiscDistance, Vector3.forward, shadowDiscRadius); } } - + static void DrawConeWireframe(float radius, float height) { var rangeCenter = Vector3.forward * height; @@ -243,7 +243,7 @@ static Vector2 DrawAreaLightHandle(Vector2 rectangleSize, bool withYAxis) return new Vector2(halfWidth * 2f, halfHeight * 2f); } - + //copy of CoreLightEditorUtilities static Vector3[] GetFrustrumProjectedRectAngles(float distance, float aspect, float tanFOV) { @@ -305,7 +305,8 @@ static void DrawSpherePortionWireframe(Vector4 aspectFovMaxRangeMinRange, float var endAngles = GetSphericalProjectedRectAngles(maxRange, aspect, tanfov); var planProjectedCrossNormal0 = new Vector3(endAngles[0].y, -endAngles[0].x, 0).normalized; var planProjectedCrossNormal1 = new Vector3(endAngles[1].y, -endAngles[1].x, 0).normalized; - Vector3[] faceNormals = new[] { + Vector3[] faceNormals = new[] + { Vector3.right - Vector3.Dot((endAngles[3] + endAngles[0]).normalized, Vector3.right) * (endAngles[3] + endAngles[0]).normalized, Vector3.up - Vector3.Dot((endAngles[0] + endAngles[1]).normalized, Vector3.up) * (endAngles[0] + endAngles[1]).normalized, Vector3.left - Vector3.Dot((endAngles[1] + endAngles[2]).normalized, Vector3.left) * (endAngles[1] + endAngles[2]).normalized, @@ -315,7 +316,8 @@ static void DrawSpherePortionWireframe(Vector4 aspectFovMaxRangeMinRange, float planProjectedCrossNormal1 - Vector3.Dot((endAngles[0] + endAngles[2]).normalized, planProjectedCrossNormal1) * (endAngles[0] + endAngles[2]).normalized, }; - float[] faceAngles = new[] { + float[] faceAngles = new[] + { Vector3.Angle(endAngles[3], endAngles[0]), Vector3.Angle(endAngles[0], endAngles[1]), Vector3.Angle(endAngles[1], endAngles[2]), @@ -336,7 +338,7 @@ static void DrawSpherePortionWireframe(Vector4 aspectFovMaxRangeMinRange, float Handles.DrawLine(startAngles[2], endAngles[2]); Handles.DrawLine(startAngles[3], endAngles[3]); } - + static Vector3[] GetSphericalProjectedRectAngles(float distance, float aspect, float tanFOV) { var angles = GetFrustrumProjectedRectAngles(distance, aspect, tanFOV); @@ -715,7 +717,7 @@ static void DrawGizmoForHDAdditionalLightData(HDAdditionalLightData src, GizmoTy // Evaluate the half dimensions of the rectangular area light float halfWidth = src.shapeWidth * 0.5f; float halfHeight = src.shapeHeight * 0.5f; - + // Evaluate the dimensions of the extended area light float extendedWidth = Mathf.Tan(angle) * depth + halfWidth; float extendedHeight = Mathf.Tan(angle) * depth + halfHeight; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.cs index dd4af53830a..05d63350e97 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/HDLightUI.cs @@ -26,7 +26,6 @@ public static IntScalableSetting ShadowResolution(HDLightType lightType, HDRende } - enum ShadowmaskMode { ShadowMask, @@ -115,10 +114,10 @@ static HDLightUI() CED.Conditional((serialized, owner) => serialized.type != HDLightType.Area && !serialized.settings.isCompletelyBaked, CED.FoldoutGroup(s_Styles.volumetricHeader, Expandable.Volumetric, k_ExpandedState, DrawVolumetric)), CED.Conditional((serialized, owner) => - { - HDLightType type = serialized.type; - return type != HDLightType.Area || type == HDLightType.Area && serialized.areaLightShape != AreaLightShape.Tube; - }, + { + HDLightType type = serialized.type; + return type != HDLightType.Area || type == HDLightType.Area && serialized.areaLightShape != AreaLightShape.Tube; + }, CED.TernaryConditional((serialized, owner) => !serialized.settings.isCompletelyBaked, CED.AdvancedFoldoutGroup(s_Styles.shadowHeader, Expandable.Shadows, k_ExpandedState, (serialized, owner) => GetAdvanced(AdvancedMode.Shadow, serialized, owner), @@ -137,9 +136,9 @@ static HDLightUI() CED.Conditional((serialized, owner) => serialized.type != HDLightType.Area, CED.FoldoutGroup(s_Styles.contactShadowsSubHeader, Expandable.ContactShadow, k_ExpandedState, FoldoutOption.SubFoldout | FoldoutOption.Indent | FoldoutOption.NoSpaceAtEnd, DrawContactShadowsContent) ) - ), + ), CED.noop //will only add parameter in first sub header - ), + ), CED.FoldoutGroup(s_Styles.shadowHeader, Expandable.Shadows, k_ExpandedState, CED.FoldoutGroup(s_Styles.bakedShadowsSubHeader, Expandable.BakedShadow, k_ExpandedState, FoldoutOption.SubFoldout | FoldoutOption.Indent | FoldoutOption.NoSpaceAtEnd, DrawBakedShadowsContent)) ) @@ -152,12 +151,12 @@ static HDLightUI() var paramSettings = Expression.Parameter(typeof(LightEditor.Settings), "settings"); System.Reflection.MethodInfo sliderWithTextureInfo = typeof(EditorGUILayout) .GetMethod( - "SliderWithTexture", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, - null, - System.Reflection.CallingConventions.Any, - new[] { typeof(GUIContent), typeof(SerializedProperty), typeof(float), typeof(float), typeof(float), typeof(Texture2D), typeof(GUILayoutOption[]) }, - null); + "SliderWithTexture", + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, + null, + System.Reflection.CallingConventions.Any, + new[] { typeof(GUIContent), typeof(SerializedProperty), typeof(float), typeof(float), typeof(float), typeof(Texture2D), typeof(GUILayoutOption[]) }, + null); var sliderWithTextureCall = Expression.Call( sliderWithTextureInfo, paramLabel, @@ -277,7 +276,7 @@ static void DrawShapeContent(SerializedHDLight serialized, Editor owner) case HDLightType.Point: EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(serialized.shapeRadius, s_Styles.lightRadius); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) { //Also affect baked shadows serialized.settings.bakedShadowRadiusProp.floatValue = serialized.shapeRadius.floatValue; @@ -303,7 +302,7 @@ static void DrawShapeContent(SerializedHDLight serialized, Editor owner) // Cone spot projector EditorGUI.BeginChangeCheck(); EditorGUILayout.Slider(serialized.settings.spotAngle, HDAdditionalLightData.k_MinSpotAngle, HDAdditionalLightData.k_MaxSpotAngle, s_Styles.outterAngle); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) { serialized.customSpotLightShadowCone.floatValue = Math.Min(serialized.customSpotLightShadowCone.floatValue, serialized.settings.spotAngle.floatValue); } @@ -534,13 +533,13 @@ internal static float ConvertLightIntensity(LightUnit oldLightUnit, LightUnit ne intensity = LightUtils.ConvertPunctualLightLumenToCandela(lightType, intensity, light.intensity, serialized.enableSpotReflector.boolValue); else if (oldLightUnit == LightUnit.Lumen && newLightUnit == LightUnit.Lux) intensity = LightUtils.ConvertPunctualLightLumenToLux(lightType, intensity, light.intensity, serialized.enableSpotReflector.boolValue, - serialized.luxAtDistance.floatValue); + serialized.luxAtDistance.floatValue); else if (oldLightUnit == LightUnit.Lumen && newLightUnit == LightUnit.Ev100) intensity = LightUtils.ConvertPunctualLightLumenToEv(lightType, intensity, light.intensity, serialized.enableSpotReflector.boolValue); // Candela -> else if (oldLightUnit == LightUnit.Candela && newLightUnit == LightUnit.Lumen) intensity = LightUtils.ConvertPunctualLightCandelaToLumen(lightType, serialized.spotLightShape.GetEnumValue(), intensity, serialized.enableSpotReflector.boolValue, - light.spotAngle, serialized.aspectRatio.floatValue); + light.spotAngle, serialized.aspectRatio.floatValue); else if (oldLightUnit == LightUnit.Candela && newLightUnit == LightUnit.Lux) intensity = LightUtils.ConvertCandelaToLux(intensity, serialized.luxAtDistance.floatValue); else if (oldLightUnit == LightUnit.Candela && newLightUnit == LightUnit.Ev100) @@ -548,7 +547,7 @@ internal static float ConvertLightIntensity(LightUnit oldLightUnit, LightUnit ne // Lux -> else if (oldLightUnit == LightUnit.Lux && newLightUnit == LightUnit.Lumen) intensity = LightUtils.ConvertPunctualLightLuxToLumen(lightType, serialized.spotLightShape.GetEnumValue(), intensity, serialized.enableSpotReflector.boolValue, - light.spotAngle, serialized.aspectRatio.floatValue, serialized.luxAtDistance.floatValue); + light.spotAngle, serialized.aspectRatio.floatValue, serialized.luxAtDistance.floatValue); else if (oldLightUnit == LightUnit.Lux && newLightUnit == LightUnit.Candela) intensity = LightUtils.ConvertLuxToCandela(intensity, serialized.luxAtDistance.floatValue); else if (oldLightUnit == LightUnit.Lux && newLightUnit == LightUnit.Ev100) @@ -556,7 +555,7 @@ internal static float ConvertLightIntensity(LightUnit oldLightUnit, LightUnit ne // EV100 -> else if (oldLightUnit == LightUnit.Ev100 && newLightUnit == LightUnit.Lumen) intensity = LightUtils.ConvertPunctualLightEvToLumen(lightType, serialized.spotLightShape.GetEnumValue(), intensity, serialized.enableSpotReflector.boolValue, - light.spotAngle, serialized.aspectRatio.floatValue); + light.spotAngle, serialized.aspectRatio.floatValue); else if (oldLightUnit == LightUnit.Ev100 && newLightUnit == LightUnit.Candela) intensity = LightUtils.ConvertEvToCandela(intensity); else if (oldLightUnit == LightUnit.Ev100 && newLightUnit == LightUnit.Lux) @@ -647,7 +646,7 @@ static void DrawEmissionContent(SerializedHDLight serialized, Editor owner) { // Use the color temperature bool to create a popup dropdown to choose between the two modes. var colorTemperaturePopupValue = Convert.ToInt32(serialized.settings.useColorTemperature.boolValue); - var lightAppearanceOptions = new [] { "Color", "Filter and Temperature" }; + var lightAppearanceOptions = new[] { "Color", "Filter and Temperature" }; colorTemperaturePopupValue = EditorGUILayout.Popup(s_Styles.lightAppearance, colorTemperaturePopupValue, lightAppearanceOptions); serialized.settings.useColorTemperature.boolValue = Convert.ToBoolean(colorTemperaturePopupValue); @@ -772,9 +771,9 @@ static void DrawEmissionContent(SerializedHDLight serialized, Editor owner) { EditorGUI.BeginChangeCheck(); UnityEngine.Object iesAsset = EditorGUILayout.ObjectField( - s_Styles.iesTexture, - serialized.type == HDLightType.Point ? serialized.iesPoint.objectReferenceValue : serialized.iesSpot.objectReferenceValue, - typeof(IESObject), false); + s_Styles.iesTexture, + serialized.type == HDLightType.Point ? serialized.iesPoint.objectReferenceValue : serialized.iesSpot.objectReferenceValue, + typeof(IESObject), false); if (EditorGUI.EndChangeCheck()) { SerializedProperty pointTex = serialized.iesPoint; @@ -782,7 +781,7 @@ static void DrawEmissionContent(SerializedHDLight serialized, Editor owner) if (iesAsset == null) { pointTex.objectReferenceValue = null; - spotTex .objectReferenceValue = null; + spotTex.objectReferenceValue = null; } else { @@ -804,7 +803,7 @@ static void DrawEmissionContent(SerializedHDLight serialized, Editor owner) } } serialized.iesPoint.serializedObject.ApplyModifiedProperties(); - serialized.iesSpot .serializedObject.ApplyModifiedProperties(); + serialized.iesSpot.serializedObject.ApplyModifiedProperties(); } } @@ -965,9 +964,9 @@ static void DrawEmissionAdvancedContent(SerializedHDLight serialized, Editor own // or if the value of layer got changed using the layer change including child mechanism (strangely apply even if object not editable), // discard the change: the child is not saved anyway so the value in HDAdditionalLightData is the only serialized one. else if (!EditorGUI.showMixedValue - && serialized.deportedAreaLightEmissiveMeshLayer != null - && !serialized.deportedAreaLightEmissiveMeshLayer.Equals(null) - && serialized.areaLightEmissiveMeshLayer.intValue != serialized.deportedAreaLightEmissiveMeshLayer.intValue) + && serialized.deportedAreaLightEmissiveMeshLayer != null + && !serialized.deportedAreaLightEmissiveMeshLayer.Equals(null) + && serialized.areaLightEmissiveMeshLayer.intValue != serialized.deportedAreaLightEmissiveMeshLayer.intValue) { GUI.changed = true; //force register change to handle update and apply later serialized.UpdateAreaLightEmissiveMeshLayer(layer); @@ -1032,13 +1031,12 @@ static void DrawShadowMapContent(SerializedHDLight serialized, Editor owner) { EditorGUILayout.PropertyField(serialized.shadowUpdateMode, s_Styles.shadowUpdateMode); - if(serialized.shadowUpdateMode.intValue > 0 && serialized.type != HDLightType.Directional) + if (serialized.shadowUpdateMode.intValue > 0 && serialized.type != HDLightType.Directional) { #if UNITY_2021_1_OR_NEWER EditorGUILayout.PropertyField(serialized.shadowAlwaysDrawDynamic, s_Styles.shadowAlwaysDrawDynamic); #endif EditorGUILayout.PropertyField(serialized.shadowUpdateUponTransformChange, s_Styles.shadowUpdateOnLightTransformChange); - } HDLightType lightType = serialized.type; @@ -1065,7 +1063,7 @@ static void DrawShadowMapContent(SerializedHDLight serialized, Editor owner) serialized.shadowResolution.@override.intValue = Mathf.Max(HDShadowManager.k_MinShadowMapResolution, serialized.shadowResolution.@override.intValue); } - if(lightType != HDLightType.Directional) + if (lightType != HDLightType.Directional) EditorGUILayout.Slider(serialized.shadowNearPlane, HDShadowUtils.k_MinShadowNearPlane, HDShadowUtils.k_MaxShadowNearPlane, s_Styles.shadowNearPlane); if (serialized.settings.isMixed) @@ -1157,7 +1155,6 @@ static void DrawShadowMapContent(SerializedHDLight serialized, Editor owner) } } - static void DrawShadowMapAdvancedContent(SerializedHDLight serialized, Editor owner) { using (new EditorGUI.DisabledScope(serialized.settings.shadowsType.GetEnumValue() == LightShadows.None)) diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSlider.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSlider.cs index 32aeb3c1e2f..7fde742c15c 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSlider.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSlider.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using UnityEngine; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSliderSettings.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSliderSettings.cs index bb987eae4fe..3e6daa3e2f6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSliderSettings.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/LightUnit/LightUnitSliderSettings.cs @@ -8,12 +8,12 @@ namespace UnityEditor.Rendering.HighDefinition struct LightUnitSliderUIDescriptor { public LightUnitSliderUIDescriptor(LightUnitSliderUIRange[] valueRanges, float[] sliderDistribution, - string cautionTooltip, string unitName, bool hasMarkers = true, bool clampValue = false) + string cautionTooltip, string unitName, bool hasMarkers = true, bool clampValue = false) : this(valueRanges, sliderDistribution, cautionTooltip, cautionTooltip, unitName, hasMarkers, clampValue) {} public LightUnitSliderUIDescriptor(LightUnitSliderUIRange[] valueRanges, float[] sliderDistribution, string belowRangeTooltip, - string aboveRangeTooltip, string unitName, bool hasMarkers = true, bool clampValue = false) + string aboveRangeTooltip, string unitName, bool hasMarkers = true, bool clampValue = false) { this.valueRanges = valueRanges; this.belowRangeTooltip = belowRangeTooltip; @@ -42,7 +42,7 @@ public LightUnitSliderUIDescriptor(LightUnitSliderUIRange[] valueRanges, float[] struct LightUnitSliderUIRange { public LightUnitSliderUIRange(Texture2D icon, string tooltip, Vector2 value) - // If no preset value provided, then by default it is the average of the value range. + // If no preset value provided, then by default it is the average of the value range. : this(icon, tooltip, value, 0.5f * (value.x + value.y)) {} @@ -61,7 +61,7 @@ public LightUnitSliderUIRange(Texture2D icon, string tooltip, Vector2 value, flo public static LightUnitSliderUIRange CautionRange(string tooltip, float value) => new LightUnitSliderUIRange { // Load the buildin caution icon with provided tooltip. - content = new GUIContent( EditorGUIUtility.TrIconContent("console.warnicon").image, tooltip), + content = new GUIContent(EditorGUIUtility.TrIconContent("console.warnicon").image, tooltip), value = new Vector2(-1, value), presetValue = -1 }; @@ -75,10 +75,10 @@ static class LightUnitSliderDescriptors { // Lux public static LightUnitSliderUIDescriptor LuxDescriptor = new LightUnitSliderUIDescriptor( - LightUnitValueRanges.LuxValueTable, - LightUnitSliderDistributions.LuxDistribution, - LightUnitTooltips.k_SunCaution, - "Lux" + LightUnitValueRanges.LuxValueTable, + LightUnitSliderDistributions.LuxDistribution, + LightUnitTooltips.k_SunCaution, + "Lux" ); // Lumen @@ -114,7 +114,7 @@ private static class LightUnitValueRanges { new LightUnitSliderUIRange(LightUnitIcon.ExteriorLight, LightUnitTooltips.k_PunctualExterior, new Vector2(3000, 40000), 10000), new LightUnitSliderUIRange(LightUnitIcon.InteriorLight, LightUnitTooltips.k_PunctualInterior, new Vector2(300, 3000), 1000), - new LightUnitSliderUIRange(LightUnitIcon.DecorativeLight,LightUnitTooltips.k_PunctualDecorative, new Vector2(15, 300), 100), + new LightUnitSliderUIRange(LightUnitIcon.DecorativeLight, LightUnitTooltips.k_PunctualDecorative, new Vector2(15, 300), 100), new LightUnitSliderUIRange(LightUnitIcon.Candlelight, LightUnitTooltips.k_PunctualCandle, new Vector2(0, 15), 12.5f), }; @@ -179,7 +179,7 @@ private static class LightUnitSliderDistributions private static class LightUnitIcon { static string GetLightUnitIconPath() => HDUtils.GetHDRenderPipelinePath() + - "/Editor/RenderPipelineResources/Texture/LightUnitIcons/"; + "/Editor/RenderPipelineResources/Texture/LightUnitIcons/"; // Note: We do not use the editor resource loading mechanism for light unit icons because we need to skin the icon correctly for the editor theme. // Maybe the resource reloader can be improved to support icon loading (thus supporting skinning)? diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs index dfd3c04cc57..5a679717135 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs @@ -30,7 +30,6 @@ protected void OnEnable() var shapeBox = shapeBoxes[targets[i] as ProbeVolume] = new HierarchicalBox(ProbeVolumeUI.Styles.k_GizmoColorBase, ProbeVolumeUI.Styles.k_BaseHandlesColor); shapeBox.monoHandle = false; blendBoxes[targets[i] as ProbeVolume] = new HierarchicalBox(ProbeVolumeUI.Styles.k_GizmoColorBase, InfluenceVolumeUI.k_HandlesColor, parent: shapeBox); - } } @@ -78,7 +77,7 @@ static void DrawGizmosSelected(ProbeVolume probeVolume, GizmoType gizmoType) blendBox.center = CenterBlendLocalPosition(probeVolume); blendBox.size = BlendSize(probeVolume); Color baseColor = probeVolume.parameters.debugColor; - baseColor.a = 8/255f; + baseColor.a = 8 / 255f; blendBox.baseColor = baseColor; blendBox.DrawHull(EditMode.editMode == k_EditBlend); @@ -154,7 +153,7 @@ protected void OnSceneGUI() probeVolume.parameters.size = shapeBox.size; Vector3 delta = probeVolume.transform.rotation * shapeBox.center - probeVolume.transform.position; - probeVolume.transform.position += delta; ; + probeVolume.transform.position += delta;; } } break; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeUI.Drawer.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeUI.Drawer.cs index aa8901e831e..a02dd5cc8e1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeUI.Drawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolume/ProbeVolumeUI.Drawer.cs @@ -54,10 +54,10 @@ enum Expandable Expandable.Baking, k_ExpandedStateBaking, Drawer_BakeToolBar - ) ) ) - ); + ) + ); static bool IsFeatureEnabled(SerializedProbeVolume serialized, Editor owner) { @@ -88,7 +88,7 @@ static void Drawer_BakeToolBar(SerializedProbeVolume serialized, Editor owner) { EditorGUILayout.HelpBox(Styles.k_FeatureOctahedralDepthEnabledNoData, MessageType.Error); } - + if (ShaderConfig.s_ProbeVolumesBilateralFilteringMode != ProbeVolumesBilateralFilteringModes.OctahedralDepth && asset != null && asset.payload.dataOctahedralDepth != null) { @@ -114,14 +114,14 @@ static void Drawer_ToolBar(SerializedProbeVolume serialized, Editor owner) GUILayout.FlexibleSpace(); EditMode.DoInspectorToolbar(new[] { ProbeVolumeEditor.k_EditShape, ProbeVolumeEditor.k_EditBlend }, Styles.s_Toolbar_Contents, () => + { + var bounds = new Bounds(); + foreach (Component targetObject in owner.targets) { - var bounds = new Bounds(); - foreach (Component targetObject in owner.targets) - { - bounds.Encapsulate(targetObject.transform.position); - } - return bounds; - }, + bounds.Encapsulate(targetObject.transform.position); + } + return bounds; + }, owner); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolumeControllerEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolumeControllerEditor.cs index e8356eb8723..8c763b1fd15 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolumeControllerEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/ProbeVolumeControllerEditor.cs @@ -14,7 +14,7 @@ public override void OnInspectorGUI() if (ShaderConfig.s_EnableProbeVolumes == 1) { if (!(GraphicsSettings.renderPipelineAsset as HDRenderPipelineAsset) - ?.currentPlatformRenderPipelineSettings.supportProbeVolume ?? false) + ?.currentPlatformRenderPipelineSettings.supportProbeVolume ?? false) { EditorGUILayout.Space(); EditorGUILayout.HelpBox("The current HDRP Asset does not support Probe Volume Global Illumination.", MessageType.Error, wide: true); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDBakedReflectionSystem.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDBakedReflectionSystem.cs index 6efad371598..24c687329b2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDBakedReflectionSystem.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDBakedReflectionSystem.cs @@ -56,7 +56,6 @@ enum BakingStages HDBakedReflectionSystem() : base(1) { - } public override bool BakeAllReflectionProbes() @@ -180,19 +179,19 @@ IScriptableBakedReflectionSystemStageNotifier handle } else { - fixed (HDProbeBakedState* oldBakedStates = &m_HDProbeBakedStates[0]) + fixed(HDProbeBakedState* oldBakedStates = &m_HDProbeBakedStates[0]) { // == 3. == // Compare hashes between baked probe states and desired probe states operationCount = CoreUnsafeUtils.CompareHashes< - HDProbeBakedState, HDProbeBakedState.ProbeBakedHash, - HDProbeBakingState, HDProbeBakingState.ProbeBakingHash - > ( - m_HDProbeBakedStates.Length, oldBakedStates, // old hashes - bakedProbeCount, states, // new hashes - addIndices, remIndices, - out addCount, out remCount - ); + HDProbeBakedState, HDProbeBakedState.ProbeBakedHash, + HDProbeBakingState, HDProbeBakingState.ProbeBakingHash + >( + m_HDProbeBakedStates.Length, oldBakedStates, // old hashes + bakedProbeCount, states, // new hashes + addIndices, remIndices, + out addCount, out remCount + ); } } @@ -350,7 +349,7 @@ IScriptableBakedReflectionSystemStageNotifier handle Array.Resize(ref m_HDProbeBakedStates, targetSize); if (targetSize > 0) { - fixed (HDProbeBakedState* bakedStates = &m_HDProbeBakedStates[0]) + fixed(HDProbeBakedState* bakedStates = &m_HDProbeBakedStates[0]) { UnsafeUtility.MemCpy( bakedStates, @@ -509,7 +508,7 @@ void DeleteCubemapAssets(bool deleteUnusedOnly) var buffer = new CoreUnsafeUtils.FixedBufferStringQueue(bufferStart, bufferLength); // Look for baked assets in scene folders - for (int sceneI = 0, sceneC = SceneManager.sceneCount; sceneI< sceneC; ++sceneI) + for (int sceneI = 0, sceneC = SceneManager.sceneCount; sceneI < sceneC; ++sceneI) { var scene = SceneManager.GetSceneAt(sceneI); var sceneFolder = HDBakingUtilities.GetBakedTextureDirectory(scene); @@ -527,11 +526,11 @@ void DeleteCubemapAssets(bool deleteUnusedOnly) { if (!HDBakingUtilities.TryParseBakedProbeAssetFileName( files[fileI], out ProbeSettings.ProbeType fileProbeType, out int fileIndex - )) + )) continue; - // This file is a baked asset for a destroyed game object - // We can destroy it + // This file is a baked asset for a destroyed game object + // We can destroy it if (!indicesSet.Contains(fileIndex) && deleteUnusedOnly // Or we delete all assets || !deleteUnusedOnly) @@ -589,19 +588,19 @@ internal static void AssignRenderData(HDProbe probe, string bakedTexturePath) switch (probe.settings.type) { case ProbeSettings.ProbeType.PlanarProbe: + { + var planarProbe = (PlanarReflectionProbe)probe; + var dataFile = bakedTexturePath + ".renderData"; + if (File.Exists(dataFile)) { - var planarProbe = (PlanarReflectionProbe)probe; - var dataFile = bakedTexturePath + ".renderData"; - if (File.Exists(dataFile)) + if (HDBakingUtilities.TryDeserializeFromDisk(dataFile, out HDProbe.RenderData renderData)) { - if (HDBakingUtilities.TryDeserializeFromDisk(dataFile, out HDProbe.RenderData renderData)) - { - HDProbeSystem.AssignRenderData(probe, renderData, ProbeSettings.Mode.Baked); - EditorUtility.SetDirty(probe); - } + HDProbeSystem.AssignRenderData(probe, renderData, ProbeSettings.Mode.Baked); + EditorUtility.SetDirty(probe); } - break; } + break; + } } } @@ -624,42 +623,42 @@ out CameraPositionSettings cameraPositionSettings switch (settings.type) { case ProbeSettings.ProbeType.ReflectionProbe: - { - var positionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, null); - HDRenderUtilities.Render(probe.settings, positionSettings, cubeRT, - out cameraSettings, out cameraPositionSettings, - forceFlipY: true, - forceInvertBackfaceCulling: true, // Cubemap have an RHS standard, so we need to invert the face culling - (uint)StaticEditorFlags.ReflectionProbeStatic - ); - HDBakingUtilities.CreateParentDirectoryIfMissing(targetFile); - Checkout(targetFile); - HDTextureUtilities.WriteTextureFileToDisk(cubeRT, targetFile); - break; - } + { + var positionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, null); + HDRenderUtilities.Render(probe.settings, positionSettings, cubeRT, + out cameraSettings, out cameraPositionSettings, + forceFlipY: true, + forceInvertBackfaceCulling: true, // Cubemap have an RHS standard, so we need to invert the face culling + (uint)StaticEditorFlags.ReflectionProbeStatic + ); + HDBakingUtilities.CreateParentDirectoryIfMissing(targetFile); + Checkout(targetFile); + HDTextureUtilities.WriteTextureFileToDisk(cubeRT, targetFile); + break; + } case ProbeSettings.ProbeType.PlanarProbe: - { - var planarProbe = (PlanarReflectionProbe)probe; - var positionSettings = ProbeCapturePositionSettings.ComputeFromMirroredReference( - probe, - planarProbe.referencePosition - ); + { + var planarProbe = (PlanarReflectionProbe)probe; + var positionSettings = ProbeCapturePositionSettings.ComputeFromMirroredReference( + probe, + planarProbe.referencePosition + ); - HDRenderUtilities.Render( - settings, - positionSettings, - planarRT, - out cameraSettings, out cameraPositionSettings - ); - HDBakingUtilities.CreateParentDirectoryIfMissing(targetFile); - Checkout(targetFile); - HDTextureUtilities.WriteTextureFileToDisk(planarRT, targetFile); - var renderData = new HDProbe.RenderData(cameraSettings, cameraPositionSettings); - var targetRenderDataFile = targetFile + ".renderData"; - Checkout(targetRenderDataFile); - HDBakingUtilities.TrySerializeToDisk(renderData, targetRenderDataFile); - break; - } + HDRenderUtilities.Render( + settings, + positionSettings, + planarRT, + out cameraSettings, out cameraPositionSettings + ); + HDBakingUtilities.CreateParentDirectoryIfMissing(targetFile); + Checkout(targetFile); + HDTextureUtilities.WriteTextureFileToDisk(planarRT, targetFile); + var renderData = new HDProbe.RenderData(cameraSettings, cameraPositionSettings); + var targetRenderDataFile = targetFile + ".renderData"; + Checkout(targetRenderDataFile); + HDBakingUtilities.TrySerializeToDisk(renderData, targetRenderDataFile); + break; + } default: throw new ArgumentOutOfRangeException(nameof(probe.settings.type)); } } @@ -670,41 +669,41 @@ internal static void ImportAssetAt(HDProbe probe, string file) switch (probe.settings.type) { case ProbeSettings.ProbeType.ReflectionProbe: - { - var importer = AssetImporter.GetAtPath(file) as TextureImporter; - if (importer == null) - return; - var settings = new TextureImporterSettings(); - importer.ReadTextureSettings(settings); - settings.sRGBTexture = false; - settings.filterMode = FilterMode.Bilinear; - settings.generateCubemap = TextureImporterGenerateCubemap.AutoCubemap; - settings.cubemapConvolution = TextureImporterCubemapConvolution.None; - settings.seamlessCubemap = false; - settings.wrapMode = TextureWrapMode.Repeat; - settings.aniso = 1; - importer.SetTextureSettings(settings); - importer.mipmapEnabled = false; - importer.textureCompression = hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCacheCompressed - ? TextureImporterCompression.Compressed - : TextureImporterCompression.Uncompressed; - importer.textureShape = TextureImporterShape.TextureCube; - importer.SaveAndReimport(); - break; - } + { + var importer = AssetImporter.GetAtPath(file) as TextureImporter; + if (importer == null) + return; + var settings = new TextureImporterSettings(); + importer.ReadTextureSettings(settings); + settings.sRGBTexture = false; + settings.filterMode = FilterMode.Bilinear; + settings.generateCubemap = TextureImporterGenerateCubemap.AutoCubemap; + settings.cubemapConvolution = TextureImporterCubemapConvolution.None; + settings.seamlessCubemap = false; + settings.wrapMode = TextureWrapMode.Repeat; + settings.aniso = 1; + importer.SetTextureSettings(settings); + importer.mipmapEnabled = false; + importer.textureCompression = hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCacheCompressed + ? TextureImporterCompression.Compressed + : TextureImporterCompression.Uncompressed; + importer.textureShape = TextureImporterShape.TextureCube; + importer.SaveAndReimport(); + break; + } case ProbeSettings.ProbeType.PlanarProbe: - { - var importer = AssetImporter.GetAtPath(file) as TextureImporter; - if (importer == null) - return; - importer.sRGBTexture = false; - importer.filterMode = FilterMode.Bilinear; - importer.mipmapEnabled = false; - importer.textureCompression = TextureImporterCompression.Uncompressed; - importer.textureShape = TextureImporterShape.Texture2D; - importer.SaveAndReimport(); - break; - } + { + var importer = AssetImporter.GetAtPath(file) as TextureImporter; + if (importer == null) + return; + importer.sRGBTexture = false; + importer.filterMode = FilterMode.Bilinear; + importer.mipmapEnabled = false; + importer.textureCompression = TextureImporterCompression.Uncompressed; + importer.textureShape = TextureImporterShape.Texture2D; + importer.SaveAndReimport(); + break; + } } } @@ -776,9 +775,9 @@ private static void CreateAndImportDummyBakedTextureIfRequired(HDProbe probe, st static Func GetGICachePath = Expression.Lambda>( Expression.Call( typeof(Lightmapping) - .GetProperty("diskCachePath", BindingFlags.Static | BindingFlags.NonPublic) - .GetGetMethod(true) + .GetProperty("diskCachePath", BindingFlags.Static | BindingFlags.NonPublic) + .GetGetMethod(true) ) - ).Compile(); + ).Compile(); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeEditor.cs index 2d1625dcc18..864f398b4f4 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeEditor.cs @@ -95,24 +95,24 @@ protected virtual void Draw(TSerialized serialized, Editor owner) CoreEditorDrawer.FoldoutGroup(HDProbeUI.k_InfluenceVolumeHeader, HDProbeUI.Expandable.Influence, HDProbeUI.k_ExpandedState, HDProbeUI.Drawer.DrawInfluenceSettings, HDProbeUI.Drawer_DifferentShapeError - ), + ), CoreEditorDrawer.AdvancedFoldoutGroup(HDProbeUI.k_CaptureSettingsHeader, HDProbeUI.Expandable.Capture, HDProbeUI.k_ExpandedState, (s, o) => s.GetEditorOnlyData(SerializedHDProbe.EditorOnlyData.CaptureSettingsIsAdvanced), (s, o) => s.ToggleEditorOnlyData(SerializedHDProbe.EditorOnlyData.CaptureSettingsIsAdvanced), CoreEditorDrawer.Group( DrawAdditionalCaptureSettings, HDProbeUI.Drawer.DrawCaptureSettings - ), + ), HDProbeUI.Drawer.DrawAdvancedCaptureSettings - ), + ), CoreEditorDrawer.FoldoutGroup(HDProbeUI.k_CustomSettingsHeader, HDProbeUI.Expandable.Custom, HDProbeUI.k_ExpandedState, HDProbeUI.Drawer.DrawCustomSettings), CoreEditorDrawer.Group(HDProbeUI.Drawer.DrawBakeButton) ).Draw(serialized, owner); } - protected virtual void DrawHandles(TSerialized serialized, Editor owner) { } - protected virtual void DrawAdditionalCaptureSettings(TSerialized serialiezed, Editor owner) { } + protected virtual void DrawHandles(TSerialized serialized, Editor owner) {} + protected virtual void DrawAdditionalCaptureSettings(TSerialized serialiezed, Editor owner) {} protected void OnSceneGUI() { @@ -140,12 +140,13 @@ static Func ComputeCapturePointPreviewSizeGetter() ); return lambda.Compile(); } + internal static float capturePointPreviewSize { get { return s_CapturePointPreviewSizeGetter(); } } public FrameSettingsRenderType GetFrameSettingsType() - => GetTarget(target).mode == ProbeSettings.Mode.Realtime - ? FrameSettingsRenderType.RealtimeReflection - : FrameSettingsRenderType.CustomOrBakedReflection; + => GetTarget(target).mode == ProbeSettings.Mode.Realtime + ? FrameSettingsRenderType.RealtimeReflection + : FrameSettingsRenderType.CustomOrBakedReflection; } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs index 81286155f03..422a639306e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs @@ -36,12 +36,12 @@ internal interface IProbeUISettingsProvider } // Constants - const EditMode.SceneViewEditMode EditBaseShape = (EditMode.SceneViewEditMode)100; - const EditMode.SceneViewEditMode EditInfluenceShape = (EditMode.SceneViewEditMode)101; - const EditMode.SceneViewEditMode EditInfluenceNormalShape = (EditMode.SceneViewEditMode)102; - const EditMode.SceneViewEditMode EditCapturePosition = (EditMode.SceneViewEditMode)103; - const EditMode.SceneViewEditMode EditMirrorPosition = (EditMode.SceneViewEditMode)104; - const EditMode.SceneViewEditMode EditMirrorRotation = (EditMode.SceneViewEditMode)105; + const EditMode.SceneViewEditMode EditBaseShape = (EditMode.SceneViewEditMode) 100; + const EditMode.SceneViewEditMode EditInfluenceShape = (EditMode.SceneViewEditMode) 101; + const EditMode.SceneViewEditMode EditInfluenceNormalShape = (EditMode.SceneViewEditMode) 102; + const EditMode.SceneViewEditMode EditCapturePosition = (EditMode.SceneViewEditMode) 103; + const EditMode.SceneViewEditMode EditMirrorPosition = (EditMode.SceneViewEditMode) 104; + const EditMode.SceneViewEditMode EditMirrorRotation = (EditMode.SceneViewEditMode) 105; //Note: EditMode.SceneViewEditMode.ReflectionProbeOrigin is still used //by legacy reflection probe and have its own mecanism that we don't want @@ -102,7 +102,6 @@ static Drawer() k_ListContent[i] = listContent.ToArray(); k_ListModes[i] = listMode.ToArray(); } - } // Tool bars @@ -123,7 +122,7 @@ public static void DrawToolbars(SerializedHDProbe serialized, Editor owner) IHDProbeEditor probeEditor = owner as IHDProbeEditor; int selected = probeEditor.showChromeGizmo ? 0 : -1; int newSelected = GUILayout.Toolbar(selected, new[] { k_ListContent[k_ListModes.Length - 1][0] }, GUILayout.Height(20), GUILayout.Width(30)); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) { //allow deselection if (selected >= 0 && newSelected == selected) @@ -137,7 +136,7 @@ public static void DrawToolbars(SerializedHDProbe serialized, Editor owner) GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } - + public static void DoToolbarShortcutKey(Editor owner) { var provider = new TProvider(); @@ -187,29 +186,30 @@ public static void DrawPrimarySettings(SerializedHDProbe serialized, Editor owne EditorGUILayout.IntPopup(serialized.probeSettings.mode, k_ModeContents, k_ModeValues, k_BakeTypeContent); #if !ENABLE_BAKED_PLANAR - } + } + #endif switch ((ProbeSettings.Mode)serialized.probeSettings.mode.intValue) { case ProbeSettings.Mode.Realtime: - { - EditorGUILayout.PropertyField(serialized.probeSettings.realtimeMode); - break; - } + { + EditorGUILayout.PropertyField(serialized.probeSettings.realtimeMode); + break; + } case ProbeSettings.Mode.Custom: + { + Rect lineRect = EditorGUILayout.GetControlRect(true, 64); + EditorGUI.BeginProperty(lineRect, k_CustomTextureContent, serialized.customTexture); { - Rect lineRect = EditorGUILayout.GetControlRect(true, 64); - EditorGUI.BeginProperty(lineRect, k_CustomTextureContent, serialized.customTexture); - { - EditorGUI.BeginChangeCheck(); - var customTexture = EditorGUI.ObjectField(lineRect, k_CustomTextureContent, serialized.customTexture.objectReferenceValue, provider.customTextureType, false); - if (EditorGUI.EndChangeCheck()) - serialized.customTexture.objectReferenceValue = customTexture; - } - EditorGUI.EndProperty(); - break; + EditorGUI.BeginChangeCheck(); + var customTexture = EditorGUI.ObjectField(lineRect, k_CustomTextureContent, serialized.customTexture.objectReferenceValue, provider.customTextureType, false); + if (EditorGUI.EndChangeCheck()) + serialized.customTexture.objectReferenceValue = customTexture; } + EditorGUI.EndProperty(); + break; + } } } @@ -257,15 +257,15 @@ public static void DrawProjectionSettings(SerializedHDProbe serialized, Editor o k_ProxyInfluenceShapeMismatchHelpBoxText, MessageType.Error, true - ); + ); } else { EditorGUILayout.HelpBox( - serialized.probeSettings.proxyUseInfluenceVolumeAsProxyVolume.boolValue ? k_NoProxyHelpBoxText : k_NoProxyInfiniteHelpBoxText, - MessageType.Info, - true - ); + serialized.probeSettings.proxyUseInfluenceVolumeAsProxyVolume.boolValue ? k_NoProxyHelpBoxText : k_NoProxyInfiniteHelpBoxText, + MessageType.Info, + true + ); } } @@ -309,59 +309,59 @@ public static void DrawBakeButton(SerializedHDProbe serialized, Editor owner) switch (mode) { case ProbeSettings.Mode.Custom: - { - if (ButtonWithDropdownList( - EditorGUIUtility.TrTextContent( - "Bake", "Bakes Probe's texture, overwriting the existing texture asset (if any)." + { + if (ButtonWithDropdownList( + EditorGUIUtility.TrTextContent( + "Bake", "Bakes Probe's texture, overwriting the existing texture asset (if any)." ), - k_BakeCustomOptionText, - data => - { - switch ((int)data) - { - case 0: - RenderInCustomAsset(serialized.target, false); - break; - } - })) + k_BakeCustomOptionText, + data => { - RenderInCustomAsset(serialized.target, true); - } - break; + switch ((int)data) + { + case 0: + RenderInCustomAsset(serialized.target, false); + break; + } + })) + { + RenderInCustomAsset(serialized.target, true); } + break; + } case ProbeSettings.Mode.Baked: - { + { #pragma warning disable 618 - if (UnityEditor.Lightmapping.giWorkflowMode - != UnityEditor.Lightmapping.GIWorkflowMode.OnDemand) - { - EditorGUILayout.HelpBox("Baking of this probe is automatic because this probe's type is 'Baked' and the Lighting window is using 'Auto Baking'. The texture created is stored in the GI cache.", MessageType.Info); - break; - } + if (UnityEditor.Lightmapping.giWorkflowMode + != UnityEditor.Lightmapping.GIWorkflowMode.OnDemand) + { + EditorGUILayout.HelpBox("Baking of this probe is automatic because this probe's type is 'Baked' and the Lighting window is using 'Auto Baking'. The texture created is stored in the GI cache.", MessageType.Info); + break; + } #pragma warning restore 618 - GUI.enabled = serialized.target.enabled; - - // Bake button in non-continous mode - if (ButtonWithDropdownList( - EditorGUIUtility.TrTextContent("Bake"), - k_BakeButtonsText, - data => - { - if ((int)data == 0) - { - var system = ScriptableBakedReflectionSystemSettings.system; - system.BakeAllReflectionProbes(); - } - }, - GUILayout.ExpandWidth(true))) - { - HDBakedReflectionSystem.BakeProbes(serialized.serializedObject.targetObjects.OfType().ToArray()); - GUIUtility.ExitGUI(); - } + GUI.enabled = serialized.target.enabled; - GUI.enabled = true; - break; + // Bake button in non-continous mode + if (ButtonWithDropdownList( + EditorGUIUtility.TrTextContent("Bake"), + k_BakeButtonsText, + data => + { + if ((int)data == 0) + { + var system = ScriptableBakedReflectionSystemSettings.system; + system.BakeAllReflectionProbes(); + } + }, + GUILayout.ExpandWidth(true))) + { + HDBakedReflectionSystem.BakeProbes(serialized.serializedObject.targetObjects.OfType().ToArray()); + GUIUtility.ExitGUI(); } + + GUI.enabled = true; + break; + } case ProbeSettings.Mode.Realtime: break; default: throw new ArgumentOutOfRangeException(); @@ -424,7 +424,7 @@ static internal void Drawer_DifferentShapeError(SerializedHDProbe serialized, Ed k_ProxyInfluenceShapeMismatchHelpBoxText, MessageType.Error, true - ); + ); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Handles.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Handles.cs index b2bcfe502dd..8f41faca410 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Handles.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Handles.cs @@ -25,41 +25,41 @@ internal static void DrawHandles(SerializedHDProbe serialized, Editor owner) break; case EditCapturePosition: case EditMirrorPosition: - { - var proxyToWorldMatrix = probe.proxyToWorld; - - SerializedProperty target; - switch (EditMode.editMode) - { - case EditCapturePosition: target = serialized.probeSettings.proxyCapturePositionProxySpace; break; - case EditMirrorPosition: target = serialized.probeSettings.proxyMirrorPositionProxySpace; break; - default: throw new ArgumentOutOfRangeException(); - } + { + var proxyToWorldMatrix = probe.proxyToWorld; - var position = proxyToWorldMatrix.MultiplyPoint(target.vector3Value); - EditorGUI.BeginChangeCheck(); - position = Handles.PositionHandle(position, proxyToWorldMatrix.rotation); - if (EditorGUI.EndChangeCheck()) - target.vector3Value = proxyToWorldMatrix.inverse.MultiplyPoint(position); - break; + SerializedProperty target; + switch (EditMode.editMode) + { + case EditCapturePosition: target = serialized.probeSettings.proxyCapturePositionProxySpace; break; + case EditMirrorPosition: target = serialized.probeSettings.proxyMirrorPositionProxySpace; break; + default: throw new ArgumentOutOfRangeException(); } + + var position = proxyToWorldMatrix.MultiplyPoint(target.vector3Value); + EditorGUI.BeginChangeCheck(); + position = Handles.PositionHandle(position, proxyToWorldMatrix.rotation); + if (EditorGUI.EndChangeCheck()) + target.vector3Value = proxyToWorldMatrix.inverse.MultiplyPoint(position); + break; + } case EditMirrorRotation: - { - var proxyToWorldMatrix = probe.proxyToWorld; + { + var proxyToWorldMatrix = probe.proxyToWorld; - var target = serialized.probeSettings.proxyMirrorRotationProxySpace; - var position = serialized.probeSettings.proxyMirrorPositionProxySpace.vector3Value; + var target = serialized.probeSettings.proxyMirrorRotationProxySpace; + var position = serialized.probeSettings.proxyMirrorPositionProxySpace.vector3Value; - using (new Handles.DrawingScope(proxyToWorldMatrix)) - { - var rotation = target.quaternionValue; - EditorGUI.BeginChangeCheck(); - rotation = Handles.RotationHandle(rotation, position); - if (EditorGUI.EndChangeCheck()) - target.quaternionValue = rotation; - } - break; + using (new Handles.DrawingScope(proxyToWorldMatrix)) + { + var rotation = target.quaternionValue; + EditorGUI.BeginChangeCheck(); + rotation = Handles.RotationHandle(rotation, position); + if (EditorGUI.EndChangeCheck()) + target.quaternionValue = rotation; } + break; + } } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Skin.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Skin.cs index 7387b917d6c..2b996822faf 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Skin.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Skin.cs @@ -40,6 +40,6 @@ static partial class HDProbeUI #else "ReflectionProbe Gizmo" #endif - ; + ; } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs index c4e95219185..89fd3191d0f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.Gizmos.cs @@ -30,9 +30,9 @@ static void DrawSelectedGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoTy static void Gizmos_CapturePoint(ReflectionProbe target) { - if(sphere == null) + if (sphere == null) sphere = Resources.GetBuiltinResource("New-Sphere.fbx"); - if(material == null) + if (material == null) material = new Material(Shader.Find("Debug/ReflectionProbePreview")); var probe = target.GetComponent(); var probePositionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, null); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs index 25a968e07a9..a4b46e0be98 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDReflectionProbeEditor.cs @@ -44,6 +44,7 @@ static void ResetReflectionProbe(MenuCommand menuCommand) // Note: we can't call this code inside the HDAdditionalReflectionData, thus why we don't wrap it in Reset() function EditorUtility.CopySerialized(HDUtils.s_DefaultHDAdditionalReflectionData, reflectionProbeAdditionalData); } + #endregion protected override void OnEnable() diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDScreenSpaceReflectionEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDScreenSpaceReflectionEditor.cs index 5b5b5549f5c..5ec10a2f4e2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDScreenSpaceReflectionEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDScreenSpaceReflectionEditor.cs @@ -152,12 +152,12 @@ void RayTracedReflectionGUI() { RayTracingPerformanceModeGUI(); } - break; + break; case RayTracingMode.Quality: { RayTracingQualityModeGUI(); } - break; + break; } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs index c190f4ac8c7..5d6d02f92e1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbeEditor.cs @@ -13,7 +13,7 @@ namespace UnityEditor.Rendering.HighDefinition sealed class PlanarReflectionProbeEditor : HDProbeEditor { public static Material GUITextureBlit2SRGBMaterial - => HDRenderPipeline.defaultAsset.renderPipelineEditorResources.materials.GUITextureBlit2SRGB; + => HDRenderPipeline.defaultAsset.renderPipelineEditorResources.materials.GUITextureBlit2SRGB; const float k_PreviewHeight = 128; @@ -74,10 +74,10 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) var row = i / rowSize; var col = i % rowSize; var itemRect = new Rect( - r.x + size.x * row + ((row > 0) ? (row - 1) * space.x : 0), - r.y + size.y * col + ((col > 0) ? (col - 1) * space.y : 0), - size.x, - size.y); + r.x + size.x * row + ((row > 0) ? (row - 1) * space.x : 0), + r.y + size.y * col + ((col > 0) ? (col - 1) * space.y : 0), + size.x, + size.y); if (m_PreviewedTextures[i] != null) EditorGUI.DrawPreviewTexture(itemRect, m_PreviewedTextures[i], previewMaterial, ScaleMode.ScaleToFit, 0, 1); @@ -332,13 +332,13 @@ struct PlanarReflectionProbeUISettingsProvider : HDProbeUI.IProbeUISettingsProvi camera = new CameraSettingsOverride { camera = (CameraSettingsFields)(-1) & ~( - CameraSettingsFields.flipYMode - | CameraSettingsFields.frustumAspect - | CameraSettingsFields.cullingInvertFaceCulling - | CameraSettingsFields.frustumMode - | CameraSettingsFields.frustumProjectionMatrix - | CameraSettingsFields.frustumFieldOfView - ) + CameraSettingsFields.flipYMode + | CameraSettingsFields.frustumAspect + | CameraSettingsFields.cullingInvertFaceCulling + | CameraSettingsFields.frustumMode + | CameraSettingsFields.frustumProjectionMatrix + | CameraSettingsFields.frustumFieldOfView + ) } }; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ProbeSettingsUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ProbeSettingsUI.Drawers.cs index 8489529cb4b..e8d31d1a78b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ProbeSettingsUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ProbeSettingsUI.Drawers.cs @@ -32,7 +32,6 @@ ProbeSettingsOverride displayedFields if ((displayedFields.probe & lighting) != 0) { - using (new EditorGUI.DisabledScope(!hd.currentPlatformRenderPipelineSettings.supportLightLayers)) { PropertyFieldWithoutToggle(ProbeSettingsFields.lightingLightLayer, serialized.lightingLightLayer, EditorGUIUtility.TrTextContent("Light Layer", "Specifies the Light Layer the Reflection Probe uses to capture its view of the Scene. The Probe only uses Lights on the Light Layer you specify."), displayedFields.probe, @@ -85,7 +84,7 @@ ProbeSettingsOverride displayedFields CameraSettingsUI.Draw(serialized.cameraSettings, owner, displayedFields.camera); // Only display the field if it should - if (((int)ProbeSettingsFields.resolution & (int)displayedFields.probe) != 0 ) + if (((int)ProbeSettingsFields.resolution & (int)displayedFields.probe) != 0) { var scalableSetting = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.planarReflectionResolution; serialized.resolutionScalable.LevelAndEnumGUILayout( @@ -94,7 +93,7 @@ ProbeSettingsOverride displayedFields } PropertyFieldWithoutToggle(ProbeSettingsFields.roughReflections, serialized.roughReflections, EditorGUIUtility.TrTextContent("Rough Reflections", "When disabled the reflections evaluated using the planar reflection will be perfectly smooth. This save GPU time when the planar reflection is used as a pure mirror."), displayedFields.probe); - + if ((displayedFields.probe & proxy) != 0) { PropertyFieldWithoutToggle(ProbeSettingsFields.lightingRangeCompression, serialized.lightingRangeCompressionFactor, EditorGUIUtility.TrTextContent("Range Compression Factor", "The result of the rendering of the probe will be divided by this factor. When the probe is read, this factor is undone as the probe data is read. This is to simply avoid issues with values clamping due to precision of the storing format."), displayedFields.probe); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedCameraSettings.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedCameraSettings.cs index 7d10a9ac3a8..bcbf6a3e7fd 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedCameraSettings.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedCameraSettings.cs @@ -48,7 +48,7 @@ internal SerializedCameraSettings(SerializedProperty root) frameSettings = new SerializedFrameSettings( root.Find((CameraSettings s) => s.renderingPathCustomFrameSettings), root.Find((CameraSettings s) => s.renderingPathCustomFrameSettingsOverrideMask) - ); + ); bufferClearColorMode = root.FindPropertyRelative("bufferClearing.clearColorMode"); bufferClearBackgroundColorHDR = root.FindPropertyRelative("bufferClearing.backgroundColorHDR"); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedHDProbe.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedHDProbe.cs index f38908a0c80..7ad07c5fef0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedHDProbe.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/SerializedHDProbe.cs @@ -50,12 +50,12 @@ internal virtual void Apply() serializedObject.ApplyModifiedProperties(); } - internal bool GetEditorOnlyData(EditorOnlyData mask) => (editorOnlyData.intValue & (int) mask) == (int) mask; + internal bool GetEditorOnlyData(EditorOnlyData mask) => (editorOnlyData.intValue & (int)mask) == (int)mask; internal void SetEditorOnlyData(EditorOnlyData mask, bool value) { if (value) - editorOnlyData.intValue |= (int) mask; + editorOnlyData.intValue |= (int)mask; else editorOnlyData.intValue &= ~(int)mask; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs index f1f9eb3f08e..15b7fbcc8fe 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Drawers.cs @@ -82,7 +82,7 @@ static void Drawer_SectionShapeBox(SerializedInfluenceVolume serialized, Editor Vector3 blendNormalPositive = serialized.boxBlendNormalDistancePositive.vector3Value; Vector3 blendNormalNegative = serialized.boxBlendNormalDistanceNegative.vector3Value; Vector3 size = serialized.boxSize.vector3Value; - for(int i = 0; i<3; ++i) + for (int i = 0; i < 3; ++i) { size[i] = Mathf.Max(0f, size[i]); } @@ -163,7 +163,7 @@ static void Drawer_AdvancedBlendDistance(SerializedInfluenceVolume serialized, b if (serialized.editorAdvancedModeEnabled.boolValue) { if (!(Mathf.Approximately(Vector3.SqrMagnitude(blendDistancePositive.vector3Value - editorAdvancedModeBlendDistancePositive.vector3Value), 0f) - && Mathf.Approximately(Vector3.SqrMagnitude(blendDistanceNegative.vector3Value - editorAdvancedModeBlendDistanceNegative.vector3Value), 0f))) + && Mathf.Approximately(Vector3.SqrMagnitude(blendDistanceNegative.vector3Value - editorAdvancedModeBlendDistanceNegative.vector3Value), 0f))) { blendDistancePositive.vector3Value = editorAdvancedModeBlendDistancePositive.vector3Value; blendDistanceNegative.vector3Value = editorAdvancedModeBlendDistanceNegative.vector3Value; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs index 644e16383a4..de0aaf20455 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Handles.cs @@ -102,7 +102,7 @@ public static void DrawHandles_EditInfluenceNormal(SerializedInfluenceVolume ser break; } } - + static void DrawBoxHandle(SerializedInfluenceVolume serialized, Editor owner, Transform transform, HierarchicalBox box) { using (new Handles.DrawingScope(Matrix4x4.TRS(Vector3.zero, transform.rotation, Vector3.one))) diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Skin.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Skin.cs index a39dc89dafe..5ff82b5e86e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Skin.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/InfluenceVolumeUI.Skin.cs @@ -2,7 +2,6 @@ namespace UnityEditor.Rendering.HighDefinition { - partial class InfluenceVolumeUI { // We need to provide gamma values to the Gizmos and Handle because they are translated back to linear diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentEditor.cs index 35805b9f2f5..fee2b265850 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/ReflectionProxyVolumeComponentEditor.cs @@ -40,7 +40,6 @@ public override void OnInspectorGUI() void OnSceneGUI() { - for (int i = 0; i < m_TypedTargets.Length; ++i) { var comp = m_TypedTargets[i]; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs index 4d4f25e68bb..6f0ed9209db 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/Volume/SerializedInfluenceVolume.cs @@ -85,21 +85,21 @@ public SerializedInfluenceVolume(SerializedProperty root) //display old data editorAdvancedModeEnabled.boolValue = - positive.x != positive.y + positive.x != positive.y || positive.x != positive.z || negative.x != negative.y || negative.x != negative.z || positive.x != negative.x; Apply(); } - if(editorAdvancedModeFaceFadePositive.vector3Value == Vector3.one + if (editorAdvancedModeFaceFadePositive.vector3Value == Vector3.one && editorAdvancedModeFaceFadeNegative.vector3Value == Vector3.one && (boxSideFadePositive.vector3Value != Vector3.one || boxSideFadeNegative.vector3Value != Vector3.one)) { editorAdvancedModeFaceFadePositive.vector3Value = boxSideFadePositive.vector3Value; editorAdvancedModeFaceFadeNegative.vector3Value = boxSideFadeNegative.vector3Value; - if(!editorAdvancedModeEnabled.boolValue) + if (!editorAdvancedModeEnabled.boolValue) { boxSideFadePositive.vector3Value = Vector3.one; boxSideFadeNegative.vector3Value = Vector3.one; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/SerializedHDLight.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/SerializedHDLight.cs index 3c994cc7bed..8b8f115b53a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/SerializedHDLight.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/SerializedHDLight.cs @@ -123,8 +123,8 @@ internal class SerializedHDLight public HDLightType type { get => haveMultipleTypeValue - ? (HDLightType)(-1) //as serialize property on enum when mixed value state happens - : (serializedObject.targetObjects[0] as HDAdditionalLightData).type; + ? (HDLightType)(-1) //as serialize property on enum when mixed value state happens + : (serializedObject.targetObjects[0] as HDAdditionalLightData).type; set { //Note: type is split in both component @@ -170,8 +170,8 @@ void System.IDisposable.Dispose() public AreaLightShape areaLightShape { get => haveMultipleAreaLightShapeValue - ? (AreaLightShape)(-1) //as serialize property on enum when mixed value state happens - : (serializedObject.targetObjects[0] as HDAdditionalLightData).areaLightShape; + ? (AreaLightShape)(-1) //as serialize property on enum when mixed value state happens + : (serializedObject.targetObjects[0] as HDAdditionalLightData).areaLightShape; set { //Note: Disc is actually changing legacyLight.type to Disc @@ -293,7 +293,6 @@ public void UpdateAreaLightEmissiveMeshCastShadow(UnityEngine.Rendering.ShadowCa areaLightEmissiveMeshCastShadow.intValue = (int)shadowCastingMode; if (deportedAreaLightEmissiveMeshCastShadow != null) //only possible while editing from prefab deportedAreaLightEmissiveMeshCastShadow.intValue = (int)shadowCastingMode; - } } @@ -418,7 +417,7 @@ public SerializedHDLight(HDAdditionalLightData[] lightDatas, LightEditor.Setting shadowUpdateUponTransformChange = o.Find("m_UpdateShadowOnLightMovement"); shadowResolution = new SerializedScalableSettingValue(o.Find((HDAdditionalLightData l) => l.shadowResolution)); - slopeBias = o.Find("m_SlopeBias"); + slopeBias = o.Find("m_SlopeBias"); normalBias = o.Find("m_NormalBias"); // private references for prefab handling @@ -467,7 +466,6 @@ public void FetchAreaLightEmissiveMeshComponents() Update(); } - public void Update() { // Case 1182968 diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/ContactShadowsEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/ContactShadowsEditor.cs index 72a622c0293..fa277e6b969 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/ContactShadowsEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/ContactShadowsEditor.cs @@ -65,6 +65,7 @@ public override void OnInspectorGUI() } } } + public override QualitySettingsBlob SaveCustomQualitySettingsAsObject(QualitySettingsBlob settings = null) { if (settings == null) diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/HDShadowSettingsEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/HDShadowSettingsEditor.cs index dd1c8e1bef3..f3e7e661615 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/HDShadowSettingsEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/Shadow/HDShadowSettingsEditor.cs @@ -23,7 +23,6 @@ public HDShadowSettingsEditor() m_State = new EditorPrefBoolFlags(Key); } - public override void OnEnable() { var o = new PropertyFetcher(serializedObject); @@ -167,7 +166,7 @@ public override bool OnGUI(SerializedDataParameter parameter, GUIContent title) float modifiableValue = value.floatValue * max; EditorGUI.BeginChangeCheck(); modifiableValue = EditorGUILayout.Slider(title, modifiableValue, 0f, max); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) value.floatValue = Mathf.Clamp01(modifiableValue / max); return true; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeEditor.cs index 4ae40c4d1ce..7991daf5225 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeEditor.cs @@ -76,7 +76,7 @@ static Vector3 BlendSize(DensityVolume densityVolume) return size - densityVolume.parameters.m_EditorUniformFade * 2f * Vector3.one; } - [DrawGizmo(GizmoType.Selected|GizmoType.Active)] + [DrawGizmo(GizmoType.Selected | GizmoType.Active)] static void DrawGizmosSelected(DensityVolume densityVolume, GizmoType gizmoType) { if (s_BlendBox == null || s_BlendBox.Equals(null) @@ -91,7 +91,7 @@ static void DrawGizmosSelected(DensityVolume densityVolume, GizmoType gizmoType) s_BlendBox.center = CenterBlendLocalPosition(densityVolume); s_BlendBox.size = BlendSize(densityVolume); Color baseColor = densityVolume.parameters.albedo; - baseColor.a = 8/255f; + baseColor.a = 8 / 255f; s_BlendBox.baseColor = baseColor; s_BlendBox.DrawHull(EditMode.editMode == k_EditBlend); @@ -183,12 +183,12 @@ void OnSceneGUI() newSize.x < 0.00001 ? 0 : previousPositiveFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousPositiveFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousPositiveFade.z * previousSize.z / newSize.z - ); + ); Vector3 newNegativeFade = new Vector3( newSize.x < 0.00001 ? 0 : previousNegativeFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousNegativeFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousNegativeFade.z * previousSize.z / newSize.z - ); + ); for (int axeIndex = 0; axeIndex < 3; ++axeIndex) { if (newPositiveFade[axeIndex] + newNegativeFade[axeIndex] > 1) @@ -227,11 +227,11 @@ void OnSceneGUI() { densityVolume.parameters.positiveFade = densityVolume.parameters.negativeFade = - new Vector3( - newSize.x > 0.00001 ? (newSize.x - newUniformFade) / newSize.x : 0f, - newSize.y > 0.00001 ? (newSize.y - newUniformFade) / newSize.y : 0f, - newSize.z > 0.00001 ? (newSize.z - newUniformFade) / newSize.z : 0f - ); + new Vector3( + newSize.x > 0.00001 ? (newSize.x - newUniformFade) / newSize.x : 0f, + newSize.y > 0.00001 ? (newSize.y - newUniformFade) / newSize.y : 0f, + newSize.z > 0.00001 ? (newSize.z - newUniformFade) / newSize.z : 0f + ); } Vector3 delta = densityVolume.transform.rotation * s_ShapeBox.center - densityVolume.transform.position; diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Drawer.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Drawer.cs index 3221169457f..20f66d22017 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Drawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Drawer.cs @@ -25,27 +25,27 @@ enum Expandable ), CED.space, CED.FoldoutGroup(Styles.k_VolumeHeader, Expandable.Volume, k_ExpandedState, - Drawer_VolumeContent + Drawer_VolumeContent ), CED.FoldoutGroup( Styles.k_DensityMaskTextureHeader, Expandable.DensityMaskTexture, k_ExpandedState, Drawer_DensityMaskTextureContent - ) - ); + ) + ); static void Drawer_ToolBar(SerializedDensityVolume serialized, Editor owner) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditMode.DoInspectorToolbar(new[] { DensityVolumeEditor.k_EditShape, DensityVolumeEditor.k_EditBlend }, Styles.s_Toolbar_Contents, () => + { + var bounds = new Bounds(); + foreach (Component targetObject in owner.targets) { - var bounds = new Bounds(); - foreach (Component targetObject in owner.targets) - { - bounds.Encapsulate(targetObject.transform.position); - } - return bounds; - }, + bounds.Encapsulate(targetObject.transform.position); + } + return bounds; + }, owner); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); @@ -56,7 +56,7 @@ static void Drawer_PrimarySettings(SerializedDensityVolume serialized, Editor ow EditorGUILayout.PropertyField(serialized.albedo, Styles.s_AlbedoLabel); EditorGUILayout.PropertyField(serialized.meanFreePath, Styles.s_MeanFreePathLabel); } - + static void Drawer_VolumeContent(SerializedDensityVolume serialized, Editor owner) { //keep previous data as value are stored in percent @@ -80,12 +80,12 @@ static void Drawer_VolumeContent(SerializedDensityVolume serialized, Editor owne newSize.x < 0.00001 ? 0 : previousPositiveFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousPositiveFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousPositiveFade.z * previousSize.z / newSize.z - ); + ); Vector3 newNegativeFade = new Vector3( newSize.x < 0.00001 ? 0 : previousNegativeFade.x * previousSize.x / newSize.x, newSize.y < 0.00001 ? 0 : previousNegativeFade.y * previousSize.y / newSize.y, newSize.z < 0.00001 ? 0 : previousNegativeFade.z * previousSize.z / newSize.z - ); + ); for (int axeIndex = 0; axeIndex < 3; ++axeIndex) { if (newPositiveFade[axeIndex] + newNegativeFade[axeIndex] > 1) diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Skin.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Skin.cs index 1f23d7d3891..a9460538748 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Skin.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/DensityVolumeUI.Skin.cs @@ -24,7 +24,7 @@ internal static class Styles public static readonly GUIContent s_BlendLabel = new GUIContent("Blend Distance", "Interior distance from the Size where the fog fades in completely."); public static readonly GUIContent s_InvertFadeLabel = new GUIContent("Invert Blend", "Inverts blend values so 0 becomes the new maximum value and the original maximum value becomes 0."); public static readonly GUIContent s_ManipulatonTypeContent = EditorGUIUtility.TrTextContent("Per Axis Control", "When checked, each face can be manipulated separatly. This also include fading options."); - + public static readonly GUIContent s_DistanceFadeStartLabel = new GUIContent("Distance Fade Start"); public static readonly GUIContent s_DistanceFadeEndLabel = new GUIContent("Distance Fade End"); diff --git a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/SerializedDensityVolume.cs b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/SerializedDensityVolume.cs index 60b4635569c..11ebeae73c0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/SerializedDensityVolume.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/SerializedDensityVolume.cs @@ -69,7 +69,7 @@ public void Apply() size.vector3Value.x > 0.00001 ? 1f - ((size.vector3Value.x - editorUniformFade.floatValue) / size.vector3Value.x) : 0f, size.vector3Value.y > 0.00001 ? 1f - ((size.vector3Value.y - editorUniformFade.floatValue) / size.vector3Value.y) : 0f, size.vector3Value.z > 0.00001 ? 1f - ((size.vector3Value.z - editorUniformFade.floatValue) / size.vector3Value.z) : 0f - ); + ); } m_SerializedObject.ApplyModifiedProperties(); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/AxF/AxFGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/AxF/AxFGUI.cs index 7b9dd6eecbc..7437454a6a2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/AxF/AxFGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/AxF/AxFGUI.cs @@ -38,9 +38,9 @@ class AxFGUI : HDShaderGUI { new SurfaceOptionUIBlock(MaterialUIBlock.Expandable.Base, features: SurfaceOptionUIBlock.Features.Surface | SurfaceOptionUIBlock.Features.BlendMode | SurfaceOptionUIBlock.Features.DoubleSided | - SurfaceOptionUIBlock.Features.AlphaCutoff | SurfaceOptionUIBlock.Features.AlphaCutoffShadowThreshold | SurfaceOptionUIBlock.Features.DoubleSidedNormalMode | - SurfaceOptionUIBlock.Features.ReceiveSSR | SurfaceOptionUIBlock.Features.ReceiveDecal | SurfaceOptionUIBlock.Features.PreserveSpecularLighting - ), + SurfaceOptionUIBlock.Features.AlphaCutoff | SurfaceOptionUIBlock.Features.AlphaCutoffShadowThreshold | SurfaceOptionUIBlock.Features.DoubleSidedNormalMode | + SurfaceOptionUIBlock.Features.ReceiveSSR | SurfaceOptionUIBlock.Features.ReceiveDecal | SurfaceOptionUIBlock.Features.PreserveSpecularLighting + ), new AxfMainSurfaceInputsUIBlock(MaterialUIBlock.Expandable.Input), new AxfSurfaceInputsUIBlock(MaterialUIBlock.Expandable.Other), new AdvancedOptionsUIBlock(MaterialUIBlock.Expandable.Advance, AdvancedOptionsUIBlock.Features.Instancing | AdvancedOptionsUIBlock.Features.SpecularOcclusion | AdvancedOptionsUIBlock.Features.AddPrecomputedVelocity), @@ -78,7 +78,7 @@ static public Vector4 AxFMappingModeToMask(AxFMappingMode mappingMode) Vector4 mask = Vector4.zero; if (mappingMode <= AxFMappingMode.UV3) { - float X,Y,Z,W; + float X, Y, Z, W; X = (mappingMode == AxFMappingMode.UV0) ? 1.0f : 0.0f; Y = (mappingMode == AxFMappingMode.UV1) ? 1.0f : 0.0f; Z = (mappingMode == AxFMappingMode.UV2) ? 1.0f : 0.0f; @@ -87,7 +87,7 @@ static public Vector4 AxFMappingModeToMask(AxFMappingMode mappingMode) } else if (mappingMode < AxFMappingMode.Triplanar) { - float X,Y,Z,W; + float X, Y, Z, W; X = (mappingMode == AxFMappingMode.PlanarYZ) ? 1.0f : 0.0f; Y = (mappingMode == AxFMappingMode.PlanarZX) ? 1.0f : 0.0f; Z = (mappingMode == AxFMappingMode.PlanarXY) ? 1.0f : 0.0f; @@ -96,7 +96,7 @@ static public Vector4 AxFMappingModeToMask(AxFMappingMode mappingMode) } return mask; } - + // All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change static public void SetupMaterialKeywordsAndPass(Material material) { @@ -127,7 +127,7 @@ static public void SetupMaterialKeywordsAndPass(Material material) CoreUtils.SetKeyword(material, "_PLANAR_LOCAL", planarIsLocal); } - // Note: for ShaderPass defines for vertmesh/varyingmesh setup, we still use the same + // Note: for ShaderPass defines for vertmesh/varyingmesh setup, we still use the same // defines _REQUIRE_UV2 and _REQUIRE_UV3, and thus if eg _REQUIRE_UV3 is defined, _REQUIRE_UV2 will // be assumed to be needed. But here in the AxFData sampling code, we use these to indicate precisely // the single set used (if not using planar/triplanar) only and thus add _REQUIRE_UV1. @@ -156,7 +156,6 @@ static public void SetupMaterialKeywordsAndPass(Material material) { CoreUtils.SetKeyword(material, "_ADD_PRECOMPUTED_VELOCITY", material.GetInt(kAddPrecomputedVelocity) != 0); } - } } } // namespace UnityEditor diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.Skin.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.Skin.cs index 2c7d3be0994..98a337c4a73 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.Skin.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.Skin.cs @@ -9,7 +9,8 @@ partial class DecalProjectorEditor const string k_EditUVTooltip = "Modify the UV positions only"; static readonly GUIContent k_SizeContent = EditorGUIUtility.TrTextContent("Size", "Sets the size of the projector."); - static readonly GUIContent[] k_SizeSubContent = new[] { + static readonly GUIContent[] k_SizeSubContent = new[] + { EditorGUIUtility.TrTextContent("Width", "Sets the width of the projection plan."), EditorGUIUtility.TrTextContent("Height", "Sets the height of the projection plan.") }; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs index b9fbacf7f6c..48030f56d53 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs @@ -175,7 +175,7 @@ public void UpdateMaterialEditor() for (int index = 0; index < targets.Length; ++index) { DecalProjector decalProjector = (targets[index] as DecalProjector); - if((decalProjector != null) && (decalProjector.material != null)) + if ((decalProjector != null) && (decalProjector.material != null)) validMaterialsCount++; } // Update material editor with the new material @@ -185,7 +185,7 @@ public void UpdateMaterialEditor() { DecalProjector decalProjector = (targets[index] as DecalProjector); - if((decalProjector != null) && (decalProjector.material != null)) + if ((decalProjector != null) && (decalProjector.material != null)) materials[validMaterialsCount++] = (targets[index] as DecalProjector).material; } m_MaterialEditor = (MaterialEditor)CreateEditor(materials); @@ -322,7 +322,7 @@ static void DrawGizmosSelected(DecalProjector decalProjector, GizmoType gizmoTyp Vector2 size = new Vector2( (decalProjector.uvScale.x > 100000 || decalProjector.uvScale.x < -100000 ? 0f : 1f / decalProjector.uvScale.x) * decalProjector.size.x, (decalProjector.uvScale.y > 100000 || decalProjector.uvScale.y < -100000 ? 0f : 1f / decalProjector.uvScale.y) * decalProjector.size.y - ); + ); Vector2 start = (Vector2)projectedPivot - new Vector2(decalProjector.uvBias.x * size.x, decalProjector.uvBias.y * size.y); Handles.DrawDottedLines( new Vector3[] @@ -376,7 +376,7 @@ public override void OnInspectorGUI() EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); - + Rect rect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector2, k_SizeContent)); EditorGUI.BeginProperty(rect, k_SizeSubContent[0], m_SizeValues[0]); EditorGUI.BeginProperty(rect, k_SizeSubContent[1], m_SizeValues[1]); @@ -434,7 +434,7 @@ public override void OnInspectorGUI() if (!decalLayerEnabled) { EditorGUILayout.HelpBox("Enable 'Decal Layers' in your HDRP Asset if you want to control the Angle Fade. There is a performance cost of enabling this option.", - MessageType.Info); + MessageType.Info); } EditorGUILayout.PropertyField(m_UVScaleProperty, k_UVScaleContent); @@ -469,7 +469,7 @@ public override void OnInspectorGUI() var hdrp = HDRenderPipeline.currentAsset; if (hdrp != null) { - foreach(var decalProjector in targets) + foreach (var decalProjector in targets) { var mat = (decalProjector as DecalProjector).material; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs index 3c5821bfb9a..0bbf6e52dd1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/CreateDecalShaderGraph.cs @@ -11,8 +11,8 @@ public static void CreateDecalGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(DecalSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -27,7 +27,7 @@ public static void CreateDecalGraph() BlockFields.SurfaceDescription.Emission, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs index 37bfb6a6986..d03242d52ba 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.Migration.cs @@ -18,7 +18,7 @@ sealed partial class DecalSubTarget : HDSubTarget, ILegacyTarget, IRequiresData< public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is DecalMasterNode1 decalMasterNode)) + if (!(masterNode is DecalMasterNode1 decalMasterNode)) return false; m_MigrateFromOldSG = true; @@ -54,13 +54,13 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(); - foreach(DecalMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(DecalMasterNode1.SlotMask))) + foreach (DecalMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(DecalMasterNode1.SlotMask))) { - if(decalMasterNode.MaterialTypeUsesSlotMask(slotMask)) + if (decalMasterNode.MaterialTypeUsesSlotMask(slotMask)) { - if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + if (!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) continue; - + var slotId = Mathf.Log((int)slotMask, 2); blockMap.Add(blockFieldDescriptor, (int)slotId); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs index 92fa4e2f24a..491477d5573 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Decal/ShaderGraph/DecalSubTarget.cs @@ -61,7 +61,7 @@ protected override void CollectPassKeywords(ref PassDescriptor pass) // Emissive pass only have the emission keyword if (!(pass.lightMode == DecalSystem.s_MaterialDecalPassNames[(int)DecalSystem.MaterialDecalPass.DecalProjectorForwardEmissive] || - pass.lightMode == DecalSystem.s_MaterialDecalPassNames[(int)DecalSystem.MaterialDecalPass.DecalMeshForwardEmissive])) + pass.lightMode == DecalSystem.s_MaterialDecalPassNames[(int)DecalSystem.MaterialDecalPass.DecalMeshForwardEmissive])) { if (decalData.affectsAlbedo) pass.keywords.Add(DecalDefines.Albedo); @@ -98,7 +98,7 @@ public override void GetFields(ref TargetFieldContext context) context.AddField(AffectsSmoothness, decalData.affectsSmoothness); context.AddField(AffectsMaskMap, decalData.affectsMaskmap); context.AddField(DecalDefault, decalData.affectsAlbedo || decalData.affectsNormal || decalData.affectsMetal || - decalData.affectsAO || decalData.affectsSmoothness ); + decalData.affectsAO || decalData.affectsSmoothness); context.AddField(Fields.LodCrossFade, decalData.supportLodCrossFade); } @@ -167,7 +167,8 @@ public override void CollectShaderProperties(PropertyCollector collector, Genera void AddAffectsProperty(string referenceName) { - collector.AddShaderProperty(new BooleanShaderProperty{ + collector.AddShaderProperty(new BooleanShaderProperty + { overrideReferenceName = referenceName, hidden = true, value = true, @@ -186,7 +187,8 @@ void AddStencilProperty(string referenceName) void AddColorMaskProperty(string referenceName) { - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { overrideReferenceName = referenceName, floatType = FloatType.Integer, hidden = true, @@ -194,7 +196,7 @@ void AddColorMaskProperty(string referenceName) } } -#region SubShaders + #region SubShaders static class SubShaders { // Relies on the order shader passes are declared in DecalSystem.cs @@ -344,9 +346,9 @@ public static class DecalPasses includes = DecalIncludes.Default, }; } -#endregion + #endregion -#region BlockMasks + #region BlockMasks static class DecalBlockMasks { public static BlockFieldDescriptor[] FragmentDefault = new BlockFieldDescriptor[] @@ -379,9 +381,9 @@ static class DecalBlockMasks BlockFields.SurfaceDescription.Emission, }; } -#endregion + #endregion -#region RequiredFields + #region RequiredFields static class DecalRequiredFields { public static FieldCollection Mesh = new FieldCollection() @@ -394,9 +396,9 @@ static class DecalRequiredFields HDStructFields.FragInputs.texCoord0, }; } -#endregion + #endregion -#region RenderStates + #region RenderStates static class DecalRenderStates { readonly static string s_DecalColorMask = "ColorMask [_DecalColorMask0]\n\tColorMask [_DecalColorMask1] 1\n\tColorMask [_DecalColorMask2] 2\n\tColorMask [_DecalColorMask3] 3"; @@ -459,9 +461,9 @@ static class DecalRenderStates { RenderState.ZTest(ZTest.LEqual) }, }; } -#endregion + #endregion -#region Pragmas + #region Pragmas static class DecalPragmas { public static PragmaCollection Instanced = new PragmaCollection @@ -538,9 +540,9 @@ static class Descriptors public static KeywordCollection Decals = new KeywordCollection { { Descriptors.Decals } }; } -#endregion + #endregion -#region Includes + #region Includes static class DecalIncludes { const string kPacking = "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl"; @@ -570,6 +572,6 @@ static class DecalIncludes { kPassDecal, IncludeLocation.Postgraph }, }; } -#endregion + #endregion } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.Styles.cs b/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.Styles.cs index a4986f18b7c..bb4fac4865a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.Styles.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.Styles.cs @@ -26,7 +26,7 @@ sealed class Styles public readonly GUIContent[] transmissionModeOptions = new GUIContent[2] { new GUIContent("Thick Object", "Choose this mode for thick objects. For performance reasons, transmitted light ignores occlusion (shadows)."), - new GUIContent("Thin Object", "Choose this mode for thin objects, such as paper or leaves. Transmitted light reuses the shadowing state of the surface.") + new GUIContent("Thin Object", "Choose this mode for thin objects, such as paper or leaves. Transmitted light reuses the shadowing state of the surface.") }; public readonly GUIContent profileMinMaxThickness = new GUIContent("Thickness Remap Values (Min-Max)", "Shows the values of the thickness remap below (in millimeters)."); public readonly GUIContent profileThicknessRemap = new GUIContent("Thickness Remap (Min-Max)", "Remaps the thickness parameter from [0, 1] to the desired range (in millimeters)."); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.cs index e061c8844f4..d3893fa1a17 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DiffusionProfileSettingsEditor.cs @@ -155,7 +155,7 @@ void RenderPreview(Profile profile) float r = obj.filterRadius; var S = obj.shapeParam; - m_ProfileMaterial.SetFloat( HDShaderIDs._MaxRadius, r); + m_ProfileMaterial.SetFloat(HDShaderIDs._MaxRadius, r); m_ProfileMaterial.SetVector(HDShaderIDs._ShapeParam, S); // Draw the profile. diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs index 08fa579a845..016a645f085 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/CreateEyeShaderGraph.cs @@ -11,16 +11,16 @@ public static void CreateEyeGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(EyeSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, BlockFields.SurfaceDescription.BaseColor, - BlockFields.SurfaceDescription.NormalTS, - HDBlockFields.SurfaceDescription.IrisNormalTS, + BlockFields.SurfaceDescription.NormalTS, + HDBlockFields.SurfaceDescription.IrisNormalTS, HDBlockFields.SurfaceDescription.BentNormal, - BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Smoothness, HDBlockFields.SurfaceDescription.IOR, BlockFields.SurfaceDescription.Occlusion, HDBlockFields.SurfaceDescription.Mask, @@ -28,7 +28,7 @@ public static void CreateEyeGraph() BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs index e249bdbeb66..c33802a2146 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs index d9cc4c52f4b..c7fb12a557f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.Migration.cs @@ -18,7 +18,7 @@ sealed partial class EyeSubTarget : LightingSubTarget, ILegacyTarget, IRequiresD public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is EyeMasterNode1 eyeMasterNode)) + if (!(masterNode is EyeMasterNode1 eyeMasterNode)) return false; m_MigrateFromOldSG = true; @@ -51,7 +51,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(); - foreach(EyeMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(EyeMasterNode1.SlotMask))) + foreach (EyeMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(EyeMasterNode1.SlotMask))) { - if(eyeMasterNode.MaterialTypeUsesSlotMask(slotMask)) + if (eyeMasterNode.MaterialTypeUsesSlotMask(slotMask)) { - if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + if (!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) continue; - if(!AdditionalSlotMaskTests(slotMask)) + if (!AdditionalSlotMaskTests(slotMask)) continue; - + var slotId = Mathf.Log((int)slotMask, 2); blockMap.Add(blockFieldDescriptor, (int)slotId); } } // Override Baked GI - if(lightingData.overrideBakedGI) + if (lightingData.overrideBakedGI) { blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, EyeMasterNode1.LightingSlotId); blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, EyeMasterNode1.BackLightingSlotId); } // Depth Offset - if(builtinData.depthOffset) + if (builtinData.depthOffset) { blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, EyeMasterNode1.DepthOffsetSlotId); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs index a57578af5d4..b4d8d3ca9ad 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/EyeSubTarget.cs @@ -72,8 +72,8 @@ public override void GetFields(ref TargetFieldContext context) context.AddField(SubsurfaceScattering, eyeData.subsurfaceScattering && systemData.surfaceType != SurfaceType.Transparent); context.AddField(SpecularAA, lightingData.specularAA && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); } public override void GetActiveBlocks(ref TargetActiveBlockContext context) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CirclePupilAnimation.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CirclePupilAnimation.cs index 66176273593..864603e2aa1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CirclePupilAnimation.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CirclePupilAnimation.cs @@ -33,7 +33,7 @@ static string Unity_CirclePupilAnimation( { AnimatedIrisUV = Vector2.zero; return - @" +@" { // Compute the normalized iris position $precision2 irisUVCentered = (IrisUV - 0.5f) * 2.0f; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CorneaRefraction.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CorneaRefraction.cs index 43a3657f1e3..2f9f988e48b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CorneaRefraction.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/CorneaRefraction.cs @@ -33,7 +33,7 @@ static string Unity_CorneaRefraction( { RefractedPositionOS = Vector3.zero; return - @" +@" { float eta = 1.0 / (CorneaIOR); CorneaNormalOS = normalize(CorneaNormalOS); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/EyeSurfaceTypeDebug.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/EyeSurfaceTypeDebug.cs index eece96b2a3d..0c2060e96b6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/EyeSurfaceTypeDebug.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/EyeSurfaceTypeDebug.cs @@ -31,7 +31,7 @@ static string Unity_EyeSurfaceTypeDebug( { SurfaceColor = Vector3.zero; return - @" +@" { $precision pixelRadius = length(PositionOS.xy); bool isSclera = pixelRadius > IrisRadius; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisLimbalRing.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisLimbalRing.cs index e6f283a6919..e453f8e8320 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisLimbalRing.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisLimbalRing.cs @@ -33,7 +33,7 @@ static string Unity_IrisLimbalRing( { LimbalRingFactor = new Vector1(); return - @" +@" { $precision NdotV = dot(float3(0.0, 0.0, 1.0), ViewDirectionOS); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOffset.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOffset.cs index 1fffbacec69..72cf274234f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOffset.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOffset.cs @@ -30,7 +30,7 @@ static string Unity_IrisOffset( { DisplacedIrisUV = Vector3.zero; return - @" +@" { DisplacedIrisUV = (IrisUV + IrisOffset); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOutOfBoundColorClamp.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOutOfBoundColorClamp.cs index 089f0c2c9ff..1de48a83b91 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOutOfBoundColorClamp.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisOutOfBoundColorClamp.cs @@ -31,7 +31,7 @@ static string Unity_IrisOutOfBoundColorClamp( { OutputColor = Vector3.zero; return - @" +@" { OutputColor = (IrisUV.x < 0.0 || IrisUV.y < 0.0 || IrisUV.x > 1.0 || IrisUV.y > 1.0) ? ClampColor : IrisColor; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisUVLocation.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisUVLocation.cs index 43b2f0e5e04..3d3be987e58 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisUVLocation.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/IrisUVLocation.cs @@ -30,7 +30,7 @@ static string Unity_IrisUVLocation( { IrisUV = Vector3.zero; return - @" +@" { $precision2 irisUVCentered = PositionOS.xy / IrisRadius; IrisUV = (irisUVCentered * 0.5 + $precision2(0.5, 0.5)); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraIrisBlend.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraIrisBlend.cs index e2b6b8420e8..c8711b1a941 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraIrisBlend.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraIrisBlend.cs @@ -48,7 +48,7 @@ static string Unity_ScleraIrisBlend( EyeSmoothness = new Vector1(); SurfaceDiffusionProfile = new Vector1(); return - @" +@" { $precision osRadius = length(PositionOS.xy); $precision innerBlendRegionRadius = IrisRadius - 0.02; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraLimbalRing.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraLimbalRing.cs index cb041784975..c265f808eb8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraLimbalRing.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraLimbalRing.cs @@ -34,7 +34,7 @@ static string Unity_ScleraLimbalRing( { LimbalRingFactor = new Vector1(); return - @" +@" { $precision NdotV = dot($precision3(0.0, 0.0, 1.0), ViewDirectionOS); // Compute the radius of the point inside the eye diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraUVLocation.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraUVLocation.cs index 1d7815b6f59..168899df6ea 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraUVLocation.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/Node/ScleraUVLocation.cs @@ -29,7 +29,7 @@ static string Unity_ScleraUVLocation( { ScleraUV = Vector2.zero; return - @" +@" { ScleraUV = PositionOS.xy + $precision2(0.5, 0.5); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/ShaderPass.template.hlsl b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/ShaderPass.template.hlsl index 5c5dd2bc911..2ef18a55f1f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/ShaderPass.template.hlsl +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Eye/ShaderGraph/ShaderPass.template.hlsl @@ -26,7 +26,7 @@ void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDes // however specularOcclusion can come from the graph, so need to be init here so it can be override. surfaceData.specularOcclusion = 1.0; - // copy across graph values, if defined + // copy across graph values, if defined $SurfaceDescription.BaseColor: surfaceData.baseColor = surfaceDescription.BaseColor; $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusion = surfaceDescription.SpecularOcclusion; $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness; @@ -82,7 +82,7 @@ void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDes bentNormalWS = surfaceData.irisNormalWS; // Use diffuse normal (iris) to fetch GI, unless users provide explicit bent normal (not affected by decals) $BentNormal: GetNormalWS(fragInputs, surfaceDescription.BentNormal, bentNormalWS, doubleSidedConstants); - + #ifdef DEBUG_DISPLAY if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs index d7425d7c14a..f5fc8f5ae5a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/CreateFabricShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph @@ -11,8 +11,8 @@ public static void CreateFabricGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(FabricSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -26,7 +26,7 @@ public static void CreateFabricGraph() BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs index 87384581322..7166a27575a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs index 88558660d60..76d0db8d1d2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.Migration.cs @@ -18,7 +18,7 @@ sealed partial class FabricSubTarget : LightingSubTarget, ILegacyTarget, IRequir public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is FabricMasterNode1 fabricMasterNode)) + if (!(masterNode is FabricMasterNode1 fabricMasterNode)) return false; m_MigrateFromOldSG = true; @@ -98,7 +98,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(); - foreach(FabricMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(FabricMasterNode1.SlotMask))) + foreach (FabricMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(FabricMasterNode1.SlotMask))) { - if(fabricMasterNode.MaterialTypeUsesSlotMask(slotMask)) + if (fabricMasterNode.MaterialTypeUsesSlotMask(slotMask)) { - if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + if (!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) continue; - if(!AdditionalSlotMaskTests(slotMask)) + if (!AdditionalSlotMaskTests(slotMask)) continue; - + var slotId = Mathf.Log((int)slotMask, 2); blockMap.Add(blockFieldDescriptor, (int)slotId); } } // Override Baked GI - if(lightingData.overrideBakedGI) + if (lightingData.overrideBakedGI) { blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, FabricMasterNode1.LightingSlotId); blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, FabricMasterNode1.BackLightingSlotId); } // Depth Offset - if(builtinData.depthOffset) + if (builtinData.depthOffset) { blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, FabricMasterNode1.DepthOffsetSlotId); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs index c43f55c7d40..b9aca89b040 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/FabricSubTarget.cs @@ -58,7 +58,7 @@ protected override SubShaderDescriptor GetRaytracingSubShaderDescriptor() if (fabricData.subsurfaceScattering) descriptor.passes.Add(HDShaderPasses.GenerateRaytracingSubsurface()); - + return descriptor; } @@ -74,8 +74,8 @@ public override void GetFields(ref TargetFieldContext context) context.AddField(EnergyConservingSpecular, fabricData.energyConservingSpecular); context.AddField(SpecularAA, lightingData.specularAA && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); } public override void GetActiveBlocks(ref TargetActiveBlockContext context) @@ -89,7 +89,7 @@ public override void GetActiveBlocks(ref TargetActiveBlockContext context) context.AddBlock(HDBlockFields.SurfaceDescription.Thickness, fabricData.transmission); // Fabric Silk - if(fabricData.materialType == FabricData.MaterialType.Silk) + if (fabricData.materialType == FabricData.MaterialType.Silk) { BlockFieldDescriptor tangentBlock; switch (lightingData.normalDropOffSpace) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/ShaderPass.template.hlsl b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/ShaderPass.template.hlsl index 66cafa3e102..f5c29b40d40 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/ShaderPass.template.hlsl +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Fabric/ShaderGraph/ShaderPass.template.hlsl @@ -94,7 +94,7 @@ void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDes $BentNormal: GetNormalWS(fragInputs, surfaceDescription.BentNormal, bentNormalWS, doubleSidedConstants); surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS); - + #ifdef DEBUG_DISPLAY if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs index 0f0e2541035..9f69c4b34d2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/CreateHairShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph @@ -11,8 +11,8 @@ public static void CreateHairGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(HairSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -32,7 +32,7 @@ public static void CreateHairGraph() HDBlockFields.SurfaceDescription.SecondarySpecularShift, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs index 7c102b59832..7e66d0c2f12 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs index f1d605dca7f..572fe7112f1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.Migration.cs @@ -18,7 +18,7 @@ sealed partial class HairSubTarget : LightingSubTarget, ILegacyTarget, IRequires public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is HairMasterNode1 hairMasterNode)) + if (!(masterNode is HairMasterNode1 hairMasterNode)) return false; m_MigrateFromOldSG = true; @@ -55,7 +55,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(); - foreach(HairMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(HairMasterNode1.SlotMask))) + foreach (HairMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(HairMasterNode1.SlotMask))) { - if(hairMasterNode.MaterialTypeUsesSlotMask(slotMask)) + if (hairMasterNode.MaterialTypeUsesSlotMask(slotMask)) { - if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + if (!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) continue; - if(!AdditionalSlotMaskTests(slotMask)) + if (!AdditionalSlotMaskTests(slotMask)) continue; - + var slotId = Mathf.Log((int)slotMask, 2); blockMap.Add(blockFieldDescriptor, (int)slotId); } } // Specular AA - if(lightingData.specularAA) + if (lightingData.specularAA) { blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, HairMasterNode1.SpecularAAScreenSpaceVarianceSlotId); blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAThreshold, HairMasterNode1.SpecularAAThresholdSlotId); } // Override Baked GI - if(lightingData.overrideBakedGI) + if (lightingData.overrideBakedGI) { blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, HairMasterNode1.LightingSlotId); blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, HairMasterNode1.BackLightingSlotId); } // Depth Offset - if(builtinData.depthOffset) + if (builtinData.depthOffset) { blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, HairMasterNode1.DepthOffsetSlotId); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs index 149a5c15bf2..09e62fdf61a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/HairSubTarget.cs @@ -69,8 +69,8 @@ public override void GetFields(ref TargetFieldContext context) // Misc context.AddField(SpecularAA, lightingData.specularAA && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); } public override void GetActiveBlocks(ref TargetActiveBlockContext context) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/ShaderPass.template.hlsl b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/ShaderPass.template.hlsl index fb134cc319c..bff84c37e40 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/ShaderPass.template.hlsl +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Hair/ShaderGraph/ShaderPass.template.hlsl @@ -118,7 +118,7 @@ void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDes bentNormalWS = N; $BentNormal: GetNormalWS(fragInputs, surfaceDescription.BentNormal, bentNormalWS, doubleSidedConstants); - + #ifdef DEBUG_DISPLAY if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/LayeredLit/LayeredLitGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/LayeredLit/LayeredLitGUI.cs index dd31c5a05ca..3a7cb7b3d06 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/LayeredLit/LayeredLitGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/LayeredLit/LayeredLitGUI.cs @@ -162,7 +162,7 @@ static public void SetupMaterialKeywordsAndPass(Material material) BaseLitGUI.SetupBaseLitMaterialPass(material); SetupLayersMappingKeywords(material); bool receiveSSR = material.GetSurfaceType() == SurfaceType.Opaque ? (material.HasProperty(kReceivesSSR) ? material.GetInt(kReceivesSSR) != 0 : false) - : (material.HasProperty(kReceivesSSRTransparent) ? material.GetInt(kReceivesSSRTransparent) != 0 : false); + : (material.HasProperty(kReceivesSSRTransparent) ? material.GetInt(kReceivesSSRTransparent) != 0 : false); BaseLitGUI.SetupStencil(material, receiveSSR, material.GetMaterialId() == MaterialId.LitSSS); if (material.HasProperty(kAddPrecomputedVelocity)) @@ -370,6 +370,5 @@ public static void SaveMaterialLayers(Material material, Material[] materialLaye materialImporter.userData = JsonUtility.ToJson(layersGUID); } - } } // namespace UnityEditor diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitGUI.cs index 46782df6360..ff8f713fdc8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitGUI.cs @@ -85,7 +85,7 @@ static public void SetupMaterialKeywordsAndPass(Material material) BaseLitGUI.SetupBaseLitKeywords(material); BaseLitGUI.SetupBaseLitMaterialPass(material); bool receiveSSR = material.GetSurfaceType() == SurfaceType.Opaque ? (material.HasProperty(kReceivesSSR) ? material.GetInt(kReceivesSSR) != 0 : false) - : (material.HasProperty(kReceivesSSRTransparent) ? material.GetInt(kReceivesSSRTransparent) != 0 : false); + : (material.HasProperty(kReceivesSSRTransparent) ? material.GetInt(kReceivesSSRTransparent) != 0 : false); BaseLitGUI.SetupStencil(material, receiveSSR, material.GetMaterialId() == MaterialId.LitSSS); if (material.HasProperty(kNormalMapSpace)) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs index c228c74c572..8580096c824 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/LitShaderPreprocessor.cs @@ -29,7 +29,7 @@ protected override bool DoShadersStripper(HDRenderPipelineAsset hdrpAsset, Shade // hitting disk on every invoke. if (shader.IsShaderGraph()) { - if(shader.TryGetMetadataOfType(out var obj)) + if (shader.TryGetMetadataOfType(out var obj)) { isBuiltInLit |= obj.shaderID == HDShaderUtils.ShaderID.SG_Lit; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs index a6b9fbfdaff..e5cd237edb8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs @@ -11,8 +11,8 @@ public static void CreateHDLitGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(HDLitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -26,7 +26,7 @@ public static void CreateHDLitGraph() BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs index 798de0ea7f8..6dfecb331a0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs index c0d3595f8c3..9f96d7a439f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.Migration.cs @@ -20,7 +20,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(coatMaskSlotId); - if(coatMaskSlot == null) + if (coatMaskSlot == null) return false; coatMaskSlot.owner = node; @@ -245,23 +245,23 @@ bool UpgradeCoatMask(HDLitMasterNode1 masterNode) blockMap.Add(BlockFields.VertexDescription.Tangent, HDLitMasterNode1.VertexTangentSlotID); // Now handle the SlotMask cases - foreach(HDLitMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(HDLitMasterNode1.SlotMask))) + foreach (HDLitMasterNode1.SlotMask slotMask in Enum.GetValues(typeof(HDLitMasterNode1.SlotMask))) { - if(hdLitMasterNode.MaterialTypeUsesSlotMask(slotMask)) + if (hdLitMasterNode.MaterialTypeUsesSlotMask(slotMask)) { - if(!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) + if (!blockMapLookup.TryGetValue(slotMask, out var blockFieldDescriptor)) continue; - if(!AdditionalSlotMaskTests(slotMask)) + if (!AdditionalSlotMaskTests(slotMask)) continue; - + var slotId = Mathf.Log((int)slotMask, 2); blockMap.Add(blockFieldDescriptor, (int)slotId); } } - + // Specular AA - if(lightingData.specularAA) + if (lightingData.specularAA) { blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, HDLitMasterNode1.SpecularAAScreenSpaceVarianceSlotId); blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAThreshold, HDLitMasterNode1.SpecularAAThresholdSlotId); @@ -269,9 +269,9 @@ bool UpgradeCoatMask(HDLitMasterNode1 masterNode) // Refraction bool hasRefraction = (systemData.surfaceType == SurfaceType.Transparent && systemData.renderQueueType != HDRenderQueue.RenderQueueType.PreRefraction && litData.refractionModel != ScreenSpaceRefraction.RefractionModel.None); - if(hasRefraction) + if (hasRefraction) { - if(!blockMap.TryGetValue(HDBlockFields.SurfaceDescription.Thickness, out _)) + if (!blockMap.TryGetValue(HDBlockFields.SurfaceDescription.Thickness, out _)) { blockMap.Add(HDBlockFields.SurfaceDescription.Thickness, HDLitMasterNode1.ThicknessSlotId); } @@ -290,14 +290,14 @@ bool UpgradeCoatMask(HDLitMasterNode1 masterNode) } // Override Baked GI - if(lightingData.overrideBakedGI) + if (lightingData.overrideBakedGI) { blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, HDLitMasterNode1.LightingSlotId); blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, HDLitMasterNode1.BackLightingSlotId); } // Depth Offset (Removed from SlotMask because of missing bits) - if(builtinData.depthOffset) + if (builtinData.depthOffset) { blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, HDLitMasterNode1.DepthOffsetSlotId); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs index a4ed5309540..6c8f37f37b9 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/HDLitSubTarget.cs @@ -119,7 +119,7 @@ public override void GetFields(ref TargetFieldContext context) context.AddField(Standard, litData.materialType == HDLitData.MaterialType.Standard); context.AddField(SubsurfaceScattering, litData.materialType == HDLitData.MaterialType.SubsurfaceScattering && systemData.surfaceType != SurfaceType.Transparent); context.AddField(Transmission, (litData.materialType == HDLitData.MaterialType.SubsurfaceScattering && litData.sssTransmission) || - (litData.materialType == HDLitData.MaterialType.Translucent)); + (litData.materialType == HDLitData.MaterialType.Translucent)); context.AddField(Translucent, litData.materialType == HDLitData.MaterialType.Translucent); // Refraction @@ -132,8 +132,8 @@ public override void GetFields(ref TargetFieldContext context) context.AddField(RayTracing, litData.rayTracing); context.AddField(SpecularAA, lightingData.specularAA && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance)); } public override void GetActiveBlocks(ref TargetActiveBlockContext context) @@ -172,14 +172,14 @@ public override void GetActiveBlocks(ref TargetActiveBlockContext context) context.AddBlock(HDBlockFields.SurfaceDescription.Anisotropy, litData.materialType == HDLitData.MaterialType.Anisotropy); context.AddBlock(HDBlockFields.SurfaceDescription.SubsurfaceMask, litData.materialType == HDLitData.MaterialType.SubsurfaceScattering); context.AddBlock(HDBlockFields.SurfaceDescription.Thickness, ((litData.materialType == HDLitData.MaterialType.SubsurfaceScattering || litData.materialType == HDLitData.MaterialType.Translucent) && - (litData.sssTransmission || litData.materialType == HDLitData.MaterialType.Translucent)) || hasRefraction); + (litData.sssTransmission || litData.materialType == HDLitData.MaterialType.Translucent)) || hasRefraction); context.AddBlock(HDBlockFields.SurfaceDescription.DiffusionProfileHash, litData.materialType == HDLitData.MaterialType.SubsurfaceScattering || litData.materialType == HDLitData.MaterialType.Translucent); context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceMask, litData.materialType == HDLitData.MaterialType.Iridescence); context.AddBlock(HDBlockFields.SurfaceDescription.IridescenceThickness, litData.materialType == HDLitData.MaterialType.Iridescence); context.AddBlock(BlockFields.SurfaceDescription.Specular, litData.materialType == HDLitData.MaterialType.SpecularColor); - context.AddBlock(BlockFields.SurfaceDescription.Metallic, litData.materialType == HDLitData.MaterialType.Standard || - litData.materialType == HDLitData.MaterialType.Anisotropy || - litData.materialType == HDLitData.MaterialType.Iridescence); + context.AddBlock(BlockFields.SurfaceDescription.Metallic, litData.materialType == HDLitData.MaterialType.Standard || + litData.materialType == HDLitData.MaterialType.Anisotropy || + litData.materialType == HDLitData.MaterialType.Iridescence); } public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) @@ -189,7 +189,8 @@ public override void CollectShaderProperties(PropertyCollector collector, Genera HDSubShaderUtilities.AddRayTracingProperty(collector, litData.rayTracing); // Refraction model property allow the material inspector to check if refraction is enabled in the shader. - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { floatType = FloatType.Enum, hidden = true, value = (int)litData.refractionModel, diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs index 1412a2e0984..e8371a06b2f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/ShaderGraph/LitSurfaceOptionPropertyBlock.cs @@ -17,7 +17,7 @@ namespace UnityEditor.Rendering.HighDefinition.ShaderGraph class LitSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock { HDLitData litData; - + class Styles { public static GUIContent enableClearCoat = new GUIContent("Clear Coat", "Enable Clear Coat"); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs index 2387634eca8..25c83d3f594 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs @@ -67,7 +67,7 @@ public override void Convert(Material srcMaterial, Material dstMaterial) // Convert _Metallic value from Gamma to Linear, or set to 1 if a map is used float metallicValue = Mathf.Pow(srcMaterial.GetFloat("_Metallic"), 2.2f); - dstMaterial.SetFloat("_Metallic", hasMetallic? 1f : metallicValue); + dstMaterial.SetFloat("_Metallic", hasMetallic ? 1f : metallicValue); } // Occlusion @@ -130,11 +130,11 @@ public override void Convert(Material srcMaterial, Material dstMaterial) Texture2D maskMap; TextureCombiner maskMapCombiner = new TextureCombiner( - metallicMap, 0, // R: Metallic from red - occlusionMap, 1, // G: Occlusion from green - detailMaskMap, 3, // B: Detail Mask from alpha - smoothnessMap, (srcMaterial.shader.name == Standard_Rough) ? -4 : 3 // A: Smoothness Texture from inverse greyscale for roughness setup, or alpha - ); + metallicMap, 0, // R: Metallic from red + occlusionMap, 1, // G: Occlusion from green + detailMaskMap, 3, // B: Detail Mask from alpha + smoothnessMap, (srcMaterial.shader.name == Standard_Rough) ? -4 : 3 // A: Smoothness Texture from inverse greyscale for roughness setup, or alpha + ); string maskMapPath = AssetDatabase.GetAssetPath(srcMaterial); maskMapPath = maskMapPath.Remove(maskMapPath.Length - 4) + "_MaskMap.png"; @@ -164,11 +164,11 @@ public override void Convert(Material srcMaterial, Material dstMaterial) { Texture2D detailMap; TextureCombiner detailCombiner = new TextureCombiner( - TextureCombiner.GetTextureSafe(srcMaterial, "_DetailAlbedoMap", Color.grey), 4, // Albedo (overlay) - TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 1, // Normal Y - TextureCombiner.midGrey, 1, // Smoothness - TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 0 // Normal X - ); + TextureCombiner.GetTextureSafe(srcMaterial, "_DetailAlbedoMap", Color.grey), 4, // Albedo (overlay) + TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 1, // Normal Y + TextureCombiner.midGrey, 1, // Smoothness + TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 0 // Normal X + ); string detailMapPath = AssetDatabase.GetAssetPath(srcMaterial); detailMapPath = detailMapPath.Remove(detailMapPath.Length - 4) + "_DetailMap.png"; detailMap = detailCombiner.Combine(detailMapPath); @@ -214,11 +214,11 @@ public override void Convert(Material srcMaterial, Material dstMaterial) Color hdrEmission = srcMaterial.GetColor("_EmissionColor"); // Get the _EMISSION keyword of the Standard shader - if ( !srcMaterial.IsKeywordEnabled("_EMISSION") ) + if (!srcMaterial.IsKeywordEnabled("_EMISSION")) hdrEmission = Color.black; // Emission toggle of Particle Standard Surface - if( srcMaterial.HasProperty("_EmissionEnabled") ) + if (srcMaterial.HasProperty("_EmissionEnabled")) if (srcMaterial.GetFloat("_EmissionEnabled") == 0) hdrEmission = Color.black; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/MaterialEditorExtension.cs b/com.unity.render-pipelines.high-definition/Editor/Material/MaterialEditorExtension.cs index 55f560d6a87..c8b261ebf1a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/MaterialEditorExtension.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/MaterialEditorExtension.cs @@ -11,7 +11,7 @@ internal static class MaterialEditorExtension public static void InitExpandableState(this MaterialEditor editor) { string key = GetKey(editor); - if(!EditorPrefs.HasKey(key)) + if (!EditorPrefs.HasKey(key)) { EditorPrefs.SetInt(key, (int)defaultExpandedState); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileMaterialPropertyDrawer.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileMaterialPropertyDrawer.cs index a753a9fa10e..c9185930840 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileMaterialPropertyDrawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileMaterialPropertyDrawer.cs @@ -8,7 +8,7 @@ class DiffusionProfileDrawer : MaterialPropertyDrawer { public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) => 0; - public override void OnGUI (Rect position, MaterialProperty prop, String label, MaterialEditor editor) + public override void OnGUI(Rect position, MaterialProperty prop, String label, MaterialEditor editor) { // Find properties var assetProperty = MaterialEditor.GetMaterialProperty(editor.targets, prop.name + "_Asset"); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfilePropertyDrawer.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfilePropertyDrawer.cs index 7602bc65734..139891def2e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfilePropertyDrawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfilePropertyDrawer.cs @@ -26,7 +26,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((DiffusionProfileSettings) evt.newValue); }); + objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((DiffusionProfileSettings)evt.newValue); }); } propertyColorField = objectField; @@ -44,7 +44,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (DiffusionProfileSettings) propertyInfo.GetValue(actualObject), + (DiffusionProfileSettings)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileShaderProperty.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileShaderProperty.cs index f1d7ba49d41..cdf11e64587 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileShaderProperty.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DiffusionProfileShaderProperty.cs @@ -43,7 +43,7 @@ internal override string GetPropertyBlockString() string f2s(float f) => System.Convert.ToDouble(f).ToString("0." + new string('#', 339)); return -$@"[DiffusionProfile]{referenceName}(""{displayName}"", Float) = {f2s(HDShadowUtils.Asfloat(hash))} + $@"[DiffusionProfile]{referenceName}(""{displayName}"", Float) = {f2s(HDShadowUtils.Asfloat(hash))} [HideInInspector]{assetReferenceName}(""{displayName}"", Vector) = ({f2s(asset.x)}, {f2s(asset.y)}, {f2s(asset.z)}, {f2s(asset.w)})"; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs index 2a908b507f7..03483512001 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/DistortionPropertyBlock.cs @@ -29,4 +29,4 @@ protected override void CreatePropertyGUI() } } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDBlockFields.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDBlockFields.cs index e2965ef3248..0d1b3e0566f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDBlockFields.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDBlockFields.cs @@ -33,51 +33,51 @@ public struct SurfaceDescription public static BlockFieldDescriptor TangentWS = new BlockFieldDescriptor(SurfaceDescription.name, "TangentWS", "Tangent (World Space)", "SURFACEDESCRIPTION_TANGENTWS", new TangentControl(CoordinateSpace.World), ShaderStage.Fragment); - public static BlockFieldDescriptor Anisotropy = new BlockFieldDescriptor(SurfaceDescription.name, "Anisotropy", "SURFACEDESCRIPTION_ANISOTROPY", + public static BlockFieldDescriptor Anisotropy = new BlockFieldDescriptor(SurfaceDescription.name, "Anisotropy", "SURFACEDESCRIPTION_ANISOTROPY", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor SubsurfaceMask = new BlockFieldDescriptor(SurfaceDescription.name, "SubsurfaceMask", "Subsurface Mask", "SURFACEDESCRIPTION_SUBSURFACEMASK", + public static BlockFieldDescriptor SubsurfaceMask = new BlockFieldDescriptor(SurfaceDescription.name, "SubsurfaceMask", "Subsurface Mask", "SURFACEDESCRIPTION_SUBSURFACEMASK", new FloatControl(1.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor Thickness = new BlockFieldDescriptor(SurfaceDescription.name, "Thickness", "SURFACEDESCRIPTION_THICKNESS", + public static BlockFieldDescriptor Thickness = new BlockFieldDescriptor(SurfaceDescription.name, "Thickness", "SURFACEDESCRIPTION_THICKNESS", new FloatControl(1.0f), ShaderStage.Fragment); - public static CustomSlotBlockFieldDescriptor DiffusionProfileHash = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "DiffusionProfileHash", "Diffusion Profile", "SURFACEDESCRIPTION_DIFFUSIONPROFILEHASH", + public static CustomSlotBlockFieldDescriptor DiffusionProfileHash = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "DiffusionProfileHash", "Diffusion Profile", "SURFACEDESCRIPTION_DIFFUSIONPROFILEHASH", () => { return new DiffusionProfileInputMaterialSlot(0, "Diffusion Profile", "DiffusionProfileHash", ShaderStageCapability.Fragment); }); - public static BlockFieldDescriptor IridescenceMask = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceMask", "Iridescence Mask", "SURFACEDESCRIPTION_IRIDESCENCEMASK", + public static BlockFieldDescriptor IridescenceMask = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceMask", "Iridescence Mask", "SURFACEDESCRIPTION_IRIDESCENCEMASK", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor IridescenceThickness = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceThickness", "Iridescence Thickness", "SURFACEDESCRIPTION_IRIDESCENCETHICKNESS", + public static BlockFieldDescriptor IridescenceThickness = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceThickness", "Iridescence Thickness", "SURFACEDESCRIPTION_IRIDESCENCETHICKNESS", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor CoatMask = new BlockFieldDescriptor(SurfaceDescription.name, "CoatMask", "Coat Mask", "SURFACEDESCRIPTION_COATMASK", + public static BlockFieldDescriptor CoatMask = new BlockFieldDescriptor(SurfaceDescription.name, "CoatMask", "Coat Mask", "SURFACEDESCRIPTION_COATMASK", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor SpecularOcclusion = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularOcclusion", "Specular Occlusion", "SURFACEDESCRIPTION_SPECULAROCCLUSION", + public static BlockFieldDescriptor SpecularOcclusion = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularOcclusion", "Specular Occlusion", "SURFACEDESCRIPTION_SPECULAROCCLUSION", new FloatControl(1.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor AlphaClipThresholdDepthPrepass = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdDepthPrepass", "Alpha Clip Threshold Depth Prepass", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDDEPTHPREPASS", + public static BlockFieldDescriptor AlphaClipThresholdDepthPrepass = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdDepthPrepass", "Alpha Clip Threshold Depth Prepass", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDDEPTHPREPASS", new FloatControl(0.5f), ShaderStage.Fragment); - public static BlockFieldDescriptor AlphaClipThresholdDepthPostpass = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdDepthPostpass", "Alpha Clip Threshold Depth Postpass", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDDEPTHPOSTPASS", + public static BlockFieldDescriptor AlphaClipThresholdDepthPostpass = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdDepthPostpass", "Alpha Clip Threshold Depth Postpass", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDDEPTHPOSTPASS", new FloatControl(0.5f), ShaderStage.Fragment); - public static BlockFieldDescriptor AlphaClipThresholdShadow = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdShadow", "Alpha Clip Threshold Shadow", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDSHADOW", + public static BlockFieldDescriptor AlphaClipThresholdShadow = new BlockFieldDescriptor(SurfaceDescription.name, "AlphaClipThresholdShadow", "Alpha Clip Threshold Shadow", "SURFACEDESCRIPTION_ALPHACLIPTHRESHOLDSHADOW", new FloatControl(0.5f), ShaderStage.Fragment); - public static BlockFieldDescriptor SpecularAAScreenSpaceVariance = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularAAScreenSpaceVariance", "Specular AA Screen Space Variance", "SURFACEDESCRIPTION_SPECULARAASCEENSPACEVARIANCE", + public static BlockFieldDescriptor SpecularAAScreenSpaceVariance = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularAAScreenSpaceVariance", "Specular AA Screen Space Variance", "SURFACEDESCRIPTION_SPECULARAASCEENSPACEVARIANCE", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor SpecularAAThreshold = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularAAThreshold", "Specular AA Threshold", "SURFACEDESCRIPTION_SPECULARAATHRESHOLD", + public static BlockFieldDescriptor SpecularAAThreshold = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularAAThreshold", "Specular AA Threshold", "SURFACEDESCRIPTION_SPECULARAATHRESHOLD", new FloatControl(0.0f), ShaderStage.Fragment); public static CustomSlotBlockFieldDescriptor BakedGI = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "BakedGI", "Baked GI", "SURFACEDESCRIPTION_BAKEDGI", () => { return new DefaultMaterialSlot(0, "Baked GI", "BakedGI", ShaderStageCapability.Fragment); }); public static CustomSlotBlockFieldDescriptor BakedBackGI = new CustomSlotBlockFieldDescriptor(SurfaceDescription.name, "BakedBackGI", "Baked Back GI", "SURFACEDESCRIPTION_BAKEDBACKGI", () => { return new DefaultMaterialSlot(0, "Baked Back GI", "BakedBackGI", ShaderStageCapability.Fragment); }); - public static BlockFieldDescriptor DepthOffset = new BlockFieldDescriptor(SurfaceDescription.name, "DepthOffset", "Depth Offset", "SURFACEDESCRIPTION_DEPTHOFFSET", + public static BlockFieldDescriptor DepthOffset = new BlockFieldDescriptor(SurfaceDescription.name, "DepthOffset", "Depth Offset", "SURFACEDESCRIPTION_DEPTHOFFSET", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor RefractionIndex = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionIndex", "Refraction Index", "SURFACEDESCRIPTION_REFRACTIONINDEX", + public static BlockFieldDescriptor RefractionIndex = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionIndex", "Refraction Index", "SURFACEDESCRIPTION_REFRACTIONINDEX", new FloatControl(1.0f), ShaderStage.Fragment); public static BlockFieldDescriptor RefractionColor = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionColor", "Refraction Color", "SURFACEDESCRIPTION_REFRACTIONCOLOR", new ColorControl(Color.white, false), ShaderStage.Fragment); - public static BlockFieldDescriptor RefractionDistance = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionDistance", "Refraction Distance", "SURFACEDESCRIPTION_REFRACTIONDISTANCE", + public static BlockFieldDescriptor RefractionDistance = new BlockFieldDescriptor(SurfaceDescription.name, "RefractionDistance", "Refraction Distance", "SURFACEDESCRIPTION_REFRACTIONDISTANCE", new FloatControl(1.0f), ShaderStage.Fragment); // -------------------------------------------------- // Decal - public static BlockFieldDescriptor NormalAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "NormalAlpha", "Normal Alpha", "SURFACEDESCRIPTION_NORMALALPHA", + public static BlockFieldDescriptor NormalAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "NormalAlpha", "Normal Alpha", "SURFACEDESCRIPTION_NORMALALPHA", new FloatControl(1.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor MAOSAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "MAOSAlpha", "MAOS Alpha", "SURFACEDESCRIPTION_MAOSALPHA", + public static BlockFieldDescriptor MAOSAlpha = new BlockFieldDescriptor(SurfaceDescription.name, "MAOSAlpha", "MAOS Alpha", "SURFACEDESCRIPTION_MAOSALPHA", new FloatControl(1.0f), ShaderStage.Fragment); // -------------------------------------------------- @@ -89,29 +89,29 @@ public struct SurfaceDescription new NormalControl(CoordinateSpace.Object), ShaderStage.Fragment); public static BlockFieldDescriptor IrisNormalWS = new BlockFieldDescriptor(SurfaceDescription.name, "IrisNormalWS", "Iris Normal (World Space)", "SURFACEDESCRIPTION_IRISNORMALWS", new NormalControl(CoordinateSpace.World), ShaderStage.Fragment); - public static BlockFieldDescriptor IOR = new BlockFieldDescriptor(SurfaceDescription.name, "IOR", "SURFACEDESCRIPTION_IOR", + public static BlockFieldDescriptor IOR = new BlockFieldDescriptor(SurfaceDescription.name, "IOR", "SURFACEDESCRIPTION_IOR", new FloatControl(1.4f), ShaderStage.Fragment); - public static BlockFieldDescriptor Mask = new BlockFieldDescriptor(SurfaceDescription.name, "Mask", "SURFACEDESCRIPTION_MASK", + public static BlockFieldDescriptor Mask = new BlockFieldDescriptor(SurfaceDescription.name, "Mask", "SURFACEDESCRIPTION_MASK", new Vector2Control(new Vector2(1.0f, 0.0f)), ShaderStage.Fragment); // -------------------------------------------------- // Hair - public static BlockFieldDescriptor Transmittance = new BlockFieldDescriptor(SurfaceDescription.name, "Transmittance", "SURFACEDESCRIPTION_TRANSMITTANCE", + public static BlockFieldDescriptor Transmittance = new BlockFieldDescriptor(SurfaceDescription.name, "Transmittance", "SURFACEDESCRIPTION_TRANSMITTANCE", new Vector3Control(0.3f * new Vector3(1.0f, 0.65f, 0.3f)), ShaderStage.Fragment); - public static BlockFieldDescriptor RimTransmissionIntensity = new BlockFieldDescriptor(SurfaceDescription.name, "RimTransmissionIntensity", "Rim Transmission Intensity", "SURFACEDESCRIPTION_RIMTRANSMISSIONINTENSITY", + public static BlockFieldDescriptor RimTransmissionIntensity = new BlockFieldDescriptor(SurfaceDescription.name, "RimTransmissionIntensity", "Rim Transmission Intensity", "SURFACEDESCRIPTION_RIMTRANSMISSIONINTENSITY", new FloatControl(0.2f), ShaderStage.Fragment); - public static BlockFieldDescriptor HairStrandDirection = new BlockFieldDescriptor(SurfaceDescription.name, "HairStrandDirection", "Hair Strand Direction", "SURFACEDESCRIPTION_HAIRSTRANDDIRECTION", + public static BlockFieldDescriptor HairStrandDirection = new BlockFieldDescriptor(SurfaceDescription.name, "HairStrandDirection", "Hair Strand Direction", "SURFACEDESCRIPTION_HAIRSTRANDDIRECTION", new Vector3Control(new Vector3(0, -1, 0)), ShaderStage.Fragment); public static BlockFieldDescriptor SpecularTint = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularTint", "Specular Tint", "SURFACEDESCRIPTION_SPECULARTINT", new ColorControl(Color.white, false), ShaderStage.Fragment); - public static BlockFieldDescriptor SpecularShift = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularShift", "Specular Shift", "SURFACEDESCRIPTION_SPECULARSHIFT", + public static BlockFieldDescriptor SpecularShift = new BlockFieldDescriptor(SurfaceDescription.name, "SpecularShift", "Specular Shift", "SURFACEDESCRIPTION_SPECULARSHIFT", new FloatControl(0.1f), ShaderStage.Fragment); public static BlockFieldDescriptor SecondarySpecularTint = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySpecularTint", "Secondary Specular Tint", "SURFACEDESCRIPTION_SECONDARYSPECULARTINT", new ColorControl(Color.grey, false), ShaderStage.Fragment); - public static BlockFieldDescriptor SecondarySmoothness = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySmoothness", "Secondary Smoothness", "SURFACEDESCRIPTION_SECONDARYSMOOTHNESS", + public static BlockFieldDescriptor SecondarySmoothness = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySmoothness", "Secondary Smoothness", "SURFACEDESCRIPTION_SECONDARYSMOOTHNESS", new FloatControl(0.5f), ShaderStage.Fragment); - public static BlockFieldDescriptor SecondarySpecularShift = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySpecularShift", "Secondary Specular Shift", "SURFACEDESCRIPTION_SECONDARYSPECULARSHIFT", + public static BlockFieldDescriptor SecondarySpecularShift = new BlockFieldDescriptor(SurfaceDescription.name, "SecondarySpecularShift", "Secondary Specular Shift", "SURFACEDESCRIPTION_SECONDARYSPECULARSHIFT", new FloatControl(-0.1f), ShaderStage.Fragment); // -------------------------------------------------- @@ -123,37 +123,37 @@ public struct SurfaceDescription new NormalControl(CoordinateSpace.Tangent), ShaderStage.Fragment); public static BlockFieldDescriptor CoatNormalWS = new BlockFieldDescriptor(SurfaceDescription.name, "CoatNormalWS", "Coat Normal (World Space)", "SURFACEDESCRIPTION_COATNORMALWS", new NormalControl(CoordinateSpace.Tangent), ShaderStage.Fragment); - public static BlockFieldDescriptor DielectricIor = new BlockFieldDescriptor(SurfaceDescription.name, "DielectricIor", "Dielectric IOR", "SURFACEDESCRIPTION_DIELECTRICIOR", + public static BlockFieldDescriptor DielectricIor = new BlockFieldDescriptor(SurfaceDescription.name, "DielectricIor", "Dielectric IOR", "SURFACEDESCRIPTION_DIELECTRICIOR", new FloatControl(1.5f), ShaderStage.Fragment); - public static BlockFieldDescriptor SmoothnessB = new BlockFieldDescriptor(SurfaceDescription.name, "SmoothnessB", "Smoothness B", "SURFACEDESCRIPTION_SMOOTHNESSB", + public static BlockFieldDescriptor SmoothnessB = new BlockFieldDescriptor(SurfaceDescription.name, "SmoothnessB", "Smoothness B", "SURFACEDESCRIPTION_SMOOTHNESSB", new FloatControl(0.5f), ShaderStage.Fragment); - public static BlockFieldDescriptor LobeMix = new BlockFieldDescriptor(SurfaceDescription.name, "LobeMix", "Lobe Mix", "SURFACEDESCRIPTION_LOBEMIX", + public static BlockFieldDescriptor LobeMix = new BlockFieldDescriptor(SurfaceDescription.name, "LobeMix", "Lobe Mix", "SURFACEDESCRIPTION_LOBEMIX", new FloatControl(0.3f), ShaderStage.Fragment); - public static BlockFieldDescriptor AnisotropyB = new BlockFieldDescriptor(SurfaceDescription.name, "AnisotropyB", "Anisotropy B", "SURFACEDESCRIPTION_ANISOTROPYB", + public static BlockFieldDescriptor AnisotropyB = new BlockFieldDescriptor(SurfaceDescription.name, "AnisotropyB", "Anisotropy B", "SURFACEDESCRIPTION_ANISOTROPYB", new FloatControl(1.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor SOFixupVisibilityRatioThreshold = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupVisibilityRatioThreshold", "SO Fixup Visibility Ratio Threshold", "SURFACEDESCRIPTION_SOFIXUPVISIBILITYRATIOTHRESHOLD", + public static BlockFieldDescriptor SOFixupVisibilityRatioThreshold = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupVisibilityRatioThreshold", "SO Fixup Visibility Ratio Threshold", "SURFACEDESCRIPTION_SOFIXUPVISIBILITYRATIOTHRESHOLD", new FloatControl(0.2f), ShaderStage.Fragment); - public static BlockFieldDescriptor SOFixupStrengthFactor = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupStrengthFactor", "SO Fixup Strength Factor", "SURFACEDESCRIPTION_SOFIXUPSTRENGTHFACTOR", + public static BlockFieldDescriptor SOFixupStrengthFactor = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupStrengthFactor", "SO Fixup Strength Factor", "SURFACEDESCRIPTION_SOFIXUPSTRENGTHFACTOR", new FloatControl(1.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor SOFixupMaxAddedRoughness = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupMaxAddedRoughness", "SO Fixup Max Added Roughness", "SURFACEDESCRIPTION_SOFIXUPMAXADDEDROUGHNESS", + public static BlockFieldDescriptor SOFixupMaxAddedRoughness = new BlockFieldDescriptor(SurfaceDescription.name, "SOFixupMaxAddedRoughness", "SO Fixup Max Added Roughness", "SURFACEDESCRIPTION_SOFIXUPMAXADDEDROUGHNESS", new FloatControl(0.2f), ShaderStage.Fragment); - public static BlockFieldDescriptor CoatSmoothness = new BlockFieldDescriptor(SurfaceDescription.name, "CoatSmoothness", "Coat Smoothness", "SURFACEDESCRIPTION_COATSMOOTHNESS", + public static BlockFieldDescriptor CoatSmoothness = new BlockFieldDescriptor(SurfaceDescription.name, "CoatSmoothness", "Coat Smoothness", "SURFACEDESCRIPTION_COATSMOOTHNESS", new FloatControl(1.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor CoatIor = new BlockFieldDescriptor(SurfaceDescription.name, "CoatIor", "Coat IOR", "SURFACEDESCRIPTION_COATIOR", + public static BlockFieldDescriptor CoatIor = new BlockFieldDescriptor(SurfaceDescription.name, "CoatIor", "Coat IOR", "SURFACEDESCRIPTION_COATIOR", new FloatControl(1.4f), ShaderStage.Fragment); - public static BlockFieldDescriptor CoatThickness = new BlockFieldDescriptor(SurfaceDescription.name, "CoatThickness", "Coat Thickness", "SURFACEDESCRIPTION_COATTHICKNESS", + public static BlockFieldDescriptor CoatThickness = new BlockFieldDescriptor(SurfaceDescription.name, "CoatThickness", "Coat Thickness", "SURFACEDESCRIPTION_COATTHICKNESS", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor CoatExtinction = new BlockFieldDescriptor(SurfaceDescription.name, "CoatExtinction", "Coat Extinction", "SURFACEDESCRIPTION_COATEXTINCTION", + public static BlockFieldDescriptor CoatExtinction = new BlockFieldDescriptor(SurfaceDescription.name, "CoatExtinction", "Coat Extinction", "SURFACEDESCRIPTION_COATEXTINCTION", new ColorControl(Color.white, true), ShaderStage.Fragment); - public static BlockFieldDescriptor Haziness = new BlockFieldDescriptor(SurfaceDescription.name, "Haziness", "SURFACEDESCRIPTION_HAZINESS", + public static BlockFieldDescriptor Haziness = new BlockFieldDescriptor(SurfaceDescription.name, "Haziness", "SURFACEDESCRIPTION_HAZINESS", new FloatControl(0.2f), ShaderStage.Fragment); - public static BlockFieldDescriptor HazeExtent = new BlockFieldDescriptor(SurfaceDescription.name, "HazeExtent", "Haze Extent", "SURFACEDESCRIPTION_HAZEEXTENT", + public static BlockFieldDescriptor HazeExtent = new BlockFieldDescriptor(SurfaceDescription.name, "HazeExtent", "Haze Extent", "SURFACEDESCRIPTION_HAZEEXTENT", new FloatControl(3.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor HazyGlossMaxDielectricF0 = new BlockFieldDescriptor(SurfaceDescription.name, "HazyGlossMaxDielectricF0", "Hazy Gloss Max Dielectric F0", "SURFACEDESCRIPTION_HAZYGLOSSMAXDIELECTRICF0", + public static BlockFieldDescriptor HazyGlossMaxDielectricF0 = new BlockFieldDescriptor(SurfaceDescription.name, "HazyGlossMaxDielectricF0", "Hazy Gloss Max Dielectric F0", "SURFACEDESCRIPTION_HAZYGLOSSMAXDIELECTRICF0", new FloatControl(0.25f), ShaderStage.Fragment); - public static BlockFieldDescriptor IridescenceCoatFixupTIR = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceCoatFixupTIR", "Iridescence Coat Fixup TIR", "SURFACEDESCRIPTION_IRIDESCENCECOATFIXUPTIR", + public static BlockFieldDescriptor IridescenceCoatFixupTIR = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceCoatFixupTIR", "Iridescence Coat Fixup TIR", "SURFACEDESCRIPTION_IRIDESCENCECOATFIXUPTIR", new FloatControl(0.0f), ShaderStage.Fragment); - public static BlockFieldDescriptor IridescenceCoatFixupTIRClamp = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceCoatFixupTIRClamp", "Iridescence Coat Fixup TIR Clamp", "SURFACEDESCRIPTION_IRIDESCENCECOATFIXUPTIRCLAMP", + public static BlockFieldDescriptor IridescenceCoatFixupTIRClamp = new BlockFieldDescriptor(SurfaceDescription.name, "IridescenceCoatFixupTIRClamp", "Iridescence Coat Fixup TIR Clamp", "SURFACEDESCRIPTION_IRIDESCENCECOATFIXUPTIRCLAMP", new FloatControl(0.0f), ShaderStage.Fragment); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDFields.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDFields.cs index 7a24b21fc34..a09d56efd07 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDFields.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDFields.cs @@ -4,7 +4,7 @@ namespace UnityEditor.Rendering.HighDefinition { static class HDFields { -#region Tags + #region Tags public const string kMaterial = "Material"; public const string kDots = "Dots"; public const string kSpecular = "Specular"; @@ -12,9 +12,9 @@ static class HDFields public const string kDistortion = "Distortion"; public const string kShaderPass = "ShaderPass"; public const string kSubShader = "SubShader"; -#endregion + #endregion -#region Fields + #region Fields // Material public static FieldDescriptor Anisotropy = new FieldDescriptor(kMaterial, "Anisotropy", "_MATERIAL_FEATURE_TRANSMISSION 1"); public static FieldDescriptor Iridescence = new FieldDescriptor(kMaterial, "Iridescence", "_MATERIAL_FEATURE_TRANSMISSION 1"); @@ -62,6 +62,6 @@ static class HDFields public static FieldDescriptor RayTracing = new FieldDescriptor(string.Empty, "RayTracing", string.Empty); public static FieldDescriptor Unlit = new FieldDescriptor(string.Empty, "Unlit", string.Empty); -#endregion + #endregion } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs index 559d224c165..149c7777d7b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDPropertiesHeader.cs @@ -12,7 +12,6 @@ class HDPropertiesHeader : Toggle { public HDPropertiesHeader(string label) : base(label) { - } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDShaderPasses.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDShaderPasses.cs index ecf7578f8f0..51b3b62d106 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDShaderPasses.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDShaderPasses.cs @@ -10,7 +10,7 @@ namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { static class HDShaderPasses { -#region Distortion Pass + #region Distortion Pass public static PassDescriptor GenerateDistortionPass(bool supportLighting) { @@ -71,10 +71,9 @@ IncludeCollection GenerateIncludes() } } + #endregion -#endregion - -#region Scene Picking Pass + #region Scene Picking Pass public static PassDescriptor GenerateScenePicking() { @@ -108,9 +107,9 @@ IncludeCollection GenerateIncludes() } } -#endregion + #endregion -#region Scene Selection Pass + #region Scene Selection Pass public static PassDescriptor GenerateSceneSelection(bool supportLighting) { @@ -150,9 +149,9 @@ IncludeCollection GenerateIncludes() } } -#endregion + #endregion -#region Shadow Caster Pass + #region Shadow Caster Pass static public PassDescriptor GenerateShadowCaster(bool supportLighting) { @@ -199,9 +198,9 @@ IncludeCollection GenerateIncludes() } } -#endregion + #endregion -#region META pass + #region META pass public static PassDescriptor GenerateMETA(bool supportLighting) { @@ -245,9 +244,9 @@ IncludeCollection GenerateIncludes() } } -#endregion + #endregion -#region Depth Forward Only + #region Depth Forward Only public static PassDescriptor GenerateDepthForwardOnlyPass(bool supportLighting) { @@ -269,7 +268,7 @@ public static PassDescriptor GenerateDepthForwardOnlyPass(bool supportLighting) RenderStateCollection GenerateRenderState() { - var renderState = new RenderStateCollection{ CoreRenderStates.DepthOnly }; + var renderState = new RenderStateCollection { CoreRenderStates.DepthOnly }; if (!supportLighting) { @@ -323,9 +322,9 @@ IncludeCollection GenerateIncludes() } } -#endregion + #endregion -#region Motion Vectors + #region Motion Vectors public static PassDescriptor GenerateMotionVectors(bool supportLighting, bool supportForward) { @@ -356,8 +355,8 @@ DefineCollection GenerateDefines() // if (supportForward) // { // defines.Add(CoreKeywordDescriptors.WriteNormalBuffer, 1); - // } - + // } + return defines; } @@ -365,7 +364,7 @@ RenderStateCollection GenerateRenderState() { var renderState = new RenderStateCollection(); renderState.Add(CoreRenderStates.MotionVectors); - + if (!supportLighting) { // Caution: When using MSAA we have motion vector, normal and depth buffer bind. @@ -401,15 +400,14 @@ IncludeCollection GenerateIncludes() } } + #endregion -#endregion - -#region Forward Only + #region Forward Only public static PassDescriptor GenerateForwardOnlyPass(bool supportLighting) { return new PassDescriptor - { + { // Definition displayName = "ForwardOnly", referenceName = supportLighting ? "SHADERPASS_FORWARD" : "SHADERPASS_FORWARD_UNLIT", @@ -465,19 +463,19 @@ IncludeCollection GenerateIncludes() includes.Add(CoreIncludes.kPassForward, IncludeLocation.Postgraph); else includes.Add(CoreIncludes.kPassForwardUnlit, IncludeLocation.Postgraph); - + return includes; } } -#endregion + #endregion -#region Back then front pass + #region Back then front pass public static PassDescriptor GenerateBackThenFront(bool supportLighting) { return new PassDescriptor - { + { // Definition displayName = "TransparentBackface", referenceName = supportLighting ? "SHADERPASS_FORWARD" : "SHADERPASS_FORWARD_UNLIT", @@ -522,9 +520,9 @@ IncludeCollection GenerateIncludes() } } -#endregion + #endregion -#region Transparent Depth Prepass + #region Transparent Depth Prepass public static PassDescriptor GenerateTransparentDepthPrepass(bool supportLighting) { @@ -538,23 +536,23 @@ public static PassDescriptor GenerateTransparentDepthPrepass(bool supportLightin validPixelBlocks = supportLighting ? new BlockFieldDescriptor[] - { - BlockFields.SurfaceDescription.Alpha, - HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, - BlockFields.SurfaceDescription.AlphaClipThreshold, - HDBlockFields.SurfaceDescription.DepthOffset, - BlockFields.SurfaceDescription.NormalTS, - BlockFields.SurfaceDescription.NormalWS, - BlockFields.SurfaceDescription.NormalOS, - BlockFields.SurfaceDescription.Smoothness, - } : - new BlockFieldDescriptor[] - { - BlockFields.SurfaceDescription.Alpha, - HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, - BlockFields.SurfaceDescription.AlphaClipThreshold, - HDBlockFields.SurfaceDescription.DepthOffset, - }, + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.Smoothness, + } : + new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass, + BlockFields.SurfaceDescription.AlphaClipThreshold, + HDBlockFields.SurfaceDescription.DepthOffset, + }, // Collections requiredFields = TransparentDepthPrepassFields, @@ -632,9 +630,9 @@ IncludeCollection GenerateIncludes() HDStructFields.FragInputs.color, }; -#endregion + #endregion -#region Transparent Depth Postpass + #region Transparent Depth Postpass public static PassDescriptor GenerateTransparentDepthPostpass(bool supportLighting) { @@ -695,9 +693,9 @@ RenderStateCollection GenerateRenderState() } } -#endregion + #endregion -#region Lit DepthOnly + #region Lit DepthOnly public static PassDescriptor GenerateLitDepthOnly() { @@ -735,9 +733,9 @@ public static PassDescriptor GenerateLitDepthOnly() { CoreKeywordDescriptors.WriteNormalBuffer }, }; -#endregion + #endregion -#region GBuffer + #region GBuffer public static PassDescriptor GenerateGBuffer() { @@ -791,9 +789,9 @@ public static PassDescriptor GenerateGBuffer() }) }, }; -#endregion + #endregion -#region Lit Forward + #region Lit Forward public static PassDescriptor GenerateLitForward() { @@ -831,9 +829,9 @@ public static PassDescriptor GenerateLitForward() { CoreIncludes.kPassForward, IncludeLocation.Postgraph }, }; -#endregion + #endregion -#region Lit Raytracing Prepass + #region Lit Raytracing Prepass public static PassDescriptor GenerateLitRaytracingPrepass() { @@ -873,9 +871,9 @@ public static PassDescriptor GenerateLitRaytracingPrepass() // Note: we use default ZTest LEqual so if the object have already been render in depth prepass, it will re-render to tag stencil }; -#endregion + #endregion -#region Raytracing Indirect + #region Raytracing Indirect public static PassDescriptor GenerateRaytracingIndirect(bool supportLighting) { @@ -931,9 +929,9 @@ IncludeCollection GenerateIncludes() { CoreKeywordDescriptors.HasLightloop, 1 }, }; -#endregion + #endregion -#region Raytracing Visibility + #region Raytracing Visibility public static PassDescriptor GenerateRaytracingVisibility(bool supportLighting) { @@ -984,9 +982,9 @@ IncludeCollection GenerateIncludes() { Defines.raytracingRaytraced }, }; -#endregion + #endregion -#region Raytracing Forward + #region Raytracing Forward public static PassDescriptor GenerateRaytracingForward(bool supportLighting) { @@ -1042,7 +1040,6 @@ IncludeCollection GenerateIncludes() } } - public static DefineCollection RaytracingForwardDefines = new DefineCollection { { Defines.shadowLow }, @@ -1050,9 +1047,9 @@ IncludeCollection GenerateIncludes() { CoreKeywordDescriptors.HasLightloop, 1 }, }; -#endregion + #endregion -#region Raytracing GBuffer + #region Raytracing GBuffer public static PassDescriptor GenerateRaytracingGBuffer(bool supportLighting) { @@ -1087,7 +1084,7 @@ IncludeCollection GenerateIncludes() // We want to have the normal buffer include if this is a gbuffer and unlit shader if (!supportLighting) includes.Add(CoreIncludes.kNormalBuffer, IncludeLocation.Pregraph); - + // If this is the gbuffer sub-shader, we want the standard lit data includes.Add(CoreIncludes.kStandardLit, IncludeLocation.Pregraph); @@ -1111,9 +1108,9 @@ IncludeCollection GenerateIncludes() { Defines.raytracingRaytraced }, }; -#endregion + #endregion -#region Path Tracing + #region Path Tracing public static PassDescriptor GeneratePathTracing(bool supportLighting) { @@ -1172,9 +1169,9 @@ IncludeCollection GenerateIncludes() { CoreKeywordDescriptors.HasLightloop, 1 }, }; -#endregion + #endregion -#region Raytracing Subsurface + #region Raytracing Subsurface public static PassDescriptor GenerateRaytracingSubsurface() { @@ -1229,9 +1226,9 @@ IncludeCollection GenerateIncludes() { Defines.raytracingRaytraced }, }; -#endregion + #endregion -#region FullScreen Debug + #region FullScreen Debug public static PassDescriptor GenerateFullScreenDebug() { @@ -1270,9 +1267,9 @@ IncludeCollection GenerateIncludes() { RenderState.ZTest(ZTest.LEqual) }, }; -#endregion + #endregion -#region Define Utility + #region Define Utility public static class Defines { @@ -1286,7 +1283,6 @@ public static class Defines public static DefineCollection raytracingRaytraced = new DefineCollection { { RayTracingQualityNode.GetRayTracingQualityKeyword(), 1} }; } -#endregion - + #endregion } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDStructFields.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDStructFields.cs index 21abde9304d..8211a3067f6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDStructFields.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDStructFields.cs @@ -9,23 +9,23 @@ public struct AttributesMesh public static string name = "AttributesMesh"; public static FieldDescriptor positionOS = new FieldDescriptor(AttributesMesh.name, "positionOS", "", ShaderValueType.Float3, "POSITION"); public static FieldDescriptor normalOS = new FieldDescriptor(AttributesMesh.name, "normalOS", "ATTRIBUTES_NEED_NORMAL", ShaderValueType.Float3, - "NORMAL", subscriptOptions : StructFieldOptions.Optional); + "NORMAL", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor tangentOS = new FieldDescriptor(AttributesMesh.name, "tangentOS", "ATTRIBUTES_NEED_TANGENT", ShaderValueType.Float4, - "TANGENT", subscriptOptions : StructFieldOptions.Optional); + "TANGENT", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor uv0 = new FieldDescriptor(AttributesMesh.name, "uv0", "ATTRIBUTES_NEED_TEXCOORD0", ShaderValueType.Float4, - "TEXCOORD0", subscriptOptions : StructFieldOptions.Optional); + "TEXCOORD0", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor uv1 = new FieldDescriptor(AttributesMesh.name, "uv1", "ATTRIBUTES_NEED_TEXCOORD1", ShaderValueType.Float4, - "TEXCOORD1", subscriptOptions : StructFieldOptions.Optional); + "TEXCOORD1", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor uv2 = new FieldDescriptor(AttributesMesh.name, "uv2", "ATTRIBUTES_NEED_TEXCOORD2", ShaderValueType.Float4, - "TEXCOORD2", subscriptOptions : StructFieldOptions.Optional); + "TEXCOORD2", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor uv3 = new FieldDescriptor(AttributesMesh.name, "uv3", "ATTRIBUTES_NEED_TEXCOORD3", ShaderValueType.Float4, - "TEXCOORD3", subscriptOptions : StructFieldOptions.Optional); + "TEXCOORD3", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor weights = new FieldDescriptor(AttributesMesh.name, "weights", "ATTRIBUTES_NEED_BLENDWEIGHTS", ShaderValueType.Float4, - "BLENDWEIGHTS", subscriptOptions : StructFieldOptions.Optional); + "BLENDWEIGHTS", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor indices = new FieldDescriptor(AttributesMesh.name, "indices", "ATTRIBUTES_NEED_BLENDINDICES", ShaderValueType.Uint4, - "BLENDINDICES", subscriptOptions : StructFieldOptions.Optional); + "BLENDINDICES", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor color = new FieldDescriptor(AttributesMesh.name, "color", "ATTRIBUTES_NEED_COLOR", ShaderValueType.Float4, - "COLOR", subscriptOptions : StructFieldOptions.Optional); + "COLOR", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor instanceID = new FieldDescriptor(AttributesMesh.name, "instanceID", "", ShaderValueType.Uint, "INSTANCEID_SEMANTIC", "UNITY_ANY_INSTANCING_ENABLED"); public static FieldDescriptor vertexID = new FieldDescriptor(AttributesMesh.name, "vertexID", "ATTRIBUTES_NEED_VERTEXID", ShaderValueType.Uint, @@ -37,21 +37,21 @@ public struct VaryingsMeshToPS public static string name = "VaryingsMeshToPS"; public static FieldDescriptor positionCS = new FieldDescriptor(VaryingsMeshToPS.name, "positionCS", "", ShaderValueType.Float4, "SV_POSITION"); public static FieldDescriptor positionRWS = new FieldDescriptor(VaryingsMeshToPS.name, "positionRWS", "VARYINGS_NEED_POSITION_WS", ShaderValueType.Float3, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor normalWS = new FieldDescriptor(VaryingsMeshToPS.name, "normalWS", "VARYINGS_NEED_NORMAL_WS", ShaderValueType.Float3, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor tangentWS = new FieldDescriptor(VaryingsMeshToPS.name, "tangentWS", "VARYINGS_NEED_TANGENT_WS", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord0 = new FieldDescriptor(VaryingsMeshToPS.name, "texCoord0", "VARYINGS_NEED_TEXCOORD0", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord1 = new FieldDescriptor(VaryingsMeshToPS.name, "texCoord1", "VARYINGS_NEED_TEXCOORD1", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord2 = new FieldDescriptor(VaryingsMeshToPS.name, "texCoord2", "VARYINGS_NEED_TEXCOORD2", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord3 = new FieldDescriptor(VaryingsMeshToPS.name, "texCoord3", "VARYINGS_NEED_TEXCOORD3", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor color = new FieldDescriptor(VaryingsMeshToPS.name, "color", "VARYINGS_NEED_COLOR", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor instanceID = new FieldDescriptor(VaryingsMeshToPS.name, "instanceID", "", ShaderValueType.Uint, "CUSTOM_INSTANCE_ID", "UNITY_ANY_INSTANCING_ENABLED"); // Note: we don't generate cullFace here as it is always present in VertMesh.hlsl @@ -63,17 +63,17 @@ public struct VaryingsMeshToDS public static FieldDescriptor positionRWS = new FieldDescriptor(VaryingsMeshToDS.name, "positionWS", "VARYINGS_NEED_POSITION_WS", ShaderValueType.Float3); public static FieldDescriptor normalWS = new FieldDescriptor(VaryingsMeshToDS.name, "normalWS", "VARYINGS_NEED_NORMAL_WS", ShaderValueType.Float3); public static FieldDescriptor tangentWS = new FieldDescriptor(VaryingsMeshToDS.name, "tangentWS", "VARYINGS_NEED_TANGENT_WS", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord0 = new FieldDescriptor(VaryingsMeshToDS.name, "texCoord0", "VARYINGS_NEED_TEXCOORD0", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord1 = new FieldDescriptor(VaryingsMeshToDS.name, "texCoord1", "VARYINGS_NEED_TEXCOORD1", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord2 = new FieldDescriptor(VaryingsMeshToDS.name, "texCoord2", "VARYINGS_NEED_TEXCOORD2", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord3 = new FieldDescriptor(VaryingsMeshToDS.name, "texCoord3", "VARYINGS_NEED_TEXCOORD3", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor color = new FieldDescriptor(VaryingsMeshToDS.name, "color", "VARYINGS_NEED_COLOR", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor instanceID = new FieldDescriptor(VaryingsMeshToDS.name, "instanceID", "", ShaderValueType.Uint, "INSTANCEID_SEMANTIC", "UNITY_ANY_INSTANCING_ENABLED"); } @@ -82,23 +82,23 @@ public struct FragInputs { public static string name = "FragInputs"; public static FieldDescriptor positionRWS = new FieldDescriptor(FragInputs.name, "positionRWS", "", ShaderValueType.Float3, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor tangentToWorld = new FieldDescriptor(FragInputs.name, "tangentToWorld", "", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord0 = new FieldDescriptor(FragInputs.name, "texCoord0", "", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord1 = new FieldDescriptor(FragInputs.name, "texCoord1", "", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord2 = new FieldDescriptor(FragInputs.name, "texCoord2", "", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor texCoord3 = new FieldDescriptor(FragInputs.name, "texCoord3", "", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor color = new FieldDescriptor(FragInputs.name, "color", "", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor primitiveID = new FieldDescriptor(FragInputs.name, "primitiveID", "", ShaderValueType.Uint, subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor IsFrontFace = new FieldDescriptor(FragInputs.name, "isFrontFace", "", ShaderValueType.Boolean, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubShaderUtilities.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubShaderUtilities.cs index 29d78c28cb3..95d1dec716b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubShaderUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubShaderUtilities.cs @@ -28,7 +28,8 @@ static class HDSubShaderUtilities // Utils property to add properties to the collector, all hidden because we use a custom UI to display them static void AddIntProperty(this PropertyCollector collector, string referenceName, int defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare) { - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { floatType = FloatType.Integer, value = defaultValue, hidden = true, @@ -40,7 +41,8 @@ static void AddIntProperty(this PropertyCollector collector, string referenceNam static void AddFloatProperty(this PropertyCollector collector, string referenceName, float defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare) { - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { floatType = FloatType.Default, hidden = true, overrideHLSLDeclaration = true, @@ -52,7 +54,8 @@ static void AddFloatProperty(this PropertyCollector collector, string referenceN static void AddFloatProperty(this PropertyCollector collector, string referenceName, string displayName, float defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare) { - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { floatType = FloatType.Default, value = defaultValue, overrideReferenceName = referenceName, @@ -65,7 +68,8 @@ static void AddFloatProperty(this PropertyCollector collector, string referenceN static void AddToggleProperty(this PropertyCollector collector, string referenceName, bool defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare) { - collector.AddShaderProperty(new BooleanShaderProperty{ + collector.AddShaderProperty(new BooleanShaderProperty + { value = defaultValue, hidden = true, overrideHLSLDeclaration = true, @@ -145,7 +149,8 @@ public static void AddBlendingStatesShaderProperties( collector.AddIntProperty(kTransparentSortPriority, sortingPriority); collector.AddToggleProperty(kEnableFogOnTransparent, fogOnTransparent); collector.AddFloatProperty("_CullModeForward", (int)CullMode.Back); - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { overrideReferenceName = kTransparentCullMode, floatType = FloatType.Enum, value = (int)transparentCullMode, @@ -155,7 +160,8 @@ public static void AddBlendingStatesShaderProperties( overrideHLSLDeclaration = true, hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare, }); - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { overrideReferenceName = kOpaqueCullMode, floatType = FloatType.Enum, value = (int)opaqueCullMode, @@ -168,7 +174,8 @@ public static void AddBlendingStatesShaderProperties( // Add ZTest properties: collector.AddIntProperty("_ZTestDepthEqualForOpaque", (int)CompareFunction.LessEqual); - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { overrideReferenceName = kZTestTransparent, floatType = FloatType.Enum, value = (int)zTest, @@ -193,7 +200,8 @@ public static void AddDoubleSidedProperty(PropertyCollector collector, DoubleSid { var normalMode = ConvertDoubleSidedModeToDoubleSidedNormalMode(mode); collector.AddToggleProperty("_DoubleSidedEnable", mode != DoubleSidedMode.Disabled); - collector.AddShaderProperty(new Vector1ShaderProperty{ + collector.AddShaderProperty(new Vector1ShaderProperty + { enumNames = {"Flip", "Mirror", "None"}, // values will be 0, 1 and 2 floatType = FloatType.Enum, overrideReferenceName = "_DoubleSidedNormalMode", @@ -202,7 +210,8 @@ public static void AddDoubleSidedProperty(PropertyCollector collector, DoubleSid hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare, value = (int)normalMode }); - collector.AddShaderProperty(new Vector4ShaderProperty{ + collector.AddShaderProperty(new Vector4ShaderProperty + { overrideReferenceName = "_DoubleSidedConstants", hidden = true, overrideHLSLDeclaration = true, @@ -215,7 +224,7 @@ public static void AddRayTracingProperty(PropertyCollector collector, bool isRay { collector.AddToggleProperty("_RayTracing", isRayTracing, HLSLDeclaration.UnityPerMaterial); } - + public static void AddPrePostPassProperties(PropertyCollector collector, bool prepass, bool postpass) { collector.AddToggleProperty(kTransparentDepthPrepassEnable, prepass); @@ -271,7 +280,7 @@ public static bool UpgradeLegacyAlphaClip(IMasterNode1 masterNode) var clipThresholdId = 8; var node = masterNode as AbstractMaterialNode; var clipThresholdSlot = node.FindSlot(clipThresholdId); - if(clipThresholdSlot == null) + if (clipThresholdSlot == null) return false; clipThresholdSlot.owner = node; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs index 5f27129af69..c6086e20842 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDSubTarget.cs @@ -74,7 +74,7 @@ ShaderGraphVersion IVersionable.version internal static MigrationDescription migrationSteps => MigrationDescription.New( Enum.GetValues(typeof(ShaderGraphVersion)).Cast().Select( version => MigrationStep.New(version, (HDSubTarget t) => t.MigrateTo(version)) - ).ToArray() + ).ToArray() ); /// @@ -120,7 +120,7 @@ protected SubShaderDescriptor PostProcessSubShader(SubShaderDescriptor subShader { if (String.IsNullOrEmpty(subShaderDescriptor.pipelineTag)) subShaderDescriptor.pipelineTag = HDRenderPipeline.k_ShaderTagName; - + var passes = subShaderDescriptor.passes.ToArray(); PassCollection finalPasses = new PassCollection(); for (int i = 0; i < passes.Length; i++) @@ -167,8 +167,8 @@ protected SubShaderDescriptor PostProcessSubShader(SubShaderDescriptor subShader passDescriptor.validVertexBlocks = tmpCtx.activeBlocks.Where(b => b.shaderStage == ShaderStage.Vertex).ToArray(); // Add keywords from subshaders: - passDescriptor.keywords = passDescriptor.keywords == null ? new KeywordCollection() : new KeywordCollection{ passDescriptor.keywords }; // Duplicate keywords to avoid side effects (static list modification) - passDescriptor.defines = passDescriptor.defines == null ? new DefineCollection() : new DefineCollection{ passDescriptor.defines }; // Duplicate defines to avoid side effects (static list modification) + passDescriptor.keywords = passDescriptor.keywords == null ? new KeywordCollection() : new KeywordCollection { passDescriptor.keywords }; // Duplicate keywords to avoid side effects (static list modification) + passDescriptor.defines = passDescriptor.defines == null ? new DefineCollection() : new DefineCollection { passDescriptor.defines }; // Duplicate defines to avoid side effects (static list modification) CollectPassKeywords(ref passDescriptor); // Set default values for HDRP "surface" passes: @@ -214,8 +214,8 @@ public override object saveContext if (needsUpdate) systemData.materialNeedsUpdateHash = hash; - return new HDSaveContext{ updateMaterials = needsUpdate }; + return new HDSaveContext { updateMaterials = needsUpdate }; } - } + } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs index e6526c90024..8f382d1759d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs @@ -85,7 +85,7 @@ public string customEditorGUI public override bool IsActive() { - if(m_ActiveSubTarget.value == null) + if (m_ActiveSubTarget.value == null) return false; bool isHDRenderPipeline = GraphicsSettings.currentRenderPipeline is HDRenderPipelineAsset; @@ -99,7 +99,7 @@ public override void Setup(ref TargetSetupContext context) // Process SubTargets TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); - if(m_ActiveSubTarget.value == null) + if (m_ActiveSubTarget.value == null) return; // Setup the active SubTarget @@ -108,7 +108,7 @@ public override void Setup(ref TargetSetupContext context) m_ActiveSubTarget.value.Setup(ref context); // Override EditorGUI - if(!string.IsNullOrEmpty(m_CustomEditorGUI)) + if (!string.IsNullOrEmpty(m_CustomEditorGUI)) { context.SetDefaultShaderGUI(m_CustomEditorGUI); } @@ -119,8 +119,8 @@ public override void GetFields(ref TargetFieldContext context) var descs = context.blocks.Select(x => x.descriptor); // Stages context.AddField(Fields.GraphVertex, descs.Contains(BlockFields.VertexDescription.Position) || - descs.Contains(BlockFields.VertexDescription.Normal) || - descs.Contains(BlockFields.VertexDescription.Tangent)); + descs.Contains(BlockFields.VertexDescription.Normal) || + descs.Contains(BlockFields.VertexDescription.Tangent)); context.AddField(Fields.GraphPixel); // SubTarget @@ -135,7 +135,7 @@ public override void GetActiveBlocks(ref TargetActiveBlockContext context) public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) { - if(m_ActiveSubTarget.value == null) + if (m_ActiveSubTarget.value == null) return; context.globalIndentLevel++; @@ -148,7 +148,7 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti return; var systemData = m_Datas.SelectValue().FirstOrDefault(x => x is SystemData) as SystemData; - if(systemData != null) + if (systemData != null) { // Force material update hash systemData.materialNeedsUpdateHash = -1; @@ -194,13 +194,13 @@ public override void ProcessPreviewMaterial(Material material) } public override object saveContext => m_ActiveSubTarget.value?.saveContext; - + // IHasMetaData public string identifier { get { - if(m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) + if (m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) return subTargetHasMetaData.identifier; return null; @@ -209,7 +209,7 @@ public string identifier public ScriptableObject GetMetadataObject() { - if(m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) + if (m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) return subTargetHasMetaData.GetMetadataObject(); return null; @@ -217,12 +217,12 @@ public ScriptableObject GetMetadataObject() public bool TrySetActiveSubTarget(Type subTargetType) { - if(!subTargetType.IsSubclassOf(typeof(SubTarget))) + if (!subTargetType.IsSubclassOf(typeof(SubTarget))) return false; - - foreach(var subTarget in m_SubTargets) + + foreach (var subTarget in m_SubTargets) { - if(subTarget.GetType().Equals(subTargetType)) + if (subTarget.GetType().Equals(subTargetType)) { m_ActiveSubTarget = subTarget; ProcessSubTargetDatas(m_ActiveSubTarget); @@ -236,7 +236,7 @@ public bool TrySetActiveSubTarget(Type subTargetType) void ProcessSubTargetDatas(SubTarget subTarget) { var typeCollection = TypeCache.GetTypesDerivedFrom(); - foreach(var type in typeCollection) + foreach (var type in typeCollection) { // Data requirement interfaces need generic type arguments // Therefore we need to use reflections to call the method @@ -248,7 +248,7 @@ void ProcessSubTargetDatas(SubTarget subTarget) void ClearUnusedData() { - for(int i = 0; i < m_Datas.Count; i++) + for (int i = 0; i < m_Datas.Count; i++) { var data = m_Datas[i]; var type = data.value.GetType(); @@ -263,12 +263,12 @@ void ClearUnusedData() public void SetDataOnSubTarget(SubTarget subTarget) where T : HDTargetData { - if(!(subTarget is IRequiresData requiresData)) + if (!(subTarget is IRequiresData requiresData)) return; - + // Ensure data object exists in list var data = m_Datas.SelectValue().FirstOrDefault(x => x.GetType().Equals(typeof(T))) as T; - if(data == null) + if (data == null) { data = Activator.CreateInstance(typeof(T)) as T; m_Datas.Add(data); @@ -280,7 +280,7 @@ public void SetDataOnSubTarget(SubTarget subTarget) where T : HDTargetData public void ValidateDataForSubTarget(SubTarget subTarget, T data) where T : HDTargetData { - if(!(subTarget is IRequiresData requiresData)) + if (!(subTarget is IRequiresData requiresData)) { m_Datas.Remove(data); } @@ -299,23 +299,23 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(); - foreach(var type in typeCollection) + foreach (var type in typeCollection) { var data = Activator.CreateInstance(type) as HDTargetData; m_Datas.Add(data); } // Process SubTargets - foreach(var subTarget in m_SubTargets) + foreach (var subTarget in m_SubTargets) { - if(!(subTarget is ILegacyTarget legacySubTarget)) + if (!(subTarget is ILegacyTarget legacySubTarget)) continue; - + // Ensure all SubTargets have any required data to fill out during upgrade ProcessSubTargetDatas(subTarget); subTarget.target = this; - - if(legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) + + if (legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) { m_ActiveSubTarget = subTarget; return true; @@ -331,7 +331,7 @@ public override bool WorksWithSRP(RenderPipelineAsset scriptableRenderPipeline) } } -#region BlockMasks + #region BlockMasks static class CoreBlockMasks { public static BlockFieldDescriptor[] Vertex = new BlockFieldDescriptor[] @@ -341,9 +341,9 @@ static class CoreBlockMasks BlockFields.VertexDescription.Tangent, }; } -#endregion + #endregion -#region StructCollections + #region StructCollections static class CoreStructCollections { public static StructCollection Default = new StructCollection @@ -354,9 +354,9 @@ static class CoreStructCollections { Structs.VertexDescriptionInputs }, }; } -#endregion + #endregion -#region FieldDependencies + #region FieldDependencies static class CoreFieldDependencies { public static DependencyCollection Varying = new DependencyCollection @@ -496,9 +496,9 @@ static class CoreFieldDependencies { SurfaceDescription }, }; } -#endregion + #endregion -#region RequiredFields + #region RequiredFields static class CoreRequiredFields { public static FieldCollection Meta = new FieldCollection() @@ -541,9 +541,9 @@ static class CoreRequiredFields HDStructFields.FragInputs.color, }; } -#endregion + #endregion -#region RenderStates + #region RenderStates static class CoreRenderStates { public static class Uniforms @@ -681,9 +681,9 @@ public static class Uniforms }) }, }; } -#endregion + #endregion -#region Pragmas + #region Pragmas static class CorePragmas { public static PragmaCollection Basic = new PragmaCollection @@ -747,10 +747,10 @@ static class CorePragmas { Pragma.InstancingOptions(InstancingOptions.NoLodFade), new FieldCondition(HDFields.DotsInstancing, true) }, { Pragma.InstancingOptions(InstancingOptions.NoLodFade), new FieldCondition(HDFields.DotsProperties, true) }, { Pragma.InstancingOptions(InstancingOptions.RenderingLayer), new FieldCondition[] - { - new FieldCondition(HDFields.DotsInstancing, false), - new FieldCondition(HDFields.DotsProperties, false), - } }, + { + new FieldCondition(HDFields.DotsInstancing, false), + new FieldCondition(HDFields.DotsProperties, false), + } }, #endif }; @@ -770,10 +770,10 @@ static class CorePragmas { Pragma.InstancingOptions(InstancingOptions.NoLodFade), new FieldCondition(HDFields.DotsInstancing, true) }, { Pragma.InstancingOptions(InstancingOptions.NoLodFade), new FieldCondition(HDFields.DotsProperties, true) }, { Pragma.InstancingOptions(InstancingOptions.RenderingLayer), new FieldCondition[] - { - new FieldCondition(HDFields.DotsInstancing, false), - new FieldCondition(HDFields.DotsProperties, false), - } }, + { + new FieldCondition(HDFields.DotsInstancing, false), + new FieldCondition(HDFields.DotsProperties, false), + } }, #endif }; @@ -784,9 +784,9 @@ static class CorePragmas { Pragma.OnlyRenderers(new Platform[] {Platform.D3D11}) }, }; } -#endregion + #endregion -#region Keywords + #region Keywords static class CoreKeywords { public static KeywordCollection RaytracingGBuffer = new KeywordCollection @@ -798,11 +798,10 @@ static class CoreKeywords { { CoreKeywordDescriptors.TransparentColorShadow }, }; - } -#endregion + #endregion -#region Defines + #region Defines static class CoreDefines { public static DefineCollection ScenePicking = new DefineCollection @@ -859,12 +858,12 @@ static class CoreDefines { CoreKeywordDescriptors.SupportBlendModePreserveSpecularLighting, 1 }, { CoreKeywordDescriptors.HasLightloop, 1 }, { RayTracingQualityNode.GetRayTracingQualityKeyword(), 0 }, - // { CoreKeywordDescriptors.LightList, 1 }, // BackThenFront Transparent use #define USE_CLUSTERED_LIGHTLIST + // { CoreKeywordDescriptors.LightList, 1 }, // BackThenFront Transparent use #define USE_CLUSTERED_LIGHTLIST }; } -#endregion + #endregion -#region Includes + #region Includes static class CoreIncludes { // CorePregraph @@ -913,7 +912,7 @@ static class CoreIncludes public const string kNormalSurfaceGradient = "Packages/com.unity.render-pipelines.core/ShaderLibrary/NormalSurfaceGradient.hlsl"; public const string kLighting = "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl"; public const string kLightLoop = "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl"; - + // Public Pregraph Material public const string kUnlit = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl"; public const string kLit = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl"; @@ -949,7 +948,7 @@ static class CoreIncludes public static IncludeCollection CorePregraph = new IncludeCollection { - { kDebugDisplay, IncludeLocation.Pregraph }, + { kDebugDisplay, IncludeLocation.Pregraph }, { kMaterial, IncludeLocation.Pregraph }, }; @@ -968,9 +967,9 @@ static class CoreIncludes { kMaterialUtilities, IncludeLocation.Pregraph }, }; } -#endregion + #endregion -#region KeywordDescriptors + #region KeywordDescriptors static class CoreKeywordDescriptors { public static KeywordDescriptor WriteNormalBuffer = new KeywordDescriptor() @@ -1326,5 +1325,5 @@ static class CoreKeywordDescriptors scope = KeywordScope.Local, }; } -#endregion + #endregion } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/DecalMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/DecalMasterNode1.cs index 1cab30b010f..8c0da331e29 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/DecalMasterNode1.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/DecalMasterNode1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEditor.Graphing; using UnityEngine.Rendering; @@ -50,7 +50,7 @@ public enum SlotMask } const SlotMask decalParameter = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.AlphaAlbedo | SlotMask.Normal | SlotMask.AlphaNormal | SlotMask.Metallic | SlotMask.Occlusion | SlotMask.Smoothness | SlotMask.AlphaMAOS | SlotMask.Emission; - + SlotMask GetActiveSlotMask() { return decalParameter; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/EyeMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/EyeMasterNode1.cs index 33d9131b913..d87eaa462b7 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/EyeMasterNode1.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/EyeMasterNode1.cs @@ -48,7 +48,7 @@ public enum MaterialType public const int LightingSlotId = 15; public const int BackLightingSlotId = 16; public const int DepthOffsetSlotId = 17; - public const int VertexNormalSlotID = 18; + public const int VertexNormalSlotID = 18; public const int VertexTangentSlotID = 19; [Flags] diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDLitMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDLitMasterNode1.cs index 15eae5d6dee..d196a6e1f95 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDLitMasterNode1.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDLitMasterNode1.cs @@ -114,7 +114,7 @@ public enum SlotMask const SlotMask IridescenceSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.IridescenceMask | SlotMask.IridescenceLayerThickness | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Metallic | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; const SlotMask SpecularColorSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Specular | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; const SlotMask TranslucentSlotMask = SlotMask.Position | SlotMask.Albedo | SlotMask.Normal | SlotMask.BentNormal | SlotMask.Thickness | SlotMask.DiffusionProfile | SlotMask.CoatMask | SlotMask.Emission | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.SpecularOcclusion | SlotMask.Alpha | SlotMask.AlphaThreshold | SlotMask.AlphaThresholdDepthPrepass | SlotMask.AlphaThresholdDepthPostpass | SlotMask.AlphaThresholdShadow | SlotMask.Lighting;// | SlotMask.DepthOffset | SlotMask.VertexNormal | SlotMask.VertexTangent; - + SlotMask GetActiveSlotMask() { switch (m_MaterialType) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDUnlitMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDUnlitMasterNode1.cs index 9d4f2a73055..d545c1941a7 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDUnlitMasterNode1.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HDUnlitMasterNode1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEditor.Graphing; using UnityEngine.Rendering; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HairMasterNode1.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HairMasterNode1.cs index 566a1fea031..afbf26ea45d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HairMasterNode1.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Legacy/HairMasterNode1.cs @@ -92,10 +92,10 @@ public enum SlotMask VertexNormal = 1 << VertexNormalSlotId, VertexTangent = 1 << VertexTangentSlotId, } - + const SlotMask KajiyaKaySlotMask = SlotMask.Position | SlotMask.VertexNormal | SlotMask.VertexTangent | SlotMask.Albedo | SlotMask.Normal | SlotMask.SpecularOcclusion | SlotMask.BentNormal | SlotMask.HairStrandDirection | SlotMask.Slot6 - | SlotMask.Transmittance | SlotMask.RimTransmissionIntensity | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.AlphaClipThresholdDepthPrepass - | SlotMask.AlphaClipThresholdDepthPostpass | SlotMask.SpecularTint | SlotMask.SpecularShift | SlotMask.SecondarySpecularTint | SlotMask.SecondarySmoothness | SlotMask.SecondarySpecularShift | SlotMask.AlphaClipThresholdShadow | SlotMask.BakedGI | SlotMask.DepthOffset; + | SlotMask.Transmittance | SlotMask.RimTransmissionIntensity | SlotMask.Smoothness | SlotMask.Occlusion | SlotMask.Alpha | SlotMask.AlphaClipThreshold | SlotMask.AlphaClipThresholdDepthPrepass + | SlotMask.AlphaClipThresholdDepthPostpass | SlotMask.SpecularTint | SlotMask.SpecularShift | SlotMask.SecondarySpecularTint | SlotMask.SecondarySmoothness | SlotMask.SecondarySpecularShift | SlotMask.AlphaClipThresholdShadow | SlotMask.BakedGI | SlotMask.DepthOffset; SlotMask GetActiveSlotMask() { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/DiffusionProfileNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/DiffusionProfileNode.cs index 81c3b65bfc9..24e4f04c0b3 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/DiffusionProfileNode.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/DiffusionProfileNode.cs @@ -64,7 +64,7 @@ public DiffusionProfileSettings diffusionProfile set { if (m_DiffusionProfileAsset == value) - return ; + return; var serializedProfile = new DiffusionProfileSerializer(); serializedProfile.diffusionProfileAsset = value; @@ -95,7 +95,7 @@ void UpgradeIfNeeded() if (m_DiffusionProfile.selectedEntry != 0) { // Can't reliably retrieve the slot value from here so we warn the user that we probably loose his diffusion profile reference - Debug.LogError("Failed to upgrade the diffusion profile node value, reseting to default value."+ + Debug.LogError("Failed to upgrade the diffusion profile node value, reseting to default value." + "\nTo remove this message save the shader graph with the new diffusion profile reference."); m_DiffusionProfile.selectedEntry = 0; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/EmissionNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/EmissionNode.cs index d3734ce4fe2..f11cc99b204 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/EmissionNode.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/EmissionNode.cs @@ -82,7 +82,8 @@ public sealed override void UpdateNodeAfterDeserialization() // Output slot:kEmissionOutputSlotName AddSlot(new ColorRGBMaterialSlot(kEmissionOutputSlotId, kEmissionOutputSlotName, kEmissionOutputSlotName , SlotType.Output, Color.black, ColorMode.HDR)); - RemoveSlotsNameNotMatching(new[] { + RemoveSlotsNameNotMatching(new[] + { kEmissionOutputSlotId, kEmissionColorInputSlotId, kEmissionIntensityInputSlotId, kEmissionExposureWeightInputSlotId }); @@ -121,26 +122,26 @@ string GetFunctionName() public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => - { - // We may need ConvertEvToLuminance() so we include CommonLighting.hlsl - s.AppendLine("#include \"Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl\""); + { + // We may need ConvertEvToLuminance() so we include CommonLighting.hlsl + s.AppendLine("#include \"Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl\""); - s.AppendLine("$precision3 {0}($precision3 ldrColor, {1} luminanceIntensity, {1} exposureWeight, {1} inverseCurrentExposureMultiplier)", - GetFunctionName(), - intensitySlot.concreteValueType.ToShaderString()); - using (s.BlockScope()) + s.AppendLine("$precision3 {0}($precision3 ldrColor, {1} luminanceIntensity, {1} exposureWeight, {1} inverseCurrentExposureMultiplier)", + GetFunctionName(), + intensitySlot.concreteValueType.ToShaderString()); + using (s.BlockScope()) + { + if (normalizeColor.isOn) { - if (normalizeColor.isOn) - { - s.AppendLine("ldrColor = ldrColor * rcp(max(Luminance(ldrColor), 1e-6));"); - } - s.AppendLine("$precision3 hdrColor = ldrColor * luminanceIntensity;"); - s.AppendNewLine(); - s.AppendLine("// Inverse pre-expose using _EmissiveExposureWeight weight"); - s.AppendLine("hdrColor = lerp(hdrColor * inverseCurrentExposureMultiplier, hdrColor, exposureWeight);"); - s.AppendLine("return hdrColor;"); + s.AppendLine("ldrColor = ldrColor * rcp(max(Luminance(ldrColor), 1e-6));"); } - }); + s.AppendLine("$precision3 hdrColor = ldrColor * luminanceIntensity;"); + s.AppendNewLine(); + s.AppendLine("// Inverse pre-expose using _EmissiveExposureWeight weight"); + s.AppendLine("hdrColor = lerp(hdrColor * inverseCurrentExposureMultiplier, hdrColor, exposureWeight);"); + s.AppendLine("return hdrColor;"); + } + }); } Vector3 GetHDREmissionColor(Vector3 ldrColor, float intensity) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/ExposureNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/ExposureNode.cs index 202694a3c88..78bfa340e17 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/ExposureNode.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/ExposureNode.cs @@ -60,7 +60,8 @@ public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new ColorRGBMaterialSlot(kExposureOutputSlotId, kExposureOutputSlotName, kExposureOutputSlotName , SlotType.Output, Color.black, ColorMode.Default)); - RemoveSlotsNameNotMatching(new[] { + RemoveSlotsNameNotMatching(new[] + { kExposureOutputSlotId, }); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/HDSceneColorNode.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/HDSceneColorNode.cs index bcaae96f8e5..9b81f9c09b0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/HDSceneColorNode.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Nodes/HDSceneColorNode.cs @@ -51,7 +51,8 @@ public sealed override void UpdateNodeAfterDeserialization() AddSlot(new Vector1MaterialSlot(kLodInputSlotId, kLodInputSlotName, kLodInputSlotName, SlotType.Input, 0, ShaderStageCapability.Fragment)); AddSlot(new ColorRGBMaterialSlot(kColorOutputSlotId, kColorOutputSlotName, kColorOutputSlotName , SlotType.Output, Color.black, ColorMode.HDR)); - RemoveSlotsNameNotMatching(new[] { + RemoveSlotsNameNotMatching(new[] + { kUvInputSlotId, kLodInputSlotId, kColorOutputSlotId, @@ -66,28 +67,28 @@ string GetFunctionName() public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("$precision3 {0}($precision2 uv, $precision lod, $precision exposureMultiplier)", GetFunctionName()); + using (s.BlockScope()) { - s.AppendLine("$precision3 {0}($precision2 uv, $precision lod, $precision exposureMultiplier)", GetFunctionName()); - using (s.BlockScope()) + if (generationMode.IsPreview()) { - if (generationMode.IsPreview()) - { - s.AppendLine("// Sampling the scene color is not supported in the preview"); - s.AppendLine("return $precision3(0.0, 0.0, 0.0);"); - } - else + s.AppendLine("// Sampling the scene color is not supported in the preview"); + s.AppendLine("return $precision3(0.0, 0.0, 0.0);"); + } + else + { + if (exposure.isOn) { - if (exposure.isOn) - { - s.AppendLine("exposureMultiplier = 1.0;"); - } - s.AppendLine("#if defined(REQUIRE_OPAQUE_TEXTURE) && defined(_SURFACE_TYPE_TRANSPARENT) && defined(SHADERPASS) && (SHADERPASS != SHADERPASS_LIGHT_TRANSPORT)"); - s.AppendLine("return SampleCameraColor(uv, lod) * exposureMultiplier;"); - s.AppendLine("#endif"); - s.AppendLine("return $precision3(0.0, 0.0, 0.0);"); + s.AppendLine("exposureMultiplier = 1.0;"); } + s.AppendLine("#if defined(REQUIRE_OPAQUE_TEXTURE) && defined(_SURFACE_TYPE_TRANSPARENT) && defined(SHADERPASS) && (SHADERPASS != SHADERPASS_LIGHT_TRANSPORT)"); + s.AppendLine("return SampleCameraColor(uv, lod) * exposureMultiplier;"); + s.AppendLine("#endif"); + s.AppendLine("return $precision3(0.0, 0.0, 0.0);"); } - }); + } + }); } public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DefaultMaterialSlot.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DefaultMaterialSlot.cs index 20e29d8b8be..807b2b07503 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DefaultMaterialSlot.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DefaultMaterialSlot.cs @@ -13,7 +13,7 @@ public DefaultMaterialSlot() {} public DefaultMaterialSlot(int slotId, string displayName, string shaderOutputName, - ShaderStageCapability stageCapability = ShaderStageCapability.All, bool hidden = false) + ShaderStageCapability stageCapability = ShaderStageCapability.All, bool hidden = false) : base(slotId, displayName, shaderOutputName, SlotType.Input, Vector3.zero, stageCapability, hidden: hidden) {} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs index acdd2a86cc5..305c7ae4dd6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Slots/DiffusionProfileInputMaterialSlot.cs @@ -27,7 +27,6 @@ private class DiffusionProfileSerializer { [SerializeField] public DiffusionProfileSettings diffusionProfileAsset = null; - } [SerializeField] @@ -60,7 +59,7 @@ public DiffusionProfileSettings diffusionProfile set { if (m_DiffusionProfileAsset == value) - return ; + return; var serializedProfile = new DiffusionProfileSerializer(); serializedProfile.diffusionProfileAsset = value; @@ -77,7 +76,7 @@ public DiffusionProfileInputMaterialSlot() } public DiffusionProfileInputMaterialSlot(int slotId, string displayName, string shaderOutputName, - ShaderStageCapability stageCapability = ShaderStageCapability.All, bool hidden = false) + ShaderStageCapability stageCapability = ShaderStageCapability.All, bool hidden = false) : base(slotId, displayName, shaderOutputName, SlotType.Input, 0.0f, stageCapability, hidden: hidden) { } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs index 8b224e2c236..fdf7a5d1c2b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertiesGUI.cs @@ -20,7 +20,7 @@ class SubTargetPropertiesGUI : VisualElement public List uiBlocks = new List(); public SubTargetPropertiesGUI(TargetPropertyGUIContext context, Action onChange, Action registerUndo, - SystemData systemData, BuiltinData builtinData, LightingData lightingData) + SystemData systemData, BuiltinData builtinData, LightingData lightingData) { this.context = context; this.onChange = onChange; @@ -37,4 +37,4 @@ public void AddPropertyBlock(SubTargetPropertyBlock block) Add(block); } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs index db21527273a..f5830463175 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SubTargetPropertyBlock.cs @@ -14,7 +14,7 @@ abstract class SubTargetPropertyBlock : VisualElement { // Null/Empty means no title protected virtual string title => null; - + protected TargetPropertyGUIContext context; protected Action onChange; protected Action registerUndo; @@ -117,7 +117,7 @@ protected void AddHelpBox(string message, MessageType type) { // We don't use UIElement HelpBox because it's width is not dynamic. int indentLevel = context.globalIndentLevel; - var imgui = new IMGUIContainer(() => + var imgui = new IMGUIContainer(() => { float indentPadding = indentLevel * 15; var rect = EditorGUILayout.GetControlRect(false, 42); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs index dc3290a3f0e..39b30d68acf 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceOptionPropertyBlock.cs @@ -53,7 +53,7 @@ protected override void CreatePropertyGUI() context.AddProperty(renderingPassText, new PopupField(renderingPassList, renderQueueType, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName) { value = renderingPassValue }, (evt) => { registerUndo(renderingPassText); - if(systemData.TryChangeRenderingPass(evt.newValue)) + if (systemData.TryChangeRenderingPass(evt.newValue)) onChange(); }); @@ -107,7 +107,7 @@ protected override void CreatePropertyGUI() AddProperty(receivesSSRTransparentText, () => lightingData.receiveSSRTransparent, (newValue) => lightingData.receiveSSRTransparent = newValue); else AddProperty(receivesSSRText, () => lightingData.receiveSSR, (newValue) => lightingData.receiveSSR = newValue); - + AddProperty(enableGeometricSpecularAAText, () => lightingData.specularAA, (newValue) => lightingData.specularAA = newValue); } AddProperty(depthOffsetEnableText, () => builtinData.depthOffset, (newValue) => builtinData.depthOffset = newValue); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs index 4d5d56b0604..75ae1731e16 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/SurfaceSubTarget.cs @@ -90,7 +90,7 @@ PassCollection GetPasses() { // We always generate the TransparentDepthPrepass as it can be use with SSR transparent passes.Add(HDShaderPasses.GenerateTransparentDepthPrepass(true)); - } + } else { // We only generate the pass if requested @@ -131,11 +131,12 @@ PassCollection GetPasses() passes.Add(HDShaderPasses.GenerateRaytracingVisibility(supportLighting)); passes.Add(HDShaderPasses.GenerateRaytracingForward(supportLighting)); passes.Add(HDShaderPasses.GenerateRaytracingGBuffer(supportLighting)); - }; + } + ; if (supportPathtracing) passes.Add(HDShaderPasses.GeneratePathTracing(supportLighting)); - + return passes; } } @@ -160,7 +161,7 @@ protected override void CollectPassKeywords(ref PassDescriptor pass) if (pass.IsLightingOrMaterial()) pass.keywords.Add(CoreKeywordDescriptors.DebugDisplay); - + if (!pass.IsDXR()) pass.keywords.Add(CoreKeywordDescriptors.LodFadeCrossfade, new FieldCondition(Fields.LodCrossFade, true)); @@ -176,7 +177,7 @@ protected override void CollectPassKeywords(ref PassDescriptor pass) public override void GetFields(ref TargetFieldContext context) { base.GetFields(ref context); - + if (supportDistortion) AddDistortionFields(ref context); @@ -192,10 +193,10 @@ public override void GetFields(ref TargetFieldContext context) // We always generate the keyword ALPHATEST_ON. All the variant of AlphaClip (shadow, pre/postpass) are only available if alpha test is on. context.AddField(Fields.AlphaTest, systemData.alphaTest - && (context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold) - || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow) - || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass) - || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass))); + && (context.pass.validPixelBlocks.Contains(BlockFields.SurfaceDescription.AlphaClipThreshold) + || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow) + || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass) + || context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPostpass))); // All the DoAlphaXXX field drive the generation of which code to use for alpha test in the template // Regular alpha test is only done if artist haven't ask to use the specific alpha test shadow one @@ -204,10 +205,10 @@ public override void GetFields(ref TargetFieldContext context) // Shadow use the specific alpha test only if user have ask to override it context.AddField(HDFields.DoAlphaTestShadow, systemData.alphaTest && builtinData.alphaTestShadow && isShadowPass && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow)); // Pre/post pass always use the specific alpha test provided for those pass context.AddField(HDFields.DoAlphaTestPrepass, systemData.alphaTest && builtinData.transparentDepthPrepass && isTransparentDepthPrepass && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.AlphaClipThresholdDepthPrepass)); // Features & Misc context.AddField(Fields.LodCrossFade, builtinData.supportLodCrossFade); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/BuiltinData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/BuiltinData.cs index d6e530607bd..53e0f803182 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/BuiltinData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/BuiltinData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/HDTargetData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/HDTargetData.cs index 138eff62bb5..6f60ee2c232 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/HDTargetData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/HDTargetData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph.Serialization; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/IRequiresData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/IRequiresData.cs index 9b27c0be9e2..6568b3b2fc1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/IRequiresData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/IRequiresData.cs @@ -1,4 +1,4 @@ -namespace UnityEditor.Rendering.HighDefinition.ShaderGraph +namespace UnityEditor.Rendering.HighDefinition.ShaderGraph { interface IRequiresData where T : HDTargetData { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/LightingData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/LightingData.cs index e3172bf0412..cd4b56e5a72 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/LightingData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/LightingData.cs @@ -54,7 +54,7 @@ public bool specularAA get => m_SpecularAA; set => m_SpecularAA = value; } - + // TODO: Was on HDLitMasterNode but seemingly replaced by a Port // [SerializeField] // float m_SpecularAAScreenSpaceVariance; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/SystemData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/SystemData.cs index 6068898f463..c104e8c570c 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/SystemData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/TargetData/SystemData.cs @@ -48,7 +48,7 @@ public CompareFunction zTest { get => m_ZTest; set => m_ZTest = value; - } + } [SerializeField] bool m_ZWrite = false; @@ -150,7 +150,8 @@ public static bool TryChangeRenderingPass(this SystemData systemData, HDRenderQu case HDRenderQueue.RenderQueueType.Unknown: case HDRenderQueue.RenderQueueType.Background: throw new ArgumentException("Unexpected kind of RenderQueue, was " + value); - }; + } + ; // Update for SurfaceType switch (systemData.surfaceType) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Templates/VertexAnimation.template.hlsl b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Templates/VertexAnimation.template.hlsl index b4126d74644..db0d5bf09d5 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Templates/VertexAnimation.template.hlsl +++ b/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/Templates/VertexAnimation.template.hlsl @@ -9,7 +9,7 @@ VertexDescriptionInputs AttributesMeshToVertexDescriptionInputs(AttributesMesh i $VertexDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = TransformWorldToViewDir(output.WorldSpaceNormal); $VertexDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f); $VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS.xyz; - $VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz); + $VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz); $VertexDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent); $VertexDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f); $VertexDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = normalize(cross(input.normalOS, input.tangentOS) * (input.tangentOS.w > 0.0f ? 1.0f : -1.0f) * GetOddNegativeScale()); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs index c7eb075732c..451be645b34 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/CreateStackLitShaderGraph.cs @@ -11,8 +11,8 @@ public static void CreateStackLitGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(StackLitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -28,7 +28,7 @@ public static void CreateStackLitGraph() BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/ShaderPass.template.hlsl b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/ShaderPass.template.hlsl index 21629b5e1dc..e4b0af2f8c8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/ShaderPass.template.hlsl +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/ShaderPass.template.hlsl @@ -154,7 +154,7 @@ void BuildSurfaceData(FragInputs fragInputs, inout SurfaceDescription surfaceDes bentNormalWS = surfaceData.normalWS; $BentNormal: GetNormalWS(fragInputs, surfaceDescription.BentNormal, bentNormalWS, doubleSidedConstants); - surfaceData.bentNormalWS = bentNormalWS; + surfaceData.bentNormalWS = bentNormalWS; surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs index c8029fb8398..b7885584167 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs index f12a7c40481..6f88fa36d18 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs @@ -18,7 +18,7 @@ sealed partial class StackLitSubTarget : LightingSubTarget, ILegacyTarget, IRequ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is StackLitMasterNode1 stackLitMasterNode)) + if (!(masterNode is StackLitMasterNode1 stackLitMasterNode)) return false; m_MigrateFromOldSG = true; @@ -70,14 +70,14 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary(CoatMaskSlotId).value == 0.0f), // context.AddField(CoatMaskOne, coat.isOn && pass.pixelBlocks.Contains(CoatMaskSlotId) && @@ -161,7 +161,7 @@ public override void GetFields(ref TargetFieldContext context) // Dual Specular Lobe Parametrization context.AddField(HazyGloss, stackLitData.dualSpecularLobe && - stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); + stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); // Misc context.AddField(EnergyConservingSpecular, stackLitData.energyConservingSpecular); @@ -169,9 +169,9 @@ public override void GetFields(ref TargetFieldContext context) // Again we assume masternode has HazyGlossMaxDielectricF0 which should always be the case // if capHazinessWrtMetallic.isOn. context.AddField(CapHazinessIfNotMetallic, stackLitData.dualSpecularLobe && - stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss && - stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic - && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0)); + stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss && + stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic + && context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0)); // Note here we combine an "enable"-like predicate and the $SurfaceDescription.(slotname) predicate // into a single $GeometricSpecularAA pedicate. // @@ -190,13 +190,13 @@ public override void GetFields(ref TargetFieldContext context) // (Note we can achieve the same results in the template on just single predicates by making defines out of them, // and using #if defined() && etc) context.AddField(GeometricSpecularAA, lightingData.specularAA && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance) && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold)); context.AddField(SpecularAA, lightingData.specularAA && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance) && - context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold)); + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance) && + context.pass.validPixelBlocks.Contains(HDBlockFields.SurfaceDescription.SpecularAAThreshold)); context.AddField(SpecularOcclusion, stackLitData.screenSpaceSpecularOcclusionBaseMode != StackLitData.SpecularOcclusionBaseMode.Off || - stackLitData.dataBasedSpecularOcclusionBaseMode != StackLitData.SpecularOcclusionBaseMode.Off); + stackLitData.dataBasedSpecularOcclusionBaseMode != StackLitData.SpecularOcclusionBaseMode.Off); // Advanced context.AddField(AnisotropyForAreaLights, stackLitData.anisotropyForAreaLights); @@ -214,19 +214,19 @@ public override void GetFields(ref TargetFieldContext context) // Screen Space Specular Occlusion AO Cone Size context.AddField(SSSpecularOcclusionAOConeSizeUniformAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && - stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.UniformAO); + stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.UniformAO); context.AddField(SSSpecularOcclusionAOConeSizeCosWeightedAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && - stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedAO); + stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedAO); context.AddField(SSSpecularOcclusionAOConeSizeCosWeightedBentCorrectAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && - stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO); + stackLitData.screenSpaceSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO); // Screen Space Specular Occlusion AO Cone Dir context.AddField(SSSpecularOcclusionAOConeDirGeomNormal, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && - stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.GeomNormal); + stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.GeomNormal); context.AddField(SSSpecularOcclusionAOConeDirBentNormal, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && - stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.BentNormal); + stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.BentNormal); context.AddField(SSSpecularOcclusionAOConeDirShadingNormal, SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) && - stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.ShadingNormal); + stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.ShadingNormal); // Data Based Specular Occlusion Base Mode context.AddField(DataBasedSpecularOcclusionBaseModeOff, stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Off); @@ -237,21 +237,21 @@ public override void GetFields(ref TargetFieldContext context) // Data Based Specular Occlusion AO Cone Size context.AddField(DataBasedSpecularOcclusionAOConeSizeUniformAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) && - stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.UniformAO); + stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.UniformAO); context.AddField(DataBasedSpecularOcclusionAOConeSizeCosWeightedAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) && - stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedAO); + stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedAO); context.AddField(DataBasedSpecularOcclusionAOConeSizeCosWeightedBentCorrectAO, SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) && - stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO); + stackLitData.dataBasedSpecularOcclusionAOConeSize == StackLitData.SpecularOcclusionAOConeSize.CosWeightedBentCorrectAO); // Specular Occlusion Cone Fixup Method context.AddField(SpecularOcclusionConeFixupMethodOff, SpecularOcclusionUsesBentNormal(stackLitData) && - stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.Off); + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.Off); context.AddField(SpecularOcclusionConeFixupMethodBoostBSDFRoughness, SpecularOcclusionUsesBentNormal(stackLitData) && - stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostBSDFRoughness); + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostBSDFRoughness); context.AddField(SpecularOcclusionConeFixupMethodTiltDirectionToGeomNormal, SpecularOcclusionUsesBentNormal(stackLitData) && - stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.TiltDirectionToGeomNormal); + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.TiltDirectionToGeomNormal); context.AddField(SpecularOcclusionConeFixupMethodBoostAndTilt, SpecularOcclusionUsesBentNormal(stackLitData) && - stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostAndTilt); + stackLitData.specularOcclusionConeFixupMethod == StackLitData.SpecularOcclusionConeFixupMethod.BoostAndTilt); } public override void GetActiveBlocks(ref TargetActiveBlockContext context) @@ -291,12 +291,12 @@ public override void GetActiveBlocks(ref TargetActiveBlockContext context) // for custom (external) SO replacing data based SO (which normally comes from some func of DataBasedSOMode(dataAO, optional bent normal)) // TODO: we would ideally need one value per lobe context.AddBlock(HDBlockFields.SurfaceDescription.SpecularOcclusion, DataBasedSpecularOcclusionIsCustom()); - context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, SpecularOcclusionUsesBentNormal(stackLitData) && - stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); - context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, SpecularOcclusionUsesBentNormal(stackLitData) && - stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); + context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); + context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, SpecularOcclusionUsesBentNormal(stackLitData) && + stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); context.AddBlock(HDBlockFields.SurfaceDescription.SOFixupMaxAddedRoughness, SpecularOcclusionUsesBentNormal(stackLitData) && SpecularOcclusionConeFixupMethodModifiesRoughness(stackLitData.specularOcclusionConeFixupMethod) && - stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); + stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off); // Coat context.AddBlock(HDBlockFields.SurfaceDescription.CoatSmoothness, stackLitData.coat); @@ -315,7 +315,7 @@ public override void GetActiveBlocks(ref TargetActiveBlockContext context) context.AddBlock(HDBlockFields.SurfaceDescription.Haziness, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); context.AddBlock(HDBlockFields.SurfaceDescription.HazeExtent, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss); context.AddBlock(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0, stackLitData.dualSpecularLobe && stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss && - stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic); + stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic); context.AddBlock(HDBlockFields.SurfaceDescription.AnisotropyB, stackLitData.dualSpecularLobe && stackLitData.anisotropy); // Iridescence @@ -389,8 +389,8 @@ public static bool SpecularOcclusionModeUsesVisibilityCone(StackLitData.Specular public static bool SpecularOcclusionUsesBentNormal(StackLitData stackLitData) { return (SpecularOcclusionModeUsesVisibilityCone(stackLitData.dataBasedSpecularOcclusionBaseMode) - || (SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) - && stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.BentNormal)); + || (SpecularOcclusionModeUsesVisibilityCone(stackLitData.screenSpaceSpecularOcclusionBaseMode) + && stackLitData.screenSpaceSpecularOcclusionAOConeDir == StackLitData.SpecularOcclusionAOConeDir.BentNormal)); } bool DataBasedSpecularOcclusionIsCustom() diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs index 35bfe88b371..09009a72448 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/StackLit/ShaderGraph/StackLitSurfaceOptionPropertyBlock.cs @@ -61,7 +61,7 @@ protected override void CreatePropertyGUI() // SpecularOcclusion from input AO (baked or data-based SO) EnumField specularOcclusionFromInputAOField; - if(stackLitData.devMode) + if (stackLitData.devMode) { specularOcclusionFromInputAOField = new EnumField(StackLitData.SpecularOcclusionBaseMode.DirectFromAO); specularOcclusionFromInputAOField.value = stackLitData.dataBasedSpecularOcclusionBaseMode; @@ -93,10 +93,10 @@ protected override void CreatePropertyGUI() AddProperty("Specular Occlusion Bent Cone Fixup", () => stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off, (newValue) => { stackLitData.specularOcclusionConeFixupMethod = newValue ? StackLitData.SpecularOcclusionConeFixupMethod.BoostAndTilt - : StackLitData.SpecularOcclusionConeFixupMethod.Off; + : StackLitData.SpecularOcclusionConeFixupMethod.Off; }, 0); } - + // Misc Cont. // Advanced Options context.AddLabel("Advanced Options", 0); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/StandardsTerrainToHDTerrainLitUpgrader.cs b/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/StandardsTerrainToHDTerrainLitUpgrader.cs index 91d4812cf55..ca72dd12b87 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/StandardsTerrainToHDTerrainLitUpgrader.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/StandardsTerrainToHDTerrainLitUpgrader.cs @@ -5,7 +5,6 @@ namespace UnityEditor.Rendering.HighDefinition { class StandardsTerrainToHDTerrainLitUpgrader : MaterialUpgrader { - public StandardsTerrainToHDTerrainLitUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null) { RenameShader(sourceShaderName, destShaderName, finalizer); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs index fd9271dc83e..acf0361bdeb 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs @@ -34,14 +34,14 @@ protected override void OnMaterialGUI(MaterialEditor materialEditor, MaterialPro using (var changed = new EditorGUI.ChangeCheckScope()) { uiBlocks.Initialize(materialEditor, props); - uiBlocks.FetchUIBlock< SurfaceOptionUIBlock >().UpdateMaterialProperties(props); - uiBlocks.FetchUIBlock< SurfaceOptionUIBlock >().OnGUI(); + uiBlocks.FetchUIBlock().UpdateMaterialProperties(props); + uiBlocks.FetchUIBlock().OnGUI(); // TODO: move the terrain UI to a MaterialUIBlock to clarify the code DrawTerrainGUI(materialEditor); - uiBlocks.FetchUIBlock< SurfaceOptionUIBlock >().UpdateMaterialProperties(props); - uiBlocks.FetchUIBlock< AdvancedOptionsUIBlock >().OnGUI(); + uiBlocks.FetchUIBlock().UpdateMaterialProperties(props); + uiBlocks.FetchUIBlock().OnGUI(); ApplyKeywordsAndPassesIfNeeded(changed.changed, uiBlocks.materials); } @@ -134,7 +134,7 @@ static public void SetupMaterialKeywordsAndPass(Material material) BaseLitGUI.SetupBaseLitKeywords(material); BaseLitGUI.SetupBaseLitMaterialPass(material); bool receiveSSR = material.GetSurfaceType() == SurfaceType.Opaque ? (material.HasProperty(kReceivesSSR) ? material.GetInt(kReceivesSSR) != 0 : false) - : (material.HasProperty(kReceivesSSRTransparent) ? material.GetInt(kReceivesSSRTransparent) != 0 : false); + : (material.HasProperty(kReceivesSSRTransparent) ? material.GetInt(kReceivesSSRTransparent) != 0 : false); BaseLitGUI.SetupStencil(material, receiveSSR, material.GetMaterialId() == MaterialId.LitSSS); // TODO: planar/triplannar support diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AdvancedOptionsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AdvancedOptionsUIBlock.cs index 89240962b87..dedeebb2b45 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AdvancedOptionsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AdvancedOptionsUIBlock.cs @@ -64,7 +64,6 @@ public override void LoadMaterialProperties() } addPrecomputedVelocity = FindProperty(kAddPrecomputedVelocity); - } public override void OnGUI() @@ -98,7 +97,7 @@ void DrawAdvancedOptionsGUI() materialEditor.ShaderProperty(specularOcclusionMode, Styles.specularOcclusionModeText); if ((m_Features & Features.AddPrecomputedVelocity) != 0) { - if ( addPrecomputedVelocity != null) + if (addPrecomputedVelocity != null) materialEditor.ShaderProperty(addPrecomputedVelocity, Styles.addPrecomputedVelocityText); } } @@ -114,7 +113,7 @@ void DrawMotionVectorToggle() // So here we workaround it with materialTag system by checking if a tag exist to know if it is // the first time we display this information. And thus setup the MotionVector Pass to false. const string materialTag = "MotionVector"; - + string tag = materials[0].GetTag(materialTag, false, "Nothing"); if (tag == "Nothing") { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfMainSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfMainSurfaceInputsUIBlock.cs index 201682f0d4e..3ac514c64a5 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfMainSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfMainSurfaceInputsUIBlock.cs @@ -48,7 +48,7 @@ public override void LoadMaterialProperties() m_MappingMask = FindProperty(m_MappingMaskText); m_PlanarSpace = FindProperty(m_PlanarSpaceText); - m_MaterialTilingOffset = FindProperty(m_MaterialTilingOffsetText); + m_MaterialTilingOffset = FindProperty(m_MaterialTilingOffsetText); } public override void OnGUI() diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs index dc09d77326e..db62da248d2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/AxfSurfaceInputsUIBlock.cs @@ -67,7 +67,6 @@ public class Styles public static GUIContent clearcoatNormalMapText = new GUIContent("Clearcoat Normal"); public static GUIContent clearcoatNormalMapTilingText = new GUIContent("Clearcoat Normal Tiling and Offset"); public static GUIContent clearcoatIORMapText = new GUIContent("Clearcoat IOR"); - } static readonly string[] AxfBrdfTypeNames = Enum.GetNames(typeof(AxfBrdfType)); @@ -316,21 +315,21 @@ public override void OnGUI() } public static uint GenFlags(bool anisotropy = false, bool clearcoat = false, bool clearcoatRefraction = false, bool useHeightMap = false, bool brdfColorDiagonalClamp = false, - bool honorMinRoughness = false) + bool honorMinRoughness = false) { uint flags = 0; - flags |= anisotropy ? (uint) AxF.FeatureFlags.AxfAnisotropy : 0U; - flags |= clearcoat ? (uint) AxF.FeatureFlags.AxfClearCoat : 0U; - flags |= clearcoatRefraction ? (uint) AxF.FeatureFlags.AxfClearCoatRefraction : 0U; - flags |= useHeightMap ? (uint) AxF.FeatureFlags.AxfUseHeightMap : 0U; - flags |= brdfColorDiagonalClamp ? (uint) AxF.FeatureFlags.AxfBRDFColorDiagonalClamp : 0U; - flags |= honorMinRoughness ? (uint) AxF.FeatureFlags.AxfHonorMinRoughness : 0U; + flags |= anisotropy ? (uint)AxF.FeatureFlags.AxfAnisotropy : 0U; + flags |= clearcoat ? (uint)AxF.FeatureFlags.AxfClearCoat : 0U; + flags |= clearcoatRefraction ? (uint)AxF.FeatureFlags.AxfClearCoatRefraction : 0U; + flags |= useHeightMap ? (uint)AxF.FeatureFlags.AxfUseHeightMap : 0U; + flags |= brdfColorDiagonalClamp ? (uint)AxF.FeatureFlags.AxfBRDFColorDiagonalClamp : 0U; + flags |= honorMinRoughness ? (uint)AxF.FeatureFlags.AxfHonorMinRoughness : 0U; return flags; } public static void ExtractFlags(uint flags, - out bool anisotropy, out bool clearcoat, out bool clearcoatRefraction, out bool useHeightMap, out bool brdfColorDiagonalClamp, - out bool honorMinRoughness) + out bool anisotropy, out bool clearcoat, out bool clearcoatRefraction, out bool useHeightMap, out bool brdfColorDiagonalClamp, + out bool honorMinRoughness) { anisotropy = (flags & (uint)AxF.FeatureFlags.AxfAnisotropy) != 0; clearcoat = (flags & (uint)AxF.FeatureFlags.AxfClearCoat) != 0; @@ -343,7 +342,7 @@ public static void ExtractFlags(uint flags, public static void DrawRightJustifiedHeader(string header) { EditorGUILayout.BeginHorizontal(); - GUILayout.Label("", GUILayout.Width(EditorGUIUtility.labelWidth-5)); + GUILayout.Label("", GUILayout.Width(EditorGUIUtility.labelWidth - 5)); GUILayout.Label(header, EditorStyles.boldLabel); //EditorGUILayout.LabelField(header, EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); @@ -358,8 +357,8 @@ void DrawAxfSurfaceOptionsGUI() // Extract flag: uint flags = (uint)m_Flags.floatValue; ExtractFlags(flags, - out bool anisotropy, out bool clearcoat, out bool clearcoatRefraction, out bool useHeightMap, out bool brdfColorDiagonalClamp, - out bool honorMinRoughness); + out bool anisotropy, out bool clearcoat, out bool clearcoatRefraction, out bool useHeightMap, out bool brdfColorDiagonalClamp, + out bool honorMinRoughness); switch (AxF_BRDFType) { @@ -540,7 +539,7 @@ void DrawAxfSurfaceOptionsGUI() // Finally write back flags: flags = GenFlags(anisotropy, clearcoat, clearcoatRefraction, useHeightMap, brdfColorDiagonalClamp, - honorMinRoughness); + honorMinRoughness); m_Flags.floatValue = (float)flags; }//DrawAxfSurfaceOptionsGUI } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSortingInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSortingInputsUIBlock.cs index eb1c845583a..5f074d78abc 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSortingInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSortingInputsUIBlock.cs @@ -24,8 +24,8 @@ public class Styles { public const string header = "Sorting Inputs"; - public static GUIContent meshDecalDepthBiasText = new GUIContent("Mesh Decal Depth Bias", "Sets a depth bias to stop the decal's Mesh from overlapping with other Meshes."); - public static GUIContent drawOrderText = new GUIContent("Draw Order", "Controls the draw order of Decal Projectors. HDRP draws decals with lower values first."); + public static GUIContent meshDecalDepthBiasText = new GUIContent("Mesh Decal Depth Bias", "Sets a depth bias to stop the decal's Mesh from overlapping with other Meshes."); + public static GUIContent drawOrderText = new GUIContent("Draw Order", "Controls the draw order of Decal Projectors. HDRP draws decals with lower values first."); } Expandable m_ExpandableBit; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs index c02be6a604d..d31fa43c50d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceInputsUIBlock.cs @@ -31,7 +31,7 @@ public class Styles public static GUIContent aoText = new GUIContent("Ambient Occlusion", "Controls the ambient occlusion of the decal."); public static GUIContent maskOpacityChannelText = new GUIContent("Mask Opacity Channel", "Specifies the source this Material uses as opacity for its Mask Map."); public static GUIContent maskMapBlueScaleText = new GUIContent("Scale Mask Map Blue Channel", "Controls the scale of the blue channel of the Mask Map. You can use this as opacity depending on the blend source you choose."); - public static GUIContent opacityBlueScaleText = new GUIContent("Mask Opacity", "Controls the opacity of the Mask (Metallic, Ambient Occlusion, Smoothness). You can use this as opacity depending on the blend source you choose."); + public static GUIContent opacityBlueScaleText = new GUIContent("Mask Opacity", "Controls the opacity of the Mask (Metallic, Ambient Occlusion, Smoothness). You can use this as opacity depending on the blend source you choose."); public static GUIContent useEmissionIntensityText = new GUIContent("Use Emission Intensity", "When enabled, this Material separates emission color and intensity. This makes the Emission Map into an LDR color and exposes the Emission Intensity property."); public static GUIContent emissionMapText = new GUIContent("Emission Map", "Specifies a map (RGB) that the Material uses for emission."); public static GUIContent emissiveIntensityText = new GUIContent("Emission Intensity", "Sets the overall strength of the emission effect."); @@ -213,7 +213,7 @@ void DrawDecalGUI() if (materials.All(m => m.GetTexture(kNormalMap))) { EditorGUI.indentLevel++; - + EditorGUI.BeginChangeCheck(); var normalBlendSrcValue = (int)normalBlendSrc.floatValue; normalBlendSrcValue = EditorGUILayout.Popup(Styles.normalOpacityChannelText, normalBlendSrcValue, allMaskMap ? blendSourceNames : blendSourceNamesNoMap); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceOptionsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceOptionsUIBlock.cs index 86aca5c42ce..44e70823070 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceOptionsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/DecalSurfaceOptionsUIBlock.cs @@ -91,7 +91,7 @@ void DrawDecalGUI() if (!perChannelMask && (affectsMetal != null || affectsAO != null)) { EditorGUILayout.HelpBox("Enable 'Metal and AO properties' in your HDRP Asset if you want to control the Metal and AO properties of decals. There is a performance cost of enabling this option.", - MessageType.Info); + MessageType.Info); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/EmissionUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/EmissionUIBlock.cs index bdff8bae4ab..c318e193524 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/EmissionUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/EmissionUIBlock.cs @@ -30,7 +30,6 @@ static EmissionUIBlock() GetLightingSettingsOrDefaultsFallback = getLightingSettingsOrDefaultsFallbackLambda.Compile(); } - public class Styles { public const string header = "Emission Inputs"; @@ -199,7 +198,7 @@ void DrawEmissionGUI() } if (EditorGUI.EndChangeCheck() || updateEmissiveColor) { - if(unitChanged) + if (unitChanged) { if (unitIsMixed) UpdateEmissionUnit(newUnitFloat); @@ -227,11 +226,10 @@ void DrawEmissionGUI() } } - public static bool BakedEmissionEnabledProperty(MaterialEditor materialEditor) { Material[] materials = Array.ConvertAll(materialEditor.targets, (UnityEngine.Object o) => { return (Material)o; }); - + // Calculate isMixed bool enabled = materials[0].globalIlluminationFlags == MaterialGlobalIlluminationFlags.BakedEmissive; bool isMixed = materials.Any(m => m.globalIlluminationFlags != materials[0].globalIlluminationFlags); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/HDShaderGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/HDShaderGUI.cs index 6e52ad39e48..fffd954cfec 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/HDShaderGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/HDShaderGUI.cs @@ -87,8 +87,9 @@ public sealed override void OnGUI(MaterialEditor materialEditor, MaterialPropert /// The list of properties the material has. protected abstract void OnMaterialGUI(MaterialEditor materialEditor, MaterialProperty[] props); - readonly static string[] floatPropertiesToSynchronize = { - kUseSplitLighting, + readonly static string[] floatPropertiesToSynchronize = + { + kUseSplitLighting, }; /// diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LayerListUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LayerListUIBlock.cs index c698386f937..c6e8cf63e3f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LayerListUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LayerListUIBlock.cs @@ -62,7 +62,7 @@ void UpdateEditorExpended(int layerNumber) public LayerListUIBlock(Expandable expandableBit) { m_ExpandableBit = expandableBit; - m_WithUV = new bool[]{ true, true, true, true }; + m_WithUV = new bool[] { true, true, true, true }; } public override void LoadMaterialProperties() diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LightingShaderGraphGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LightingShaderGraphGUI.cs index 9e8eb3d643b..a8224e1963b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LightingShaderGraphGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LightingShaderGraphGUI.cs @@ -54,7 +54,7 @@ public static void SetupMaterialKeywordsAndPass(Material material) receiveSSR = material.HasProperty(kReceivesSSRTransparent) ? material.GetFloat(kReceivesSSRTransparent) != 0 : false; else receiveSSR = material.HasProperty(kReceivesSSR) ? material.GetFloat(kReceivesSSR) != 0 : false; - bool useSplitLighting = material.HasProperty(kUseSplitLighting) ? material.GetInt(kUseSplitLighting) != 0: false; + bool useSplitLighting = material.HasProperty(kUseSplitLighting) ? material.GetInt(kUseSplitLighting) != 0 : false; BaseLitGUI.SetupStencil(material, receiveSSR, useSplitLighting); if (material.HasProperty(kAddPrecomputedVelocity)) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitShaderGraphGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitShaderGraphGUI.cs index 467d4358de9..04966b150c4 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitShaderGraphGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitShaderGraphGUI.cs @@ -13,7 +13,7 @@ internal class LitShaderGraphGUI : LightingShaderGraphGUI { public LitShaderGraphGUI() { - // Lit SG have refraction block + // Lit SG have refraction block uiBlocks.Insert(1, new TransparencyUIBlock(MaterialUIBlock.Expandable.Transparency, TransparencyUIBlock.Features.Refraction)); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs index 7fcd31abf63..9368c9c9d1f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/LitSurfaceInputsUIBlock.cs @@ -499,9 +499,9 @@ void DrawSurfaceInputsGUI() // Fetch the surface option block which contains the function to update the displacement datas if (m_LayerCount == 1) - surfaceOption = parent.FetchUIBlock< SurfaceOptionUIBlock >(); + surfaceOption = parent.FetchUIBlock(); else - surfaceOption = parent.parent.FetchUIBlock< SurfaceOptionUIBlock >(); + surfaceOption = parent.parent.FetchUIBlock(); surfaceOption.UpdateDisplacement(m_LayerIndex); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlock.cs index b4b0b60656f..1d6dd64fa11 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlock.cs @@ -25,14 +25,14 @@ abstract class MaterialUIBlock internal enum Expandable : uint { // Standard - Base = 1<<0, - Input = 1<<1, - Tesselation = 1<<2, - Transparency = 1<<3, + Base = 1 << 0, + Input = 1 << 1, + Tesselation = 1 << 2, + Transparency = 1 << 3, // Free slot 4 - Detail = 1<<5, - Emissive = 1<<6, - Advance = 1<<7, + Detail = 1 << 5, + Emissive = 1 << 6, + Advance = 1 << 7, Other = 1 << 8, ShaderGraph = 1 << 9, @@ -109,7 +109,7 @@ protected MaterialProperty[] FindPropertyLayered(string propertyName, int layerC // If the layerCount is 1, then it means that the property we're fetching is not from a layered material // thus it doesn't have a prefix - string[] prefixes = (layerCount > 1) ? new []{"0", "1", "2", "3"} : new []{""}; + string[] prefixes = (layerCount > 1) ? new[] {"0", "1", "2", "3"} : new[] {""}; for (int i = 0; i < layerCount; i++) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlockList.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlockList.cs index 0ca851ed8b6..487e68c8300 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlockList.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/MaterialUIBlockList.cs @@ -82,7 +82,7 @@ public void Initialize(MaterialEditor materialEditor, MaterialProperty[] propert /// /// MaterialUIBlock type /// - public T FetchUIBlock< T >() where T : MaterialUIBlock + public T FetchUIBlock() where T : MaterialUIBlock { return this.FirstOrDefault(uiBlock => uiBlock is T) as T; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs index 83568222420..edab68ee684 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/RefractionUIBlock.cs @@ -119,7 +119,7 @@ public override void OnGUI() default: break; } - + if (refractionModel.floatValue != 0 && blendMode != null) { if (blendMode.floatValue != (int)BlendMode.Alpha) diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs index 42a6b526433..decd3c34df7 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/SurfaceOptionUIBlock.cs @@ -32,7 +32,7 @@ public enum Features ShowPrePassAndPostPass = 1 << 12, ShowDepthOffsetOnly = 1 << 13, PreserveSpecularLighting = 1 << 14, - Unlit = Surface | BlendMode | DoubleSided | AlphaCutoff | AlphaCutoffThreshold | AlphaCutoffShadowThreshold| AlphaToMask | BackThenFrontRendering | ShowAfterPostProcessPass | ShowPrePassAndPostPass | ShowDepthOffsetOnly, + Unlit = Surface | BlendMode | DoubleSided | AlphaCutoff | AlphaCutoffThreshold | AlphaCutoffShadowThreshold | AlphaToMask | BackThenFrontRendering | ShowAfterPostProcessPass | ShowPrePassAndPostPass | ShowDepthOffsetOnly, Lit = All ^ SurfaceOptionUIBlock.Features.ShowAfterPostProcessPass ^ ShowDepthOffsetOnly, // Lit can't be display in after postprocess pass All = ~0, } @@ -410,7 +410,7 @@ void DrawAlphaCutoffGUI() { // For shadergraphs we show this slider only if the feature is enabled in the shader settings. bool showAlphaClipThreshold = true; - + bool isShaderGraph = AreMaterialsShaderGraphs(); if (isShaderGraph) showAlphaClipThreshold = GetShaderDefaultFloatValue(kAlphaCutoffEnabled) > 0.0f; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TessellationOptionsUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TessellationOptionsUIBlock.cs index a6c1de28031..e4a7bdd07e1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TessellationOptionsUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TessellationOptionsUIBlock.cs @@ -69,7 +69,7 @@ public override void OnGUI() { // If we don't have tesselation if (tessellationMode == null) - return ; + return; using (var header = new MaterialHeaderScope(Styles.header, (uint)m_ExpandableBit, materialEditor)) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TransparencyUIBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TransparencyUIBlock.cs index 134d69f6140..ef367798a48 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TransparencyUIBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TransparencyUIBlock.cs @@ -48,7 +48,7 @@ public override void OnGUI() { // Disable the block if one of the materials is not transparent: if (materials.Any(material => material.GetSurfaceType() != SurfaceType.Transparent)) - return ; + return; // If refraction model is not enabled in SG, we don't show the section var shader = materials[0].shader; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/BaseUnlitGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/BaseUnlitGUI.cs index 8e563d755d6..61e90c4d055 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/BaseUnlitGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/BaseUnlitGUI.cs @@ -28,7 +28,7 @@ public static void SetupBaseUnlitKeywords(this Material material) bool alphaToMaskEnable = alphaTestEnable && material.HasProperty(kAlphaToMask) && material.GetFloat(kAlphaToMask) > 0.0f; CoreUtils.SetKeyword(material, "_ALPHATOMASK_ON", alphaToMaskEnable); - + SurfaceType surfaceType = material.GetSurfaceType(); CoreUtils.SetKeyword(material, "_SURFACE_TYPE_TRANSPARENT", surfaceType == SurfaceType.Transparent); @@ -342,8 +342,7 @@ static public void SetupBaseUnlitPass(this Material material) // don't do any vertex deformation but we can still have // skinning / morph target material.SetShaderPassEnabled(HDShaderPassNames.s_MotionVectorsStr, addPrecomputedVelocity); - } + } } - } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs index b1aa150d61d..6cc9fafd70d 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/CreateHDUnlitShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.HighDefinition.ShaderGraph @@ -11,8 +11,8 @@ public static void CreateHDUnlitGraph() var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget)); target.TrySetActiveSubTarget(typeof(HDUnlitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -21,7 +21,7 @@ public static void CreateHDUnlitGraph() BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs index 8d229a24df1..1c7921e5629 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitData.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering.HighDefinition; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs index badd39fbf27..5affc1f2ba3 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitDistortionPropertyBlock.cs @@ -25,4 +25,4 @@ protected override void CreatePropertyGUI() AddProperty(distortionOnlyText, () => unlitData.distortionOnly, (newValue) => unlitData.distortionOnly = newValue, 1); } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs index fbbecb664f3..5fd23905347 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.Migration.cs @@ -18,7 +18,7 @@ sealed partial class HDUnlitSubTarget : ILegacyTarget public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - switch(masterNode) + switch (masterNode) { case UnlitMasterNode1 unlitMasterNode: UpgradeUnlitMasterNode(unlitMasterNode, out blockMap); diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs index bcf6c751417..c5d9d6c17c9 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/ShaderGraph/HDUnlitSubTarget.cs @@ -62,7 +62,7 @@ protected override SubShaderDescriptor GetSubShaderDescriptor() return new SubShaderDescriptor { generatesPreview = true, - passes = new PassCollection{ { HDShaderPasses.GenerateDistortionPass(false), new FieldCondition(TransparentDistortion, true) } } + passes = new PassCollection { { HDShaderPasses.GenerateDistortionPass(false), new FieldCondition(TransparentDistortion, true) } } }; } else @@ -116,7 +116,7 @@ protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockL public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) { base.CollectShaderProperties(collector, generationMode); - + if (unlitData.enableShadowMatte) { uint mantissa = ((uint)LightFeatureFlags.Punctual | (uint)LightFeatureFlags.Directional | (uint)LightFeatureFlags.Area) & 0x007FFFFFu; diff --git a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/UnlitGUI.cs b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/UnlitGUI.cs index 224157a61d6..dce05ae3a97 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/UnlitGUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Material/Unlit/UnlitGUI.cs @@ -48,7 +48,6 @@ public static void SetupUnlitMaterialKeywordsAndPass(Material material) { CoreUtils.SetKeyword(material, "_ADD_PRECOMPUTED_VELOCITY", material.GetInt(kAddPrecomputedVelocity) != 0); } - } } } // namespace UnityEditor diff --git a/com.unity.render-pipelines.high-definition/Editor/PackageInfo.cs b/com.unity.render-pipelines.high-definition/Editor/PackageInfo.cs index 322f4b27f49..82b1040e109 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PackageInfo.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PackageInfo.cs @@ -1,3 +1,3 @@ using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.HDRP.Editor")] \ No newline at end of file +[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.HDRP.Editor")] diff --git a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/BloomEditor.cs b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/BloomEditor.cs index 175dca79415..c1d8a874e7e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/BloomEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/BloomEditor.cs @@ -69,6 +69,7 @@ public override void OnInspectorGUI() PropertyField(m_Anamorphic); } } + public override QualitySettingsBlob SaveCustomQualitySettingsAsObject(QualitySettingsBlob settings = null) { if (settings == null) diff --git a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ChromaticAberrationEditor.cs b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ChromaticAberrationEditor.cs index 9817b3b86a0..0e4eb5d24ca 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ChromaticAberrationEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ChromaticAberrationEditor.cs @@ -35,6 +35,7 @@ public override void OnInspectorGUI() PropertyField(m_MaxSamples); } } + public override QualitySettingsBlob SaveCustomQualitySettingsAsObject(QualitySettingsBlob settings = null) { if (settings == null) @@ -56,4 +57,3 @@ public override void LoadSettingsFromQualityPreset(RenderPipelineSettings settin } } } - diff --git a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ExposureEditor.cs b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ExposureEditor.cs index b5b30844d5e..b4fc8ca7e38 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ExposureEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ExposureEditor.cs @@ -99,10 +99,10 @@ public override void OnInspectorGUI() EditorGUILayout.Space(); PropertyField(m_MeteringMode); - if(m_MeteringMode.value.intValue == (int)MeteringMode.MaskWeighted) + if (m_MeteringMode.value.intValue == (int)MeteringMode.MaskWeighted) PropertyField(m_WeightTextureMask); - if (m_MeteringMode.value.intValue == (int) MeteringMode.ProceduralMask) + if (m_MeteringMode.value.intValue == (int)MeteringMode.ProceduralMask) { EditorGUILayout.Space(); EditorGUILayout.LabelField("Procedural Mask", EditorStyles.miniLabel); @@ -158,7 +158,7 @@ public override void OnInspectorGUI() PropertyField(m_Compensation); - if(mode == (int)ExposureMode.AutomaticHistogram) + if (mode == (int)ExposureMode.AutomaticHistogram) { EditorGUILayout.Space(); EditorGUILayout.LabelField("Histogram", EditorStyles.miniLabel); @@ -197,7 +197,7 @@ public override void OnInspectorGUI() { // Default unity field m_TargetMidGray.value.intValue = EditorGUILayout.Popup(EditorGUIUtility.TrTextContent("Target Mid Grey", "Sets the desired Mid gray level used by the auto exposure (i.e. to what grey value the auto exposure system maps the average scene luminance)."), - m_TargetMidGray.value.intValue, s_MidGrayNames); + m_TargetMidGray.value.intValue, s_MidGrayNames); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/MotionBlurEditor.cs b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/MotionBlurEditor.cs index 597e701bcd2..5c22c2aa017 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/MotionBlurEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/MotionBlurEditor.cs @@ -80,27 +80,23 @@ public override void OnInspectorGUI() using (new EditorGUI.DisabledScope(!(mode == (int)CameraClampMode.Rotation || mode == (int)CameraClampMode.SeparateTranslationAndRotation))) { PropertyField(m_CameraRotClamp, EditorGUIUtility.TrTextContent("Rotation Clamp", "Sets the maximum length, as a fraction of the screen's full resolution, that the motion vectors resulting from Camera rotation can have." + - " Only valid if Camera clamp mode is set to Rotation or Separate Translation And Rotation.")); + " Only valid if Camera clamp mode is set to Rotation or Separate Translation And Rotation.")); } using (new EditorGUI.DisabledScope(!(mode == (int)CameraClampMode.Translation || mode == (int)CameraClampMode.SeparateTranslationAndRotation))) { PropertyField(m_CameraTransClamp, EditorGUIUtility.TrTextContent("Translation Clamp", "Sets the maximum length, as a fraction of the screen's full resolution, that the motion vectors resulting from Camera translation can have." + - " Only valid if Camera clamp mode is set to Translation or Separate Translation And Rotation.")); - + " Only valid if Camera clamp mode is set to Translation or Separate Translation And Rotation.")); } using (new EditorGUI.DisabledScope(mode != (int)CameraClampMode.FullCameraMotionVector)) { PropertyField(m_CameraFullClamp, EditorGUIUtility.TrTextContent("Motion Vector Clamp", "Sets the maximum length, as a fraction of the screen's full resolution, that the motion vectors resulting from Camera movement can have." + - " Only valid if Camera clamp mode is set to Full Camera Motion Vector.")); - + " Only valid if Camera clamp mode is set to Full Camera Motion Vector.")); } } } - - - } } + public override QualitySettingsBlob SaveCustomQualitySettingsAsObject(QualitySettingsBlob settings = null) { if (settings == null) diff --git a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/SerializedGlobalPostProcessSettings.cs b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/SerializedGlobalPostProcessSettings.cs index a769660417d..4db29a12eda 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/SerializedGlobalPostProcessSettings.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/SerializedGlobalPostProcessSettings.cs @@ -1,4 +1,3 @@ - namespace UnityEditor.Rendering.HighDefinition { class SerializedGlobalPostProcessSettings diff --git a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/TrackballUIDrawer.cs b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/TrackballUIDrawer.cs index 3cab7005ae8..1b4c41f79ec 100644 --- a/com.unity.render-pipelines.high-definition/Editor/PostProcessing/TrackballUIDrawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/PostProcessing/TrackballUIDrawer.cs @@ -29,7 +29,7 @@ public void OnGUI(SerializedProperty property, SerializedProperty overrideState, Debug.LogWarning("TrackballUIDrawer requires a Vector4 property"); return; } - + m_ComputeFunc = computeFunc; var value = property.vector4Value; @@ -159,7 +159,7 @@ void DrawWheel(ref Vector4 value, bool overrideState) { var valuesRect = GUILayoutUtility.GetRect(1f, 17f); valuesRect.width /= (displayInputFields ? 4f : 3.0f); - if(displayInputFields) + if (displayInputFields) { GUI.Label(valuesRect, "RGB Value:", EditorStyles.centeredGreyMiniLabel); valuesRect.x += valuesRect.width; diff --git a/com.unity.render-pipelines.high-definition/Editor/RayTracing/ReflectionKernelGenerator.cs b/com.unity.render-pipelines.high-definition/Editor/RayTracing/ReflectionKernelGenerator.cs index 6210083164f..0b0c8cb0c1e 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RayTracing/ReflectionKernelGenerator.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RayTracing/ReflectionKernelGenerator.cs @@ -62,8 +62,7 @@ void GetLocalFrame(Vector3 localZ, Vector3 localX, out Vector3 localY) localY = Vector3.Cross(localZ, localX); } - - bool intersectPlane(Vector3 n, Vector3 p0, Vector3 l0, Vector3 l, ref float t) + bool intersectPlane(Vector3 n, Vector3 p0, Vector3 l0, Vector3 l, ref float t) { float denom = Vector3.Dot(n, l); if (Mathf.Abs(denom) > 1e-6) @@ -72,9 +71,8 @@ bool intersectPlane(Vector3 n, Vector3 p0, Vector3 l0, Vector3 l, ref float t) t = Vector3.Dot(p0l0, n) / denom; return (t >= 0); } - return false; - } - + return false; + } public void GenerateTable(CameraParameters cameraParameters, int angleSubdivision, float brdfPercentage, int outputWidth, int outputHeight) { @@ -111,7 +109,7 @@ public void GenerateTable(CameraParameters cameraParameters, int angleSubdivisio // Let's compute the reflected direction Vector3 reflected = incidentViewVector - 2 * normalVector * Vector3.Dot(incidentViewVector, normalVector); - // Let's compute the local to world matrix + // Let's compute the local to world matrix Vector3 localX = new Vector3(1.0f, 0.0f, 0.0f); Vector3 localY = new Vector3(); GetLocalFrame(reflected, localX, out localY); @@ -198,7 +196,7 @@ public void GenerateTable(CameraParameters cameraParameters, int angleSubdivisio // Let's compute the reflected direction Vector3 reflected = incidentViewVector - 2 * normalVector * Vector3.Dot(incidentViewVector, normalVector); - // Let's compute the local to world matrix + // Let's compute the local to world matrix Vector3 localX = new Vector3(1.0f, 0.0f, 0.0f); Vector3 localY = new Vector3(); GetLocalFrame(reflected, localX, out localY); @@ -251,7 +249,7 @@ public void GenerateTable(CameraParameters cameraParameters, int angleSubdivisio { for (int wIdx = 0; wIdx < outputWidth; ++wIdx) { - color.r = outputFilter[2*(wIdx + hIdx * outputWidth)]; + color.r = outputFilter[2 * (wIdx + hIdx * outputWidth)]; color.g = outputFilter[2 * (wIdx + hIdx * outputWidth) + 1]; color.b = 0.0f; color.a = 1.0f; @@ -262,4 +260,4 @@ public void GenerateTable(CameraParameters cameraParameters, int angleSubdivisio File.WriteAllBytes(Application.dataPath + "/KernelSizes.png", bytes); } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/RayTracing/SolidAngleKernelGenerator.cs b/com.unity.render-pipelines.high-definition/Editor/RayTracing/SolidAngleKernelGenerator.cs index 870d7709725..856a1b479f0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RayTracing/SolidAngleKernelGenerator.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RayTracing/SolidAngleKernelGenerator.cs @@ -70,7 +70,7 @@ void GetLocalFrame(Vector3 localZ, Vector3 localX, out Vector3 localY) localY = Vector3.Cross(localZ, localX); } - bool intersectPlane(Vector3 n, Vector3 p0, Vector3 l0, Vector3 l, ref float t) + bool intersectPlane(Vector3 n, Vector3 p0, Vector3 l0, Vector3 l, ref float t) { float denom = Vector3.Dot(n, l); if (Mathf.Abs(denom) > 1e-6) @@ -79,7 +79,7 @@ bool intersectPlane(Vector3 n, Vector3 p0, Vector3 l0, Vector3 l, ref float t) t = Vector3.Dot(p0l0, n) / denom; return (t >= 0); } - return false; + return false; } public void GenerateTable(CameraParameters cameraParameters, int angleSubdivision, float brdfPercentage, int outputWidth, int outputHeight, int outputDepth) @@ -120,7 +120,7 @@ public void GenerateTable(CameraParameters cameraParameters, int angleSubdivisio // Let's compute the rotated normal (takes degrees) Vector3 normalVector = Quaternion.AngleAxis(cameraParameters.planeAngle, Vector3.right) * -Vector3.forward; - // Let's compute the local to world matrix + // Let's compute the local to world matrix Vector3 localX = new Vector3(1.0f, 0.0f, 0.0f); Vector3 localY = new Vector3(); GetLocalFrame(normalVector, localX, out localY); @@ -180,4 +180,4 @@ public void GenerateTable(CameraParameters cameraParameters, int angleSubdivisio AssetDatabase.Refresh(); } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraEditor.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraEditor.cs index bc84862c7be..94f012b6345 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraEditor.cs @@ -63,7 +63,7 @@ RenderTexture GetPreviewTextureWithSize(int width, int height) return m_PreviewTexture; } } - + [ScriptableRenderPipelineExtension(typeof(HDRenderPipelineAsset))] class HDCameraContextualMenu : IRemoveAdditionalDataContextualMenu { diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs index 4bbc19eef20..464aede76d6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Drawers.cs @@ -138,8 +138,8 @@ static HDCameraUI() CED.Group( Drawer_CameraWarnings, Drawer_FieldRenderingPath - ) - ); + ) + ); public static readonly CED.IDrawer SectionPhysicalSettings = CED.FoldoutGroup( physicalSettingsHeaderContent, @@ -147,8 +147,8 @@ static HDCameraUI() k_ExpandedState, CED.Group( Drawer_PhysicalCamera - ) - ); + ) + ); public static readonly CED.IDrawer SectionOutputSettings = CED.FoldoutGroup( outputSettingsHeaderContent, @@ -164,8 +164,8 @@ static HDCameraUI() Drawer_FieldRenderTarget, Drawer_FieldDepth, Drawer_FieldNormalizedViewPort - ) - ); + ) + ); public static readonly CED.IDrawer SectionFrameSettings = CED.Conditional( (serialized, owner) => k_ExpandedState[Expandable.General], @@ -182,6 +182,7 @@ static void Drawer_FieldVolumeLayerMask(SerializedHDCamera p, Editor owner) { EditorGUILayout.PropertyField(p.volumeLayerMask, volumeLayerMaskContent); } + static void Drawer_FieldVolumeAnchorOverride(SerializedHDCamera p, Editor owner) { EditorGUILayout.PropertyField(p.volumeAnchorOverride, volumeAnchorOverrideContent); @@ -213,7 +214,7 @@ static void Drawer_Projection(SerializedHDCamera p, Editor owner) cam.orthographic.boolValue = (projectionType == ProjectionType.Orthographic); } EditorGUI.EndProperty(); - + if (cam.orthographic.hasMultipleDifferentValues) return; @@ -322,7 +323,7 @@ static void Drawer_PhysicalCamera(SerializedHDCamera p, Editor owner) int oldFilmGateIndex = Array.IndexOf(k_ApertureFormatValues, new Vector2((float)Math.Round(cam.sensorSize.vector2Value.x, 3), (float)Math.Round(cam.sensorSize.vector2Value.y, 3))); // If it is not one of the preset sizes, set it to custom - oldFilmGateIndex = (oldFilmGateIndex == -1) ? k_CustomPresetIndex: oldFilmGateIndex; + oldFilmGateIndex = (oldFilmGateIndex == -1) ? k_CustomPresetIndex : oldFilmGateIndex; // Get the new user selection int newFilmGateIndex = EditorGUILayout.Popup(cameraTypeContent, oldFilmGateIndex, k_ApertureFormatNames); @@ -475,7 +476,7 @@ static void Drawer_PhysicalCamera(SerializedHDCamera p, Editor owner) p.aperture.floatValue = Mathf.Clamp(float.Parse(newAperture), HDPhysicalCamera.kMinAperture, HDPhysicalCamera.kMaxAperture); } catch - { } + {} } EditorGUILayout.EndHorizontal(); @@ -535,7 +536,7 @@ static void Drawer_FieldClear(SerializedHDCamera p, Editor owner) // if(p.clearColorMode.GetEnumValue() == HDAdditionalCameraData.ClearColorMode.BackgroundColor) or no sky in scene EditorGUILayout.PropertyField(p.backgroundColorHDR, backgroundColorContent); - if(p.clearDepth.boolValue == false) + if (p.clearDepth.boolValue == false) p.clearDepth.boolValue = true; } @@ -555,7 +556,7 @@ static void Drawer_Antialiasing(SerializedHDCamera p, Editor owner) { EditorGUILayout.PropertyField(p.SMAAQuality, SMAAQualityPresetContent); } - else if(p.antialiasing.intValue == (int)HDAdditionalCameraData.AntialiasingMode.TemporalAntialiasing) + else if (p.antialiasing.intValue == (int)HDAdditionalCameraData.AntialiasingMode.TemporalAntialiasing) { EditorGUILayout.PropertyField(p.taaQualityLevel, TAAQualityLevelContent); @@ -569,7 +570,7 @@ static void Drawer_Antialiasing(SerializedHDCamera p, Editor owner) EditorGUILayout.PropertyField(p.taaAntiFlicker, TAAAntiFlicker); } - if(p.taaQualityLevel.intValue == (int)HDAdditionalCameraData.TAAQualityLevel.High) + if (p.taaQualityLevel.intValue == (int)HDAdditionalCameraData.TAAQualityLevel.High) { EditorGUILayout.PropertyField(p.taaMotionVectorRejection, TAAMotionVectorRejection); EditorGUILayout.PropertyField(p.taaAntiRinging, TAAAntiRingingContent); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/SerializedHDCamera.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/SerializedHDCamera.cs index 1ed00c4411c..4a10190cdc2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/SerializedHDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/SerializedHDCamera.cs @@ -10,7 +10,7 @@ class SerializedHDCamera public SerializedObject serializedAdditionalDataObject; //public SerializedProperty backgroundColor; - + public SerializedProperty iso; public SerializedProperty shutterSpeed; public SerializedProperty aperture; @@ -97,7 +97,7 @@ public SerializedHDCamera(SerializedObject serializedObject) frameSettings = new SerializedFrameSettings( serializedAdditionalDataObject.FindProperty("m_RenderingPathCustomFrameSettings"), serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.renderingPathCustomFrameSettingsOverrideMask) - ); + ); probeLayerMask = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.probeLayerMask); allowDynamicResolution = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.allowDynamicResolution); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawer.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawer.cs index 3ffc0e3db43..f04909f4c3c 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawer.cs @@ -10,270 +10,268 @@ namespace UnityEditor.Rendering.HighDefinition { - /// - /// Custom UI class for custom passes - /// - [CustomPassDrawerAttribute(typeof(CustomPass))] + /// + /// Custom UI class for custom passes + /// + [CustomPassDrawerAttribute(typeof(CustomPass))] public class CustomPassDrawer { - class Styles - { - public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; + class Styles + { + public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; public static float reorderableListHandleIndentWidth = 12; - public static GUIContent callback = new GUIContent("Event", "Chose the Callback position for this render pass object."); - public static GUIContent enabled = new GUIContent("Enabled", "Enable or Disable the custom pass"); - public static GUIContent targetDepthBuffer = new GUIContent("Target Depth Buffer"); - public static GUIContent targetColorBuffer = new GUIContent("Target Color Buffer"); - public static GUIContent clearFlags = new GUIContent("Clear Flags", "Clear Flags used when the render targets will are bound, before the pass renders."); - } - - /// - /// List of the elements you can show/hide in the default custom pass UI. - /// - [Flags] - public enum PassUIFlag - { - /// Hides all the default UI fields. - None = 0x00, - /// Shows the name field. - Name = 0x01, - /// Shows the target color buffer field. - TargetColorBuffer = 0x02, - /// Shows the target depth buffer field. - TargetDepthBuffer = 0x04, - /// Shows the clear flags field. - ClearFlags = 0x08, - /// Shows all the default UI fields. - All = ~0, - } - - /// - /// Controls which field of the common pass UI is displayed. - /// - protected virtual PassUIFlag commonPassUIFlags => PassUIFlag.All; - - bool firstTime = true; - - // Serialized Properties - SerializedProperty m_Name; - SerializedProperty m_Enabled; - SerializedProperty m_TargetColorBuffer; - SerializedProperty m_TargetDepthBuffer; - SerializedProperty m_ClearFlags; - SerializedProperty m_PassFoldout; - List m_CustomPassUserProperties = new List(); - CustomPass m_CustomPass; - Type m_PassType => m_CustomPass.GetType(); - - void FetchProperties(SerializedProperty property) - { - m_Name = property.FindPropertyRelative("m_Name"); - m_Enabled = property.FindPropertyRelative("enabled"); - m_TargetColorBuffer = property.FindPropertyRelative("targetColorBuffer"); - m_TargetDepthBuffer = property.FindPropertyRelative("targetDepthBuffer"); - m_ClearFlags = property.FindPropertyRelative("clearFlags"); - m_PassFoldout = property.FindPropertyRelative("passFoldout"); - } - - void LoadUserProperties(SerializedProperty customPass) - { - // Store all fields in CustomPass so we can exclude them when retrieving the user custom pass type - var customPassFields = typeof(CustomPass).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - - foreach (var field in m_PassType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) - { - var serializeField = field.GetCustomAttribute(); - var hideInInspector = field.GetCustomAttribute(); - var nonSerialized = field.GetCustomAttribute(); - - if (customPassFields.Any(f => f.Name == field.Name)) - continue; - - if (nonSerialized != null || hideInInspector != null) - continue; - - if (!field.IsPublic && serializeField == null) - continue; - - var prop = customPass.FindPropertyRelative(field.Name); - if (prop != null) - m_CustomPassUserProperties.Add(prop); - } - - - } - - void InitInternal(SerializedProperty customPass) - { - FetchProperties(customPass); - Initialize(customPass); - LoadUserProperties(customPass); - firstTime = false; - } - - /// - /// Use this function to initialize the local SerializedProperty you will use in your pass. - /// - /// Your custom pass instance represented as a SerializedProperty - protected virtual void Initialize(SerializedProperty customPass) {} - - internal void SetPass(CustomPass pass) => m_CustomPass = pass; - - internal void OnGUI(Rect rect, SerializedProperty property, GUIContent label) - { - rect.height = EditorGUIUtility.singleLineHeight; - EditorGUI.BeginChangeCheck(); - - if (firstTime) - InitInternal(property); - - DoHeaderGUI(ref rect); - - if (m_PassFoldout.boolValue) - { - EditorGUI.EndChangeCheck(); - return; - } - - EditorGUI.BeginDisabledGroup(!m_Enabled.boolValue); - { - DoCommonSettingsGUI(ref rect); - - DoPassGUI(property, rect); - } - EditorGUI.EndDisabledGroup(); - - if (EditorGUI.EndChangeCheck()) - property.serializedObject.ApplyModifiedProperties(); - } - - void DoCommonSettingsGUI(ref Rect rect) - { - if ((commonPassUIFlags & PassUIFlag.Name) != 0) - { - EditorGUI.BeginChangeCheck(); - EditorGUI.PropertyField(rect, m_Name); - if (EditorGUI.EndChangeCheck()) - m_CustomPass.name = m_Name.stringValue; - rect.y += Styles.defaultLineSpace; - } - - if ((commonPassUIFlags & PassUIFlag.TargetColorBuffer) != 0) + public static GUIContent callback = new GUIContent("Event", "Chose the Callback position for this render pass object."); + public static GUIContent enabled = new GUIContent("Enabled", "Enable or Disable the custom pass"); + public static GUIContent targetDepthBuffer = new GUIContent("Target Depth Buffer"); + public static GUIContent targetColorBuffer = new GUIContent("Target Color Buffer"); + public static GUIContent clearFlags = new GUIContent("Clear Flags", "Clear Flags used when the render targets will are bound, before the pass renders."); + } + + /// + /// List of the elements you can show/hide in the default custom pass UI. + /// + [Flags] + public enum PassUIFlag + { + /// Hides all the default UI fields. + None = 0x00, + /// Shows the name field. + Name = 0x01, + /// Shows the target color buffer field. + TargetColorBuffer = 0x02, + /// Shows the target depth buffer field. + TargetDepthBuffer = 0x04, + /// Shows the clear flags field. + ClearFlags = 0x08, + /// Shows all the default UI fields. + All = ~0, + } + + /// + /// Controls which field of the common pass UI is displayed. + /// + protected virtual PassUIFlag commonPassUIFlags => PassUIFlag.All; + + bool firstTime = true; + + // Serialized Properties + SerializedProperty m_Name; + SerializedProperty m_Enabled; + SerializedProperty m_TargetColorBuffer; + SerializedProperty m_TargetDepthBuffer; + SerializedProperty m_ClearFlags; + SerializedProperty m_PassFoldout; + List m_CustomPassUserProperties = new List(); + CustomPass m_CustomPass; + Type m_PassType => m_CustomPass.GetType(); + + void FetchProperties(SerializedProperty property) + { + m_Name = property.FindPropertyRelative("m_Name"); + m_Enabled = property.FindPropertyRelative("enabled"); + m_TargetColorBuffer = property.FindPropertyRelative("targetColorBuffer"); + m_TargetDepthBuffer = property.FindPropertyRelative("targetDepthBuffer"); + m_ClearFlags = property.FindPropertyRelative("clearFlags"); + m_PassFoldout = property.FindPropertyRelative("passFoldout"); + } + + void LoadUserProperties(SerializedProperty customPass) + { + // Store all fields in CustomPass so we can exclude them when retrieving the user custom pass type + var customPassFields = typeof(CustomPass).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + foreach (var field in m_PassType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) + { + var serializeField = field.GetCustomAttribute(); + var hideInInspector = field.GetCustomAttribute(); + var nonSerialized = field.GetCustomAttribute(); + + if (customPassFields.Any(f => f.Name == field.Name)) + continue; + + if (nonSerialized != null || hideInInspector != null) + continue; + + if (!field.IsPublic && serializeField == null) + continue; + + var prop = customPass.FindPropertyRelative(field.Name); + if (prop != null) + m_CustomPassUserProperties.Add(prop); + } + } + + void InitInternal(SerializedProperty customPass) + { + FetchProperties(customPass); + Initialize(customPass); + LoadUserProperties(customPass); + firstTime = false; + } + + /// + /// Use this function to initialize the local SerializedProperty you will use in your pass. + /// + /// Your custom pass instance represented as a SerializedProperty + protected virtual void Initialize(SerializedProperty customPass) {} + + internal void SetPass(CustomPass pass) => m_CustomPass = pass; + + internal void OnGUI(Rect rect, SerializedProperty property, GUIContent label) + { + rect.height = EditorGUIUtility.singleLineHeight; + EditorGUI.BeginChangeCheck(); + + if (firstTime) + InitInternal(property); + + DoHeaderGUI(ref rect); + + if (m_PassFoldout.boolValue) + { + EditorGUI.EndChangeCheck(); + return; + } + + EditorGUI.BeginDisabledGroup(!m_Enabled.boolValue); + { + DoCommonSettingsGUI(ref rect); + + DoPassGUI(property, rect); + } + EditorGUI.EndDisabledGroup(); + + if (EditorGUI.EndChangeCheck()) + property.serializedObject.ApplyModifiedProperties(); + } + + void DoCommonSettingsGUI(ref Rect rect) + { + if ((commonPassUIFlags & PassUIFlag.Name) != 0) { - EditorGUI.BeginProperty(rect, Styles.targetColorBuffer, m_TargetColorBuffer); - // There is still a bug with SerializedReference and PropertyField so we can't use it yet - // EditorGUI.PropertyField(rect, m_TargetColorBuffer, Styles.targetColorBuffer); - m_TargetColorBuffer.intValue = (int)(CustomPass.TargetBuffer)EditorGUI.EnumPopup(rect, Styles.targetColorBuffer, (CustomPass.TargetBuffer)m_TargetColorBuffer.intValue); - EditorGUI.EndProperty(); + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(rect, m_Name); + if (EditorGUI.EndChangeCheck()) + m_CustomPass.name = m_Name.stringValue; + rect.y += Styles.defaultLineSpace; + } + + if ((commonPassUIFlags & PassUIFlag.TargetColorBuffer) != 0) + { + EditorGUI.BeginProperty(rect, Styles.targetColorBuffer, m_TargetColorBuffer); + // There is still a bug with SerializedReference and PropertyField so we can't use it yet + // EditorGUI.PropertyField(rect, m_TargetColorBuffer, Styles.targetColorBuffer); + m_TargetColorBuffer.intValue = (int)(CustomPass.TargetBuffer)EditorGUI.EnumPopup(rect, Styles.targetColorBuffer, (CustomPass.TargetBuffer)m_TargetColorBuffer.intValue); + EditorGUI.EndProperty(); rect.y += Styles.defaultLineSpace; } if ((commonPassUIFlags & PassUIFlag.TargetDepthBuffer) != 0) { - EditorGUI.BeginProperty(rect, Styles.targetColorBuffer, m_TargetDepthBuffer); - // EditorGUI.PropertyField(rect, m_TargetDepthBuffer, Styles.targetDepthBuffer); - m_TargetDepthBuffer.intValue = (int)(CustomPass.TargetBuffer)EditorGUI.EnumPopup(rect, Styles.targetDepthBuffer, (CustomPass.TargetBuffer)m_TargetDepthBuffer.intValue); - EditorGUI.EndProperty(); + EditorGUI.BeginProperty(rect, Styles.targetColorBuffer, m_TargetDepthBuffer); + // EditorGUI.PropertyField(rect, m_TargetDepthBuffer, Styles.targetDepthBuffer); + m_TargetDepthBuffer.intValue = (int)(CustomPass.TargetBuffer)EditorGUI.EnumPopup(rect, Styles.targetDepthBuffer, (CustomPass.TargetBuffer)m_TargetDepthBuffer.intValue); + EditorGUI.EndProperty(); rect.y += Styles.defaultLineSpace; } if ((commonPassUIFlags & PassUIFlag.ClearFlags) != 0) { - EditorGUI.BeginProperty(rect, Styles.clearFlags, m_ClearFlags); - // EditorGUI.PropertyField(rect, m_ClearFlags, Styles.clearFlags); - m_ClearFlags.intValue = (int)(ClearFlag)EditorGUI.EnumPopup(rect, Styles.clearFlags, (ClearFlag)m_ClearFlags.intValue); - EditorGUI.EndProperty(); + EditorGUI.BeginProperty(rect, Styles.clearFlags, m_ClearFlags); + // EditorGUI.PropertyField(rect, m_ClearFlags, Styles.clearFlags); + m_ClearFlags.intValue = (int)(ClearFlag)EditorGUI.EnumPopup(rect, Styles.clearFlags, (ClearFlag)m_ClearFlags.intValue); + EditorGUI.EndProperty(); rect.y += Styles.defaultLineSpace; - } - } - - /// - /// Implement this function to draw your custom GUI. - /// - /// Your custom pass instance represented as a SerializedProperty - /// space available for you to draw the UI - protected virtual void DoPassGUI(SerializedProperty customPass, Rect rect) - { - foreach (var prop in m_CustomPassUserProperties) - { - EditorGUI.PropertyField(rect, prop, true); - rect.y += EditorGUI.GetPropertyHeight(prop); - } - } - - void DoHeaderGUI(ref Rect rect) - { - var enabledSize = EditorStyles.boldLabel.CalcSize(Styles.enabled) + new Vector2(Styles.reorderableListHandleIndentWidth, 0); - var headerRect = new Rect(rect.x + Styles.reorderableListHandleIndentWidth, - rect.y + EditorGUIUtility.standardVerticalSpacing, - rect.width - Styles.reorderableListHandleIndentWidth - enabledSize.x, - EditorGUIUtility.singleLineHeight); - rect.y += Styles.defaultLineSpace; - var enabledRect = headerRect; - enabledRect.x = rect.xMax - enabledSize.x; - enabledRect.width = enabledSize.x; - - EditorGUI.BeginProperty(headerRect, GUIContent.none, m_PassFoldout); - { - m_PassFoldout.boolValue = EditorGUI.Foldout(headerRect, m_PassFoldout.boolValue, $"{m_Name.stringValue} ({m_PassType.Name})", true, EditorStyles.boldLabel); - } - EditorGUI.EndProperty(); - EditorGUI.BeginProperty(enabledRect, Styles.enabled, m_Enabled); - { - EditorGUIUtility.labelWidth = enabledRect.width - 14; - m_Enabled.boolValue = EditorGUI.Toggle(enabledRect, Styles.enabled, m_Enabled.boolValue); - EditorGUIUtility.labelWidth = 0; - } - EditorGUI.EndProperty(); - } - - /// - /// Implement this functions if you implement DoPassGUI. The result of this function must match the number of lines displayed in your custom GUI. - /// Note that this height can be dynamic. - /// - /// Your custom pass instance represented as a SerializedProperty - /// The height in pixels of tour custom pass GUI - protected virtual float GetPassHeight(SerializedProperty customPass) - { - float height = 0; - - foreach (var prop in m_CustomPassUserProperties) - { - height += EditorGUI.GetPropertyHeight(prop); - height += EditorGUIUtility.standardVerticalSpacing; - } - - return height; - } - - internal float GetPropertyHeight(SerializedProperty property, GUIContent label) - { - float height = Styles.defaultLineSpace; - - if (firstTime) - InitInternal(property); - - if (m_PassFoldout.boolValue) - return height; - - if (!firstTime) - { - int lines = 4; // name + target buffers + clearFlags - - if (commonPassUIFlags != PassUIFlag.All) - { - lines = 0; - for (int i = 0; i < 32; i++) - lines += (((int)commonPassUIFlags & (1 << i)) != 0) ? 1 : 0; - } - - height += Styles.defaultLineSpace * lines; - } - - return height + GetPassHeight(property); - } - - internal GUIContent[] GetMaterialPassNames(Material mat) + } + } + + /// + /// Implement this function to draw your custom GUI. + /// + /// Your custom pass instance represented as a SerializedProperty + /// space available for you to draw the UI + protected virtual void DoPassGUI(SerializedProperty customPass, Rect rect) + { + foreach (var prop in m_CustomPassUserProperties) + { + EditorGUI.PropertyField(rect, prop, true); + rect.y += EditorGUI.GetPropertyHeight(prop); + } + } + + void DoHeaderGUI(ref Rect rect) + { + var enabledSize = EditorStyles.boldLabel.CalcSize(Styles.enabled) + new Vector2(Styles.reorderableListHandleIndentWidth, 0); + var headerRect = new Rect(rect.x + Styles.reorderableListHandleIndentWidth, + rect.y + EditorGUIUtility.standardVerticalSpacing, + rect.width - Styles.reorderableListHandleIndentWidth - enabledSize.x, + EditorGUIUtility.singleLineHeight); + rect.y += Styles.defaultLineSpace; + var enabledRect = headerRect; + enabledRect.x = rect.xMax - enabledSize.x; + enabledRect.width = enabledSize.x; + + EditorGUI.BeginProperty(headerRect, GUIContent.none, m_PassFoldout); + { + m_PassFoldout.boolValue = EditorGUI.Foldout(headerRect, m_PassFoldout.boolValue, $"{m_Name.stringValue} ({m_PassType.Name})", true, EditorStyles.boldLabel); + } + EditorGUI.EndProperty(); + EditorGUI.BeginProperty(enabledRect, Styles.enabled, m_Enabled); + { + EditorGUIUtility.labelWidth = enabledRect.width - 14; + m_Enabled.boolValue = EditorGUI.Toggle(enabledRect, Styles.enabled, m_Enabled.boolValue); + EditorGUIUtility.labelWidth = 0; + } + EditorGUI.EndProperty(); + } + + /// + /// Implement this functions if you implement DoPassGUI. The result of this function must match the number of lines displayed in your custom GUI. + /// Note that this height can be dynamic. + /// + /// Your custom pass instance represented as a SerializedProperty + /// The height in pixels of tour custom pass GUI + protected virtual float GetPassHeight(SerializedProperty customPass) + { + float height = 0; + + foreach (var prop in m_CustomPassUserProperties) + { + height += EditorGUI.GetPropertyHeight(prop); + height += EditorGUIUtility.standardVerticalSpacing; + } + + return height; + } + + internal float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + float height = Styles.defaultLineSpace; + + if (firstTime) + InitInternal(property); + + if (m_PassFoldout.boolValue) + return height; + + if (!firstTime) + { + int lines = 4; // name + target buffers + clearFlags + + if (commonPassUIFlags != PassUIFlag.All) + { + lines = 0; + for (int i = 0; i < 32; i++) + lines += (((int)commonPassUIFlags & (1 << i)) != 0) ? 1 : 0; + } + + height += Styles.defaultLineSpace * lines; + } + + return height + GetPassHeight(property); + } + + internal GUIContent[] GetMaterialPassNames(Material mat) { GUIContent[] passNames = new GUIContent[mat.passCount]; @@ -282,8 +280,8 @@ internal GUIContent[] GetMaterialPassNames(Material mat) string passName = mat.GetPassName(i); passNames[i] = new GUIContent(string.IsNullOrEmpty(passName) ? i.ToString() : passName); } - + return passNames; } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawerAttribute.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawerAttribute.cs index 822fe5a8e9d..b754b72ea1f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawerAttribute.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassDrawerAttribute.cs @@ -2,18 +2,18 @@ namespace UnityEditor.Rendering.HighDefinition { - /// - /// Tells a CustomPassDrawer which CustomPass class is intended for the GUI inside the CustomPassDrawer class - /// - [AttributeUsage(AttributeTargets.Class)] - public class CustomPassDrawerAttribute : Attribute - { - internal Type targetPassType; + /// + /// Tells a CustomPassDrawer which CustomPass class is intended for the GUI inside the CustomPassDrawer class + /// + [AttributeUsage(AttributeTargets.Class)] + public class CustomPassDrawerAttribute : Attribute + { + internal Type targetPassType; - /// - /// Indicates that the class is a Custom Pass drawer and that it replaces the default Custom Pass GUI. - /// - /// The Custom Pass type. - public CustomPassDrawerAttribute(Type targetPassType) => this.targetPassType = targetPassType; - } -} \ No newline at end of file + /// + /// Indicates that the class is a Custom Pass drawer and that it replaces the default Custom Pass GUI. + /// + /// The Custom Pass type. + public CustomPassDrawerAttribute(Type targetPassType) => this.targetPassType = targetPassType; + } +} diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassVolumeEditor.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassVolumeEditor.cs index 3cd01bc08ab..89ea3d37fa7 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassVolumeEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassVolumeEditor.cs @@ -140,7 +140,7 @@ CustomPassDrawer GetCustomPassDrawer(SerializedProperty pass, CustomPass referen void DrawSettingsGUI() { serializedObject.Update(); - + EditorGUI.BeginChangeCheck(); { Rect isGlobalRect = EditorGUILayout.GetControlRect(); @@ -192,7 +192,7 @@ void CreateReorderableList(SerializedProperty passList) m_CustomPassList.drawElementCallback = (rect, index, active, focused) => { EditorGUI.BeginChangeCheck(); - + passList.serializedObject.ApplyModifiedProperties(); var customPass = passList.GetArrayElementAtIndex(index); var drawer = GetCustomPassDrawer(customPass, m_Volume.customPasses[index], index); @@ -231,12 +231,12 @@ void CreateReorderableList(SerializedProperty passList) passList.serializedObject.Update(); // Notify the prefab that something have changed: PrefabUtility.RecordPrefabInstancePropertyModifications(target); - }); + }); } menu.ShowAsContext(); - }; + }; } float GetCustomPassEditorHeight(SerializedProperty pass) => EditorGUIUtility.singleLineHeight; } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/DrawRenderersCustomPassDrawer.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/DrawRenderersCustomPassDrawer.cs index e59432dfb88..1e49ab162e6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/DrawRenderersCustomPassDrawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/DrawRenderersCustomPassDrawer.cs @@ -42,10 +42,10 @@ private class Styles public static GUIContent sortingCriteria = new GUIContent("Sorting", "Sorting settings used to render objects in a certain order."); public static GUIContent shaderPass = new GUIContent("Shader Pass", "Sets which pass will be used to render the materials. If the pass does not exists, the material will not be rendered."); - //Depth Settings - public static GUIContent overrideDepth = new GUIContent("Override Depth", "Override depth state of the objects rendered."); - public static GUIContent depthWrite = new GUIContent("Write Depth", "Chose to write depth to the screen."); - public static GUIContent depthCompareFunction = new GUIContent("Depth Test", "Choose a new test setting for the depth."); + //Depth Settings + public static GUIContent overrideDepth = new GUIContent("Override Depth", "Override depth state of the objects rendered."); + public static GUIContent depthWrite = new GUIContent("Write Depth", "Chose to write depth to the screen."); + public static GUIContent depthCompareFunction = new GUIContent("Depth Test", "Choose a new test setting for the depth."); //Camera Settings public static GUIContent overrideCamera = new GUIContent("Camera", "Override camera projections."); @@ -67,7 +67,7 @@ private class Styles SerializedProperty m_FilterFoldout; SerializedProperty m_RendererFoldout; SerializedProperty m_PassFoldout; - SerializedProperty m_TargetDepthBuffer; + SerializedProperty m_TargetDepthBuffer; // Filter SerializedProperty m_RenderQueue; @@ -97,7 +97,7 @@ protected override void Initialize(SerializedProperty customPass) m_FilterFoldout = customPass.FindPropertyRelative("filterFoldout"); m_RendererFoldout = customPass.FindPropertyRelative("rendererFoldout"); m_PassFoldout = customPass.FindPropertyRelative("passFoldout"); - m_TargetDepthBuffer = customPass.FindPropertyRelative("targetDepthBuffer"); + m_TargetDepthBuffer = customPass.FindPropertyRelative("targetDepthBuffer"); // Filter props m_RenderQueue = customPass.FindPropertyRelative("renderQueueType"); @@ -120,7 +120,7 @@ protected override void Initialize(SerializedProperty customPass) m_ShaderPassesList = new ReorderableList(null, m_ShaderPasses, true, true, true, true); m_ShaderPassesList.drawElementCallback = - (Rect rect, int index, bool isActive, bool isFocused) => + (Rect rect, int index, bool isActive, bool isFocused) => { var element = m_ShaderPassesList.serializedProperty.GetArrayElementAtIndex(index); var propRect = new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight); @@ -194,7 +194,7 @@ bool ShowMsaaObjectInfo() { if (HDRenderPipeline.currentAsset == null || !HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.supportMSAA) return false; - + if (m_Volume.injectionPoint != CustomPassInjectionPoint.AfterPostProcess && m_Volume.injectionPoint != CustomPassInjectionPoint.BeforePostProcess) return false; @@ -209,7 +209,7 @@ void DoFilters(ref Rect rect) { EditorGUI.indentLevel++; EditorGUI.BeginProperty(rect, Styles.renderQueueFilter, m_RenderQueue); - // There is still a bug with SerializedReference and PropertyField so we can't use it yet + // There is still a bug with SerializedReference and PropertyField so we can't use it yet // EditorGUI.PropertyField(rect, m_RenderQueue, Styles.renderQueueFilter); m_RenderQueue.intValue = (int)(CustomPass.RenderQueueType)EditorGUI.EnumPopup(rect, Styles.renderQueueFilter, (CustomPass.RenderQueueType)m_RenderQueue.intValue); EditorGUI.EndProperty(); @@ -260,7 +260,7 @@ void DoMaterialOverride(ref Rect rect) else { EditorGUI.BeginProperty(rect, Styles.renderQueueFilter, m_RenderQueue); - // There is still a bug with SerializedReference and PropertyField so we can't use it yet + // There is still a bug with SerializedReference and PropertyField so we can't use it yet // EditorGUI.PropertyField(rect, m_ShaderPass, Styles.shaderPass); m_ShaderPass.intValue = (int)(DrawRenderersCustomPass.ShaderPass)EditorGUI.EnumPopup(rect, Styles.shaderPass, (DrawRenderersCustomPass.ShaderPass)m_ShaderPass.intValue); EditorGUI.EndProperty(); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs index 4b22384b7d0..eec8cb355e2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs @@ -9,81 +9,81 @@ namespace UnityEditor.Rendering.HighDefinition { - /// - /// FullScreen custom pass drawer - /// - [CustomPassDrawerAttribute(typeof(FullScreenCustomPass))] + /// + /// FullScreen custom pass drawer + /// + [CustomPassDrawerAttribute(typeof(FullScreenCustomPass))] class FullScreenCustomPassDrawer : CustomPassDrawer { - private class Styles - { - public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; + private class Styles + { + public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; public static float helpBoxHeight = EditorGUIUtility.singleLineHeight * 2; public static GUIContent fullScreenPassMaterial = new GUIContent("FullScreen Material", "FullScreen Material used for the full screen DrawProcedural."); public static GUIContent materialPassName = new GUIContent("Pass Name", "The shader pass to use for your fullscreen pass."); - public static GUIContent fetchColorBuffer = new GUIContent("Fetch Color Buffer", "Tick this if your effect sample/fetch the camera color buffer"); + public static GUIContent fetchColorBuffer = new GUIContent("Fetch Color Buffer", "Tick this if your effect sample/fetch the camera color buffer"); - public readonly static string writeAndFetchColorBufferWarning = "Fetching and Writing to the camera color buffer at the same time is not supported on most platforms."; - } + public readonly static string writeAndFetchColorBufferWarning = "Fetching and Writing to the camera color buffer at the same time is not supported on most platforms."; + } - // Fullscreen pass - SerializedProperty m_FullScreenPassMaterial; + // Fullscreen pass + SerializedProperty m_FullScreenPassMaterial; SerializedProperty m_MaterialPassName; - SerializedProperty m_FetchColorBuffer; - SerializedProperty m_TargetColorBuffer; + SerializedProperty m_FetchColorBuffer; + SerializedProperty m_TargetColorBuffer; - CustomPass.TargetBuffer targetColorBuffer => (CustomPass.TargetBuffer)m_TargetColorBuffer.intValue; + CustomPass.TargetBuffer targetColorBuffer => (CustomPass.TargetBuffer)m_TargetColorBuffer.intValue; - protected override void Initialize(SerializedProperty customPass) - { - m_FullScreenPassMaterial = customPass.FindPropertyRelative("fullscreenPassMaterial"); + protected override void Initialize(SerializedProperty customPass) + { + m_FullScreenPassMaterial = customPass.FindPropertyRelative("fullscreenPassMaterial"); m_MaterialPassName = customPass.FindPropertyRelative("materialPassName"); - m_FetchColorBuffer = customPass.FindPropertyRelative("fetchColorBuffer"); - m_TargetColorBuffer = customPass.FindPropertyRelative("targetColorBuffer"); - } + m_FetchColorBuffer = customPass.FindPropertyRelative("fetchColorBuffer"); + m_TargetColorBuffer = customPass.FindPropertyRelative("targetColorBuffer"); + } - protected override void DoPassGUI(SerializedProperty customPass, Rect rect) + protected override void DoPassGUI(SerializedProperty customPass, Rect rect) { - EditorGUI.PropertyField(rect, m_FetchColorBuffer, Styles.fetchColorBuffer); - rect.y += Styles.defaultLineSpace; + EditorGUI.PropertyField(rect, m_FetchColorBuffer, Styles.fetchColorBuffer); + rect.y += Styles.defaultLineSpace; - if (m_FetchColorBuffer.boolValue && targetColorBuffer == CustomPass.TargetBuffer.Camera) - { - // We add a warning to prevent fetching and writing to the same render target - Rect helpBoxRect = rect; - helpBoxRect.height = Styles.helpBoxHeight; - EditorGUI.HelpBox(helpBoxRect, Styles.writeAndFetchColorBufferWarning, MessageType.Warning); - rect.y += Styles.helpBoxHeight; - } + if (m_FetchColorBuffer.boolValue && targetColorBuffer == CustomPass.TargetBuffer.Camera) + { + // We add a warning to prevent fetching and writing to the same render target + Rect helpBoxRect = rect; + helpBoxRect.height = Styles.helpBoxHeight; + EditorGUI.HelpBox(helpBoxRect, Styles.writeAndFetchColorBufferWarning, MessageType.Warning); + rect.y += Styles.helpBoxHeight; + } - EditorGUI.PropertyField(rect, m_FullScreenPassMaterial, Styles.fullScreenPassMaterial); - rect.y += Styles.defaultLineSpace; - if (m_FullScreenPassMaterial.objectReferenceValue is Material mat) - { - using (new EditorGUI.IndentLevelScope()) - { - EditorGUI.BeginProperty(rect, Styles.materialPassName, m_MaterialPassName); - { - EditorGUI.BeginChangeCheck(); - int index = mat.FindPass(m_MaterialPassName.stringValue); - index = EditorGUI.IntPopup(rect, Styles.materialPassName, index, GetMaterialPassNames(mat), Enumerable.Range(0, mat.passCount).ToArray()); - if (EditorGUI.EndChangeCheck()) - m_MaterialPassName.stringValue = mat.GetPassName(index); - } - EditorGUI.EndProperty(); - } - } + EditorGUI.PropertyField(rect, m_FullScreenPassMaterial, Styles.fullScreenPassMaterial); + rect.y += Styles.defaultLineSpace; + if (m_FullScreenPassMaterial.objectReferenceValue is Material mat) + { + using (new EditorGUI.IndentLevelScope()) + { + EditorGUI.BeginProperty(rect, Styles.materialPassName, m_MaterialPassName); + { + EditorGUI.BeginChangeCheck(); + int index = mat.FindPass(m_MaterialPassName.stringValue); + index = EditorGUI.IntPopup(rect, Styles.materialPassName, index, GetMaterialPassNames(mat), Enumerable.Range(0, mat.passCount).ToArray()); + if (EditorGUI.EndChangeCheck()) + m_MaterialPassName.stringValue = mat.GetPassName(index); + } + EditorGUI.EndProperty(); + } + } } - protected override float GetPassHeight(SerializedProperty customPass) - { - int lineCount = (m_FullScreenPassMaterial.objectReferenceValue is Material ? 3 : 2); - int height = (int)(Styles.defaultLineSpace * lineCount); + protected override float GetPassHeight(SerializedProperty customPass) + { + int lineCount = (m_FullScreenPassMaterial.objectReferenceValue is Material ? 3 : 2); + int height = (int)(Styles.defaultLineSpace * lineCount); - height += (m_FetchColorBuffer.boolValue && targetColorBuffer == CustomPass.TargetBuffer.Camera) ? (int)Styles.helpBoxHeight : 0; + height += (m_FetchColorBuffer.boolValue && targetColorBuffer == CustomPass.TargetBuffer.Camera) ? (int)Styles.helpBoxHeight : 0; - return height; - } + return height; + } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDEditorUtils.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDEditorUtils.cs index 759485b4de1..15d312b3cd4 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDEditorUtils.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDEditorUtils.cs @@ -26,9 +26,9 @@ class HDEditorUtils private static (StyleSheet baseSkin, StyleSheet professionalSkin, StyleSheet personalSkin) LoadStyleSheets(string basePath) => ( - AssetDatabase.LoadAssetAtPath($"{basePath}.uss"), - AssetDatabase.LoadAssetAtPath($"{basePath}Light.uss"), - AssetDatabase.LoadAssetAtPath($"{basePath}Dark.uss") + AssetDatabase.LoadAssetAtPath($"{basePath}.uss"), + AssetDatabase.LoadAssetAtPath($"{basePath}Light.uss"), + AssetDatabase.LoadAssetAtPath($"{basePath}Dark.uss") ); internal static void AddStyleSheets(VisualElement element, string baseSkinPath) @@ -47,11 +47,9 @@ internal static void AddStyleSheets(VisualElement element, string baseSkinPath) } } - static readonly Action k_DefaultDrawer = (p, l) => EditorGUILayout.PropertyField(p, l); - internal static T LoadAsset(string relativePath) where T : UnityEngine.Object => AssetDatabase.LoadAssetAtPath(HDUtils.GetHDRenderPipelinePath() + relativePath); @@ -95,7 +93,7 @@ internal static bool IsAssetPath(string path) { var isPathRooted = Path.IsPathRooted(path); return isPathRooted && path.StartsWith(Application.dataPath) - || !isPathRooted && path.StartsWith("Assets"); + || !isPathRooted && path.StartsWith("Assets"); } // Copy texture from cache @@ -231,7 +229,7 @@ internal static void DrawLightLayerMask_Internal(Rect rect, GUIContent label, Se internal static void DrawDecalLayerMask_Internal(Rect rect, GUIContent label, SerializedProperty property) { if (HDRenderPipeline.defaultAsset == null) - return ; + return; EditorGUI.BeginProperty(rect, label, property); @@ -243,7 +241,6 @@ internal static void DrawDecalLayerMask_Internal(Rect rect, GUIContent label, Se EditorGUI.EndProperty(); } - /// /// Should be placed between BeginProperty / EndProperty /// @@ -332,7 +329,7 @@ public static IEnumerable EnumerateDisplayName(this SerializedProperty p public static bool IsTargetAlive(this SerializedProperty property) => property != null && property.serializedObject.targetObject != null && - !property.serializedObject.targetObject.Equals(null); + !property.serializedObject.targetObject.Equals(null); /// /// Helper to get an enum value from a SerializedProperty. @@ -383,7 +380,7 @@ public static string GetEnumName(this SerializedProperty property) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetEnumValue(this SerializedProperty property, T value) where T : Enum - // intValue actually is the value underlying beside the enum + // intValue actually is the value underlying beside the enum => SetEnumValue_Internal(property, value); /// @@ -547,13 +544,13 @@ public static void SetInline(this SerializedProperty serializedProperty, T va [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T GetEnumValue_Internal(SerializedProperty property) - // intValue actually is the value underlying beside the enum + // intValue actually is the value underlying beside the enum => (T)(object)property.intValue; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SetEnumValue_Internal(SerializedProperty property, T value) - // intValue actually is the value underlying beside the enum + // intValue actually is the value underlying beside the enum => property.intValue = (int)(object)value; } } diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs index c15f087eae6..de72f564a66 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs @@ -308,7 +308,7 @@ static void ResetAllMaterialKeywordsInProjectAndScenes() try { - var scenes = AssetDatabase.FindAssets("t:Scene", new string[]{ "Assets" }); + var scenes = AssetDatabase.FindAssets("t:Scene", new string[] { "Assets" }); var scale = 1f / Mathf.Max(1, scenes.Length); for (var i = 0; i < scenes.Length; ++i) { @@ -343,7 +343,7 @@ static void ResetAllMaterialKeywordsInProjectAndScenes() static void ResetAllMaterialAssetsKeywords(float progressScale, float progressOffset) { - var matIds = AssetDatabase.FindAssets("t:Material", new string[]{ "Assets" }); // do not include packages + var matIds = AssetDatabase.FindAssets("t:Material", new string[] { "Assets" }); // do not include packages bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive); @@ -440,7 +440,7 @@ static void CheckSceneContentForRayTracing(MenuCommand menuCommand) currentRenderer.GetSharedMaterials(materialArray); if (materialArray == null) { - Debug.LogWarning("The object "+ currentRenderer.name + " has a null material array."); + Debug.LogWarning("The object " + currentRenderer.name + " has a null material array."); generalErrorFlag = true; continue; } @@ -494,7 +494,7 @@ static void CheckSceneContentForRayTracing(MenuCommand menuCommand) { bool materialIsTransparent = currentMaterial.IsKeywordEnabled("_SURFACE_TYPE_TRANSPARENT") || (HDRenderQueue.k_RenderQueue_Transparent.lowerBound <= currentMaterial.renderQueue - && HDRenderQueue.k_RenderQueue_Transparent.upperBound >= currentMaterial.renderQueue); + && HDRenderQueue.k_RenderQueue_Transparent.upperBound >= currentMaterial.renderQueue); // aggregate the transparency info materialIsOnlyTransparent &= materialIsTransparent; diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs index 15442d62a35..aa269b77616 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs @@ -224,7 +224,7 @@ public class GeneralSection public static readonly GUIContent lutSize = EditorGUIUtility.TrTextContent("Grading LUT Size", "Sets size of the internal and external color grading lookup textures (LUTs)."); public static readonly GUIContent lutFormat = EditorGUIUtility.TrTextContent("Grading LUT Format", "Specifies the encoding format for color grading lookup textures. Lower precision formats are faster and use less memory at the expense of color precision."); - public static readonly GUIContent bufferFormat = EditorGUIUtility.TrTextContent("Buffer Format", "Specifies the encoding format of the color buffers that are used during post processing. Lower precision formats are faster and use less memory at the expense of color precision."); + public static readonly GUIContent bufferFormat = EditorGUIUtility.TrTextContent("Buffer Format", "Specifies the encoding format of the color buffers that are used during post processing. Lower precision formats are faster and use less memory at the expense of color precision."); public static readonly GUIContent[] shadowBitDepthNames = { new GUIContent("32 bit"), new GUIContent("16 bit") }; public static readonly int[] shadowBitDepthValues = { (int)DepthBits.Depth32, (int)DepthBits.Depth16 }; diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs index 716207621a4..99fc77eb05b 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs @@ -127,24 +127,24 @@ static HDRenderPipelineUI() CED.Select( (serialized, owner) => serialized.defaultFrameSettings, FrameSettingsUI.InspectorInnerbox(withOverride: false) - ) + ) ), CED.Conditional( (serialized, owner) => k_ExpandedState[Expandable.BakedOrCustomProbeFrameSettings], CED.Select( (serialized, owner) => serialized.defaultBakedOrCustomReflectionFrameSettings, FrameSettingsUI.InspectorInnerbox(withOverride: false) - ) + ) ), CED.Conditional( (serialized, owner) => k_ExpandedState[Expandable.RealtimeProbeFrameSettings], CED.Select( (serialized, owner) => serialized.defaultRealtimeReflectionFrameSettings, FrameSettingsUI.InspectorInnerbox(withOverride: false) - ) + ) ), CED.Group((serialized, owner) => EditorGUILayout.EndVertical()) - ); + ); static public void ApplyChangedDisplayedFrameSettings(SerializedHDRenderPipelineAsset serialized, Editor owner) { @@ -299,7 +299,7 @@ static void Drawer_SectionReflection(SerializedHDRenderPipelineAsset serialized, // We need to clamp the values to the resolution int atlasResolution = serialized.renderPipelineSettings.lightLoopSettings.planarReflectionAtlasSize.intValue; int numLevels = serialized.renderPipelineSettings.planarReflectionResolution.values.arraySize; - for(int levelIdx = 0; levelIdx < numLevels; ++levelIdx) + for (int levelIdx = 0; levelIdx < numLevels; ++levelIdx) { SerializedProperty levelValue = serialized.renderPipelineSettings.planarReflectionResolution.values.GetArrayElementAtIndex(levelIdx); levelValue.intValue = Mathf.Min(levelValue.intValue, atlasResolution); @@ -314,13 +314,13 @@ static void Drawer_SectionReflection(SerializedHDRenderPipelineAsset serialized, } EditorGUILayout.PropertyField(serialized.renderPipelineSettings.lightLoopSettings.maxPlanarReflectionOnScreen, Styles.maxPlanarReflectionOnScreen); } - + EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen, Styles.maxEnvContent); if (EditorGUI.EndChangeCheck()) - serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen.intValue, 1, HDRenderPipeline.k_MaxEnvLightsOnScreen); + serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen.intValue = Mathf.Clamp(serialized.renderPipelineSettings.lightLoopSettings.maxEnvLightsOnScreen.intValue, 1, HDRenderPipeline.k_MaxEnvLightsOnScreen); } static void Drawer_SectionSky(SerializedHDRenderPipelineAsset serialized, Editor owner) @@ -362,7 +362,7 @@ static void Drawer_SectionShadows(SerializedHDRenderPipelineAsset serialized, Ed ++EditorGUI.indentLevel; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(serialized.renderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots, Styles.maxScreenSpaceShadowSlots); - serialized.renderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots.intValue = Mathf.Max(serialized.renderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots.intValue, 4); + serialized.renderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots.intValue = Mathf.Max(serialized.renderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots.intValue, 4); EditorGUILayout.PropertyField(serialized.renderPipelineSettings.hdShadowInitParams.screenSpaceShadowBufferFormat, Styles.screenSpaceShadowFormat); --EditorGUI.indentLevel; } @@ -373,7 +373,7 @@ static void Drawer_SectionShadows(SerializedHDRenderPipelineAsset serialized, Ed if (m_ShowDirectionalLightSection) { ++EditorGUI.indentLevel; - EditorGUILayout.IntPopup(serialized.renderPipelineSettings.hdShadowInitParams.directionalShadowMapDepthBits, Styles.shadowBitDepthNames, Styles.shadowBitDepthValues, Styles.directionalShadowPrecisionContent); + EditorGUILayout.IntPopup(serialized.renderPipelineSettings.hdShadowInitParams.directionalShadowMapDepthBits, Styles.shadowBitDepthNames, Styles.shadowBitDepthValues, Styles.directionalShadowPrecisionContent); serialized.renderPipelineSettings.hdShadowInitParams.shadowResolutionDirectional.ValueGUI(Styles.directionalLightsShadowTiers); EditorGUILayout.DelayedIntField(serialized.renderPipelineSettings.hdShadowInitParams.maxDirectionalShadowMapResolution, Styles.maxShadowResolution); --EditorGUI.indentLevel; @@ -401,7 +401,7 @@ static void Drawer_SectionShadows(SerializedHDRenderPipelineAsset serialized, Ed --EditorGUI.indentLevel; ++EditorGUI.indentLevel; - // Because we don't know if the asset is old and had the cached shadow map resolution field, if it was set as default float (0) we force a default. + // Because we don't know if the asset is old and had the cached shadow map resolution field, if it was set as default float (0) we force a default. if (serialized.renderPipelineSettings.hdShadowInitParams.cachedPunctualShadowAtlasResolution.intValue == 0) { serialized.renderPipelineSettings.hdShadowInitParams.cachedPunctualShadowAtlasResolution.intValue = 2048; @@ -438,7 +438,6 @@ static void Drawer_SectionShadows(SerializedHDRenderPipelineAsset serialized, Ed } CoreEditorUtils.DrawEnumPopup(serialized.renderPipelineSettings.hdShadowInitParams.cachedAreaShadowAtlasResolution, typeof(ShadowResolutionValue), Styles.cachedShadowAtlasResolution); --EditorGUI.indentLevel; - } } @@ -582,7 +581,7 @@ static void Drawer_SectionPostProcessSettings(SerializedHDRenderPipelineAsset se serialized.renderPipelineSettings.postProcessSettings.lutSize.intValue = Mathf.Clamp(serialized.renderPipelineSettings.postProcessSettings.lutSize.intValue, GlobalPostProcessSettings.k_MinLutSize, GlobalPostProcessSettings.k_MaxLutSize); EditorGUILayout.PropertyField(serialized.renderPipelineSettings.postProcessSettings.lutFormat, Styles.lutFormat); - EditorGUILayout.PropertyField(serialized.renderPipelineSettings.postProcessSettings.bufferFormat, Styles.bufferFormat); + EditorGUILayout.PropertyField(serialized.renderPipelineSettings.postProcessSettings.bufferFormat, Styles.bufferFormat); } static void Drawer_SectionXRSettings(SerializedHDRenderPipelineAsset serialized, Editor owner) @@ -908,7 +907,6 @@ static void Drawer_SectionFogQualitySettings(SerializedHDRenderPipelineAsset ser } } - static void Drawer_SectionRenderingUnsorted(SerializedHDRenderPipelineAsset serialized, Editor owner) { EditorGUILayout.PropertyField(serialized.renderPipelineSettings.colorBufferFormat, Styles.colorBufferFormatContent); @@ -1057,7 +1055,7 @@ static void Drawer_SectionLightingUnsorted(SerializedHDRenderPipelineAsset seria static void Drawer_SectionMaterialUnsorted(SerializedHDRenderPipelineAsset serialized, Editor owner) { EditorGUILayout.PropertyField(serialized.availableMaterialQualityLevels); - var v = EditorGUILayout.EnumPopup(Styles.materialQualityLevelContent, (MaterialQuality) serialized.defaultMaterialQualityLevel.intValue); + var v = EditorGUILayout.EnumPopup(Styles.materialQualityLevelContent, (MaterialQuality)serialized.defaultMaterialQualityLevel.intValue); serialized.defaultMaterialQualityLevel.intValue = (int)(object)v; EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportDistortion, Styles.supportDistortion); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs index 0512cc5718a..0f20f468491 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDShaderUtils.cs @@ -87,9 +87,12 @@ public static bool ResetMaterialKeywords(Material material) MaterialResetter resetter; // If we send a non HDRP material we don't throw an exception, the return type already handles errors. - try { + try + { k_MaterialResetters.TryGetValue(GetShaderEnumFromShader(material.shader), out resetter); - } catch { + } + catch + { return false; } @@ -110,11 +113,11 @@ public static bool ResetMaterialKeywords(Material material) /// The list of shader preprocessor internal static List GetBaseShaderPreprocessorList() => UnityEngine.Rendering.CoreUtils - .GetAllTypesDerivedFrom() - .Select(Activator.CreateInstance) - .Cast() - .OrderByDescending(spp => spp.Priority) - .ToList(); + .GetAllTypesDerivedFrom() + .Select(Activator.CreateInstance) + .Cast() + .OrderByDescending(spp => spp.Priority) + .ToList(); internal static bool IsHDRPShader(Shader shader, bool upgradable = false) { @@ -142,9 +145,9 @@ internal static bool IsUnlitHDRPShader(Shader shader) // Throw exception if no metadata is found // This case should be handled by the Target HDMetadata obj; - if(!shader.TryGetMetadataOfType(out obj)) + if (!shader.TryGetMetadataOfType(out obj)) throw new ArgumentException("Unknown shader"); - + return obj.shaderID == ShaderID.SG_Unlit; } else @@ -170,9 +173,9 @@ internal static ShaderID GetShaderEnumFromShader(Shader shader) // Throw exception if no metadata is found // This case should be handled by the Target HDMetadata obj; - if(!shader.TryGetMetadataOfType(out obj)) + if (!shader.TryGetMetadataOfType(out obj)) throw new ArgumentException("Unknown shader"); - + return obj.shaderID; } else diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Raytracing/GlobalIlluminationEditor.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Raytracing/GlobalIlluminationEditor.cs index c013e290935..508f7547350 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Raytracing/GlobalIlluminationEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Raytracing/GlobalIlluminationEditor.cs @@ -92,7 +92,6 @@ public void DenoiserGUI() public override void OnInspectorGUI() { - HDRenderPipelineAsset currentAsset = HDRenderPipeline.currentAsset; if (!currentAsset?.currentPlatformRenderPipelineSettings.supportSSGI ?? false) { @@ -143,7 +142,7 @@ public override void OnInspectorGUI() DenoiserGUI(); } } - break; + break; case RayTracingMode.Quality: { PropertyField(m_RayLength, k_RayLengthText); @@ -152,7 +151,7 @@ public override void OnInspectorGUI() PropertyField(m_BounceCount); DenoiserGUI(); } - break; + break; } } } @@ -180,7 +179,6 @@ public override void OnInspectorGUI() EditorGUI.indentLevel--; } - } } @@ -192,7 +190,7 @@ public override void OnInspectorGUI() using (new HDEditorUtils.IndentScope()) using (new QualityScope(this)) { - PropertyField(m_FullResolutionSS,EditorGUIUtility.TrTextContent("Full Resolution", "Enables full resolution mode.")); + PropertyField(m_FullResolutionSS, EditorGUIUtility.TrTextContent("Full Resolution", "Enables full resolution mode.")); PropertyField(m_RaySteps); PropertyField(m_FilterRadius); } @@ -201,6 +199,7 @@ public override void OnInspectorGUI() } } } + public override QualitySettingsBlob SaveCustomQualitySettingsAsObject(QualitySettingsBlob settings = null) { if (settings == null) diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/ScalableSettingLevelParameterEditor.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/ScalableSettingLevelParameterEditor.cs index de006eccc07..40babae8afa 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/ScalableSettingLevelParameterEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/ScalableSettingLevelParameterEditor.cs @@ -14,7 +14,7 @@ public override bool OnGUI(SerializedDataParameter parameter, GUIContent title) return false; var o = parameter.GetObjectRef(); - var (level, useOverride) = o.levelAndOverride; + var(level, useOverride) = o.levelAndOverride; var rect = GUILayoutUtility.GetRect(0, float.Epsilon, 0, EditorGUIUtility.singleLineHeight); // Magic number for padding diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DefaultSettingsPanel.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DefaultSettingsPanel.cs index e4f61b7ebd6..532e4816082 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DefaultSettingsPanel.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DefaultSettingsPanel.cs @@ -117,7 +117,7 @@ public void OnActivate(string searchContext, VisualElement rootElement) var serializedObject = new SerializedObject(HDRenderPipeline.defaultAsset); m_SerializeHDRPAsset = new SerializedHDRenderPipelineAsset(serializedObject); - + var editorResources = HDRenderPipeline.defaultAsset.renderPipelineEditorResources; if (!EditorUtility.IsPersistent(editorResources)) { diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DiffusionProfileSettingsListUI.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DiffusionProfileSettingsListUI.cs index 32db22b8b14..ebaf17cf3b1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DiffusionProfileSettingsListUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/DiffusionProfileSettingsListUI.cs @@ -61,7 +61,7 @@ void CreateReorderableList(SerializedProperty parameter) if (parameter.arraySize >= DiffusionProfileConstants.DIFFUSION_PROFILE_COUNT - 1) { Debug.LogError("Limit of 15 diffusion profiles reached."); - return ; + return; } parameter.InsertArrayElementAtIndex(parameter.arraySize); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/FrameSettingsUI.Drawers.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/FrameSettingsUI.Drawers.cs index be84ce61ab9..f769a62783c 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/FrameSettingsUI.Drawers.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/FrameSettingsUI.Drawers.cs @@ -32,7 +32,7 @@ public static MaterialQuality Into(this MaterialQualityMode quality) public static MaterialQualityMode Into(this MaterialQuality quality) { - if (quality == (MaterialQuality) 0) + if (quality == (MaterialQuality)0) return MaterialQualityMode.FromQualitySettings; switch (quality) { @@ -64,58 +64,58 @@ enum Expandable static Rect lastBoxRect; internal static CED.IDrawer Inspector(bool withOverride = true) => CED.Group( - CED.Group((serialized, owner) => - { - lastBoxRect = EditorGUILayout.BeginVertical("box"); + CED.Group((serialized, owner) => + { + lastBoxRect = EditorGUILayout.BeginVertical("box"); - // Add dedicated scope here and on each FrameSettings field to have the contextual menu on everything - Rect rect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight); - using (new SerializedFrameSettings.TitleDrawingScope(rect, FrameSettingsUI.frameSettingsHeaderContent, serialized)) - { - EditorGUI.LabelField(rect, FrameSettingsUI.frameSettingsHeaderContent, EditorStyles.boldLabel); - } - }), - InspectorInnerbox(withOverride), - CED.Group((serialized, owner) => + // Add dedicated scope here and on each FrameSettings field to have the contextual menu on everything + Rect rect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight); + using (new SerializedFrameSettings.TitleDrawingScope(rect, FrameSettingsUI.frameSettingsHeaderContent, serialized)) { - EditorGUILayout.EndVertical(); - using (new SerializedFrameSettings.TitleDrawingScope(lastBoxRect, FrameSettingsUI.frameSettingsHeaderContent, serialized)) - { - //Nothing to draw. - //We just want to have a big blue bar at left that match the whole framesetting box. - //This is because framesettings will be considered as one bg block from prefab point - //of view as there is no way to separate it bit per bit in serialization and Prefab - //override API rely on SerializedProperty. - } - }) - ); + EditorGUI.LabelField(rect, FrameSettingsUI.frameSettingsHeaderContent, EditorStyles.boldLabel); + } + }), + InspectorInnerbox(withOverride), + CED.Group((serialized, owner) => + { + EditorGUILayout.EndVertical(); + using (new SerializedFrameSettings.TitleDrawingScope(lastBoxRect, FrameSettingsUI.frameSettingsHeaderContent, serialized)) + { + //Nothing to draw. + //We just want to have a big blue bar at left that match the whole framesetting box. + //This is because framesettings will be considered as one bg block from prefab point + //of view as there is no way to separate it bit per bit in serialization and Prefab + //override API rely on SerializedProperty. + } + }) + ); //separated to add enum popup on default frame settings internal static CED.IDrawer InspectorInnerbox(bool withOverride = true) => CED.Group( - CED.FoldoutGroup(renderingSettingsHeaderContent, Expandable.RenderingPasses, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, - CED.Group(206, (serialized, owner) => Drawer_SectionRenderingSettings(serialized, owner, withOverride)) - ), - CED.FoldoutGroup(lightSettingsHeaderContent, Expandable.LightingSettings, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, - CED.Group(206, (serialized, owner) => Drawer_SectionLightingSettings(serialized, owner, withOverride)) - ), - CED.FoldoutGroup(asyncComputeSettingsHeaderContent, Expandable.AsynComputeSettings, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, - CED.Group(206, (serialized, owner) => Drawer_SectionAsyncComputeSettings(serialized, owner, withOverride)) - ), - CED.FoldoutGroup(lightLoopSettingsHeaderContent, Expandable.LightLoop, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, - CED.Group(206, (serialized, owner) => Drawer_SectionLightLoopSettings(serialized, owner, withOverride)) - ), - CED.Group((serialized, owner) => + CED.FoldoutGroup(renderingSettingsHeaderContent, Expandable.RenderingPasses, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, + CED.Group(206, (serialized, owner) => Drawer_SectionRenderingSettings(serialized, owner, withOverride)) + ), + CED.FoldoutGroup(lightSettingsHeaderContent, Expandable.LightingSettings, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, + CED.Group(206, (serialized, owner) => Drawer_SectionLightingSettings(serialized, owner, withOverride)) + ), + CED.FoldoutGroup(asyncComputeSettingsHeaderContent, Expandable.AsynComputeSettings, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, + CED.Group(206, (serialized, owner) => Drawer_SectionAsyncComputeSettings(serialized, owner, withOverride)) + ), + CED.FoldoutGroup(lightLoopSettingsHeaderContent, Expandable.LightLoop, k_ExpandedState, FoldoutOption.Indent | FoldoutOption.Boxed, + CED.Group(206, (serialized, owner) => Drawer_SectionLightLoopSettings(serialized, owner, withOverride)) + ), + CED.Group((serialized, owner) => + { + RenderPipelineSettings hdrpSettings = GetHDRPAssetFor(owner).currentPlatformRenderPipelineSettings; + if (hdrpSettings.supportRayTracing) { - RenderPipelineSettings hdrpSettings = GetHDRPAssetFor(owner).currentPlatformRenderPipelineSettings; - if (hdrpSettings.supportRayTracing) - { - bool rtEffectUseAsync = (serialized.IsEnabled(FrameSettingsField.SSRAsync) ?? false) || (serialized.IsEnabled(FrameSettingsField.SSAOAsync) ?? false) + bool rtEffectUseAsync = (serialized.IsEnabled(FrameSettingsField.SSRAsync) ?? false) || (serialized.IsEnabled(FrameSettingsField.SSAOAsync) ?? false) //|| (serialized.IsEnabled(FrameSettingsField.ContactShadowsAsync) ?? false) // Contact shadow async is not visible in the UI for now and defaults to true. - ; - if (rtEffectUseAsync) - EditorGUILayout.HelpBox("Asynchronous execution of Raytracing effects is not supported. Asynchronous Execution will be forced to false for them", MessageType.Warning); - } - })); + ; + if (rtEffectUseAsync) + EditorGUILayout.HelpBox("Asynchronous execution of Raytracing effects is not supported. Asynchronous Execution will be forced to false for them", MessageType.Warning); + } + })); static HDRenderPipelineAsset GetHDRPAssetFor(Editor owner) { @@ -217,7 +217,7 @@ static void Drawer_SectionRenderingSettings(SerializedFrameSettings serialized, } }); - bool clearGBufferEnablable = (hdrpAssetSupportDeferred && (defaultDeferredUsed || frameSettingsOverrideToDeferred)) ||(hdrpAssetIsDeferred); + bool clearGBufferEnablable = (hdrpAssetSupportDeferred && (defaultDeferredUsed || frameSettingsOverrideToDeferred)) || (hdrpAssetIsDeferred); area.AmmendInfo(FrameSettingsField.ClearGBuffers, overrideable: () => clearGBufferEnablable, overridedDefaultValue: clearGBufferEnablable && defaultFrameSettings.IsEnabled(FrameSettingsField.ClearGBuffers), @@ -248,7 +248,7 @@ static void Drawer_SectionRenderingSettings(SerializedFrameSettings serialized, area.AmmendInfo(FrameSettingsField.Distortion, overrideable: () => hdrpSettings.supportDistortion); area.AmmendInfo(FrameSettingsField.Postprocess, overrideable: () => (frameSettingType != FrameSettingsRenderType.CustomOrBakedReflection && - frameSettingType != FrameSettingsRenderType.RealtimeReflection)); + frameSettingType != FrameSettingsRenderType.RealtimeReflection)); area.AmmendInfo( FrameSettingsField.LODBiasMode, @@ -335,7 +335,7 @@ static void Drawer_SectionLightingSettings(SerializedFrameSettings serialized, E customGetter: () => serialized.sssQualityMode.GetEnumValue(), customSetter: v => serialized.sssQualityMode.SetEnumValue((SssQualityMode)v), customOverrideable: () => hdrpSettings.supportSubsurfaceScattering - && (serialized.IsEnabled(FrameSettingsField.SubsurfaceScattering) ?? false), + && (serialized.IsEnabled(FrameSettingsField.SubsurfaceScattering) ?? false), hasMixedValues: serialized.sssQualityMode.hasMultipleDifferentValues ); area.AmmendInfo(FrameSettingsField.SssQualityLevel, @@ -343,8 +343,8 @@ static void Drawer_SectionLightingSettings(SerializedFrameSettings serialized, E customGetter: () => (ScalableLevel3ForFrameSettingsUIOnly)serialized.sssQualityLevel.intValue, // 3 levels customSetter: v => serialized.sssQualityLevel.intValue = Math.Max(0, Math.Min((int)v, 2)), // Levels 0-2 customOverrideable: () => hdrpSettings.supportSubsurfaceScattering - && (serialized.IsEnabled(FrameSettingsField.SubsurfaceScattering) ?? false) - && (serialized.sssQualityMode.GetEnumValue() == SssQualityMode.FromQualitySettings), + && (serialized.IsEnabled(FrameSettingsField.SubsurfaceScattering) ?? false) + && (serialized.sssQualityMode.GetEnumValue() == SssQualityMode.FromQualitySettings), hasMixedValues: serialized.sssQualityLevel.hasMultipleDifferentValues ); area.AmmendInfo(FrameSettingsField.SssCustomSampleBudget, @@ -352,8 +352,8 @@ static void Drawer_SectionLightingSettings(SerializedFrameSettings serialized, E customGetter: () => serialized.sssCustomSampleBudget.intValue, customSetter: v => serialized.sssCustomSampleBudget.intValue = Math.Max(1, Math.Min((int)v, (int)DefaultSssSampleBudgetForQualityLevel.Max)), customOverrideable: () => hdrpSettings.supportSubsurfaceScattering - && (serialized.IsEnabled(FrameSettingsField.SubsurfaceScattering) ?? false) - && (serialized.sssQualityMode.GetEnumValue() != SssQualityMode.FromQualitySettings), + && (serialized.IsEnabled(FrameSettingsField.SubsurfaceScattering) ?? false) + && (serialized.sssQualityMode.GetEnumValue() != SssQualityMode.FromQualitySettings), hasMixedValues: serialized.sssCustomSampleBudget.hasMultipleDifferentValues ); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/OverridableFrameSettingsArea.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/OverridableFrameSettingsArea.cs index 92a6e8d8380..9c6aa06d2a2 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/OverridableFrameSettingsArea.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/OverridableFrameSettingsArea.cs @@ -147,7 +147,7 @@ public void Draw(bool withOverride) throw new ArgumentOutOfRangeException("Cannot be used without using the constructor with a capacity initializer."); if (withOverride & GUI.enabled) OverridesHeaders(); - for (int i = 0; i< fields.Count; ++i) + for (int i = 0; i < fields.Count; ++i) DrawField(fields[i], withOverride); } @@ -192,7 +192,7 @@ void DrawField(Field field, bool withOverride) // MixedValueState is handled by style for small tickbox for strange reason //EditorGUI.showMixedValue = mixedValue; - bool modifiedValue = EditorGUI.Toggle(overrideRect, overrideTooltip, originalValue, mixedValue? CoreEditorStyles.smallMixedTickbox : CoreEditorStyles.smallTickbox); + bool modifiedValue = EditorGUI.Toggle(overrideRect, overrideTooltip, originalValue, mixedValue ? CoreEditorStyles.smallMixedTickbox : CoreEditorStyles.smallTickbox); //EditorGUI.showMixedValue = false; if (originalValue ^ modifiedValue) @@ -202,7 +202,7 @@ void DrawField(Field field, bool withOverride) EditorGUI.indentLevel = currentIndent; } - using(new SerializedFrameSettings.TitleDrawingScope(labelRect, field.label, serializedFrameSettings)) + using (new SerializedFrameSettings.TitleDrawingScope(labelRect, field.label, serializedFrameSettings)) { HDEditorUtils.HandlePrefixLabelWithIndent(lineRect, labelRect, field.label); } @@ -295,7 +295,6 @@ void DrawField(Field field, bool withOverride) default: throw new ArgumentException("Unknown FrameSettingsFieldAttribute"); } - } } EditorGUI.showMixedValue = false; @@ -379,6 +378,6 @@ class FrameSettingsNotFoundInGroupException : Exception { public FrameSettingsNotFoundInGroupException(string message) : base(message) - { } + {} } } diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedFrameSettings.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedFrameSettings.cs index b7f49dcd186..2793aae3d0f 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedFrameSettings.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedFrameSettings.cs @@ -32,8 +32,8 @@ public LitShaderMode? litShaderMode return val == null ? (LitShaderMode?)null : val.Value == true - ? LitShaderMode.Deferred - : LitShaderMode.Forward; + ? LitShaderMode.Deferred + : LitShaderMode.Forward; } set => SetEnabled(FrameSettingsField.LitShaderMode, value == LitShaderMode.Deferred); } diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs index 523453e1259..833e05bcda0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs @@ -3,7 +3,6 @@ namespace UnityEditor.Rendering.HighDefinition { - class SerializedHDRenderPipelineAsset { public SerializedObject serializedObject; diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedLowResTransparencySettings.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedLowResTransparencySettings.cs index 18941e22058..8e56c06d8e6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedLowResTransparencySettings.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedLowResTransparencySettings.cs @@ -1,4 +1,4 @@ -using UnityEditor.Rendering; +using UnityEditor.Rendering; using UnityEngine.Rendering.HighDefinition; namespace UnityEditor.Rendering.HighDefinition diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedPostProcessingQualitySettings.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedPostProcessingQualitySettings.cs index 1800666e722..06d60591e59 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedPostProcessingQualitySettings.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedPostProcessingQualitySettings.cs @@ -46,7 +46,7 @@ public SerializedPostProcessingQualitySettings(SerializedProperty root) // Bloom BloomRes = root.Find((GlobalPostProcessingQualitySettings s) => s.BloomRes); BloomHighFilteringQuality = root.Find((GlobalPostProcessingQualitySettings s) => s.BloomHighQualityFiltering); - BloomHighPrefilteringQuality= root.Find((GlobalPostProcessingQualitySettings s) => s.BloomHighQualityPrefiltering); + BloomHighPrefilteringQuality = root.Find((GlobalPostProcessingQualitySettings s) => s.BloomHighQualityPrefiltering); // Chromatic Aberration ChromaticAbMaxSamples = root.Find((GlobalPostProcessingQualitySettings s) => s.ChromaticAberrationMaxSamples); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSetting.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSetting.cs index 8db7756ffc3..c4f9b7309eb 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSetting.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSetting.cs @@ -31,7 +31,7 @@ public SerializedScalableSetting(SerializedProperty property) /// /// true when the value was evaluated, false when the value could not be evaluated. public bool TryGetLevelValue(int level, out T value) - where T: struct + where T : struct { if (level < values.arraySize && level >= 0) { @@ -135,13 +135,13 @@ ScalableSettingSchema schema /// The labels for each sub value field. /// The current values of the fields. static void MultiField(Rect position, GUIContent[] subLabels, T[] values) - where T: struct + where T : struct { // The number of slots we need to fit into this rectangle var length = values.Length; // Let's compute the space allocated for every field including the label - var num = position.width / (float) length; + var num = position.width / (float)length; // Reset the indentation var indentLevel = EditorGUI.indentLevel; @@ -157,13 +157,13 @@ static void MultiField(Rect position, GUIContent[] subLabels, T[] values) for (var index = 0; index < values.Length; ++index) { // Let's first compute what is the width of the label of this scalable setting level - // We make sure that the label doesn't go beyond the space available for this scalable setting level + // We make sure that the label doesn't go beyond the space available for this scalable setting level EditorGUIUtility.labelWidth = Mathf.Clamp(CalcPrefixLabelWidth(subLabels[index], (GUIStyle)null), 0, num); - - // Define the rectangle for the field + + // Define the rectangle for the field var fieldSlot = new Rect(position.x + pixelShift, position.y, num, position.height); - // Draw the right field depending on its type. + // Draw the right field depending on its type. if (typeof(T) == typeof(int)) values[index] = (T)(object)EditorGUI.DelayedIntField(fieldSlot, subLabels[index], (int)(object)values[index]); else if (typeof(T) == typeof(bool)) @@ -171,7 +171,7 @@ static void MultiField(Rect position, GUIContent[] subLabels, T[] values) else if (typeof(T) == typeof(float)) values[index] = (T)(object)EditorGUI.FloatField(fieldSlot, subLabels[index], (float)(object)values[index]); else if (typeof(T).IsEnum) - values[index] = (T)(object)EditorGUI.EnumPopup(fieldSlot, subLabels[index], (Enum)(object)values[index]); + values[index] = (T)(object)EditorGUI.EnumPopup(fieldSlot, subLabels[index], (Enum)(object)values[index]); else throw new ArgumentOutOfRangeException($"<{typeof(T)}> is not a supported type for multi field"); diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSettingValue.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSettingValue.cs index 6f4fe0bd362..ae321567a87 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSettingValue.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedScalableSettingValue.cs @@ -19,8 +19,8 @@ internal class SerializedScalableSettingValue /// false if it has a single value. /// public bool hasMultipleValues => useOverride.hasMultipleDifferentValues - || useOverride.boolValue && @override.hasMultipleDifferentValues - || !useOverride.boolValue && level.hasMultipleDifferentValues; + || useOverride.boolValue && @override.hasMultipleDifferentValues + || !useOverride.boolValue && level.hasMultipleDifferentValues; public SerializedScalableSettingValue(SerializedProperty property) { @@ -210,7 +210,7 @@ ScalableSettingSchema schema EditorGUI.BeginProperty(levelRect, label, self.useOverride); { EditorGUI.BeginChangeCheck(); - var (level, useOverride) = LevelFieldGUI( + var(level, useOverride) = LevelFieldGUI( levelRect, GUIContent.none, schema, @@ -232,7 +232,7 @@ ScalableSettingSchema schema /// /// Draw the scalable setting as a popup and field GUI in a single line. - /// + /// /// This helper statically dispatch the appropriate GUI call depending /// on the multiselection state of the serialized properties. /// diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VirtualTexturingSettingsUI.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VirtualTexturingSettingsUI.cs index c9e67f8f139..70ba0b28791 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VirtualTexturingSettingsUI.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VirtualTexturingSettingsUI.cs @@ -77,9 +77,9 @@ ReorderableList CreateGPUCacheSizeOverrideList(SerializedProperty property, Reor list.drawHeaderCallback = (Rect rect) => - { - GUI.Label(rect, s_Styles.gpuCacheSize); - }; + { + GUI.Label(rect, s_Styles.gpuCacheSize); + }; list.drawElementCallback = drawCallback; @@ -116,6 +116,7 @@ void GraphicsFormatToFormatAndChannelTransformString(GraphicsFormat graphicsForm format = formatString.Substring(0, lastUnderscore); channelTransform = formatString.Substring(lastUnderscore + 1); } + GraphicsFormat FormatAndChannelTransformStringToGraphicsFormat(string format, string channelTransform) { if (format == "None") return GraphicsFormat.None; @@ -156,7 +157,7 @@ void GPUCacheSizeOverridesGUI(Rect rect, int settingIdx, SerializedProperty sett } #endif - GraphicsFormat serializedFormat = (GraphicsFormat) cacheSizeOverrideProperty.FindPropertyRelative("format").intValue; + GraphicsFormat serializedFormat = (GraphicsFormat)cacheSizeOverrideProperty.FindPropertyRelative("format").intValue; GraphicsFormatToFormatAndChannelTransformString(serializedFormat, out string formatString, out string channelTransformString); @@ -254,10 +255,10 @@ void GPUCacheSizeOverridesGUI(Rect rect, int settingIdx, SerializedProperty sett rect.position += new Vector2(sizeLabelWidth, 0); rect.width = sizeWidth; - cacheSizeOverride.sizeInMegaBytes = (uint) Mathf.Max(GPUCacheSizeMinValue, - EditorGUI.DelayedIntField(rect, (int) cacheSizeOverride.sizeInMegaBytes)); + cacheSizeOverride.sizeInMegaBytes = (uint)Mathf.Max(GPUCacheSizeMinValue, + EditorGUI.DelayedIntField(rect, (int)cacheSizeOverride.sizeInMegaBytes)); cacheSizeOverrideProperty.FindPropertyRelative("sizeInMegaBytes").intValue = - (int) cacheSizeOverride.sizeInMegaBytes; + (int)cacheSizeOverride.sizeInMegaBytes; } void DrawStreamingOverrideElement(Rect rect, int settingIdx, bool active, bool focused) diff --git a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VolumeComponentWithQualityEditor.cs b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VolumeComponentWithQualityEditor.cs index 02c8c12c311..d06c2af1391 100644 --- a/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VolumeComponentWithQualityEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/VolumeComponentWithQualityEditor.cs @@ -24,7 +24,7 @@ private struct QualitySetting Dictionary settings = new Dictionary(); - public static bool IsEqual (QualitySettingsBlob left, QualitySettingsBlob right) + public static bool IsEqual(QualitySettingsBlob left, QualitySettingsBlob right) { if (right == null && left == null) { @@ -191,7 +191,7 @@ public override void OnInspectorGUI() s_CustomSettingsHistory.TryGetValue(serializedObject.targetObject, out history); if (history != null) { - SaveCustomQualitySettingsAsObject(history); + SaveCustomQualitySettingsAsObject(history); } else { @@ -201,7 +201,6 @@ public override void OnInspectorGUI() { s_CustomSettingsHistory.Add(serializedObject.targetObject, history); } - } } LoadSettingsFromQualityPreset(pipeline.currentPlatformRenderPipelineSettings, newQualityLevel); @@ -232,7 +231,7 @@ protected void CopySetting(ref SerializedDataParameter setting, T value) wher /// /// This function should be overriden by a volume component to load preset settings from RenderPipelineSettings /// - public virtual void LoadSettingsFromQualityPreset(RenderPipelineSettings settings, int level) { } + public virtual void LoadSettingsFromQualityPreset(RenderPipelineSettings settings, int level) {} /// /// This function should be overriden by a volume component to return an opaque object (binary blob) with the custom quality settings currently in use. @@ -242,7 +241,6 @@ public virtual void LoadSettingsFromQualityPreset(RenderPipelineSettings setting /// /// This function should be overriden by a volume component to load a custom preset setting from an opaque binary blob (as returned from SaveCustomQualitySettingsAsObject) /// - public virtual void LoadSettingsFromObject(QualitySettingsBlob settings) { } + public virtual void LoadSettingsFromObject(QualitySettingsBlob settings) {} } - } diff --git a/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicDxrScenePipeline.cs b/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicDxrScenePipeline.cs index 4f76a63ad00..822100f53c3 100644 --- a/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicDxrScenePipeline.cs +++ b/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicDxrScenePipeline.cs @@ -7,10 +7,10 @@ namespace UnityEditor.Rendering.HighDefinition class HDRPBasicDxrScenePipeline : ISceneTemplatePipeline { void ISceneTemplatePipeline.AfterTemplateInstantiation(SceneTemplateAsset sceneTemplateAsset, Scene scene, bool isAdditive, string sceneName) - { } + {} void ISceneTemplatePipeline.BeforeTemplateInstantiation(SceneTemplateAsset sceneTemplateAsset, bool isAdditive, string sceneName) - { } + {} bool ISceneTemplatePipeline.IsValidTemplateForInstantiation(SceneTemplateAsset sceneTemplateAsset) { diff --git a/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicScenePipeline.cs b/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicScenePipeline.cs index 7ff45f0bb5e..f535dc31ef8 100644 --- a/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicScenePipeline.cs +++ b/com.unity.render-pipelines.high-definition/Editor/SceneTemplates/HDRPBasicScenePipeline.cs @@ -7,10 +7,10 @@ namespace UnityEditor.Rendering.HighDefinition class HDRPBasicScenePipeline : ISceneTemplatePipeline { void ISceneTemplatePipeline.AfterTemplateInstantiation(SceneTemplateAsset sceneTemplateAsset, Scene scene, bool isAdditive, string sceneName) - { } + {} void ISceneTemplatePipeline.BeforeTemplateInstantiation(SceneTemplateAsset sceneTemplateAsset, bool isAdditive, string sceneName) - { } + {} bool ISceneTemplatePipeline.IsValidTemplateForInstantiation(SceneTemplateAsset sceneTemplateAsset) { diff --git a/com.unity.render-pipelines.high-definition/Editor/Sky/AtmosphericScattering/FogEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Sky/AtmosphericScattering/FogEditor.cs index 1d616f9e574..ad385a022d0 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Sky/AtmosphericScattering/FogEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Sky/AtmosphericScattering/FogEditor.cs @@ -100,7 +100,7 @@ public override void OnInspectorGUI() using (new HDEditorUtils.IndentScope()) { if (!m_ColorMode.value.hasMultipleDifferentValues && - (FogColorMode) m_ColorMode.value.intValue == FogColorMode.ConstantColor) + (FogColorMode)m_ColorMode.value.intValue == FogColorMode.ConstantColor) { PropertyField(m_Color); } @@ -146,7 +146,7 @@ public override void OnInspectorGUI() using (new HDEditorUtils.IndentScope()) { - if ((FogControl) m_FogControlMode.value.intValue == FogControl.Balance) + if ((FogControl)m_FogControlMode.value.intValue == FogControl.Balance) { PropertyField(m_VolumetricFogBudget); PropertyField(m_ResolutionDepthRatio); diff --git a/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs index 993d94c747f..08b2e42cf82 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs @@ -117,7 +117,7 @@ public void GetUpperHemisphereLuxValue() float max = Mathf.Max(hdriIntensity.r, hdriIntensity.g, hdriIntensity.b); if (max == 0.0f) max = 1.0f; - m_UpperHemisphereLuxColor.value.vector3Value = new Vector3(hdriIntensity.r/max, hdriIntensity.g/max, hdriIntensity.b/max); + m_UpperHemisphereLuxColor.value.vector3Value = new Vector3(hdriIntensity.r / max, hdriIntensity.g / max, hdriIntensity.b / max); m_UpperHemisphereLuxColor.value.vector3Value *= 0.5f; // Arbitrary 25% to not have too dark or too bright shadow } diff --git a/com.unity.render-pipelines.high-definition/Editor/Sky/PhysicallyBasedSky/PhysicallyBasedSkyEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Sky/PhysicallyBasedSky/PhysicallyBasedSkyEditor.cs index 5dd28e72c96..fa70349fef4 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Sky/PhysicallyBasedSky/PhysicallyBasedSkyEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Sky/PhysicallyBasedSky/PhysicallyBasedSkyEditor.cs @@ -53,45 +53,45 @@ public override void OnEnable() base.OnEnable(); m_CommonUIElementsMask = (uint)SkySettingsUIElement.UpdateMode - | (uint)SkySettingsUIElement.SkyIntensity - | (uint)SkySettingsUIElement.IncludeSunInBaking; + | (uint)SkySettingsUIElement.SkyIntensity + | (uint)SkySettingsUIElement.IncludeSunInBaking; var o = new PropertyFetcher(serializedObject); - m_Type = Unpack(o.Find(x => x.type)); - m_SphericalMode = Unpack(o.Find(x => x.sphericalMode)); - m_SeaLevel = Unpack(o.Find(x => x.seaLevel)); - m_PlanetaryRadius = Unpack(o.Find(x => x.planetaryRadius)); - m_PlanetCenterPosition = Unpack(o.Find(x => x.planetCenterPosition)); - m_PlanetRotation = Unpack(o.Find(x => x.planetRotation)); - m_GroundColorTexture = Unpack(o.Find(x => x.groundColorTexture)); - m_GroundTint = Unpack(o.Find(x => x.groundTint)); - m_GroundEmissionTexture = Unpack(o.Find(x => x.groundEmissionTexture)); - m_GroundEmissionMultiplier = Unpack(o.Find(x => x.groundEmissionMultiplier)); - - m_SpaceRotation = Unpack(o.Find(x => x.spaceRotation)); - m_SpaceEmissionTexture = Unpack(o.Find(x => x.spaceEmissionTexture)); - m_SpaceEmissionMultiplier = Unpack(o.Find(x => x.spaceEmissionMultiplier)); - - m_AirMaximumAltitude = Unpack(o.Find(x => x.airMaximumAltitude)); - m_AirDensityR = Unpack(o.Find(x => x.airDensityR)); - m_AirDensityG = Unpack(o.Find(x => x.airDensityG)); - m_AirDensityB = Unpack(o.Find(x => x.airDensityB)); - m_AirTint = Unpack(o.Find(x => x.airTint)); - - m_AerosolMaximumAltitude = Unpack(o.Find(x => x.aerosolMaximumAltitude)); - m_AerosolDensity = Unpack(o.Find(x => x.aerosolDensity)); - m_AerosolTint = Unpack(o.Find(x => x.aerosolTint)); - m_AerosolAnisotropy = Unpack(o.Find(x => x.aerosolAnisotropy)); - - m_ColorSaturation = Unpack(o.Find(x => x.colorSaturation)); - m_AlphaSaturation = Unpack(o.Find(x => x.alphaSaturation)); - m_AlphaMultiplier = Unpack(o.Find(x => x.alphaMultiplier)); - m_HorizonTint = Unpack(o.Find(x => x.horizonTint)); - m_ZenithTint = Unpack(o.Find(x => x.zenithTint)); - m_HorizonZenithShift = Unpack(o.Find(x => x.horizonZenithShift)); - - m_NumberOfBounces = Unpack(o.Find(x => x.numberOfBounces)); + m_Type = Unpack(o.Find(x => x.type)); + m_SphericalMode = Unpack(o.Find(x => x.sphericalMode)); + m_SeaLevel = Unpack(o.Find(x => x.seaLevel)); + m_PlanetaryRadius = Unpack(o.Find(x => x.planetaryRadius)); + m_PlanetCenterPosition = Unpack(o.Find(x => x.planetCenterPosition)); + m_PlanetRotation = Unpack(o.Find(x => x.planetRotation)); + m_GroundColorTexture = Unpack(o.Find(x => x.groundColorTexture)); + m_GroundTint = Unpack(o.Find(x => x.groundTint)); + m_GroundEmissionTexture = Unpack(o.Find(x => x.groundEmissionTexture)); + m_GroundEmissionMultiplier = Unpack(o.Find(x => x.groundEmissionMultiplier)); + + m_SpaceRotation = Unpack(o.Find(x => x.spaceRotation)); + m_SpaceEmissionTexture = Unpack(o.Find(x => x.spaceEmissionTexture)); + m_SpaceEmissionMultiplier = Unpack(o.Find(x => x.spaceEmissionMultiplier)); + + m_AirMaximumAltitude = Unpack(o.Find(x => x.airMaximumAltitude)); + m_AirDensityR = Unpack(o.Find(x => x.airDensityR)); + m_AirDensityG = Unpack(o.Find(x => x.airDensityG)); + m_AirDensityB = Unpack(o.Find(x => x.airDensityB)); + m_AirTint = Unpack(o.Find(x => x.airTint)); + + m_AerosolMaximumAltitude = Unpack(o.Find(x => x.aerosolMaximumAltitude)); + m_AerosolDensity = Unpack(o.Find(x => x.aerosolDensity)); + m_AerosolTint = Unpack(o.Find(x => x.aerosolTint)); + m_AerosolAnisotropy = Unpack(o.Find(x => x.aerosolAnisotropy)); + + m_ColorSaturation = Unpack(o.Find(x => x.colorSaturation)); + m_AlphaSaturation = Unpack(o.Find(x => x.alphaSaturation)); + m_AlphaMultiplier = Unpack(o.Find(x => x.alphaMultiplier)); + m_HorizonTint = Unpack(o.Find(x => x.horizonTint)); + m_ZenithTint = Unpack(o.Find(x => x.zenithTint)); + m_HorizonZenithShift = Unpack(o.Find(x => x.horizonZenithShift)); + + m_NumberOfBounces = Unpack(o.Find(x => x.numberOfBounces)); } public override void OnInspectorGUI() @@ -114,7 +114,7 @@ public override void OnInspectorGUI() EditorGUILayout.LabelField("Planet"); if (type == PhysicallyBasedSkyModel.EarthSimple) - PropertyField(m_SeaLevel); + PropertyField(m_SeaLevel); else { PropertyField(m_SphericalMode); @@ -136,7 +136,7 @@ public override void OnInspectorGUI() PropertyField(m_GroundColorTexture); } - PropertyField(m_GroundTint); + PropertyField(m_GroundTint); if (type != PhysicallyBasedSkyModel.EarthSimple) { PropertyField(m_GroundEmissionTexture); @@ -156,16 +156,16 @@ public override void OnInspectorGUI() { EditorGUILayout.Space(); EditorGUILayout.LabelField("Air"); - PropertyField(m_AirMaximumAltitude); - PropertyField(m_AirDensityR); + PropertyField(m_AirMaximumAltitude); + PropertyField(m_AirDensityR); PropertyField(m_AirDensityG); PropertyField(m_AirDensityB); - PropertyField(m_AirTint); + PropertyField(m_AirTint); } EditorGUILayout.Space(); EditorGUILayout.LabelField("Aerosols"); - PropertyField(m_AerosolDensity); + PropertyField(m_AerosolDensity); PropertyField(m_AerosolTint); if (type != PhysicallyBasedSkyModel.EarthSimple) { @@ -175,16 +175,16 @@ public override void OnInspectorGUI() EditorGUILayout.Space(); EditorGUILayout.LabelField("Artistic Overrides"); - PropertyField(m_ColorSaturation); - PropertyField(m_AlphaSaturation); - PropertyField(m_AlphaMultiplier); - PropertyField(m_HorizonTint); - PropertyField(m_HorizonZenithShift); - PropertyField(m_ZenithTint); + PropertyField(m_ColorSaturation); + PropertyField(m_AlphaSaturation); + PropertyField(m_AlphaMultiplier); + PropertyField(m_HorizonTint); + PropertyField(m_HorizonZenithShift); + PropertyField(m_ZenithTint); EditorGUILayout.Space(); EditorGUILayout.LabelField("Miscellaneous"); - PropertyField(m_NumberOfBounces); + PropertyField(m_NumberOfBounces); base.CommonSkySettingsGUI(); } diff --git a/com.unity.render-pipelines.high-definition/Editor/Sky/SkySettingsEditor.cs b/com.unity.render-pipelines.high-definition/Editor/Sky/SkySettingsEditor.cs index e64a036d7d7..ec85a3d67d6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Sky/SkySettingsEditor.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Sky/SkySettingsEditor.cs @@ -106,7 +106,7 @@ protected void CommonSkySettingsGUI() "Upper hemisphere lux value: {0}\nAbsolute multiplier: {1}", m_UpperHemisphereLuxValue.value.floatValue, (m_DesiredLuxValue.value.floatValue / m_UpperHemisphereLuxValue.value.floatValue) - ), MessageType.Info); + ), MessageType.Info); } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsDark.uss b/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsDark.uss index cefa9e4e146..d9e579e4538 100644 --- a/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsDark.uss +++ b/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsDark.uss @@ -1,4 +1,4 @@ -.unity-list-view .odd { +.unity-list-view .odd { background-color: #3f3f3f; } diff --git a/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsLight.uss b/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsLight.uss index 9c6e447ea86..2d0aebfa62a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsLight.uss +++ b/com.unity.render-pipelines.high-definition/Editor/USS/QualitySettingsLight.uss @@ -1,4 +1,4 @@ -.unity-list-view .odd { +.unity-list-view .odd { background-color: #bcbcbc; } diff --git a/com.unity.render-pipelines.high-definition/Editor/Upgraders/UpgradeStandardShaderMaterials.cs b/com.unity.render-pipelines.high-definition/Editor/Upgraders/UpgradeStandardShaderMaterials.cs index a0d1dd2c185..1211c1a0b6c 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Upgraders/UpgradeStandardShaderMaterials.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Upgraders/UpgradeStandardShaderMaterials.cs @@ -18,9 +18,9 @@ static List GetHDUpgraders() upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Texture", "HDRP/Unlit")); upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Transparent", "HDRP/Unlit")); upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Transparent Cutout", "HDRP/Unlit")); - - upgraders.Add(new StandardsTerrainToHDTerrainLitUpgrader("Nature/Terrain/Standard", "HDRP/TerrainLit")); - + + upgraders.Add(new StandardsTerrainToHDTerrainLitUpgrader("Nature/Terrain/Standard", "HDRP/TerrainLit")); + return upgraders; } @@ -35,27 +35,27 @@ internal static void UpgradeMaterialsSelection() { MaterialUpgrader.UpgradeSelection(GetHDUpgraders(), "Upgrade to HD Material"); } - - [MenuItem("Edit/Render Pipeline/HD Render Pipeline/Upgrade from Builtin pipeline/Upgrade Scene Terrains to High Definition Terrains")] - static void UpgradeSceneTerrainsToHighDefinitionTerrains(MenuCommand menuCommand) - { - var LegacyDefaultTerrainMat = AssetDatabase.GetBuiltinExtraResource("Default-Terrain-Standard.mat"); - var HDRPTerrainMat = AssetDatabase.LoadAssetAtPath("Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDTerrainMaterial.mat"); + + [MenuItem("Edit/Render Pipeline/HD Render Pipeline/Upgrade from Builtin pipeline/Upgrade Scene Terrains to High Definition Terrains")] + static void UpgradeSceneTerrainsToHighDefinitionTerrains(MenuCommand menuCommand) + { + var LegacyDefaultTerrainMat = AssetDatabase.GetBuiltinExtraResource("Default-Terrain-Standard.mat"); + var HDRPTerrainMat = AssetDatabase.LoadAssetAtPath("Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/Material/DefaultHDTerrainMaterial.mat"); var terrainArray = UnityEngine.GameObject.FindObjectsOfType(); - if (terrainArray.Length == 0) - { - Debug.LogWarning("No terrains were found in the scene."); - return; - } - - foreach (Terrain currentTerrain in terrainArray) + if (terrainArray.Length == 0) { - if(currentTerrain.materialTemplate == LegacyDefaultTerrainMat) - { - currentTerrain.materialTemplate = HDRPTerrainMat; - } - } - } + Debug.LogWarning("No terrains were found in the scene."); + return; + } + + foreach (Terrain currentTerrain in terrainArray) + { + if (currentTerrain.materialTemplate == LegacyDefaultTerrainMat) + { + currentTerrain.materialTemplate = HDRPTerrainMat; + } + } + } } } diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractDistortionOutput.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractDistortionOutput.cs index ed6b2f5024e..93dd7786395 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractDistortionOutput.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractDistortionOutput.cs @@ -9,7 +9,7 @@ namespace UnityEditor.VFX { abstract class VFXAbstractDistortionOutput : VFXAbstractParticleOutput { - public VFXAbstractDistortionOutput(bool strip = false) : base(strip) { } + public VFXAbstractDistortionOutput(bool strip = false) : base(strip) {} public enum DistortionMode { @@ -136,7 +136,7 @@ public override IEnumerable additionalDefines foreach (var define in base.additionalDefines) yield return define; - switch(distortionMode) + switch (distortionMode) { case DistortionMode.ScreenSpace: yield return "DISTORTION_SCREENSPACE"; diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractParticleHDRPLitOutput.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractParticleHDRPLitOutput.cs index 467a80a226d..0f40eeadec5 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractParticleHDRPLitOutput.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXAbstractParticleHDRPLitOutput.cs @@ -92,7 +92,7 @@ public enum BaseColorMapMode [VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector), SerializeField, Tooltip("When enabled, particles can be affected by environment light set in the global volume profile.")] protected bool enableEnvLight = true; - protected VFXAbstractParticleHDRPLitOutput(bool strip = false) : base(strip) { } + protected VFXAbstractParticleHDRPLitOutput(bool strip = false) : base(strip) {} protected virtual bool allowTextures { get { return shaderGraph == null; }} @@ -213,7 +213,7 @@ protected override IEnumerable CollectGPUExpressions(IEnumer foreach (var exp in base.CollectGPUExpressions(slotExpressions)) yield return exp; - if( shaderGraph == null) + if (shaderGraph == null) { yield return slotExpressions.First(o => o.name == "smoothness"); @@ -230,12 +230,12 @@ protected override IEnumerable CollectGPUExpressions(IEnumer case MaterialType.Translucent: case MaterialType.SimpleLitTranslucent: - { - yield return slotExpressions.First(o => o.name == "thickness"); - uint diffusionProfileHash = (diffusionProfileAsset?.profile != null) ? diffusionProfileAsset.profile.hash : 0; - yield return new VFXNamedExpression(VFXValue.Constant(diffusionProfileHash), "diffusionProfileHash"); - break; - } + { + yield return slotExpressions.First(o => o.name == "thickness"); + uint diffusionProfileHash = (diffusionProfileAsset?.profile != null) ? diffusionProfileAsset.profile.hash : 0; + yield return new VFXNamedExpression(VFXValue.Constant(diffusionProfileHash), "diffusionProfileHash"); + break; + } default: break; } diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionPlanarPrimitiveOutput.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionPlanarPrimitiveOutput.cs index eaf73b13f35..ade45285ec6 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionPlanarPrimitiveOutput.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionPlanarPrimitiveOutput.cs @@ -14,7 +14,7 @@ class VFXDistortionPlanarPrimitiveOutput : VFXAbstractDistortionOutput //[VFXSetting] // tmp dont expose as settings atm public bool useGeometryShader = false; - public override string name { get { return "Output Particle Distortion " + primitiveType.ToString(); ; } } + public override string name { get { return "Output Particle Distortion " + primitiveType.ToString();; } } public override string codeGeneratorTemplate { get { return RenderPipeTemplate("VFXParticleDistortionPlanarPrimitive"); } } public override VFXTaskType taskType { diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionQuadStripOutput.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionQuadStripOutput.cs index 1f74fb70ab5..f20280723ae 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionQuadStripOutput.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXDistortionQuadStripOutput.cs @@ -17,7 +17,7 @@ class VFXDistortionQuadStripOutput : VFXAbstractDistortionOutput [VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector), SerializeField, Tooltip("When enabled, the axisZ attribute is used to orient the strip instead of facing the Camera.")] private bool UseCustomZAxis = false; - VFXDistortionQuadStripOutput() : base(true) { } + VFXDistortionQuadStripOutput() : base(true) {} public override string name { get { return "Output Strip Distortion Quad"; } } public override string codeGeneratorTemplate { get { return RenderPipeTemplate("VFXParticleDistortionPlanarPrimitive"); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXLitQuadStripOutput.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXLitQuadStripOutput.cs index 2be65decdbc..d603285fb27 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXLitQuadStripOutput.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/Outputs/VFXLitQuadStripOutput.cs @@ -8,7 +8,7 @@ namespace UnityEditor.VFX [VFXInfo(experimental = true)] class VFXLitQuadStripOutput : VFXAbstractParticleHDRPLitOutput { - protected VFXLitQuadStripOutput() : base(true) { } // strips + protected VFXLitQuadStripOutput() : base(true) {} // strips public override string name { get { return "Output ParticleStrip Lit Quad"; } } public override string codeGeneratorTemplate { get { return RenderPipeTemplate("VFXParticleLitPlanarPrimitive"); } } diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPBinder.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPBinder.cs index f2957ae8a46..f3545274799 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPBinder.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPBinder.cs @@ -20,7 +20,7 @@ public override void SetupMaterial(Material mat) { HDShaderUtils.ResetMaterialKeywords(mat); } - catch(ArgumentException) // Silently catch the 'Unknown shader' in case of non HDRP shaders + catch (ArgumentException) // Silently catch the 'Unknown shader' in case of non HDRP shaders {} } } diff --git a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPSubOutput.cs b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPSubOutput.cs index f60f6b5a05a..297690915f9 100644 --- a/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPSubOutput.cs +++ b/com.unity.render-pipelines.high-definition/Editor/VFXGraph/VFXHDRPSubOutput.cs @@ -14,10 +14,10 @@ class VFXHDRPSubOutput : VFXSRPSubOutput public OpaqueRenderQueue opaqueRenderQueue = OpaqueRenderQueue.Default; [VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector), Header("HDRP"), Tooltip("Specifies when in the render queue particles are drawn. This is useful for drawing particles behind refractive surfaces like frosted glass, for performance gains by rendering them in low resolution, or to draw particles after post processing so they are not affected by effects such as Depth of Field.")] - public TransparentRenderQueue transparentRenderQueue = TransparentRenderQueue.Default; + public TransparentRenderQueue transparentRenderQueue = TransparentRenderQueue.Default; // Caps - public override bool supportsExposure { get { return true; } } + public override bool supportsExposure { get { return true; } } public override bool supportsMotionVector { get @@ -51,7 +51,7 @@ public override void OnSettingModified(VFXSetting setting) base.OnSettingModified(setting); // Reset to default if render queue is invalid if (setting.name == "transparentRenderQueue") - { + { if (!supportsQueueSelection || (isLit && transparentRenderQueue == TransparentRenderQueue.AfterPostProcessing)) transparentRenderQueue = TransparentRenderQueue.Default; } @@ -80,7 +80,7 @@ public override IEnumerable GetFilteredOutEnumerators(string name) } } } - + public override string GetBlendModeStr() { bool isOffscreen = transparentRenderQueue == TransparentRenderQueue.LowResolution || transparentRenderQueue == TransparentRenderQueue.AfterPostProcessing; @@ -120,9 +120,9 @@ public override string GetRenderQueueStr() //TODO : extend & factorize this method public static void GetStencilStateForPasses(bool receiveDecals, bool receiveSSR, bool useObjectVelocity, bool hasSubsurfaceScattering, - out int stencilWriteMask, out int stencilRef, - out int stencilWriteMaskGBuffer, out int stencilRefGBuffer, - out int stencilWriteMaskDistortion, out int stencilRefDistortion) + out int stencilWriteMask, out int stencilRef, + out int stencilWriteMaskGBuffer, out int stencilRefGBuffer, + out int stencilWriteMaskDistortion, out int stencilRefDistortion) { stencilWriteMask = 0; stencilRef = 0; @@ -134,7 +134,7 @@ public static void GetStencilStateForPasses(bool receiveDecals, bool receiveSSR, stencilRef |= useObjectVelocity ? (int)StencilUsage.ObjectMotionVector : 0; stencilRefGBuffer = (int)StencilUsage.RequiresDeferredLighting; - if(hasSubsurfaceScattering) + if (hasSubsurfaceScattering) stencilRefGBuffer |= (int)StencilUsage.SubsurfaceScattering; stencilWriteMaskGBuffer = (int)StencilUsage.RequiresDeferredLighting | (int)StencilUsage.SubsurfaceScattering; @@ -149,8 +149,8 @@ public override IEnumerable> GetStencilSta int stencilGBufferWriteMask, stencilRefGBuffer; int stencilWriteMaskDistortion, stencilRefDistortion; GetStencilStateForPasses(false, false, true, false, out stencilWriteMask, out stencilRef, - out stencilGBufferWriteMask, out stencilRefGBuffer, - out stencilWriteMaskDistortion, out stencilRefDistortion); + out stencilGBufferWriteMask, out stencilRefGBuffer, + out stencilWriteMaskDistortion, out stencilRefDistortion); var stencilForMV = new VFXShaderWriter(); stencilForMV.WriteFormat("Stencil\n{{\n WriteMask {0}\n Ref {1}\n Comp Always\n Pass Replace\n}}", stencilWriteMask, stencilRef); yield return new KeyValuePair("${VFXStencilMotionVector}", stencilForMV); diff --git a/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs b/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs index 5f77883e485..0f033d17e1a 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Configuration.cs @@ -76,22 +76,22 @@ static void LoadReflectionMethods() new[] { qualityVariable }, Expression.Assign(qualityVariable, Expression.Call(getLightmapEncodingQualityForPlatformGroupInfo, buildTargetGroupParameter)), Expression.Convert(qualityVariable, typeof(LightmapEncodingQualityCopy)) - ); + ); var setLightmapEncodingQualityForPlatformGroupBlock = Expression.Block( new[] { qualityVariable }, Expression.Assign(qualityVariable, Expression.Convert(qualityParameter, lightEncodingQualityType)), Expression.Call(setLightmapEncodingQualityForPlatformGroupInfo, buildTargetGroupParameter, qualityVariable) - ); + ); var getStaticBatchingBlock = Expression.Block( new[] { staticBatchingVariable, dynamicBatchingVariable }, Expression.Call(getStaticBatchingInfo, buildTargetParameter, staticBatchingVariable, dynamicBatchingVariable), Expression.Equal(staticBatchingVariable, Expression.Constant(1)) - ); + ); var setStaticBatchingBlock = Expression.Block( new[] { staticBatchingVariable, dynamicBatchingVariable }, Expression.Call(getStaticBatchingInfo, buildTargetParameter, staticBatchingVariable, dynamicBatchingVariable), Expression.Call(setStaticBatchingInfo, buildTargetParameter, Expression.Convert(staticBatchingParameter, typeof(int)), dynamicBatchingVariable) - ); + ); var getLightmapEncodingQualityForPlatformGroupLambda = Expression.Lambda>(getLightmapEncodingQualityForPlatformGroupBlock, buildTargetGroupParameter); var setLightmapEncodingQualityForPlatformGroupLambda = Expression.Lambda>(setLightmapEncodingQualityForPlatformGroupBlock, buildTargetGroupParameter, qualityParameter); var calculateSelectedBuildTargetLambda = Expression.Lambda>(Expression.Call(null, calculateSelectedBuildTargetInfo)); @@ -295,7 +295,6 @@ void RestartFixAllAfterDomainReload() HDProjectSettings.wizardNeedToRunFixAllAgainAfterDomainReload = true; } - void CheckPersistentFixAll() { if (HDProjectSettings.wizardNeedToRunFixAllAgainAfterDomainReload) @@ -344,6 +343,7 @@ bool IsLightmapCorrect() && GetLightmapEncodingQualityForPlatformGroup(BuildTargetGroup.Lumin) == LightmapEncodingQualityCopy.High && GetLightmapEncodingQualityForPlatformGroup(BuildTargetGroup.WSA) == LightmapEncodingQualityCopy.High; } + void FixLightmap(bool fromAsyncUnused) { SetLightmapEncodingQualityForPlatformGroup(BuildTargetGroup.Standalone, LightmapEncodingQualityCopy.High); @@ -366,7 +366,7 @@ void FixShadow(bool fromAsyncUnised) } bool IsShadowmaskCorrect() - //QualitySettings.SetQualityLevel.set quality is too costy to be use at frame + //QualitySettings.SetQualityLevel.set quality is too costy to be use at frame => QualitySettings.shadowmaskMode == ShadowmaskMode.DistanceShadowmask; void FixShadowmask(bool fromAsyncUnused) { @@ -387,7 +387,7 @@ void FixHdrpAssetUsed(bool fromAsync) return; CreateOrLoad(fromAsync ? () => m_Fixer.Stop() - : (Action)null, + : (Action)null, asset => GraphicsSettings.renderPipelineAsset = asset); } @@ -453,6 +453,7 @@ bool IsHdrpAssetDiffusionProfileCorrect() var profileList = HDRenderPipeline.defaultAsset?.diffusionProfileSettingsList; return IsHdrpAssetUsedCorrect() && profileList.Length != 0 && profileList.Any(p => p != null); } + void FixHdrpAssetDiffusionProfile(bool fromAsyncUnused) { if (!IsHdrpAssetUsedCorrect()) @@ -487,6 +488,7 @@ bool IsDefaultVolumeProfileAssigned() && !hdAsset.defaultVolumeProfile.Equals(null) && hdAsset.defaultVolumeProfile != hdAsset.renderPipelineEditorResources.defaultSettingsVolumeProfile; } + void FixDefaultVolumeProfileAssigned(bool fromAsyncUnused) { if (!IsHdrpAssetUsedCorrect()) @@ -535,10 +537,11 @@ void FixOldVRSystemForCurrentBuildTargetGroup(bool fromAsyncUnused) bool IsVRXRManagementPackageInstalledCorrect() { m_UsedPackageRetriever.ProcessAsync( - k_XRanagementPackageName, - (installed, info) => vrXRManagementInstalledCheck = installed); + k_XRanagementPackageName, + (installed, info) => vrXRManagementInstalledCheck = installed); return vrXRManagementInstalledCheck; } + void FixVRXRManagementPackageInstalled(bool fromAsync) { if (fromAsync) @@ -550,10 +553,11 @@ void FixVRXRManagementPackageInstalled(bool fromAsync) bool IsVRLegacyHelpersCorrect() { m_UsedPackageRetriever.ProcessAsync( - k_LegacyInputHelpersPackageName, - (installed, info) => vrLegacyHelpersInstalledCheck = installed); + k_LegacyInputHelpersPackageName, + (installed, info) => vrLegacyHelpersInstalledCheck = installed); return vrLegacyHelpersInstalledCheck; } + void FixVRLegacyHelpers(bool fromAsync) { if (fromAsync) @@ -589,8 +593,8 @@ void FixDXRDirect3D12(bool fromAsyncUnused) buidTarget, new[] { GraphicsDeviceType.Direct3D12 } .Concat( - PlayerSettings.GetGraphicsAPIs(buidTarget) - .Where(x => x != GraphicsDeviceType.Direct3D12)) + PlayerSettings.GetGraphicsAPIs(buidTarget) + .Where(x => x != GraphicsDeviceType.Direct3D12)) .ToArray()); } else @@ -645,8 +649,8 @@ void FixDXRAsset(bool fromAsyncUnused) = AssetDatabase.LoadAssetAtPath(HDUtils.GetHDRenderPipelinePath() + "Runtime/RenderPipelineResources/HDRenderPipelineRayTracingResources.asset"); ResourceReloader.ReloadAllNullIn(HDRenderPipeline.defaultAsset.renderPipelineRayTracingResources, HDUtils.GetHDRenderPipelinePath()); // IMPORTANT: We display the error only if we are D3D12 as the supportsRayTracing always return false in any other device even if OS/HW supports DXR. - // The D3D12 is a separate check in the wizard, so it is fine not to display an error in case we are not D3D12. - if (!SystemInfo.supportsRayTracing && IsDXRDirect3D12Correct()) + // The D3D12 is a separate check in the wizard, so it is fine not to display an error in case we are not D3D12. + if (!SystemInfo.supportsRayTracing && IsDXRDirect3D12Correct()) Debug.LogError("Your hardware and/or OS don't support DXR!"); if (!HDProjectSettings.wizardNeedRestartAfterChangingToDX12 && PlayerSettings.GetGraphicsAPIs(CalculateSelectedBuildTarget()).FirstOrDefault() != GraphicsDeviceType.Direct3D12) { @@ -720,10 +724,10 @@ bool IsDXRGIFSCorrect() bool IsArchitecture64Bits() => EditorUserBuildSettings.activeBuildTarget == BuildTarget.StandaloneWindows64; - void FixArchitecture64Bits(bool fromAsyncUnused) - { - EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64); - } + void FixArchitecture64Bits(bool fromAsyncUnused) + { + EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64); + } bool IsDXRStaticBatchingCorrect() => !GetStaticBatching(CalculateSelectedBuildTarget()); diff --git a/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.UIElement.cs b/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.UIElement.cs index ff755a40365..554478f07fb 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.UIElement.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.UIElement.cs @@ -58,7 +58,7 @@ static ObjectSelector() #else Expression.Call(objectSelectorVariable, showInfo, objectParameter, typeParameter, Expression.Constant(null, typeof(SerializedProperty)), Expression.Constant(false), Expression.Constant(null, typeof(List)), Expression.Constant(null, typeof(Action)), onChangedObjectParameter) #endif - ); + ); var showObjectSelectorLambda = Expression.Lambda>>(showObjectSelectorBlock, objectParameter, typeParameter, onChangedObjectParameter); ShowObjectSelector = showObjectSelectorLambda.Compile(); @@ -85,6 +85,7 @@ public static void Show(UnityEngine.Object obj, Type type, Action(Action onCancel, Action onObjectChanged) onCancel?.Invoke(); break; case 2: //Load - { - m_Fixer.Pause(); - ObjectSelector.Show(target, typeof(T), o => onObjectChanged?.Invoke((T)o), m_Fixer.Unpause); - break; - } + { + m_Fixer.Pause(); + ObjectSelector.Show(target, typeof(T), o => onObjectChanged?.Invoke((T)o), m_Fixer.Unpause); + break; + } default: throw new ArgumentException("Unrecognized option"); @@ -179,8 +180,8 @@ void Repopulate() class ToolbarRadio : UIElements.Toolbar, INotifyValueChanged { - public new class UxmlFactory : UxmlFactory { } - public new class UxmlTraits : Button.UxmlTraits { } + public new class UxmlFactory : UxmlFactory {} + public new class UxmlTraits : Button.UxmlTraits {} List radios = new List(); @@ -243,7 +244,7 @@ public void AddRadios((string label, string tooltip)[] tabs) { radios[radioLength - 1].RemoveFromClassList("LastRadio"); } - foreach (var (label, tooltip) in tabs) + foreach (var(label, tooltip) in tabs) AddRadio(label, tooltip); radios[radioLength - 1].AddToClassList("LastRadio"); @@ -317,7 +318,7 @@ public virtual void CheckUpdate() class HiddableUpdatableContainer : VisualElementUpdatable { - public HiddableUpdatableContainer(Func tester, bool haveFixer = false) : base(tester, haveFixer) { } + public HiddableUpdatableContainer(Func tester, bool haveFixer = false) : base(tester, haveFixer) {} public override void CheckUpdate() { @@ -382,10 +383,10 @@ public ConfigInfoLine(string label, string error, MessageType messageType, strin testRow.Add(statusKO); } testRow.Add(fixer); - + Add(testRow); HelpBox.Kind kind; - switch(messageType) + switch (messageType) { default: case MessageType.None: kind = HelpBox.Kind.None; break; @@ -417,7 +418,7 @@ protected override void UpdateDisplay(bool statusOK, bool haveFixer) if (m_VisibleStatus) { this.Q(name: "StatusOK").style.display = statusOK ? DisplayStyle.Flex : DisplayStyle.None; - this.Q(name: "StatusError").style.display = !statusOK ? (m_SkipErrorIcon ? DisplayStyle.None: DisplayStyle.Flex) : DisplayStyle.None; + this.Q(name: "StatusError").style.display = !statusOK ? (m_SkipErrorIcon ? DisplayStyle.None : DisplayStyle.Flex) : DisplayStyle.None; } this.Q(name: "Resolver").style.display = statusOK || !haveFixer ? DisplayStyle.None : DisplayStyle.Flex; this.Q(name: "HelpBox").style.display = statusOK ? DisplayStyle.None : DisplayStyle.Flex; @@ -434,7 +435,7 @@ public enum Kind Warning, Error } - + readonly Label label; readonly Image icon; diff --git a/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Window.cs b/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Window.cs index 20a8ffc229e..d96770d48c1 100644 --- a/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Window.cs +++ b/com.unity.render-pipelines.high-definition/Editor/Wizard/HDWizard.Window.cs @@ -164,7 +164,7 @@ public ConfigStyle(string label, string error, string button = resolve, MessageT public static readonly ConfigStyle dxr64bits = new ConfigStyle( label: "Architecture 64 bits", error: "To build your Project to a Unity Player, ray tracing requires that the build uses 64 bit architecture."); - public static readonly ConfigStyle dxrStaticBatching = new ConfigStyle( + public static readonly ConfigStyle dxrStaticBatching = new ConfigStyle( label: "Static Batching", error: "Static Batching is not supported!"); public static readonly ConfigStyle dxrActivated = new ConfigStyle( @@ -299,16 +299,18 @@ private void CreateGUI() container.Add(CreateTitle(Style.configurationTitle)); container.Add(CreateTabbedBox( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? new[] { - (Style.hdrpConfigLabel, Style.hdrpConfigTooltip), - (Style.hdrpVRConfigLabel, Style.hdrpVRConfigTooltip), - (Style.hdrpDXRConfigLabel, Style.hdrpDXRConfigTooltip), - } - : new[] { - (Style.hdrpConfigLabel, Style.hdrpConfigTooltip), - //VR only supported on window - //DXR only supported on window - }, + ? new[] + { + (Style.hdrpConfigLabel, Style.hdrpConfigTooltip), + (Style.hdrpVRConfigLabel, Style.hdrpVRConfigTooltip), + (Style.hdrpDXRConfigLabel, Style.hdrpDXRConfigTooltip), + } + : new[] + { + (Style.hdrpConfigLabel, Style.hdrpConfigTooltip), + //VR only supported on window + //DXR only supported on window + }, out m_BaseUpdatable)); m_BaseUpdatable.Add(new FixAllButton( @@ -430,10 +432,10 @@ VisualElement CreateWizardBehaviour() VisualElement CreateLargeButton(string title, Action action) => new Button(action) - { - text = title, - name = "LargeButton" - }; + { + text = title, + name = "LargeButton" + }; VisualElement CreateInstallConfigPackageArea() { @@ -501,7 +503,7 @@ void GroupEntriesForDisplay(VisualElement container, InclusiveScope filter) var hdrpAsset = HDRenderPipeline.currentAsset; if (entry.displayAssetName && hdrpAsset != null) { - error += " (" + hdrpAsset.name +")."; + error += " (" + hdrpAsset.name + ")."; } container.Add(new ConfigInfoLine( @@ -549,7 +551,7 @@ HelpBox CreateHdrpVersionChecker() helpBox.kind = HelpBox.Kind.Info; helpBox.text = String.Format(Style.hdrpVersionWithLocalPackage, packageInfo.version, version); } - else if(compatibleWithVersionCall && (new Version(packageInfo.version) < new Version(version))) + else if (compatibleWithVersionCall && (new Version(packageInfo.version) < new Version(version))) { helpBox.kind = HelpBox.Kind.Warning; helpBox.text = String.Format(Style.hdrpVersionNotLast, packageInfo.version, version); diff --git a/com.unity.render-pipelines.high-definition/Runtime/AssemblyInfo.cs b/com.unity.render-pipelines.high-definition/Runtime/AssemblyInfo.cs index c3dcc3c23c8..5e1c66dae63 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/AssemblyInfo.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/AssemblyInfo.cs @@ -4,4 +4,3 @@ [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Editor.Tests")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Runtime.Tests")] [assembly: InternalsVisibleTo("HDRP_TestRunner")] - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/AdditionalCompositorData.cs b/com.unity.render-pipelines.high-definition/Runtime/Compositor/AdditionalCompositorData.cs index cfc3a55dd23..4ef34605944 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/AdditionalCompositorData.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/AdditionalCompositorData.cs @@ -34,7 +34,7 @@ public void ResetData() clearAlpha = true; imageFitMode = BackgroundFitMode.Stretch; - if (layerFilters !=null) + if (layerFilters != null) { layerFilters.Clear(); layerFilters = null; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/AlphaInjection.cs b/com.unity.render-pipelines.high-definition/Runtime/Compositor/AlphaInjection.cs index ecb707f932f..8e7ee09e4eb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/AlphaInjection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/AlphaInjection.cs @@ -5,7 +5,7 @@ namespace UnityEngine.Rendering.HighDefinition.Compositor { - // Injects an external alpha texture into the alpha channel. Used for controlling which pixels will be affected by post processing. + // Injects an external alpha texture into the alpha channel. Used for controlling which pixels will be affected by post processing. // Use VolumeComponentDeprecated to hide the component from the volume menu (it's for internal compositor use only) [Serializable, VolumeComponentDeprecated] internal sealed class AlphaInjection : CustomPostProcessVolumeComponent, IPostProcessComponent @@ -60,5 +60,4 @@ public override void Cleanup() CoreUtils.Destroy(m_Material); } } - } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionLayer.cs b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionLayer.cs index 747da77bff9..2bcb00c11f8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionLayer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionLayer.cs @@ -22,7 +22,7 @@ public enum LayerType Image = 2 }; - // The graphics format options exposed in the UI + // The graphics format options exposed in the UI public enum UIColorBufferFormat { R11G11B10 = GraphicsFormat.B10G11R11_UFloatPack32, @@ -139,7 +139,7 @@ public float aspectRatio internal bool isUsingACameraClone => !m_LayerCamera.Equals(m_Camera); // The input alpha will be mapped between the min and max range when blending between the post-processed and plain image regions. This way the user can controls how steep is the transition. - [SerializeField] float m_AlphaMin = 0.0f; + [SerializeField] float m_AlphaMin = 0.0f; [SerializeField] float m_AlphaMax = 1.0f; private CompositorLayer() @@ -152,13 +152,13 @@ public static CompositorLayer CreateStackLayer(LayerType type = CompositorLayer. newLayer.m_LayerName = layerName; newLayer.m_Type = type; newLayer.m_Camera = CompositionManager.GetSceneCamera(); - newLayer.m_CullingMask = newLayer.m_Camera? newLayer.m_Camera.cullingMask : 0; //LayerMask.GetMask("None"); + newLayer.m_CullingMask = newLayer.m_Camera ? newLayer.m_Camera.cullingMask : 0; //LayerMask.GetMask("None"); newLayer.m_OutputTarget = CompositorLayer.OutputTarget.CameraStack; newLayer.m_ClearDepth = true; if (newLayer.m_Type == LayerType.Image || newLayer.m_Type == LayerType.Video) { - // Image and movie layers do not render any 3D objects + // Image and movie layers do not render any 3D objects newLayer.m_OverrideCullingMask = true; newLayer.m_CullingMask = 0; @@ -190,9 +190,9 @@ static float EnumToScale(ResolutionScale scale) static T AddComponent(GameObject go) where T : Component { #if UNITY_EDITOR - return UnityEditor.Undo.AddComponent(go); + return UnityEditor.Undo.AddComponent(go); #else - return go.AddComponent(); + return go.AddComponent(); #endif } @@ -227,7 +227,7 @@ public void Init(string layerID = "") m_LayerName = layerID; } - // Compositor output layers (that allocate the render targets) also need a reference camera, just to get the reference pixel width/height + // Compositor output layers (that allocate the render targets) also need a reference camera, just to get the reference pixel width/height // Note: Movie & image layers are rendered at the output resolution (and not the movie/image resolution). This is required to have post-processing effects like film grain at full res. if (m_Camera == null) { @@ -243,7 +243,7 @@ public void Init(string layerID = "") // - it has no layer overrides // - is not shared between layers // - is not used in an mage/video layer (in this case the camera is not exposed at all, so it makes sense to let the compositor manage it) - // - it does not force-clear the RT (the first layer of a stack, even if disabled by the user), still clears the RT + // - it does not force-clear the RT (the first layer of a stack, even if disabled by the user), still clears the RT bool shouldClear = !enabled && m_LayerPositionInStack == 0; bool isImageOrVideo = (m_Type == LayerType.Image || m_Type == LayerType.Video); if (!isImageOrVideo && !hasLayerOverrides && !shouldClear && !compositor.IsThisCameraShared(m_Camera)) @@ -252,7 +252,7 @@ public void Init(string layerID = "") } else { - // Clone the camera that was given by the user. We avoid calling Instantiate because we don't want to clone any other children that might be attachen to the camera + // Clone the camera that was given by the user. We avoid calling Instantiate because we don't want to clone any other children that might be attachen to the camera var newCameraGameObject = new GameObject("Layer " + layerID) { hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy | HideFlags.HideAndDontSave @@ -332,7 +332,7 @@ public void Init(string layerID = "") } m_AOVRenderTargets.Clear(); } - if(m_AOVMap != null) + if (m_AOVMap != null) { m_AOVMap.Clear(); m_AOVMap = null; @@ -367,7 +367,7 @@ public void Init(string layerID = "") } } - // layer overrides + // layer overrides SetLayerMaskOverrides(); if (m_Type == LayerType.Video && m_InputVideo != null) @@ -383,7 +383,7 @@ public void Init(string layerID = "") layerData.imageFitMode = m_BackgroundFit; } - // Custom pass to inject an alpha mask + // Custom pass to inject an alpha mask SetAdditionalLayerData(); if (m_InputFilters == null) @@ -559,7 +559,6 @@ public void UpdateOutputCamera() { CopyInternalCameraData(); } - } public void Update() @@ -699,8 +698,8 @@ public void SetupLayerCamera(CompositorLayer targetLayer, int layerPositionInSta new[] { AOVBuffers.Color }, (cmd, textures, properties) => { - // copy result to the output buffer - cmd.Blit(textures[0], targetLayer.m_AOVRenderTargets[indexLocalCopy]); + // copy result to the output buffer + cmd.Blit(textures[0], targetLayer.m_AOVRenderTargets[indexLocalCopy]); } ); outputIndex++; @@ -715,6 +714,5 @@ public void SetupLayerCamera(CompositorLayer targetLayer, int layerPositionInSta cameraData.SetAOVRequests(null); } } - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionManager.cs index d1269b3188d..e54ad28e7b0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionManager.cs @@ -64,14 +64,13 @@ public bool enableOutput m_OutputCamera.enabled = value; // also change the layers - foreach(var layer in m_InputLayers) + foreach (var layer in m_InputLayers) { if (layer.camera && layer.isUsingACameraClone) { layer.camera.enabled = value; } } - } } } @@ -134,8 +133,8 @@ public bool shaderPropertiesAreDirty static private CompositionManager s_CompositorInstance; - // Built-in Color.black has an alpha of 1, so defien here a fully transparent black - static Color s_TransparentBlack = new Color(0, 0, 0, 0); + // Built-in Color.black has an alpha of 1, so defien here a fully transparent black + static Color s_TransparentBlack = new Color(0, 0, 0, 0); #region Validation public bool ValidateLayerListOrder(int oldIndex, int newIndex) @@ -165,7 +164,6 @@ public bool RuntimeCheck() return true; } - // Validates the rendering pipeline and fixes potential issues bool ValidatePipeline() { @@ -288,6 +286,7 @@ bool ValidateAndFixRuntime() return true; } + #endregion // This is called when we change camera, to remove the custom draw callback from the old camera before we set the new one @@ -358,7 +357,7 @@ public void DeleteLayerRTs() { m_InputLayers[i].DestroyCameras(); } - + for (int i = m_InputLayers.Count - 1; i >= 0; --i) { m_InputLayers[i].DestroyRT(); @@ -397,7 +396,7 @@ void SetupCompositorLayers() public void SetNewCompositionShader() { - // When we load a new shader, we need to clear the serialized material. + // When we load a new shader, we need to clear the serialized material. m_Material = null; SetupCompositionMaterial(); } @@ -453,7 +452,7 @@ void SetupGlobalCompositorVolume() var compositorVolumes = Resources.FindObjectsOfTypeAll(typeof(CustomPassVolume)); foreach (CustomPassVolume volume in compositorVolumes) { - if(volume.isGlobal && volume.injectionPoint == CustomPassInjectionPoint.BeforeRendering) + if (volume.isGlobal && volume.injectionPoint == CustomPassInjectionPoint.BeforeRendering) { Debug.LogWarning($"A custom volume pass with name ${volume.name} was already registered on the BeforeRendering injection point."); } @@ -608,7 +607,7 @@ public string GetNewSubLayerName(int index, CompositorLayer.LayerType type = Com public void AddNewLayer(int index, CompositorLayer.LayerType type = CompositorLayer.LayerType.Camera) { var newLayer = CompositorLayer.CreateStackLayer(type, GetNewSubLayerName(index, type)); - + if (index >= 0 && index < m_InputLayers.Count) { m_InputLayers.Insert(index, newLayer); @@ -745,7 +744,7 @@ void CustomRender(ScriptableRenderContext context, HDCamera camera) cmdbuff.ClearRenderTarget(false, true, Color.black); return; } - + timeSinceLastRepaint = 0; @@ -755,7 +754,7 @@ void CustomRender(ScriptableRenderContext context, HDCamera camera) int layerIndex = 0; foreach (var layer in m_InputLayers) { - if (layer.outputTarget != CompositorLayer.OutputTarget.CameraStack) // stacked cameras are not exposed as compositor layers + if (layer.outputTarget != CompositorLayer.OutputTarget.CameraStack) // stacked cameras are not exposed as compositor layers { m_Material.SetTexture(layer.name, layer.GetRenderTarget(), RenderTextureSubElement.Color); } @@ -795,7 +794,7 @@ void CustomRender(ScriptableRenderContext context, HDCamera camera) ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); cmd.Blit(null, BuiltinRenderTextureType.CameraTarget, m_Material, m_Material.FindPass("ForwardOnly")); } - + context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } @@ -815,7 +814,6 @@ internal bool IsThisCameraShared(Camera camera) int count = 0; foreach (var layer in m_InputLayers) { - if (layer.outputTarget == CompositorLayer.OutputTarget.CameraStack && camera.Equals(layer.sourceCamera)) { @@ -857,7 +855,7 @@ static public Vector4 GetAlphaScaleAndBiasForCamera(HDCamera hdCamera) float alphaMax = compositorData.alphaMax; if (alphaMax == alphaMin) - alphaMax += 0.0001f; // Mathf.Epsilon is too small and in this case it creates precission issues + alphaMax += 0.0001f; // Mathf.Epsilon is too small and in this case it creates precission issues float alphaScale = 1.0f / (alphaMax - alphaMin); float alphaBias = -alphaMin * alphaScale; @@ -902,6 +900,5 @@ static internal RenderTexture GetClearDepthForStackedCamera(HDCamera hdCamera) } return null; } - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionProfile.cs b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionProfile.cs index a01d2e908c1..fce8250fec2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionProfile.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CompositionProfile.cs @@ -10,7 +10,7 @@ internal class CompositionProfile : ScriptableObject { [SerializeField] List m_ShaderProperties = new List(); - public void AddPropertiesFromShaderAndMaterial (CompositionManager compositor, Shader shader, Material material) + public void AddPropertiesFromShaderAndMaterial(CompositionManager compositor, Shader shader, Material material) { // reflect the non-texture shader properties List propertyNames = new List(); @@ -52,7 +52,7 @@ public void AddShaderProperty(CompositionManager compositor, ShaderProperty sp) // Check if property should be shown in the inspector bool hide = ((int)sp.flags & (int)ShaderPropertyFlags.NonModifiableTextureData) != 0 - || ((int)sp.flags & (int)ShaderPropertyFlags.HideInInspector) != 0; + || ((int)sp.flags & (int)ShaderPropertyFlags.HideInInspector) != 0; if (!hide) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CustomClear.cs b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CustomClear.cs index 9e821d2abc1..3cb2436fe3b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/CustomClear.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/CustomClear.cs @@ -80,7 +80,7 @@ protected override void Execute(CustomPassContext ctx) m_FullscreenPassMaterial.SetVector(ShaderIDs.k_BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); m_FullscreenPassMaterial.SetInt(ShaderIDs.k_ClearAlpha, layerData.clearAlpha ? 1 : 0); - // draw a quad (not Triangle), to support letter boxing and stretching + // draw a quad (not Triangle), to support letter boxing and stretching ctx.cmd.DrawProcedural(Matrix4x4.identity, m_FullscreenPassMaterial, (int)PassType.DrawTextureAndClearStencil, MeshTopology.Quads, 4, 1); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/AlphaInjection.shader b/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/AlphaInjection.shader index 90ac3d581ec..69adb2bdb2a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/AlphaInjection.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/AlphaInjection.shader @@ -36,7 +36,7 @@ Shader "Hidden/Shader/AlphaInjection" TEXTURE2D_X(_InputTexture); TEXTURE2D(_AlphaTexture); - + float4 CustomPostProcess(Varyings input) : SV_Target { UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/ChromaKeying.shader b/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/ChromaKeying.shader index 1f2a41392e0..009be36ace5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/ChromaKeying.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Compositor/Shaders/ChromaKeying.shader @@ -36,39 +36,39 @@ Shader "Hidden/Shader/ChromaKeying" // List of properties to control your post process effect float3 _KeyColor; - float4 _KeyParams; + float4 _KeyParams; TEXTURE2D_X(_InputTexture); - // RGB <-> YCgCo color space conversion - float3 RGB2YCgCo(float3 rgb) - { - float3x3 m = { - 0.25, 0.5, 0.25, - -0.25, 0.5, -0.25, - 0.50, 0.0, -0.50 - }; - return mul(m, rgb); - } - - float3 YCgCo2RGB(float3 ycgco) - { - return float3( - ycgco.x - ycgco.y + ycgco.z, - ycgco.x + ycgco.y, - ycgco.x - ycgco.y - ycgco.z - ); - } - - // Adapted from https://github.com/keijiro/ProcAmp - // Main difference is that we do the chroma keying in linear space (not gamma) - float ChromaKeyAt(float3 keyColorYCoCg, float2 uv) - { - float3 rgb = LOAD_TEXTURE2D_X_LOD(_InputTexture, uv, 0).xyz; - float3 inputColor = LinearToSRGB(rgb); - - float d = distance(RGB2YCgCo(inputColor).yz, keyColorYCoCg.yz) * 10 ; - return smoothstep(_KeyParams.x, _KeyParams.x + _KeyParams.y, d); - } + // RGB <-> YCgCo color space conversion + float3 RGB2YCgCo(float3 rgb) + { + float3x3 m = { + 0.25, 0.5, 0.25, + -0.25, 0.5, -0.25, + 0.50, 0.0, -0.50 + }; + return mul(m, rgb); + } + + float3 YCgCo2RGB(float3 ycgco) + { + return float3( + ycgco.x - ycgco.y + ycgco.z, + ycgco.x + ycgco.y, + ycgco.x - ycgco.y - ycgco.z + ); + } + + // Adapted from https://github.com/keijiro/ProcAmp + // Main difference is that we do the chroma keying in linear space (not gamma) + float ChromaKeyAt(float3 keyColorYCoCg, float2 uv) + { + float3 rgb = LOAD_TEXTURE2D_X_LOD(_InputTexture, uv, 0).xyz; + float3 inputColor = LinearToSRGB(rgb); + + float d = distance(RGB2YCgCo(inputColor).yz, keyColorYCoCg.yz) * 10 ; + return smoothstep(_KeyParams.x, _KeyParams.x + _KeyParams.y, d); + } float4 CustomPostProcess(Varyings input) : SV_Target { @@ -76,29 +76,29 @@ Shader "Hidden/Shader/ChromaKeying" uint2 positionSS = input.texcoord * _ScreenSize.xy; float3 outColor = LOAD_TEXTURE2D_X_LOD(_InputTexture, positionSS, 0).xyz; - float3 keyColorYCoCg = RGB2YCgCo(_KeyColor); - - // Calculate keys for surrounding four points and get the minima of them. - // This works like a blur and dilate filter. - float4 duv = _ScreenSize.zwzw * float4(-0.5, -0.5, 0.5, 0.5); - float alpha = ChromaKeyAt(keyColorYCoCg, positionSS + duv.xy); - alpha = min(alpha, ChromaKeyAt(keyColorYCoCg, positionSS + duv.zy)); - alpha = min(alpha, ChromaKeyAt(keyColorYCoCg, positionSS + duv.xw)); - alpha = min(alpha, ChromaKeyAt(keyColorYCoCg, positionSS + duv.zw)); - - if (_KeyParams.z > 0) - { - // Spill removal - // What the following lines do is flattening the CgCo chroma values - // so that dot(ycgco, _KeyCgCo) == 0.5. This shifts colors toward - // the anticolor of the key color. - outColor = RGB2YCgCo(LinearToSRGB(outColor)); - float sub = dot(keyColorYCoCg.yz, outColor.yz) / dot(keyColorYCoCg.yz, keyColorYCoCg.yz); - outColor.yz -= keyColorYCoCg.yz * (sub + 0.5) * _KeyParams.z; - outColor = SRGBToLinear(YCgCo2RGB(outColor)); - } - - return float4(outColor, alpha); + float3 keyColorYCoCg = RGB2YCgCo(_KeyColor); + + // Calculate keys for surrounding four points and get the minima of them. + // This works like a blur and dilate filter. + float4 duv = _ScreenSize.zwzw * float4(-0.5, -0.5, 0.5, 0.5); + float alpha = ChromaKeyAt(keyColorYCoCg, positionSS + duv.xy); + alpha = min(alpha, ChromaKeyAt(keyColorYCoCg, positionSS + duv.zy)); + alpha = min(alpha, ChromaKeyAt(keyColorYCoCg, positionSS + duv.xw)); + alpha = min(alpha, ChromaKeyAt(keyColorYCoCg, positionSS + duv.zw)); + + if (_KeyParams.z > 0) + { + // Spill removal + // What the following lines do is flattening the CgCo chroma values + // so that dot(ycgco, _KeyCgCo) == 0.5. This shifts colors toward + // the anticolor of the key color. + outColor = RGB2YCgCo(LinearToSRGB(outColor)); + float sub = dot(keyColorYCoCg.yz, outColor.yz) / dot(keyColorYCoCg.yz, keyColorYCoCg.yz); + outColor.yz -= keyColorYCoCg.yz * (sub + 0.5) * _KeyParams.z; + outColor = SRGBToLinear(YCgCo2RGB(outColor)); + } + + return float4(outColor, alpha); } ENDHLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/ClearUIntTextureArray.compute b/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/ClearUIntTextureArray.compute index 2c3fe4e73c2..b1e6603ade7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/ClearUIntTextureArray.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/ClearUIntTextureArray.compute @@ -1,4 +1,4 @@ -#pragma kernel ClearUIntTexture +#pragma kernel ClearUIntTexture #pragma kernel ClearUIntTextureArray #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/GPUCopy.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/GPUCopy.cs index 19bb3f40ea0..e83a1e45069 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/GPUCopy.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/CoreResources/GPUCopy.cs @@ -93,6 +93,7 @@ void SampleCopyChannel( } } } + public void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RTHandle source, RTHandle target, RectInt rect) { Debug.Assert(source.rt.volumeDepth == target.rt.volumeDepth); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/Debugging/FrameSettingsFieldAttribute.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/Debugging/FrameSettingsFieldAttribute.cs index a6ba788a7ec..9d5830a221a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/Debugging/FrameSettingsFieldAttribute.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/Debugging/FrameSettingsFieldAttribute.cs @@ -17,7 +17,7 @@ public static string CamelToPascalCaseWithSpace(this string text, bool preserveA if (char.IsUpper(text[i])) if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) || (preserveAcronyms && char.IsUpper(text[i - 1]) && - i < text.Length - 1 && !char.IsUpper(text[i + 1]))) + i < text.Length - 1 && !char.IsUpper(text[i + 1]))) newText.Append(' '); newText.Append(text[i]); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/EncodeBC6H.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/EncodeBC6H.cs index 252eb038f2e..96e2c485bd5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/EncodeBC6H.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/EncodeBC6H.cs @@ -36,9 +36,9 @@ public EncodeBC6H(ComputeShader shader) m_Shader = shader; m_KEncodeFastCubemapMip = m_Shader.FindKernel("KEncodeFastCubemapMip"); - + // Disabling this code as we currently don't use BC6H encoding and it seems to create issue when enabling virtual texturing. - //uint x, y, z; + //uint x, y, z; //m_Shader.GetKernelThreadGroupSizes(m_KEncodeFastCubemapMip, out x, out y, out z); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache.cs index 4f9283aa887..2b9006d999e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache.cs @@ -59,6 +59,7 @@ virtual public bool IsCreated() { return true; } + public string GetCacheName() { return m_CacheName; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache2D.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache2D.cs index 441336adaf7..1c0c2f8f3a3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache2D.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCache2D.cs @@ -2,7 +2,7 @@ namespace UnityEngine.Rendering.HighDefinition { - class TextureCache2D : TextureCache + class TextureCache2D : TextureCache { private RenderTexture m_Cache; @@ -19,20 +19,22 @@ bool TextureHasMipmaps(Texture texture) else return ((RenderTexture)texture).useMipMap; } + override public bool IsCreated() { return m_Cache.IsCreated(); } + protected override bool TransferToSlice(CommandBuffer cmd, int sliceIndex, Texture[] textureArray) { // Make sure the array is not null or empty and that the first texture is a render-texture or a texture2D - if(textureArray == null || textureArray.Length == 0 && (!(textureArray[0] is RenderTexture) && !(textureArray[0] is Texture2D))) + if (textureArray == null || textureArray.Length == 0 && (!(textureArray[0] is RenderTexture) && !(textureArray[0] is Texture2D))) { return false; } // First check here is to check if all the sub-texture have the same size - for(int texIDx = 1; texIDx < textureArray.Length; ++texIDx) + for (int texIDx = 1; texIDx < textureArray.Length; ++texIDx) { // We cannot update if the textures if they don't have the same size or not the right type if (textureArray[texIDx].width != textureArray[0].width || textureArray[texIDx].height != textureArray[0].height || (!(textureArray[0] is RenderTexture) && !(textureArray[0] is Texture2D))) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCacheCubemap.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCacheCubemap.cs index 4a4c3cb0ba3..ad9d629bc68 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCacheCubemap.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/Textures/TextureCacheCubemap.cs @@ -167,7 +167,7 @@ internal void ClearCache() { for (int mipIdx = 0; mipIdx < mipCount; ++mipIdx) { - for(int faceIdx = 0; faceIdx < 6; ++faceIdx) + for (int faceIdx = 0; faceIdx < 6; ++faceIdx) { Graphics.SetRenderTarget(m_Cache, mipIdx, (CubemapFace)faceIdx, depthSlice); GL.Clear(false, true, Color.clear); @@ -196,7 +196,7 @@ public void Release() private bool TransferToPanoCache(CommandBuffer cmd, int sliceIndex, Texture[] textureArray) { - for(int texIdx = 0; texIdx < textureArray.Length; ++texIdx) + for (int texIdx = 0; texIdx < textureArray.Length; ++texIdx) { m_CubeBlitMaterial.SetTexture(m_cubeSrcTexPropName, textureArray[texIdx]); for (int m = 0; m < m_NumPanoMipLevels; m++) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs index 15c8c304287..555eb2dc7a7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Core/Utilities/GeometryUtils.cs @@ -194,14 +194,14 @@ public static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 sourceProjection, Vecto var inversion = sourceProjection.inverse; var cps = new Vector4( - Mathf.Sign(clipPlane.x), - Mathf.Sign(clipPlane.y), - 1.0f, - 1.0f); + Mathf.Sign(clipPlane.x), + Mathf.Sign(clipPlane.y), + 1.0f, + 1.0f); var q = inversion * cps; Vector4 M4 = new Vector4(projection[3], projection[7], projection[11], projection[15]); - var c = clipPlane * ((2.0f*Vector4.Dot(M4, q)) / Vector4.Dot(clipPlane, q)); + var c = clipPlane * ((2.0f * Vector4.Dot(M4, q)) / Vector4.Dot(clipPlane, q)); projection[2] = c.x - M4.x; projection[6] = c.y - M4.y; @@ -261,4 +261,3 @@ public static Matrix4x4 CalculateProjectionMatrix(Camera camera) } } // class GeometryUtils } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs index 25da615781f..cfe6c604fc7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs @@ -420,7 +420,7 @@ public ColorPickerDebugMode GetDebugColorPickerMode() return data.colorPickerDebugSettings.colorPickerMode; } - /// + /// /// Returns the current Probe Volume Debug Mode. /// /// Current Probe Volume Debug Mode. @@ -684,7 +684,7 @@ public void SetDebugLightingMode(DebugLightingMode value) data.lightingDebugSettings.debugLightingMode = value; } - /// + /// /// Set the current Probe Volume Debug Mode. /// /// Desired Probe Volume Debug Mode. @@ -693,7 +693,7 @@ internal void SetProbeVolumeDebugMode(ProbeVolumeDebugMode value) data.lightingDebugSettings.probeVolumeDebugMode = value; } - /// + /// /// Set the current Probe Volume Atlas Mode. /// /// Desired Probe Volume Atlas Mode. @@ -799,8 +799,8 @@ float GetSamplerTiming(DebugProfilingType type, ProfilingSampler sampler) { // Find the right accumulated dictionary var accumulatedDictionary = type == DebugProfilingType.CPU ? m_AccumulatedCPUTiming : - type == DebugProfilingType.InlineCPU ? m_AccumulatedInlineCPUTiming : - m_AccumulatedGPUTiming; + type == DebugProfilingType.InlineCPU ? m_AccumulatedInlineCPUTiming : + m_AccumulatedGPUTiming; AccumulatedTiming accTiming = null; if (accumulatedDictionary.TryGetValue(sampler.name, out accTiming)) @@ -820,8 +820,8 @@ float GetSamplerTiming(DebugProfilingType type, ProfilingSampler sampler) // Find the right accumulated dictionary and add it there if not existing yet. var accumulatedDictionary = type == DebugProfilingType.CPU ? m_AccumulatedCPUTiming : - type == DebugProfilingType.InlineCPU ? m_AccumulatedInlineCPUTiming : - m_AccumulatedGPUTiming; + type == DebugProfilingType.InlineCPU ? m_AccumulatedInlineCPUTiming : + m_AccumulatedGPUTiming; foreach (var sampler in m_RecordedSamplers) @@ -849,8 +849,8 @@ float GetSamplerTiming(DebugProfilingType type, ProfilingSampler sampler) // Find the right accumulated dictionary and add it there if not existing yet. var accumulatedDictionary = type == DebugProfilingType.CPU ? m_AccumulatedCPUTiming : - type == DebugProfilingType.InlineCPU ? m_AccumulatedInlineCPUTiming : - m_AccumulatedGPUTiming; + type == DebugProfilingType.InlineCPU ? m_AccumulatedInlineCPUTiming : + m_AccumulatedGPUTiming; foreach (var sampler in m_RecordedSamplersRT) @@ -915,7 +915,6 @@ internal void UpdateAveragedProfilerTimings() m_TimeSinceLastAvgValue = 0.0f; m_AccumulatedFrames = 0; } - } void RegisterDisplayStatsDebug() @@ -979,12 +978,12 @@ void RegisterMaterialDebug() var list = new List(); list.Add(new DebugUI.EnumField { displayName = "Common Material Properties", getter = () => (int)data.materialDebugSettings.debugViewMaterialCommonValue, setter = value => SetDebugViewCommonMaterialProperty((MaterialSharedProperty)value), autoEnum = typeof(MaterialSharedProperty), getIndex = () => (int)data.materialDebugSettings.debugViewMaterialCommonValue, setIndex = value => { data.ResetExclusiveEnumIndices(); data.materialDebugSettings.debugViewMaterialCommonValue = (MaterialSharedProperty)value; } }); - list.Add( new DebugUI.EnumField { displayName = "Material", getter = () => (data.materialDebugSettings.debugViewMaterial[0]) == 0 ? 0 : data.materialDebugSettings.debugViewMaterial[1], setter = value => SetDebugViewMaterial(value), enumNames = MaterialDebugSettings.debugViewMaterialStrings, enumValues = MaterialDebugSettings.debugViewMaterialValues, getIndex = () => data.materialDebugSettings.materialEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.materialDebugSettings.materialEnumIndex = value; } }); - list.Add( new DebugUI.EnumField { displayName = "Engine", getter = () => data.materialDebugSettings.debugViewEngine, setter = value => SetDebugViewEngine(value), enumNames = MaterialDebugSettings.debugViewEngineStrings, enumValues = MaterialDebugSettings.debugViewEngineValues, getIndex = () => data.engineEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.engineEnumIndex = value; } }); - list.Add( new DebugUI.EnumField { displayName = "Attributes", getter = () => (int)data.materialDebugSettings.debugViewVarying, setter = value => SetDebugViewVarying((DebugViewVarying)value), autoEnum = typeof(DebugViewVarying), getIndex = () => data.attributesEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.attributesEnumIndex = value; } }); - list.Add( new DebugUI.EnumField { displayName = "Properties", getter = () => (int)data.materialDebugSettings.debugViewProperties, setter = value => SetDebugViewProperties((DebugViewProperties)value), autoEnum = typeof(DebugViewProperties), getIndex = () => data.propertiesEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.propertiesEnumIndex = value; } }); - list.Add( new DebugUI.EnumField { displayName = "GBuffer", getter = () => data.materialDebugSettings.debugViewGBuffer, setter = value => SetDebugViewGBuffer(value), enumNames = MaterialDebugSettings.debugViewMaterialGBufferStrings, enumValues = MaterialDebugSettings.debugViewMaterialGBufferValues, getIndex = () => data.gBufferEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.gBufferEnumIndex = value; } }); - list.Add( new DebugUI.EnumField { displayName = "Material Validator", getter = () => (int)data.fullScreenDebugMode, setter = value => SetFullScreenDebugMode((FullScreenDebugMode)value), enumNames = s_MaterialFullScreenDebugStrings, enumValues = s_MaterialFullScreenDebugValues, onValueChanged = RefreshMaterialDebug, getIndex = () => data.materialValidatorDebugModeEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.materialValidatorDebugModeEnumIndex = value; } }); + list.Add(new DebugUI.EnumField { displayName = "Material", getter = () => (data.materialDebugSettings.debugViewMaterial[0]) == 0 ? 0 : data.materialDebugSettings.debugViewMaterial[1], setter = value => SetDebugViewMaterial(value), enumNames = MaterialDebugSettings.debugViewMaterialStrings, enumValues = MaterialDebugSettings.debugViewMaterialValues, getIndex = () => data.materialDebugSettings.materialEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.materialDebugSettings.materialEnumIndex = value; } }); + list.Add(new DebugUI.EnumField { displayName = "Engine", getter = () => data.materialDebugSettings.debugViewEngine, setter = value => SetDebugViewEngine(value), enumNames = MaterialDebugSettings.debugViewEngineStrings, enumValues = MaterialDebugSettings.debugViewEngineValues, getIndex = () => data.engineEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.engineEnumIndex = value; } }); + list.Add(new DebugUI.EnumField { displayName = "Attributes", getter = () => (int)data.materialDebugSettings.debugViewVarying, setter = value => SetDebugViewVarying((DebugViewVarying)value), autoEnum = typeof(DebugViewVarying), getIndex = () => data.attributesEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.attributesEnumIndex = value; } }); + list.Add(new DebugUI.EnumField { displayName = "Properties", getter = () => (int)data.materialDebugSettings.debugViewProperties, setter = value => SetDebugViewProperties((DebugViewProperties)value), autoEnum = typeof(DebugViewProperties), getIndex = () => data.propertiesEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.propertiesEnumIndex = value; } }); + list.Add(new DebugUI.EnumField { displayName = "GBuffer", getter = () => data.materialDebugSettings.debugViewGBuffer, setter = value => SetDebugViewGBuffer(value), enumNames = MaterialDebugSettings.debugViewMaterialGBufferStrings, enumValues = MaterialDebugSettings.debugViewMaterialGBufferValues, getIndex = () => data.gBufferEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.gBufferEnumIndex = value; } }); + list.Add(new DebugUI.EnumField { displayName = "Material Validator", getter = () => (int)data.fullScreenDebugMode, setter = value => SetFullScreenDebugMode((FullScreenDebugMode)value), enumNames = s_MaterialFullScreenDebugStrings, enumValues = s_MaterialFullScreenDebugValues, onValueChanged = RefreshMaterialDebug, getIndex = () => data.materialValidatorDebugModeEnumIndex, setIndex = value => { data.ResetExclusiveEnumIndices(); data.materialValidatorDebugModeEnumIndex = value; } }); if (data.fullScreenDebugMode == FullScreenDebugMode.ValidateDiffuseColor || data.fullScreenDebugMode == FullScreenDebugMode.ValidateSpecularColor) { @@ -1089,7 +1088,8 @@ void RegisterLightingDebug() max = () => 4.0f, }); - shadows.children.Add(new DebugUI.BoolField{ + shadows.children.Add(new DebugUI.BoolField + { displayName = "Clear Shadow Atlas", getter = () => data.lightingDebugSettings.clearShadowAtlas, setter = (v) => data.lightingDebugSettings.clearShadowAtlas = v @@ -1109,23 +1109,25 @@ void RegisterLightingDebug() lighting.children.Add(new DebugUI.Foldout { displayName = "Show Lights By Type", - children = { - new DebugUI.BoolField { displayName = "Directional Lights", getter = () => data.lightingDebugSettings.showDirectionalLight, setter = value => data.lightingDebugSettings.showDirectionalLight = value }, - new DebugUI.BoolField { displayName = "Punctual Lights", getter = () => data.lightingDebugSettings.showPunctualLight, setter = value => data.lightingDebugSettings.showPunctualLight = value }, - new DebugUI.BoolField { displayName = "Area Lights", getter = () => data.lightingDebugSettings.showAreaLight, setter = value => data.lightingDebugSettings.showAreaLight = value }, - new DebugUI.BoolField { displayName = "Reflection Probes", getter = () => data.lightingDebugSettings.showReflectionProbe, setter = value => data.lightingDebugSettings.showReflectionProbe = value }, - } + children = + { + new DebugUI.BoolField { displayName = "Directional Lights", getter = () => data.lightingDebugSettings.showDirectionalLight, setter = value => data.lightingDebugSettings.showDirectionalLight = value }, + new DebugUI.BoolField { displayName = "Punctual Lights", getter = () => data.lightingDebugSettings.showPunctualLight, setter = value => data.lightingDebugSettings.showPunctualLight = value }, + new DebugUI.BoolField { displayName = "Area Lights", getter = () => data.lightingDebugSettings.showAreaLight, setter = value => data.lightingDebugSettings.showAreaLight = value }, + new DebugUI.BoolField { displayName = "Reflection Probes", getter = () => data.lightingDebugSettings.showReflectionProbe, setter = value => data.lightingDebugSettings.showReflectionProbe = value }, + } }); lighting.children.Add(new DebugUI.Foldout { displayName = "Probe Volumes", - children = { - new DebugUI.EnumField { displayName = "Probe Volume Debug Mode", getter = () => (int)data.lightingDebugSettings.probeVolumeDebugMode, setter = value => SetProbeVolumeDebugMode((ProbeVolumeDebugMode)value), autoEnum = typeof(ProbeVolumeDebugMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.probeVolumeDebugModeEnumIndex, setIndex = value => data.probeVolumeDebugModeEnumIndex = value }, - new DebugUI.EnumField { displayName = "Probe Volume Atlas Slice Mode", getter = () => (int)data.lightingDebugSettings.probeVolumeAtlasSliceMode, setter = value => SetProbeVolumeAtlasSliceMode((ProbeVolumeAtlasSliceMode)value), autoEnum = typeof(ProbeVolumeAtlasSliceMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.probeVolumeAtlasSliceModeEnumIndex, setIndex = value => data.probeVolumeAtlasSliceModeEnumIndex = value }, - new DebugUI.FloatField { displayName = "Probe Volume Range Min Value", getter = () => data.lightingDebugSettings.probeVolumeMinValue, setter = value => data.lightingDebugSettings.probeVolumeMinValue = value }, - new DebugUI.FloatField { displayName = "Probe Volume Range Max Value", getter = () => data.lightingDebugSettings.probeVolumeMaxValue, setter = value => data.lightingDebugSettings.probeVolumeMaxValue = value }, - } + children = + { + new DebugUI.EnumField { displayName = "Probe Volume Debug Mode", getter = () => (int)data.lightingDebugSettings.probeVolumeDebugMode, setter = value => SetProbeVolumeDebugMode((ProbeVolumeDebugMode)value), autoEnum = typeof(ProbeVolumeDebugMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.probeVolumeDebugModeEnumIndex, setIndex = value => data.probeVolumeDebugModeEnumIndex = value }, + new DebugUI.EnumField { displayName = "Probe Volume Atlas Slice Mode", getter = () => (int)data.lightingDebugSettings.probeVolumeAtlasSliceMode, setter = value => SetProbeVolumeAtlasSliceMode((ProbeVolumeAtlasSliceMode)value), autoEnum = typeof(ProbeVolumeAtlasSliceMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.probeVolumeAtlasSliceModeEnumIndex, setIndex = value => data.probeVolumeAtlasSliceModeEnumIndex = value }, + new DebugUI.FloatField { displayName = "Probe Volume Range Min Value", getter = () => data.lightingDebugSettings.probeVolumeMinValue, setter = value => data.lightingDebugSettings.probeVolumeMinValue = value }, + new DebugUI.FloatField { displayName = "Probe Volume Range Max Value", getter = () => data.lightingDebugSettings.probeVolumeMaxValue, setter = value => data.lightingDebugSettings.probeVolumeMaxValue = value }, + } }); var exposureFoldout = new DebugUI.Foldout @@ -1136,8 +1138,8 @@ void RegisterLightingDebug() new DebugUI.EnumField { displayName = "Debug Mode", - getter = () => (int) data.lightingDebugSettings.exposureDebugMode, - setter = value => SetExposureDebugMode((ExposureDebugMode) value), + getter = () => (int)data.lightingDebugSettings.exposureDebugMode, + setter = value => SetExposureDebugMode((ExposureDebugMode)value), autoEnum = typeof(ExposureDebugMode), onValueChanged = RefreshLightingDebug, getIndex = () => data.exposureDebugModeEnumIndex, setIndex = value => data.exposureDebugModeEnumIndex = value @@ -1155,7 +1157,7 @@ void RegisterLightingDebug() setter = value => data.lightingDebugSettings.displayMaskOnly = value }); } - if (data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.HistogramView) + if (data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.HistogramView) { exposureFoldout.children.Add( new DebugUI.BoolField() @@ -1181,7 +1183,6 @@ void RegisterLightingDebug() getter = () => data.lightingDebugSettings.displayFinalImageHistogramAsRGB, setter = value => data.lightingDebugSettings.displayFinalImageHistogramAsRGB = value }); - } exposureFoldout.children.Add( @@ -1202,7 +1203,8 @@ void RegisterLightingDebug() if (data.lightingDebugSettings.debugLightLayers) { var container = new DebugUI.Container(); - container.children.Add(new DebugUI.BoolField { + container.children.Add(new DebugUI.BoolField + { displayName = "Use Selected Light", getter = () => data.lightingDebugSettings.debugSelectionLightLayers, setter = value => data.lightingDebugSettings.debugSelectionLightLayers = value, @@ -1223,7 +1225,8 @@ void RegisterLightingDebug() } else { - var field = new DebugUI.BitField { + var field = new DebugUI.BitField + { displayName = "Filter Layers", getter = () => data.lightingDebugSettings.debugLightLayersFilterMask, setter = value => data.lightingDebugSettings.debugLightLayersFilterMask = (DebugLightLayersMask)value, @@ -1241,7 +1244,8 @@ void RegisterLightingDebug() { int index = i; var asset = (RenderPipelineManager.currentPipeline as HDRenderPipeline).asset; - layersColor.children.Add( new DebugUI.ColorField { + layersColor.children.Add(new DebugUI.ColorField + { displayName = asset.renderingLayerMaskNames[i], flags = DebugUI.Flags.EditorOnly, getter = () => data.lightingDebugSettings.debugRenderingLayersColors[index], @@ -1340,7 +1344,6 @@ void RegisterLightingDebug() { children = { - new DebugUI.FloatField { displayName = "Debug Mip", getter = () => data.fullscreenDebugMip, setter = value => data.fullscreenDebugMip = value, min = () => 0f, max = () => 1f, incStep = 0.05f }, new DebugUI.BoolField { displayName = "Enable Depth Remap", getter = () => data.enableDebugDepthRemap, setter = value => data.enableDebugDepthRemap = value }, new DebugUI.FloatField { displayName = "Depth range min value", getter = () => data.fullScreenDebugDepthRemap.x, setter = value => data.fullScreenDebugDepthRemap.x = value, min = () => 0f, max = () => 1f, incStep = 0.05f }, @@ -1365,7 +1368,7 @@ void RegisterLightingDebug() { data.fullScreenContactShadowLightIndex = value; }, - min = () => -1, // -1 will display all contact shadow + min = () => - 1, // -1 will display all contact shadow max = () => TiledLightingConstants.s_LightListMaxPrunedEntries - 1 }, } @@ -1410,7 +1413,7 @@ void RegisterLightingDebug() { var container = new DebugUI.Container { - children = + children = { new DebugUI.EnumField { displayName = "Light Volume Debug Type", getter = () => (int)data.lightingDebugSettings.lightVolumeDebugByCategory, setter = value => data.lightingDebugSettings.lightVolumeDebugByCategory = (LightVolumeDebug)value, autoEnum = typeof(LightVolumeDebug), getIndex = () => data.lightVolumeDebugTypeEnumIndex, setIndex = value => data.lightVolumeDebugTypeEnumIndex = value, onValueChanged = RefreshLightingDebug } } @@ -1503,7 +1506,7 @@ void RegisterVolumeDebug() { displayName = "Camera", getter = () => data.volumeDebugSettings.selectedCameraIndex, - setter = value => data.volumeDebugSettings.selectedCameraIndex= value, + setter = value => data.volumeDebugSettings.selectedCameraIndex = value, enumNames = componentNames.ToArray(), enumValues = componentValues.ToArray(), getIndex = () => data.volumeCameraEnumIndex, @@ -1528,7 +1531,7 @@ DebugUI.Widget makeWidget(string name, VolumeParameter param) hdr = p.hdr, showAlpha = p.showAlpha, getter = () => p.value, - setter = _ => { } + setter = _ => {} }; } @@ -1539,7 +1542,7 @@ DebugUI.Widget makeWidget(string name, VolumeParameter param) { displayName = name, getter = () => p.value, - setter = _ => { } + setter = _ => {} }; } @@ -1595,30 +1598,31 @@ DebugUI.Widget makeWidget(string name, VolumeParameter param) var row = new DebugUI.Table.Row() { displayName = "Volume Info", - children = { new DebugUI.Value() { displayName = "Interpolated Value", - getter = () => { - // This getter is called first at each render - // It is used to update the volumes - if (Time.time - timer < refreshRate) - return ""; - timer = Time.deltaTime; - if (data.volumeDebugSettings.selectedCameraIndex != 0) - { - var newVolumes = data.volumeDebugSettings.GetVolumes(); - if (!data.volumeDebugSettings.RefreshVolumes(newVolumes)) - { - for (int i = 0; i < newVolumes.Length; i++) - { - var visible = data.volumeDebugSettings.VolumeHasInfluence(newVolumes[i]); - table.SetColumnVisibility(i + 1, visible); - } - return ""; - } - } - RefreshVolumeDebug(null, false); - return ""; - } - } } + children = { new DebugUI.Value() { + displayName = "Interpolated Value", + getter = () => { + // This getter is called first at each render + // It is used to update the volumes + if (Time.time - timer < refreshRate) + return ""; + timer = Time.deltaTime; + if (data.volumeDebugSettings.selectedCameraIndex != 0) + { + var newVolumes = data.volumeDebugSettings.GetVolumes(); + if (!data.volumeDebugSettings.RefreshVolumes(newVolumes)) + { + for (int i = 0; i < newVolumes.Length; i++) + { + var visible = data.volumeDebugSettings.VolumeHasInfluence(newVolumes[i]); + table.SetColumnVisibility(i + 1, visible); + } + return ""; + } + } + RefreshVolumeDebug(null, false); + return ""; + } + } } }; row.opened = true; @@ -1731,12 +1735,12 @@ void RegisterRenderingDebug() { children = { - new DebugUI.EnumField { displayName = "Terrain Texture", getter = ()=>(int)data.mipMapDebugSettings.terrainTexture, setter = value => data.mipMapDebugSettings.terrainTexture = (DebugMipMapModeTerrainTexture)value, autoEnum = typeof(DebugMipMapModeTerrainTexture), getIndex = () => data.terrainTextureEnumIndex, setIndex = value => data.terrainTextureEnumIndex = value } + new DebugUI.EnumField { displayName = "Terrain Texture", getter = () => (int)data.mipMapDebugSettings.terrainTexture, setter = value => data.mipMapDebugSettings.terrainTexture = (DebugMipMapModeTerrainTexture)value, autoEnum = typeof(DebugMipMapModeTerrainTexture), getIndex = () => data.terrainTextureEnumIndex, setIndex = value => data.terrainTextureEnumIndex = value } } }); } - widgetList.AddRange(new [] + widgetList.AddRange(new[] { new DebugUI.Container { @@ -1753,7 +1757,8 @@ void RegisterRenderingDebug() widgetList.Add(new DebugUI.BoolField { displayName = "False Color Mode", getter = () => data.falseColorDebugSettings.falseColor, setter = value => data.falseColorDebugSettings.falseColor = value, onValueChanged = RefreshRenderingDebug }); if (data.falseColorDebugSettings.falseColor) { - widgetList.Add(new DebugUI.Container{ + widgetList.Add(new DebugUI.Container + { flags = DebugUI.Flags.EditorOnly, children = { @@ -1856,10 +1861,11 @@ void FillFullScreenDebugEnum(ref GUIContent[] strings, ref int[] values, FullScr index++; } } + void FillTileClusterDebugEnum() { string[] names = Enum.GetNames(typeof(TileClusterCategoryDebug)); - for(int i=0; i frameHeight) return false; - // ---- Draw General frame ---- + // ---- Draw General frame ---- if (uv.x < borderSize.x || uv.x >(1.0f - borderSize.x)) { outColor = 0.0; @@ -265,7 +265,7 @@ Shader "Hidden/HDRP/DebugExposure" } float2 GetMinMaxLabelRange(float currEV) - { + { if (_CenterAroundTargetExposure > 0) { int maxAtBothSide = min(0.5f * (ParamExposureLimitMax - ParamExposureLimitMin), 10); @@ -317,7 +317,7 @@ Shader "Hidden/HDRP/DebugExposure" else { binIndex = centerBin; - + locWithinBin = (higherMidPoint - coordOnX); } } @@ -403,7 +403,7 @@ Shader "Hidden/HDRP/DebugExposure" if (isEdgeOfBin) outColor.rgb = 0; } - // ---- Draw labels ---- + // ---- Draw labels ---- // Number of labels int labelCount = 12; @@ -431,7 +431,7 @@ Shader "Hidden/HDRP/DebugExposure" DrawTriangleIndicator(float2(unormCoord.xy), labelFrameHeightScreen, targetEVInRange, halfIndicatorSize, float3(0.9f, 0.75f, 0.1f), outColor); DrawTriangleIndicator(float2(unormCoord.xy), labelFrameHeightScreen, evInRange, halfIndicatorSize, float3(0.15f, 0.15f, 0.1f), outColor); } - // TODO: Add bar? + // TODO: Add bar? //else //{ // if (_CenterAroundTargetExposure > 0) @@ -712,7 +712,7 @@ Shader "Hidden/HDRP/DebugExposure" float binLocMax = 1.0f - safeBand; if (DrawEmptyFrame(uv, float3(0.125, 0.125, 0.125), 0.4, histFrameHeight, heightLabelBar, outputColor)) { - // Draw labels + // Draw labels const int labelCount = 12; int minLabelLocationX = DEBUG_FONT_TEXT_WIDTH * 0.25; int maxLabelLocationX = _ScreenSize.x - (DEBUG_FONT_TEXT_WIDTH * 3); @@ -728,7 +728,7 @@ Shader "Hidden/HDRP/DebugExposure" DrawInteger(labelValue, float3(1.0f, 1.0f, 1.0f), unormCoord, labelLoc, outputColor.rgb); } float remappedX = (((float)unormCoord.x / _ScreenSize.x) - binLocMin) / (binLocMax - binLocMin); - // Draw bins + // Draw bins uint bin = saturate(remappedX) * 255; float4 val = _FullImageHistogram[bin]; val /= float4(maxValue, maxValue, maxValue, maxLuma); @@ -802,7 +802,7 @@ Shader "Hidden/HDRP/DebugExposure" Blend Off Cull Off HLSLPROGRAM - #pragma fragment FragImageHistogram + #pragma fragment FragImageHistogram ENDHLSL } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.compute b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.compute index b5d937b117d..0731ffaadf6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.compute @@ -25,10 +25,10 @@ void LightVolumeGradient(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gro { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - // Fetch the current pixel coordinate - uint2 currentPixelCoordinate = groupId * DEBUG_LIGHT_VOLUME_TILE_SIZE + groupThreadId; + // Fetch the current pixel coordinate + uint2 currentPixelCoordinate = groupId * DEBUG_LIGHT_VOLUME_TILE_SIZE + groupThreadId; - // Lightcount at this pixel + // Lightcount at this pixel float lightCount = _DebugLightCountBuffer[COORD_TEXTURE2D_X(currentPixelCoordinate)].r; // Tonemap this pixel value @@ -48,10 +48,10 @@ void LightVolumeColors(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 group { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - // Fetch the current pixel coordinate - uint2 currentPixelCoordinate = groupId * DEBUG_LIGHT_VOLUME_TILE_SIZE + groupThreadId; + // Fetch the current pixel coordinate + uint2 currentPixelCoordinate = groupId * DEBUG_LIGHT_VOLUME_TILE_SIZE + groupThreadId; - // Lightcount at this pixel + // Lightcount at this pixel float lightCount = _DebugLightCountBuffer[COORD_TEXTURE2D_X(currentPixelCoordinate)].r; // Look around this pixel to check if this should be displayed as a border @@ -59,18 +59,18 @@ void LightVolumeColors(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 group bool isBorder = false; for (float radiusX = -_BorderRadius; radiusX <= _BorderRadius; ++radiusX) { - for (float radiusY = -_BorderRadius; radiusY <= _BorderRadius; ++radiusY) - { - // Compute the target pixel - int2 targetpixel = int2((uint)currentPixelCoordinate.x + radiusX, (uint)currentPixelCoordinate.y + radiusY); - float neighborLightCount = _DebugLightCountBuffer[COORD_TEXTURE2D_X(targetpixel)].r; - maxLightCount = max(maxLightCount, neighborLightCount); - if(neighborLightCount != lightCount) - { - isBorder = true; + for (float radiusY = -_BorderRadius; radiusY <= _BorderRadius; ++radiusY) + { + // Compute the target pixel + int2 targetpixel = int2((uint)currentPixelCoordinate.x + radiusX, (uint)currentPixelCoordinate.y + radiusY); + float neighborLightCount = _DebugLightCountBuffer[COORD_TEXTURE2D_X(targetpixel)].r; + maxLightCount = max(maxLightCount, neighborLightCount); + if(neighborLightCount != lightCount) + { + isBorder = true; break; - } - } + } + } } // Tonemap the light count diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.cs index c954fdff596..e0228c93a5b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugLightVolumes.cs @@ -116,16 +116,15 @@ public RenderLightVolumesParameters PrepareLightVolumeParameters(HDCamera hdCame } public static void RenderLightVolumes(CommandBuffer cmd, - in RenderLightVolumesParameters parameters, - RenderTargetIdentifier[] accumulationMRT, // [0] = m_LightCountBuffer, [1] m_ColorAccumulationBuffer - RTHandle lightCountBuffer, - RTHandle colorAccumulationBuffer, - RTHandle debugLightVolumesTexture, - RTHandle depthBuffer, - RTHandle destination, - MaterialPropertyBlock mpb) + in RenderLightVolumesParameters parameters, + RenderTargetIdentifier[] accumulationMRT, // [0] = m_LightCountBuffer, [1] m_ColorAccumulationBuffer + RTHandle lightCountBuffer, + RTHandle colorAccumulationBuffer, + RTHandle debugLightVolumesTexture, + RTHandle depthBuffer, + RTHandle destination, + MaterialPropertyBlock mpb) { - if (parameters.lightOverlapEnabled) { // We only need the accumulation buffer, not the color (we only disply the outline of the light shape in this mode). @@ -224,7 +223,7 @@ static void RenderLightVolume( { Matrix4x4 positionMat = Matrix4x4.Translate(currentLegacyLight.transform.position); - switch(currentHDRLight.ComputeLightType(currentLegacyLight)) + switch (currentHDRLight.ComputeLightType(currentLegacyLight)) { case HDLightType.Point: mpb.SetColor(_ColorShaderID, new Color(0.0f, 0.5f, 0.0f, 1.0f)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs index 69077e181b7..aa9a7385892 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs @@ -103,7 +103,6 @@ public enum DebugLightLayersMask } - static class DebugLightHierarchyExtensions { public static bool IsEnabledFor( @@ -188,7 +187,6 @@ public enum ExposureDebugMode FinalImageHistogramView, /// Visualize the scene color weighted as the metering mode selected. MeteringWeighted, - } @@ -204,7 +202,7 @@ internal enum ProbeVolumeDebugMode VisualizeValidity } - /// + /// /// Probe Volume Atlas Slicing Modes. /// [GenerateHLSL] @@ -223,7 +221,7 @@ internal enum ProbeVolumeAtlasSliceMode OctahedralDepth } - /// + /// /// Lighting Debug Settings. /// [Serializable] @@ -266,13 +264,13 @@ public bool IsDebugDisplayEnabled() public ShadowMapDebugMode shadowDebugMode = ShadowMapDebugMode.None; /// Current Probe Volume Debug Mode. [SerializeField] internal ProbeVolumeDebugMode probeVolumeDebugMode = ProbeVolumeDebugMode.None; - /// Current Probe Volume Atlas Slicing Mode. + /// Current Probe Volume Atlas Slicing Mode. [SerializeField] internal ProbeVolumeAtlasSliceMode probeVolumeAtlasSliceMode = ProbeVolumeAtlasSliceMode.IrradianceSH00; - /// The minimum display threshold for atlas slices. + /// The minimum display threshold for atlas slices. [SerializeField] internal float probeVolumeMinValue = 0.0f; - /// The maximum display threshold for atlas slices. + /// The maximum display threshold for atlas slices. [SerializeField] internal float probeVolumeMaxValue = 1.0f; - /// True if Shadow Map debug mode should be displayed for the currently selected light. + /// True if Shadow Map debug mode should be displayed for the currently selected light. public bool shadowDebugUseSelection = false; /// Index in the list of currently visible lights of the shadow map to display. public uint shadowMapIndex = 0; @@ -375,10 +373,10 @@ public bool IsDebugDisplayEnabled() // Internal APIs internal bool IsDebugDisplayRemovePostprocess() { - return debugLightingMode == DebugLightingMode.LuxMeter || debugLightingMode == DebugLightingMode.LuminanceMeter || - debugLightingMode == DebugLightingMode.VisualizeCascade || debugLightingMode == DebugLightingMode.VisualizeShadowMasks || - debugLightingMode == DebugLightingMode.IndirectDiffuseOcclusion || debugLightingMode == DebugLightingMode.IndirectSpecularOcclusion || - debugLightingMode == DebugLightingMode.ProbeVolume; + return debugLightingMode == DebugLightingMode.LuxMeter || debugLightingMode == DebugLightingMode.LuminanceMeter || + debugLightingMode == DebugLightingMode.VisualizeCascade || debugLightingMode == DebugLightingMode.VisualizeShadowMasks || + debugLightingMode == DebugLightingMode.IndirectDiffuseOcclusion || debugLightingMode == DebugLightingMode.IndirectSpecularOcclusion || + debugLightingMode == DebugLightingMode.ProbeVolume; } internal static Vector4[] GetDefaultRenderingLayersColorPalette() diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialDebug.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialDebug.cs index a3c1ef995e5..1a2d2cd5204 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialDebug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialDebug.cs @@ -175,7 +175,7 @@ static void FillWithProperties(Type type, ref List debugViewMaterial if (Attribute.IsDefined(field, typeof(PackingAttribute))) { var packingAttributes = (PackingAttribute[])field.GetCustomAttributes(typeof(PackingAttribute), false); - foreach(PackingAttribute packAttr in packingAttributes) + foreach (PackingAttribute packAttr in packingAttributes) { displayNames.AddRange(packAttr.displayNames); } @@ -275,7 +275,7 @@ static void BuildDebugRepresentation() List materialItems = GetAllMaterialDatas(); // Init list - List < GUIContent> debugViewMaterialStringsList = new List(); + List debugViewMaterialStringsList = new List(); List debugViewMaterialValuesList = new List(); List debugViewEngineStringsList = new List(); List debugViewEngineValuesList = new List(); @@ -449,7 +449,8 @@ static void BuildDebugRepresentation() /// /// Current Debug View Material. /// - public int[] debugViewMaterial { + public int[] debugViewMaterial + { get => m_DebugViewMaterial; internal set { @@ -619,7 +620,7 @@ public void SetDebugViewGBuffer(int value) /// True if Material debug is enabled. public bool IsDebugViewMaterialEnabled() { - int size = m_DebugViewMaterial?[0] ?? 0; + int size = m_DebugViewMaterial ? [0] ?? 0; bool enabled = false; for (int i = 1; i <= size; ++i) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialError.shader b/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialError.shader index ef0badb4c15..60c312caa59 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialError.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialError.shader @@ -1,4 +1,4 @@ -Shader "Hidden/HDRP/MaterialError" +Shader "Hidden/HDRP/MaterialError" { SubShader { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/RayCountManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/RayCountManager.cs index 05a5db62144..f47e21d3050 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/RayCountManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/RayCountManager.cs @@ -69,7 +69,7 @@ public void Init(HDRenderPipelineRayTracingResources rayTracingResources) m_ReducedRayCountBuffer2 = new ComputeBuffer((int)RayCountValues.Count + 1, sizeof(uint)); // Initialize the CPU ray count (Optional) - for(int i = 0; i < (int)RayCountValues.Count; ++i) + for (int i = 0; i < (int)RayCountValues.Count; ++i) { m_ReducedRayCountValues[i] = 0; } @@ -227,7 +227,6 @@ public void EvaluateRayCount(CommandBuffer cmd, HDCamera camera) // Enqueue an Async read-back for the single value AsyncGPUReadbackRequest singleReadBack = AsyncGPUReadback.Request(m_ReducedRayCountBuffer2, (int)RayCountValues.Count * sizeof(uint), 0); rayCountReadbacks.Enqueue(singleReadBack); - } } } @@ -240,14 +239,14 @@ public uint GetRaysPerFrame(RayCountValues rayCountValue) } else { - while(rayCountReadbacks.Peek().done || rayCountReadbacks.Peek().hasError == true) + while (rayCountReadbacks.Peek().done || rayCountReadbacks.Peek().hasError == true) { // If this has an error, just skip it if (!rayCountReadbacks.Peek().hasError) { // Grab the native array from this readback NativeArray sampleCount = rayCountReadbacks.Peek().GetData(); - for(int i = 0; i < (int)RayCountValues.Count; ++i) + for (int i = 0; i < (int)RayCountValues.Count; ++i) { m_ReducedRayCountValues[i] = sampleCount[i]; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Debug/VolumeDebug.cs b/com.unity.render-pipelines.high-definition/Runtime/Debug/VolumeDebug.cs index 67f825c6333..5351a93011f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Debug/VolumeDebug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Debug/VolumeDebug.cs @@ -131,9 +131,9 @@ static public List componentTypes if (s_ComponentTypes == null) { s_ComponentTypes = VolumeManager.instance.baseComponentTypes - .Where(t => !t.IsDefined(typeof(VolumeComponentDeprecated), false)) - .OrderBy(t => ComponentDisplayName(t)) - .ToList(); + .Where(t => !t.IsDefined(typeof(VolumeComponentDeprecated), false)) + .OrderBy(t => ComponentDisplayName(t)) + .ToList(); } return s_ComponentTypes; } @@ -164,7 +164,6 @@ internal static void UnRegisterCamera(HDAdditionalCameraData camera) cameras.Remove(camera); } - internal VolumeParameter GetParameter(VolumeComponent component, FieldInfo field) { return (VolumeParameter)field.GetValue(component); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs index 51277988dca..af4a832a07d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/Fog.cs @@ -98,7 +98,7 @@ public FogControl fogControlMode /// Number of slices of the volumetric buffer (3D texture) along the camera's focal axis. [Tooltip("Number of slices of the volumetric buffer (3D texture) along the camera's focal axis.")] public ClampedIntParameter volumeSliceCount = new ClampedIntParameter(64, 1, maxFogSliceCount); - + /// Defines the performance to quality ratio of the volumetric fog. A value of 0 being the least resource-intensive and a value of 1 being the highest quality. /// Try to minimize this value to find a compromise between quality and performance. public float volumetricFogBudget @@ -250,7 +250,7 @@ public enum FogColorMode sealed class FogTypeParameter : VolumeParameter { public FogTypeParameter(FogType value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} } /// @@ -265,7 +265,7 @@ public sealed class FogColorParameter : VolumeParameter /// Fog Color Parameter. /// Initial override state. public FogColorParameter(FogColorMode value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} } /// @@ -295,7 +295,7 @@ public sealed class FogControlParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public FogControlParameter(FogControl value, bool overrideState = false) : base(value, overrideState) { } + public FogControlParameter(FogControl value, bool overrideState = false) : base(value, overrideState) {} } /// @@ -332,6 +332,6 @@ public sealed class FogDenoisingModeParameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. - public FogDenoisingModeParameter(FogDenoisingMode value, bool overrideState = false) : base(value, overrideState) { } + public FogDenoisingModeParameter(FogDenoisingMode value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl index 6908c059203..c5a59b10c18 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/AtmosphericScattering/ShaderVariablesAtmosphericScattering.hlsl @@ -5,4 +5,3 @@ TEXTURECUBE_ARRAY(_SkyTexture); #define _MipFogMaxMip _MipFogParameters.z #define _FogColor _FogColor - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/DiffusionProfileOverride.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/DiffusionProfileOverride.cs index addd4b7f7ba..0367d6dbc7d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/DiffusionProfileOverride.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/DiffusionProfileOverride.cs @@ -15,6 +15,6 @@ sealed class DiffusionProfileOverride : VolumeComponent sealed class DiffusionProfileSettingsParameter : VolumeParameter { public DiffusionProfileSettingsParameter(DiffusionProfileSettings[] value, bool overrideState = true) - : base(value, overrideState) { } + : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/GlobalIlluminationUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/GlobalIlluminationUtils.cs index a0a581772d1..12c066160df 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/GlobalIlluminationUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/GlobalIlluminationUtils.cs @@ -93,82 +93,82 @@ public static bool LightDataGIExtract(Light light, ref LightDataGI lightDataGI) switch (add.spotLightShape) { case SpotLightShape.Cone: - { - SpotLight spot; - spot.instanceID = light.GetInstanceID(); - spot.shadow = light.shadows != LightShadows.None; - spot.mode = lightMode; + { + SpotLight spot; + spot.instanceID = light.GetInstanceID(); + spot.shadow = light.shadows != LightShadows.None; + spot.mode = lightMode; #if UNITY_EDITOR - spot.sphereRadius = light.shadows != LightShadows.None ? light.shadowRadius : 0.0f; + spot.sphereRadius = light.shadows != LightShadows.None ? light.shadowRadius : 0.0f; #else - spot.sphereRadius = 0.0f; + spot.sphereRadius = 0.0f; #endif - spot.position = light.transform.position; - spot.orientation = light.transform.rotation; - spot.color = directColor; - spot.indirectColor = indirectColor; - spot.range = light.range; - spot.coneAngle = light.spotAngle * Mathf.Deg2Rad; - spot.innerConeAngle = light.spotAngle * Mathf.Deg2Rad * add.innerSpotPercent01; - spot.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation; - spot.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle; - lightDataGI.Init(ref spot, ref cookie); - lightDataGI.shape1 = (float)AngularFalloffType.AnalyticAndInnerAngle; - if (light.cookie != null) - lightDataGI.cookieID = light.cookie.GetInstanceID(); - else if (add.IESSpot != null) - lightDataGI.cookieID = add.IESSpot.GetInstanceID(); - else - lightDataGI.cookieID = 0; - } - break; + spot.position = light.transform.position; + spot.orientation = light.transform.rotation; + spot.color = directColor; + spot.indirectColor = indirectColor; + spot.range = light.range; + spot.coneAngle = light.spotAngle * Mathf.Deg2Rad; + spot.innerConeAngle = light.spotAngle * Mathf.Deg2Rad * add.innerSpotPercent01; + spot.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation; + spot.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle; + lightDataGI.Init(ref spot, ref cookie); + lightDataGI.shape1 = (float)AngularFalloffType.AnalyticAndInnerAngle; + if (light.cookie != null) + lightDataGI.cookieID = light.cookie.GetInstanceID(); + else if (add.IESSpot != null) + lightDataGI.cookieID = add.IESSpot.GetInstanceID(); + else + lightDataGI.cookieID = 0; + } + break; case SpotLightShape.Pyramid: - { - SpotLightPyramidShape pyramid; - pyramid.instanceID = light.GetInstanceID(); - pyramid.shadow = light.shadows != LightShadows.None; - pyramid.mode = lightMode; - pyramid.position = light.transform.position; - pyramid.orientation = light.transform.rotation; - pyramid.color = directColor; - pyramid.indirectColor = indirectColor; - pyramid.range = light.range; - pyramid.angle = light.spotAngle * Mathf.Deg2Rad; - pyramid.aspectRatio = add.aspectRatio; - pyramid.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation; - lightDataGI.Init(ref pyramid, ref cookie); - if (light.cookie != null) - lightDataGI.cookieID = light.cookie.GetInstanceID(); - else if (add.IESSpot != null) - lightDataGI.cookieID = add.IESSpot.GetInstanceID(); - else - lightDataGI.cookieID = 0; - } - break; + { + SpotLightPyramidShape pyramid; + pyramid.instanceID = light.GetInstanceID(); + pyramid.shadow = light.shadows != LightShadows.None; + pyramid.mode = lightMode; + pyramid.position = light.transform.position; + pyramid.orientation = light.transform.rotation; + pyramid.color = directColor; + pyramid.indirectColor = indirectColor; + pyramid.range = light.range; + pyramid.angle = light.spotAngle * Mathf.Deg2Rad; + pyramid.aspectRatio = add.aspectRatio; + pyramid.falloff = add.applyRangeAttenuation ? FalloffType.InverseSquared : FalloffType.InverseSquaredNoRangeAttenuation; + lightDataGI.Init(ref pyramid, ref cookie); + if (light.cookie != null) + lightDataGI.cookieID = light.cookie.GetInstanceID(); + else if (add.IESSpot != null) + lightDataGI.cookieID = add.IESSpot.GetInstanceID(); + else + lightDataGI.cookieID = 0; + } + break; case SpotLightShape.Box: - { - SpotLightBoxShape box; - box.instanceID = light.GetInstanceID(); - box.shadow = light.shadows != LightShadows.None; - box.mode = lightMode; - box.position = light.transform.position; - box.orientation = light.transform.rotation; - box.color = directColor; - box.indirectColor = indirectColor; - box.range = light.range; - box.width = add.shapeWidth; - box.height = add.shapeHeight; - lightDataGI.Init(ref box, ref cookie); - if (light.cookie != null) - lightDataGI.cookieID = light.cookie.GetInstanceID(); - else if (add.IESSpot != null) - lightDataGI.cookieID = add.IESSpot.GetInstanceID(); - else - lightDataGI.cookieID = 0; - } - break; + { + SpotLightBoxShape box; + box.instanceID = light.GetInstanceID(); + box.shadow = light.shadows != LightShadows.None; + box.mode = lightMode; + box.position = light.transform.position; + box.orientation = light.transform.rotation; + box.color = directColor; + box.indirectColor = indirectColor; + box.range = light.range; + box.width = add.shapeWidth; + box.height = add.shapeHeight; + lightDataGI.Init(ref box, ref cookie); + if (light.cookie != null) + lightDataGI.cookieID = light.cookie.GetInstanceID(); + else if (add.IESSpot != null) + lightDataGI.cookieID = add.IESSpot.GetInstanceID(); + else + lightDataGI.cookieID = 0; + } + break; default: Debug.Assert(false, "Encountered an unknown SpotLightShape."); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/IndirectLightingController.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/IndirectLightingController.cs index e7ca7212754..7d6379cac26 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/IndirectLightingController.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/IndirectLightingController.cs @@ -57,7 +57,7 @@ public sealed class LightLayerEnumParameter : VolumeParameter /// Light Layer Enum parameter. /// Initial override value. public LightLayerEnumParameter(LightLayerEnum value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.Migration.cs index af0f8ca6b1c..5d104353b2f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.Migration.cs @@ -61,123 +61,123 @@ Version IVersionable.version private static readonly MigrationDescription k_HDLightMigrationSteps = MigrationDescription.New( - MigrationStep.New(Version.ShadowNearPlane, (HDAdditionalLightData data) => + MigrationStep.New(Version.ShadowNearPlane, (HDAdditionalLightData data) => + { + // Added ShadowNearPlane to HDRP additional light data, we don't use Light.shadowNearPlane anymore + // ShadowNearPlane have been move to HDRP as default legacy unity clamp it to 0.1 and we need to be able to go below that + data.shadowNearPlane = data.legacyLight.shadowNearPlane; + }), + MigrationStep.New(Version.LightLayer, (HDAdditionalLightData data) => + { + // Migrate HDAdditionalLightData.lightLayer to Light.renderingLayerMask + data.legacyLight.renderingLayerMask = LightLayerToRenderingLayerMask((int)data.m_LightLayers, data.legacyLight.renderingLayerMask); + }), + MigrationStep.New(Version.ShadowLayer, (HDAdditionalLightData data) => + { + // Added the ShadowLayer + // When we upgrade the option to decouple light and shadow layers will be disabled + // so we can sync the shadow layer mask (from the legacyLight) and the new light layer mask + data.lightlayersMask = (LightLayerEnum)RenderingLayerMaskToLightLayer(data.legacyLight.renderingLayerMask); + }), + MigrationStep.New(Version.ShadowResolution, (HDAdditionalLightData data) => + { + var additionalShadow = data.GetComponent(); + if (additionalShadow != null) { - // Added ShadowNearPlane to HDRP additional light data, we don't use Light.shadowNearPlane anymore - // ShadowNearPlane have been move to HDRP as default legacy unity clamp it to 0.1 and we need to be able to go below that - data.shadowNearPlane = data.legacyLight.shadowNearPlane; - }), - MigrationStep.New(Version.LightLayer, (HDAdditionalLightData data) => - { - // Migrate HDAdditionalLightData.lightLayer to Light.renderingLayerMask - data.legacyLight.renderingLayerMask = LightLayerToRenderingLayerMask((int)data.m_LightLayers, data.legacyLight.renderingLayerMask); - }), - MigrationStep.New(Version.ShadowLayer, (HDAdditionalLightData data) => - { - // Added the ShadowLayer - // When we upgrade the option to decouple light and shadow layers will be disabled - // so we can sync the shadow layer mask (from the legacyLight) and the new light layer mask - data.lightlayersMask = (LightLayerEnum)RenderingLayerMaskToLightLayer(data.legacyLight.renderingLayerMask); - }), - MigrationStep.New(Version.ShadowResolution, (HDAdditionalLightData data) => - { - var additionalShadow = data.GetComponent(); - if (additionalShadow != null) - { - data.m_ObsoleteCustomShadowResolution = additionalShadow.customResolution; - data.m_ObsoleteContactShadows = additionalShadow.contactShadows; + data.m_ObsoleteCustomShadowResolution = additionalShadow.customResolution; + data.m_ObsoleteContactShadows = additionalShadow.contactShadows; - data.shadowDimmer = additionalShadow.shadowDimmer; - data.volumetricShadowDimmer = additionalShadow.volumetricShadowDimmer; - data.shadowFadeDistance = additionalShadow.shadowFadeDistance; - data.shadowTint = additionalShadow.shadowTint; - data.normalBias = additionalShadow.normalBias; - data.shadowUpdateMode = additionalShadow.shadowUpdateMode; - data.shadowCascadeRatios = additionalShadow.shadowCascadeRatios; - data.shadowCascadeBorders = additionalShadow.shadowCascadeBorders; - data.shadowAlgorithm = additionalShadow.shadowAlgorithm; - data.shadowVariant = additionalShadow.shadowVariant; - data.shadowPrecision = additionalShadow.shadowPrecision; - CoreUtils.Destroy(additionalShadow); - } + data.shadowDimmer = additionalShadow.shadowDimmer; + data.volumetricShadowDimmer = additionalShadow.volumetricShadowDimmer; + data.shadowFadeDistance = additionalShadow.shadowFadeDistance; + data.shadowTint = additionalShadow.shadowTint; + data.normalBias = additionalShadow.normalBias; + data.shadowUpdateMode = additionalShadow.shadowUpdateMode; + data.shadowCascadeRatios = additionalShadow.shadowCascadeRatios; + data.shadowCascadeBorders = additionalShadow.shadowCascadeBorders; + data.shadowAlgorithm = additionalShadow.shadowAlgorithm; + data.shadowVariant = additionalShadow.shadowVariant; + data.shadowPrecision = additionalShadow.shadowPrecision; + CoreUtils.Destroy(additionalShadow); + } - data.shadowResolution.@override = data.m_ObsoleteCustomShadowResolution; - switch (data.m_ObsoleteShadowResolutionTier) - { - case ShadowResolutionTier.Low: data.shadowResolution.level = 0; break; - case ShadowResolutionTier.Medium: data.shadowResolution.level = 1; break; - case ShadowResolutionTier.High: data.shadowResolution.level = 2; break; - case ShadowResolutionTier.VeryHigh: data.shadowResolution.level = 3; break; - } - data.shadowResolution.useOverride = !data.m_ObsoleteUseShadowQualitySettings; - data.useContactShadow.@override = data.m_ObsoleteContactShadows; - }), - MigrationStep.New(Version.RemoveAdditionalShadowData, (HDAdditionalLightData data) => + data.shadowResolution.@override = data.m_ObsoleteCustomShadowResolution; + switch (data.m_ObsoleteShadowResolutionTier) { - var shadow = data.GetComponent(); - if (shadow != null) - CoreUtils.Destroy(shadow); - }), - MigrationStep.New(Version.AreaLightShapeTypeLogicIsolation, (HDAdditionalLightData data) => + case ShadowResolutionTier.Low: data.shadowResolution.level = 0; break; + case ShadowResolutionTier.Medium: data.shadowResolution.level = 1; break; + case ShadowResolutionTier.High: data.shadowResolution.level = 2; break; + case ShadowResolutionTier.VeryHigh: data.shadowResolution.level = 3; break; + } + data.shadowResolution.useOverride = !data.m_ObsoleteUseShadowQualitySettings; + data.useContactShadow.@override = data.m_ObsoleteContactShadows; + }), + MigrationStep.New(Version.RemoveAdditionalShadowData, (HDAdditionalLightData data) => + { + var shadow = data.GetComponent(); + if (shadow != null) + CoreUtils.Destroy(shadow); + }), + MigrationStep.New(Version.AreaLightShapeTypeLogicIsolation, (HDAdditionalLightData data) => + { + // It is now mixed in an other Enum: PointLightHDType + // As it is int that live under Enum and used for serialization, + // there is no serialization issue but we must move datas where they should be. + switch ((LightTypeExtent)data.m_PointlightHDType) { - // It is now mixed in an other Enum: PointLightHDType - // As it is int that live under Enum and used for serialization, - // there is no serialization issue but we must move datas where they should be. - switch ((LightTypeExtent)data.m_PointlightHDType) - { - case LightTypeExtent.Punctual: - data.m_PointlightHDType = PointLightHDType.Punctual; - break; - case LightTypeExtent.Rectangle: - data.m_PointlightHDType = PointLightHDType.Area; - data.m_AreaLightShape = AreaLightShape.Rectangle; - break; - case LightTypeExtent.Tube: - data.m_PointlightHDType = PointLightHDType.Area; - data.m_AreaLightShape = AreaLightShape.Tube; - break; + case LightTypeExtent.Punctual: + data.m_PointlightHDType = PointLightHDType.Punctual; + break; + case LightTypeExtent.Rectangle: + data.m_PointlightHDType = PointLightHDType.Area; + data.m_AreaLightShape = AreaLightShape.Rectangle; + break; + case LightTypeExtent.Tube: + data.m_PointlightHDType = PointLightHDType.Area; + data.m_AreaLightShape = AreaLightShape.Tube; + break; //No other AreaLight types where supported at this time - } - }), - MigrationStep.New(Version.PCSSUIUpdate, (HDAdditionalLightData data) => - { - // The min filter size is now in the [0..1] range when user facing - data.minFilterSize = data.minFilterSize * 1000.0f; - }), - MigrationStep.New(Version.MoveEmissionMesh, (HDAdditionalLightData data) => + } + }), + MigrationStep.New(Version.PCSSUIUpdate, (HDAdditionalLightData data) => + { + // The min filter size is now in the [0..1] range when user facing + data.minFilterSize = data.minFilterSize * 1000.0f; + }), + MigrationStep.New(Version.MoveEmissionMesh, (HDAdditionalLightData data) => + { + MeshRenderer emissiveMesh = data.GetComponent(); + bool emissiveMeshWasHere = emissiveMesh != null; + ShadowCastingMode oldShadowCastingMode = default; + MotionVectorGenerationMode oldMotionVectorMode = default; + if (emissiveMeshWasHere) { - MeshRenderer emissiveMesh = data.GetComponent(); - bool emissiveMeshWasHere = emissiveMesh != null; - ShadowCastingMode oldShadowCastingMode = default; - MotionVectorGenerationMode oldMotionVectorMode = default; - if (emissiveMeshWasHere) - { - oldShadowCastingMode = emissiveMesh.shadowCastingMode; - oldMotionVectorMode = emissiveMesh.motionVectorGenerationMode; - } + oldShadowCastingMode = emissiveMesh.shadowCastingMode; + oldMotionVectorMode = emissiveMesh.motionVectorGenerationMode; + } - CoreUtils.Destroy(data.GetComponent()); - CoreUtils.Destroy(emissiveMesh); - - if (emissiveMeshWasHere) - { - data.m_AreaLightEmissiveMeshShadowCastingMode = oldShadowCastingMode; - data.m_AreaLightEmissiveMeshMotionVectorGenerationMode = oldMotionVectorMode; - } - }), - MigrationStep.New(Version.EnableApplyRangeAttenuationOnBoxLight, (HDAdditionalLightData data) => + CoreUtils.Destroy(data.GetComponent()); + CoreUtils.Destroy(emissiveMesh); + + if (emissiveMeshWasHere) + { + data.m_AreaLightEmissiveMeshShadowCastingMode = oldShadowCastingMode; + data.m_AreaLightEmissiveMeshMotionVectorGenerationMode = oldMotionVectorMode; + } + }), + MigrationStep.New(Version.EnableApplyRangeAttenuationOnBoxLight, (HDAdditionalLightData data) => + { + // When enabling range attenuation for box light, the default value was "true" + // causing a migration issue. So when we migrate we setup applyRangeAttenuation to false + // if we are a box light to keep the previous behavior + if (data.type == HDLightType.Spot) { - // When enabling range attenuation for box light, the default value was "true" - // causing a migration issue. So when we migrate we setup applyRangeAttenuation to false - // if we are a box light to keep the previous behavior - if (data.type == HDLightType.Spot) + if (data.spotLightShape == SpotLightShape.Box) { - if (data.spotLightShape == SpotLightShape.Box) - { - data.applyRangeAttenuation = false; - } + data.applyRangeAttenuation = false; } - }) + } + }) ); #pragma warning restore 0618, 0612 diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs index f163b5f575a..47cf4cbdfad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Light/HDAdditionalLightData.cs @@ -117,7 +117,7 @@ public static BoolScalableSetting UseContactShadow(HDRenderPipelineAsset hdrp) = /// List of the lights that overlaps when the OverlapLight scene view mode is enabled internal static HashSet s_overlappingHDLights = new HashSet(); -#region HDLight Properties API + #region HDLight Properties API [SerializeField, FormerlySerializedAs("displayLightIntensity")] float m_Intensity; @@ -221,7 +221,7 @@ public float spotIESCutoffPercent /// /// Get the inner spot radius between 0 and 1. /// - public float spotIESCutoffPercent01 => spotIESCutoffPercent/100f; + public float spotIESCutoffPercent01 => spotIESCutoffPercent / 100f; [Range(0.0f, 16.0f)] [SerializeField, FormerlySerializedAs("lightDimmer")] @@ -1442,12 +1442,12 @@ public ShadowUpdateMode shadowUpdateMode if (m_ShadowUpdateMode != ShadowUpdateMode.EveryFrame && value == ShadowUpdateMode.EveryFrame) { - if(!preserveCachedShadow) + if (!preserveCachedShadow) { HDShadowManager.cachedShadowManager.EvictLight(this); } } - else if(legacyLight.shadows != LightShadows.None && m_ShadowUpdateMode == ShadowUpdateMode.EveryFrame && value != ShadowUpdateMode.EveryFrame) + else if (legacyLight.shadows != LightShadows.None && m_ShadowUpdateMode == ShadowUpdateMode.EveryFrame && value != ShadowUpdateMode.EveryFrame) { HDShadowManager.cachedShadowManager.RegisterLight(this); } @@ -1481,7 +1481,7 @@ public bool updateUponLightMovement get => m_UpdateShadowOnLightMovement; set { - if(m_UpdateShadowOnLightMovement != value) + if (m_UpdateShadowOnLightMovement != value) { if (m_UpdateShadowOnLightMovement) HDShadowManager.cachedShadowManager.RegisterTransformToCache(this); @@ -1595,9 +1595,9 @@ public bool affectsVolumetric set => useVolumetric = value; } -#endregion + #endregion -#region Internal API for moving shadow datas from AdditionalShadowData to HDAdditionalLightData + #region Internal API for moving shadow datas from AdditionalShadowData to HDAdditionalLightData [SerializeField] float[] m_ShadowCascadeRatios = new float[3] { 0.05f, 0.2f, 0.3f }; @@ -1639,7 +1639,7 @@ internal int shadowPrecision set => m_ShadowPrecision = value; } -#endregion + #endregion #pragma warning disable 0414 // The field '...' is assigned but its value is never used, these fields are used by the inspector // This is specific for the LightEditor GUI and not use at runtime @@ -1704,7 +1704,7 @@ void CreateChildEmissiveMeshViewerIfNeeded() { #if UNITY_EDITOR if (PrefabUtility.IsPartOfPrefabAsset(this)) - return; + return; #endif bool here = m_ChildEmissiveMeshViewer != null && !m_ChildEmissiveMeshViewer.Equals(null); @@ -1841,7 +1841,7 @@ public int areaLightEmissiveMeshLayer void OnDestroy() { - if(lightIdxForCachedShadows >= 0) // If it is within the cached system we need to evict it. + if (lightIdxForCachedShadows >= 0) // If it is within the cached system we need to evict it. HDShadowManager.cachedShadowManager.EvictLight(this); } @@ -1870,8 +1870,8 @@ int GetShadowRequestCount(HDShadowSettings shadowSettings, HDLightType lightType return lightType == HDLightType.Point ? 6 : lightType == HDLightType.Directional - ? shadowSettings.cascadeShadowSplitCount.value - : 1; + ? shadowSettings.cascadeShadowSplitCount.value + : 1; } /// @@ -1879,7 +1879,7 @@ int GetShadowRequestCount(HDShadowSettings shadowSettings, HDLightType lightType /// public void RequestShadowMapRendering() { - if(shadowUpdateMode == ShadowUpdateMode.OnDemand) + if (shadowUpdateMode == ShadowUpdateMode.OnDemand) HDShadowManager.cachedShadowManager.ScheduleShadowUpdate(this); } @@ -1940,8 +1940,8 @@ internal void EvaluateShadowState(HDCamera hdCamera, in ProcessedLightData proce { bool validShadow = false; if (processedLight.gpuLightType == GPULightType.Point - || processedLight.gpuLightType == GPULightType.Rectangle - || processedLight.gpuLightType == GPULightType.Spot) + || processedLight.gpuLightType == GPULightType.Rectangle + || processedLight.gpuLightType == GPULightType.Spot) { validShadow = true; } @@ -2021,7 +2021,7 @@ internal void ReserveShadowMap(Camera camera, HDShadowManager shadowManager, HDS // ease out and invert the curve, give more importance to closer distances distance01 = 1.0f - Mathf.Pow(distance01, 2); - // normalized ratio between light range and distance + // normalized ratio between light range and distance float range01 = Mathf.Clamp01(visibleLight.range / Vector3.Distance(camera.transform.position, visibleLight.GetPosition())); float scaleFactor01 = Mathf.Max(distance01, range01); @@ -2103,8 +2103,8 @@ private void UpdateDirectionalShadowRequest(HDShadowManager manager, HDShadowSet } internal void UpdateShadowRequestData(HDCamera hdCamera, HDShadowManager manager, HDShadowSettings shadowSettings, VisibleLight visibleLight, - CullingResults cullResults, int lightIndex, LightingDebugSettings lightingDebugSettings, HDShadowFilteringQuality filteringQuality, - Vector2 viewportSize, HDLightType lightType, int shadowIndex, ref HDShadowRequest shadowRequest) + CullingResults cullResults, int lightIndex, LightingDebugSettings lightingDebugSettings, HDShadowFilteringQuality filteringQuality, + Vector2 viewportSize, HDLightType lightType, int shadowIndex, ref HDShadowRequest shadowRequest) { Matrix4x4 invViewProjection = Matrix4x4.identity; Vector3 cameraPos = hdCamera.mainViewConstants.worldSpaceCameraPos; @@ -2155,7 +2155,7 @@ internal void UpdateShadowRequestData(HDCamera hdCamera, HDShadowManager manager } internal int UpdateShadowRequest(HDCamera hdCamera, HDShadowManager manager, HDShadowSettings shadowSettings, VisibleLight visibleLight, - CullingResults cullResults, int lightIndex, LightingDebugSettings lightingDebugSettings, HDShadowFilteringQuality filteringQuality, out int shadowRequestCount) + CullingResults cullResults, int lightIndex, LightingDebugSettings lightingDebugSettings, HDShadowFilteringQuality filteringQuality, out int shadowRequestCount) { int firstShadowRequestIndex = -1; Vector3 cameraPos = hdCamera.mainViewConstants.worldSpaceCameraPos; @@ -2222,7 +2222,7 @@ internal int UpdateShadowRequest(HDCamera hdCamera, HDShadowManager manager, HDS shadowRequest.shouldUseCachedShadowData = false; shadowRequest.shouldRenderCachedComponent = true; } - else if(hasCachedComponent) + else if (hasCachedComponent) { shadowRequest.cachedShadowData.cacheTranslationDelta = cameraPos - m_CachedViewPos; shadowRequest.shouldUseCachedShadowData = true; @@ -2230,10 +2230,9 @@ internal int UpdateShadowRequest(HDCamera hdCamera, HDShadowManager manager, HDS // If directional we still need to calculate the split data. if (lightType == HDLightType.Directional) UpdateDirectionalShadowRequest(manager, shadowSettings, visibleLight, cullResults, viewportSize, index, lightIndex, cameraPos, shadowRequest, out invViewProjection); - } - if(needToUpdateDynamicContent && !hasUpdatedRequestData) + if (needToUpdateDynamicContent && !hasUpdatedRequestData) { shadowRequest.shouldUseCachedShadowData = false; @@ -2268,7 +2267,7 @@ void SetCommonShadowRequestSettings(HDShadowRequest shadowRequest, VisibleLight // zBuffer param to reconstruct depth position (for transmission) float f = legacyLight.range; float n = shadowNearPlane; - shadowRequest.zBufferParam = new Vector4((f-n)/n, 1.0f, (f-n)/(n*f), 1.0f/f); + shadowRequest.zBufferParam = new Vector4((f - n) / n, 1.0f, (f - n) / (n * f), 1.0f / f); shadowRequest.worldTexelSize = 2.0f / shadowRequest.deviceProjectionYFlip.m00 / viewportSize.x * Mathf.Sqrt(2.0f); shadowRequest.normalBias = normalBias; @@ -2330,7 +2329,7 @@ void SetCommonShadowRequestSettings(HDShadowRequest shadowRequest, VisibleLight { var devProj = shadowRequest.deviceProjection; float frustumExtentZ = Vector4.Dot(new Vector4(devProj.m32, -devProj.m32, -devProj.m22, devProj.m22), new Vector4(devProj.m22, devProj.m32, devProj.m23, devProj.m33)) / - (devProj.m22 * (devProj.m22 - devProj.m32)); + (devProj.m22 * (devProj.m22 - devProj.m32)); // We use the light view frustum derived from view projection matrix and angular diameter to work out a filter size in // shadow map space, essentially figuring out the footprint of the cone subtended by the light on the shadow map @@ -2358,7 +2357,7 @@ void SetCommonShadowRequestSettings(HDShadowRequest shadowRequest, VisibleLight // If we are PCSS, the blur radius can be quite big, hence we need to tweak up the slope bias if (filteringQuality == HDShadowFilteringQuality.High) { - if(softness > 0.01f) + if (softness > 0.01f) { // maxBaseBias is an empirically set value, also the lerp stops at a shadow softness of 0.05, then is clamped. float maxBaseBias = 18.0f; @@ -2691,7 +2690,7 @@ void OnValidate() #endif } -#region Update functions to patch values in the Light component when we change properties inside HDAdditionalLightData + #region Update functions to patch values in the Light component when we change properties inside HDAdditionalLightData void SetLightIntensityPunctual(float intensity) { @@ -3053,7 +3052,7 @@ internal void RefreshCachedShadow() #endregion -#region User API functions + #region User API functions /// /// Set the color of the light. @@ -3122,7 +3121,7 @@ public void SetCookie(Texture cookie, Vector2 directionalLightCookieSize) if (cookie.dimension != TextureDimension.Tex2D) { Debug.LogError("Texture dimension " + cookie.dimension + " is not supported for area lights."); - return ; + return; } areaLightCookie = cookie; } @@ -3131,12 +3130,12 @@ public void SetCookie(Texture cookie, Vector2 directionalLightCookieSize) if (lightType == HDLightType.Point && cookie.dimension != TextureDimension.Cube) { Debug.LogError("Texture dimension " + cookie.dimension + " is not supported for point lights."); - return ; + return; } else if ((lightType == HDLightType.Directional || lightType == HDLightType.Spot) && cookie.dimension != TextureDimension.Tex2D) // Only 2D cookie are supported for Directional and Spot lights { Debug.LogError("Texture dimension " + cookie.dimension + " is not supported for Directional/Spot lights."); - return ; + return; } if (lightType == HDLightType.Directional) { @@ -3359,7 +3358,7 @@ public LightmapBakeType lightmapBakeType } #endif -#endregion + #endregion /// /// Converts a light layer into a rendering layer mask. @@ -3392,8 +3391,8 @@ ShadowMapType shadowMapType => (type == HDLightType.Area && areaLightShape == AreaLightShape.Rectangle) ? ShadowMapType.AreaLightAtlas : type != HDLightType.Directional - ? ShadowMapType.PunctualAtlas - : ShadowMapType.CascadedDirectional; + ? ShadowMapType.PunctualAtlas + : ShadowMapType.CascadedDirectional; void OnEnable() { @@ -3408,7 +3407,7 @@ void OnEnable() /// /// Deserialization callback /// - void ISerializationCallbackReceiver.OnAfterDeserialize() { } + void ISerializationCallbackReceiver.OnAfterDeserialize() {} /// /// Serialization callback @@ -3430,8 +3429,8 @@ internal ShadowMapType GetShadowMapType(HDLightType lightType) { return (lightType == HDLightType.Area && areaLightShape == AreaLightShape.Rectangle) ? ShadowMapType.AreaLightAtlas : lightType != HDLightType.Directional - ? ShadowMapType.PunctualAtlas - : ShadowMapType.CascadedDirectional; + ? ShadowMapType.PunctualAtlas + : ShadowMapType.CascadedDirectional; } /// Tell if the light is overlapping for the light overlap debug mode diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs index 7c0519be4f8..d2cb31d2e1e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs @@ -84,7 +84,7 @@ public void Release() { CoreUtils.Destroy(m_MaterialFilterAreaLights); - if(m_TempRenderTexture0 != null) + if (m_TempRenderTexture0 != null) { m_TempRenderTexture0.Release(); m_TempRenderTexture0 = null; @@ -142,7 +142,6 @@ void ReserveTempTextureIfNeeded(CommandBuffer cmd, int mipMapCount) cmd.SetRenderTarget(m_TempRenderTexture1, mipIdx); cmd.ClearRenderTarget(false, true, Color.clear); } - } } @@ -189,7 +188,7 @@ Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source, int finalWidth // Then operate on all the remaining mip levels Vector4 sourceSize = Vector4.zero; - for (int mipIndex=1; mipIndex < mipMapCount; mipIndex++) + for (int mipIndex = 1; mipIndex < mipMapCount; mipIndex++) { { // Perform horizontal blur sourceSize.Set(viewportWidth / (float)sourceWidth * 1.0f, viewportHeight / (float)sourceHeight, 1.0f / sourceWidth, 1.0f / sourceHeight); @@ -203,7 +202,7 @@ Texture FilterAreaLightTexture(CommandBuffer cmd, Texture source, int finalWidth m_MPBFilterAreaLights.SetVector(s_sourceSize, sourceSize); m_MPBFilterAreaLights.SetVector(s_uvLimits, uvLimits); - cmd.SetRenderTarget(m_TempRenderTexture1, mipIndex-1); // Temp texture is already 1 mip lower than source + cmd.SetRenderTarget(m_TempRenderTexture1, mipIndex - 1); // Temp texture is already 1 mip lower than source cmd.SetViewport(new Rect(0, 0, viewportWidth, viewportHeight)); cmd.DrawProcedural(Matrix4x4.identity, m_MaterialFilterAreaLights, 1, MeshTopology.Triangles, 3, 1, m_MPBFilterAreaLights); } @@ -365,7 +364,7 @@ public void ReserveSpaceCube(Texture cookie) Debug.Assert(cookie.dimension == TextureDimension.Cube); - int projectionSize = 2*cookie.width; + int projectionSize = 2 * cookie.width; if (projectionSize < k_MinCookieSize) return; @@ -381,7 +380,7 @@ public void ReserveSpaceCube(Texture cookieA, Texture cookieB) Debug.Assert(cookieA.dimension == TextureDimension.Cube && cookieB.dimension == TextureDimension.Cube); - int projectionSize = 2*(int)Mathf.Max(cookieA.width, cookieB.width); + int projectionSize = 2 * (int)Mathf.Max(cookieA.width, cookieB.width); if (projectionSize < k_MinCookieSize) return; @@ -408,7 +407,7 @@ public Vector4 FetchCubeCookie(CommandBuffer cmd, Texture cookie) if (m_CookieAtlas.NeedsUpdate(cookie, true)) { - Vector4 sourceScaleOffset = new Vector4(projectionSize/(float)atlasTexture.rt.width, projectionSize/(float)atlasTexture.rt.height, 0, 0); + Vector4 sourceScaleOffset = new Vector4(projectionSize / (float)atlasTexture.rt.width, projectionSize / (float)atlasTexture.rt.height, 0, 0); Texture filteredProjected = FilterAreaLightTexture(cmd, cookie, projectionSize, projectionSize); m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie)); @@ -437,7 +436,7 @@ public Vector4 FetchCubeCookie(CommandBuffer cmd, Texture cookie, Texture ies) if (m_CookieAtlas.NeedsUpdate(cookie, ies, true)) { - Vector4 sourceScaleOffset = new Vector4(projectionSize/(float)atlasTexture.rt.width, projectionSize/(float)atlasTexture.rt.height, 0, 0); + Vector4 sourceScaleOffset = new Vector4(projectionSize / (float)atlasTexture.rt.width, projectionSize / (float)atlasTexture.rt.height, 0, 0); Texture filteredProjected = FilterAreaLightTexture(cmd, cookie, projectionSize, projectionSize); m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); @@ -463,7 +462,7 @@ public Vector4 GetCookieAtlasSize() m_CookieAtlas.AtlasTexture.rt.height, 1.0f / m_CookieAtlas.AtlasTexture.rt.width, 1.0f / m_CookieAtlas.AtlasTexture.rt.height - ); + ); } public Vector4 GetCookieAtlasDatas() @@ -474,7 +473,7 @@ public Vector4 GetCookieAtlasDatas() padding / (float)m_CookieAtlas.AtlasTexture.rt.width, cookieAtlasLastValidMip, 0 - ); + ); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs index 504c2aa7d66..b499b73a4a6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs @@ -310,12 +310,12 @@ public void CopyEntityDataToComputeBuffers() static int[] s_EntityDataSizesPerCategory = new int[(int)BoundedEntityCategory.Count] // Can't make it const in C#... { - Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight - Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight - Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe - Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal - Marshal.SizeOf(typeof(DensityVolumeData)), // BoundedEntityCategory.DensityVolume - // Marshal.SizeOf(typeof(ProbeVolumeEngineData)) // BoundedEntityCategory.ProbeVolume + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.PunctualLight + Marshal.SizeOf(typeof(LightData)), // BoundedEntityCategory.AreaLight + Marshal.SizeOf(typeof(EnvLightData)), // BoundedEntityCategory.ReflectionProbe + Marshal.SizeOf(typeof(DecalData)), // BoundedEntityCategory.Decal + Marshal.SizeOf(typeof(DensityVolumeData)), // BoundedEntityCategory.DensityVolume + // Marshal.SizeOf(typeof(ProbeVolumeEngineData)) // BoundedEntityCategory.ProbeVolume }; // The entity count is the same for all views. @@ -504,7 +504,7 @@ public enum TileClusterCategoryDebug : int EnvironmentAndArea = 6, /// All lights. EnvironmentAndAreaAndPunctual = 7, - /// Probe Volumes. + /// Probe Volumes. ProbeVolumes = 8, /// Decals. Decal = 16, @@ -632,7 +632,7 @@ public void Initialize(HDRenderPipelineAsset hdrpAsset, RenderPipelineResources // For regular reflection probes, we need to convolve with all the BSDF functions GraphicsFormat probeCacheFormat = lightLoopSettings.reflectionProbeFormat == ReflectionAndPlanarProbeFormat.R11G11B10 ? - GraphicsFormat.B10G11R11_UFloatPack32 : GraphicsFormat.R16G16B16A16_SFloat; + GraphicsFormat.B10G11R11_UFloatPack32 : GraphicsFormat.R16G16B16A16_SFloat; // BC6H requires CPP feature not yet available //if (lightLoopSettings.reflectionCacheCompressed) @@ -787,8 +787,8 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, // the header (containing index ranges, 2 * sizeof(uint16)) and // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). int coarseTileBufferElementCount = coarseTileBufferDimensions.x * coarseTileBufferDimensions.y - * (int)BoundedEntityCategory.Count * viewCount - * (2 + TiledLightingConstants.s_CoarseTileEntryLimit) / 2; + * (int)BoundedEntityCategory.Count * viewCount + * (2 + TiledLightingConstants.s_CoarseTileEntryLimit) / 2; coarseTileBuffer = new ComputeBuffer(coarseTileBufferElementCount, sizeof(uint)); // Index range + index list @@ -798,8 +798,8 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, // the header (containing index ranges, 2 * sizeof(uint16)) and // the body (containing index lists, TiledLightingConstants.s_CoarseTileEntryLimit * sizeof(uint16)). int fineTileBufferElementCount = fineTileBufferDimensions.x * fineTileBufferDimensions.y - * (int)BoundedEntityCategory.Count * viewCount - * (2 + TiledLightingConstants.s_FineTileEntryLimit) / 2; + * (int)BoundedEntityCategory.Count * viewCount + * (2 + TiledLightingConstants.s_FineTileEntryLimit) / 2; fineTileBuffer = new ComputeBuffer(fineTileBufferElementCount, sizeof(uint)); // Index range + index list @@ -820,7 +820,6 @@ public void AllocateNonRenderGraphResolutionDependentBuffers(HDCamera hdCamera, listsAreClear = false; } - public void AllocateResolutionDependentBuffers(HDCamera hdCamera, int width, int height, int viewCount, int maxBoundedEntityCount, bool renderGraphEnabled) { // convexBoundsBuffer = new ComputeBuffer(viewCount * maxLightOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(FiniteLightBound))); @@ -1140,7 +1139,7 @@ void InitShadowSystem(HDRenderPipelineAsset hdAsset, RenderPipelineResources def void DeinitShadowSystem() { - if(m_ShadowManager != null) + if (m_ShadowManager != null) { m_ShadowManager.Dispose(); m_ShadowManager = null; @@ -1298,7 +1297,7 @@ void InitializeLightLoop(IBLFilterBSDF[] iBLFilterBSDFArray) // Setup shadow algorithms var shadowParams = asset.currentPlatformRenderPipelineSettings.hdShadowInitParams; - var shadowKeywords = new[]{"SHADOW_LOW", "SHADOW_MEDIUM", "SHADOW_HIGH"}; + var shadowKeywords = new[] {"SHADOW_LOW", "SHADOW_MEDIUM", "SHADOW_HIGH"}; foreach (var p in shadowKeywords) Shader.DisableKeyword(p); Shader.EnableKeyword(shadowKeywords[(int)shadowParams.shadowFilteringQuality]); @@ -1490,26 +1489,26 @@ static Vector3 ComputeAtmosphericOpticalDepth(PhysicallyBasedSky skySettings, fl Vector2 Z = R * rcpH; float cosHoriz = ComputeCosineOfHorizonAngle(r, R); - float sinTheta = Mathf.Sqrt(Saturate(1 - cosTheta * cosTheta)); + float sinTheta = Mathf.Sqrt(Saturate(1 - cosTheta * cosTheta)); Vector2 ch; ch.x = ChapmanUpperApprox(z.x, Mathf.Abs(cosTheta)) * Mathf.Exp(Z.x - z.x); // Rescaling adds 'exp' ch.y = ChapmanUpperApprox(z.y, Mathf.Abs(cosTheta)) * Mathf.Exp(Z.y - z.y); // Rescaling adds 'exp' if ((!alwaysAboveHorizon) && (cosTheta < cosHoriz)) // Below horizon, intersect sphere - { - float sinGamma = (r / R) * sinTheta; - float cosGamma = Mathf.Sqrt(Saturate(1 - sinGamma * sinGamma)); + { + float sinGamma = (r / R) * sinTheta; + float cosGamma = Mathf.Sqrt(Saturate(1 - sinGamma * sinGamma)); - Vector2 ch_2; + Vector2 ch_2; ch_2.x = ChapmanUpperApprox(Z.x, cosGamma); // No need to rescale ch_2.y = ChapmanUpperApprox(Z.y, cosGamma); // No need to rescale - ch = ch_2 - ch; + ch = ch_2 - ch; } else if (cosTheta < 0) // Above horizon, lower hemisphere { - // z_0 = n * r_0 = (n * r) * sin(theta) = z * sin(theta). + // z_0 = n * r_0 = (n * r) * sin(theta) = z * sin(theta). // Ch(z, theta) = 2 * exp(z - z_0) * Ch(z_0, Pi/2) - Ch(z, Pi - theta). Vector2 z_0 = z * sinTheta; Vector2 b = new Vector2(Mathf.Exp(Z.x - z_0.x), Mathf.Exp(Z.x - z_0.x)); // Rescaling cancels out 'z' and adds 'Z' @@ -1527,8 +1526,8 @@ static Vector3 ComputeAtmosphericOpticalDepth(PhysicallyBasedSky skySettings, fl float aerosolExtinction = skySettings.GetAerosolExtinctionCoefficient(); return new Vector3(optDepth.x * airExtinction.x + optDepth.y * aerosolExtinction, - optDepth.x * airExtinction.y + optDepth.y * aerosolExtinction, - optDepth.x * airExtinction.z + optDepth.y * aerosolExtinction); + optDepth.x * airExtinction.y + optDepth.y * aerosolExtinction, + optDepth.x * airExtinction.z + optDepth.y * aerosolExtinction); } // Computes transmittance along the light path segment. @@ -1611,7 +1610,7 @@ internal DirectionalLightData GetDirectionalLightData(CommandBuffer cmd, HDCamer lightData.shadowDimmer = additionalLightData.shadowDimmer; lightData.volumetricShadowDimmer = additionalLightData.volumetricShadowDimmer; - GetContactShadowMask(additionalLightData, HDAdditionalLightData.ScalableSettings.UseContactShadow(m_Asset), hdCamera, isRasterization: true, ref lightData.contactShadowMask,ref lightData.isRayTracedContactShadow); + GetContactShadowMask(additionalLightData, HDAdditionalLightData.ScalableSettings.UseContactShadow(m_Asset), hdCamera, isRasterization: true, ref lightData.contactShadowMask, ref lightData.isRayTracedContactShadow); // We want to have a colored penumbra if the flag is on and the color is not gray bool penumbraTint = additionalLightData.penumbraTint && ((additionalLightData.shadowTint.r != additionalLightData.shadowTint.g) || (additionalLightData.shadowTint.g != additionalLightData.shadowTint.b)); @@ -1646,7 +1645,7 @@ internal DirectionalLightData GetDirectionalLightData(CommandBuffer cmd, HDCamer m_CurrentShadowSortedSunLightIndex = sortedIndex; } //Value of max smoothness is derived from AngularDiameter. Formula results from eyeballing. Angular diameter of 0 results in 1 and angular diameter of 80 results in 0. - float maxSmoothness = Mathf.Clamp01(1.35f / (1.0f + Mathf.Pow(1.15f * (0.0315f * additionalLightData.angularDiameter + 0.4f),2f)) - 0.11f); + float maxSmoothness = Mathf.Clamp01(1.35f / (1.0f + Mathf.Pow(1.15f * (0.0315f * additionalLightData.angularDiameter + 0.4f), 2f)) - 0.11f); // Value of max smoothness is from artists point of view, need to convert from perceptual smoothness to roughness lightData.minRoughness = (1.0f - maxSmoothness) * (1.0f - maxSmoothness); @@ -1677,7 +1676,7 @@ internal DirectionalLightData GetDirectionalLightData(CommandBuffer cmd, HDCamer var skySettings = hdCamera.volumeStack.GetComponent(); // Ignores distance (at infinity). - Vector3 transm = EvaluateAtmosphericAttenuation(skySettings, - lightData.forward, hdCamera.camera.transform.position); + Vector3 transm = EvaluateAtmosphericAttenuation(skySettings, -lightData.forward, hdCamera.camera.transform.position); lightData.color.x *= transm.x; lightData.color.y *= transm.y; lightData.color.z *= transm.z; @@ -1699,7 +1698,7 @@ internal DirectionalLightData GetDirectionalLightData(CommandBuffer cmd, HDCamer // This function evaluates if there is currently enough screen space sahdow slots of a given light based on its light type bool EnoughScreenSpaceShadowSlots(GPULightType gpuLightType, int screenSpaceChannelSlot) { - if(gpuLightType == GPULightType.Rectangle) + if (gpuLightType == GPULightType.Rectangle) { // Area lights require two shadow slots return (screenSpaceChannelSlot + 1) < m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots; @@ -1866,7 +1865,8 @@ internal LightData GetLightData(CommandBuffer cmd, HDCamera hdCamera, HDShadowSe (lightType == HDLightType.Spot && (lightComponent.cookie != null || additionalLightData.IESPoint != null)) || ((lightType == HDLightType.Area && lightData.lightType == GPULightType.Rectangle) && (lightComponent.cookie != null || additionalLightData.IESSpot != null)) || (lightType == HDLightType.Point && (lightComponent.cookie != null || additionalLightData.IESPoint != null)) - )) + ) + ) { switch (lightType) { @@ -2198,89 +2198,89 @@ internal bool GetEnvLightData(CommandBuffer cmd, HDCamera hdCamera, in Processed switch (probe) { case PlanarReflectionProbe planarProbe: - { - if (probe.mode == ProbeSettings.Mode.Realtime - && !hdCamera.frameSettings.IsEnabled(FrameSettingsField.PlanarProbe)) - break; + { + if (probe.mode == ProbeSettings.Mode.Realtime + && !hdCamera.frameSettings.IsEnabled(FrameSettingsField.PlanarProbe)) + break; - // Grab the render data that was used to render the probe - var renderData = planarProbe.renderData; - // Grab the world to camera matrix of the capture camera - var worldToCameraRHSMatrix = renderData.worldToCameraRHS; - // Grab the projection matrix that was used to render - var projectionMatrix = renderData.projectionMatrix; - // Build an alternative matrix for projection that is not oblique - var projectionMatrixNonOblique = Matrix4x4.Perspective(renderData.fieldOfView, probe.texture.width / probe.texture.height, probe.settings.cameraSettings.frustum.nearClipPlaneRaw, probe.settings.cameraSettings.frustum.farClipPlane); - - // Convert the projection matrices to their GPU version - var gpuProj = GL.GetGPUProjectionMatrix(projectionMatrix, true); - var gpuProjNonOblique = GL.GetGPUProjectionMatrix(projectionMatrixNonOblique, true); - - // Build the oblique and non oblique view projection matrices - var vp = gpuProj * worldToCameraRHSMatrix; - var vpNonOblique = gpuProjNonOblique * worldToCameraRHSMatrix; - - // We need to collect the set of parameters required for the filtering - IBLFilterBSDF.PlanarTextureFilteringParameters planarTextureFilteringParameters = new IBLFilterBSDF.PlanarTextureFilteringParameters(); - planarTextureFilteringParameters.smoothPlanarReflection = !probe.settings.roughReflections; - planarTextureFilteringParameters.probeNormal = Vector3.Normalize(hdCamera.camera.transform.position - renderData.capturePosition); - planarTextureFilteringParameters.probePosition = probe.gameObject.transform.position; - planarTextureFilteringParameters.captureCameraDepthBuffer = planarProbe.realtimeDepthTexture; - planarTextureFilteringParameters.captureCameraScreenSize = new Vector4(probe.texture.width, probe.texture.height, 1.0f / probe.texture.width, 1.0f / probe.texture.height); - planarTextureFilteringParameters.captureCameraIVP = vp.inverse; - planarTextureFilteringParameters.captureCameraIVP_NonOblique = vpNonOblique.inverse; - planarTextureFilteringParameters.captureCameraVP_NonOblique = vpNonOblique; - planarTextureFilteringParameters.captureCameraPosition = renderData.capturePosition; - planarTextureFilteringParameters.captureFOV = renderData.fieldOfView; - planarTextureFilteringParameters.captureNearPlane = probe.settings.cameraSettings.frustum.nearClipPlaneRaw; - planarTextureFilteringParameters.captureFarPlane = probe.settings.cameraSettings.frustum.farClipPlane; - - // Fetch the slice and do the filtering - var scaleOffset = m_TextureCaches.reflectionPlanarProbeCache.FetchSlice(cmd, probe.texture, ref planarTextureFilteringParameters, out int fetchIndex); - - // We don't need to provide the capture position - // It is already encoded in the 'worldToCameraRHSMatrix' - capturePosition = Vector3.zero; - - // Indices start at 1, because -0 == 0, we can know from the bit sign which cache to use - envIndex = scaleOffset == Vector4.zero ? int.MinValue : -(fetchIndex + 1); - - // If the max number of planar on screen is reached - if (fetchIndex >= m_MaxPlanarReflectionOnScreen) - { - Debug.LogWarning("Maximum planar reflection probe on screen reached. To fix this error, increase the maximum number of planar reflections on screen in the HDRP asset."); - break; - } + // Grab the render data that was used to render the probe + var renderData = planarProbe.renderData; + // Grab the world to camera matrix of the capture camera + var worldToCameraRHSMatrix = renderData.worldToCameraRHS; + // Grab the projection matrix that was used to render + var projectionMatrix = renderData.projectionMatrix; + // Build an alternative matrix for projection that is not oblique + var projectionMatrixNonOblique = Matrix4x4.Perspective(renderData.fieldOfView, probe.texture.width / probe.texture.height, probe.settings.cameraSettings.frustum.nearClipPlaneRaw, probe.settings.cameraSettings.frustum.farClipPlane); + + // Convert the projection matrices to their GPU version + var gpuProj = GL.GetGPUProjectionMatrix(projectionMatrix, true); + var gpuProjNonOblique = GL.GetGPUProjectionMatrix(projectionMatrixNonOblique, true); + + // Build the oblique and non oblique view projection matrices + var vp = gpuProj * worldToCameraRHSMatrix; + var vpNonOblique = gpuProjNonOblique * worldToCameraRHSMatrix; + + // We need to collect the set of parameters required for the filtering + IBLFilterBSDF.PlanarTextureFilteringParameters planarTextureFilteringParameters = new IBLFilterBSDF.PlanarTextureFilteringParameters(); + planarTextureFilteringParameters.smoothPlanarReflection = !probe.settings.roughReflections; + planarTextureFilteringParameters.probeNormal = Vector3.Normalize(hdCamera.camera.transform.position - renderData.capturePosition); + planarTextureFilteringParameters.probePosition = probe.gameObject.transform.position; + planarTextureFilteringParameters.captureCameraDepthBuffer = planarProbe.realtimeDepthTexture; + planarTextureFilteringParameters.captureCameraScreenSize = new Vector4(probe.texture.width, probe.texture.height, 1.0f / probe.texture.width, 1.0f / probe.texture.height); + planarTextureFilteringParameters.captureCameraIVP = vp.inverse; + planarTextureFilteringParameters.captureCameraIVP_NonOblique = vpNonOblique.inverse; + planarTextureFilteringParameters.captureCameraVP_NonOblique = vpNonOblique; + planarTextureFilteringParameters.captureCameraPosition = renderData.capturePosition; + planarTextureFilteringParameters.captureFOV = renderData.fieldOfView; + planarTextureFilteringParameters.captureNearPlane = probe.settings.cameraSettings.frustum.nearClipPlaneRaw; + planarTextureFilteringParameters.captureFarPlane = probe.settings.cameraSettings.frustum.farClipPlane; + + // Fetch the slice and do the filtering + var scaleOffset = m_TextureCaches.reflectionPlanarProbeCache.FetchSlice(cmd, probe.texture, ref planarTextureFilteringParameters, out int fetchIndex); + + // We don't need to provide the capture position + // It is already encoded in the 'worldToCameraRHSMatrix' + capturePosition = Vector3.zero; + + // Indices start at 1, because -0 == 0, we can know from the bit sign which cache to use + envIndex = scaleOffset == Vector4.zero ? int.MinValue : -(fetchIndex + 1); + + // If the max number of planar on screen is reached + if (fetchIndex >= m_MaxPlanarReflectionOnScreen) + { + Debug.LogWarning("Maximum planar reflection probe on screen reached. To fix this error, increase the maximum number of planar reflections on screen in the HDRP asset."); + break; + } - atlasScaleOffset = scaleOffset; + atlasScaleOffset = scaleOffset; - m_TextureCaches.env2DAtlasScaleOffset[fetchIndex] = scaleOffset; - m_TextureCaches.env2DCaptureVP[fetchIndex] = vp; + m_TextureCaches.env2DAtlasScaleOffset[fetchIndex] = scaleOffset; + m_TextureCaches.env2DCaptureVP[fetchIndex] = vp; - // Propagate the smoothness information to the env light data - envLightData.roughReflections = probe.settings.roughReflections ? 1.0f : 0.0f; + // Propagate the smoothness information to the env light data + envLightData.roughReflections = probe.settings.roughReflections ? 1.0f : 0.0f; - var capturedForwardWS = renderData.captureRotation * Vector3.forward; - //capturedForwardWS.z *= -1; // Transform to RHS standard - m_TextureCaches.env2DCaptureForward[fetchIndex] = new Vector4(capturedForwardWS.x, capturedForwardWS.y, capturedForwardWS.z, 0.0f); - break; - } + var capturedForwardWS = renderData.captureRotation * Vector3.forward; + //capturedForwardWS.z *= -1; // Transform to RHS standard + m_TextureCaches.env2DCaptureForward[fetchIndex] = new Vector4(capturedForwardWS.x, capturedForwardWS.y, capturedForwardWS.z, 0.0f); + break; + } case HDAdditionalReflectionData _: - { - envIndex = m_TextureCaches.reflectionProbeCache.FetchSlice(cmd, probe.texture); - // Indices start at 1, because -0 == 0, we can know from the bit sign which cache to use - envIndex = envIndex == -1 ? int.MinValue : (envIndex + 1); - - // Calculate settings to use for the probe - var probePositionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, camera.transform); - HDRenderUtilities.ComputeCameraSettingsFromProbeSettings( - probe.settings, probePositionSettings, - out _, out var cameraPositionSettings, 0 - ); - capturePosition = cameraPositionSettings.position; + { + envIndex = m_TextureCaches.reflectionProbeCache.FetchSlice(cmd, probe.texture); + // Indices start at 1, because -0 == 0, we can know from the bit sign which cache to use + envIndex = envIndex == -1 ? int.MinValue : (envIndex + 1); + + // Calculate settings to use for the probe + var probePositionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, camera.transform); + HDRenderUtilities.ComputeCameraSettingsFromProbeSettings( + probe.settings, probePositionSettings, + out _, out var cameraPositionSettings, 0 + ); + capturePosition = cameraPositionSettings.position; - break; - } + break; + } } // int.MinValue means that the texture is not ready yet (ie not convolved/compressed yet) if (envIndex == int.MinValue) @@ -2629,8 +2629,8 @@ static int ComputeFixedPointLogDepth(float w, float f, int numBits = 16) f = Mathf.Max(f, 0.11f); // Avoid degenerate configurations - float x = Mathf.Max(1, w * (1/n)); - float z = Log2f(x) / Log2f(f * (1/n)); + float x = Mathf.Max(1, w * (1 / n)); + float z = Log2f(x) / Log2f(f * (1 / n)); return Mathf.RoundToInt(z * ((1 << numBits) - 1)); } @@ -2660,9 +2660,9 @@ internal static BoundedEntitySortingKeyLayout GeBoundedEntitySortingKeyLayoutLay layout.lightTypeBitCount = CeilLog2i((int)GPULightType.Count); layout.indexBitCount = BoundedEntitySortingKeyLayout.k_EntityIndexBitCount; layout.totalBitCount = layout.categoryBitCount - + layout.fixedPointLogDepthBitCount - + layout.lightTypeBitCount - + layout.indexBitCount; + + layout.fixedPointLogDepthBitCount + + layout.lightTypeBitCount + + layout.indexBitCount; // LSB -> MSB. layout.indexOffset = 0; layout.lightTypeOffset = layout.indexBitCount + layout.indexOffset; @@ -2681,9 +2681,9 @@ internal static ulong GenerateBoundedEntitySortingKey(int index, BoundedEntityCa Debug.Assert(0 <= (int)category && (int)category < (int)BoundedEntityCategory.Count); ulong key = ((ulong)category << layout.categoryOffset) - | ((ulong)fixedPointLogDepth << layout.fixedPointLogDepthOffset) - | ((ulong)lightType << layout.lightTypeOffset) - | ((ulong)index << layout.indexOffset); + | ((ulong)fixedPointLogDepth << layout.fixedPointLogDepthOffset) + | ((ulong)lightType << layout.lightTypeOffset) + | ((ulong)index << layout.indexOffset); return key; } @@ -2718,7 +2718,7 @@ void PreprocessLightData(ref ProcessedLightData processedData, VisibleLight ligh processedData.gpuLightType = GPULightType.Count; EvaluateGPULightType(processedData.additionalLightData.type, processedData.additionalLightData.spotLightShape, processedData.additionalLightData.areaLightShape, - ref processedData.lightCategory, ref processedData.gpuLightType); + ref processedData.lightCategory, ref processedData.gpuLightType); processedData.lightDistanceFade = processedData.gpuLightType == GPULightType.Directional ? 1.0f : HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.fadeDistance); processedData.volumetricDistanceFade = processedData.gpuLightType == GPULightType.Directional ? 1.0f : HDUtils.ComputeLinearDistanceFade(processedData.distanceToCamera, additionalLightData.volumetricFadeDistance); @@ -2886,7 +2886,7 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu #if UNITY_EDITOR if ((m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugUseSelection - || m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) + || m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) && UnityEditor.Selection.activeGameObject == lightComponent.gameObject) { m_DebugSelectedLightShadowIndex = shadowIndex; @@ -2917,7 +2917,7 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // Go through both categories at the same time (to make the existing code work). int start = m_BoundedEntityCollection.GetEntitySortKeyArrayOffset(BoundedEntityCategory.PunctualLight); int count = m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.PunctualLight) - + m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight); + + m_BoundedEntityCollection.GetEntityCount(BoundedEntityCategory.AreaLight); Debug.Assert(((int)BoundedEntityCategory.AreaLight - (int)BoundedEntityCategory.PunctualLight) == 1); @@ -2929,8 +2929,8 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); - var gpuLightType = (GPULightType) ((sortKey >> layout.lightTypeOffset) & ((1ul << layout.lightTypeBitCount) - 1)); - var lightIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); + var gpuLightType = (GPULightType)((sortKey >> layout.lightTypeOffset) & ((1ul << layout.lightTypeBitCount) - 1)); + var lightIndex = (int)((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); Debug.Assert(category == BoundedEntityCategory.PunctualLight || category == BoundedEntityCategory.AreaLight); @@ -2952,7 +2952,7 @@ void PrepareGPULightdata(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu #if UNITY_EDITOR if ((m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugUseSelection - || m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) + || m_CurrentDebugDisplaySettings.data.lightingDebugSettings.shadowDebugMode == ShadowMapDebugMode.SingleShadow) && UnityEditor.Selection.activeGameObject == lightComponent.gameObject) { m_DebugSelectedLightShadowIndex = shadowIndex; @@ -3018,7 +3018,7 @@ static uint CalculateProbeLogVolume(Bounds bounds) // - 1+ term is to prevent having negative values in the log result // - 1000* is too keep 3 digit after the dot while we truncate the result later // - 1048575 is 2^20-1 as we pack the result on 20bit later - float boxVolume = 8f* bounds.extents.x * bounds.extents.y * bounds.extents.z; + float boxVolume = 8f * bounds.extents.x * bounds.extents.y * bounds.extents.z; uint logVolume = (uint)Math.Max(0, Math.Min((int)(1000 * Mathf.Log(1 + boxVolume, 1.05f)), 1048575)); return logVolume; } @@ -3061,10 +3061,10 @@ int PreprocessVisibleProbes(HDCamera hdCamera, CullingResults cullResults, HDPro int includedProbeCount = 0; var enableReflectionProbes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ReflectionProbe) && - (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.ReflectionProbe)); + (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.ReflectionProbe)); var enablePlanarProbes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.PlanarProbe) && - (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.PlanarProbe)); + (!hasDebugLightFilter || debugLightFilter.IsEnabledFor(ProbeSettings.ProbeType.PlanarProbe)); if (enableReflectionProbes) { @@ -3154,13 +3154,13 @@ void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); - var gpuLightType = (GPULightType) ((sortKey >> layout.lightTypeOffset) & ((1ul << layout.lightTypeBitCount) - 1)); - var probeIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); + var gpuLightType = (GPULightType)((sortKey >> layout.lightTypeOffset) & ((1ul << layout.lightTypeBitCount) - 1)); + var probeIndex = (int)((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); Debug.Assert(category == BoundedEntityCategory.ReflectionProbe); ProcessedProbeData processedProbe = (gpuLightType == GPULightType.PlanarReflection) ? m_ProcessedPlanarProbeData[probeIndex] - : m_ProcessedReflectionProbeData[probeIndex]; + : m_ProcessedReflectionProbeData[probeIndex]; EnvLightData envLightData = new EnvLightData(); if (GetEnvLightData(cmd, hdCamera, processedProbe, ref envLightData)) @@ -3187,7 +3187,7 @@ void PrepareGPUProbeData(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu // Return true if BakedShadowMask are enabled bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, - HDProbeCullingResults hdProbeCullingResults, DensityVolumeList densityVolumes, ProbeVolumeList probeVolumes, DebugDisplaySettings debugDisplaySettings, AOVRequestData aovRequest) + HDProbeCullingResults hdProbeCullingResults, DensityVolumeList densityVolumes, ProbeVolumeList probeVolumes, DebugDisplaySettings debugDisplaySettings, AOVRequestData aovRequest) { var debugLightFilter = debugDisplaySettings.GetDebugLightFilterMode(); var hasDebugLightFilter = debugLightFilter != DebugLightFilterMode.None; @@ -3331,7 +3331,7 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); - var decalIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); + var decalIndex = (int)((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); Debug.Assert(category == BoundedEntityCategory.Decal); @@ -3376,7 +3376,7 @@ bool PrepareLightsForGPU(CommandBuffer cmd, HDCamera hdCamera, CullingResults cu ulong sortKey = m_BoundedEntityCollection.GetEntitySortKey(viewIndex, sortIndex); var category = (BoundedEntityCategory)((sortKey >> layout.categoryOffset) & ((1ul << layout.categoryBitCount) - 1)); - var densityVolumeIndex = (int) ((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); + var densityVolumeIndex = (int)((sortKey >> layout.indexOffset) & ((1ul << layout.indexBitCount) - 1)); Debug.Assert(category == BoundedEntityCategory.DensityVolume); @@ -3575,9 +3575,9 @@ static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuf const int maxAllowedGroups = 65535; // On higher resolutions we might end up with more than 65535 group which is not allowed, so we need to to have multiple dispatches. int i = 0; - while(totalNumberOfGroupsNeeded > 0) + while (totalNumberOfGroupsNeeded > 0) { - countAndOffset.y = maxAllowedGroups * i; + countAndOffset.y = maxAllowedGroups * i; cmd.SetComputeVectorParam(parameters.clearLightListCS, HDShaderIDs._LightListEntriesAndOffset, countAndOffset); int currGroupCount = Math.Min(maxAllowedGroups, totalNumberOfGroupsNeeded); @@ -3589,9 +3589,9 @@ static void ClearLightList(in BuildGPULightListParameters parameters, CommandBuf } } - static void ClearLightLists( in BuildGPULightListParameters parameters, - in BuildGPULightListResources resources, - CommandBuffer cmd) + static void ClearLightLists(in BuildGPULightListParameters parameters, + in BuildGPULightListResources resources, + CommandBuffer cmd) { // We should not have to clear anything. That consumes GPU time and creates GPU bubbles. // We should, however, discard the contents of the resource. For more information, see @@ -3669,7 +3669,7 @@ static void FillScreenTiles(in BuildGPULightListParameters parameters, in BuildG int coarseBufferSize = parameters.coarseTileBufferDimensions.x * parameters.coarseTileBufferDimensions.y; int fineTilesPerCoarseTile = (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize) - * (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize); + * (TiledLightingConstants.s_CoarseTileSize / TiledLightingConstants.s_FineTileSize); int kernel, groupCount; @@ -3748,7 +3748,7 @@ static void PerformClassification(in BuildGPULightListParameters parameters, in // Note that all material feature flag bellow are in the same GBuffer (inGBuffer2) and thus material classification only sample one Gbuffer cmd.SetComputeTextureParam(parameters.classificationShader, 0, HDShaderIDs._GBufferTexture[2], resources.gBuffer[2]); - cmd.SetComputeBufferParam( parameters.classificationShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); + cmd.SetComputeBufferParam(parameters.classificationShader, 0, HDShaderIDs.g_TileFeatureFlags, resources.tileFeatureFlags); if (resources.stencilTexture.rt == null || resources.stencilTexture.rt.stencilFormat == GraphicsFormat.None) // We are accessing MSAA resolved version and not the depth stencil buffer directly. @@ -3771,7 +3771,6 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BuildDispatchIndirect))) { - // Assume that we use fine (and not coarse) tiles in the shader. int numTiles = parameters.fineTileBufferDimensions.x * parameters.fineTileBufferDimensions.y; @@ -3782,7 +3781,6 @@ static void BuildDispatchIndirect(in BuildGPULightListParameters parameters, in cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_NumTiles, numTiles); cmd.SetComputeIntParam(parameters.clearDispatchIndirectShader, HDShaderIDs.g_VertexPerTile, k_HasNativeQuadSupport ? 4 : 6); cmd.DispatchCompute(parameters.clearDispatchIndirectShader, s_ClearDrawProceduralIndirectKernel, 1, 1, 1); - } else { @@ -3806,9 +3804,9 @@ static bool DeferredUseComputeAsPixel(FrameSettings frameSettings) return frameSettings.IsEnabled(FrameSettingsField.DeferredTile) && (!frameSettings.IsEnabled(FrameSettingsField.ComputeLightEvaluation) || k_PreferFragment); } - unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters( HDCamera hdCamera, - TileAndClusterData tileAndClusterData, - ref ShaderVariablesLightList constantBuffer) + unsafe BuildGPULightListParameters PrepareBuildGPULightListParameters(HDCamera hdCamera, + TileAndClusterData tileAndClusterData, + ref ShaderVariablesLightList constantBuffer) { BuildGPULightListParameters parameters = new BuildGPULightListParameters(); @@ -4133,7 +4131,7 @@ unsafe void UpdateShaderVariablesGlobalLightLoop(ref ShaderVariablesGlobal cb, H // Old stuff below... cb._NumTileFtplX = (uint)GetNumTileFtplX(hdCamera); cb._NumTileFtplY = (uint)GetNumTileFtplY(hdCamera); - cb.g_fClustScale = (float)(geomSeries / (hdCamera.camera.farClipPlane - hdCamera.camera.nearClipPlane)); ; + cb.g_fClustScale = (float)(geomSeries / (hdCamera.camera.farClipPlane - hdCamera.camera.nearClipPlane));; cb.g_fClustBase = k_ClustLogBase; cb.g_fNearPlane = hdCamera.camera.nearClipPlane; cb.g_fFarPlane = hdCamera.camera.farClipPlane; @@ -4197,7 +4195,6 @@ static void PushLightLoopGlobalParams(in LightLoopGlobalParameters param, Comman } } - void RenderShadowMaps(ScriptableRenderContext renderContext, CommandBuffer cmd, in ShaderVariablesGlobal globalCB, CullingResults cullResults, HDCamera hdCamera) { // kick off the shadow jobs here @@ -4271,7 +4268,7 @@ ContactShadowsParameters PrepareContactShadowsParameters(HDCamera hdCamera, floa parameters.contactShadowsCS = contactShadowComputeShader; parameters.contactShadowsCS.shaderKeywords = null; - if(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) { parameters.contactShadowsCS.EnableKeyword("ENABLE_MSAA"); } @@ -4310,13 +4307,12 @@ ContactShadowsParameters PrepareContactShadowsParameters(HDCamera hdCamera, floa return parameters; } - static void RenderContactShadows( in ContactShadowsParameters parameters, - RTHandle contactShadowRT, - RTHandle depthTexture, - ComputeBuffer lightList, - CommandBuffer cmd) + static void RenderContactShadows(in ContactShadowsParameters parameters, + RTHandle contactShadowRT, + RTHandle depthTexture, + ComputeBuffer lightList, + CommandBuffer cmd) { - cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters, parameters.params1); cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters2, parameters.params2); cmd.SetComputeVectorParam(parameters.contactShadowsCS, HDShaderIDs._ContactShadowParamsParameters3, parameters.params3); @@ -4658,12 +4654,12 @@ LightLoopDebugOverlayParameters PrepareLightLoopDebugOverlayParameters() } static void RenderLightLoopDebugOverlay(in DebugParameters debugParameters, - CommandBuffer cmd, - ComputeBuffer tileBuffer, - ComputeBuffer lightListBuffer, - ComputeBuffer perVoxelLightListBuffer, - ComputeBuffer dispatchIndirectBuffer, - RTHandle depthTexture) + CommandBuffer cmd, + ComputeBuffer tileBuffer, + ComputeBuffer lightListBuffer, + ComputeBuffer perVoxelLightListBuffer, + ComputeBuffer dispatchIndirectBuffer, + RTHandle depthTexture) { var hdCamera = debugParameters.hdCamera; var parameters = debugParameters.lightingOverlayParameters; @@ -4672,7 +4668,6 @@ static void RenderLightLoopDebugOverlay(in DebugParameters debugParameters, { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.TileClusterLightingDebug))) { - int w = hdCamera.actualWidth; int h = hdCamera.actualHeight; int numTilesX = (w + 15) / 16; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl index 5bd90de1e74..ea486540a36 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ShaderVariablesLightLoop.hlsl @@ -18,7 +18,7 @@ StructuredBuffer _DirectionalLightData; StructuredBuffer _PunctualLightData; StructuredBuffer _AreaLightData; StructuredBuffer _ReflectionProbeData; -// StructuredBuffer _DecalData; // Defined elsewhere +// StructuredBuffer _DecalData; // Defined elsewhere StructuredBuffer _DensityVolumeData; // Used by directional and spot lights diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute index cce3f47aedf..74bbb861060 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/cleardispatchindirect.compute @@ -8,7 +8,7 @@ RWBuffer g_DispatchIndirectBuffer : register( u0 ); // Indirect argument #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs.hlsl" #ifdef PLATFORM_LANE_COUNT -#define NR_THREADS PLATFORM_LANE_COUNT +#define NR_THREADS PLATFORM_LANE_COUNT #else #define NR_THREADS 64 // default to 64 threads per group on other platforms.. #endif @@ -21,7 +21,7 @@ void ClearDispatchIndirect(uint dispatchThreadId : SV_DispatchThreadID) { // On iOS, we get a GPU hang/reset based upon the execution of the ClearDispatchIndirect kernel. // The buffer is created using the 'NUM_FEATURE_VARIANTS' constant but we're dispatching a threadgroup of 64 threads, so we are presumably going out of bounds (Metal GPU errors are not terribly descriptive, but this is a common cause). - // In DirectX out-of-bounds reads are always zero and out-of-bounds writes are are a no op. + // In DirectX out-of-bounds reads are always zero and out-of-bounds writes are are a no op. if (dispatchThreadId >= NUM_FEATURE_VARIANTS) return; @@ -35,7 +35,7 @@ void ClearDrawProceduralIndirect(uint dispatchThreadId : SV_DispatchThreadID) { // On iOS, we get a GPU hang/reset based upon the execution of the ClearDispatchIndirect kernel. // The buffer is created using the 'NUM_FEATURE_VARIANTS' constant but we're dispatching a threadgroup of 64 threads, so we are presumably going out of bounds (Metal GPU errors are not terribly descriptive, but this is a common cause). - // In DirectX out-of-bounds reads are always zero and out-of-bounds writes are are a no op. + // In DirectX out-of-bounds reads are always zero and out-of-bounds writes are are a no op. if (dispatchThreadId >= NUM_FEATURE_VARIANTS) return; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute index 41b471c1851..9352c48dfd5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute @@ -41,13 +41,13 @@ groupshared uint lightOffs; // Only usage of that constant. float GetLinearDepth(float2 pixXY, float zDptBufSpace, uint eyeIndex) // 0 is near 1 is far { - float4x4 g_mInvScrProjection = g_mInvScrProjectionArr[eyeIndex]; + float4x4 g_mInvScrProjection = g_mInvScrProjectionArr[eyeIndex]; #ifdef USE_OBLIQUE_MODE - float2 res2 = mul(g_mInvScrProjection, float4(pixXY, zDptBufSpace, 1.0)).zw; - return res2.x / res2.y; + float2 res2 = mul(g_mInvScrProjection, float4(pixXY, zDptBufSpace, 1.0)).zw; + return res2.x / res2.y; #else - // for perspective projection m22 is zero and m23 is +1/-1 (depends on left/right hand proj) + // for perspective projection m22 is zero and m23 is +1/-1 (depends on left/right hand proj) // however this function must also work for orthographic projection so we keep it like this. float m22 = g_mInvScrProjection[2].z, m23 = g_mInvScrProjection[2].w; float m32 = g_mInvScrProjection[3].z, m33 = g_mInvScrProjection[3].w; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute index 4869b05ddec..fbaa15a3e0f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute @@ -5,10 +5,10 @@ #pragma kernel TileLightListGen_DepthRT_SrcBigTile LIGHTLISTGEN=TileLightListGen_DepthRT_SrcBigTile ENABLE_DEPTH_TEXTURE_BACKPLANE USE_TWO_PASS_TILED_LIGHTING #pragma kernel TileLightListGen_DepthRT_MSAA_SrcBigTile LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_SrcBigTile ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_TWO_PASS_TILED_LIGHTING -#pragma kernel TileLightListGen_DepthRT_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE USE_OBLIQUE_MODE -#pragma kernel TileLightListGen_DepthRT_MSAA_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_OBLIQUE_MODE -#pragma kernel TileLightListGen_DepthRT_SrcBigTile_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_SrcBigTile_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE USE_TWO_PASS_TILED_LIGHTING USE_OBLIQUE_MODE -#pragma kernel TileLightListGen_DepthRT_MSAA_SrcBigTile_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_SrcBigTile_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_TWO_PASS_TILED_LIGHTING USE_OBLIQUE_MODE +#pragma kernel TileLightListGen_DepthRT_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE USE_OBLIQUE_MODE +#pragma kernel TileLightListGen_DepthRT_MSAA_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_OBLIQUE_MODE +#pragma kernel TileLightListGen_DepthRT_SrcBigTile_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_SrcBigTile_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE USE_TWO_PASS_TILED_LIGHTING USE_OBLIQUE_MODE +#pragma kernel TileLightListGen_DepthRT_MSAA_SrcBigTile_Oblique LIGHTLISTGEN=TileLightListGen_DepthRT_MSAA_SrcBigTile_Oblique ENABLE_DEPTH_TEXTURE_BACKPLANE MSAA_ENABLED USE_TWO_PASS_TILED_LIGHTING USE_OBLIQUE_MODE // #pragma enable_d3d11_debug_symbols @@ -87,8 +87,8 @@ float GetLinearDepth(float2 pixXY, float zDptBufSpace, uint eyeIndex) // 0 is float4x4 g_mInvScrProjection = g_mInvScrProjectionArr[eyeIndex]; #ifdef USE_OBLIQUE_MODE - float2 res2 = mul(g_mInvScrProjection, float4(pixXY, zDptBufSpace, 1.0)).zw; - return res2.x / res2.y; + float2 res2 = mul(g_mInvScrProjection, float4(pixXY, zDptBufSpace, 1.0)).zw; + return res2.x / res2.y; #else // for perspective projection m22 is zero and m23 is +1/-1 (depends on left/right hand proj) // however this function must also work for orthographic projection so we keep it like this. @@ -233,19 +233,19 @@ void LIGHTLISTGEN(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) for(int i=0; i /// Convert EV100 to Candela @@ -174,7 +173,7 @@ public static float ConvertEvToLuminance(float ev) /// /// public static float ConvertEvToCandela(float ev) - // From punctual point of view candela and luminance is the same + // From punctual point of view candela and luminance is the same => ConvertEvToLuminance(ev); /// @@ -184,7 +183,7 @@ public static float ConvertEvToCandela(float ev) /// /// public static float ConvertEvToLux(float ev, float distance) - // From punctual point of view candela and luminance is the same + // From punctual point of view candela and luminance is the same => ConvertCandelaToLux(ConvertEvToLuminance(ev), distance); /// @@ -204,7 +203,7 @@ public static float ConvertLuminanceToEv(float luminance) /// /// public static float ConvertCandelaToEv(float candela) - // From punctual point of view candela and luminance is the same + // From punctual point of view candela and luminance is the same => ConvertLuminanceToEv(candela); /// @@ -214,7 +213,7 @@ public static float ConvertCandelaToEv(float candela) /// /// public static float ConvertLuxToEv(float lux, float distance) - // From punctual point of view candela and luminance is the same + // From punctual point of view candela and luminance is the same => ConvertLuminanceToEv(ConvertLuxToCandela(lux, distance)); // Helper for punctual and area light unit conversion @@ -492,7 +491,7 @@ internal static void ConvertLightIntensity(LightUnit oldLightUnit, LightUnit new // Lux -> else if (oldLightUnit == LightUnit.Lux && newLightUnit == LightUnit.Lumen) intensity = LightUtils.ConvertPunctualLightLuxToLumen(lightType, hdLight.spotLightShape, intensity, hdLight.enableSpotReflector, - light.spotAngle, hdLight.aspectRatio, hdLight.luxAtDistance); + light.spotAngle, hdLight.aspectRatio, hdLight.luxAtDistance); else if (oldLightUnit == LightUnit.Lux && newLightUnit == LightUnit.Candela) intensity = LightUtils.ConvertLuxToCandela(intensity, hdLight.luxAtDistance); else if (oldLightUnit == LightUnit.Lux && newLightUnit == LightUnit.Ev100) @@ -500,7 +499,7 @@ internal static void ConvertLightIntensity(LightUnit oldLightUnit, LightUnit new // EV100 -> else if (oldLightUnit == LightUnit.Ev100 && newLightUnit == LightUnit.Lumen) intensity = LightUtils.ConvertPunctualLightEvToLumen(lightType, hdLight.spotLightShape, intensity, hdLight.enableSpotReflector, - light.spotAngle, hdLight.aspectRatio); + light.spotAngle, hdLight.aspectRatio); else if (oldLightUnit == LightUnit.Ev100 && newLightUnit == LightUnit.Candela) intensity = LightUtils.ConvertEvToCandela(intensity); else if (oldLightUnit == LightUnit.Ev100 && newLightUnit == LightUnit.Lux) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute index 7c128f232be..5aabd1dbb82 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute @@ -6,7 +6,7 @@ // #pragma enable_d3d11_debug_symbols // The process is done in 3 steps. We start by converting the depth from oblique to regular frustum depth. -// Then we build a mip chain of both the depth and the color. The depth is averaged in 2x2 and the color +// Then we build a mip chain of both the depth and the color. The depth is averaged in 2x2 and the color // is filtered in a wider neighborhood (otherwise we get too much artifacts) when doing the actual filtering. // The filtering estimates the pixel footprint of the blur based on the distance to the occluder, the roughness // of the current mip and the distance to the pixel. we then select the input from the right mip (the idea) @@ -58,7 +58,7 @@ CBUFFER_END // Output buffer of our filtering code RW_TEXTURE2D(float3, _FilteredPlanarReflectionBuffer); -// These angles have been experimentally computed to match the result of reflection probes. Initially this was a table dependent on angle and roughness, but given that every planar has a +// These angles have been experimentally computed to match the result of reflection probes. Initially this was a table dependent on angle and roughness, but given that every planar has a // finite number of LODs and those LODS have fixed roughness and the angle changes the result, but not that much. I changed it to a per LOD LUT static const float reflectionProbeEquivalentAngles[UNITY_SPECCUBE_LOD_STEPS + 1] = {0.0, 0.04, 0.12, 0.4, 0.9, 1.2, 1.2}; @@ -86,7 +86,7 @@ void FilterPlanarReflection(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 // Compute the position on the plane we shall be integrating from float t = -1.0; if (!IntersectRayPlane(_CaptureCameraPositon, rayDirection, _ReflectionPlanePosition, _ReflectionPlaneNormal, t)) - { + { // If there is no plane intersection, there is nothing to filter (means that is a position that cannot be reflected) _FilteredPlanarReflectionBuffer[currentCoord] = float3(0.0, 0.0, 0.0); return; @@ -120,7 +120,7 @@ void FilterPlanarReflection(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 const float mipBias = _SourceMipIndex > 3 ? lerp(0.0, 2.0, (_MaxMipLevels - _SourceMipIndex) / _MaxMipLevels) : 0.0; // Read the integration color that we should take - const float3 integrationColor = SAMPLE_TEXTURE2D_LOD(_ReflectionColorMipChain, s_trilinear_clamp_sampler, sampleCoords, clamp(miplevel + _SourceMipIndex + mipBias, 0, _MaxMipLevels)).xyz; + const float3 integrationColor = SAMPLE_TEXTURE2D_LOD(_ReflectionColorMipChain, s_trilinear_clamp_sampler, sampleCoords, clamp(miplevel + _SourceMipIndex + mipBias, 0, _MaxMipLevels)).xyz; // Write the output ray data _FilteredPlanarReflectionBuffer[currentCoord] = integrationColor; @@ -148,7 +148,7 @@ void DownScale(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupThreadId { const int2 tapCoord = currentCoord * 2 + uint2(x, y); // If the pixel is outside the current screen size, its weight becomes zero - float weight = tapCoord.x > _CaptureCurrentScreenSize.x || tapCoord.x < 0 + float weight = tapCoord.x > _CaptureCurrentScreenSize.x || tapCoord.x < 0 || tapCoord.y > _CaptureCurrentScreenSize.y || tapCoord.y < 0 ? 0.0 : 1.0; averageColor += LOAD_TEXTURE2D_LOD(_ReflectionColorMipChain, tapCoord, _SourceMipIndex).xyz * weight; sumW += weight; @@ -158,7 +158,7 @@ void DownScale(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupThreadId _HalfResReflectionBuffer[currentCoord] = averageColor / sumW; // We average the 4 depths and move on - _HalfResDepthBuffer[currentCoord] = (LOAD_TEXTURE2D_LOD(_DepthTextureMipChain, currentCoord * 2, _SourceMipIndex).x + _HalfResDepthBuffer[currentCoord] = (LOAD_TEXTURE2D_LOD(_DepthTextureMipChain, currentCoord * 2, _SourceMipIndex).x + LOAD_TEXTURE2D_LOD(_DepthTextureMipChain, currentCoord * 2 + uint2(0,1), _SourceMipIndex).x + LOAD_TEXTURE2D_LOD(_DepthTextureMipChain, currentCoord * 2 + uint2(1,0), _SourceMipIndex).x + LOAD_TEXTURE2D_LOD(_DepthTextureMipChain, currentCoord * 2 + uint2(1,1), _SourceMipIndex).x) * 0.25; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/DebugDisplayProbeVolume.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/DebugDisplayProbeVolume.shader index f9d28b2b62b..a8b904debbe 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/DebugDisplayProbeVolume.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/DebugDisplayProbeVolume.shader @@ -104,7 +104,7 @@ Shader "Hidden/ScriptableRenderPipeline/DebugDisplayProbeVolume" #endif float valueValidity = saturate((ProbeVolumeSampleValidity(uvw) - _ValidRange.x) * _ValidRange.y); - + #if SHADEROPTIONS_PROBE_VOLUMES_BILATERAL_FILTERING == PROBEVOLUMESBILATERALFILTERINGMODES_OCTAHEDRAL_DEPTH float2 valueOctahedralDepthMeanAndVariance = saturate((SAMPLE_TEXTURE2D_LOD(_AtlasTextureOctahedralDepth, ltc_linear_clamp_sampler, input.texcoord * _AtlasTextureOctahedralDepthScaleBias.xy + _AtlasTextureOctahedralDepthScaleBias.zw, 0).xy - _ValidRange.x) * _ValidRange.y); #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs index 0f4c8ae14e2..14d45eaac13 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.cs @@ -370,7 +370,6 @@ internal struct ProbeVolumeSettingsKey public int resolutionZ; public float backfaceTolerance; public int dilationIterations; - } [Serializable] @@ -562,7 +561,6 @@ internal ProbeVolumeEngineData ConvertToEngineData() return data; } - } // class ProbeVolumeArtistParameters [ExecuteAlways] @@ -717,8 +715,8 @@ internal bool IsAssetCompatibleResolution() if (probeVolumeAsset) { return parameters.resolutionX == probeVolumeAsset.resolutionX && - parameters.resolutionY == probeVolumeAsset.resolutionY && - parameters.resolutionZ == probeVolumeAsset.resolutionZ; + parameters.resolutionY == probeVolumeAsset.resolutionY && + parameters.resolutionZ == probeVolumeAsset.resolutionZ; } return false; } @@ -804,7 +802,7 @@ internal void OnProbesBakeCompleted() // In the future, we should add an API call for GetAdditionalBakedProbes() without octahedralDepth required. var octahedralDepth = new NativeArray(numProbes * 8 * 8, Allocator.Temp, NativeArrayOptions.UninitializedMemory); - if(UnityEditor.Experimental.Lightmapping.GetAdditionalBakedProbes(GetID(), sh, validity, octahedralDepth)) + if (UnityEditor.Experimental.Lightmapping.GetAdditionalBakedProbes(GetID(), sh, validity, octahedralDepth)) { if (!probeVolumeAsset || GetID() != probeVolumeAsset.instanceID) probeVolumeAsset = ProbeVolumeAsset.CreateAsset(GetID()); @@ -1038,6 +1036,7 @@ internal void DrawSelectedProbes() foreach (Matrix4x4[] matrices in m_DebugProbeMatricesList) Graphics.DrawMeshInstanced(mesh, submeshIndex, material, matrices, matrices.Length, properties, castShadows, receiveShadows, layer, emptyCamera, lightProbeUsage, lightProbeProxyVolume); } + #endif } } // UnityEngine.Experimental.Rendering.HDPipeline diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl index ff11d05d630..dc3c0b0c81e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl @@ -133,9 +133,9 @@ void ProbeVolumeComputeOBBBoundsToFrame(OrientedBBox probeVolumeBounds, out floa { obbFrame = float3x3(probeVolumeBounds.right, probeVolumeBounds.up, cross(probeVolumeBounds.right, probeVolumeBounds.up)); obbExtents = float3(probeVolumeBounds.extentX, probeVolumeBounds.extentY, probeVolumeBounds.extentZ); - obbCenter = probeVolumeBounds.center; + obbCenter = probeVolumeBounds.center; } - + void ProbeVolumeComputeTexel3DAndWeight( float weightHierarchy, @@ -353,7 +353,7 @@ float3 ProbeVolumeEvaluateSphericalHarmonicsL0(float3 normalWS, ProbeVolumeSpher #ifdef DEBUG_DISPLAY if (_DebugProbeVolumeMode == PROBEVOLUMEDEBUGMODE_VISUALIZE_DEBUG_COLORS) { - float3 debugColors = coefficients.data[0].rgb; + float3 debugColors = coefficients.data[0].rgb; return debugColors; } else if (_DebugProbeVolumeMode == PROBEVOLUMEDEBUGMODE_VISUALIZE_VALIDITY) @@ -375,7 +375,7 @@ float3 ProbeVolumeEvaluateSphericalHarmonicsL1(float3 normalWS, ProbeVolumeSpher #ifdef DEBUG_DISPLAY if (_DebugProbeVolumeMode == PROBEVOLUMEDEBUGMODE_VISUALIZE_DEBUG_COLORS) { - float3 debugColors = coefficients.data[0].rgb; + float3 debugColors = coefficients.data[0].rgb; return debugColors; } else if (_DebugProbeVolumeMode == PROBEVOLUMEDEBUGMODE_VISUALIZE_VALIDITY) @@ -397,7 +397,7 @@ float3 ProbeVolumeEvaluateSphericalHarmonicsL2(float3 normalWS, ProbeVolumeSpher #ifdef DEBUG_DISPLAY if (_DebugProbeVolumeMode == PROBEVOLUMEDEBUGMODE_VISUALIZE_DEBUG_COLORS) { - float3 debugColors = coefficients.data[0].rgb; + float3 debugColors = coefficients.data[0].rgb; return debugColors; } else if (_DebugProbeVolumeMode == PROBEVOLUMEDEBUGMODE_VISUALIZE_VALIDITY) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAccumulate.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAccumulate.hlsl index 35ce9eb06c5..90fef27040f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAccumulate.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAccumulate.hlsl @@ -41,7 +41,7 @@ #elif PROBE_VOLUMES_ACCUMULATE_MODE == PROBEVOLUMESENCODINGMODES_SPHERICAL_HARMONICS_L2 ZERO_INITIALIZE(ProbeVolumeSphericalHarmonicsL2, coefficients); #endif - + #if !SHADEROPTIONS_PROBE_VOLUMES_ADDITIVE_BLENDING if (weightHierarchy >= 1.0) { return; } @@ -107,7 +107,7 @@ float3 obbExtents; float3 obbCenter; ProbeVolumeComputeOBBBoundsToFrame(s_probeVolumeBounds, obbFrame, obbExtents, obbCenter); - + // Note: When normal bias is > 0, bounds using in tile / cluster assignment are conservatively dilated CPU side to handle worst case normal bias. float3 samplePositionWS = normalWS * s_probeVolumeData.normalBiasWS + posInput.positionWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAsset.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAsset.cs index 5ddbb3cf08c..82882f96b0e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAsset.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAsset.cs @@ -93,41 +93,42 @@ internal static ProbeVolumeAsset CreateAsset(int id = -1) return asset; } - protected internal static Vector3Int[] s_Offsets = new Vector3Int[] { + protected internal static Vector3Int[] s_Offsets = new Vector3Int[] + { // middle slice - new Vector3Int( 1, 0, 0), - new Vector3Int( 1, 0, 1), - new Vector3Int( 1, 0, -1), + new Vector3Int(1, 0, 0), + new Vector3Int(1, 0, 1), + new Vector3Int(1, 0, -1), new Vector3Int(-1, 0, 0), new Vector3Int(-1, 0, 1), new Vector3Int(-1, 0, -1), - new Vector3Int( 0, 0, 1), - new Vector3Int( 0, 0, -1), + new Vector3Int(0, 0, 1), + new Vector3Int(0, 0, -1), // upper slice - new Vector3Int( 0, 1, 0), - new Vector3Int( 1, 1, 0), - new Vector3Int( 1, 1, 1), - new Vector3Int( 1, 1, -1), + new Vector3Int(0, 1, 0), + new Vector3Int(1, 1, 0), + new Vector3Int(1, 1, 1), + new Vector3Int(1, 1, -1), new Vector3Int(-1, 1, 0), new Vector3Int(-1, 1, 1), new Vector3Int(-1, 1, -1), - new Vector3Int( 0, 1, 1), - new Vector3Int( 0, 1, -1), + new Vector3Int(0, 1, 1), + new Vector3Int(0, 1, -1), // lower slice - new Vector3Int( 0, -1, 0), - new Vector3Int( 1, -1, 0), - new Vector3Int( 1, -1, 1), - new Vector3Int( 1, -1, -1), + new Vector3Int(0, -1, 0), + new Vector3Int(1, -1, 0), + new Vector3Int(1, -1, 1), + new Vector3Int(1, -1, -1), new Vector3Int(-1, -1, 0), new Vector3Int(-1, -1, 1), new Vector3Int(-1, -1, -1), - new Vector3Int( 0, -1, 1), - new Vector3Int( 0, -1, -1), + new Vector3Int(0, -1, 1), + new Vector3Int(0, -1, -1), }; protected internal int ComputeIndex1DFrom3D(Vector3Int pos) @@ -219,7 +220,7 @@ void DilateIntoInvalidProbes(float backfaceTolerance, int dilateIterations) // Foreach probe, gather neighboring probe data, weighted by validity. // TODO: "validity" is actually stored as how occluded the surface is, so it is really inverse validity. - // We should probably rename this to avoid confusion. + // We should probably rename this to avoid confusion. for (int z = 0; z < resolutionZ; ++z) { for (int y = 0; y < resolutionY; ++y) @@ -268,6 +269,7 @@ internal void Dilate(float backfaceTolerance, int dilationIterations) this.backfaceTolerance = backfaceTolerance; this.dilationIterations = dilationIterations; } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlas.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlas.hlsl index 15a973ecccc..277f3a5ad60 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlas.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlas.hlsl @@ -124,7 +124,7 @@ void ProbeVolumeSwizzleAndNormalizeSphericalHarmonicsL2(inout ProbeVolumeSpheric // Now just need to perform final SH2 normalization: // Again, normalization from: https://www.ppsloan.org/publications/StupidSH36.pdf // Appendix A10 Shader/CPU code for Irradiance Environment Maps - + // Normalize DC term: coefficients.data[0].w -= coefficients.data[3].z; coefficients.data[1].w -= coefficients.data[4].z; @@ -136,4 +136,4 @@ void ProbeVolumeSwizzleAndNormalizeSphericalHarmonicsL2(inout ProbeVolumeSpheric coefficients.data[5].z *= 3.0; } -#endif \ No newline at end of file +#endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlasBlit.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlasBlit.compute index 73c5cbb1206..3128afe810e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlasBlit.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeAtlasBlit.compute @@ -82,7 +82,7 @@ void PROBE_VOLUME_ATLAS_BLIT_KERNEL(uint groupThreadId : SV_GroupThreadID, uint const uint SH_STRIDE_L2 = (9 * 3) - SH_STRIDE_L01; #if SHADEROPTIONS_PROBE_VOLUMES_ENCODING_MODE == PROBEVOLUMESENCODINGMODES_SPHERICAL_HARMONICS_L1 - + _ProbeVolumeAtlasWriteTextureSH[uint3(writeIndex.x, writeIndex.y, writeIndex.z + _ProbeVolumeAtlasResolutionAndSliceCount.z * 0)] = float4( _ProbeVolumeAtlasReadSHL01Buffer[readIndex * SH_STRIDE_L01 + 0], // shAr.w _ProbeVolumeAtlasReadSHL01Buffer[readIndex * SH_STRIDE_L01 + 1], // shAg.w @@ -150,5 +150,5 @@ void PROBE_VOLUME_ATLAS_BLIT_KERNEL(uint groupThreadId : SV_GroupThreadID, uint #else #error "Unsupported ShaderOptions.ProbeVolumesAtlasEncodingMode."; -#endif +#endif } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs index 9929416eeb6..ad25be4d9da 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeLighting.cs @@ -358,16 +358,16 @@ unsafe void UpdateShaderVariablesGlobalProbeVolumes(ref ShaderVariablesGlobal cb cb._EnableProbeVolumes = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) ? 1u : 0u; cb._ProbeVolumeCount = (uint)m_VisibleProbeVolumeBounds.Count; cb._ProbeVolumeAtlasResolutionAndSliceCount = new Vector4( - s_ProbeVolumeAtlasResolution, - s_ProbeVolumeAtlasResolution, - s_ProbeVolumeAtlasResolution, - m_ProbeVolumeAtlasSHRTDepthSliceCount + s_ProbeVolumeAtlasResolution, + s_ProbeVolumeAtlasResolution, + s_ProbeVolumeAtlasResolution, + m_ProbeVolumeAtlasSHRTDepthSliceCount ); cb._ProbeVolumeAtlasResolutionAndSliceCountInverse = new Vector4( - 1.0f / (float)s_ProbeVolumeAtlasResolution, - 1.0f / (float)s_ProbeVolumeAtlasResolution, - 1.0f / (float)s_ProbeVolumeAtlasResolution, - 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount + 1.0f / (float)s_ProbeVolumeAtlasResolution, + 1.0f / (float)s_ProbeVolumeAtlasResolution, + 1.0f / (float)s_ProbeVolumeAtlasResolution, + 1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount ); if (ShaderConfig.s_ProbeVolumesBilateralFilteringMode == ProbeVolumesBilateralFilteringModes.OctahedralDepth) @@ -549,7 +549,6 @@ internal bool EnsureProbeVolumeInAtlas(ScriptableRenderContext renderContext, Co int numThreadGroups = Mathf.CeilToInt((float)size / (float)kBatchSize); cmd.DispatchCompute(s_ProbeVolumeAtlasBlitCS, s_ProbeVolumeAtlasBlitKernel, numThreadGroups, 1, 1); return true; - } return false; } @@ -673,7 +672,6 @@ internal bool EnsureProbeVolumeInAtlasOctahedralDepth(ScriptableRenderContext re cmd.DispatchCompute(s_ProbeVolumeAtlasOctahedralDepthConvolveCS, s_ProbeVolumeAtlasOctahedralDepthConvolveKernel, probeCountX, probeCountY, 1); } return true; - } return false; } @@ -881,8 +879,8 @@ internal static float CalculateProbeVolumeLogVolume(Vector3 size) // - 1+ term is to prevent having negative values in the log result // - 1000* is too keep 3 digit after the dot while we truncate the result later // - 1048575 is 2^20-1 as we pack the result on 20bit later - float boxVolume = 8f* size.x * size.y * size.z; - float logVolume = Mathf.Clamp(Mathf.Log(1 + boxVolume, 1.05f)*1000, 0, 1048575); + float boxVolume = 8f * size.x * size.y * size.z; + float logVolume = Mathf.Clamp(Mathf.Log(1 + boxVolume, 1.05f) * 1000, 0, 1048575); return logVolume; } @@ -1026,6 +1024,5 @@ static void DisplayProbeVolumeAtlas(CommandBuffer cmd, in ProbeVolumeDebugOverla cmd.DrawProcedural(Matrix4x4.identity, parameters.material, parameters.material.FindPass("ProbeVolume"), MeshTopology.Triangles, 3, 1, propertyBlock); debugOverlay.Next(); } - } // class ProbeVolumeLighting } // namespace UnityEngine.Experimental.Rendering.HDPipeline diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeManager.cs index 6ca6a0fa081..b437e2280b7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ProbeVolume/ProbeVolumeManager.cs @@ -45,6 +45,7 @@ internal void RegisterVolume(ProbeVolume volume) volumes.Add(volume); } + internal void DeRegisterVolume(ProbeVolume volume) { if (!volumes.Contains(volume)) @@ -153,6 +154,7 @@ internal static void BakeSelected() UnityEditor.Lightmapping.BakeAsync(); } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Legacy.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Legacy.cs index f567c805d18..93de81d4611 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Legacy.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Legacy.cs @@ -11,7 +11,7 @@ ReflectionProbe reflectionProbe { get { - if(m_LegacyProbe == null || m_LegacyProbe.Equals(null)) + if (m_LegacyProbe == null || m_LegacyProbe.Equals(null)) { m_LegacyProbe = GetComponent(); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Migration.cs index 1e6d632db22..e6a3f705c30 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDAdditionalReflectionData.Migration.cs @@ -20,85 +20,85 @@ enum ReflectionProbeVersion static readonly MigrationDescription k_ReflectionProbeMigration = MigrationDescription.New( - MigrationStep.New(ReflectionProbeVersion.RemoveUsageOfLegacyProbeParamsForStocking, (HDAdditionalReflectionData t) => - { + MigrationStep.New(ReflectionProbeVersion.RemoveUsageOfLegacyProbeParamsForStocking, (HDAdditionalReflectionData t) => + { #pragma warning disable 618 // Type or member is obsolete - t.m_ObsoleteBlendDistancePositive = t.m_ObsoleteBlendDistanceNegative = Vector3.one * t.reflectionProbe.blendDistance; - t.m_ObsoleteWeight = t.reflectionProbe.importance; - t.m_ObsoleteMultiplier = t.reflectionProbe.intensity; - switch (t.reflectionProbe.refreshMode) - { - case UnityEngine.Rendering.ReflectionProbeRefreshMode.EveryFrame: t.realtimeMode = ProbeSettings.RealtimeMode.EveryFrame; break; - case UnityEngine.Rendering.ReflectionProbeRefreshMode.OnAwake: t.realtimeMode = ProbeSettings.RealtimeMode.OnEnable; break; - } -#pragma warning restore 618 // Type or member is obsolete - }), - MigrationStep.New(ReflectionProbeVersion.UseInfluenceVolume, (HDAdditionalReflectionData t) => + t.m_ObsoleteBlendDistancePositive = t.m_ObsoleteBlendDistanceNegative = Vector3.one * t.reflectionProbe.blendDistance; + t.m_ObsoleteWeight = t.reflectionProbe.importance; + t.m_ObsoleteMultiplier = t.reflectionProbe.intensity; + switch (t.reflectionProbe.refreshMode) { + case UnityEngine.Rendering.ReflectionProbeRefreshMode.EveryFrame: t.realtimeMode = ProbeSettings.RealtimeMode.EveryFrame; break; + case UnityEngine.Rendering.ReflectionProbeRefreshMode.OnAwake: t.realtimeMode = ProbeSettings.RealtimeMode.OnEnable; break; + } +#pragma warning restore 618 // Type or member is obsolete + }), + MigrationStep.New(ReflectionProbeVersion.UseInfluenceVolume, (HDAdditionalReflectionData t) => + { #pragma warning disable 618 - t.m_ObsoleteInfluenceVolume = t.m_ObsoleteInfluenceVolume ?? new InfluenceVolume(); - t.m_ObsoleteInfluenceVolume.boxSize = t.reflectionProbe.size; - t.m_ObsoleteInfluenceVolume.obsoleteOffset = t.reflectionProbe.center; - t.m_ObsoleteInfluenceVolume.sphereRadius = t.m_ObsoleteInfluenceSphereRadius; - t.m_ObsoleteInfluenceVolume.shape = t.m_ObsoleteInfluenceShape; //must be done after each size transfert - t.m_ObsoleteInfluenceVolume.boxBlendDistancePositive = t.m_ObsoleteBlendDistancePositive; - t.m_ObsoleteInfluenceVolume.boxBlendDistanceNegative = t.m_ObsoleteBlendDistanceNegative; - t.m_ObsoleteInfluenceVolume.boxBlendNormalDistancePositive = t.m_ObsoleteBlendNormalDistancePositive; - t.m_ObsoleteInfluenceVolume.boxBlendNormalDistanceNegative = t.m_ObsoleteBlendNormalDistanceNegative; - t.m_ObsoleteInfluenceVolume.boxSideFadePositive = t.m_ObsoleteBoxSideFadePositive; - t.m_ObsoleteInfluenceVolume.boxSideFadeNegative = t.m_ObsoleteBoxSideFadeNegative; + t.m_ObsoleteInfluenceVolume = t.m_ObsoleteInfluenceVolume ?? new InfluenceVolume(); + t.m_ObsoleteInfluenceVolume.boxSize = t.reflectionProbe.size; + t.m_ObsoleteInfluenceVolume.obsoleteOffset = t.reflectionProbe.center; + t.m_ObsoleteInfluenceVolume.sphereRadius = t.m_ObsoleteInfluenceSphereRadius; + t.m_ObsoleteInfluenceVolume.shape = t.m_ObsoleteInfluenceShape; //must be done after each size transfert + t.m_ObsoleteInfluenceVolume.boxBlendDistancePositive = t.m_ObsoleteBlendDistancePositive; + t.m_ObsoleteInfluenceVolume.boxBlendDistanceNegative = t.m_ObsoleteBlendDistanceNegative; + t.m_ObsoleteInfluenceVolume.boxBlendNormalDistancePositive = t.m_ObsoleteBlendNormalDistancePositive; + t.m_ObsoleteInfluenceVolume.boxBlendNormalDistanceNegative = t.m_ObsoleteBlendNormalDistanceNegative; + t.m_ObsoleteInfluenceVolume.boxSideFadePositive = t.m_ObsoleteBoxSideFadePositive; + t.m_ObsoleteInfluenceVolume.boxSideFadeNegative = t.m_ObsoleteBoxSideFadeNegative; #pragma warning restore 618 - }), - MigrationStep.New(ReflectionProbeVersion.MergeEditors, (HDAdditionalReflectionData t) => - { + }), + MigrationStep.New(ReflectionProbeVersion.MergeEditors, (HDAdditionalReflectionData t) => + { #pragma warning disable 618 - t.m_ObsoleteInfiniteProjection = !t.reflectionProbe.boxProjection; + t.m_ObsoleteInfiniteProjection = !t.reflectionProbe.boxProjection; #pragma warning restore 618 - t.reflectionProbe.boxProjection = false; - }), - MigrationStep.New(ReflectionProbeVersion.AddCaptureSettingsAndFrameSettings, (HDAdditionalReflectionData t) => - { + t.reflectionProbe.boxProjection = false; + }), + MigrationStep.New(ReflectionProbeVersion.AddCaptureSettingsAndFrameSettings, (HDAdditionalReflectionData t) => + { #pragma warning disable 618, 612 - t.m_ObsoleteCaptureSettings = t.m_ObsoleteCaptureSettings ?? new ObsoleteCaptureSettings(); - t.m_ObsoleteCaptureSettings.cullingMask = t.reflectionProbe.cullingMask; + t.m_ObsoleteCaptureSettings = t.m_ObsoleteCaptureSettings ?? new ObsoleteCaptureSettings(); + t.m_ObsoleteCaptureSettings.cullingMask = t.reflectionProbe.cullingMask; #if UNITY_EDITOR //m_UseOcclusionCulling is not exposed in c# ! - var serializedReflectionProbe = new UnityEditor.SerializedObject(t.reflectionProbe); - t.m_ObsoleteCaptureSettings.useOcclusionCulling = serializedReflectionProbe.FindProperty("m_UseOcclusionCulling").boolValue; + var serializedReflectionProbe = new UnityEditor.SerializedObject(t.reflectionProbe); + t.m_ObsoleteCaptureSettings.useOcclusionCulling = serializedReflectionProbe.FindProperty("m_UseOcclusionCulling").boolValue; #endif - t.m_ObsoleteCaptureSettings.nearClipPlane = t.reflectionProbe.nearClipPlane; - t.m_ObsoleteCaptureSettings.farClipPlane = t.reflectionProbe.farClipPlane; + t.m_ObsoleteCaptureSettings.nearClipPlane = t.reflectionProbe.nearClipPlane; + t.m_ObsoleteCaptureSettings.farClipPlane = t.reflectionProbe.farClipPlane; #pragma warning restore 618, 612 - }), - MigrationStep.New(ReflectionProbeVersion.ModeAndTextures, (HDAdditionalReflectionData t) => - { + }), + MigrationStep.New(ReflectionProbeVersion.ModeAndTextures, (HDAdditionalReflectionData t) => + { #pragma warning disable 618 - t.m_ObsoleteMode = (ProbeSettings.Mode)t.reflectionProbe.mode; + t.m_ObsoleteMode = (ProbeSettings.Mode)t.reflectionProbe.mode; #pragma warning restore 618 - t.SetTexture(ProbeSettings.Mode.Baked, t.reflectionProbe.bakedTexture); - t.SetTexture(ProbeSettings.Mode.Custom, t.reflectionProbe.customBakedTexture); - }), - MigrationStep.New(ReflectionProbeVersion.ProbeSettings, (HDAdditionalReflectionData t) => - { - k_Migration.ExecuteStep(t, Version.ProbeSettings); + t.SetTexture(ProbeSettings.Mode.Baked, t.reflectionProbe.bakedTexture); + t.SetTexture(ProbeSettings.Mode.Custom, t.reflectionProbe.customBakedTexture); + }), + MigrationStep.New(ReflectionProbeVersion.ProbeSettings, (HDAdditionalReflectionData t) => + { + k_Migration.ExecuteStep(t, Version.ProbeSettings); #pragma warning disable 618 - // Migrate capture position - // Previously, the capture position of a reflection probe was the position of the game object - // and the center of the influence volume is (transform.position + t.influenceVolume.m_ObsoleteOffset) in world space - // Now, the center of the influence volume is the position of the transform and the capture position - // is t.probeSettings.proxySettings.capturePositionProxySpace and is in capture space + // Migrate capture position + // Previously, the capture position of a reflection probe was the position of the game object + // and the center of the influence volume is (transform.position + t.influenceVolume.m_ObsoleteOffset) in world space + // Now, the center of the influence volume is the position of the transform and the capture position + // is t.probeSettings.proxySettings.capturePositionProxySpace and is in capture space - var capturePositionWS = t.transform.position; - // set the transform position to the influence position world space - var mat = Matrix4x4.TRS(t.transform.position, t.transform.rotation, Vector3.one); - t.transform.position = mat.MultiplyPoint(t.influenceVolume.obsoleteOffset); + var capturePositionWS = t.transform.position; + // set the transform position to the influence position world space + var mat = Matrix4x4.TRS(t.transform.position, t.transform.rotation, Vector3.one); + t.transform.position = mat.MultiplyPoint(t.influenceVolume.obsoleteOffset); - var capturePositionPS = t.proxyToWorld.inverse.MultiplyPoint(capturePositionWS); - t.m_ProbeSettings.proxySettings.capturePositionProxySpace = capturePositionPS; + var capturePositionPS = t.proxyToWorld.inverse.MultiplyPoint(capturePositionWS); + t.m_ProbeSettings.proxySettings.capturePositionProxySpace = capturePositionPS; #pragma warning restore 618 - }), - MigrationStep.New(ReflectionProbeVersion.SeparatePassThrough, (HDAdditionalReflectionData t) => k_Migration.ExecuteStep(t, Version.SeparatePassThrough)), - MigrationStep.New(ReflectionProbeVersion.UpgradeFrameSettingsToStruct, (HDAdditionalReflectionData t) => k_Migration.ExecuteStep(t, Version.UpgradeFrameSettingsToStruct)) + }), + MigrationStep.New(ReflectionProbeVersion.SeparatePassThrough, (HDAdditionalReflectionData t) => k_Migration.ExecuteStep(t, Version.SeparatePassThrough)), + MigrationStep.New(ReflectionProbeVersion.UpgradeFrameSettingsToStruct, (HDAdditionalReflectionData t) => k_Migration.ExecuteStep(t, Version.UpgradeFrameSettingsToStruct)) ); [SerializeField, FormerlySerializedAs("version"), FormerlySerializedAs("m_Version")] diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbe.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbe.cs index 259f179ec02..f900585d5d8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbe.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbe.cs @@ -259,6 +259,7 @@ public Texture GetTexture(ProbeSettings.Mode targetMode) default: throw new ArgumentOutOfRangeException(); } } + /// /// Set the texture for a specific target mode. /// @@ -337,6 +338,7 @@ public RenderData GetRenderData(ProbeSettings.Mode targetMode) default: throw new ArgumentOutOfRangeException(); } } + /// /// Set the render data for a specific mode. /// @@ -478,8 +480,8 @@ public ProbeSettings settings internal Vector3 influenceExtents => influenceVolume.extents; internal Matrix4x4 proxyToWorld => proxyVolume != null - ? Matrix4x4.TRS(proxyVolume.transform.position, proxyVolume.transform.rotation, Vector3.one) - : influenceToWorld; + ? Matrix4x4.TRS(proxyVolume.transform.position, proxyVolume.transform.rotation, Vector3.one) + : influenceToWorld; internal bool wasRenderedAfterOnEnable { get; private set; } = false; internal int lastRenderedFrame { get; private set; } = int.MinValue; @@ -499,7 +501,7 @@ internal void SetIsRendered(int frame) /// Prepare the probe for culling. /// You should call this method when you update the parameters during runtime. /// - public virtual void PrepareCulling() { } + public virtual void PrepareCulling() {} /// /// Request to render this probe next update. @@ -541,6 +543,7 @@ void OnEnable() UnityEditor.EditorApplication.hierarchyChanged += UpdateProbeName; #endif } + void OnDisable() { HDProbeSystem.UnregisterProbe(this); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbeSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbeSystem.cs index b28dff79630..df04d57a323 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbeSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDProbeSystem.cs @@ -90,46 +90,46 @@ public static Texture CreateRenderTargetForMode(HDProbe probe, ProbeSettings.Mod switch (targetMode) { case ProbeSettings.Mode.Realtime: - { - var format = (GraphicsFormat)hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionProbeFormat; + { + var format = (GraphicsFormat)hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionProbeFormat; - switch (settings.type) - { - case ProbeSettings.ProbeType.PlanarProbe: - target = HDRenderUtilities.CreatePlanarProbeRenderTarget( - (int)probe.resolution, format - ); - break; - case ProbeSettings.ProbeType.ReflectionProbe: - target = HDRenderUtilities.CreateReflectionProbeRenderTarget( - (int)hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize, - format - ); - break; - } - break; + switch (settings.type) + { + case ProbeSettings.ProbeType.PlanarProbe: + target = HDRenderUtilities.CreatePlanarProbeRenderTarget( + (int)probe.resolution, format + ); + break; + case ProbeSettings.ProbeType.ReflectionProbe: + target = HDRenderUtilities.CreateReflectionProbeRenderTarget( + (int)hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize, + format + ); + break; } + break; + } case ProbeSettings.Mode.Baked: case ProbeSettings.Mode.Custom: - { - // Custom and Baked texture only support float16 for now - var format = GraphicsFormat.R16G16B16A16_SFloat; + { + // Custom and Baked texture only support float16 for now + var format = GraphicsFormat.R16G16B16A16_SFloat; - switch (settings.type) - { - case ProbeSettings.ProbeType.PlanarProbe: - target = HDRenderUtilities.CreatePlanarProbeRenderTarget( - (int)probe.resolution, format - ); - break; - case ProbeSettings.ProbeType.ReflectionProbe: - target = HDRenderUtilities.CreateReflectionProbeRenderTarget( - (int)hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize, format - ); - break; - } - break; + switch (settings.type) + { + case ProbeSettings.ProbeType.PlanarProbe: + target = HDRenderUtilities.CreatePlanarProbeRenderTarget( + (int)probe.resolution, format + ); + break; + case ProbeSettings.ProbeType.ReflectionProbe: + target = HDRenderUtilities.CreateReflectionProbeRenderTarget( + (int)hd.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize, format + ); + break; } + break; + } } return target; @@ -328,7 +328,7 @@ int probeCount if (probeBounds != null) { var h = new Hash128(); - fixed (BoundingSphere* s = &probeBounds[0]) + fixed(BoundingSphere* s = &probeBounds[0]) { var stride = (ulong)UnsafeUtility.SizeOf(); var size = stride * (ulong)probeBounds.Length; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDRuntimeReflectionSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDRuntimeReflectionSystem.cs index 0eba21ec6e5..78d4e2f6eeb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDRuntimeReflectionSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/HDRuntimeReflectionSystem.cs @@ -23,6 +23,7 @@ static HDRuntimeReflectionSystem() var method = type.GetMethod("BuiltinUpdate", BindingFlags.Static | BindingFlags.NonPublic); BuiltinUpdate = method; } + #endif static HDRuntimeReflectionSystem k_instance = new HDRuntimeReflectionSystem(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbeCache.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbeCache.cs index 37e53ff7676..b5f855e366c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbeCache.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbeCache.cs @@ -61,7 +61,6 @@ void Initialize() Graphics.SetRenderTarget(m_ConvolutionTargetTexture, mipIdx, CubemapFace.Unknown); GL.Clear(false, true, Color.clear); } - } m_FrameProbeIndex = 0; @@ -126,8 +125,8 @@ public Vector4 FetchSlice(CommandBuffer cmd, Texture texture, ref IBLFilterBSDF. Debug.LogError("Can't convolve or update the planar reflection render target"); } else // Either we add it to the atlas - if (!UpdatePlanarTexture(cmd, texture, ref planarTextureFilteringParameters, ref scaleOffset)) - Debug.LogError("No more space in the planar reflection probe atlas. To solve this issue, increase the size of the Planar Reflection Probe Atlas in the HDRP settings."); + if (!UpdatePlanarTexture(cmd, texture, ref planarTextureFilteringParameters, ref scaleOffset)) + Debug.LogError("No more space in the planar reflection probe atlas. To solve this issue, increase the size of the Planar Reflection Probe Atlas in the HDRP settings."); return scaleOffset; } @@ -208,7 +207,7 @@ internal static long GetApproxCacheSizeInByte(int nbElement, int atlasResolution internal static int GetMaxCacheSizeForWeightInByte(int weight, GraphicsFormat format) => PowerOfTwoTextureAtlas.GetMaxCacheSizeForWeightInByte(weight, true, format); - + internal Vector4 GetAtlasDatas() { float padding = Mathf.Pow(2.0f, m_TextureAtlas.mipPadding) * 2.0f; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/ReflectionProbeCache.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/ReflectionProbeCache.cs index 43bbb943f8b..db4aa7364e2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/ReflectionProbeCache.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/ReflectionProbeCache.cs @@ -90,7 +90,7 @@ public void Release() m_TextureCache.Release(); CoreUtils.Destroy(m_TempRenderTexture); - if(m_ConvolutionTargetTextureArray != null) + if (m_ConvolutionTargetTextureArray != null) { for (int bsdfIdx = 0; bsdfIdx < m_IBLFilterBSDF.Length; ++bsdfIdx) { @@ -194,7 +194,7 @@ Texture[] ConvolveProbeTexture(CommandBuffer cmd, Texture texture) cmd.GenerateMips(convolutionSourceTexture); } - for(int bsdfIdx = 0; bsdfIdx < m_IBLFilterBSDF.Length; ++bsdfIdx) + for (int bsdfIdx = 0; bsdfIdx < m_IBLFilterBSDF.Length; ++bsdfIdx) { m_IBLFilterBSDF[bsdfIdx].FilterCubemap(cmd, convolutionSourceTexture, m_ConvolutionTargetTextureArray[bsdfIdx]); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.Migration.cs index f0df19c3cd6..3c87c7b616b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.Migration.cs @@ -38,7 +38,7 @@ enum Version #pragma warning restore 649 //never assigned /// Serialization callback - public void OnBeforeSerialize() { } + public void OnBeforeSerialize() {} /// Serialization callback public void OnAfterDeserialize() => k_Migration.Migrate(this); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.cs index f10ef9f4e04..bdd8f8f34d1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/InfluenceVolume.cs @@ -49,7 +49,7 @@ public partial class InfluenceVolume /// Offset of sub volume defining fading. public Vector3 boxBlendOffset => (boxBlendDistanceNegative - boxBlendDistancePositive) * 0.5f; /// Size of sub volume defining fading. - public Vector3 boxBlendSize => -(boxBlendDistancePositive + boxBlendDistanceNegative); + public Vector3 boxBlendSize => - (boxBlendDistancePositive + boxBlendDistanceNegative); /// /// Position of fade sub volume maxOffset point relative to InfluenceVolume max corner. /// Values between 0 (on InfluenceVolume hull) to half of boxSize corresponding axis. @@ -64,7 +64,7 @@ public partial class InfluenceVolume /// Offset of sub volume defining fading relative to normal orientation. public Vector3 boxBlendNormalOffset => (boxBlendNormalDistanceNegative - boxBlendNormalDistancePositive) * 0.5f; /// Size of sub volume defining fading relative to normal orientation. - public Vector3 boxBlendNormalSize => -(boxBlendNormalDistancePositive + boxBlendNormalDistanceNegative); + public Vector3 boxBlendNormalSize => - (boxBlendNormalDistancePositive + boxBlendNormalDistanceNegative); /// /// Position of normal fade sub volume maxOffset point relative to InfluenceVolume max corner. /// Values between 0 (on InfluenceVolume hull) to half of boxSize corresponding axis (on origin for this axis). @@ -157,7 +157,7 @@ internal Bounds GetBoundsAt(Vector3 position) } internal Matrix4x4 GetInfluenceToWorld(Transform transform) - => Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); + => Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); internal EnvShapeType envShape { @@ -205,14 +205,14 @@ internal void CopyTo(InfluenceVolume data) } Vector3 GetExtents(InfluenceShape shape) + { + switch (shape) { - switch (shape) - { - default: - case InfluenceShape.Box: - return Vector3.Max(Vector3.one * 0.0001f, boxSize * 0.5f); - case InfluenceShape.Sphere: - return Mathf.Max(0.0001f, sphereRadius) * Vector3.one; + default: + case InfluenceShape.Box: + return Vector3.Max(Vector3.one * 0.0001f, boxSize * 0.5f); + case InfluenceShape.Sphere: + return Mathf.Max(0.0001f, sphereRadius) * Vector3.one; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.Migration.cs index 9514356eed0..8005adf3f43 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.Migration.cs @@ -35,7 +35,7 @@ enum Version bool m_ObsoleteBoxInfiniteProjection = false; /// Serialization callback - void ISerializationCallbackReceiver.OnBeforeSerialize() { } + void ISerializationCallbackReceiver.OnBeforeSerialize() {} /// Serialization callback void ISerializationCallbackReceiver.OnAfterDeserialize() => k_Migration.Migrate(this); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.cs index 465e838a526..8404a75b23d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/Volume/ProxyVolume.cs @@ -41,13 +41,13 @@ internal Hash128 ComputeHash() } Vector3 GetExtents(ProxyShape shape) + { + switch (shape) { - switch (shape) - { - case ProxyShape.Box: return m_BoxSize * 0.5f; - case ProxyShape.Sphere: return Vector3.one * m_SphereRadius; - default: return Vector3.one; - } + case ProxyShape.Box: return m_BoxSize * 0.5f; + case ProxyShape.Sphere: return Vector3.one * m_SphereRadius; + default: return Vector3.one; } } + } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs index 03e3ed1f536..0aa99566a7b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.RenderGraph.cs @@ -39,7 +39,7 @@ public TextureHandle Render(RenderGraph renderGraph, HDCamera hdCamera, TextureH var outputHistory = renderGraph.ImportTexture(hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.AmbientOcclusion)); Vector2 historySize = new Vector2(historyRT.referenceSize.x * historyRT.scaleFactor.x, - historyRT.referenceSize.y * historyRT.scaleFactor.y); + historyRT.referenceSize.y * historyRT.scaleFactor.y); var rtScaleForHistory = hdCamera.historyRTHandleProperties.rtHandleScale; var aoParameters = PrepareRenderAOParameters(hdCamera, historySize * rtScaleForHistory, frameCount, depthMipInfo); @@ -74,15 +74,15 @@ TextureHandle RenderAO(RenderGraph renderGraph, in RenderAOParameters parameters passData.parameters = parameters; passData.packedData = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one * scaleFactor, true, true) - { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "AO Packed data" })); + { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "AO Packed data" })); passData.depthPyramid = builder.ReadTexture(depthPyramid); passData.normalBuffer = builder.ReadTexture(normalBuffer); builder.SetRenderFunc( - (RenderAOPassData data, RenderGraphContext ctx) => - { - RenderAO(data.parameters, data.packedData, data.depthPyramid, data.normalBuffer, ctx.cmd); - }); + (RenderAOPassData data, RenderGraphContext ctx) => + { + RenderAO(data.parameters, data.packedData, data.depthPyramid, data.normalBuffer, ctx.cmd); + }); return passData.packedData; } @@ -99,13 +99,13 @@ class DenoiseAOPassData public TextureHandle motionVectors; } - TextureHandle DenoiseAO( RenderGraph renderGraph, - in RenderAOParameters parameters, - TextureHandle depthTexture, - TextureHandle motionVectors, - TextureHandle aoPackedData, - TextureHandle currentHistory, - TextureHandle outputHistory) + TextureHandle DenoiseAO(RenderGraph renderGraph, + in RenderAOParameters parameters, + TextureHandle depthTexture, + TextureHandle motionVectors, + TextureHandle aoPackedData, + TextureHandle currentHistory, + TextureHandle outputHistory) { TextureHandle denoiseOutput; @@ -135,17 +135,17 @@ TextureHandle DenoiseAO( RenderGraph renderGraph, denoiseOutput = passData.denoiseOutput; builder.SetRenderFunc( - (DenoiseAOPassData data, RenderGraphContext ctx) => - { - DenoiseAO( data.parameters, - data.packedData, - data.packedDataBlurred, - data.currentHistory, - data.outputHistory, - data.motionVectors, - data.denoiseOutput, - ctx.cmd); - }); + (DenoiseAOPassData data, RenderGraphContext ctx) => + { + DenoiseAO(data.parameters, + data.packedData, + data.packedDataBlurred, + data.currentHistory, + data.outputHistory, + data.motionVectors, + data.denoiseOutput, + ctx.cmd); + }); if (parameters.fullResolution) return passData.denoiseOutput; @@ -174,10 +174,10 @@ TextureHandle UpsampleAO(RenderGraph renderGraph, in RenderAOParameters paramete passData.output = builder.WriteTexture(CreateAmbientOcclusionTexture(renderGraph)); builder.SetRenderFunc( - (UpsampleAOPassData data, RenderGraphContext ctx) => - { - UpsampleAO(data.parameters, data.depthTexture, data.input, data.output, ctx.cmd); - }); + (UpsampleAOPassData data, RenderGraphContext ctx) => + { + UpsampleAO(data.parameters, data.depthTexture, data.input, data.output, ctx.cmd); + }); return passData.output; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs index 668a61d61b7..7fa30c964f2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/AmbientOcclusion.cs @@ -382,14 +382,14 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, Vector2 historySiz parameters.runningRes.y * invHalfTanFOV * 0.25f, settings.radius.value, settings.stepCount - ); + ); cb._AOParams1 = new Vector4( settings.intensity.value, 1.0f / (settings.radius.value * settings.radius.value), (frameCount / 6) % 4, (frameCount % 6) - ); + ); // We start from screen space position, so we bake in this factor the 1 / resolution as well. @@ -398,7 +398,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, Vector2 historySiz 2.0f / (invHalfTanFOV * parameters.runningRes.y), 1.0f / (invHalfTanFOV * aspectRatio), 1.0f / invHalfTanFOV - ); + ); float scaleFactor = (parameters.runningRes.x * parameters.runningRes.y) / (540.0f * 960.0f); float radInPixels = Mathf.Max(16, settings.maximumRadiusInPixels * Mathf.Sqrt(scaleFactor)); @@ -452,7 +452,7 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, Vector2 historySiz { parameters.gtaoCS.EnableKeyword("TEMPORAL"); } - if(parameters.fullResolution) + if (parameters.fullResolution) { parameters.gtaoCS.EnableKeyword("FULL_RES"); } @@ -499,10 +499,10 @@ RenderAOParameters PrepareRenderAOParameters(HDCamera camera, Vector2 historySiz } static void RenderAO(in RenderAOParameters parameters, - RTHandle packedDataTexture, - RTHandle depthTexture, - RTHandle normalBuffer, - CommandBuffer cmd) + RTHandle packedDataTexture, + RTHandle depthTexture, + RTHandle normalBuffer, + CommandBuffer cmd) { ConstantBuffer.Push(cmd, parameters.cb, parameters.gtaoCS, HDShaderIDs._ShaderVariablesAmbientOcclusion); cmd.SetComputeTextureParam(parameters.gtaoCS, parameters.gtaoKernel, HDShaderIDs._AOPackedData, packedDataTexture); @@ -517,14 +517,14 @@ static void RenderAO(in RenderAOParameters parameters, cmd.DispatchCompute(parameters.gtaoCS, parameters.gtaoKernel, threadGroupX, threadGroupY, parameters.viewCount); } - static void DenoiseAO( in RenderAOParameters parameters, - RTHandle packedDataTex, - RTHandle packedDataBlurredTex, - RTHandle packedHistoryTex, - RTHandle packedHistoryOutputTex, - RTHandle motionVectors, - RTHandle aoOutputTex, - CommandBuffer cmd) + static void DenoiseAO(in RenderAOParameters parameters, + RTHandle packedDataTex, + RTHandle packedDataBlurredTex, + RTHandle packedHistoryTex, + RTHandle packedHistoryOutputTex, + RTHandle motionVectors, + RTHandle aoOutputTex, + CommandBuffer cmd) { const int groupSizeX = 8; const int groupSizeY = 8; @@ -573,11 +573,11 @@ static void DenoiseAO( in RenderAOParameters parameters, } } - static void UpsampleAO( in RenderAOParameters parameters, - RTHandle depthTexture, - RTHandle input, - RTHandle output, - CommandBuffer cmd) + static void UpsampleAO(in RenderAOParameters parameters, + RTHandle depthTexture, + RTHandle input, + RTHandle output, + CommandBuffer cmd) { bool blurAndUpsample = !parameters.temporalAccumulation; @@ -594,7 +594,6 @@ static void UpsampleAO( in RenderAOParameters parameters, int threadGroupX = ((int)(parameters.runningRes.x) + (groupSizeX - 1)) / groupSizeX; int threadGroupY = ((int)(parameters.runningRes.y) + (groupSizeY - 1)) / groupSizeY; cmd.DispatchCompute(parameters.upsampleAndBlurAOCS, parameters.upsampleAndBlurKernel, threadGroupX, threadGroupY, parameters.viewCount); - } else { @@ -623,7 +622,7 @@ internal void Dispatch(CommandBuffer cmd, HDCamera camera, RTHandle depthTexture var historyOutput = camera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.AmbientOcclusion); Vector2 historySize = new Vector2(currentHistory.referenceSize.x * currentHistory.scaleFactor.x, - currentHistory.referenceSize.y * currentHistory.scaleFactor.y); + currentHistory.referenceSize.y * currentHistory.scaleFactor.y); var rtScaleForHistory = camera.historyRTHandleProperties.rtHandleScale; var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute index 334c1131a2e..1dbeaa58d8e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute @@ -146,7 +146,7 @@ RW_TEXTURE2D_X(float, _AOPackedData); [numthreads(8,8,1)] void GTAOMain(uint3 dispatchThreadId : SV_DispatchThreadID) { - UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); + UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); // Read buffers as early as possible. float currDepth = GetDepthForCentral(dispatchThreadId.xy); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute index 6b5b569f1df..143e98a33e8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute @@ -9,16 +9,16 @@ // // Developed by Minigraph // -// Author: James Stanard +// Author: James Stanard // #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl" #pragma kernel BlurUpsample BLUR_AND_UPSAMPLE -#pragma kernel BilateralUpsampling UPSAMPLE_KERNEL=BilateralUpsampling UPSAMPLE_ONLY +#pragma kernel BilateralUpsampling UPSAMPLE_KERNEL=BilateralUpsampling UPSAMPLE_ONLY #pragma kernel BoxUpsampling UPSAMPLE_KERNEL=BoxUpsampling UPSAMPLE_ONLY BOX -// Currently not used. -#pragma kernel Blur BLUR_KERNEL_NAME=Blur BLUR +// Currently not used. +#pragma kernel Blur BLUR_KERNEL_NAME=Blur BLUR #pragma kernel Blur_FullRes BLUR_KERNEL_NAME=Blur_FullRes BLUR FULL_RES TEXTURE2D_X(_AOPackedData); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.compute index 67dc858b066..97c7167676d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.compute @@ -109,7 +109,7 @@ void SPATIAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID , uint2 groupTh || tapCoord.y < 0) continue; #else - if (tapCoord.x >= _ScreenSize.x + if (tapCoord.x >= _ScreenSize.x || tapCoord.x < 0 || tapCoord.y >= _ScreenSize.y || tapCoord.y < 0) @@ -170,7 +170,7 @@ void TEMPORAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID int2 centerCoord = dispatchThreadId.xy; - // Read the color as early as possible + // Read the color as early as possible float4 color0 = LOAD_TEXTURE2D_X(_InputNoisyBuffer0, centerCoord); float4 color1 = LOAD_TEXTURE2D_X(_InputNoisyBuffer1, centerCoord); @@ -186,7 +186,7 @@ void TEMPORAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID float depth = LOAD_TEXTURE2D_X(_DepthTexture, centerCoord).r; PositionInputs posInputs = GetPositionInput(centerCoord, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, GetWorldToViewMatrix()); #endif - + // Initialize the output buffer in case of an early exit. _OutputFilteredBuffer0[COORD_TEXTURE2D_X(centerCoord)] = color0; _OutputFilteredBuffer1[COORD_TEXTURE2D_X(centerCoord)] = float4(color1.xyz, 1.0); @@ -208,12 +208,12 @@ void TEMPORAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID #if HALF_RES historyTapCoord *= 0.5; // If the pixel was outside of the screen during the previous frame, invalidate the history - if (historyTapCoord.x >= _HalfScreenSize.x || historyTapCoord.x < 0 + if (historyTapCoord.x >= _HalfScreenSize.x || historyTapCoord.x < 0 || historyTapCoord.y >= _HalfScreenSize.y || historyTapCoord.y < 0) return; #else // If the pixel was outside of the screen during the previous frame, invalidate the history - if (historyTapCoord.x >= _ScreenSize.x || historyTapCoord.x < 0 + if (historyTapCoord.x >= _ScreenSize.x || historyTapCoord.x < 0 || historyTapCoord.y >= _ScreenSize.y || historyTapCoord.y < 0) return; #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.cs index 4e89ddee127..bab1ecf7ae6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/SSGIDenoiser.cs @@ -24,7 +24,7 @@ public SSGIDenoiser() } public void Init(RenderPipelineResources rpResources, SharedRTManager sharedRTManager, HDRenderPipeline renderPipeline) - { + { // Keep track of the resources m_SSGIDenoiserCS = rpResources.shaders.ssGIDenoiserCS; @@ -47,8 +47,8 @@ public void Release() { } - void EvaluateDispatchParameters(HDCamera hdCamera, bool halfResolution, int tileSize, - out int numTilesX, out int numTilesY, out Vector4 halfScreenSize) + void EvaluateDispatchParameters(HDCamera hdCamera, bool halfResolution, int tileSize, + out int numTilesX, out int numTilesY, out Vector4 halfScreenSize) { if (halfResolution) { @@ -58,7 +58,6 @@ void EvaluateDispatchParameters(HDCamera hdCamera, bool halfResolution, int tile numTilesX = (texWidth + (tileSize - 1)) / tileSize; numTilesY = (texHeight + (tileSize - 1)) / tileSize; halfScreenSize = new Vector4(texWidth, texHeight, 1.0f / texWidth, 1.0f / texHeight); - } else { @@ -74,8 +73,8 @@ void EvaluateDispatchParameters(HDCamera hdCamera, bool halfResolution, int tile RTHandle IndirectDiffuseHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: string.Format("IndirectDiffuseHistoryBuffer{0}", frameIndex)); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: string.Format("IndirectDiffuseHistoryBuffer{0}", frameIndex)); } struct SSGIDenoiserParameters @@ -259,6 +258,7 @@ RTHandle RequestIndirectDiffuseHistory0(HDCamera hdCamera, out bool historyRequi } return indirectDiffuseHistory; } + RTHandle RequestIndirectDiffuseHistory1(HDCamera hdCamera, out bool historyRequireClear) { historyRequireClear = false; @@ -326,31 +326,31 @@ public SSGIDenoiserOutput Denoise(RenderGraph renderGraph, HDCamera hdCamera, var historyDepthBuffer = halfResolution ? hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth1) : hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth); passData.historyDepthBuffer = historyDepthBuffer != null ? builder.ReadTexture(renderGraph.ImportTexture(historyDepthBuffer)) : renderGraph.defaultResources.blackTextureXR; passData.intermediateBuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Denoiser Intermediate0" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Denoiser Intermediate0" }); passData.intermediateBuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Denoiser Intermediate1" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Denoiser Intermediate1" }); passData.inputOutputBuffer0 = builder.WriteTexture(builder.ReadTexture(inputOutputBuffer0)); passData.inputOutputBuffer1 = builder.WriteTexture(builder.ReadTexture(inputOutputBuffer1)); passData.parameters = PrepareSSGIDenoiserParameters(hdCamera, halfResolution, historyValidity, historyRequireClear, depthMipInfo); builder.SetRenderFunc( - (DenoiseSSGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - SSGIDenoiserResources resources = new SSGIDenoiserResources(); - resources.depthTexture = data.depthTexture; - resources.normalBuffer = data.normalBuffer; - resources.motionVectorsBuffer = data.motionVectorsBuffer; - resources.indirectDiffuseHistory0 = data.indirectDiffuseHistory0; - resources.indirectDiffuseHistory1 = data.indirectDiffuseHistory1; - resources.historyDepthBuffer = data.historyDepthBuffer; - resources.intermediateBuffer0 = data.intermediateBuffer0; - resources.intermediateBuffer1 = data.intermediateBuffer1; - resources.inputOutputBuffer0 = data.inputOutputBuffer0; - resources.inputOutputBuffer1 = data.inputOutputBuffer1; - Denoise(ctx.cmd, data.parameters, resources); - }); + (DenoiseSSGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + SSGIDenoiserResources resources = new SSGIDenoiserResources(); + resources.depthTexture = data.depthTexture; + resources.normalBuffer = data.normalBuffer; + resources.motionVectorsBuffer = data.motionVectorsBuffer; + resources.indirectDiffuseHistory0 = data.indirectDiffuseHistory0; + resources.indirectDiffuseHistory1 = data.indirectDiffuseHistory1; + resources.historyDepthBuffer = data.historyDepthBuffer; + resources.intermediateBuffer0 = data.intermediateBuffer0; + resources.intermediateBuffer1 = data.intermediateBuffer1; + resources.inputOutputBuffer0 = data.inputOutputBuffer0; + resources.inputOutputBuffer1 = data.inputOutputBuffer1; + Denoise(ctx.cmd, data.parameters, resources); + }); SSGIDenoiserOutput denoiserOutput = new SSGIDenoiserOutput(); denoiserOutput.outputBuffer0 = inputOutputBuffer0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.RenderGraph.cs index b39d4e12223..108b299ecf5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.RenderGraph.cs @@ -47,27 +47,27 @@ TraceOutput TraceSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllumina var historyDepth = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth); passData.historyDepth = historyDepth != null ? builder.ReadTexture(renderGraph.ImportTexture(historyDepth)) : renderGraph.defaultResources.blackTextureXR; passData.hitPointBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Hit Point"}); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Hit Point"}); passData.outputBuffer0 = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Signal0"})); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Signal0"})); passData.outputBuffer1 = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Signal1" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Signal1" })); builder.SetRenderFunc( - (TraceSSGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - SSGITraceResources resources = new SSGITraceResources(); - resources.depthTexture = data.depthTexture; - resources.normalBuffer = data.normalBuffer; - resources.motionVectorsBuffer = data.motionVectorsBuffer; - resources.colorPyramid = data.colorPyramid; - resources.historyDepth = data.historyDepth; - resources.hitPointBuffer = data.hitPointBuffer; - resources.outputBuffer0 = data.outputBuffer0; - resources.outputBuffer1 = data.outputBuffer1; - ExecuteSSGITrace(ctx.cmd, data.parameters, resources); - }); + (TraceSSGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + SSGITraceResources resources = new SSGITraceResources(); + resources.depthTexture = data.depthTexture; + resources.normalBuffer = data.normalBuffer; + resources.motionVectorsBuffer = data.motionVectorsBuffer; + resources.colorPyramid = data.colorPyramid; + resources.historyDepth = data.historyDepth; + resources.hitPointBuffer = data.hitPointBuffer; + resources.outputBuffer0 = data.outputBuffer0; + resources.outputBuffer1 = data.outputBuffer1; + ExecuteSSGITrace(ctx.cmd, data.parameters, resources); + }); TraceOutput traceOutput = new TraceOutput(); traceOutput.outputBuffer0 = passData.outputBuffer0; traceOutput.outputBuffer1 = passData.outputBuffer1; @@ -93,18 +93,18 @@ TextureHandle UpscaleSSGI(RenderGraph renderGraph, HDCamera hdCamera, GlobalIllu passData.depthTexture = builder.ReadTexture(depthPyramid); passData.inputBuffer = builder.ReadTexture(inputBuffer); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Final" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "SSGI Final" })); builder.SetRenderFunc( - (UpscaleSSGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - SSGIUpscaleResources resources = new SSGIUpscaleResources(); - resources.depthTexture = data.depthTexture; - resources.inputBuffer = data.inputBuffer; - resources.outputBuffer = data.outputBuffer; - ExecuteSSGIUpscale(ctx.cmd, data.parameters, resources); - }); + (UpscaleSSGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + SSGIUpscaleResources resources = new SSGIUpscaleResources(); + resources.depthTexture = data.depthTexture; + resources.inputBuffer = data.inputBuffer; + resources.outputBuffer = data.outputBuffer; + ExecuteSSGIUpscale(ctx.cmd, data.parameters, resources); + }); return passData.outputBuffer; } } @@ -133,17 +133,17 @@ TextureHandle ConvertSSGI(RenderGraph renderGraph, HDCamera hdCamera, bool halfR passData.inoutputBuffer1 = builder.WriteTexture(builder.ReadTexture(inoutputBuffer1)); builder.SetRenderFunc( - (ConvertSSGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - SSGIConvertResources resources = new SSGIConvertResources(); - resources.depthTexture = data.depthTexture; - resources.stencilBuffer = data.stencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.inoutBuffer0 = data.inoutputBuffer0; - resources.inputBufer1 = data.inoutputBuffer1; - ExecuteSSGIConversion(ctx.cmd, data.parameters, resources); - }); + (ConvertSSGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + SSGIConvertResources resources = new SSGIConvertResources(); + resources.depthTexture = data.depthTexture; + resources.stencilBuffer = data.stencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.inoutBuffer0 = data.inoutputBuffer0; + resources.inputBufer1 = data.inoutputBuffer1; + ExecuteSSGIConversion(ctx.cmd, data.parameters, resources); + }); return passData.inoutputBuffer0; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute index f92ab53210a..bee3a08bc54 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute @@ -273,8 +273,8 @@ void TRACE_GLOBAL_ILLUMINATION(uint3 dispatchThreadId : SV_DispatchThreadID, uin // Input hit point texture that holds the NDC position if an intersection was found TEXTURE2D_X(_IndirectDiffuseHitPointTexture); // Depth buffer of the previous frame (full resolution) -TEXTURE2D_X(_HistoryDepthTexture); -// Output indirect diffuse texture +TEXTURE2D_X(_HistoryDepthTexture); +// Output indirect diffuse texture RW_TEXTURE2D_X(float4, _IndirectDiffuseTexture0RW); RW_TEXTURE2D_X(float4, _IndirectDiffuseTexture1RW); @@ -342,9 +342,9 @@ void REPROJECT_GLOBAL_ILLUMINATION(uint3 dispatchThreadId : SV_DispatchThreadID, float2 prevFrameUV = prevFrameNDC * _ColorPyramidUvScaleAndLimitPrevFrame.xy; // If the previous value to read was out of screen, this is invalid, needs a fallback - if ((prevFrameUV.x < 0) - || (prevFrameUV.x > _ColorPyramidUvScaleAndLimitPrevFrame.z) - || (prevFrameUV.y < 0) + if ((prevFrameUV.x < 0) + || (prevFrameUV.x > _ColorPyramidUvScaleAndLimitPrevFrame.z) + || (prevFrameUV.y < 0) || (prevFrameUV.y > _ColorPyramidUvScaleAndLimitPrevFrame.w)) invalid = true; @@ -415,7 +415,7 @@ void ConvertYCoCgToRGBUtil(float4 inYSH, float2 inCoCg, float3 inNormal, out flo outColor = max(outColor, 0.0); } -TEXTURE2D_X(_IndirectDiffuseTexture1); +TEXTURE2D_X(_IndirectDiffuseTexture1); [numthreads(INDIRECT_DIFFUSE_TILE_SIZE, INDIRECT_DIFFUSE_TILE_SIZE, 1)] void CONVERT_YCOCG_TO_RGB(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_GroupID) @@ -454,7 +454,7 @@ void CONVERT_YCOCG_TO_RGB(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gr // Convert the signal back to a color float3 color; - float4 ySH = _IndirectDiffuseTexture0RW[COORD_TEXTURE2D_X(currentCoord)]; + float4 ySH = _IndirectDiffuseTexture0RW[COORD_TEXTURE2D_X(currentCoord)]; float3 cocgB = LOAD_TEXTURE2D_X(_IndirectDiffuseTexture1, currentCoord).xyz; ConvertYCoCgToRGBUtil(ySH, cocgB.xy, normalData.normalWS, color); @@ -462,7 +462,7 @@ void CONVERT_YCOCG_TO_RGB(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gr color = color / (1.0 - color); // The mulitplication is wrong, but with all the approximations that we need to compensate a bit - // the fact that the signal was significantly attenuated (due to blurring in tonemapped space to reduce the blobbyness). + // the fact that the signal was significantly attenuated (due to blurring in tonemapped space to reduce the blobbyness). // This has been experimentally tested. However, it needs more testing and potetially reverted if found more harmful than useful color *= (lerp(2.5, 1.0, cocgB.z)); @@ -473,4 +473,4 @@ void CONVERT_YCOCG_TO_RGB(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gr // Output the color as well as the blend factor _IndirectDiffuseTexture0RW[COORD_TEXTURE2D_X(currentCoord)] = float4(color, cocgB.z); -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs index e702885d691..f02966b0cd1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.cs @@ -264,7 +264,7 @@ SSGIConvertParameters PrepareSSGIConvertParameters(HDCamera hdCamera, bool halfR // Grab the right kernel parameters.ssGICS = m_Asset.renderPipelineResources.shaders.screenSpaceGlobalIlluminationCS; - parameters.convertKernel = halfResolution? m_ConvertYCoCgToRGBHalfKernel : m_ConvertYCoCgToRGBKernel; + parameters.convertKernel = halfResolution ? m_ConvertYCoCgToRGBHalfKernel : m_ConvertYCoCgToRGBKernel; var info = m_SharedRTManager.GetDepthBufferMipChainInfo(); parameters.offsetBuffer = info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer); @@ -399,7 +399,7 @@ private float EvaluateIndirectDiffuseHistoryValidityCombined(HDCamera hdCamera, { // Evaluate the history validity float effectHistoryValidity = hdCamera.EffectHistoryValidity(HDCamera.HistoryEffectSlot.GlobalIllumination0, fullResolution, rayTraced) - && hdCamera.EffectHistoryValidity(HDCamera.HistoryEffectSlot.GlobalIllumination1, fullResolution, rayTraced) ? 1.0f : 0.0f; + && hdCamera.EffectHistoryValidity(HDCamera.HistoryEffectSlot.GlobalIllumination1, fullResolution, rayTraced) ? 1.0f : 0.0f; return EvaluateHistoryValidity(hdCamera) * effectHistoryValidity; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceLighting.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceLighting.hlsl index 710a67804c9..08313742c43 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceLighting.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceLighting.hlsl @@ -1,4 +1,4 @@ -// Performs fading at the edge of the screen. +// Performs fading at the edge of the screen. float EdgeOfScreenFade(float2 coordNDC, float fadeRcpLength) { float2 coordCS = coordNDC * 2 - 1; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflection.cs index 21f4a1c80d9..885cce8a719 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflection.cs @@ -27,7 +27,7 @@ public sealed class SSRAlgoParameter : VolumeParameterSSR Algo Type parameter. /// Initial override state. public SSRAlgoParameter(ScreenSpaceReflectionAlgorithm value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} } /// diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceTracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceTracing.hlsl index 10b55b9eb82..8ff56b057e8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceTracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceTracing.hlsl @@ -90,4 +90,3 @@ bool ScreenSpaceProxyRaycastRefraction(ScreenSpaceProxyRaycastInput input, out S } #endif - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute index 9de3847588e..f22bf98a454 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute @@ -5,9 +5,9 @@ #define THREADS 8 -#pragma kernel ConvertAndBlur KERNEL_MAIN=ConvertAndBlur BLUR_SIZE=9 -#pragma kernel Blur KERNEL_MAIN=Blur BLUR_SIZE=9 ALREADY_EVSM -#pragma kernel CopyMoments +#pragma kernel ConvertAndBlur KERNEL_MAIN=ConvertAndBlur BLUR_SIZE=9 +#pragma kernel Blur KERNEL_MAIN=Blur BLUR_SIZE=9 ALREADY_EVSM +#pragma kernel CopyMoments #pragma only_renderers d3d11 playstation xboxone vulkan metal switch @@ -157,7 +157,7 @@ void KERNEL_MAIN(uint3 dispatchId : SV_DispatchThreadID, uint3 groupThreadId : S } } -#else +#else [numthreads(THREADS, THREADS, 1)] void CopyMoments(uint3 dispatchId : SV_DispatchThreadID) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowAtlas.cs index 5681f760d7a..d4f93228e26 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowAtlas.cs @@ -34,7 +34,7 @@ struct CachedTransform private int m_AtlasResolutionInSlots; // Atlas Resolution / m_MinSlotSize - private bool m_NeedOptimalPacking = true; // Whenever this is set to true, the pending lights are sorted before insertion. + private bool m_NeedOptimalPacking = true; // Whenever this is set to true, the pending lights are sorted before insertion. private List m_AtlasSlots; // One entry per slot (of size m_MinSlotSize) true if occupied, false if free. @@ -87,6 +87,7 @@ public override void InitAtlas(RenderPipelineResources renderPipelineResources, m_CanTryPlacement = true; m_NeedOptimalPacking = true; } + // ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------ @@ -97,7 +98,7 @@ public void AddBlitRequestsForUpdatedShadows(HDDynamicShadowAtlas dynamicAtlas) { foreach (var request in m_ShadowRequests) { - if(request.shouldRenderCachedComponent) // meaning it has been updated this time frame + if (request.shouldRenderCachedComponent) // meaning it has been updated this time frame { dynamicAtlas.AddRequestToPendingBlitFromCache(request); } @@ -105,12 +106,13 @@ public void AddBlitRequestsForUpdatedShadows(HDDynamicShadowAtlas dynamicAtlas) } // ------------------------------------------------------------------------------------------ - // Functions to access and deal with the C# representation of the atlas + // Functions to access and deal with the C# representation of the atlas // ------------------------------------------------------------------------------------------ private bool IsEntryEmpty(int x, int y) { return (m_AtlasSlots[y * m_AtlasResolutionInSlots + x] == false); } + private bool IsEntryFull(int x, int y) { return (m_AtlasSlots[y * m_AtlasResolutionInSlots + x]); @@ -182,16 +184,17 @@ internal bool GetSlotInAtlas(int resolution, out int x, out int y) return false; } - // --------------------------------------------------------------------------------------- + + // --------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------ - // Entry and exit points to the atlas + // Entry and exit points to the atlas // ------------------------------------------------------------------------------------------ internal int GetNextLightIdentifier() { int outputId = m_NextLightID; - m_NextLightID += m_MaxShadowsPerLight; // We give unique identifiers to each + m_NextLightID += m_MaxShadowsPerLight; // We give unique identifiers to each return outputId; } @@ -201,7 +204,7 @@ internal void RegisterLight(HDAdditionalLightData lightData) if (lightData.lightIdxForCachedShadows >= 0 && m_PlacedShadows.ContainsKey(lightData.lightIdxForCachedShadows)) return; - // We register only if not already pending placement and if enabled. + // We register only if not already pending placement and if enabled. if (!m_RegisteredLightDataPendingPlacement.ContainsKey(lightData.lightIdxForCachedShadows) && lightData.isActiveAndEnabled) { #if UNITY_2020_2_OR_NEWER @@ -263,12 +266,11 @@ internal void RemoveTransformFromCache(HDAdditionalLightData lightData) m_TransformCaches.Remove(lightData.lightIdxForCachedShadows); } - // ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------ - // Atlassing on the actual textures + // Atlassing on the actual textures // ------------------------------------------------------------------------------------------ @@ -343,12 +345,12 @@ private bool PlaceMultipleShadows(int startIdx, int numberOfShadows) } // If they all fit, we actually placed them, otherwise we mark the slot that we temp filled as free and go on. - if(successfullyPlaced == numberOfShadows) // Success. + if (successfullyPlaced == numberOfShadows) // Success. { for (int j = 0; j < numberOfShadows; ++j) { var record = m_TempListForPlacement[startIdx + j]; - + record.offsetInAtlas = new Vector4(placements[j].x * m_MinSlotSize, placements[j].y * m_MinSlotSize, placements[j].x, placements[j].y); m_ShadowsPendingRendering.Add(record.shadowIndex, record); @@ -357,10 +359,10 @@ private bool PlaceMultipleShadows(int startIdx, int numberOfShadows) return true; } - else if(successfullyPlaced > 0) // Couldn't place them all, but we placed something, so we revert those placements. + else if (successfullyPlaced > 0) // Couldn't place them all, but we placed something, so we revert those placements. { int numEntries = HDUtils.DivRoundUp(m_TempListForPlacement[startIdx].viewportSize, m_MinSlotSize); - for (int j=0; j angleDiffThreshold || Mathf.Abs(angleDiff.y) > angleDiffThreshold || Mathf.Abs(angleDiff.z) > angleDiffThreshold) { needUpdate = true; @@ -600,5 +602,3 @@ internal bool NeedRenderingDueToTransformChange(HDAdditionalLightData lightData, // ------------------------------------------------------------------------------------------ } } - - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowManager.cs index c206b5f055f..729b235da62 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDCachedShadowManager.cs @@ -9,7 +9,7 @@ namespace UnityEngine.Rendering.HighDefinition // we use this cached shadow manager only as a source of utilities functions, but the data is stored in the dynamic shadow atlas. /// - /// The class responsible to handle cached shadow maps (shadows with Update mode set to OnEnable or OnDemand). + /// The class responsible to handle cached shadow maps (shadows with Update mode set to OnEnable or OnDemand). /// public class HDCachedShadowManager { @@ -28,7 +28,7 @@ public class HDCachedShadowManager // Cached atlas internal HDCachedShadowAtlas punctualShadowAtlas; internal HDCachedShadowAtlas areaShadowAtlas; - // Cache here to be able to compute resolutions. + // Cache here to be able to compute resolutions. private HDShadowInitParameters m_InitParams; // ------------------------ Debug API ------------------------------- @@ -66,11 +66,12 @@ internal void PrintLightStatusInCachedAtlas() } } } + #endif // ------------------------ Public API ------------------------------- /// - /// This function verifies if a shadow map of resolution shadowResolution for a light of type lightType would fit in the atlas when inserted. + /// This function verifies if a shadow map of resolution shadowResolution for a light of type lightType would fit in the atlas when inserted. /// /// The resolution of the hypothetical shadow map that we are assessing. /// The type of the light that cast the hypothetical shadow map that we are assessing. @@ -100,7 +101,7 @@ public bool WouldFitInAtlas(int shadowResolution, HDLightType lightType) /// /// If a light is added after a scene is loaded, its placement in the atlas might be not optimal and the suboptimal placement might prevent a light to find a place in the atlas. /// This function will force a defragmentation of the atlas containing lights of type lightType and redistributes the shadows inside so that the placement is optimal. Note however that this will also mark the shadow maps - /// as dirty and they will be re-rendered as soon the light will come into view for the first time after this function call. + /// as dirty and they will be re-rendered as soon the light will come into view for the first time after this function call. /// /// The type of the light contained in the atlas that need defragmentation. public void DefragAtlas(HDLightType lightType) @@ -125,13 +126,13 @@ public void ForceEvictLight(HDAdditionalLightData lightData) /// /// This function can be used to register a light to the cached shadow system if not already registered. It is necessary to call this function if a light has been /// evicted with ForceEvictLight and it needs to be registered again. Please note that a light is automatically registered when enabled or when the shadow update changes - /// from EveryFrame to OnDemand or OnEnable. + /// from EveryFrame to OnDemand or OnEnable. /// /// The light to register. public void ForceRegisterLight(HDAdditionalLightData lightData) { // Note: this is for now just calling the internal API, but having a separate API helps with future - // changes to the process. + // changes to the process. RegisterLight(lightData); } @@ -153,14 +154,14 @@ private HDCachedShadowManager() } internal void InitPunctualShadowAtlas(RenderPipelineResources renderPipelineResources, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, HDShadowInitParameters initParams, - HDShadowAtlas.BlurAlgorithm blurAlgorithm = HDShadowAtlas.BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "") + HDShadowAtlas.BlurAlgorithm blurAlgorithm = HDShadowAtlas.BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "") { m_InitParams = initParams; punctualShadowAtlas.InitAtlas(renderPipelineResources, width, height, atlasShaderID, clearMaterial, maxShadowRequests, initParams, blurAlgorithm, filterMode, depthBufferBits, format, name); } internal void InitAreaLightShadowAtlas(RenderPipelineResources renderPipelineResources, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, HDShadowInitParameters initParams, - HDShadowAtlas.BlurAlgorithm blurAlgorithm = HDShadowAtlas.BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "") + HDShadowAtlas.BlurAlgorithm blurAlgorithm = HDShadowAtlas.BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "") { m_InitParams = initParams; areaShadowAtlas.InitAtlas(renderPipelineResources, width, height, atlasShaderID, clearMaterial, maxShadowRequests, initParams, blurAlgorithm, filterMode, depthBufferBits, format, name); @@ -230,17 +231,16 @@ internal void RemoveTransformFromCache(HDAdditionalLightData lightData) areaShadowAtlas.RemoveTransformFromCache(lightData); } - internal void AssignSlotsInAtlases() { punctualShadowAtlas.AssignOffsetsInAtlas(m_InitParams); - if(ShaderConfig.s_AreaLights == 1) + if (ShaderConfig.s_AreaLights == 1) areaShadowAtlas.AssignOffsetsInAtlas(m_InitParams); } internal bool NeedRenderingDueToTransformChange(HDAdditionalLightData lightData, HDLightType lightType) { - if(lightData.updateUponLightMovement) + if (lightData.updateUponLightMovement) { if (lightType == HDLightType.Directional) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDDynamicShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDDynamicShadowAtlas.cs index 9fee8c471a1..811edc43b04 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDDynamicShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDDynamicShadowAtlas.cs @@ -18,7 +18,6 @@ public HDDynamicShadowAtlas(RenderPipelineResources renderPipelineResources, int m_SortedRequestsCache = new HDShadowResolutionRequest[Mathf.CeilToInt(maxShadowRequests)]; } - internal void ReserveResolution(HDShadowResolutionRequest shadowRequest) { m_ShadowResolutionRequests.Add(shadowRequest); @@ -123,7 +122,8 @@ void LayoutResize() currentMaxXCache = Mathf.Max(currentMaxXCache, currentMaxX + r.width); m_ShadowResolutionRequests[index].dynamicAtlasViewport = r; index++; - } while (y < currentMaxY && index < m_ShadowResolutionRequests.Count); + } + while (y < currentMaxY && index < m_ShadowResolutionRequests.Count); currentMaxY = Mathf.Max(currentMaxY, currentY); currentMaxX = currentMaxXCache; if (index >= m_ShadowResolutionRequests.Count) @@ -140,7 +140,8 @@ void LayoutResize() currentMaxYCache = Mathf.Max(currentMaxYCache, currentMaxY + r.height); m_ShadowResolutionRequests[index].dynamicAtlasViewport = r; index++; - } while (x < currentMaxX && index < m_ShadowResolutionRequests.Count); + } + while (x < currentMaxX && index < m_ShadowResolutionRequests.Count); currentMaxX = Mathf.Max(currentMaxX, currentX); currentMaxY = currentMaxYCache; } @@ -187,7 +188,6 @@ internal struct ShadowBlitParameters public Material blitMaterial; public MaterialPropertyBlock blitMaterialPropertyBlock; public Vector2Int cachedShadowAtlasSize; - } internal ShadowBlitParameters PrepareShadowBlitParameters(HDCachedShadowAtlas cachedAtlas, Material blitMaterial, MaterialPropertyBlock blitMpb) @@ -229,4 +229,3 @@ public override void Clear() } } } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDIMS.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDIMS.hlsl index 586a2a0c644..b65429ba570 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDIMS.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDIMS.hlsl @@ -1,11 +1,11 @@ // Part of this code has been given by Christoph Peter in the Demo code of the "Improved Moment Shadow Maps for Translucent Occluders, Soft Shadows and Single Scattering" paper // -// To the extent possible under law, the author(s) have dedicated all copyright and -// related and neighboring rights to this software to the public domain worldwide. +// To the extent possible under law, the author(s) have dedicated all copyright and +// related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // -// You should have received a copy of the CC0 Public Domain Dedication along with -// this software. If not, see . +// You should have received a copy of the CC0 Public Domain Dedication along with +// this software. If not, see . // Link: http://jcgt.org/published/0006/01/03/ // Given that the default texture2d type matches a float4, we beed to manually declare this texture for the improved moment shadow algorithm @@ -72,7 +72,7 @@ void Compute4MomentAverageBlockerDepth(out float OutAverageBlockerDepth, out flo // Backward substitution to solve L^T*c3=c2 c[1]-=L21*c[2]; c[0]-=dot(c.yz,b.xy); - // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions + // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions // z[1] and z[2] z.yz=GetRoots(c); // Compute weights of the Dirac-deltas at the roots @@ -98,7 +98,7 @@ void EstimatePenumbraSize(out float2 OutKernelSize,out float OutDepthBias, float float4 ComputeRectangleAverage_uint4(float2 LeftTop,float2 RightBottom, float4 TextureSize, float2 FixedPrecision) { - // The summed area table is essentially off by one because the top left texel + // The summed area table is essentially off by one because the top left texel // already holds the integral over the top left texel. Compensate for that. LeftTop-=TextureSize.zw; RightBottom-=TextureSize.zw; @@ -111,8 +111,8 @@ float4 ComputeRectangleAverage_uint4(float2 LeftTop,float2 RightBottom, float4 T int2 iRightBottom=int2(RightBottomPixelFloor); float2 LeftTopFactor=float2(1.0f,1.0f)-(LeftTopPixel-LeftTopPixelFloor); float2 RightBottomFactor=RightBottomPixel-RightBottomPixelFloor; - // Sample the summed area table at all relevant locations. The first two indices - // determine whether we are at the left top or right bottom of the rectangle, + // Sample the summed area table at all relevant locations. The first two indices + // determine whether we are at the left top or right bottom of the rectangle, // the latter two determine the pixel offset. int x, y; uint4 Samples[2][2][2][2]; @@ -196,7 +196,7 @@ void Compute4MomentUnboundedShadowIntensity(out float OutShadowIntensity, // Backward substitution to solve L^T*c3=c2 c[1]-=L21*c[2]; c[0]-=dot(c.yz,b.xy); - // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions + // Solve the quadratic equation c[0]+c[1]*z+c[2]*z^2 to obtain solutions // z[1] and z[2] float InvC2=1.0f/c[2]; float p=c[1]*InvC2; @@ -226,7 +226,7 @@ float3x2 ComputeDirectionalLightSoftShadowParameters(float4x4 ViewToProjectionSp dot(float4(ViewToProjectionSpace._43,-ViewToProjectionSpace._43,-ViewToProjectionSpace._33,ViewToProjectionSpace._33),float4(ViewToProjectionSpace._33,ViewToProjectionSpace._43,ViewToProjectionSpace._34,ViewToProjectionSpace._44))/ (ViewToProjectionSpace._33*(ViewToProjectionSpace._33-ViewToProjectionSpace._43)) ); - // Compute a factor that turns a depth difference into a kernel size as texture + // Compute a factor that turns a depth difference into a kernel size as texture // coordinate float3x2 OutLightParameter; OutLightParameter._11=0.5f*tan(0.5f*LightSourceAngle)*FrustumExtents.z/FrustumExtents.x; @@ -287,8 +287,8 @@ float SampleShadow_IMS(HDShadowData sd, float3 tcs, float depthBias, float kerne // Compute the integral in the target rectangle float4 averageOptimizedMoment = ComputeIntegerRectangleAverage_uint4(searchRegion, _CascadeShadowAtlasSize.xy, fixedPrecision.y); - - // Convert the moment to canonical + + // Convert the moment to canonical Convert4MomentOptimizedToCanonical(averageOptimizedMoment, averageOptimizedMoment, MOMENT_BIAS); // Compute the average depth and the shadow intensity @@ -304,7 +304,7 @@ float SampleShadow_IMS(HDShadowData sd, float3 tcs, float depthBias, float kerne // Estimate the size of the penumbra for this pixel float2 penumbraKernelSize = float2(0.0, 0.0); - float estimatedDepthBias = 0.0f; + float estimatedDepthBias = 0.0f; EstimatePenumbraSize(penumbraKernelSize, estimatedDepthBias, averageBlockerDepth, pixelShadowmapDepth, lightParameters, kernelSizeParameter, maxDepthBias); // Estimate the region of the filter with the penumbra estimation @@ -321,7 +321,7 @@ float SampleShadow_IMS(HDShadowData sd, float3 tcs, float depthBias, float kerne // Compute the shadow intensity float shadowIntensity = 0.0f; Compute4MomentUnboundedShadowIntensity(shadowIntensity, biasedMoment, pixelShadowmapDepth, estimatedDepthBias); - + // Inverse it and we are done return 1.0 - shadowIntensity; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDPCSS.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDPCSS.hlsl index e028c6e731b..724f578a1a5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDPCSS.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDPCSS.hlsl @@ -155,7 +155,7 @@ real PCSS(real3 coord, real filterRadius, real2 scale, real2 offset, real2 sampl // Overfiltering will leak results from other shadow lights. //TODO: Investigate moving this to blocker search. // coord.xy = clamp(coord.xy, float2(UMin, VMin), float2(UMax, VMax)); - + if (U <= UMin || U >= UMax || V <= VMin || V >= VMax) sum += SAMPLE_TEXTURE2D_SHADOW(shadowMap, compSampler, real3(coord.xy, coord.z)).r; else diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs index 6cb0ca526ae..6955baff282 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowAtlas.cs @@ -44,7 +44,7 @@ public enum BlurAlgorithm // if false we filter only for dynamic) protected bool m_IsACacheForShadows; - public HDShadowAtlas() { } + public HDShadowAtlas() {} public virtual void InitAtlas(RenderPipelineResources renderPipelineResources, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, HDShadowInitParameters initParams, BlurAlgorithm blurAlgorithm = BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "") { @@ -181,12 +181,12 @@ RenderShadowsParameters PrepareRenderShadowsParameters(in ShaderVariablesGlobal return parameters; } - static void RenderShadows( in RenderShadowsParameters parameters, - RTHandle atlasRenderTexture, - ShadowDrawingSettings shadowDrawSettings, - ScriptableRenderContext renderContext, - bool renderingOnAShadowCache, - CommandBuffer cmd) + static void RenderShadows(in RenderShadowsParameters parameters, + RTHandle atlasRenderTexture, + ShadowDrawingSettings shadowDrawSettings, + ScriptableRenderContext renderContext, + bool renderingOnAShadowCache, + CommandBuffer cmd) { cmd.SetRenderTarget(atlasRenderTexture, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); @@ -197,7 +197,7 @@ static void RenderShadows( in RenderShadowsParameters parameters, foreach (var shadowRequest in parameters.shadowRequests) { bool shouldSkipRequest = shadowRequest.shadowMapType != ShadowMapType.CascadedDirectional ? !shadowRequest.shouldRenderCachedComponent && renderingOnAShadowCache : - shadowRequest.shouldUseCachedShadowData; + shadowRequest.shouldUseCachedShadowData; if (shouldSkipRequest) continue; @@ -248,7 +248,6 @@ static void RenderShadows( in RenderShadowsParameters parameters, } cmd.SetGlobalFloat(HDShaderIDs._ZClip, 1.0f); // Re-enable zclip globally cmd.SetGlobalDepthBias(0.0f, 0.0f); // Reset depth bias. - } public bool HasBlurredEVSM() @@ -258,16 +257,17 @@ public bool HasBlurredEVSM() // This is a 9 tap filter, a gaussian with std. dev of 3. This standard deviation with this amount of taps probably cuts // the tail of the gaussian a bit too much, and it is a very fat curve, but it seems to work fine for our use case. - static readonly Vector4[] evsmBlurWeights = { + static readonly Vector4[] evsmBlurWeights = + { new Vector4(0.1531703f, 0.1448929f, 0.1226492f, 0.0929025f), new Vector4(0.06297021f, 0.0f, 0.0f, 0.0f), }; - unsafe static void EVSMBlurMoments( RenderShadowsParameters parameters, - RTHandle atlasRenderTexture, - RTHandle[] momentAtlasRenderTextures, - bool blurOnACache, - CommandBuffer cmd) + unsafe static void EVSMBlurMoments(RenderShadowsParameters parameters, + RTHandle atlasRenderTexture, + RTHandle[] momentAtlasRenderTextures, + bool blurOnACache, + CommandBuffer cmd) { ComputeShader shadowBlurMomentsCS = parameters.evsmShadowBlurMomentsCS; @@ -287,7 +287,7 @@ unsafe static void EVSMBlurMoments( RenderShadowsParameters parameters, foreach (var shadowRequest in parameters.shadowRequests) { bool shouldSkipRequest = shadowRequest.shadowMapType != ShadowMapType.CascadedDirectional ? !shadowRequest.shouldRenderCachedComponent && blurOnACache : - shadowRequest.shouldUseCachedShadowData; + shadowRequest.shouldUseCachedShadowData; if (shouldSkipRequest) continue; @@ -356,12 +356,12 @@ unsafe static void EVSMBlurMoments( RenderShadowsParameters parameters, } } - static void IMBlurMoment( RenderShadowsParameters parameters, - RTHandle atlas, - RTHandle atlasMoment, - RTHandle intermediateSummedAreaTexture, - RTHandle summedAreaTexture, - CommandBuffer cmd) + static void IMBlurMoment(RenderShadowsParameters parameters, + RTHandle atlas, + RTHandle atlasMoment, + RTHandle intermediateSummedAreaTexture, + RTHandle summedAreaTexture, + CommandBuffer cmd) { // If the target kernel is not available ComputeShader momentCS = parameters.imShadowBlurMomentsCS; @@ -444,7 +444,7 @@ public void Release() if (m_Atlas != null) RTHandles.Release(m_Atlas); - if(m_AtlasMoments != null && m_AtlasMoments.Length > 0) + if (m_AtlasMoments != null && m_AtlasMoments.Length > 0) { for (int i = 0; i < m_AtlasMoments.Length; ++i) { @@ -460,7 +460,6 @@ public void Release() { RTHandles.Release(m_IntermediateSummedAreaTexture); m_IntermediateSummedAreaTexture = null; - } if (m_SummedAreaTexture != null) @@ -471,4 +470,3 @@ public void Release() } } } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs index 6dd3d6587c8..a9a9fc15880 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.RenderGraph.cs @@ -84,14 +84,14 @@ void BindShadowGlobalResources(RenderGraph renderGraph, in ShadowResult shadowRe passData.shadowResult = ReadShadowResult(shadowResult, builder); builder.AllowPassCulling(false); builder.SetRenderFunc( - (BindShadowGlobalResourcesPassData data, RenderGraphContext ctx) => - { - BindAtlasTexture(ctx, data.shadowResult.punctualShadowResult, HDShaderIDs._ShadowmapAtlas); - BindAtlasTexture(ctx, data.shadowResult.directionalShadowResult, HDShaderIDs._ShadowmapCascadeAtlas); - BindAtlasTexture(ctx, data.shadowResult.areaShadowResult, HDShaderIDs._ShadowmapAreaAtlas); - BindAtlasTexture(ctx, data.shadowResult.cachedPunctualShadowResult, HDShaderIDs._CachedShadowmapAtlas); - BindAtlasTexture(ctx, data.shadowResult.cachedAreaShadowResult, HDShaderIDs._CachedAreaLightShadowmapAtlas); - }); + (BindShadowGlobalResourcesPassData data, RenderGraphContext ctx) => + { + BindAtlasTexture(ctx, data.shadowResult.punctualShadowResult, HDShaderIDs._ShadowmapAtlas); + BindAtlasTexture(ctx, data.shadowResult.directionalShadowResult, HDShaderIDs._ShadowmapCascadeAtlas); + BindAtlasTexture(ctx, data.shadowResult.areaShadowResult, HDShaderIDs._ShadowmapAreaAtlas); + BindAtlasTexture(ctx, data.shadowResult.cachedPunctualShadowResult, HDShaderIDs._CachedShadowmapAtlas); + BindAtlasTexture(ctx, data.shadowResult.cachedAreaShadowResult, HDShaderIDs._CachedAreaLightShadowmapAtlas); + }); } } @@ -117,10 +117,10 @@ internal void BlitCachedShadows(RenderGraph renderGraph, ref ShadowResult shadow passData.atlasTexture = builder.WriteTexture(shadowResult.punctualShadowResult); builder.SetRenderFunc( - (BlitCachedShadowPassData data, RenderGraphContext ctx) => - { - HDDynamicShadowAtlas.BlitCachedIntoAtlas(data.shadowBlitParameters, data.atlasTexture, data.sourceCachedAtlas, ctx.cmd); - }); + (BlitCachedShadowPassData data, RenderGraphContext ctx) => + { + HDDynamicShadowAtlas.BlitCachedIntoAtlas(data.shadowBlitParameters, data.atlasTexture, data.sourceCachedAtlas, ctx.cmd); + }); } } @@ -136,10 +136,10 @@ internal void BlitCachedShadows(RenderGraph renderGraph, ref ShadowResult shadow passData.atlasTexture = builder.WriteTexture(shadowResult.areaShadowResult); builder.SetRenderFunc( - (BlitCachedShadowPassData data, RenderGraphContext ctx) => - { - HDDynamicShadowAtlas.BlitCachedIntoAtlas(data.shadowBlitParameters, data.atlasTexture, data.sourceCachedAtlas, ctx.cmd); - }); + (BlitCachedShadowPassData data, RenderGraphContext ctx) => + { + HDDynamicShadowAtlas.BlitCachedIntoAtlas(data.shadowBlitParameters, data.atlasTexture, data.sourceCachedAtlas, ctx.cmd); + }); } } } @@ -147,7 +147,6 @@ internal void BlitCachedShadows(RenderGraph renderGraph, ref ShadowResult shadow partial class HDShadowAtlas { - public TextureDesc GetTextureDesc(bool clearBuffer = false) { return new TextureDesc(width, height) @@ -171,7 +170,7 @@ class RenderShadowsPassData TextureHandle AllocateMomentAtlas(RenderGraph renderGraph, string name) { return renderGraph.CreateTexture(new TextureDesc(width / 2, height / 2) - { colorFormat = GraphicsFormat.R32G32_SFloat, useMipMap = true, autoGenerateMips = false, name = name, enableRandomWrite = true }); + { colorFormat = GraphicsFormat.R32G32_SFloat, useMipMap = true, autoGenerateMips = false, name = name, enableRandomWrite = true }); } internal void RenderShadows(RenderGraph renderGraph, CullingResults cullResults, in ShaderVariablesGlobal globalCB, FrameSettings frameSettings, string shadowPassName, ref TextureHandle result) @@ -202,39 +201,39 @@ internal void RenderShadows(RenderGraph renderGraph, CullingResults cullResults, else if (passData.parameters.blurAlgorithm == BlurAlgorithm.IM) { passData.momentAtlasTexture1 = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(width, height) - { colorFormat = GraphicsFormat.R32G32B32A32_SFloat, name = m_MomentName, enableRandomWrite = true })); + { colorFormat = GraphicsFormat.R32G32B32A32_SFloat, name = m_MomentName, enableRandomWrite = true })); passData.intermediateSummedAreaTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(width, height) - { colorFormat = GraphicsFormat.R32G32B32A32_SInt, name = m_IntermediateSummedAreaName, enableRandomWrite = true })); + { colorFormat = GraphicsFormat.R32G32B32A32_SInt, name = m_IntermediateSummedAreaName, enableRandomWrite = true })); passData.summedAreaTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(width, height) - { colorFormat = GraphicsFormat.R32G32B32A32_SInt, name = m_SummedAreaName, enableRandomWrite = true })); + { colorFormat = GraphicsFormat.R32G32B32A32_SInt, name = m_SummedAreaName, enableRandomWrite = true })); result = passData.momentAtlasTexture1; } builder.SetRenderFunc( - (RenderShadowsPassData data, RenderGraphContext context) => - { - RenderShadows( data.parameters, - data.atlasTexture, - data.shadowDrawSettings, - context.renderContext, - data.isRenderingOnACache, - context.cmd); - - if (data.parameters.blurAlgorithm == BlurAlgorithm.EVSM) + (RenderShadowsPassData data, RenderGraphContext context) => { - RTHandle[] momentTextures = context.renderGraphPool.GetTempArray(2); - momentTextures[0] = data.momentAtlasTexture1; - momentTextures[1] = data.momentAtlasTexture2; - - EVSMBlurMoments(data.parameters, data.atlasTexture, momentTextures, data.isRenderingOnACache, context.cmd); - } - else if (data.parameters.blurAlgorithm == BlurAlgorithm.IM) - { - IMBlurMoment(data.parameters, data.atlasTexture, data.momentAtlasTexture1, data.intermediateSummedAreaTexture, data.summedAreaTexture, context.cmd); - } - }); + RenderShadows(data.parameters, + data.atlasTexture, + data.shadowDrawSettings, + context.renderContext, + data.isRenderingOnACache, + context.cmd); + + if (data.parameters.blurAlgorithm == BlurAlgorithm.EVSM) + { + RTHandle[] momentTextures = context.renderGraphPool.GetTempArray(2); + momentTextures[0] = data.momentAtlasTexture1; + momentTextures[1] = data.momentAtlasTexture2; + + EVSMBlurMoments(data.parameters, data.atlasTexture, momentTextures, data.isRenderingOnACache, context.cmd); + } + else if (data.parameters.blurAlgorithm == BlurAlgorithm.IM) + { + IMBlurMoment(data.parameters, data.atlasTexture, data.momentAtlasTexture1, data.intermediateSummedAreaTexture, data.summedAreaTexture, context.cmd); + } + }); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs index c3ff8337c0c..3046bca3c66 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowManager.cs @@ -37,7 +37,7 @@ enum ShadowMapUpdateType Dynamic = 0, // Fully cached shadow maps (nothing is rendered unless requested) Cached, - // Mixed, static shadow caster are cached and updated as indicated, dynamic are drawn on top. + // Mixed, static shadow caster are cached and updated as indicated, dynamic are drawn on top. Mixed } @@ -194,9 +194,9 @@ internal static HDShadowAtlasInitParams GetDefault() areaLightShadowAtlas = HDShadowAtlasInitParams.GetDefault(), cachedPunctualLightShadowAtlas = 2048, cachedAreaLightShadowAtlas = 1024, - shadowResolutionDirectional = new IntScalableSetting(new []{ 256, 512, 1024, 2048 }, ScalableSettingSchemaId.With4Levels), - shadowResolutionArea = new IntScalableSetting(new []{ 256, 512, 1024, 2048 }, ScalableSettingSchemaId.With4Levels), - shadowResolutionPunctual = new IntScalableSetting(new []{ 256, 512, 1024, 2048 }, ScalableSettingSchemaId.With4Levels), + shadowResolutionDirectional = new IntScalableSetting(new[] { 256, 512, 1024, 2048 }, ScalableSettingSchemaId.With4Levels), + shadowResolutionArea = new IntScalableSetting(new[] { 256, 512, 1024, 2048 }, ScalableSettingSchemaId.With4Levels), + shadowResolutionPunctual = new IntScalableSetting(new[] { 256, 512, 1024, 2048 }, ScalableSettingSchemaId.With4Levels), shadowFilteringQuality = HDShadowFilteringQuality.Medium, supportScreenSpaceShadows = false, maxScreenSpaceShadowSlots = 4, @@ -204,7 +204,6 @@ internal static HDShadowAtlasInitParams GetDefault() maxDirectionalShadowMapResolution = 2048, maxAreaShadowMapResolution = 2048, maxPunctualShadowMapResolution = 2048, - }; internal const int k_DefaultShadowAtlasResolution = 4096; @@ -284,7 +283,7 @@ partial class HDShadowManager : IDisposable ComputeBuffer m_DirectionalShadowDataBuffer; // The two shadowmaps atlases we uses, one for directional cascade (without resize) and the second for the rest of the shadows - HDDynamicShadowAtlas m_CascadeAtlas; + HDDynamicShadowAtlas m_CascadeAtlas; HDDynamicShadowAtlas m_Atlas; HDDynamicShadowAtlas m_AreaLightShadowAtlas; @@ -324,14 +323,14 @@ public void InitShadowManager(RenderPipelineResources renderPipelineResources, H // The cascade atlas will be allocated only if there is a directional light m_Atlas = new HDDynamicShadowAtlas(renderPipelineResources, initParams.punctualLightShadowAtlas.shadowAtlasResolution, initParams.punctualLightShadowAtlas.shadowAtlasResolution, - HDShaderIDs._ShadowmapAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams, depthBufferBits: initParams.punctualLightShadowAtlas.shadowAtlasDepthBits, name: "Shadow Map Atlas"); + HDShaderIDs._ShadowmapAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams, depthBufferBits: initParams.punctualLightShadowAtlas.shadowAtlasDepthBits, name: "Shadow Map Atlas"); // Cascade atlas render texture will only be allocated if there is a shadow casting directional light HDShadowAtlas.BlurAlgorithm cascadeBlur = GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS ? HDShadowAtlas.BlurAlgorithm.IM : HDShadowAtlas.BlurAlgorithm.None; m_CascadeAtlas = new HDDynamicShadowAtlas(renderPipelineResources, 1, 1, HDShaderIDs._ShadowmapCascadeAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams, cascadeBlur, depthBufferBits: initParams.directionalShadowsDepthBits, name: "Cascade Shadow Map Atlas"); if (ShaderConfig.s_AreaLights == 1) m_AreaLightShadowAtlas = new HDDynamicShadowAtlas(renderPipelineResources, initParams.areaLightShadowAtlas.shadowAtlasResolution, initParams.areaLightShadowAtlas.shadowAtlasResolution, - HDShaderIDs._ShadowmapAreaAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams, HDShadowAtlas.BlurAlgorithm.EVSM, depthBufferBits: initParams.areaLightShadowAtlas.shadowAtlasDepthBits, name: "Area Light Shadow Map Atlas"); + HDShaderIDs._ShadowmapAreaAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams, HDShadowAtlas.BlurAlgorithm.EVSM, depthBufferBits: initParams.areaLightShadowAtlas.shadowAtlasDepthBits, name: "Area Light Shadow Map Atlas"); m_ShadowDataBuffer = new ComputeBuffer(initParams.maxShadowRequests, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDShadowData))); m_DirectionalShadowDataBuffer = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(HDDirectionalShadowData))); @@ -339,10 +338,10 @@ public void InitShadowManager(RenderPipelineResources renderPipelineResources, H m_MaxShadowRequests = initParams.maxShadowRequests; cachedShadowManager.InitPunctualShadowAtlas(renderPipelineResources, initParams.cachedPunctualLightShadowAtlas, initParams.cachedPunctualLightShadowAtlas, - HDShaderIDs._CachedShadowmapAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams: initParams, depthBufferBits: initParams.punctualLightShadowAtlas.shadowAtlasDepthBits, name: "Cached Shadow Map Atlas"); + HDShaderIDs._CachedShadowmapAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams: initParams, depthBufferBits: initParams.punctualLightShadowAtlas.shadowAtlasDepthBits, name: "Cached Shadow Map Atlas"); if (ShaderConfig.s_AreaLights == 1) cachedShadowManager.InitAreaLightShadowAtlas(renderPipelineResources, initParams.cachedAreaLightShadowAtlas, initParams.cachedAreaLightShadowAtlas, - HDShaderIDs._CachedAreaLightShadowmapAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams: initParams, HDShadowAtlas.BlurAlgorithm.EVSM, depthBufferBits: initParams.areaLightShadowAtlas.shadowAtlasDepthBits, name: "Cached Area Light Shadow Map Atlas"); + HDShaderIDs._CachedAreaLightShadowmapAtlas, m_ClearShadowMaterial, initParams.maxShadowRequests, initParams: initParams, HDShadowAtlas.BlurAlgorithm.EVSM, depthBufferBits: initParams.areaLightShadowAtlas.shadowAtlasDepthBits, name: "Cached Area Light Shadow Map Atlas"); } public void InitializeNonRenderGraphResources() @@ -386,7 +385,8 @@ public static DirectionalShadowAlgorithm GetDirectionalShadowAlgorithm() { return DirectionalShadowAlgorithm.PCSS; } - }; + } + ; return DirectionalShadowAlgorithm.PCF5x5; } @@ -491,11 +491,11 @@ internal void UpdateShadowRequest(int index, HDShadowRequest shadowRequest, Shad if (addDynamic) { m_Atlas.AddShadowRequest(shadowRequest); - if(updateType == ShadowMapUpdateType.Mixed) + if (updateType == ShadowMapUpdateType.Mixed) m_Atlas.AddRequestToPendingBlitFromCache(shadowRequest); } - break; + break; } case ShadowMapType.CascadedDirectional: { @@ -517,7 +517,8 @@ internal void UpdateShadowRequest(int index, HDShadowRequest shadowRequest, Shad break; } - }; + } + ; } public void UpdateCascade(int cascadeIndex, Vector4 cullingSphere, float border) @@ -531,10 +532,10 @@ public void UpdateCascade(int cascadeIndex, Vector4 cullingSphere, float border) unsafe { - fixed (float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades) + fixed(float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades) ((Vector4 *)sphereCascadesBuffer)[cascadeIndex] = cullingSphere; - fixed (float * cascadeBorders = m_DirectionalShadowData.cascadeBorders) - cascadeBorders[cascadeIndex] = border; + fixed(float * cascadeBorders = m_DirectionalShadowData.cascadeBorders) + cascadeBorders[cascadeIndex] = border; } } @@ -582,7 +583,7 @@ HDShadowData CreateShadowData(HDShadowRequest shadowRequest, HDShadowAtlas atlas unsafe Vector4 GetCascadeSphereAtIndex(int index) { - fixed (float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades) + fixed(float * sphereCascadesBuffer = m_DirectionalShadowData.sphereCascades) { return ((Vector4 *)sphereCascadesBuffer)[index]; } @@ -636,7 +637,7 @@ unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, HDCamera ca Debug.Assert(m_ShadowRequests[i] != null); HDShadowAtlas atlas = m_Atlas; - if(m_ShadowRequests[i].isInCachedAtlas) + if (m_ShadowRequests[i].isInCachedAtlas) { atlas = cachedShadowManager.punctualShadowAtlas; } @@ -648,7 +649,7 @@ unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, HDCamera ca else if (m_ShadowRequests[i].shadowMapType == ShadowMapType.AreaLightAtlas) { atlas = m_AreaLightShadowAtlas; - if(m_ShadowRequests[i].isInCachedAtlas) + if (m_ShadowRequests[i].isInCachedAtlas) { atlas = cachedShadowManager.areaShadowAtlas; } @@ -671,7 +672,7 @@ unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, HDCamera ca int first = k_DirectionalShadowCascadeCount, second = k_DirectionalShadowCascadeCount; - fixed (float *sphereBuffer = m_DirectionalShadowData.sphereCascades) + fixed(float *sphereBuffer = m_DirectionalShadowData.sphereCascades) { Vector4 * sphere = (Vector4 *)sphereBuffer; for (int i = 0; i < k_DirectionalShadowCascadeCount; i++) @@ -702,7 +703,7 @@ public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer c { // Avoid to do any commands if there is no shadow to draw if (m_ShadowRequestCount == 0) - return ; + return; using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderCachedPunctualShadowMaps))) { @@ -745,19 +746,18 @@ public void BlitCacheIntoAtlas(CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BlitPunctualMixedCachedShadowMaps))) { - HDDynamicShadowAtlas.BlitCachedIntoAtlas(m_Atlas.PrepareShadowBlitParameters(cachedShadowManager.punctualShadowAtlas, m_BlitShadowMaterial, m_BlitShadowPropertyBlock), - m_Atlas.renderTarget, - cachedShadowManager.punctualShadowAtlas.renderTarget, - cmd); + m_Atlas.renderTarget, + cachedShadowManager.punctualShadowAtlas.renderTarget, + cmd); } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BlitAreaMixedCachedShadowMaps))) { HDDynamicShadowAtlas.BlitCachedIntoAtlas(m_AreaLightShadowAtlas.PrepareShadowBlitParameters(cachedShadowManager.areaShadowAtlas, m_BlitShadowMaterial, m_BlitShadowPropertyBlock), - m_AreaLightShadowAtlas.renderTarget, - cachedShadowManager.areaShadowAtlas.renderTarget, - cmd); + m_AreaLightShadowAtlas.renderTarget, + cachedShadowManager.areaShadowAtlas.renderTarget, + cmd); } } @@ -793,7 +793,7 @@ public void Clear() if (ShaderConfig.s_AreaLights == 1) m_AreaLightShadowAtlas.Clear(); - cachedShadowManager.ClearShadowRequests(); + cachedShadowManager.ClearShadowRequests(); m_ShadowResolutionRequestCounter = 0; @@ -889,7 +889,8 @@ public void DisplayShadowMap(in ShadowDebugAtlasTextures atlasTextures, int shad } break; } - }; + } + ; } public void Dispose() diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSampling.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSampling.hlsl index 3385619cefd..d912a266a1c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSampling.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSampling.hlsl @@ -319,7 +319,7 @@ float SampleShadow_PCSS(float3 tcs, float2 posSS, float2 scale, float2 offset, f dist = min(dist, 7.5); // We need to clamp the distance as the fitted curve will do strange things after this and because there is no point in scale further after this point. float dist2 = dist * dist; float dist4 = dist2 * dist2; - // Fitted curve to match ray trace reference as good as possible. + // Fitted curve to match ray trace reference as good as possible. float distScale = 3.298300241 - 2.001364639 * dist + 0.4967311427 * dist2 - 0.05464058455 * dist * dist2 + 0.0021974 * dist2 * dist2; shadowSoftness *= distScale; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowUtils.cs index 4b9fb0c4a5f..47176b82d59 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowUtils.cs @@ -31,7 +31,7 @@ static float GetPunctualFilterWidthInTexels(HDShadowFilteringQuality quality) } public static void ExtractPointLightData(VisibleLight visibleLight, Vector2 viewportSize, float nearPlane, float normalBiasMax, uint faceIndex, HDShadowFilteringQuality filteringQuality, - out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) + out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) { Vector4 lightDir; @@ -41,7 +41,7 @@ public static void ExtractPointLightData(VisibleLight visibleLight, Vector2 view // TODO: box spot and pyramid spots with non 1 aspect ratios shadow are incorrectly culled, see when scriptable culling will be here public static void ExtractSpotLightData(SpotLightShape shape, float spotAngle, float nearPlane, float aspectRatio, float shapeWidth, float shapeHeight, VisibleLight visibleLight, Vector2 viewportSize, float normalBiasMax, HDShadowFilteringQuality filteringQuality, - out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) + out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) { Vector4 lightDir; @@ -90,7 +90,7 @@ public static void ExtractDirectionalLightData(VisibleLight visibleLight, Vector // Currently area light shadows are not supported public static void ExtractRectangleAreaLightData(VisibleLight visibleLight, Vector3 shadowPosition, float areaLightShadowCone, float shadowNearPlane, Vector2 shapeSize, Vector2 viewportSize, float normalBiasMax, HDShadowFilteringQuality filteringQuality, - out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) + out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) { Vector4 lightDir; float aspectRatio = shapeSize.x / shapeSize.y; @@ -232,7 +232,7 @@ public static Matrix4x4 ExtractSpotLightProjectionMatrix(float range, float spot mat.m11 = e; } - mat.m22 = -(f + n)/(f - n); + mat.m22 = -(f + n) / (f - n); mat.m23 = -2 * f * n / (f - n); mat.m32 = -1; @@ -265,7 +265,7 @@ static Matrix4x4 ExtractSpotLightMatrix(VisibleLight vl, float spotAngle, float deviceProj = GL.GetGPUProjectionMatrix(proj, false); proj = GL.GetGPUProjectionMatrix(proj, true); InvertPerspective(ref deviceProj, ref view, out vpinverse); - return CoreMatrixUtils.MultiplyPerspectiveMatrix(deviceProj, view); + return CoreMatrixUtils.MultiplyPerspectiveMatrix(deviceProj, view); } static Matrix4x4 ExtractPointLightMatrix(VisibleLight vl, uint faceIdx, float nearPlane, float guardAngle, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute index a40eae42bc2..c8554a7aaa7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute @@ -30,14 +30,14 @@ RWTexture2D _FilterOutputTexture; [numthreads(MOMENT_SHADOW_TILE_SIZE, MOMENT_SHADOW_TILE_SIZE, 1)] void ComputeMomentShadows(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_GroupID) { - // Fetch the current pixel coordinate - uint2 currentPixelCoordinate = groupId * MOMENT_SHADOW_TILE_SIZE + groupThreadId; - // Displace by the offset in the atlas + // Fetch the current pixel coordinate + uint2 currentPixelCoordinate = groupId * MOMENT_SHADOW_TILE_SIZE + groupThreadId; + // Displace by the offset in the atlas currentPixelCoordinate += _MomentShadowmapSlotST.zw; // If this pixel is outside of the range of the current kernel, skip it if(float(currentPixelCoordinate.x) >= _MomentShadowmapSlotST.z + _MomentShadowmapSlotST.x || float(currentPixelCoordinate.y) >= _MomentShadowmapSlotST.w + _MomentShadowmapSlotST.y) - return; + return; // Compute the different moments float z = 1.0 - _ShadowmapAtlas[currentPixelCoordinate].x; @@ -51,10 +51,10 @@ void ComputeMomentShadows(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId float4 moments = float4(z, z2, z3, z3 * z); // Optimize the moments - moments.xz = mul(moments.xz, float2x2(1.5f, sqrt(3.0f) * 0.5f, -2.0f, -sqrt(3.0f) * 2.0f / 9.0f)) + 0.5f; - moments.yw = mul(moments.yw, float2x2(4.0f, 0.5f, -4.0f, 0.5f)); + moments.xz = mul(moments.xz, float2x2(1.5f, sqrt(3.0f) * 0.5f, -2.0f, -sqrt(3.0f) * 2.0f / 9.0f)) + 0.5f; + moments.yw = mul(moments.yw, float2x2(4.0f, 0.5f, -4.0f, 0.5f)); - // Output the moments to the atlas + // Output the moments to the atlas _MomentShadowAtlas[currentPixelCoordinate] = moments; } @@ -148,14 +148,14 @@ void MomentSummedAreaTableVertical(uint groupThreadId : SV_GroupThreadID, uint g [numthreads(MOMENT_SHADOW_TILE_SIZE, MOMENT_SHADOW_TILE_SIZE, 1)] void HORIZONTAL_FILTER_PASS(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_GroupID) { - // Fetch the current pixel coordinate - uint2 currentPixelCoordinate = groupId * MOMENT_SHADOW_TILE_SIZE + groupThreadId; - // Displace by the offset in the atlas + // Fetch the current pixel coordinate + uint2 currentPixelCoordinate = groupId * MOMENT_SHADOW_TILE_SIZE + groupThreadId; + // Displace by the offset in the atlas currentPixelCoordinate += _MomentShadowmapSlotST.zw; // If this pixel is outside of the range of the current kernel, skip it if(currentPixelCoordinate.x >= _MomentShadowmapSlotST.z + _MomentShadowmapSlotST.x || currentPixelCoordinate.y >= _MomentShadowmapSlotST.w + _MomentShadowmapSlotST.y) - return; + return; // Inverse dimension of the atlas float2 invAtlasSize = 1.0f / _MomentShadowmapSize; @@ -200,21 +200,21 @@ void HORIZONTAL_FILTER_PASS(uint2 groupThreadId : SV_GroupThreadID, uint2 groupI + 0.0581035630769f * SAMPLE_TEXTURE2D_LOD(_FilterInputTexture, s_linear_clamp_sampler, tc3, 0); #endif - // Output the moments to the atlas + // Output the moments to the atlas _FilterOutputTexture[currentPixelCoordinate] = horizontalFiltered; } [numthreads(MOMENT_SHADOW_TILE_SIZE, MOMENT_SHADOW_TILE_SIZE, 1)] void VERTICAL_FILTER_PASS(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_GroupID) { - // Fetch the current pixel coordinate - uint2 currentPixelCoordinate = groupId * MOMENT_SHADOW_TILE_SIZE + groupThreadId; - // Displace by the offset in the atlas + // Fetch the current pixel coordinate + uint2 currentPixelCoordinate = groupId * MOMENT_SHADOW_TILE_SIZE + groupThreadId; + // Displace by the offset in the atlas currentPixelCoordinate += _MomentShadowmapSlotST.zw; // If this pixel is outside of the range of the current kernel, skip it if(currentPixelCoordinate.x >= _MomentShadowmapSlotST.z + _MomentShadowmapSlotST.x || currentPixelCoordinate.y >= _MomentShadowmapSlotST.w + _MomentShadowmapSlotST.y) - return; + return; // Inverse dimension of the atlas float2 invAtlasSize = 1.0f / _MomentShadowmapSize; @@ -259,7 +259,7 @@ void VERTICAL_FILTER_PASS(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId + 0.0581035630769f * SAMPLE_TEXTURE2D_LOD(_FilterInputTexture, s_linear_clamp_sampler, tc3, 0); #endif - // Output the moments to the atlas + // Output the moments to the atlas _FilterOutputTexture[currentPixelCoordinate] = filtered; } */ diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs index f3bab113b14..40a520d224c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.RenderGraph.cs @@ -22,7 +22,6 @@ internal TextureHandle CreateScreenSpaceShadowTextureArray(RenderGraph renderGra }); } - class ScreenSpaceShadowDebugPassData { public SSShadowDebugParameters parameters; @@ -41,16 +40,16 @@ TextureHandle EvaluateShadowDebugView(RenderGraph renderGraph, HDCamera hdCamera passData.parameters = PrepareSSShadowDebugParameters(hdCamera, (int)m_CurrentDebugDisplaySettings.data.screenSpaceShadowIndex); passData.screenSpaceShadowArray = builder.ReadTexture(screenSpaceShadowArray); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "EvaluateShadowDebug" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "EvaluateShadowDebug" })); builder.SetRenderFunc( - (ScreenSpaceShadowDebugPassData data, RenderGraphContext context) => - { - SSShadowDebugResources resources = new SSShadowDebugResources(); - resources.screenSpaceShadowArray = data.screenSpaceShadowArray; - resources.outputBuffer = data.outputBuffer; - ExecuteShadowDebugView(context.cmd, data.parameters, resources); - }); + (ScreenSpaceShadowDebugPassData data, RenderGraphContext context) => + { + SSShadowDebugResources resources = new SSShadowDebugResources(); + resources.screenSpaceShadowArray = data.screenSpaceShadowArray; + resources.outputBuffer = data.outputBuffer; + ExecuteShadowDebugView(context.cmd, data.parameters, resources); + }); return passData.outputBuffer; } } @@ -72,13 +71,13 @@ void WriteScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera, TextureH passData.outputShadowArrayBuffer = builder.WriteTexture(builder.ReadTexture(screenSpaceShadowArray)); builder.SetRenderFunc( - (WriteScreenSpaceShadowPassData data, RenderGraphContext context) => - { - WriteScreenSpaceShadowResources resources = new WriteScreenSpaceShadowResources(); - resources.inputShadowBuffer = data.inputShadowBuffer; - resources.outputShadowArrayBuffer = data.outputShadowArrayBuffer; - ExecuteWriteScreenSpaceShadow(context.cmd, data.parameters, resources); - }); + (WriteScreenSpaceShadowPassData data, RenderGraphContext context) => + { + WriteScreenSpaceShadowResources resources = new WriteScreenSpaceShadowResources(); + resources.inputShadowBuffer = data.inputShadowBuffer; + resources.outputShadowArrayBuffer = data.outputShadowArrayBuffer; + ExecuteWriteScreenSpaceShadow(context.cmd, data.parameters, resources); + }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs index 9899f163faf..22103907eae 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManager.cs @@ -22,7 +22,7 @@ public partial class HDRenderPipeline ComputeShader m_ScreenSpaceShadowsFilterCS; // Kernels - // Shared shadow kernels + // Shared shadow kernels int m_ClearShadowTexture; int m_OutputShadowTextureKernel; int m_OutputColorShadowTextureKernel; @@ -77,7 +77,7 @@ static RTHandle ShadowHistoryValidityBufferAllocatorFunction(string viewName, in GraphicsFormat graphicsFormat = (GraphicsFormat)hdPipelineAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.screenSpaceShadowBufferFormat; int numShadowSlices = Math.Max((int)Math.Ceiling(hdrp.m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots / 4.0f), 1); return rtHandleSystem.Alloc(Vector2.one, slices: numShadowSlices * TextureXR.slices, dimension: TextureDimension.Tex2DArray, filterMode: FilterMode.Point, colorFormat: graphicsFormat, - enableRandomWrite: true, useDynamicScale: true, useMipMap: false, name: string.Format("{0}_ShadowHistoryValidityBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useDynamicScale: true, useMipMap: false, name: string.Format("{0}_ShadowHistoryValidityBuffer{1}", viewName, frameIndex)); } static RTHandle ShadowHistoryDistanceBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) @@ -87,7 +87,7 @@ static RTHandle ShadowHistoryDistanceBufferAllocatorFunction(string viewName, in GraphicsFormat graphicsFormat = (GraphicsFormat)hdPipelineAsset.currentPlatformRenderPipelineSettings.hdShadowInitParams.screenSpaceShadowBufferFormat; int numShadowSlices = Math.Max((int)Math.Ceiling(hdrp.m_Asset.currentPlatformRenderPipelineSettings.hdShadowInitParams.maxScreenSpaceShadowSlots / 4.0f), 1); return rtHandleSystem.Alloc(Vector2.one, slices: numShadowSlices * TextureXR.slices, dimension: TextureDimension.Tex2DArray, filterMode: FilterMode.Point, colorFormat: graphicsFormat, - enableRandomWrite: true, useDynamicScale: true, useMipMap: false, name: string.Format("{0}_ShadowHistoryDistanceBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useDynamicScale: true, useMipMap: false, name: string.Format("{0}_ShadowHistoryDistanceBuffer{1}", viewName, frameIndex)); } RTHandle RequestShadowHistoryBuffer(HDCamera hdCamera) @@ -125,25 +125,25 @@ static void GetShadowChannelMask(int shadowSlot, ScreenSpaceShadowType shadowTyp switch (outputChannel) { case 0: - { - outputMask.Set(1.0f, 0.0f, 0.0f, 0.0f); - break; - } + { + outputMask.Set(1.0f, 0.0f, 0.0f, 0.0f); + break; + } case 1: - { - outputMask.Set(0.0f, 1.0f, 0.0f, 0.0f); - break; - } + { + outputMask.Set(0.0f, 1.0f, 0.0f, 0.0f); + break; + } case 2: - { - outputMask.Set(0.0f, 0.0f, 1.0f, 0.0f); - break; - } + { + outputMask.Set(0.0f, 0.0f, 1.0f, 0.0f); + break; + } case 3: - { - outputMask.Set(0.0f, 0.0f, 0.0f, 1.0f); - break; - } + { + outputMask.Set(0.0f, 0.0f, 0.0f, 1.0f); + break; + } } } else if (shadowType == ScreenSpaceShadowType.Area) @@ -151,20 +151,20 @@ static void GetShadowChannelMask(int shadowSlot, ScreenSpaceShadowType shadowTyp switch (outputChannel) { case 0: - { - outputMask.Set(1.0f, 1.0f, 0.0f, 0.0f); - break; - } + { + outputMask.Set(1.0f, 1.0f, 0.0f, 0.0f); + break; + } case 1: - { - outputMask.Set(0.0f, 1.0f, 1.0f, 0.0f); - break; - } + { + outputMask.Set(0.0f, 1.0f, 1.0f, 0.0f); + break; + } case 2: - { - outputMask.Set(0.0f, 0.0f, 1.0f, 1.0f); - break; - } + { + outputMask.Set(0.0f, 0.0f, 1.0f, 1.0f); + break; + } default: Debug.Assert(false); break; @@ -175,10 +175,10 @@ static void GetShadowChannelMask(int shadowSlot, ScreenSpaceShadowType shadowTyp switch (outputChannel) { case 0: - { - outputMask.Set(1.0f, 1.0f, 1.0f, 0.0f); - break; - } + { + outputMask.Set(1.0f, 1.0f, 1.0f, 0.0f); + break; + } default: Debug.Assert(false); break; @@ -313,7 +313,7 @@ bool RenderLightScreenSpaceShadows(HDCamera hdCamera, CommandBuffer cmd) GPULightType lightType = GPULightType.Point; EvaluateGPULightType(extraLightData.type, extraLightData.spotLightShape, extraLightData.areaLightShape, - ref category, ref lightType); + ref category, ref lightType); /* TODO: Broken in XR, fix later // Trigger the right algorithm based on the light type diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs index 67ea7ec7edb..dfd79243181 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerArea.cs @@ -125,8 +125,8 @@ struct RTSAreaRayTraceResources } RTSAreaRayTraceResources PrepareRTSAreaRayTraceResources(HDCamera hdCamera, RTHandle directionBuffer, RTHandle rayLengthBuffer, - RTHandle intermediateBufferRGBA0, RTHandle intermediateBufferRGBA1, RTHandle intermediateBufferRG0, - RTHandle shadowHistoryArray, RTHandle analyticHistoryArray) + RTHandle intermediateBufferRGBA0, RTHandle intermediateBufferRGBA1, RTHandle intermediateBufferRG0, + RTHandle shadowHistoryArray, RTHandle analyticHistoryArray) { RTSAreaRayTraceResources rtsartResources = new RTSAreaRayTraceResources(); @@ -297,7 +297,7 @@ static void ExecuteSSSAreaRayTrace(CommandBuffer cmd, RTSAreaRayTraceParameters cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._DenoiseOutputTextureRW, sssartResources.intermediateBufferRGBA1); cmd.SetComputeFloatParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._HistoryValidity, parameters.historyValidity); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, numTilesX, numTilesY, parameters.viewCount); - + // Update the shadow history buffer cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateAnalyticHistoryKernel, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateAnalyticHistoryKernel, HDShaderIDs._AnalyticHistoryBuffer, sssartResources.analyticHistoryArray); @@ -344,7 +344,7 @@ static void ExecuteSSSAreaRayTrace(CommandBuffer cmd, RTSAreaRayTraceParameters } void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera - , in LightData lightData, HDAdditionalLightData additionalLightData, int lightIndex) + , in LightData lightData, HDAdditionalLightData additionalLightData, int lightIndex) { RTHandle intermediateBufferRG0 = GetRayTracingBuffer(InternalRayTracingBuffers.RG0); RTHandle intermediateBufferRGBA0 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA0); @@ -360,8 +360,8 @@ void RenderAreaScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera RTSAreaRayTraceParameters sssartParams = PrepareRTSAreaRayTraceParameters(hdCamera, additionalLightData, lightData, lightIndex); RTSAreaRayTraceResources sssartResources = PrepareRTSAreaRayTraceResources(hdCamera, directionBuffer, rayLengthBuffer, - intermediateBufferRGBA0, intermediateBufferRGBA1, intermediateBufferRG0, - shadowHistoryArray, analyticHistoryArray); + intermediateBufferRGBA0, intermediateBufferRGBA1, intermediateBufferRG0, + shadowHistoryArray, analyticHistoryArray); ExecuteSSSAreaRayTrace(cmd, sssartParams, sssartResources); int areaShadowSlot = -1; // m_lightList.lights[lightIndex].screenSpaceShadowIndex; // TODO FIX ME @@ -406,7 +406,7 @@ class RTShadowAreaPassData } void RenderAreaScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera - , in LightData lightData, HDAdditionalLightData additionalLightData, int lightIndex, + , in LightData lightData, HDAdditionalLightData additionalLightData, int lightIndex, PrepassOutput prepassOutput, TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVectorsBuffer, TextureHandle rayCountTexture, TextureHandle screenSpaceShadowArray) { // Grab the history buffers for shadows @@ -443,7 +443,7 @@ void RenderAreaScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera // Intermediate buffers passData.directionBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Direction Buffer" }); passData.rayLengthBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Ray Length Buffer" }); - passData.intermediateBufferRGBA1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Buffer RGBA1" }); ; + passData.intermediateBufferRGBA1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Buffer RGBA1" });; passData.intermediateBufferRG0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Buffer RG0" }); // Debug textures @@ -452,33 +452,33 @@ void RenderAreaScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera // Output buffers passData.outputShadowTexture = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Shadow Buffer" }))); builder.SetRenderFunc( - (RTShadowAreaPassData data, RenderGraphContext context) => - { - RTSAreaRayTraceResources resources = new RTSAreaRayTraceResources(); - // Input Buffers - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.motionVectorsBuffer = data.motionVectorsBuffer; - resources.gbuffer0 = data.gbuffer0; - resources.gbuffer1 = data.gbuffer1; - resources.gbuffer2 = data.gbuffer2; - resources.gbuffer3 = data.gbuffer3; - resources.shadowHistoryArray = data.shadowHistoryArray; - resources.analyticHistoryArray = data.analyticHistoryArray; - - // Intermediate buffers - resources.directionBuffer = data.directionBuffer; - resources.rayLengthBuffer = data.rayLengthBuffer; - resources.intermediateBufferRGBA1 = data.intermediateBufferRGBA1; - resources.intermediateBufferRG0 = data.intermediateBufferRG0; - - // Debug textures - resources.rayCountTexture = data.rayCountTexture; - - // Output buffers - resources.outputShadowTexture = data.outputShadowTexture; - ExecuteSSSAreaRayTrace(context.cmd, data.parameters, resources); - }); + (RTShadowAreaPassData data, RenderGraphContext context) => + { + RTSAreaRayTraceResources resources = new RTSAreaRayTraceResources(); + // Input Buffers + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.motionVectorsBuffer = data.motionVectorsBuffer; + resources.gbuffer0 = data.gbuffer0; + resources.gbuffer1 = data.gbuffer1; + resources.gbuffer2 = data.gbuffer2; + resources.gbuffer3 = data.gbuffer3; + resources.shadowHistoryArray = data.shadowHistoryArray; + resources.analyticHistoryArray = data.analyticHistoryArray; + + // Intermediate buffers + resources.directionBuffer = data.directionBuffer; + resources.rayLengthBuffer = data.rayLengthBuffer; + resources.intermediateBufferRGBA1 = data.intermediateBufferRGBA1; + resources.intermediateBufferRG0 = data.intermediateBufferRG0; + + // Debug textures + resources.rayCountTexture = data.rayCountTexture; + + // Output buffers + resources.outputShadowTexture = data.outputShadowTexture; + ExecuteSSSAreaRayTrace(context.cmd, data.parameters, resources); + }); areaShadow = passData.outputShadowTexture; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs index 8847078c6e0..93b5c35e7e7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.RenderGraph.cs @@ -7,8 +7,8 @@ namespace UnityEngine.Rendering.HighDefinition public partial class HDRenderPipeline { TextureHandle DenoiseDirectionalScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVetorsBuffer, - TextureHandle noisyBuffer, TextureHandle velocityBuffer, TextureHandle distanceBuffer) + TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVetorsBuffer, + TextureHandle noisyBuffer, TextureHandle velocityBuffer, TextureHandle distanceBuffer) { // Is the history still valid? int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)TiledLightingConstants.s_ScreenSpaceShadowIndexMask; @@ -26,20 +26,20 @@ TextureHandle DenoiseDirectionalScreenSpaceShadow(RenderGraph renderGraph, HDCam // Apply the temporal denoiser HDTemporalFilter temporalFilter = GetTemporalFilter(); HDTemporalFilter.TemporalDenoiserArrayOutputData temporalFilterResult = temporalFilter.DenoiseBuffer(renderGraph, hdCamera, - depthBuffer, normalBuffer, motionVetorsBuffer, - noisyBuffer, shadowHistoryArray, - distanceBuffer, shadowHistoryDistanceArray, - velocityBuffer, - shadowHistoryValidityArray, - dirShadowIndex / 4, m_ShadowChannelMask0, m_ShadowChannelMask1, - true, !m_CurrentSunLightAdditionalLightData.colorShadow, historyValidity); + depthBuffer, normalBuffer, motionVetorsBuffer, + noisyBuffer, shadowHistoryArray, + distanceBuffer, shadowHistoryDistanceArray, + velocityBuffer, + shadowHistoryValidityArray, + dirShadowIndex / 4, m_ShadowChannelMask0, m_ShadowChannelMask1, + true, !m_CurrentSunLightAdditionalLightData.colorShadow, historyValidity); // Apply the spatial denoiser HDDiffuseShadowDenoiser shadowDenoiser = GetDiffuseShadowDenoiser(); TextureHandle denoisedBuffer = shadowDenoiser.DenoiseBufferDirectional(renderGraph, hdCamera, - depthBuffer, normalBuffer, - temporalFilterResult.outputSignal, temporalFilterResult.outputSignalDistance, - m_CurrentSunLightAdditionalLightData.filterSizeTraced, m_CurrentSunLightAdditionalLightData.angularDiameter * 0.5f, !m_CurrentSunLightAdditionalLightData.colorShadow); + depthBuffer, normalBuffer, + temporalFilterResult.outputSignal, temporalFilterResult.outputSignalDistance, + m_CurrentSunLightAdditionalLightData.filterSizeTraced, m_CurrentSunLightAdditionalLightData.angularDiameter * 0.5f, !m_CurrentSunLightAdditionalLightData.colorShadow); // Now that we have overriden this history, mark is as used by this light hdCamera.PropagateShadowHistory(m_CurrentSunLightAdditionalLightData, dirShadowIndex, GPULightType.Directional); @@ -79,25 +79,25 @@ void RenderRayTracedDirectionalScreenSpaceShadow(RenderGraph renderGraph, HDCame // Output Buffers passData.velocityBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8_SNorm, enableRandomWrite = true, clearBuffer = true, name = "Velocity Buffer" }))); + { colorFormat = GraphicsFormat.R8_SNorm, enableRandomWrite = true, clearBuffer = true, name = "Velocity Buffer" }))); passData.distanceBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, clearBuffer = true, name = "Distance Buffer" }))); + { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, clearBuffer = true, name = "Distance Buffer" }))); passData.outputShadowBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, clearBuffer = true, name = "RT Directional Shadow" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, clearBuffer = true, name = "RT Directional Shadow" }))); builder.SetRenderFunc( - (RTSDirectionalTracePassData data, RenderGraphContext context) => - { - RTShadowDirectionalTraceResources resources = new RTShadowDirectionalTraceResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.directionBuffer = data.directionBuffer; - resources.rayCountTexture = data.rayCountTexture; - resources.velocityBuffer = data.velocityBuffer; - resources.distanceBuffer = data.distanceBuffer; - resources.outputShadowBuffer = data.outputShadowBuffer; - ExecuteSSSDirectionalTrace(context.cmd, data.parameters, resources); - }); + (RTSDirectionalTracePassData data, RenderGraphContext context) => + { + RTShadowDirectionalTraceResources resources = new RTShadowDirectionalTraceResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.directionBuffer = data.directionBuffer; + resources.rayCountTexture = data.rayCountTexture; + resources.velocityBuffer = data.velocityBuffer; + resources.distanceBuffer = data.distanceBuffer; + resources.outputShadowBuffer = data.outputShadowBuffer; + ExecuteSSSDirectionalTrace(context.cmd, data.parameters, resources); + }); directionalShadow = passData.outputShadowBuffer; velocityBuffer = passData.velocityBuffer; distanceBuffer = passData.distanceBuffer; @@ -107,12 +107,12 @@ void RenderRayTracedDirectionalScreenSpaceShadow(RenderGraph renderGraph, HDCame if (m_CurrentSunLightAdditionalLightData.filterTracedShadow && rtsdtParams.softShadow) { directionalShadow = DenoiseDirectionalScreenSpaceShadow(renderGraph, hdCamera, - depthBuffer, normalBuffer, motionVetorsBuffer, - directionalShadow, velocityBuffer, distanceBuffer); + depthBuffer, normalBuffer, motionVetorsBuffer, + directionalShadow, velocityBuffer, distanceBuffer); } int dirShadowIndex = m_CurrentSunLightDirectionalLightData.screenSpaceShadowIndex & (int)TiledLightingConstants.s_ScreenSpaceShadowIndexMask; - ScreenSpaceShadowType shadowType = m_CurrentSunLightAdditionalLightData.colorShadow? ScreenSpaceShadowType.Color: ScreenSpaceShadowType.GrayScale; + ScreenSpaceShadowType shadowType = m_CurrentSunLightAdditionalLightData.colorShadow ? ScreenSpaceShadowType.Color : ScreenSpaceShadowType.GrayScale; // Write the result texture to the screen space shadow buffer WriteScreenSpaceShadow(renderGraph, hdCamera, directionalShadow, screenSpaceShadowArray, dirShadowIndex, shadowType); @@ -146,10 +146,10 @@ void RenderDirectionalLightScreenSpaceShadow(RenderGraph renderGraph, HDCamera h passData.screenSpaceShadowArray = builder.ReadTexture(builder.WriteTexture(screenSpaceShadowArray)); builder.SetRenderFunc( - (SSSDirectionalTracePassData data, RenderGraphContext context) => - { - ExecuteSSShadowDirectional(context.cmd, data.parameters, context.renderGraphPool.GetTempMaterialPropertyBlock(), data.normalBuffer, data.screenSpaceShadowArray); - }); + (SSSDirectionalTracePassData data, RenderGraphContext context) => + { + ExecuteSSShadowDirectional(context.cmd, data.parameters, context.renderGraphPool.GetTempMaterialPropertyBlock(), data.normalBuffer, data.screenSpaceShadowArray); + }); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs index 98c22615d6b..9f27e3d857a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerDirectional.cs @@ -191,8 +191,8 @@ static float EvaluateHistoryValidityDirectionalShadow(HDCamera hdCamera, int dir historyValidity = 0.0f; else #endif - // We need to check if something invalidated the history buffers - historyValidity *= EvaluateHistoryValidity(hdCamera); + // We need to check if something invalidated the history buffers + historyValidity *= EvaluateHistoryValidity(hdCamera); return historyValidity; } @@ -217,12 +217,12 @@ void DenoiseDirectionalScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera, R // Apply the temporal denoiser HDTemporalFilter temporalFilter = GetTemporalFilter(); temporalFilter.DenoiseBuffer(cmd, hdCamera, inoutBuffer, shadowHistoryArray, - shadowHistoryValidityArray, - velocityBuffer, - intermediateBuffer, - dirShadowIndex / 4, m_ShadowChannelMask0, - distanceBuffer, shadowHistoryDistanceArray, intermediateDistanceBuffer, m_ShadowChannelMask1, - true, singleChannel: !m_CurrentSunLightAdditionalLightData.colorShadow, historyValidity: historyValidity); + shadowHistoryValidityArray, + velocityBuffer, + intermediateBuffer, + dirShadowIndex / 4, m_ShadowChannelMask0, + distanceBuffer, shadowHistoryDistanceArray, intermediateDistanceBuffer, m_ShadowChannelMask1, + true, singleChannel: !m_CurrentSunLightAdditionalLightData.colorShadow, historyValidity: historyValidity); // Apply the spatial denoiser HDDiffuseShadowDenoiser shadowDenoiser = GetDiffuseShadowDenoiser(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.RenderGraph.cs index c5556947ccc..b32fcea0b4e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.RenderGraph.cs @@ -7,9 +7,9 @@ namespace UnityEngine.Rendering.HighDefinition public partial class HDRenderPipeline { TextureHandle DenoisePunctualScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera, - HDAdditionalLightData additionalLightData, in LightData lightData, - TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVetorsBuffer, - TextureHandle noisyBuffer, TextureHandle velocityBuffer, TextureHandle distanceBufferI) + HDAdditionalLightData additionalLightData, in LightData lightData, + TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVetorsBuffer, + TextureHandle noisyBuffer, TextureHandle velocityBuffer, TextureHandle distanceBufferI) { // Is the history still valid? float historyValidity = EvaluateHistoryValidityPointShadow(hdCamera, lightData, additionalLightData); @@ -37,30 +37,30 @@ TextureHandle DenoisePunctualScreenSpaceShadow(RenderGraph renderGraph, HDCamera RTHandle shadowHistoryValidityArray = RequestShadowHistoryValidityBuffer(hdCamera); temporalFilterResult = temporalFilter.DenoiseBuffer(renderGraph, hdCamera, - depthBuffer, normalBuffer, motionVetorsBuffer, - noisyBuffer, shadowHistoryArray, - distanceBuffer, shadowHistoryDistanceArray, - velocityBuffer, - shadowHistoryValidityArray, - lightData.screenSpaceShadowIndex / 4, m_ShadowChannelMask0, m_ShadowChannelMask0, - additionalLightData.distanceBasedFiltering, true, historyValidity); + depthBuffer, normalBuffer, motionVetorsBuffer, + noisyBuffer, shadowHistoryArray, + distanceBuffer, shadowHistoryDistanceArray, + velocityBuffer, + shadowHistoryValidityArray, + lightData.screenSpaceShadowIndex / 4, m_ShadowChannelMask0, m_ShadowChannelMask0, + additionalLightData.distanceBasedFiltering, true, historyValidity); TextureHandle denoisedBuffer; if (additionalLightData.distanceBasedFiltering) { HDDiffuseShadowDenoiser shadowDenoiser = GetDiffuseShadowDenoiser(); denoisedBuffer = shadowDenoiser.DenoiseBufferSphere(renderGraph, hdCamera, - depthBuffer, normalBuffer, - temporalFilterResult.outputSignal, temporalFilterResult.outputSignalDistance, - additionalLightData.filterSizeTraced, additionalLightData.transform.position, additionalLightData.shapeRadius); + depthBuffer, normalBuffer, + temporalFilterResult.outputSignal, temporalFilterResult.outputSignalDistance, + additionalLightData.filterSizeTraced, additionalLightData.transform.position, additionalLightData.shapeRadius); } else { HDSimpleDenoiser simpleDenoiser = GetSimpleDenoiser(); denoisedBuffer = simpleDenoiser.DenoiseBufferNoHistory(renderGraph, hdCamera, - depthBuffer, normalBuffer, - temporalFilterResult.outputSignal, - additionalLightData.filterSizeTraced, true); + depthBuffer, normalBuffer, + temporalFilterResult.outputSignal, + additionalLightData.filterSizeTraced, true); } // Now that we have overriden this history, mark is as used by this light @@ -90,7 +90,7 @@ class RTSPunctualTracePassData } void RenderPunctualScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera - , in LightData lightData, HDAdditionalLightData additionalLightData, int lightIndex, + , in LightData lightData, HDAdditionalLightData additionalLightData, int lightIndex, PrepassOutput prepassOutput, TextureHandle depthBuffer, TextureHandle normalBuffer, TextureHandle motionVectorsBuffer, TextureHandle rayCountTexture, TextureHandle screenSpaceShadowArray) { TextureHandle pointShadowBuffer; @@ -112,26 +112,26 @@ void RenderPunctualScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera // Output Buffers passData.velocityBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8_SNorm, enableRandomWrite = true, name = "Velocity Buffer" }))); + { colorFormat = GraphicsFormat.R8_SNorm, enableRandomWrite = true, name = "Velocity Buffer" }))); passData.distanceBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Distance Buffer" }))); + { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Distance Buffer" }))); passData.outputShadowBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "RT Sphere Shadow" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "RT Sphere Shadow" }))); builder.SetRenderFunc( - (RTSPunctualTracePassData data, RenderGraphContext context) => - { - SSSPunctualRayTraceResources resources = new SSSPunctualRayTraceResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.directionBuffer = data.directionBuffer; - resources.rayLengthBuffer = data.rayLengthBuffer; - resources.rayCountTexture = data.rayCountTexture; - resources.velocityBuffer = data.velocityBuffer; - resources.distanceBuffer = data.distanceBuffer; - resources.outputShadowBuffer = data.outputShadowBuffer; - ExecuteSSSPunctualRayTrace(context.cmd, data.parameters, resources); - }); + (RTSPunctualTracePassData data, RenderGraphContext context) => + { + SSSPunctualRayTraceResources resources = new SSSPunctualRayTraceResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.directionBuffer = data.directionBuffer; + resources.rayLengthBuffer = data.rayLengthBuffer; + resources.rayCountTexture = data.rayCountTexture; + resources.velocityBuffer = data.velocityBuffer; + resources.distanceBuffer = data.distanceBuffer; + resources.outputShadowBuffer = data.outputShadowBuffer; + ExecuteSSSPunctualRayTrace(context.cmd, data.parameters, resources); + }); pointShadowBuffer = passData.outputShadowBuffer; velocityBuffer = passData.velocityBuffer; distanceBuffer = passData.distanceBuffer; @@ -141,9 +141,9 @@ void RenderPunctualScreenSpaceShadow(RenderGraph renderGraph, HDCamera hdCamera if (additionalLightData.filterTracedShadow && rtsptParams.softShadow) { pointShadowBuffer = DenoisePunctualScreenSpaceShadow(renderGraph, hdCamera, - additionalLightData, lightData, - depthBuffer, normalBuffer, motionVectorsBuffer, - pointShadowBuffer, velocityBuffer, distanceBuffer); + additionalLightData, lightData, + depthBuffer, normalBuffer, motionVectorsBuffer, + pointShadowBuffer, velocityBuffer, distanceBuffer); } // Write the result texture to the screen space shadow buffer diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.cs index ab45b5d3208..7f18f729b0a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadowManagerPunctual.cs @@ -210,8 +210,8 @@ static float EvaluateHistoryValidityPointShadow(HDCamera hdCamera, LightData lig } void DenoisePunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera, - HDAdditionalLightData additionalLightData, in LightData lightData, - RTHandle velocityBuffer, RTHandle distanceBufferI, RTHandle shadowBuffer) + HDAdditionalLightData additionalLightData, in LightData lightData, + RTHandle velocityBuffer, RTHandle distanceBufferI, RTHandle shadowBuffer) { // Request the additional temporary buffers we shall be using RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); @@ -232,7 +232,7 @@ void DenoisePunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera, { distanceBuffer = distanceBufferI; shadowHistoryDistanceArray = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedShadowDistanceValidity) - ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedShadowDistanceValidity, ShadowHistoryDistanceBufferAllocatorFunction, 1); ; + ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedShadowDistanceValidity, ShadowHistoryDistanceBufferAllocatorFunction, 1);; denoisedDistanceBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.RG1); } @@ -244,12 +244,12 @@ void DenoisePunctualScreenSpaceShadow(CommandBuffer cmd, HDCamera hdCamera, // Apply the temporal denoiser temporalFilter.DenoiseBuffer(cmd, hdCamera, shadowBuffer, shadowHistoryArray, - shadowHistoryValidityArray, - velocityBuffer, - intermediateBuffer1, - lightData.screenSpaceShadowIndex / 4, m_ShadowChannelMask0, - distanceBuffer, shadowHistoryDistanceArray, denoisedDistanceBuffer, m_ShadowChannelMask0, - additionalLightData.distanceBasedFiltering, singleChannel: true, historyValidity: historyValidity); + shadowHistoryValidityArray, + velocityBuffer, + intermediateBuffer1, + lightData.screenSpaceShadowIndex / 4, m_ShadowChannelMask0, + distanceBuffer, shadowHistoryDistanceArray, denoisedDistanceBuffer, m_ShadowChannelMask0, + additionalLightData.distanceBasedFiltering, singleChannel: true, historyValidity: historyValidity); if (additionalLightData.distanceBasedFiltering) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader index 29659aae29a..3bddbad325a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader @@ -37,7 +37,7 @@ Shader "Hidden/ScriptableRenderPipeline/ShadowBlit" TEXTURE2D(_CachedShadowmapAtlas); float4 _BlitScaleBias; - + Varyings Vert(Attributes input) { Varyings output; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowMoments.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowMoments.hlsl index bce8d31f69c..9254c4c3749 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowMoments.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowMoments.hlsl @@ -40,7 +40,7 @@ float ShadowMoments_WarpDepth_PosOnly(float depth, float exponent) } // This uses exp2 instead of exp (as it has a native hw instruction), as such, the exponent -// expects a log2(e) factor baked in. +// expects a log2(e) factor baked in. float ShadowMoments_WarpDepth_PosOnlyBaseTwo(float depth, float exponent) { // Rescale depth into [-1;1] diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/SphericalHarmonics.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/SphericalHarmonics.cs index bcd796eb711..1f42899007c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/SphericalHarmonics.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/SphericalHarmonics.cs @@ -45,42 +45,42 @@ internal struct SphericalHarmonicsL1 }; // These operators are implemented so that SphericalHarmonicsL1 matches API of SphericalHarmonicsL2. - public static SphericalHarmonicsL1 operator +(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) => new SphericalHarmonicsL1() + public static SphericalHarmonicsL1 operator+(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) => new SphericalHarmonicsL1() { shAr = lhs.shAr + rhs.shAr, shAg = lhs.shAg + rhs.shAg, shAb = lhs.shAb + rhs.shAb }; - public static SphericalHarmonicsL1 operator -(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) => new SphericalHarmonicsL1() + public static SphericalHarmonicsL1 operator-(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) => new SphericalHarmonicsL1() { shAr = lhs.shAr - rhs.shAr, shAg = lhs.shAg - rhs.shAg, shAb = lhs.shAb - rhs.shAb }; - public static SphericalHarmonicsL1 operator *(SphericalHarmonicsL1 lhs, float rhs) => new SphericalHarmonicsL1() + public static SphericalHarmonicsL1 operator*(SphericalHarmonicsL1 lhs, float rhs) => new SphericalHarmonicsL1() { shAr = lhs.shAr * rhs, shAg = lhs.shAg * rhs, shAb = lhs.shAb * rhs }; - public static SphericalHarmonicsL1 operator /(SphericalHarmonicsL1 lhs, float rhs) => new SphericalHarmonicsL1() + public static SphericalHarmonicsL1 operator/(SphericalHarmonicsL1 lhs, float rhs) => new SphericalHarmonicsL1() { shAr = lhs.shAr / rhs, shAg = lhs.shAg / rhs, shAb = lhs.shAb / rhs }; - public static bool operator ==(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) + public static bool operator==(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) { return lhs.shAr == rhs.shAr && lhs.shAg == rhs.shAg && lhs.shAb == rhs.shAb; } - public static bool operator !=(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) + public static bool operator!=(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) { return !(lhs == rhs); } @@ -88,7 +88,7 @@ internal struct SphericalHarmonicsL1 public override bool Equals(object other) { if (!(other is SphericalHarmonicsL1)) return false; - return this == (SphericalHarmonicsL1) other; + return this == (SphericalHarmonicsL1)other; } public override int GetHashCode() @@ -137,7 +137,6 @@ public static SphericalHarmonicsL2 Convolve(SphericalHarmonicsL2 sh, ZonalHarmon // to obtain the canonical values of SH. public static SphericalHarmonicsL2 UndoCosineRescaling(SphericalHarmonicsL2 sh) { - for (int c = 0; c < 3; c++) { for (int i = 0; i < 9; i++) @@ -149,7 +148,6 @@ public static SphericalHarmonicsL2 UndoCosineRescaling(SphericalHarmonicsL2 sh) return sh; } - const float k0 = 0.28209479177387814347f; // {0, 0} : 1/2 * sqrt(1/Pi) const float k1 = 0.48860251190291992159f; // {1, 0} : 1/2 * sqrt(3/Pi) const float k2 = 1.09254843059207907054f; // {2,-2} : 1/2 * sqrt(15/Pi) @@ -165,7 +163,6 @@ public static SphericalHarmonicsL2 UndoCosineRescaling(SphericalHarmonicsL2 sh) // (c_0 - c_6) + c_1 y + c_2 z + c_3 x + c_4 x y + c_5 y z + c_6 (3 z^2) + c_7 x z + c_8 (x^2 - y^2) public static SphericalHarmonicsL2 PremultiplyCoefficients(SphericalHarmonicsL2 sh) { - for (int c = 0; c < 3; c++) { for (int i = 0; i < 9; i++) @@ -195,7 +192,6 @@ public static SphericalHarmonicsL2 RescaleCoefficients(SphericalHarmonicsL2 sh, // See SetSHEMapConstants() in "Stupid Spherical Harmonics Tricks". public static void PackCoefficients(Vector4[] packedCoeffs, SphericalHarmonicsL2 sh) { - // Constant + linear for (int c = 0; c < 3; c++) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/SurfaceShading.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Lighting/SurfaceShading.hlsl index bd1e63138f7..1619f52dbf2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/SurfaceShading.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/SurfaceShading.hlsl @@ -199,5 +199,3 @@ DirectLighting ShadeSurface_Punctual(LightLoopContext lightLoopContext, return lighting; } - - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs index 2e9c0a6f86c..40b75c46ee9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DensityVolume.cs @@ -227,6 +227,7 @@ void UpdateDecalVisibility() DensityVolumeManager.manager.RegisterVolume(this); } } + #endif private void OnDisable() diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/Texture3DAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/Texture3DAtlas.cs index 0af5f1f6575..5d764c93b7e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/Texture3DAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/Texture3DAtlas.cs @@ -87,7 +87,7 @@ public void GenerateAtlas(CommandBuffer cmd) int textureSliceSize = m_atlasSize * m_atlasSize * m_atlasSize; int totalTextureSize = textureSliceSize * m_textures.Count; - Color [] colorData = new Color[totalTextureSize]; + Color[] colorData = new Color[totalTextureSize]; m_atlas = new Texture3D(m_atlasSize, m_atlasSize, m_atlasSize * m_textures.Count, m_format, true); //Iterate through all the textures and append their texture data to the texture array @@ -95,7 +95,7 @@ public void GenerateAtlas(CommandBuffer cmd) for (int i = 0; i < m_textures.Count; i++) { Texture3D tex = m_textures[i]; - Color [] texData = tex.GetPixels(); + Color[] texData = tex.GetPixels(); Array.Copy(texData, 0, colorData, textureSliceSize * i, texData.Length); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute index bf12c76f3c8..fcdd492cf4e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute @@ -5,7 +5,7 @@ // #pragma enable_d3d11_debug_symbols #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -#pragma kernel VolumeVoxelizationBruteforceOptimal VolumeVoxelization=VolumeVoxelizationBruteforceOptimal VL_PRESET_OPTIMAL +#pragma kernel VolumeVoxelizationBruteforceOptimal VolumeVoxelization=VolumeVoxelizationBruteforceOptimal VL_PRESET_OPTIMAL #pragma kernel VolumeVoxelizationTiledOptimal VolumeVoxelization=VolumeVoxelizationTiledOptimal COARSE_BINNING VL_PRESET_OPTIMAL #pragma kernel VolumeVoxelizationBruteforce VolumeVoxelization=VolumeVoxelizationBruteforce #pragma kernel VolumeVoxelizationTiled VolumeVoxelization=VolumeVoxelizationTiled COARSE_BINNING @@ -106,7 +106,7 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay float t0 = DecodeLogarithmicDepthGeneralized(0, _VBufferDistanceDecodingParams); float de = _VBufferRcpSliceCount; // Log-encoded distance between slices - float z0 = t0 * cosRay; // Distance to linear depth + float z0 = t0 * cosRay; // Distance to linear depth uint zBin0 = ComputeZBinIndex(z0); for (uint slice = 0; slice < _VBufferSliceCount; slice++) @@ -118,8 +118,8 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay float dt = t1 - t0; float t = t0 + 0.5 * dt; - float z1 = t1 * cosRay; // Distance to linear depth - uint zBin1 = ComputeZBinIndex(z1); + float z1 = t1 * cosRay; // Distance to linear depth + uint zBin1 = ComputeZBinIndex(z1); float3 voxelCenterWS = ray.originWS + t * ray.centerDirWS; @@ -250,7 +250,7 @@ void FillVolumetricDensityBuffer(PositionInputs posInput, uint tile, JitteredRay _VBufferDensity[voxelCoord] = float4(voxelScattering, voxelExtinction); - t0 = t1; + t0 = t1; zBin0 = zBin1; } } @@ -273,10 +273,10 @@ void VolumeVoxelization(uint3 dispatchThreadId : SV_DispatchThreadID, #ifdef VL_PRESET_OPTIMAL // The entire thread group is within the same light tile. uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE; - uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); + uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); #else // No compile-time optimizations, no scalarization. - uint tile = ComputeTileIndex(pixelCoord); + uint tile = ComputeTileIndex(pixelCoord); #endif // Reminder: our voxels are sphere-capped right frustums (truncated right pyramids). diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute index 70e9bbc94f2..afcc860bd6f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute @@ -31,7 +31,7 @@ #define USE_DEPTH_BUFFER 1 // Accounts for opaque geometry along the camera ray // Filter out lights that are not meant to be affecting volumetric once per thread rather than per voxel. This has the downside that it limits the max processable lights to MAX_SUPPORTED_LIGHTS -// which might be lower than the max number of lights that might be in the big tile. +// which might be lower than the max number of lights that might be in the big tile. #define PRE_FILTER_LIGHT_LIST 1 && defined(USE_BIG_TILE_LIGHTLIST) //-------------------------------------------------------------------------------------------------- @@ -77,7 +77,7 @@ TEXTURE2D_X(_MaxZMaskTexture); #if PRE_FILTER_LIGHT_LIST -#define MAX_SUPPORTED_LIGHTS min(48, MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE) +#define MAX_SUPPORTED_LIGHTS min(48, MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE) groupshared int gs_localLightList[GROUP_SIZE_1D*GROUP_SIZE_1D][MAX_SUPPORTED_LIGHTS]; #endif @@ -253,7 +253,7 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF if (featureFlags & LIGHTFEATUREFLAGS_PUNCTUAL) { - uint i = 0; + uint i = 0; LightData light; while (TryLoadPunctualLightData(i, tile, zBinRange, light)) @@ -262,93 +262,93 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF light.contactShadowMask = 0; light.shadowDimmer = light.volumetricShadowDimmer; - float weight = 0; // Monte Carlo weight + float weight = 0; // Monte Carlo weight if (light.lightType == GPULIGHTTYPE_PROJECTOR_BOX) { - bool sampleLight = (light.volumetricLightDimmer > 0); + bool sampleLight = (light.volumetricLightDimmer > 0); - // Convert the box light from OBB to AABB. - // 'light.right' and 'light.up' vectors are pre-scaled on the CPU by (2/w) and (2/h). - float3x3 rotMat = float3x3(light.right, light.up, light.forward); + // Convert the box light from OBB to AABB. + // 'light.right' and 'light.up' vectors are pre-scaled on the CPU by (2/w) and (2/h). + float3x3 rotMat = float3x3(light.right, light.up, light.forward); - float3 o = mul(rotMat, ray.originWS - light.positionRWS); - float3 d = mul(rotMat, ray.jitterDirWS); + float3 o = mul(rotMat, ray.originWS - light.positionRWS); + float3 d = mul(rotMat, ray.jitterDirWS); - float3 boxPt0 = float3(-1, -1, 0); - float3 boxPt1 = float3( 1, 1, light.range); + float3 boxPt0 = float3(-1, -1, 0); + float3 boxPt1 = float3( 1, 1, light.range); - float tEntr, tExit; - sampleLight = sampleLight && IntersectRayAABB(o, d, boxPt0, boxPt1, t0, t1, tEntr, tExit); + float tEntr, tExit; + sampleLight = sampleLight && IntersectRayAABB(o, d, boxPt0, boxPt1, t0, t1, tEntr, tExit); - // Is it worth evaluating the light? - if (sampleLight) - { - float tOffset; - ImportanceSampleHomogeneousMedium(rndVal, extinction, tExit - tEntr, tOffset, weight); + // Is it worth evaluating the light? + if (sampleLight) + { + float tOffset; + ImportanceSampleHomogeneousMedium(rndVal, extinction, tExit - tEntr, tOffset, weight); - // Compute transmittance from 't0' to 'tEntr'. - weight *= TransmittanceHomogeneousMedium(extinction, tEntr - t0); + // Compute transmittance from 't0' to 'tEntr'. + weight *= TransmittanceHomogeneousMedium(extinction, tEntr - t0); - float t = tEntr + tOffset; - posInput.positionWS = ray.originWS + t * ray.jitterDirWS; - } + float t = tEntr + tOffset; + posInput.positionWS = ray.originWS + t * ray.jitterDirWS; + } } else // (light.lightType != GPULIGHTTYPE_PROJECTOR_BOX) { - bool sampleLight = (light.volumetricLightDimmer > 0); - - float tEntr = t0; - float tExit = t1; - - // Perform ray-cone intersection for pyramid and spot lights. - if (light.lightType != GPULIGHTTYPE_POINT) - { - float lenMul = 1; - - if (light.lightType == GPULIGHTTYPE_PROJECTOR_PYRAMID) - { - // 'light.right' and 'light.up' vectors are pre-scaled on the CPU - // s.t. if you were to place them at the distance of 1 directly in front - // of the light, they would give you the "footprint" of the light. - // For spot lights, the cone fit is exact. - // For pyramid lights, however, this is the "inscribed" cone - // (contained within the pyramid), and we want to intersect - // the "escribed" cone (which contains the pyramid). - // Therefore, we have to scale the radii by the sqrt(2). - lenMul = rsqrt(2); - } - - float3 coneAxisX = lenMul * light.right; - float3 coneAxisY = lenMul * light.up; - - sampleLight = sampleLight && IntersectRayCone(ray.originWS, ray.jitterDirWS, - light.positionRWS, light.forward, - coneAxisX, coneAxisY, - t0, t1, tEntr, tExit); - } - - // Is it worth evaluating the light? - if (sampleLight) - { - float lightSqRadius = light.size.x; - - float t, distSq, rcpPdf; - ImportanceSamplePunctualLight(rndVal, light.positionRWS, lightSqRadius, - ray.originWS, ray.jitterDirWS, - tEntr, tExit, - t, distSq, rcpPdf); - - // Compute transmittance from 't0' to 't'. - weight = TransmittanceHomogeneousMedium(extinction, t - t0) * rcpPdf; - - posInput.positionWS = ray.originWS + t * ray.jitterDirWS; - } + bool sampleLight = (light.volumetricLightDimmer > 0); + + float tEntr = t0; + float tExit = t1; + + // Perform ray-cone intersection for pyramid and spot lights. + if (light.lightType != GPULIGHTTYPE_POINT) + { + float lenMul = 1; + + if (light.lightType == GPULIGHTTYPE_PROJECTOR_PYRAMID) + { + // 'light.right' and 'light.up' vectors are pre-scaled on the CPU + // s.t. if you were to place them at the distance of 1 directly in front + // of the light, they would give you the "footprint" of the light. + // For spot lights, the cone fit is exact. + // For pyramid lights, however, this is the "inscribed" cone + // (contained within the pyramid), and we want to intersect + // the "escribed" cone (which contains the pyramid). + // Therefore, we have to scale the radii by the sqrt(2). + lenMul = rsqrt(2); + } + + float3 coneAxisX = lenMul * light.right; + float3 coneAxisY = lenMul * light.up; + + sampleLight = sampleLight && IntersectRayCone(ray.originWS, ray.jitterDirWS, + light.positionRWS, light.forward, + coneAxisX, coneAxisY, + t0, t1, tEntr, tExit); + } + + // Is it worth evaluating the light? + if (sampleLight) + { + float lightSqRadius = light.size.x; + + float t, distSq, rcpPdf; + ImportanceSamplePunctualLight(rndVal, light.positionRWS, lightSqRadius, + ray.originWS, ray.jitterDirWS, + tEntr, tExit, + t, distSq, rcpPdf); + + // Compute transmittance from 't0' to 't'. + weight = TransmittanceHomogeneousMedium(extinction, t - t0) * rcpPdf; + + posInput.positionWS = ray.originWS + t * ray.jitterDirWS; + } } if (weight > 0) { - float3 L; + float3 L; float4 distances; // {d, d^2, 1/d, d_proj} GetPunctualLightVectors(posInput.positionWS, light, L, distances); @@ -389,7 +389,7 @@ VoxelLighting EvaluateVoxelLightingLocal(LightLoopContext context, uint featureF lighting.radianceComplete += (weight * lightColor.rgb) * phase; } - i++; + i++; } } @@ -403,7 +403,7 @@ void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, float t0 = DecodeLogarithmicDepthGeneralized(0, _VBufferDistanceDecodingParams); float de = _VBufferRcpSliceCount; // Log-encoded distance between slices - float z0 = t0 * cosRay; // Distance to linear depth + float z0 = t0 * cosRay; // Distance to linear depth uint zBin0 = ComputeZBinIndex(z0); // The contribution of the ambient probe does not depend on the position, @@ -437,8 +437,8 @@ void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, } #endif - float z1 = t1 * cosRay; // Distance to linear depth - uint zBin1 = ComputeZBinIndex(z1); + float z1 = t1 * cosRay; // Distance to linear depth + uint zBin1 = ComputeZBinIndex(z1); float dt = t1 - t0; // Is geometry-aware @@ -597,7 +597,7 @@ void FillVolumetricLightingBuffer(LightLoopContext context, uint featureFlags, // Compute the optical depth up to the end of the interval. opticalDepth += 0.5 * blendValue.a; - t0 = tNext; + t0 = tNext; zBin0 = zBin1; // TODO: maybe not a good idea with the "stop ray at geometry" feature active if (t0 * 0.99 > ray.maxDist) @@ -679,10 +679,10 @@ void VolumetricLighting(uint3 dispatchThreadId : SV_DispatchThreadID, #ifdef VL_PRESET_OPTIMAL // The entire thread group is within the same light tile. uint2 tileCoord = groupOffset * VBUFFER_VOXEL_SIZE / TILE_SIZE; - uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); + uint tile = IndexFromCoordinate(tileCoord, TILE_BUFFER_DIMS.x); #else // No compile-time optimizations, no scalarization. - uint tile = ComputeTileIndex(pixelCoord); + uint tile = ComputeTileIndex(pixelCoord); #endif // Do not jitter 'voxelCoord' else. It's expected to correspond to the center of the voxel. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs index 134a0b1cacd..d1dd59b71d1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.cs @@ -131,15 +131,15 @@ public VBufferParameters(Vector3Int viewportSize, float depthExtent, float camNe internal Vector3 ComputeViewportScale(Vector3Int bufferSize) { return new Vector3(HDUtils.ComputeViewportScale(viewportSize.x, bufferSize.x), - HDUtils.ComputeViewportScale(viewportSize.y, bufferSize.y), - HDUtils.ComputeViewportScale(viewportSize.z, bufferSize.z)); + HDUtils.ComputeViewportScale(viewportSize.y, bufferSize.y), + HDUtils.ComputeViewportScale(viewportSize.z, bufferSize.z)); } internal Vector3 ComputeViewportLimit(Vector3Int bufferSize) { return new Vector3(HDUtils.ComputeViewportLimit(viewportSize.x, bufferSize.x), - HDUtils.ComputeViewportLimit(viewportSize.y, bufferSize.y), - HDUtils.ComputeViewportLimit(viewportSize.z, bufferSize.z)); + HDUtils.ComputeViewportLimit(viewportSize.y, bufferSize.y), + HDUtils.ComputeViewportLimit(viewportSize.z, bufferSize.z)); } internal float ComputeLastSliceDistance(uint sliceCount) @@ -285,11 +285,11 @@ static internal VBufferParameters ComputeVolumetricBufferParameters(HDCamera hdC Vector3Int viewportSize = ComputeVolumetricViewportSize(hdCamera, ref voxelSize); return new VBufferParameters(viewportSize, controller.depthExtent.value, - hdCamera.camera.nearClipPlane, - hdCamera.camera.farClipPlane, - hdCamera.camera.fieldOfView, - controller.sliceDistributionUniformity.value, - voxelSize); + hdCamera.camera.nearClipPlane, + hdCamera.camera.farClipPlane, + hdCamera.camera.fieldOfView, + controller.sliceDistributionUniformity.value, + voxelSize); } static internal void ReinitializeVolumetricBufferParams(HDCamera hdCamera) @@ -364,9 +364,10 @@ static internal void ResizeVolumetricBuffer(ref RTHandle rt, string name, int vi depth = Math.Max(depth, viewportDepth); rt = RTHandles.Alloc(width, height, depth, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, // 8888_sRGB is not precise enough - dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: name); + dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: name); } } + struct GenerateMaxZParameters { public ComputeShader generateMaxZCS; @@ -405,7 +406,7 @@ GenerateMaxZParameters PrepareGenerateMaxZParameters(HDCamera hdCamera, HDUtils. float ratio = (float)currentParams.viewportSize.x / (float)hdCamera.actualWidth; parameters.dilationWidth = ratio < 0.1f ? 2 : - ratio < 0.5f ? 1 : 0; + ratio < 0.5f ? 1 : 0; parameters.viewCount = hdCamera.viewCount; @@ -445,7 +446,7 @@ static void GenerateMaxZ(in GenerateMaxZParameters parameters, RTHandle depthTex maskH, parameters.minDepthMipOffset.x, parameters.minDepthMipOffset.y - ); + ); cmd.SetComputeVectorParam(cs, HDShaderIDs._SrcOffsetAndLimit, srcLimitAndDepthOffset); cmd.SetComputeFloatParam(cs, HDShaderIDs._DilationWidth, parameters.dilationWidth); @@ -470,7 +471,6 @@ static void GenerateMaxZ(in GenerateMaxZParameters parameters, RTHandle depthTex cmd.SetComputeVectorParam(cs, HDShaderIDs._SrcOffsetAndLimit, srcLimitAndDepthOffset); cmd.DispatchCompute(cs, kernel, dispatchX, dispatchY, parameters.viewCount); - } internal void GenerateMaxZ(CommandBuffer cmd, HDCamera camera, RTHandle depthTexture, HDUtils.PackedMipChainInfo depthMipInfo, int frameIndex) @@ -496,7 +496,7 @@ static internal void CreateVolumetricHistoryBuffers(HDCamera hdCamera, int buffe for (int i = 0; i < bufferCount; i++) { hdCamera.volumetricHistoryBuffers[i] = RTHandles.Alloc(minSize, minSize, minSize, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, // 8888_sRGB is not precise enough - dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: string.Format("VBufferHistory{0}", i)); + dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: string.Format("VBufferHistory{0}", i)); } hdCamera.volumetricHistoryIsValid = false; @@ -519,7 +519,7 @@ static internal void DestroyVolumetricHistoryBuffers(HDCamera hdCamera) } // Must be called AFTER UpdateVolumetricBufferParams. - static readonly string[] volumetricHistoryBufferNames = new string[2]{ "VBufferHistory0", "VBufferHistory1" }; + static readonly string[] volumetricHistoryBufferNames = new string[2] { "VBufferHistory0", "VBufferHistory1" }; static internal void ResizeVolumetricHistoryBuffers(HDCamera hdCamera, int frameIndex) { if (!hdCamera.IsVolumetricReprojectionEnabled()) @@ -546,8 +546,8 @@ static internal void ResizeVolumetricHistoryBuffers(HDCamera hdCamera, int frame // We only resize the feedback buffer (#0), not the history buffer (#1). // We must NOT resize the buffer from the previous frame (#1), as that would invalidate its contents. ResizeVolumetricBuffer(ref hdCamera.volumetricHistoryBuffers[currIdx], volumetricHistoryBufferNames[currIdx], currentParams.viewportSize.x, - currentParams.viewportSize.y, - currentParams.viewportSize.z); + currentParams.viewportSize.y, + currentParams.viewportSize.z); } internal void CreateVolumetricLightingBuffers() @@ -563,21 +563,20 @@ internal void CreateVolumetricLightingBuffers() const int minSize = 4; m_DensityBuffer = RTHandles.Alloc(minSize, minSize, minSize, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, // 8888_sRGB is not precise enough - dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: "VBufferDensity"); + dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: "VBufferDensity"); m_LightingBuffer = RTHandles.Alloc(minSize, minSize, minSize, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, // 8888_sRGB is not precise enough - dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: "VBufferLighting"); + dimension: TextureDimension.Tex3D, enableRandomWrite: true, name: "VBufferLighting"); - m_MaxZMask8x = RTHandles.Alloc(Vector2.one * 0.125f, TextureXR.slices, dimension: TextureXR.dimension, colorFormat: GraphicsFormat.R32_SFloat, - enableRandomWrite: true, name: "MaxZ mask 8x"); + m_MaxZMask8x = RTHandles.Alloc(Vector2.one * 0.125f, TextureXR.slices, dimension: TextureXR.dimension, colorFormat: GraphicsFormat.R32_SFloat, + enableRandomWrite: true, name: "MaxZ mask 8x"); - m_MaxZMask = RTHandles.Alloc(Vector2.one / 16.0f, TextureXR.slices, dimension: TextureXR.dimension, colorFormat: GraphicsFormat.R32_SFloat, - enableRandomWrite: true, name: "MaxZ mask"); + m_MaxZMask = RTHandles.Alloc(Vector2.one / 16.0f, TextureXR.slices, dimension: TextureXR.dimension, colorFormat: GraphicsFormat.R32_SFloat, + enableRandomWrite: true, name: "MaxZ mask"); m_DilatedMaxZMask = RTHandles.Alloc(Vector2.one / 16.0f, TextureXR.slices, dimension: TextureXR.dimension, colorFormat: GraphicsFormat.R32_SFloat, - enableRandomWrite: true, name: "Dilated MaxZ mask"); - + enableRandomWrite: true, name: "Dilated MaxZ mask"); } internal void DestroyVolumetricLightingBuffers() @@ -614,11 +613,11 @@ internal void ResizeVolumetricLightingBuffers(HDCamera hdCamera, int frameIndex) var currentParams = hdCamera.vBufferParams[currIdx]; ResizeVolumetricBuffer(ref m_DensityBuffer, "VBufferDensity", currentParams.viewportSize.x, - currentParams.viewportSize.y, - currentParams.viewportSize.z); + currentParams.viewportSize.y, + currentParams.viewportSize.z); ResizeVolumetricBuffer(ref m_LightingBuffer, "VBufferLighting", currentParams.viewportSize.x, - currentParams.viewportSize.y, - currentParams.viewportSize.z); + currentParams.viewportSize.y, + currentParams.viewportSize.z); // TODO RENDERGRAPH: For now those texture are not handled by render graph. // When they are we won't have the m_DensityBuffer handy for getting the current size in UpdateShaderVariablesGlobalVolumetrics @@ -878,10 +877,10 @@ VolumeVoxelizationParameters PrepareVolumeVoxelizationParameters(HDCamera hdCame return parameters; } - static void VolumeVoxelizationPass( in VolumeVoxelizationParameters parameters, - RTHandle densityBuffer, - ComputeBuffer bigTileLightList, - CommandBuffer cmd) + static void VolumeVoxelizationPass(in VolumeVoxelizationParameters parameters, + RTHandle densityBuffer, + ComputeBuffer bigTileLightList, + CommandBuffer cmd) { if (parameters.tiledLighting) cmd.SetComputeBufferParam(parameters.voxelizationCS, parameters.voxelizationKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList); @@ -914,7 +913,6 @@ void VolumeVoxelizationPass(HDCamera hdCamera, CommandBuffer cmd, int frameIndex // https://www.desmos.com/calculator/kcpfvltz7c static void GetHexagonalClosePackedSpheres7(Vector2[] coords) { - float r = 0.17054068870105443882f; float d = 2 * r; float s = r * Mathf.Sqrt(3); @@ -1007,15 +1005,15 @@ VolumetricLightingParameters PrepareVolumetricLightingParameters(HDCamera hdCame return parameters; } - static void VolumetricLightingPass( in VolumetricLightingParameters parameters, - RTHandle depthTexture, - RTHandle densityBuffer, - RTHandle lightingBuffer, - RTHandle maxZTexture, - RTHandle historyRT, - RTHandle feedbackRT, - ComputeBuffer bigTileLightList, - CommandBuffer cmd) + static void VolumetricLightingPass(in VolumetricLightingParameters parameters, + RTHandle depthTexture, + RTHandle densityBuffer, + RTHandle lightingBuffer, + RTHandle maxZTexture, + RTHandle historyRT, + RTHandle feedbackRT, + ComputeBuffer bigTileLightList, + CommandBuffer cmd) { if (parameters.tiledLighting) cmd.SetComputeBufferParam(parameters.volumetricLightingCS, parameters.volumetricLightingKernel, HDShaderIDs.g_vBigTileLightList, bigTileLightList); @@ -1048,8 +1046,8 @@ static void FilterVolumetricLighting(in VolumetricLightingParameters parameters, // The shader defines GROUP_SIZE_1D_XY = 8 and GROUP_SIZE_1D_Z = 1 cmd.SetComputeTextureParam(parameters.volumetricLightingFilteringCS, parameters.volumetricFilteringKernel, HDShaderIDs._VBufferLighting, lightingBuffer); cmd.DispatchCompute(parameters.volumetricLightingFilteringCS, parameters.volumetricFilteringKernel, HDUtils.DivRoundUp((int)parameters.resolution.x, 8), - HDUtils.DivRoundUp((int)parameters.resolution.y, 8), - parameters.sliceCount); + HDUtils.DivRoundUp((int)parameters.resolution.y, 8), + parameters.sliceCount); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute index d1a2a66a649..bfeca995c1e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute @@ -28,7 +28,7 @@ RW_TEXTURE3D(float4, _VBufferLighting); #define GROUP_SIZE_1D_XY 8 #define GROUP_SIZE_1D_Z 1 -#define FILTER_SIZE_1D (GROUP_SIZE_1D_XY + 2) // With a 8x8 group, we have a 10x10 working area +#define FILTER_SIZE_1D (GROUP_SIZE_1D_XY + 2) // With a 8x8 group, we have a 10x10 working area #define LDS_SIZE FILTER_SIZE_1D * FILTER_SIZE_1D // TODO: May use 1 uint for 2 pixels diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl index f07497ec0c5..24f7ae012ee 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.hlsl @@ -331,7 +331,7 @@ void GetBSDFDataDebug(uint paramId, BSDFData bsdfData, inout float3 result, inou float3 vsGeomNormal = TransformWorldToViewDir(bsdfData.geomNormalWS); result = IsNormalized(vsGeomNormal) ? vsGeomNormal * 0.5 + 0.5 : float3(1.0, 0.0, 0.0); break; - } + } } } @@ -870,14 +870,14 @@ float3 SamplesFlakes(float2 offsets[NB_FLAKES_RND_SHIFTS], uint sliceIndex, BSD { // We can't use SAMPLE_TEXTURE2D_ARRAY, the compiler can't unroll in that case, and the lightloop is built with unroll // That's why we calculate gradients or LOD earlier. - // TODO: The LOD code path (useFlakesMipLevel == true) is kept for a possible performance/appearance trade-off + // TODO: The LOD code path (useFlakesMipLevel == true) is kept for a possible performance/appearance trade-off // (less VGPR for LOD) and also for (future) raytracing, it is easier to substitute an approximate single LOD value // than a full 2x2 Jacobian. float3 val = 0; bool useFlakesMipLevel = all(bsdfData.flakesDdxZY == (float2)0); // should be known statically! #ifdef _MAPPING_TRIPLANAR - val += bsdfData.flakesTriplanarWeights.x * + val += bsdfData.flakesTriplanarWeights.x * (useFlakesMipLevel ? SAMPLE_TEXTURE2D_ARRAY_LOD(_CarPaint2_BTFFlakeMap, sampler_CarPaint2_BTFFlakeMap, bsdfData.flakesUVZY + offsets[FLAKES_SHIFT_IDX_PLANAR_ZY], @@ -886,7 +886,7 @@ float3 SamplesFlakes(float2 offsets[NB_FLAKES_RND_SHIFTS], uint sliceIndex, BSD bsdfData.flakesUVZY + offsets[FLAKES_SHIFT_IDX_PLANAR_ZY], sliceIndex, bsdfData.flakesDdxZY, bsdfData.flakesDdyZY).xyz ); - val += bsdfData.flakesTriplanarWeights.y * + val += bsdfData.flakesTriplanarWeights.y * (useFlakesMipLevel ? SAMPLE_TEXTURE2D_ARRAY_LOD(_CarPaint2_BTFFlakeMap, sampler_CarPaint2_BTFFlakeMap, bsdfData.flakesUVXZ + offsets[FLAKES_SHIFT_IDX_PLANAR_XZ], @@ -894,7 +894,7 @@ float3 SamplesFlakes(float2 offsets[NB_FLAKES_RND_SHIFTS], uint sliceIndex, BSD : SAMPLE_TEXTURE2D_ARRAY_GRAD(_CarPaint2_BTFFlakeMap, sampler_CarPaint2_BTFFlakeMap, bsdfData.flakesUVXZ + offsets[FLAKES_SHIFT_IDX_PLANAR_XZ], sliceIndex, bsdfData.flakesDdxXZ, bsdfData.flakesDdyXZ).xyz ); - val += bsdfData.flakesTriplanarWeights.z * + val += bsdfData.flakesTriplanarWeights.z * (useFlakesMipLevel ? SAMPLE_TEXTURE2D_ARRAY_LOD(_CarPaint2_BTFFlakeMap, sampler_CarPaint2_BTFFlakeMap, bsdfData.flakesUVXY + offsets[FLAKES_SHIFT_IDX_PLANAR_XY], @@ -904,7 +904,7 @@ float3 SamplesFlakes(float2 offsets[NB_FLAKES_RND_SHIFTS], uint sliceIndex, BSD sliceIndex, bsdfData.flakesDdxXY, bsdfData.flakesDdyXY).xyz ); val *= _CarPaint2_BTFFlakeMapScale; #else - val = _CarPaint2_BTFFlakeMapScale * + val = _CarPaint2_BTFFlakeMapScale * (useFlakesMipLevel ? SAMPLE_TEXTURE2D_ARRAY_LOD(_CarPaint2_BTFFlakeMap, sampler_CarPaint2_BTFFlakeMap, bsdfData.flakesUVZY + offsets[0], sliceIndex, bsdfData.flakesMipLevelZY).xyz @@ -1160,7 +1160,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput preLightData.iblDominantDirectionWS_BottomLobeOnTop = FindAverageBaseLobeDirOnTop(bsdfData, preLightData, reflectedLobeDirUndercoat); // much better // reflectedLobeDirUndercoat is now adjusted to correspond to the refracted-back on top direction returned by FindAverageBaseLobeDirOnTop() - //sanity check: If both normals are equal, then this shouldn't change the output: + //sanity check: If both normals are equal, then this shouldn't change the output: //preLightData.iblDominantDirectionWS_BottomLobeOnTop = reflect(-viewWS_Clearcoat, bsdfData.clearcoatNormalWS); //reflectedLobeDirUndercoat = reflect(-preLightData.viewWS_UnderCoat, bsdfData.normalWS); } @@ -1220,7 +1220,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput preLightData.singleBRDFColor = 1.0; float thetaH = 0; //acos(clamp(NdotH, 0, 1)); float thetaD = acos(clamp(preLightData.NdotV_UnderCoat, 0, 1)); - // The above is the same as + // The above is the same as //float3 lightDir = reflect(-preLightData.viewWS_UnderCoat, bsdfData.normalWS); //float3 H = normalize(preLightData.viewWS_UnderCoat + lightDir); //float NdotH = dot(bsdfData.normalWS, H); @@ -1295,7 +1295,7 @@ PreLightData GetPreLightData(float3 viewWS_Clearcoat, PositionInputs posInput float oneOverLobeCnt = rcp(CARPAINT2_LOBE_COUNT); preLightData.iblPerceptualRoughness = RoughnessToPerceptualRoughness(sumRoughness * oneOverLobeCnt); tempF0 = sumF0 * oneOverLobeCnt; - // todo_BeckmannToGGX + // todo_BeckmannToGGX GetPreIntegratedFGDCookTorranceAndLambert(NdotV_UnderCoat, preLightData.iblPerceptualRoughness, tempF0 * preLightData.singleBRDFColor, specularFGD, diffuseFGD, reflectivity); preLightData.iblPerceptualRoughness = PerceptualRoughnessBeckmannToGGX(preLightData.iblPerceptualRoughness); specularFGD *= GetPreIntegratedFGDCookTorranceSampleMutiplier(); @@ -2523,22 +2523,22 @@ IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext, // and in case of carpaint, one for each lobe. However, if we would like to "correctly" take into account the effect, we would have // to calculate the effect on the bottom layer where directions are different, and then use FindAverageBaseLobeDirOnTop(). // We decide to just apply the effect on top instead. - // (FindAverageBaseLobeDirOnTop is alreayd an approximation ignoring under-horizon or TIR. If we saturated to the critical angle undercoat + // (FindAverageBaseLobeDirOnTop is alreayd an approximation ignoring under-horizon or TIR. If we saturated to the critical angle undercoat // and thus grazing when exiting on top, a tilt back for off-specular effect might in fact have no effect since the lobe could still // be under horizon. On the other hand, if we didn't have to saturate, a little tilt-back toward normal (from GetModifiedEnvSamplingDir) // should have translated into a bigger one on top because of angle range decompression.) envSamplingDirForBottomLayer = GetModifiedEnvSamplingDir(lightData, bsdfData.clearcoatNormalWS, preLightData.iblDominantDirectionWS_BottomLobeOnTop, preLightData.iblPerceptualRoughness, NdotV); - // Note: using _influenceShapeType and projectionShapeType instead of (lightData|proxyData).shapeType allow to make compiler optimization in case the type is know (like for sky) + // Note: using _influenceShapeType and projectionShapeType instead of (lightData|proxyData).shapeType allow to make compiler optimization in case the type is know (like for sky) float intersectionDistance = EvaluateLight_EnvIntersection(positionWS, bsdfData.clearcoatNormalWS, lightData, _influenceShapeType, envSamplingDirForBottomLayer, weight); // ...here the normal is only used for normal fading mode of the influence volume. // Another problem with having even two fetch directions is the reflection hierarchy that only supports one weight. - // (TODO: We could have a vector tracking multiplied weights already applied per lobe that we update and that is + // (TODO: We could have a vector tracking multiplied weights already applied per lobe that we update and that is // passed back by the light loop but otherwise opaque to it, with the single hierarchyWeight tracked alongside. - // That way no "overlighting" would be done and by returning the hierarchyWeight = min(all weights) up to now, + // That way no "overlighting" would be done and by returning the hierarchyWeight = min(all weights) up to now, // we could potentially avoid artifacts in having eg the clearcoat reflection not available from one influence volume - // while the base has full weight reflection. This ends up always preventing a blend for the coat reflection when the + // while the base has full weight reflection. This ends up always preventing a blend for the coat reflection when the // bottom reflection is full. Lit doesn't have this problem too much in practice since only GetModifiedEnvSamplingDir // changes the direction vs the coat.) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFData.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFData.hlsl index f39a564e071..c1549ed4d92 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFData.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFData.hlsl @@ -187,7 +187,7 @@ float4 AxfSampleTexture2D(TEXTURE2D_PARAM(textureName, samplerName), float4 scal bool useLod = lodBiasOrGrad == 1; bool useBias = lodBiasOrGrad == 2; bool useGrad = lodBiasOrGrad == 3; - bool useCachedDdxDdy = false; + bool useCachedDdxDdy = false; #ifdef AXF_REUSE_SCREEN_DDXDDY useCachedDdxDdy = false; #endif @@ -195,19 +195,19 @@ float4 AxfSampleTexture2D(TEXTURE2D_PARAM(textureName, samplerName), float4 scal #ifdef _MAPPING_TRIPLANAR float4 val = 0; - val += uvMapping.triplanarWeights.x + val += uvMapping.triplanarWeights.x * ( useLod ? SAMPLE_TEXTURE2D_LOD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvZY, scaleOffset), lodOrBias.x) : useBias ? SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvZY, scaleOffset), lodOrBias.x) : useGrad ? SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvZY, scaleOffset), triDdx[0], triDdy[0]) : useCachedDdxDdy ? SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvZY, scaleOffset), scaleOffset.xy * uvMapping.ddxZY, scaleOffset.xy * uvMapping.ddyZY) : SAMPLE_TEXTURE2D(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvZY, scaleOffset)) ); - val += uvMapping.triplanarWeights.y + val += uvMapping.triplanarWeights.y * ( useLod ? SAMPLE_TEXTURE2D_LOD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXZ, scaleOffset), lodOrBias.y) : useBias ? SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXZ, scaleOffset), lodOrBias.y) : useGrad ? SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXZ, scaleOffset), triDdx[1], triDdy[1]) : useCachedDdxDdy ? SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXZ, scaleOffset), scaleOffset.xy * uvMapping.ddxXZ, scaleOffset.xy * uvMapping.ddyXZ) : SAMPLE_TEXTURE2D(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXZ, scaleOffset)) ); - val += uvMapping.triplanarWeights.z + val += uvMapping.triplanarWeights.z * ( useLod ? SAMPLE_TEXTURE2D_LOD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXY, scaleOffset), lodOrBias.z) : useBias ? SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXY, scaleOffset), lodOrBias.z) : useGrad ? SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, AXF_TRANSFORM_TEXUV(uvMapping.uvXY, scaleOffset), triDdx[2], triDdy[2]) @@ -235,7 +235,7 @@ float3 AxFSampleTexture2DNormalAsSurfaceGrad(TEXTURE2D_PARAM(textureName, sample bool useLod = lodBiasOrGrad == 1; bool useBias = lodBiasOrGrad == 2; bool useGrad = lodBiasOrGrad == 3; - bool useCachedDdxDdy = false; + bool useCachedDdxDdy = false; #ifdef AXF_REUSE_SCREEN_DDXDDY useCachedDdxDdy = true; #endif @@ -482,7 +482,7 @@ float2 AxFGetRoughnessFromSpecularLobeTexture(float2 specularLobe) // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html // http://simonstechblog.blogspot.com/2011/12/microfacet-brdf.html - // We thus have + // We thus have // roughnessBeckmann = sqrt(2) * rsqrt(exp2(abs(specularLobe.xy)) + 2); // shiniExp = 2 * rcp(max(0.0001,(roughnessBeckmann*roughnessBeckmann))) - 2; @@ -591,7 +591,7 @@ void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs p float perceptualRoughness = RoughnessToPerceptualRoughness(GetScalarRoughness(surfaceData.specularLobe)); - //TODO + //TODO //#if defined(_SPECULAR_OCCLUSION_FROM_BENT_NORMAL_MAP) // Note: we use normalWS as it will always exist and be equal to clearcoatNormalWS if there's no coat // (otherwise we do SO with the base lobe, might be wrong depending on way AO is computed, will be wrong either way with a single non-lobe specific value) @@ -607,8 +607,8 @@ void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs p // Finalize tangent space surfaceData.tangentWS = uvMapping.vertexTangentWS; // TODOTODO: - // This is crappy: anisotropy rotation don't mix triplanar style like scalar values because of what it represents. That's why in HDRP we use - // tangent space tangent vector maps and triplanar sample those as we do normals in the surface gradients framework! + // This is crappy: anisotropy rotation don't mix triplanar style like scalar values because of what it represents. That's why in HDRP we use + // tangent space tangent vector maps and triplanar sample those as we do normals in the surface gradients framework! // Better to rebuild a gradient in the proper space from each rotation, combine those gradients as normals and resolve here. if (HasAnisotropy()) { @@ -666,7 +666,7 @@ void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs p // No back lighting with AxF InitBuiltinData(posInput, alpha, surfaceData.normalWS, surfaceData.normalWS, input.texCoord1, input.texCoord2, builtinData); - + #ifdef _ALPHATEST_ON // Used for sharpening by alpha to mask builtinData.alphaClipTreshold = _AlphaCutoff; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFLTCAreaLight/LtcData.GGX2.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFLTCAreaLight/LtcData.GGX2.cs index ee4c0969e8a..9191236b1bb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFLTCAreaLight/LtcData.GGX2.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxFLTCAreaLight/LtcData.GGX2.cs @@ -9,7 +9,8 @@ partial class LTCAreaLight // • roughness = ( / 63 )^2 // • cosTheta = 1 - ( / 63 )^2 // - public static double[,] s_LtcMatrixData_GGX = new double[k_LtcLUTResolution * k_LtcLUTResolution, k_LtcLUTMatrixDim * k_LtcLUTMatrixDim] { + public static double[,] s_LtcMatrixData_GGX = new double[k_LtcLUTResolution * k_LtcLUTResolution, k_LtcLUTMatrixDim * k_LtcLUTMatrixDim] + { { 249.99972516083, 0, -2.35158682407516E-09, 0, 249.99972516083, 0, 9.40635763724274E-12, 0, 1 }, { 249.99972516083, 0, -6.1932882001426E-09, 0, 249.99972516083, 0, 2.47731800351314E-11, 0, 1 }, { 249.99972516083, 0, -1.84402568106453E-08, 0, 249.99972516083, 0, 7.37611083323486E-11, 0, 1 }, { 220.49964865921, 0, -5.12586846192175E-08, 0, 220.49964865921, 0, 2.32466060290371E-10, 0, 1 }, { 124.030590285527, 0, -4.84301716700758E-08, 0, 124.030590285527, 0, 3.90469573341434E-10, 0, 1 }, { 79.3790316808135, 0, -5.13550351597887E-08, 0, 79.3790316808135, 0, 6.46959708028305E-10, 0, 1 }, { 55.1235929120602, 0, -4.96528441935784E-08, 0, 55.1235929120602, 0, 9.00754859589625E-10, 0, 1 }, { 40.4981603373294, 0, -5.85023023608724E-08, 0, 40.4981603373294, 0, 1.44456691053563E-09, 0, 1 }, { 31.0053811128358, 0, -4.92814208924551E-08, 0, 31.0053811128358, 0, 1.58944735151323E-09, 0, 1 }, { 24.4969875965314, 0, -5.36548203561093E-08, 0, 24.4969875965314, 0, 2.19026197179062E-09, 0, 1 }, { 19.8411972620128, 0, -5.35403051060404E-08, 0, 19.8411972620128, 0, 2.69844124822782E-09, 0, 1 }, { 16.3962591717518, 0, -4.92930039295324E-08, 0, 16.3962591717518, 0, 3.0063567191263E-09, 0, 1 }, { 13.7758684216582, 0, -5.12003824983554E-08, 0, 13.7758684216582, 0, 3.71667185916635E-09, 0, 1 }, { 11.7363174287487, 0, -4.12478507819388E-08, 0, 11.7363174287487, 0, 3.51454798597217E-09, 0, 1 }, { 10.1178181464916, 0, -5.10312181762129E-08, 0, 10.1178181464916, 0, 5.04369790377268E-09, 0, 1 }, { 8.81199517673572, 0, -5.20683220345778E-08, 0, 8.81199517673572, 0, 5.90880055995058E-09, 0, 1 }, { 7.74302105929495, 0, -5.52646155954912E-08, 0, 7.74302105929495, 0, 7.13734538138056E-09, 0, 1 }, { 6.8574249986839, 0, -5.2430241156594E-08, 0, 6.8574249986839, 0, 7.64576224554503E-09, 0, 1 }, { 6.11633555437548, 0, -4.96724877600275E-08, 0, 6.11633555437548, 0, 8.12128231331144E-09, 0, 1 }, { 5.49522486068625, 0, -5.27931845448473E-08, 0, 5.49522486068626, 0, 9.60710178077306E-09, 0, 1 }, { 5.01253186221066, 0, -4.48432561385957E-08, 0, 5.01253186221066, 0, 8.94622864677785E-09, 0, 1 }, { 4.54478340939888, 0, -3.7324833053011E-08, 0, 4.54478340939888, 0, 8.21267587269858E-09, 0, 1 }, { 4.13925586407918, 0, -4.2799673886404E-08, 0, 4.13925586407919, 0, 1.03399440121166E-08, 0, 1 }, { 3.78610359388004, 0, -4.59492519237764E-08, 0, 3.78610359388004, 0, 1.21362901950306E-08, 0, 1 }, { 3.4779130151006, 0, -4.48351305923097E-08, 0, 3.4779130151006, 0, 1.28913892893934E-08, 0, 1 }, { 3.21046137456232, 0, -4.12042777024413E-08, 0, 3.21046137456232, 0, 1.28343788929897E-08, 0, 1 }, { 2.98388474794477, 0, -4.43903154442322E-08, 0, 2.98388474794477, 0, 1.4876685661136E-08, 0, 1 }, { 2.77921482105912, 0, -3.87377627843715E-08, 0, 2.77921482105912, 0, 1.39383837804985E-08, 0, 1 }, { 2.58757430625212, 0, -3.46795153326855E-08, 0, 2.58757430625212, 0, 1.34023263598237E-08, 0, 1 }, { 2.42032542884521, 0, -3.77554589546857E-08, 0, 2.42032542884522, 0, 1.55993316042213E-08, 0, 1 }, { 2.27712916853536, 0, -3.37465231307334E-08, 0, 2.27712916853536, 0, 1.48197667471095E-08, 0, 1 }, { 2.14098188145856, 0, -3.74537571106628E-08, 0, 2.14098188145856, 0, 1.74937291319566E-08, 0, 1 }, { 2.01934552621459, 0, -3.81046066412548E-08, 0, 2.01934552621459, 0, 1.88697804048843E-08, 0, 1 }, { 1.91449371795389, 0, -3.66573289653752E-08, 0, 1.91449371795389, 0, 1.91472704358375E-08, 0, 1 }, { 1.81331445811834, 0, -2.77685481359264E-08, 0, 1.81331445811834, 0, 1.53136969771594E-08, 0, 1 }, { 1.72525193655925, 0, -3.43443950123012E-08, 0, 1.72525193655925, 0, 1.99068868056429E-08, 0, 1 }, { 1.6440674925966, 0, -3.30333649433396E-08, 0, 1.6440674925966, 0, 2.0092462804655E-08, 0, 1 }, { 1.57097191318885, 0, -2.89556532742908E-08, 0, 1.57097191318885, 0, 1.84316810702967E-08, 0, 1 }, { 1.50406410053135, 0, -3.76054021876725E-08, 0, 1.50406410053135, 0, 2.5002526271578E-08, 0, 0.999999999999999 }, { 1.44396733621497, 0, -3.30591007364969E-08, 0, 1.44396733621497, 0, 2.2894631968029E-08, 0, 0.999999999999999 }, { 1.38801010300016, 0, -3.38178907304926E-08, 0, 1.38801010300016, 0, 2.43642972463931E-08, 0, 0.999999999999999 }, { 1.33826618093002, 0, -3.21007233648853E-08, 0, 1.33826618093002, 0, 2.39868001017385E-08, 0, 0.999999999999999 }, { 1.25003209898949, 0, -3.53393174378494E-08, 0, 1.25003209898949, 0, 2.82707279808392E-08, 0, 0.999999999999999 }, { 1.25003209898949, 0, -3.4105499348838E-08, 0, 1.25003209898949, 0, 2.72836988557401E-08, 0, 0.999999999999999 }, { 1.1773249812826, 0, -3.03692379111505E-08, 0, 1.1773249812826, 0, 2.579511892975E-08, 0, 0.999999999999999 }, { 1.1773249812826, 0, -3.27582593940015E-08, 0, 1.1773249812826, 0, 2.78243135198863E-08, 0, 0.999999999999999 }, { 1.09019445871237, 0, -2.96785427238806E-08, 0, 1.09019445871237, 0, 2.7223164167367E-08, 0, 0.999999999999999 }, { 1.09019445871237, 0, -2.93556402478319E-08, 0, 1.09019445871237, 0, 2.69269762043223E-08, 0, 0.999999999999999 }, { 1.09019445871237, 0, -3.34367616099921E-08, 0, 1.09019445871237, 0, 3.06704563968196E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -3.36323999761134E-08, 0, 1, 0, 3.36323999761134E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -2.77374194723734E-08, 0, 1, 0, 2.77374194723734E-08, 0, 0.999999999999999 }, { 0.999999999999998, 0, -4.18260519552404E-08, 0, 1, 0, 4.18260519552404E-08, 0, 0.999999999999998 }, { 1, 0, -2.0792134236558E-08, 0, 1, 0, 2.0792134236558E-08, 0, 1 }, { 0.999999999999999, 0, -3.20445217028009E-08, 0, 1, 0, 3.20445217028009E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -2.52821461543817E-08, 0, 1, 0, 2.52821461543817E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -3.70039501262908E-08, 0, 1, 0, 3.70039501262908E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -3.29134408616482E-08, 0, 1, 0, 3.29134408616482E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -2.87970447487851E-08, 0, 1, 0, 2.87970447487851E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -2.64988049281101E-08, 0, 1, 0, 2.64988049281101E-08, 0, 0.999999999999999 }, { 1, 0, -2.01495424789755E-08, 0, 1, 0, 2.01495424789755E-08, 0, 1 }, { 0.999999999999999, 0, -3.63770311651023E-08, 0, 1, 0, 3.63770311651023E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -3.61919845204283E-08, 0, 1, 0, 3.61919845204283E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -3.43134196612027E-08, 0, 1, 0, 3.43134196612027E-08, 0, 0.999999999999999 }, { 0.999999999999999, 0, -3.18707833457665E-08, 0, 1, 0, 3.18707833457665E-08, 0, 0.999999999999999 }, // Cos(theta) = 1 { 249.936706690368, 0, 5.61152608121829, 0, 250.062752059257, 0, -0.0224461519228493, 0, 0.999748055622475 }, { 249.936706544073, 0, 5.61152933755871, 0, 250.062752059257, 0, -0.022446164948227, 0, 0.999748055037294 }, { 249.936704370534, 0, 5.61157771747294, 0, 250.062752059257, 0, -0.0224463584681217, 0, 0.999748046343125 }, { 220.444059291464, 0, 4.94940890121771, 0, 220.55518528361, 0, -0.0224463677719627, 0, 0.999748045925135 }, { 123.999381006855, 0, 2.78403345210448, 0, 124.061893662422, 0, -0.0224463034594411, 0, 0.99974810847925 }, { 79.3590373329927, 0, 1.78176881393803, 0, 79.3990383288232, 0, -0.0224463398604398, 0, 0.999748047179106 }, { 55.1097653522054, 0, 1.23732438761666, 0, 55.1375694909148, 0, -0.0224463659111945, 0, 0.999748046008733 }, { 40.4879641911111, 0, 0.909034318512554, 0, 40.5084531907256, 0, -0.0224463156704531, 0, 0.999748048265881 }, { 30.9975744670345, 0, 0.695956765534018, 0, 31.0132100012686, 0, -0.0224463462571149, 0, 0.999748106556496 }, { 24.4907744137122, 0, 0.549866048394318, 0, 24.5031193489786, 0, -0.0224462532186934, 0, 0.999748110736392 }, { 19.8362526228787, 0, 0.445361383836487, 0, 19.8462221151567, 0, -0.0224461641338781, 0, 0.999747995409116 }, { 16.3921917915592, 0, 0.368038724874638, 0, 16.4003896166652, 0, -0.0224461490156599, 0, 0.999748115417855 }, { 13.7724373052482, 0, 0.30921954376937, 0, 13.779389838809, 0, -0.0224459825929371, 0, 0.999748063229807 }, { 11.733403689589, 0, 0.263435441029996, 0, 11.7393112769214, 0, -0.0224456941738468, 0, 0.999748076187218 }, { 10.1153153395902, 0, 0.227107172754874, 0, 10.1204329136075, 0, -0.0224449639384079, 0, 0.999748049328003 }, { 8.80973963162431, 0, 0.197795632671606, 0, 8.8141873233667, 0, -0.0224433339051792, 0, 0.999748122552761 }, { 7.74118526987494, 0, 0.173808537085578, 0, 7.74503411158499, 0, -0.0224391883450253, 0, 0.99974818942717 }, { 6.85573032553224, 0, 0.153921081401336, 0, 6.85910290448169, 0, -0.0224256229862892, 0, 0.999748500170819 }, { 6.11474657092118, 0, 0.137274049356678, 0, 6.11779755999053, 0, -0.0223642777214091, 0, 0.999749937269265 }, { 5.49435024789379, 0, 0.123285065594626, 0, 5.49700308232718, 0, -0.0218898754008676, 0, 0.999760446273529 }, { 5.0050194174198, 0, 0.112158097942443, 0, 5.00747755258788, 0, -0.0206910335732738, 0, 0.999785875541753 }, { 4.54367477693257, 0, 0.101998695262028, 0, 4.54590852465353, 0, -0.022417759600123, 0, 0.999748733728541 }, { 4.13823819345704, 0, 0.0928810651507418, 0, 4.14032029951877, 0, -0.022389730333869, 0, 0.999749274621619 }, { 3.78522535391971, 0, 0.0849383729126612, 0, 3.78712981062427, 0, -0.0223231136171198, 0, 0.99975082353695 }, { 3.47725656052158, 0, 0.077993759377565, 0, 3.47889053653563, 0, -0.0221411031282761, 0, 0.999754865369964 }, { 3.20983892775547, 0, 0.0718809479909394, 0, 3.21141995570889, 0, -0.0215944436926462, 0, 0.999766798982804 }, { 2.98369684332256, 0, 0.0665057644524883, 0, 2.98514342350851, 0, -0.0201261367555525, 0, 0.999797374510434 }, { 2.77858252341236, 0, 0.0622449131695045, 0, 2.77988518324872, 0, -0.0220404495653679, 0, 0.999757048469761 }, { 2.58706944467462, 0, 0.0578343454486483, 0, 2.58833144859269, 0, -0.0216201864485913, 0, 0.999766222682478 }, { 2.420047912587, 0, 0.053872145007143, 0, 2.42120272912127, 0, -0.0207745811004126, 0, 0.999784198634445 }, { 2.27623377097568, 0, 0.050327780296591, 0, 2.27736544320128, 0, -0.0198029615544142, 0, 0.999803903541718 }, { 2.14060704310248, 0, 0.0475008081611562, 0, 2.1415886488846, 0, -0.0209681923672342, 0, 0.999780168128298 }, { 2.01912594996957, 0, 0.0444522909259654, 0, 2.02001765316817, 0, -0.0199234929065781, 0, 0.999801498491073 }, { 1.91305591630472, 0, 0.0418777794141375, 0, 1.91384307127268, 0, -0.0196033939869512, 0, 0.999807835391859 }, { 1.81309518050647, 0, 0.0395544579375008, 0, 1.81382376991663, 0, -0.0196259626555668, 0, 0.999807367079979 }, { 1.72506921426309, 0, 0.0370521970466009, 0, 1.72573950567881, 0, -0.0182659717904212, 0, 0.99983315983851 }, { 1.64380823953779, 0, 0.0352828898368588, 0, 1.64438414430532, 0, -0.0189058212072399, 0, 0.99982129232607 }, { 1.57078581280697, 0, 0.0329943787533442, 0, 1.57146973951907, 0, -0.017441935450815, 0, 0.999847866793313 }, { 1.503901128074, 0, 0.031449743260161, 0, 1.50444637114617, 0, -0.0178363827506599, 0, 0.999840922942999 }, { 1.44347216338998, 0, 0.0294904916314813, 0, 1.44402783562175, 0, -0.0166494390305807, 0, 0.999861417386587 }, { 1.38799258642851, 0, 0.0278967807781863, 0, 1.38845236976742, 0, -0.0164234417514614, 0, 0.999865078050608 }, { 1.33777501104505, 0, 0.0263639893604965, 0, 1.3382797309942, 0, -0.0159714613753992, 0, 0.999872450092889 }, { 1.24994366062863, 0, 0.0234095518112964, 0, 1.25034189884332, 0, -0.0147564648461011, 0, 0.999891132582432 }, { 1.24994663491867, 0, 0.0232533970753101, 0, 1.25034189884332, 0, -0.0146315488693477, 0, 0.999893015892183 }, { 1.17697412860489, 0, 0.021483544389643, 0, 1.17743454426534, 0, -0.0139199010246247, 0, 0.999903144132751 }, { 1.17699648217941, 0, 0.0202188239333476, 0, 1.17743454426534, 0, -0.012845455323585, 0, 0.99991748029418 }, { 1.08978465655143, 0, 0.0176864303886164, 0, 1.09018880636586, 0, -0.0122250819875025, 0, 0.999925226392564 }, { 1.08979163262631, 0, 0.0172572642800218, 0, 1.09018880636586, 0, -0.0118313032168124, 0, 0.999930050834961 }, { 1.08980681519439, 0, 0.016269989284445, 0, 1.09018880636586, 0, -0.0109254381864269, 0, 0.999940355101701 }, { 0.999950127390427, 0, 0.00998795328357067, 0, 1, 0, -0.00998795328357067, 0, 0.999950127390427 }, { 0.999958051655997, 0, 0.0091568907210251, 0, 1, 0, -0.0091568907210251, 0, 0.999958051655997 }, { 0.999963812532784, 0, 0.00851033392978927, 0, 1, 0, -0.00851033392978927, 0, 0.999963812532784 }, { 0.99996874929944, 0, 0.00790459089758978, 0, 1, 0, -0.00790459089758978, 0, 0.99996874929944 }, { 0.999974814484357, 0, 0.00709493062785382, 0, 1, 0, -0.00709493062785382, 0, 0.999974814484357 }, { 0.999980470728288, 0, 0.00625610262324583, 0, 1, 0, -0.00625610262324583, 0, 0.999980470728288 }, { 0.99998518803781, 0, 0.00544000866329519, 0, 1, 0, -0.00544000866329519, 0, 0.99998518803781 }, { 0.999989082750575, 0, 0.00467807497007881, 0, 1, 0, -0.00467807497007881, 0, 0.999989082750575 }, { 0.999992011456293, 0, 0.00400438602058364, 0, 1, 0, -0.00400438602058364, 0, 0.999992011456293 }, { 0.999994328702737, 0, 0.00335769285743845, 0, 1, 0, -0.00335769285743845, 0, 0.999994328702737 }, { 0.999996447134158, 0, 0.00267004344344455, 0, 1, 0, -0.00267004344344455, 0, 0.999996447134158 }, { 0.999998121343996, 0, 0.00194576492993735, 0, 1, 0, -0.00194576492993735, 0, 0.999998121343996 }, { 0.999999266123321, 0, 0.00122830637642442, 0, 1, 0, -0.00122830637642442, 0, 0.999999266123321 }, { 0.999999858260981, 0, 0.000566173947918004, 0, 1, 0, -0.000566173947918004, 0, 0.999999858260981 }, { 0.999999999996448, 0, -1.88474132300384E-06, 0, 1, 0, 1.88474132300384E-06, 0, 0.999999999996448 }, // Cos(theta) = 0.9997481 { 249.747946032757, 0, 11.2210063718171, 0, 250.252122492123, 0, -0.0448832765388937, 0, 0.998992271371299 }, { 249.747769663881, 0, 11.2210027313826, 0, 250.251953398092, 0, -0.0448839852025519, 0, 0.998992207563527 }, { 249.747769997956, 0, 11.2209990211062, 0, 250.251953398092, 0, -0.0448839703614296, 0, 0.998992208899826 }, { 220.277414669825, 0, 9.89691552735173, 0, 220.722064229233, 0, -0.0448839761470766, 0, 0.998992148533116 }, { 123.905658260305, 0, 5.56699739312793, 0, 124.155725189259, 0, -0.0448839703614296, 0, 0.998992208899826 }, { 79.299046838306, 0, 3.56285242571012, 0, 79.4591080307488, 0, -0.044883896155817, 0, 0.998992215581313 }, { 55.0681388148786, 0, 2.474174486513, 0, 55.1793055485798, 0, -0.0448840313608391, 0, 0.998992263253196 }, { 40.4573117573255, 0, 1.81771918651403, 0, 40.5390104533836, 0, -0.0448840016785911, 0, 0.998992265925795 }, { 30.9741605012835, 0, 1.39164794838302, 0, 31.0367009048871, 0, -0.0448838367913259, 0, 0.998992220926495 }, { 24.4722917031819, 0, 1.09952261341445, 0, 24.5216223911301, 0, -0.0448838738941329, 0, 0.998992217585757 }, { 19.8212569174399, 0, 0.890553883081805, 0, 19.8612142697156, 0, -0.0448836698286894, 0, 0.99899223595978 }, { 16.3798109601023, 0, 0.735933301123757, 0, 16.4128326933238, 0, -0.0448833396136751, 0, 0.998992265692114 }, { 13.7619936175426, 0, 0.618316466010059, 0, 13.7898048937422, 0, -0.0448828874000512, 0, 0.998992186717244 }, { 11.7245587662405, 0, 0.526772223364751, 0, 11.7481859723876, 0, -0.0448822863345144, 0, 0.998992240835665 }, { 10.107799180935, 0, 0.454138764098364, 0, 10.1279886452715, 0, -0.044880609286944, 0, 0.998992391828923 }, { 8.8031049633604, 0, 0.395512495863937, 0, 8.82084002787945, 0, -0.0448771628744438, 0, 0.998992582417967 }, { 7.73543863465769, 0, 0.347537098604611, 0, 7.75080667551585, 0, -0.0448684528901736, 0, 0.998992887705717 }, { 6.85050749890715, 0, 0.307775682422324, 0, 6.86439848427502, 0, -0.0448403666806515, 0, 0.998994218010491 }, { 6.11030852323534, 0, 0.274509709908383, 0, 6.12263078655031, 0, -0.0447121449016421, 0, 0.998999870486422 }, { 5.4913878756896, 0, 0.246589311927804, 0, 5.50232567830171, 0, -0.0436700936418822, 0, 0.9990459850758 }, { 4.99523637934682, 0, 0.224037222564612, 0, 5.0051436589855, 0, -0.041655187302997, 0, 0.99913205489467 }, { 4.54033527837627, 0, 0.203958898428542, 0, 4.54930770397337, 0, -0.0448242559520895, 0, 0.99899482911195 }, { 4.13528571573805, 0, 0.18573366747823, 0, 4.14341537024394, 0, -0.0447673172693832, 0, 0.998997492114421 }, { 3.78251379939504, 0, 0.169864113342979, 0, 3.79002376836072, 0, -0.0446307863721488, 0, 0.999003570528342 }, { 3.4748674733131, 0, 0.155970794837089, 0, 3.48163257664505, 0, -0.0442557015268773, 0, 0.999020254165919 }, { 3.20820219419506, 0, 0.143743045406678, 0, 3.21426062140431, 0, -0.043126460755059, 0, 0.999069671469618 }, { 2.98187786968825, 0, 0.133086329326874, 0, 2.98769035449573, 0, -0.0407093598128861, 0, 0.999171102074752 }, { 2.77672444884535, 0, 0.124435203876184, 0, 2.78201177090984, 0, -0.0440350281077569, 0, 0.99902998134012 }, { 2.58568516803254, 0, 0.115640906644737, 0, 2.59057696104853, 0, -0.0432011729466983, 0, 0.999066374515153 }, { 2.41895900170998, 0, 0.107692466002089, 0, 2.42343539002652, 0, -0.041489775563733, 0, 0.999138965509964 }, { 2.27352927572255, 0, 0.100808588720582, 0, 2.27781123319826, 0, -0.0404520730073813, 0, 0.999181510501091 }, { 2.13959083767267, 0, 0.0950365531517551, 0, 2.14356821475426, 0, -0.041892114795544, 0, 0.999122137278407 }, { 2.01833630420658, 0, 0.0888969574330842, 0, 2.0219971283604, 0, -0.0397911135863967, 0, 0.99920800692091 }, { 1.91091919874902, 0, 0.0837413462286546, 0, 1.91432318138166, 0, -0.0392839037591647, 0, 0.999228118904818 }, { 1.81237203321686, 0, 0.0791038889722267, 0, 1.81554046714707, 0, -0.0392006762813723, 0, 0.999231377728085 }, { 1.72367006422387, 0, 0.0743072893601868, 0, 1.7265982861, 0, -0.037380633806782, 0, 0.999301123886555 }, { 1.64300893469735, 0, 0.0704671622315507, 0, 1.64592287297417, 0, -0.0375986472235243, 0, 0.999292871923989 }, { 1.56978234130597, 0, 0.0662645173776501, 0, 1.57225575429113, 0, -0.0356861977304961, 0, 0.999363084519508 }, { 1.5032788544816, 0, 0.0627842756562273, 0, 1.50561741775558, 0, -0.0353547013736122, 0, 0.999374847419443 }, { 1.44228169921887, 0, 0.0590801851202805, 0, 1.44469535130439, 0, -0.0337691801798827, 0, 0.999429674061797 }, { 1.38747568086987, 0, 0.0557940960544797, 0, 1.38959694510553, 0, -0.0328078360422556, 0, 0.999461645580771 }, { 1.33688954536745, 0, 0.052534056115798, 0, 1.33885657708165, 0, -0.0315281987758624, 0, 0.999502828205237 }, { 1.24912556505835, 0, 0.0480944895477841, 0, 1.2510405351022, 0, -0.0302378918237648, 0, 0.999542747668862 }, { 1.24919027684214, 0, 0.0463835341573287, 0, 1.2510405351022, 0, -0.0288688033093827, 0, 0.999583233802803 }, { 1.17605559257383, 0, 0.0421455410361522, 0, 1.17780282359236, 0, -0.0274792613291253, 0, 0.999622342973359 }, { 1.17610880805696, 0, 0.0406356069630812, 0, 1.17780282359236, 0, -0.0261958556915728, 0, 0.999656862969016 }, { 1.08891398268098, 0, 0.0357955235043003, 0, 1.09037790438744, 0, -0.0247415421216435, 0, 0.999693891853337 }, { 1.08897283555812, 0, 0.0339586683165254, 0, 1.09037790438744, 0, -0.0230552009293867, 0, 0.999734223804911 }, { 1.08902205892995, 0, 0.0323402095740163, 0, 1.09037790438744, 0, -0.0215693801389456, 0, 0.999767344636172 }, { 0.999794922360746, 0, 0.0202517942313681, 0, 1, 0, -0.0202517942313681, 0, 0.999794922360746 }, { 0.999824407738856, 0, 0.0187375851547369, 0, 1, 0, -0.0187375851547369, 0, 0.999824407738856 }, { 0.999853908512309, 0, 0.0170927215281507, 0, 1, 0, -0.0170927215281507, 0, 0.999853908512309 }, { 0.999880184153089, 0, 0.0154792385411265, 0, 1, 0, -0.0154792385411265, 0, 0.999880184153089 }, { 0.999902949450706, 0, 0.0139333090554366, 0, 1, 0, -0.0139333090554366, 0, 0.999902949450706 }, { 0.999922052760882, 0, 0.012483766684855, 0, 1, 0, -0.012483766684855, 0, 0.999922052760882 }, { 0.999939050329947, 0, 0.0110418072965664, 0, 1, 0, -0.0110418072965664, 0, 0.999939050329947 }, { 0.999954423698343, 0, 0.00954839141843103, 0, 1, 0, -0.00954839141843103, 0, 0.999954423698343 }, { 0.999967565252196, 0, 0.00805718491851225, 0, 1, 0, -0.00805718491851225, 0, 0.999967565252196 }, { 0.999978201275882, 0, 0.00660405551785873, 0, 1, 0, -0.00660405551785873, 0, 0.999978201275882 }, { 0.999986433326967, 0, 0.00520545318391351, 0, 1, 0, -0.00520545318391351, 0, 0.999986433326967 }, { 0.999992429700822, 0, 0.00388335250256577, 0, 1, 0, -0.00388335250256577, 0, 0.999992429700822 }, { 0.999996871739639, 0, 0.00250744827360521, 0, 1, 0, -0.00250744827360521, 0, 0.999996871739639 }, { 0.999999236380495, 0, 0.00124035451092836, 0, 1, 0, -0.00124035451092836, 0, 0.999999236380495 }, { 0.999999999581178, 0, -2.04651387235352E-05, 0, 1, 0, 2.04651387235352E-05, 0, 0.999999999581178 }, // Cos(theta) = 0.9989922 diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader index 5dddd6a2842..e4f7ee21b66 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader @@ -76,7 +76,7 @@ Shader "Hidden/HDRP/PreIntegratedFGD_CookTorrance" // weight = fr * (N.L) with fr = F(H) * G(V, L) * D(H) / (4 * (N.L) * (N.V)) // weight over pdf is: // weightOverPdf = F(H) * G(V, L) * (L.H) / ((N.H) * (N.V)) - // weightOverPdf = F(H) * 4 * (N.L) * V(V, L) * (L.H) / (N.H) + // weightOverPdf = F(H) * 4 * (N.L) * V(V, L) * (L.H) / (N.H) // with V(V, L) = G(V, L) / (4 * (N.L) * (N.V)) // Reminder: (L.H) == (V.H) // F is applied outside the function diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFDepthPass.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFDepthPass.hlsl index 1d2693a270e..868e04f1e19 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFDepthPass.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFDepthPass.hlsl @@ -54,7 +54,7 @@ #define VARYINGS_NEED_COLOR #endif #elif defined(LOD_FADE_CROSSFADE) - #define VARYINGS_NEED_POSITION_WS // Required to get view vector use in cross fade effect + #define VARYINGS_NEED_POSITION_WS // Required to get view vector use in cross fade effect #endif // This include will define the various Attributes/Varyings structure diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFSharePass.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFSharePass.hlsl index 0be4e9396a0..c07b1f69fd6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFSharePass.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/ShaderPass/AxFSharePass.hlsl @@ -2,7 +2,7 @@ #error Undefine_SHADERPASS #endif -// NOTE: Copied from LitSharePass.hlsl, we will need most of this, but at first, vs the unlit, we have +// NOTE: Copied from LitSharePass.hlsl, we will need most of this, but at first, vs the unlit, we have // diffuse lighting, and also consider the _DOUBLESIDED_ON option. // This first set of define allow to say which attributes will be use by the mesh in the vertex and domain shader (for tesselation) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl index 39c22b59120..57a77da2eb0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl @@ -39,7 +39,7 @@ void EncodeMotionVector(float2 motionVector, out float4 outBuffer) bool PixelSetAsNoMotionVectors(float4 inBuffer) { - return inBuffer.x > 1.0f; + return inBuffer.x > 1.0f; } void DecodeMotionVector(float4 inBuffer, out float2 motionVector) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/BuiltinGIUtilities.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/BuiltinGIUtilities.hlsl index 5a0d0146881..4233594409e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/BuiltinGIUtilities.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/BuiltinGIUtilities.hlsl @@ -122,15 +122,15 @@ void SampleBakedGI( bakeDiffuseLighting = float3(0, 0, 0); backBakeDiffuseLighting = float3(0, 0, 0); - // Check if we are RTGI in which case we don't want to read GI at all (We rely fully on the raytrace effect) - // The check need to be here to work with both regular shader and shader graph - // Note: with Probe volume it will prevent to add the UNINITIALIZED_GI tag and - // the ProbeVolume will not be evaluate in the lightloop which is the desired behavior - // Also this code only needs to be executed in the rasterization pipeline, otherwise it will lead to udnefined behaviors in ray tracing + // Check if we are RTGI in which case we don't want to read GI at all (We rely fully on the raytrace effect) + // The check need to be here to work with both regular shader and shader graph + // Note: with Probe volume it will prevent to add the UNINITIALIZED_GI tag and + // the ProbeVolume will not be evaluate in the lightloop which is the desired behavior + // Also this code only needs to be executed in the rasterization pipeline, otherwise it will lead to udnefined behaviors in ray tracing #if !defined(_SURFACE_TYPE_TRANSPARENT) && (SHADERPASS != SHADERPASS_RAYTRACING_INDIRECT) && (SHADERPASS != SHADERPASS_RAYTRACING_GBUFFER) if (_IndirectDiffuseMode == INDIRECTDIFFUSEMODE_RAYTRACE) return; -#endif +#endif float3 positionRWS = posInputs.positionWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DBufferManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DBufferManager.cs index 0f93eacee1c..2c476e8d30d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DBufferManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DBufferManager.cs @@ -4,8 +4,6 @@ namespace UnityEngine.Rendering.HighDefinition { class DBufferManager : MRTBufferManager { - - public DBufferManager() : base(Decal.GetMaterialDBufferCount()) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl index 43244685eb8..6d5bc6229f4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl @@ -5,43 +5,43 @@ #ifdef DECALS_4RT #define DBufferType3 float2 -#define OUTPUT_DBUFFER(NAME) \ - out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \ - out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \ - out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \ - out DBufferType3 MERGE_NAME(NAME, 3) : SV_Target3 +#define OUTPUT_DBUFFER(NAME) \ + out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \ + out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \ + out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \ + out DBufferType3 MERGE_NAME(NAME, 3) : SV_Target3 -#define DECLARE_DBUFFER_TEXTURE(NAME) \ - TEXTURE2D_X(MERGE_NAME(NAME, 0)); \ - TEXTURE2D_X(MERGE_NAME(NAME, 1)); \ - TEXTURE2D_X(MERGE_NAME(NAME, 2)); \ - TEXTURE2D_X(MERGE_NAME(NAME, 3)); +#define DECLARE_DBUFFER_TEXTURE(NAME) \ + TEXTURE2D_X(MERGE_NAME(NAME, 0)); \ + TEXTURE2D_X(MERGE_NAME(NAME, 1)); \ + TEXTURE2D_X(MERGE_NAME(NAME, 2)); \ + TEXTURE2D_X(MERGE_NAME(NAME, 3)); -#define FETCH_DBUFFER(NAME, TEX, unCoord2) \ - DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 0), unCoord2); \ - DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 1), unCoord2); \ - DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 2), unCoord2); \ - DBufferType3 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 3), unCoord2).xy; // Caution: We do .xy to match #define DBufferType3 float2 and avoid a shader warning +#define FETCH_DBUFFER(NAME, TEX, unCoord2) \ + DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 0), unCoord2); \ + DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 1), unCoord2); \ + DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 2), unCoord2); \ + DBufferType3 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 3), unCoord2).xy; // Caution: We do .xy to match #define DBufferType3 float2 and avoid a shader warning #define ENCODE_INTO_DBUFFER(DECAL_SURFACE_DATA, NAME) EncodeIntoDBuffer(DECAL_SURFACE_DATA, MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), MERGE_NAME(NAME,3)) #define DECODE_FROM_DBUFFER(NAME, DECAL_SURFACE_DATA) DecodeFromDBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), MERGE_NAME(NAME,3), DECAL_SURFACE_DATA) #else -#define OUTPUT_DBUFFER(NAME) \ - out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \ - out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \ - out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2 +#define OUTPUT_DBUFFER(NAME) \ + out DBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \ + out DBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \ + out DBufferType2 MERGE_NAME(NAME, 2) : SV_Target2 -#define DECLARE_DBUFFER_TEXTURE(NAME) \ - TEXTURE2D_X(MERGE_NAME(NAME, 0)); \ - TEXTURE2D_X(MERGE_NAME(NAME, 1)); \ - TEXTURE2D_X(MERGE_NAME(NAME, 2)); +#define DECLARE_DBUFFER_TEXTURE(NAME) \ + TEXTURE2D_X(MERGE_NAME(NAME, 0)); \ + TEXTURE2D_X(MERGE_NAME(NAME, 1)); \ + TEXTURE2D_X(MERGE_NAME(NAME, 2)); -#define FETCH_DBUFFER(NAME, TEX, unCoord2) \ - DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 0), unCoord2); \ - DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 1), unCoord2); \ - DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 2), unCoord2); +#define FETCH_DBUFFER(NAME, TEX, unCoord2) \ + DBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 0), unCoord2); \ + DBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 1), unCoord2); \ + DBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D_X(MERGE_NAME(TEX, 2), unCoord2); #define ENCODE_INTO_DBUFFER(DECAL_SURFACE_DATA, NAME) EncodeIntoDBuffer(DECAL_SURFACE_DATA, MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2)) #define DECODE_FROM_DBUFFER(NAME, DECAL_SURFACE_DATA) DecodeFromDBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), DECAL_SURFACE_DATA) @@ -54,7 +54,7 @@ void EncodeIntoDBuffer( DecalSurfaceData surfaceData , out DBufferType1 outDBuffer1 , out DBufferType2 outDBuffer2 #ifdef DECALS_4RT - , out DBufferType3 outDBuffer3 + , out DBufferType3 outDBuffer3 #endif ) { @@ -62,7 +62,7 @@ void EncodeIntoDBuffer( DecalSurfaceData surfaceData outDBuffer1 = float4(surfaceData.normalWS.xyz * 0.5 + 0.5, surfaceData.normalWS.w); outDBuffer2 = surfaceData.mask; #ifdef DECALS_4RT - outDBuffer3 = surfaceData.MAOSBlend; + outDBuffer3 = surfaceData.MAOSBlend; #endif } @@ -71,7 +71,7 @@ void DecodeFromDBuffer( , DBufferType1 inDBuffer1 , DBufferType2 inDBuffer2 #ifdef DECALS_4RT - , DBufferType3 inDBuffer3 + , DBufferType3 inDBuffer3 #endif , out DecalSurfaceData surfaceData ) @@ -84,8 +84,8 @@ void DecodeFromDBuffer( surfaceData.normalWS.w = inDBuffer1.w; surfaceData.mask = inDBuffer2; #ifdef DECALS_4RT - surfaceData.MAOSBlend = inDBuffer3; + surfaceData.MAOSBlend = inDBuffer3; #else - surfaceData.MAOSBlend = float2(surfaceData.mask.w, surfaceData.mask.w); + surfaceData.MAOSBlend = float2(surfaceData.mask.w, surfaceData.mask.w); #endif } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader index 1bf513b3060..3a4dd39b1e6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader @@ -2,15 +2,15 @@ Shader "HDRP/Decal" { Properties { - _BaseColor("_BaseColor", Color) = (1,1,1,1) + _BaseColor("_BaseColor", Color) = (1,1,1,1) _BaseColorMap("BaseColorMap", 2D) = "white" {} _NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map _MaskMap("MaskMap", 2D) = "white" {} _DecalBlend("_DecalBlend", Range(0.0, 1.0)) = 0.5 - [HideInInspector] _NormalBlendSrc("_NormalBlendSrc", Float) = 0.0 - [HideInInspector] _MaskBlendSrc("_MaskBlendSrc", Float) = 1.0 - [HideInInspector] _DecalMeshDepthBias("_DecalMeshDepthBias", Float) = 0.0 - [HideInInspector] _DrawOrder("_DrawOrder", Int) = 0 + [HideInInspector] _NormalBlendSrc("_NormalBlendSrc", Float) = 0.0 + [HideInInspector] _MaskBlendSrc("_MaskBlendSrc", Float) = 1.0 + [HideInInspector] _DecalMeshDepthBias("_DecalMeshDepthBias", Float) = 0.0 + [HideInInspector] _DrawOrder("_DrawOrder", Int) = 0 [HDR] _EmissiveColor("EmissiveColor", Color) = (0, 0, 0) // Used only to serialize the LDR and HDR emissive color in the material UI, // in the shader only the _EmissiveColor should be used @@ -49,11 +49,11 @@ Shader "HDRP/Decal" [HideInInspector] _DecalStencilRef("_DecalStencilRef", Int) = 16 [HideInInspector] _DecalStencilWriteMask("_DecalStencilWriteMask", Int) = 16 - // Decal color masks + // Decal color masks [HideInInspector]_DecalColorMask0("_DecalColorMask0", Int) = 0 [HideInInspector]_DecalColorMask1("_DecalColorMask1", Int) = 0 - [HideInInspector]_DecalColorMask2("_DecalColorMask2", Int) = 0 - [HideInInspector]_DecalColorMask3("_DecalColorMask3", Int) = 0 + [HideInInspector]_DecalColorMask2("_DecalColorMask2", Int) = 0 + [HideInInspector]_DecalColorMask3("_DecalColorMask3", Int) = 0 // TODO: Remove when name garbage is solve (see IsHDRenderPipelineDecal) // This marker allow to identify that a Material is a HDRP/Decal @@ -74,7 +74,7 @@ Shader "HDRP/Decal" #pragma shader_feature_local _NORMALMAP #pragma shader_feature_local _EMISSIVEMAP - #pragma shader_feature_local _MATERIAL_AFFECTS_ALBEDO + #pragma shader_feature_local _MATERIAL_AFFECTS_ALBEDO #pragma shader_feature_local _MATERIAL_AFFECTS_NORMAL #pragma shader_feature_local _MATERIAL_AFFECTS_MASKMAP @@ -103,10 +103,10 @@ Shader "HDRP/Decal" // DecalSubTarget.cs - class SubShaders // Caution: passes stripped in builds (like the scene picking pass) need to be put last to have consistent indices - Pass // 0 - { - Name "DBufferProjector" - Tags{"LightMode" = "DBufferProjector"} // Metalness + Pass // 0 + { + Name "DBufferProjector" + Tags{"LightMode" = "DBufferProjector"} // Metalness Stencil { @@ -116,35 +116,35 @@ Shader "HDRP/Decal" Pass Replace } - // back faces with zfail, for cases when camera is inside the decal volume - Cull Front - ZWrite Off - ZTest Greater + // back faces with zfail, for cases when camera is inside the decal volume + Cull Front + ZWrite Off + ZTest Greater - // using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html - Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha - Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha - Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha - Blend 3 Zero OneMinusSrcColor + // using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html + Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha + Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha + Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha + Blend 3 Zero OneMinusSrcColor ColorMask [_DecalColorMask0] ColorMask [_DecalColorMask1] 1 ColorMask [_DecalColorMask2] 2 ColorMask [_DecalColorMask3] 3 - HLSLPROGRAM + HLSLPROGRAM #pragma multi_compile DECALS_3RT DECALS_4RT - #define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR + #define SHADERPASS SHADERPASS_DBUFFER_PROJECTOR #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProperties.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderPass/DecalSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderPass/DecalSharePass.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl" - ENDHLSL - } + ENDHLSL + } Pass // 1 { @@ -180,10 +180,10 @@ Shader "HDRP/Decal" ENDHLSL } - Pass // 2 - { - Name "DBufferMesh" - Tags{"LightMode" = "DBufferMesh"} + Pass // 2 + { + Name "DBufferMesh" + Tags{"LightMode" = "DBufferMesh"} Stencil { @@ -193,13 +193,13 @@ Shader "HDRP/Decal" Pass Replace } - ZWrite Off - ZTest LEqual + ZWrite Off + ZTest LEqual - // using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html - Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha - Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha - Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha + // using alpha compositing https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html + Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha + Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha + Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 3 Zero OneMinusSrcColor ColorMask [_DecalColorMask0] @@ -207,22 +207,22 @@ Shader "HDRP/Decal" ColorMask [_DecalColorMask2] 2 ColorMask [_DecalColorMask3] 3 - HLSLPROGRAM + HLSLPROGRAM #pragma multi_compile DECALS_3RT DECALS_4RT // enable dithering LOD crossfade #pragma multi_compile _ LOD_FADE_CROSSFADE - #define SHADERPASS SHADERPASS_DBUFFER_MESH + #define SHADERPASS SHADERPASS_DBUFFER_MESH #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProperties.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderPass/DecalSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderPass/DecalSharePass.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl" - ENDHLSL - } + ENDHLSL + } Pass // 3 { @@ -287,12 +287,12 @@ Shader "HDRP/Decal" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/ShaderPass/DecalSharePass.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/PickingSpaceTransforms.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl" - + #pragma editor_sync_compilation ENDHLSL } - } + } CustomEditor "Rendering.HighDefinition.DecalUI" } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl index edaaddf7536..4c3bd1d4f3f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalData.hlsl @@ -12,15 +12,15 @@ void GetSurfaceData(FragInputs input, float3 V, PositionInputs posInput, float a float fadeFactor = clamp(normalToWorld[0][3], 0.0f, 1.0f) * angleFadeFactor; float2 scale = float2(normalToWorld[3][0], normalToWorld[3][1]); float2 offset = float2(normalToWorld[3][2], normalToWorld[3][3]); - float2 texCoords = input.texCoord0.xy * scale + offset; + float2 texCoords = input.texCoord0.xy * scale + offset; #elif (SHADERPASS == SHADERPASS_DBUFFER_MESH) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_MESH) #ifdef LOD_FADE_CROSSFADE // enable dithering LOD transition if user select CrossFade transition in LOD group LODDitheringTransition(ComputeFadeMaskSeed(V, posInput.positionSS), unity_LODFade.x); #endif - float fadeFactor = _DecalBlend.x; - float2 texCoords = input.texCoord0.xy; + float fadeFactor = _DecalBlend.x; + float2 texCoords = input.texCoord0.xy; #endif float albedoMapBlend = fadeFactor; @@ -44,11 +44,11 @@ void GetSurfaceData(FragInputs input, float3 V, PositionInputs posInput, float a #ifdef _COLORMAP surfaceData.baseColor *= SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, texCoords); #endif - surfaceData.baseColor.w *= fadeFactor; + surfaceData.baseColor.w *= fadeFactor; albedoMapBlend = surfaceData.baseColor.w; // outside _COLORMAP because we still have base color for albedoMapBlend #ifndef _MATERIAL_AFFECTS_ALBEDO - surfaceData.baseColor.w = 0.0; // dont blend any albedo - Note: as we already do RT color masking this is not needed, albedo will not be affected anyway + surfaceData.baseColor.w = 0.0; // dont blend any albedo - Note: as we already do RT color masking this is not needed, albedo will not be affected anyway #endif // In case of Smoothness / AO / Metal, all the three are always computed but color mask can change @@ -58,7 +58,7 @@ void GetSurfaceData(FragInputs input, float3 V, PositionInputs posInput, float a #ifdef _MASKMAP surfaceData.mask = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, texCoords); surfaceData.mask.z *= _DecalMaskMapBlueScale; - maskMapBlend *= surfaceData.mask.z; // store before overwriting with smoothness + maskMapBlend *= surfaceData.mask.z; // store before overwriting with smoothness #ifdef DECALS_4RT surfaceData.mask.x = lerp(_MetallicRemapMin, _MetallicRemapMax, surfaceData.mask.x); surfaceData.mask.y = lerp(_AORemapMin, _AORemapMax, surfaceData.mask.y); @@ -66,7 +66,7 @@ void GetSurfaceData(FragInputs input, float3 V, PositionInputs posInput, float a surfaceData.mask.z = lerp(_SmoothnessRemapMin, _SmoothnessRemapMax, surfaceData.mask.w); #else surfaceData.mask.z = _DecalMaskMapBlueScale; - maskMapBlend *= surfaceData.mask.z; // store before overwriting with smoothness + maskMapBlend *= surfaceData.mask.z; // store before overwriting with smoothness #ifdef DECALS_4RT surfaceData.mask.x = _Metallic; surfaceData.mask.y = _AO; @@ -74,32 +74,32 @@ void GetSurfaceData(FragInputs input, float3 V, PositionInputs posInput, float a surfaceData.mask.z = _Smoothness; #endif - surfaceData.mask.w = _MaskBlendSrc ? maskMapBlend : albedoMapBlend; + surfaceData.mask.w = _MaskBlendSrc ? maskMapBlend : albedoMapBlend; #endif - // needs to be after mask, because blend source could be in the mask map blue + // needs to be after mask, because blend source could be in the mask map blue // Note: We always use a texture here as the decal atlas for transparent decal cluster only handle texture case // If no texture is assign it is the bump texture (0.0, 0.0, 1.0) #ifdef _MATERIAL_AFFECTS_NORMAL #ifdef _NORMALMAP - float3 normalTS = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords)); + float3 normalTS = UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords)); #else float3 normalTS = float3(0.0, 0.0, 1.0); #endif float3 normalWS = float3(0.0, 0.0, 0.0); #if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) - normalWS = mul((float3x3)normalToWorld, normalTS); - #elif (SHADERPASS == SHADERPASS_DBUFFER_MESH) + normalWS = mul((float3x3)normalToWorld, normalTS); + #elif (SHADERPASS == SHADERPASS_DBUFFER_MESH) // We need to normalize as we use mikkt tangent space and this is expected (tangent space is not normalize) normalWS = normalize(TransformTangentToWorld(normalTS, input.tangentToWorld)); #endif - surfaceData.normalWS.xyz = normalWS; - surfaceData.normalWS.w = _NormalBlendSrc ? maskMapBlend : albedoMapBlend; + surfaceData.normalWS.xyz = normalWS; + surfaceData.normalWS.w = _NormalBlendSrc ? maskMapBlend : albedoMapBlend; #endif - surfaceData.MAOSBlend.xy = float2(surfaceData.mask.w, surfaceData.mask.w); + surfaceData.MAOSBlend.xy = float2(surfaceData.mask.w, surfaceData.mask.w); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader index 3ec8bddbdbd..3ef91064367 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader @@ -14,8 +14,8 @@ Shader "Hidden/HDRP/Material/Decal/DecalNormalBuffer" #pragma only_renderers d3d11 playstation xboxone vulkan metal switch #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/NormalBuffer.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/NormalBuffer.hlsl" #if defined(PLATFORM_NEEDS_UNORM_UAV_SPECIFIER) && defined(PLATFORM_SUPPORTS_EXPLICIT_BINDING) // Explicit binding is needed on D3D since we bind the UAV to slot 1 and we don't have a colour RT bound to fix a D3D warning. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs index c7fc5193039..27e9764c59b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs @@ -58,7 +58,7 @@ public float drawDistance } [SerializeField] - [Range(0,1)] + [Range(0, 1)] private float m_FadeScale = 0.9f; /// /// Percent of the distance from the camera at which this Decal start to fade off. @@ -355,6 +355,7 @@ void UpdateDecalVisibility() DecalSystem.instance.UpdateCachedData(m_Handle, GetCachedDecalData()); } } + #endif void OnDisable() @@ -422,6 +423,7 @@ void Update() // only run in editor DecalSystem.instance.UpdateCachedData(m_Handle, GetCachedDecalData()); } } + #endif void LateUpdate() diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs index adcee6fdab4..ac94c629c1e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs @@ -444,7 +444,6 @@ public DecalSet(Material material) InitializeMaterialValues(); } - private BoundingSphere GetDecalProjectBoundingSphere(Matrix4x4 decalToWorld) { Vector4 min = new Vector4(); @@ -497,7 +496,7 @@ public void UpdateCachedData(DecalHandle handle, in DecalProjector.CachedDecalDa float angleEnd = data.endAngleFade / 180.0f; var range = Mathf.Max(0.0001f, angleEnd - angleStart); m_CachedAngleFade[index].x = 1.0f - (0.25f - angleStart) / range; - m_CachedAngleFade[index].y = - 0.25f / range; + m_CachedAngleFade[index].y = -0.25f / range; } m_CachedUVScaleBias[index] = data.uvScaleBias; m_CachedAffectsTransparency[index] = data.affectsTransparency; @@ -918,13 +917,13 @@ internal void SetCullResult(CullResult.Set value) } } - void SetupMipStreamingSettings(Texture texture, bool allMips) - { - if (texture) - { - if (texture.dimension == UnityEngine.Rendering.TextureDimension.Tex2D) - { - Texture2D tex2D = (texture as Texture2D); + void SetupMipStreamingSettings(Texture texture, bool allMips) + { + if (texture) + { + if (texture.dimension == UnityEngine.Rendering.TextureDimension.Tex2D) + { + Texture2D tex2D = (texture as Texture2D); if (tex2D) { if (allMips) @@ -932,9 +931,9 @@ void SetupMipStreamingSettings(Texture texture, bool allMips) else tex2D.ClearRequestedMipmapLevel(); } - } - } - } + } + } + } void SetupMipStreamingSettings(Material material, bool allMips) { @@ -1115,7 +1114,6 @@ public void UpdateTextureAtlas(CommandBuffer cmd) UpdateDecalDatasWithAtlasInfo(); } - public void CreateDrawData() { m_DecalDatasCount = 0; @@ -1149,7 +1147,7 @@ public void CreateDrawData() foreach (var decalSet in m_DecalSetsRenderList) decalSet.CreateDrawData(); - } + } public void Cleanup() { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.Migration.cs index 0f5a06049e6..eb7d7e0d483 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.Migration.cs @@ -144,7 +144,7 @@ static void UpgradeMaterial(Material mat, DiffusionProfileSettings mainProfile, var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(mainProfile)); SerializableGUIDs profiles = JsonUtility.FromJson(importer.userData); - if (String.IsNullOrEmpty(profiles.assetGUIDs?[index])) + if (String.IsNullOrEmpty(profiles.assetGUIDs ? [index])) { Debug.LogError("Could not upgrade diffusion profile reference in material " + mat + ": index " + index + " not found in main diffusion profile"); return; @@ -171,13 +171,12 @@ static void UpgradeMaterial(Material mat, DiffusionProfileSettings mainProfile, stencilGBufferRef |= (int)StencilUsage.SubsurfaceScattering; } - if(mat.HasProperty("_ReceivesSSR") && mat.GetInt("_ReceivesSSR") == 1) + if (mat.HasProperty("_ReceivesSSR") && mat.GetInt("_ReceivesSSR") == 1) { stencilWriteMask |= (int)StencilUsage.TraceReflectionRay; stencilRef |= (int)StencilUsage.TraceReflectionRay; stencilGBufferMask |= (int)StencilUsage.TraceReflectionRay; stencilGBufferRef |= (int)StencilUsage.TraceReflectionRay; - } // As we tag both during motion vector pass and Gbuffer pass we need a separate state and we need to use the write mask @@ -226,6 +225,7 @@ public void TryToUpgrade() EditorApplication.delayCall += UnityEditor.AssetDatabase.Refresh; } } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs index 73d76786719..05b0e73c6d8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/DiffusionProfile/DiffusionProfileSettings.cs @@ -85,8 +85,8 @@ void UpdateKernel() // Rather inconvenient to support (S = Inf). shapeParam = new Vector3(Mathf.Min(16777216, 1.0f / sd.x), - Mathf.Min(16777216, 1.0f / sd.y), - Mathf.Min(16777216, 1.0f / sd.z)); + Mathf.Min(16777216, 1.0f / sd.y), + Mathf.Min(16777216, 1.0f / sd.z)); // Filter radius is, strictly speaking, infinite. // The magnitude of the function decays exponentially, but it is never truly zero. @@ -172,7 +172,7 @@ static float SampleBurleyDiffusionProfile(float u, float rcpS) u = 1 - u; // Convert CDF to CCDF float g = 1 + (4 * u) * (2 * u + Mathf.Sqrt(1 + (4 * u) * u)); - float n = Mathf.Pow(g, -1.0f/3.0f); // g^(-1/3) + float n = Mathf.Pow(g, -1.0f / 3.0f); // g^(-1/3) float p = (g * n) * n; // g^(+1/3) float c = 1 + p + n; // 1 + g^(+1/3) + g^(-1/3) float x = 3 * Mathf.Log(c / (4 * u)); @@ -185,13 +185,13 @@ public bool Equals(DiffusionProfile other) if (other == null) return false; - return scatteringDistance == other.scatteringDistance && - transmissionTint == other.transmissionTint && - texturingMode == other.texturingMode && - transmissionMode == other.transmissionMode && - thicknessRemap == other.thicknessRemap && - worldScale == other.worldScale && - ior == other.ior; + return scatteringDistance == other.scatteringDistance && + transmissionTint == other.transmissionTint && + texturingMode == other.texturingMode && + transmissionMode == other.transmissionMode && + thicknessRemap == other.thicknessRemap && + worldScale == other.worldScale && + ior == other.ior; } } @@ -238,13 +238,14 @@ internal void Reset() profile.hash = DiffusionProfileHashTable.GenerateUniqueHash(this); } } + #endif internal void UpdateCache() { worldScaleAndFilterRadiusAndThicknessRemap = new Vector4(profile.worldScale, - profile.filterRadius, - profile.thicknessRemap.x, - profile.thicknessRemap.y - profile.thicknessRemap.x); + profile.filterRadius, + profile.thicknessRemap.x, + profile.thicknessRemap.y - profile.thicknessRemap.x); shapeParamAndMaxScatterDist = profile.shapeParam; shapeParamAndMaxScatterDist.w = profile.maxScatteringDistance; // Convert ior to fresnel0 diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl index f1609102420..d7622471901 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/Eye.hlsl @@ -228,13 +228,13 @@ void GetBSDFDataDebug(uint paramId, BSDFData bsdfData, inout float3 result, inou float3 vsDiffuseNormal = TransformWorldToViewDir(bsdfData.diffuseNormalWS); result = IsNormalized(vsDiffuseNormal) ? vsDiffuseNormal * 0.5 + 0.5 : float3(1.0, 0.0, 0.0); break; - } + } case DEBUGVIEW_EYE_BSDFDATA_GEOMETRIC_NORMAL_VIEW_SPACE: { float3 vsGeomNormal = TransformWorldToViewDir(bsdfData.geomNormalWS); result = IsNormalized(vsGeomNormal) ? vsGeomNormal * 0.5 + 0.5 : float3(1.0, 0.0, 0.0); break; - } + } case DEBUGVIEW_EYE_BSDFDATA_IOR: result = saturate((bsdfData.IOR - 1.0) / 1.5).xxx; break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeRaytracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeRaytracing.hlsl index 8b4d16911e8..38373f1bf56 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeRaytracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeRaytracing.hlsl @@ -41,7 +41,7 @@ void FitToStandardLit( SurfaceData surfaceData , BuiltinData builtinData , uint2 positionSS , out StandardBSDFData outStandardlit) -{ +{ outStandardlit.baseColor = surfaceData.baseColor; outStandardlit.specularOcclusion = surfaceData.specularOcclusion; outStandardlit.normalWS = surfaceData.normalWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeUtils.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeUtils.hlsl index c2157382d13..9183bc2517e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeUtils.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeUtils.hlsl @@ -49,7 +49,7 @@ void CirclePupilAnimation(float2 irusUV, float pupilRadius, float pupilAperture, void CorneaRefraction(float3 positionOS, float3 viewDirectionOS, float3 corneaNormalOS, float corneaIOR, float irisPlaneOffset, out float3 refractedPositionOS) { - // Compute the refracted + // Compute the refracted float eta = 1.0 / (corneaIOR); corneaNormalOS = normalize(corneaNormalOS); viewDirectionOS = -normalize(viewDirectionOS); @@ -98,7 +98,7 @@ void ScleraLimbalRing(float3 positionOS, float3 viewOS, float irisRadius, float void ScleraIrisBlend(float3 scleraColor, float3 scleraNormal, float scleraSmoothness, float3 irisColor, float3 irisNormal, float corneaSmoothness, - float irisRadius, + float irisRadius, float3 positionOS, float diffusionProfileSclera, float diffusionProfileIris, out float3 eyeColor, out float surfaceMask, @@ -118,4 +118,4 @@ void ScleraIrisBlend(float3 scleraColor, float3 scleraNormal, float scleraSmooth surfaceDiffusionProfile = lerp(diffusionProfileSclera, diffusionProfileIris, floor(surfaceMask)); } -#endif // EYE_UTILS_HLSL \ No newline at end of file +#endif // EYE_UTILS_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricRaytracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricRaytracing.hlsl index 8bf02869b6c..4c93889e4e1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricRaytracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricRaytracing.hlsl @@ -49,7 +49,7 @@ void FitToStandardLit( SurfaceData surfaceData , BuiltinData builtinData , uint2 positionSS , out StandardBSDFData outStandardlit) -{ +{ outStandardlit.baseColor = surfaceData.baseColor; outStandardlit.specularOcclusion = surfaceData.specularOcclusion; outStandardlit.normalWS = surfaceData.normalWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricReference.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricReference.hlsl index daeb7337326..90e78bb5d8a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricReference.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/FabricReference.hlsl @@ -10,7 +10,7 @@ float3 IntegrateSpecularCottonWoolIBLRef(LightLoopContext lightLoopContext, float3x3 localToWorld = GetLocalFrame(bsdfData.normalWS); float NdotV = ClampNdotV(dot(bsdfData.normalWS, V)); float3 acc = float3(0.0, 0.0, 0.0); - + // Add some jittering on Hammersley2d float2 randNum = InitRandom(V.xy * 0.5 + 0.5); @@ -51,7 +51,7 @@ float3 IntegrateSpecularSilkIBLRef(LightLoopContext lightLoopContext, float3x3 localToWorld = float3x3(bsdfData.tangentWS, bsdfData.bitangentWS, bsdfData.normalWS); float NdotV = ClampNdotV(dot(bsdfData.normalWS, V)); float3 acc = float3(0.0, 0.0, 0.0); - + // Add some jittering on Hammersley2d float2 randNum = InitRandom(V.xy * 0.5 + 0.5); @@ -65,7 +65,7 @@ float3 IntegrateSpecularSilkIBLRef(LightLoopContext lightLoopContext, float3 L; float weightOverPdf; ImportanceSampleAnisoGGX(u, V, localToWorld, bsdfData.roughnessT, bsdfData.roughnessB, NdotV, L, VdotH, NdotL, weightOverPdf); - + if (NdotL > 0.0) { // Fresnel component is apply here as describe in ImportanceSampleGGX function diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/GBufferManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/GBufferManager.cs index 5e6ff71f87a..76c45c37435 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/GBufferManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/GBufferManager.cs @@ -11,7 +11,7 @@ enum GBufferUsage LightLayers, ShadowMask #if ENABLE_VIRTUALTEXTURES - ,VTFeedback + , VTFeedback #endif } @@ -157,6 +157,7 @@ public RTHandle GetSubsurfaceScatteringBuffer(int index) return null; } + #if ENABLE_VIRTUALTEXTURES public RTHandle GetVTFeedbackBuffer() { @@ -164,8 +165,9 @@ public RTHandle GetVTFeedbackBuffer() { return m_RTs[m_VTFeedbackIndex]; } - return null; + return null; } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/IBLFilterGGX.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/IBLFilterGGX.cs index e4b919a1775..fa26f0b849d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/IBLFilterGGX.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/IBLFilterGGX.cs @@ -224,7 +224,7 @@ void BuildColorAndDepthMipChain(CommandBuffer cmd, RenderTexture sourceColor, Re currentScreenSize.Set(currentTexWidth, currentTexHeight, 1.0f / currentTexWidth, 1.0f / currentTexHeight); cmd.SetComputeVectorParam(m_PlanarReflectionFilteringCS, HDShaderIDs._CaptureCurrentScreenSize, currentScreenSize); cmd.SetComputeFloatParam(m_PlanarReflectionFilteringCS, HDShaderIDs._CaptureCameraFarPlane, planarTextureFilteringParameters.captureFarPlane); - + // Input textures cmd.SetComputeTextureParam(m_PlanarReflectionFilteringCS, m_PlanarReflectionDepthConversionKernel, HDShaderIDs._DepthTextureOblique, sourceDepth); @@ -327,7 +327,7 @@ override public void FilterPlanarTexture(CommandBuffer cmd, RenderTexture source cmd.SetComputeVectorParam(m_PlanarReflectionFilteringCS, HDShaderIDs._CaptureCameraPositon, planarTextureFilteringParameters.captureCameraPosition); cmd.SetComputeMatrixParam(m_PlanarReflectionFilteringCS, HDShaderIDs._CaptureCameraIVP_NO, planarTextureFilteringParameters.captureCameraIVP_NonOblique); cmd.SetComputeFloatParam(m_PlanarReflectionFilteringCS, HDShaderIDs._CaptureCameraFOV, planarTextureFilteringParameters.captureFOV * Mathf.PI / 180.0f); - + // Set output textures cmd.SetComputeTextureParam(m_PlanarReflectionFilteringCS, m_PlanarReflectionFilteringKernel, HDShaderIDs._FilteredPlanarReflectionBuffer, m_PlanarReflectionFilterTex1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl index 956d873f3a3..b7ab42be989 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl @@ -223,7 +223,7 @@ void GetBSDFDataDebug(uint paramId, BSDFData bsdfData, inout float3 result, inou float3 vsGeomNormal = TransformWorldToViewDir(bsdfData.geomNormalWS); result = IsNormalized(vsGeomNormal) ? vsGeomNormal * 0.5 + 0.5 : float3(1.0, 0.0, 0.0); break; - } + } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/HairRayTracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/HairRayTracing.hlsl index 96358e5e15c..46ec54c843f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/HairRayTracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/HairRayTracing.hlsl @@ -42,7 +42,7 @@ void FitToStandardLit( SurfaceData surfaceData , BuiltinData builtinData , uint2 positionSS , out StandardBSDFData outStandardlit) -{ +{ outStandardlit.baseColor = surfaceData.diffuseColor; outStandardlit.specularOcclusion = surfaceData.specularOcclusion; outStandardlit.normalWS = surfaceData.normalWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/LTCAreaLight.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/LTCAreaLight.cs index 110b8e4b3a5..8d9c9913ded 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/LTCAreaLight.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/LTCAreaLight.cs @@ -55,9 +55,9 @@ public static void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat f // Both GGX and Disney Diffuse BRDFs have zero values in columns 1, 3, 5, 7. // Column 8 contains only ones. pixels[i] = new Color(Mathf.Min(clampValue, (float)LUTTransformInv[i, 0]), - Mathf.Min(clampValue, (float)LUTTransformInv[i, 2]), - Mathf.Min(clampValue, (float)LUTTransformInv[i, 4]), - Mathf.Min(clampValue, (float)LUTTransformInv[i, 6])); + Mathf.Min(clampValue, (float)LUTTransformInv[i, 2]), + Mathf.Min(clampValue, (float)LUTTransformInv[i, 4]), + Mathf.Min(clampValue, (float)LUTTransformInv[i, 6])); } tex.SetPixels(pixels, arrayElement); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader index aec99daee1a..046ec642308 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader @@ -687,8 +687,8 @@ Shader "HDRP/LayeredLit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -736,8 +736,8 @@ Shader "HDRP/LayeredLit" #else #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitMotionVectorPass.hlsl" #endif - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -771,8 +771,8 @@ Shader "HDRP/LayeredLit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -824,8 +824,8 @@ Shader "HDRP/LayeredLit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl" #endif - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -903,8 +903,8 @@ Shader "HDRP/LayeredLit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl" #pragma vertex Vert #pragma fragment Frag diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader index 3cd90511e28..257875efed1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader @@ -529,7 +529,7 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Tessellation.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/FragInputs.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.cs.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.cs.hlsl" //------------------------------------------------------------------------------------- // variable declaration @@ -569,7 +569,7 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/PickingSpaceTransforms.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" @@ -603,8 +603,8 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -657,7 +657,7 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl" @@ -691,8 +691,8 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -732,8 +732,8 @@ Shader "HDRP/LayeredLitTessellation" #else #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitMotionVectorPass.hlsl" #endif - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl" // TODO: Tesselation can't work with velocity for now... #pragma vertex Vert @@ -763,8 +763,8 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -811,8 +811,8 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl" #endif - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -885,8 +885,8 @@ Shader "HDRP/LayeredLitTessellation" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl" #pragma vertex Vert #pragma fragment Frag diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.cs index 495a8be908c..9bc4aa1caed 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.cs @@ -238,13 +238,13 @@ public override void GetMaterialGBufferDescription(HDRenderPipelineAsset asset, enableWrite[3] = true; #if ENABLE_VIRTUALTEXTURES - int index = 4; - RTFormat[index] = VTBufferManager.GetFeedbackBufferFormat(); - gBufferUsage[index] = GBufferUsage.VTFeedback; - enableWrite[index] = false; - index++; + int index = 4; + RTFormat[index] = VTBufferManager.GetFeedbackBufferFormat(); + gBufferUsage[index] = GBufferUsage.VTFeedback; + enableWrite[index] = false; + index++; #else - int index = 4; + int index = 4; #endif if (supportLightLayers) @@ -264,7 +264,6 @@ public override void GetMaterialGBufferDescription(HDRenderPipelineAsset asset, } } - //----------------------------------------------------------------------------- // Init precomputed texture //----------------------------------------------------------------------------- diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl index d51a8def137..ef992a4f2fa 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl @@ -1016,7 +1016,7 @@ void GetBSDFDataDebug(uint paramId, BSDFData bsdfData, inout float3 result, inou float3 vsGeomNormal = TransformWorldToViewDir(bsdfData.geomNormalWS); result = IsNormalized(vsGeomNormal) ? vsGeomNormal * 0.5 + 0.5 : float3(1.0, 0.0, 0.0); break; - } + } case DEBUGVIEW_LIT_BSDFDATA_IOR: result = saturate((bsdfData.ior - 1.0) / 1.5).xxx; break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitDataIndividualLayer.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitDataIndividualLayer.hlsl index 8d6ef077aaa..39dc46d0f6d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitDataIndividualLayer.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitDataIndividualLayer.hlsl @@ -135,7 +135,7 @@ float3 ADD_IDX(GetNormalTS)(FragInputs input, LayerTexCoord layerTexCoord, float // This can happen with object space normal map not being set, but we still want detail map. // If we are tangent space, _NORMALMAP_IDX is always defined if we have _DETAIL_MAP_IDX. - #if defined(_DETAIL_MAP_IDX) + #if defined(_DETAIL_MAP_IDX) #ifdef SURFACE_GRADIENT normalTS += detailNormalTS * detailMask; #else @@ -207,14 +207,14 @@ float ADD_IDX(GetSurfaceData)(FragInputs input, LayerTexCoord layerTexCoord, out surfaceData.baseColor = color.rgb; float alpha = color.a; #ifdef _DETAIL_MAP_IDX - + // Goal: we want the detail albedo map to be able to darken down to black and brighten up to white the surface albedo. // The scale control the speed of the gradient. We simply remap detailAlbedo from [0..1] to [-1..1] then perform a lerp to black or white // with a factor based on speed. // For base color we interpolate in sRGB space (approximate here as square) as it get a nicer perceptual gradient float albedoDetailSpeed = saturate(abs(detailAlbedo) * ADD_IDX(_DetailAlbedoScale)); float3 baseColorOverlay = lerp(sqrt(surfaceData.baseColor), (detailAlbedo < 0.0) ? float3(0.0, 0.0, 0.0) : float3(1.0, 1.0, 1.0), albedoDetailSpeed * albedoDetailSpeed); - baseColorOverlay *= baseColorOverlay; + baseColorOverlay *= baseColorOverlay; // Lerp with details mask surfaceData.baseColor = lerp(surfaceData.baseColor, saturate(baseColorOverlay), detailMask); #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitProperties.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitProperties.hlsl index b5b7aeb9e6b..d20882376c4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitProperties.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitProperties.hlsl @@ -494,4 +494,3 @@ UNITY_DOTS_INSTANCING_END(MaterialPropertyMetadata) #endif #endif - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitConstantPass.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitConstantPass.hlsl index 33179936a42..9e8ec58fe71 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitConstantPass.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitConstantPass.hlsl @@ -3,4 +3,4 @@ #endif // This include will define the various Attributes/Varyings structure -#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VaryingMesh.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VaryingMesh.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl index 5833e86b947..e626affa0a1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl @@ -54,7 +54,7 @@ #define VARYINGS_NEED_COLOR #endif #elif defined(LOD_FADE_CROSSFADE) - #define VARYINGS_NEED_POSITION_WS // Required to get view vector use in cross fade effect + #define VARYINGS_NEED_POSITION_WS // Required to get view vector use in cross fade effect #endif #ifdef _DOUBLESIDED_ON diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl index e32d1b691d4..efd5d37400a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl @@ -34,9 +34,9 @@ float4 ApplyBlendMode(float3 diffuseLighting, float3 specularLighting, float opa opacity = 0; #ifndef _ALPHATEST_ON else - // We hardcode opacity to 1 to avoid issues in forward when alpha might be coming from the texture source, but we don't want to keep it in case alpha is preserved. + // We hardcode opacity to 1 to avoid issues in forward when alpha might be coming from the texture source, but we don't want to keep it in case alpha is preserved. opacity = 1; - #endif + #endif return float4(diffuseLighting + specularLighting, opacity); #else diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.cs index dfec42b6308..de8634e2ab4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.cs @@ -53,7 +53,7 @@ public void Build(FGDIndex index) var hdrp = HDRenderPipeline.defaultAsset; int res = (int)FGDTexture.Resolution; - switch(index) + switch (index) { case FGDIndex.FGD_GGXAndDisneyDiffuse: m_PreIntegratedFGDMaterial[(int)index] = CoreUtils.CreateEngineMaterial(hdrp.renderPipelineResources.shaders.preIntegratedFGD_GGXDisneyDiffusePS); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl index fdb13c6851a..0406cdf8cb2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl @@ -53,7 +53,7 @@ void GetPreIntegratedFGDCharlieAndFabricLambert(float NdotV, float perceptualRou preFGD.y = preFGD.y / (1 - preFGD.y); specularFGD = preFGD.yyy * fresnel0; - + // z = FabricLambert diffuseFGD = preFGD.z; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader index 8ca287228f8..822cb83081e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader @@ -19,7 +19,7 @@ Shader "Hidden/HDRP/preIntegratedFGD_GGXDisneyDiffuse" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.cs.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD.cs.hlsl" struct Attributes { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SharedRTManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SharedRTManager.cs index 8f1d4ca98e4..234cdbeb81d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SharedRTManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SharedRTManager.cs @@ -79,7 +79,7 @@ public void InitSharedBuffers(GBufferManager gbufferManager, RenderPipelineSetti m_CameraDepthBufferMipChainInfo.Allocate(); m_CameraDepthBufferMipChain = RTHandles.Alloc(ComputeDepthBufferMipChainSize, TextureXR.slices, colorFormat: GraphicsFormat.R32_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, name: "CameraDepthBufferMipChain"); - if(settings.lowresTransparentSettings.enabled) + if (settings.lowresTransparentSettings.enabled) { // Create the half res depth buffer used for low resolution transparency m_CameraHalfResDepthBuffer = RTHandles.Alloc(Vector2.one * 0.5f, TextureXR.slices, DepthBits.Depth32, dimension: TextureXR.dimension, useDynamicScale: true, name: "LowResDepthBuffer"); @@ -373,7 +373,7 @@ public void Build(HDRenderPipelineAsset hdAsset) public void AllocateCoarseStencilBuffer(int width, int height, int viewCount) { - if(width > 8 && height > 8) + if (width > 8 && height > 8) m_CoarseStencilBuffer = new ComputeBuffer(HDUtils.DivRoundUp(width, 8) * HDUtils.DivRoundUp(height, 8) * viewCount, sizeof(uint)); } @@ -424,7 +424,7 @@ public void Cleanup() RTHandles.Release(m_NormalMSAART); RTHandles.Release(m_DepthAsColorMSAART); - // Do not forget to release the materials + // Do not forget to release the materials CoreUtils.Destroy(m_DepthResolveMaterial); CoreUtils.Destroy(m_ColorResolveMaterial); CoreUtils.Destroy(m_MotionVectorResolve); @@ -446,11 +446,11 @@ public static int SampleCountToPassIndex(MSAASamples samples) return 2; case MSAASamples.MSAA8x: return 3; - }; + } + ; return 0; } - // Bind the normal buffer that is needed public void BindNormalBuffer(CommandBuffer cmd, bool isMSAA = false) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SphericalCapPivot/SPTDistribution.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/SphericalCapPivot/SPTDistribution.hlsl index d3337075575..b4d79531c00 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SphericalCapPivot/SPTDistribution.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SphericalCapPivot/SPTDistribution.hlsl @@ -42,7 +42,7 @@ float SphereCapSolidAngle(SphereCap c) // // SolidAngle( PivotTransform(sCap) ) / 4*PI // -// Integral of fitted GGX_projected is thus: +// Integral of fitted GGX_projected is thus: // // [ SolidAngle( PivotTransform(sCap) ) / 4*PI ] * FGD // @@ -50,18 +50,18 @@ float SphereCapSolidAngle(SphereCap c) // // Basis vectors b1, b2 and b3 arranged as rows, b3 = shading normal, // view vector lies in the b0-b2 plane. -// +// float3 ExtractPivot(float clampedNdotV, float perceptualRoughness, float3x3 orthoBasisViewNormal) { float theta = FastACosPos(clampedNdotV); float2 uv = PIVOT_LUT_OFFSET + PIVOT_LUT_SCALE * float2(perceptualRoughness, theta * INV_HALF_PI); - + float2 pivotParams = SAMPLE_TEXTURE2D_LOD(_PivotData, s_linear_clamp_sampler, uv, 0).rg; float pivotNorm = pivotParams.r; float pivotElev = pivotParams.g; float3 pivot = pivotNorm * float3(sin(pivotElev), 0, cos(pivotElev)); - // express the pivot in world space + // express the pivot in world space // (basis is left-mul WtoFrame rotation, so a right-mul FrameToW rotation) pivot = mul(pivot, orthoBasisViewNormal); @@ -84,10 +84,10 @@ float2 R2ToPR2(float2 pivotDir, float pivotMag) // be expressed in the same basis. SphereCap CapToPCap(SphereCap cap, float3 pivot) { - // Avoid instability between returning huge apertures to + // Avoid instability between returning huge apertures to // none when near these extremes (eg near 1.0, ie degenerate - // cap, depending on the pivot, we can get a cap of - // cos aperture near -1.0 or 1.0 ). See area calculation + // cap, depending on the pivot, we can get a cap of + // cos aperture near -1.0 or 1.0 ). See area calculation // below: we can clamp here, or test area later. cap.cosA = clamp(cap.cosA, -0.9999, 0.9999); @@ -131,17 +131,17 @@ SphereCap CapToPCap(SphereCap cap, float3 pivot) float2 dir1 = float2(a1 + a2, a3 - a4); // Rot(-aperture) (clockwise) float2 dir2 = float2(a1 - a2, a3 + a4); // Rot(+aperture) (counter clockwise) - // Pivot transform the original cap endpoints in the 2D plane + // Pivot transform the original cap endpoints in the 2D plane // to get the pivotCap endpoints: float2 dir1Xf = R2ToPR2(dir1, pivotMag); float2 dir2Xf = R2ToPR2(dir2, pivotMag); - // Compute the pivotCap 2D direction (note that the pivotCap + // Compute the pivotCap 2D direction (note that the pivotCap // direction is NOT the pivot transform of the original direction): - // It is the mean direction direction of the two pivotCap endpoints - // ie their half-vector, up to a sign. + // It is the mean direction direction of the two pivotCap endpoints + // ie their half-vector, up to a sign. // This sign is important, as a smaller than 90 degree aperture cap - // can, with the proper pivot, yield a cap with a much larger + // can, with the proper pivot, yield a cap with a much larger // aperture (ie covering more than an hemisphere). // float area = dir1Xf.x * dir2Xf.y - dir1Xf.y * dir2Xf.x; @@ -149,8 +149,8 @@ SphereCap CapToPCap(SphereCap cap, float3 pivot) float s = area >= 0.0 ? 1.0 : -1.0; float2 dirXf = s * normalize(dir1Xf + dir2Xf); - // Compute the 3D pivotCap parameters: - // Transform back the pivotCap endpoints into 3D and compute + // Compute the 3D pivotCap parameters: + // Transform back the pivotCap endpoints into 3D and compute // cosine of aperture. float3 pivotCapDir = dirXf.x * pivotDir + dirXf.y * pivotOrthoDir; float pivotCapCosA = dot(dirXf, dir1Xf); @@ -169,7 +169,7 @@ SphereCap CapToPCap(SphereCap cap, float3 pivot) // V becomes the cone ray-set indicator function. We have: // // Vs = Integral[ bsdf(w_i, w_o) (n dot w_i) dw_i ]_{over visibility cone} / FGD -// +// // We approximate the GGX bsdf() with an SPTD transformed from a uniform distribution // on the whole unit sphere S^2, and the integral thus becomes (see ExtractPivot) // @@ -177,7 +177,7 @@ SphereCap CapToPCap(SphereCap cap, float3 pivot) // = Integral[ Dstd(w_ii) dw_ii ]_{over g(visibility cone)} * normalization / FGD // // where normalization is as explained for ExtractPivot since the fit is up to that -// normalization, and here it is FGD; +// normalization, and here it is FGD; // g() is the pivot transform (ie CapToPCap), and w_ii := g(w_i) and here we use the // uniform Dstd(w) = 1/4pi. // @@ -198,9 +198,9 @@ SphereCap CapToPCap(SphereCap cap, float3 pivot) // limited to a hemisphere and even though the fit minimizes weight away from the // specular lobe, it can't aligned support. // -float ComputeVs(SphereCap visibleCap, - float clampedNdotV, - float perceptualRoughness, +float ComputeVs(SphereCap visibleCap, + float clampedNdotV, + float perceptualRoughness, float3x3 orthoBasisViewNormal, float useExtraCap = false, SphereCap extraCap = (SphereCap)0.0) @@ -216,7 +216,7 @@ float ComputeVs(SphereCap visibleCap, SphereCap c2 = CapToPCap(extraCap, pivot); res = SphericalCapIntersectionSolidArea(c1.cosA, c2.cosA, dot(c1.dir, c2.dir)); } - else + else { res = SphereCapSolidAngle(c1); } @@ -262,14 +262,14 @@ SphereCap GetBentVisibility(float3 bentNormalWS, float ambientOcclusion, int alg // Geometric Derivation of the Irradiance of Polygonal Lights - Heitz 2017 // https://hal.archives-ouvertes.fr/hal-01458129/document // p5 - // - // The formula below is derived from AO (aka Vd) being considered that + // + // The formula below is derived from AO (aka Vd) being considered that // projected solid angle (given the bent visibility assumption). // // (Note that Monte Carlo with IS would typically be used to sample the // visibility to compute the AO, and the IS rebalancing PDF ratio (weights) - // could then have been applied to the directions or not when calculating - // the bent cone direction. We don't do anything about that, but cone of + // could then have been applied to the directions or not when calculating + // the bent cone direction. We don't do anything about that, but cone of // visibility is a gross approximation anyway and can be pretty bad if its // shape on the hemisphere of directions is very segmented.) cosAv = sqrt(1.0 - saturate(ambientOcclusion/dot(bentNormalWS, normalWS)) ); @@ -407,11 +407,10 @@ float GetSpecularOcclusionFromBentAOConeCone(float3 V, float3 bentNormalWS, floa float HemiClippedReflectionLobeSolidAngle = SphericalCapIntersectionSolidArea(0.0, cosAs, cosB); #if 1 // Original, less expensive, but allow the cone approximation to go under horizon of full hemisphere - // and unecessarily dampens SO (ie more occlusion). + // and unecessarily dampens SO (ie more occlusion). return SphericalCapIntersectionSolidArea(cosAv, cosAs, cosB) / ReflectionLobeSolidAngle; #else // More correct, but more expensive: return saturate(SphericalCapIntersectionSolidArea(cosAv, cosAs, cosB) / HemiClippedReflectionLobeSolidAngle); #endif } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl index b075888907a..8bf42e1cb80 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl @@ -3851,7 +3851,7 @@ DirectLighting EvaluateBSDF_Line( LightLoopContext lightLoopContext, { localP1 = mul(P1, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX])); localP2 = mul(P2, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX])); - B = normalize(cross(localP1, localP2)); + B = normalize(cross(localP1, localP2)); } if (AREA_LIGHTS_ANISOTROPY_ENABLED) // statically known, so no need for if else, just overwrite the above { @@ -3884,7 +3884,7 @@ DirectLighting EvaluateBSDF_Line( LightLoopContext lightLoopContext, localP2 = mul(P2, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX])); if (AREA_LIGHTS_ANISOTROPY_ENABLED) { - // In that case orthoBasisViewNormal[] is per lobe due to anistropic hack, + // In that case orthoBasisViewNormal[] is per lobe due to anistropic hack, // use orthoBasisViewNormalDiffuse: localP1 = mul(P1, transpose(preLightData.orthoBasisViewNormalDiffuse)); localP2 = mul(P2, transpose(preLightData.orthoBasisViewNormalDiffuse)); @@ -3971,21 +3971,21 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, { lightData.diffuseDimmer *= intensity; lightData.specularDimmer *= intensity; - + // Translate the light s.t. the shaded point is at the origin of the coordinate system. lightData.positionRWS -= positionWS; - + float4x3 lightVerts; - + // TODO: some of this could be precomputed. lightVerts[0] = lightData.positionRWS + lightData.right * -halfWidth + lightData.up * -halfHeight; // LL lightVerts[1] = lightData.positionRWS + lightData.right * -halfWidth + lightData.up * halfHeight; // UL lightVerts[2] = lightData.positionRWS + lightData.right * halfWidth + lightData.up * halfHeight; // UR lightVerts[3] = lightData.positionRWS + lightData.right * halfWidth + lightData.up * -halfHeight; // LR - + // Rotate the endpoints into the local coordinate system. float4x3 localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX])); - + if (AREA_LIGHTS_ANISOTROPY_ENABLED) // statically known, so no need for if else, just overwrite the above { // Since we proceed with calculating diffuse and transmission irradiance, we setup @@ -3994,11 +3994,11 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, // the proper base layer normal: localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormalDiffuse)); } - + // Calculate the L irradiance (ltcValue) first for the diffuse part and transmission, // then for the specular base layer and finishing with the coat. float3 ltcValue; - + // Evaluate the diffuse part // Polygon irradiance in the transformed configuration. float4x3 LD = mul(localLightVerts, preLightData.ltcTransformDiffuse); @@ -4013,18 +4013,18 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, } // We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF(). lighting.diffuse = preLightData.diffuseFGD * preLightData.diffuseEnergy * ltcValue; - + UNITY_BRANCH if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION)) { // Flip the view vector and the normal. The bitangent stays the same. float3x3 flipMatrix = float3x3(-1, 0, 0, 0, 1, 0, 0, 0, -1); - + // Use the Lambertian approximation for performance reasons. // The matrix multiplication should not generate any extra ALU on GCN. float3x3 ltcTransform = mul(flipMatrix, k_identity3x3); - + // Polygon irradiance in the transformed configuration. // TODO: double evaluation is very inefficient! This is a temporary solution. float4x3 LTD = mul(localLightVerts, ltcTransform); @@ -4040,12 +4040,12 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, // VLAYERED_DIFFUSE_ENERGY_HACKED_TERM: // In Lit with Lambert, there's no diffuseFGD, it is one. In our case, we also // need a diffuse energy term when vlayered. - + // We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass. // We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF(). lighting.diffuse += bsdfData.transmittance * ltcValue * preLightData.diffuseEnergy; } - + // Evaluate the specular lobes for the stack IF_DEBUG( if ( _DebugLobeMask.y != 0.0) ) { @@ -4065,7 +4065,7 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, float3 formFactorAS = PolygonFormFactor(LAS); ltcValue *= SampleAreaLightCookie(lightData.cookieScaleOffset, LAS, formFactorAS); } - + // See EvaluateBSDF_Env TODOENERGY: lighting.specular += preLightData.energyCompensationFactor[BASE_LOBEA_IDX] * preLightData.specularFGD[BASE_LOBEA_IDX] * ltcValue; } @@ -4086,10 +4086,10 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, float3 formFactorS = PolygonFormFactor(LS); ltcValue *= SampleAreaLightCookie(lightData.cookieScaleOffset, LS, formFactorS); } - + lighting.specular += preLightData.energyCompensationFactor[BASE_LOBEB_IDX] * preLightData.specularFGD[BASE_LOBEB_IDX] * ltcValue; } - + if (IsVLayeredEnabled(bsdfData)) { if (IsCoatNormalMapEnabled(bsdfData)) @@ -4120,7 +4120,7 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, SHADOW_TYPE shadow = EvaluateShadow_RectArea(lightLoopContext, posInput, lightData, builtinData, bsdfData.normalWS, normalize(lightData.positionRWS), length(lightData.positionRWS)); lightData.color.rgb *= ComputeShadowColor(shadow, lightData.shadowTint, lightData.penumbraTint); - + // Save ALU by applying 'lightData.color' only once. lighting.diffuse *= lightData.color; lighting.specular *= lightData.color; @@ -4132,7 +4132,7 @@ DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext, localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX])); if (AREA_LIGHTS_ANISOTROPY_ENABLED) { - // In that case orthoBasisViewNormal[] is per lobe due to anistropic hack, + // In that case orthoBasisViewNormal[] is per lobe due to anistropic hack, // use orthoBasisViewNormalDiffuse: localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormalDiffuse)); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitRayTracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitRayTracing.hlsl index 9f5445f31f6..b99b75e4c18 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitRayTracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitRayTracing.hlsl @@ -73,7 +73,7 @@ void FitToStandardLit( SurfaceData surfaceData , BuiltinData builtinData , uint2 positionSS , out StandardBSDFData outStandardlit) -{ +{ outStandardlit.baseColor = surfaceData.baseColor; outStandardlit.specularOcclusion = surfaceData.specularOcclusionCustomInput; outStandardlit.normalWS = surfaceData.normalWS; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/StandardLit/StandardLit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/StandardLit/StandardLit.hlsl index 8268b4bc13e..c56277bb808 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/StandardLit/StandardLit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/StandardLit/StandardLit.hlsl @@ -9,16 +9,16 @@ void EncodeIntoStandardGBuffer( StandardBSDFData standardBSDFData , out GBufferType3 outGBuffer3 ) { - // GBuffer0 + // GBuffer0 outGBuffer0 = float4(standardBSDFData.baseColor, standardBSDFData.specularOcclusion); - // GBuffer1 + // GBuffer1 NormalData normalData; normalData.normalWS = standardBSDFData.normalWS; normalData.perceptualRoughness = standardBSDFData.perceptualRoughness; EncodeIntoNormalBuffer(normalData, outGBuffer1); - // GBuffer2 + // GBuffer2 outGBuffer2.rgb = FastLinearToSRGB(standardBSDFData.fresnel0); outGBuffer2.a = PackFloatInt8bit(standardBSDFData.coatMask, GBUFFER_LIT_STANDARD, 8); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader index 178f7ad994a..7f30d70da24 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader @@ -55,12 +55,12 @@ Shader "Hidden/HDRP/CombineLighting" } Cull Off - ZTest Less // Required for XR occlusion mesh optimization + ZTest Less // Required for XR occlusion mesh optimization ZWrite Off Blend One One // Additive HLSLPROGRAM - + float4 Frag(Varyings input) : SV_Target { UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs index 6e3a9da25e3..208cda9ef92 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManager.cs @@ -49,7 +49,7 @@ void InitSSSBuffers() // We need to allocate the texture if we are in forward or both in case one of the cameras is in enable forward only mode if (settings.supportMSAA && settings.supportedLitShaderMode != RenderPipelineSettings.SupportedLitShaderMode.DeferredOnly) { - m_SSSColorMSAA = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8B8A8_SRGB, dimension: TextureXR.dimension, enableMSAA: true, bindTextureMS: true, useDynamicScale: true, name: "SSSBufferMSAA"); + m_SSSColorMSAA = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R8G8B8A8_SRGB, dimension: TextureXR.dimension, enableMSAA: true, bindTextureMS: true, useDynamicScale: true, name: "SSSBufferMSAA"); } if ((settings.supportedLitShaderMode & RenderPipelineSettings.SupportedLitShaderMode.DeferredOnly) != 0) //deferred or both @@ -248,7 +248,7 @@ SubsurfaceScatteringParameters PrepareSubsurfaceScatteringParameters(HDCamera hd parameters.subsurfaceScatteringCS = m_SubsurfaceScatteringCS; parameters.subsurfaceScatteringCS.shaderKeywords = null; - if(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)) { m_SubsurfaceScatteringCS.EnableKeyword("ENABLE_MSAA"); } @@ -265,14 +265,13 @@ SubsurfaceScatteringParameters PrepareSubsurfaceScatteringParameters(HDCamera hd return parameters; } - void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle colorBufferRT, RTHandle diffuseBufferRT, RTHandle depthStencilBufferRT, RTHandle depthTextureRT, RTHandle normalBuffer) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) return; - BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd, resolveOnly:false); + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd, resolveOnly: false); var settings = hdCamera.volumeStack.GetComponent(); @@ -310,7 +309,6 @@ void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle c } } - // Combines specular lighting and diffuse lighting with subsurface scattering. // In the case our frame is MSAA, for the moment given the fact that we do not have read/write access to the stencil buffer of the MSAA target; we need to keep this pass MSAA // However, the compute can't output and MSAA target so we blend the non-MSAA target into the MSAA one. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManagerRT.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManagerRT.cs index 94258344602..8084cd357fc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManagerRT.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScatteringManagerRT.cs @@ -19,8 +19,8 @@ public partial class HDRenderPipeline static RTHandle SubSurfaceHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: string.Format("{0}_SubSurfaceHistoryBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: string.Format("{0}_SubSurfaceHistoryBuffer{1}", viewName, frameIndex)); } void InitializeSubsurfaceScatteringRT() @@ -36,7 +36,6 @@ void InitializeSubsurfaceScatteringRT() void CleanupSubsurfaceScatteringRT() { - } struct SSSRayTracingParameters @@ -111,9 +110,9 @@ struct SSSRayTracingResources } SSSRayTracingResources PrepareSSSRayTracingResources(RTHandle sssColor, - RTHandle intermediateBuffer0, RTHandle intermediateBuffer1, - RTHandle intermediateBuffer2, RTHandle intermediateBuffer3, - RTHandle directionBuffer, RTHandle outputBuffer) + RTHandle intermediateBuffer0, RTHandle intermediateBuffer1, + RTHandle intermediateBuffer2, RTHandle intermediateBuffer3, + RTHandle directionBuffer, RTHandle outputBuffer) { SSSRayTracingResources sssrtResources = new SSSRayTracingResources(); @@ -288,7 +287,7 @@ static void ExecuteCombineSubsurfaceScattering(CommandBuffer cmd, SSSCombinePara RTHandle RequestRayTracedSSSHistoryTexture(HDCamera hdCamera) { return hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface) - ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface, SubSurfaceHistoryBufferAllocatorFunction, 1); + ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface, SubSurfaceHistoryBufferAllocatorFunction, 1); } void RenderSubsurfaceScatteringRT(HDCamera hdCamera, CommandBuffer cmd, RTHandle colorBufferRT, @@ -310,9 +309,9 @@ void RenderSubsurfaceScatteringRT(HDCamera hdCamera, CommandBuffer cmd, RTHandle // Evaluate the lighting for the samples that we need to SSSRayTracingParameters sssrtParams = PrepareSSSRayTracingParameters(hdCamera, settings); SSSRayTracingResources sssrtResources = PrepareSSSRayTracingResources(m_SSSColor, - intermediateBuffer0, intermediateBuffer1, - intermediateBuffer2, intermediateBuffer3, directionBuffer, - intermediateBuffer4); + intermediateBuffer0, intermediateBuffer1, + intermediateBuffer2, intermediateBuffer3, directionBuffer, + intermediateBuffer4); ExecuteRTSubsurfaceScattering(cmd, sssrtParams, sssrtResources); // Grab the history buffer @@ -370,34 +369,34 @@ TextureHandle TraceRTSSS(RenderGraph renderGraph, HDCamera hdCamera, TextureHand passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.sssColor = builder.ReadTexture(sssColor); passData.intermediateBuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 0" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 0" }); passData.intermediateBuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 1" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 1" }); passData.intermediateBuffer2 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 2" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 2" }); passData.intermediateBuffer3 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 3" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate Texture 3" }); passData.directionBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Distance buffer" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Distance buffer" }); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced SSS" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced SSS" })); builder.SetRenderFunc( - (TraceRTSSSPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - SSSRayTracingResources ssstResources = new SSSRayTracingResources(); - ssstResources.depthStencilBuffer = data.depthStencilBuffer; - ssstResources.normalBuffer = data.normalBuffer; - ssstResources.sssColor = data.sssColor; - ssstResources.intermediateBuffer0 = data.intermediateBuffer0; - ssstResources.intermediateBuffer1 = data.intermediateBuffer1; - ssstResources.intermediateBuffer2 = data.intermediateBuffer2; - ssstResources.intermediateBuffer3 = data.intermediateBuffer3; - ssstResources.directionBuffer = data.directionBuffer; - ssstResources.outputBuffer = data.outputBuffer; - ExecuteRTSubsurfaceScattering(ctx.cmd, data.parameters, ssstResources); - }); + (TraceRTSSSPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + SSSRayTracingResources ssstResources = new SSSRayTracingResources(); + ssstResources.depthStencilBuffer = data.depthStencilBuffer; + ssstResources.normalBuffer = data.normalBuffer; + ssstResources.sssColor = data.sssColor; + ssstResources.intermediateBuffer0 = data.intermediateBuffer0; + ssstResources.intermediateBuffer1 = data.intermediateBuffer1; + ssstResources.intermediateBuffer2 = data.intermediateBuffer2; + ssstResources.intermediateBuffer3 = data.intermediateBuffer3; + ssstResources.directionBuffer = data.directionBuffer; + ssstResources.outputBuffer = data.outputBuffer; + ExecuteRTSubsurfaceScattering(ctx.cmd, data.parameters, ssstResources); + }); return passData.outputBuffer; } @@ -441,26 +440,26 @@ TextureHandle CombineRTSSS(RenderGraph renderGraph, HDCamera hdCamera, TextureHa passData.colorBuffer = builder.ReadTexture(builder.WriteTexture(colorBuffer)); builder.SetRenderFunc( - (ComposeRTSSSPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - SSSCombineResources ssscResources = new SSSCombineResources(); - ssscResources.depthStencilBuffer = data.depthStencilBuffer; - ssscResources.sssColor = data.sssColor; - ssscResources.ssgiBuffer = data.ssgiBuffer; - ssscResources.diffuseLightingBuffer = data.diffuseLightingBuffer; - ssscResources.subsurfaceBuffer = data.subsurfaceBuffer; - ssscResources.outputColorBuffer = data.colorBuffer; - ExecuteCombineSubsurfaceScattering(ctx.cmd, data.parameters, ssscResources); - }); + (ComposeRTSSSPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + SSSCombineResources ssscResources = new SSSCombineResources(); + ssscResources.depthStencilBuffer = data.depthStencilBuffer; + ssscResources.sssColor = data.sssColor; + ssscResources.ssgiBuffer = data.ssgiBuffer; + ssscResources.diffuseLightingBuffer = data.diffuseLightingBuffer; + ssscResources.subsurfaceBuffer = data.subsurfaceBuffer; + ssscResources.outputColorBuffer = data.colorBuffer; + ExecuteCombineSubsurfaceScattering(ctx.cmd, data.parameters, ssscResources); + }); return passData.colorBuffer; } } TextureHandle RenderSubsurfaceScatteringRT(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthStencilBuffer, TextureHandle normalBuffer, TextureHandle colorBuffer, - TextureHandle sssColor, TextureHandle diffuseBuffer, TextureHandle motionVectorsBuffer, TextureHandle ssgiBuffer) + TextureHandle depthStencilBuffer, TextureHandle normalBuffer, TextureHandle colorBuffer, + TextureHandle sssColor, TextureHandle diffuseBuffer, TextureHandle motionVectorsBuffer, TextureHandle ssgiBuffer) { using (new RenderGraphProfilingScope(renderGraph, ProfilingSampler.Get(HDProfileId.RaytracingSSS))) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader index 418d4dc4b0d..211a009f207 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader @@ -35,7 +35,7 @@ Shader "HDRP/TerrainLit" [ToggleUI] _EnableInstancedPerPixelNormal("Instanced per pixel normal", Float) = 1.0 - [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} + [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} // Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor" // value that exist to identify if the GI emission need to be enabled. @@ -80,7 +80,7 @@ Shader "HDRP/TerrainLit" #pragma multi_compile_instancing #pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap - #pragma multi_compile _ _ALPHATEST_ON + #pragma multi_compile _ _ALPHATEST_ON // All our shaders use same name for entry point #pragma vertex Vert diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitData.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitData.hlsl index 8a65550acff..87d73c91f68 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitData.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitData.hlsl @@ -61,8 +61,8 @@ SAMPLER(sampler_TerrainHolesTexture); void ClipHoles(float2 uv) { - float hole = SAMPLE_TEXTURE2D(_TerrainHolesTexture, sampler_TerrainHolesTexture, uv).r; - DoAlphaTest(hole, 0.5); + float hole = SAMPLE_TEXTURE2D(_TerrainHolesTexture, sampler_TerrainHolesTexture, uv).r; + DoAlphaTest(hole, 0.5); } #endif @@ -159,8 +159,8 @@ void GetSurfaceAndBuiltinData(inout FragInputs input, float3 V, inout PositionIn #endif #ifdef _ALPHATEST_ON - ClipHoles(input.texCoord0.xy); -#endif + ClipHoles(input.texCoord0.xy); +#endif // terrain lightmap uvs are always taken from uv0 input.texCoord1 = input.texCoord2 = input.texCoord0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl index bafa0278633..857c4ffeb27 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl @@ -1,4 +1,4 @@ -#define HAVE_MESH_MODIFICATION +#define HAVE_MESH_MODIFICATION #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/FragInputs.hlsl" @@ -17,8 +17,8 @@ #endif #if defined(_ALPHATEST_ON) - #define ATTRIBUTES_NEED_TEXCOORD0 - #define VARYINGS_NEED_TEXCOORD0 + #define ATTRIBUTES_NEED_TEXCOORD0 + #define VARYINGS_NEED_TEXCOORD0 #endif #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader index 30bc04f7250..596c8dba2db 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader @@ -21,7 +21,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap" [HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal [HideInInspector] _ZTestGBuffer("_ZTestGBuffer", Int) = 4 - [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} + [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} // Caution: C# code in BaseLitUI.cs call LightmapEmissionFlagsProperty() which assume that there is an existing "_EmissionColor" // value that exist to identify if the GI emission need to be enabled. @@ -51,7 +51,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap" #pragma multi_compile_instancing #pragma instancing_options assumeuniformscaling nomatrices nolightprobe nolightmap - #pragma multi_compile _ _ALPHATEST_ON + #pragma multi_compile _ _ALPHATEST_ON #pragma vertex Vert #pragma fragment Frag diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap.hlsl index 77009b4b6d1..f90eb81cbe9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap.hlsl @@ -184,12 +184,12 @@ void TerrainSplatBlend(float2 controlUV, float2 splatBaseUV, inout TerrainLitSur #elif defined(_TERRAIN_BLEND_DENSITY) // Denser layers are more visible. float4 opacityAsDensity0 = saturate((float4(albedo[0].a, albedo[1].a, albedo[2].a, albedo[3].a) - (float4(1.0, 1.0, 1.0, 1.0) - blendMasks0)) * 20.0); // 20.0 is the number of steps in inputAlphaMask (Density mask. We decided 20 empirically) - opacityAsDensity0 += 0.001f * blendMasks0; // if all weights are zero, default to what the blend mask says + opacityAsDensity0 += 0.001f * blendMasks0; // if all weights are zero, default to what the blend mask says float4 useOpacityAsDensityParam0 = { _DiffuseRemapScale0.w, _DiffuseRemapScale1.w, _DiffuseRemapScale2.w, _DiffuseRemapScale3.w }; // 1 is off blendMasks0 = lerp(opacityAsDensity0, blendMasks0, useOpacityAsDensityParam0); #ifdef _TERRAIN_8_LAYERS float4 opacityAsDensity1 = saturate((float4(albedo[4].a, albedo[5].a, albedo[6].a, albedo[7].a) - (float4(1.0, 1.0, 1.0, 1.0) - blendMasks1)) * 20.0); // 20.0 is the number of steps in inputAlphaMask (Density mask. We decided 20 empirically) - opacityAsDensity1 += 0.001f * blendMasks1; // if all weights are zero, default to what the blend mask says + opacityAsDensity1 += 0.001f * blendMasks1; // if all weights are zero, default to what the blend mask says float4 useOpacityAsDensityParam1 = { _DiffuseRemapScale4.w, _DiffuseRemapScale5.w, _DiffuseRemapScale6.w, _DiffuseRemapScale7.w }; blendMasks1 = lerp(opacityAsDensity1, blendMasks1, useOpacityAsDensityParam1); #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader b/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader index 9874e7593f2..64197367440 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader @@ -221,9 +221,9 @@ Shader "HDRP/Unlit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitDepthPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitDepthPass.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -276,8 +276,8 @@ Shader "HDRP/Unlit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -324,8 +324,8 @@ Shader "HDRP/Unlit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForwardUnlit.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -358,8 +358,8 @@ Shader "HDRP/Unlit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitSharePass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl" #pragma vertex Vert #pragma fragment Frag @@ -391,7 +391,7 @@ Shader "HDRP/Unlit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitDepthPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl" #pragma vertex Vert @@ -431,8 +431,8 @@ Shader "HDRP/Unlit" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/ShaderPass/UnlitDistortionPass.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDistortion.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDistortion.hlsl" #pragma vertex Vert #pragma fragment Frag diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl index 03d564563f1..ac85f5a1abf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitData.hlsl @@ -26,7 +26,7 @@ void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs p // Builtin Data ZERO_INITIALIZE(BuiltinData, builtinData); // No call to InitBuiltinData as we don't have any lighting builtinData.opacity = alpha; - + #ifdef _ALPHATEST_ON // Used for sharpening by alpha to mask builtinData.alphaClipTreshold = _AlphaCutoff; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitRaytracing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitRaytracing.hlsl index 89a044132dd..812dd54fa24 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitRaytracing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/UnlitRaytracing.hlsl @@ -8,7 +8,7 @@ void FitToStandardLit( SurfaceData surfaceData { ZERO_INITIALIZE(StandardBSDFData, outStandardlit); - + // Output is not to be lit outStandardlit.emissiveAndBaked = surfaceData.color * GetInverseCurrentExposureMultiplier() + builtinData.emissiveColor; outStandardlit.isUnlit = 1; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Material/VTBufferManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Material/VTBufferManager.cs index d5fec43b3a3..7533c7efb6b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Material/VTBufferManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Material/VTBufferManager.cs @@ -9,7 +9,6 @@ class VTBufferManager { public static TextureHandle CreateVTFeedbackBuffer(RenderGraph renderGraph, bool msaa) { - #if UNITY_2020_2_OR_NEWER FastMemoryDesc colorFastMemDesc; colorFastMemDesc.inFastMemory = true; @@ -125,11 +124,11 @@ public void Resolve(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle in passData.lowres = builder.WriteTexture(renderGraph.ImportTexture(m_LowresResolver)); builder.SetRenderFunc( - (ResolveVTData data, RenderGraphContext ctx) => - { - ResolveVTDispatch(data.parameters, ctx.cmd, data.input, data.lowres); - VirtualTexturing.System.Update(); - }); + (ResolveVTData data, RenderGraphContext ctx) => + { + ResolveVTDispatch(data.parameters, ctx.cmd, data.input, data.lowres); + VirtualTexturing.System.Update(); + }); } } } @@ -172,7 +171,7 @@ static void ResolveVTDispatch(in ResolveVTParameters parameters, CommandBuffer c var resolveCounter = 0; var startOffsetX = (resolveCounter % kResolveScaleFactor); var startOffsetY = (resolveCounter / kResolveScaleFactor) % kResolveScaleFactor; - cmd.SetComputeVectorParam(parameters.downsampleCS, HDShaderIDs._Params, new Vector4(kResolveScaleFactor, startOffsetX, startOffsetY, /*unused*/-1)); + cmd.SetComputeVectorParam(parameters.downsampleCS, HDShaderIDs._Params, new Vector4(kResolveScaleFactor, startOffsetX, startOffsetY, /*unused*/ -1)); cmd.SetComputeVectorParam(parameters.downsampleCS, HDShaderIDs._Params1, new Vector4(parameters.width, parameters.height, parameters.lowresWidth, parameters.lowresHeight)); var TGSize = 8; //Match shader cmd.DispatchCompute(parameters.downsampleCS, parameters.downsampleKernel, ((int)parameters.lowresWidth + (TGSize - 1)) / TGSize, ((int)parameters.lowresHeight + (TGSize - 1)) / TGSize, 1); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PackageInfo.cs b/com.unity.render-pipelines.high-definition/Runtime/PackageInfo.cs index 7455e43fd6a..d67ccdb3eed 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PackageInfo.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PackageInfo.cs @@ -3,4 +3,4 @@ [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition-Tests.Runtime")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition-Tests.Editor")] [assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.HDRP.Runtime")] -[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.HDRP.Editor")] \ No newline at end of file +[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.HDRP.Editor")] diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Bloom.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Bloom.cs index d642e9b0f58..8eb56e86732 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Bloom.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Bloom.cs @@ -164,6 +164,6 @@ public sealed class BloomResolutionParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public BloomResolutionParameter(BloomResolution value, bool overrideState = false) : base(value, overrideState) { } + public BloomResolutionParameter(BloomResolution value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/DepthOfField.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/DepthOfField.cs index 2fbe254e642..a418592494e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/DepthOfField.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/DepthOfField.cs @@ -316,7 +316,7 @@ public sealed class DepthOfFieldModeParameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. - public DepthOfFieldModeParameter(DepthOfFieldMode value, bool overrideState = false) : base(value, overrideState) { } + public DepthOfFieldModeParameter(DepthOfFieldMode value, bool overrideState = false) : base(value, overrideState) {} } /// @@ -330,6 +330,6 @@ public sealed class DepthOfFieldResolutionParameter : VolumeParameter /// The initial value to store in the parameter. /// The initial override state for the parameter. - public DepthOfFieldResolutionParameter(DepthOfFieldResolution value, bool overrideState = false) : base(value, overrideState) { } + public DepthOfFieldResolutionParameter(DepthOfFieldResolution value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Exposure.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Exposure.cs index f498b023b5e..4f44b8f0080 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Exposure.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Exposure.cs @@ -237,8 +237,6 @@ public enum MeteringMode /// Create a weight mask centered around the specified UV and with the desired parameters. /// ProceduralMask, - - } /// @@ -329,7 +327,7 @@ public sealed class MeteringModeParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public MeteringModeParameter(MeteringMode value, bool overrideState = false) : base(value, overrideState) { } + public MeteringModeParameter(MeteringMode value, bool overrideState = false) : base(value, overrideState) {} } /// @@ -371,6 +369,6 @@ public sealed class TargetMidGrayParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public TargetMidGrayParameter(TargetMidGray value, bool overrideState = false) : base(value, overrideState) { } + public TargetMidGrayParameter(TargetMidGray value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/FilmGrain.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/FilmGrain.cs index 1ef678988d3..133eb73a7a5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/FilmGrain.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/FilmGrain.cs @@ -119,6 +119,6 @@ public sealed class FilmGrainLookupParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public FilmGrainLookupParameter(FilmGrainLookup value, bool overrideState = false) : base(value, overrideState) { } + public FilmGrainLookupParameter(FilmGrainLookup value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/MotionBlur.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/MotionBlur.cs index 027edfc5e83..9b390a89df4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/MotionBlur.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/MotionBlur.cs @@ -3,7 +3,6 @@ namespace UnityEngine.Rendering.HighDefinition { - /// /// Determine how the component of the motion vectors coming from the camera are clamped. /// @@ -46,7 +45,7 @@ public sealed class CameraClampModeParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public CameraClampModeParameter(CameraClampMode value, bool overrideState = false) : base(value, overrideState) { } + public CameraClampModeParameter(CameraClampMode value, bool overrideState = false) : base(value, overrideState) {} } /// @@ -83,7 +82,7 @@ public sealed class MotionBlur : VolumeComponentWithQuality, IPostProcessCompone /// /// Determine how the component of the motion vectors coming from the camera is clamped. It is important to remember that clamping the camera component separately, velocities relative to camera might change too (e.g. an object parented to a camera - /// when the camera moves might not have a 0 motion vector anymore). + /// when the camera moves might not have a 0 motion vector anymore). /// [Tooltip("Determine if and how the component of the motion vectors coming from the camera is clamped in a special fashion.")] public CameraClampModeParameter specialCameraClampMode = new CameraClampModeParameter(CameraClampMode.None); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Tonemapping.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Tonemapping.cs index 9e8f10eb717..db8003d210d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Tonemapping.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Tonemapping.cs @@ -141,12 +141,12 @@ public bool ValidateLUT() { case Texture3D t: valid |= t.width == t.height - && t.height == t.depth; + && t.height == t.depth; break; case RenderTexture rt: valid |= rt.dimension == TextureDimension.Tex3D - && rt.width == rt.height - && rt.height == rt.volumeDepth; + && rt.width == rt.height + && rt.height == rt.volumeDepth; break; } @@ -165,6 +165,6 @@ public sealed class TonemappingModeParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public TonemappingModeParameter(TonemappingMode value, bool overrideState = false) : base(value, overrideState) { } + public TonemappingModeParameter(TonemappingMode value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Vignette.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Vignette.cs index 021d605c8f5..085694a0b24 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Vignette.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/Vignette.cs @@ -103,6 +103,6 @@ public sealed class VignetteModeParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public VignetteModeParameter(VignetteMode value, bool overrideState = false) : base(value, overrideState) { } + public VignetteModeParameter(VignetteMode value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/CustomPostProcessing/CustomPostProcessInjectionPoint.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/CustomPostProcessing/CustomPostProcessInjectionPoint.cs index 911b2ca484b..90bccb3ee05 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/CustomPostProcessing/CustomPostProcessInjectionPoint.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/CustomPostProcessing/CustomPostProcessInjectionPoint.cs @@ -14,4 +14,4 @@ public enum CustomPostProcessInjectionPoint /// After Post Processing. AfterPostProcess = 2, } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs index 13ba503aa58..d058e1dd5f7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.RenderGraph.cs @@ -5,7 +5,6 @@ namespace UnityEngine.Rendering.HighDefinition { - partial class PostProcessSystem { class ColorGradingPassData @@ -184,13 +183,12 @@ void FillBloomMipsTextureHandles(BloomData bloomData, RenderGraph renderGraph, R var pixelSize = new Vector2Int((int)m_BloomMipsInfo[i].x, (int)m_BloomMipsInfo[i].y); bloomData.mipsDown[i] = builder.CreateTransientTexture(new TextureDesc(scale, true, true) - { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "BloomMipDown" }); + { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "BloomMipDown" }); if (i != 0) { bloomData.mipsUp[i] = builder.CreateTransientTexture(new TextureDesc(scale, true, true) - { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "BloomMipUp" }); - + { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "BloomMipUp" }); } } @@ -215,13 +213,13 @@ TextureHandle DoCopyAlpha(RenderGraph renderGraph, HDCamera hdCamera, TextureHan passData.parameters = PrepareCopyAlphaParameters(hdCamera); passData.source = builder.ReadTexture(source); passData.outputAlpha = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { name = "Alpha Channel Copy", colorFormat = GraphicsFormat.R16_SFloat, enableRandomWrite = true })); + { name = "Alpha Channel Copy", colorFormat = GraphicsFormat.R16_SFloat, enableRandomWrite = true })); builder.SetRenderFunc( - (AlphaCopyPassData data, RenderGraphContext ctx) => - { - DoCopyAlpha(data.parameters, data.source, data.outputAlpha, ctx.cmd); - }); + (AlphaCopyPassData data, RenderGraphContext ctx) => + { + DoCopyAlpha(data.parameters, data.source, data.outputAlpha, ctx.cmd); + }); return passData.outputAlpha; } @@ -247,13 +245,13 @@ TextureHandle StopNaNsPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHa passData.source = builder.ReadTexture(source); passData.parameters = PrepareStopNaNParameters(hdCamera); TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "Stop NaNs Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (StopNaNPassData data, RenderGraphContext ctx) => - { - DoStopNaNs(data.parameters, ctx.cmd, data.source, data.destination); - }); + (StopNaNPassData data, RenderGraphContext ctx) => + { + DoStopNaNs(data.parameters, ctx.cmd, data.source, data.destination); + }); return passData.destination; } @@ -289,26 +287,26 @@ TextureHandle DynamicExposurePass(RenderGraph renderGraph, HDCamera hdCamera, Te (DynamicExposureData data, RenderGraphContext ctx) => { DoHistogramBasedExposure(data.parameters, ctx.cmd, data.source, - data.prevExposure, - data.nextExposure, - data.exposureDebugData); + data.prevExposure, + data.nextExposure, + data.exposureDebugData); }); } else { passData.tmpTarget1024 = builder.CreateTransientTexture(new TextureDesc(1024, 1024, true, false) - { colorFormat = GraphicsFormat.R16G16_SFloat, enableRandomWrite = true, name = "Average Luminance Temp 1024" }); + { colorFormat = GraphicsFormat.R16G16_SFloat, enableRandomWrite = true, name = "Average Luminance Temp 1024" }); passData.tmpTarget32 = builder.CreateTransientTexture(new TextureDesc(32, 32, true, false) - { colorFormat = GraphicsFormat.R16G16_SFloat, enableRandomWrite = true, name = "Average Luminance Temp 32" }); + { colorFormat = GraphicsFormat.R16G16_SFloat, enableRandomWrite = true, name = "Average Luminance Temp 32" }); builder.SetRenderFunc( (DynamicExposureData data, RenderGraphContext ctx) => { DoDynamicExposure(data.parameters, ctx.cmd, data.source, - data.prevExposure, - data.nextExposure, - data.tmpTarget1024, - data.tmpTarget32); + data.prevExposure, + data.nextExposure, + data.tmpTarget1024, + data.tmpTarget32); }); } } @@ -324,13 +322,13 @@ TextureHandle DynamicExposurePass(RenderGraph renderGraph, HDCamera hdCamera, Te passData.prevExposure = builder.ReadTexture(renderGraph.ImportTexture(prevExp)); TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "Apply Exposure Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (ApplyExposureData data, RenderGraphContext ctx) => - { - ApplyExposure(data.parameters, ctx.cmd, data.source, data.destination, data.prevExposure); - }); + (ApplyExposureData data, RenderGraphContext ctx) => + { + ApplyExposure(data.parameters, ctx.cmd, data.source, data.destination, data.prevExposure); + }); source = passData.destination; } @@ -362,21 +360,21 @@ TextureHandle DoTemporalAntialiasing(RenderGraph renderGraph, HDCamera hdCamera, passData.nextMVLen = builder.WriteTexture(renderGraph.ImportTexture(nextMVLen)); TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "TAA Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (TemporalAntiAliasingData data, RenderGraphContext ctx) => - { - DoTemporalAntialiasing(data.parameters, ctx.cmd, data.source, - data.destination, - data.motionVecTexture, - data.depthBuffer, - data.depthMipChain, - data.prevHistory, - data.nextHistory, - data.prevMVLen, - data.nextMVLen); - }); + (TemporalAntiAliasingData data, RenderGraphContext ctx) => + { + DoTemporalAntialiasing(data.parameters, ctx.cmd, data.source, + data.destination, + data.motionVecTexture, + data.depthBuffer, + data.depthMipChain, + data.prevHistory, + data.nextHistory, + data.prevMVLen, + data.nextMVLen); + }); source = passData.destination; } @@ -393,22 +391,22 @@ TextureHandle SMAAPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle builder.ReadTexture(depthBuffer); passData.depthBuffer = builder.WriteTexture(depthBuffer); passData.smaaEdgeTex = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "SMAA Edge Texture" }); + { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "SMAA Edge Texture" }); passData.smaaBlendTex = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "SMAA Blend Texture" }); + { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "SMAA Blend Texture" }); TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "SMAA Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (SMAAData data, RenderGraphContext ctx) => - { - DoSMAA(data.parameters, ctx.cmd, data.source, - data.smaaEdgeTex, - data.smaaBlendTex, - data.destination, - data.depthBuffer); - }); + (SMAAData data, RenderGraphContext ctx) => + { + DoSMAA(data.parameters, ctx.cmd, data.source, + data.smaaEdgeTex, + data.smaaBlendTex, + data.destination, + data.depthBuffer); + }); source = passData.destination; } @@ -424,9 +422,9 @@ TextureHandle DepthOfFieldPass(RenderGraph renderGraph, HDCamera hdCamera, Textu // If Path tracing is enabled, then DoF is computed in the path tracer by sampling the lens aperure (when using the physical camera mode) bool isDoFPathTraced = (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && - hdCamera.volumeStack.GetComponent().enable.value && - hdCamera.camera.cameraType != CameraType.Preview && - m_DepthOfField.focusMode == DepthOfFieldMode.UsePhysicalCamera); + hdCamera.volumeStack.GetComponent().enable.value && + hdCamera.camera.cameraType != CameraType.Preview && + m_DepthOfField.focusMode == DepthOfFieldMode.UsePhysicalCamera); // Depth of Field is done right after TAA as it's easier to just re-project the CoC // map rather than having to deal with all the implications of doing it before TAA @@ -467,20 +465,19 @@ TextureHandle DepthOfFieldPass(RenderGraph renderGraph, HDCamera hdCamera, Textu if (passData.parameters.nearLayerActive) { passData.pingNearRGB = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "Ping Near RGB" }); + { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "Ping Near RGB" }); passData.pongNearRGB = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "Pong Near RGB" }); + { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "Pong Near RGB" }); passData.nearCoC = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Near CoC" }); + { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Near CoC" }); passData.nearAlpha = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Near Alpha" }); + { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Near Alpha" }); passData.dilatedNearCoC = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Dilated Near CoC" }); - + { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Dilated Near CoC" }); } else { @@ -494,13 +491,13 @@ TextureHandle DepthOfFieldPass(RenderGraph renderGraph, HDCamera hdCamera, Textu if (passData.parameters.farLayerActive) { passData.pingFarRGB = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = m_ColorFormat, useMipMap = true, enableRandomWrite = true, name = "Ping Far RGB" }); + { colorFormat = m_ColorFormat, useMipMap = true, enableRandomWrite = true, name = "Ping Far RGB" }); passData.pongFarRGB = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "Pong Far RGB" }); + { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "Pong Far RGB" }); passData.farCoC = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = k_CoCFormat, useMipMap = true, enableRandomWrite = true, name = "Far CoC" }); + { colorFormat = k_CoCFormat, useMipMap = true, enableRandomWrite = true, name = "Far CoC" }); } else { @@ -510,14 +507,14 @@ TextureHandle DepthOfFieldPass(RenderGraph renderGraph, HDCamera hdCamera, Textu } passData.fullresCoC = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Full res CoC" }); + { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Full res CoC" }); int passCount = Mathf.CeilToInt((passData.parameters.nearMaxBlur + 2f) / 4f); passData.dilationPingPongRT = TextureHandle.nullHandle; if (passCount > 1) { passData.dilationPingPongRT = builder.CreateTransientTexture(new TextureDesc(screenScale, true, true) - { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Dilation ping pong CoC" }); + { colorFormat = k_CoCFormat, enableRandomWrite = true, name = "Dilation ping pong CoC" }); } var mipScale = scale; @@ -541,39 +538,38 @@ TextureHandle DepthOfFieldPass(RenderGraph renderGraph, HDCamera hdCamera, Textu passData.farBokehTileList = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(dofParameters.threadGroup8.x * dofParameters.threadGroup8.y, sizeof(uint), ComputeBufferType.Append) { name = "Bokeh Far Tile List" }); builder.SetRenderFunc( - (DepthofFieldData data, RenderGraphContext ctx) => - { - var mipsHandles = ctx.renderGraphPool.GetTempArray(4); - - for (int i = 0; i < 4; ++i) + (DepthofFieldData data, RenderGraphContext ctx) => { - mipsHandles[i] = data.mips[i]; - } + var mipsHandles = ctx.renderGraphPool.GetTempArray(4); - ((ComputeBuffer)data.nearBokehTileList).SetCounterValue(0u); - ((ComputeBuffer)data.farBokehTileList).SetCounterValue(0u); + for (int i = 0; i < 4; ++i) + { + mipsHandles[i] = data.mips[i]; + } - DoDepthOfField(data.parameters, ctx.cmd, data.source, data.destination, data.depthBuffer, data.pingNearRGB, data.pongNearRGB, data.nearCoC, data.nearAlpha, - data.dilatedNearCoC, data.pingFarRGB, data.pongFarRGB, data.farCoC, data.fullresCoC, mipsHandles, data.dilationPingPongRT, data.prevCoC, data.nextCoC, data.motionVecTexture, - data.bokehNearKernel, data.bokehFarKernel, data.bokehIndirectCmd, data.nearBokehTileList, data.farBokehTileList, data.taaEnabled); - }); + ((ComputeBuffer)data.nearBokehTileList).SetCounterValue(0u); + ((ComputeBuffer)data.farBokehTileList).SetCounterValue(0u); - source = passData.destination; + DoDepthOfField(data.parameters, ctx.cmd, data.source, data.destination, data.depthBuffer, data.pingNearRGB, data.pongNearRGB, data.nearCoC, data.nearAlpha, + data.dilatedNearCoC, data.pingFarRGB, data.pongFarRGB, data.farCoC, data.fullresCoC, mipsHandles, data.dilationPingPongRT, data.prevCoC, data.nextCoC, data.motionVecTexture, + data.bokehNearKernel, data.bokehFarKernel, data.bokehIndirectCmd, data.nearBokehTileList, data.farBokehTileList, data.taaEnabled); + }); + source = passData.destination; } else { passData.fullresCoC = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = k_CoCFormat, enableRandomWrite = true, useMipMap = true, name = "Full res CoC" }); + { colorFormat = k_CoCFormat, enableRandomWrite = true, useMipMap = true, name = "Full res CoC" }); passData.pingFarRGB = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = m_ColorFormat, useMipMap = true, enableRandomWrite = true, name = "DoF Source Pyramid" }); + { colorFormat = m_ColorFormat, useMipMap = true, enableRandomWrite = true, name = "DoF Source Pyramid" }); builder.SetRenderFunc( - (DepthofFieldData data, RenderGraphContext ctx) => - { - DoPhysicallyBasedDepthOfField(data.parameters, ctx.cmd, data.source, data.destination, data.fullresCoC, data.prevCoC, data.nextCoC, data.motionVecTexture, data.pingFarRGB, data.taaEnabled); - }); + (DepthofFieldData data, RenderGraphContext ctx) => + { + DoPhysicallyBasedDepthOfField(data.parameters, ctx.cmd, data.source, data.destination, data.fullresCoC, data.prevCoC, data.nextCoC, data.motionVecTexture, data.pingFarRGB, data.taaEnabled); + }); source = passData.destination; } @@ -604,30 +600,29 @@ TextureHandle DepthOfFieldPass(RenderGraph renderGraph, HDCamera hdCamera, Textu passData.nextMVLen = TextureHandle.nullHandle; TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "Post-DoF TAA Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (TemporalAntiAliasingData data, RenderGraphContext ctx) => - { - DoTemporalAntialiasing(data.parameters, ctx.cmd, data.source, - data.destination, - data.motionVecTexture, - data.depthBuffer, - data.depthMipChain, - data.prevHistory, - data.nextHistory, - data.prevMVLen, - data.nextMVLen); - - // Temporary hack to make post-dof TAA work with rendergraph (still the first frame flashes black). We need a better solution. - m_IsDoFHisotoryValid = true; - }); + (TemporalAntiAliasingData data, RenderGraphContext ctx) => + { + DoTemporalAntialiasing(data.parameters, ctx.cmd, data.source, + data.destination, + data.motionVecTexture, + data.depthBuffer, + data.depthMipChain, + data.prevHistory, + data.nextHistory, + data.prevMVLen, + data.nextMVLen); + + // Temporary hack to make post-dof TAA work with rendergraph (still the first frame flashes black). We need a better solution. + m_IsDoFHisotoryValid = true; + }); source = passData.destination; } postDoFTAAEnabled = true; - } else { @@ -658,13 +653,13 @@ TextureHandle MotionBlurPass(RenderGraph renderGraph, HDCamera hdCamera, Texture Vector2 tileTexScale = new Vector2((float)passData.parameters.tileTargetSize.x / hdCamera.actualWidth, (float)passData.parameters.tileTargetSize.y / hdCamera.actualHeight); passData.preppedMotionVec = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, name = "Prepped Motion Vectors" }); + { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, name = "Prepped Motion Vectors" }); passData.minMaxTileVel = builder.CreateTransientTexture(new TextureDesc(tileTexScale, true, true) - { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, name = "MinMax Tile Motion Vectors" }); + { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, name = "MinMax Tile Motion Vectors" }); passData.maxTileNeigbourhood = builder.CreateTransientTexture(new TextureDesc(tileTexScale, true, true) - { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, name = "Max Neighbourhood Tile" }); + { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, name = "Max Neighbourhood Tile" }); passData.tileToScatterMax = TextureHandle.nullHandle; passData.tileToScatterMin = TextureHandle.nullHandle; @@ -672,28 +667,28 @@ TextureHandle MotionBlurPass(RenderGraph renderGraph, HDCamera hdCamera, Texture if (passData.parameters.motionblurSupportScattering) { passData.tileToScatterMax = builder.CreateTransientTexture(new TextureDesc(tileTexScale, true, true) - { colorFormat = GraphicsFormat.R32_UInt, enableRandomWrite = true, name = "Tile to Scatter Max" }); + { colorFormat = GraphicsFormat.R32_UInt, enableRandomWrite = true, name = "Tile to Scatter Max" }); passData.tileToScatterMin = builder.CreateTransientTexture(new TextureDesc(tileTexScale, true, true) - { colorFormat = GraphicsFormat.R16_SFloat, enableRandomWrite = true, name = "Tile to Scatter Min" }); + { colorFormat = GraphicsFormat.R16_SFloat, enableRandomWrite = true, name = "Tile to Scatter Min" }); } TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "Motion Blur Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (MotionBlurData data, RenderGraphContext ctx) => - { - DoMotionBlur(data.parameters, ctx.cmd, data.source, - data.destination, - data.depthBuffer, - data.motionVecTexture, - data.preppedMotionVec, - data.minMaxTileVel, - data.maxTileNeigbourhood, - data.tileToScatterMax, - data.tileToScatterMin); - }); + (MotionBlurData data, RenderGraphContext ctx) => + { + DoMotionBlur(data.parameters, ctx.cmd, data.source, + data.destination, + data.depthBuffer, + data.motionVecTexture, + data.preppedMotionVec, + data.minMaxTileVel, + data.maxTileNeigbourhood, + data.tileToScatterMax, + data.tileToScatterMin); + }); source = passData.destination; } @@ -715,10 +710,10 @@ TextureHandle PaniniProjectionPass(RenderGraph renderGraph, HDCamera hdCamera, T passData.destination = builder.WriteTexture(dest); builder.SetRenderFunc( - (PaniniProjectionData data, RenderGraphContext ctx) => - { - DoPaniniProjection(data.parameters, ctx.cmd, data.source, data.destination); - }); + (PaniniProjectionData data, RenderGraphContext ctx) => + { + DoPaniniProjection(data.parameters, ctx.cmd, data.source, data.destination); + }); source = passData.destination; } @@ -743,19 +738,19 @@ TextureHandle BloomPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandl builder.SetRenderFunc( - (BloomData data, RenderGraphContext ctx) => - { - var bloomMipDown = ctx.renderGraphPool.GetTempArray(data.parameters.bloomMipCount); - var bloomMipUp = ctx.renderGraphPool.GetTempArray(data.parameters.bloomMipCount); - - for (int i = 0; i < data.parameters.bloomMipCount; ++i) + (BloomData data, RenderGraphContext ctx) => { - bloomMipDown[i] = data.mipsDown[i]; - bloomMipUp[i] = data.mipsUp[i]; - } + var bloomMipDown = ctx.renderGraphPool.GetTempArray(data.parameters.bloomMipCount); + var bloomMipUp = ctx.renderGraphPool.GetTempArray(data.parameters.bloomMipCount); - DoBloom(data.parameters, ctx.cmd, data.source, bloomMipDown, bloomMipUp); - }); + for (int i = 0; i < data.parameters.bloomMipCount; ++i) + { + bloomMipDown[i] = data.mipsDown[i]; + bloomMipUp[i] = data.mipsUp[i]; + } + + DoBloom(data.parameters, ctx.cmd, data.source, bloomMipDown, bloomMipUp); + }); bloomTexture = passData.mipsUp[0]; } @@ -788,10 +783,10 @@ TextureHandle ColorGradingPass(RenderGraph renderGraph, HDCamera hdCamera) logLutOutput = passData.logLut; builder.SetRenderFunc( - (ColorGradingPassData data, RenderGraphContext ctx) => - { - DoColorGrading(data.parameters, data.logLut, ctx.cmd); - }); + (ColorGradingPassData data, RenderGraphContext ctx) => + { + DoColorGrading(data.parameters, data.logLut, ctx.cmd); + }); } return logLutOutput; @@ -811,15 +806,15 @@ TextureHandle UberPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle passData.destination = builder.WriteTexture(dest); builder.SetRenderFunc( - (UberPostPassData data, RenderGraphContext ctx) => - { - DoUberPostProcess(data.parameters, - data.source, - data.destination, - data.logLut, - data.bloomTexture, - ctx.cmd); - }); + (UberPostPassData data, RenderGraphContext ctx) => + { + DoUberPostProcess(data.parameters, + data.source, + data.destination, + data.logLut, + data.bloomTexture, + ctx.cmd); + }); source = passData.destination; } @@ -838,13 +833,13 @@ TextureHandle FXAAPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle passData.source = builder.ReadTexture(source); passData.parameters = PrepareFXAAParameters(hdCamera); TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "FXAA Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; builder.SetRenderFunc( - (FXAAData data, RenderGraphContext ctx) => - { - DoFXAA(data.parameters, ctx.cmd, data.source, data.destination); - }); + (FXAAData data, RenderGraphContext ctx) => + { + DoFXAA(data.parameters, ctx.cmd, data.source, data.destination); + }); source = passData.destination; } @@ -865,15 +860,15 @@ TextureHandle ContrastAdaptiveSharpeningPass(RenderGraph renderGraph, HDCamera h passData.source = builder.ReadTexture(source); passData.parameters = PrepareContrastAdaptiveSharpeningParameters(hdCamera); TextureHandle dest = GetPostprocessOutputHandle(renderGraph, "Contrast Adaptive Sharpen Destination"); - passData.destination = builder.WriteTexture(dest); ; + passData.destination = builder.WriteTexture(dest);; passData.casParametersBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(2, sizeof(uint) * 4) { name = "Cas Parameters" }); builder.SetRenderFunc( - (CASData data, RenderGraphContext ctx) => - { - DoContrastAdaptiveSharpening(data.parameters, ctx.cmd, data.source, data.destination, data.casParametersBuffer); - }); + (CASData data, RenderGraphContext ctx) => + { + DoContrastAdaptiveSharpening(data.parameters, ctx.cmd, data.source, data.destination, data.casParametersBuffer); + }); source = passData.destination; } @@ -892,10 +887,10 @@ void FinalPass(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle afterPo passData.destination = builder.WriteTexture(finalRT); builder.SetRenderFunc( - (FinalPassData data, RenderGraphContext ctx) => - { - DoFinalPass(data.parameters, data.source, data.afterPostProcessTexture, data.destination, data.alphaTexture, ctx.cmd); - }); + (FinalPassData data, RenderGraphContext ctx) => + { + DoFinalPass(data.parameters, data.source, data.afterPostProcessTexture, data.destination, data.alphaTexture, ctx.cmd); + }); } } @@ -946,18 +941,18 @@ bool DoCustomPostProcess(RenderGraph renderGraph, HDCamera hdCamera, ref Texture passData.source = builder.ReadTexture(source); passData.destination = builder.UseColorBuffer(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "CustomPostProcesDestination" }), 0); + { colorFormat = m_ColorFormat, enableRandomWrite = true, name = "CustomPostProcesDestination" }), 0); passData.hdCamera = hdCamera; passData.customPostProcess = customPP; builder.SetRenderFunc( - (CustomPostProcessData data, RenderGraphContext ctx) => - { - // Temporary: see comment above - ctx.cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, data.depthBuffer); - ctx.cmd.SetGlobalTexture(HDShaderIDs._NormalBufferTexture, data.normalBuffer); + (CustomPostProcessData data, RenderGraphContext ctx) => + { + // Temporary: see comment above + ctx.cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, data.depthBuffer); + ctx.cmd.SetGlobalTexture(HDShaderIDs._NormalBufferTexture, data.normalBuffer); - data.customPostProcess.Render(ctx.cmd, data.hdCamera, data.source, data.destination); - }); + data.customPostProcess.Render(ctx.cmd, data.hdCamera, data.source, data.destination); + }); customPostProcessExecuted = true; source = passData.destination; @@ -984,16 +979,16 @@ TextureHandle CustomPostProcessPass(RenderGraph renderGraph, HDCamera hdCamera, } public void Render(RenderGraph renderGraph, - HDCamera hdCamera, - BlueNoise blueNoise, - TextureHandle colorBuffer, - TextureHandle afterPostProcessTexture, - TextureHandle depthBuffer, - TextureHandle depthBufferMipChain, - TextureHandle normalBuffer, - TextureHandle motionVectors, - TextureHandle finalRT, - bool flipY) + HDCamera hdCamera, + BlueNoise blueNoise, + TextureHandle colorBuffer, + TextureHandle afterPostProcessTexture, + TextureHandle depthBuffer, + TextureHandle depthBufferMipChain, + TextureHandle normalBuffer, + TextureHandle motionVectors, + TextureHandle finalRT, + bool flipY) { renderGraph.BeginProfilingSampler(ProfilingSampler.Get(HDProfileId.PostProcessing)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs index bce080e146f..93fc5e85ba1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/PostProcessSystem.cs @@ -244,7 +244,6 @@ public void Cleanup() m_HistogramBuffer = null; m_DebugImageHistogramBuffer = null; m_DebugExposureData = null; - } public void InitializeNonRenderGraphResources(HDRenderPipelineAsset hdAsset) @@ -280,9 +279,9 @@ public void InitializeNonRenderGraphResources(HDRenderPipelineAsset hdAsset) if (m_KeepAlpha) { m_AlphaTexture = RTHandles.Alloc( - Vector2.one, slices: TextureXR.slices, dimension: TextureXR.dimension, - colorFormat: GraphicsFormat.R16_SFloat, enableRandomWrite: true, name: "Alpha Channel Copy" - ); + Vector2.one, slices: TextureXR.slices, dimension: TextureXR.dimension, + colorFormat: GraphicsFormat.R16_SFloat, enableRandomWrite: true, name: "Alpha Channel Copy" + ); } } @@ -313,10 +312,8 @@ public void CleanupNonRenderGraphResources() m_NearBokehTileList = null; m_FarBokehTileList = null; m_ContrastAdaptiveSharpen = null; - } - // In some cases, the internal buffer of render textures might be invalid. // Usually when using these textures with API such as SetRenderTarget, they are recreated internally. // This is not the case when these textures are used exclusively with Compute Shaders. So to make sure they work in this case, we recreate them here. @@ -589,9 +586,9 @@ void PoolSource(ref RTHandle src, RTHandle dst) // If Path tracing is enabled, then DoF is computed in the path tracer by sampling the lens aperure (when using the physical camera mode) bool isDoFPathTraced = (camera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && - m_PathTracing.enable.value && - camera.camera.cameraType != CameraType.Preview && - m_DepthOfField.focusMode == DepthOfFieldMode.UsePhysicalCamera); + m_PathTracing.enable.value && + camera.camera.cameraType != CameraType.Preview && + m_DepthOfField.focusMode == DepthOfFieldMode.UsePhysicalCamera); // Depth of Field is done right after TAA as it's easier to just re-project the CoC // map rather than having to deal with all the implications of doing it before TAA @@ -647,7 +644,7 @@ void PoolSource(ref RTHandle src, RTHandle dst) RTHandle prevCoC = null; RTHandle nextCoC = null; - if(taaEnabled) + if (taaEnabled) GrabCoCHistory(camera, out prevCoC, out nextCoC, useMips: false); ValidateComputeBuffer(ref m_BokehNearKernel, dofParameters.nearSampleCount * dofParameters.nearSampleCount, sizeof(uint)); @@ -661,8 +658,8 @@ void PoolSource(ref RTHandle src, RTHandle dst) m_FarBokehTileList.SetCounterValue(0u); DoDepthOfField(dofParameters, cmd, source, destination, depthBuffer, pingNearRGB, pongNearRGB, nearCoC, nearAlpha, - dilatedNearCoC, pingFarRGB, pongFarRGB, farCoC, fullresCoC, dofSafePathMips, dilationPingPongRT, prevCoC, nextCoC, motionVecTexture, - m_BokehNearKernel, m_BokehFarKernel, m_BokehIndirectCmd, m_NearBokehTileList, m_FarBokehTileList, taaEnabled); + dilatedNearCoC, pingFarRGB, pongFarRGB, farCoC, fullresCoC, dofSafePathMips, dilationPingPongRT, prevCoC, nextCoC, motionVecTexture, + m_BokehNearKernel, m_BokehFarKernel, m_BokehIndirectCmd, m_NearBokehTileList, m_FarBokehTileList, taaEnabled); m_HDInstance.PushFullScreenDebugTexture(camera, cmd, fullresCoC, FullScreenDebugMode.DepthOfFieldCoc); @@ -682,9 +679,9 @@ void PoolSource(ref RTHandle src, RTHandle dst) m_Pool.Recycle(dilatedNearCoC); } - if(m_UseSafePath) + if (m_UseSafePath) { - for (int i=0; i<4; ++i) + for (int i = 0; i < 4; ++i) { m_Pool.Recycle(dofSafePathMips[i]); } @@ -696,7 +693,6 @@ void PoolSource(ref RTHandle src, RTHandle dst) } m_Pool.Recycle(fullresCoC); - } else { @@ -722,7 +718,7 @@ void PoolSource(ref RTHandle src, RTHandle dst) var taaParams = PrepareTAAParameters(camera, postDof); GrabTemporalAntialiasingHistoryTextures(camera, out var prevHistory, out var nextHistory, postDof); - DoTemporalAntialiasing(taaParams, cmd, source, taaDestination, motionVecTexture, depthBuffer, depthMipChain, prevHistory, nextHistory, prevMVLen:null, nextMVLen:null); + DoTemporalAntialiasing(taaParams, cmd, source, taaDestination, motionVecTexture, depthBuffer, depthMipChain, prevHistory, nextHistory, prevMVLen: null, nextMVLen: null); PoolSource(ref source, taaDestination); postDoFTAAEnabled = true; } @@ -746,9 +742,9 @@ void PoolSource(ref RTHandle src, RTHandle dst) var mbParams = PrepareMotionBlurParameters(camera); RTHandle preppedMotionVec, minMaxTileVel, maxTileNeigbourhood, tileToScatterMax, tileToScatterMin; AllocateMotionBlurRenderTargets(mbParams, camera, - out preppedMotionVec, out minMaxTileVel, - out maxTileNeigbourhood, out tileToScatterMax, - out tileToScatterMin); + out preppedMotionVec, out minMaxTileVel, + out maxTileNeigbourhood, out tileToScatterMax, + out tileToScatterMin); DoMotionBlur(PrepareMotionBlurParameters(camera), cmd, source, destination, depthMipChain, motionVecTexture, preppedMotionVec, minMaxTileVel, maxTileNeigbourhood, tileToScatterMax, tileToScatterMin); RecycleMotionBlurRenderTargets(preppedMotionVec, minMaxTileVel, maxTileNeigbourhood, tileToScatterMax, tileToScatterMin); @@ -944,11 +940,11 @@ void PrepareAlphaScaleParameters(ref UberPostParameters parameters, HDCamera cam } static void DoUberPostProcess(in UberPostParameters parameters, - RTHandle source, - RTHandle destination, - RTHandle logLut, - RTHandle bloomTexture, - CommandBuffer cmd) + RTHandle source, + RTHandle destination, + RTHandle logLut, + RTHandle bloomTexture, + CommandBuffer cmd) { // Color grading cmd.SetComputeTextureParam(parameters.uberPostCS, parameters.uberPostKernel, HDShaderIDs._LogLut3D, logLut); @@ -1125,7 +1121,6 @@ static void ApplyExposure(in ApplyExposureParameters parameters, CommandBuffer c cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._InputTexture, source); cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._OutputTexture, destination); cmd.DispatchCompute(cs, kernel, (parameters.width + 7) / 8, (parameters.height + 7) / 8, parameters.viewCount); - } struct ExposureParameters @@ -1172,7 +1167,7 @@ ExposureParameters PrepareExposureParameters(HDCamera hdCamera) #if UNITY_EDITOR || HDAdditionalSceneViewSettings.sceneExposureOverriden && hdCamera.camera.cameraType == CameraType.SceneView #endif - ) + ) { parameters.exposureReductionKernel = parameters.exposureCS.FindKernel("KFixedExposure"); parameters.exposureParams = new Vector4(m_Exposure.compensation.value + m_DebugExposureCompensation, m_Exposure.fixedExposure.value, 0f, 0f); @@ -1269,9 +1264,9 @@ ExposureParameters PrepareExposureParameters(HDCamera hdCamera) [MethodImpl(MethodImplOptions.AggressiveInlining)] bool IsExposureFixed(HDCamera camera) => m_Exposure.mode.value == ExposureMode.Fixed || m_Exposure.mode.value == ExposureMode.UsePhysicalCamera #if UNITY_EDITOR - || (camera.camera.cameraType == CameraType.SceneView && HDAdditionalSceneViewSettings.sceneExposureOverriden) + || (camera.camera.cameraType == CameraType.SceneView && HDAdditionalSceneViewSettings.sceneExposureOverriden) #endif - ; + ; public RTHandle GetExposureTexture(HDCamera camera) { @@ -1427,9 +1422,9 @@ void PrepareExposureCurveData(out float min, out float max) { float currTime = min + step * i; pixels[i] = new Color(curve.Evaluate(currTime), - minCurveHasPoints ? minCurve.Evaluate(currTime) : defaultMin, - maxCurveHasPoints ? maxCurve.Evaluate(currTime) : defaultMax, - 0f); + minCurveHasPoints ? minCurve.Evaluate(currTime) : defaultMin, + maxCurveHasPoints ? maxCurve.Evaluate(currTime) : defaultMax, + 0f); } } @@ -1691,16 +1686,16 @@ TemporalAntiAliasingParameters PrepareTAAParameters(HDCamera camera, bool PostDO } static void DoTemporalAntialiasing(in TemporalAntiAliasingParameters taaParams, - CommandBuffer cmd, - RTHandle source, - RTHandle destination, - RTHandle motionVecTexture, - RTHandle depthBuffer, - RTHandle depthMipChain, - RTHandle prevHistory, - RTHandle nextHistory, - RTHandle prevMVLen, - RTHandle nextMVLen) + CommandBuffer cmd, + RTHandle source, + RTHandle destination, + RTHandle motionVecTexture, + RTHandle depthBuffer, + RTHandle depthMipChain, + RTHandle prevHistory, + RTHandle nextHistory, + RTHandle prevMVLen, + RTHandle nextMVLen) { if (taaParams.resetPostProcessingHistory) { @@ -1725,7 +1720,7 @@ static void DoTemporalAntialiasing(in TemporalAntiAliasingParameters taaParams, taaParams.taaPropertyBlock.SetTexture(HDShaderIDs._DepthTexture, depthMipChain); Vector2 historySize = new Vector2(prevHistory.referenceSize.x * prevHistory.scaleFactor.x, - prevHistory.referenceSize.y * prevHistory.scaleFactor.y); + prevHistory.referenceSize.y * prevHistory.scaleFactor.y); var taaHistorySize = new Vector4(historySize.x, historySize.y, 1.0f / historySize.x, 1.0f / historySize.y); taaParams.taaPropertyBlock.SetVector(HDShaderIDs._TaaPostParameters, taaParams.taaParameters); @@ -1787,13 +1782,13 @@ void ReleasePostDoFTAAHistoryTextures(HDCamera camera) camera.ReleaseHistoryFrameRT((int)HDCameraFrameHistoryType.TemporalAntialiasingPostDoF); } } + #endregion #region Depth Of Field struct DepthOfFieldParameters { - public ComputeShader dofKernelCS; public int dofKernelKernel; public ComputeShader dofCoCCS; @@ -1990,7 +1985,7 @@ DepthOfFieldParameters PrepareDoFParameters(HDCamera camera) parameters.dofPrefilterCS.EnableKeyword("FULL_RES"); parameters.dofCombineCS.EnableKeyword("FULL_RES"); } - else if(parameters.highQualityFiltering) + else if (parameters.highQualityFiltering) { parameters.dofCombineCS.EnableKeyword("HIGH_QUALITY"); } @@ -2579,10 +2574,9 @@ static void DoPhysicallyBasedDepthOfField(in DepthOfFieldParameters dofParameter if (dofParameters.focusMode == DepthOfFieldMode.UsePhysicalCamera) { - // The sensor scale is used to convert the CoC size from mm to screen pixels float sensorScale; - if (dofParameters.camera.camera.gateFit == Camera.GateFitMode.Horizontal ) + if (dofParameters.camera.camera.gateFit == Camera.GateFitMode.Horizontal) sensorScale = (0.5f / dofParameters.camera.camera.sensorSize.x) * dofParameters.camera.camera.pixelWidth; else sensorScale = (0.5f / dofParameters.camera.camera.sensorSize.y) * dofParameters.camera.camera.pixelHeight; @@ -2658,6 +2652,7 @@ static void DoPhysicallyBasedDepthOfField(in DepthOfFieldParameters dofParameter cmd.DispatchCompute(cs, kernel, (dofParameters.camera.actualWidth + 7) / 8, (dofParameters.camera.actualHeight + 7) / 8, dofParameters.camera.viewCount); } } + #endregion #region Motion Blur @@ -2786,9 +2781,9 @@ MotionBlurParameters PrepareMotionBlurParameters(HDCamera camera) } void AllocateMotionBlurRenderTargets(in MotionBlurParameters motionBlurParams, HDCamera camera, - out RTHandle preppedMotionVec, out RTHandle minMaxTileVel, - out RTHandle maxTileNeigbourhood, out RTHandle tileToScatterMax, - out RTHandle tileToScatterMin) + out RTHandle preppedMotionVec, out RTHandle minMaxTileVel, + out RTHandle maxTileNeigbourhood, out RTHandle tileToScatterMax, + out RTHandle tileToScatterMin) { Vector2 tileTexScale = new Vector2((float)motionBlurParams.tileTargetSize.x / camera.actualWidth, (float)motionBlurParams.tileTargetSize.y / camera.actualHeight); @@ -2806,8 +2801,8 @@ void AllocateMotionBlurRenderTargets(in MotionBlurParameters motionBlurParams, H } void RecycleMotionBlurRenderTargets(RTHandle preppedMotionVec, RTHandle minMaxTileVel, - RTHandle maxTileNeigbourhood, RTHandle tileToScatterMax, - RTHandle tileToScatterMin) + RTHandle maxTileNeigbourhood, RTHandle tileToScatterMax, + RTHandle tileToScatterMin) { m_Pool.Recycle(minMaxTileVel); m_Pool.Recycle(maxTileNeigbourhood); @@ -2820,9 +2815,9 @@ void RecycleMotionBlurRenderTargets(RTHandle preppedMotionVec, RTHandle minMaxTi } static void DoMotionBlur(in MotionBlurParameters motionBlurParams, CommandBuffer cmd, RTHandle source, RTHandle destination, RTHandle depthTexture, RTHandle motionVectorTexture, - RTHandle preppedMotionVec, RTHandle minMaxTileVel, - RTHandle maxTileNeigbourhood, RTHandle tileToScatterMax, - RTHandle tileToScatterMin) + RTHandle preppedMotionVec, RTHandle minMaxTileVel, + RTHandle maxTileNeigbourhood, RTHandle tileToScatterMax, + RTHandle tileToScatterMin) { int tileSize = 32; @@ -3526,13 +3521,13 @@ ColorGradingParameters PrepareColorGradingParameters() { parameters.hableCurve = m_HableCurve; parameters.hableCurve.Init( - m_Tonemapping.toeStrength.value, - m_Tonemapping.toeLength.value, - m_Tonemapping.shoulderStrength.value, - m_Tonemapping.shoulderLength.value, - m_Tonemapping.shoulderAngle.value, - m_Tonemapping.gamma.value - ); + m_Tonemapping.toeStrength.value, + m_Tonemapping.toeLength.value, + m_Tonemapping.shoulderStrength.value, + m_Tonemapping.shoulderLength.value, + m_Tonemapping.shoulderAngle.value, + m_Tonemapping.gamma.value + ); } else if (parameters.tonemappingMode == TonemappingMode.External) { @@ -3548,8 +3543,8 @@ ColorGradingParameters PrepareColorGradingParameters() // TODO: User lut support static void DoColorGrading(in ColorGradingParameters parameters, - RTHandle internalLogLuT, - CommandBuffer cmd) + RTHandle internalLogLuT, + CommandBuffer cmd) { var builderCS = parameters.builderCS; var builderKernel = parameters.builderKernel; @@ -3896,8 +3891,8 @@ static void DoContrastAdaptiveSharpening(in CASParameters parameters, CommandBuf cmd.DispatchCompute(cs, kMain, dispatchX, dispatchY, parameters.viewCount); } - } + #endregion #region Final Pass @@ -3955,12 +3950,12 @@ FinalPassParameters PrepareFinalPass(HDCamera hdCamera, BlueNoise blueNoise, boo return parameters; } - static void DoFinalPass( in FinalPassParameters parameters, - RTHandle source, - RTHandle afterPostProcessTexture, - RenderTargetIdentifier destination, - RTHandle alphaTexture, - CommandBuffer cmd) + static void DoFinalPass(in FinalPassParameters parameters, + RTHandle source, + RTHandle afterPostProcessTexture, + RenderTargetIdentifier destination, + RTHandle alphaTexture, + CommandBuffer cmd) { // Final pass has to be done in a pixel shader as it will be the one writing straight // to the backbuffer eventually @@ -4021,7 +4016,6 @@ static void DoFinalPass( in FinalPassParameters parameters, float scaledOffsetY = offsetY * uvScaleY; finalPassMaterial.SetVector(HDShaderIDs._GrainTextureParams, new Vector4(uvScaleX, uvScaleY, offsetX, offsetY)); - } } @@ -4038,7 +4032,7 @@ static void DoFinalPass( in FinalPassParameters parameters, finalPassMaterial.EnableKeyword("DITHER"); finalPassMaterial.SetTexture(HDShaderIDs._BlueNoiseTexture, blueNoiseTexture); finalPassMaterial.SetVector(HDShaderIDs._DitherParams, new Vector3(parameters.hdCamera.actualWidth / blueNoiseTexture.width, - parameters.hdCamera.actualHeight / blueNoiseTexture.height, textureId)); + parameters.hdCamera.actualHeight / blueNoiseTexture.height, textureId)); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute index 0fe6b2af62b..85ac1ed7b37 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute @@ -24,7 +24,7 @@ float3 BilinearSample(float2 uv, float2 offset, out float weight) { CTYPE c = SAMPLE_TEXTURE2D_X_LOD(_InputTexture, s_linear_clamp_sampler, ClampAndScaleUVForBilinear(uv + offset * _ScreenSize.zw), 0.0).CTYPE_SWIZZLE; #ifdef ENABLE_ALPHA - // When alpha is enabled, regions with zero alpha should not generate any bloom / glow. Therefore we pre-multipy the color with the alpha channel here and the rest + // When alpha is enabled, regions with zero alpha should not generate any bloom / glow. Therefore we pre-multipy the color with the alpha channel here and the rest // of the computations remain float3. Still, when bloom is applied to the final image, bloom will still be spread on regions with zero alpha (see UberPost.compute) c.xyz *= c.w; #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute index 2d64cd54246..dd5956527b4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute @@ -9,7 +9,7 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_a.hlsl" // two elements: -// [0] = const0 +// [0] = const0 // [1] = const1 // ComputeBuffer is allocated with stride sizeof(int)*4, 2 elements RWStructuredBuffer CasParameters; @@ -25,21 +25,21 @@ RW_TEXTURE2D_X(float4, _OutputTexture); AF3 CasLoad(ASU2 p) { - return _InputTexture[COORD_TEXTURE2D_X(p)].xyz; + return _InputTexture[COORD_TEXTURE2D_X(p)].xyz; } -void CasInput(inout AF1 r, inout AF1 g, inout AF1 b) +void CasInput(inout AF1 r, inout AF1 g, inout AF1 b) { } AF4 CasOutput(AF4 pix) { - return pix; + return pix; } void WritePix(AU2 gxy, AF4 casPix) { - _OutputTexture[COORD_TEXTURE2D_X(gxy)] = casPix; + _OutputTexture[COORD_TEXTURE2D_X(gxy)] = casPix; } #include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_cas.hlsl" @@ -49,36 +49,36 @@ void WritePix(AU2 gxy, AF4 casPix) void KMain(uint3 LocalThreadId : SV_GroupThreadID, uint3 WorkGroupId : SV_GroupID, uint3 dispatchThreadId : SV_DispatchThreadID) { - UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); + UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); - uint4 c0 = CasParameters[0]; - uint4 c1 = CasParameters[1]; + uint4 c0 = CasParameters[0]; + uint4 c1 = CasParameters[1]; - AF3 c; + AF3 c; - // Do remapping of local xy in workgroup for a more PS-like swizzle pattern. - AU2 gxy = ARmp8x8(LocalThreadId.x) + AU2(WorkGroupId.x << 4u, WorkGroupId.y << 4u); - // Filter. - CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); - WritePix(gxy, CasOutput(AF4(c, 1))); + // Do remapping of local xy in workgroup for a more PS-like swizzle pattern. + AU2 gxy = ARmp8x8(LocalThreadId.x) + AU2(WorkGroupId.x << 4u, WorkGroupId.y << 4u); + // Filter. + CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); + WritePix(gxy, CasOutput(AF4(c, 1))); - gxy.x += 8u; - CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); - WritePix(gxy, CasOutput(AF4(c, 1))); + gxy.x += 8u; + CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); + WritePix(gxy, CasOutput(AF4(c, 1))); - gxy.y += 8u; - CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); - WritePix(gxy, CasOutput(AF4(c, 1))); + gxy.y += 8u; + CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); + WritePix(gxy, CasOutput(AF4(c, 1))); - gxy.x -= 8u; - CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); - WritePix(gxy, CasOutput(AF4(c, 1))); + gxy.x -= 8u; + CasFilter(c.r, c.g, c.b, gxy, c0, c1, false, true); + WritePix(gxy, CasOutput(AF4(c, 1))); } /* Doing this on the GPU despite the fact that CAS provides a CPU version -of CasSetup(). This is done to prevent us from having to rewrite a C# +of CasSetup(). This is done to prevent us from having to rewrite a C# version every time CAS changes. This is not called from KMain to reduce overhead during main render. */ @@ -86,11 +86,11 @@ during main render. void KInitialize() { - uint4 c0; - uint4 c1; + uint4 c0; + uint4 c1; - CasSetup(c0, c1, Sharpness, InputTextureDimensions * _RTHandleScale.xy, OutputTextureDimensions); + CasSetup(c0, c1, Sharpness, InputTextureDimensions * _RTHandleScale.xy, OutputTextureDimensions); - CasParameters[0] = c0; - CasParameters[1] = c1; + CasParameters[0] = c0; + CasParameters[1] = c1; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute index 01bd3790317..75a431e9b75 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute @@ -108,4 +108,3 @@ void KMain(uint2 groupId : SV_GroupID, uint2 groupThreadId : SV_GroupThreadID, u VerticalPass(dispatchThreadId.xy, (groupThreadId.y << 3u) + groupThreadId.x); } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute index fb3def888d5..9eb7d92d0d7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute @@ -120,7 +120,7 @@ void MAIN(uint3 dispatchThreadId : SV_DispatchThreadID) CTYPE sampColor = SAMPLE_TEXTURE2D_X_LOD(_InputTexture, SamplerTap, sampTap, mip).CTYPE_SWIZZLE; float sampCoC = SAMPLE_TEXTURE2D_X_LOD(_InputCoCTexture, SamplerTap, sampTap, mip).x; - + #if NEAR { float weight = saturate(1.0 - (sampCoC - samp0CoC)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute index 52eac523d27..dcf957b54c1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute @@ -4,7 +4,7 @@ #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -#pragma kernel KMainPreCombineFar +#pragma kernel KMainPreCombineFar #pragma multi_compile _ ENABLE_ALPHA diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCPyramid.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCPyramid.compute index e6dc4e7ee0c..2737fee39dc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCPyramid.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCPyramid.compute @@ -95,7 +95,7 @@ void KMainCoCPyramid(uint3 dispatchThreadId : SV_DispatchThreadID, uint groupInd return; GroupMemoryBarrierWithGroupSync(); - + // Fourth mip - checks that X and Y are multiples of 8 if ((groupIndex & 0xE7) == 0) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute index 7586aecb532..03e44f4443e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute @@ -119,7 +119,7 @@ void KMain(uint3 dispatchThreadId : SV_DispatchThreadID) // If there is a larger CoC that overlaps the central pixel then it will have greater depth float centerCoC = GetCoCRadius(posInputs.positionSS); float maxRadius = abs(centerCoC); - + float dR = rcp(NumRings); int blueNoiseOffset = _TaaFrameInfo.w != 0.0 ? _TaaFrameInfo.z : 0; int numSamples = maxRadius > 0 ? NumRings : 0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ExposureCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ExposureCommon.hlsl index 7f74f3af74a..36c91f9c1a9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ExposureCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ExposureCommon.hlsl @@ -42,7 +42,7 @@ CBUFFER_END #define ParamEvaluateMode _Variants.w #define ProceduralCenter _ProceduralMaskParams.xy // Transformed in screen space on CPU -#define ProceduralRadii _ProceduralMaskParams.zw +#define ProceduralRadii _ProceduralMaskParams.zw #define ProceduralSoftness _ProceduralMaskParams2.x #define ProceduralMin _ProceduralMaskParams2.y #define ProceduralMax _ProceduralMaskParams2.z diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute index 568b8686f4c..dba67b737ef 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute @@ -15,7 +15,7 @@ void FXAA(uint3 dispatchThreadId : SV_DispatchThreadID) { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z); uint2 positionSS = dispatchThreadId.xy; - float2 positionNDC = positionSS * _ScreenSize.zw + (0.5 * _ScreenSize.zw); + float2 positionNDC = positionSS * _ScreenSize.zw + (0.5 * _ScreenSize.zw); float3 outColor = Load(_InputTexture, positionSS, 0, 0); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader index 7c56dd69910..d5a3bfcc72e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader @@ -97,10 +97,10 @@ Shader "Hidden/HDRP/FinalPass" CTYPE outColor = LOAD_TEXTURE2D_X(_InputTexture, positionSS).CTYPE_SWIZZLE; #endif - #if !defined(ENABLE_ALPHA) + #if !defined(ENABLE_ALPHA) float outAlpha = (_KeepAlpha == 1.0) ? LOAD_TEXTURE2D_X(_AlphaTexture, positionSS).x : 1.0; - #endif - + #endif + #if FXAA RunFXAA(_InputTexture, sampler_LinearClamp, outColor.rgb, positionSS, positionNDC); #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute index a72bc28bac3..3be9ef43963 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute @@ -4,7 +4,7 @@ // TODO List to investigate // - Worth considering multiple histograms per lane in the thread. (i.e. sharedHisto[BINS][NUMB_HIST] ) // - At the moment the dispatch is at half res, but the buffer sampled is full res, -// causing fairly bad cache behaviour. Can we use the mip chain realistically without issues? [The one we have is blurred and might be incomplete?] +// causing fairly bad cache behaviour. Can we use the mip chain realistically without issues? [The one we have is blurred and might be incomplete?] #pragma kernel KHistogramGen GEN_PASS #pragma kernel KHistogramReduce REDUCE_PASS @@ -30,7 +30,7 @@ void KHistogramGen(uint groupIndex : SV_GroupIndex, { // Groupshared memory is not guaranteed to be 0 initialized. // Note that currently the branch is always true (GROUP_SIZE_X * GROUP_SIZE_Y == HISTOGRAM_BINS). Here as safeguard if changing group size or bins. - if (groupIndex < HISTOGRAM_BINS) + if (groupIndex < HISTOGRAM_BINS) { gs_localHistogram[groupIndex] = 0u; } @@ -65,11 +65,11 @@ void KHistogramGen(uint groupIndex : SV_GroupIndex, #if USE_WAVE_INTRINSICS #define WAVE_SIZE PLATFORM_LANE_COUNT -#define SUM_SCRATCH_SIZE HISTOGRAM_BINS / WAVE_SIZE +#define SUM_SCRATCH_SIZE HISTOGRAM_BINS / WAVE_SIZE #else -#define SUM_SCRATCH_SIZE HISTOGRAM_BINS +#define SUM_SCRATCH_SIZE HISTOGRAM_BINS #endif @@ -91,7 +91,7 @@ float ComputeTotalSum(uint threadID, float threadVal) gs_partialSums[waveIDInGroup] = waveSum; } - // We have values for all the waves, let's sync. + // We have values for all the waves, let's sync. GroupMemoryBarrierWithGroupSync(); sum = gs_partialSums[0]; @@ -151,7 +151,7 @@ void KHistogramReduce(uint3 dispatchThreadId : SV_DispatchThreadID) float2 extremesSums = float2(_HistogramMinPercentile, _HistogramMaxPercentile) * sum; - // TODO: Can we be a bit more parallel here? + // TODO: Can we be a bit more parallel here? if (threadID == 0) { float evProcessedSum = 0; @@ -180,5 +180,5 @@ void KHistogramReduce(uint3 dispatchThreadId : SV_DispatchThreadID) #endif } - + } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute index b882684f898..cb3ebf485c0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute @@ -86,7 +86,7 @@ float3 ColorGrade(float3 colorLutSpace) #endif colorLog = (colorLog - ACEScc_MIDGRAY) * _HueSatCon.z + ACEScc_MIDGRAY; - + #if defined(TONEMAPPING_ACES) colorLinear = ACES_to_ACEScg(ACEScc_to_ACES(colorLog)); #else diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute index 1d8f8edfc9f..5c658168b75 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute @@ -41,12 +41,12 @@ TEXTURE2D_X(_TileMaxNeighbourhood); #define ONLY_FAST_PATH 2 #define DEBUG_EXECUTION NORMAL - + // ------------Options------------------ #define MIRROR_WEIGHTS 1 #define TILE_JITTER 1 -// When this is set to 1, samples are taken from both the central direction and the maximum direction in the tile. This reduces bugs when very different velocities are available in a tile. -// This however also can cause the blur to look slightly different. +// When this is set to 1, samples are taken from both the central direction and the maximum direction in the tile. This reduces bugs when very different velocities are available in a tile. +// This however also can cause the blur to look slightly different. #define GUERTIN2014_DOUBLE_DIR 0 #define DOT_WEIGHTING 1 #define DOT_MULTIPLIER 1 * DOT_WEIGHTING @@ -128,7 +128,7 @@ void MirrorWeights(float depth1, float depth2, float motionVec1, float motionVec } // --------------------------------------------- -// Sample processing +// Sample processing // --------------------------------------------- CTYPE ProcessSampleFastPath(uint sampleNumber, float2 dir, float invSampleCount, float2 centralUV, float randomVal, float dirSign) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurCommon.hlsl index 9cd5c6d4bc8..06d660b14e1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurCommon.hlsl @@ -4,7 +4,7 @@ #define WAVE_SIZE 64u -#ifdef MOTION_VEC_PREPPING +#ifdef MOTION_VEC_PREPPING RW_TEXTURE2D_X(float3, _MotionVecAndDepth); #else TEXTURE2D_X(_MotionVecAndDepth); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute index 257eb6827ba..23e0c0ee0bc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute @@ -30,7 +30,7 @@ float3 ParallelReduction(uint gid, uint threadIdx, float2 motionVec) uint waveCount = ((TILE_SIZE * TILE_SIZE) / WAVE_SIZE); - // Find min/max for this wave and store it in LDS. + // Find min/max for this wave and store it in LDS. float waveMin = WaveActiveMin(motionVecLength); uint waveMax = WaveActiveMax(packedMotionVec); @@ -41,7 +41,7 @@ float3 ParallelReduction(uint gid, uint threadIdx, float2 motionVec) gs_maxMotionVec[waveIDInGroup] = waveMax; } - // We have values for all the waves, let's sync. + // We have values for all the waves, let's sync. GroupMemoryBarrierWithGroupSync(); if (threadIdx == 0) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute index 9184228cde8..369fc25779c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute @@ -40,9 +40,9 @@ float2 GetDeltaNDCVec(float4 positionWS, float4 prevPosWS, float4x4 currM, float clipWP.xy /= clipWP.w; clipPrevWP.xy /= clipPrevWP.w; - + float2 outDeltaVec = (clipWP.xy - clipPrevWP.xy); - outDeltaVec *= 0.5f; + outDeltaVec *= 0.5f; #if UNITY_UV_STARTS_AT_TOP outDeltaVec.y = -outDeltaVec.y; @@ -55,7 +55,7 @@ float2 GetDeltaNDCVec(float4 positionWS, float4 prevPosWS, float4x4 currM, float // Prep motion vectors so that the velocity due to rotation is clamped more lightly // A bit of code duplication but keeping separate make it clearer. -#ifdef NO_SPECIAL_CLAMP +#ifdef NO_SPECIAL_CLAMP float2 ComputeMotionVec(PositionInputs posInput, float2 sampledMotionVec) { @@ -135,7 +135,7 @@ float2 ComputeMotionVec(PositionInputs posInput, float2 sampledMotionVec) #else -#error +#error #endif @@ -146,7 +146,7 @@ void MotionVecPreppingCS(uint3 dispatchThreadId : SV_DispatchThreadID) float3 motionVecAndDepth = 0.0f; float4 motionVecBufferSample = LOAD_TEXTURE2D_X(_CameraMotionVectorsTexture, dispatchThreadId.xy); - // if we have a value > 1.0f, it means we have selected the "no motion option", hence we force motionVec 0. + // if we have a value > 1.0f, it means we have selected the "no motion option", hence we force motionVec 0. bool forceNoMotion = PixelSetAsNoMotionVectors(motionVecBufferSample); float2 motionVec; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute index 7ffab1524a1..ccd8a2aee5e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute @@ -113,7 +113,7 @@ void TileNeighbourhood(uint3 dispatchID : SV_DispatchThreadID, uint gid : SV_Gro // TODO: We need to find a better min motionVec determination. #if USE_NEIGHBOURHOOD_MIN -// Find min of the tile in the 1-ring neighbourhood? This is incorrect, but might be worth perf wise. +// Find min of the tile in the 1-ring neighbourhood? This is incorrect, but might be worth perf wise. float v0 = _TileToScatterMin[COORD_TEXTURE2D_X(clamp(id.xy + int2(-1, 1), int2(0, 0), maxCoords))]; float v1 = _TileToScatterMin[COORD_TEXTURE2D_X(clamp(id.xy + int2(0, 1), int2(0, 0), maxCoords))]; float v2 = _TileToScatterMin[COORD_TEXTURE2D_X(clamp(id.xy + int2(1, 1), int2(0, 0), maxCoords))]; diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute index f47907317b5..3f697d84050 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute @@ -78,7 +78,7 @@ float2 Panini_Generic(float2 view_pos, float d) // d | / // | / , // |/ . - // P + // P // | ´ // | , ´ // +- ´ diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.hlsl index 8a4a1581cb9..4aec7a0727a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.hlsl @@ -52,7 +52,7 @@ * * The shader has three passes, chained together as follows: * - * |input|------------------ + * |input|------------------ * v | * [ SMAA*EdgeDetection ] | * v | @@ -62,7 +62,7 @@ * v | * |blendTex| | * v | - * [ SMAANeighborhoodBlending ] <------ + * [ SMAANeighborhoodBlending ] <------ * v * |output| * @@ -561,7 +561,7 @@ #define SMAATexturePass2D(tex) tex #define SMAASampleLevelZero(tex, coord) SAMPLE_TEXTURE2D_X_LOD(tex, LinearSampler, ClampAndScaleUVForBilinear(coord), 0) #define SMAASampleLevelZeroNoRescale(tex, coord) tex.SampleLevel(LinearSampler, coord, 0) -#define SMAASampleLevelZeroPoint(tex, coord) SAMPLE_TEXTURE2D_X_LOD(tex, PointSampler, ClampAndScaleUVForPoint(coord), 0) +#define SMAASampleLevelZeroPoint(tex, coord) SAMPLE_TEXTURE2D_X_LOD(tex, PointSampler, ClampAndScaleUVForPoint(coord), 0) #define SMAASampleLevelZeroOffset(tex, coord, offset) SAMPLE_TEXTURE2D_X_LOD(tex, LinearSampler, ClampAndScaleUVForBilinear(coord + offset * SMAA_RT_METRICS.xy), 0) #define SMAASample(tex, coord) SAMPLE_TEXTURE2D_X(tex, LinearSampler, ClampAndScaleUVForBilinear(coord)) #define SMAASamplePoint(tex, coord) SAMPLE_TEXTURE2D_X(tex, PointSampler, ClampAndScaleUVForPoint(coord)) diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader index 00970be6749..8c7c62e2620 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader @@ -17,7 +17,7 @@ Shader "Hidden/PostProcessing/SubpixelMorphologicalAntialiasing" { Cull Off ZWrite Off ZTest Always - // Edge detection + // Edge detection Pass { Stencil diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader index b0584eb0e91..18c25a82d1c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader @@ -29,7 +29,7 @@ Shader "Hidden/HDRP/TemporalAA" // Tier definitions // --------------------------------------------------- // TODO: YCoCg gives better result in terms of ghosting reduction, but it also seems to let through - // some additional aliasing that is undesirable in some occasions. Would like to investigate better. + // some additional aliasing that is undesirable in some occasions. Would like to investigate better. #ifdef LOW_QUALITY #define YCOCG 0 #define HISTORY_SAMPLING_METHOD BILINEAR @@ -57,7 +57,7 @@ Shader "Hidden/HDRP/TemporalAA" #elif defined(HIGH_QUALITY) // TODO: We can do better in term of quality here (e.g. subpixel changes etc) and can be optimized a bit more - #define YCOCG 1 + #define YCOCG 1 #define HISTORY_SAMPLING_METHOD BICUBIC_5TAP #define WIDE_NEIGHBOURHOOD 1 #define NEIGHBOUROOD_CORNER_METHOD VARIANCE @@ -70,7 +70,7 @@ Shader "Hidden/HDRP/TemporalAA" #define PERCEPTUAL_SPACE_ONLY_END 0 && (PERCEPTUAL_SPACE == 0) #elif defined(POST_DOF) - #define YCOCG 1 + #define YCOCG 1 #define HISTORY_SAMPLING_METHOD BILINEAR #define WIDE_NEIGHBOURHOOD 0 #define NEIGHBOUROOD_CORNER_METHOD VARIANCE @@ -167,7 +167,7 @@ Shader "Hidden/HDRP/TemporalAA" history.xyz *= PerceptualWeight(history); // ----------------------------------------------------- - // --------------- Gather neigbourhood data --------------- + // --------------- Gather neigbourhood data --------------- CTYPE color = Fetch4(_InputTexture, uv, 0.0, _RTHandleScale.xy).CTYPE_SWIZZLE; color = clamp(color, 0, CLAMP_MAX); color = ConvertToWorkingSpace(color); @@ -183,7 +183,7 @@ Shader "Hidden/HDRP/TemporalAA" if (offScreen) history = filteredColor; - // --------------- Get neighbourhood information and clamp history --------------- + // --------------- Get neighbourhood information and clamp history --------------- float colorLuma = GetLuma(filteredColor); float historyLuma = GetLuma(history); @@ -289,7 +289,7 @@ Shader "Hidden/HDRP/TemporalAA" { Stencil { - ReadMask [_StencilMask] + ReadMask [_StencilMask] Ref [_StencilRef] Comp Equal Pass Keep diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntialiasing.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntialiasing.hlsl index eaff2540d4d..501aa5610f0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntialiasing.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntialiasing.hlsl @@ -55,7 +55,7 @@ float4 Fetch4Array(Texture2DArray tex, uint slot, float2 coords, float2 offset, /// Neighbourhood sampling options #define PLUS 0 // Faster! Can allow for read across twice (paying cost of 2 samples only) -#define CROSS 1 // Can only do one fast read diagonal +#define CROSS 1 // Can only do one fast read diagonal #define SMALL_NEIGHBOURHOOD_SHAPE PLUS // Neighbourhood AABB options @@ -328,7 +328,7 @@ float ModifyBlendWithMotionVectorRejection(TEXTURE2D_X(VelocityMagnitudeTexture) } // --------------------------------------------------- -// History sampling +// History sampling // --------------------------------------------------- CTYPE HistoryBilinear(TEXTURE2D_X(HistoryTexture), float2 UV) @@ -418,7 +418,7 @@ CTYPE GetFilteredHistory(TEXTURE2D_X(HistoryTexture), float2 UV, float sharpenin // --------------------------------------------------- // Neighbourhood related. // --------------------------------------------------- -#define SMALL_NEIGHBOURHOOD_SIZE 4 +#define SMALL_NEIGHBOURHOOD_SIZE 4 #define NEIGHBOUR_COUNT ((WIDE_NEIGHBOURHOOD == 0) ? SMALL_NEIGHBOURHOOD_SIZE : 8) struct NeighbourhoodSamples diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute index 50377530ecc..1f7ec2be4d5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute @@ -177,7 +177,7 @@ void Uber(uint3 dispatchThreadId : SV_DispatchThreadID) } #ifdef ENABLE_ALPHA - // Bloom should also spread in areas with zero alpha, so we save the image with bloom here to do the mixing at the end of the shader + // Bloom should also spread in areas with zero alpha, so we save the image with bloom here to do the mixing at the end of the shader inputColor.xyz = color.xyz; #endif } diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_a.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_a.hlsl index 834f8034661..c0c5d7bc4ba 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_a.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_a.hlsl @@ -141,7 +141,7 @@ static AW1 AMaxW1(AW1 a,AW1 b){return a>b?a:b;} static AU1 AMaxU1(AU1 a,AU1 b){return a>b?a:b;} static AL1 AMaxL1(AL1 a,AL1 b){return a>b?a:b;} - // These follow the convention that A integer types don't have sign, until they are operated on. + // These follow the convention that A integer types don't have sign, until they are operated on. static AB1 AMaxSB1(AB1 a,AB1 b){return ((ASB1)a)>((ASB1)b)?a:b;} static AW1 AMaxSW1(AW1 a,AW1 b){return ((ASW1)a)>((ASW1)b)?a:b;} static AU1 AMaxSU1(AU1 a,AU1 b){return ((ASU1)a)>((ASU1)b)?a:b;} @@ -259,7 +259,7 @@ #ifndef A_SKIP_EXT #ifdef A_HALF //#extension GL_EXT_shader_16bit_storage:require - //#extension GL_EXT_shader_explicit_arithmetic_types:require + //#extension GL_EXT_shader_explicit_arithmetic_types:require #endif //------------------------------------------------------------------------------------------------------------------------------ #ifdef A_LONG @@ -641,7 +641,7 @@ #define AU4_AF4(x) asuint(AF4(x)) //------------------------------------------------------------------------------------------------------------------------------ AU1 AU1_AH2_AF2_x(AF2 a){return f32tof16(a.x)|(f32tof16(a.y)<<16);} - #define AU1_AH2_AF2(a) AU1_AH2_AF2_x(AF2(a)) + #define AU1_AH2_AF2(a) AU1_AH2_AF2_x(AF2(a)) #define AU1_AB4Unorm_AF4(x) D3DCOLORtoUBYTE4(AF4(x)) //------------------------------------------------------------------------------------------------------------------------------ AF2 AF2_AH2_AU1_x(AU1 x){return AF2(f16tof32(x&0xFFFF),f16tof32(x>>16));} @@ -945,7 +945,7 @@ // IDEAS // ===== // - Polaris hardware has 16-bit support, but non-double rate. -// Could be possible still get part double rate for some of this logic, +// Could be possible still get part double rate for some of this logic, // by clearing out the lower half's sign when necessary and using 32-bit ops... //============================================================================================================================== #ifdef A_HALF @@ -1003,14 +1003,14 @@ // Valid input range is {-1 to 1} representing {0 to 2 pi}. // Output range is {-1/4 to -1/4} representing {-1 to 1}. AF1 APSinF1(AF1 x){return x*abs(x)-x;} // MAD. - AF1 APCosF1(AF1 x){x=AFractF1(x*AF1_(0.5)+AF1_(0.75));x=x*AF1_(2.0)-AF1_(1.0);return APSinF1(x);} // 3x MAD, FRACT + AF1 APCosF1(AF1 x){x=AFractF1(x*AF1_(0.5)+AF1_(0.75));x=x*AF1_(2.0)-AF1_(1.0);return APSinF1(x);} // 3x MAD, FRACT //------------------------------------------------------------------------------------------------------------------------------ #ifdef A_HALF // For a packed {sin,cos} pair, // - Native takes 16 clocks and 4 issue slots (no packed transcendentals). // - Parabolic takes 8 clocks and 8 issue slots (only fract is non-packed). AH2 APSinH2(AH2 x){return x*abs(x)-x;} // AND,FMA - AH2 APCosH2(AH2 x){x=AFractH2(x*AH2_(0.5)+AH2_(0.75));x=x*AH2_(2.0)-AH2_(1.0);return APSinH2(x);} // 3x FMA, 2xFRACT, AND + AH2 APCosH2(AH2 x){x=AFractH2(x*AH2_(0.5)+AH2_(0.75));x=x*AH2_(2.0)-AH2_(1.0);return APSinH2(x);} // 3x FMA, 2xFRACT, AND #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1052,7 +1052,7 @@ AF1 ATo709F1(AF1 c){return max(min(c*AF1_(4.5),AF1_(0.018)),AF1_(1.099)*pow(c,AF1_(0.45))-AF1_(0.099));} //------------------------------------------------------------------------------------------------------------------------------ // Note 'rcpX' is '1/x', where the 'x' is what would be used in AFromGamma(). - AF1 AToGammaF1(AF1 c,AF1 rcpX){return pow(c,rcpX);} + AF1 AToGammaF1(AF1 c,AF1 rcpX){return pow(c,rcpX);} //------------------------------------------------------------------------------------------------------------------------------ AF1 AToPqF1(AF1 x){AF1 p=pow(x,AF1_(0.159302)); return pow((AF1_(0.835938)+AF1_(18.8516)*p)/(AF1_(1.0)+AF1_(18.6875)*p),AF1_(78.8438));} @@ -1064,7 +1064,7 @@ AF1 AFrom709F1(AF1 c){return max(min(c*AF1_(1.0/4.5),AF1_(0.081)), pow((c+AF1_(0.099))*(AF1_(1.0)/(AF1_(1.099))),AF1_(1.0/0.45)));} //------------------------------------------------------------------------------------------------------------------------------ - AF1 AFromGammaF1(AF1 c,AF1 x){return pow(c,x);} + AF1 AFromGammaF1(AF1 c,AF1 x){return pow(c,x);} //------------------------------------------------------------------------------------------------------------------------------ AF1 AFromPqF1(AF1 x){AF1 p=pow(x,AF1_(0.0126833)); return pow(ASatF1(p-AF1_(0.835938))/(AF1_(18.8516)-AF1_(18.6875)*p),AF1_(6.27739));} @@ -1077,7 +1077,7 @@ #ifdef A_HALF AH2 ATo709H2(AH2 c){return max(min(c*AH2_(4.5),AH2_(0.018)),AH2_(1.099)*pow(c,AH2_(0.45))-AH2_(0.099));} //------------------------------------------------------------------------------------------------------------------------------ - AH2 AToGammaH2(AH2 c,AH1 rcpX){return pow(c,AH2_(rcpX));} + AH2 AToGammaH2(AH2 c,AH1 rcpX){return pow(c,AH2_(rcpX));} //------------------------------------------------------------------------------------------------------------------------------ AH2 AToSrgbH2(AH2 c){return max(min(c*AH2_(12.92),AH2_(0.0031308)),AH2_(1.055)*pow(c,AH2_(0.41666))-AH2_(0.055));} //------------------------------------------------------------------------------------------------------------------------------ @@ -1116,14 +1116,14 @@ // Details, // LANE TO 8x8 MAPPING // =================== - // 00 01 08 09 10 11 18 19 + // 00 01 08 09 10 11 18 19 // 02 03 0a 0b 12 13 1a 1b // 04 05 0c 0d 14 15 1c 1d - // 06 07 0e 0f 16 17 1e 1f - // 20 21 28 29 30 31 38 39 + // 06 07 0e 0f 16 17 1e 1f + // 20 21 28 29 30 31 38 39 // 22 23 2a 2b 32 33 3a 3b // 24 25 2c 2d 34 35 3c 3d - // 26 27 2e 2f 36 37 3e 3f + // 26 27 2e 2f 36 37 3e 3f AU2 ARmpRed8x8(AU1 a){return AU2(ABfiM(ABfe(a,2u,3u),a,1u),ABfiM(ABfe(a,3u,3u),ABfe(a,1u,2u),2u));} #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1175,7 +1175,7 @@ // ... // 1023 = 2^(-14)*(1-2^(-10)) = 2^(-14)*(1-1/1024) ... last denormal value // 1024 = 2^(-14) = 1/16384 .......................... first normal value that still maps to integers -// 2047 .............................................. last normal value that still maps to integers +// 2047 .............................................. last normal value that still maps to integers // Scaling limits, // 2^15 = 32768 ...................................... largest power of 2 scaling // Largest pow2 conversion mapping is at *32768, @@ -1183,4 +1183,3 @@ // 1024 : 8 // 2047 : a little less than 16 //============================================================================================================================== - diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_cas.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_cas.hlsl index d95dabeea08..5ae75cbb1aa 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_cas.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_cas.hlsl @@ -80,7 +80,7 @@ // =========================== // // Setup layout. Example below for VK_FORMAT_R16G16B16A16_SFLOAT. // layout(set=0,binding=0,rgba16f)uniform image2D imgSrc; -// layout(set=0,binding=1,rgba16f)uniform image2D imgDst; +// layout(set=0,binding=1,rgba16f)uniform image2D imgDst; // ... // // Setup pre-portability-header defines (sets up GLSL/HLSL path, packed math support, etc) // #define A_GPU 1 @@ -183,7 +183,7 @@ // - This could be used for both sRGB or FreeSync2 native (gamma 2.2) cases. // - Load/store with either 10:10:10:2 UNORM or 8:8:8:8 UNORM (aka VK_FORMAT_R8G8B8A8_UNORM). // - Use gamma 2.0 conversion in CasInput(), as an approximation. -// - Modifications: +// - Modifications: // // Change the CasInput*() function to square the inputs. // void CasInput(inout AF1 r,inout AF1 g,inout AF1 b){r*=r;g*=g;b*=b;} // void CasInputH(inout AH2 r,inout AH2 g,inout AH2 b){r*=r;g*=g;b*=b;} @@ -304,7 +304,7 @@ // This 'A' ranges from 0 := no sharpening, to 1 := full sharpening. // Then 'A' is scaled by the sharpness knob while being transformed to a negative lobe (values from -1/5 to -1/8 for A=1). // The final filter kernel looks like this, -// 0 A 0 +// 0 A 0 // A 1 A <-- Center is always 1.0, followed by the negative lobe 'A' in a ring, and windowed into a circle with the 0.0s. // 0 A 0 // The local neighborhood is then multiplied by the kernel weights, summed and divided by the sum of the kernel weights. @@ -321,7 +321,7 @@ // It then interpolates between those no-scaling results. // The interpolation is adaptive. // To hide bilinear interpolation and restore diagonals, it bilaterally weights by closer distance to 2x2 average. -// This makes visual edges thin out a little. +// This makes visual edges thin out a little. // The weighting uses the maximums computed in the prior filtering logic. //------------------------------------------------------------------------------------------------------------------------------ // IDEAS FOR FUTURE @@ -418,17 +418,17 @@ AP1 CasSupportScaling(AF1 outX,AF1 outY,AF1 inX,AF1 inY){return ((outX*outY)/(in AU4 const0, // Constants generated by CasSetup(). AU4 const1, AP1 noScaling, // Must be a compile-time literal value, true = sharpen only (no resize). - AP1 lowQuality){ // Must be a compile-time literal value, true = weight by green channel (faster, but lower quality). + AP1 lowQuality){ // Must be a compile-time literal value, true = weight by green channel (faster, but lower quality). //------------------------------------------------------------------------------------------------------------------------------ // Debug a checker pattern of on/off tiles for visual inspection. #ifdef CAS_DEBUG_CHECKER if((((ip.x^ip.y)>>8u)&1u)==0u){AF3 pix0=CasLoad(ASU2(ip)); pixR=pix0.r;pixG=pix0.g;pixB=pix0.b;CasInput(pixR,pixG,pixB);return;} - #endif + #endif //------------------------------------------------------------------------------------------------------------------------------ // No scaling algorithm uses minimal 3x3 pixel neighborhood. if(noScaling){ - // a b c + // a b c // d e f // g h i ASU2 sp=ASU2(ip); @@ -781,7 +781,7 @@ AP1 CasSupportScaling(AF1 outX,AF1 outY,AF1 inX,AF1 inY){return ((outX*outY)/(in // i j k l // n o // _____ _____ _____ _____ - // fs gt + // fs gt // // _____ _____ _____ _____ // fs s gt fs t gt @@ -870,13 +870,13 @@ AP1 CasSupportScaling(AF1 outX,AF1 outY,AF1 inX,AF1 inY){return ((outX*outY)/(in AU4 const0, // Constants generated by CasSetup(). AU4 const1, AP1 noScaling, // Must be a compile-time literal value, true = sharpen only (no resize). - AP1 lowQuality){ // Must be a compile-time literal value, true = weight by green channel (faster, but lower quality). + AP1 lowQuality){ // Must be a compile-time literal value, true = weight by green channel (faster, but lower quality). //------------------------------------------------------------------------------------------------------------------------------ // Debug a checker pattern of on/off tiles for visual inspection. #ifdef CAS_DEBUG_CHECKER if((((ip.x^ip.y)>>8u)&1u)==0u){AH3 pix0=CasLoadH(ASW2(ip));AH3 pix1=CasLoadH(ASW2(ip)+ASW2(8,0)); pixR=AH2(pix0.r,pix1.r);pixG=AH2(pix0.g,pix1.g);pixB=AH2(pix0.b,pix1.b);CasInputH(pixR,pixG,pixB);return;} - #endif + #endif //------------------------------------------------------------------------------------------------------------------------------ // No scaling algorithm uses minimal 3x3 pixel neighborhood. if(noScaling){ @@ -941,7 +941,7 @@ AP1 CasSupportScaling(AF1 outX,AF1 outY,AF1 inX,AF1 inY){return ((outX*outY)/(in // Soft min and max. AH2 mnR=min(min(fR,hR),min(min(bR,dR),eR)); AH2 mnG=min(min(fG,hG),min(min(bG,dG),eG)); - AH2 mnB=min(min(fB,hB),min(min(bB,dB),eB)); + AH2 mnB=min(min(fB,hB),min(min(bB,dB),eB)); AH2 mnR2=min(min(gR,iR),min(min(aR,cR),mnR)); AH2 mnG2=min(min(gG,iG),min(min(aG,cG),mnG)); AH2 mnB2=min(min(gB,iB),min(min(aB,cB),mnB)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_lpm.hlsl b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_lpm.hlsl index d29152decca..89d99f126c3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_lpm.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ffx_lpm.hlsl @@ -59,9 +59,9 @@ // Or reduce green a little {1.0,1.0/2.0,1.0/32.0} -> to tint blues towards purple on over-exposure. // If wanting a stronger blue->purple, drop both green and blue {1.0,1.0/4.0,1.0/128.0}. // Note that crosstalk value should be tuned differently based on the color space. -// Suggest tuning crosstalk separately for Rec.2020 and Rec.709 primaries for example. +// Suggest tuning crosstalk separately for Rec.2020 and Rec.709 primaries for example. //------------------------------------------------------------------------------------------------------------------------------ -// SETUP THE MAPPER +// SETUP THE MAPPER // ================ // This would typically be done on the CPU, but showing the GPU code here. // ... @@ -105,7 +105,7 @@ // ... // mapM=constants.mapM; // mapN=constants.mapN; -// ... +// ... // // Run the tone/gamut-mapper. // // The 'c.rgb' is the color to map, using the no-shoulder tuning option. // LpmFilter(c.r,c.g,c.b,false,LPM_CONFIG_709_709, // <-- Using the LPM_CONFIG_ prefab to make inputs easier. @@ -154,7 +154,7 @@ //------------------------------------------------------------------------------------------------------------------------------ // Used by LpmSetup() to build constants for the GPU setup path. //------------------------------------------------------------------------------------------------------------------------------ -// Color math references, +// Color math references, // - http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html // - https://en.wikipedia.org/wiki/SRGB#The_sRGB_transfer_function_.28.22gamma.22.29 // - http://www.ryanjuckett.com/programming/rgb-color-space-conversion/ @@ -210,7 +210,7 @@ ox=r3*s;oy=g3*s;oz=b3*s;} //============================================================================================================================== // Visualize difference between two values, by bits of precision. - // This is useful when doing approximation to reference comparisons. + // This is useful when doing approximation to reference comparisons. AP1 LpmD(AF1 a,AF1 b){return abs(a-b)<1.0;} //------------------------------------------------------------------------------------------------------------------------------ AF1 LpmC(AF1 a,AF1 b){AF1 c=1.0; // 6-bits or less (the color) @@ -227,7 +227,7 @@ //============================================================================================================================== // HDR10 RANGE LIMITING SCALAR //------------------------------------------------------------------------------------------------------------------------------ -// As of 2019, HDR10 supporting TVs typically have PQ tonal curves with near clipping long before getting to the peak 10K nits. +// As of 2019, HDR10 supporting TVs typically have PQ tonal curves with near clipping long before getting to the peak 10K nits. // Unfortunately this clipping point changes per TV (requires some amount of user calibration). // Some examples, // https://youtu.be/M7OsbpU4oCQ?t=875 @@ -272,7 +272,7 @@ // 2020 ......... Rec.2020 // 709 .......... Rec.709 // P3 ........... DCI-P3 with D65 white-point -// -------------- +// -------------- // OUTPUT COLOR SPACE // ================== // FS2RAW ....... Faster 32-bit/pixel FreeSync2 raw gamma 2.2 output (native display primaries) @@ -406,12 +406,12 @@ // map0 saturation.r saturation.g saturation.b contrast // map1 toneScaleBias.x toneScaleBias.y lumaT.r lumaT.g // map2 lumaT.b crosstalk.r crosstalk.g crosstalk.b -// map3 rcpLumaT.r rcpLumaT.g rcpLumaT.b con2R.r +// map3 rcpLumaT.r rcpLumaT.g rcpLumaT.b con2R.r // -- -// map4 con2R.g con2R.b con2G.r con2G.g +// map4 con2R.g con2R.b con2G.r con2G.g // map5 con2G.b con2B.r con2B.g con2B.b // map6 shoulderContrast lumaW.r lumaW.g lumaW.b -// map7 softGap.x softGap.y conR.r conR.g +// map7 softGap.x softGap.y conR.r conR.g // -- // map8 conR.b conG.r conG.g conG.b // map9 conB.r conB.g conB.b (reserved) @@ -428,11 +428,11 @@ // mapG.rg saturation.r saturation.g saturation.b contrast // mapG.ba toneScaleBias.x toneScaleBias.y lumaT.r lumaT.g // mapH.rg lumaT.b crosstalk.r crosstalk.g crosstalk.b -// mapH.ba rcpLumaT.r rcpLumaT.g rcpLumaT.b con2R.r -// mapI.rg con2R.g con2R.b con2G.r con2G.g +// mapH.ba rcpLumaT.r rcpLumaT.g rcpLumaT.b con2R.r +// mapI.rg con2R.g con2R.b con2G.r con2G.g // mapI.ba con2G.b con2B.r con2B.g con2B.b // mapJ.rg shoulderContrast lumaW.r lumaW.g lumaW.b -// mapJ.ba softGap.x softGap.y conR.r conR.g +// mapJ.ba softGap.x softGap.y conR.r conR.g // -- // mapK.rg conR.b conG.r conG.g conG.b // mapK.ba conB.r conB.g conB.b (reserved) @@ -470,9 +470,9 @@ AF1 softGap, // Range of 0 to a little over zero, controls how much feather region in out-of-gamut mapping, 0=clip. // Tonemapping control. AF1 hdrMax, // Maximum input value. - AF1 exposure, // Number of stops between 'hdrMax' and 18% mid-level on input. + AF1 exposure, // Number of stops between 'hdrMax' and 18% mid-level on input. AF1 contrast, // Input range {0.0 (no extra contrast) to 1.0 (maximum contrast)}. - AF1 shoulderContrast, // Shoulder shaping, 1.0 = no change (fast path). + AF1 shoulderContrast, // Shoulder shaping, 1.0 = no change (fast path). AF3 saturation, // A per channel adjustment, use <0 decrease, 0=no change, >0 increase. AF3 crosstalk){ // One channel must be 1.0, the rest can be <= 1.0 but not zero. //----------------------------------------------------------------------------------------------------------------------------- @@ -498,14 +498,14 @@ AF1 w2=pow(hdrMax,cs)*midOut; AF1 w3=pow(midIn,cs)*midOut; toneScaleBias.y=(w0-w1)/(w2-w3); -//----------------------------------------------------------------------------------------------------------------------------- +//----------------------------------------------------------------------------------------------------------------------------- AF3 lumaW;AF3 rgbToXyzXW;AF3 rgbToXyzYW;AF3 rgbToXyzZW; LpmColRgbToXyz(rgbToXyzXW,rgbToXyzYW,rgbToXyzZW,xyRedW,xyGreenW,xyBlueW,xyWhiteW); // Use the Y vector of the matrix for the associated luma coef. // For safety, make sure the vector sums to 1.0. lumaW=rgbToXyzYW; lumaW*=ARcpF1(lumaW.r+lumaW.g+lumaW.b); -//----------------------------------------------------------------------------------------------------------------------------- +//----------------------------------------------------------------------------------------------------------------------------- // The 'lumaT' for crosstalk mapping is always based on the output color space, unless soft conversion is not used. AF3 lumaT;AF3 rgbToXyzXO;AF3 rgbToXyzYO;AF3 rgbToXyzZO; LpmColRgbToXyz(rgbToXyzXO,rgbToXyzYO,rgbToXyzZO,xyRedO,xyGreenO,xyBlueO,xyWhiteO); @@ -589,7 +589,7 @@ mapK.ba=AU2_AH4(AH4(AH1(conB.r),AH1(conB.g),AH1(conB.b),AH1(0.0))); #ifdef A_HLSL mapL=mapM=mapN=AU4_(0); - #endif + #endif #endif } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -622,7 +622,7 @@ AP1 con, // Use first RGB conversion matrix (should be a compile-time immediate), if 'soft' then 'con' must be true also. AF3 conR,AF3 conG,AF3 conB, // RGB conversion matrix (working to output space conversion). AP1 soft, // Use soft gamut mapping (should be a compile-time immediate). - AF2 softGap, // {x,(1-x)/(x*0.693147180559)}, where 'x' is gamut mapping soft fall-off amount. + AF2 softGap, // {x,(1-x)/(x*0.693147180559)}, where 'x' is gamut mapping soft fall-off amount. AP1 con2, // Use last RGB conversion matrix (should be a compile-time immediate). AP1 clip, // Use clipping on last conversion matrix. AP1 scaleOnly, // Do scaling only (special case for 709 HDR to scRGB). @@ -678,7 +678,7 @@ colorR=ASatF1(ratioR*ratioScale);colorG=ASatF1(ratioG*ratioScale);colorB=ASatF1(ratioB*ratioScale); // Capability per channel to increase value (3x MAD). // This factors in crosstalk factor to avoid multiplies later. - // '(1.0-ratio)*crosstalk' optimized to '-crosstalk*ratio+crosstalk' + // '(1.0-ratio)*crosstalk' optimized to '-crosstalk*ratio+crosstalk' AF1 capR=AF1_(-crosstalk.r)*colorR+AF1_(crosstalk.r); AF1 capG=AF1_(-crosstalk.g)*colorG+AF1_(crosstalk.g); AF1 capB=AF1_(-crosstalk.b)*colorB+AF1_(crosstalk.b); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/SubFrameManager.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/SubFrameManager.cs index 5bfd3ce6183..75779e829da 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/SubFrameManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/SubFrameManager.cs @@ -4,7 +4,7 @@ using UnityEngine.Experimental.Rendering; #if UNITY_EDITOR - using UnityEditor; +using UnityEditor; #endif // UNITY_EDITOR namespace UnityEngine.Rendering.HighDefinition @@ -84,15 +84,18 @@ internal void Reset(int camID) camData.ResetIteration(); SetCameraData(camID, camData); } + internal void Reset() { foreach (int camID in m_CameraCache.Keys.ToList()) Reset(camID); } + internal void Clear() { m_CameraCache.Clear(); } + internal void SelectiveReset(uint maxSamples) { foreach (int camID in m_CameraCache.Keys.ToList()) @@ -221,7 +224,7 @@ internal Vector4 ComputeFrameWeights(int camID) CameraData camData = GetCameraData(camID); float totalWeight = camData.accumulatedWeight; - float time = m_AccumulationSamples > 0 ? (float) camData.currentIteration / m_AccumulationSamples : 0.0f; + float time = m_AccumulationSamples > 0 ? (float)camData.currentIteration / m_AccumulationSamples : 0.0f; float weight = isRecording ? ShutterProfile(time) : 1.0f; @@ -354,5 +357,4 @@ static void RenderAccumulation(in RenderAccumulationParameters parameters, RTHan } } } - } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.Migration.cs index 9422ce17d48..3657ebfb52d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.Migration.cs @@ -65,7 +65,7 @@ protected enum Version }), MigrationStep.New(Version.AddReflectionSettings, (HDAdditionalCameraData data) => FrameSettings.MigrateToDefaultReflectionSettings(ref data.renderingPathCustomFrameSettings) - ), + ), MigrationStep.New(Version.AddCustomPostprocessAndCustomPass, (HDAdditionalCameraData data) => { FrameSettings.MigrateToCustomPostprocessAndCustomPass(ref data.renderingPathCustomFrameSettings); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs index aaaf4d3c588..bc0087105fc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs @@ -31,18 +31,18 @@ public class HDPhysicalCamera public const int kMaxBladeCount = 11; // Camera body - [SerializeField] [Min(1f)] int m_Iso = 200; - [SerializeField] [Min(0f)] float m_ShutterSpeed = 1f / 200f; + [SerializeField][Min(1f)] int m_Iso = 200; + [SerializeField][Min(0f)] float m_ShutterSpeed = 1f / 200f; // Lens // Note: focalLength is already defined in the regular camera component - [SerializeField] [Range(kMinAperture, kMaxAperture)] float m_Aperture = 16f; + [SerializeField][Range(kMinAperture, kMaxAperture)] float m_Aperture = 16f; // Aperture shape - [SerializeField] [Range(kMinBladeCount, kMaxBladeCount)] int m_BladeCount = 5; + [SerializeField][Range(kMinBladeCount, kMaxBladeCount)] int m_BladeCount = 5; [SerializeField] Vector2 m_Curvature = new Vector2(2f, 11f); - [SerializeField] [Range(0f, 1f)] float m_BarrelClipping = 0.25f; - [SerializeField] [Range(-1f, 1f)] float m_Anamorphism = 0f; + [SerializeField][Range(0f, 1f)] float m_BarrelClipping = 0.25f; + [SerializeField][Range(-1f, 1f)] float m_Anamorphism = 0f; /// /// The sensor sensitivity (ISO). @@ -289,7 +289,7 @@ public enum TAAQualityLevel [Range(0.0f, 1.0f)] public float taaAntiFlicker = 0.5f; - /// Larger is this value, more likely history will be rejected when current and reprojected history motion vector differ by a substantial amount. + /// Larger is this value, more likely history will be rejected when current and reprojected history motion vector differ by a substantial amount. /// Larger values can decrease ghosting but will also reintroduce aliasing on the aforementioned cases. [Range(0.0f, 1.0f)] public float taaMotionVectorRejection = 0.0f; @@ -381,10 +381,10 @@ string IFrameSettingsHistoryContainer.panelName /// /// . Action IDebugData.GetReset() - //caution: we actually need to retrieve the right - //m_FrameSettingsHistory as it is a struct so no direct - // => m_FrameSettingsHistory.TriggerReset - => () => m_RenderingPathHistory.TriggerReset(); + //caution: we actually need to retrieve the right + //m_FrameSettingsHistory as it is a struct so no direct + // => m_FrameSettingsHistory.TriggerReset + => () => m_RenderingPathHistory.TriggerReset(); internal ProfilingSampler profilingSampler; @@ -657,7 +657,7 @@ public RTHandle GetGraphicsBuffer(BufferAccessType type) { HDCamera hdCamera = HDCamera.GetOrCreate(m_Camera); if ((type & BufferAccessType.Color) != 0) - return hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain); + return hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain); else if ((type & BufferAccessType.Depth) != 0) return hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth); else if ((type & BufferAccessType.Normal) != 0) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs index f1140e236a9..26f6a155c9c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs @@ -164,6 +164,7 @@ public RTHandle GetCurrentFrameRT(int id) { return m_HistoryRTSystem.GetFrameRT(id, 0); } + #endregion #region Internal API @@ -345,13 +346,13 @@ internal GameObject exposureTarget internal IEnumerable aovRequests => m_AdditionalCameraData != null && !m_AdditionalCameraData.Equals(null) - ? m_AdditionalCameraData.aovRequests - : Enumerable.Empty(); + ? m_AdditionalCameraData.aovRequests + : Enumerable.Empty(); internal LayerMask probeLayerMask => m_AdditionalCameraData != null ? m_AdditionalCameraData.probeLayerMask - : (LayerMask)~0; + : (LayerMask) ~0; internal float probeRangeCompressionFactor => m_AdditionalCameraData != null @@ -361,8 +362,8 @@ internal float probeRangeCompressionFactor internal bool ValidShadowHistory(HDAdditionalLightData lightData, int screenSpaceShadowIndex, GPULightType lightType) { return shadowHistoryUsage[screenSpaceShadowIndex].lightInstanceID == lightData.GetInstanceID() - && (shadowHistoryUsage[screenSpaceShadowIndex].frameCount == (cameraFrameCount - 1)) - && (shadowHistoryUsage[screenSpaceShadowIndex].lightType == lightType); + && (shadowHistoryUsage[screenSpaceShadowIndex].frameCount == (cameraFrameCount - 1)) + && (shadowHistoryUsage[screenSpaceShadowIndex].lightType == lightType); } internal void PropagateShadowHistory(HDAdditionalLightData lightData, int screenSpaceShadowIndex, GPULightType lightType) @@ -375,8 +376,8 @@ internal void PropagateShadowHistory(HDAdditionalLightData lightData, int screen internal bool EffectHistoryValidity(HistoryEffectSlot slot, bool fullResolution, bool rayTraced) { return (historyEffectUsage[(int)slot].frameCount == (cameraFrameCount - 1)) - && (historyEffectUsage[(int)slot].fullResolution == fullResolution) - && (historyEffectUsage[(int)slot].rayTraced == rayTraced); + && (historyEffectUsage[(int)slot].fullResolution == fullResolution) + && (historyEffectUsage[(int)slot].rayTraced == rayTraced); } internal void PropagateEffectHistoryValidity(HistoryEffectSlot slot, bool fullResolution, bool rayTraced) @@ -463,7 +464,7 @@ internal void Update(FrameSettings currentFrameSettings, HDRenderPipeline hdrp, if (historyEffectUsage == null || historyEffectUsage.Length != (int)HistoryEffectSlot.Count) { historyEffectUsage = new HistoryEffectValidity[(int)HistoryEffectSlot.Count]; - for(int i = 0; i < (int)HistoryEffectSlot.Count; ++i) + for (int i = 0; i < (int)HistoryEffectSlot.Count; ++i) { // We invalidate all the frame indices for the first usage historyEffectUsage[i].frameCount = -1; @@ -633,7 +634,6 @@ internal static void ClearAll() // Look for any camera that hasn't been used in the last frame and remove them from the pool. internal static void CleanUnused() { - foreach (var key in s_Cameras.Keys) { var camera = s_Cameras[key]; @@ -721,10 +721,9 @@ unsafe internal void UpdateShaderVariablesGlobalCB(ref ShaderVariablesGlobal cb, cb._ProbeExposureScale = exposureMultiplierForProbes; cb._TransparentCameraOnlyMotionVectors = (frameSettings.IsEnabled(FrameSettingsField.MotionVectors) && - !frameSettings.IsEnabled(FrameSettingsField.TransparentsWriteMotionVector)) ? 1 : 0; + !frameSettings.IsEnabled(FrameSettingsField.TransparentsWriteMotionVector)) ? 1 : 0; } - unsafe internal void UpdateShaderVariablesXRCB(ref ShaderVariablesXR cb) { for (int i = 0; i < viewCount; i++) @@ -848,21 +847,21 @@ internal void ExecuteCaptureActions(RenderGraph renderGraph, TextureHandle input // We need to blit to an intermediate texture because input resolution can be bigger than the camera resolution // Since recorder does not know about this, we need to send a texture of the right size. passData.tempTexture = builder.CreateTransientTexture(new TextureDesc(actualWidth, actualHeight) - { colorFormat = inputDesc.colorFormat, name = "TempCaptureActions" }); + { colorFormat = inputDesc.colorFormat, name = "TempCaptureActions" }); builder.SetRenderFunc( - (ExecuteCaptureActionsPassData data, RenderGraphContext ctx) => - { - var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock(); - mpb.SetTexture(HDShaderIDs._BlitTexture, data.input); - mpb.SetVector(HDShaderIDs._BlitScaleBias, data.viewportScale); - mpb.SetFloat(HDShaderIDs._BlitMipLevel, 0); - ctx.cmd.SetRenderTarget(data.tempTexture); - ctx.cmd.DrawProcedural(Matrix4x4.identity, data.blitMaterial, 0, MeshTopology.Triangles, 3, 1, mpb); - - for (data.recorderCaptureActions.Reset(); data.recorderCaptureActions.MoveNext();) - data.recorderCaptureActions.Current(data.tempTexture, ctx.cmd); - }); + (ExecuteCaptureActionsPassData data, RenderGraphContext ctx) => + { + var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock(); + mpb.SetTexture(HDShaderIDs._BlitTexture, data.input); + mpb.SetVector(HDShaderIDs._BlitScaleBias, data.viewportScale); + mpb.SetFloat(HDShaderIDs._BlitMipLevel, 0); + ctx.cmd.SetRenderTarget(data.tempTexture); + ctx.cmd.DrawProcedural(Matrix4x4.identity, data.blitMaterial, 0, MeshTopology.Triangles, 3, 1, mpb); + + for (data.recorderCaptureActions.Reset(); data.recorderCaptureActions.MoveNext();) + data.recorderCaptureActions.Current(data.tempTexture, ctx.cmd); + }); } } @@ -897,7 +896,6 @@ internal void UpdateCurrentSky(SkyManager skyManager) m_LightingOverrideSky.skySettings = newSkyOverride; lightingSky = m_LightingOverrideSky; - } else { @@ -946,7 +944,7 @@ public RTHandle Allocator(string id, int frameIndex, RTHandleSystem rtHandleSyst float m_AmbientOcclusionResolutionScale = 0.0f; // Factor used to track if history should be reallocated for Ambient Occlusion float m_ScreenSpaceAccumulationResolutionScale = 0.0f; // Use another scale if AO & SSR don't have the same resolution public ScreenSpaceReflectionAlgorithm - currentSSRAlgorithm = ScreenSpaceReflectionAlgorithm.Approximation; // Store current algorithm which help to know if we trigger to reset history SSR Buffers + currentSSRAlgorithm = ScreenSpaceReflectionAlgorithm.Approximation; // Store current algorithm which help to know if we trigger to reset history SSR Buffers internal ViewConstants[] m_XRViewConstants; @@ -997,7 +995,6 @@ void UpdateAntialiasing() taaAntiFlicker = m_AdditionalCameraData.taaAntiFlicker; taaAntiRinging = m_AdditionalCameraData.taaAntiHistoryRinging; taaMotionVectorRejection = m_AdditionalCameraData.taaMotionVectorRejection; - } else antialiasing = AntialiasingMode.None; @@ -1010,7 +1007,7 @@ void UpdateAntialiasing() } // When changing antialiasing mode to TemporalAA we must reset the history, otherwise we get one frame of garbage - if ( (previousAntialiasing != antialiasing && antialiasing == AntialiasingMode.TemporalAntialiasing) + if ((previousAntialiasing != antialiasing && antialiasing == AntialiasingMode.TemporalAntialiasing) || (m_PreviousClearColorMode != clearColorMode)) { resetPostProcessingHistory = true; @@ -1075,7 +1072,7 @@ void UpdateAllViewConstants(bool jitterProjectionMatrix, bool updatePreviousFram void UpdateViewConstants(ref ViewConstants viewConstants, Matrix4x4 projMatrix, Matrix4x4 viewMatrix, Vector3 cameraPosition, bool jitterProjectionMatrix, bool updatePreviousFrameConstants) { - // If TAA is enabled projMatrix will hold a jittered projection matrix. The original, + // If TAA is enabled projMatrix will hold a jittered projection matrix. The original, // non-jittered projection matrix can be accessed via nonJitteredProjMatrix. var nonJitteredCameraProj = projMatrix; var cameraProj = jitterProjectionMatrix @@ -1100,7 +1097,6 @@ void UpdateViewConstants(ref ViewConstants viewConstants, Matrix4x4 projMatrix, { // In case we are not camera relative, gpuView contains the camera translation component at this stage, so we need to remove it. noTransViewMatrix.SetColumn(3, new Vector4(0, 0, 0, 1)); - } var gpuVPNoTrans = gpuNonJitteredProj * noTransViewMatrix; @@ -1403,8 +1399,8 @@ static RTHandle HistoryBufferAllocatorFunction(string viewName, int frameIndex, var hdPipeline = (HDRenderPipeline)RenderPipelineManager.currentPipeline; return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: (GraphicsFormat)hdPipeline.currentPlatformRenderPipelineSettings.colorBufferFormat, - dimension: TextureXR.dimension, enableRandomWrite: true, useMipMap: true, autoGenerateMips: false, useDynamicScale: true, - name: string.Format("{0}_CameraColorBufferMipChain{1}", viewName, frameIndex)); + dimension: TextureXR.dimension, enableRandomWrite: true, useMipMap: true, autoGenerateMips: false, useDynamicScale: true, + name: string.Format("{0}_CameraColorBufferMipChain{1}", viewName, frameIndex)); } void ReleaseHistoryBuffer() @@ -1419,6 +1415,7 @@ Rect GetPixelRect() else return new Rect(camera.pixelRect.x, camera.pixelRect.y, camera.pixelWidth, camera.pixelHeight); } + #endregion } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/CullingGroupManager.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/CullingGroupManager.cs index 085a34cb30a..06c8ad1d7f5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/CullingGroupManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/CullingGroupManager.cs @@ -2,7 +2,6 @@ namespace UnityEngine.Rendering.HighDefinition { - class CullingGroupManager { static CullingGroupManager m_Instance; @@ -21,7 +20,7 @@ static public CullingGroupManager instance public CullingGroup Alloc() { CullingGroup group; - if(m_FreeList.Count > 0) + if (m_FreeList.Count > 0) { group = m_FreeList.Pop(); } @@ -39,7 +38,7 @@ public void Free(CullingGroup group) public void Cleanup() { - foreach( CullingGroup group in m_FreeList) + foreach (CullingGroup group in m_FreeList) { group.Dispose(); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalLightingQualitySettings.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalLightingQualitySettings.cs index 17a9ba99790..0b6e6452da0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalLightingQualitySettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalLightingQualitySettings.cs @@ -249,7 +249,5 @@ internal GlobalLightingQualitySettings() public float[] Fog_DepthRatio = new float[s_QualitySettingCount]; // TODO: Shadows. This needs to be discussed further as there is an idiosyncracy here as we have different level of quality settings, //some for resolution per light (4 levels) some per volume (which are 3 levels everywhere). This needs to be discussed more. - - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalPostProcessingQualitySettings.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalPostProcessingQualitySettings.cs index 489040faf1c..39d3c7ed98e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalPostProcessingQualitySettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/GlobalPostProcessingQualitySettings.cs @@ -30,7 +30,6 @@ public enum Level public ScalableSettingLevelParameter(int level, bool useOverride, bool overrideState = false) : base(useOverride ? LevelCount : (int)level, overrideState) { - } internal static int GetScalableSettingLevelParameterValue(int level, bool useOverride) @@ -46,7 +45,7 @@ internal static int GetScalableSettingLevelParameterValue(int level, bool useOve get => value == LevelCount ? ((int)Level.Low, true) : (value, false); set { - var (level, useOverride) = value; + var(level, useOverride) = value; this.value = GetScalableSettingLevelParameterValue(level, useOverride); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDGPUAsyncTask.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDGPUAsyncTask.cs index 3fcde65410e..d700ceaecf7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDGPUAsyncTask.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDGPUAsyncTask.cs @@ -87,8 +87,7 @@ public void EndWithPostWork(CommandBuffer cmd, HDCamera hdCamera, Action { }); + EndWithPostWork(cmd, hdCamera, (_1, _2) => {}); } } - } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs index d4414df65ab..e314f5daaba 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs @@ -35,16 +35,16 @@ void RenderTransparencyOverdraw(RenderGraph renderGraph, TextureHandle depthBuff passData.transparencyLowResRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparencyLowResRL)); builder.SetRenderFunc( - (TransparencyOverdrawPassData data, RenderGraphContext ctx) => - { - RenderTransparencyOverdraw( data.parameters, - data.output, - data.depthBuffer, - data.transparencyRL, - data.transparencyAfterPostRL, - data.transparencyLowResRL, - ctx.renderContext, ctx.cmd); - }); + (TransparencyOverdrawPassData data, RenderGraphContext ctx) => + { + RenderTransparencyOverdraw(data.parameters, + data.output, + data.depthBuffer, + data.transparencyRL, + data.transparencyAfterPostRL, + data.transparencyLowResRL, + ctx.renderContext, ctx.cmd); + }); transparencyOverdrawOutput = passData.output; } @@ -75,15 +75,15 @@ void RenderFullScreenDebug(RenderGraph renderGraph, TextureHandle colorBuffer, T passData.rendererList = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.rendererList)); builder.SetRenderFunc( - (FullScreenDebugPassData data, RenderGraphContext ctx) => - { - RenderFullScreenDebug( data.parameters, - data.output, - data.depthBuffer, - data.debugBuffer, - data.rendererList, - ctx.renderContext, ctx.cmd); - }); + (FullScreenDebugPassData data, RenderGraphContext ctx) => + { + RenderFullScreenDebug(data.parameters, + data.output, + data.depthBuffer, + data.debugBuffer, + data.rendererList, + ctx.renderContext, ctx.cmd); + }); fullscreenDebugOutput = passData.output; fullscreenDebugBuffer = passData.debugBuffer; @@ -116,13 +116,13 @@ TextureHandle ResolveFullScreenDebug(RenderGraph renderGraph, in DebugParameters else passData.fullscreenBuffer = builder.CreateTransientComputeBuffer(new ComputeBufferDesc(4, sizeof(uint))); passData.output = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "ResolveFullScreenDebug" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "ResolveFullScreenDebug" })); builder.SetRenderFunc( - (ResolveFullScreenDebugPassData data, RenderGraphContext ctx) => - { - ResolveFullScreenDebug(data.debugParameters, ctx.renderGraphPool.GetTempMaterialPropertyBlock(), data.input, data.depthPyramid, data.output, data.fullscreenBuffer, ctx.cmd); - }); + (ResolveFullScreenDebugPassData data, RenderGraphContext ctx) => + { + ResolveFullScreenDebug(data.debugParameters, ctx.renderGraphPool.GetTempMaterialPropertyBlock(), data.input, data.depthPyramid, data.output, data.fullscreenBuffer, ctx.cmd); + }); return passData.output; } @@ -145,10 +145,10 @@ TextureHandle ResolveColorPickerDebug(RenderGraph renderGraph, in DebugParameter { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "ResolveColorPickerDebug" })); builder.SetRenderFunc( - (ResolveColorPickerDebugPassData data, RenderGraphContext ctx) => - { - ResolveColorPickerDebug(data.debugParameters, data.input, data.output, ctx.cmd); - }); + (ResolveColorPickerDebugPassData data, RenderGraphContext ctx) => + { + ResolveColorPickerDebug(data.debugParameters, data.input, data.output, ctx.cmd); + }); return passData.output; } @@ -174,10 +174,10 @@ void RenderSkyReflectionOverlay(RenderGraph renderGraph, in DebugParameters debu passData.depthBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); builder.SetRenderFunc( - (DebugOverlayPassData data, RenderGraphContext ctx) => - { - RenderSkyReflectionOverlay(data.debugParameters, ctx.cmd, ctx.renderGraphPool.GetTempMaterialPropertyBlock()); - }); + (DebugOverlayPassData data, RenderGraphContext ctx) => + { + RenderSkyReflectionOverlay(data.debugParameters, ctx.cmd, ctx.renderGraphPool.GetTempMaterialPropertyBlock()); + }); } } @@ -193,10 +193,10 @@ void RenderRayCountOverlay(RenderGraph renderGraph, in DebugParameters debugPara passData.depthBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); builder.SetRenderFunc( - (DebugOverlayPassData data, RenderGraphContext ctx) => - { - RenderRayCountOverlay(data.debugParameters, ctx.cmd); - }); + (DebugOverlayPassData data, RenderGraphContext ctx) => + { + RenderRayCountOverlay(data.debugParameters, ctx.cmd); + }); } } @@ -234,11 +234,10 @@ void RenderLightLoopDebugOverlay(RenderGraph renderGraph, in DebugParameters deb } builder.SetRenderFunc( - (DebugLightLoopOverlayPassData data, RenderGraphContext ctx) => - { - RenderLightLoopDebugOverlay(data.debugParameters, ctx.cmd, data.tileList, data.lightList, data.perVoxelLightList, data.dispatchIndirect, data.depthPyramidTexture); - - }); + (DebugLightLoopOverlayPassData data, RenderGraphContext ctx) => + { + RenderLightLoopDebugOverlay(data.debugParameters, ctx.cmd, data.tileList, data.lightList, data.perVoxelLightList, data.dispatchIndirect, data.depthPyramidTexture); + }); } } @@ -254,10 +253,10 @@ void RenderProbeVolumeDebugOverlay(RenderGraph renderGraph, in DebugParameters d passData.depthBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); builder.SetRenderFunc( - (DebugLightLoopOverlayPassData data, RenderGraphContext ctx) => - { - RenderProbeVolumeDebugOverlay(data.debugParameters, ctx.cmd); - }); + (DebugLightLoopOverlayPassData data, RenderGraphContext ctx) => + { + RenderProbeVolumeDebugOverlay(data.debugParameters, ctx.cmd); + }); } } @@ -281,19 +280,19 @@ void RenderShadowsDebugOverlay(RenderGraph renderGraph, in DebugParameters debug passData.shadowTextures = HDShadowManager.ReadShadowResult(shadowResult, builder); builder.SetRenderFunc( - (RenderShadowsDebugOverlayPassData data, RenderGraphContext ctx) => - { - var debugParams = data.debugParameters; + (RenderShadowsDebugOverlayPassData data, RenderGraphContext ctx) => + { + var debugParams = data.debugParameters; - var shadowAtlases = new HDShadowManager.ShadowDebugAtlasTextures(); - shadowAtlases.punctualShadowAtlas = data.shadowTextures.punctualShadowResult; - shadowAtlases.cascadeShadowAtlas = data.shadowTextures.directionalShadowResult; - shadowAtlases.areaShadowAtlas = data.shadowTextures.areaShadowResult; - shadowAtlases.cachedPunctualShadowAtlas = data.shadowTextures.cachedPunctualShadowResult; - shadowAtlases.cachedAreaShadowAtlas = data.shadowTextures.cachedAreaShadowResult; + var shadowAtlases = new HDShadowManager.ShadowDebugAtlasTextures(); + shadowAtlases.punctualShadowAtlas = data.shadowTextures.punctualShadowResult; + shadowAtlases.cascadeShadowAtlas = data.shadowTextures.directionalShadowResult; + shadowAtlases.areaShadowAtlas = data.shadowTextures.areaShadowResult; + shadowAtlases.cachedPunctualShadowAtlas = data.shadowTextures.cachedPunctualShadowResult; + shadowAtlases.cachedAreaShadowAtlas = data.shadowTextures.cachedAreaShadowResult; - RenderShadowsDebugOverlay(debugParams, shadowAtlases, ctx.cmd, ctx.renderGraphPool.GetTempMaterialPropertyBlock()); - }); + RenderShadowsDebugOverlay(debugParams, shadowAtlases, ctx.cmd, ctx.renderGraphPool.GetTempMaterialPropertyBlock()); + }); } } @@ -309,22 +308,21 @@ void RenderDecalOverlay(RenderGraph renderGraph, in DebugParameters debugParamet passData.depthBuffer = builder.UseDepthBuffer(depthBuffer, DepthAccess.ReadWrite); builder.SetRenderFunc( - (DebugOverlayPassData data, RenderGraphContext ctx) => - { - DecalSystem.instance.RenderDebugOverlay(data.debugParameters.hdCamera, ctx.cmd, data.debugParameters.debugDisplaySettings, data.debugParameters.debugOverlay); - }); + (DebugOverlayPassData data, RenderGraphContext ctx) => + { + DecalSystem.instance.RenderDebugOverlay(data.debugParameters.hdCamera, ctx.cmd, data.debugParameters.debugDisplaySettings, data.debugParameters.debugOverlay); + }); } } - void RenderDebugOverlays( RenderGraph renderGraph, - in DebugParameters debugParameters, - TextureHandle colorBuffer, - TextureHandle depthBuffer, - TextureHandle depthPyramidTexture, - in BuildGPULightListOutput lightLists, - in ShadowResult shadowResult) + void RenderDebugOverlays(RenderGraph renderGraph, + in DebugParameters debugParameters, + TextureHandle colorBuffer, + TextureHandle depthBuffer, + TextureHandle depthPyramidTexture, + in BuildGPULightListOutput lightLists, + in ShadowResult shadowResult) { - RenderSkyReflectionOverlay(renderGraph, debugParameters, colorBuffer, depthBuffer); RenderRayCountOverlay(renderGraph, debugParameters, colorBuffer, depthBuffer); RenderLightLoopDebugOverlay(renderGraph, debugParameters, colorBuffer, depthBuffer, lightLists, depthPyramidTexture); @@ -353,7 +351,7 @@ static void RenderLightVolumes(RenderGraph renderGraph, in DebugParameters debug { passData.parameters = s_lightVolumes.PrepareLightVolumeParameters(debugParameters.hdCamera, debugParameters.debugDisplaySettings.data.lightingDebugSettings, cullResults); passData.lightCountBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat= GraphicsFormat.R32_SFloat, clearBuffer = true, clearColor = Color.black, name = "LightVolumeCount" }); + { colorFormat = GraphicsFormat.R32_SFloat, clearBuffer = true, clearColor = Color.black, name = "LightVolumeCount" }); passData.colorAccumulationBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, clearBuffer = true, clearColor = Color.black, name = "LightVolumeColorAccumulation" }); passData.debugLightVolumesTexture = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) @@ -362,25 +360,24 @@ static void RenderLightVolumes(RenderGraph renderGraph, in DebugParameters debug passData.destination = builder.WriteTexture(destination); builder.SetRenderFunc( - (RenderLightVolumesPassData data, RenderGraphContext ctx) => - { - RenderTargetIdentifier[] mrt = ctx.renderGraphPool.GetTempArray(2); - mrt[0] = data.lightCountBuffer; - mrt[1] = data.colorAccumulationBuffer; - - DebugLightVolumes.RenderLightVolumes( ctx.cmd, - data.parameters, - mrt, data.lightCountBuffer, - data.colorAccumulationBuffer, - data.debugLightVolumesTexture, - data.depthBuffer, - data.destination, - ctx.renderGraphPool.GetTempMaterialPropertyBlock()); - }); + (RenderLightVolumesPassData data, RenderGraphContext ctx) => + { + RenderTargetIdentifier[] mrt = ctx.renderGraphPool.GetTempArray(2); + mrt[0] = data.lightCountBuffer; + mrt[1] = data.colorAccumulationBuffer; + + DebugLightVolumes.RenderLightVolumes(ctx.cmd, + data.parameters, + mrt, data.lightCountBuffer, + data.colorAccumulationBuffer, + data.debugLightVolumesTexture, + data.depthBuffer, + data.destination, + ctx.renderGraphPool.GetTempMaterialPropertyBlock()); + }); } } - class DebugImageHistogramData { public PostProcessSystem.DebugImageHistogramParameters parameters; @@ -394,10 +391,10 @@ void GenerateDebugImageHistogram(RenderGraph renderGraph, HDCamera hdCamera, Tex passData.source = builder.ReadTexture(source); passData.parameters = m_PostProcessSystem.PrepareDebugImageHistogramParameters(hdCamera); builder.SetRenderFunc( - (DebugImageHistogramData data, RenderGraphContext ctx) => - { - PostProcessSystem.GenerateDebugImageHistogram(data.parameters, ctx.cmd, data.source); - }); + (DebugImageHistogramData data, RenderGraphContext ctx) => + { + PostProcessSystem.GenerateDebugImageHistogram(data.parameters, ctx.cmd, data.source); + }); } } @@ -436,34 +433,33 @@ TextureHandle RenderExposureDebug(RenderGraph renderGraph, HDCamera hdCamera, De passData.histogramBuffer = debugParameters.debugDisplaySettings.data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.FinalImageHistogramView ? m_PostProcessSystem.GetDebugImageHistogramBuffer() : m_PostProcessSystem.GetHistogramBuffer(); builder.SetRenderFunc( - (DebugExposureData data, RenderGraphContext ctx) => - { - RenderExposureDebug(data.debugParameters, data.colorBuffer, data.debugFullScreenTexture, - data.previousExposure, - data.currentExposure, - data.debugExposureData, - data.output, - data.customToneMapCurve, - data.lutSize, - data.proceduralMeteringParams1, - data.proceduralMeteringParams2, - data.histogramBuffer, ctx.cmd); - - }); + (DebugExposureData data, RenderGraphContext ctx) => + { + RenderExposureDebug(data.debugParameters, data.colorBuffer, data.debugFullScreenTexture, + data.previousExposure, + data.currentExposure, + data.debugExposureData, + data.output, + data.customToneMapCurve, + data.lutSize, + data.proceduralMeteringParams1, + data.proceduralMeteringParams2, + data.histogramBuffer, ctx.cmd); + }); return passData.output; } } - TextureHandle RenderDebug( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - TextureHandle depthBuffer, - TextureHandle depthPyramidTexture, - TextureHandle colorPickerDebugTexture, - in BuildGPULightListOutput lightLists, - in ShadowResult shadowResult, - CullingResults cullResults) + TextureHandle RenderDebug(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthBuffer, + TextureHandle depthPyramidTexture, + TextureHandle colorPickerDebugTexture, + in BuildGPULightListOutput lightLists, + in ShadowResult shadowResult, + CullingResults cullResults) { // We don't want any overlay for these kind of rendering if (hdCamera.camera.cameraType == CameraType.Reflection || hdCamera.camera.cameraType == CameraType.Preview) @@ -537,10 +533,10 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu passData.outputColor = builder.WriteTexture(output); builder.SetRenderFunc( - (DebugViewMaterialData data, RenderGraphContext context) => - { - HDUtils.DrawFullScreen(context.cmd, data.debugGBufferMaterial, data.outputColor); - }); + (DebugViewMaterialData data, RenderGraphContext context) => + { + HDUtils.DrawFullScreen(context.cmd, data.debugGBufferMaterial, data.outputColor); + }); } } else @@ -567,18 +563,18 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu passData.clearDepth = hdCamera.clearDepth; builder.SetRenderFunc( - (DebugViewMaterialData data, RenderGraphContext context) => - { - // If we are doing camera stacking, then we want to clear the debug color and depth buffer using the data from the previous camera on the stack - // Note: Ideally here we would like to draw directly on the same buffers as the previous camera, but currently the compositor is not using - // Texture Arrays so this would not work. We might need to revise this in the future. - if (data.clearColorTexture != null) + (DebugViewMaterialData data, RenderGraphContext context) => { - HDUtils.BlitColorAndDepth(context.cmd, data.clearColorTexture, data.clearDepthTexture, new Vector4(1, 1, 0, 0), 0, !data.clearDepth); - } - DrawOpaqueRendererList(context, data.frameSettings, data.opaqueRendererList); - DrawTransparentRendererList(context, data.frameSettings, data.transparentRendererList); - }); + // If we are doing camera stacking, then we want to clear the debug color and depth buffer using the data from the previous camera on the stack + // Note: Ideally here we would like to draw directly on the same buffers as the previous camera, but currently the compositor is not using + // Texture Arrays so this would not work. We might need to revise this in the future. + if (data.clearColorTexture != null) + { + HDUtils.BlitColorAndDepth(context.cmd, data.clearColorTexture, data.clearDepthTexture, new Vector4(1, 1, 0, 0), 0, !data.clearDepth); + } + DrawOpaqueRendererList(context, data.frameSettings, data.opaqueRendererList); + DrawTransparentRendererList(context, data.frameSettings, data.transparentRendererList); + }); } } @@ -630,13 +626,13 @@ void PushFullScreenDebugTexture(RenderGraph renderGraph, TextureHandle input, in { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "DebugFullScreen" }), 0); builder.SetRenderFunc( - (PushFullScreenDebugPassData data, RenderGraphContext ctx) => - { - if (data.mipIndex != -1) - HDUtils.BlitCameraTexture(ctx.cmd, data.input, data.output, data.mipIndex); - else - HDUtils.BlitCameraTexture(ctx.cmd, data.input, data.output); - }); + (PushFullScreenDebugPassData data, RenderGraphContext ctx) => + { + if (data.mipIndex != -1) + HDUtils.BlitCameraTexture(ctx.cmd, data.input, data.output, data.mipIndex); + else + HDUtils.BlitCameraTexture(ctx.cmd, data.input, data.output); + }); m_DebugFullScreenTexture = passData.output; } @@ -672,23 +668,23 @@ void PushFullScreenVTFeedbackDebugTexture(RenderGraph renderGraph, TextureHandle passData.msaa = msaa; passData.input = builder.ReadTexture(input); passData.output = builder.UseColorBuffer(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "DebugFullScreen" }), 0); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "DebugFullScreen" }), 0); builder.SetRenderFunc( - (PushFullScreenVTDebugPassData data, RenderGraphContext ctx) => - { - CoreUtils.SetRenderTarget(ctx.cmd, data.output); - data.material.SetTexture(data.msaa ? HDShaderIDs._BlitTextureMSAA : HDShaderIDs._BlitTexture, data.input); - ctx.cmd.DrawProcedural(Matrix4x4.identity, data.material, data.msaa ? 1 : 0, MeshTopology.Triangles, 3, 1); - }); + (PushFullScreenVTDebugPassData data, RenderGraphContext ctx) => + { + CoreUtils.SetRenderTarget(ctx.cmd, data.output); + data.material.SetTexture(data.msaa ? HDShaderIDs._BlitTextureMSAA : HDShaderIDs._BlitTexture, data.input); + ctx.cmd.DrawProcedural(Matrix4x4.identity, data.material, data.msaa ? 1 : 0, MeshTopology.Triangles, 3, 1); + }); m_DebugFullScreenTexture = passData.output; - } m_FullScreenDebugPushed = true; } } + #endif TextureHandle PushColorPickerDebugTexture(RenderGraph renderGraph, TextureHandle input) @@ -700,10 +696,10 @@ TextureHandle PushColorPickerDebugTexture(RenderGraph renderGraph, TextureHandle { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, name = "DebugColorPicker" }), 0); builder.SetRenderFunc( - (PushFullScreenDebugPassData data, RenderGraphContext ctx) => - { - HDUtils.BlitCameraTexture(ctx.cmd, data.input, data.output); - }); + (PushFullScreenDebugPassData data, RenderGraphContext ctx) => + { + HDUtils.BlitCameraTexture(ctx.cmd, data.input, data.output); + }); return passData.output; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs index 50f22cba622..56c1d128f65 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LightLoop.cs @@ -124,13 +124,13 @@ static BuildGPULightListResources PrepareBuildGPULightListResources(RenderGraphC return buildLightListResources; } - BuildGPULightListOutput BuildGPULightList( RenderGraph renderGraph, - HDCamera hdCamera, - TileAndClusterData tileAndClusterData, - ref ShaderVariablesLightList constantBuffer, - TextureHandle depthStencilBuffer, - TextureHandle stencilBufferCopy, - GBufferOutput gBuffer) + BuildGPULightListOutput BuildGPULightList(RenderGraph renderGraph, + HDCamera hdCamera, + TileAndClusterData tileAndClusterData, + ref ShaderVariablesLightList constantBuffer, + TextureHandle depthStencilBuffer, + TextureHandle stencilBufferCopy, + GBufferOutput gBuffer) { using (var builder = renderGraph.AddRenderPass("Build Light List", out var passData, ProfilingSampler.Get(HDProfileId.BuildLightList))) { @@ -207,20 +207,20 @@ BuildGPULightListOutput BuildGPULightList( RenderGraph rend } builder.SetRenderFunc( - (BuildGPULightListPassData data, RenderGraphContext context) => - { - var buildLightListResources = PrepareBuildGPULightListResources(context, data); + (BuildGPULightListPassData data, RenderGraphContext context) => + { + var buildLightListResources = PrepareBuildGPULightListResources(context, data); - //bool tileFlagsWritten = false; + //bool tileFlagsWritten = false; - ClearLightLists(data.buildGPULightListParameters, buildLightListResources, context.cmd); - GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); - //BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd); - // BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd); - // VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd); + ClearLightLists(data.buildGPULightListParameters, buildLightListResources, context.cmd); + GenerateLightsScreenSpaceAABBs(data.buildGPULightListParameters, buildLightListResources, context.cmd); + //BigTilePrepass(data.buildGPULightListParameters, buildLightListResources, context.cmd); + // BuildPerTileLightList(data.buildGPULightListParameters, buildLightListResources, ref tileFlagsWritten, context.cmd); + // VoxelLightListGeneration(data.buildGPULightListParameters, buildLightListResources, context.cmd); - // BuildDispatchIndirectArguments(data.buildGPULightListParameters, buildLightListResources, tileFlagsWritten, context.cmd); - }); + // BuildDispatchIndirectArguments(data.buildGPULightListParameters, buildLightListResources, tileFlagsWritten, context.cmd); + }); return passData.output; } @@ -232,7 +232,6 @@ class PushGlobalCameraParamPassData public int frameCount; public ShaderVariablesGlobal globalCB; public ShaderVariablesXR xrCB; - } void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) @@ -245,13 +244,13 @@ void PushGlobalCameraParams(RenderGraph renderGraph, HDCamera hdCamera) passData.xrCB = m_ShaderVariablesXRCB; builder.SetRenderFunc( - (PushGlobalCameraParamPassData data, RenderGraphContext context) => - { - data.hdCamera.UpdateShaderVariablesGlobalCB(ref data.globalCB, data.frameCount); - ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); - data.hdCamera.UpdateShaderVariablesXRCB(ref data.xrCB); - ConstantBuffer.PushGlobal(context.cmd, data.xrCB, HDShaderIDs._ShaderVariablesXR); - }); + (PushGlobalCameraParamPassData data, RenderGraphContext context) => + { + data.hdCamera.UpdateShaderVariablesGlobalCB(ref data.globalCB, data.frameCount); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + data.hdCamera.UpdateShaderVariablesXRCB(ref data.xrCB); + ConstantBuffer.PushGlobal(context.cmd, data.xrCB, HDShaderIDs._ShaderVariablesXR); + }); } } @@ -266,8 +265,10 @@ internal ShadowResult RenderShadows(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle CreateDiffuseLightingBuffer(RenderGraph renderGraph, bool msaa) { return renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = !msaa, - bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = true, clearColor = Color.clear, name = msaa ? "CameraSSSDiffuseLightingMSAA" : "CameraSSSDiffuseLighting" }); + { + colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = !msaa, + bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = true, clearColor = Color.clear, name = msaa ? "CameraSSSDiffuseLightingMSAA" : "CameraSSSDiffuseLighting" + }); } class DeferredLightingPassData @@ -297,15 +298,15 @@ struct LightingOutput public TextureHandle colorBuffer; } - LightingOutput RenderDeferredLighting( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - TextureHandle depthStencilBuffer, - TextureHandle depthPyramidTexture, - in LightingBuffers lightingBuffers, - in GBufferOutput gbuffer, - in ShadowResult shadowResult, - in BuildGPULightListOutput lightLists) + LightingOutput RenderDeferredLighting(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + TextureHandle depthPyramidTexture, + in LightingBuffers lightingBuffers, + in GBufferOutput gbuffer, + in ShadowResult shadowResult, + in BuildGPULightListOutput lightLists) { if (hdCamera.frameSettings.litShaderMode != LitShaderMode.Deferred || !hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects)) @@ -325,7 +326,7 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, // TODO RENDERGRAPH: Check how to avoid this kind of pattern. // Unfortunately, the low level needs this texture to always be bound with UAV enabled, so in order to avoid effectively creating the full resolution texture here, // we need to create a small dummy texture. - passData.sssDiffuseLightingBuffer = builder.CreateTransientTexture(new TextureDesc(1, 1, true, true) { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true } ); + passData.sssDiffuseLightingBuffer = builder.CreateTransientTexture(new TextureDesc(1, 1, true, true) { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true }); } passData.depthBuffer = builder.ReadTexture(depthStencilBuffer); passData.depthTexture = builder.ReadTexture(depthPyramidTexture); @@ -349,55 +350,55 @@ LightingOutput RenderDeferredLighting( RenderGraph renderGraph, output.colorBuffer = passData.colorBuffer; builder.SetRenderFunc( - (DeferredLightingPassData data, RenderGraphContext context) => - { - var resources = new DeferredLightingResources(); - - resources.colorBuffers = context.renderGraphPool.GetTempArray(2); - resources.colorBuffers[0] = data.colorBuffer; - resources.colorBuffers[1] = data.sssDiffuseLightingBuffer; - resources.depthStencilBuffer = data.depthBuffer; - resources.depthTexture = data.depthTexture; - - resources.lightListBuffer = data.lightListBuffer; - resources.tileFeatureFlagsBuffer = data.tileFeatureFlagsBuffer; - resources.tileListBuffer = data.tileListBuffer; - resources.dispatchIndirectBuffer = data.dispatchIndirectBuffer; - - // TODO RENDERGRAPH: try to find a better way to bind this. - // Issue is that some GBuffers have several names (for example normal buffer is both NormalBuffer and GBuffer1) - // So it's not possible to use auto binding via dependency to shaderTagID - // Should probably get rid of auto binding and go explicit all the way (might need to wait for us to remove non rendergraph code path). - for (int i = 0; i < data.gbufferCount; ++i) - context.cmd.SetGlobalTexture(HDShaderIDs._GBufferTexture[i], data.gbuffer[i]); - - if (data.lightLayersTextureIndex != -1) - context.cmd.SetGlobalTexture(HDShaderIDs._LightLayersTexture, data.gbuffer[data.lightLayersTextureIndex]); - else - context.cmd.SetGlobalTexture(HDShaderIDs._LightLayersTexture, TextureXR.GetWhiteTexture()); - - if (data.shadowMaskTextureIndex != -1) - context.cmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, data.gbuffer[data.shadowMaskTextureIndex]); - else - context.cmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, TextureXR.GetWhiteTexture()); - - // TODO RENDERGRAPH: Remove these SetGlobal and properly send these textures to the deferred passes and bind them directly to compute shaders. - // This can wait that we remove the old code path. - BindGlobalLightingBuffers(data.lightingBuffers, context.cmd); - - if (data.parameters.enableTile) + (DeferredLightingPassData data, RenderGraphContext context) => { - bool useCompute = data.parameters.useComputeLightingEvaluation && !k_PreferFragment; - if (useCompute) - RenderComputeDeferredLighting(data.parameters, resources, context.cmd); + var resources = new DeferredLightingResources(); + + resources.colorBuffers = context.renderGraphPool.GetTempArray(2); + resources.colorBuffers[0] = data.colorBuffer; + resources.colorBuffers[1] = data.sssDiffuseLightingBuffer; + resources.depthStencilBuffer = data.depthBuffer; + resources.depthTexture = data.depthTexture; + + resources.lightListBuffer = data.lightListBuffer; + resources.tileFeatureFlagsBuffer = data.tileFeatureFlagsBuffer; + resources.tileListBuffer = data.tileListBuffer; + resources.dispatchIndirectBuffer = data.dispatchIndirectBuffer; + + // TODO RENDERGRAPH: try to find a better way to bind this. + // Issue is that some GBuffers have several names (for example normal buffer is both NormalBuffer and GBuffer1) + // So it's not possible to use auto binding via dependency to shaderTagID + // Should probably get rid of auto binding and go explicit all the way (might need to wait for us to remove non rendergraph code path). + for (int i = 0; i < data.gbufferCount; ++i) + context.cmd.SetGlobalTexture(HDShaderIDs._GBufferTexture[i], data.gbuffer[i]); + + if (data.lightLayersTextureIndex != -1) + context.cmd.SetGlobalTexture(HDShaderIDs._LightLayersTexture, data.gbuffer[data.lightLayersTextureIndex]); else - RenderComputeAsPixelDeferredLighting(data.parameters, resources, context.cmd); - } - else - { - RenderPixelDeferredLighting(data.parameters, resources, context.cmd); - } - }); + context.cmd.SetGlobalTexture(HDShaderIDs._LightLayersTexture, TextureXR.GetWhiteTexture()); + + if (data.shadowMaskTextureIndex != -1) + context.cmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, data.gbuffer[data.shadowMaskTextureIndex]); + else + context.cmd.SetGlobalTexture(HDShaderIDs._ShadowMaskTexture, TextureXR.GetWhiteTexture()); + + // TODO RENDERGRAPH: Remove these SetGlobal and properly send these textures to the deferred passes and bind them directly to compute shaders. + // This can wait that we remove the old code path. + BindGlobalLightingBuffers(data.lightingBuffers, context.cmd); + + if (data.parameters.enableTile) + { + bool useCompute = data.parameters.useComputeLightingEvaluation && !k_PreferFragment; + if (useCompute) + RenderComputeDeferredLighting(data.parameters, resources, context.cmd); + else + RenderComputeAsPixelDeferredLighting(data.parameters, resources, context.cmd); + } + else + { + RenderPixelDeferredLighting(data.parameters, resources, context.cmd); + } + }); return output; } @@ -423,13 +424,13 @@ class RenderSSRPassData //public TextureHandle debugTexture; } - TextureHandle RenderSSR( RenderGraph renderGraph, - HDCamera hdCamera, - ref PrepassOutput prepassOutput, - TextureHandle clearCoatMask, - TextureHandle rayCountTexture, - Texture skyTexture, - bool transparent) + TextureHandle RenderSSR(RenderGraph renderGraph, + HDCamera hdCamera, + ref PrepassOutput prepassOutput, + TextureHandle clearCoatMask, + TextureHandle rayCountTexture, + Texture skyTexture, + bool transparent) { if (!hdCamera.IsSSREnabled(transparent)) return renderGraph.defaultResources.blackTextureXR; @@ -442,8 +443,8 @@ TextureHandle RenderSSR( RenderGraph renderGraph, if (usesRaytracedReflections) { result = RenderRayTracedReflections(renderGraph, hdCamera, - prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.normalBuffer, prepassOutput.resolvedMotionVectorsBuffer, clearCoatMask, skyTexture, rayCountTexture, - m_FrameCount, m_ShaderVariablesRayTracingCB, transparent); + prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.normalBuffer, prepassOutput.resolvedMotionVectorsBuffer, clearCoatMask, skyTexture, rayCountTexture, + m_FrameCount, m_ShaderVariablesRayTracingCB, transparent); } else { @@ -483,12 +484,12 @@ TextureHandle RenderSSR( RenderGraph renderGraph, // In practice, these textures are sparse (mostly black). Therefore, clearing them is fast (due to CMASK), // and much faster than fully overwriting them from within SSR shaders. passData.hitPointsTexture = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16_UNorm, clearBuffer = true, clearColor = Color.clear, enableRandomWrite = true, name = transparent ? "SSR_Hit_Point_Texture_Trans" : "SSR_Hit_Point_Texture" }); + { colorFormat = GraphicsFormat.R16G16_UNorm, clearBuffer = true, clearColor = Color.clear, enableRandomWrite = true, name = transparent ? "SSR_Hit_Point_Texture_Trans" : "SSR_Hit_Point_Texture" }); if (usePBRAlgo) { TextureHandle ssrAccum = renderGraph.ImportTexture(hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ScreenSpaceReflectionAccumulation)); - TextureHandle ssrAccumPrev = renderGraph.ImportTexture(hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ScreenSpaceReflectionAccumulation)); ; + TextureHandle ssrAccumPrev = renderGraph.ImportTexture(hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ScreenSpaceReflectionAccumulation));; passData.ssrAccum = builder.WriteTexture(ssrAccum); passData.ssrAccumPrev = builder.WriteTexture(ssrAccumPrev); passData.lightingTexture = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) @@ -501,25 +502,25 @@ TextureHandle RenderSSR( RenderGraph renderGraph, } builder.SetRenderFunc( - (RenderSSRPassData data, RenderGraphContext context) => - { - RenderSSR( data.parameters, - data.hdCamera, - data.blueNoise, - data.depthBuffer, - data.depthPyramid, - data.normalBuffer, - data.motionVectorsBuffer, - data.hitPointsTexture, - data.stencilBuffer, - data.clearCoatMask, - data.colorPyramid, - data.ssrAccum, - data.lightingTexture, - data.ssrAccumPrev, - data.coarseStencilBuffer, - context.cmd, context.renderContext); - }); + (RenderSSRPassData data, RenderGraphContext context) => + { + RenderSSR(data.parameters, + data.hdCamera, + data.blueNoise, + data.depthBuffer, + data.depthPyramid, + data.normalBuffer, + data.motionVectorsBuffer, + data.hitPointsTexture, + data.stencilBuffer, + data.clearCoatMask, + data.colorPyramid, + data.ssrAccum, + data.lightingTexture, + data.ssrAccumPrev, + data.coarseStencilBuffer, + context.cmd, context.renderContext); + }); if (usePBRAlgo) { @@ -576,10 +577,10 @@ TextureHandle RenderContactShadows(RenderGraph renderGraph, HDCamera hdCamera, T result = passData.contactShadowsTexture; builder.SetRenderFunc( - (RenderContactShadowPassData data, RenderGraphContext context) => - { - RenderContactShadows(data.parameters, data.contactShadowsTexture, data.depthTexture, data.lightList, context.cmd); - }); + (RenderContactShadowPassData data, RenderGraphContext context) => + { + RenderContactShadows(data.parameters, data.contactShadowsTexture, data.depthTexture, data.lightList, context.cmd); + }); } PushFullScreenDebugTexture(renderGraph, result, FullScreenDebugMode.ContactShadows); @@ -593,10 +594,10 @@ class VolumeVoxelizationPassData public ComputeBufferHandle bigTileLightListBuffer; } - TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, - HDCamera hdCamera, - ComputeBufferHandle bigTileLightList, - int frameIndex) + TextureHandle VolumeVoxelizationPass(RenderGraph renderGraph, + HDCamera hdCamera, + ComputeBufferHandle bigTileLightList, + int frameIndex) { if (Fog.IsVolumetricFogEnabled(hdCamera)) { @@ -616,13 +617,13 @@ TextureHandle VolumeVoxelizationPass( RenderGraph renderGraph, passData.densityBuffer = builder.WriteTexture(renderGraph.ImportTexture(m_DensityBuffer)); builder.SetRenderFunc( - (VolumeVoxelizationPassData data, RenderGraphContext ctx) => - { - VolumeVoxelizationPass( data.parameters, - data.densityBuffer, - data.bigTileLightListBuffer, - ctx.cmd); - }); + (VolumeVoxelizationPassData data, RenderGraphContext ctx) => + { + VolumeVoxelizationPass(data.parameters, + data.densityBuffer, + data.bigTileLightListBuffer, + ctx.cmd); + }); return passData.densityBuffer; } @@ -660,10 +661,10 @@ TextureHandle GenerateMaxZPass(RenderGraph renderGraph, HDCamera hdCamera, Textu passData.dilatedMaxZBuffer = builder.WriteTexture(passData.dilatedMaxZBuffer); builder.SetRenderFunc( - (GenerateMaxZMaskPassData data, RenderGraphContext ctx) => - { - GenerateMaxZ(data.parameters, data.depthTexture, data.maxZ8xBuffer, data.maxZBuffer, data.dilatedMaxZBuffer, ctx.cmd); - }); + (GenerateMaxZMaskPassData data, RenderGraphContext ctx) => + { + GenerateMaxZ(data.parameters, data.depthTexture, data.maxZ8xBuffer, data.maxZBuffer, data.dilatedMaxZBuffer, ctx.cmd); + }); return passData.dilatedMaxZBuffer; } @@ -720,21 +721,21 @@ TextureHandle VolumetricLightingPass(RenderGraph renderGraph, HDCamera hdCamera, HDShadowManager.ReadShadowResult(shadowResult, builder); builder.SetRenderFunc( - (VolumetricLightingPassData data, RenderGraphContext ctx) => - { - VolumetricLightingPass( data.parameters, - data.depthTexture, - data.densityBuffer, - data.lightingBuffer, - data.maxZBuffer, - data.parameters.enableReprojection ? data.historyBuffer : (RTHandle)null, - data.parameters.enableReprojection ? data.feedbackBuffer : (RTHandle)null, - data.bigTileLightListBuffer, - ctx.cmd); - - if (data.parameters.filterVolume) - FilterVolumetricLighting(data.parameters, data.lightingBuffer, ctx.cmd); - }); + (VolumetricLightingPassData data, RenderGraphContext ctx) => + { + VolumetricLightingPass(data.parameters, + data.depthTexture, + data.densityBuffer, + data.lightingBuffer, + data.maxZBuffer, + data.parameters.enableReprojection ? data.historyBuffer : (RTHandle)null, + data.parameters.enableReprojection ? data.feedbackBuffer : (RTHandle)null, + data.bigTileLightListBuffer, + ctx.cmd); + + if (data.parameters.filterVolume) + FilterVolumetricLighting(data.parameters, data.lightingBuffer, ctx.cmd); + }); if (parameters.enableReprojection) hdCamera.volumetricHistoryIsValid = true; // For the next frame.. diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LookDev.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LookDev.cs index 13cb9253aac..f18b178488d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LookDev.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.LookDev.cs @@ -75,6 +75,7 @@ bool UpdateVolumeProfile(Volume volume, out VisualEnvironment visualEnvironment, return false; } } + #endif /// @@ -203,15 +204,15 @@ void IDataProvider.OnEndRendering(StageRuntimeInterface SRI) /// IEnumerable IDataProvider.supportedDebugModes => new[] - { - "Albedo", - "Normal", - "Smoothness", - "AmbientOcclusion", - "Metal", - "Specular", - "Alpha" - }; + { + "Albedo", + "Normal", + "Smoothness", + "AmbientOcclusion", + "Metal", + "Specular", + "Alpha" + }; /// /// This hook allows HDRP to update the debug mode used while requested in the LookDev. diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs index c37c835d8e5..b55bfbf88c2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs @@ -14,18 +14,18 @@ class AfterPostProcessPassData public RendererListHandle transparentAfterPostprocessRL; } - TextureHandle RenderPostProcess( RenderGraph renderGraph, - PrepassOutput prepassOutput, - TextureHandle inputColor, - TextureHandle backBuffer, - CullingResults cullResults, - HDCamera hdCamera) + TextureHandle RenderPostProcess(RenderGraph renderGraph, + PrepassOutput prepassOutput, + TextureHandle inputColor, + TextureHandle backBuffer, + CullingResults cullResults, + HDCamera hdCamera) { PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); TextureHandle afterPostProcessBuffer = renderGraph.defaultResources.blackTextureXR; TextureHandle dest = HDUtils.PostProcessIsFinalPass(parameters.hdCamera) ? backBuffer : renderGraph.CreateTexture( - new TextureDesc(Vector2.one, true, true) { colorFormat = GetColorBufferFormat(), name = "Intermediate Postprocess buffer" }); + new TextureDesc(Vector2.one, true, true) { colorFormat = GetColorBufferFormat(), name = "Intermediate Postprocess buffer" }); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) { @@ -41,10 +41,10 @@ TextureHandle RenderPostProcess( RenderGraph renderGraph, passData.transparentAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparentAfterPPDesc)); builder.SetRenderFunc( - (AfterPostProcessPassData data, RenderGraphContext ctx) => - { - RenderAfterPostProcess(data.parameters, data.opaqueAfterPostprocessRL, data.transparentAfterPostprocessRL, ctx.renderContext, ctx.cmd); - }); + (AfterPostProcessPassData data, RenderGraphContext ctx) => + { + RenderAfterPostProcess(data.parameters, data.opaqueAfterPostprocessRL, data.transparentAfterPostprocessRL, ctx.renderContext, ctx.cmd); + }); afterPostProcessBuffer = passData.afterPostProcessBuffer; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs index b4e0fda65ad..44df7865fa6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs @@ -36,8 +36,7 @@ void InitializePrepass(HDRenderPipelineAsset hdAsset) m_DepthBufferMipChainInfo.Allocate(); m_DepthPyramidDesc = new TextureDesc(ComputeDepthBufferMipChainSize, true, true) - { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "CameraDepthBufferMipChain" }; - + { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "CameraDepthBufferMipChain" }; } void CleanupPrepass() @@ -99,7 +98,8 @@ TextureHandle CreateDepthBuffer(RenderGraph renderGraph, bool clear, bool msaa) #endif TextureDesc depthDesc = new TextureDesc(Vector2.one, true, true) - { depthBufferBits = DepthBits.Depth32, bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = clear, name = msaa ? "CameraDepthStencilMSAA" : "CameraDepthStencil" + { + depthBufferBits = DepthBits.Depth32, bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = clear, name = msaa ? "CameraDepthStencilMSAA" : "CameraDepthStencil" #if UNITY_2020_2_OR_NEWER , fastMemoryDesc = fastMemDesc #endif @@ -118,7 +118,8 @@ TextureHandle CreateNormalBuffer(RenderGraph renderGraph, bool msaa) #endif TextureDesc normalDesc = new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = NeedClearGBuffer(), clearColor = Color.black, bindTextureMS = msaa, enableMSAA = msaa, enableRandomWrite = !msaa, name = msaa ? "NormalBufferMSAA" : "NormalBuffer" + { + colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = NeedClearGBuffer(), clearColor = Color.black, bindTextureMS = msaa, enableMSAA = msaa, enableRandomWrite = !msaa, name = msaa ? "NormalBufferMSAA" : "NormalBuffer" #if UNITY_2020_2_OR_NEWER , fastMemoryDesc = fastMemDesc #endif @@ -129,14 +130,14 @@ TextureHandle CreateNormalBuffer(RenderGraph renderGraph, bool msaa) TextureHandle CreateDecalPrepassBuffer(RenderGraph renderGraph, bool msaa) { TextureDesc decalDesc = new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = true, clearColor = Color.clear, bindTextureMS = false, enableMSAA = msaa, enableRandomWrite = !msaa, name = msaa ? "DecalPrepassBufferMSAA" : "DecalPrepassBuffer" }; + { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = true, clearColor = Color.clear, bindTextureMS = false, enableMSAA = msaa, enableRandomWrite = !msaa, name = msaa ? "DecalPrepassBufferMSAA" : "DecalPrepassBuffer" }; return renderGraph.CreateTexture(decalDesc); } TextureHandle CreateMotionVectorBuffer(RenderGraph renderGraph, bool msaa, bool clear) { TextureDesc motionVectorDesc = new TextureDesc(Vector2.one, true, true) - { colorFormat = Builtin.GetMotionVectorFormat(), bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = clear, clearColor = Color.clear, name = msaa ? "Motion Vectors MSAA" : "Motion Vectors" }; + { colorFormat = Builtin.GetMotionVectorFormat(), bindTextureMS = msaa, enableMSAA = msaa, clearBuffer = clear, clearColor = Color.clear, name = msaa ? "Motion Vectors MSAA" : "Motion Vectors" }; return renderGraph.CreateTexture(motionVectorDesc); } @@ -173,14 +174,14 @@ void BindMotionVectorPassColorBuffers(in RenderGraphBuilder builder, in PrepassO } PrepassOutput RenderPrepass(RenderGraph renderGraph, - TextureHandle colorBuffer, - TextureHandle sssBuffer, - TextureHandle vtFeedbackBuffer, - CullingResults cullingResults, - CullingResults customPassCullingResults, - HDCamera hdCamera, - AOVRequestData aovRequest, - List aovBuffers) + TextureHandle colorBuffer, + TextureHandle sssBuffer, + TextureHandle vtFeedbackBuffer, + CullingResults cullingResults, + CullingResults customPassCullingResults, + HDCamera hdCamera, + AOVRequestData aovRequest, + List aovBuffers) { m_IsDepthBufferCopyValid = false; @@ -246,8 +247,8 @@ PrepassOutput RenderPrepass(RenderGraph renderGraph, // Only on consoles is safe to read and write from/to the depth atlas bool mip1FromDownsampleForLowResTrans = SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; mip1FromDownsampleForLowResTrans = mip1FromDownsampleForLowResTrans && hdCamera.frameSettings.IsEnabled(FrameSettingsField.LowResTransparent); DownsampleDepthForLowResTransparency(renderGraph, hdCamera, mip1FromDownsampleForLowResTrans, ref result); @@ -309,7 +310,7 @@ bool RenderDepthPrepass(RenderGraph renderGraph, CullingResults cull, HDCamera h { decalBuffer = renderGraph.defaultResources.blackTextureXR; output.depthAsColor = renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R32_SFloat, clearBuffer = true, clearColor = Color.black, bindTextureMS = true, enableMSAA = true, name = "DepthAsColorMSAA" }); + { colorFormat = GraphicsFormat.R32_SFloat, clearBuffer = true, clearColor = Color.black, bindTextureMS = true, enableMSAA = true, name = "DepthAsColorMSAA" }); output.normalBuffer = CreateNormalBuffer(renderGraph, msaa); return false; } @@ -349,39 +350,39 @@ bool RenderDepthPrepass(RenderGraph renderGraph, CullingResults cull, HDCamera h decalBuffer = renderGraph.defaultResources.blackTextureXR; builder.SetRenderFunc( - (DepthPrepassData data, RenderGraphContext context) => - { - RenderTargetIdentifier[] deferredMrt = null; - if (data.hasDepthDeferredPass && data.decalLayersEnabled) - { - deferredMrt = context.renderGraphPool.GetTempArray(1); - deferredMrt[0] = data.decalBuffer; - } - - var forwardMrt = context.renderGraphPool.GetTempArray((data.msaaEnabled ? 2 : 1) + (data.decalLayersEnabled ? 1 : 0)); - if (data.msaaEnabled) + (DepthPrepassData data, RenderGraphContext context) => { - forwardMrt[0] = data.depthAsColorBuffer; - forwardMrt[1] = data.normalBuffer; - if (data.decalLayersEnabled) - forwardMrt[2] = data.decalBuffer; - } - else - { - forwardMrt[0] = data.normalBuffer; - if (data.decalLayersEnabled) - forwardMrt[1] = data.decalBuffer; - } - - RenderDepthPrepass(context.renderContext, context.cmd, data.frameSettings - , deferredMrt - , forwardMrt - , data.depthBuffer - , data.rendererListDepthDeferred - , data.rendererListDepthForward - , data.hasDepthDeferredPass - ); - }); + RenderTargetIdentifier[] deferredMrt = null; + if (data.hasDepthDeferredPass && data.decalLayersEnabled) + { + deferredMrt = context.renderGraphPool.GetTempArray(1); + deferredMrt[0] = data.decalBuffer; + } + + var forwardMrt = context.renderGraphPool.GetTempArray((data.msaaEnabled ? 2 : 1) + (data.decalLayersEnabled ? 1 : 0)); + if (data.msaaEnabled) + { + forwardMrt[0] = data.depthAsColorBuffer; + forwardMrt[1] = data.normalBuffer; + if (data.decalLayersEnabled) + forwardMrt[2] = data.decalBuffer; + } + else + { + forwardMrt[0] = data.normalBuffer; + if (data.decalLayersEnabled) + forwardMrt[1] = data.decalBuffer; + } + + RenderDepthPrepass(context.renderContext, context.cmd, data.frameSettings + , deferredMrt + , forwardMrt + , data.depthBuffer + , data.rendererListDepthDeferred + , data.rendererListDepthForward + , data.hasDepthDeferredPass + ); + }); } return depthPrepassParameters.shouldRenderMotionVectorAfterGBuffer; @@ -417,13 +418,13 @@ void RenderObjectsMotionVectors(RenderGraph renderGraph, CullingResults cull, HD renderGraph.CreateRendererList(CreateOpaqueRendererListDesc(cull, hdCamera.camera, HDShaderPassNames.s_MotionVectorsName, PerObjectData.MotionVectors, stateBlock: stateBlock))); builder.SetRenderFunc( - (ObjectMotionVectorsPassData data, RenderGraphContext context) => - { - // Disable write to normal buffer for unlit shader (the normal buffer binding change when using MSAA) - context.cmd.SetGlobalInt(HDShaderIDs._ColorMaskNormal, data.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? (int)ColorWriteMask.All : 0); + (ObjectMotionVectorsPassData data, RenderGraphContext context) => + { + // Disable write to normal buffer for unlit shader (the normal buffer binding change when using MSAA) + context.cmd.SetGlobalInt(HDShaderIDs._ColorMaskNormal, data.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? (int)ColorWriteMask.All : 0); - DrawOpaqueRendererList(context, data.frameSettings, data.rendererList); - }); + DrawOpaqueRendererList(context, data.frameSettings, data.rendererList); + }); } } @@ -465,15 +466,17 @@ void SetupGBufferTargets(RenderGraph renderGraph, HDCamera hdCamera, GBufferPass // If we are in deferred mode and the SSR is enabled, we need to make sure that the second gbuffer is cleared given that we are using that information for clear coat selection bool clearGBuffer2 = clearGBuffer || hdCamera.IsSSREnabled(); passData.gbufferRT[currentIndex++] = builder.UseColorBuffer(renderGraph.CreateTexture( - new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = clearGBuffer2, clearColor = Color.clear, name = "GBuffer2" + new TextureDesc(Vector2.one, true, true) { + colorFormat = GraphicsFormat.R8G8B8A8_UNorm, clearBuffer = clearGBuffer2, clearColor = Color.clear, name = "GBuffer2" #if UNITY_2020_2_OR_NEWER , fastMemoryDesc = gbufferFastMemDesc #endif }), 2); passData.gbufferRT[currentIndex++] = builder.UseColorBuffer(renderGraph.CreateTexture( - new TextureDesc(Vector2.one, true, true) { colorFormat = Builtin.GetLightingBufferFormat(), clearBuffer = clearGBuffer, clearColor = Color.clear, name = "GBuffer3" + new TextureDesc(Vector2.one, true, true) { + colorFormat = Builtin.GetLightingBufferFormat(), clearBuffer = clearGBuffer, clearColor = Color.clear, name = "GBuffer3" #if UNITY_2020_2_OR_NEWER - , fastMemoryDesc = gbufferFastMemDesc + , fastMemoryDesc = gbufferFastMemDesc #endif }), 3); @@ -534,11 +537,11 @@ void RenderGBuffer(RenderGraph renderGraph, TextureHandle sssBuffer, TextureHand passData.dBuffer = ReadDBuffer(prepassOutput.dbuffer, builder); builder.SetRenderFunc( - (GBufferPassData data, RenderGraphContext context) => - { - BindDBufferGlobalData(data.dBuffer, context); - DrawOpaqueRendererList(context, data.frameSettings, data.rendererList); - }); + (GBufferPassData data, RenderGraphContext context) => + { + BindDBufferGlobalData(data.dBuffer, context); + DrawOpaqueRendererList(context, data.frameSettings, data.rendererList); + }); } } @@ -597,19 +600,19 @@ void ResolvePrepassBuffers(RenderGraph renderGraph, HDCamera hdCamera, ref Prepa output.depthValuesMSAA = passData.depthValuesBuffer; builder.SetRenderFunc( - (ResolvePrepassData data, RenderGraphContext context) => - { - data.depthResolveMaterial.SetTexture(HDShaderIDs._NormalTextureMS, data.normalBufferMSAA); - data.depthResolveMaterial.SetTexture(HDShaderIDs._DepthTextureMS, data.depthAsColorBufferMSAA); - if (data.needMotionVectors) + (ResolvePrepassData data, RenderGraphContext context) => { - data.depthResolveMaterial.SetTexture(HDShaderIDs._MotionVectorTextureMS, data.motionVectorBufferMSAA); - } + data.depthResolveMaterial.SetTexture(HDShaderIDs._NormalTextureMS, data.normalBufferMSAA); + data.depthResolveMaterial.SetTexture(HDShaderIDs._DepthTextureMS, data.depthAsColorBufferMSAA); + if (data.needMotionVectors) + { + data.depthResolveMaterial.SetTexture(HDShaderIDs._MotionVectorTextureMS, data.motionVectorBufferMSAA); + } - CoreUtils.SetKeyword(context.cmd, "_HAS_MOTION_VECTORS", data.needMotionVectors); + CoreUtils.SetKeyword(context.cmd, "_HAS_MOTION_VECTORS", data.needMotionVectors); - context.cmd.DrawProcedural(Matrix4x4.identity, data.depthResolveMaterial, data.depthResolvePassIndex, MeshTopology.Triangles, 3, 1); - }); + context.cmd.DrawProcedural(Matrix4x4.identity, data.depthResolveMaterial, data.depthResolvePassIndex, MeshTopology.Triangles, 3, 1); + }); } } @@ -624,7 +627,7 @@ class CopyDepthPassData void CopyDepthBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput output) { - if(!hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects)) + if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects)) { output.depthPyramidTexture = renderGraph.defaultResources.blackTextureXR; return; @@ -643,18 +646,18 @@ void CopyDepthBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref Pre output.depthPyramidTexture = passData.outputDepth; builder.SetRenderFunc( - (CopyDepthPassData data, RenderGraphContext context) => - { - // TODO: maybe we don't actually need the top MIP level? - // That way we could avoid making the copy, and build the MIP hierarchy directly. - // The downside is that our SSR tracing accuracy would decrease a little bit. - // But since we never render SSR at full resolution, this may be acceptable. - - // TODO: reading the depth buffer with a compute shader will cause it to decompress in place. - // On console, to preserve the depth test performance, we must NOT decompress the 'm_CameraDepthStencilBuffer' in place. - // We should call decompressDepthSurfaceToCopy() and decompress it to 'm_CameraDepthBufferMipChain'. - data.GPUCopy.SampleCopyChannel_xyzw2x(context.cmd, data.inputDepth, data.outputDepth, new RectInt(0, 0, data.width, data.height)); - }); + (CopyDepthPassData data, RenderGraphContext context) => + { + // TODO: maybe we don't actually need the top MIP level? + // That way we could avoid making the copy, and build the MIP hierarchy directly. + // The downside is that our SSR tracing accuracy would decrease a little bit. + // But since we never render SSR at full resolution, this may be acceptable. + + // TODO: reading the depth buffer with a compute shader will cause it to decompress in place. + // On console, to preserve the depth test performance, we must NOT decompress the 'm_CameraDepthStencilBuffer' in place. + // We should call decompressDepthSurfaceToCopy() and decompress it to 'm_CameraDepthBufferMipChain'. + data.GPUCopy.SampleCopyChannel_xyzw2x(context.cmd, data.inputDepth, data.outputDepth, new RectInt(0, 0, data.width, data.height)); + }); } m_IsDepthBufferCopyValid = true; @@ -684,10 +687,10 @@ void BuildCoarseStencilAndResolveIfNeeded(RenderGraph renderGraph, HDCamera hdCa else passData.resolvedStencil = output.stencilBuffer; builder.SetRenderFunc( - (ResolveStencilPassData data, RenderGraphContext context) => - { - BuildCoarseStencilAndResolveIfNeeded(data.parameters, data.inputDepth, data.resolvedStencil, data.coarseStencilBuffer, context.cmd); - }); + (ResolveStencilPassData data, RenderGraphContext context) => + { + BuildCoarseStencilAndResolveIfNeeded(data.parameters, data.inputDepth, data.resolvedStencil, data.coarseStencilBuffer, context.cmd); + }); bool isMSAAEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); if (isMSAAEnabled) @@ -775,8 +778,8 @@ void RenderDBuffer(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle dec } bool canReadBoundDepthBuffer = SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; if (!canReadBoundDepthBuffer) { @@ -786,8 +789,8 @@ void RenderDBuffer(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle dec // If we have an incomplete depth buffer use for decal we will need to do another copy // after the rendering of the GBuffer - if (( hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred) && - !hdCamera.frameSettings.IsEnabled(FrameSettingsField.DepthPrepassWithDeferredRendering)) + if ((hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred) && + !hdCamera.frameSettings.IsEnabled(FrameSettingsField.DepthPrepassWithDeferredRendering)) m_IsDepthBufferCopyValid = false; using (var builder = renderGraph.AddRenderPass("DBufferRender", out var passData, ProfilingSampler.Get(HDProfileId.DBufferRender))) @@ -799,29 +802,29 @@ void RenderDBuffer(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle dec passData.depthTexture = canReadBoundDepthBuffer ? builder.ReadTexture(output.resolvedDepthBuffer) : builder.ReadTexture(output.depthPyramidTexture); builder.SetRenderFunc( - (RenderDBufferPassData data, RenderGraphContext context) => - { - RenderTargetIdentifier[] rti = context.renderGraphPool.GetTempArray(data.dBufferCount); - RTHandle[] rt = context.renderGraphPool.GetTempArray(data.dBufferCount); - - // TODO : Remove once we remove old renderer - // This way we can directly use the UseColorBuffer API and set clear color directly at resource creation and not in the RenderDBuffer shared function. - for (int i = 0; i < data.dBufferCount; ++i) + (RenderDBufferPassData data, RenderGraphContext context) => { - rt[i] = data.mrt[i]; - rti[i] = rt[i]; - } - - RenderDBuffer( data.parameters, - rti, - rt, - data.depthStencilBuffer, - data.depthTexture, - data.meshDecalsRendererList, - data.decalBuffer, - context.renderContext, - context.cmd); - }); + RenderTargetIdentifier[] rti = context.renderGraphPool.GetTempArray(data.dBufferCount); + RTHandle[] rt = context.renderGraphPool.GetTempArray(data.dBufferCount); + + // TODO : Remove once we remove old renderer + // This way we can directly use the UseColorBuffer API and set clear color directly at resource creation and not in the RenderDBuffer shared function. + for (int i = 0; i < data.dBufferCount; ++i) + { + rt[i] = data.mrt[i]; + rti[i] = rt[i]; + } + + RenderDBuffer(data.parameters, + rti, + rt, + data.depthStencilBuffer, + data.depthTexture, + data.meshDecalsRendererList, + data.decalBuffer, + context.renderContext, + context.cmd); + }); } } @@ -847,14 +850,14 @@ void DecalNormalPatch(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOut passData.depthStencilBuffer = builder.ReadTexture(output.resolvedDepthBuffer); builder.SetRenderFunc( - (DBufferNormalPatchData data, RenderGraphContext ctx) => - { - RTHandle[] mrt = ctx.renderGraphPool.GetTempArray(data.dBuffer.dBufferCount); - for (int i = 0; i < data.dBuffer.dBufferCount; ++i) - mrt[i] = data.dBuffer.mrt[i]; - - DecalNormalPatch(data.parameters, mrt, data.depthStencilBuffer, data.normalBuffer, ctx.cmd); - }); + (DBufferNormalPatchData data, RenderGraphContext ctx) => + { + RTHandle[] mrt = ctx.renderGraphPool.GetTempArray(data.dBuffer.dBufferCount); + for (int i = 0; i < data.dBuffer.dBufferCount; ++i) + mrt[i] = data.dBuffer.mrt[i]; + + DecalNormalPatch(data.parameters, mrt, data.depthStencilBuffer, data.normalBuffer, ctx.cmd); + }); } } } @@ -892,7 +895,7 @@ void DownsampleDepthForLowResTransparency(RenderGraph renderGraph, HDCamera hdCa passData.downsampleDepthMaterial = m_DownsampleDepthMaterial; passData.depthTexture = builder.ReadTexture(output.depthPyramidTexture); - if(computeMip1OfPyramid) + if (computeMip1OfPyramid) { passData.depthTexture = builder.WriteTexture(passData.depthTexture); } @@ -900,21 +903,21 @@ void DownsampleDepthForLowResTransparency(RenderGraph renderGraph, HDCamera hdCa new TextureDesc(Vector2.one * 0.5f, true, true) { depthBufferBits = DepthBits.Depth32, name = "LowResDepthBuffer" }), DepthAccess.Write); builder.SetRenderFunc( - (DownsampleDepthForLowResPassData data, RenderGraphContext context) => - { - if (data.computesMip1OfAtlas) + (DownsampleDepthForLowResPassData data, RenderGraphContext context) => { - data.downsampleDepthMaterial.SetVector(HDShaderIDs._DstOffset, new Vector4(data.mip0Offset.x, data.mip0Offset.y, 0.0f, 0.0f)); - context.cmd.SetRandomWriteTarget(1, data.depthTexture); - } - - context.cmd.DrawProcedural(Matrix4x4.identity, data.downsampleDepthMaterial, 0, MeshTopology.Triangles, 3, 1, null); - - if (data.computesMip1OfAtlas) - { - context.cmd.ClearRandomWriteTargets(); - } - }); + if (data.computesMip1OfAtlas) + { + data.downsampleDepthMaterial.SetVector(HDShaderIDs._DstOffset, new Vector4(data.mip0Offset.x, data.mip0Offset.y, 0.0f, 0.0f)); + context.cmd.SetRandomWriteTarget(1, data.depthTexture); + } + + context.cmd.DrawProcedural(Matrix4x4.identity, data.downsampleDepthMaterial, 0, MeshTopology.Triangles, 3, 1, null); + + if (data.computesMip1OfAtlas) + { + context.cmd.ClearRandomWriteTargets(); + } + }); output.downsampledDepthBuffer = passData.downsampledDepthBuffer; } @@ -948,10 +951,10 @@ void GenerateDepthPyramid(RenderGraph renderGraph, HDCamera hdCamera, bool mip0A passData.mip0AlreadyComputed = mip0AlreadyComputed; builder.SetRenderFunc( - (GenerateDepthPyramidPassData data, RenderGraphContext context) => - { - data.mipGenerator.RenderMinDepthPyramid(context.cmd, data.depthTexture, data.mipInfo, data.mip0AlreadyComputed); - }); + (GenerateDepthPyramidPassData data, RenderGraphContext context) => + { + data.mipGenerator.RenderMinDepthPyramid(context.cmd, data.depthTexture, data.mipInfo, data.mip0AlreadyComputed); + }); output.depthPyramidTexture = passData.depthTexture; } @@ -987,10 +990,10 @@ void RenderCameraMotionVectors(RenderGraph renderGraph, HDCamera hdCamera, Textu passData.motionVectorsBuffer = builder.WriteTexture(motionVectorsBuffer); builder.SetRenderFunc( - (CameraMotionVectorsPassData data, RenderGraphContext context) => - { - HDUtils.DrawFullScreen(context.cmd, data.cameraMotionVectorsMaterial,data.motionVectorsBuffer, data.depthBuffer, null, 0); - }); + (CameraMotionVectorsPassData data, RenderGraphContext context) => + { + HDUtils.DrawFullScreen(context.cmd, data.cameraMotionVectorsMaterial, data.motionVectorsBuffer, data.depthBuffer, null, 0); + }); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 15df5695634..028165e2504 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -5,19 +5,18 @@ namespace UnityEngine.Rendering.HighDefinition { - public partial class HDRenderPipeline { - class TempPassData { }; + class TempPassData {}; // Needed only because of custom pass. See comment at ResolveMSAAColor. TextureHandle m_NonMSAAColorBuffer; - void ExecuteWithRenderGraph( RenderRequest renderRequest, - AOVRequestData aovRequest, - List aovBuffers, - ScriptableRenderContext renderContext, - CommandBuffer commandBuffer) + void ExecuteWithRenderGraph(RenderRequest renderRequest, + AOVRequestData aovRequest, + List aovBuffers, + ScriptableRenderContext renderContext, + CommandBuffer commandBuffer) { var hdCamera = renderRequest.hdCamera; var camera = hdCamera.camera; @@ -109,12 +108,12 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, // Evaluate the clear coat mask texture based on the lit shader mode var clearCoatMask = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? prepassOutput.gbuffer.mrt[2] : m_RenderGraph.defaultResources.blackTextureXR; lightingBuffers.ssrLightingBuffer = RenderSSR(m_RenderGraph, - hdCamera, - ref prepassOutput, - clearCoatMask, - rayCountTexture, - m_SkyManager.GetSkyReflection(hdCamera), - transparent: false); + hdCamera, + ref prepassOutput, + clearCoatMask, + rayCountTexture, + m_SkyManager.GetSkyReflection(hdCamera), + transparent: false); switch (GetIndirectDiffuseMode(hdCamera)) { @@ -124,8 +123,8 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, case IndirectDiffuseMode.Raytrace: lightingBuffers.ssgiLightingBuffer = RenderRayTracedIndirectDiffuse(m_RenderGraph, hdCamera, - prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.normalBuffer, prepassOutput.resolvedMotionVectorsBuffer, m_SkyManager.GetSkyReflection(hdCamera), rayCountTexture, - m_FrameCount, m_ShaderVariablesRayTracingCB); + prepassOutput.depthBuffer, prepassOutput.stencilBuffer, prepassOutput.normalBuffer, prepassOutput.resolvedMotionVectorsBuffer, m_SkyManager.GetSkyReflection(hdCamera), rayCountTexture, + m_FrameCount, m_ShaderVariablesRayTracingCB); break; default: lightingBuffers.ssgiLightingBuffer = m_RenderGraph.defaultResources.blackTextureXR; @@ -164,8 +163,8 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value && GetRayTracingState() && hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) { colorBuffer = RenderSubsurfaceScatteringRT(m_RenderGraph, hdCamera, - prepassOutput.depthBuffer, prepassOutput.normalBuffer, colorBuffer, - lightingBuffers.sssBuffer, lightingBuffers.diffuseLightingBuffer, prepassOutput.motionVectorsBuffer, lightingBuffers.ssgiLightingBuffer); + prepassOutput.depthBuffer, prepassOutput.normalBuffer, colorBuffer, + lightingBuffers.sssBuffer, lightingBuffers.diffuseLightingBuffer, prepassOutput.motionVectorsBuffer, lightingBuffers.ssgiLightingBuffer); } else RenderSubsurfaceScattering(m_RenderGraph, hdCamera, colorBuffer, lightingBuffers, ref prepassOutput); @@ -273,15 +272,15 @@ void ExecuteWithRenderGraph( RenderRequest renderRequest, { hdCamera.ExecuteCaptureActions(m_RenderGraph, colorBuffer); - postProcessDest = RenderDebug( m_RenderGraph, - hdCamera, - postProcessDest, - prepassOutput.resolvedDepthBuffer, - prepassOutput.depthPyramidTexture, - colorPickerTexture, - gpuLightListOutput, - shadowResult, - cullingResults); + postProcessDest = RenderDebug(m_RenderGraph, + hdCamera, + postProcessDest, + prepassOutput.resolvedDepthBuffer, + prepassOutput.depthPyramidTexture, + colorPickerTexture, + gpuLightListOutput, + shadowResult, + cullingResults); StopXRSinglePass(m_RenderGraph, hdCamera); @@ -338,10 +337,10 @@ void BlitFinalCameraTexture(RenderGraph renderGraph, HDCamera hdCamera, TextureH passData.destination = builder.WriteTexture(destination); builder.SetRenderFunc( - (FinalBlitPassData data, RenderGraphContext context) => - { - BlitFinalCameraTexture(data.parameters, context.renderGraphPool.GetTempMaterialPropertyBlock(), data.source, data.destination, context.cmd); - }); + (FinalBlitPassData data, RenderGraphContext context) => + { + BlitFinalCameraTexture(data.parameters, context.renderGraphPool.GetTempMaterialPropertyBlock(), data.source, data.destination, context.cmd); + }); } } @@ -377,25 +376,25 @@ void SetFinalTarget(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle de passData.flipY = hdCamera.isMainGameView; builder.SetRenderFunc( - (SetFinalTargetPassData data, RenderGraphContext ctx) => - { - // We need to make sure the viewport is correctly set for the editor rendering. It might have been changed by debug overlay rendering just before. - ctx.cmd.SetRenderTarget(data.finalTarget); - ctx.cmd.SetViewport(data.finalViewport); - - if (data.copyDepth) + (SetFinalTargetPassData data, RenderGraphContext ctx) => { - using (new ProfilingScope(ctx.cmd, ProfilingSampler.Get(HDProfileId.CopyDepthInTargetTexture))) + // We need to make sure the viewport is correctly set for the editor rendering. It might have been changed by debug overlay rendering just before. + ctx.cmd.SetRenderTarget(data.finalTarget); + ctx.cmd.SetViewport(data.finalViewport); + + if (data.copyDepth) { - var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock(); - mpb.SetTexture(HDShaderIDs._InputDepth, data.depthBuffer); - // When we are Main Game View we need to flip the depth buffer ourselves as we are after postprocess / blit that have already flipped the screen - mpb.SetInt("_FlipY", data.flipY ? 1 : 0); - mpb.SetVector(HDShaderIDs._BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); - CoreUtils.DrawFullScreen(ctx.cmd, data.copyDepthMaterial, mpb); + using (new ProfilingScope(ctx.cmd, ProfilingSampler.Get(HDProfileId.CopyDepthInTargetTexture))) + { + var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock(); + mpb.SetTexture(HDShaderIDs._InputDepth, data.depthBuffer); + // When we are Main Game View we need to flip the depth buffer ourselves as we are after postprocess / blit that have already flipped the screen + mpb.SetInt("_FlipY", data.flipY ? 1 : 0); + mpb.SetVector(HDShaderIDs._BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); + CoreUtils.DrawFullScreen(ctx.cmd, data.copyDepthMaterial, mpb); + } } - } - }); + }); } } @@ -420,19 +419,19 @@ void CopyXRDepth(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depth passData.output = builder.WriteTexture(output); builder.SetRenderFunc( - (CopyXRDepthPassData data, RenderGraphContext ctx) => - { - var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock(); - RTHandle depthRT = data.depthBuffer; + (CopyXRDepthPassData data, RenderGraphContext ctx) => + { + var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock(); + RTHandle depthRT = data.depthBuffer; - mpb.SetTexture(HDShaderIDs._InputDepth, data.depthBuffer); - mpb.SetVector(HDShaderIDs._BlitScaleBias, depthRT.rtHandleProperties.rtHandleScale / DynamicResolutionHandler.instance.GetCurrentScale()); - mpb.SetInt("_FlipY", 1); + mpb.SetTexture(HDShaderIDs._InputDepth, data.depthBuffer); + mpb.SetVector(HDShaderIDs._BlitScaleBias, depthRT.rtHandleProperties.rtHandleScale / DynamicResolutionHandler.instance.GetCurrentScale()); + mpb.SetInt("_FlipY", 1); - ctx.cmd.SetRenderTarget(data.output, 0, CubemapFace.Unknown, -1); - ctx.cmd.SetViewport(data.viewport); - CoreUtils.DrawFullScreen(ctx.cmd, data.copyDepth, mpb); - }); + ctx.cmd.SetRenderTarget(data.output, 0, CubemapFace.Unknown, -1); + ctx.cmd.SetViewport(data.viewport); + CoreUtils.DrawFullScreen(ctx.cmd, data.copyDepth, mpb); + }); } } } @@ -462,18 +461,17 @@ class ForwardTransparentPassData : ForwardPassData public TextureHandle transparentSSRLighting; public TextureHandle volumetricLighting; public TextureHandle depthPyramidTexture; - } - void PrepareCommonForwardPassData( RenderGraph renderGraph, - RenderGraphBuilder builder, - ForwardPassData data, - bool opaque, - FrameSettings frameSettings, - RendererListDesc rendererListDesc, - in BuildGPULightListOutput lightLists, - TextureHandle depthBuffer, - ShadowResult shadowResult) + void PrepareCommonForwardPassData(RenderGraph renderGraph, + RenderGraphBuilder builder, + ForwardPassData data, + bool opaque, + FrameSettings frameSettings, + RendererListDesc rendererListDesc, + in BuildGPULightListOutput lightLists, + TextureHandle depthBuffer, + ShadowResult shadowResult) { bool useFptl = frameSettings.IsEnabled(FrameSettingsField.FPTLForForwardOpaque) && opaque; @@ -507,25 +505,25 @@ static void BindGlobalLightListBuffers(ForwardPassData data, RenderGraphContext // The RenderForward pass will render the appropriate pass depends on the engine settings. In case of forward only rendering, both "Forward" pass and "ForwardOnly" pass // material will be render for both transparent and opaque. In case of deferred, both path are used for transparent but only "ForwardOnly" is use for opaque. // (Thus why "Forward" and "ForwardOnly" are exclusive, else they will render two times" - void RenderForwardOpaque( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - in LightingBuffers lightingBuffers, - in BuildGPULightListOutput lightLists, - TextureHandle depthBuffer, - TextureHandle vtFeedbackBuffer, - ShadowResult shadowResult, - DBufferOutput dbuffer, - CullingResults cullResults) + void RenderForwardOpaque(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + in LightingBuffers lightingBuffers, + in BuildGPULightListOutput lightLists, + TextureHandle depthBuffer, + TextureHandle vtFeedbackBuffer, + ShadowResult shadowResult, + DBufferOutput dbuffer, + CullingResults cullResults) { bool debugDisplay = m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled(); if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects)) return; - using (var builder = renderGraph.AddRenderPass( debugDisplay ? "Forward Opaque Debug" : "Forward Opaque", - out var passData, - debugDisplay ? ProfilingSampler.Get(HDProfileId.ForwardOpaqueDebug) : ProfilingSampler.Get(HDProfileId.ForwardOpaque))) + using (var builder = renderGraph.AddRenderPass(debugDisplay ? "Forward Opaque Debug" : "Forward Opaque", + out var passData, + debugDisplay ? ProfilingSampler.Get(HDProfileId.ForwardOpaqueDebug) : ProfilingSampler.Get(HDProfileId.ForwardOpaque))) { PrepareCommonForwardPassData(renderGraph, builder, passData, true, hdCamera.frameSettings, PrepareForwardOpaqueRendererList(cullResults, hdCamera), lightLists, depthBuffer, shadowResult); @@ -555,34 +553,34 @@ void RenderForwardOpaque( RenderGraph renderGraph, passData.lightingBuffers = ReadLightingBuffers(lightingBuffers, builder); builder.SetRenderFunc( - (ForwardOpaquePassData data, RenderGraphContext context) => - { - // TODO RENDERGRAPH: replace with UseColorBuffer when removing old rendering (SetRenderTarget is called inside RenderForwardRendererList because of that). - var mrt = context.renderGraphPool.GetTempArray(data.renderTargetCount); - for (int i = 0; i < data.renderTargetCount; ++i) - mrt[i] = data.renderTarget[i]; + (ForwardOpaquePassData data, RenderGraphContext context) => + { + // TODO RENDERGRAPH: replace with UseColorBuffer when removing old rendering (SetRenderTarget is called inside RenderForwardRendererList because of that). + var mrt = context.renderGraphPool.GetTempArray(data.renderTargetCount); + for (int i = 0; i < data.renderTargetCount; ++i) + mrt[i] = data.renderTarget[i]; - BindGlobalLightListBuffers(data, context); - BindDBufferGlobalData(data.dbuffer, context); - BindGlobalLightingBuffers(data.lightingBuffers, context.cmd); + BindGlobalLightListBuffers(data, context); + BindDBufferGlobalData(data.dbuffer, context); + BindGlobalLightingBuffers(data.lightingBuffers, context.cmd); - RenderForwardRendererList(data.frameSettings, data.rendererList, mrt, data.depthBuffer, data.lightListBuffer, true, context.renderContext, context.cmd); - }); + RenderForwardRendererList(data.frameSettings, data.rendererList, mrt, data.depthBuffer, data.lightListBuffer, true, context.renderContext, context.cmd); + }); } } - void RenderForwardTransparent( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - in PrepassOutput prepassOutput, - TextureHandle vtFeedbackBuffer, - TextureHandle volumetricLighting, - TextureHandle ssrLighting, - TextureHandle? colorPyramid, - in BuildGPULightListOutput lightLists, - in ShadowResult shadowResult, - CullingResults cullResults, - bool preRefractionPass) + void RenderForwardTransparent(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + in PrepassOutput prepassOutput, + TextureHandle vtFeedbackBuffer, + TextureHandle volumetricLighting, + TextureHandle ssrLighting, + TextureHandle? colorPyramid, + in BuildGPULightListOutput lightLists, + in ShadowResult shadowResult, + CullingResults cullResults, + bool preRefractionPass) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentObjects)) return; @@ -646,29 +644,28 @@ void RenderForwardTransparent( RenderGraph renderGraph, builder.SetRenderFunc( (ForwardTransparentPassData data, RenderGraphContext context) => - { - // TODO: replace with UseColorBuffer when removing old rendering. - var mrt = context.renderGraphPool.GetTempArray(data.renderTargetCount); - for (int i = 0; i < data.renderTargetCount; ++i) - mrt[i] = data.renderTarget[i]; + { + // TODO: replace with UseColorBuffer when removing old rendering. + var mrt = context.renderGraphPool.GetTempArray(data.renderTargetCount); + for (int i = 0; i < data.renderTargetCount; ++i) + mrt[i] = data.renderTarget[i]; - // Bind all global data/parameters for transparent forward pass - context.cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, data.renderMotionVecForTransparent ? (int)ColorWriteMask.All : 0); - if (data.decalsEnabled) - DecalSystem.instance.SetAtlas(context.cmd); // for clustered decals + // Bind all global data/parameters for transparent forward pass + context.cmd.SetGlobalInt(HDShaderIDs._ColorMaskTransparentVel, data.renderMotionVecForTransparent ? (int)ColorWriteMask.All : 0); + if (data.decalsEnabled) + DecalSystem.instance.SetAtlas(context.cmd); // for clustered decals - BindGlobalLightListBuffers(data, context); + BindGlobalLightListBuffers(data, context); - context.cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, data.transparentSSRLighting); - context.cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, data.volumetricLighting); - context.cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, data.depthPyramidTexture); + context.cmd.SetGlobalTexture(HDShaderIDs._SsrLightingTexture, data.transparentSSRLighting); + context.cmd.SetGlobalTexture(HDShaderIDs._VBufferLighting, data.volumetricLighting); + context.cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, data.depthPyramidTexture); - RenderForwardRendererList( data.frameSettings, data.rendererList, mrt, data.depthBuffer, data.lightListBuffer, false, context.renderContext, context.cmd); - }); + RenderForwardRendererList(data.frameSettings, data.rendererList, mrt, data.depthBuffer, data.lightListBuffer, false, context.renderContext, context.cmd); + }); } } - void RenderTransparentDepthPrepass(RenderGraph renderGraph, HDCamera hdCamera, in PrepassOutput prepassOutput, CullingResults cull) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentPrepass)) @@ -686,10 +683,10 @@ void RenderTransparentDepthPrepass(RenderGraph renderGraph, HDCamera hdCamera, i CreateTransparentRendererListDesc(cull, hdCamera.camera, m_TransparentDepthPrepassNames))); builder.SetRenderFunc( - (ForwardPassData data, RenderGraphContext context) => - { - DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.rendererList); - }); + (ForwardPassData data, RenderGraphContext context) => + { + DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.rendererList); + }); } } @@ -707,10 +704,10 @@ void RenderTransparentDepthPostpass(RenderGraph renderGraph, HDCamera hdCamera, CreateTransparentRendererListDesc(cull, hdCamera.camera, m_TransparentDepthPostpassNames))); builder.SetRenderFunc( - (ForwardPassData data, RenderGraphContext context) => - { - DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.rendererList); - }); + (ForwardPassData data, RenderGraphContext context) => + { + DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.rendererList); + }); } } @@ -739,16 +736,16 @@ TextureHandle RenderLowResTransparent(RenderGraph renderGraph, HDCamera hdCamera { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, clearBuffer = true, clearColor = Color.black, name = "Low res transparent" }), 0); builder.SetRenderFunc( - (RenderLowResTransparentPassData data, RenderGraphContext context) => - { - UpdateOffscreenRenderingConstants(ref data.globalCB, true, 2u); - ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + (RenderLowResTransparentPassData data, RenderGraphContext context) => + { + UpdateOffscreenRenderingConstants(ref data.globalCB, true, 2u); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); - DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.rendererList); + DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.rendererList); - UpdateOffscreenRenderingConstants(ref data.globalCB, false, 1u); - ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); - }); + UpdateOffscreenRenderingConstants(ref data.globalCB, false, 1u); + ConstantBuffer.PushGlobal(context.cmd, data.globalCB, HDShaderIDs._ShaderVariablesGlobal); + }); return passData.lowResBuffer; } @@ -782,12 +779,12 @@ void UpsampleTransparent(RenderGraph renderGraph, HDCamera hdCamera, TextureHand passData.downsampledDepthBuffer = builder.ReadTexture(downsampledDepthBuffer); builder.SetRenderFunc( - (UpsampleTransparentPassData data, RenderGraphContext context) => - { - data.upsampleMaterial.SetTexture(HDShaderIDs._LowResTransparent, data.lowResTransparentBuffer); - data.upsampleMaterial.SetTexture(HDShaderIDs._LowResDepthTexture, data.downsampledDepthBuffer); - context.cmd.DrawProcedural(Matrix4x4.identity, data.upsampleMaterial, 0, MeshTopology.Triangles, 3, 1, null); - }); + (UpsampleTransparentPassData data, RenderGraphContext context) => + { + data.upsampleMaterial.SetTexture(HDShaderIDs._LowResTransparent, data.lowResTransparentBuffer); + data.upsampleMaterial.SetTexture(HDShaderIDs._LowResDepthTexture, data.downsampledDepthBuffer); + context.cmd.DrawProcedural(Matrix4x4.identity, data.upsampleMaterial, 0, MeshTopology.Triangles, 3, 1, null); + }); } } @@ -801,7 +798,7 @@ void SetGlobalColorForCustomPass(RenderGraph renderGraph, TextureHandle colorBuf using (var builder = renderGraph.AddRenderPass("SetGlobalColorForCustomPass", out var passData)) { passData.colorBuffer = builder.ReadTexture(colorBuffer); - builder.SetRenderFunc( (SetGlobalColorPassData data, RenderGraphContext context) => + builder.SetRenderFunc((SetGlobalColorPassData data, RenderGraphContext context) => { RTHandle colorPyramid = data.colorBuffer; if (colorPyramid != null) @@ -809,6 +806,7 @@ void SetGlobalColorForCustomPass(RenderGraph renderGraph, TextureHandle colorBuf }); } } + class RecursiveRenderingPrepassPassData { public FrameSettings frameSettings; @@ -854,35 +852,34 @@ void RenderRayTracingPrepass(RenderGraph renderGraph, CullingResults cull, HDCam } builder.SetRenderFunc( - (RecursiveRenderingPrepassPassData data, RenderGraphContext context) => - { - if (data.clear) - CoreUtils.SetRenderTarget(context.cmd, data.flagMask, data.depthBuffer, clearFlag: ClearFlag.Color, Color.black); - else - CoreUtils.SetRenderTarget(context.cmd, data.flagMask, data.depthBuffer); + (RecursiveRenderingPrepassPassData data, RenderGraphContext context) => + { + if (data.clear) + CoreUtils.SetRenderTarget(context.cmd, data.flagMask, data.depthBuffer, clearFlag: ClearFlag.Color, Color.black); + else + CoreUtils.SetRenderTarget(context.cmd, data.flagMask, data.depthBuffer); - DrawOpaqueRendererList(context.renderContext, context.cmd, data.frameSettings, data.opaqueRenderList); - DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.transparentRenderList); - }); + DrawOpaqueRendererList(context.renderContext, context.cmd, data.frameSettings, data.opaqueRenderList); + DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.transparentRenderList); + }); } } - - TextureHandle RenderTransparency( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - TextureHandle vtFeedbackBuffer, - TextureHandle currentColorPyramid, - TextureHandle volumetricLighting, - TextureHandle rayCountTexture, - Texture skyTexture, - in BuildGPULightListOutput lightLists, - ref PrepassOutput prepassOutput, - ShadowResult shadowResult, - CullingResults cullingResults, - CullingResults customPassCullingResults, - AOVRequestData aovRequest, - List aovBuffers) + TextureHandle RenderTransparency(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle vtFeedbackBuffer, + TextureHandle currentColorPyramid, + TextureHandle volumetricLighting, + TextureHandle rayCountTexture, + Texture skyTexture, + in BuildGPULightListOutput lightLists, + ref PrepassOutput prepassOutput, + ShadowResult shadowResult, + CullingResults cullingResults, + CullingResults customPassCullingResults, + AOVRequestData aovRequest, + List aovBuffers) { RenderTransparentDepthPrepass(renderGraph, hdCamera, prepassOutput, cullingResults); @@ -935,11 +932,11 @@ class RenderForwardEmissivePassData public RendererListHandle rendererList; } - void RenderForwardEmissive( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - TextureHandle depthStencilBuffer, - CullingResults cullingResults) + void RenderForwardEmissive(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + CullingResults cullingResults) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentObjects) && !hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects)) @@ -957,21 +954,21 @@ void RenderForwardEmissive( RenderGraph renderGraph, builder.SetRenderFunc( (RenderForwardEmissivePassData data, RenderGraphContext context) => - { - CoreUtils.DrawRendererList(context.renderContext, context.cmd, data.rendererList); - if (data.enableDecals) - DecalSystem.instance.RenderForwardEmissive(context.cmd); - }); + { + CoreUtils.DrawRendererList(context.renderContext, context.cmd, data.rendererList); + if (data.enableDecals) + DecalSystem.instance.RenderForwardEmissive(context.cmd); + }); } } // This is use to Display legacy shader with an error shader [System.Diagnostics.Conditional("DEVELOPMENT_BUILD"), System.Diagnostics.Conditional("UNITY_EDITOR")] void RenderForwardError(RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - TextureHandle depthStencilBuffer, - CullingResults cullResults) + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + CullingResults cullResults) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentObjects) && !hdCamera.frameSettings.IsEnabled(FrameSettingsField.OpaqueObjects)) @@ -1028,10 +1025,10 @@ void SendGeometryGraphicsBuffers(RenderGraph renderGraph, TextureHandle normalBu } builder.SetRenderFunc( - (SendGeometryBuffersPassData data, RenderGraphContext ctx) => - { - SendGeometryGraphicsBuffers(data.parameters, data.normalBuffer, data.depthBuffer, ctx.cmd); - }); + (SendGeometryBuffersPassData data, RenderGraphContext ctx) => + { + SendGeometryGraphicsBuffers(data.parameters, data.normalBuffer, data.depthBuffer, ctx.cmd); + }); } } @@ -1049,10 +1046,10 @@ void SendColorGraphicsBuffer(RenderGraph renderGraph, HDCamera hdCamera) passData.hdCamera = hdCamera; builder.SetRenderFunc( - (SendColorGraphicsBufferPassData data, RenderGraphContext ctx) => - { - SendColorGraphicsBuffer(ctx.cmd, data.hdCamera); - }); + (SendColorGraphicsBufferPassData data, RenderGraphContext ctx) => + { + SendColorGraphicsBuffer(ctx.cmd, data.hdCamera); + }); } } @@ -1072,11 +1069,11 @@ void ClearStencilBuffer(RenderGraph renderGraph, TextureHandle colorBuffer, Text passData.depthBuffer = builder.WriteTexture(depthBuffer); builder.SetRenderFunc( - (ClearStencilPassData data, RenderGraphContext ctx) => - { - data.clearStencilMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.HDRPReservedBits); - HDUtils.DrawFullScreen(ctx.cmd, data.clearStencilMaterial, data.colorBuffer, data.depthBuffer); - }); + (ClearStencilPassData data, RenderGraphContext ctx) => + { + data.clearStencilMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.HDRPReservedBits); + HDUtils.DrawFullScreen(ctx.cmd, data.clearStencilMaterial, data.colorBuffer, data.depthBuffer); + }); } } @@ -1112,10 +1109,10 @@ void PreRenderSky(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colo passData.frameCount = m_FrameCount; builder.SetRenderFunc( - (PreRenderSkyPassData data, RenderGraphContext context) => - { - data.skyManager.PreRenderSky(data.hdCamera, data.sunLight, data.colorBuffer, data.normalBuffer, data.depthStencilBuffer, data.debugDisplaySettings, data.frameCount, context.cmd); - }); + (PreRenderSkyPassData data, RenderGraphContext context) => + { + data.skyManager.PreRenderSky(data.hdCamera, data.sunLight, data.colorBuffer, data.normalBuffer, data.depthStencilBuffer, data.debugDisplaySettings, data.frameCount, context.cmd); + }); } } @@ -1156,19 +1153,19 @@ void RenderSky(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBu passData.frameCount = m_FrameCount; builder.SetRenderFunc( - (RenderSkyPassData data, RenderGraphContext context) => - { - // Necessary to perform dual-source (polychromatic alpha) blending which is not supported by Unity. - // We load from the color buffer, perform blending manually, and store to the atmospheric scattering buffer. - // Then we perform a copy from the atmospheric scattering buffer back to the color buffer. - data.skyManager.RenderSky(data.hdCamera, data.sunLight, data.colorBuffer, data.depthStencilBuffer, data.debugDisplaySettings, data.frameCount, context.cmd); - - if (Fog.IsFogEnabled(data.hdCamera) || Fog.IsPBRFogEnabled(data.hdCamera)) + (RenderSkyPassData data, RenderGraphContext context) => { - var pixelCoordToViewDirWS = data.hdCamera.mainViewConstants.pixelCoordToViewDirWS; - data.skyManager.RenderOpaqueAtmosphericScattering(context.cmd, data.hdCamera, data.colorBuffer, data.depthTexture, data.volumetricLighting, data.intermediateBuffer, data.depthStencilBuffer, pixelCoordToViewDirWS, data.hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)); - } - }); + // Necessary to perform dual-source (polychromatic alpha) blending which is not supported by Unity. + // We load from the color buffer, perform blending manually, and store to the atmospheric scattering buffer. + // Then we perform a copy from the atmospheric scattering buffer back to the color buffer. + data.skyManager.RenderSky(data.hdCamera, data.sunLight, data.colorBuffer, data.depthStencilBuffer, data.debugDisplaySettings, data.frameCount, context.cmd); + + if (Fog.IsFogEnabled(data.hdCamera) || Fog.IsPBRFogEnabled(data.hdCamera)) + { + var pixelCoordToViewDirWS = data.hdCamera.mainViewConstants.pixelCoordToViewDirWS; + data.skyManager.RenderOpaqueAtmosphericScattering(context.cmd, data.hdCamera, data.colorBuffer, data.depthTexture, data.volumetricLighting, data.intermediateBuffer, data.depthStencilBuffer, pixelCoordToViewDirWS, data.hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)); + } + }); } } @@ -1190,14 +1187,14 @@ void GenerateColorPyramid(RenderGraph renderGraph, HDCamera hdCamera, TextureHan passData.mipGenerator = m_MipGenerator; builder.SetRenderFunc( - (GenerateColorPyramidData data, RenderGraphContext context) => - { - Vector2Int pyramidSize = new Vector2Int(data.hdCamera.actualWidth, data.hdCamera.actualHeight); - data.hdCamera.colorPyramidHistoryMipCount = data.mipGenerator.RenderColorGaussianPyramid(context.cmd, pyramidSize, data.inputColor, data.colorPyramid); - // TODO RENDERGRAPH: We'd like to avoid SetGlobals like this but it's required by custom passes currently. - // We will probably be able to remove those once we push custom passes fully to render graph. - context.cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, data.colorPyramid); - }); + (GenerateColorPyramidData data, RenderGraphContext context) => + { + Vector2Int pyramidSize = new Vector2Int(data.hdCamera.actualWidth, data.hdCamera.actualHeight); + data.hdCamera.colorPyramidHistoryMipCount = data.mipGenerator.RenderColorGaussianPyramid(context.cmd, pyramidSize, data.inputColor, data.colorPyramid); + // TODO RENDERGRAPH: We'd like to avoid SetGlobals like this but it's required by custom passes currently. + // We will probably be able to remove those once we push custom passes fully to render graph. + context.cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, data.colorPyramid); + }); } // Note: hdCamera.colorPyramidHistoryMipCount is going to be one frame late here (rendering, which is done later, is updating it) @@ -1214,10 +1211,10 @@ class AccumulateDistortionPassData public FrameSettings frameSettings; } - TextureHandle AccumulateDistortion( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle depthStencilBuffer, - CullingResults cullResults) + TextureHandle AccumulateDistortion(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle depthStencilBuffer, + CullingResults cullResults) { using (var builder = renderGraph.AddRenderPass("Accumulate Distortion", out var passData, ProfilingSampler.Get(HDProfileId.AccumulateDistortion))) { @@ -1229,10 +1226,10 @@ TextureHandle AccumulateDistortion( RenderGraph renderGraph, CreateTransparentRendererListDesc(cullResults, hdCamera.camera, HDShaderPassNames.s_DistortionVectorsName))); builder.SetRenderFunc( - (AccumulateDistortionPassData data, RenderGraphContext context) => - { - DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.distortionRendererList); - }); + (AccumulateDistortionPassData data, RenderGraphContext context) => + { + DrawTransparentRendererList(context.renderContext, context.cmd, data.frameSettings, data.distortionRendererList); + }); return passData.distortionBuffer; } @@ -1249,12 +1246,12 @@ class RenderDistortionPassData public bool roughDistortion; } - void RenderDistortion( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - TextureHandle depthStencilBuffer, - TextureHandle colorPyramidBuffer, - TextureHandle distortionBuffer) + void RenderDistortion(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + TextureHandle depthStencilBuffer, + TextureHandle colorPyramidBuffer, + TextureHandle distortionBuffer) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Distortion)) return; @@ -1270,27 +1267,26 @@ void RenderDistortion( RenderGraph renderGraph, passData.size = new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1f / hdCamera.actualWidth, 1f / hdCamera.actualHeight); builder.SetRenderFunc( - (RenderDistortionPassData data, RenderGraphContext context) => - { - if (!data.roughDistortion) - HDUtils.BlitCameraTexture(context.cmd, data.colorBuffer, data.sourceColorBuffer); - - // TODO: Set stencil stuff via parameters rather than hard-coding it in shader. - data.applyDistortionMaterial.SetTexture(HDShaderIDs._DistortionTexture, data.distortionBuffer); - data.applyDistortionMaterial.SetTexture(HDShaderIDs._ColorPyramidTexture, data.sourceColorBuffer); - data.applyDistortionMaterial.SetVector(HDShaderIDs._Size, data.size); - data.applyDistortionMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.DistortionVectors); - data.applyDistortionMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.DistortionVectors); - data.applyDistortionMaterial.SetInt(HDShaderIDs._RoughDistortion, data.roughDistortion ? 1 : 0); - - HDUtils.DrawFullScreen(context.cmd, data.applyDistortionMaterial, data.colorBuffer, data.depthStencilBuffer, null, 0); - }); + (RenderDistortionPassData data, RenderGraphContext context) => + { + if (!data.roughDistortion) + HDUtils.BlitCameraTexture(context.cmd, data.colorBuffer, data.sourceColorBuffer); + + // TODO: Set stencil stuff via parameters rather than hard-coding it in shader. + data.applyDistortionMaterial.SetTexture(HDShaderIDs._DistortionTexture, data.distortionBuffer); + data.applyDistortionMaterial.SetTexture(HDShaderIDs._ColorPyramidTexture, data.sourceColorBuffer); + data.applyDistortionMaterial.SetVector(HDShaderIDs._Size, data.size); + data.applyDistortionMaterial.SetInt(HDShaderIDs._StencilMask, (int)StencilUsage.DistortionVectors); + data.applyDistortionMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilUsage.DistortionVectors); + data.applyDistortionMaterial.SetInt(HDShaderIDs._RoughDistortion, data.roughDistortion ? 1 : 0); + + HDUtils.DrawFullScreen(context.cmd, data.applyDistortionMaterial, data.colorBuffer, data.depthStencilBuffer, null, 0); + }); } } TextureHandle CreateColorBuffer(RenderGraph renderGraph, HDCamera hdCamera, bool msaa) { - #if UNITY_2020_2_OR_NEWER FastMemoryDesc colorFastMemDesc; colorFastMemDesc.inFastMemory = true; @@ -1356,12 +1352,12 @@ TextureHandle ResolveMSAAColor(RenderGraph renderGraph, HDCamera hdCamera, Textu passData.passIndex = SampleCountToPassIndex(m_MSAASamples); builder.SetRenderFunc( - (ResolveColorData data, RenderGraphContext context) => - { - var mpb = context.renderGraphPool.GetTempMaterialPropertyBlock(); - mpb.SetTexture(HDShaderIDs._ColorTextureMS, data.input); - context.cmd.DrawProcedural(Matrix4x4.identity, data.resolveMaterial, data.passIndex, MeshTopology.Triangles, 3, 1, mpb); - }); + (ResolveColorData data, RenderGraphContext context) => + { + var mpb = context.renderGraphPool.GetTempMaterialPropertyBlock(); + mpb.SetTexture(HDShaderIDs._ColorTextureMS, data.input); + context.cmd.DrawProcedural(Matrix4x4.identity, data.resolveMaterial, data.passIndex, MeshTopology.Triangles, 3, 1, mpb); + }); return passData.output; } @@ -1431,11 +1427,10 @@ void RenderAccumulation(RenderGraph renderGraph, HDCamera hdCamera, TextureHandl passData.history = builder.WriteTexture(history); builder.SetRenderFunc( - (RenderAccumulationPassData data, RenderGraphContext ctx) => - { - RenderAccumulation(data.parameters, data.input, data.output, data.history, ctx.cmd); - }); - + (RenderAccumulationPassData data, RenderGraphContext ctx) => + { + RenderAccumulation(data.parameters, data.input, data.output, data.history, ctx.cmd); + }); } } @@ -1465,27 +1460,27 @@ void RenderGizmos(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colo passData.exposureTexture = isMatCapView ? (Texture)Texture2D.blackTexture : m_PostProcessSystem.GetExposureTexture(hdCamera).rt; builder.SetRenderFunc( - (RenderGizmosPassData data, RenderGraphContext ctx) => - { - Gizmos.exposure = data.exposureTexture; + (RenderGizmosPassData data, RenderGraphContext ctx) => + { + Gizmos.exposure = data.exposureTexture; - ctx.renderContext.ExecuteCommandBuffer(ctx.cmd); - ctx.cmd.Clear(); - ctx.renderContext.DrawGizmos(data.camera, data.gizmoSubset); - }); + ctx.renderContext.ExecuteCommandBuffer(ctx.cmd); + ctx.cmd.Clear(); + ctx.renderContext.DrawGizmos(data.camera, data.gizmoSubset); + }); } } #endif } - bool RenderCustomPass( RenderGraph renderGraph, - HDCamera hdCamera, - TextureHandle colorBuffer, - in PrepassOutput prepassOutput, - CullingResults cullingResults, - CustomPassInjectionPoint injectionPoint, - AOVRequestData aovRequest, - List aovCustomPassBuffers) + bool RenderCustomPass(RenderGraph renderGraph, + HDCamera hdCamera, + TextureHandle colorBuffer, + in PrepassOutput prepassOutput, + CullingResults cullingResults, + CustomPassInjectionPoint injectionPoint, + AOVRequestData aovRequest, + List aovCustomPassBuffers) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) return false; @@ -1542,13 +1537,13 @@ void BindCustomPassBuffers(RenderGraph renderGraph, HDCamera hdCamera) passData.customDepthTexture = m_CustomPassDepthBuffer; builder.SetRenderFunc( - (BindCustomPassBuffersPassData data, RenderGraphContext ctx) => - { - if (data.customColorTexture.IsValueCreated) - ctx.cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, data.customColorTexture.Value); - if (data.customDepthTexture.IsValueCreated) - ctx.cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, data.customDepthTexture.Value); - }); + (BindCustomPassBuffersPassData data, RenderGraphContext ctx) => + { + if (data.customColorTexture.IsValueCreated) + ctx.cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, data.customColorTexture.Value); + if (data.customDepthTexture.IsValueCreated) + ctx.cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, data.customDepthTexture.Value); + }); } } } @@ -1571,12 +1566,12 @@ void RenderWireOverlay(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle passData.hdCamera = hdCamera; builder.SetRenderFunc( - (RenderWireOverlayPassData data, RenderGraphContext ctx) => - { - ctx.renderContext.ExecuteCommandBuffer(ctx.cmd); - ctx.cmd.Clear(); - ctx.renderContext.DrawWireOverlay(data.hdCamera.camera); - }); + (RenderWireOverlayPassData data, RenderGraphContext ctx) => + { + ctx.renderContext.ExecuteCommandBuffer(ctx.cmd); + ctx.cmd.Clear(); + ctx.renderContext.DrawWireOverlay(data.hdCamera.camera); + }); } } #endif diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs index 76318029a9c..46066c1125c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraphUtils.cs @@ -27,7 +27,8 @@ static int SampleCountToPassIndex(MSAASamples samples) return 2; case MSAASamples.MSAA8x: return 3; - }; + } + ; return 0; } @@ -62,7 +63,6 @@ Color GetColorBufferClearColor(HDCamera hdCamera) return clearColor; } - // XR Specific class XRRenderingPassData { @@ -78,10 +78,10 @@ internal static void StartXRSinglePass(RenderGraph renderGraph, HDCamera hdCamer passData.xr = hdCamera.xr; builder.SetRenderFunc( - (XRRenderingPassData data, RenderGraphContext context) => - { - data.xr.StartSinglePass(context.cmd); - }); + (XRRenderingPassData data, RenderGraphContext context) => + { + data.xr.StartSinglePass(context.cmd); + }); } } } @@ -95,10 +95,10 @@ internal static void StopXRSinglePass(RenderGraph renderGraph, HDCamera hdCamera passData.xr = hdCamera.xr; builder.SetRenderFunc( - (XRRenderingPassData data, RenderGraphContext context) => - { - data.xr.StopSinglePass(context.cmd); - }); + (XRRenderingPassData data, RenderGraphContext context) => + { + data.xr.StopSinglePass(context.cmd); + }); } } } @@ -117,10 +117,10 @@ void EndCameraXR(RenderGraph renderGraph, HDCamera hdCamera) passData.hdCamera = hdCamera; builder.SetRenderFunc( - (EndCameraXRPassData data, RenderGraphContext ctx) => - { - data.hdCamera.xr.EndCamera(ctx.cmd, data.hdCamera); - }); + (EndCameraXRPassData data, RenderGraphContext ctx) => + { + data.hdCamera.xr.EndCamera(ctx.cmd, data.hdCamera); + }); } } } @@ -145,10 +145,10 @@ void RenderXROcclusionMeshes(RenderGraph renderGraph, HDCamera hdCamera, Texture passData.clearColor = GetColorBufferClearColor(hdCamera); builder.SetRenderFunc( - (RenderOcclusionMeshesPassData data, RenderGraphContext ctx) => - { - data.hdCamera.xr.RenderOcclusionMeshes(ctx.cmd, data.clearColor, data.colorBuffer, data.depthBuffer); - }); + (RenderOcclusionMeshesPassData data, RenderGraphContext ctx) => + { + data.hdCamera.xr.RenderOcclusionMeshes(ctx.cmd, data.clearColor, data.colorBuffer, data.depthBuffer); + }); } } } @@ -170,10 +170,10 @@ static internal void BlitCameraTexture(RenderGraph renderGraph, TextureHandle so passData.mipLevel = mipLevel; passData.bilinear = bilinear; builder.SetRenderFunc( - (BlitCameraTextureData data, RenderGraphContext ctx) => - { - HDUtils.BlitCameraTexture(ctx.cmd, data.source, data.destination, data.mipLevel, data.bilinear); - }); + (BlitCameraTextureData data, RenderGraphContext ctx) => + { + HDUtils.BlitCameraTexture(ctx.cmd, data.source, data.destination, data.mipLevel, data.bilinear); + }); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs index ba31930f9e3..25c248674c0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs @@ -66,8 +66,8 @@ void RenderSubsurfaceScattering(RenderGraph renderGraph, HDCamera hdCamera, Text if (passData.parameters.needTemporaryBuffer) { passData.cameraFilteringBuffer = builder.CreateTransientTexture( - new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, clearBuffer = true, clearColor = Color.clear, name = "SSSCameraFiltering" }); + new TextureDesc(Vector2.one, true, true) + { colorFormat = GraphicsFormat.B10G11R11_UFloatPack32, enableRandomWrite = true, clearBuffer = true, clearColor = Color.clear, name = "SSSCameraFiltering" }); } else { @@ -78,19 +78,19 @@ void RenderSubsurfaceScattering(RenderGraph renderGraph, HDCamera hdCamera, Text } builder.SetRenderFunc( - (SubsurfaceScaterringPassData data, RenderGraphContext context) => - { - var resources = new SubsurfaceScatteringResources(); - resources.colorBuffer = data.colorBuffer; - resources.diffuseBuffer = data.diffuseBuffer; - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.depthTexture = data.depthTexture; - resources.cameraFilteringBuffer = data.cameraFilteringBuffer; - resources.sssBuffer = data.sssBuffer; - resources.coarseStencilBuffer = data.coarseStencilBuffer; + (SubsurfaceScaterringPassData data, RenderGraphContext context) => + { + var resources = new SubsurfaceScatteringResources(); + resources.colorBuffer = data.colorBuffer; + resources.diffuseBuffer = data.diffuseBuffer; + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.depthTexture = data.depthTexture; + resources.cameraFilteringBuffer = data.cameraFilteringBuffer; + resources.sssBuffer = data.sssBuffer; + resources.coarseStencilBuffer = data.coarseStencilBuffer; - RenderSubsurfaceScattering(data.parameters, resources, context.cmd); - }); + RenderSubsurfaceScattering(data.parameters, resources, context.cmd); + }); } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs index 74fb1ee9d07..d2d00576faa 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs @@ -88,6 +88,7 @@ internal static Volume GetOrCreateDefaultVolume() return s_DefaultVolume; } + #endregion /// @@ -219,9 +220,9 @@ internal static Volume GetOrCreateDefaultVolume() ShaderTagId[] m_ForwardOnlyPassNames = { HDShaderPassNames.s_ForwardOnlyName, HDShaderPassNames.s_SRPDefaultUnlitName }; ShaderTagId[] m_AllTransparentPassNames = { HDShaderPassNames.s_TransparentBackfaceName, - HDShaderPassNames.s_ForwardOnlyName, - HDShaderPassNames.s_ForwardName, - HDShaderPassNames.s_SRPDefaultUnlitName }; + HDShaderPassNames.s_ForwardOnlyName, + HDShaderPassNames.s_ForwardName, + HDShaderPassNames.s_SRPDefaultUnlitName }; ShaderTagId[] m_TransparentNoBackfaceNames = { HDShaderPassNames.s_ForwardOnlyName, HDShaderPassNames.s_ForwardName, @@ -229,8 +230,8 @@ internal static Volume GetOrCreateDefaultVolume() ShaderTagId[] m_AllForwardOpaquePassNames = { HDShaderPassNames.s_ForwardOnlyName, - HDShaderPassNames.s_ForwardName, - HDShaderPassNames.s_SRPDefaultUnlitName }; + HDShaderPassNames.s_ForwardName, + HDShaderPassNames.s_SRPDefaultUnlitName }; ShaderTagId[] m_DepthOnlyAndDepthForwardOnlyPassNames = { HDShaderPassNames.s_DepthForwardOnlyName, HDShaderPassNames.s_DepthOnlyName }; ShaderTagId[] m_DepthForwardOnlyPassNames = { HDShaderPassNames.s_DepthForwardOnlyName }; @@ -637,7 +638,7 @@ void UpgradeResourcesInAssetIfNeeded(HDRenderPipelineAsset asset) HDUtils.GetHDRenderPipelinePath())) { InternalEditorUtility.SaveToSerializedFileAndForget( - new Object[]{asset.renderPipelineEditorResources }, + new Object[] {asset.renderPipelineEditorResources }, editorResourcesPath, true); } @@ -705,6 +706,7 @@ internal void SwitchRenderTargetsToFastMem(CommandBuffer cmd, HDCamera camera) // Trying to fit the depth pyramid m_SharedRTManager.GetDepthTexture().SwitchToFastMemory(cmd, residencyFraction: 1.0f, FastMemoryFlags.SpillTop, false); } + #endif /// /// Resets the reference size of the internal RTHandle System. @@ -901,7 +903,7 @@ void SetRenderingFeatures() overridesFog = true, overridesOtherLightingSettings = true, editableMaterialRenderQueue = false - // Enlighten is deprecated in 2019.3 and above + // Enlighten is deprecated in 2019.3 and above , enlighten = false , overridesLODBias = true , overridesMaximumLODLevel = true @@ -955,7 +957,7 @@ bool IsSupportedPlatformAndDevice(out GraphicsDeviceType unsupportedGraphicDevic { HDUtils.DisplayMessageNotification("Unable to compile Default Material based on Lit.shader. Either there is a compile error in Lit.shader or the current platform / API isn't compatible."); return false; - } + } #if UNITY_EDITOR UnityEditor.BuildTarget activeBuildTarget = UnityEditor.EditorUserBuildSettings.activeBuildTarget; @@ -1167,7 +1169,7 @@ protected override void Dispose(bool disposing) CleanupVolumetricLighting(); CleanupProbeVolumes(); - for(int bsdfIdx = 0; bsdfIdx < m_IBLFilterArray.Length; ++bsdfIdx) + for (int bsdfIdx = 0; bsdfIdx < m_IBLFilterArray.Length; ++bsdfIdx) { m_IBLFilterArray[bsdfIdx].Cleanup(); } @@ -1227,10 +1229,11 @@ void DisposeProbeCameraPool() else { #endif - m_ProbeCameraCache.Dispose(); - m_ProbeCameraCache = null; + m_ProbeCameraCache.Dispose(); + m_ProbeCameraCache = null; #if UNITY_EDITOR - } + } + #endif CleanupRenderGraph(); @@ -1250,7 +1253,6 @@ void DisposeProbeCameraPool() HDUtils.ReleaseComponentSingletons(); } - void Resize(HDCamera hdCamera) { // m_MaxCameraWidth and m_MaxCameraHeight start at 0 so we will at least go through this once at first frame to allocate the buffers for the first time. @@ -1356,7 +1358,6 @@ void UpdateShaderVariablesXRCB(HDCamera hdCamera, CommandBuffer cmd) ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesXRCB, HDShaderIDs._ShaderVariablesXR); } - void UpdateShaderVariablesRaytracingCB(HDCamera hdCamera, CommandBuffer cmd) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) @@ -1418,7 +1419,7 @@ BuildCoarseStencilAndResolveParameters PrepareBuildCoarseStencilParameters(HDCam // The following features require a copy of the stencil, if none are active, no need to do the resolve. bool resolveIsNecessary = GetFeatureVariantsEnabled(hdCamera.frameSettings); resolveIsNecessary = resolveIsNecessary || hdCamera.IsSSREnabled() - || hdCamera.IsSSREnabled(transparent: true); + || hdCamera.IsSSREnabled(transparent: true); // We need the resolve only with msaa parameters.resolveIsNecessary = resolveIsNecessary && MSAAEnabled; @@ -1426,7 +1427,7 @@ BuildCoarseStencilAndResolveParameters PrepareBuildCoarseStencilParameters(HDCam parameters.resolveKernel = parameters.resolveIsNecessary ? kernel + 3 : kernel; // We have a different variant if we need to resolve to non-MSAA stencil parameters.resolveOnly = resolveOnly; - if(parameters.resolveIsNecessary && resolveOnly) + if (parameters.resolveIsNecessary && resolveOnly) { parameters.resolveKernel = (kernel - 1) + 7; } @@ -1439,9 +1440,8 @@ void BuildCoarseStencilAndResolveIfNeeded(HDCamera hdCamera, CommandBuffer cmd, var parameters = PrepareBuildCoarseStencilParameters(hdCamera, resolveOnly); bool msaaEnabled = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); BuildCoarseStencilAndResolveIfNeeded(parameters, m_SharedRTManager.GetDepthStencilBuffer(msaaEnabled), - msaaEnabled ? m_SharedRTManager.GetStencilBuffer(msaaEnabled) : null, - m_SharedRTManager.GetCoarseStencilBuffer(), cmd); - + msaaEnabled ? m_SharedRTManager.GetStencilBuffer(msaaEnabled) : null, + m_SharedRTManager.GetCoarseStencilBuffer(), cmd); } static void BuildCoarseStencilAndResolveIfNeeded(BuildCoarseStencilAndResolveParameters parameters, RTHandle depthStencilBuffer, RTHandle resolvedStencilBuffer, ComputeBuffer coarseStencilBuffer, CommandBuffer cmd) @@ -1542,6 +1542,7 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c { Render(renderContext, new List(cameras)); } + #endif /// @@ -1599,7 +1600,7 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c } var dynResHandler = DynamicResolutionHandler.instance; - if(m_EnableRenderGraph) + if (m_EnableRenderGraph) { dynResHandler.Update(m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings); } @@ -1616,7 +1617,6 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c } - // This syntax is awful and hostile to debugging, please don't use it... using (ListPool.Get(out List renderRequests)) using (ListPool.Get(out List rootRenderRequestIndices)) @@ -1696,11 +1696,11 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c // Try to compute the parameters of the request or skip the request var skipRequest = !TryCalculateFrameParameters( - camera, - xrPass, - out var additionalCameraData, - out var hdCamera, - out var cullingParameters); + camera, + xrPass, + out var additionalCameraData, + out var hdCamera, + out var cullingParameters); // Note: In case of a custom render, we have false here and 'TryCull' is not executed if (!skipRequest) @@ -1768,7 +1768,7 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c index = renderRequests.Count, cameraSettings = CameraSettings.From(hdCamera), viewDependentProbesData = ListPool<(HDProbe.RenderData, HDProbe)>.Get() - // TODO: store DecalCullResult + // TODO: store DecalCullResult }; renderRequests.Add(request); // This is a root render request @@ -1862,7 +1862,7 @@ float ComputeVisibility(int visibleInIndex, HDProbe visibleProbe) AddHDProbeRenderRequests( visibleProbe, viewerTransform, - new List<(int index, float weight)>{visibility}, + new List<(int index, float weight)> {visibility}, HDUtils.GetSceneCullingMaskFromCamera(visibleInRenderRequest.hdCamera.camera), parentCamera, visibleInRenderRequest.hdCamera.camera.fieldOfView, @@ -1991,16 +1991,17 @@ ref List renderDatas _cullingResults.Reset(); if (!(TryCalculateFrameParameters( - camera, - m_XRSystem.emptyPass, - out _, - out var hdCamera, - out var cullingParameters - ) - && TryCull( - camera, hdCamera, renderContext, m_SkyManager, cullingParameters, m_Asset, - ref _cullingResults - ))) + camera, + m_XRSystem.emptyPass, + out _, + out var hdCamera, + out var cullingParameters + ) + && TryCull( + camera, hdCamera, renderContext, m_SkyManager, cullingParameters, m_Asset, + ref _cullingResults + ) + )) { // Skip request and free resources UnsafeGenericPool.Release(_cullingResults); @@ -2020,20 +2021,20 @@ ref _cullingResults HDAdditionalCameraData hdCam; camera.TryGetComponent(out hdCam); hdCam.flipYMode = visibleProbe.type == ProbeSettings.ProbeType.ReflectionProbe - ? HDAdditionalCameraData.FlipYMode.ForceFlipY - : HDAdditionalCameraData.FlipYMode.Automatic; + ? HDAdditionalCameraData.FlipYMode.ForceFlipY + : HDAdditionalCameraData.FlipYMode.Automatic; if (!visibleProbe.realtimeTexture.IsCreated()) visibleProbe.realtimeTexture.Create(); var renderData = new HDProbe.RenderData( - camera.worldToCameraMatrix, - camera.projectionMatrix, - camera.transform.position, - camera.transform.rotation, - cameraSettings[j].frustum.fieldOfView, - cameraSettings[j].frustum.aspect - ); + camera.worldToCameraMatrix, + camera.projectionMatrix, + camera.transform.position, + camera.transform.rotation, + cameraSettings[j].frustum.fieldOfView, + cameraSettings[j].frustum.aspect + ); renderDatas.Add(renderData); @@ -2058,7 +2059,7 @@ ref _cullingResults index = renderRequests.Count, cameraSettings = cameraSettings[j], viewDependentProbesData = ListPool<(HDProbe.RenderData, HDProbe)>.Get() - // TODO: store DecalCullResult + // TODO: store DecalCullResult }; if (m_SkyManager.HasSetValidAmbientProbe(hdCamera)) @@ -2147,7 +2148,7 @@ ref _cullingResults using (GenericPool>.Get(out Stack stack)) { stack.Clear(); - for (int i = rootRenderRequestIndices.Count -1; i >= 0; --i) + for (int i = rootRenderRequestIndices.Count - 1; i >= 0; --i) { stack.Push(rootRenderRequestIndices[i]); while (stack.Count > 0) @@ -2166,7 +2167,6 @@ ref _cullingResults using (new ProfilingScope(null, ProfilingSampler.Get(HDProfileId.HDRenderPipelineAllRenderRequest))) { - // Warm up the RTHandle system so that it gets init to the maximum resolution available (avoiding to call multiple resizes // that can lead to high memory spike as the memory release is delayed while the creation is immediate). { @@ -2296,7 +2296,6 @@ ref _cullingResults #else EndFrameRendering(renderContext, cameras); #endif - } void PropagateScreenSpaceShadowData() @@ -2330,7 +2329,7 @@ AOVRequestData aovRequest m_CurrentHDCamera = hdCamera; // Render graph deals with Fast memory support in an automatic way. - if(!m_EnableRenderGraph) + if (!m_EnableRenderGraph) { #if UNITY_2020_2_OR_NEWER SwitchRenderTargetsToFastMem(cmd, hdCamera); @@ -2355,690 +2354,689 @@ AOVRequestData aovRequest { aovRequest.AllocateTargetTexturesIfRequired(ref aovBuffers, ref aovCustomPassBuffers); - // If we render a reflection view or a preview we should not display any debug information - // This need to be call before ApplyDebugDisplaySettings() - if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview) - { - // Neutral allow to disable all debug settings - m_CurrentDebugDisplaySettings = s_NeutralDebugDisplaySettings; - } - else - { - // Make sure we are in sync with the debug menu for the msaa count - m_MSAASamples = (m_DebugDisplaySettings.data.msaaSamples != MSAASamples.None) ? - m_DebugDisplaySettings.data.msaaSamples : - m_Asset.currentPlatformRenderPipelineSettings.msaaSampleCount; + // If we render a reflection view or a preview we should not display any debug information + // This need to be call before ApplyDebugDisplaySettings() + if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview) + { + // Neutral allow to disable all debug settings + m_CurrentDebugDisplaySettings = s_NeutralDebugDisplaySettings; + } + else + { + // Make sure we are in sync with the debug menu for the msaa count + m_MSAASamples = (m_DebugDisplaySettings.data.msaaSamples != MSAASamples.None) ? + m_DebugDisplaySettings.data.msaaSamples : + m_Asset.currentPlatformRenderPipelineSettings.msaaSampleCount; - m_SharedRTManager.SetNumMSAASamples(m_MSAASamples); + m_SharedRTManager.SetNumMSAASamples(m_MSAASamples); - m_DebugDisplaySettings.UpdateCameraFreezeOptions(); + m_DebugDisplaySettings.UpdateCameraFreezeOptions(); - m_CurrentDebugDisplaySettings = m_DebugDisplaySettings; - } + m_CurrentDebugDisplaySettings = m_DebugDisplaySettings; + } - aovRequest.SetupDebugData(ref m_CurrentDebugDisplaySettings); + aovRequest.SetupDebugData(ref m_CurrentDebugDisplaySettings); - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) - { - // Must update after getting DebugDisplaySettings - m_RayCountManager.ClearRayCount(cmd, hdCamera, m_CurrentDebugDisplaySettings.data.countRays); - } + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) + { + // Must update after getting DebugDisplaySettings + m_RayCountManager.ClearRayCount(cmd, hdCamera, m_CurrentDebugDisplaySettings.data.countRays); + } - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) - { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferPrepareDrawData))) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) { - // TODO: update singleton with DecalCullResults - DecalSystem.instance.CurrentCamera = hdCamera.camera; // Singletons are extremely dangerous... - DecalSystem.instance.LoadCullResults(decalCullingResults); - DecalSystem.instance.UpdateCachedMaterialData(); // textures, alpha or fade distances could've changed - DecalSystem.instance.CreateDrawData(); // prepare data is separate from draw - DecalSystem.instance.UpdateTextureAtlas(cmd); // as this is only used for transparent pass, would've been nice not to have to do this if no transparent renderers are visible, needs to happen after CreateDrawData + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferPrepareDrawData))) + { + // TODO: update singleton with DecalCullResults + DecalSystem.instance.CurrentCamera = hdCamera.camera; // Singletons are extremely dangerous... + DecalSystem.instance.LoadCullResults(decalCullingResults); + DecalSystem.instance.UpdateCachedMaterialData(); // textures, alpha or fade distances could've changed + DecalSystem.instance.CreateDrawData(); // prepare data is separate from draw + DecalSystem.instance.UpdateTextureAtlas(cmd); // as this is only used for transparent pass, would've been nice not to have to do this if no transparent renderers are visible, needs to happen after CreateDrawData + } } - } - using (new ProfilingScope(null, ProfilingSampler.Get(HDProfileId.CustomPassVolumeUpdate))) - { - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) - CustomPassVolume.Update(hdCamera); - } + using (new ProfilingScope(null, ProfilingSampler.Get(HDProfileId.CustomPassVolumeUpdate))) + { + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) + CustomPassVolume.Update(hdCamera); + } - // Do anything we need to do upon a new frame. - // The NewFrame must be after the VolumeManager update and before Resize because it uses properties set in NewFrame - LightLoopNewFrame(cmd, hdCamera); + // Do anything we need to do upon a new frame. + // The NewFrame must be after the VolumeManager update and before Resize because it uses properties set in NewFrame + LightLoopNewFrame(cmd, hdCamera); - // Apparently scissor states can leak from editor code. As it is not used currently in HDRP (apart from VR). We disable scissor at the beginning of the frame. - cmd.DisableScissorRect(); + // Apparently scissor states can leak from editor code. As it is not used currently in HDRP (apart from VR). We disable scissor at the beginning of the frame. + cmd.DisableScissorRect(); - Resize(hdCamera); - m_PostProcessSystem.BeginFrame(cmd, hdCamera, this); + Resize(hdCamera); + m_PostProcessSystem.BeginFrame(cmd, hdCamera, this); - ApplyDebugDisplaySettings(hdCamera, cmd); + ApplyDebugDisplaySettings(hdCamera, cmd); - if (DebugManager.instance.displayRuntimeUI + if (DebugManager.instance.displayRuntimeUI #if UNITY_EDITOR || DebugManager.instance.displayEditorUI #endif ) - m_CurrentDebugDisplaySettings.UpdateAveragedProfilerTimings(); + m_CurrentDebugDisplaySettings.UpdateAveragedProfilerTimings(); - SetupCameraProperties(hdCamera, renderContext, cmd); - - // TODO: Find a correct place to bind these material textures - // We have to bind the material specific global parameters in this mode - foreach (var material in m_MaterialList) - material.Bind(cmd); + SetupCameraProperties(hdCamera, renderContext, cmd); - // Frustum cull density volumes on the CPU. Can be performed as soon as the camera is set up. - DensityVolumeList densityVolumes = PrepareVisibleDensityVolumeList(hdCamera, cmd, hdCamera.time); + // TODO: Find a correct place to bind these material textures + // We have to bind the material specific global parameters in this mode + foreach (var material in m_MaterialList) + material.Bind(cmd); - // Frustum cull probe volumes on the CPU. Can be performed as soon as the camera is set up. - ProbeVolumeList probeVolumes = PrepareVisibleProbeVolumeList(renderContext, hdCamera, cmd); - // Cache probe volume list as a member variable so it can be accessed inside of async compute tasks. - SetProbeVolumeList(probeVolumes); + // Frustum cull density volumes on the CPU. Can be performed as soon as the camera is set up. + DensityVolumeList densityVolumes = PrepareVisibleDensityVolumeList(hdCamera, cmd, hdCamera.time); - // Note: Legacy Unity behave like this for ShadowMask - // When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword. - // However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong. - // Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer). - // It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader. - // So the first thing to do is to go through all the light: PrepareLightsForGPU - bool enableBakeShadowMask = PrepareLightsForGPU(cmd, hdCamera, cullingResults, hdProbeCullingResults, densityVolumes, probeVolumes, m_CurrentDebugDisplaySettings, aovRequest); + // Frustum cull probe volumes on the CPU. Can be performed as soon as the camera is set up. + ProbeVolumeList probeVolumes = PrepareVisibleProbeVolumeList(renderContext, hdCamera, cmd); + // Cache probe volume list as a member variable so it can be accessed inside of async compute tasks. + SetProbeVolumeList(probeVolumes); - UpdateGlobalConstantBuffers(hdCamera, cmd); + // Note: Legacy Unity behave like this for ShadowMask + // When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword. + // However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong. + // Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer). + // It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader. + // So the first thing to do is to go through all the light: PrepareLightsForGPU + bool enableBakeShadowMask = PrepareLightsForGPU(cmd, hdCamera, cullingResults, hdProbeCullingResults, densityVolumes, probeVolumes, m_CurrentDebugDisplaySettings, aovRequest); - // Do the same for ray tracing if allowed - if (m_RayTracingSupported) - { - BuildRayTracingLightData(cmd, hdCamera, m_CurrentDebugDisplaySettings); - } + UpdateGlobalConstantBuffers(hdCamera, cmd); - // Configure all the keywords - ConfigureKeywords(enableBakeShadowMask, hdCamera, cmd); + // Do the same for ray tracing if allowed + if (m_RayTracingSupported) + { + BuildRayTracingLightData(cmd, hdCamera, m_CurrentDebugDisplaySettings); + } - // Caution: We require sun light here as some skies use the sun light to render, it means that UpdateSkyEnvironment must be called after PrepareLightsForGPU. - // TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute). - if (!m_CurrentDebugDisplaySettings.IsMatcapViewEnabled(hdCamera)) - UpdateSkyEnvironment(hdCamera, renderContext, m_FrameCount, cmd); - else - cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, CoreUtils.magentaCubeTextureArray); + // Configure all the keywords + ConfigureKeywords(enableBakeShadowMask, hdCamera, cmd); - VFXManager.ProcessCameraCommand(camera, cmd); + // Caution: We require sun light here as some skies use the sun light to render, it means that UpdateSkyEnvironment must be called after PrepareLightsForGPU. + // TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute). + if (!m_CurrentDebugDisplaySettings.IsMatcapViewEnabled(hdCamera)) + UpdateSkyEnvironment(hdCamera, renderContext, m_FrameCount, cmd); + else + cmd.SetGlobalTexture(HDShaderIDs._SkyTexture, CoreUtils.magentaCubeTextureArray); - if (GL.wireframe) - { - RenderWireFrame(cullingResults, hdCamera, target.id, renderContext, cmd); - return; - } + VFXManager.ProcessCameraCommand(camera, cmd); - if (m_EnableRenderGraph) - { - try + if (GL.wireframe) { - ExecuteWithRenderGraph(renderRequest, aovRequest, aovBuffers, renderContext, cmd); + RenderWireFrame(cullingResults, hdCamera, target.id, renderContext, cmd); + return; } - catch(Exception e) + + if (m_EnableRenderGraph) { - Debug.LogError("Error while building Render Graph."); - Debug.LogException(e); + try + { + ExecuteWithRenderGraph(renderRequest, aovRequest, aovBuffers, renderContext, cmd); + } + catch (Exception e) + { + Debug.LogError("Error while building Render Graph."); + Debug.LogException(e); + } + return; } - return; - } - hdCamera.xr.StartSinglePass(cmd); + hdCamera.xr.StartSinglePass(cmd); - ClearBuffers(hdCamera, cmd); + ClearBuffers(hdCamera, cmd); - // Render XR occlusion mesh to depth buffer early in the frame to improve performance - if (hdCamera.xr.enabled && m_Asset.currentPlatformRenderPipelineSettings.xrSettings.occlusionMesh) - { - bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); - Color clearColor = GetColorBufferClearColor(hdCamera); + // Render XR occlusion mesh to depth buffer early in the frame to improve performance + if (hdCamera.xr.enabled && m_Asset.currentPlatformRenderPipelineSettings.xrSettings.occlusionMesh) + { + bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); + Color clearColor = GetColorBufferClearColor(hdCamera); - hdCamera.xr.StopSinglePass(cmd); - hdCamera.xr.RenderOcclusionMeshes(cmd, clearColor, msaa ? m_CameraColorMSAABuffer : m_CameraColorBuffer, m_SharedRTManager.GetDepthStencilBuffer(msaa)); - hdCamera.xr.StartSinglePass(cmd); - } + hdCamera.xr.StopSinglePass(cmd); + hdCamera.xr.RenderOcclusionMeshes(cmd, clearColor, msaa ? m_CameraColorMSAABuffer : m_CameraColorBuffer, m_SharedRTManager.GetDepthStencilBuffer(msaa)); + hdCamera.xr.StartSinglePass(cmd); + } - // Bind the custom color/depth before the first custom pass - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) - { - if (m_CustomPassColorBuffer.IsValueCreated) - cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, m_CustomPassColorBuffer.Value); - if (m_CustomPassDepthBuffer.IsValueCreated) - cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, m_CustomPassDepthBuffer.Value); - } + // Bind the custom color/depth before the first custom pass + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.CustomPass)) + { + if (m_CustomPassColorBuffer.IsValueCreated) + cmd.SetGlobalTexture(HDShaderIDs._CustomColorTexture, m_CustomPassColorBuffer.Value); + if (m_CustomPassDepthBuffer.IsValueCreated) + cmd.SetGlobalTexture(HDShaderIDs._CustomDepthTexture, m_CustomPassDepthBuffer.Value); + } - RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeRendering, aovRequest, aovCustomPassBuffers); + RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeRendering, aovRequest, aovCustomPassBuffers); - RenderRayTracingPrepass(cullingResults, hdCamera, renderContext, cmd, false); + RenderRayTracingPrepass(cullingResults, hdCamera, renderContext, cmd, false); - // This is always false in forward and if it is true, is equivalent of saying we have a partial depth prepass. - bool shouldRenderMotionVectorAfterGBuffer = RenderDepthPrepass(cullingResults, hdCamera, renderContext, cmd); - if (!shouldRenderMotionVectorAfterGBuffer) - { - // If objects motion vectors if enabled, this will render the objects with motion vector into the target buffers (in addition to the depth) - // Note: An object with motion vector must not be render in the prepass otherwise we can have motion vector write that should have been rejected - RenderObjectsMotionVectors(cullingResults, hdCamera, renderContext, cmd); - } - // If we have MSAA, we need to complete the motion vector buffer before buffer resolves, hence we need to run camera mv first. - // This is always fine since shouldRenderMotionVectorAfterGBuffer is always false for forward. - bool needCameraMVBeforeResolve = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); - if (needCameraMVBeforeResolve) - { - RenderCameraMotionVectors(cullingResults, hdCamera, renderContext, cmd); - } + // This is always false in forward and if it is true, is equivalent of saying we have a partial depth prepass. + bool shouldRenderMotionVectorAfterGBuffer = RenderDepthPrepass(cullingResults, hdCamera, renderContext, cmd); + if (!shouldRenderMotionVectorAfterGBuffer) + { + // If objects motion vectors if enabled, this will render the objects with motion vector into the target buffers (in addition to the depth) + // Note: An object with motion vector must not be render in the prepass otherwise we can have motion vector write that should have been rejected + RenderObjectsMotionVectors(cullingResults, hdCamera, renderContext, cmd); + } + // If we have MSAA, we need to complete the motion vector buffer before buffer resolves, hence we need to run camera mv first. + // This is always fine since shouldRenderMotionVectorAfterGBuffer is always false for forward. + bool needCameraMVBeforeResolve = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); + if (needCameraMVBeforeResolve) + { + RenderCameraMotionVectors(cullingResults, hdCamera, renderContext, cmd); + } - PreRenderSky(hdCamera, cmd); + PreRenderSky(hdCamera, cmd); - // Now that all depths have been rendered, resolve the depth buffer - m_SharedRTManager.ResolveSharedRT(cmd, hdCamera); + // Now that all depths have been rendered, resolve the depth buffer + m_SharedRTManager.ResolveSharedRT(cmd, hdCamera); - RenderDBuffer(hdCamera, cmd, renderContext, cullingResults); + RenderDBuffer(hdCamera, cmd, renderContext, cullingResults); - RenderGBuffer(cullingResults, hdCamera, renderContext, cmd); + RenderGBuffer(cullingResults, hdCamera, renderContext, cmd); - DecalNormalPatch(hdCamera, cmd); + DecalNormalPatch(hdCamera, cmd); - // We can now bind the normal buffer to be use by any effect - m_SharedRTManager.BindNormalBuffer(cmd); + // We can now bind the normal buffer to be use by any effect + m_SharedRTManager.BindNormalBuffer(cmd); - // After Depth and Normals/roughness including decals - bool depthBufferModified = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterOpaqueDepthAndNormal, aovRequest, aovCustomPassBuffers); + // After Depth and Normals/roughness including decals + bool depthBufferModified = RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterOpaqueDepthAndNormal, aovRequest, aovCustomPassBuffers); - // If the depth was already copied in RenderDBuffer, we force the copy again because the custom pass modified the depth. - if (depthBufferModified) - m_IsDepthBufferCopyValid = false; + // If the depth was already copied in RenderDBuffer, we force the copy again because the custom pass modified the depth. + if (depthBufferModified) + m_IsDepthBufferCopyValid = false; - // Only on consoles is safe to read and write from/to the depth atlas - bool mip1FromDownsampleForLowResTrans = SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; - mip1FromDownsampleForLowResTrans = mip1FromDownsampleForLowResTrans && hdCamera.frameSettings.IsEnabled(FrameSettingsField.LowResTransparent); + // Only on consoles is safe to read and write from/to the depth atlas + bool mip1FromDownsampleForLowResTrans = SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 || + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; + mip1FromDownsampleForLowResTrans = mip1FromDownsampleForLowResTrans && hdCamera.frameSettings.IsEnabled(FrameSettingsField.LowResTransparent); - DownsampleDepthForLowResTransparency(hdCamera, cmd, m_SharedRTManager.GetDepthTexture(), mip1FromDownsampleForLowResTrans); + DownsampleDepthForLowResTransparency(hdCamera, cmd, m_SharedRTManager.GetDepthTexture(), mip1FromDownsampleForLowResTrans); - // In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing. - GenerateDepthPyramid(hdCamera, cmd, FullScreenDebugMode.DepthPyramid, mip1FromDownsampleForLowResTrans); + // In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing. + GenerateDepthPyramid(hdCamera, cmd, FullScreenDebugMode.DepthPyramid, mip1FromDownsampleForLowResTrans); - // Depth texture is now ready, bind it (Depth buffer could have been bind before if DBuffer is enable) - cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, m_SharedRTManager.GetDepthTexture()); + // Depth texture is now ready, bind it (Depth buffer could have been bind before if DBuffer is enable) + cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, m_SharedRTManager.GetDepthTexture()); - if (shouldRenderMotionVectorAfterGBuffer) - { - // See the call RenderObjectsMotionVectors() above and comment - RenderObjectsMotionVectors(cullingResults, hdCamera, renderContext, cmd); - } + if (shouldRenderMotionVectorAfterGBuffer) + { + // See the call RenderObjectsMotionVectors() above and comment + RenderObjectsMotionVectors(cullingResults, hdCamera, renderContext, cmd); + } - // In case we don't have MSAA, we always run camera motion vectors when is safe to assume Object MV are rendered - if(!needCameraMVBeforeResolve) - { - RenderCameraMotionVectors(cullingResults, hdCamera, renderContext, cmd); - } + // In case we don't have MSAA, we always run camera motion vectors when is safe to assume Object MV are rendered + if (!needCameraMVBeforeResolve) + { + RenderCameraMotionVectors(cullingResults, hdCamera, renderContext, cmd); + } - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors)) - cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); - else - cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, TextureXR.GetBlackTexture()); + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors)) + cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); + else + cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, TextureXR.GetBlackTexture()); #if UNITY_EDITOR - var showGizmos = camera.cameraType == CameraType.SceneView || (camera.targetTexture == null && camera.cameraType == CameraType.Game); + var showGizmos = camera.cameraType == CameraType.SceneView || (camera.targetTexture == null && camera.cameraType == CameraType.Game); #endif - RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); + RenderTransparencyOverdraw(cullingResults, hdCamera, renderContext, cmd); - if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() && m_CurrentDebugDisplaySettings.IsFullScreenDebugPassEnabled()) - { - RenderFullScreenDebug(cullingResults, hdCamera, renderContext, cmd); - } - else if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() || m_CurrentDebugDisplaySettings.IsMaterialValidationEnabled() || CoreUtils.IsSceneLightingDisabled(hdCamera.camera)) - { - RenderDebugViewMaterial(cullingResults, hdCamera, renderContext, cmd); - } - else if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && - hdCamera.volumeStack.GetComponent().enable.value && - hdCamera.camera.cameraType != CameraType.Preview) - { - // We only request the light cluster if we are gonna use it for debug mode - if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() && m_CurrentDebugDisplaySettings.IsFullScreenDebugPassEnabled()) { - HDRaytracingLightCluster lightCluster = RequestLightCluster(); - lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + RenderFullScreenDebug(cullingResults, hdCamera, renderContext, cmd); } - - RenderPathTracing(hdCamera, cmd, m_CameraColorBuffer); - } - else - { - // When debug is enabled we need to clear otherwise we may see non-shadows areas with stale values. - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ContactShadows) && m_CurrentDebugDisplaySettings.data.fullScreenDebugMode == FullScreenDebugMode.ContactShadows) + else if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() || m_CurrentDebugDisplaySettings.IsMaterialValidationEnabled() || CoreUtils.IsSceneLightingDisabled(hdCamera.camera)) { - CoreUtils.SetRenderTarget(cmd, m_ContactShadowBuffer, ClearFlag.Color, Color.clear); + RenderDebugViewMaterial(cullingResults, hdCamera, renderContext, cmd); } + else if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && + hdCamera.volumeStack.GetComponent().enable.value && + hdCamera.camera.cameraType != CameraType.Preview) + { + // We only request the light cluster if we are gonna use it for debug mode + if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + { + HDRaytracingLightCluster lightCluster = RequestLightCluster(); + lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + } - // NOTE: Currently we profiled that generating the HTile for SSR and using it is not worth it the optimization. - // However if the generated HTile will be used for something else but SSR, this should be made NOT resolve only and - // re-enabled in the shader. - if (hdCamera.IsSSREnabled()) - BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd, resolveOnly: true); + RenderPathTracing(hdCamera, cmd, m_CameraColorBuffer); + } + else + { + // When debug is enabled we need to clear otherwise we may see non-shadows areas with stale values. + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ContactShadows) && m_CurrentDebugDisplaySettings.data.fullScreenDebugMode == FullScreenDebugMode.ContactShadows) + { + CoreUtils.SetRenderTarget(cmd, m_ContactShadowBuffer, ClearFlag.Color, Color.clear); + } - hdCamera.xr.StopSinglePass(cmd); + // NOTE: Currently we profiled that generating the HTile for SSR and using it is not worth it the optimization. + // However if the generated HTile will be used for something else but SSR, this should be made NOT resolve only and + // re-enabled in the shader. + if (hdCamera.IsSSREnabled()) + BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd, resolveOnly: true); - var buildLightListTask = new HDGPUAsyncTask("Build light list", ComputeQueueType.Background); - // It is important that this task is in the same queue as the build light list due to dependency it has on it. If really need to move it, put an extra fence to make sure buildLightListTask has finished. - var volumeVoxelizationTask = new HDGPUAsyncTask("Volumetric voxelization", ComputeQueueType.Background); - var SSRTask = new HDGPUAsyncTask("Screen Space Reflection", ComputeQueueType.Background); - var SSAOTask = new HDGPUAsyncTask("SSAO", ComputeQueueType.Background); + hdCamera.xr.StopSinglePass(cmd); - // Avoid garbage by explicitely passing parameters to the lambdas - var asyncParams = new HDGPUAsyncTaskParams - { - renderContext = renderContext, - hdCamera = hdCamera, - frameCount = m_FrameCount, - }; + var buildLightListTask = new HDGPUAsyncTask("Build light list", ComputeQueueType.Background); + // It is important that this task is in the same queue as the build light list due to dependency it has on it. If really need to move it, put an extra fence to make sure buildLightListTask has finished. + var volumeVoxelizationTask = new HDGPUAsyncTask("Volumetric voxelization", ComputeQueueType.Background); + var SSRTask = new HDGPUAsyncTask("Screen Space Reflection", ComputeQueueType.Background); + var SSAOTask = new HDGPUAsyncTask("SSAO", ComputeQueueType.Background); - var haveAsyncTaskWithShadows = false; - if (hdCamera.frameSettings.BuildLightListRunsAsync()) - { - buildLightListTask.Start(cmd, asyncParams, Callback, !haveAsyncTaskWithShadows); + // Avoid garbage by explicitely passing parameters to the lambdas + var asyncParams = new HDGPUAsyncTaskParams + { + renderContext = renderContext, + hdCamera = hdCamera, + frameCount = m_FrameCount, + }; - haveAsyncTaskWithShadows = true; + var haveAsyncTaskWithShadows = false; + if (hdCamera.frameSettings.BuildLightListRunsAsync()) + { + buildLightListTask.Start(cmd, asyncParams, Callback, !haveAsyncTaskWithShadows); - void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) - => BuildGPULightListsCommon(a.hdCamera, c); - } + haveAsyncTaskWithShadows = true; - if (hdCamera.frameSettings.VolumeVoxelizationRunsAsync()) - { - volumeVoxelizationTask.Start(cmd, asyncParams, Callback, !haveAsyncTaskWithShadows); + void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) + => BuildGPULightListsCommon(a.hdCamera, c); + } - haveAsyncTaskWithShadows = true; + if (hdCamera.frameSettings.VolumeVoxelizationRunsAsync()) + { + volumeVoxelizationTask.Start(cmd, asyncParams, Callback, !haveAsyncTaskWithShadows); - void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) - => VolumeVoxelizationPass(a.hdCamera, c, m_FrameCount); - } + haveAsyncTaskWithShadows = true; - if (hdCamera.frameSettings.SSRRunsAsync()) - { - SSRTask.Start(cmd, asyncParams, Callback, !haveAsyncTaskWithShadows); + void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) + => VolumeVoxelizationPass(a.hdCamera, c, m_FrameCount); + } - haveAsyncTaskWithShadows = true; + if (hdCamera.frameSettings.SSRRunsAsync()) + { + SSRTask.Start(cmd, asyncParams, Callback, !haveAsyncTaskWithShadows); - void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) - => RenderSSR(a.hdCamera, c, a.renderContext); - } + haveAsyncTaskWithShadows = true; - if (hdCamera.frameSettings.SSAORunsAsync()) - { - var depthTexture = m_SharedRTManager.GetDepthTexture(); - var normalBuffer = m_SharedRTManager.GetNormalBuffer(); - var motionVectors = m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors ? m_SharedRTManager.GetMotionVectorsBuffer() : TextureXR.GetBlackTexture(); + void Callback(CommandBuffer c, HDGPUAsyncTaskParams a) + => RenderSSR(a.hdCamera, c, a.renderContext); + } - SSAOTask.Start(cmd, asyncParams, AsyncSSAODispatch, !haveAsyncTaskWithShadows); - haveAsyncTaskWithShadows = true; + if (hdCamera.frameSettings.SSAORunsAsync()) + { + var depthTexture = m_SharedRTManager.GetDepthTexture(); + var normalBuffer = m_SharedRTManager.GetNormalBuffer(); + var motionVectors = m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors ? m_SharedRTManager.GetMotionVectorsBuffer() : TextureXR.GetBlackTexture(); - void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) - => m_AmbientOcclusionSystem.Dispatch(c, a.hdCamera, depthTexture, normalBuffer, motionVectors, a.frameCount); - } + SSAOTask.Start(cmd, asyncParams, AsyncSSAODispatch, !haveAsyncTaskWithShadows); + haveAsyncTaskWithShadows = true; - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderShadowMaps))) - { - // This call overwrites camera properties passed to the shader system. - RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); + void AsyncSSAODispatch(CommandBuffer c, HDGPUAsyncTaskParams a) + => m_AmbientOcclusionSystem.Dispatch(c, a.hdCamera, depthTexture, normalBuffer, motionVectors, a.frameCount); + } - hdCamera.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); - ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); - } + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderShadowMaps))) + { + // This call overwrites camera properties passed to the shader system. + RenderShadowMaps(renderContext, cmd, m_ShaderVariablesGlobalCB, cullingResults, hdCamera); - hdCamera.xr.StartSinglePass(cmd); + hdCamera.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB, m_FrameCount); + ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); + } - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) - { - // We only request the light cluster if we are gonna use it for debug mode - if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + hdCamera.xr.StartSinglePass(cmd); + + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { - HDRaytracingLightCluster lightCluster = RequestLightCluster(); - lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + // We only request the light cluster if we are gonna use it for debug mode + if (FullScreenDebugMode.LightCluster == m_CurrentDebugDisplaySettings.data.fullScreenDebugMode && GetRayTracingClusterState()) + { + HDRaytracingLightCluster lightCluster = RequestLightCluster(); + lightCluster.EvaluateClusterDebugView(cmd, hdCamera); + } } - } - switch (GetIndirectDiffuseMode(hdCamera)) - { - case IndirectDiffuseMode.Off: - BindBlackIndirectDiffuseTexture(cmd); - break; + switch (GetIndirectDiffuseMode(hdCamera)) + { + case IndirectDiffuseMode.Off: + BindBlackIndirectDiffuseTexture(cmd); + break; - case IndirectDiffuseMode.ScreenSpace: - RenderSSGI(hdCamera, cmd, renderContext, m_FrameCount); - BindIndirectDiffuseTexture(cmd); - break; + case IndirectDiffuseMode.ScreenSpace: + RenderSSGI(hdCamera, cmd, renderContext, m_FrameCount); + BindIndirectDiffuseTexture(cmd); + break; - case IndirectDiffuseMode.Raytrace: - RenderRayTracedIndirectDiffuse(hdCamera, cmd, renderContext, m_FrameCount); - break; - } + case IndirectDiffuseMode.Raytrace: + RenderRayTracedIndirectDiffuse(hdCamera, cmd, renderContext, m_FrameCount); + break; + } - if (!hdCamera.frameSettings.SSRRunsAsync()) - { - // Needs the depth pyramid and motion vectors, as well as the render of the previous frame. - RenderSSR(hdCamera, cmd, renderContext); - } + if (!hdCamera.frameSettings.SSRRunsAsync()) + { + // Needs the depth pyramid and motion vectors, as well as the render of the previous frame. + RenderSSR(hdCamera, cmd, renderContext); + } - // Contact shadows needs the light loop so we do them after the build light list - if (hdCamera.frameSettings.BuildLightListRunsAsync()) - { - buildLightListTask.EndWithPostWork(cmd, hdCamera, Callback); + // Contact shadows needs the light loop so we do them after the build light list + if (hdCamera.frameSettings.BuildLightListRunsAsync()) + { + buildLightListTask.EndWithPostWork(cmd, hdCamera, Callback); - void Callback(CommandBuffer c, HDCamera cam) + void Callback(CommandBuffer c, HDCamera cam) + { + var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); + var globalParams = hdrp.PrepareLightLoopGlobalParameters(cam, m_TileAndClusterData); + PushLightLoopGlobalParams(globalParams, c); + } + } + else { - var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); - var globalParams = hdrp.PrepareLightLoopGlobalParameters(cam, m_TileAndClusterData); - PushLightLoopGlobalParams(globalParams, c); + BuildGPULightLists(hdCamera, cmd); } - } - else - { - BuildGPULightLists(hdCamera, cmd); - } - if (!hdCamera.frameSettings.SSAORunsAsync()) - { - var motionVectors = m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors ? m_SharedRTManager.GetMotionVectorsBuffer() : TextureXR.GetBlackTexture(); - m_AmbientOcclusionSystem.Render(cmd, hdCamera, renderContext, m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetNormalBuffer(), motionVectors, m_ShaderVariablesRayTracingCB, m_FrameCount); - } + if (!hdCamera.frameSettings.SSAORunsAsync()) + { + var motionVectors = m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors ? m_SharedRTManager.GetMotionVectorsBuffer() : TextureXR.GetBlackTexture(); + m_AmbientOcclusionSystem.Render(cmd, hdCamera, renderContext, m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetNormalBuffer(), motionVectors, m_ShaderVariablesRayTracingCB, m_FrameCount); + } - // Run the contact shadows here as they need the light list - HDUtils.CheckRTCreated(m_ContactShadowBuffer); - RenderContactShadows(hdCamera, cmd); - PushFullScreenDebugTexture(hdCamera, cmd, m_ContactShadowBuffer, FullScreenDebugMode.ContactShadows); + // Run the contact shadows here as they need the light list + HDUtils.CheckRTCreated(m_ContactShadowBuffer); + RenderContactShadows(hdCamera, cmd); + PushFullScreenDebugTexture(hdCamera, cmd, m_ContactShadowBuffer, FullScreenDebugMode.ContactShadows); - RenderScreenSpaceShadows(hdCamera, cmd); + RenderScreenSpaceShadows(hdCamera, cmd); - if (hdCamera.frameSettings.VolumeVoxelizationRunsAsync()) - { - volumeVoxelizationTask.End(cmd, hdCamera); - } - else - { - // Perform the voxelization step which fills the density 3D texture. - VolumeVoxelizationPass(hdCamera, cmd, m_FrameCount); - } + if (hdCamera.frameSettings.VolumeVoxelizationRunsAsync()) + { + volumeVoxelizationTask.End(cmd, hdCamera); + } + else + { + // Perform the voxelization step which fills the density 3D texture. + VolumeVoxelizationPass(hdCamera, cmd, m_FrameCount); + } - GenerateMaxZ(cmd, hdCamera, m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetDepthBufferMipChainInfo(), m_FrameCount); + GenerateMaxZ(cmd, hdCamera, m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetDepthBufferMipChainInfo(), m_FrameCount); - // Render the volumetric lighting. - // The pass requires the volume properties, the light list and the shadows, and can run async. - VolumetricLightingPass(hdCamera, cmd, m_FrameCount); + // Render the volumetric lighting. + // The pass requires the volume properties, the light list and the shadows, and can run async. + VolumetricLightingPass(hdCamera, cmd, m_FrameCount); - if (hdCamera.frameSettings.SSAORunsAsync()) - { - SSAOTask.EndWithPostWork(cmd, hdCamera, Callback); - void Callback(CommandBuffer c, HDCamera cam) + if (hdCamera.frameSettings.SSAORunsAsync()) { - var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); - hdrp.m_AmbientOcclusionSystem.PostDispatchWork(c, cam); + SSAOTask.EndWithPostWork(cmd, hdCamera, Callback); + void Callback(CommandBuffer c, HDCamera cam) + { + var hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); + hdrp.m_AmbientOcclusionSystem.PostDispatchWork(c, cam); + } } - } - SetContactShadowsTexture(hdCamera, m_ContactShadowBuffer, cmd); + SetContactShadowsTexture(hdCamera, m_ContactShadowBuffer, cmd); - if (hdCamera.frameSettings.SSRRunsAsync()) - { - SSRTask.End(cmd, hdCamera); - } + if (hdCamera.frameSettings.SSRRunsAsync()) + { + SSRTask.End(cmd, hdCamera); + } - RenderDeferredLighting(hdCamera, cmd); + RenderDeferredLighting(hdCamera, cmd); - RenderForwardOpaque(cullingResults, hdCamera, renderContext, cmd); + RenderForwardOpaque(cullingResults, hdCamera, renderContext, cmd); - // Normal buffer could be reuse after that - if (aovRequest.isValid) - aovRequest.PushCameraTexture(cmd, AOVBuffers.Normals, hdCamera, m_SharedRTManager.GetNormalBuffer(), aovBuffers); + // Normal buffer could be reuse after that + if (aovRequest.isValid) + aovRequest.PushCameraTexture(cmd, AOVBuffers.Normals, hdCamera, m_SharedRTManager.GetNormalBuffer(), aovBuffers); - m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraSssDiffuseLightingMSAABuffer, m_CameraSssDiffuseLightingBuffer); - m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, GetSSSBufferMSAA(), GetSSSBuffer()); + m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraSssDiffuseLightingMSAABuffer, m_CameraSssDiffuseLightingBuffer); + m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, GetSSSBufferMSAA(), GetSSSBuffer()); - // SSS pass here handle both SSS material from deferred and forward - RenderSubsurfaceScattering(hdCamera, cmd, hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? m_CameraColorMSAABuffer : m_CameraColorBuffer, - m_CameraSssDiffuseLightingBuffer, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetNormalBuffer()); + // SSS pass here handle both SSS material from deferred and forward + RenderSubsurfaceScattering(hdCamera, cmd, hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA) ? m_CameraColorMSAABuffer : m_CameraColorBuffer, + m_CameraSssDiffuseLightingBuffer, m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetNormalBuffer()); - RenderForwardEmissive(cullingResults, hdCamera, renderContext, cmd); + RenderForwardEmissive(cullingResults, hdCamera, renderContext, cmd); - RenderSky(hdCamera, cmd); + RenderSky(hdCamera, cmd); - // Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) - SendGeometryGraphicsBuffers(PrepareSendGeometryBuffersParameters(hdCamera, m_SharedRTManager.GetDepthBufferMipChainInfo()), m_SharedRTManager.GetNormalBuffer(), m_SharedRTManager.GetDepthTexture(), cmd); + // Send all the geometry graphics buffer to client systems if required (must be done after the pyramid and before the transparent depth pre-pass) + SendGeometryGraphicsBuffers(PrepareSendGeometryBuffersParameters(hdCamera, m_SharedRTManager.GetDepthBufferMipChainInfo()), m_SharedRTManager.GetNormalBuffer(), m_SharedRTManager.GetDepthTexture(), cmd); - m_PostProcessSystem.DoUserAfterOpaqueAndSky(cmd, hdCamera, m_CameraColorBuffer); + m_PostProcessSystem.DoUserAfterOpaqueAndSky(cmd, hdCamera, m_CameraColorBuffer); - // No need for old stencil values here since from transparent on different features are tagged - ClearStencilBuffer(cmd); + // No need for old stencil values here since from transparent on different features are tagged + ClearStencilBuffer(cmd); - RenderTransparentDepthPrepass(cullingResults, hdCamera, renderContext, cmd); + RenderTransparentDepthPrepass(cullingResults, hdCamera, renderContext, cmd); - RenderSSRTransparent(hdCamera, cmd, renderContext); + RenderSSRTransparent(hdCamera, cmd, renderContext); - RenderRayTracingPrepass(cullingResults, hdCamera, renderContext, cmd, true); - RaytracingRecursiveRender(hdCamera, cmd); + RenderRayTracingPrepass(cullingResults, hdCamera, renderContext, cmd, true); + RaytracingRecursiveRender(hdCamera, cmd); - // To allow users to fetch the current color buffer, we temporarily bind the camera color buffer - cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, m_CameraColorBuffer); - RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePreRefraction, aovRequest, aovCustomPassBuffers); + // To allow users to fetch the current color buffer, we temporarily bind the camera color buffer + cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, m_CameraColorBuffer); + RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePreRefraction, aovRequest, aovCustomPassBuffers); - // Render pre refraction objects - RenderForwardTransparent(cullingResults, hdCamera, true, renderContext, cmd); + // Render pre refraction objects + RenderForwardTransparent(cullingResults, hdCamera, true, renderContext, cmd); - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) || hdCamera.IsSSREnabled()) - { - // First resolution of the color buffer for the color pyramid - m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraColorMSAABuffer, m_CameraColorBuffer); + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Refraction) || hdCamera.IsSSREnabled()) + { + // First resolution of the color buffer for the color pyramid + m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraColorMSAABuffer, m_CameraColorBuffer); - RTHandle colorPyramid = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain); - RenderColorPyramid(hdCamera, cmd, colorPyramid, FullScreenDebugMode.PreRefractionColorPyramid); + RTHandle colorPyramid = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain); + RenderColorPyramid(hdCamera, cmd, colorPyramid, FullScreenDebugMode.PreRefractionColorPyramid); - // Bind current color pyramid for shader graph SceneColorNode on transparent objects - cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain)); - } - else - { - cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, TextureXR.GetBlackTexture()); - } - - // We don't have access to the color pyramid with transparent if rough refraction is disabled - RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeTransparent, aovRequest, aovCustomPassBuffers); + // Bind current color pyramid for shader graph SceneColorNode on transparent objects + cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain)); + } + else + { + cmd.SetGlobalTexture(HDShaderIDs._ColorPyramidTexture, TextureXR.GetBlackTexture()); + } - // Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects. - RenderForwardTransparent(cullingResults, hdCamera, false, renderContext, cmd); + // We don't have access to the color pyramid with transparent if rough refraction is disabled + RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforeTransparent, aovRequest, aovCustomPassBuffers); - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentsWriteMotionVector)) - { - m_SharedRTManager.ResolveMotionVectorTexture(cmd, hdCamera); - cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); - } + // Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects. + RenderForwardTransparent(cullingResults, hdCamera, false, renderContext, cmd); - // We push the motion vector debug texture here as transparent object can overwrite the motion vector texture content. - if (m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors) - PushFullScreenDebugTexture(hdCamera, cmd, m_SharedRTManager.GetMotionVectorsBuffer(), FullScreenDebugMode.MotionVectors); + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.TransparentsWriteMotionVector)) + { + m_SharedRTManager.ResolveMotionVectorTexture(cmd, hdCamera); + cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_SharedRTManager.GetMotionVectorsBuffer()); + } - // Second resolve the color buffer for finishing the frame - m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraColorMSAABuffer, m_CameraColorBuffer); + // We push the motion vector debug texture here as transparent object can overwrite the motion vector texture content. + if (m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors) + PushFullScreenDebugTexture(hdCamera, cmd, m_SharedRTManager.GetMotionVectorsBuffer(), FullScreenDebugMode.MotionVectors); - // Render All forward error - RenderForwardError(cullingResults, hdCamera, renderContext, cmd); + // Second resolve the color buffer for finishing the frame + m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraColorMSAABuffer, m_CameraColorBuffer); - RenderLowResTransparent(cullingResults, hdCamera, renderContext, cmd); + // Render All forward error + RenderForwardError(cullingResults, hdCamera, renderContext, cmd); - UpsampleTransparent(hdCamera, cmd); + RenderLowResTransparent(cullingResults, hdCamera, renderContext, cmd); - // Fill depth buffer to reduce artifact for transparent object during postprocess - RenderTransparentDepthPostpass(cullingResults, hdCamera, renderContext, cmd); + UpsampleTransparent(hdCamera, cmd); - AccumulateDistortion(cullingResults, hdCamera, renderContext, cmd); - RenderDistortion(hdCamera, cmd); + // Fill depth buffer to reduce artifact for transparent object during postprocess + RenderTransparentDepthPostpass(cullingResults, hdCamera, renderContext, cmd); - PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.NanTracker); - PushFullScreenLightingDebugTexture(hdCamera, cmd, m_CameraColorBuffer); + AccumulateDistortion(cullingResults, hdCamera, renderContext, cmd); + RenderDistortion(hdCamera, cmd); - if (m_SubFrameManager.isRecording && m_SubFrameManager.subFrameCount > 1) - { - RenderAccumulation(hdCamera, m_CameraColorBuffer, m_CameraColorBuffer, false, cmd); - } + PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.NanTracker); + PushFullScreenLightingDebugTexture(hdCamera, cmd, m_CameraColorBuffer); -#if UNITY_EDITOR - // Render gizmos that should be affected by post processes - if (showGizmos) - { - if(m_CurrentDebugDisplaySettings.GetDebugLightingMode() == DebugLightingMode.MatcapView) + if (m_SubFrameManager.isRecording && m_SubFrameManager.subFrameCount > 1) { - Gizmos.exposure = Texture2D.blackTexture; + RenderAccumulation(hdCamera, m_CameraColorBuffer, m_CameraColorBuffer, false, cmd); } - else + +#if UNITY_EDITOR + // Render gizmos that should be affected by post processes + if (showGizmos) { - Gizmos.exposure = m_PostProcessSystem.GetExposureTexture(hdCamera).rt; - } + if (m_CurrentDebugDisplaySettings.GetDebugLightingMode() == DebugLightingMode.MatcapView) + { + Gizmos.exposure = Texture2D.blackTexture; + } + else + { + Gizmos.exposure = m_PostProcessSystem.GetExposureTexture(hdCamera).rt; + } - RenderGizmos(cmd, camera, renderContext, GizmoSubset.PreImageEffects); - } + RenderGizmos(cmd, camera, renderContext, GizmoSubset.PreImageEffects); + } #endif - } + } #if ENABLE_VIRTUALTEXTURES - if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.VirtualTexturing)) - { - m_VtBufferManager.Resolve(cmd, m_GbufferManager.GetVTFeedbackBuffer(), hdCamera); - VirtualTexturing.System.Update(); - - if (m_VTDebugBlit != null) + if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.VirtualTexturing)) { - PushFullScreenVTFeedbackDebugTexture(cmd, GetVTFeedbackBufferForForward(hdCamera), hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)); + m_VtBufferManager.Resolve(cmd, m_GbufferManager.GetVTFeedbackBuffer(), hdCamera); + VirtualTexturing.System.Update(); + + if (m_VTDebugBlit != null) + { + PushFullScreenVTFeedbackDebugTexture(cmd, GetVTFeedbackBufferForForward(hdCamera), hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)); + } } - } #endif - // At this point, m_CameraColorBuffer has been filled by either debug views are regular rendering so we can push it here. - PushColorPickerDebugTexture(cmd, hdCamera, m_CameraColorBuffer); + // At this point, m_CameraColorBuffer has been filled by either debug views are regular rendering so we can push it here. + PushColorPickerDebugTexture(cmd, hdCamera, m_CameraColorBuffer); - RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePostProcess, aovRequest, aovCustomPassBuffers); + RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.BeforePostProcess, aovRequest, aovCustomPassBuffers); - if (aovRequest.isValid) - aovRequest.PushCameraTexture(cmd, AOVBuffers.Color, hdCamera, m_CameraColorBuffer, aovBuffers); + if (aovRequest.isValid) + aovRequest.PushCameraTexture(cmd, AOVBuffers.Color, hdCamera, m_CameraColorBuffer, aovBuffers); - RenderTargetIdentifier postProcessDest = HDUtils.PostProcessIsFinalPass(hdCamera) ? target.id : m_IntermediateAfterPostProcessBuffer; - RenderPostProcess(cullingResults, hdCamera, postProcessDest, renderContext, cmd); + RenderTargetIdentifier postProcessDest = HDUtils.PostProcessIsFinalPass(hdCamera) ? target.id : m_IntermediateAfterPostProcessBuffer; + RenderPostProcess(cullingResults, hdCamera, postProcessDest, renderContext, cmd); - // If requested, compute histogram of the very final image - if (m_CurrentDebugDisplaySettings.data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.FinalImageHistogramView) - { - var debugImageHistogramParam = m_PostProcessSystem.PrepareDebugImageHistogramParameters(hdCamera); - PostProcessSystem.GenerateDebugImageHistogram(debugImageHistogramParam, cmd, m_IntermediateAfterPostProcessBuffer); - } + // If requested, compute histogram of the very final image + if (m_CurrentDebugDisplaySettings.data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.FinalImageHistogramView) + { + var debugImageHistogramParam = m_PostProcessSystem.PrepareDebugImageHistogramParameters(hdCamera); + PostProcessSystem.GenerateDebugImageHistogram(debugImageHistogramParam, cmd, m_IntermediateAfterPostProcessBuffer); + } - PushFullScreenExposureDebugTexture(cmd, m_IntermediateAfterPostProcessBuffer); + PushFullScreenExposureDebugTexture(cmd, m_IntermediateAfterPostProcessBuffer); - RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess, aovRequest, aovCustomPassBuffers); + RenderCustomPass(renderContext, cmd, hdCamera, customPassCullingResults, CustomPassInjectionPoint.AfterPostProcess, aovRequest, aovCustomPassBuffers); - // Copy and rescale depth buffer for XR devices - if (hdCamera.xr.enabled && hdCamera.xr.copyDepth) - { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.XRDepthCopy))) + // Copy and rescale depth buffer for XR devices + if (hdCamera.xr.enabled && hdCamera.xr.copyDepth) { - var depthBuffer = m_SharedRTManager.GetDepthStencilBuffer(); - var rtScale = depthBuffer.rtHandleProperties.rtHandleScale / DynamicResolutionHandler.instance.GetCurrentScale(); + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.XRDepthCopy))) + { + var depthBuffer = m_SharedRTManager.GetDepthStencilBuffer(); + var rtScale = depthBuffer.rtHandleProperties.rtHandleScale / DynamicResolutionHandler.instance.GetCurrentScale(); - m_CopyDepthPropertyBlock.SetTexture(HDShaderIDs._InputDepth, depthBuffer); - m_CopyDepthPropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, rtScale); - m_CopyDepthPropertyBlock.SetInt("_FlipY", 1); + m_CopyDepthPropertyBlock.SetTexture(HDShaderIDs._InputDepth, depthBuffer); + m_CopyDepthPropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, rtScale); + m_CopyDepthPropertyBlock.SetInt("_FlipY", 1); - cmd.SetRenderTarget(target.id, 0, CubemapFace.Unknown, -1); - cmd.SetViewport(hdCamera.finalViewport); - CoreUtils.DrawFullScreen(cmd, m_CopyDepth, m_CopyDepthPropertyBlock); + cmd.SetRenderTarget(target.id, 0, CubemapFace.Unknown, -1); + cmd.SetViewport(hdCamera.finalViewport); + CoreUtils.DrawFullScreen(cmd, m_CopyDepth, m_CopyDepthPropertyBlock); + } } - } - // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. - // Because of this, we need another blit here to the final render target at the right viewport. - if (!HDUtils.PostProcessIsFinalPass(hdCamera) || aovRequest.isValid) - { - hdCamera.ExecuteCaptureActions(m_IntermediateAfterPostProcessBuffer, cmd); + // In developer build, we always render post process in m_AfterPostProcessBuffer at (0,0) in which we will then render debug. + // Because of this, we need another blit here to the final render target at the right viewport. + if (!HDUtils.PostProcessIsFinalPass(hdCamera) || aovRequest.isValid) + { + hdCamera.ExecuteCaptureActions(m_IntermediateAfterPostProcessBuffer, cmd); - RenderDebug(hdCamera, cmd, cullingResults); + RenderDebug(hdCamera, cmd, cullingResults); - hdCamera.xr.StopSinglePass(cmd); + hdCamera.xr.StopSinglePass(cmd); - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BlitToFinalRTDevBuildOnly))) - { - for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.BlitToFinalRTDevBuildOnly))) { - var finalBlitParams = PrepareFinalBlitParameters(hdCamera, viewIndex); - BlitFinalCameraTexture(finalBlitParams, m_BlitPropertyBlock, m_IntermediateAfterPostProcessBuffer, target.id, cmd); + for (int viewIndex = 0; viewIndex < hdCamera.viewCount; ++viewIndex) + { + var finalBlitParams = PrepareFinalBlitParameters(hdCamera, viewIndex); + BlitFinalCameraTexture(finalBlitParams, m_BlitPropertyBlock, m_IntermediateAfterPostProcessBuffer, target.id, cmd); - // If a depth target is specified, fill it - if (target.targetDepth != null) - BlitFinalCameraTexture(finalBlitParams, m_BlitPropertyBlock, m_SharedRTManager.GetDepthTexture(), target.targetDepth, cmd); + // If a depth target is specified, fill it + if (target.targetDepth != null) + BlitFinalCameraTexture(finalBlitParams, m_BlitPropertyBlock, m_SharedRTManager.GetDepthTexture(), target.targetDepth, cmd); + } } - } - if (aovRequest.isValid) - aovRequest.PushCameraTexture(cmd, AOVBuffers.Output, hdCamera, m_IntermediateAfterPostProcessBuffer, aovBuffers); - } + if (aovRequest.isValid) + aovRequest.PushCameraTexture(cmd, AOVBuffers.Output, hdCamera, m_IntermediateAfterPostProcessBuffer, aovBuffers); + } - // XR mirror view and blit do device - hdCamera.xr.EndCamera(cmd, hdCamera); + // XR mirror view and blit do device + hdCamera.xr.EndCamera(cmd, hdCamera); - // Send all the color graphics buffer to client systems if required. - SendColorGraphicsBuffer(cmd, hdCamera); + // Send all the color graphics buffer to client systems if required. + SendColorGraphicsBuffer(cmd, hdCamera); - // Due to our RT handle system we don't write into the backbuffer depth buffer (as our depth buffer can be bigger than the one provided) - // So we need to do a copy of the corresponding part of RT depth buffer in the target depth buffer in various situation: - // - RenderTexture (camera.targetTexture != null) has a depth buffer (camera.targetTexture.depth != 0) - // - We are rendering into the main game view (i.e not a RenderTexture camera.cameraType == CameraType.Game && hdCamera.camera.targetTexture == null) in the editor for allowing usage of Debug.DrawLine and Debug.Ray. - // - We draw Gizmo/Icons in the editor (hdCamera.camera.targetTexture != null && camera.targetTexture.depth != 0 - The Scene view has a targetTexture and a depth texture) - // TODO: If at some point we get proper render target aliasing, we will be able to use the provided depth texture directly with our RT handle system - // Note: Debug.DrawLine and Debug.Ray only work in editor, not in player - var copyDepth = hdCamera.camera.targetTexture != null && hdCamera.camera.targetTexture.depth != 0; + // Due to our RT handle system we don't write into the backbuffer depth buffer (as our depth buffer can be bigger than the one provided) + // So we need to do a copy of the corresponding part of RT depth buffer in the target depth buffer in various situation: + // - RenderTexture (camera.targetTexture != null) has a depth buffer (camera.targetTexture.depth != 0) + // - We are rendering into the main game view (i.e not a RenderTexture camera.cameraType == CameraType.Game && hdCamera.camera.targetTexture == null) in the editor for allowing usage of Debug.DrawLine and Debug.Ray. + // - We draw Gizmo/Icons in the editor (hdCamera.camera.targetTexture != null && camera.targetTexture.depth != 0 - The Scene view has a targetTexture and a depth texture) + // TODO: If at some point we get proper render target aliasing, we will be able to use the provided depth texture directly with our RT handle system + // Note: Debug.DrawLine and Debug.Ray only work in editor, not in player + var copyDepth = hdCamera.camera.targetTexture != null && hdCamera.camera.targetTexture.depth != 0; #if UNITY_EDITOR - copyDepth = copyDepth || hdCamera.isMainGameView; // Specific case of Debug.DrawLine and Debug.Ray + copyDepth = copyDepth || hdCamera.isMainGameView; // Specific case of Debug.DrawLine and Debug.Ray #endif - if (copyDepth && !hdCamera.xr.enabled) - { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.CopyDepthInTargetTexture))) + if (copyDepth && !hdCamera.xr.enabled) { - cmd.SetRenderTarget(target.id); - cmd.SetViewport(hdCamera.finalViewport); - m_CopyDepthPropertyBlock.SetTexture(HDShaderIDs._InputDepth, m_SharedRTManager.GetDepthStencilBuffer()); - // When we are Main Game View we need to flip the depth buffer ourselves as we are after postprocess / blit that have already flipped the screen - m_CopyDepthPropertyBlock.SetInt("_FlipY", hdCamera.isMainGameView ? 1 : 0); - m_CopyDepthPropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); - CoreUtils.DrawFullScreen(cmd, m_CopyDepth, m_CopyDepthPropertyBlock); + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.CopyDepthInTargetTexture))) + { + cmd.SetRenderTarget(target.id); + cmd.SetViewport(hdCamera.finalViewport); + m_CopyDepthPropertyBlock.SetTexture(HDShaderIDs._InputDepth, m_SharedRTManager.GetDepthStencilBuffer()); + // When we are Main Game View we need to flip the depth buffer ourselves as we are after postprocess / blit that have already flipped the screen + m_CopyDepthPropertyBlock.SetInt("_FlipY", hdCamera.isMainGameView ? 1 : 0); + m_CopyDepthPropertyBlock.SetVector(HDShaderIDs._BlitScaleBias, new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); + CoreUtils.DrawFullScreen(cmd, m_CopyDepth, m_CopyDepthPropertyBlock); + } } - } - if (aovRequest.isValid) - { - aovRequest.PushCameraTexture(cmd, AOVBuffers.DepthStencil, hdCamera, m_SharedRTManager.GetDepthStencilBuffer(), aovBuffers); - if (m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors) - aovRequest.PushCameraTexture(cmd, AOVBuffers.MotionVectors, hdCamera, m_SharedRTManager.GetMotionVectorsBuffer(), aovBuffers); - - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.AOVExecute))) + if (aovRequest.isValid) { - aovRequest.Execute(cmd, aovBuffers, aovCustomPassBuffers, RenderOutputProperties.From(hdCamera)); + aovRequest.PushCameraTexture(cmd, AOVBuffers.DepthStencil, hdCamera, m_SharedRTManager.GetDepthStencilBuffer(), aovBuffers); + if (m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors) + aovRequest.PushCameraTexture(cmd, AOVBuffers.MotionVectors, hdCamera, m_SharedRTManager.GetMotionVectorsBuffer(), aovBuffers); + + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.AOVExecute))) + { + aovRequest.Execute(cmd, aovBuffers, aovCustomPassBuffers, RenderOutputProperties.From(hdCamera)); + } } - } #if UNITY_EDITOR - // We need to make sure the viewport is correctly set for the editor rendering. It might have been changed by debug overlay rendering just before. - cmd.SetViewport(hdCamera.finalViewport); + // We need to make sure the viewport is correctly set for the editor rendering. It might have been changed by debug overlay rendering just before. + cmd.SetViewport(hdCamera.finalViewport); - if (camera.cameraType == CameraType.SceneView) - RenderWireOverlay(cmd, camera, renderContext); + if (camera.cameraType == CameraType.SceneView) + RenderWireOverlay(cmd, camera, renderContext); - // Render overlay Gizmos - if (showGizmos) - RenderGizmos(cmd, camera, renderContext, GizmoSubset.PostImageEffects); + // Render overlay Gizmos + if (showGizmos) + RenderGizmos(cmd, camera, renderContext, GizmoSubset.PostImageEffects); #endif - } // using (ListPool.Get(out var aovCustomPassBuffers)) // This is required so that all commands up to here are executed before EndCameraRendering is called for the user. @@ -3187,7 +3185,7 @@ out ScriptableCullingParameters cullingParams } } - if(CoreUtils.IsSceneLightingDisabled(camera)) + if (CoreUtils.IsSceneLightingDisabled(camera)) { currentFrameSettings.SetEnabled(FrameSettingsField.ExposureControl, false); } @@ -3429,6 +3427,7 @@ void RenderWireOverlay(CommandBuffer cmd, Camera camera, ScriptableRenderContext renderContext.DrawWireOverlay(camera); } } + #endif static RendererListDesc CreateOpaqueRendererListDesc( @@ -3624,41 +3623,41 @@ DepthPrepassParameters PrepareDepthPrepass(CullingResults cull, HDCamera hdCamer // decalsEnabled // LitShaderMode.Forward // Range Opaque both deferred and forward - depth + optional msaa + normal - // Range opaqueDecal for both deferred and forward - depth + optional msaa + normal + decal - // Range opaqueAlphaTest for both deferred and forward - depth + optional msaa + normal - // Range opaqueDecalAlphaTes for both deferred and forward - depth + optional msaa + normal + decal + // Range opaqueDecal for both deferred and forward - depth + optional msaa + normal + decal + // Range opaqueAlphaTest for both deferred and forward - depth + optional msaa + normal + // Range opaqueDecalAlphaTes for both deferred and forward - depth + optional msaa + normal + decal // LitShaderMode.Deferred // fullDeferredPrepass - // Range Opaque for deferred - depth - // Range opaqueDecal for deferred - depth + decal - // Range opaqueAlphaTest for deferred - depth - // Range opaqueDecalAlphaTes for deferred - depth + decal - - // Range Opaque for forward - depth + normal - // Range opaqueDecal for forward - depth + normal + decal - // Range opaqueAlphaTest for forward - depth + normal - // Range opaqueDecalAlphaTes for forward - depth + normal + decal - // !fullDeferredPrepass - // Range opaqueDecal for deferred - depth + decal - // Range opaqueAlphaTest for deferred - depth - // Range opaqueDecalAlphaTes for deferred - depth + decal - - // Range Opaque for forward - depth + normal - // Range opaqueDecal for forward - depth + normal + decal - // Range opaqueAlphaTest for forward - depth + normal - // Range opaqueDecalAlphaTesT for forward - depth + normal + decal + // Range Opaque for deferred - depth + // Range opaqueDecal for deferred - depth + decal + // Range opaqueAlphaTest for deferred - depth + // Range opaqueDecalAlphaTes for deferred - depth + decal + + // Range Opaque for forward - depth + normal + // Range opaqueDecal for forward - depth + normal + decal + // Range opaqueAlphaTest for forward - depth + normal + // Range opaqueDecalAlphaTes for forward - depth + normal + decal + // !fullDeferredPrepass + // Range opaqueDecal for deferred - depth + decal + // Range opaqueAlphaTest for deferred - depth + // Range opaqueDecalAlphaTes for deferred - depth + decal + + // Range Opaque for forward - depth + normal + // Range opaqueDecal for forward - depth + normal + decal + // Range opaqueAlphaTest for forward - depth + normal + // Range opaqueDecalAlphaTesT for forward - depth + normal + decal // !decalsEnabled // LitShaderMode.Forward - // Range Opaque..OpaqueDecalAlphaTest for deferred and forward - depth + optional msaa + normal + // Range Opaque..OpaqueDecalAlphaTest for deferred and forward - depth + optional msaa + normal // LitShaderMode.Deferred // fullDeferredPrepass - // Range Opaque..OpaqueDecalAlphaTest for deferred - depth + // Range Opaque..OpaqueDecalAlphaTest for deferred - depth - // Range Opaque..OpaqueDecalAlphaTest for forward - depth + normal - // !fullDeferredPrepass - // Range OpaqueAlphaTest..OpaqueDecalAlphaTest for deferred - depth + // Range Opaque..OpaqueDecalAlphaTest for forward - depth + normal + // !fullDeferredPrepass + // Range OpaqueAlphaTest..OpaqueDecalAlphaTest for deferred - depth - // Range Opaque..OpaqueDecalAlphaTest for forward - depth + normal + // Range Opaque..OpaqueDecalAlphaTest for forward - depth + normal var result = new DepthPrepassParameters(); @@ -3680,13 +3679,13 @@ DepthPrepassParameters PrepareDepthPrepass(CullingResults cull, HDCamera hdCamer if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.AlphaToMask)) stateBlock = m_AlphaToMaskBlock; - result.depthForwardRendererListDesc = CreateOpaqueRendererListDesc( cull, hdCamera.camera, m_DepthOnlyAndDepthForwardOnlyPassNames, stateBlock: stateBlock, excludeObjectMotionVectors: objectMotionEnabled); + result.depthForwardRendererListDesc = CreateOpaqueRendererListDesc(cull, hdCamera.camera, m_DepthOnlyAndDepthForwardOnlyPassNames, stateBlock: stateBlock, excludeObjectMotionVectors: objectMotionEnabled); break; case LitShaderMode.Deferred: result.hasDepthDeferredPass = true; result.passName = fullDeferredPrepass ? "Full Depth Prepass (Deferred)" : - (decalsEnabled ? "Partial Depth Prepass (Deferred - Decal + AlphaTest)" : "Partial Depth Prepass (Deferred - AlphaTest)"); + (decalsEnabled ? "Partial Depth Prepass (Deferred - Decal + AlphaTest)" : "Partial Depth Prepass (Deferred - AlphaTest)"); bool excludeMotion = fullDeferredPrepass ? objectMotionEnabled : false; @@ -3694,7 +3693,7 @@ DepthPrepassParameters PrepareDepthPrepass(CullingResults cull, HDCamera hdCamer result.depthDeferredRendererListDesc = CreateOpaqueRendererListDesc( cull, hdCamera.camera, m_DepthOnlyPassNames, renderQueueRange: fullDeferredPrepass ? HDRenderQueue.k_RenderQueue_AllOpaque : - (decalsEnabled ? HDRenderQueue.k_RenderQueue_OpaqueDecalAndAlphaTest : HDRenderQueue.k_RenderQueue_OpaqueAlphaTest), + (decalsEnabled ? HDRenderQueue.k_RenderQueue_OpaqueDecalAndAlphaTest : HDRenderQueue.k_RenderQueue_OpaqueAlphaTest), stateBlock: m_AlphaToMaskBlock, excludeObjectMotionVectors: excludeMotion); @@ -3708,16 +3707,16 @@ DepthPrepassParameters PrepareDepthPrepass(CullingResults cull, HDCamera hdCamer return result; } - static void RenderDepthPrepass( ScriptableRenderContext renderContext, - CommandBuffer cmd, - FrameSettings frameSettings, - RenderTargetIdentifier[] deferredMrt, - RenderTargetIdentifier[] forwardMrt, - RTHandle depthBuffer, - in RendererList depthDeferredRendererListDesc, - in RendererList depthForwardRendererListDesc, - bool hasDepthDeferredPass - ) + static void RenderDepthPrepass(ScriptableRenderContext renderContext, + CommandBuffer cmd, + FrameSettings frameSettings, + RenderTargetIdentifier[] deferredMrt, + RenderTargetIdentifier[] forwardMrt, + RTHandle depthBuffer, + in RendererList depthDeferredRendererListDesc, + in RendererList depthForwardRendererListDesc, + bool hasDepthDeferredPass + ) { // Disable write to normal buffer for unlit shader (the normal buffer binding change when using MSAA) cmd.SetGlobalInt(HDShaderIDs._ColorMaskNormal, frameSettings.IsEnabled(FrameSettingsField.MSAA) ? (int)ColorWriteMask.All : 0); @@ -3748,13 +3747,13 @@ bool RenderDepthPrepass(CullingResults cull, HDCamera hdCamera, ScriptableRender using (new ProfilingScope(cmd, ProfilingSampler.Get(depthPrepassParameters.profilingId))) { RenderDepthPrepass(renderContext, cmd, hdCamera.frameSettings, - m_SharedRTManager.GetDepthPrepassDeferredRTI(hdCamera.frameSettings), - m_SharedRTManager.GetDepthPrepassForwardRTI(hdCamera.frameSettings), - m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), - RendererList.Create(depthPrepassParameters.depthDeferredRendererListDesc), - RendererList.Create(depthPrepassParameters.depthForwardRendererListDesc), - depthPrepassParameters.hasDepthDeferredPass - ); + m_SharedRTManager.GetDepthPrepassDeferredRTI(hdCamera.frameSettings), + m_SharedRTManager.GetDepthPrepassForwardRTI(hdCamera.frameSettings), + m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), + RendererList.Create(depthPrepassParameters.depthDeferredRendererListDesc), + RendererList.Create(depthPrepassParameters.depthForwardRendererListDesc), + depthPrepassParameters.hasDepthDeferredPass + ); } return depthPrepassParameters.shouldRenderMotionVectorAfterGBuffer; @@ -3790,10 +3789,10 @@ void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext } bool canReadBoundDepthBuffer = SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || - SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne || + SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12; - if(!canReadBoundDepthBuffer) + if (!canReadBoundDepthBuffer) { // We need to copy depth buffer texture if we want to bind it at this stage CopyDepthBufferIfNeeded(hdCamera, cmd); @@ -3801,21 +3800,21 @@ void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext // If we have an incomplete depth buffer use for decal we will need to do another copy // after the rendering of the GBuffer - if (( hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred) && - !hdCamera.frameSettings.IsEnabled(FrameSettingsField.DepthPrepassWithDeferredRendering)) + if ((hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred) && + !hdCamera.frameSettings.IsEnabled(FrameSettingsField.DepthPrepassWithDeferredRendering)) m_IsDepthBufferCopyValid = false; using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferRender))) { var parameters = PrepareRenderDBufferParameters(hdCamera); - RenderDBuffer( parameters, - m_DbufferManager.GetBuffersRTI(), - m_DbufferManager.GetRTHandles(), - m_SharedRTManager.GetDepthStencilBuffer(), - canReadBoundDepthBuffer ? m_SharedRTManager.GetDepthStencilBuffer() : m_SharedRTManager.GetDepthTexture(), - RendererList.Create(PrepareMeshDecalsRendererList(cullingResults, hdCamera, parameters.use4RTs)), - m_SharedRTManager.GetDecalPrepassBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), - renderContext, cmd); + RenderDBuffer(parameters, + m_DbufferManager.GetBuffersRTI(), + m_DbufferManager.GetRTHandles(), + m_SharedRTManager.GetDepthStencilBuffer(), + canReadBoundDepthBuffer ? m_SharedRTManager.GetDepthStencilBuffer() : m_SharedRTManager.GetDepthTexture(), + RendererList.Create(PrepareMeshDecalsRendererList(cullingResults, hdCamera, parameters.use4RTs)), + m_SharedRTManager.GetDecalPrepassBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), + renderContext, cmd); m_DbufferManager.BindBufferAsTextures(cmd); } @@ -3868,11 +3867,11 @@ DBufferNormalPatchParameters PrepareDBufferNormalPatchParameters(HDCamera hdCame return parameters; } - static void DecalNormalPatch( DBufferNormalPatchParameters parameters, - RTHandle[] dBuffer, - RTHandle depthStencilBuffer, - RTHandle normalBuffer, - CommandBuffer cmd) + static void DecalNormalPatch(DBufferNormalPatchParameters parameters, + RTHandle[] dBuffer, + RTHandle depthStencilBuffer, + RTHandle normalBuffer, + CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.DBufferNormal))) { @@ -3929,15 +3928,15 @@ RenderDBufferParameters PrepareRenderDBufferParameters(HDCamera hdCamera) return parameters; } - static void RenderDBuffer( in RenderDBufferParameters parameters, - RenderTargetIdentifier[] mrt, - RTHandle[] rtHandles, - RTHandle depthStencilBuffer, - RTHandle depthTexture, - RendererList meshDecalsRendererList, - RTHandle decalPrepassBuffer, - ScriptableRenderContext renderContext, - CommandBuffer cmd) + static void RenderDBuffer(in RenderDBufferParameters parameters, + RenderTargetIdentifier[] mrt, + RTHandle[] rtHandles, + RTHandle depthStencilBuffer, + RTHandle depthTexture, + RendererList meshDecalsRendererList, + RTHandle decalPrepassBuffer, + ScriptableRenderContext renderContext, + CommandBuffer cmd) { // for alpha compositing, color is cleared to 0, alpha to 1 // https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch23.html @@ -3961,7 +3960,7 @@ static void RenderDBuffer( in RenderDBufferParameters parameters, { for (int rtindex = 0; rtindex < 3; rtindex++) { - m_Dbuffer3RtIds[rtindex] = mrt[rtindex]; + m_Dbuffer3RtIds[rtindex] = mrt[rtindex]; } // this actually sets the MRTs and HTile RWTexture, this is done separately because we do not have an api to clear MRTs to different colors CoreUtils.SetRenderTarget(cmd, m_Dbuffer3RtIds, depthStencilBuffer); // do not clear anymore @@ -4097,14 +4096,14 @@ TransparencyOverdrawParameters PrepareTransparencyOverdrawParameters(HDCamera hd return parameters; } - static void RenderTransparencyOverdraw( TransparencyOverdrawParameters parameters, - RTHandle colorBuffer, - RTHandle depthBuffer, - in RendererList transparencyRL, - in RendererList transparencyAfterPostRL, - in RendererList transparencyLowResRL, - ScriptableRenderContext renderContext, - CommandBuffer cmd) + static void RenderTransparencyOverdraw(TransparencyOverdrawParameters parameters, + RTHandle colorBuffer, + RTHandle depthBuffer, + in RendererList transparencyRL, + in RendererList transparencyAfterPostRL, + in RendererList transparencyLowResRL, + ScriptableRenderContext renderContext, + CommandBuffer cmd) { CoreUtils.SetRenderTarget(cmd, colorBuffer, depthBuffer, clearFlag: ClearFlag.Color, clearColor: Color.black); @@ -4128,13 +4127,13 @@ void RenderTransparencyOverdraw(CullingResults cull, HDCamera hdCamera, Scriptab if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() && m_CurrentDebugDisplaySettings.data.fullScreenDebugMode == FullScreenDebugMode.TransparencyOverdraw) { var parameters = PrepareTransparencyOverdrawParameters(hdCamera, cull); - RenderTransparencyOverdraw( parameters, - m_CameraColorBuffer, - m_SharedRTManager.GetDepthStencilBuffer(), - RendererList.Create(parameters.transparencyRL), - RendererList.Create(parameters.transparencyAfterPostRL), - RendererList.Create(parameters.transparencyLowResRL), - renderContext, cmd); + RenderTransparencyOverdraw(parameters, + m_CameraColorBuffer, + m_SharedRTManager.GetDepthStencilBuffer(), + RendererList.Create(parameters.transparencyRL), + RendererList.Create(parameters.transparencyAfterPostRL), + RendererList.Create(parameters.transparencyLowResRL), + renderContext, cmd); PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.TransparencyOverdraw); } } @@ -4155,13 +4154,13 @@ FullScreenDebugParameters PrepareFullScreenDebugParameters(HDCamera hdCamera, Cu return parameters; } - static void RenderFullScreenDebug( FullScreenDebugParameters parameters, - RTHandle colorBuffer, - RTHandle depthBuffer, - ComputeBuffer debugBuffer, - in RendererList rendererList, - ScriptableRenderContext renderContext, - CommandBuffer cmd) + static void RenderFullScreenDebug(FullScreenDebugParameters parameters, + RTHandle colorBuffer, + RTHandle depthBuffer, + ComputeBuffer debugBuffer, + in RendererList rendererList, + ScriptableRenderContext renderContext, + CommandBuffer cmd) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderFullScreenDebug))) { @@ -4178,12 +4177,12 @@ void RenderFullScreenDebug(CullingResults cullResults, HDCamera hdCamera, Script { bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); var parameters = PrepareFullScreenDebugParameters(hdCamera, cullResults); - RenderFullScreenDebug( parameters, - msaa ? m_CameraColorMSAABuffer : m_CameraColorBuffer, - m_SharedRTManager.GetDepthStencilBuffer(msaa), - m_SharedRTManager.GetFullScreenDebugBuffer(), - RendererList.Create(parameters.rendererList), - renderContext, cmd); + RenderFullScreenDebug(parameters, + msaa ? m_CameraColorMSAABuffer : m_CameraColorBuffer, + m_SharedRTManager.GetDepthStencilBuffer(msaa), + m_SharedRTManager.GetFullScreenDebugBuffer(), + RendererList.Create(parameters.rendererList), + renderContext, cmd); if (msaa) m_SharedRTManager.ResolveMSAAColor(cmd, hdCamera, m_CameraColorMSAABuffer, m_CameraColorBuffer); @@ -4263,7 +4262,7 @@ RendererListDesc PrepareForwardOpaqueRendererList(CullingResults cullResults, HD var passNames = hdCamera.frameSettings.litShaderMode == LitShaderMode.Forward ? m_ForwardAndForwardOnlyPassNames : m_ForwardOnlyPassNames; - return CreateOpaqueRendererListDesc(cullResults, hdCamera.camera, passNames, m_CurrentRendererConfigurationBakedLighting); + return CreateOpaqueRendererListDesc(cullResults, hdCamera.camera, passNames, m_CurrentRendererConfigurationBakedLighting); } // Guidelines: In deferred by default there is no opaque in forward. However it is possible to force an opaque material to render in forward @@ -4294,8 +4293,8 @@ void RenderForwardOpaque(CullingResults cullResults, HDCamera hdCamera, Scriptab #else const int offset = 1; #endif - renderTarget[offset+0] = msaa ? m_CameraSssDiffuseLightingMSAABuffer : m_CameraSssDiffuseLightingBuffer; - renderTarget[offset+1] = msaa ? GetSSSBufferMSAA() : GetSSSBuffer(); + renderTarget[offset + 0] = msaa ? m_CameraSssDiffuseLightingMSAABuffer : m_CameraSssDiffuseLightingBuffer; + renderTarget[offset + 1] = msaa ? GetSSSBufferMSAA() : GetSSSBuffer(); } else { @@ -4310,11 +4309,11 @@ void RenderForwardOpaque(CullingResults cullResults, HDCamera hdCamera, Scriptab } RenderForwardRendererList(hdCamera.frameSettings, - RendererList.Create(PrepareForwardOpaqueRendererList(cullResults, hdCamera)), - renderTarget, - m_SharedRTManager.GetDepthStencilBuffer(msaa), - useFptl ? m_TileAndClusterData.lightList : m_TileAndClusterData.perVoxelLightLists, - true, renderContext, cmd); + RendererList.Create(PrepareForwardOpaqueRendererList(cullResults, hdCamera)), + renderTarget, + m_SharedRTManager.GetDepthStencilBuffer(msaa), + useFptl ? m_TileAndClusterData.lightList : m_TileAndClusterData.perVoxelLightLists, + true, renderContext, cmd); } } @@ -4356,7 +4355,6 @@ RendererListDesc PrepareForwardTransparentRendererList(CullingResults cullResult return CreateTransparentRendererListDesc(cullResults, hdCamera.camera, passNames, m_CurrentRendererConfigurationBakedLighting, transparentRange); } - void RenderForwardTransparent(CullingResults cullResults, HDCamera hdCamera, bool preRefraction, ScriptableRenderContext renderContext, CommandBuffer cmd) { // If rough refraction are turned off, we render all transparents in the Transparent pass and we skip the PreRefraction one. @@ -4400,22 +4398,22 @@ void RenderForwardTransparent(CullingResults cullResults, HDCamera hdCamera, boo } RenderForwardRendererList(hdCamera.frameSettings, - RendererList.Create(PrepareForwardTransparentRendererList(cullResults, hdCamera, preRefraction)), - m_MRTTransparentMotionVec, - m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), - m_TileAndClusterData.perVoxelLightLists, - false, renderContext, cmd); + RendererList.Create(PrepareForwardTransparentRendererList(cullResults, hdCamera, preRefraction)), + m_MRTTransparentMotionVec, + m_SharedRTManager.GetDepthStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), + m_TileAndClusterData.perVoxelLightLists, + false, renderContext, cmd); } } - static void RenderForwardRendererList( FrameSettings frameSettings, - RendererList rendererList, - RenderTargetIdentifier[] renderTarget, - RTHandle depthBuffer, - ComputeBuffer lightListBuffer, - bool opaque, - ScriptableRenderContext renderContext, - CommandBuffer cmd) + static void RenderForwardRendererList(FrameSettings frameSettings, + RendererList rendererList, + RenderTargetIdentifier[] renderTarget, + RTHandle depthBuffer, + ComputeBuffer lightListBuffer, + bool opaque, + ScriptableRenderContext renderContext, + CommandBuffer cmd) { // Note: SHADOWS_SHADOWMASK keyword is enabled in HDRenderPipeline.cs ConfigureForShadowMask bool useFptl = opaque && frameSettings.IsEnabled(FrameSettingsField.FPTLForForwardOpaque); @@ -4574,27 +4572,27 @@ void RenderObjectsMotionVectors(CullingResults cullResults, HDCamera hdCamera, S // decalsEnabled // LitShaderMode.Forward // Range Opaque both deferred and forward - depth + optional msaa + motion + force zero decal + normal - // Range opaqueDecal for both deferred and forward - depth + optional msaa + motion + decal + normal - // Range opaqueAlphaTest for both deferred and forward - depth + optional msaa + motion + force zero decal + normal - // Range opaqueDecalAlphaTest for both deferred and forward - depth + optional msaa + motion + decal + normal + // Range opaqueDecal for both deferred and forward - depth + optional msaa + motion + decal + normal + // Range opaqueAlphaTest for both deferred and forward - depth + optional msaa + motion + force zero decal + normal + // Range opaqueDecalAlphaTest for both deferred and forward - depth + optional msaa + motion + decal + normal // LitShaderMode.Deferred - // Range Opaque for deferred - depth + motion + force zero decal - // Range opaqueDecal for deferred - depth + motion + decal - // Range opaqueAlphaTest for deferred - depth + motion + force zero decal - // Range opaqueDecalAlphaTes for deferred - depth + motion + decal + // Range Opaque for deferred - depth + motion + force zero decal + // Range opaqueDecal for deferred - depth + motion + decal + // Range opaqueAlphaTest for deferred - depth + motion + force zero decal + // Range opaqueDecalAlphaTes for deferred - depth + motion + decal - // Range Opaque for forward - depth + motion + force zero decal + normal - // Range opaqueDecal for forward - depth + motion + decal + normal - // Range opaqueAlphaTest for forward - depth + motion + force zero decal + normal - // Range opaqueDecalAlphaTest for forward - depth + motion + decal + normal + // Range Opaque for forward - depth + motion + force zero decal + normal + // Range opaqueDecal for forward - depth + motion + decal + normal + // Range opaqueAlphaTest for forward - depth + motion + force zero decal + normal + // Range opaqueDecalAlphaTest for forward - depth + motion + decal + normal // !decalsEnabled // LitShaderMode.Forward - // Range Opaque..OpaqueDecalAlphaTest for deferred and forward - depth + motion + optional msaa + normal + // Range Opaque..OpaqueDecalAlphaTest for deferred and forward - depth + motion + optional msaa + normal // LitShaderMode.Deferred - // Range Opaque..OpaqueDecalAlphaTest for deferred - depth + motion + // Range Opaque..OpaqueDecalAlphaTest for deferred - depth + motion - // Range Opaque..OpaqueDecalAlphaTest for forward - depth + motion + normal + // Range Opaque..OpaqueDecalAlphaTest for forward - depth + motion + normal // These flags are still required in SRP or the engine won't compute previous model matrices... // If the flag hasn't been set yet on this camera, motion vectors will skip a frame. @@ -4619,7 +4617,7 @@ void RenderCameraMotionVectors(CullingResults cullResults, HDCamera hdCamera, Sc using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.CameraMotionVectors))) { - bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); + bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); // These flags are still required in SRP or the engine won't compute previous model matrices... // If the flag hasn't been set yet on this camera, motion vectors will skip a frame. @@ -4700,23 +4698,23 @@ RenderSSRParameters PrepareSSRParameters(HDCamera hdCamera, in HDUtils.PackedMip return parameters; } - static void RenderSSR( in RenderSSRParameters parameters, - HDCamera hdCamera, - BlueNoise blueNoise, - RTHandle depthTexture, - RTHandle depthPyramid, - RTHandle normalBuffer, - RTHandle motionVectorsBuffer, - RTHandle SsrHitPointTexture, - RTHandle stencilBuffer, - RTHandle clearCoatMask, - RTHandle previousColorPyramid, - RTHandle ssrAccum, - RTHandle ssrLightingTexture, - RTHandle ssrAccumPrev, - ComputeBuffer coarseStencilBuffer, - CommandBuffer cmd, - ScriptableRenderContext renderContext) + static void RenderSSR(in RenderSSRParameters parameters, + HDCamera hdCamera, + BlueNoise blueNoise, + RTHandle depthTexture, + RTHandle depthPyramid, + RTHandle normalBuffer, + RTHandle motionVectorsBuffer, + RTHandle SsrHitPointTexture, + RTHandle stencilBuffer, + RTHandle clearCoatMask, + RTHandle previousColorPyramid, + RTHandle ssrAccum, + RTHandle ssrLightingTexture, + RTHandle ssrAccumPrev, + ComputeBuffer coarseStencilBuffer, + CommandBuffer cmd, + ScriptableRenderContext renderContext) { var cs = parameters.ssrCS; @@ -4846,8 +4844,8 @@ void RenderSSR(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext ren var motionVectors = m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors ? m_SharedRTManager.GetMotionVectorsBuffer() : TextureXR.GetBlackTexture(); RenderSSR(parameters, hdCamera, GetBlueNoiseManager(), m_SharedRTManager.GetDepthStencilBuffer(), m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetNormalBuffer(), motionVectors, m_SsrHitPointTexture, - m_SharedRTManager.GetStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), clearCoatMask, previousColorPyramid, - ssrAccumulation, m_SsrLightingTexture, ssrAccumulationPrev, m_SharedRTManager.GetCoarseStencilBuffer(), cmd, renderContext); + m_SharedRTManager.GetStencilBuffer(hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA)), clearCoatMask, previousColorPyramid, + ssrAccumulation, m_SsrLightingTexture, ssrAccumulationPrev, m_SharedRTManager.GetCoarseStencilBuffer(), cmd, renderContext); if (!hdCamera.colorPyramidHistoryIsValid) { @@ -4899,7 +4897,7 @@ void RenderSSRTransparent(HDCamera hdCamera, CommandBuffer cmd, ScriptableRender var motionVectors = m_Asset.currentPlatformRenderPipelineSettings.supportMotionVectors ? m_SharedRTManager.GetMotionVectorsBuffer() : TextureXR.GetBlackTexture(); RenderSSR(parameters, hdCamera, GetBlueNoiseManager(), m_SharedRTManager.GetDepthStencilBuffer(), m_SharedRTManager.GetDepthTexture(), m_SharedRTManager.GetNormalBuffer(), motionVectors, - m_SsrHitPointTexture, m_SharedRTManager.GetStencilBuffer(), TextureXR.GetBlackTexture(), previousColorPyramid, null, m_SsrLightingTexture, null, m_SharedRTManager.GetCoarseStencilBuffer(), cmd, renderContext); + m_SsrHitPointTexture, m_SharedRTManager.GetStencilBuffer(), TextureXR.GetBlackTexture(), previousColorPyramid, null, m_SsrLightingTexture, null, m_SharedRTManager.GetCoarseStencilBuffer(), cmd, renderContext); // If color pyramid was not valid, we bind a black texture if (!hdCamera.colorPyramidHistoryIsValid) @@ -4962,7 +4960,7 @@ void DownsampleDepthForLowResTransparency(HDCamera hdCamera, CommandBuffer cmd, CoreUtils.SetRenderTarget(cmd, m_SharedRTManager.GetLowResDepthBuffer()); cmd.SetViewport(new Rect(0, 0, hdCamera.actualWidth * 0.5f, hdCamera.actualHeight * 0.5f)); // TODO: Add option to switch modes at runtime - if(settings.checkerboardDepthBuffer) + if (settings.checkerboardDepthBuffer) { m_DownsampleDepthMaterial.EnableKeyword("CHECKERBOARD_DOWNSAMPLE"); } @@ -4993,7 +4991,7 @@ void UpsampleTransparent(HDCamera hdCamera, CommandBuffer cmd) using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.UpsampleLowResTransparent))) { CoreUtils.SetRenderTarget(cmd, m_CameraColorBuffer); - if(settings.upsampleType == LowResTransparentUpsample.Bilinear) + if (settings.upsampleType == LowResTransparentUpsample.Bilinear) { m_UpsampleTransparency.EnableKeyword("BILINEAR"); } @@ -5157,6 +5155,7 @@ void PushFullScreenVTFeedbackDebugTexture(CommandBuffer cmd, RTHandle textureID, cmd.DrawProcedural(Matrix4x4.identity, m_VTDebugBlit, msaa ? 1 : 0, MeshTopology.Triangles, 3, 1); } } + #endif internal void PushFullScreenDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RTHandle textureID, FullScreenDebugMode debugMode) @@ -5247,13 +5246,13 @@ DebugParameters PrepareDebugParameters(HDCamera hdCamera, HDUtils.PackedMipChain return parameters; } - static void ResolveFullScreenDebug( in DebugParameters parameters, - MaterialPropertyBlock mpb, - RTHandle inputFullScreenDebug, - RTHandle inputDepthPyramid, - RTHandle output, - ComputeBuffer fullscreenBuffer, - CommandBuffer cmd) + static void ResolveFullScreenDebug(in DebugParameters parameters, + MaterialPropertyBlock mpb, + RTHandle inputFullScreenDebug, + RTHandle inputDepthPyramid, + RTHandle output, + ComputeBuffer fullscreenBuffer, + CommandBuffer cmd) { mpb.SetTexture(HDShaderIDs._DebugFullScreenTexture, inputFullScreenDebug); mpb.SetTexture(HDShaderIDs._CameraDepthTexture, inputDepthPyramid); @@ -5279,9 +5278,9 @@ static void ResolveFullScreenDebug( in DebugParameters parameters, } static void ResolveColorPickerDebug(in DebugParameters parameters, - RTHandle debugColorPickerBuffer, - RTHandle output, - CommandBuffer cmd) + RTHandle debugColorPickerBuffer, + RTHandle output, + CommandBuffer cmd) { ColorPickerDebugSettings colorPickerDebugSettings = parameters.debugDisplaySettings.data.colorPickerDebugSettings; FalseColorDebugSettings falseColorDebugSettings = parameters.debugDisplaySettings.data.falseColorDebugSettings; @@ -5306,24 +5305,24 @@ static void ResolveColorPickerDebug(in DebugParameters parameters, } static void RenderExposureDebug(in DebugParameters parameters, - RTHandle inputColorBuffer, - RTHandle postprocessedColorBuffer, - RTHandle currentExposure, - RTHandle prevExposure, - RTHandle debugExposureData, - RTHandle output, - HableCurve hableCurve, - int lutSize, - Vector4 proceduralParams1, - Vector4 proceduralParams2, - ComputeBuffer histogramBuffer, - CommandBuffer cmd) + RTHandle inputColorBuffer, + RTHandle postprocessedColorBuffer, + RTHandle currentExposure, + RTHandle prevExposure, + RTHandle debugExposureData, + RTHandle output, + HableCurve hableCurve, + int lutSize, + Vector4 proceduralParams1, + Vector4 proceduralParams2, + ComputeBuffer histogramBuffer, + CommandBuffer cmd) { // Grab exposure parameters var exposureSettings = parameters.hdCamera.volumeStack.GetComponent(); Vector4 exposureParams = new Vector4(exposureSettings.compensation.value + parameters.debugDisplaySettings.data.lightingDebugSettings.debugExposure, exposureSettings.limitMin.value, - exposureSettings.limitMax.value, 0f); + exposureSettings.limitMax.value, 0f); Vector4 exposureVariants = new Vector4(1.0f, (int)exposureSettings.meteringMode.value, (int)exposureSettings.adaptationMode.value, 0.0f); Vector2 histogramFraction = exposureSettings.histogramPercentages.value / 100.0f; @@ -5363,7 +5362,7 @@ static void RenderExposureDebug(in DebugParameters parameters, var tonemappingMode = toneMapIsEnabled ? tonemappingSettings.mode.value : TonemappingMode.None; bool drawTonemapCurve = tonemappingMode != TonemappingMode.None && - parameters.debugDisplaySettings.data.lightingDebugSettings.showTonemapCurveAlongHistogramView; + parameters.debugDisplaySettings.data.lightingDebugSettings.showTonemapCurveAlongHistogramView; bool centerAroundMiddleGrey = parameters.debugDisplaySettings.data.lightingDebugSettings.centerHistogramAroundMiddleGrey; parameters.debugExposureMaterial.SetVector(HDShaderIDs._ExposureDebugParams, new Vector4(drawTonemapCurve ? 1.0f : 0.0f, (int)tonemappingMode, centerAroundMiddleGrey ? 1 : 0, 0)); @@ -5446,15 +5445,15 @@ void RenderDebug(HDCamera hdCamera, CommandBuffer cmd, CullingResults cullResult m_PostProcessSystem.ComputeProceduralMeteringParams(hdCamera, out Vector4 proceduralParams1, out Vector4 proceduralParams2); RenderExposureDebug(debugParams, m_CameraColorBuffer, m_DebugFullScreenTempBuffer, - m_PostProcessSystem.GetPreviousExposureTexture(hdCamera), - m_PostProcessSystem.GetExposureTexture(hdCamera), - m_PostProcessSystem.GetExposureDebugData(), - m_IntermediateAfterPostProcessBuffer, - m_PostProcessSystem.GetCustomToneMapCurve(), - m_PostProcessSystem.GetLutSize(), - proceduralParams1, - proceduralParams2, - debugParams.debugDisplaySettings.data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.FinalImageHistogramView ? m_PostProcessSystem.GetDebugImageHistogramBuffer() : m_PostProcessSystem.GetHistogramBuffer(), cmd); + m_PostProcessSystem.GetPreviousExposureTexture(hdCamera), + m_PostProcessSystem.GetExposureTexture(hdCamera), + m_PostProcessSystem.GetExposureDebugData(), + m_IntermediateAfterPostProcessBuffer, + m_PostProcessSystem.GetCustomToneMapCurve(), + m_PostProcessSystem.GetLutSize(), + proceduralParams1, + proceduralParams2, + debugParams.debugDisplaySettings.data.lightingDebugSettings.exposureDebugMode == ExposureDebugMode.FinalImageHistogramView ? m_PostProcessSystem.GetDebugImageHistogramBuffer() : m_PostProcessSystem.GetHistogramBuffer(), cmd); } // First resolve color picker @@ -5533,7 +5532,7 @@ void ClearBuffers(HDCamera hdCamera, CommandBuffer cmd) // Special handling for Preview we force to clear with background color (i.e black) // Note that the sky use in this case is the last one setup. If there is no scene or game, there is no sky use as reflection in the preview HDUtils.IsRegularPreviewCamera(hdCamera.camera) - ) + ) { CoreUtils.SetRenderTarget(cmd, msaa ? m_CameraColorMSAABuffer : m_CameraColorBuffer, m_SharedRTManager.GetDepthStencilBuffer(msaa), ClearFlag.Color, GetColorBufferClearColor(hdCamera)); } @@ -5689,12 +5688,11 @@ void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTarg else CoreUtils.SetRenderTarget(cmd, GetAfterPostProcessOffScreenBuffer(), m_SharedRTManager.GetDepthStencilBuffer(), clearFlag: ClearFlag.Color, clearColor: Color.black); - // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass + // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass RenderAfterPostProcess(parameters - , RendererList.Create(parameters.opaqueAfterPPDesc) - , RendererList.Create(parameters.transparentAfterPPDesc) - , renderContext, cmd); - + , RendererList.Create(parameters.opaqueAfterPPDesc) + , RendererList.Create(parameters.transparentAfterPPDesc) + , renderContext, cmd); } } @@ -5717,7 +5715,6 @@ void RenderPostProcess(CullingResults cullResults, HDCamera hdCamera, RenderTarg ); } - RTHandle GetAfterPostProcessOffScreenBuffer() { // Here we share GBuffer albedo buffer since it's not needed anymore else we @@ -5733,12 +5730,11 @@ static void UpdateOffscreenRenderingConstants(ref ShaderVariablesGlobal cb, bool cb._OffScreenDownsampleFactor = factor; } - static void RenderAfterPostProcess( PostProcessParameters parameters, - in RendererList opaqueAfterPostProcessRendererList, - in RendererList transparentAfterPostProcessRendererList, - ScriptableRenderContext renderContext, CommandBuffer cmd) + static void RenderAfterPostProcess(PostProcessParameters parameters, + in RendererList opaqueAfterPostProcessRendererList, + in RendererList transparentAfterPostProcessRendererList, + ScriptableRenderContext renderContext, CommandBuffer cmd) { - using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.AfterPostProcessing))) { // Note about AfterPostProcess and TAA: @@ -5808,11 +5804,10 @@ SendGeometryGraphcisBuffersParameters PrepareSendGeometryBuffersParameters(HDCam } static void SendGeometryGraphicsBuffers(in SendGeometryGraphcisBuffersParameters parameters, - RTHandle mainNormalBuffer, - RTHandle mainDepthBuffer, - CommandBuffer cmd) + RTHandle mainNormalBuffer, + RTHandle mainDepthBuffer, + CommandBuffer cmd) { - var hdCamera = parameters.hdCamera; Texture normalBuffer = null; @@ -5846,6 +5841,7 @@ RTHandle Allocator(string id, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: localDepthBuffer.rt.graphicsFormat, dimension: TextureXR.dimension, enableRandomWrite: localDepthBuffer.rt.enableRandomWrite, name: $"{id}_Depth History Buffer"); } + depthBuffer = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.Depth, Allocator, 1); for (int i = 0; i < hdCamera.viewCount; i++) @@ -5990,6 +5986,7 @@ RTHandle GetVTFeedbackBufferForForward(HDCamera hdCamera) return m_VtBufferManager.FeedbackBuffer; } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.Migration.cs index c017086c957..8f481a52552 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.Migration.cs @@ -136,7 +136,7 @@ enum Version FrameSettings.MigrateVirtualTexturing(ref data.m_RenderingPathDefaultCameraFrameSettings); FrameSettings.MigrateVirtualTexturing(ref data.m_RenderingPathDefaultBakedOrCustomReflectionFrameSettings); FrameSettings.MigrateVirtualTexturing(ref data.m_RenderingPathDefaultRealtimeReflectionFrameSettings); - }) + }) ); [SerializeField] diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs index da808ff7136..2defba252bf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs @@ -31,7 +31,6 @@ public partial class HDRenderPipelineAsset : RenderPipelineAsset, IVirtualTextur HDRenderPipelineAsset() { - } void Reset() => OnValidate(); @@ -146,7 +145,7 @@ internal HDRenderPipelineEditorResources renderPipelineEditorResources internal ref FrameSettings GetDefaultFrameSettings(FrameSettingsRenderType type) { - switch(type) + switch (type) { case FrameSettingsRenderType.Camera: return ref m_RenderingPathDefaultCameraFrameSettings; @@ -433,6 +432,7 @@ internal bool AddDiffusionProfile(DiffusionProfileSettings profile) return false; } } + #endif /// diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineEditorResources.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineEditorResources.cs index 463e42327d5..59881f08350 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineEditorResources.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineEditorResources.cs @@ -84,7 +84,7 @@ public override void OnInspectorGUI() if (UnityEditor.EditorPrefs.GetBool("DeveloperMode") && GUILayout.Button("Reload All")) { - foreach(var field in typeof(HDRenderPipelineEditorResources).GetFields()) + foreach (var field in typeof(HDRenderPipelineEditorResources).GetFields()) field.SetValue(target, null); ResourceReloader.ReloadAllNullIn(target, HDUtils.GetHDRenderPipelinePath()); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderQueue.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderQueue.cs index ecdb412efa3..9816142c225 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderQueue.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderQueue.cs @@ -68,7 +68,7 @@ public enum RenderQueueType internal static RenderQueueType MigrateRenderQueueToHDRP10(RenderQueueType renderQueue) { - switch((int)renderQueue) + switch ((int)renderQueue) { case 0: return RenderQueueType.Background; // Background case 1: return RenderQueueType.Opaque; // Opaque @@ -159,7 +159,7 @@ public static int ChangeType(RenderQueueType targetType, int offset = 0, bool al public static RenderQueueType GetTransparentEquivalent(RenderQueueType type) { - switch(type) + switch (type) { case RenderQueueType.Opaque: return RenderQueueType.Transparent; @@ -193,7 +193,6 @@ public static RenderQueueType GetOpaqueEquivalent(RenderQueueType type) } } - //utility: split opaque/transparent queue public enum OpaqueRenderQueue { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs index 008d4507deb..e378929e0f3 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs @@ -4,7 +4,6 @@ namespace UnityEngine.Rendering.HighDefinition { - [GenerateHLSL] internal enum StencilUsage { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs index febd0431fa4..420f522a61d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStringConstants.cs @@ -403,7 +403,7 @@ static class HDShaderIDs public static readonly int _ColorPyramidTexture = Shader.PropertyToID("_ColorPyramidTexture"); public static readonly int _ColorPyramidUvScaleAndLimitPrevFrame = Shader.PropertyToID("_ColorPyramidUvScaleAndLimitPrevFrame"); public static readonly int _RoughDistortion = Shader.PropertyToID("_RoughDistortion"); - + public static readonly int _DebugColorPickerTexture = Shader.PropertyToID("_DebugColorPickerTexture"); public static readonly int _ColorPickerMode = Shader.PropertyToID("_ColorPickerMode"); public static readonly int _ApplyLinearToSRGB = Shader.PropertyToID("_ApplyLinearToSRGB"); @@ -592,7 +592,7 @@ static class HDShaderIDs public static readonly int _DistanceTexture = Shader.PropertyToID("_DistanceTexture"); public static readonly int _JitterFramePeriod = Shader.PropertyToID("_JitterFramePeriod"); public static readonly int _SingleReflectionBounce = Shader.PropertyToID("_SingleReflectionBounce"); - + // Reflections public static readonly int _ReflectionHistorybufferRW = Shader.PropertyToID("_ReflectionHistorybufferRW"); public static readonly int _CurrentFrameTexture = Shader.PropertyToID("_CurrentFrameTexture"); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs index aefe4331ea8..36e115e3e1e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs @@ -3,7 +3,7 @@ using UnityEngine.Experimental.Rendering.RenderGraphModule; #if UNITY_EDITOR - using UnityEditor; +using UnityEditor; #endif // UNITY_EDITOR namespace UnityEngine.Rendering.HighDefinition @@ -81,8 +81,8 @@ void InitPathTracing() #endif // UNITY_EDITOR m_RadianceTexture = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R32G32B32A32_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: "PathTracingFrameBuffer"); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: "PathTracingFrameBuffer"); } void ReleasePathTracing() @@ -119,7 +119,7 @@ private void OnSceneEdit() // If we just change the sample count, we don't necessarily want to reset iteration if (m_PathTracingSettings && m_CacheMaxIteration != m_PathTracingSettings.maximumSamples.value) { - m_CacheMaxIteration = (uint) m_PathTracingSettings.maximumSamples.value; + m_CacheMaxIteration = (uint)m_PathTracingSettings.maximumSamples.value; m_SubFrameManager.SelectiveReset(m_CacheMaxIteration); } else @@ -155,8 +155,8 @@ private void CheckDirtiness(HDCamera hdCamera) // Check camera resolution dirtiness if (hdCamera.actualWidth != camData.width || hdCamera.actualHeight != camData.height) { - camData.width = (uint) hdCamera.actualWidth; - camData.height = (uint) hdCamera.actualHeight; + camData.width = (uint)hdCamera.actualWidth; + camData.height = (uint)hdCamera.actualHeight; camData.ResetIteration(); m_SubFrameManager.SetCameraData(camID, camData); return; @@ -201,7 +201,7 @@ private void CheckDirtiness(HDCamera hdCamera) // Check lights dirtiness if (m_CacheLightCount != m_RayTracingLights.lightCount) { - m_CacheLightCount = (uint) m_RayTracingLights.lightCount; + m_CacheLightCount = (uint)m_RayTracingLights.lightCount; ResetPathTracing(); return; } @@ -218,8 +218,8 @@ private void CheckDirtiness(HDCamera hdCamera) static RTHandle PathTracingHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R32G32B32A32_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: string.Format("{0}_PathTracingHistoryBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: string.Format("{0}_PathTracingHistoryBuffer{1}", viewName, frameIndex)); } struct PathTracingParameters @@ -321,8 +321,8 @@ void RenderPathTracing(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText } #if UNITY_HDRP_DXR_TESTS_DEFINE - if (Application.isPlaying) - m_SubFrameManager.subFrameCount = 1; + if (Application.isPlaying) + m_SubFrameManager.subFrameCount = 1; #endif if (parameters.cameraData.currentIteration < m_SubFrameManager.subFrameCount) @@ -346,16 +346,15 @@ TextureHandle RenderPathTracing(RenderGraph renderGraph, in PathTracingParameter passData.output = builder.WriteTexture(pathTracingBuffer); builder.SetRenderFunc( - (RenderPathTracingData data, RenderGraphContext ctx) => - { - RenderPathTracing(data.parameters, data.output, ctx.cmd); - }); + (RenderPathTracingData data, RenderGraphContext ctx) => + { + RenderPathTracing(data.parameters, data.output, ctx.cmd); + }); return passData.output; } } - TextureHandle RenderPathTracing(RenderGraph renderGraph, HDCamera hdCamera) { RayTracingShader pathTracingShader = m_Asset.renderPipelineRayTracingResources.pathTracing; @@ -389,8 +388,8 @@ TextureHandle RenderPathTracing(RenderGraph renderGraph, HDCamera hdCamera) #if UNITY_HDRP_DXR_TESTS_DEFINE - if (Application.isPlaying) - m_SubFrameManager.subFrameCount = 1; + if (Application.isPlaying) + m_SubFrameManager.subFrameCount = 1; #endif if (parameters.cameraData.currentIteration < m_SubFrameManager.subFrameCount) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingIntersection.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingIntersection.hlsl index 325da305f69..42fe7f6a366 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingIntersection.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingIntersection.hlsl @@ -6,17 +6,17 @@ // Structure that defines the current state of the intersection, for path tracing struct PathIntersection { - float t; - // Resulting value (often color) of the ray - float3 value; - // Cone representation of the ray - RayCone cone; - // The remaining available depth for the current Ray - uint remainingDepth; - // Pixel coordinate from which the initial ray was launched - uint2 pixelCoord; - // Max roughness encountered along the path - float maxRoughness; + float t; + // Resulting value (often color) of the ray + float3 value; + // Cone representation of the ray + RayCone cone; + // The remaining available depth for the current Ray + uint remainingDepth; + // Pixel coordinate from which the initial ray was launched + uint2 pixelCoord; + // Max roughness encountered along the path + float maxRoughness; }; #endif // UNITY_PATH_TRACING_INTERSECTION_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingVolume.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingVolume.hlsl index 9a6cf4279a2..cdea387dec0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingVolume.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingVolume.hlsl @@ -146,9 +146,9 @@ void ComputeVolumeScattering(inout PathIntersection pathIntersection : SV_RayPay RayDesc ray; ray.Origin = scatteringPosition; ray.TMin = 0.0; - + PathIntersection nextPathIntersection; - + // Light sampling if (computeDirect) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseDenoiser.cs index 86cbc1dffd3..7d548d4bdaf 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseDenoiser.cs @@ -182,16 +182,16 @@ public TextureHandle Denoise(RenderGraph renderGraph, HDCamera hdCamera, Diffuse passData.outputBuffer = builder.WriteTexture(outputBuffer); builder.SetRenderFunc( - (DiffuseDenoiserPassData data, RenderGraphContext ctx) => - { - DiffuseDenoiserResources ddResources = new DiffuseDenoiserResources(); - ddResources.depthStencilBuffer = data.depthStencilBuffer; - ddResources.normalBuffer = data.normalBuffer; - ddResources.noisyBuffer = data.noisyBuffer; - ddResources.intermediateBuffer = data.intermediateBuffer; - ddResources.outputBuffer = data.outputBuffer; - DenoiseBuffer(ctx.cmd, data.parameters, ddResources); - }); + (DiffuseDenoiserPassData data, RenderGraphContext ctx) => + { + DiffuseDenoiserResources ddResources = new DiffuseDenoiserResources(); + ddResources.depthStencilBuffer = data.depthStencilBuffer; + ddResources.normalBuffer = data.normalBuffer; + ddResources.noisyBuffer = data.noisyBuffer; + ddResources.intermediateBuffer = data.intermediateBuffer; + ddResources.outputBuffer = data.outputBuffer; + DenoiseBuffer(ctx.cmd, data.parameters, ddResources); + }); return passData.outputBuffer; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseShadowDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseShadowDenoiser.cs index f96be535572..1fc0a8b4b30 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseShadowDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDDiffuseShadowDenoiser.cs @@ -158,8 +158,8 @@ static void ExecuteDiffuseShadowDirectionalDenoiser(CommandBuffer cmd, DiffuseSh } public void DenoiseBufferDirectional(CommandBuffer cmd, HDCamera hdCamera, - RTHandle noisyBuffer, RTHandle distanceBuffer, RTHandle outputBuffer, - int kernelSize, float angularDiameter, bool singleChannel = true) + RTHandle noisyBuffer, RTHandle distanceBuffer, RTHandle outputBuffer, + int kernelSize, float angularDiameter, bool singleChannel = true) { // Request the intermediate buffer we need RTHandle intermediateBuffer = m_RenderPipeline.GetRayTracingBuffer(InternalRayTracingBuffers.RGBA3); @@ -181,9 +181,9 @@ class DiffuseShadowDenoiserDirectionalPassData } public TextureHandle DenoiseBufferDirectional(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthBuffer, TextureHandle normalBuffer, - TextureHandle noisyBuffer, TextureHandle distanceBuffer, - int kernelSize, float angularDiameter, bool singleChannel = true) + TextureHandle depthBuffer, TextureHandle normalBuffer, + TextureHandle noisyBuffer, TextureHandle distanceBuffer, + int kernelSize, float angularDiameter, bool singleChannel = true) { using (var builder = renderGraph.AddRenderPass("TemporalDenoiser", out var passData, ProfilingSampler.Get(HDProfileId.DiffuseFilter))) { @@ -201,27 +201,27 @@ public TextureHandle DenoiseBufferDirectional(RenderGraph renderGraph, HDCamera // Temporary buffers passData.intermediateBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate buffer" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate buffer" }); // Output buffer passData.outputBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Denoised Buffer" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Denoised Buffer" }))); builder.SetRenderFunc( - (DiffuseShadowDenoiserDirectionalPassData data, RenderGraphContext ctx) => - { - DiffuseShadowDirectionalDenoiserResources resources = new DiffuseShadowDirectionalDenoiserResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.distanceBuffer = data.distanceBuffer; - resources.noisyBuffer = data.noisyBuffer; - - resources.intermediateBuffer = data.intermediateBuffer; - - resources.outputBuffer = data.outputBuffer; - ExecuteDiffuseShadowDirectionalDenoiser(ctx.cmd, data.parameters, resources); - }); + (DiffuseShadowDenoiserDirectionalPassData data, RenderGraphContext ctx) => + { + DiffuseShadowDirectionalDenoiserResources resources = new DiffuseShadowDirectionalDenoiserResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.distanceBuffer = data.distanceBuffer; + resources.noisyBuffer = data.noisyBuffer; + + resources.intermediateBuffer = data.intermediateBuffer; + + resources.outputBuffer = data.outputBuffer; + ExecuteDiffuseShadowDirectionalDenoiser(ctx.cmd, data.parameters, resources); + }); return passData.outputBuffer; } } @@ -344,8 +344,8 @@ static void ExecuteDiffuseShadowSphereDenoiser(CommandBuffer cmd, DiffuseShadowS } public void DenoiseBufferSphere(CommandBuffer cmd, HDCamera hdCamera, - RTHandle noisyBuffer, RTHandle distanceBuffer, RTHandle outputBuffer, - int kernelSize, Vector3 lightPosition, float lightRadius) + RTHandle noisyBuffer, RTHandle distanceBuffer, RTHandle outputBuffer, + int kernelSize, Vector3 lightPosition, float lightRadius) { // Request the intermediate buffers that we need RTHandle intermediateBuffer = m_RenderPipeline.GetRayTracingBuffer(InternalRayTracingBuffers.RGBA3); @@ -367,9 +367,9 @@ class DiffuseShadowDenoiserSpherePassData } public TextureHandle DenoiseBufferSphere(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthBuffer, TextureHandle normalBuffer, - TextureHandle noisyBuffer, TextureHandle distanceBuffer, - int kernelSize, Vector3 lightPosition, float lightRadius) + TextureHandle depthBuffer, TextureHandle normalBuffer, + TextureHandle noisyBuffer, TextureHandle distanceBuffer, + int kernelSize, Vector3 lightPosition, float lightRadius) { using (var builder = renderGraph.AddRenderPass("DiffuseDenoiser", out var passData, ProfilingSampler.Get(HDProfileId.DiffuseFilter))) { @@ -387,27 +387,27 @@ public TextureHandle DenoiseBufferSphere(RenderGraph renderGraph, HDCamera hdCam // Temporary buffers passData.intermediateBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate buffer" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate buffer" }); // Output buffer passData.outputBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Denoised Buffer" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Denoised Buffer" }))); builder.SetRenderFunc( - (DiffuseShadowDenoiserSpherePassData data, RenderGraphContext ctx) => - { - DiffuseShadowSphereDenoiserResources resources = new DiffuseShadowSphereDenoiserResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.distanceBuffer = data.distanceBuffer; - resources.noisyBuffer = data.noisyBuffer; - - resources.intermediateBuffer = data.intermediateBuffer; - - resources.outputBuffer = data.outputBuffer; - ExecuteDiffuseShadowSphereDenoiser(ctx.cmd, data.parameters, resources); - }); + (DiffuseShadowDenoiserSpherePassData data, RenderGraphContext ctx) => + { + DiffuseShadowSphereDenoiserResources resources = new DiffuseShadowSphereDenoiserResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.distanceBuffer = data.distanceBuffer; + resources.noisyBuffer = data.noisyBuffer; + + resources.intermediateBuffer = data.intermediateBuffer; + + resources.outputBuffer = data.outputBuffer; + ExecuteDiffuseShadowSphereDenoiser(ctx.cmd, data.parameters, resources); + }); return passData.outputBuffer; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.RenderGraph.cs index 963c0c28428..2870a87ece4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.RenderGraph.cs @@ -52,20 +52,20 @@ TextureHandle TraceAO(RenderGraph renderGraph, in AmbientOcclusionTraceParameter passData.rayCountTexture = builder.ReadTexture(builder.WriteTexture(rayCountTexture)); // Depending of if we will have to denoise (or not), we need to allocate the final format, or a bigger texture passData.outputTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8_UNorm, enableRandomWrite = true, name = "Ray Traced Ambient Occlusion" })); + { colorFormat = GraphicsFormat.R8_UNorm, enableRandomWrite = true, name = "Ray Traced Ambient Occlusion" })); builder.SetRenderFunc( - (TraceRTAOPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - AmbientOcclusionTraceResources aotResources = new AmbientOcclusionTraceResources(); - aotResources.depthStencilBuffer = data.depthPyramid; - aotResources.normalBuffer = data.normalBuffer; - aotResources.rayCountTexture = data.rayCountTexture; - aotResources.outputTexture = data.outputTexture; - - TraceAO(ctx.cmd, data.parameters, aotResources); - }); + (TraceRTAOPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + AmbientOcclusionTraceResources aotResources = new AmbientOcclusionTraceResources(); + aotResources.depthStencilBuffer = data.depthPyramid; + aotResources.normalBuffer = data.normalBuffer; + aotResources.rayCountTexture = data.rayCountTexture; + aotResources.outputTexture = data.outputTexture; + + TraceAO(ctx.cmd, data.parameters, aotResources); + }); return passData.outputTexture; } @@ -112,11 +112,11 @@ TextureHandle ComposeAO(RenderGraph renderGraph, in AmbientOcclusionComposeParam passData.outputTexture = builder.ReadTexture(builder.WriteTexture(aoTexture)); builder.SetRenderFunc( - (ComposeRTAOPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - ComposeAO(ctx.cmd, data.parameters, data.outputTexture); - }); + (ComposeRTAOPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + ComposeAO(ctx.cmd, data.parameters, data.outputTexture); + }); return passData.outputTexture; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs index 9bf44e6bec8..0211dcd9ab0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingAmbientOcclusion.cs @@ -54,11 +54,10 @@ public void CleanupNonRenderGraphResources() static RTHandle AmbientOcclusionHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: string.Format("{0}_AmbientOcclusionHistoryBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: string.Format("{0}_AmbientOcclusionHistoryBuffer{1}", viewName, frameIndex)); } - static public void SetDefaultAmbientOcclusionTexture(CommandBuffer cmd) { cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, TextureXR.GetBlackTexture()); @@ -191,7 +190,6 @@ public void RenderRTAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputText // TODO: All the push-debug stuff should be centralized somewhere (RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, outputTexture, FullScreenDebugMode.ScreenSpaceAmbientOcclusion); - } static public void TraceAO(CommandBuffer cmd, AmbientOcclusionTraceParameters aoTraceParameters, AmbientOcclusionTraceResources aoTraceResources) @@ -273,7 +271,6 @@ static public void ComposeAO(CommandBuffer cmd, AmbientOcclusionComposeParameter // Bind the textures and the params cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, outputTexture); - } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.RenderGraph.cs index 97a33b9c628..7ef794e061f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.RenderGraph.cs @@ -38,39 +38,39 @@ TextureHandle DeferredLightingRT(RenderGraph renderGraph, in DeferredLightingRTP // Temporary buffers passData.gbuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_SRGB, enableRandomWrite = true, name = "GBuffer0" }); + { colorFormat = GraphicsFormat.R8G8B8A8_SRGB, enableRandomWrite = true, name = "GBuffer0" }); passData.gbuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "GBuffer1" }); + { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "GBuffer1" }); passData.gbuffer2 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "GBuffer2" }); + { colorFormat = GraphicsFormat.R8G8B8A8_UNorm, enableRandomWrite = true, name = "GBuffer2" }); passData.gbuffer3 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = Builtin.GetLightingBufferFormat(), enableRandomWrite = true, name = "GBuffer3" }); + { colorFormat = Builtin.GetLightingBufferFormat(), enableRandomWrite = true, name = "GBuffer3" }); passData.distanceBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Distance Buffer" }); + { colorFormat = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Distance Buffer" }); // Output buffers passData.rayCountTexture = builder.WriteTexture(builder.ReadTexture(rayCountTexture)); passData.litBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Deferred Lighting Result" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Deferred Lighting Result" })); builder.SetRenderFunc( - (DeferredLightingRTRPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - DeferredLightingRTResources rtrDirGenResources = new DeferredLightingRTResources(); - rtrDirGenResources.directionBuffer = data.directionBuffer; - rtrDirGenResources.depthStencilBuffer = data.depthStencilBuffer; - rtrDirGenResources.normalBuffer = data.normalBuffer; - rtrDirGenResources.skyTexture = data.skyTexture; - rtrDirGenResources.gbuffer0 = data.gbuffer0; - rtrDirGenResources.gbuffer1 = data.gbuffer1; - rtrDirGenResources.gbuffer2 = data.gbuffer2; - rtrDirGenResources.gbuffer3 = data.gbuffer3; - rtrDirGenResources.distanceBuffer = data.distanceBuffer; - rtrDirGenResources.rayCountTexture = data.rayCountTexture; - rtrDirGenResources.litBuffer = data.litBuffer; - RenderRaytracingDeferredLighting(ctx.cmd, data.parameters, rtrDirGenResources); - }); + (DeferredLightingRTRPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + DeferredLightingRTResources rtrDirGenResources = new DeferredLightingRTResources(); + rtrDirGenResources.directionBuffer = data.directionBuffer; + rtrDirGenResources.depthStencilBuffer = data.depthStencilBuffer; + rtrDirGenResources.normalBuffer = data.normalBuffer; + rtrDirGenResources.skyTexture = data.skyTexture; + rtrDirGenResources.gbuffer0 = data.gbuffer0; + rtrDirGenResources.gbuffer1 = data.gbuffer1; + rtrDirGenResources.gbuffer2 = data.gbuffer2; + rtrDirGenResources.gbuffer3 = data.gbuffer3; + rtrDirGenResources.distanceBuffer = data.distanceBuffer; + rtrDirGenResources.rayCountTexture = data.rayCountTexture; + rtrDirGenResources.litBuffer = data.litBuffer; + RenderRaytracingDeferredLighting(ctx.cmd, data.parameters, rtrDirGenResources); + }); return passData.litBuffer; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs index d7a7b3ee151..3cc1f36eb97 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingDeferredLightLoop.cs @@ -125,22 +125,22 @@ void CheckBinningBuffersSize(HDCamera hdCamera) int bufferSizeY = numTilesRayBinY * binningTileSize; // Resize the binning buffers if required - if (bufferSizeX * bufferSizeY > m_RayBinResult.count) + if (bufferSizeX * bufferSizeY > m_RayBinResult.count) + { + if (m_RayBinResult != null) { - if(m_RayBinResult != null) - { - CoreUtils.SafeRelease(m_RayBinResult); - CoreUtils.SafeRelease(m_RayBinSizeResult); - m_RayBinResult = null; - m_RayBinSizeResult = null; - } - - if (bufferSizeX * bufferSizeY > 0) - { - m_RayBinResult = new ComputeBuffer(bufferSizeX * bufferSizeY, sizeof(uint)); - m_RayBinSizeResult = new ComputeBuffer(numTilesRayBinX * numTilesRayBinY, sizeof(uint)); - } + CoreUtils.SafeRelease(m_RayBinResult); + CoreUtils.SafeRelease(m_RayBinSizeResult); + m_RayBinResult = null; + m_RayBinSizeResult = null; } + + if (bufferSizeX * bufferSizeY > 0) + { + m_RayBinResult = new ComputeBuffer(bufferSizeX * bufferSizeY, sizeof(uint)); + m_RayBinSizeResult = new ComputeBuffer(numTilesRayBinX * numTilesRayBinY, sizeof(uint)); + } + } } static void BinRays(CommandBuffer cmd, in DeferredLightingRTParameters config, RTHandle directionBuffer, int texWidth, int texHeight) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.RenderGraph.cs index ded4579be8b..2c31b10b3f4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.RenderGraph.cs @@ -23,18 +23,18 @@ TextureHandle DirGenRTGI(RenderGraph renderGraph, in RTIndirectDiffuseDirGenPara passData.depthStencilBuffer = builder.ReadTexture(depthPyramid); passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "GI Ray Directions" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "GI Ray Directions" })); builder.SetRenderFunc( - (DirGenRTGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - RTIndirectDiffuseDirGenResources rtgiDirGenResources = new RTIndirectDiffuseDirGenResources(); - rtgiDirGenResources.depthStencilBuffer = data.depthStencilBuffer; - rtgiDirGenResources.normalBuffer = data.normalBuffer; - rtgiDirGenResources.outputBuffer = data.outputBuffer; - RTIndirectDiffuseDirGen(ctx.cmd, data.parameters, rtgiDirGenResources); - }); + (DirGenRTGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + RTIndirectDiffuseDirGenResources rtgiDirGenResources = new RTIndirectDiffuseDirGenResources(); + rtgiDirGenResources.depthStencilBuffer = data.depthStencilBuffer; + rtgiDirGenResources.normalBuffer = data.normalBuffer; + rtgiDirGenResources.outputBuffer = data.outputBuffer; + RTIndirectDiffuseDirGen(ctx.cmd, data.parameters, rtgiDirGenResources); + }); return passData.outputBuffer; } @@ -51,7 +51,7 @@ class UpscaleRTGIPassData } TextureHandle UpscaleRTGI(RenderGraph renderGraph, in RTIndirectDiffuseUpscaleParameters parameters, - TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle indirectDiffuseBuffer, TextureHandle directionBuffer) + TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle indirectDiffuseBuffer, TextureHandle directionBuffer) { using (var builder = renderGraph.AddRenderPass("Upscale the RTGI result", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingIndirectDiffuseUpscale))) { @@ -63,20 +63,20 @@ TextureHandle UpscaleRTGI(RenderGraph renderGraph, in RTIndirectDiffuseUpscalePa passData.indirectDiffuseBuffer = builder.ReadTexture(indirectDiffuseBuffer); passData.directionBuffer = builder.ReadTexture(directionBuffer); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Indirect Diffuse" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Indirect Diffuse" })); builder.SetRenderFunc( - (UpscaleRTGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - RTIndirectDiffuseUpscaleResources rtgiUpscaleResources = new RTIndirectDiffuseUpscaleResources(); - rtgiUpscaleResources.depthStencilBuffer = data.depthBuffer; - rtgiUpscaleResources.normalBuffer = data.normalBuffer; - rtgiUpscaleResources.indirectDiffuseBuffer = data.indirectDiffuseBuffer; - rtgiUpscaleResources.directionBuffer = data.directionBuffer; - rtgiUpscaleResources.outputBuffer = data.outputBuffer; - RTIndirectDiffuseUpscale(ctx.cmd, data.parameters, rtgiUpscaleResources); - }); + (UpscaleRTGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + RTIndirectDiffuseUpscaleResources rtgiUpscaleResources = new RTIndirectDiffuseUpscaleResources(); + rtgiUpscaleResources.depthStencilBuffer = data.depthBuffer; + rtgiUpscaleResources.normalBuffer = data.normalBuffer; + rtgiUpscaleResources.indirectDiffuseBuffer = data.indirectDiffuseBuffer; + rtgiUpscaleResources.directionBuffer = data.directionBuffer; + rtgiUpscaleResources.outputBuffer = data.outputBuffer; + RTIndirectDiffuseUpscale(ctx.cmd, data.parameters, rtgiUpscaleResources); + }); return passData.outputBuffer; } @@ -102,11 +102,11 @@ TextureHandle AdjustRTGIWeight(RenderGraph renderGraph, in AdjustRTIDWeightParam passData.indirectDiffuseBuffer = builder.ReadTexture(builder.WriteTexture(indirectDiffuseBuffer)); builder.SetRenderFunc( - (AdjustRTGIWeightPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - AdjustRTIDWeight(ctx.cmd, data.parameters, data.indirectDiffuseBuffer, data.depthPyramid, data.stencilBuffer); - }); + (AdjustRTGIWeightPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + AdjustRTIDWeight(ctx.cmd, data.parameters, data.indirectDiffuseBuffer, data.depthPyramid, data.stencilBuffer); + }); return passData.indirectDiffuseBuffer; } @@ -120,8 +120,8 @@ static RTHandle RequestRayTracedIndirectDiffuseHistoryTexture(HDCamera hdCamera) } TextureHandle RenderIndirectDiffusePerformance(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, Texture skyTexture, - int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing) + TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, Texture skyTexture, + int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing) { // Pointer to the final result TextureHandle rtgiResult; @@ -137,7 +137,7 @@ TextureHandle RenderIndirectDiffusePerformance(RenderGraph renderGraph, HDCamera RTIndirectDiffuseUpscaleParameters rtgiUpscaleParameters = PrepareRTIndirectDiffuseUpscaleParameters(hdCamera, settings); rtgiResult = UpscaleRTGI(renderGraph, in rtgiUpscaleParameters, - depthPyramid, normalBuffer, lightingBuffer, directionBuffer); + depthPyramid, normalBuffer, lightingBuffer, directionBuffer); // Denoise if required rtgiResult = DenoiseRTGI(renderGraph, hdCamera, rtgiResult, depthPyramid, normalBuffer, motionVectors); @@ -168,27 +168,27 @@ TextureHandle QualityRTGI(RenderGraph renderGraph, in QualityRTIndirectDiffusePa passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.rayCountTexture = builder.WriteTexture(builder.ReadTexture(rayCountTexture)); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Indirect Diffuse" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Indirect Diffuse" })); builder.SetRenderFunc( - (TraceQualityRTGIPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - QualityRTIndirectDiffuseResources rtgiQRenderingResources = new QualityRTIndirectDiffuseResources(); - rtgiQRenderingResources.depthBuffer = data.depthBuffer; - rtgiQRenderingResources.normalBuffer = data.normalBuffer; - rtgiQRenderingResources.rayCountTexture = data.rayCountTexture; - rtgiQRenderingResources.outputBuffer = data.outputBuffer; - RenderQualityRayTracedIndirectDiffuse(ctx.cmd, data.parameters, rtgiQRenderingResources); - }); + (TraceQualityRTGIPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + QualityRTIndirectDiffuseResources rtgiQRenderingResources = new QualityRTIndirectDiffuseResources(); + rtgiQRenderingResources.depthBuffer = data.depthBuffer; + rtgiQRenderingResources.normalBuffer = data.normalBuffer; + rtgiQRenderingResources.rayCountTexture = data.rayCountTexture; + rtgiQRenderingResources.outputBuffer = data.outputBuffer; + RenderQualityRayTracedIndirectDiffuse(ctx.cmd, data.parameters, rtgiQRenderingResources); + }); return passData.outputBuffer; } } TextureHandle RenderIndirectDiffuseQuality(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, Texture skyTexture, - int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing) + TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, Texture skyTexture, + int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing) { var settings = hdCamera.volumeStack.GetComponent(); @@ -268,8 +268,8 @@ TextureHandle DenoiseRTGI(RenderGraph renderGraph, HDCamera hdCamera, TextureHan } TextureHandle RenderRayTracedIndirectDiffuse(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, Texture skyTexture, TextureHandle rayCountTexture, - int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing) + TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, Texture skyTexture, TextureHandle rayCountTexture, + int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing) { GlobalIllumination giSettings = hdCamera.volumeStack.GetComponent(); @@ -285,12 +285,12 @@ TextureHandle RenderRayTracedIndirectDiffuse(RenderGraph renderGraph, HDCamera h if (qualityMode) rtreflResult = RenderIndirectDiffuseQuality(renderGraph, hdCamera, - depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, skyTexture, - frameCount, shaderVariablesRaytracing); + depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, skyTexture, + frameCount, shaderVariablesRaytracing); else rtreflResult = RenderIndirectDiffusePerformance(renderGraph, hdCamera, - depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, skyTexture, - frameCount, shaderVariablesRaytracing); + depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, skyTexture, + frameCount, shaderVariablesRaytracing); return rtreflResult; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs index 010b2231b4c..4e9f7c11ae9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingIndirectDiffuse.cs @@ -33,10 +33,10 @@ void ReleaseRayTracedIndirectDiffuse() static RTHandle IndirectDiffuseHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: string.Format("{0}_IndirectDiffuseHistoryBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: string.Format("{0}_IndirectDiffuseHistoryBuffer{1}", viewName, frameIndex)); } - + void RenderRayTracedIndirectDiffuse(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, int frameCount) { GlobalIllumination giSettings = hdCamera.volumeStack.GetComponent(); @@ -346,7 +346,7 @@ AdjustRTIDWeightParameters PrepareAdjustRTIDWeightParametersParameters(HDCamera return parameters; } - + static void AdjustRTIDWeight(CommandBuffer cmd, AdjustRTIDWeightParameters parameters, RTHandle indirectDiffuseTexture, RTHandle depthPyramid, RTHandle stencilBuffer) { // Input data @@ -554,7 +554,7 @@ void RenderIndirectDiffuseQuality(HDCamera hdCamera, CommandBuffer cmd, Scriptab QualityRTIndirectDiffuseResources qrtidResources = PrepareQualityRTIndirectDiffuseResources(m_IndirectDiffuseBuffer0); RenderQualityRayTracedIndirectDiffuse(cmd, qrtidParameters, qrtidResources); } - + using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingFilterIndirectDiffuse))) { if (giSettings.denoise) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs index 728e48f6d30..4023fa900a6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingLightCluster.cs @@ -59,7 +59,7 @@ class HDRaytracingLightCluster public static readonly int _ClusterCenterPosition = Shader.PropertyToID("_ClusterCenterPosition"); public static readonly int _ClusterDimension = Shader.PropertyToID("_ClusterDimension"); - // Temporary variables + // Temporary variables // This value is now fixed for every HDRP asset int m_NumLightsPerCell = 0; @@ -82,7 +82,6 @@ class HDRaytracingLightCluster public HDRaytracingLightCluster() { - } public void Initialize(HDRenderPipeline renderPipeline) @@ -370,7 +369,7 @@ void BuildGPULightVolumes(HDCamera hdCamera, HDRayTracingLights rayTracingLights if (currentEnvLight != null) { - if(currentEnvLight.influenceVolume.shape == InfluenceShape.Sphere) + if (currentEnvLight.influenceVolume.shape == InfluenceShape.Sphere) { m_LightVolumesCPUArray[lightIdx + indexOffset].shape = 0; m_LightVolumesCPUArray[lightIdx + indexOffset].range = new Vector3(currentEnvLight.influenceVolume.sphereRadius, currentEnvLight.influenceVolume.sphereRadius, currentEnvLight.influenceVolume.sphereRadius); @@ -520,7 +519,7 @@ void BuildLightData(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights ray LightData lightData = new LightData(); // When the user deletes a light source in the editor, there is a single frame where the light is null before the collection of light in the scene is triggered // the workaround for this is simply to add an invalid light for that frame - if(additionalLightData == null) + if (additionalLightData == null) { m_LightDataCPUArray.Add(lightData); continue; @@ -741,18 +740,18 @@ public void EvaluateClusterDebugView(RenderGraph renderGraph, HDCamera hdCamera, passData.depthStencilBuffer = builder.UseDepthBuffer(depthStencilBuffer, DepthAccess.Read); passData.depthPyramid = builder.ReadTexture(depthStencilBuffer); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Light Cluster Debug Texture" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Light Cluster Debug Texture" })); builder.SetRenderFunc( - (LightClusterDebugPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - LightClusterDebugResources resources = new LightClusterDebugResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.depthTexture = data.depthPyramid; - resources.debugLightClusterTexture = data.outputBuffer; - ExecuteLightClusterDebug(ctx.cmd, data.parameters, resources); - }); + (LightClusterDebugPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + LightClusterDebugResources resources = new LightClusterDebugResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.depthTexture = data.depthPyramid; + resources.debugLightClusterTexture = data.outputBuffer; + ExecuteLightClusterDebug(ctx.cmd, data.parameters, resources); + }); debugTexture = passData.outputBuffer; } @@ -764,6 +763,7 @@ public ComputeBuffer GetCluster() { return m_LightCluster; } + public ComputeBuffer GetLightDatas() { return m_LightDataGPUArray; @@ -816,7 +816,6 @@ void InvalidateCluster() maxClusterPos.Set(-float.MaxValue, -float.MaxValue, -float.MaxValue); punctualLightCount = 0; areaLightCount = 0; - return; } public void CullForRayTracing(HDCamera hdCamera, HDRayTracingLights rayTracingLights) @@ -842,9 +841,9 @@ public void CullForRayTracing(HDCamera hdCamera, HDRayTracingLights rayTracingLi EvaluateClusterVolume(hdCamera); } - public void BuildLightClusterBuffer(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights rayTracingLights) - { - // If there is no lights to process or no environment not the shader is missing + public void BuildLightClusterBuffer(CommandBuffer cmd, HDCamera hdCamera, HDRayTracingLights rayTracingLights) + { + // If there is no lights to process or no environment not the shader is missing if (totalLightCount == 0 || rayTracingLights.lightCount == 0 || !m_RenderPipeline.GetRayTracingState()) return; @@ -855,7 +854,7 @@ public void BuildLightClusterBuffer(CommandBuffer cmd, HDCamera hdCamera, HDRayT BuildLightCluster(hdCamera, cmd); } - public void ReserveCookieAtlasSlots( HDRayTracingLights rayTracingLights) + public void ReserveCookieAtlasSlots(HDRayTracingLights rayTracingLights) { for (int lightIdx = 0; lightIdx < rayTracingLights.hdLightArray.Count; ++lightIdx) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs index b8ca9d4c4c4..5340e6efb3b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingManager.cs @@ -230,8 +230,8 @@ AccelerationStructureStatus AddInstanceToRAS(Renderer currentRenderer, // Is the sub material transparent? subMeshTransparentArray[meshIdx] = currentMaterial.IsKeywordEnabled("_SURFACE_TYPE_TRANSPARENT") - || (HDRenderQueue.k_RenderQueue_Transparent.lowerBound <= currentMaterial.renderQueue - && HDRenderQueue.k_RenderQueue_Transparent.upperBound >= currentMaterial.renderQueue); + || (HDRenderQueue.k_RenderQueue_Transparent.lowerBound <= currentMaterial.renderQueue + && HDRenderQueue.k_RenderQueue_Transparent.upperBound >= currentMaterial.renderQueue); // Aggregate the transparency info materialIsOnlyTransparent &= subMeshTransparentArray[meshIdx]; @@ -239,8 +239,8 @@ AccelerationStructureStatus AddInstanceToRAS(Renderer currentRenderer, // Is the material alpha tested? subMeshCutoffArray[meshIdx] = currentMaterial.IsKeywordEnabled("_ALPHATEST_ON") - || (HDRenderQueue.k_RenderQueue_OpaqueAlphaTest.lowerBound <= currentMaterial.renderQueue - && HDRenderQueue.k_RenderQueue_OpaqueAlphaTest.upperBound >= currentMaterial.renderQueue); + || (HDRenderQueue.k_RenderQueue_OpaqueAlphaTest.lowerBound <= currentMaterial.renderQueue + && HDRenderQueue.k_RenderQueue_OpaqueAlphaTest.upperBound >= currentMaterial.renderQueue); // Force it to be non single sided if it has the keyword if there is a reason bool doubleSided = currentMaterial.doubleSidedGI || currentMaterial.IsKeywordEnabled("_DOUBLESIDED_ON"); @@ -402,7 +402,7 @@ internal void BuildRayTracingAccelerationStructure(HDCamera hdCamera) case AreaLightShape.Tube: m_RayTracingLights.hdLineLightArray.Add(hdLight); break; - //TODO: case AreaLightShape.Disc: + //TODO: case AreaLightShape.Disc: } break; } @@ -428,9 +428,9 @@ internal void BuildRayTracingAccelerationStructure(HDCamera hdCamera) } m_RayTracingLights.lightCount = m_RayTracingLights.hdPointLightArray.Count - + m_RayTracingLights.hdLineLightArray.Count - + m_RayTracingLights.hdRectLightArray.Count - + m_RayTracingLights.reflectionProbeArray.Count; + + m_RayTracingLights.hdLineLightArray.Count + + m_RayTracingLights.hdRectLightArray.Count + + m_RayTracingLights.reflectionProbeArray.Count; AmbientOcclusion aoSettings = hdCamera.volumeStack.GetComponent(); bool rtAOEnabled = aoSettings.rayTracing.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.SSAO); @@ -461,12 +461,12 @@ internal void BuildRayTracingAccelerationStructure(HDCamera hdCamera) // This objects should be included into the RAS AddInstanceToRAS(currentRenderer, - rayTracedShadows, - rtAOEnabled, aoSettings.layerMask.value, - rtREnabled, reflSettings.layerMask.value, - rtGIEnabled, giSettings.layerMask.value, - rrEnabled, recursiveSettings.layerMask.value, - ptEnabled, pathTracingSettings.layerMask.value); + rayTracedShadows, + rtAOEnabled, aoSettings.layerMask.value, + rtREnabled, reflSettings.layerMask.value, + rtGIEnabled, giSettings.layerMask.value, + rrEnabled, recursiveSettings.layerMask.value, + ptEnabled, pathTracingSettings.layerMask.value); } int matCount = m_MaterialCRCs.Count; @@ -538,12 +538,12 @@ internal void BuildRayTracingAccelerationStructure(HDCamera hdCamera) // This objects should be included into the RAS AddInstanceToRAS(currentRenderer, - rayTracedShadows, - aoSettings.rayTracing.value, aoSettings.layerMask.value, - reflSettings.rayTracing.value, reflSettings.layerMask.value, - giSettings.rayTracing.value, giSettings.layerMask.value, - recursiveSettings.enable.value, recursiveSettings.layerMask.value, - pathTracingSettings.enable.value, pathTracingSettings.layerMask.value); + rayTracedShadows, + aoSettings.rayTracing.value, aoSettings.layerMask.value, + reflSettings.rayTracing.value, reflSettings.layerMask.value, + giSettings.rayTracing.value, giSettings.layerMask.value, + recursiveSettings.enable.value, recursiveSettings.layerMask.value, + pathTracingSettings.enable.value, pathTracingSettings.layerMask.value); } // Check if the amount of materials being tracked has changed @@ -581,7 +581,7 @@ internal int RayTracingFrameIndex(HDCamera hdCamera, int targetFrameCount = 8) return 0; else #endif - return (int)hdCamera.GetCameraFrameCount() % targetFrameCount; + return (int)hdCamera.GetCameraFrameCount() % targetFrameCount; } internal bool RayTracingLightClusterRequired(HDCamera hdCamera) @@ -593,10 +593,10 @@ internal bool RayTracingLightClusterRequired(HDCamera hdCamera) SubSurfaceScattering subSurface = hdCamera.volumeStack.GetComponent(); return (m_ValidRayTracingState && (reflSettings.rayTracing.value - || giSettings.rayTracing.value - || recursiveSettings.enable.value - || pathTracingSettings.enable.value - || subSurface.rayTracing.value)); + || giSettings.rayTracing.value + || recursiveSettings.enable.value + || pathTracingSettings.enable.value + || subSurface.rayTracing.value)); } internal void CullForRayTracing(CommandBuffer cmd, HDCamera hdCamera) @@ -625,7 +625,7 @@ internal void BuildRayTracingLightData(CommandBuffer cmd, HDCamera hdCamera, Deb UpdateShaderVariablesRaytracingLightLoopCB(hdCamera, cmd); - m_RayTracingLightCluster.BuildLightClusterBuffer(cmd, hdCamera, m_RayTracingLights); + m_RayTracingLightCluster.BuildLightClusterBuffer(cmd, hdCamera, m_RayTracingLights); } } @@ -637,8 +637,8 @@ static internal float EvaluateHistoryValidity(HDCamera hdCamera) historyValidity = 0.0f; else #endif - // We need to check if something invalidated the history buffers - historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; + // We need to check if something invalidated the history buffers + historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; return historyValidity; } @@ -689,10 +689,10 @@ static internal bool GatherRayTracingSupport(RenderPipelineSettings rpSetting) static internal bool rayTracingSupportedBySystem => UnityEngine.SystemInfo.supportsRayTracing #if UNITY_EDITOR - && (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.StandaloneWindows64 - || UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.StandaloneWindows) + && (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.StandaloneWindows64 + || UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.StandaloneWindows) #endif - ; + ; internal BlueNoise GetBlueNoiseManager() { @@ -780,7 +780,7 @@ internal RTHandle AllocateBuffer(InternalRayTracingBuffers bufferID) { case InternalRayTracingBuffers.Direction: { - m_RayTracingDirectionBuffer = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true,useMipMap: false, name: "RaytracingDirectionBuffer"); + m_RayTracingDirectionBuffer = RTHandles.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, enableRandomWrite: true, useDynamicScale: true, useMipMap: false, name: "RaytracingDirectionBuffer"); return m_RayTracingDirectionBuffer; } case InternalRayTracingBuffers.Distance: diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs index ddef4b1f079..e5032f8d4e7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingRecursiveRenderer.cs @@ -191,19 +191,19 @@ TextureHandle RaytracingRecursiveRender(RenderGraph renderGraph, HDCamera hdCame // Right now the debug buffer is written to independently of what is happening. This must be changed // TODO RENDERGRAPH passData.debugBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Recursive Rendering Debug Texture" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Recursive Rendering Debug Texture" })); builder.SetRenderFunc( - (RecursiveRenderingPassData data, RenderGraphContext ctx) => - { - RecursiveRendererResources rrResources = new RecursiveRendererResources(); - rrResources.depthStencilBuffer = data.depthStencilBuffer; - rrResources.flagMask = data.flagMask; - rrResources.debugBuffer = data.debugBuffer; - rrResources.rayCountTexture = data.rayCountTexture; - rrResources.outputBuffer = data.outputBuffer; - ExecuteRecursiveRendering(ctx.cmd, data.parameters, rrResources); - }); + (RecursiveRenderingPassData data, RenderGraphContext ctx) => + { + RecursiveRendererResources rrResources = new RecursiveRendererResources(); + rrResources.depthStencilBuffer = data.depthStencilBuffer; + rrResources.flagMask = data.flagMask; + rrResources.debugBuffer = data.debugBuffer; + rrResources.rayCountTexture = data.rayCountTexture; + rrResources.outputBuffer = data.outputBuffer; + ExecuteRecursiveRendering(ctx.cmd, data.parameters, rrResources); + }); PushFullScreenDebugTexture(m_RenderGraph, passData.debugBuffer, FullScreenDebugMode.RecursiveRayTracing); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.RenderGraph.cs index e539c779090..bbe84b68ad4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.RenderGraph.cs @@ -27,20 +27,20 @@ TextureHandle DirGenRTR(RenderGraph renderGraph, in RTReflectionDirGenParameters passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Directions" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Directions" })); builder.SetRenderFunc( - (DirGenRTRPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - RTReflectionDirGenResources rtrDirGenResources = new RTReflectionDirGenResources(); - rtrDirGenResources.depthBuffer = data.depthBuffer; - rtrDirGenResources.stencilBuffer = data.stencilBuffer; - rtrDirGenResources.normalBuffer = data.normalBuffer; - rtrDirGenResources.clearCoatMaskTexture = data.clearCoatMaskTexture; - rtrDirGenResources.outputBuffer = data.outputBuffer; - RTReflectionDirectionGeneration(ctx.cmd, data.parameters, rtrDirGenResources); - }); + (DirGenRTRPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + RTReflectionDirGenResources rtrDirGenResources = new RTReflectionDirGenResources(); + rtrDirGenResources.depthBuffer = data.depthBuffer; + rtrDirGenResources.stencilBuffer = data.stencilBuffer; + rtrDirGenResources.normalBuffer = data.normalBuffer; + rtrDirGenResources.clearCoatMaskTexture = data.clearCoatMaskTexture; + rtrDirGenResources.outputBuffer = data.outputBuffer; + RTReflectionDirectionGeneration(ctx.cmd, data.parameters, rtrDirGenResources); + }); return passData.outputBuffer; } @@ -58,7 +58,7 @@ class UpscaleRTRPassData } TextureHandle UpscaleRTR(RenderGraph renderGraph, in RTReflectionUpscaleParameters parameters, - TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle clearCoatTexture, TextureHandle lightingTexture, TextureHandle hitPointTexture) + TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle clearCoatTexture, TextureHandle lightingTexture, TextureHandle hitPointTexture) { using (var builder = renderGraph.AddRenderPass("Upscale the RTR result", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingIndirectDiffuseUpscale))) { @@ -71,21 +71,21 @@ TextureHandle UpscaleRTR(RenderGraph renderGraph, in RTReflectionUpscaleParamete passData.lightingTexture = builder.ReadTexture(lightingTexture); passData.hitPointTexture = builder.ReadTexture(hitPointTexture); passData.outputTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Reflections" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Reflections" })); builder.SetRenderFunc( - (UpscaleRTRPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - RTReflectionUpscaleResources rtrUpscaleResources = new RTReflectionUpscaleResources(); - rtrUpscaleResources.depthStencilBuffer = data.depthStencilBuffer; - rtrUpscaleResources.normalBuffer = data.normalBuffer; - rtrUpscaleResources.clearCoatMaskTexture = data.clearCoatMaskTexture; - rtrUpscaleResources.lightingTexture = data.lightingTexture; - rtrUpscaleResources.hitPointTexture = data.hitPointTexture; - rtrUpscaleResources.outputTexture = data.outputTexture; - UpscaleRTReflections(ctx.cmd, data.parameters, rtrUpscaleResources); - }); + (UpscaleRTRPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + RTReflectionUpscaleResources rtrUpscaleResources = new RTReflectionUpscaleResources(); + rtrUpscaleResources.depthStencilBuffer = data.depthStencilBuffer; + rtrUpscaleResources.normalBuffer = data.normalBuffer; + rtrUpscaleResources.clearCoatMaskTexture = data.clearCoatMaskTexture; + rtrUpscaleResources.lightingTexture = data.lightingTexture; + rtrUpscaleResources.hitPointTexture = data.hitPointTexture; + rtrUpscaleResources.outputTexture = data.outputTexture; + UpscaleRTReflections(ctx.cmd, data.parameters, rtrUpscaleResources); + }); return passData.outputTexture; } @@ -99,8 +99,8 @@ static RTHandle RequestRayTracedReflectionsHistoryTexture(HDCamera hdCamera) } TextureHandle RenderReflectionsPerformance(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, TextureHandle clearCoatTexture, Texture skyTexture, - int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing, bool transparent) + TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, TextureHandle clearCoatTexture, Texture skyTexture, + int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing, bool transparent) { // Pointer to the final result TextureHandle rtrResult; @@ -116,7 +116,7 @@ TextureHandle RenderReflectionsPerformance(RenderGraph renderGraph, HDCamera hdC RTReflectionUpscaleParameters rtrUpscaleParameters = PrepareRTReflectionUpscaleParameters(hdCamera, settings); rtrResult = UpscaleRTR(renderGraph, in rtrUpscaleParameters, - depthPyramid, normalBuffer, clearCoatTexture, lightingBuffer, directionBuffer); + depthPyramid, normalBuffer, clearCoatTexture, lightingBuffer, directionBuffer); // Denoise if required if (settings.denoise && !transparent) @@ -158,29 +158,29 @@ TextureHandle QualityRTR(RenderGraph renderGraph, in RTRQualityRenderingParamete passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture); passData.rayCountTexture = builder.WriteTexture(builder.ReadTexture(rayCountTexture)); passData.outputTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Reflections" })); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Reflections" })); builder.SetRenderFunc( - (TraceQualityRTRPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - RTRQualityRenderingResources rtrQRenderingResources = new RTRQualityRenderingResources(); - rtrQRenderingResources.depthBuffer = data.depthBuffer; - rtrQRenderingResources.stencilBuffer = data.stencilBuffer; - rtrQRenderingResources.normalBuffer = data.normalBuffer; - rtrQRenderingResources.clearCoatMaskTexture = data.clearCoatMaskTexture; - rtrQRenderingResources.rayCountTexture = data.rayCountTexture; - rtrQRenderingResources.outputTexture = data.outputTexture; - RenderQualityRayTracedReflections(ctx.cmd, data.parameters, rtrQRenderingResources); - }); + (TraceQualityRTRPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + RTRQualityRenderingResources rtrQRenderingResources = new RTRQualityRenderingResources(); + rtrQRenderingResources.depthBuffer = data.depthBuffer; + rtrQRenderingResources.stencilBuffer = data.stencilBuffer; + rtrQRenderingResources.normalBuffer = data.normalBuffer; + rtrQRenderingResources.clearCoatMaskTexture = data.clearCoatMaskTexture; + rtrQRenderingResources.rayCountTexture = data.rayCountTexture; + rtrQRenderingResources.outputTexture = data.outputTexture; + RenderQualityRayTracedReflections(ctx.cmd, data.parameters, rtrQRenderingResources); + }); return passData.outputTexture; } } TextureHandle RenderReflectionsQuality(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, TextureHandle clearCoatTexture, Texture skyTexture, - int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing, bool transparent) + TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle rayCountTexture, TextureHandle clearCoatTexture, Texture skyTexture, + int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing, bool transparent) { TextureHandle rtrResult; @@ -206,8 +206,8 @@ TextureHandle RenderReflectionsQuality(RenderGraph renderGraph, HDCamera hdCamer } TextureHandle RenderRayTracedReflections(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle clearCoatTexture, Texture skyTexture, TextureHandle rayCountTexture, - int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing, bool transparent) + TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle motionVectors, TextureHandle clearCoatTexture, Texture skyTexture, TextureHandle rayCountTexture, + int frameCount, ShaderVariablesRaytracing shaderVariablesRaytracing, bool transparent) { ScreenSpaceReflection reflectionSettings = hdCamera.volumeStack.GetComponent(); @@ -223,12 +223,12 @@ TextureHandle RenderRayTracedReflections(RenderGraph renderGraph, HDCamera hdCam if (qualityMode) rtreflResult = RenderReflectionsQuality(renderGraph, hdCamera, - depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, clearCoatTexture, skyTexture, - frameCount, shaderVariablesRaytracing, transparent); + depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, clearCoatTexture, skyTexture, + frameCount, shaderVariablesRaytracing, transparent); else rtreflResult = RenderReflectionsPerformance(renderGraph, hdCamera, - depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, clearCoatTexture, skyTexture, - frameCount, shaderVariablesRaytracing, transparent); + depthPyramid, stencilBuffer, normalBuffer, motionVectors, rayCountTexture, clearCoatTexture, skyTexture, + frameCount, shaderVariablesRaytracing, transparent); return rtreflResult; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs index c37987e17f9..4431fb704d0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDRaytracingReflection.cs @@ -36,8 +36,8 @@ void InitRayTracedReflections() static RTHandle ReflectionHistoryBufferAllocatorFunction(string viewName, int frameIndex, RTHandleSystem rtHandleSystem) { return rtHandleSystem.Alloc(Vector2.one, TextureXR.slices, colorFormat: GraphicsFormat.R16G16B16A16_SFloat, dimension: TextureXR.dimension, - enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, - name: string.Format("{0}_ReflectionHistoryBuffer{1}", viewName, frameIndex)); + enableRandomWrite: true, useMipMap: false, autoGenerateMips: false, + name: string.Format("{0}_ReflectionHistoryBuffer{1}", viewName, frameIndex)); } void ReleaseRayTracedReflections() @@ -374,7 +374,7 @@ void RenderReflectionsPerformance(HDCamera hdCamera, CommandBuffer cmd, RTHandle HDReflectionDenoiser reflectionDenoiser = GetReflectionDenoiser(); ReflectionDenoiserParameters reflDenoiserParameters = reflectionDenoiser.PrepareReflectionDenoiserParameters(hdCamera, EvaluateHistoryValidity(hdCamera), settings.denoiserRadius, false); ReflectionDenoiserResources reflectionDenoiserResources = reflectionDenoiser.PrepareReflectionDenoiserResources(hdCamera, outputTexture, reflectionHistory, - intermediateBuffer0, intermediateBuffer1); + intermediateBuffer0, intermediateBuffer1); // Denoise HDReflectionDenoiser.DenoiseBuffer(cmd, reflDenoiserParameters, reflectionDenoiserResources); @@ -549,7 +549,7 @@ void RenderReflectionsQuality(HDCamera hdCamera, CommandBuffer cmd, RTHandle out HDReflectionDenoiser reflectionDenoiser = GetReflectionDenoiser(); ReflectionDenoiserParameters reflDenoiserParameters = reflectionDenoiser.PrepareReflectionDenoiserParameters(hdCamera, EvaluateHistoryValidity(hdCamera), settings.denoiserRadius, rtrQRenderingParameters.bounceCount == 1); ReflectionDenoiserResources reflectionDenoiserResources = reflectionDenoiser.PrepareReflectionDenoiserResources(hdCamera, outputTexture, reflectionHistory, - intermediateBuffer0, intermediateBuffer1); + intermediateBuffer0, intermediateBuffer1); HDReflectionDenoiser.DenoiseBuffer(cmd, reflDenoiserParameters, reflectionDenoiserResources); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs index f84820d65c6..3fbc4e2607f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDReflectionDenoiser.cs @@ -75,7 +75,6 @@ public void Release() { } - internal ReflectionDenoiserParameters PrepareReflectionDenoiserParameters(HDCamera hdCamera, float historyValidity, int maxKernelSize, bool singleReflectionBounce) { ReflectionDenoiserParameters reflDenoiserParams = new ReflectionDenoiserParameters(); @@ -103,8 +102,8 @@ internal ReflectionDenoiserParameters PrepareReflectionDenoiserParameters(HDCame } internal ReflectionDenoiserResources PrepareReflectionDenoiserResources(HDCamera hdCamera, - RTHandle noisyToOutputSignal, RTHandle historySignal, - RTHandle intermediateBuffer0, RTHandle intermediateBuffer1) + RTHandle noisyToOutputSignal, RTHandle historySignal, + RTHandle intermediateBuffer0, RTHandle intermediateBuffer1) { ReflectionDenoiserResources reflDenoiserResources = new ReflectionDenoiserResources(); reflDenoiserResources.historySignal = historySignal; @@ -135,7 +134,7 @@ public static void DenoiseBuffer(CommandBuffer cmd, ReflectionDenoiserParameters cmd.SetComputeTextureParam(reflDenoiserParameters.reflectionDenoiserCS, reflDenoiserParameters.temporalAccumulationKernel, HDShaderIDs._CameraMotionVectorsTexture, reflDenoiserResources.motionVectorBuffer); cmd.SetComputeFloatParam(reflDenoiserParameters.reflectionDenoiserCS, HDShaderIDs._HistoryValidity, reflDenoiserParameters.historyValidity); cmd.SetComputeIntParam(reflDenoiserParameters.reflectionDenoiserCS, HDShaderIDs._SingleReflectionBounce, reflDenoiserParameters.singleReflectionBounce); - + cmd.DispatchCompute(reflDenoiserParameters.reflectionDenoiserCS, reflDenoiserParameters.temporalAccumulationKernel, numTilesX, numTilesY, reflDenoiserParameters.viewCount); cmd.SetComputeTextureParam(reflDenoiserParameters.reflectionDenoiserCS, reflDenoiserParameters.copyHistoryKernel, HDShaderIDs._DenoiseInputTexture, reflDenoiserResources.intermediateBuffer0); @@ -174,7 +173,7 @@ class ReflectionDenoiserPassData } public TextureHandle DenoiseRTR(RenderGraph renderGraph, in ReflectionDenoiserParameters parameters, HDCamera hdCamera, - TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle motionVectorBuffer, TextureHandle clearCoatTexture, TextureHandle lightingTexture, RTHandle historyBuffer) + TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle motionVectorBuffer, TextureHandle clearCoatTexture, TextureHandle lightingTexture, RTHandle historyBuffer) { using (var builder = renderGraph.AddRenderPass("Denoise ray traced reflections", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingFilterReflection))) { @@ -186,26 +185,26 @@ public TextureHandle DenoiseRTR(RenderGraph renderGraph, in ReflectionDenoiserPa passData.motionVectorBuffer = builder.ReadTexture(motionVectorBuffer); passData.intermediateBuffer0 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "IntermediateTexture0" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "IntermediateTexture0" }); passData.intermediateBuffer1 = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "IntermediateTexture1" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "IntermediateTexture1" }); passData.historySignal = builder.ReadTexture(builder.WriteTexture(renderGraph.ImportTexture(historyBuffer))); passData.noisyToOutputSignal = builder.ReadTexture(builder.WriteTexture(lightingTexture)); builder.SetRenderFunc( - (ReflectionDenoiserPassData data, RenderGraphContext ctx) => - { - // We need to fill the structure that holds the various resources - ReflectionDenoiserResources rtrDenoiseResources = new ReflectionDenoiserResources(); - rtrDenoiseResources.depthBuffer = data.depthBuffer; - rtrDenoiseResources.normalBuffer = data.normalBuffer; - rtrDenoiseResources.motionVectorBuffer = data.motionVectorBuffer; - rtrDenoiseResources.intermediateBuffer0 = data.intermediateBuffer0; - rtrDenoiseResources.intermediateBuffer1 = data.intermediateBuffer1; - rtrDenoiseResources.historySignal = data.historySignal; - rtrDenoiseResources.noisyToOutputSignal = data.noisyToOutputSignal; - DenoiseBuffer(ctx.cmd, data.parameters, rtrDenoiseResources); - }); + (ReflectionDenoiserPassData data, RenderGraphContext ctx) => + { + // We need to fill the structure that holds the various resources + ReflectionDenoiserResources rtrDenoiseResources = new ReflectionDenoiserResources(); + rtrDenoiseResources.depthBuffer = data.depthBuffer; + rtrDenoiseResources.normalBuffer = data.normalBuffer; + rtrDenoiseResources.motionVectorBuffer = data.motionVectorBuffer; + rtrDenoiseResources.intermediateBuffer0 = data.intermediateBuffer0; + rtrDenoiseResources.intermediateBuffer1 = data.intermediateBuffer1; + rtrDenoiseResources.historySignal = data.historySignal; + rtrDenoiseResources.noisyToOutputSignal = data.noisyToOutputSignal; + DenoiseBuffer(ctx.cmd, data.parameters, rtrDenoiseResources); + }); return passData.noisyToOutputSignal; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs index 0b2690cabd4..2ac04f1a3be 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDSimpleDenoiser.cs @@ -105,7 +105,6 @@ SimpleDenoiserResources PrepareSimpleDenoiserResources(RTHandle noisyBuffer, RTH return sdResources; } - static void ExecuteSimpleDenoiser(CommandBuffer cmd, SimpleDenoiserParameters sdParams, SimpleDenoiserResources sdResources) { // Evaluate the dispatch parameters @@ -155,9 +154,9 @@ class SimpleDenoiserPassData } public TextureHandle DenoiseBufferNoHistory(RenderGraph renderGraph, HDCamera hdCamera, - TextureHandle depthBuffer, TextureHandle normalBuffer, - TextureHandle noisyBuffer, - int kernelSize, bool singleChannel) + TextureHandle depthBuffer, TextureHandle normalBuffer, + TextureHandle noisyBuffer, + int kernelSize, bool singleChannel) { using (var builder = renderGraph.AddRenderPass("DiffuseDenoiser", out var passData, ProfilingSampler.Get(HDProfileId.DiffuseFilter))) { @@ -174,26 +173,26 @@ public TextureHandle DenoiseBufferNoHistory(RenderGraph renderGraph, HDCamera hd // Temporary buffers passData.intermediateBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate buffer" }); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Intermediate buffer" }); // Output buffer passData.outputBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Denoised Buffer" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Denoised Buffer" }))); builder.SetRenderFunc( - (SimpleDenoiserPassData data, RenderGraphContext ctx) => - { - SimpleDenoiserResources resources = new SimpleDenoiserResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.noisyBuffer = data.noisyBuffer; - - resources.intermediateBuffer = data.intermediateBuffer; - - resources.outputBuffer = data.outputBuffer; - ExecuteSimpleDenoiser(ctx.cmd, data.parameters, resources); - }); + (SimpleDenoiserPassData data, RenderGraphContext ctx) => + { + SimpleDenoiserResources resources = new SimpleDenoiserResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.noisyBuffer = data.noisyBuffer; + + resources.intermediateBuffer = data.intermediateBuffer; + + resources.outputBuffer = data.outputBuffer; + ExecuteSimpleDenoiser(ctx.cmd, data.parameters, resources); + }); return passData.outputBuffer; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.RenderGraph.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.RenderGraph.cs index 7c692732066..670e7b29ae4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.RenderGraph.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.RenderGraph.cs @@ -48,24 +48,24 @@ public TextureHandle Denoise(RenderGraph renderGraph, HDCamera hdCamera, Tempora // Output buffers passData.outputBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Output" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Output" }))); builder.SetRenderFunc( - (TemporalFilterPassData data, RenderGraphContext ctx) => - { - TemporalFilterResources tfResources = new TemporalFilterResources(); - tfResources.depthStencilBuffer = data.depthStencilBuffer; - tfResources.normalBuffer = data.normalBuffer; - tfResources.velocityBuffer = data.velocityBuffer; - tfResources.motionVectorBuffer = data.motionVectorBuffer; - tfResources.historyDepthTexture = data.historyDepthTexture; - tfResources.historyNormalTexture = data.historyNormalTexture; - tfResources.noisyBuffer = data.noisyBuffer; - tfResources.validationBuffer = data.validationBuffer; - tfResources.historyBuffer = data.historyBuffer; - tfResources.outputBuffer = data.outputBuffer; - DenoiseBuffer(ctx.cmd, data.parameters, tfResources); - }); + (TemporalFilterPassData data, RenderGraphContext ctx) => + { + TemporalFilterResources tfResources = new TemporalFilterResources(); + tfResources.depthStencilBuffer = data.depthStencilBuffer; + tfResources.normalBuffer = data.normalBuffer; + tfResources.velocityBuffer = data.velocityBuffer; + tfResources.motionVectorBuffer = data.motionVectorBuffer; + tfResources.historyDepthTexture = data.historyDepthTexture; + tfResources.historyNormalTexture = data.historyNormalTexture; + tfResources.noisyBuffer = data.noisyBuffer; + tfResources.validationBuffer = data.validationBuffer; + tfResources.historyBuffer = data.historyBuffer; + tfResources.outputBuffer = data.outputBuffer; + DenoiseBuffer(ctx.cmd, data.parameters, tfResources); + }); return passData.outputBuffer; } } @@ -141,30 +141,30 @@ public TemporalDenoiserArrayOutputData DenoiseBuffer(RenderGraph renderGraph, HD // Output textures passData.outputBuffer = builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Output" }))); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Output" }))); passData.outputDistanceSignal = distanceBased ? builder.ReadTexture(builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) - { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Distance output" }))) : new TextureHandle(); + { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Temporal Filter Distance output" }))) : new TextureHandle(); builder.SetRenderFunc( - (TemporalFilterArrayPassData data, RenderGraphContext ctx) => - { - TemporalFilterArrayResources resources = new TemporalFilterArrayResources(); - resources.depthStencilBuffer = data.depthStencilBuffer; - resources.normalBuffer = data.normalBuffer; - resources.motionVectorBuffer = data.motionVectorBuffer; - resources.velocityBuffer = data.velocityBuffer; - resources.historyDepthTexture = data.historyDepthTexture; - resources.historyNormalTexture = data.historyNormalTexture; - resources.noisyBuffer = data.noisyBuffer; - resources.distanceBuffer = data.distanceBuffer; - resources.validationBuffer = data.validationBuffer; - resources.historyBuffer = data.historyBuffer; - resources.validationHistoryBuffer = data.validationHistoryBuffer; - resources.distanceHistorySignal = data.distanceHistorySignal; - resources.outputBuffer = data.outputBuffer; - resources.outputDistanceSignal = data.outputDistanceSignal; - ExecuteTemporalFilterArray(ctx.cmd, data.parameters, resources); - }); + (TemporalFilterArrayPassData data, RenderGraphContext ctx) => + { + TemporalFilterArrayResources resources = new TemporalFilterArrayResources(); + resources.depthStencilBuffer = data.depthStencilBuffer; + resources.normalBuffer = data.normalBuffer; + resources.motionVectorBuffer = data.motionVectorBuffer; + resources.velocityBuffer = data.velocityBuffer; + resources.historyDepthTexture = data.historyDepthTexture; + resources.historyNormalTexture = data.historyNormalTexture; + resources.noisyBuffer = data.noisyBuffer; + resources.distanceBuffer = data.distanceBuffer; + resources.validationBuffer = data.validationBuffer; + resources.historyBuffer = data.historyBuffer; + resources.validationHistoryBuffer = data.validationHistoryBuffer; + resources.distanceHistorySignal = data.distanceHistorySignal; + resources.outputBuffer = data.outputBuffer; + resources.outputDistanceSignal = data.outputDistanceSignal; + ExecuteTemporalFilterArray(ctx.cmd, data.parameters, resources); + }); resultData.outputSignal = passData.outputBuffer; resultData.outputSignalDistance = passData.outputDistanceSignal; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs index d07c10ce4fb..f31e41ca9f0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/HDTemporalFilter.cs @@ -227,7 +227,7 @@ struct TemporalFilterArrayParameters TemporalFilterArrayParameters PrepareTemporalFilterArrayParameters(HDCamera hdCamera, bool distanceBased, bool singleChannel, float historyValidity, int sliceIndex, Vector4 channelMask, Vector4 distanceChannelMask) { TemporalFilterArrayParameters tfaParams = new TemporalFilterArrayParameters(); - + // Set the camera parameters tfaParams.texWidth = hdCamera.actualWidth; tfaParams.texHeight = hdCamera.actualHeight; @@ -280,8 +280,8 @@ struct TemporalFilterArrayResources } TemporalFilterArrayResources PrepareTemporalFilterArrayResources(HDCamera hdCamera, RTHandle noisyBuffer, RTHandle distanceBuffer, RTHandle validationBuffer, - RTHandle historyBuffer, RTHandle validationHistoryBuffer, RTHandle distanceHistorySignal, - RTHandle outputBuffer, RTHandle outputDistanceSignal) + RTHandle historyBuffer, RTHandle validationHistoryBuffer, RTHandle distanceHistorySignal, + RTHandle outputBuffer, RTHandle outputDistanceSignal) { TemporalFilterArrayResources tfaResources = new TemporalFilterArrayResources(); @@ -424,8 +424,8 @@ public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera, TemporalFilterArrayParameters tfaParams = PrepareTemporalFilterArrayParameters(hdCamera, distanceBased, singleChannel, historyValidity, sliceIndex, channelMask, distanceChannelMask); TemporalFilterArrayResources tfaResources = PrepareTemporalFilterArrayResources(hdCamera, noisyBuffer, distanceBuffer, validationBuffer, - historyBuffer, validationHistoryBuffer, distanceHistorySignal, - outputBuffer, outputDistanceSignal); + historyBuffer, validationHistoryBuffer, distanceHistorySignal, + outputBuffer, outputDistanceSignal); ExecuteTemporalFilterArray(cmd, tfaParams, tfaResources); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingMode.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingMode.cs index d847363fc78..bc157c5a7ec 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingMode.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingMode.cs @@ -28,6 +28,6 @@ public sealed class RayTracingModeParameter : VolumeParameter /// /// The initial value to store in the parameter. /// The initial override state for the parameter. - public RayTracingModeParameter(RayTracingMode value, bool overrideState = false) : base(value, overrideState) { } + public RayTracingModeParameter(RayTracingMode value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs index 3426f42bfaa..b4165bf0b93 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs @@ -43,4 +43,3 @@ public RayTracingSettings() } } } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute index 6f159867ac4..222e0145eb1 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute @@ -85,7 +85,7 @@ void RAY_BINNING(uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_Grou // Output the indices of the original pixels uint groupdIndex = groupId.y * _RayBinTileCountX + groupId.x; uint globalOffset = groupdIndex * RAY_BINNING_TILE_SIZE * RAY_BINNING_TILE_SIZE + gs_binOffset[binIndex] + rayBinIndex; - _RayBinResult[globalOffset] = ((currentCoord.x & 0xffff) << 16) + (currentCoord.y & 0xffff); + _RayBinResult[globalOffset] = ((currentCoord.x & 0xffff) << 16) + (currentCoord.y & 0xffff); } // Then output the size of every bin diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader index 8a07205cea0..ab4766a9585 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader @@ -1,9 +1,9 @@ Shader "Hidden/HDRP/DebugLightCluster" { SubShader - { + { Tags { "Queue"="Transparent+0" "IgnoreProjector"="True" "RenderType"="Transparent" } - + HLSLINCLUDE #pragma only_renderers d3d11 @@ -91,7 +91,7 @@ Shader "Hidden/HDRP/DebugLightCluster" }; ENDHLSL - + Pass { Cull Back @@ -106,7 +106,7 @@ Shader "Hidden/HDRP/DebugLightCluster" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/ShaderVariablesRaytracingLightLoop.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingLightCluster.hlsl" - + struct AttributesDefault { float3 positionOS : POSITION; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute index c7cfc3e293f..3bf105004b8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute @@ -60,7 +60,7 @@ void RAYTRACING_DEFERRED(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gro if (LOAD_TEXTURE2D_X(_RaytracingDistanceBuffer, currentCoord).x < 0.0) { - float3 newSampleColor = clamp(LOAD_TEXTURE2D_X(_GBufferTexture3, currentCoord).rgb * GetCurrentExposureMultiplier(), 0.0, _RaytracingIntensityClamp) + float3 newSampleColor = clamp(LOAD_TEXTURE2D_X(_GBufferTexture3, currentCoord).rgb * GetCurrentExposureMultiplier(), 0.0, _RaytracingIntensityClamp) * (_RaytracingPreExposition ? 1.0 : GetInverseCurrentExposureMultiplier() ); _RaytracingLitBufferRW[COORD_TEXTURE2D_X(currentCoord)] = float4(newSampleColor, 0.0); return; @@ -182,7 +182,7 @@ void RaytracingDiffuseDeferred(uint3 dispatchThreadId : SV_DispatchThreadID, uin // Compute the prelight data PreLightData preLightData = GetPreLightData(viewWS, posInput, bsdfData); - + // Evaluate lighting LightLoopOutput lightLoopOutput; LightLoop(viewWS, posInput, preLightData, bsdfData, builtinData, 0.0, 1.0, float3(0.0, 0.0, 0.0), float3(0.0, 0.0, 0.0), lightLoopOutput); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingIntersectonGBuffer.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingIntersectonGBuffer.hlsl index 325a2fea02a..ea70b7dbef6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingIntersectonGBuffer.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingIntersectonGBuffer.hlsl @@ -10,4 +10,4 @@ struct RayIntersectionGBuffer GBufferType1 gbuffer1; GBufferType2 gbuffer2; GBufferType3 gbuffer3; -}; \ No newline at end of file +}; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute index b807aa840fe..b53383d5a9c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute @@ -106,7 +106,7 @@ void BILATERAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupT float2 newSample; newSample.x = GetLDSequenceSampleFloat(sampleIndex + sampleOffset, 0); newSample.y = GetLDSequenceSampleFloat(sampleIndex + sampleOffset, 1); - + // Convert the sample to a local unit disk newSample = SampleDiskCubic(newSample.x, newSample.y); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute index d71541b6866..f27ba5a6da4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute @@ -63,7 +63,7 @@ void BILATERAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupT const BilateralData center = TapBilateralData(centerCoord); #if DIRECTIONAL_LIGHT - // For the directonal light, the solid angle can be used directly + // For the directonal light, the solid angle can be used directly float lightSolidAngle = _DirectionalLightAngle; #else // Compute the light vector @@ -141,4 +141,4 @@ void BILATERAL_FILTER(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupT float3 finalColor = colorSum / wSum; _DenoiseOutputTextureRW[COORD_TEXTURE2D_X(centerCoord)] = float4(finalColor, 1.0); #endif -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute index e9810b74bb2..c4d03d8312f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute @@ -9,7 +9,7 @@ #pragma kernel CopyHistorySingleArray COPY_HISTORY=CopyHistorySingleArray SINGLE_CHANNEL OUTPUT_IS_ARRAY #pragma kernel CopyHistorySingleArrayNoValidity COPY_HISTORY=CopyHistorySingleArrayNoValidity SINGLE_CHANNEL OUTPUT_IS_ARRAY NO_VALIDITY -#pragma kernel CopyHistoryColor COPY_HISTORY=CopyHistoryColor +#pragma kernel CopyHistoryColor COPY_HISTORY=CopyHistoryColor #pragma kernel CopyHistoryColorArray COPY_HISTORY=CopyHistoryColorArray OUTPUT_IS_ARRAY // Common includes @@ -52,7 +52,7 @@ float _HistoryValidity; // The maximal normal difference threshold #define MAX_NORMAL_DIFFERENCE 0.65 // The minimal motion distance -#define MINIMAL_MOTION_DISTANCE 0.001 +#define MINIMAL_MOTION_DISTANCE 0.001 [numthreads(TEMPORAL_FILTER_TILE_SIZE, TEMPORAL_FILTER_TILE_SIZE, 1)] void ValidateHistory(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupThreadId : SV_GroupThreadID, uint2 groupId : SV_GroupID) @@ -120,14 +120,14 @@ void ValidateHistory(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 groupTh float4 historyNormal = LOAD_TEXTURE2D_X(_HistoryNormalTexture, historyTapCoord); NormalData historyNormalData; DecodeFromNormalBuffer(historyNormal, historyNormalData); - + // If the current normal is too different from the previous one, discard the history. if (dot(normalData.normalWS, historyNormalData.normalWS) < MAX_NORMAL_DIFFERENCE) { _ValidationBufferRW[COORD_TEXTURE2D_X(centerCoord)] = 0; return; } - + // We sample the velocity buffer, if not null float sampleVelocity = LOAD_TEXTURE2D_X(_VelocityBuffer, centerCoord).r; if (sampleVelocity > MINIMAL_MOTION_DISTANCE) @@ -209,7 +209,7 @@ void TEMPORAL_ACCUMULATION(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 g float sampleCount = history.w; #endif #endif - + // Get the velocity of the current sample float sampleVelocity = LOAD_TEXTURE2D_X(_VelocityBuffer, centerCoord).r; @@ -265,10 +265,10 @@ void COPY_HISTORY(uint3 dispatchThreadId : SV_DispatchThreadID) #endif #if SINGLE_CHANNEL - _DenoiseOutputTextureRW[targetPixel] = (1.0 - _DenoisingHistoryMask) * previousHistoryValues + _DenoiseOutputTextureRW[targetPixel] = (1.0 - _DenoisingHistoryMask) * previousHistoryValues + _DenoisingHistoryMask * LOAD_TEXTURE2D_X(_DenoiseInputTexture, dispatchThreadId.xy).x; #if !defined(NO_VALIDITY) - _ValidityOutputTextureRW[targetPixel] = (1.0 - _DenoisingHistoryMask) * previousValidityValues + _ValidityOutputTextureRW[targetPixel] = (1.0 - _DenoisingHistoryMask) * previousValidityValues + _DenoisingHistoryMask * LOAD_TEXTURE2D_X(_DenoiseInputTexture, dispatchThreadId.xy).y; #endif #else diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/OnlineVariance.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/OnlineVariance.hlsl index 0235bc2c003..bc9e9380cca 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/OnlineVariance.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/OnlineVariance.hlsl @@ -33,7 +33,7 @@ void PushValue(inout VarianceEstimator variance, float value) variance.newS = variance.oldS + (value - variance.oldM)*(value - variance.newM); // set up for next iteration - variance.oldM = variance.newM; + variance.oldM = variance.newM; variance.oldS = variance.newS; } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingCommon.hlsl index 51b7f2edb5d..05d569609e4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingCommon.hlsl @@ -49,4 +49,4 @@ struct StandardBSDFData uint isUnlit; }; -#endif // RAY_TRACING_COMMON_HLSL \ No newline at end of file +#endif // RAY_TRACING_COMMON_HLSL diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingLightCluster.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingLightCluster.hlsl index 8f274c8584a..72635f517b4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingLightCluster.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingLightCluster.hlsl @@ -2,32 +2,32 @@ uint GetTotalLightClusterCellCount(int cellIndex) { - return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 0]; + return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 0]; } uint GetPunctualLightClusterCellCount(int cellIndex) { - return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 1]; + return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 1]; } uint GetAreaLightClusterCellCount(int cellIndex) { - return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 2]; + return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 2]; } uint GetEnvLightClusterCellCount(int cellIndex) { - return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 3]; + return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 3]; } uint GetLightClusterCellLightByIndex(int cellIndex, int lightIndex) { - return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 4 + lightIndex]; + return _RaytracingLightCluster[cellIndex * (_LightPerCellCount + 4) + 4 + lightIndex]; } bool PointInsideCluster(float3 positionWS) { - return !(positionWS.x < _MinClusterPos.x || positionWS.y < _MinClusterPos.y || positionWS.z < _MinClusterPos.z + return !(positionWS.x < _MinClusterPos.x || positionWS.y < _MinClusterPos.y || positionWS.z < _MinClusterPos.z || positionWS.x > _MaxClusterPos.x || positionWS.y > _MaxClusterPos.y || positionWS.z > _MaxClusterPos.z); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingFragInputs.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingFragInputs.hlsl index 7996a62c8e9..a0107a09b94 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingFragInputs.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingFragInputs.hlsl @@ -1,17 +1,17 @@ // FIXME: Should probably be renamed as we don't need rayIntersection as input anymore (neither do we need incidentDirection) void BuildFragInputsFromIntersection(IntersectionVertex currentVertex, float3 incidentDirection, out FragInputs outFragInputs) { - outFragInputs.positionSS = float4(0.0, 0.0, 0.0, 0.0); - outFragInputs.positionRWS = WorldRayOrigin() + WorldRayDirection() * RayTCurrent(); - outFragInputs.texCoord0 = currentVertex.texCoord0; - outFragInputs.texCoord1 = currentVertex.texCoord1; - outFragInputs.texCoord2 = currentVertex.texCoord2; - outFragInputs.texCoord3 = currentVertex.texCoord3; - outFragInputs.color = currentVertex.color; + outFragInputs.positionSS = float4(0.0, 0.0, 0.0, 0.0); + outFragInputs.positionRWS = WorldRayOrigin() + WorldRayDirection() * RayTCurrent(); + outFragInputs.texCoord0 = currentVertex.texCoord0; + outFragInputs.texCoord1 = currentVertex.texCoord1; + outFragInputs.texCoord2 = currentVertex.texCoord2; + outFragInputs.texCoord3 = currentVertex.texCoord3; + outFragInputs.color = currentVertex.color; float3 normalWS = normalize(mul(currentVertex.normalOS, (float3x3)WorldToObject3x4())); - float3 tangentWS = normalize(mul(currentVertex.tangentOS.xyz, (float3x3)WorldToObject3x4())); - outFragInputs.tangentToWorld = CreateTangentToWorld(normalWS, tangentWS, sign(currentVertex.tangentOS.w)); + float3 tangentWS = normalize(mul(currentVertex.tangentOS.xyz, (float3x3)WorldToObject3x4())); + outFragInputs.tangentToWorld = CreateTangentToWorld(normalWS, tangentWS, sign(currentVertex.tangentOS.w)); - outFragInputs.isFrontFace = dot(incidentDirection, outFragInputs.tangentToWorld[2]) < 0.0f; -} \ No newline at end of file + outFragInputs.isFrontFace = dot(incidentDirection, outFragInputs.tangentToWorld[2]) < 0.0f; +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingIntersection.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingIntersection.hlsl index d9305a82e8f..0f1cfacb0c8 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingIntersection.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingIntersection.hlsl @@ -7,39 +7,39 @@ // Raycone structure that defines the stateof the ray struct RayCone { - float width; - float spreadAngle; + float width; + float spreadAngle; }; // Structure that defines the current state of the intersection struct RayIntersection { - // Origin of the current ray -- FIXME: can be obtained by WorldRayPosition(), should we remove it? - float3 origin; - // Direction of the current ray -- FIXME: can be obtained by WorldRayDirection(), should we remove it? - float3 incidentDirection; - // Distance of the intersection - float t; - // Value that holds the color of the ray - float3 color; - // Cone representation of the ray - RayCone cone; - // The remaining available depth for the current Ray - uint remainingDepth; - // Current sample index - uint sampleIndex; - // Ray counter (used for multibounce) - uint rayCount; - // Pixel coordinate from which the initial ray was launched - uint2 pixelCoord; - // Velocity for the intersection point - float velocity; + // Origin of the current ray -- FIXME: can be obtained by WorldRayPosition(), should we remove it? + float3 origin; + // Direction of the current ray -- FIXME: can be obtained by WorldRayDirection(), should we remove it? + float3 incidentDirection; + // Distance of the intersection + float t; + // Value that holds the color of the ray + float3 color; + // Cone representation of the ray + RayCone cone; + // The remaining available depth for the current Ray + uint remainingDepth; + // Current sample index + uint sampleIndex; + // Ray counter (used for multibounce) + uint rayCount; + // Pixel coordinate from which the initial ray was launched + uint2 pixelCoord; + // Velocity for the intersection point + float velocity; }; struct AttributeData { - // Barycentric value of the intersection - float2 barycentrics; + // Barycentric value of the intersection + float2 barycentrics; }; // Macro that interpolate any attribute using barycentric coordinates @@ -48,24 +48,24 @@ struct AttributeData // Structure to fill for intersections struct IntersectionVertex { - // Object space normal of the vertex - float3 normalOS; - // Object space tangent of the vertex - float4 tangentOS; - // UV coordinates - float4 texCoord0; - float4 texCoord1; - float4 texCoord2; - float4 texCoord3; - float4 color; + // Object space normal of the vertex + float3 normalOS; + // Object space tangent of the vertex + float4 tangentOS; + // UV coordinates + float4 texCoord0; + float4 texCoord1; + float4 texCoord2; + float4 texCoord3; + float4 color; #ifdef USE_RAY_CONE_LOD - // Value used for LOD sampling - float triangleArea; - float texCoord0Area; - float texCoord1Area; - float texCoord2Area; - float texCoord3Area; + // Value used for LOD sampling + float triangleArea; + float texCoord0Area; + float texCoord1Area; + float texCoord2Area; + float texCoord3Area; #endif }; @@ -80,97 +80,97 @@ void FetchIntersectionVertex(uint vertexIndex, out IntersectionVertex outVertex) outVertex.tangentOS = 0.0; #endif - #ifdef ATTRIBUTES_NEED_TEXCOORD0 + #ifdef ATTRIBUTES_NEED_TEXCOORD0 outVertex.texCoord0 = UnityRayTracingFetchVertexAttribute4(vertexIndex, kVertexAttributeTexCoord0); #else outVertex.texCoord0 = 0.0; - #endif + #endif - #ifdef ATTRIBUTES_NEED_TEXCOORD1 + #ifdef ATTRIBUTES_NEED_TEXCOORD1 outVertex.texCoord1 = UnityRayTracingFetchVertexAttribute4(vertexIndex, kVertexAttributeTexCoord1); #else outVertex.texCoord1 = 0.0; - #endif + #endif - #ifdef ATTRIBUTES_NEED_TEXCOORD2 + #ifdef ATTRIBUTES_NEED_TEXCOORD2 outVertex.texCoord2 = UnityRayTracingFetchVertexAttribute4(vertexIndex, kVertexAttributeTexCoord2); - #else - outVertex.texCoord2 = 0.0; - #endif + #else + outVertex.texCoord2 = 0.0; + #endif - #ifdef ATTRIBUTES_NEED_TEXCOORD3 + #ifdef ATTRIBUTES_NEED_TEXCOORD3 outVertex.texCoord3 = UnityRayTracingFetchVertexAttribute4(vertexIndex, kVertexAttributeTexCoord3); - #else - outVertex.texCoord3 = 0.0; - #endif + #else + outVertex.texCoord3 = 0.0; + #endif - #ifdef ATTRIBUTES_NEED_COLOR + #ifdef ATTRIBUTES_NEED_COLOR outVertex.color = UnityRayTracingFetchVertexAttribute4(vertexIndex, kVertexAttributeColor); - #else - outVertex.color = 0.0; - #endif + #else + outVertex.color = 0.0; + #endif } void GetCurrentIntersectionVertex(AttributeData attributeData, out IntersectionVertex outVertex) { - // Fetch the indices of the currentr triangle - uint3 triangleIndices = UnityRayTracingFetchTriangleIndices(PrimitiveIndex()); + // Fetch the indices of the currentr triangle + uint3 triangleIndices = UnityRayTracingFetchTriangleIndices(PrimitiveIndex()); - // Fetch the 3 vertices - IntersectionVertex v0, v1, v2; - FetchIntersectionVertex(triangleIndices.x, v0); - FetchIntersectionVertex(triangleIndices.y, v1); - FetchIntersectionVertex(triangleIndices.z, v2); + // Fetch the 3 vertices + IntersectionVertex v0, v1, v2; + FetchIntersectionVertex(triangleIndices.x, v0); + FetchIntersectionVertex(triangleIndices.y, v1); + FetchIntersectionVertex(triangleIndices.z, v2); - // Compute the full barycentric coordinates - float3 barycentricCoordinates = float3(1.0 - attributeData.barycentrics.x - attributeData.barycentrics.y, attributeData.barycentrics.x, attributeData.barycentrics.y); + // Compute the full barycentric coordinates + float3 barycentricCoordinates = float3(1.0 - attributeData.barycentrics.x - attributeData.barycentrics.y, attributeData.barycentrics.x, attributeData.barycentrics.y); + + // Interpolate all the data + outVertex.normalOS = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.normalOS, v1.normalOS, v2.normalOS, barycentricCoordinates); - // Interpolate all the data - outVertex.normalOS = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.normalOS, v1.normalOS, v2.normalOS, barycentricCoordinates); - #ifdef ATTRIBUTES_NEED_TANGENT - outVertex.tangentOS = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.tangentOS, v1.tangentOS, v2.tangentOS, barycentricCoordinates); - #else - outVertex.tangentOS = 0.0; - #endif - - #ifdef ATTRIBUTES_NEED_TEXCOORD0 - outVertex.texCoord0 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord0, v1.texCoord0, v2.texCoord0, barycentricCoordinates); - #else - outVertex.texCoord0 = 0.0; - #endif - - #ifdef ATTRIBUTES_NEED_TEXCOORD1 - outVertex.texCoord1 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord1, v1.texCoord1, v2.texCoord1, barycentricCoordinates); - #else - outVertex.texCoord1 = 0.0; - #endif - - #ifdef ATTRIBUTES_NEED_TEXCOORD2 - outVertex.texCoord2 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord2, v1.texCoord2, v2.texCoord2, barycentricCoordinates); - #else - outVertex.texCoord2 = 0.0; - #endif - - #ifdef ATTRIBUTES_NEED_TEXCOORD3 - outVertex.texCoord3 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord3, v1.texCoord3, v2.texCoord3, barycentricCoordinates); - #else - outVertex.texCoord3 = 0.0; - #endif - - #ifdef ATTRIBUTES_NEED_COLOR - outVertex.color = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.color, v1.color, v2.color, barycentricCoordinates); - #else - outVertex.color = 0.0; - #endif + outVertex.tangentOS = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.tangentOS, v1.tangentOS, v2.tangentOS, barycentricCoordinates); + #else + outVertex.tangentOS = 0.0; + #endif + + #ifdef ATTRIBUTES_NEED_TEXCOORD0 + outVertex.texCoord0 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord0, v1.texCoord0, v2.texCoord0, barycentricCoordinates); + #else + outVertex.texCoord0 = 0.0; + #endif + + #ifdef ATTRIBUTES_NEED_TEXCOORD1 + outVertex.texCoord1 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord1, v1.texCoord1, v2.texCoord1, barycentricCoordinates); + #else + outVertex.texCoord1 = 0.0; + #endif + + #ifdef ATTRIBUTES_NEED_TEXCOORD2 + outVertex.texCoord2 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord2, v1.texCoord2, v2.texCoord2, barycentricCoordinates); + #else + outVertex.texCoord2 = 0.0; + #endif + + #ifdef ATTRIBUTES_NEED_TEXCOORD3 + outVertex.texCoord3 = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.texCoord3, v1.texCoord3, v2.texCoord3, barycentricCoordinates); + #else + outVertex.texCoord3 = 0.0; + #endif + + #ifdef ATTRIBUTES_NEED_COLOR + outVertex.color = INTERPOLATE_RAYTRACING_ATTRIBUTE(v0.color, v1.color, v2.color, barycentricCoordinates); + #else + outVertex.color = 0.0; + #endif #ifdef USE_RAY_CONE_LOD - // Compute the lambda value (area computed in object space) - outVertex.triangleArea = length(cross(v1.positionOS - v0.positionOS, v2.positionOS - v0.positionOS)); - outVertex.texCoord0Area = abs((v1.texCoord0.x - v0.texCoord0.x) * (v2.texCoord0.y - v0.texCoord0.y) - (v2.texCoord0.x - v0.texCoord0.x) * (v1.texCoord0.y - v0.texCoord0.y)); - outVertex.texCoord1Area = abs((v1.texCoord1.x - v0.texCoord1.x) * (v2.texCoord1.y - v0.texCoord1.y) - (v2.texCoord1.x - v0.texCoord1.x) * (v1.texCoord1.y - v0.texCoord1.y)); - outVertex.texCoord2Area = abs((v1.texCoord2.x - v0.texCoord2.x) * (v2.texCoord2.y - v0.texCoord2.y) - (v2.texCoord2.x - v0.texCoord2.x) * (v1.texCoord2.y - v0.texCoord2.y)); - outVertex.texCoord3Area = abs((v1.texCoord3.x - v0.texCoord3.x) * (v2.texCoord3.y - v0.texCoord3.y) - (v2.texCoord3.x - v0.texCoord3.x) * (v1.texCoord3.y - v0.texCoord3.y)); + // Compute the lambda value (area computed in object space) + outVertex.triangleArea = length(cross(v1.positionOS - v0.positionOS, v2.positionOS - v0.positionOS)); + outVertex.texCoord0Area = abs((v1.texCoord0.x - v0.texCoord0.x) * (v2.texCoord0.y - v0.texCoord0.y) - (v2.texCoord0.x - v0.texCoord0.x) * (v1.texCoord0.y - v0.texCoord0.y)); + outVertex.texCoord1Area = abs((v1.texCoord1.x - v0.texCoord1.x) * (v2.texCoord1.y - v0.texCoord1.y) - (v2.texCoord1.x - v0.texCoord1.x) * (v1.texCoord1.y - v0.texCoord1.y)); + outVertex.texCoord2Area = abs((v1.texCoord2.x - v0.texCoord2.x) * (v2.texCoord2.y - v0.texCoord2.y) - (v2.texCoord2.x - v0.texCoord2.x) * (v1.texCoord2.y - v0.texCoord2.y)); + outVertex.texCoord3Area = abs((v1.texCoord3.x - v0.texCoord3.x) * (v2.texCoord3.y - v0.texCoord3.y) - (v2.texCoord3.x - v0.texCoord3.x) * (v1.texCoord3.y - v0.texCoord3.y)); #endif } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute index a1a1bf1e5c2..0de82b4e769 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute @@ -80,7 +80,7 @@ void RaytracingLightCluster(uint3 threadID : SV_GroupThreadID, uint3 groupId : S { // When the shape we are processing is a sphere, the radius is stored in the three channels float squareRange = currentLight.range.x * currentLight.range.x; - + // So basically we need to flag this cell if one of the corners of the cell happens to be in the sphere for(uint cIdx = 0; cIdx < 8; ++cIdx) { @@ -94,8 +94,8 @@ void RaytracingLightCluster(uint3 threadID : SV_GroupThreadID, uint3 groupId : S } // One additional case that we need to check is: Is the light inside the cell? - if (!intersects) - { + if (!intersects) + { float3 distanceToCenter = abs(cellCenterPosition - currentLight.position) * 2.0; intersects = (distanceToCenter.x < _ClusterCellSize.x) && (distanceToCenter.y < _ClusterCellSize.y) && (distanceToCenter.z < _ClusterCellSize.z); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl index 9e1c8b2b5a9..8ed9c0ea233 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl @@ -4,7 +4,7 @@ void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, BuiltinData builtinData, float reflectionHierarchyWeight, float refractionHierarchyWeight, float3 reflection, float3 transmission, - out LightLoopOutput lightLoopOutput) + out LightLoopOutput lightLoopOutput) { // Init LightLoop output structure ZERO_INITIALIZE(LightLoopOutput, lightLoopOutput); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingMacros.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingMacros.hlsl index 3dbf5fd05df..dd7105a1a94 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingMacros.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingMacros.hlsl @@ -1,11 +1,11 @@ #ifdef SAMPLE_TEXTURE2D #undef SAMPLE_TEXTURE2D -#define SAMPLE_TEXTURE2D(textureName, samplerName, coord2) textureName.SampleLevel(samplerName, coord2, 0) +#define SAMPLE_TEXTURE2D(textureName, samplerName, coord2) textureName.SampleLevel(samplerName, coord2, 0) #endif #ifdef SAMPLE_TEXTURE3D #undef SAMPLE_TEXTURE3D -#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.SampleLevel(samplerName, coord3, 0) +#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.SampleLevel(samplerName, coord3, 0) #endif #ifdef SAMPLE_TEXTURECUBE_ARRAY diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingMIS.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingMIS.hlsl index 61cc714514c..e18f4738795 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingMIS.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingMIS.hlsl @@ -86,7 +86,7 @@ void InitSphericalQuad(LightData areaLightData, float3 positionWS, out SphQuad s bool InitSphericalQuad(LightData areaLightData, float3 positionWS, float3 normalWS, inout SphQuad squad) { ZERO_INITIALIZE(SphQuad, squad); - + // Dimension of the area light float halfWidth = areaLightData.size.x * 0.5; float halfHeight = areaLightData.size.y * 0.5; @@ -106,7 +106,7 @@ bool InitSphericalQuad(LightData areaLightData, float3 positionWS, float3 normal { return false; } - + float3 ex = v1 - v0; float3 ey = v3 - v0; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute index 6b6548c2e94..bfea90ec1e9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute @@ -634,7 +634,7 @@ void RaytracingSpotShadowSample(uint3 dispatchThreadId : SV_DispatchThreadID, ui float samplePDF = 1.0; if (_RaytracingLightRadius > 0.001) { - SampleSphericalCone(lightData.positionRWS, _RaytracingLightRadius, lightData.forward, + SampleSphericalCone(lightData.positionRWS, _RaytracingLightRadius, lightData.forward, _RaytracingSpotAngle, noiseValue.x, noiseValue.y, posInput.positionWS, normalData.normalWS, lightPosition, samplePDF); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute index dcffc8d49ea..dd30259e7fb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute @@ -81,7 +81,7 @@ void AreaShadowHistoryCopy(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 g float4 previousValue = _AreaShadowHistoryRW[uint3(centerCoord, INDEX_TEXTURE2D_ARRAY_X(_DenoisingHistorySlice))]; // Only replace where the mask is 1.0 - _AreaShadowHistoryRW[uint3(centerCoord, INDEX_TEXTURE2D_ARRAY_X(_DenoisingHistorySlice))] = (1.0 - _DenoisingHistoryMask) * previousValue + _AreaShadowHistoryRW[uint3(centerCoord, INDEX_TEXTURE2D_ARRAY_X(_DenoisingHistorySlice))] = (1.0 - _DenoisingHistoryMask) * previousValue + _DenoisingHistoryMaskSn * LOAD_TEXTURE2D_X(_DenoiseInputTexture, centerCoord).x + _DenoisingHistoryMaskUn * LOAD_TEXTURE2D_X(_DenoiseInputTexture, centerCoord).y; } @@ -165,7 +165,7 @@ void AreaShadowApplyTAA(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 grou color = FastTonemapPerChannelInvert(lerp(color, history, feedback)); color = clamp(color, 0.0, CLAMP_MAX); - + _DenoiseOutputTextureRW[COORD_TEXTURE2D_X(centerCoord)] = float4(color, LOAD_TEXTURE2D_X(_AnalyticProbBuffer, centerCoord).x, 1.0); } @@ -478,7 +478,7 @@ void AREA_SHADOW_DENOISE(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gro // We should not tap outside of the screen (given that its a unit, if we go below zero we wrap around) if ((int)tapCoord.x > _ScreenSize.x || (int)tapCoord.y > _ScreenSize.y) continue; - + // Compute the weight (skip computation for the center) const float w = r ? gaussian(r, sigma) * ComputeBilateralWeight(center, TapBilateralData(tapCoord)) : 1.0; @@ -509,7 +509,7 @@ void AreaShadowNoDenoise(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gro // Compute the shadow value that we need to store float shadowValue = inputValues.y > 0.0 ? inputValues.x / inputValues.y : 0.0; - + // Only override when the mask is 1.0 _DenoiseOutputTextureRW[COORD_TEXTURE2D_X(currentCoord)] = float4(shadowValue,shadowValue,shadowValue, 1.0); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalCone.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalCone.hlsl index b9b990b1877..5375b79fe24 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalCone.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalCone.hlsl @@ -1,6 +1,6 @@ void SampleSphericalCone(float3 conePosition, float coneRadius, float3 coneDir, float coneAngle, - float u, float v, + float u, float v, float3 position, float3 normal, out float3 outPosition, out float outPDF) { // Compute the half angle cosine diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalQuad.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalQuad.hlsl index 0efd8da4703..f0c73c6d9d2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalQuad.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalQuad.hlsl @@ -4,14 +4,14 @@ bool IntersectPlane(float3 ray_origin, float3 ray_dir, float3 pos, float3 normal, out float t) { - float denom = dot(normal, ray_dir); - if (abs(denom) > PLANE_INTERSECTION_EPSILON) - { - float3 d = pos - ray_origin; - t = dot(d, normal) / denom; - return (t >= 0); - } - return false; + float denom = dot(normal, ray_dir); + if (abs(denom) > PLANE_INTERSECTION_EPSILON) + { + float3 d = pos - ray_origin; + t = dot(d, normal) / denom; + return (t >= 0); + } + return false; } struct SphQuad @@ -71,12 +71,12 @@ void SphQuadInit(float3 s, float3 ex, float3 ey, float3 o, out SphQuad squad) float g1 = FastACos(-dot(n1, n2)); float g2 = FastACos(-dot(n2, n3)); float g3 = FastACos(-dot(n3, n0)); - + // compute predefined constants squad.b0 = n0.z; squad.b1 = n2.z; squad.b0sq = squad.b0 * squad.b0; - squad.k = 2.0f * PI - g2 - g3; + squad.k = 2.0f * PI - g2 - g3; // compute solid angle from internal angles squad.S = g0 + g1 - squad.k; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalSphere.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalSphere.hlsl index b0192dbd44b..7e4821b75bb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalSphere.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/SphericalSphere.hlsl @@ -1,13 +1,13 @@ float dist2(float3 vecA, float3 vecB) { - float3 res = vecA - vecB; - return dot(res, res); + float3 res = vecA - vecB; + return dot(res, res); } float dist(float3 vecA, float3 vecB) { - float3 res = vecA - vecB; - return length(res); + float3 res = vecA - vecB; + return length(res); } void SampleSphericalSphere(float3 spherePosition, float sphereRadius, float u, float v, float3 position, float3 normal, out float3 outPosition, out float outPDF) @@ -32,7 +32,7 @@ void SampleSphericalSphere(float3 spherePosition, float sphereRadius, float u, f // Compute surface normal and sampled point on sphere. float cphi = cos(phi); float sphi = sin(phi); - float3 nWorld = sinAlpha * cphi * -localToWorld[0] + sinAlpha * sphi * -localToWorld[1] + cosAlpha * -wc; + float3 nWorld = sinAlpha * cphi * -localToWorld[0] + sinAlpha * sphi * -localToWorld[1] + cosAlpha * -wc; // Compute the world position of the sample outPosition = sphereRadius * nWorld + spherePosition; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute index bd05dac8f37..4167c71c550 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute @@ -55,8 +55,8 @@ void BlendSubSurfaceData(uint3 dispatchThreadId : SV_DispatchThreadID, uint2 gro // Blend and we are done _DiffuseLightingTextureRW[COORD_TEXTURE2D_X(currentCoord)] = float4(lerp(_DiffuseLightingTextureRW[COORD_TEXTURE2D_X(currentCoord)].xyz * albedo * GetInverseCurrentExposureMultiplier() - , _SubSurfaceLightingBuffer[COORD_TEXTURE2D_X(currentCoord)].xyz - , sssData.subsurfaceMask), 1.0); + , _SubSurfaceLightingBuffer[COORD_TEXTURE2D_X(currentCoord)].xyz + , sssData.subsurfaceMask), 1.0); } // The buffer of indirect diffuse lighting that shall be used @@ -84,4 +84,4 @@ void BlendSubSurfaceDataWithGI(uint3 dispatchThreadId : SV_DispatchThreadID, uin _DiffuseLightingTextureRW[COORD_TEXTURE2D_X(currentCoord)] = float4(lerp(_DiffuseLightingTextureRW[COORD_TEXTURE2D_X(currentCoord)].xyz * albedo * GetInverseCurrentExposureMultiplier() , _SubSurfaceLightingBuffer[COORD_TEXTURE2D_X(currentCoord)].xyz + indirectDiffuse , sssData.subsurfaceMask), 1.0); -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequest.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequest.cs index 97bedec4d4f..27e3e946286 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequest.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequest.cs @@ -64,8 +64,8 @@ public unsafe struct AOVRequest { get { - fixed (AOVRequest* pThis = &this) - return pThis; + fixed(AOVRequest* pThis = &this) + return pThis; } } @@ -178,4 +178,3 @@ public void FillDebugData(DebugDisplaySettings debug) } } } - diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs index 23e1635c372..2acba0f4600 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestData.cs @@ -153,7 +153,6 @@ public void AllocateTargetTexturesIfRequired(ref List textures, ref Li Debug.LogError("Allocation for requested AOVBuffers ID: " + bufferId.ToString() + " have fail. Please ensure the callback allocator do the correct allocation."); } } - } if (m_CustomPassAOVBuffers != null) @@ -232,10 +231,10 @@ List targets passData.target = targets[index]; builder.SetRenderFunc( - (PushCameraTexturePassData data, RenderGraphContext ctx) => - { - HDUtils.BlitCameraTexture(ctx.cmd, data.source, data.target); - }); + (PushCameraTexturePassData data, RenderGraphContext ctx) => + { + HDUtils.BlitCameraTexture(ctx.cmd, data.source, data.target); + }); } } @@ -326,13 +325,13 @@ List targets passData.target = targets[index]; builder.SetRenderFunc( - (PushCustomPassTexturePassData data, RenderGraphContext ctx) => - { - if (data.customPassSource != null) - HDUtils.BlitCameraTexture(ctx.cmd, data.customPassSource, data.target); - else - HDUtils.BlitCameraTexture(ctx.cmd, data.source, data.target); - }); + (PushCustomPassTexturePassData data, RenderGraphContext ctx) => + { + if (data.customPassSource != null) + HDUtils.BlitCameraTexture(ctx.cmd, data.customPassSource, data.target); + else + HDUtils.BlitCameraTexture(ctx.cmd, data.source, data.target); + }); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestDataCollection.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestDataCollection.cs index 86a20d6c08c..17ee6f9054d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestDataCollection.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/AOVRequestDataCollection.cs @@ -14,7 +14,7 @@ public class AOVRequestDataCollection : IEnumerable, IDisposable /// Build a new collection from requests. /// Requests to include in the collection. public AOVRequestDataCollection(List aovRequestData) - // Transfer ownership of the list + // Transfer ownership of the list => m_AOVRequestData = aovRequestData; /// Enumerate the frame passes. diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/RenderOutputProperties.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/RenderOutputProperties.cs index 09512f1f488..8409d07bf0d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/RenderOutputProperties.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/AOV/RenderOutputProperties.cs @@ -25,9 +25,9 @@ public RenderOutputProperties(Vector2Int outputSize, Matrix4x4 cameraToWorldMatr /// The camera to use. internal static RenderOutputProperties From(HDCamera hdCamera) => new RenderOutputProperties( - new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight), - hdCamera.camera.cameraToWorldMatrix, - hdCamera.mainViewConstants.projMatrix + new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight), + hdCamera.camera.cameraToWorldMatrix, + hdCamera.mainViewConstants.projMatrix ); } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPass.cs index 4be291aa1fa..837910b6a4c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPass.cs @@ -262,50 +262,50 @@ internal void ExecuteInternal(RenderGraph renderGraph, HDCamera hdCamera, Cullin this.currentRenderTarget = ReadRenderTargets(builder, targets); builder.SetRenderFunc( - (ExecutePassData data, RenderGraphContext ctx) => - { - var customPass = data.customPass; - - ctx.cmd.SetGlobalFloat(HDShaderIDs._CustomPassInjectionPoint, (float)customPass.injectionPoint); - if (customPass.currentRenderTarget.colorBufferRG.IsValid() && customPass.injectionPoint == CustomPassInjectionPoint.AfterPostProcess) - ctx.cmd.SetGlobalTexture(HDShaderIDs._AfterPostProcessColorBuffer, customPass.currentRenderTarget.colorBufferRG); - - if (customPass.currentRenderTarget.motionVectorBufferRG.IsValid() && (customPass.injectionPoint == CustomPassInjectionPoint.BeforePostProcess || customPass.injectionPoint == CustomPassInjectionPoint.AfterPostProcess)) - ctx.cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, customPass.currentRenderTarget.motionVectorBufferRG); - - if (!customPass.isSetup) + (ExecutePassData data, RenderGraphContext ctx) => { - customPass.Setup(ctx.renderContext, ctx.cmd); - customPass.isSetup = true; - // TODO RENDERGRAPH: We still need to allocate this otherwise it would be null when switching off render graph (because isSetup stays true). - // We can remove the member altogether when we remove the non render graph code path. - customPass.userMaterialPropertyBlock = new MaterialPropertyBlock(); - } - - customPass.SetCustomPassTarget(ctx.cmd); - - var outputColorBuffer = customPass.currentRenderTarget.colorBufferRG; - - // Create the custom pass context: - CustomPassContext customPassCtx = new CustomPassContext( - ctx.renderContext, ctx.cmd, data.hdCamera, - data.cullingResult, - outputColorBuffer, - customPass.currentRenderTarget.depthBufferRG, - customPass.currentRenderTarget.normalBufferRG, - customPass.currentRenderTarget.customColorBuffer, - customPass.currentRenderTarget.customDepthBuffer, - ctx.renderGraphPool.GetTempMaterialPropertyBlock() + var customPass = data.customPass; + + ctx.cmd.SetGlobalFloat(HDShaderIDs._CustomPassInjectionPoint, (float)customPass.injectionPoint); + if (customPass.currentRenderTarget.colorBufferRG.IsValid() && customPass.injectionPoint == CustomPassInjectionPoint.AfterPostProcess) + ctx.cmd.SetGlobalTexture(HDShaderIDs._AfterPostProcessColorBuffer, customPass.currentRenderTarget.colorBufferRG); + + if (customPass.currentRenderTarget.motionVectorBufferRG.IsValid() && (customPass.injectionPoint == CustomPassInjectionPoint.BeforePostProcess || customPass.injectionPoint == CustomPassInjectionPoint.AfterPostProcess)) + ctx.cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, customPass.currentRenderTarget.motionVectorBufferRG); + + if (!customPass.isSetup) + { + customPass.Setup(ctx.renderContext, ctx.cmd); + customPass.isSetup = true; + // TODO RENDERGRAPH: We still need to allocate this otherwise it would be null when switching off render graph (because isSetup stays true). + // We can remove the member altogether when we remove the non render graph code path. + customPass.userMaterialPropertyBlock = new MaterialPropertyBlock(); + } + + customPass.SetCustomPassTarget(ctx.cmd); + + var outputColorBuffer = customPass.currentRenderTarget.colorBufferRG; + + // Create the custom pass context: + CustomPassContext customPassCtx = new CustomPassContext( + ctx.renderContext, ctx.cmd, data.hdCamera, + data.cullingResult, + outputColorBuffer, + customPass.currentRenderTarget.depthBufferRG, + customPass.currentRenderTarget.normalBufferRG, + customPass.currentRenderTarget.customColorBuffer, + customPass.currentRenderTarget.customDepthBuffer, + ctx.renderGraphPool.GetTempMaterialPropertyBlock() ); - customPass.isExecuting = true; - customPass.Execute(customPassCtx); - customPass.isExecuting = false; + customPass.isExecuting = true; + customPass.Execute(customPassCtx); + customPass.isExecuting = false; - // Set back the camera color buffer if we were using a custom buffer as target - if (customPass.targetDepthBuffer != TargetBuffer.Camera) - CoreUtils.SetRenderTarget(ctx.cmd, outputColorBuffer); - }); + // Set back the camera color buffer if we were using a custom buffer as target + if (customPass.targetDepthBuffer != TargetBuffer.Camera) + CoreUtils.SetRenderTarget(ctx.cmd, outputColorBuffer); + }); } } @@ -331,8 +331,8 @@ bool IsMSAAEnabled(HDCamera hdCamera) // if MSAA is enabled and the current injection point is before transparent. bool msaa = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MSAA); msaa &= injectionPoint == CustomPassInjectionPoint.BeforePreRefraction - || injectionPoint == CustomPassInjectionPoint.BeforeTransparent - || injectionPoint == CustomPassInjectionPoint.AfterOpaqueDepthAndNormal; + || injectionPoint == CustomPassInjectionPoint.BeforeTransparent + || injectionPoint == CustomPassInjectionPoint.AfterOpaqueDepthAndNormal; return msaa; } @@ -395,7 +395,7 @@ protected virtual void Execute(ScriptableRenderContext renderContext, CommandBuf protected virtual void Execute(CustomPassContext ctx) { #pragma warning disable CS0618 // Member is obsolete - Execute(ctx.renderContext, ctx.cmd, ctx.hdCamera, ctx.cullingResults); + Execute(ctx.renderContext, ctx.cmd, ctx.hdCamera, ctx.cullingResults); #pragma warning restore CS0618 } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl index fb5e97ceed7..f964a156c7d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl @@ -65,4 +65,4 @@ Varyings Vert(Attributes input) return output; } -#endif // CUSTOM_PASS_COMMON \ No newline at end of file +#endif // CUSTOM_PASS_COMMON diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassContext.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassContext.cs index 34e97601f4c..585fe6e8e8c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassContext.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassContext.cs @@ -76,4 +76,4 @@ internal CustomPassContext( this.propertyBlock = propertyBlock; } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassInjectionPoint.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassInjectionPoint.cs index 012a32c83d1..382d4a5967d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassInjectionPoint.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassInjectionPoint.cs @@ -27,4 +27,4 @@ public enum CustomPassInjectionPoint /// This injection point is before HDRP renders post-processing and custom post-processing effects. AfterPostProcess = 3, } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderers.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderers.hlsl index d5fdc76aa94..72a8b54f757 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderers.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderers.hlsl @@ -26,4 +26,4 @@ float _CustomPassInjectionPoint; float _FadeValue; -#endif // CUSTOM_PASS_RENDERERS \ No newline at end of file +#endif // CUSTOM_PASS_RENDERERS diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader index 296f6e95fb3..e0c5c27e37a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader @@ -1,4 +1,4 @@ -Shader "Renderers/CustomPassRenderersUtils" +Shader "Renderers/CustomPassRenderersUtils" { Properties { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.cs index 5892a2c0c8f..04e36552c4d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.cs @@ -86,7 +86,7 @@ public static void DownSample(in CustomPassContext ctx, RTHandle source, RTHandl // Check if the texture provided is at least half of the size of source. if (destination.rt.width < source.rt.width / 2 || destination.rt.height < source.rt.height / 2) Debug.LogError("Destination for DownSample is too small, it needs to be at least half as big as source."); - if (source.rt.antiAliasing > 1 || destination.rt.antiAliasing > 1) + if (source.rt.antiAliasing > 1 || destination.rt.antiAliasing > 1) Debug.LogError($"DownSample is not supported with MSAA buffers"); using (new ProfilingScope(ctx.cmd, downSampleSampler)) @@ -127,7 +127,7 @@ public static void Copy(in CustomPassContext ctx, RTHandle source, RTHandle dest { if (source == destination) Debug.LogError("Can't copy the buffer. Source has to be different from the destination."); - if (source.rt.antiAliasing > 1 || destination.rt.antiAliasing > 1) + if (source.rt.antiAliasing > 1 || destination.rt.antiAliasing > 1) Debug.LogError($"Copy is not supported with MSAA buffers"); using (new ProfilingScope(ctx.cmd, copySampler)) @@ -216,7 +216,7 @@ public static void HorizontalGaussianBlur(in CustomPassContext ctx, RTHandle sou { if (source == destination) Debug.LogError("Can't blur the buffer. Source has to be different from the destination."); - if (source.rt.antiAliasing > 1 || destination.rt.antiAliasing > 1) + if (source.rt.antiAliasing > 1 || destination.rt.antiAliasing > 1) Debug.LogError($"GaussianBlur is not supported with MSAA buffers"); using (new ProfilingScope(ctx.cmd, horizontalBlurSampler)) @@ -333,7 +333,7 @@ public static void GaussianBlur(in CustomPassContext ctx, RTHandle source, RTHan /// number of weights you want to generate /// a GPU compute buffer containing the weights internal static ComputeBuffer GetGaussianWeights(int weightCount) - { + { float[] weights; ComputeBuffer gpuWeights; @@ -341,32 +341,32 @@ internal static ComputeBuffer GetGaussianWeights(int weightCount) return gpuWeights; weights = new float[weightCount]; - float integrationBound = 3; - float p = -integrationBound; + float integrationBound = 3; + float p = -integrationBound; float c = 0; float step = (1.0f / (float)weightCount) * integrationBound * 2; - for (int i = 0; i < weightCount; i++) - { - float w = (Gaussian(p) / (float)weightCount) * integrationBound * 2; + for (int i = 0; i < weightCount; i++) + { + float w = (Gaussian(p) / (float)weightCount) * integrationBound * 2; weights[i] = w; - p += step; + p += step; c += w; - } + } - // Gaussian function - float Gaussian(float x, float sigma = 1) - { - float a = 1.0f / Mathf.Sqrt(2 * Mathf.PI * sigma * sigma); - float b = Mathf.Exp(-(x * x) / (2 * sigma * sigma)); - return a * b; - } + // Gaussian function + float Gaussian(float x, float sigma = 1) + { + float a = 1.0f / Mathf.Sqrt(2 * Mathf.PI * sigma * sigma); + float b = Mathf.Exp(-(x * x) / (2 * sigma * sigma)); + return a * b; + } gpuWeights = new ComputeBuffer(weights.Length, sizeof(float)); gpuWeights.SetData(weights); gaussianWeightsCache[weightCount] = gpuWeights; return gpuWeights; - } + } /// /// Convert a Custom Pass render queue type to a RenderQueueRange that can be used in DrawRenderers @@ -578,7 +578,7 @@ internal static void SetRenderTargetWithScaleBias(in CustomPassContext ctx, Mate block.SetVector(HDShaderIDs._ViewPortSize, new Vector4(destSize.x, destSize.y, 1.0f / destSize.x, 1.0f / destSize.y)); block.SetVector(HDShaderIDs._ViewportScaleBias, new Vector4(1.0f / destScaleBias.x, 1.0f / destScaleBias.y, destScaleBias.z, destScaleBias.w)); } - + static void SetSourceSize(MaterialPropertyBlock block, RTHandle source) { Vector2 sourceSize = source.GetScaledSize(source.rtHandleProperties.currentViewportSize); @@ -586,4 +586,4 @@ static void SetSourceSize(MaterialPropertyBlock block, RTHandle source) block.SetVector(HDShaderIDs._SourceScaleFactor, new Vector4(source.scaleFactor.x, source.scaleFactor.y, 1.0f / source.scaleFactor.x, 1.0f / source.scaleFactor.y)); } } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassVolume.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassVolume.cs index fe008da625d..9914cfb048d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassVolume.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassVolume.cs @@ -100,6 +100,7 @@ void UpdateCustomPassVolumeVisibility() { visible = !UnityEditor.SceneVisibilityManager.instance.IsHidden(gameObject); } + #endif bool IsVisible(HDCamera hdCamera) @@ -113,7 +114,7 @@ bool IsVisible(HDCamera hdCamera) // We never execute volume if the layer is not within the culling layers of the camera if ((hdCamera.volumeLayerMask & (1 << gameObject.layer)) == 0) return false; - + return true; } @@ -429,6 +430,7 @@ void OnDrawGizmos() } } } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader index 338400e04e2..722ffbc5e8e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader @@ -93,7 +93,7 @@ Shader "Hidden/HDRP/ApplyDistortion" uint mipCeiled = ceil(mip); float texelsToClamp = (1u << mipCeiled); - + float2 uv = ClampAndScaleUV(distordedUV, _Size.zw, texelsToClamp); float4 sampled = SAMPLE_TEXTURE2D_X_LOD(_ColorPyramidTexture, s_trilinear_clamp_sampler, uv, mip); return sampled; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DrawRenderersCustomPass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DrawRenderersCustomPass.cs index 8aff33e8dd5..894688ac8bc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DrawRenderersCustomPass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DrawRenderersCustomPass.cs @@ -93,14 +93,16 @@ protected override void Setup(ScriptableRenderContext renderContext, CommandBuff if (String.IsNullOrEmpty(overrideMaterialPassName) && overrideMaterial != null) overrideMaterialPassName = overrideMaterial.GetPassName(overrideMaterialPassIndex); - forwardShaderTags = new ShaderTagId[] { + forwardShaderTags = new ShaderTagId[] + { HDShaderPassNames.s_ForwardName, // HD Lit shader HDShaderPassNames.s_ForwardOnlyName, // HD Unlit shader HDShaderPassNames.s_SRPDefaultUnlitName, // Cross SRP Unlit shader HDShaderPassNames.s_EmptyName, // Add an empty slot for the override material }; - depthShaderTags = new ShaderTagId[] { + depthShaderTags = new ShaderTagId[] + { HDShaderPassNames.s_DepthForwardOnlyName, HDShaderPassNames.s_DepthOnlyName, HDShaderPassNames.s_EmptyName, // Add an empty slot for the override material diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FullScreenCustomPass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FullScreenCustomPass.cs index 92a278997cf..6091a3e0c13 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FullScreenCustomPass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FullScreenCustomPass.cs @@ -54,7 +54,7 @@ protected override void Execute(CustomPassContext ctx) if (fetchColorBuffer) { ResolveMSAAColorBuffer(ctx.cmd, ctx.hdCamera); - // reset the render target to the UI + // reset the render target to the UI SetRenderTargetAuto(ctx.cmd); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute index 32e7152268d..cd1713556b4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute @@ -10,7 +10,7 @@ // In some cases we might want to avoid stopping integrating volumetric even if > max distance if the gradient is very big. -// Realistically, with the dilation step this was never seen as necessary. +// Realistically, with the dilation step this was never seen as necessary. #define GENERATE_GRADIENT 0 #if GENERATE_GRADIENT @@ -22,7 +22,7 @@ #endif #ifdef PLATFORM_LANE_COUNT -#define WAVE_SIZE PLATFORM_LANE_COUNT +#define WAVE_SIZE PLATFORM_LANE_COUNT #else #define WAVE_SIZE 64 #endif @@ -30,7 +30,7 @@ // --------------------------------- CBUFFER_START(cb) float4 _SrcOffsetAndLimit; -float _DilationWidth; +float _DilationWidth; CBUFFER_END #define _SrcLimit _SrcOffsetAndLimit.xy @@ -68,7 +68,7 @@ float PrepareDepthForOutput(float depth) // GetDepthToDownsample should be used to enforce the right depth is used. float ParallelReduction(uint gid, uint threadIdx, float depth) { -#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS +#ifdef PLATFORM_SUPPORTS_WAVE_INTRINSICS return WaveActiveMax(depth); #else gs_maxDepth[threadIdx] = depth; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MipGenerator.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MipGenerator.cs index afae9573f41..ee2591c635d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MipGenerator.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MipGenerator.cs @@ -68,7 +68,7 @@ public void RenderMinDepthPyramid(CommandBuffer cmd, RenderTexture texture, HDUt // and we don't support Min samplers either. So we are forced to perform 4x loads. for (int i = 1; i < info.mipLevelCount; i++) { - if (mip1AlreadyComputed && i == 1) continue; + if (mip1AlreadyComputed && i == 1) continue; Vector2Int dstSize = info.mipLevelSizes[i]; Vector2Int dstOffset = info.mipLevelOffsets[i]; @@ -86,8 +86,8 @@ public void RenderMinDepthPyramid(CommandBuffer cmd, RenderTexture texture, HDUt m_DstOffset[2] = 0; m_DstOffset[3] = 0; - cmd.SetComputeIntParams( cs, HDShaderIDs._SrcOffsetAndLimit, m_SrcOffset); - cmd.SetComputeIntParams( cs, HDShaderIDs._DstOffset, m_DstOffset); + cmd.SetComputeIntParams(cs, HDShaderIDs._SrcOffsetAndLimit, m_SrcOffset); + cmd.SetComputeIntParams(cs, HDShaderIDs._DstOffset, m_DstOffset); cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DepthMipChain, texture); cmd.DispatchCompute(cs, kernel, HDUtils.DivRoundUp(dstSize.x, 8), HDUtils.DivRoundUp(dstSize.y, 8), texture.volumeDepth); @@ -137,16 +137,16 @@ public int RenderColorGaussianPyramid(CommandBuffer cmd, Vector2Int size, Textur if (m_TempDownsamplePyramid[rtIndex] == null) { m_TempDownsamplePyramid[rtIndex] = RTHandles.Alloc( - Vector2.one * 0.5f, - sourceIsArray ? TextureXR.slices : 1, - dimension: source.dimension, - filterMode: FilterMode.Bilinear, - colorFormat: destination.graphicsFormat, - enableRandomWrite: false, - useMipMap: false, - enableMSAA: false, - useDynamicScale: true, - name: "Temporary Downsampled Pyramid" + Vector2.one * 0.5f, + sourceIsArray ? TextureXR.slices : 1, + dimension: source.dimension, + filterMode: FilterMode.Bilinear, + colorFormat: destination.graphicsFormat, + enableRandomWrite: false, + useMipMap: false, + enableMSAA: false, + useDynamicScale: true, + name: "Temporary Downsampled Pyramid" ); cmd.SetRenderTarget(m_TempDownsamplePyramid[rtIndex]); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader index 444647f28fd..6a39449b45a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader @@ -15,7 +15,7 @@ Shader "Hidden/HDRP/CameraMotionVectors" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/FragInputs.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VaryingMesh.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VertMesh.hlsl" - #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl" + #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl" struct Attributes { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs index 2a53fd38784..11770d32a30 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/SceneViewDrawMode.cs @@ -22,7 +22,7 @@ static private bool RejectDrawMode(SceneView.CameraMode cameraMode) cameraMode.drawMode == DrawCameraMode.DeferredNormal || cameraMode.drawMode == DrawCameraMode.ValidateAlbedo || cameraMode.drawMode == DrawCameraMode.ValidateMetalSpecular - ) + ) return false; return true; @@ -34,7 +34,7 @@ static void UpdateSceneViewStates() { if (sceneViewHaveValidateFunction.Contains(sceneView)) continue; - + sceneView.onValidateCameraMode += RejectDrawMode; sceneViewHaveValidateFunction.Add(sceneView); @@ -50,7 +50,7 @@ static public void SetupDrawMode() static public void ResetDrawMode() { EditorApplication.update -= UpdateSceneViewStates; - + foreach (var sceneView in sceneViewHaveValidateFunction) sceneView.onValidateCameraMode -= RejectDrawMode; sceneViewHaveValidateFunction.Clear(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs index 8ff5a87415f..97880a4fe0f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.Migration.cs @@ -206,7 +206,7 @@ internal static void MigrateFromClassVersion(ref ObsoleteFrameSettings oldFrameS { if ((val & oldFrameSettingsFormat.overrides) > 0) { - switch(val) + switch (val) { case ObsoleteFrameSettingsOverrides.Shadow: newFrameSettingsOverrideMask.mask[(int)FrameSettingsField.ShadowMaps] = true; @@ -344,6 +344,7 @@ internal static void MigrateFromClassVersion(ref ObsoleteFrameSettings oldFrameS //free space: oldFrameSettingsFormat = null; } + #pragma warning restore 618 // Type or member is obsolete internal static void MigrateToCustomPostprocessAndCustomPass(ref FrameSettings cameraFrameSettings) @@ -435,6 +436,6 @@ internal static void MigrateRoughDistortion(ref FrameSettings cameraFrameSetting internal static void MigrateVirtualTexturing(ref FrameSettings cameraFrameSettings) { cameraFrameSettings.SetEnabled(FrameSettingsField.VirtualTexturing, true); - } + } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs index b7a0b6c918a..eb0d409a638 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettings.cs @@ -261,19 +261,19 @@ public enum FrameSettingsField SSGI = 95, /// When enabled, Cameras using these Frame Settings render subsurface scattering (SSS) effects for GameObjects that use a SSS Material. [FrameSettingsField(1, customOrderInGroup: 46, autoName: SubsurfaceScattering, - tooltip: "When enabled, Cameras using these Frame Settings render subsurface scattering (SSS) effects for GameObjects that use a SSS Material (Depends on \"Subsurface Scattering\" in current HDRP Asset).")] + tooltip: "When enabled, Cameras using these Frame Settings render subsurface scattering (SSS) effects for GameObjects that use a SSS Material (Depends on \"Subsurface Scattering\" in current HDRP Asset).")] SubsurfaceScattering = 46, /// Configures the sample budget of the Subsurface Scattering algorithm using Quality Levels. You can either pick from one of the existing values in the Quality Settings, or request a custom number of samples. [FrameSettingsField(1, customOrderInGroup: 47, displayedName: "Quality Mode", positiveDependencies: new[] { SubsurfaceScattering }, type: FrameSettingsFieldAttribute.DisplayType.Others, targetType: typeof(SssQualityMode), - tooltip: "Configures the way the sample budget of the Subsurface Scattering algorithm is determined. You can either pick from one of the existing values in the Quality Settings, or request a custom number of samples.")] + tooltip: "Configures the way the sample budget of the Subsurface Scattering algorithm is determined. You can either pick from one of the existing values in the Quality Settings, or request a custom number of samples.")] SssQualityMode = 47, /// Sets the Quality Level of the Subsurface Scattering algorithm. [FrameSettingsField(1, customOrderInGroup: 48, displayedName: "Quality Level", positiveDependencies: new[] { SubsurfaceScattering }, type: FrameSettingsFieldAttribute.DisplayType.Others, - tooltip: "Sets the Quality Level of the Subsurface Scattering algorithm.")] + tooltip: "Sets the Quality Level of the Subsurface Scattering algorithm.")] SssQualityLevel = 48, /// Sets the custom sample budget of the Subsurface Scattering algorithm. [FrameSettingsField(1, customOrderInGroup: 49, displayedName: "Custom Sample Budget", positiveDependencies: new[] { SubsurfaceScattering }, type: FrameSettingsFieldAttribute.DisplayType.Others, - tooltip: "Sets the custom sample budget of the Subsurface Scattering algorithm.")] + tooltip: "Sets the custom sample budget of the Subsurface Scattering algorithm.")] SssCustomSampleBudget = 49, /// When enabled, Cameras using these Frame Settings render subsurface scattering (SSS) Materials with an added transmission effect (only if you enable Transmission on the SSS Material in the Material's Inspector). @@ -376,7 +376,8 @@ partial struct FrameSettings { internal static FrameSettings NewDefaultCamera() => new FrameSettings() { - bitDatas = new BitArray128(new uint[] { + bitDatas = new BitArray128(new uint[] + { (uint)FrameSettingsField.ShadowMaps, (uint)FrameSettingsField.ContactShadows, (uint)FrameSettingsField.Shadowmask, @@ -453,7 +454,8 @@ partial struct FrameSettings }; internal static FrameSettings NewDefaultRealtimeReflectionProbe() => new FrameSettings() { - bitDatas = new BitArray128(new uint[] { + bitDatas = new BitArray128(new uint[] + { (uint)FrameSettingsField.ShadowMaps, //(uint)FrameSettingsField.ContactShadow, //(uint)FrameSettingsField.ShadowMask, @@ -510,7 +512,8 @@ partial struct FrameSettings }; internal static FrameSettings NewDefaultCustomOrBakeReflectionProbe() => new FrameSettings() { - bitDatas = new BitArray128(new uint[] { + bitDatas = new BitArray128(new uint[] + { (uint)FrameSettingsField.ShadowMaps, (uint)FrameSettingsField.ContactShadows, (uint)FrameSettingsField.Shadowmask, @@ -700,25 +703,25 @@ internal static void Override(ref FrameSettings overriddenFrameSettings, FrameSe overriddenFrameSettings.bitDatas = (overridingFrameSettings.bitDatas & frameSettingsOverideMask.mask) | (~frameSettingsOverideMask.mask & overriddenFrameSettings.bitDatas); //other overrides - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.SssQualityMode]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.SssQualityMode]) overriddenFrameSettings.sssQualityMode = overridingFrameSettings.sssQualityMode; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.SssQualityLevel]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.SssQualityLevel]) overriddenFrameSettings.sssQualityLevel = overridingFrameSettings.sssQualityLevel; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.SssCustomSampleBudget]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.SssCustomSampleBudget]) overriddenFrameSettings.sssCustomSampleBudget = overridingFrameSettings.sssCustomSampleBudget; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.LODBias]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.LODBias]) overriddenFrameSettings.lodBias = overridingFrameSettings.lodBias; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.LODBiasMode]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.LODBiasMode]) overriddenFrameSettings.lodBiasMode = overridingFrameSettings.lodBiasMode; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.LODBiasQualityLevel]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.LODBiasQualityLevel]) overriddenFrameSettings.lodBiasQualityLevel = overridingFrameSettings.lodBiasQualityLevel; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.MaximumLODLevel]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.MaximumLODLevel]) overriddenFrameSettings.maximumLODLevel = overridingFrameSettings.maximumLODLevel; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.MaximumLODLevelMode]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.MaximumLODLevelMode]) overriddenFrameSettings.maximumLODLevelMode = overridingFrameSettings.maximumLODLevelMode; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.MaximumLODLevelQualityLevel]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.MaximumLODLevelQualityLevel]) overriddenFrameSettings.maximumLODLevelQualityLevel = overridingFrameSettings.maximumLODLevelQualityLevel; - if (frameSettingsOverideMask.mask[(uint) FrameSettingsField.MaterialQualityLevel]) + if (frameSettingsOverideMask.mask[(uint)FrameSettingsField.MaterialQualityLevel]) overriddenFrameSettings.materialQuality = overridingFrameSettings.materialQuality; } @@ -837,7 +840,7 @@ internal static void AggregateFrameSettings(ref FrameSettings aggregatedFrameSet additionalData, ref defaultHdrpAsset.GetDefaultFrameSettings(additionalData?.defaultFrameSettings ?? FrameSettingsRenderType.Camera), //fallback on Camera for SceneCamera and PreviewCamera hdrpAsset.currentPlatformRenderPipelineSettings - ); + ); // Note: this version is the one tested as there is issue getting HDRenderPipelineAsset in batchmode in unit test framework currently. /// Aggregation is default with override of the renderer then sanitized depending on supported features of hdrpasset. @@ -860,7 +863,7 @@ internal static void AggregateFrameSettings(ref FrameSettings aggregatedFrameSet /// First frame settings. /// Second frame settings. /// True if both settings are equal. - public static bool operator ==(FrameSettings a, FrameSettings b) + public static bool operator==(FrameSettings a, FrameSettings b) => a.bitDatas == b.bitDatas && a.sssQualityMode == b.sssQualityMode && a.sssQualityLevel == b.sssQualityLevel @@ -879,7 +882,7 @@ internal static void AggregateFrameSettings(ref FrameSettings aggregatedFrameSet /// First frame settings. /// Second frame settings. /// True if settings are not equal. - public static bool operator !=(FrameSettings a, FrameSettings b) => !(a == b); + public static bool operator!=(FrameSettings a, FrameSettings b) => !(a == b); /// /// Equality operator between two FrameSettings. Return `true` if equivalent. (comparison of content). @@ -991,7 +994,8 @@ public DebuggerGroup[] Keys groups.Add(new DebuggerGroup("Bits without attribute", noAttribute.Where(fs => fs != FrameSettingsField.None)?.Select(fs => new DebuggerEntry(Enum.GetName(typeof(FrameSettingsField), fs), m_FrameSettings.bitDatas[(uint)fs])).ToArray())); - groups.Add(new DebuggerGroup("Non Bit data", new DebuggerEntry[] { + groups.Add(new DebuggerGroup("Non Bit data", new DebuggerEntry[] + { new DebuggerEntry("sssQualityMode", m_FrameSettings.sssQualityMode), new DebuggerEntry("sssQualityLevel", m_FrameSettings.sssQualityLevel), new DebuggerEntry("sssCustomSampleBudget", m_FrameSettings.sssCustomSampleBudget), diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettingsHistory.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettingsHistory.cs index 052de2359b8..125120fabad 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettingsHistory.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/FrameSettingsHistory.cs @@ -65,9 +65,9 @@ public MinimalHistoryContainer() => m_FrameSettingsHistory.debug = HDRenderPipeline.defaultAsset?.GetDefaultFrameSettings(FrameSettingsRenderType.Camera) ?? new FrameSettings(); Action IDebugData.GetReset() - //caution: we actually need to retrieve the - //m_FrameSettingsHistory as it is a struct so no direct - // => m_FrameSettingsHistory.TriggerReset + //caution: we actually need to retrieve the + //m_FrameSettingsHistory as it is a struct so no direct + // => m_FrameSettingsHistory.TriggerReset => () => m_FrameSettingsHistory.TriggerReset(); } internal static IFrameSettingsHistoryContainer sceneViewFrameSettingsContainer = new MinimalHistoryContainer(); @@ -114,6 +114,7 @@ static FrameSettingsHistory() attributes[value] = type.GetField(Enum.GetName(type, value)).GetCustomAttribute(); } } + /// Same than FrameSettings.AggregateFrameSettings but keep history of agregation in a collection for DebugMenu. /// Aggregation is default with override of the renderer then sanitazed depending on supported features of hdrpasset. Then the DebugMenu override occurs. /// The aggregated FrameSettings result. @@ -130,7 +131,7 @@ public static void AggregateFrameSettings(ref FrameSettings aggregatedFrameSetti additionalData, ref defaultHdrpAsset.GetDefaultFrameSettings(additionalData?.defaultFrameSettings ?? FrameSettingsRenderType.Camera), //fallback on Camera for SceneCamera and PreviewCamera hdrpAsset.currentPlatformRenderPipelineSettings - ); + ); // Note: this version is the one tested as there is issue getting HDRenderPipelineAsset in batchmode in unit test framework currently. /// Same than FrameSettings.AggregateFrameSettings but keep history of agregation in a collection for DebugMenu. @@ -220,7 +221,7 @@ static DebugUI.HistoryEnumField GenerateHistoryEnumField(HDRenderPipelineAsset d // Contrarily to other enum of DebugMenu, we do not need to stock index as // it can be computed again with data in the dedicated debug section of history getIndex = () => frameSettingsContainer.frameSettingsHistory.debug.IsEnabled(field) ? 1 : 0, - setIndex = (int a) => { }, + setIndex = (int a) => {}, historyIndexGetter = new Func[] { @@ -257,7 +258,7 @@ static DebugUI.HistoryEnumField GenerateHistoryEnumField(HDRenderPipelineAsset d field.Key, field.Value, RetrieveEnumTypeByField(field.Key) - )); + )); break; case FrameSettingsFieldAttribute.DisplayType.Others: // for now, skip other display settings. Add them if needed break; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs index dba0c3b8c63..ce4622f6685 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs @@ -108,9 +108,9 @@ internal static RenderPipelineSettings NewDefault() supportDitheringCrossFade = true, supportTerrainHole = false, planarReflectionResolution = new PlanarReflectionAtlasResolutionScalableSetting(new[] { PlanarReflectionAtlasResolution.Resolution256, - PlanarReflectionAtlasResolution.Resolution1024, - PlanarReflectionAtlasResolution.Resolution2048 }, - ScalableSettingSchemaId.With3Levels), + PlanarReflectionAtlasResolution.Resolution1024, + PlanarReflectionAtlasResolution.Resolution2048 }, + ScalableSettingSchemaId.With3Levels), lightLoopSettings = GlobalLightLoopSettings.NewDefault(), hdShadowInitParams = HDShadowInitParameters.NewDefault(), decalSettings = GlobalDecalSettings.NewDefault(), @@ -153,7 +153,6 @@ public struct LightSettings { useContactShadow = new BoolScalableSetting(new[] { false, false, true }, ScalableSettingSchemaId.With3Levels) }; - } @@ -169,7 +168,7 @@ public class PlanarReflectionAtlasResolutionScalableSetting : ScalableSettingThe values of the settings /// The schema of the setting. public PlanarReflectionAtlasResolutionScalableSetting(PlanarReflectionAtlasResolution[] values, ScalableSettingSchemaId schemaId) - : base(values, schemaId) + : base(values, schemaId) { } } @@ -276,7 +275,7 @@ public PlanarReflectionAtlasResolutionScalableSetting(PlanarReflectionAtlasResol /// Global Probe Volume settings. [SerializeField] internal GlobalProbeVolumeSettings probeVolumeSettings; - /// Global light loop settings. + /// Global light loop settings. public GlobalLightLoopSettings lightLoopSettings; /// Global shadows settings. public HDShadowInitParameters hdShadowInitParams; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSetting.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSetting.cs index 317002c828a..734d3c1764e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSetting.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSetting.cs @@ -104,7 +104,7 @@ public class IntScalableSetting : ScalableSetting /// /// The values of the settings /// The schema of the setting. - public IntScalableSetting(int[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) { } + public IntScalableSetting(int[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) {} } /// . [Serializable] @@ -115,7 +115,7 @@ public class UintScalableSetting : ScalableSetting /// /// The values of the settings /// The schema of the setting. - public UintScalableSetting(uint[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) { } + public UintScalableSetting(uint[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) {} } /// . [Serializable] @@ -126,7 +126,7 @@ public class FloatScalableSetting : ScalableSetting /// /// The values of the settings /// The schema of the setting. - public FloatScalableSetting(float[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) { } + public FloatScalableSetting(float[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) {} } /// . [Serializable] @@ -137,7 +137,7 @@ public class BoolScalableSetting : ScalableSetting /// /// The values of the settings /// The schema of the setting. - public BoolScalableSetting(bool[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) { } + public BoolScalableSetting(bool[] values, ScalableSettingSchemaId schemaId) : base(values, schemaId) {} } #endregion } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchema.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchema.cs index 39bf12ab676..0ed04cfa330 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchema.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchema.cs @@ -18,10 +18,12 @@ public class ScalableSettingSchema /// internal static readonly Dictionary Schemas = new Dictionary { - { ScalableSettingSchemaId.With3Levels, new ScalableSettingSchema(new[] { + { ScalableSettingSchemaId.With3Levels, new ScalableSettingSchema(new[] + { new GUIContent("Low"), new GUIContent("Medium"), new GUIContent("High") }) }, - { ScalableSettingSchemaId.With4Levels, new ScalableSettingSchema(new[] { + { ScalableSettingSchemaId.With4Levels, new ScalableSettingSchema(new[] + { new GUIContent("Low"), new GUIContent("Medium"), new GUIContent("High"), new GUIContent("Ultra") }) }, }; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchemaId.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchemaId.cs index 9d640d1bc3c..f9adba6b410 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchemaId.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingSchemaId.cs @@ -8,7 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition /// Use to get a schema. /// [Serializable] - public struct ScalableSettingSchemaId: IEquatable + public struct ScalableSettingSchemaId : IEquatable { /// A scalable setting with 3 levels. public static readonly ScalableSettingSchemaId With3Levels = new ScalableSettingSchemaId("With3Levels"); @@ -46,6 +46,5 @@ public override bool Equals(object obj) /// /// The string representation. public override string ToString() => m_Id; - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingValue.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingValue.cs index 0ecb6b9890f..0595a30e586 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingValue.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/ScalableSettingValue.cs @@ -66,12 +66,12 @@ public void CopyTo(ScalableSettingValue target) // Unity's serialization API. /// An int scalable setting value - [Serializable] public class IntScalableSettingValue: ScalableSettingValue {} + [Serializable] public class IntScalableSettingValue : ScalableSettingValue {} /// An uint scalable setting value - [Serializable] public class UintScalableSettingValue: ScalableSettingValue {} + [Serializable] public class UintScalableSettingValue : ScalableSettingValue {} /// An float scalable setting value - [Serializable] public class FloatScalableSettingValue: ScalableSettingValue {} + [Serializable] public class FloatScalableSettingValue : ScalableSettingValue {} /// An bool scalable setting value - [Serializable] public class BoolScalableSettingValue: ScalableSettingValue {} + [Serializable] public class BoolScalableSettingValue : ScalableSettingValue {} #endregion } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl index 0bad0519ebe..25284c7acb6 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl @@ -8,9 +8,9 @@ void MeshDecalsPositionZBias(inout VaryingsToPS input) { #if UNITY_REVERSED_Z - input.vmesh.positionCS.z -= _DecalMeshDepthBias; + input.vmesh.positionCS.z -= _DecalMeshDepthBias; #else - input.vmesh.positionCS.z += _DecalMeshDepthBias; + input.vmesh.positionCS.z += _DecalMeshDepthBias; #endif } @@ -19,7 +19,7 @@ PackedVaryingsType Vert(AttributesMesh inputMesh) VaryingsType varyingsType; varyingsType.vmesh = VertMesh(inputMesh); #if (SHADERPASS == SHADERPASS_DBUFFER_MESH) - MeshDecalsPositionZBias(varyingsType); + MeshDecalsPositionZBias(varyingsType); #endif return PackVaryingsType(varyingsType); } @@ -45,7 +45,7 @@ void Frag( PackedVaryingsToPS packedInput, #if (SHADERPASS == SHADERPASS_DBUFFER_PROJECTOR) || (SHADERPASS == SHADERPASS_FORWARD_EMISSIVE_PROJECTOR) - float depth = LoadCameraDepth(input.positionSS.xy); + float depth = LoadCameraDepth(input.positionSS.xy); PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V); // Decal layer mask accepted by the receiving material diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl index ac30500b291..3f30668dbd0 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl @@ -110,7 +110,7 @@ void Frag( PackedVaryingsToPS packedInput bool forceNoMotion = unity_MotionVectorsParams.y == 0.0; // Setting the motionVector to a value more than 2 set as a flag for "force no motion". This is valid because, given that the velocities are in NDC, - // a value of >1 can never happen naturally, unless explicitely set. + // a value of >1 can never happen naturally, unless explicitely set. if (forceNoMotion) outMotionVector = float4(2.0, 0.0, 0.0, 0.0); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRayTracingSubSurface.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRayTracingSubSurface.hlsl index e2a87b493fe..c7014fc4b63 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRayTracingSubSurface.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRayTracingSubSurface.hlsl @@ -19,7 +19,7 @@ void ClosestSubSurface(inout RayIntersectionSubSurface rayIntersection : SV_RayP // Build the Frag inputs from the intersection vertex FragInputs fragInput; BuildFragInputsFromIntersection(currentVertex, incidentDirection, fragInput); - + PositionInputs posInput; posInput.positionWS = fragInput.positionRWS; posInput.positionSS = rayIntersection.pixelCoord; diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingForward.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingForward.hlsl index 8eaf89c13ba..edf9262d34f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingForward.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingForward.hlsl @@ -7,7 +7,7 @@ void ClosestHitForward(inout RayIntersection rayIntersection : SV_RayPayload, At { UNITY_XR_ASSIGN_VIEW_INDEX(DispatchRaysIndex().z); - // The first thing that we should do is grab the intersection vertice + // The first thing that we should do is grab the intersection vertice IntersectionVertex currentVertex; GetCurrentIntersectionVertex(attributeData, currentVertex); @@ -33,7 +33,7 @@ void ClosestHitForward(inout RayIntersection rayIntersection : SV_RayPayload, At BuiltinData builtinData; bool isVisible; GetSurfaceAndBuiltinData(fragInput, viewWS, posInput, surfaceData, builtinData, currentVertex, rayIntersection.cone, isVisible); - + // Compute the bsdf data BSDFData bsdfData = ConvertSurfaceDataToBSDFData(posInput.positionSS, surfaceData); @@ -205,7 +205,7 @@ void ClosestHitForward(inout RayIntersection rayIntersection : SV_RayPayload, At // the unlit color is not impacted by that. Thus, we multiply it by the inverse of the current exposure multiplier. rayIntersection.color = bsdfData.color * GetInverseCurrentExposureMultiplier() + builtinData.emissiveColor; #endif - + // Apply fog attenuation ApplyFogAttenuation(WorldRayOrigin(), WorldRayDirection(), rayIntersection.t, rayIntersection.color, true); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingGBuffer.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingGBuffer.hlsl index 8edbf5da3cc..5e08da59e8f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingGBuffer.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingGBuffer.hlsl @@ -27,7 +27,7 @@ void ClosestHitGBuffer(inout RayIntersectionGBuffer rayIntersectionGbuffer : SV_ cone.width = 0.0; cone.spreadAngle = 0.0; GetSurfaceAndBuiltinData(fragInput, -incidentDir, posInput, surfaceData, builtinData, currentVertex, cone, isVisible); - + // First we pack the data into the standard bsdf data StandardBSDFData standardLitData; ZERO_INITIALIZE(StandardBSDFData, standardLitData); diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingIndirect.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingIndirect.hlsl index 9ea6f4f1275..03aabd8346e 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingIndirect.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingIndirect.hlsl @@ -8,7 +8,7 @@ void ClosestHitMain(inout RayIntersection rayIntersection : SV_RayPayload, Attri { UNITY_XR_ASSIGN_VIEW_INDEX(DispatchRaysIndex().z); - // The first thing that we should do is grab the intersection vertice + // The first thing that we should do is grab the intersection vertice IntersectionVertex currentVertex; GetCurrentIntersectionVertex(attributeData, currentVertex); @@ -86,7 +86,7 @@ void ClosestHitMain(inout RayIntersection rayIntersection : SV_RayPayload, Attri reflectedIntersection.remainingDepth = rayIntersection.remainingDepth + 1; reflectedIntersection.pixelCoord = rayIntersection.pixelCoord; reflectedIntersection.sampleIndex = rayIntersection.sampleIndex; - + // In order to achieve filtering for the textures, we need to compute the spread angle of the pixel reflectedIntersection.cone.spreadAngle = rayIntersection.cone.spreadAngle; reflectedIntersection.cone.width = rayIntersection.cone.width; @@ -113,7 +113,7 @@ void ClosestHitMain(inout RayIntersection rayIntersection : SV_RayPayload, Attri } } #endif - + // Run the lightloop LightLoopOutput lightLoopOutput; LightLoop(viewWS, posInput, preLightData, bsdfData, builtinData, reflectedWeight, 0.0, reflected, float3(0.0, 0.0, 0.0), lightLoopOutput); @@ -168,7 +168,7 @@ void AnyHitMain(inout RayIntersection rayIntersection : SV_RayPayload, Attribute BuiltinData builtinData; bool isVisible; GetSurfaceAndBuiltinData(fragInput, viewWS, posInput, surfaceData, builtinData, currentVertex, rayIntersection.cone, isVisible); - + // If this fella should be culled, then we cull it if(!isVisible) { diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingVisibility.hlsl b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingVisibility.hlsl index afd9a25bf55..88b9d134a1b 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingVisibility.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassRaytracingVisibility.hlsl @@ -30,7 +30,7 @@ void AnyHitVisibility(inout RayIntersection rayIntersection : SV_RayPayload, Att { UNITY_XR_ASSIGN_VIEW_INDEX(DispatchRaysIndex().z); - // The first thing that we should do is grab the intersection vertice + // The first thing that we should do is grab the intersection vertice IntersectionVertex currentVertex; GetCurrentIntersectionVertex(attributeData, currentVertex); @@ -58,7 +58,7 @@ void AnyHitVisibility(inout RayIntersection rayIntersection : SV_RayPayload, Att float3 positionOS = ObjectRayOrigin() + ObjectRayDirection() * rayIntersection.t; float3 previousPositionWS = TransformPreviousObjectToWorld(positionOS); rayIntersection.velocity = saturate(length(previousPositionWS - fragInput.positionRWS)); - + #if HAS_REFRACTION rayIntersection.color *= lerp(surfaceData.transmittanceColor, float3(0.0, 0.0, 0.0), 1.0 - surfaceData.transmittanceMask); #else diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/BlueNoise.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/BlueNoise.cs index d662ef556a7..566284bd2e5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/BlueNoise.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/BlueNoise.cs @@ -166,6 +166,5 @@ internal static void BindDitheredTextureSet(CommandBuffer cmd, DitheredTextureSe cmd.SetGlobalTexture(HDShaderIDs._RankingTileXSPP, ditheredTextureSet.rankingTile); cmd.SetGlobalTexture(HDShaderIDs._ScramblingTexture, ditheredTextureSet.scramblingTex); } - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs index de48a9ce708..3d190230265 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs @@ -138,7 +138,7 @@ internal static int GetRuntimeDebugPanelWidth(HDCamera hdCamera) /// /// internal static float ProjectionMatrixAspect(in Matrix4x4 matrix) - => -matrix.m11 / matrix.m00; + => - matrix.m11 / matrix.m00; internal static Matrix4x4 ComputePixelCoordToWorldSpaceViewDirectionMatrix(float verticalFoV, Vector2 lensShift, Vector4 screenSize, Matrix4x4 worldToViewMatrix, bool renderToCubemap, float aspectRatio = -1) { @@ -166,9 +166,9 @@ internal static Matrix4x4 ComputePixelCoordToWorldSpaceViewDirectionMatrix(float } var viewSpaceRasterTransform = new Matrix4x4(new Vector4(m00, 0.0f, 0.0f, 0.0f), - new Vector4(0.0f, m11, 0.0f, 0.0f), - new Vector4(m20, m21, -1.0f, 0.0f), - new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); + new Vector4(0.0f, m11, 0.0f, 0.0f), + new Vector4(m20, m21, -1.0f, 0.0f), + new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Remove the translation component. var homogeneousZero = new Vector4(0, 0, 0, 1); @@ -392,7 +392,6 @@ public static void BlitCameraTexture(CommandBuffer cmd, RTHandle source, RTHandl BlitTexture(cmd, source, viewportScale, material, pass); } - /// /// Blit a RTHandle to another RTHandle. /// This will properly account for partial usage (in term of resolution) of the texture for the current viewport. @@ -546,7 +545,6 @@ internal static bool IsRegularPreviewCamera(Camera camera) { camera.TryGetComponent(out var additionalCameraData); return (additionalCameraData == null) || !additionalCameraData.isEditorCameraPreview; - } return false; } @@ -583,7 +581,7 @@ internal static RenderPipelineAsset SwitchToBuiltinRenderPipeline(out bool asset // IMPORTANT: RenderPipelineManager.currentPipeline won't be HDRP until a camera.Render() call is made. internal static void RestoreRenderPipelineAsset(bool wasUnsetFromQuality, RenderPipelineAsset renderPipelineAsset) { - if(wasUnsetFromQuality) + if (wasUnsetFromQuality) { QualitySettings.renderPipeline = renderPipelineAsset; } @@ -591,7 +589,6 @@ internal static void RestoreRenderPipelineAsset(bool wasUnsetFromQuality, Render { GraphicsSettings.renderPipelineAsset = renderPipelineAsset; } - } internal struct PackedMipChainInfo @@ -656,8 +653,8 @@ public void ComputePackedMipChainInfo(Vector2Int viewportSize) textureSize.x = Math.Max(textureSize.x, mipBegin.x + mipSize.x); textureSize.y = Math.Max(textureSize.y, mipBegin.y + mipSize.y); - - } while ((mipSize.x > 1) || (mipSize.y > 1)); + } + while ((mipSize.x > 1) || (mipSize.y > 1)); mipLevelCount = mipLevel + 1; m_OffsetBufferWillNeedUpdate = true; @@ -665,7 +662,6 @@ public void ComputePackedMipChainInfo(Vector2Int viewportSize) public ComputeBuffer GetOffsetBufferData(ComputeBuffer mipLevelOffsetsBuffer) { - if (m_OffsetBufferWillNeedUpdate) { mipLevelOffsetsBuffer.SetData(mipLevelOffsets); @@ -708,23 +704,23 @@ internal static float ComputeViewportLimit(int viewportSize, int bufferSize) internal static Vector4 ComputeViewportScaleAndLimit(Vector2Int viewportSize, Vector2Int bufferSize) { return new Vector4(ComputeViewportScale(viewportSize.x, bufferSize.x), // Scale(x) - ComputeViewportScale(viewportSize.y, bufferSize.y), // Scale(y) - ComputeViewportLimit(viewportSize.x, bufferSize.x), // Limit(x) - ComputeViewportLimit(viewportSize.y, bufferSize.y)); // Limit(y) + ComputeViewportScale(viewportSize.y, bufferSize.y), // Scale(y) + ComputeViewportLimit(viewportSize.x, bufferSize.x), // Limit(x) + ComputeViewportLimit(viewportSize.y, bufferSize.y)); // Limit(y) } // Note: If you add new platform in this function, think about adding support in IsSupportedBuildTarget() function below internal static bool IsSupportedGraphicDevice(GraphicsDeviceType graphicDevice) { return (graphicDevice == GraphicsDeviceType.Direct3D11 || - graphicDevice == GraphicsDeviceType.Direct3D12 || - graphicDevice == GraphicsDeviceType.PlayStation4 || - graphicDevice == GraphicsDeviceType.XboxOne || - graphicDevice == GraphicsDeviceType.XboxOneD3D12 || - graphicDevice == GraphicsDeviceType.Metal || - graphicDevice == GraphicsDeviceType.Vulkan - // Switch isn't supported currently (19.3) - /* || graphicDevice == GraphicsDeviceType.Switch */); + graphicDevice == GraphicsDeviceType.Direct3D12 || + graphicDevice == GraphicsDeviceType.PlayStation4 || + graphicDevice == GraphicsDeviceType.XboxOne || + graphicDevice == GraphicsDeviceType.XboxOneD3D12 || + graphicDevice == GraphicsDeviceType.Metal || + graphicDevice == GraphicsDeviceType.Vulkan + // Switch isn't supported currently (19.3) + /* || graphicDevice == GraphicsDeviceType.Switch */); } #if UNITY_EDITOR @@ -732,16 +728,16 @@ internal static bool IsSupportedGraphicDevice(GraphicsDeviceType graphicDevice) internal static bool IsSupportedBuildTarget(UnityEditor.BuildTarget buildTarget) { return (buildTarget == UnityEditor.BuildTarget.StandaloneWindows || - buildTarget == UnityEditor.BuildTarget.StandaloneWindows64 || - buildTarget == UnityEditor.BuildTarget.StandaloneLinux64 || - buildTarget == UnityEditor.BuildTarget.Stadia || - buildTarget == UnityEditor.BuildTarget.StandaloneOSX || - buildTarget == UnityEditor.BuildTarget.WSAPlayer || - buildTarget == UnityEditor.BuildTarget.XboxOne || - buildTarget == UnityEditor.BuildTarget.PS4 || - // buildTarget == UnityEditor.BuildTarget.iOS || // IOS isn't supported - // buildTarget == UnityEditor.BuildTarget.Switch || // Switch isn't supported - buildTarget == UnityEditor.BuildTarget.CloudRendering); + buildTarget == UnityEditor.BuildTarget.StandaloneWindows64 || + buildTarget == UnityEditor.BuildTarget.StandaloneLinux64 || + buildTarget == UnityEditor.BuildTarget.Stadia || + buildTarget == UnityEditor.BuildTarget.StandaloneOSX || + buildTarget == UnityEditor.BuildTarget.WSAPlayer || + buildTarget == UnityEditor.BuildTarget.XboxOne || + buildTarget == UnityEditor.BuildTarget.PS4 || + // buildTarget == UnityEditor.BuildTarget.iOS || // IOS isn't supported + // buildTarget == UnityEditor.BuildTarget.Switch || // Switch isn't supported + buildTarget == UnityEditor.BuildTarget.CloudRendering); } internal static bool AreGraphicsAPIsSupported(UnityEditor.BuildTarget target, ref GraphicsDeviceType unsupportedGraphicDevice) @@ -881,7 +877,7 @@ internal static bool WillCustomPassBeExecuted(HDCamera hdCamera, CustomPassInjec bool executed = false; CustomPassVolume.GetActivePassVolumes(injectionPoint, m_TempCustomPassVolumeList); - foreach(var customPassVolume in m_TempCustomPassVolumeList) + foreach (var customPassVolume in m_TempCustomPassVolumeList) { if (customPassVolume == null) return false; @@ -914,8 +910,8 @@ internal static Vector4 ConvertGUIDToVector4(string guid) unsafe { - fixed (byte * b = bytes) - vector = *(Vector4 *)b; + fixed(byte * b = bytes) + vector = *(Vector4 *)b; } return vector; @@ -1060,7 +1056,6 @@ internal static UInt64 GetSceneCullingMaskFromCamera(Camera camera) #else return 0; #endif - } internal static HDAdditionalCameraData TryGetAdditionalCameraDataOrDefault(Camera camera) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlas.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlas.cs index 5fac496f1f7..a6381cfcb18 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlas.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlas.cs @@ -53,7 +53,7 @@ public AtlasNode Allocate(int width, int height, bool powerOfTwoPadding) if (width > height) // logic to decide which way to split { - // +--------+------+ + // +--------+------+ m_RightChild.m_Rect.z = m_Rect.z + width; // | | | m_RightChild.m_Rect.w = m_Rect.w; // +--------+------+ m_RightChild.m_Rect.x = m_Rect.x - width; // | | @@ -173,7 +173,7 @@ public Texture2DAtlas(int width, int height, GraphicsFormat format, FilterMode f autoGenerateMips: false, name: name ); - m_IsAtlasTextureOwner = true; + m_IsAtlasTextureOwner = true; // We clear on create to avoid garbage data to be present in the atlas int mipCount = useMipMap ? GetTextureMipmapCount(m_Width, m_Height) : 1; @@ -309,14 +309,14 @@ protected int GetTextureHash(Texture texture) #if UNITY_EDITOR hash = 23 * hash + texture.imageContentsHash.GetHashCode(); #endif - hash = 23*hash + texture.GetInstanceID().GetHashCode(); - hash = 23*hash + texture.graphicsFormat.GetHashCode(); - hash = 23*hash + texture.wrapMode.GetHashCode(); - hash = 23*hash + texture.width.GetHashCode(); - hash = 23*hash + texture.height.GetHashCode(); - hash = 23*hash + texture.filterMode.GetHashCode(); - hash = 23*hash + texture.anisoLevel.GetHashCode(); - hash = 23*hash + texture.mipmapCount.GetHashCode(); + hash = 23 * hash + texture.GetInstanceID().GetHashCode(); + hash = 23 * hash + texture.graphicsFormat.GetHashCode(); + hash = 23 * hash + texture.wrapMode.GetHashCode(); + hash = 23 * hash + texture.width.GetHashCode(); + hash = 23 * hash + texture.height.GetHashCode(); + hash = 23 * hash + texture.filterMode.GetHashCode(); + hash = 23 * hash + texture.anisoLevel.GetHashCode(); + hash = 23 * hash + texture.mipmapCount.GetHashCode(); } return hash; @@ -328,7 +328,6 @@ protected int GetTextureHash(Texture textureA, Texture textureB) return hash; } - public int GetTextureID(Texture texture) { return texture.GetInstanceID(); @@ -336,7 +335,7 @@ public int GetTextureID(Texture texture) public int GetTextureID(Texture textureA, Texture textureB) { - return GetTextureID(textureA) + 23* GetTextureID(textureB); + return GetTextureID(textureA) + 23 * GetTextureID(textureB); } public bool IsCached(out Vector4 scaleOffset, Texture textureA, Texture textureB) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlasDynamic.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlasDynamic.cs index d79d739df68..7e8d83bf883 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlasDynamic.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture2DAtlasDynamic.cs @@ -57,7 +57,7 @@ public void AtlasNodeFree(Int16 index) } } - [StructLayout(LayoutKind.Explicit, Size=32)] + [StructLayout(LayoutKind.Explicit, Size = 32)] private struct AtlasNode { private enum AtlasNodeFlags : uint @@ -99,7 +99,7 @@ public void SetIsOccupied() public void ClearIsOccupied() { UInt16 isOccupiedMask = (UInt16)AtlasNodeFlags.IsOccupied; - m_Flags &= (UInt16)~isOccupiedMask; + m_Flags &= (UInt16) ~isOccupiedMask; } public bool IsLeafNode() diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlasDynamic.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlasDynamic.cs index e6d96757d1a..df0b7e5e8fc 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlasDynamic.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlasDynamic.cs @@ -99,7 +99,7 @@ public void SetIsOccupied() public void ClearIsOccupied() { UInt16 isOccupiedMask = (UInt16)Atlas3DNodeFlags.IsOccupied; - m_Flags &= (UInt16)~isOccupiedMask; + m_Flags &= (UInt16) ~isOccupiedMask; } public bool IsLeafNode() diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRPass.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRPass.cs index 8b7c4afce73..a077166f990 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRPass.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRPass.cs @@ -62,6 +62,7 @@ internal XRView(XRDisplaySubsystem.XRRenderPass renderPass, XRDisplaySubsystem.X viewport.y *= renderPass.renderTargetDesc.height; viewport.height *= renderPass.renderTargetDesc.height; } + #endif } @@ -181,6 +182,7 @@ internal void AddView(XRDisplaySubsystem.XRRenderPass xrSdkRenderPass, XRDisplay { AddViewInternal(new XRView(xrSdkRenderPass, xrSdkRenderParameter)); } + #endif internal static void Release(XRPass xrPass) diff --git a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRSystem.cs b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRSystem.cs index 9f644933687..7f8324d0b13 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRSystem.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/XR/XRSystem.cs @@ -66,7 +66,7 @@ internal XRSystem(RenderPipelineResources.ShaderResources shaders) [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)] internal static void XRSystemInit() { - if (GraphicsSettings.currentRenderPipeline == null) + if (GraphicsSettings.currentRenderPipeline == null) return; #if UNITY_2020_2_OR_NEWER @@ -82,6 +82,7 @@ internal static void XRSystemInit() displayList[i].textureLayout = XRDisplaySubsystem.TextureLayout.Texture2DArray; } } + #endif // Compute the maximum number of views (slices) to allocate for texture arrays @@ -102,6 +103,7 @@ internal int GetMaxViews() return maxViews; } + #if UNITY_2021_1_OR_NEWER internal List<(Camera, XRPass)> SetupFrame(List cameras, bool singlePassAllowed, bool singlePassTestModeActive) #else @@ -145,7 +147,7 @@ internal int GetMaxViews() // Disable vsync on the main display when rendering to a XR device QualitySettings.vSyncCount = 0; - if(display != null) + if (display != null) { display.zNear = camera.nearClipPlane; display.zFar = camera.farClipPlane; @@ -405,6 +407,7 @@ bool LayoutSinglePassTestMode(XRLayout frameLayout) return false; } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Scripting/GameObjectExtension.cs b/com.unity.render-pipelines.high-definition/Runtime/Scripting/GameObjectExtension.cs index e5d9ba49aa0..8401b597d67 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Scripting/GameObjectExtension.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Scripting/GameObjectExtension.cs @@ -13,7 +13,7 @@ public static class GameObjectExtension /// The created HDRP Light component public static HDAdditionalLightData AddHDLight(this GameObject gameObject, HDLightTypeAndShape lightTypeAndShape) { - var hdLight = gameObject.AddComponent< HDAdditionalLightData >(); + var hdLight = gameObject.AddComponent(); HDAdditionalLightData.InitDefaultHDAdditionalLightData(hdLight); @@ -28,8 +28,8 @@ public static HDAdditionalLightData AddHDLight(this GameObject gameObject, HDLig /// The GameObject on which the light is going to be removed public static void RemoveHDLight(this GameObject gameObject) { - var light = gameObject.GetComponent< Light >(); - var hdLight = gameObject.GetComponent< HDAdditionalLightData >(); + var light = gameObject.GetComponent(); + var hdLight = gameObject.GetComponent(); // destroy light components in order CoreUtils.Destroy(hdLight); diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader index c15de359b38..467c1da930a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader @@ -27,7 +27,7 @@ Shader "Hidden/HDRP/CopyStencilBuffer" RW_TEXTURE2D_X(float, _HTile); // DXGI_FORMAT_R8_UINT is not supported by Unity RW_TEXTURE2D_X(float, _StencilBufferCopy); // DXGI_FORMAT_R8_UINT is not supported by Unity #endif - + struct Attributes { uint vertexID : SV_VertexID; @@ -156,7 +156,7 @@ Shader "Hidden/HDRP/CopyStencilBuffer" { // Note, when supporting D3D 11.3+, this can be a one off copy pass. // This is essentially the equivalent of Pass 1, but writing to a UAV instead. - Name "Pass 3 - Initialize Stencil UAV copy with 1 if value different from stencilRef to output" + Name "Pass 3 - Initialize Stencil UAV copy with 1 if value different from stencilRef to output" Stencil { @@ -187,7 +187,7 @@ Shader "Hidden/HDRP/CopyStencilBuffer" Pass { - Name "Pass 4 - Update Stencil UAV copy with Stencil Ref" + Name "Pass 4 - Update Stencil UAV copy with Stencil Ref" Stencil { diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute index 97f12198fcb..372b0025b2c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute @@ -1,7 +1,7 @@ #pragma only_renderers d3d11 playstation xboxone vulkan metal switch -#pragma kernel MAIN KERNEL_NAME=MAIN NUM_SAMPLES=1 COARSE_STENCIL -#pragma kernel MAIN_MSAA_2 KERNEL_NAME=MAIN_MSAA_2 NUM_SAMPLES=2 MSAA COARSE_STENCIL +#pragma kernel MAIN KERNEL_NAME=MAIN NUM_SAMPLES=1 COARSE_STENCIL +#pragma kernel MAIN_MSAA_2 KERNEL_NAME=MAIN_MSAA_2 NUM_SAMPLES=2 MSAA COARSE_STENCIL #pragma kernel MAIN_MSAA_4 KERNEL_NAME=MAIN_MSAA_4 NUM_SAMPLES=4 MSAA COARSE_STENCIL #pragma kernel MAIN_MSAA_8 KERNEL_NAME=MAIN_MSAA_8 NUM_SAMPLES=8 MSAA COARSE_STENCIL @@ -47,7 +47,7 @@ void KERNEL_NAME(uint3 groupId : SV_GroupID, { UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadID.z); - // The best shot at resolving is being overly conservative, hence the OR operator. This is by nature inaccurate. + // The best shot at resolving is being overly conservative, hence the OR operator. This is by nature inaccurate. uint resolvedStencil = 0; if (dispatchThreadID.x < (uint)_ScreenSize.x && dispatchThreadID.y < (uint)_ScreenSize.y) diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphFunctions.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphFunctions.hlsl index b1415cd650b..86080b58668 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphFunctions.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphFunctions.hlsl @@ -16,7 +16,7 @@ float3 shadergraph_HDSampleSceneColor(float2 uv) { #if defined(REQUIRE_OPAQUE_TEXTURE) && defined(_SURFACE_TYPE_TRANSPARENT) && defined(SHADERPASS) && (SHADERPASS != SHADERPASS_LIGHT_TRANSPORT) // We always remove the pre-exposure when we sample the scene color - return SampleCameraColor(uv) * GetInverseCurrentExposureMultiplier(); + return SampleCameraColor(uv) * GetInverseCurrentExposureMultiplier(); #endif return float3(0, 0, 0); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphHeader.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphHeader.hlsl index 5dd54a1ccf6..a05d1e165fb 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphHeader.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphHeader.hlsl @@ -5,6 +5,6 @@ // Always include Shader Graph version // Always include last to avoid double macros -#include "Packages/com.unity.shadergraph/ShaderGraphLibrary/Functions.hlsl" +#include "Packages/com.unity.shadergraph/ShaderGraphLibrary/Functions.hlsl" #endif // UNITY_HEADER_HD_INCLUDED diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl index 20dbbc07604..69a5c5e5011 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariablesFunctions.hlsl @@ -10,7 +10,7 @@ // Note: we need to mask out only 8bits of the layer mask before encoding it as otherwise any value > 255 will map to all layers active if save in a buffer uint GetMeshRenderingLightLayer() -{ +{ return _EnableLightLayers ? (asuint(unity_RenderingLayer.x) & RENDERING_LIGHT_LAYERS_MASK) >> RENDERING_LIGHT_LAYERS_MASK_SHIFT : DEFAULT_LIGHT_LAYERS; } @@ -136,7 +136,7 @@ float3x3 BuildTangentToWorld(float4 tangentWS, float3 normalWS) // by uniformly scaling all 3 vectors since normalization of the perturbed normal will cancel it. tangentToWorld[0] = tangentToWorld[0] * renormFactor; tangentToWorld[1] = tangentToWorld[1] * renormFactor; - tangentToWorld[2] = tangentToWorld[2] * renormFactor; // normalizes the interpolated vertex normal + tangentToWorld[2] = tangentToWorld[2] * renormFactor; // normalizes the interpolated vertex normal return tangentToWorld; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader index 4c16834469a..efce720c4ef 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader @@ -27,11 +27,11 @@ Shader "Hidden/HDRP/XROcclusionMesh" { Varyings output; output.vertex = float4(input.vertex.xy * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), UNITY_NEAR_CLIP_VALUE, 1.0f); - + #if XR_OCCLUSION_MESH_COMBINED output.rtArrayIndex = input.vertex.z; #endif - + return output; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader b/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader index 1006bb027b7..914cef45193 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader @@ -14,7 +14,7 @@ Shader "Hidden/HDRP/Sky/GradientSky" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyUtils.hlsl" - float4 _GradientBottom; + float4 _GradientBottom; float4 _GradientMiddle; float4 _GradientTop; float _GradientDiffusion; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.cs index 768a8981ecb..88798fb37e4 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.cs @@ -45,7 +45,7 @@ public class HDRISky : SkySettings public FloatParameter groundLevel = new FloatParameter(0.0f); /// Extent of the Backplate (if circle only the X value is considered). [Tooltip("Extent of the Backplate (if circle only the X value is considered).")] - public Vector2Parameter scale = new Vector2Parameter(Vector2.one*32.0f); + public Vector2Parameter scale = new Vector2Parameter(Vector2.one * 32.0f); /// Backplate's projection distance to varying the cubemap projection on the plate. [Tooltip("Backplate's projection distance to varying the cubemap projection on the plate.")] public MinFloatParameter projectionDistance = new MinFloatParameter(16.0f, 1e-7f); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader index eff6573a11a..c7fbb6d3e6c 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader @@ -48,7 +48,7 @@ Shader "Hidden/HDRP/Sky/HDRISky" TEXTURECUBE(_Cubemap); SAMPLER(sampler_Cubemap); - + TEXTURE2D(_Flowmap); SAMPLER(sampler_Flowmap); @@ -60,7 +60,7 @@ Shader "Hidden/HDRP/Sky/HDRISky" uint _BackplateShadowFilter; float4 _FlowmapParam; // x upper hemisphere only, y scroll factor, zw scroll direction (cosPhi and sinPhi) - + #define _Intensity _SkyParam.x #define _CosPhi _SkyParam.z #define _SinPhi _SkyParam.w diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISkyRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISkyRenderer.cs index e9e361db358..57d95045406 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISkyRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISkyRenderer.cs @@ -37,8 +37,8 @@ public override void Cleanup() private void GetParameters(out float intensity, out float phi, out float backplatePhi, BuiltinSkyParameters builtinParams, HDRISky hdriSky) { intensity = GetSkyIntensity(hdriSky, builtinParams.debugSettings); - phi = -Mathf.Deg2Rad*hdriSky.rotation.value; // -rotation to match Legacy... - backplatePhi = phi - Mathf.Deg2Rad*hdriSky.plateRotation.value; + phi = -Mathf.Deg2Rad * hdriSky.rotation.value; // -rotation to match Legacy... + backplatePhi = phi - Mathf.Deg2Rad * hdriSky.plateRotation.value; } private Vector4 GetBackplateParameters0(HDRISky hdriSky) @@ -59,7 +59,7 @@ private Vector4 GetBackplateParameters1(float backplatePhi, HDRISky hdriSky) { // x: BackplateType, y: BlendAmount, zw: backplate rotation (cosPhi_plate, sinPhi_plate) float type = 3.0f; - float blendAmount = hdriSky.blendAmount.value/100.0f; + float blendAmount = hdriSky.blendAmount.value / 100.0f; switch (hdriSky.backplateType.value) { case BackplateType.Disc: @@ -82,7 +82,7 @@ private Vector4 GetBackplateParameters1(float backplatePhi, HDRISky hdriSky) private Vector4 GetBackplateParameters2(HDRISky hdriSky) { // xy: BackplateTextureRotation (cos/sin), zw: Backplate Texture Offset - float localPhi = -Mathf.Deg2Rad*hdriSky.plateTexRotation.value; + float localPhi = -Mathf.Deg2Rad * hdriSky.plateTexRotation.value; return new Vector4(Mathf.Cos(localPhi), Mathf.Sin(localPhi), hdriSky.plateTexOffset.value.x, hdriSky.plateTexOffset.value.y); } @@ -153,7 +153,7 @@ public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderFo else m_SkyHDRIMaterial.DisableKeyword("USE_FLOWMAP"); - float rot = -Mathf.Deg2Rad*hdriSky.scrollDirection.value; + float rot = -Mathf.Deg2Rad * hdriSky.scrollDirection.value; bool upperHemisphereOnly = hdriSky.upperHemisphereOnly.value || hdriSky.procedural.value; Vector4 flowmapParam = new Vector4(upperHemisphereOnly ? 1.0f : 0.0f, scrollFactor, Mathf.Cos(rot), Mathf.Sin(rot)); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader index 2b2ac0af321..56355a0184f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader @@ -47,7 +47,7 @@ Shader "Hidden/HDRP/IntegrateHDRI" return output; } - + // With HDRI that have a large range (including the sun) it can be challenging to // compute the lux value without multiple importance sampling. diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs index 0044eaa223b..77b7d7aee30 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs @@ -294,8 +294,8 @@ internal Vector3 GetAirScatteringCoefficient() return new Vector3(airExt.x * airAlb.x, - airExt.y * airAlb.y, - airExt.z * airAlb.z); + airExt.y * airAlb.y, + airExt.z * airAlb.z); } internal float GetAerosolScaleHeight() @@ -332,8 +332,8 @@ internal Vector3 GetAerosolScatteringCoefficient() float aerExt = GetAerosolExtinctionCoefficient(); return new Vector3(aerExt * aerosolTint.value.r, - aerExt * aerosolTint.value.g, - aerExt * aerosolTint.value.b); + aerExt * aerosolTint.value.g, + aerExt * aerosolTint.value.b); } PhysicallyBasedSky() diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl index cee55d86c5f..8567fe6881a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyCommon.hlsl @@ -252,26 +252,26 @@ float3 ComputeAtmosphericOpticalDepth(float r, float cosTheta, bool aboveHorizon float2 z = n * r; float2 Z = n * R; - float sinTheta = sqrt(saturate(1 - cosTheta * cosTheta)); + float sinTheta = sqrt(saturate(1 - cosTheta * cosTheta)); float2 ch; ch.x = ChapmanUpperApprox(z.x, abs(cosTheta)) * exp(Z.x - z.x); // Rescaling adds 'exp' ch.y = ChapmanUpperApprox(z.y, abs(cosTheta)) * exp(Z.y - z.y); // Rescaling adds 'exp' if (!aboveHorizon) // Below horizon, intersect sphere - { - float sinGamma = (r / R) * sinTheta; - float cosGamma = sqrt(saturate(1 - sinGamma * sinGamma)); + { + float sinGamma = (r / R) * sinTheta; + float cosGamma = sqrt(saturate(1 - sinGamma * sinGamma)); - float2 ch_2; + float2 ch_2; ch_2.x = ChapmanUpperApprox(Z.x, cosGamma); // No need to rescale ch_2.y = ChapmanUpperApprox(Z.y, cosGamma); // No need to rescale - ch = ch_2 - ch; + ch = ch_2 - ch; } else if (cosTheta < 0) // Above horizon, lower hemisphere { - // z_0 = n * r_0 = (n * r) * sin(theta) = z * sin(theta). + // z_0 = n * r_0 = (n * r) * sin(theta) = z * sin(theta). // Ch(z, theta) = 2 * exp(z - z_0) * Ch(z_0, Pi/2) - Ch(z, Pi - theta). float2 z_0 = z * sinTheta; float2 b = exp(Z - z_0); // Rescaling cancels out 'z' and adds 'Z' diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs index 739610d2c08..7dd17adf306 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSkyRenderer.cs @@ -63,9 +63,9 @@ class PrecomputationData RTHandle AllocateGroundIrradianceTable(int index) { var table = RTHandles.Alloc((int)PbrSkyConfig.GroundIrradianceTableSize, 1, - colorFormat: s_ColorFormat, - enableRandomWrite: true, - name: string.Format("GroundIrradianceTable{0}", index)); + colorFormat: s_ColorFormat, + enableRandomWrite: true, + name: string.Format("GroundIrradianceTable{0}", index)); Debug.Assert(table != null); @@ -76,13 +76,13 @@ RTHandle AllocateInScatteredRadianceTable(int index) { // Emulate a 4D texture with a "deep" 3D texture. var table = RTHandles.Alloc((int)PbrSkyConfig.InScatteredRadianceTableSizeX, - (int)PbrSkyConfig.InScatteredRadianceTableSizeY, - (int)PbrSkyConfig.InScatteredRadianceTableSizeZ * - (int)PbrSkyConfig.InScatteredRadianceTableSizeW, - dimension: TextureDimension.Tex3D, - colorFormat: s_ColorFormat, - enableRandomWrite: true, - name: string.Format("InScatteredRadianceTable{0}", index)); + (int)PbrSkyConfig.InScatteredRadianceTableSizeY, + (int)PbrSkyConfig.InScatteredRadianceTableSizeZ * + (int)PbrSkyConfig.InScatteredRadianceTableSizeW, + dimension: TextureDimension.Tex3D, + colorFormat: s_ColorFormat, + enableRandomWrite: true, + name: string.Format("InScatteredRadianceTable{0}", index)); Debug.Assert(table != null); @@ -166,9 +166,9 @@ void PrecomputeTables(CommandBuffer cmd) // Re-illuminate the sky with each bounce. // Emulate a 4D dispatch with a "deep" 3D dispatch. cmd.DispatchCompute(s_InScatteredRadiancePrecomputationCS, pass, (int)PbrSkyConfig.InScatteredRadianceTableSizeX / 4, - (int)PbrSkyConfig.InScatteredRadianceTableSizeY / 4, - (int)PbrSkyConfig.InScatteredRadianceTableSizeZ / 4 * - (int)PbrSkyConfig.InScatteredRadianceTableSizeW); + (int)PbrSkyConfig.InScatteredRadianceTableSizeY / 4, + (int)PbrSkyConfig.InScatteredRadianceTableSizeZ / 4 * + (int)PbrSkyConfig.InScatteredRadianceTableSizeW); } { @@ -232,7 +232,6 @@ public void BindBuffers(CommandBuffer cmd, MaterialPropertyBlock mpb) s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._AerosolSingleScatteringTexture, CoreUtils.blackVolumeTexture); s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._MultipleScatteringTexture, CoreUtils.blackVolumeTexture); } - } public bool Update(BuiltinSkyParameters builtinParams, PhysicallyBasedSky pbrSky) @@ -458,12 +457,12 @@ public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderFo // Precomputation is done, shading is next. Quaternion planetRotation = Quaternion.Euler(pbrSky.planetRotation.value.x, - pbrSky.planetRotation.value.y, - pbrSky.planetRotation.value.z); + pbrSky.planetRotation.value.y, + pbrSky.planetRotation.value.z); Quaternion spaceRotation = Quaternion.Euler(pbrSky.spaceRotation.value.x, - pbrSky.spaceRotation.value.y, - pbrSky.spaceRotation.value.z); + pbrSky.spaceRotation.value.y, + pbrSky.spaceRotation.value.z); s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix); s_PbrSkyMaterialProperties.SetVector(HDShaderIDs._WorldSpaceCameraPos1, cameraPos); @@ -488,7 +487,7 @@ public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderFo { hasGroundEmissionTexture = 1; s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundEmissionTexture, pbrSky.groundEmissionTexture.value); - s_PbrSkyMaterialProperties.SetFloat( HDShaderIDs._GroundEmissionMultiplier, pbrSky.groundEmissionMultiplier.value); + s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._GroundEmissionMultiplier, pbrSky.groundEmissionMultiplier.value); } s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundEmissionTexture, hasGroundEmissionTexture); @@ -498,7 +497,7 @@ public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderFo { hasSpaceEmissionTexture = 1; s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._SpaceEmissionTexture, pbrSky.spaceEmissionTexture.value); - s_PbrSkyMaterialProperties.SetFloat( HDShaderIDs._SpaceEmissionMultiplier, pbrSky.spaceEmissionMultiplier.value); + s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._SpaceEmissionMultiplier, pbrSky.spaceEmissionMultiplier.value); } s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasSpaceEmissionTexture, hasSpaceEmissionTexture); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs index 42c93cf1f3c..7179c195a03 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyManager.cs @@ -321,7 +321,6 @@ void InitializeBlackCubemapArray() } } - public void Cleanup() { CoreUtils.Destroy(m_StandardSkyboxMaterial); @@ -381,7 +380,7 @@ Texture GetSkyCubemap(SkyUpdateContext skyContext) Texture GetReflectionTexture(SkyUpdateContext skyContext) { if (skyContext.IsValid() && IsCachedContextValid(skyContext)) - { + { ref var context = ref m_CachedSkyContexts[skyContext.cachedSkyRenderingContextId]; return context.renderingContext.skyboxBSDFCubemapArray; } @@ -429,7 +428,6 @@ internal bool HasSetValidAmbientProbe(HDCamera hdCamera) } return false; - } internal void SetupAmbientProbe(HDCamera hdCamera) @@ -552,7 +550,6 @@ int GetSunLightHashCode(Light light) } } - void AllocateNewRenderingContext(SkyUpdateContext skyContext, int slot, int newHash, bool supportConvolution, in SphericalHarmonicsL2 previousAmbientProbe, string name) { Debug.Assert(m_CachedSkyContexts[slot].hash == 0); @@ -692,16 +689,16 @@ internal void RequestStaticEnvironmentUpdate() m_RequireWaitForAsyncReadBackRequest = true; } - public void UpdateEnvironment( HDCamera hdCamera, - ScriptableRenderContext renderContext, - SkyUpdateContext skyContext, - Light sunLight, - bool updateRequired, - bool updateAmbientProbe, - bool staticSky, - SkyAmbientMode ambientMode, - int frameIndex, - CommandBuffer cmd) + public void UpdateEnvironment(HDCamera hdCamera, + ScriptableRenderContext renderContext, + SkyUpdateContext skyContext, + Light sunLight, + bool updateRequired, + bool updateAmbientProbe, + bool staticSky, + SkyAmbientMode ambientMode, + int frameIndex, + CommandBuffer cmd) { if (skyContext.IsValid()) { @@ -877,13 +874,13 @@ public void PreRenderSky(HDCamera hdCamera, Light sunLight, RTHandle colorBuffer if (skyContext.IsValid()) { UpdateBuiltinParameters(skyContext, - hdCamera, - sunLight, - colorBuffer, - depthBuffer, - debugSettings, - frameIndex, - cmd); + hdCamera, + sunLight, + colorBuffer, + depthBuffer, + debugSettings, + frameIndex, + cmd); SkyAmbientMode ambientMode = hdCamera.volumeStack.GetComponent().skyAmbientMode.value; int skyHash = ComputeSkyHash(hdCamera, skyContext, sunLight, ambientMode); @@ -909,13 +906,13 @@ public void RenderSky(HDCamera hdCamera, Light sunLight, RTHandle colorBuffer, R using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderSky))) { UpdateBuiltinParameters(skyContext, - hdCamera, - sunLight, - colorBuffer, - depthBuffer, - debugSettings, - frameIndex, - cmd); + hdCamera, + sunLight, + colorBuffer, + depthBuffer, + debugSettings, + frameIndex, + cmd); SkyAmbientMode ambientMode = hdCamera.volumeStack.GetComponent().skyAmbientMode.value; int skyHash = ComputeSkyHash(hdCamera, skyContext, sunLight, ambientMode); @@ -943,12 +940,12 @@ public void RenderSky(HDCamera hdCamera, Light sunLight, RTHandle colorBuffer, R } public void RenderOpaqueAtmosphericScattering(CommandBuffer cmd, HDCamera hdCamera, - RTHandle colorBuffer, - RTHandle depthTexture, - RTHandle volumetricLighting, - RTHandle intermediateBuffer, - RTHandle depthBuffer, - Matrix4x4 pixelCoordToViewDirWS, bool isMSAA) + RTHandle colorBuffer, + RTHandle depthTexture, + RTHandle volumetricLighting, + RTHandle intermediateBuffer, + RTHandle depthBuffer, + Matrix4x4 pixelCoordToViewDirWS, bool isMSAA) { using (new ProfilingScope(m_BuiltinParameters.commandBuffer, ProfilingSampler.Get(HDProfileId.OpaqueAtmosphericScattering))) { @@ -961,7 +958,7 @@ public void RenderOpaqueAtmosphericScattering(CommandBuffer cmd, HDCamera hdCame if (Fog.IsPBRFogEnabled(hdCamera)) { - m_OpaqueAtmScatteringBlock.SetTexture(isMSAA? HDShaderIDs._ColorTextureMS : HDShaderIDs._ColorTexture, colorBuffer); + m_OpaqueAtmScatteringBlock.SetTexture(isMSAA ? HDShaderIDs._ColorTextureMS : HDShaderIDs._ColorTexture, colorBuffer); // Color -> Intermediate. HDUtils.DrawFullScreen(cmd, m_OpaqueAtmScatteringMaterial, intermediateBuffer, depthBuffer, m_OpaqueAtmScatteringBlock, isMSAA ? 3 : 2); @@ -1093,6 +1090,7 @@ void OnBakeStarted() DynamicGI.UpdateEnvironment(); } + #endif } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyRenderer.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyRenderer.cs index 26c5ad3da60..d7592eef990 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyRenderer.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkyRenderer.cs @@ -33,7 +33,7 @@ public abstract class SkyRenderer /// Engine parameters that you can use to render the sky. /// Pass in true if you want to render the sky into a cubemap for lighting. This is useful when the sky renderer needs a different implementation in this case. /// If the sky renderer supports the rendering of a sun disk, it must not render it if this is set to false. - public virtual void PreRenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk) { } + public virtual void PreRenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk) {} /// /// Whether the PreRenderSky step is required. @@ -61,7 +61,7 @@ protected static float GetSkyIntensity(SkySettings skySettings, DebugDisplaySett { float skyIntensity = 1.0f; - switch(skySettings.skyIntensityMode.value) + switch (skySettings.skyIntensityMode.value) { case SkyIntensityMode.Exposure: // Note: Here we use EV100 of sky as a multiplier, so it is the opposite of when use with a Camera @@ -86,7 +86,6 @@ protected static float GetSkyIntensity(SkySettings skySettings, DebugDisplaySett /// Sky system builtin parameters. public virtual void SetGlobalSkyData(CommandBuffer cmd, BuiltinSkyParameters builtinParams) { - } internal bool DoUpdate(BuiltinSkyParameters parameters) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkySettings.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkySettings.cs index 73c790cad10..bd2980b3ba7 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/SkySettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/SkySettings.cs @@ -79,7 +79,7 @@ public sealed class BackplateTypeParameter : VolumeParameter /// Backplate Type parameter. /// Initial override state. public BackplateTypeParameter(BackplateType value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} } /// diff --git a/com.unity.render-pipelines.high-definition/Runtime/Sky/VisualEnvironment.cs b/com.unity.render-pipelines.high-definition/Runtime/Sky/VisualEnvironment.cs index f6619c61d8d..99105738f70 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Sky/VisualEnvironment.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Sky/VisualEnvironment.cs @@ -60,6 +60,6 @@ public sealed class SkyAmbientModeParameter : VolumeParameter /// Sky Ambient Mode parameter. /// Initial override value. public SkyAmbientModeParameter(SkyAmbientMode value, bool overrideState = false) - : base(value, overrideState) { } + : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraCache.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraCache.cs index 16cec78e9fe..abf1b02df4f 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraCache.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraCache.cs @@ -54,11 +54,11 @@ public void ClearCamerasUnusedFor(int frameWindow, int frameCount) { if (m_Cache == null) throw new ObjectDisposedException(nameof(CameraCache)); - + // In case cameraKeysCache length does not matches the current cache length, we resize it: if (cameraKeysCache.Length != m_Cache.Count) cameraKeysCache = new K[m_Cache.Count]; - + // Copy keys to remove them from the dictionary (avoids collection modifed while iterating error) m_Cache.Keys.CopyTo(cameraKeysCache, 0); foreach (var key in cameraKeysCache) diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraSettings.cs index 742170e8ec3..c5aee297567 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/CameraSettings.cs @@ -73,11 +73,11 @@ public struct BufferClearing /// Default value. /// The default value. public static BufferClearing NewDefault() => new BufferClearing - { - clearColorMode = HDAdditionalCameraData.ClearColorMode.Sky, - backgroundColorHDR = new Color32(6, 18, 48, 0), - clearDepth = true - }; + { + clearColorMode = HDAdditionalCameraData.ClearColorMode.Sky, + backgroundColorHDR = new Color32(6, 18, 48, 0), + clearDepth = true + }; /// Define the source for the clear color. public HDAdditionalCameraData.ClearColorMode clearColorMode; @@ -101,10 +101,10 @@ public struct Volumes /// Default value. /// The default value. public static Volumes NewDefault() => new Volumes - { - layerMask = -1, - anchorOverride = null - }; + { + layerMask = -1, + anchorOverride = null + }; /// The to use for the volumes. public LayerMask layerMask; @@ -131,14 +131,14 @@ public struct Frustum /// Default value. /// The default value. public static Frustum NewDefault() => new Frustum - { - mode = Mode.ComputeProjectionMatrix, - aspect = 1.0f, - farClipPlaneRaw = 1000.0f, - nearClipPlaneRaw = 0.1f, - fieldOfView = 90.0f, - projectionMatrix = Matrix4x4.identity - }; + { + mode = Mode.ComputeProjectionMatrix, + aspect = 1.0f, + farClipPlaneRaw = 1000.0f, + nearClipPlaneRaw = 0.1f, + fieldOfView = 90.0f, + projectionMatrix = Matrix4x4.identity + }; /// Defines how the projection matrix is computed. public enum Mode @@ -235,11 +235,11 @@ public struct Culling /// Default value. /// The default value. public static Culling NewDefault() => new Culling - { - cullingMask = -1, - useOcclusionCulling = true, - sceneCullingMaskOverride = 0 - }; + { + cullingMask = -1, + useOcclusionCulling = true, + sceneCullingMaskOverride = 0 + }; /// True when occlusion culling will be performed during rendering, false otherwise. public bool useOcclusionCulling; @@ -255,18 +255,18 @@ public struct Culling /// Default value. /// The default value and allocate ~250B of garbage. public static CameraSettings NewDefault() => new CameraSettings - { - bufferClearing = BufferClearing.NewDefault(), - culling = Culling.NewDefault(), - renderingPathCustomFrameSettings = FrameSettings.NewDefaultCamera(), - frustum = Frustum.NewDefault(), - customRenderingSettings = false, - volumes = Volumes.NewDefault(), - flipYMode = HDAdditionalCameraData.FlipYMode.Automatic, - invertFaceCulling = false, - probeLayerMask = ~0, - probeRangeCompressionFactor = 1.0f - }; + { + bufferClearing = BufferClearing.NewDefault(), + culling = Culling.NewDefault(), + renderingPathCustomFrameSettings = FrameSettings.NewDefaultCamera(), + frustum = Frustum.NewDefault(), + customRenderingSettings = false, + volumes = Volumes.NewDefault(), + flipYMode = HDAdditionalCameraData.FlipYMode.Automatic, + invertFaceCulling = false, + probeLayerMask = ~0, + probeRangeCompressionFactor = 1.0f + }; /// Default camera settings. public static readonly CameraSettings defaultCameraSettingsNonAlloc = NewDefault(); diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDAdditionalSceneViewSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDAdditionalSceneViewSettings.cs index 0063c9baa5f..1ef7ab04cf2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDAdditionalSceneViewSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDAdditionalSceneViewSettings.cs @@ -138,7 +138,7 @@ static void DoAdditionalSettings(SceneView sceneView) sceneExposureOverriden = EditorGUILayout.Toggle(Styles.OverrideExposure, sceneExposureOverriden); if (sceneExposureOverriden) sceneExposure = EditorGUILayout.Slider(Styles.OverriddenExposure, sceneExposure, -11.0f, 16.0f); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) { SceneView.RepaintAll(); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDBakingUtilities.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDBakingUtilities.cs index 2736a6102a2..c500b696662 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDBakingUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDBakingUtilities.cs @@ -37,7 +37,7 @@ public static string GetBakedTextureFilePath(HDProbe probe) probe.settings.type, SceneObjectIDMap.GetOrCreateSceneObjectID( probe.gameObject, SceneObjectCategory.ReflectionProbe - ), + ), probe.gameObject.scene ); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderPipelinePreferences.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderPipelinePreferences.cs index fc6a4b5f959..89b9861cc38 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderPipelinePreferences.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderPipelinePreferences.cs @@ -55,7 +55,7 @@ static SettingsProvider PreferenceGUI() Load(); matcapViewMixAlbedo = EditorGUILayout.Toggle("Mix Albedo in the Matcap", matcapViewMixAlbedo); - if(matcapViewMixAlbedo) + if (matcapViewMixAlbedo) matcapViewScale = EditorGUILayout.FloatField("Matcap intensity scale", matcapViewScale); } }; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderUtilities.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderUtilities.cs index 17437fa2f3d..752ac579c43 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDRenderUtilities.cs @@ -98,60 +98,60 @@ public static void Render( switch (target.dimension) { case TextureDimension.Tex2D: - { + { #if DEBUG - Debug.LogWarning( - "A static flags bitmask was provided but this is ignored when rendering into a Tex2D" - ); + Debug.LogWarning( + "A static flags bitmask was provided but this is ignored when rendering into a Tex2D" + ); #endif - Assert.IsNotNull(rtTarget); - camera.targetTexture = rtTarget; - camera.Render(); - camera.targetTexture = null; - target.IncrementUpdateCount(); - break; - } + Assert.IsNotNull(rtTarget); + camera.targetTexture = rtTarget; + camera.Render(); + camera.targetTexture = null; + target.IncrementUpdateCount(); + break; + } case TextureDimension.Cube: - { - Assert.IsTrue(rtTarget != null || cubeTarget != null); + { + Assert.IsTrue(rtTarget != null || cubeTarget != null); - var canHandleStaticFlags = false; + var canHandleStaticFlags = false; #if UNITY_EDITOR - canHandleStaticFlags = true; + canHandleStaticFlags = true; #endif - // ReSharper disable ConditionIsAlwaysTrueOrFalse - if (canHandleStaticFlags && staticFlags != 0) - // ReSharper restore ConditionIsAlwaysTrueOrFalse - { + // ReSharper disable ConditionIsAlwaysTrueOrFalse + if (canHandleStaticFlags && staticFlags != 0) + // ReSharper restore ConditionIsAlwaysTrueOrFalse + { #if UNITY_EDITOR - UnityEditor.Rendering.EditorCameraUtils.RenderToCubemap( - camera, - rtTarget, - -1, - (UnityEditor.StaticEditorFlags)staticFlags - ); + UnityEditor.Rendering.EditorCameraUtils.RenderToCubemap( + camera, + rtTarget, + -1, + (UnityEditor.StaticEditorFlags)staticFlags + ); #endif - } - else + } + else + { + // ReSharper disable ConditionIsAlwaysTrueOrFalse + if (!canHandleStaticFlags && staticFlags != 0) + // ReSharper restore ConditionIsAlwaysTrueOrFalse { - // ReSharper disable ConditionIsAlwaysTrueOrFalse - if (!canHandleStaticFlags && staticFlags != 0) - // ReSharper restore ConditionIsAlwaysTrueOrFalse - { - Debug.LogWarning( - "A static flags bitmask was provided but this is ignored in player builds" - ); - } - - if (rtTarget != null) - camera.RenderToCubemap(rtTarget); - if (cubeTarget != null) - camera.RenderToCubemap(cubeTarget); + Debug.LogWarning( + "A static flags bitmask was provided but this is ignored in player builds" + ); } - target.IncrementUpdateCount(); - break; + if (rtTarget != null) + camera.RenderToCubemap(rtTarget); + if (cubeTarget != null) + camera.RenderToCubemap(cubeTarget); } + + target.IncrementUpdateCount(); + break; + } } } finally @@ -235,24 +235,24 @@ public static void GenerateRenderingSettingsFor( switch (settings.type) { case ProbeSettings.ProbeType.PlanarProbe: - { - cameras.Add(cameraSettings); - cameraPositions.Add(cameraPositionSettings); - break; - } + { + cameras.Add(cameraSettings); + cameraPositions.Add(cameraPositionSettings); + break; + } case ProbeSettings.ProbeType.ReflectionProbe: + { + for (int i = 0; i < 6; ++i) { - for (int i = 0; i < 6; ++i) - { - var cameraPositionCopy = cameraPositionSettings; - cameraPositionCopy.rotation = cameraPositionCopy.rotation * Quaternion.Euler( - s_GenerateRenderingSettingsFor_Rotations[i] - ); - cameras.Add(cameraSettings); - cameraPositions.Add(cameraPositionCopy); - } - break; + var cameraPositionCopy = cameraPositionSettings; + cameraPositionCopy.rotation = cameraPositionCopy.rotation * Quaternion.Euler( + s_GenerateRenderingSettingsFor_Rotations[i] + ); + cameras.Add(cameraSettings); + cameraPositions.Add(cameraPositionCopy); } + break; + } } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDTextureUtilities.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDTextureUtilities.cs index 7c969703d43..213774f5246 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDTextureUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/HDTextureUtilities.cs @@ -64,36 +64,36 @@ public static Texture2D CopyRenderTextureToTexture2D(RenderTexture source) switch (source.dimension) { case TextureDimension.Cube: - { - var resolution = source.width; + { + var resolution = source.width; - var result = RenderTexture.GetTemporary(resolution * 6, resolution, 0, source.format); - var cmd = new CommandBuffer(); - for (var i = 0; i < 6; ++i) - cmd.CopyTexture(source, i, 0, 0, 0, resolution, resolution, result, 0, 0, i * resolution, 0); - Graphics.ExecuteCommandBuffer(cmd); + var result = RenderTexture.GetTemporary(resolution * 6, resolution, 0, source.format); + var cmd = new CommandBuffer(); + for (var i = 0; i < 6; ++i) + cmd.CopyTexture(source, i, 0, 0, 0, resolution, resolution, result, 0, 0, i * resolution, 0); + Graphics.ExecuteCommandBuffer(cmd); - var t2D = new Texture2D(resolution * 6, resolution, format, false); - var a = RenderTexture.active; - RenderTexture.active = result; - t2D.ReadPixels(new Rect(0, 0, 6 * resolution, resolution), 0, 0, false); - RenderTexture.active = a; - RenderTexture.ReleaseTemporary(result); + var t2D = new Texture2D(resolution * 6, resolution, format, false); + var a = RenderTexture.active; + RenderTexture.active = result; + t2D.ReadPixels(new Rect(0, 0, 6 * resolution, resolution), 0, 0, false); + RenderTexture.active = a; + RenderTexture.ReleaseTemporary(result); - return t2D; - } + return t2D; + } case TextureDimension.Tex2D: - { - var resolution = source.width; - var result = new Texture2D(resolution, resolution, format, false); + { + var resolution = source.width; + var result = new Texture2D(resolution, resolution, format, false); - Graphics.SetRenderTarget(source, 0); - result.ReadPixels(new Rect(0, 0, resolution, resolution), 0, 0); - result.Apply(); - Graphics.SetRenderTarget(null); + Graphics.SetRenderTarget(source, 0); + result.ReadPixels(new Rect(0, 0, resolution, resolution), 0, 0); + result.Apply(); + Graphics.SetRenderTarget(null); - return result; - } + return result; + } default: throw new ArgumentException(); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeCapturePositionSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeCapturePositionSettings.cs index b2d3a2c24e8..03c4bc3f3b9 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeCapturePositionSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeCapturePositionSettings.cs @@ -164,7 +164,7 @@ static ProbeCapturePositionSettings ComputeFrom( // If reference position and proxy position is exactly the same, we end up in some degeneracies triggered // by engine code when computing culling parameters. This is an extremely rare case, but can happen // in editor when focusing on the planar probe. So if that happens, we offset them 0.1 mm apart. - if(Vector3.Distance(result.proxyPosition, referencePosition) < 1e-4f) + if (Vector3.Distance(result.proxyPosition, referencePosition) < 1e-4f) { referencePosition += new Vector3(1e-4f, 1e-4f, 1e-4f); } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettings.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettings.cs index 7a63b3fa1bd..cd97ceb546a 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettings.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettings.cs @@ -131,7 +131,7 @@ public struct Lighting /// A multiplier applied to the radiance of the Probe. public float multiplier; /// A weight applied to the influence of the Probe. - [Range(0,1)] + [Range(0, 1)] public float weight; /// An enum flag to select which Light Layers this Probe interacts with. public LightLayerEnum lightLayer; @@ -265,7 +265,7 @@ public static ProbeSettings NewDefault() /// The proxy settings of the probe for the current volume. public ProxySettings proxySettings; /// An int scalable setting value - [Serializable] public class PlanarReflectionAtlasResolutionScalableSettingValue : ScalableSettingValue { } + [Serializable] public class PlanarReflectionAtlasResolutionScalableSettingValue : ScalableSettingValue {} /// Camera settings to use when capturing data. /// The resolution of the probe. public PlanarReflectionAtlasResolutionScalableSettingValue resolutionScalable; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettingsUtilities.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettingsUtilities.cs index 276a17a4ff2..0981a2dae96 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettingsUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/ProbeSettingsUtilities.cs @@ -60,28 +60,28 @@ public static void ApplySettings( switch (positionMode) { case PositionMode.UseProbeTransform: - { - cameraPosition.mode = CameraPositionSettings.Mode.ComputeWorldToCameraMatrix; - var proxyMatrix = Matrix4x4.TRS(probePosition.proxyPosition, probePosition.proxyRotation, Vector3.one); - cameraPosition.position = proxyMatrix.MultiplyPoint(settings.proxySettings.capturePositionProxySpace); - cameraPosition.rotation = proxyMatrix.rotation * settings.proxySettings.captureRotationProxySpace; - - // In case of probe baking, 99% of the time, orientation of the cubemap doesn't matters - // so, we build one without any rotation, thus we don't have to change the basis - // during sampling the cubemap. - if (settings.type == ProbeSettings.ProbeType.ReflectionProbe) - cameraPosition.rotation = Quaternion.identity; - break; - } + { + cameraPosition.mode = CameraPositionSettings.Mode.ComputeWorldToCameraMatrix; + var proxyMatrix = Matrix4x4.TRS(probePosition.proxyPosition, probePosition.proxyRotation, Vector3.one); + cameraPosition.position = proxyMatrix.MultiplyPoint(settings.proxySettings.capturePositionProxySpace); + cameraPosition.rotation = proxyMatrix.rotation * settings.proxySettings.captureRotationProxySpace; + + // In case of probe baking, 99% of the time, orientation of the cubemap doesn't matters + // so, we build one without any rotation, thus we don't have to change the basis + // during sampling the cubemap. + if (settings.type == ProbeSettings.ProbeType.ReflectionProbe) + cameraPosition.rotation = Quaternion.identity; + break; + } case PositionMode.MirrorReferenceTransformWithProbePlane: - { - cameraPosition.mode = CameraPositionSettings.Mode.UseWorldToCameraMatrixField; - ApplyMirroredReferenceTransform( - ref settings, ref probePosition, - ref cameraSettings, ref cameraPosition - ); - break; - } + { + cameraPosition.mode = CameraPositionSettings.Mode.UseWorldToCameraMatrixField; + ApplyMirroredReferenceTransform( + ref settings, ref probePosition, + ref cameraSettings, ref cameraPosition + ); + break; + } } // Update the clip plane @@ -122,7 +122,7 @@ ref CameraPositionSettings cameraPosition // InOut parameter var mirrorPosition = proxyMatrix.MultiplyPoint(settings.proxySettings.mirrorPositionProxySpace); var mirrorForward = proxyMatrix.MultiplyVector(settings.proxySettings.mirrorRotationProxySpace * Vector3.forward); var reflectionMatrix = GeometryUtils.CalculateReflectionMatrix(mirrorPosition, mirrorForward); - + // If the camera is on the reflection plane, we offset it by 0.1 mm to avoid a degenerate case. if (Vector3.Dot(mirrorForward, probePosition.referencePosition - mirrorPosition) < 1e-4f) probePosition.referencePosition += 1e-4f * mirrorForward; @@ -183,10 +183,10 @@ internal static void ApplyPlanarFrustumHandling( // (A lot of pixel can be discarded in the render texture). This way we can have a greater // resolution for the planar with the same cost. cameraSettings.frustum.fieldOfView = Mathf.Min( - settings.influence.ComputeFOVAt( + settings.influence.ComputeFOVAt( probePosition.referencePosition, mirrorPosition, probePosition.influenceToWorld - ) * settings.frustum.automaticScale, - k_MaxFieldOfView + ) * settings.frustum.automaticScale, + k_MaxFieldOfView ); break; } diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/SceneObjectIDMap.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/SceneObjectIDMap.cs index 1132c6b5464..57642b82a45 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/SceneObjectIDMap.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/SceneObjectIDMap.cs @@ -107,8 +107,8 @@ static SceneObjectIDMapSceneAsset CreateSceneIDMapFor(Scene scene) var gameObject = new GameObject(SceneObjectIDMapSceneAsset.k_GameObjectName) { hideFlags = HideFlags.DontSaveInBuild - | HideFlags.HideInHierarchy - | HideFlags.HideInInspector + | HideFlags.HideInHierarchy + | HideFlags.HideInInspector }; var result = gameObject.AddComponent(); SceneManager.MoveGameObjectToScene(gameObject, scene); @@ -161,7 +161,7 @@ List outGameObjects, List outIndices CleanDestroyedGameObjects(); var intCategory = Convert.ToInt32(category); - for (int i = m_Entries.Count - 1; i >= 0 ; --i) + for (int i = m_Entries.Count - 1; i >= 0; --i) { if (m_Entries[i].category != intCategory) continue; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/TypeInfo.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/TypeInfo.cs index 2e3d33a1bf9..a8fe368557d 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/TypeInfo.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/TypeInfo.cs @@ -5,7 +5,7 @@ namespace UnityEngine.Rendering.HighDefinition static class TypeInfo { struct EnumInfoJITCache - // closest way to constraint to an enum without 'Enum' generic constraint + // closest way to constraint to an enum without 'Enum' generic constraint where TEnum : struct, IConvertible { public static readonly TEnum[] values; diff --git a/com.unity.render-pipelines.high-definition/Runtime/Utilities/VolumeComponentWithQuality.cs b/com.unity.render-pipelines.high-definition/Runtime/Utilities/VolumeComponentWithQuality.cs index 05c52bf7203..4796a8196ff 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/Utilities/VolumeComponentWithQuality.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/Utilities/VolumeComponentWithQuality.cs @@ -14,7 +14,7 @@ public abstract class VolumeComponentWithQuality : VolumeComponent static internal GlobalPostProcessingQualitySettings GetPostProcessingQualitySettings() { var pipeline = (HDRenderPipeline)RenderPipelineManager.currentPipeline; - if(pipeline != null) + if (pipeline != null) { return pipeline.currentPlatformRenderPipelineSettings.postProcessQualitySettings; } @@ -41,6 +41,5 @@ protected bool UsesQualitySettings() { return !quality.levelAndOverride.useOverride && (HDRenderPipeline)RenderPipelineManager.currentPipeline != null; } - } } diff --git a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXCommon.hlsl b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXCommon.hlsl index 78684f3182c..4d3c2f3a1f2 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXCommon.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXCommon.hlsl @@ -39,13 +39,13 @@ void VFXTransformPSInputs(inout VFX_VARYING_PS_INPUTS input) float4 VFXTransformFinalColor(float4 color) { #ifdef DEBUG_DISPLAY - if (_DebugFullScreenMode == FULLSCREENDEBUGMODE_TRANSPARENCY_OVERDRAW) + if (_DebugFullScreenMode == FULLSCREENDEBUGMODE_TRANSPARENCY_OVERDRAW) { color = _DebugTransparencyOverdrawWeight * float4(TRANSPARENCY_OVERDRAW_COST, TRANSPARENCY_OVERDRAW_COST, TRANSPARENCY_OVERDRAW_COST, TRANSPARENCY_OVERDRAW_A); } #endif - return color; + return color; } float4 VFXTransformPositionWorldToClip(float3 posWS) @@ -141,7 +141,7 @@ float4 VFXApplyFog(float4 color,float4 posCS,float3 posWS) float3 volColor, volOpacity; EvaluateAtmosphericScattering(posInput, V, volColor, volOpacity); // Premultiplied alpha - + #if VFX_BLENDMODE_ALPHA color.rgb = color.rgb * (1 - volOpacity) + volColor * color.a; #elif VFX_BLENDMODE_ADD diff --git a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXDefines.hlsl b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXDefines.hlsl index 1bdd262dc40..577dc7d8219 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXDefines.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXDefines.hlsl @@ -3,14 +3,14 @@ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/MaterialBlendModeEnum.cs.hlsl" #if VFX_BLENDMODE_ALPHA - #define _BlendMode BLENDMODE_ALPHA + #define _BlendMode BLENDMODE_ALPHA #elif VFX_BLENDMODE_ADD - #define _BlendMode BLENDMODE_ADDITIVE + #define _BlendMode BLENDMODE_ADDITIVE #elif VFX_BLENDMODE_PREMULTIPLY - #define _BlendMode BLENDMODE_PREMULTIPLY + #define _BlendMode BLENDMODE_PREMULTIPLY #else //Opaque, doesn't really matter what we specify, but a definition is needed to avoid compilation errors. - #define _BlendMode BLENDMODE_ALPHA + #define _BlendMode BLENDMODE_ALPHA #endif #ifdef _BLENDMODE_PRESERVE_SPECULAR_LIGHTING diff --git a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLit.hlsl b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLit.hlsl index 03fb93a5a65..e144ad300de 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLit.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLit.hlsl @@ -74,9 +74,9 @@ BuiltinData VFXGetBuiltinData(const VFX_VARYING_PS_INPUTS i,const PositionInputs #if defined(VFX_VARYING_EMISSIVE) && (HDRP_USE_EMISSIVE_COLOR || HDRP_USE_ADDITIONAL_EMISSIVE_COLOR) builtinData.emissiveColor *= i.VFX_VARYING_EMISSIVE; #endif - #ifdef VFX_VARYING_EXPOSUREWEIGHT - builtinData.emissiveColor *= lerp(GetInverseCurrentExposureMultiplier(),1.0f,i.VFX_VARYING_EXPOSUREWEIGHT); - #endif + #ifdef VFX_VARYING_EXPOSUREWEIGHT + builtinData.emissiveColor *= lerp(GetInverseCurrentExposureMultiplier(),1.0f,i.VFX_VARYING_EXPOSUREWEIGHT); + #endif #endif builtinData.emissiveColor *= opacity; diff --git a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl index d8f996cc6cf..e4520e90ec5 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl +++ b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Shaders/VFXLitPixelOutput.hlsl @@ -93,7 +93,7 @@ float4 VFXGetPixelOutputForward(const VFX_VARYING_PS_INPUTS i, float3 normalWS, VFXGetHDRPLitData(surfaceData,builtinData,bsdfData,preLightData,i,normalWS,uvData,tileIndex); float3 posRWS = VFXGetPositionRWS(i); - PositionInputs posInput = GetPositionInput(i.VFX_VARYING_POSCS.xy, _ScreenSize.zw, i.VFX_VARYING_POSCS.z, i.VFX_VARYING_POSCS.w, posRWS, tileIndex); + PositionInputs posInput = GetPositionInput(i.VFX_VARYING_POSCS.xy, _ScreenSize.zw, i.VFX_VARYING_POSCS.z, i.VFX_VARYING_POSCS.w, posRWS, tileIndex); return VFXCalcPixelOutputForward(surfaceData,builtinData,preLightData, bsdfData, posInput, posRWS); } @@ -104,13 +104,13 @@ float4 VFXGetPixelOutputForward(const VFX_VARYING_PS_INPUTS i, float3 normalWS, float4 VFXGetPixelOutputForwardShaderGraph(const VFX_VARYING_PS_INPUTS i, const SurfaceData surfaceData, float3 emissiveColor, float opacity) { - uint2 tileIndex = uint2(i.VFX_VARYING_POSCS.xy) / GetTileSize(); + uint2 tileIndex = uint2(i.VFX_VARYING_POSCS.xy) / GetTileSize(); float3 posRWS = VFXGetPositionRWS(i); - float4 posSS = i.VFX_VARYING_POSCS; - PositionInputs posInput = GetPositionInput(posSS.xy, _ScreenSize.zw, posSS.z, posSS.w, posRWS, tileIndex); + float4 posSS = i.VFX_VARYING_POSCS; + PositionInputs posInput = GetPositionInput(posSS.xy, _ScreenSize.zw, posSS.z, posSS.w, posRWS, tileIndex); PreLightData preLightData = (PreLightData)0; - BSDFData bsdfData = (BSDFData)0; + BSDFData bsdfData = (BSDFData)0; bsdfData = ConvertSurfaceDataToBSDFData(posSS.xy, surfaceData); preLightData = GetPreLightData(GetWorldSpaceNormalizeViewDir(posRWS),posInput,bsdfData); diff --git a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Utility/PropertyBinders/HDRPCameraBinder.cs b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Utility/PropertyBinders/HDRPCameraBinder.cs index 38155111c86..a8fcbfb7b31 100644 --- a/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Utility/PropertyBinders/HDRPCameraBinder.cs +++ b/com.unity.render-pipelines.high-definition/Runtime/VFXGraph/Utility/PropertyBinders/HDRPCameraBinder.cs @@ -154,7 +154,6 @@ public override void UpdateBinding(VisualEffect component) if (color != null) component.SetTexture(m_ColorBuffer, color.rt); - } /// @@ -166,5 +165,4 @@ public override string ToString() return string.Format($"HDRP Camera : '{(AdditionalData == null? "null" : AdditionalData.gameObject.name)}' -> {CameraProperty}"); } } - } diff --git a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMP_SDF-Mobile_Ztest.shader b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMP_SDF-Mobile_Ztest.shader index ddabb7d5c67..f5add92d4f4 100644 --- a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMP_SDF-Mobile_Ztest.shader +++ b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMP_SDF-Mobile_Ztest.shader @@ -6,233 +6,233 @@ Shader "TextMeshPro/Mobile/Distance FieldZTest" { Properties { - _FaceColor ("Face Color", Color) = (1,1,1,1) - _FaceDilate ("Face Dilate", Range(-1,1)) = 0 - - _OutlineColor ("Outline Color", Color) = (0,0,0,1) - _OutlineWidth ("Outline Thickness", Range(0,1)) = 0 - _OutlineSoftness ("Outline Softness", Range(0,1)) = 0 - - _UnderlayColor ("Border Color", Color) = (0,0,0,.5) - _UnderlayOffsetX ("Border OffsetX", Range(-1,1)) = 0 - _UnderlayOffsetY ("Border OffsetY", Range(-1,1)) = 0 - _UnderlayDilate ("Border Dilate", Range(-1,1)) = 0 - _UnderlaySoftness ("Border Softness", Range(0,1)) = 0 - - _WeightNormal ("Weight Normal", float) = 0 - _WeightBold ("Weight Bold", float) = .5 - - _ShaderFlags ("Flags", float) = 0 - _ScaleRatioA ("Scale RatioA", float) = 1 - _ScaleRatioB ("Scale RatioB", float) = 1 - _ScaleRatioC ("Scale RatioC", float) = 1 - - _MainTex ("Font Atlas", 2D) = "white" {} - _TextureWidth ("Texture Width", float) = 512 - _TextureHeight ("Texture Height", float) = 512 - _GradientScale ("Gradient Scale", float) = 5 - _ScaleX ("Scale X", float) = 1 - _ScaleY ("Scale Y", float) = 1 - _PerspectiveFilter ("Perspective Correction", Range(0, 1)) = 0.875 - _Sharpness ("Sharpness", Range(-1,1)) = 0 - - _VertexOffsetX ("Vertex OffsetX", float) = 0 - _VertexOffsetY ("Vertex OffsetY", float) = 0 - - _ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767) - _MaskSoftnessX ("Mask SoftnessX", float) = 0 - _MaskSoftnessY ("Mask SoftnessY", float) = 0 - - _StencilComp ("Stencil Comparison", Float) = 8 - _Stencil ("Stencil ID", Float) = 0 - _StencilOp ("Stencil Operation", Float) = 0 - _StencilWriteMask ("Stencil Write Mask", Float) = 255 - _StencilReadMask ("Stencil Read Mask", Float) = 255 - - _ColorMask ("Color Mask", Float) = 15 + _FaceColor ("Face Color", Color) = (1,1,1,1) + _FaceDilate ("Face Dilate", Range(-1,1)) = 0 + + _OutlineColor ("Outline Color", Color) = (0,0,0,1) + _OutlineWidth ("Outline Thickness", Range(0,1)) = 0 + _OutlineSoftness ("Outline Softness", Range(0,1)) = 0 + + _UnderlayColor ("Border Color", Color) = (0,0,0,.5) + _UnderlayOffsetX ("Border OffsetX", Range(-1,1)) = 0 + _UnderlayOffsetY ("Border OffsetY", Range(-1,1)) = 0 + _UnderlayDilate ("Border Dilate", Range(-1,1)) = 0 + _UnderlaySoftness ("Border Softness", Range(0,1)) = 0 + + _WeightNormal ("Weight Normal", float) = 0 + _WeightBold ("Weight Bold", float) = .5 + + _ShaderFlags ("Flags", float) = 0 + _ScaleRatioA ("Scale RatioA", float) = 1 + _ScaleRatioB ("Scale RatioB", float) = 1 + _ScaleRatioC ("Scale RatioC", float) = 1 + + _MainTex ("Font Atlas", 2D) = "white" {} + _TextureWidth ("Texture Width", float) = 512 + _TextureHeight ("Texture Height", float) = 512 + _GradientScale ("Gradient Scale", float) = 5 + _ScaleX ("Scale X", float) = 1 + _ScaleY ("Scale Y", float) = 1 + _PerspectiveFilter ("Perspective Correction", Range(0, 1)) = 0.875 + _Sharpness ("Sharpness", Range(-1,1)) = 0 + + _VertexOffsetX ("Vertex OffsetX", float) = 0 + _VertexOffsetY ("Vertex OffsetY", float) = 0 + + _ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767) + _MaskSoftnessX ("Mask SoftnessX", float) = 0 + _MaskSoftnessY ("Mask SoftnessY", float) = 0 + + _StencilComp ("Stencil Comparison", Float) = 8 + _Stencil ("Stencil ID", Float) = 0 + _StencilOp ("Stencil Operation", Float) = 0 + _StencilWriteMask ("Stencil Write Mask", Float) = 255 + _StencilReadMask ("Stencil Read Mask", Float) = 255 + + _ColorMask ("Color Mask", Float) = 15 } SubShader { - Tags - { - "Queue"="Transparent" - "IgnoreProjector"="True" - "RenderType"="Transparent" - } - - - Stencil - { - Ref [_Stencil] - Comp [_StencilComp] - Pass [_StencilOp] - ReadMask [_StencilReadMask] - WriteMask [_StencilWriteMask] - } - - Cull [_CullMode] - ZWrite Off - Lighting Off - Fog { Mode Off } - ZTest LEqual - Blend One OneMinusSrcAlpha - ColorMask [_ColorMask] - - Pass { - CGPROGRAM - #pragma vertex VertShader - #pragma fragment PixShader - #pragma shader_feature __ OUTLINE_ON - #pragma shader_feature __ UNDERLAY_ON UNDERLAY_INNER - - #pragma multi_compile __ UNITY_UI_CLIP_RECT - #pragma multi_compile __ UNITY_UI_ALPHACLIP - - #include "UnityCG.cginc" - #include "UnityUI.cginc" - #include "TMPro_Properties.cginc" - - struct vertex_t { - UNITY_VERTEX_INPUT_INSTANCE_ID - float4 vertex : POSITION; - float3 normal : NORMAL; - fixed4 color : COLOR; - float2 texcoord0 : TEXCOORD0; - float2 texcoord1 : TEXCOORD1; - }; - - struct pixel_t { - UNITY_VERTEX_INPUT_INSTANCE_ID - UNITY_VERTEX_OUTPUT_STEREO - float4 vertex : SV_POSITION; - fixed4 faceColor : COLOR; - fixed4 outlineColor : COLOR1; - float4 texcoord0 : TEXCOORD0; // Texture UV, Mask UV - half4 param : TEXCOORD1; // Scale(x), BiasIn(y), BiasOut(z), Bias(w) - half4 mask : TEXCOORD2; // Position in clip space(xy), Softness(zw) - #if (UNDERLAY_ON | UNDERLAY_INNER) - float4 texcoord1 : TEXCOORD3; // Texture UV, alpha, reserved - half2 underlayParam : TEXCOORD4; // Scale(x), Bias(y) - #endif - }; - - - pixel_t VertShader(vertex_t input) - { - pixel_t output; - - UNITY_INITIALIZE_OUTPUT(pixel_t, output); - UNITY_SETUP_INSTANCE_ID(input); - UNITY_TRANSFER_INSTANCE_ID(input, output); - UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); - - float bold = step(input.texcoord1.y, 0); - - float4 vert = input.vertex; - vert.x += _VertexOffsetX; - vert.y += _VertexOffsetY; - float4 vPosition = UnityObjectToClipPos(vert); - - float2 pixelSize = vPosition.w; - pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy)); - - float scale = rsqrt(dot(pixelSize, pixelSize)); - scale *= abs(input.texcoord1.y) * _GradientScale * (_Sharpness + 1); - if(UNITY_MATRIX_P[3][3] == 0) scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(input.normal.xyz), normalize(WorldSpaceViewDir(vert))))); - - float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0; - weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5; - - float layerScale = scale; - - scale /= 1 + (_OutlineSoftness * _ScaleRatioA * scale); - float bias = (0.5 - weight) * scale - 0.5; - float outline = _OutlineWidth * _ScaleRatioA * 0.5 * scale; - - float opacity = input.color.a; - #if (UNDERLAY_ON | UNDERLAY_INNER) - opacity = 1.0; - #endif - - fixed4 faceColor = fixed4(input.color.rgb, opacity) * _FaceColor; - faceColor.rgb *= faceColor.a; - - fixed4 outlineColor = _OutlineColor; - outlineColor.a *= opacity; - outlineColor.rgb *= outlineColor.a; - outlineColor = lerp(faceColor, outlineColor, sqrt(min(1.0, (outline * 2)))); - - #if (UNDERLAY_ON | UNDERLAY_INNER) - layerScale /= 1 + ((_UnderlaySoftness * _ScaleRatioC) * layerScale); - float layerBias = (.5 - weight) * layerScale - .5 - ((_UnderlayDilate * _ScaleRatioC) * .5 * layerScale); - - float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth; - float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight; - float2 layerOffset = float2(x, y); - #endif - - // Generate UV for the Masking Texture - float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); - float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy); - - // Populate structure for pixel shader - output.vertex = vPosition; - output.faceColor = faceColor; - output.outlineColor = outlineColor; - output.texcoord0 = float4(input.texcoord0.x, input.texcoord0.y, maskUV.x, maskUV.y); - output.param = half4(scale, bias - outline, bias + outline, bias); - output.mask = half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_MaskSoftnessX, _MaskSoftnessY) + pixelSize.xy)); - #if (UNDERLAY_ON || UNDERLAY_INNER) - output.texcoord1 = float4(input.texcoord0 + layerOffset, input.color.a, 0); - output.underlayParam = half2(layerScale, layerBias); - #endif - - return output; - } - - - // PIXEL SHADER - fixed4 PixShader(pixel_t input) : SV_Target - { - UNITY_SETUP_INSTANCE_ID(input); - - half d = tex2D(_MainTex, input.texcoord0.xy).a * input.param.x; - half4 c = input.faceColor * saturate(d - input.param.w); - - #ifdef OUTLINE_ON - c = lerp(input.outlineColor, input.faceColor, saturate(d - input.param.z)); - c *= saturate(d - input.param.y); - #endif - - #if UNDERLAY_ON - d = tex2D(_MainTex, input.texcoord1.xy).a * input.underlayParam.x; - c += float4(_UnderlayColor.rgb * _UnderlayColor.a, _UnderlayColor.a) * saturate(d - input.underlayParam.y) * (1 - c.a); - #endif - - #if UNDERLAY_INNER - half sd = saturate(d - input.param.z); - d = tex2D(_MainTex, input.texcoord1.xy).a * input.underlayParam.x; - c += float4(_UnderlayColor.rgb * _UnderlayColor.a, _UnderlayColor.a) * (1 - saturate(d - input.underlayParam.y)) * sd * (1 - c.a); - #endif - - // Alternative implementation to UnityGet2DClipping with support for softness. - #if UNITY_UI_CLIP_RECT - half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw); - c *= m.x * m.y; - #endif - - #if (UNDERLAY_ON | UNDERLAY_INNER) - c *= input.texcoord1.z; - #endif - - #if UNITY_UI_ALPHACLIP - clip(c.a - 0.001); - #endif - - return c; - } - ENDCG - } + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + } + + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull [_CullMode] + ZWrite Off + Lighting Off + Fog { Mode Off } + ZTest LEqual + Blend One OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass { + CGPROGRAM + #pragma vertex VertShader + #pragma fragment PixShader + #pragma shader_feature __ OUTLINE_ON + #pragma shader_feature __ UNDERLAY_ON UNDERLAY_INNER + + #pragma multi_compile __ UNITY_UI_CLIP_RECT + #pragma multi_compile __ UNITY_UI_ALPHACLIP + + #include "UnityCG.cginc" + #include "UnityUI.cginc" + #include "TMPro_Properties.cginc" + + struct vertex_t { + UNITY_VERTEX_INPUT_INSTANCE_ID + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float2 texcoord0 : TEXCOORD0; + float2 texcoord1 : TEXCOORD1; + }; + + struct pixel_t { + UNITY_VERTEX_INPUT_INSTANCE_ID + UNITY_VERTEX_OUTPUT_STEREO + float4 vertex : SV_POSITION; + fixed4 faceColor : COLOR; + fixed4 outlineColor : COLOR1; + float4 texcoord0 : TEXCOORD0; // Texture UV, Mask UV + half4 param : TEXCOORD1; // Scale(x), BiasIn(y), BiasOut(z), Bias(w) + half4 mask : TEXCOORD2; // Position in clip space(xy), Softness(zw) + #if (UNDERLAY_ON | UNDERLAY_INNER) + float4 texcoord1 : TEXCOORD3; // Texture UV, alpha, reserved + half2 underlayParam : TEXCOORD4; // Scale(x), Bias(y) + #endif + }; + + + pixel_t VertShader(vertex_t input) + { + pixel_t output; + + UNITY_INITIALIZE_OUTPUT(pixel_t, output); + UNITY_SETUP_INSTANCE_ID(input); + UNITY_TRANSFER_INSTANCE_ID(input, output); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); + + float bold = step(input.texcoord1.y, 0); + + float4 vert = input.vertex; + vert.x += _VertexOffsetX; + vert.y += _VertexOffsetY; + float4 vPosition = UnityObjectToClipPos(vert); + + float2 pixelSize = vPosition.w; + pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy)); + + float scale = rsqrt(dot(pixelSize, pixelSize)); + scale *= abs(input.texcoord1.y) * _GradientScale * (_Sharpness + 1); + if(UNITY_MATRIX_P[3][3] == 0) scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(input.normal.xyz), normalize(WorldSpaceViewDir(vert))))); + + float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0; + weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5; + + float layerScale = scale; + + scale /= 1 + (_OutlineSoftness * _ScaleRatioA * scale); + float bias = (0.5 - weight) * scale - 0.5; + float outline = _OutlineWidth * _ScaleRatioA * 0.5 * scale; + + float opacity = input.color.a; + #if (UNDERLAY_ON | UNDERLAY_INNER) + opacity = 1.0; + #endif + + fixed4 faceColor = fixed4(input.color.rgb, opacity) * _FaceColor; + faceColor.rgb *= faceColor.a; + + fixed4 outlineColor = _OutlineColor; + outlineColor.a *= opacity; + outlineColor.rgb *= outlineColor.a; + outlineColor = lerp(faceColor, outlineColor, sqrt(min(1.0, (outline * 2)))); + + #if (UNDERLAY_ON | UNDERLAY_INNER) + layerScale /= 1 + ((_UnderlaySoftness * _ScaleRatioC) * layerScale); + float layerBias = (.5 - weight) * layerScale - .5 - ((_UnderlayDilate * _ScaleRatioC) * .5 * layerScale); + + float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth; + float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight; + float2 layerOffset = float2(x, y); + #endif + + // Generate UV for the Masking Texture + float4 clampedRect = clamp(_ClipRect, -2e10, 2e10); + float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy); + + // Populate structure for pixel shader + output.vertex = vPosition; + output.faceColor = faceColor; + output.outlineColor = outlineColor; + output.texcoord0 = float4(input.texcoord0.x, input.texcoord0.y, maskUV.x, maskUV.y); + output.param = half4(scale, bias - outline, bias + outline, bias); + output.mask = half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * half2(_MaskSoftnessX, _MaskSoftnessY) + pixelSize.xy)); + #if (UNDERLAY_ON || UNDERLAY_INNER) + output.texcoord1 = float4(input.texcoord0 + layerOffset, input.color.a, 0); + output.underlayParam = half2(layerScale, layerBias); + #endif + + return output; + } + + + // PIXEL SHADER + fixed4 PixShader(pixel_t input) : SV_Target + { + UNITY_SETUP_INSTANCE_ID(input); + + half d = tex2D(_MainTex, input.texcoord0.xy).a * input.param.x; + half4 c = input.faceColor * saturate(d - input.param.w); + + #ifdef OUTLINE_ON + c = lerp(input.outlineColor, input.faceColor, saturate(d - input.param.z)); + c *= saturate(d - input.param.y); + #endif + + #if UNDERLAY_ON + d = tex2D(_MainTex, input.texcoord1.xy).a * input.underlayParam.x; + c += float4(_UnderlayColor.rgb * _UnderlayColor.a, _UnderlayColor.a) * saturate(d - input.underlayParam.y) * (1 - c.a); + #endif + + #if UNDERLAY_INNER + half sd = saturate(d - input.param.z); + d = tex2D(_MainTex, input.texcoord1.xy).a * input.underlayParam.x; + c += float4(_UnderlayColor.rgb * _UnderlayColor.a, _UnderlayColor.a) * (1 - saturate(d - input.underlayParam.y)) * sd * (1 - c.a); + #endif + + // Alternative implementation to UnityGet2DClipping with support for softness. + #if UNITY_UI_CLIP_RECT + half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw); + c *= m.x * m.y; + #endif + + #if (UNDERLAY_ON | UNDERLAY_INNER) + c *= input.texcoord1.z; + #endif + + #if UNITY_UI_ALPHACLIP + clip(c.a - 0.001); + #endif + + return c; + } + ENDCG + } } CustomEditor "TMPro.EditorUtilities.TMP_SDFShaderGUI" diff --git a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro.cginc b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro.cginc index 5898130446f..11613ecc8b5 100644 --- a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro.cginc +++ b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro.cginc @@ -1,84 +1,83 @@ float2 UnpackUV(float uv) -{ - float2 output; - output.x = floor(uv / 4096); - output.y = uv - 4096 * output.x; +{ + float2 output; + output.x = floor(uv / 4096); + output.y = uv - 4096 * output.x; - return output * 0.001953125; + return output * 0.001953125; } fixed4 GetColor(half d, fixed4 faceColor, fixed4 outlineColor, half outline, half softness) { - half faceAlpha = 1-saturate((d - outline * 0.5 + softness * 0.5) / (1.0 + softness)); - half outlineAlpha = saturate((d + outline * 0.5)) * sqrt(min(1.0, outline)); + half faceAlpha = 1-saturate((d - outline * 0.5 + softness * 0.5) / (1.0 + softness)); + half outlineAlpha = saturate((d + outline * 0.5)) * sqrt(min(1.0, outline)); - faceColor.rgb *= faceColor.a; - outlineColor.rgb *= outlineColor.a; + faceColor.rgb *= faceColor.a; + outlineColor.rgb *= outlineColor.a; - faceColor = lerp(faceColor, outlineColor, outlineAlpha); + faceColor = lerp(faceColor, outlineColor, outlineAlpha); - faceColor *= faceAlpha; + faceColor *= faceAlpha; - return faceColor; + return faceColor; } float3 GetSurfaceNormal(float4 h, float bias) { - bool raisedBevel = step(1, fmod(_ShaderFlags, 2)); + bool raisedBevel = step(1, fmod(_ShaderFlags, 2)); - h += bias+_BevelOffset; + h += bias+_BevelOffset; - float bevelWidth = max(.01, _OutlineWidth+_BevelWidth); + float bevelWidth = max(.01, _OutlineWidth+_BevelWidth); // Track outline - h -= .5; - h /= bevelWidth; - h = saturate(h+.5); + h -= .5; + h /= bevelWidth; + h = saturate(h+.5); - if(raisedBevel) h = 1 - abs(h*2.0 - 1.0); - h = lerp(h, sin(h*3.141592/2.0), _BevelRoundness); - h = min(h, 1.0-_BevelClamp); - h *= _Bevel * bevelWidth * _GradientScale * -2.0; + if(raisedBevel) h = 1 - abs(h*2.0 - 1.0); + h = lerp(h, sin(h*3.141592/2.0), _BevelRoundness); + h = min(h, 1.0-_BevelClamp); + h *= _Bevel * bevelWidth * _GradientScale * -2.0; - float3 va = normalize(float3(1.0, 0.0, h.y - h.x)); - float3 vb = normalize(float3(0.0, -1.0, h.w - h.z)); + float3 va = normalize(float3(1.0, 0.0, h.y - h.x)); + float3 vb = normalize(float3(0.0, -1.0, h.w - h.z)); - return cross(va, vb); + return cross(va, vb); } float3 GetSurfaceNormal(float2 uv, float bias, float3 delta) { - // Read "height field" + // Read "height field" float4 h = {tex2D(_MainTex, uv - delta.xz).a, - tex2D(_MainTex, uv + delta.xz).a, - tex2D(_MainTex, uv - delta.zy).a, - tex2D(_MainTex, uv + delta.zy).a}; + tex2D(_MainTex, uv + delta.xz).a, + tex2D(_MainTex, uv - delta.zy).a, + tex2D(_MainTex, uv + delta.zy).a}; - return GetSurfaceNormal(h, bias); + return GetSurfaceNormal(h, bias); } float3 GetSpecular(float3 n, float3 l) { - float spec = pow(max(0.0, dot(n, l)), _Reflectivity); - return _SpecularColor.rgb * spec * _SpecularPower; + float spec = pow(max(0.0, dot(n, l)), _Reflectivity); + return _SpecularColor.rgb * spec * _SpecularPower; } float4 GetGlowColor(float d, float scale) { - float glow = d - (_GlowOffset*_ScaleRatioB) * 0.5 * scale; - float t = lerp(_GlowInner, (_GlowOuter * _ScaleRatioB), step(0.0, glow)) * 0.5 * scale; - glow = saturate(abs(glow/(1.0 + t))); - glow = 1.0-pow(glow, _GlowPower); - glow *= sqrt(min(1.0, t)); // Fade off glow thinner than 1 screen pixel - return float4(_GlowColor.rgb, saturate(_GlowColor.a * glow * 2)); + float glow = d - (_GlowOffset*_ScaleRatioB) * 0.5 * scale; + float t = lerp(_GlowInner, (_GlowOuter * _ScaleRatioB), step(0.0, glow)) * 0.5 * scale; + glow = saturate(abs(glow/(1.0 + t))); + glow = 1.0-pow(glow, _GlowPower); + glow *= sqrt(min(1.0, t)); // Fade off glow thinner than 1 screen pixel + return float4(_GlowColor.rgb, saturate(_GlowColor.a * glow * 2)); } float4 BlendARGB(float4 overlying, float4 underlying) { - overlying.rgb *= overlying.a; - underlying.rgb *= underlying.a; - float3 blended = overlying.rgb + ((1-overlying.a)*underlying.rgb); - float alpha = underlying.a + (1-underlying.a)*overlying.a; - return float4(blended, alpha); + overlying.rgb *= overlying.a; + underlying.rgb *= underlying.a; + float3 blended = overlying.rgb + ((1-overlying.a)*underlying.rgb); + float alpha = underlying.a + (1-underlying.a)*overlying.a; + return float4(blended, alpha); } - diff --git a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Properties.cginc b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Properties.cginc index 2e962588cf9..a1a3981f458 100644 --- a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Properties.cginc +++ b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Properties.cginc @@ -1,85 +1,85 @@ // UI Editable properties -uniform sampler2D _FaceTex; // Alpha : Signed Distance -uniform float _FaceUVSpeedX; -uniform float _FaceUVSpeedY; -uniform fixed4 _FaceColor; // RGBA : Color + Opacity -uniform float _FaceDilate; // v[ 0, 1] -uniform float _OutlineSoftness; // v[ 0, 1] +uniform sampler2D _FaceTex; // Alpha : Signed Distance +uniform float _FaceUVSpeedX; +uniform float _FaceUVSpeedY; +uniform fixed4 _FaceColor; // RGBA : Color + Opacity +uniform float _FaceDilate; // v[ 0, 1] +uniform float _OutlineSoftness; // v[ 0, 1] -uniform sampler2D _OutlineTex; // RGBA : Color + Opacity -uniform float _OutlineUVSpeedX; -uniform float _OutlineUVSpeedY; -uniform fixed4 _OutlineColor; // RGBA : Color + Opacity -uniform float _OutlineWidth; // v[ 0, 1] +uniform sampler2D _OutlineTex; // RGBA : Color + Opacity +uniform float _OutlineUVSpeedX; +uniform float _OutlineUVSpeedY; +uniform fixed4 _OutlineColor; // RGBA : Color + Opacity +uniform float _OutlineWidth; // v[ 0, 1] -uniform float _Bevel; // v[ 0, 1] -uniform float _BevelOffset; // v[-1, 1] -uniform float _BevelWidth; // v[-1, 1] -uniform float _BevelClamp; // v[ 0, 1] -uniform float _BevelRoundness; // v[ 0, 1] +uniform float _Bevel; // v[ 0, 1] +uniform float _BevelOffset; // v[-1, 1] +uniform float _BevelWidth; // v[-1, 1] +uniform float _BevelClamp; // v[ 0, 1] +uniform float _BevelRoundness; // v[ 0, 1] -uniform sampler2D _BumpMap; // Normal map -uniform float _BumpOutline; // v[ 0, 1] -uniform float _BumpFace; // v[ 0, 1] +uniform sampler2D _BumpMap; // Normal map +uniform float _BumpOutline; // v[ 0, 1] +uniform float _BumpFace; // v[ 0, 1] -uniform samplerCUBE _Cube; // Cube / sphere map -uniform fixed4 _ReflectFaceColor; // RGB intensity -uniform fixed4 _ReflectOutlineColor; -//uniform float _EnvTiltX; // v[-1, 1] -//uniform float _EnvTiltY; // v[-1, 1] +uniform samplerCUBE _Cube; // Cube / sphere map +uniform fixed4 _ReflectFaceColor; // RGB intensity +uniform fixed4 _ReflectOutlineColor; +//uniform float _EnvTiltX; // v[-1, 1] +//uniform float _EnvTiltY; // v[-1, 1] uniform float3 _EnvMatrixRotation; -uniform float4x4 _EnvMatrix; +uniform float4x4 _EnvMatrix; -uniform fixed4 _SpecularColor; // RGB intensity -uniform float _LightAngle; // v[ 0,Tau] -uniform float _SpecularPower; // v[ 0, 1] -uniform float _Reflectivity; // v[ 5, 15] -uniform float _Diffuse; // v[ 0, 1] -uniform float _Ambient; // v[ 0, 1] +uniform fixed4 _SpecularColor; // RGB intensity +uniform float _LightAngle; // v[ 0,Tau] +uniform float _SpecularPower; // v[ 0, 1] +uniform float _Reflectivity; // v[ 5, 15] +uniform float _Diffuse; // v[ 0, 1] +uniform float _Ambient; // v[ 0, 1] -uniform fixed4 _UnderlayColor; // RGBA : Color + Opacity -uniform float _UnderlayOffsetX; // v[-1, 1] -uniform float _UnderlayOffsetY; // v[-1, 1] -uniform float _UnderlayDilate; // v[-1, 1] -uniform float _UnderlaySoftness; // v[ 0, 1] +uniform fixed4 _UnderlayColor; // RGBA : Color + Opacity +uniform float _UnderlayOffsetX; // v[-1, 1] +uniform float _UnderlayOffsetY; // v[-1, 1] +uniform float _UnderlayDilate; // v[-1, 1] +uniform float _UnderlaySoftness; // v[ 0, 1] -uniform fixed4 _GlowColor; // RGBA : Color + Intesity -uniform float _GlowOffset; // v[-1, 1] -uniform float _GlowOuter; // v[ 0, 1] -uniform float _GlowInner; // v[ 0, 1] -uniform float _GlowPower; // v[ 1, 1/(1+4*4)] +uniform fixed4 _GlowColor; // RGBA : Color + Intesity +uniform float _GlowOffset; // v[-1, 1] +uniform float _GlowOuter; // v[ 0, 1] +uniform float _GlowInner; // v[ 0, 1] +uniform float _GlowPower; // v[ 1, 1/(1+4*4)] // API Editable properties -uniform float _ShaderFlags; -uniform float _WeightNormal; -uniform float _WeightBold; +uniform float _ShaderFlags; +uniform float _WeightNormal; +uniform float _WeightBold; -uniform float _ScaleRatioA; -uniform float _ScaleRatioB; -uniform float _ScaleRatioC; +uniform float _ScaleRatioA; +uniform float _ScaleRatioB; +uniform float _ScaleRatioC; -uniform float _VertexOffsetX; -uniform float _VertexOffsetY; +uniform float _VertexOffsetX; +uniform float _VertexOffsetY; -//uniform float _UseClipRect; -uniform float _MaskID; -uniform sampler2D _MaskTex; -uniform float4 _MaskCoord; -uniform float4 _ClipRect; // bottom left(x,y) : top right(z,w) -//uniform float _MaskWipeControl; -//uniform float _MaskEdgeSoftness; -//uniform fixed4 _MaskEdgeColor; -//uniform bool _MaskInverse; +//uniform float _UseClipRect; +uniform float _MaskID; +uniform sampler2D _MaskTex; +uniform float4 _MaskCoord; +uniform float4 _ClipRect; // bottom left(x,y) : top right(z,w) +//uniform float _MaskWipeControl; +//uniform float _MaskEdgeSoftness; +//uniform fixed4 _MaskEdgeColor; +//uniform bool _MaskInverse; -uniform float _MaskSoftnessX; -uniform float _MaskSoftnessY; +uniform float _MaskSoftnessX; +uniform float _MaskSoftnessY; // Font Atlas properties -uniform sampler2D _MainTex; -uniform float _TextureWidth; -uniform float _TextureHeight; -uniform float _GradientScale; -uniform float _ScaleX; -uniform float _ScaleY; -uniform float _PerspectiveFilter; -uniform float _Sharpness; +uniform sampler2D _MainTex; +uniform float _TextureWidth; +uniform float _TextureHeight; +uniform float _GradientScale; +uniform float _ScaleX; +uniform float _ScaleY; +uniform float _PerspectiveFilter; +uniform float _Sharpness; diff --git a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Surface.cginc b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Surface.cginc index 9a58aef2693..495c3ec8461 100644 --- a/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Surface.cginc +++ b/com.unity.render-pipelines.high-definition/Samples~/MaterialSamples/TextMesh Pro/Resources/Shaders/TMPro_Surface.cginc @@ -1,115 +1,115 @@ void VertShader(inout appdata_full v, out Input data) { - v.vertex.x += _VertexOffsetX; - v.vertex.y += _VertexOffsetY; + v.vertex.x += _VertexOffsetX; + v.vertex.y += _VertexOffsetY; - UNITY_INITIALIZE_OUTPUT(Input, data); + UNITY_INITIALIZE_OUTPUT(Input, data); - float bold = step(v.texcoord1.y, 0); + float bold = step(v.texcoord1.y, 0); - // Generate normal for backface - float3 view = ObjSpaceViewDir(v.vertex); - v.normal *= sign(dot(v.normal, view)); + // Generate normal for backface + float3 view = ObjSpaceViewDir(v.vertex); + v.normal *= sign(dot(v.normal, view)); #if USE_DERIVATIVE - data.param.y = 1; + data.param.y = 1; #else - float4 vert = v.vertex; - float4 vPosition = UnityObjectToClipPos(vert); - float2 pixelSize = vPosition.w; - - pixelSize /= float2(_ScaleX, _ScaleY) * mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy); - float scale = rsqrt(dot(pixelSize, pixelSize)); - scale *= abs(v.texcoord1.y) * _GradientScale * (_Sharpness + 1); - scale = lerp(scale * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(v.normal.xyz), normalize(WorldSpaceViewDir(vert))))); - data.param.y = scale; + float4 vert = v.vertex; + float4 vPosition = UnityObjectToClipPos(vert); + float2 pixelSize = vPosition.w; + + pixelSize /= float2(_ScaleX, _ScaleY) * mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy); + float scale = rsqrt(dot(pixelSize, pixelSize)); + scale *= abs(v.texcoord1.y) * _GradientScale * (_Sharpness + 1); + scale = lerp(scale * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(v.normal.xyz), normalize(WorldSpaceViewDir(vert))))); + data.param.y = scale; #endif - //float opacity = v.color.a; + //float opacity = v.color.a; - data.param.x = (lerp(_WeightNormal, _WeightBold, bold) / 4.0 + _FaceDilate) * _ScaleRatioA * 0.5; // + data.param.x = (lerp(_WeightNormal, _WeightBold, bold) / 4.0 + _FaceDilate) * _ScaleRatioA * 0.5; // - v.texcoord1.xy = UnpackUV(v.texcoord1.x); - data.viewDirEnv = mul((float3x3)_EnvMatrix, WorldSpaceViewDir(v.vertex)); + v.texcoord1.xy = UnpackUV(v.texcoord1.x); + data.viewDirEnv = mul((float3x3)_EnvMatrix, WorldSpaceViewDir(v.vertex)); } void PixShader(Input input, inout SurfaceOutput o) { #if USE_DERIVATIVE | BEVEL_ON - float3 delta = float3(1.0 / _TextureWidth, 1.0 / _TextureHeight, 0.0); + float3 delta = float3(1.0 / _TextureWidth, 1.0 / _TextureHeight, 0.0); - float4 smp4x = { tex2D(_MainTex, input.uv_MainTex - delta.xz).a, - tex2D(_MainTex, input.uv_MainTex + delta.xz).a, - tex2D(_MainTex, input.uv_MainTex - delta.zy).a, - tex2D(_MainTex, input.uv_MainTex + delta.zy).a }; + float4 smp4x = { tex2D(_MainTex, input.uv_MainTex - delta.xz).a, + tex2D(_MainTex, input.uv_MainTex + delta.xz).a, + tex2D(_MainTex, input.uv_MainTex - delta.zy).a, + tex2D(_MainTex, input.uv_MainTex + delta.zy).a }; #endif #if USE_DERIVATIVE - // Screen space scaling reciprocal with anisotropic correction - float2 edgeNormal = Normalize(float2(smp4x.x - smp4x.y, smp4x.z - smp4x.w)); - float2 res = float2(_TextureWidth * input.param.y, _TextureHeight); - float2 tdx = ddx(input.uv_MainTex)*res; - float2 tdy = ddy(input.uv_MainTex)*res; - float lx = length(tdx); - float ly = length(tdy); - float s = sqrt(min(lx, ly) / max(lx, ly)); - s = lerp(1, s, abs(dot(normalize(tdx + tdy), edgeNormal))); - float scale = rsqrt(abs(tdx.x * tdy.y - tdx.y * tdy.x)) * (_GradientScale * 2) * s; + // Screen space scaling reciprocal with anisotropic correction + float2 edgeNormal = Normalize(float2(smp4x.x - smp4x.y, smp4x.z - smp4x.w)); + float2 res = float2(_TextureWidth * input.param.y, _TextureHeight); + float2 tdx = ddx(input.uv_MainTex)*res; + float2 tdy = ddy(input.uv_MainTex)*res; + float lx = length(tdx); + float ly = length(tdy); + float s = sqrt(min(lx, ly) / max(lx, ly)); + s = lerp(1, s, abs(dot(normalize(tdx + tdy), edgeNormal))); + float scale = rsqrt(abs(tdx.x * tdy.y - tdx.y * tdy.x)) * (_GradientScale * 2) * s; #else - float scale = input.param.y; + float scale = input.param.y; #endif - // Signed distance - float c = tex2D(_MainTex, input.uv_MainTex).a; - float sd = (.5 - c - input.param.x) * scale + .5; - float outline = _OutlineWidth*_ScaleRatioA * scale; - float softness = _OutlineSoftness*_ScaleRatioA * scale; + // Signed distance + float c = tex2D(_MainTex, input.uv_MainTex).a; + float sd = (.5 - c - input.param.x) * scale + .5; + float outline = _OutlineWidth*_ScaleRatioA * scale; + float softness = _OutlineSoftness*_ScaleRatioA * scale; - // Color & Alpha - float4 faceColor = _FaceColor; - float4 outlineColor = _OutlineColor; - faceColor *= input.color; - outlineColor.a *= input.color.a; - faceColor *= tex2D(_FaceTex, float2(input.uv2_FaceTex.x + _FaceUVSpeedX * _Time.y, input.uv2_FaceTex.y + _FaceUVSpeedY * _Time.y)); - outlineColor *= tex2D(_OutlineTex, float2(input.uv2_OutlineTex.x + _OutlineUVSpeedX * _Time.y, input.uv2_OutlineTex.y + _OutlineUVSpeedY * _Time.y)); - faceColor = GetColor(sd, faceColor, outlineColor, outline, softness); - faceColor.rgb /= max(faceColor.a, 0.0001); + // Color & Alpha + float4 faceColor = _FaceColor; + float4 outlineColor = _OutlineColor; + faceColor *= input.color; + outlineColor.a *= input.color.a; + faceColor *= tex2D(_FaceTex, float2(input.uv2_FaceTex.x + _FaceUVSpeedX * _Time.y, input.uv2_FaceTex.y + _FaceUVSpeedY * _Time.y)); + outlineColor *= tex2D(_OutlineTex, float2(input.uv2_OutlineTex.x + _OutlineUVSpeedX * _Time.y, input.uv2_OutlineTex.y + _OutlineUVSpeedY * _Time.y)); + faceColor = GetColor(sd, faceColor, outlineColor, outline, softness); + faceColor.rgb /= max(faceColor.a, 0.0001); #if BEVEL_ON - // Face Normal - float3 n = GetSurfaceNormal(smp4x, input.param.x); - - // Bumpmap - float3 bump = UnpackNormal(tex2D(_BumpMap, input.uv2_FaceTex.xy)).xyz; - bump *= lerp(_BumpFace, _BumpOutline, saturate(sd + outline * 0.5)); - bump = lerp(float3(0, 0, 1), bump, faceColor.a); - n = normalize(n - bump); - - // Cubemap reflection - fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDirEnv, mul((float3x3)unity_ObjectToWorld, n))); - float3 emission = reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a; + // Face Normal + float3 n = GetSurfaceNormal(smp4x, input.param.x); + + // Bumpmap + float3 bump = UnpackNormal(tex2D(_BumpMap, input.uv2_FaceTex.xy)).xyz; + bump *= lerp(_BumpFace, _BumpOutline, saturate(sd + outline * 0.5)); + bump = lerp(float3(0, 0, 1), bump, faceColor.a); + n = normalize(n - bump); + + // Cubemap reflection + fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDirEnv, mul((float3x3)unity_ObjectToWorld, n))); + float3 emission = reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a; #else - float3 n = float3(0, 0, -1); - float3 emission = float3(0, 0, 0); + float3 n = float3(0, 0, -1); + float3 emission = float3(0, 0, 0); #endif #if GLOW_ON - float4 glowColor = GetGlowColor(sd, scale); - glowColor.a *= input.color.a; - emission += glowColor.rgb*glowColor.a; - faceColor = BlendARGB(glowColor, faceColor); - faceColor.rgb /= max(faceColor.a, 0.0001); + float4 glowColor = GetGlowColor(sd, scale); + glowColor.a *= input.color.a; + emission += glowColor.rgb*glowColor.a; + faceColor = BlendARGB(glowColor, faceColor); + faceColor.rgb /= max(faceColor.a, 0.0001); #endif - // Set Standard output structure - o.Albedo = faceColor.rgb; - o.Normal = -n; - o.Emission = emission; - o.Specular = lerp(_FaceShininess, _OutlineShininess, saturate(sd + outline * 0.5)); - o.Gloss = 1; - o.Alpha = faceColor.a; + // Set Standard output structure + o.Albedo = faceColor.rgb; + o.Normal = -n; + o.Emission = emission; + o.Specular = lerp(_FaceShininess, _OutlineShininess, saturate(sd + outline * 0.5)); + o.Gloss = 1; + o.Alpha = faceColor.a; } diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs index 5148f8ca2d0..433f542aba8 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/FrameSettingsTest.cs @@ -20,7 +20,7 @@ public void TearDown() CoreUtils.Destroy(m_ToClean); FrameSettingsHistory.containers?.Clear(); } - catch { } + catch {} } [Test] @@ -63,7 +63,7 @@ public void NoDoubleBitIndex() StringBuilder availables = new StringBuilder(); for (int i = 0; i < fsm.mask.capacity; ++i) { - if(!singleValues.Contains(i)) + if (!singleValues.Contains(i)) availables.AppendFormat("{0} ", i); } Debug.Log($"Available bit in FrameSettings: {availables}"); @@ -494,7 +494,7 @@ out GameObject prefab } string GeneratePrefabYAML(LegacyFrameSettings legacyFrameSettings) - => $@"%YAML 1.1 + => $@"%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &3102262843427888416 GameObject: @@ -682,7 +682,5 @@ string GeneratePrefabYAML(LegacyFrameSettings legacyFrameSettings) m_ObsoleteBoxSideFadePositive: {{x: 1, y: 1, z: 1}} m_ObsoleteBoxSideFadeNegative: {{x: 1, y: 1, z: 1}} "; - - } } diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/HDRenderUtilitiesTests.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/HDRenderUtilitiesTests.cs index b4d74dcd61f..1fbac24ce11 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/HDRenderUtilitiesTests.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/HDRenderUtilitiesTests.cs @@ -30,12 +30,12 @@ public void RenderThrowWhenFrameSettingsIsNull() public void RenderThrowWhenTargetIsNotARenderTextureForTex2DRendering() { Assert.Throws(() => HDRenderUtilities.Render( - new CameraSettings - { - renderingPathCustomFrameSettings = default - }, - default(CameraPositionSettings), - Texture2D.whiteTexture + new CameraSettings + { + renderingPathCustomFrameSettings = default + }, + default(CameraPositionSettings), + Texture2D.whiteTexture )); } } diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/ProbeSettingsUtilitiesTests.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/ProbeSettingsUtilitiesTests.cs index 6378999fe77..4a2cf9b382e 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/ProbeSettingsUtilitiesTests.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/ProbeSettingsUtilitiesTests.cs @@ -18,7 +18,7 @@ public void ApplyObliqueNearClipPlane() probeSettings.proxySettings.capturePositionProxySpace, Quaternion.LookRotation(Vector3.forward), Vector3.one - ).inverse; + ).inverse; ProbeSettingsUtilities.ApplyObliqueNearClipPlane( ref probeSettings, ref probePosition, diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingTests.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingTests.cs index e05f089d509..b9fef3c776d 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingTests.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingTests.cs @@ -6,7 +6,7 @@ namespace UnityEngine.Rendering.HighDefinition.Tests { class SerializedScalableSettingTests { - class ValueDeclaration: ScriptableObject + class ValueDeclaration : ScriptableObject { public IntScalableSetting intValue = new IntScalableSetting(new[] { 1, 2, 3 }, ScalableSettingSchemaId.With3Levels); } diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingValueTests.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingValueTests.cs index e7aa5a53508..d8121fa302d 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingValueTests.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/SerializedScalableSettingValueTests.cs @@ -6,12 +6,12 @@ namespace UnityEngine.Rendering.HighDefinition.Tests { class SerializedScalableSettingValueTests { - class ValueUsage: ScriptableObject + class ValueUsage : ScriptableObject { public IntScalableSettingValue intValue = new IntScalableSettingValue(); } - class ValueDeclaration: ScriptableObject + class ValueDeclaration : ScriptableObject { public IntScalableSetting intValue = new IntScalableSetting(new[] { 1, 2, 3 }, ScalableSettingSchemaId.With3Levels); } @@ -83,7 +83,8 @@ public void TryGetValueWorks_ForMissingLevelValue() public void TryGetValueWorks_ForMultipleDifferentValues() { var decl = ScriptableObject.CreateInstance(); - var usages = new[] { + var usages = new[] + { ScriptableObject.CreateInstance(), ScriptableObject.CreateInstance(), }; @@ -143,7 +144,8 @@ public void TryGetValueWorks_ForMultipleDifferentValues() public void TryGetValueWorks_ForMultipleIdenticalValues() { var decl = ScriptableObject.CreateInstance(); - var usages = new[] { + var usages = new[] + { ScriptableObject.CreateInstance(), ScriptableObject.CreateInstance(), }; diff --git a/com.unity.render-pipelines.high-definition/Tests/Editor/TestFramework/RandomUtilities.cs b/com.unity.render-pipelines.high-definition/Tests/Editor/TestFramework/RandomUtilities.cs index a2f3c6aa1dd..8ea35571ed4 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Editor/TestFramework/RandomUtilities.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Editor/TestFramework/RandomUtilities.cs @@ -13,6 +13,7 @@ public static float RandomFloat(float i, float seed) if (f < 0) f += 1; return f; } + public static Color RandomColor(float i) { return new Color( diff --git a/com.unity.render-pipelines.high-definition/Tests/Runtime/RuntimeExampleTest.cs b/com.unity.render-pipelines.high-definition/Tests/Runtime/RuntimeExampleTest.cs index ed3e28d0bd1..e08ffec278f 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Runtime/RuntimeExampleTest.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Runtime/RuntimeExampleTest.cs @@ -1,21 +1,23 @@ -using UnityEngine; +using UnityEngine; using UnityEngine.TestTools; using NUnit.Framework; using System.Collections; -class RuntimeExampleTest { +class RuntimeExampleTest +{ + [Test] + public void PlayModeSampleTestSimplePasses() + { + // Use the Assert class to test conditions. + } - [Test] - public void PlayModeSampleTestSimplePasses() { - // Use the Assert class to test conditions. - } - - // A UnityTest behaves like a coroutine in PlayMode - // and allows you to yield null to skip a frame in EditMode - [UnityTest] - public IEnumerator PlayModeSampleTestWithEnumeratorPasses() { - // Use the Assert class to test conditions. - // yield to skip a frame - yield return null; - } + // A UnityTest behaves like a coroutine in PlayMode + // and allows you to yield null to skip a frame in EditMode + [UnityTest] + public IEnumerator PlayModeSampleTestWithEnumeratorPasses() + { + // Use the Assert class to test conditions. + // yield to skip a frame + yield return null; + } } diff --git a/com.unity.render-pipelines.high-definition/Tests/Runtime/SampleRuntimeTests.cs b/com.unity.render-pipelines.high-definition/Tests/Runtime/SampleRuntimeTests.cs index 6c7e080cf34..7785c6480c1 100644 --- a/com.unity.render-pipelines.high-definition/Tests/Runtime/SampleRuntimeTests.cs +++ b/com.unity.render-pipelines.high-definition/Tests/Runtime/SampleRuntimeTests.cs @@ -13,7 +13,7 @@ class SampleRuntimeTests { const float k_Epsilon = 1e-4f; - static List s_Scenes = new List { }; + static List s_Scenes = new List {}; public IEnumerator SampleLoadSceneTest() { diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl index a7e9eaa21cb..90c8b3c0ec9 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl @@ -1,2 +1,2 @@ #include "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Version.hlsl" -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/Input.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/Input.hlsl index f2186538d4c..3fee5f7ee3c 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/Input.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/Input.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/Lighting.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/Lighting.hlsl index d44749c0684..d0b2e2498b4 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/Lighting.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/Lighting.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/Particles.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/Particles.hlsl index ba94b58d2a2..3eb79725320 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/Particles.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/Particles.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Particles.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Particles.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/ShaderGraphFunctions.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/ShaderGraphFunctions.hlsl index 49ee39a7f82..20a4060f1ee 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/ShaderGraphFunctions.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/ShaderGraphFunctions.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/Shadows.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/Shadows.hlsl index e172681ba8c..ea140b0231c 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/Shadows.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/Shadows.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/SurfaceInput.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/SurfaceInput.hlsl index 286b085e5a8..99c4c3cc489 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/SurfaceInput.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/SurfaceInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/UnityInput.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/UnityInput.hlsl index d7cd4c9effc..d67cd01b4f8 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/UnityInput.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/UnityInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/ShaderLibrary/Version.hlsl b/com.unity.render-pipelines.lightweight/ShaderLibrary/Version.hlsl index e5f26a0268e..8b4bc87649b 100644 --- a/com.unity.render-pipelines.lightweight/ShaderLibrary/Version.hlsl +++ b/com.unity.render-pipelines.lightweight/ShaderLibrary/Version.hlsl @@ -6,4 +6,4 @@ #define LWRP_6_3_OR_NEWER #define LWRP_6_2_OR_NEWER #define LWRP_6_1_OR_NEWER -#define LWRP_6_0_OR_NEWER \ No newline at end of file +#define LWRP_6_0_OR_NEWER diff --git a/com.unity.render-pipelines.lightweight/Shaders/2D/Include/LightingUtility.hlsl b/com.unity.render-pipelines.lightweight/Shaders/2D/Include/LightingUtility.hlsl index cf6a9be8be7..62ad34879be 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/2D/Include/LightingUtility.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/2D/Include/LightingUtility.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/2D/Include/NormalsRenderingShared.hlsl b/com.unity.render-pipelines.lightweight/Shaders/2D/Include/NormalsRenderingShared.hlsl index 0238766cc8f..49f250b77f3 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/2D/Include/NormalsRenderingShared.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/2D/Include/NormalsRenderingShared.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/BakedLitMetaPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/BakedLitMetaPass.hlsl index e3a1dd7d31e..5a6e9642b9a 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/BakedLitMetaPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/BakedLitMetaPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/BakedLitMetaPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/BakedLitMetaPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/DepthOnlyPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/DepthOnlyPass.hlsl index bb95832a513..4e4e06f32ec 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/DepthOnlyPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/DepthOnlyPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/DepthOnlyPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/DepthOnlyPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/LitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/LitInput.hlsl index b88a48e8657..93c107c57d8 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/LitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/LitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/LitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/LitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/LitMetaPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/LitMetaPass.hlsl index 7612883dfc4..7b0354d176e 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/LitMetaPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/LitMetaPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/LitMetaPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/LitMetaPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardInput.hlsl index bddd287efbe..6158e7e21e3 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7BillboardInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7BillboardInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardPasses.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardPasses.hlsl index ef1522b8b48..4d27a4bda96 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardPasses.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7BillboardPasses.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7BillboardPasses.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7BillboardPasses.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonInput.hlsl index fbe43bd6a21..abdfec8d038 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonPasses.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonPasses.hlsl index 45ebb12111e..3f0c7c640bb 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonPasses.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7CommonPasses.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonPasses.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7CommonPasses.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Input.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Input.hlsl index 647896460a5..71b1861aca2 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Input.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Input.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Input.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Input.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Passes.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Passes.hlsl index f0d9db534d5..bd7edfdb23a 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Passes.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree7Passes.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Passes.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Passes.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Input.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Input.hlsl index 7afac36727e..5ac0b972d2f 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Input.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Input.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Input.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Input.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Passes.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Passes.hlsl index 13b90c9a4ef..3e1bd54e8d7 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Passes.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Nature/SpeedTree8Passes.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Passes.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree8Passes.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitForwardPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitForwardPass.hlsl index b29df90e7aa..01cb52f4505 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitForwardPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitForwardPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitInput.hlsl index c5782760025..09e07e96f76 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesLitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl index 01cfcacf4fc..2b74200c2d6 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitForwardPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitInput.hlsl index e2efe7c46c5..9480cc432d0 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesSimpleLitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesSimpleLitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitForwardPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitForwardPass.hlsl index d20a1ea3486..59ada738ab9 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitForwardPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitForwardPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlitForwardPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlitForwardPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitInput.hlsl index 84b8d8d6d61..d5b3e436c4d 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Particles/ParticlesUnlitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesUnlitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/ShadowCasterPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/ShadowCasterPass.hlsl index 859dfb2fc06..35141d883da 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/ShadowCasterPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/ShadowCasterPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/ShadowCasterPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/ShadowCasterPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/SimpleLitForwardPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/SimpleLitForwardPass.hlsl index 10db567f798..f44bd4ab6d7 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/SimpleLitForwardPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/SimpleLitForwardPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitForwardPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitForwardPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/SimpleLitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/SimpleLitInput.hlsl index 0ecd2933cf3..153b9b5c1ae 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/SimpleLitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/SimpleLitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/SimpleLitMetaPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/SimpleLitMetaPass.hlsl index b73c67f92e7..a58dc7c52de 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/SimpleLitMetaPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/SimpleLitMetaPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitMetaPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/SimpleLitMetaPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitInput.hlsl index 4ce665a9616..ae74d9e21f8 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitMetaPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitMetaPass.hlsl index 2d3a6d6f467..78dc5d9e319 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitMetaPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitMetaPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitMetaPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitMetaPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitPasses.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitPasses.hlsl index eebffddc336..bc214bd9e49 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitPasses.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Terrain/TerrainLitPasses.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassInput.hlsl index e3209e444c8..99c07851d74 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassPasses.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassPasses.hlsl index 62236d84df9..38922d9e47e 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassPasses.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Terrain/WavingGrassPasses.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassPasses.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassPasses.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/UnlitInput.hlsl b/com.unity.render-pipelines.lightweight/Shaders/UnlitInput.hlsl index 474f1d41cb4..62d677668a4 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/UnlitInput.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/UnlitInput.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/UnlitInput.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/UnlitInput.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/UnlitMetaPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/UnlitMetaPass.hlsl index e2f54fbe71f..f308f1a930c 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/UnlitMetaPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/UnlitMetaPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/UnlitMetaPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/UnlitMetaPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Utils/CopyDepthPass.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Utils/CopyDepthPass.hlsl index 81bb5a3ec07..4665740f59d 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Utils/CopyDepthPass.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Utils/CopyDepthPass.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/CopyDepthPass.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/CopyDepthPass.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Shaders/Utils/Lightweight2D.hlsl b/com.unity.render-pipelines.lightweight/Shaders/Utils/Lightweight2D.hlsl index 3d79ee63386..a136f2d248b 100644 --- a/com.unity.render-pipelines.lightweight/Shaders/Utils/Lightweight2D.hlsl +++ b/com.unity.render-pipelines.lightweight/Shaders/Utils/Lightweight2D.hlsl @@ -1 +1 @@ -#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/Universal2D.hlsl" \ No newline at end of file +#include "Packages/com.unity.render-pipelines.universal/Shaders/Utils/Universal2D.hlsl" diff --git a/com.unity.render-pipelines.lightweight/Tests/Editor/LightweightEditorTests.cs b/com.unity.render-pipelines.lightweight/Tests/Editor/LightweightEditorTests.cs index a3e0bc11939..53a5af43376 100644 --- a/com.unity.render-pipelines.lightweight/Tests/Editor/LightweightEditorTests.cs +++ b/com.unity.render-pipelines.lightweight/Tests/Editor/LightweightEditorTests.cs @@ -10,4 +10,4 @@ public void DummyTest() { Assert.IsTrue(true); } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.universal/Editor/2D/CompositeShadowCaster2DEditor.cs b/com.unity.render-pipelines.universal/Editor/2D/CompositeShadowCaster2DEditor.cs index 4f24cb66e88..ac23cb59611 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/CompositeShadowCaster2DEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/CompositeShadowCaster2DEditor.cs @@ -6,7 +6,6 @@ namespace UnityEditor.Experimental.Rendering.Universal { - [CustomEditor(typeof(CompositeShadowCaster2D))] internal class CompositeShadowCaster2DEditor : Editor { diff --git a/com.unity.render-pipelines.universal/Editor/2D/FreeformPathPresets.cs b/com.unity.render-pipelines.universal/Editor/2D/FreeformPathPresets.cs index 64d18304ef1..4c5cb0295f8 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/FreeformPathPresets.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/FreeformPathPresets.cs @@ -11,9 +11,9 @@ public static Vector3[] CreateSquare() { Vector3[] returnPath = new Vector3[4] { - new Vector3(-0.5f,-0.5f), - new Vector3( 0.5f,-0.5f), - new Vector3( 0.5f, 0.5f), + new Vector3(-0.5f, -0.5f), + new Vector3(0.5f, -0.5f), + new Vector3(0.5f, 0.5f), new Vector3(-0.5f, 0.5f) }; @@ -25,9 +25,9 @@ public static Vector3[] CreateIsometricDiamond() Vector3[] returnPath = new Vector3[4] { new Vector3(-0.5f, 0.0f), - new Vector3( 0.0f,-0.25f), - new Vector3( 0.5f, 0.0f), - new Vector3( 0.0f, 0.25f) + new Vector3(0.0f, -0.25f), + new Vector3(0.5f, 0.0f), + new Vector3(0.0f, 0.25f) }; return returnPath; diff --git a/com.unity.render-pipelines.universal/Editor/2D/Light2DEditor.cs b/com.unity.render-pipelines.universal/Editor/2D/Light2DEditor.cs index 494b36f5bb3..9f72bf9dc36 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/Light2DEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/Light2DEditor.cs @@ -72,7 +72,7 @@ private static class Styles public static GUIContent lightTypeGlobal = new GUIContent("Global", Resources.Load("InspectorIcons/GlobalLight") as Texture); public static GUIContent[] lightTypeOptions = new GUIContent[] { lightTypeFreeform, lightTypeSprite, lightTypePoint, lightTypeGlobal }; - + public static GUIContent blendingSettingsFoldout = EditorGUIUtility.TrTextContent("Blending", "Options used for blending"); public static GUIContent shadowsSettingsFoldout = EditorGUIUtility.TrTextContent("Shadows", "Options used for shadows"); public static GUIContent volumetricSettingsFoldout = EditorGUIUtility.TrTextContent("Volumetric", "Options used for volumetric lighting"); @@ -184,7 +184,7 @@ private void AnalyticsTrackChanges(SerializedObject serializedObject) foreach (Object targetObj in serializedObject.targetObjects) { Light2D light2d = (Light2D)targetObj; - if(!m_ModifiedLights.Contains(light2d)) + if (!m_ModifiedLights.Contains(light2d)) m_ModifiedLights.Add(light2d); } } @@ -275,13 +275,13 @@ internal void SendModifiedAnalytics(Analytics.Renderer2DAnalytics analytics, Lig void OnDestroy() { - if(m_ModifiedLights != null && m_ModifiedLights.Count > 0) + if (m_ModifiedLights != null && m_ModifiedLights.Count > 0) { foreach (Light2D light in m_ModifiedLights) { SendModifiedAnalytics(m_Analytics, light); } - } + } } void DrawBlendingGroup() @@ -344,7 +344,6 @@ void DrawNormalMapGroup() } } - void DrawFoldouts() { DrawBlendingGroup(); @@ -400,7 +399,7 @@ void DrawToggleProperty(GUIContent label, SerializedProperty boolProperty, Seria EditorGUI.BeginDisabledGroup(!boolProperty.boolValue); EditorGUILayout.PropertyField(property, label); EditorGUI.EndDisabledGroup(); - + EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel = savedIndentLevel; @@ -471,7 +470,6 @@ void DrawGlobalLight(SerializedObject serializedObject) void DrawParametricDeprecated(SerializedObject serializedObject) { - GUIContent buttonText = targets.Length > 1 ? Styles.deprecatedParametricLightButtonMulti : Styles.deprecatedParametricLightButtonSingle; GUIContent helpText = targets.Length > 1 ? Styles.deprecatedParametricLightWarningMulti : Styles.deprecatedParametricLightWarningSingle; string dialogText = targets.Length > 1 ? Styles.deprecatedParametricLightDialogTextMulti : Styles.deprecatedParametricLightDialogTextSingle; @@ -494,7 +492,7 @@ void DrawParametricDeprecated(SerializedObject serializedObject) } } EditorGUILayout.Space(); - EditorGUILayout.HelpBox(Styles.deprecatedParametricLightInstructions); + EditorGUILayout.HelpBox(Styles.deprecatedParametricLightInstructions); } bool DrawLightCommon() @@ -519,7 +517,6 @@ bool DrawLightCommon() m_LightIntensity.floatValue = Mathf.Max(m_LightIntensity.floatValue, 0); return meshChanged; - } void DrawSpotLight(SerializedObject serializedObject) @@ -528,7 +525,7 @@ void DrawSpotLight(SerializedObject serializedObject) DrawInnerAndOuterSpotAngle(m_PointInnerAngle, m_PointOuterAngle, Styles.InnerOuterSpotAngle); EditorGUILayout.Slider(m_FalloffIntensity, 0, 1, Styles.generalFalloffIntensity); - if(m_DeprecatedPointLightSprite.objectReferenceValue != null) + if (m_DeprecatedPointLightSprite.objectReferenceValue != null) EditorGUILayout.PropertyField(m_DeprecatedPointLightSprite, Styles.pointLightSprite); m_SortingLayerDropDown.OnTargetSortingLayers(serializedObject, targets, Styles.generalSortingLayerPrefixLabel, AnalyticsTrackChanges); @@ -710,59 +707,59 @@ void OnSceneGUI() switch (light.lightType) { case Light2D.LightType.Point: - { - Undo.RecordObject(light.transform, "Edit Point Light Transform"); - Undo.RecordObject(light, "Edit Point Light"); + { + Undo.RecordObject(light.transform, "Edit Point Light Transform"); + Undo.RecordObject(light, "Edit Point Light"); - DrawRangeHandles(light); - DrawAngleHandles(light); + DrawRangeHandles(light); + DrawAngleHandles(light); - if (GUI.changed) - EditorUtility.SetDirty(light); - } - break; + if (GUI.changed) + EditorUtility.SetDirty(light); + } + break; case Light2D.LightType.Sprite: + { + var cookieSprite = light.lightCookieSprite; + if (cookieSprite != null) { - var cookieSprite = light.lightCookieSprite; - if (cookieSprite != null) - { - Vector3 min = cookieSprite.bounds.min; - Vector3 max = cookieSprite.bounds.max; - - Vector3 v0 = t.TransformPoint(new Vector3(min.x, min.y)); - Vector3 v1 = t.TransformPoint(new Vector3(max.x, min.y)); - Vector3 v2 = t.TransformPoint(new Vector3(max.x, max.y)); - Vector3 v3 = t.TransformPoint(new Vector3(min.x, max.y)); - - Handles.DrawLine(v0, v1); - Handles.DrawLine(v1, v2); - Handles.DrawLine(v2, v3); - Handles.DrawLine(v3, v0); - } + Vector3 min = cookieSprite.bounds.min; + Vector3 max = cookieSprite.bounds.max; + + Vector3 v0 = t.TransformPoint(new Vector3(min.x, min.y)); + Vector3 v1 = t.TransformPoint(new Vector3(max.x, min.y)); + Vector3 v2 = t.TransformPoint(new Vector3(max.x, max.y)); + Vector3 v3 = t.TransformPoint(new Vector3(min.x, max.y)); + + Handles.DrawLine(v0, v1); + Handles.DrawLine(v1, v2); + Handles.DrawLine(v2, v3); + Handles.DrawLine(v3, v0); } - break; + } + break; case Light2D.LightType.Freeform: - { - // Draw the falloff shape's outline - List falloffShape = light.GetFalloffShape(); - Handles.color = Color.white; - - for (int i = 0; i < falloffShape.Count - 1; ++i) - { - Handles.DrawLine(t.TransformPoint(falloffShape[i]), t.TransformPoint(falloffShape[i + 1])); - } + { + // Draw the falloff shape's outline + List falloffShape = light.GetFalloffShape(); + Handles.color = Color.white; - Handles.DrawLine(t.TransformPoint(falloffShape[falloffShape.Count - 1]), t.TransformPoint(falloffShape[0])); + for (int i = 0; i < falloffShape.Count - 1; ++i) + { + Handles.DrawLine(t.TransformPoint(falloffShape[i]), t.TransformPoint(falloffShape[i + 1])); + } - for (int i = 0; i < light.shapePath.Length - 1; ++i) - { - Handles.DrawLine(t.TransformPoint(light.shapePath[i]), - t.TransformPoint(light.shapePath[i + 1])); - } + Handles.DrawLine(t.TransformPoint(falloffShape[falloffShape.Count - 1]), t.TransformPoint(falloffShape[0])); - Handles.DrawLine(t.TransformPoint(light.shapePath[light.shapePath.Length - 1]), t.TransformPoint(light.shapePath[0])); + for (int i = 0; i < light.shapePath.Length - 1; ++i) + { + Handles.DrawLine(t.TransformPoint(light.shapePath[i]), + t.TransformPoint(light.shapePath[i + 1])); } - break; + + Handles.DrawLine(t.TransformPoint(light.shapePath[light.shapePath.Length - 1]), t.TransformPoint(light.shapePath[0])); + } + break; } } @@ -787,32 +784,30 @@ public override void OnInspectorGUI() switch (m_LightType.intValue) { case (int)Light2D.LightType.Point: - { - - DrawSpotLight(serializedObject); - } - break; + { + DrawSpotLight(serializedObject); + } + break; case (int)Light2D.LightType.Freeform: - { - DrawShapeLight(serializedObject); - } - break; + { + DrawShapeLight(serializedObject); + } + break; case (int)Light2D.LightType.Sprite: - { - DrawSpriteLight(serializedObject); - } - break; + { + DrawSpriteLight(serializedObject); + } + break; case (int)Light2D.LightType.Global: - { - - DrawGlobalLight(serializedObject); - } - break; + { + DrawGlobalLight(serializedObject); + } + break; case (int)Light2D.DeprecatedLightType.Parametric: - { - DrawParametricDeprecated(serializedObject); - } - break; + { + DrawParametricDeprecated(serializedObject); + } + break; } AnalyticsTrackChanges(serializedObject); @@ -827,10 +822,9 @@ public override void OnInspectorGUI() { EditorGUILayout.HelpBox(Styles.renderPipelineUnassignedWarning); - if(meshChanged) + if (meshChanged) lightObject.UpdateMesh(true); } } - } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/Light2DEditorUtility.cs b/com.unity.render-pipelines.universal/Editor/2D/Light2DEditorUtility.cs index caeb5f12f20..6b1ecd976d8 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/Light2DEditorUtility.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/Light2DEditorUtility.cs @@ -8,40 +8,40 @@ namespace UnityEditor.Experimental.Rendering.Universal internal static class Light2DEditorUtility { static Material s_TexCapMaterial = CoreUtils.CreateEngineMaterial(Shader.Find("Hidden/Internal-GUITexture")); - + static internal void GUITextureCap(int controlID, Texture texture, Vector3 position, Quaternion rotation, float size, EventType eventType, bool isAngleHandle) { switch (eventType) { case (EventType.Layout): - { - Vector2 size2 = Vector2.one * size * 0.5f; - if (isAngleHandle) - size2.x = 0.0f; + { + Vector2 size2 = Vector2.one * size * 0.5f; + if (isAngleHandle) + size2.x = 0.0f; - HandleUtility.AddControl(controlID, DistanceToRectangle(position, rotation, size2)); - break; - } + HandleUtility.AddControl(controlID, DistanceToRectangle(position, rotation, size2)); + break; + } case (EventType.Repaint): - { - s_TexCapMaterial.mainTexture = texture; - s_TexCapMaterial.SetPass(0); + { + s_TexCapMaterial.mainTexture = texture; + s_TexCapMaterial.SetPass(0); - float w = texture.width; - float h = texture.height; - float max = Mathf.Max(w, h); - Vector3 scale = new Vector2(w / max, h / max) * size * 0.5f; + float w = texture.width; + float h = texture.height; + float max = Mathf.Max(w, h); + Vector3 scale = new Vector2(w / max, h / max) * size * 0.5f; - if (Camera.current == null) - scale.y *= -1f; + if (Camera.current == null) + scale.y *= -1f; - Matrix4x4 matrix = new Matrix4x4(); - matrix.SetTRS(position, rotation, scale); + Matrix4x4 matrix = new Matrix4x4(); + matrix.SetTRS(position, rotation, scale); - Graphics.DrawMeshNow(RenderingUtils.fullscreenMesh, matrix); - } - break; + Graphics.DrawMeshNow(RenderingUtils.fullscreenMesh, matrix); + } + break; } } @@ -99,7 +99,7 @@ public static Renderer2DData GetRenderer2DData() // try get the default Renderer2DData rendererData = pipelineAsset.scriptableRendererData as Renderer2DData; - if(rendererData == null) + if (rendererData == null) { foreach (Camera camera in Camera.allCameras) { diff --git a/com.unity.render-pipelines.universal/Editor/2D/Renderer2DAnalytics.cs b/com.unity.render-pipelines.universal/Editor/2D/Renderer2DAnalytics.cs index 481720f267f..b00f2831829 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/Renderer2DAnalytics.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/Renderer2DAnalytics.cs @@ -11,7 +11,7 @@ struct AnalyticsDataTypes public const string k_Renderer2DDataString = "u2drendererdata"; } - internal interface IAnalyticsData { }; + internal interface IAnalyticsData {}; [Serializable] internal struct Light2DData : IAnalyticsData diff --git a/com.unity.render-pipelines.universal/Editor/2D/Renderer2DMenus.cs b/com.unity.render-pipelines.universal/Editor/2D/Renderer2DMenus.cs index 768256cd5ae..7adf5576747 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/Renderer2DMenus.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/Renderer2DMenus.cs @@ -15,8 +15,6 @@ using UnityEditorInternal; - - namespace UnityEditor.Experimental.Rendering.Universal { static class Renderer2DMenus @@ -58,7 +56,6 @@ internal static void PlaceGameObjectInFrontOfSceneView(GameObject go) } } - // This is from GOCreationCommands internal static void Place(GameObject go, GameObject parent) { @@ -95,7 +92,7 @@ static void CreateLight(MenuCommand menuCommand, Light2D.LightType type, Vector3 Light2D light2D = go.GetComponent(); light2D.lightType = type; - if(shapePath != null && shapePath.Length > 0) + if (shapePath != null && shapePath.Length > 0) light2D.shapePath = shapePath; var parent = menuCommand.context as GameObject; diff --git a/com.unity.render-pipelines.universal/Editor/2D/Renderer2DUpgrader.cs b/com.unity.render-pipelines.universal/Editor/2D/Renderer2DUpgrader.cs index 30788b7d377..d499c4397f6 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/Renderer2DUpgrader.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/Renderer2DUpgrader.cs @@ -26,21 +26,19 @@ static void ProcessAssetDatabaseObjects(string searchString, Upgrader upgr } } - public static void UpgradeObjectWithParametricLights(GameObject obj) { Light2D[] lights = obj.GetComponents(); - if(lights.Length > 0) + if (lights.Length > 0) { foreach (var light in lights) UpgradeParametricLight(light); } } - public static void UpgradeParametricLight(Light2D light) { - if(light.lightType == (Light2D.LightType)Light2D.DeprecatedLightType.Parametric) + if (light.lightType == (Light2D.LightType)Light2D.DeprecatedLightType.Parametric) { light.lightType = Light2D.LightType.Freeform; @@ -107,7 +105,6 @@ static void UpgradeGameObject(GameObject go) { newMaterials[i] = renderer.sharedMaterials[i]; } - } if (upgraded) @@ -136,8 +133,6 @@ static void UpgradeMaterial(Material mat) } } - - [MenuItem("Edit/Render Pipeline/Universal Render Pipeline/Upgrade Project Materials to 2D Renderer Materials", false)] static void UpgradeProjectTo2DRenderer() { @@ -164,7 +159,7 @@ static void UpgradeSceneTo2DRenderer() } } } - + [MenuItem("Edit/Render Pipeline/Universal Render Pipeline/Upgrade Project Materials to 2D Renderer Materials", true)] [MenuItem("Edit/Render Pipeline/Universal Render Pipeline/Upgrade Scene Materials to 2D Renderer Materials", true)] static bool MenuValidation() @@ -216,7 +211,5 @@ public static void UpgradeParametricLightsInScene() { UpgradeParametricLightsInScene(true); } - - } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DEditor.cs b/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DEditor.cs index 9ba61f62565..7607be74e7f 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DEditor.cs @@ -9,7 +9,6 @@ namespace UnityEditor.Experimental.Rendering.Universal { - internal class ShadowCasterPath : ScriptablePath { internal Bounds GetBounds() @@ -50,7 +49,7 @@ public override void SetDefaultShape() internal class ShadowCaster2DEditor : PathComponentEditor { [EditorTool("Edit Shadow Caster Shape", typeof(ShadowCaster2D))] - class ShadowCaster2DShadowCasterShapeTool : ShadowCaster2DShapeTool { }; + class ShadowCaster2DShadowCasterShapeTool : ShadowCaster2DShapeTool {}; private static class Styles { @@ -103,7 +102,6 @@ public void ShadowCaster2DInspectorGUI() where T : ShadowCaster2DShapeTool DoSnappingInspector(); } - public void OnSceneGUI() { if (m_CastsShadows.boolValue) @@ -112,9 +110,9 @@ public void OnSceneGUI() public bool HasRenderer() { - if(targets != null) + if (targets != null) { - for(int i=0;i(); @@ -132,7 +130,7 @@ public override void OnInspectorGUI() using (new EditorGUI.DisabledScope(!HasRenderer())) // Done to support multiedit { - EditorGUILayout.PropertyField(m_UseRendererSilhouette, Styles.shadowMode); + EditorGUILayout.PropertyField(m_UseRendererSilhouette, Styles.shadowMode); } EditorGUILayout.PropertyField(m_CastsShadows, Styles.castsShadows); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DShapeTool.cs b/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DShapeTool.cs index ea50032b9f1..300eae085f9 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DShapeTool.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShadowCaster2DShapeTool.cs @@ -9,7 +9,7 @@ namespace UnityEditor.Experimental.Rendering.Universal class ShadowCaster2DShapeTool : PathEditorTool { const string k_ShapePath = "m_ShapePath"; - + protected override IShape GetShape(Object target) { return (target as ShadowCaster2D).shapePath.ToPolygon(false); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePath.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePath.cs index bc3fe13eecf..2621969a137 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePath.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePath.cs @@ -28,7 +28,7 @@ public ShapeType shapeType } public IUndoObject undoObject { get; set; } - + public Matrix4x4 localToWorldMatrix { get { return m_LocalToWorldMatrix; } @@ -68,7 +68,7 @@ public bool isOpenEnded { if (pointCount < 3) return true; - + return m_IsOpenEnded; } set { m_IsOpenEnded = value; } @@ -113,7 +113,7 @@ public void Clear() { m_ControlPoints.Clear(); } - + private ControlPoint TransformPoint(Matrix4x4 transformMatrix, ControlPoint controlPoint) { if (transformMatrix == Matrix4x4.identity) diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathController.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathController.cs index e9575254be4..a12de0727f7 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathController.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathController.cs @@ -114,7 +114,7 @@ public void RemoveSelectedPoints() if (editablePath.pointCount != pointsCountToRemove) { - var indices = editablePath.selection.elements.OrderByDescending( i => i); + var indices = editablePath.selection.elements.OrderByDescending(i => i); foreach (var index in indices) { @@ -139,7 +139,7 @@ public void MoveSelectedPoints(Vector3 delta) for (var i = 0; i < editablePath.pointCount; ++i) { if (editablePath.selection.Contains(i)) - { + { var controlPoint = editablePath.GetPoint(i); controlPoint.position += delta; editablePath.SetPoint(i, controlPoint); @@ -151,7 +151,7 @@ public void MoveEdge(int index, Vector3 delta) { if (editablePath.isOpenEnded && index == editablePath.pointCount - 1) return; - + var controlPoint = editablePath.GetPoint(index); controlPoint.position += delta; editablePath.SetPoint(index, controlPoint); @@ -208,8 +208,8 @@ public void SetRightTangent(int index, Vector3 position, bool setToLinear, bool editablePath.SetPoint(index, controlPoint); } - public void ClearClosestPath() { } - public void AddClosestPath(float distance) { } + public void ClearClosestPath() {} + public void AddClosestPath(float distance) {} private Vector3 GetLeftTangentPosition(int index) { diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathExtensions.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathExtensions.cs index 9dd9fd17e58..26e56a83096 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathExtensions.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/EditablePathExtensions.cs @@ -11,8 +11,8 @@ public static Polygon ToPolygon(this IEditablePath path) { var polygon = new Polygon() { - isOpenEnded = path.isOpenEnded, - points = new Vector3[path.pointCount] + isOpenEnded = path.isOpenEnded, + points = new Vector3[path.pointCount] }; for (var i = 0; i < path.pointCount; ++i) @@ -27,25 +27,25 @@ public static Spline ToSpline(this IEditablePath path) if (path.isOpenEnded) count -= 2; - + var spline = new Spline() { - isOpenEnded = path.isOpenEnded, - points = new Vector3[count] + isOpenEnded = path.isOpenEnded, + points = new Vector3[count] }; for (var i = 0; i < path.pointCount; ++i) { var point = path.GetPoint(i); - spline.points[i*3] = point.position; + spline.points[i * 3] = point.position; if (i * 3 + 1 < count) { - var nextIndex = EditablePathUtility.Mod(i+1, path.pointCount); + var nextIndex = EditablePathUtility.Mod(i + 1, path.pointCount); - spline.points[i*3 + 1] = path.CalculateRightTangent(i); - spline.points[i*3 + 2] = path.CalculateLeftTangent(nextIndex); + spline.points[i * 3 + 1] = path.CalculateRightTangent(i); + spline.points[i * 3 + 2] = path.CalculateLeftTangent(nextIndex); } } @@ -91,7 +91,7 @@ public static Vector3 CalculateRightTangent(this IEditablePath path, int index) if (isEndpoint) return point.position; - + if (isTangentLinear) { var nextPoint = path.GetNextPoint(index); @@ -127,7 +127,7 @@ public static void UpdateTangentMode(this IEditablePath path, int index) controlPoint.tangentMode = TangentMode.Broken; else if (controlPoint.tangentMode != TangentMode.Continuous) controlPoint.tangentMode = TangentMode.Broken; - + controlPoint.StoreTangents(); path.SetPoint(index, controlPoint); path.localToWorldMatrix = localToWorldMatrix; @@ -143,7 +143,7 @@ public static void UpdateTangentsFromMode(this IEditablePath path) for (var i = 0; i < path.pointCount; ++i) { var controlPoint = path.GetPoint(i); - + if (controlPoint.tangentMode == TangentMode.Linear) { controlPoint.localLeftTangent = Vector3.zero; @@ -158,10 +158,10 @@ public static void UpdateTangentsFromMode(this IEditablePath path) var liniarLeftPosition = (prevPoint.position - controlPoint.position) / 3f; var isLeftTangentLinear = isLeftEndpoint || (controlPoint.localLeftTangent - liniarLeftPosition).sqrMagnitude < kEpsilon; - if (isLeftTangentLinear) + if (isLeftTangentLinear) controlPoint.localLeftTangent = Vector3.zero; - var isRightEndpoint = path.isOpenEnded && i == path.pointCount-1; + var isRightEndpoint = path.isOpenEnded && i == path.pointCount - 1; var liniarRightPosition = (nextPoint.position - controlPoint.position) / 3f; var isRightTangentLinear = isRightEndpoint || (controlPoint.localRightTangent - liniarRightPosition).sqrMagnitude < kEpsilon; @@ -232,7 +232,7 @@ public static void SetTangentMode(this IEditablePath path, int index, TangentMod { var isLeftLinear = controlPoint.localLeftTangent == Vector3.zero; var isRightLinear = controlPoint.localRightTangent == Vector3.zero; - + if (isLeftLinear || isRightLinear) { if (isLeftLinear) diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/MultipleEditablePathController.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/MultipleEditablePathController.cs index c7fe1c661a4..dc01bf0e543 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/MultipleEditablePathController.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditablePath/MultipleEditablePathController.cs @@ -68,7 +68,7 @@ public void ClearSelection() { editablePath = s; m_Controller.ClearSelection(); - }); + }); editablePath = current; } @@ -141,7 +141,7 @@ public void AddClosestPath(float distance) private void ForEach(Action action) { - foreach(var path in m_Paths) + foreach (var path in m_Paths) { if (path == null) continue; diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePath.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePath.cs index ba4d0decda4..b7dcac0735e 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePath.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePath.cs @@ -16,7 +16,7 @@ public T[] data { if (value.Length != pointCount) throw new Exception("Custom data count does not match control point count"); - + m_Data.Clear(); m_Data.AddRange(value); } @@ -67,6 +67,6 @@ protected virtual T Create() return Activator.CreateInstance(); } - protected virtual void Destroy(T data) { } + protected virtual void Destroy(T data) {} } -} \ No newline at end of file +} diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePathInspector.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePathInspector.cs index 349cdac7460..5f79041db7a 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePathInspector.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/GenericScriptablePathInspector.cs @@ -7,7 +7,7 @@ namespace UnityEditor.Experimental.Rendering.Universal.Path2D { - internal class GenericScriptablePathInspector : ScriptablePathInspector where U : ScriptableData + internal class GenericScriptablePathInspector : ScriptablePathInspector where U : ScriptableData { private List m_DataObjects = new List(); private List m_SelectedDataObjects = new List(); @@ -53,19 +53,19 @@ private void PrepareDataObjects() m_SelectedDataObjects.Clear(); - foreach(var path in paths) + foreach (var path in paths) elementCount += path.pointCount; - + while (m_DataObjects.Count < elementCount) CreateDataObject(); var index = 0; - foreach(var path in paths) + foreach (var path in paths) { var genericPath = path as GenericScriptablePath; var customDataArray = genericPath.data; var length = customDataArray.Length; - + for (var i = 0; i < length; ++i) { var dataObject = m_DataObjects[index + i]; @@ -78,7 +78,7 @@ private void PrepareDataObjects() m_SelectedDataObjects.Add(dataObject); } } - + index += length; } } @@ -86,17 +86,17 @@ private void PrepareDataObjects() private void SetDataObjects() { var index = 0; - foreach(var path in paths) + foreach (var path in paths) { var genericPath = path as GenericScriptablePath; var customDataArray = genericPath.data; var length = customDataArray.Length; - + for (var i = 0; i < length; ++i) customDataArray[i] = m_DataObjects[index + i].data; genericPath.data = customDataArray; - + index += length; } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathComponentEditor.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathComponentEditor.cs index 9de65c2378c..025ea95bb05 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathComponentEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathComponentEditor.cs @@ -9,7 +9,7 @@ using UnityEditor.Experimental.Rendering.Universal.Path2D; #if !UNITY_2020_2_OR_NEWER -using ToolManager=UnityEditor.EditorTools.EditorTools; +using ToolManager = UnityEditor.EditorTools.EditorTools; #endif namespace UnityEditor.Experimental.Rendering.Universal.Path2D diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorTool.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorTool.cs index bc49c049892..b29be3acfe1 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorTool.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorTool.cs @@ -9,7 +9,7 @@ using UnityObject = UnityEngine.Object; #if !UNITY_2020_2_OR_NEWER -using ToolManager=UnityEditor.EditorTools.EditorTools; +using ToolManager = UnityEditor.EditorTools.EditorTools; #endif namespace UnityEditor.Experimental.Rendering.Universal.Path2D @@ -81,7 +81,7 @@ internal static bool IsAvailable() where T : EditorTool internal static T GetEditorTool() where T : EditorTool { - foreach(var tool in m_Tools) + foreach (var tool in m_Tools) { if (tool.GetType().Equals(typeof(T))) return tool as T; @@ -271,7 +271,7 @@ private void SetupRectSelector() private void ForEachTarget(Action action) { - foreach(var target in targets) + foreach (var target in targets) { if (target == null) continue; @@ -489,11 +489,11 @@ private Vector3 GetRight(UnityObject target) } protected abstract IShape GetShape(UnityObject target); - protected virtual void Initialize(T path, SerializedObject serializedObject) { } + protected virtual void Initialize(T path, SerializedObject serializedObject) {} protected abstract void SetShape(T path, SerializedObject serializedObject); - protected virtual void OnActivate() { } - protected virtual void OnDeactivate() { } - protected virtual void OnCustomGUI(T path) { } + protected virtual void OnActivate() {} + protected virtual void OnDeactivate() {} + protected virtual void OnCustomGUI(T path) {} } } #pragma warning restore 0618 diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorToolExtensions.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorToolExtensions.cs index 7856eae9548..d13d064d3d2 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorToolExtensions.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/PathEditorToolExtensions.cs @@ -18,7 +18,7 @@ public static void CycleTangentMode(this PathEditorTool pathEditorTool) wh var tangentMode = TangentMode.Linear; var targets = pathEditorTool.targets; - foreach(var target in targets) + foreach (var target in targets) { var path = pathEditorTool.GetPath(target); @@ -31,7 +31,7 @@ public static void CycleTangentMode(this PathEditorTool pathEditorTool) wh continue; var point = path.GetPoint(i); - + if (first) { first = false; @@ -53,7 +53,7 @@ public static void CycleTangentMode(this PathEditorTool pathEditorTool) wh else tangentMode = GetNextTangentMode(tangentMode); - foreach(var target in targets) + foreach (var target in targets) { var path = pathEditorTool.GetPath(target); @@ -78,7 +78,7 @@ public static void MirrorTangent(this PathEditorTool pathEditorTool) where { var targets = pathEditorTool.targets; - foreach(var target in targets) + foreach (var target in targets) { var path = pathEditorTool.GetPath(target); @@ -104,5 +104,4 @@ private static TangentMode GetNextTangentMode(TangentMode tangentMode) return (TangentMode)((((int)tangentMode) + 1) % Enum.GetValues(typeof(TangentMode)).Length); } } - } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePath.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePath.cs index 1a011e58e7b..03b7a452963 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePath.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePath.cs @@ -31,7 +31,7 @@ public ShapeType shapeType public IUndoObject undoObject { get { return this; } - set { } + set {} } public ISelection selection diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePathInspector.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePathInspector.cs index 2eb545a76c6..e92932e6fc3 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePathInspector.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/EditorTool/ScriptablePathInspector.cs @@ -30,7 +30,7 @@ private static GUIContent IconContent(string personal, string pro, string toolti { if (EditorGUIUtility.isProSkin) return IconContent(pro, tooltip); - + return IconContent(personal, tooltip); } } @@ -43,8 +43,8 @@ protected List paths get { if (m_Paths == null) - m_Paths = targets.Select( t => t as ScriptablePath).ToList(); - + m_Paths = targets.Select(t => t as ScriptablePath).ToList(); + return m_Paths; } } @@ -59,7 +59,7 @@ protected void DoTangentModeInspector() { if (!IsAnyShapeType(ShapeType.Spline)) return; - + EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(Contents.tangentModeLabel); @@ -102,9 +102,9 @@ protected void DoPositionInspector() { if (m_Dragged == false) { - foreach(var path in paths) + foreach (var path in paths) path.undoObject.RegisterUndo("Point Position"); - + m_Dragged = true; } @@ -128,13 +128,13 @@ private bool DoToggle(bool value, GUIContent icon) value = GUILayout.Toggle(value, icon, buttonStyle, GUILayout.Width(kButtonWidth), GUILayout.Height(kButtonHeight)); changed = check.changed; } - + return value && changed; } private bool GetToggleStateFromTangentMode(TangentMode mode) { - foreach(var path in paths) + foreach (var path in paths) { var selection = path.selection; @@ -142,13 +142,13 @@ private bool GetToggleStateFromTangentMode(TangentMode mode) if (path.GetPoint(index).tangentMode != mode) return false; } - + return true; } private void SetMixedTangentMode(TangentMode tangentMode) { - foreach(var path in paths) + foreach (var path in paths) { path.undoObject.RegisterUndo("Tangent Mode"); @@ -164,7 +164,7 @@ private bool GetMixedPosition(out Vector3 position) var first = true; position = Vector3.zero; - foreach(var path in paths) + foreach (var path in paths) { var selection = path.selection; var matrix = path.localToWorldMatrix; @@ -188,13 +188,13 @@ private bool GetMixedPosition(out Vector3 position) path.localToWorldMatrix = matrix; } - + return false; } private void SetMixedDeltaPosition(Vector3 delta) { - foreach(var path in paths) + foreach (var path in paths) { var selection = path.selection; var matrix = path.localToWorldMatrix; @@ -214,7 +214,7 @@ private void SetMixedDeltaPosition(Vector3 delta) private bool IsAnyShapeType(ShapeType shapeType) { - foreach(var path in paths) + foreach (var path in paths) if (path.shapeType == shapeType) return true; @@ -223,7 +223,7 @@ private bool IsAnyShapeType(ShapeType shapeType) protected bool IsAnyPointSelected() { - foreach(var path in paths) + foreach (var path in paths) if (path.selection.Count > 0) return true; diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/ClickAction.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/ClickAction.cs index ccfa7e16b61..31daa4e8ea1 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/ClickAction.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/ClickAction.cs @@ -24,7 +24,7 @@ protected override bool GetTriggerContidtion(IGUIState guiState) protected override void OnTrigger(IGUIState guiState) { base.OnTrigger(guiState); - + if (onClick != null) onClick(guiState, hoveredControl); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/CommandAction.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/CommandAction.cs index c7f5ede8ec5..1d7186babf8 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/CommandAction.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/CommandAction.cs @@ -24,13 +24,13 @@ protected override bool GetTriggerContidtion(IGUIState guiState) return false; } - + protected override bool GetFinishContidtion(IGUIState guiState) { if (guiState.eventType == EventType.ExecuteCommand && guiState.commandName == m_CommandName) { guiState.UseCurrentEvent(); - + return true; } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/Control.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/Control.cs index c389c8df3b5..44f9f6af3bd 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/Control.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/Control.cs @@ -106,12 +106,10 @@ protected virtual LayoutData OnBeginLayout(LayoutData data, IGUIState guiState) protected virtual void OnEndLayout(IGUIState guiState) { - } protected virtual void OnRepaint(IGUIState guiState, int index) { - } protected virtual int GetCount() diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/DefaultControl.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/DefaultControl.cs index 3578113e901..e9df67bcc68 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/DefaultControl.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/DefaultControl.cs @@ -6,7 +6,7 @@ namespace UnityEditor.Experimental.Rendering.Universal.Path2D.GUIFramework internal abstract class DefaultControl : Control { public static readonly float kPickDistance = 5f; - + public DefaultControl(string name) : base(name) { } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIAction.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIAction.cs index 598b356515b..68d497190c0 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIAction.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIAction.cs @@ -75,7 +75,7 @@ public void PreRepaint(IGUIState guiState) private void Repaint(IGUIState guiState) { Debug.Assert(guiState.eventType == EventType.Repaint); - + if (onRepaint != null) onRepaint(guiState, this); } @@ -96,17 +96,14 @@ internal bool IsRepaintOnMouseMoveEnabled(IGUIState guiState) protected virtual bool CanTrigger(IGUIState guiState) { return true; } protected virtual void OnTrigger(IGUIState guiState) { - } protected virtual void OnPerform(IGUIState guiState) { - } protected virtual void OnFinish(IGUIState guiState) { - } } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIState.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIState.cs index f867f2a2a1f..7316e8ffa73 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIState.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUIState.cs @@ -131,7 +131,7 @@ public float DistanceToSegment(Vector3 p1, Vector3 p2) return HandleUtility.DistancePointToLineSegment(Event.current.mousePosition, p1, p2); } - + public float DistanceToCircle(Vector3 center, float radius) { return HandleUtility.DistanceToCircle(center, radius); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUISystem.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUISystem.cs index d213de9dcba..6a7726589aa 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUISystem.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GUISystem.cs @@ -55,7 +55,7 @@ public void OnGUI() m_ControlIDCheck = controlIDCheck; else if (m_GUIState.eventType != EventType.Used && m_ControlIDCheck != controlIDCheck) Debug.LogWarning("GetControlID at event " + m_GUIState.eventType + " returns a controlID different from the one in Layout event"); - + var nearestLayoutData = LayoutData.zero; foreach (var control in m_Controls) diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericControl.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericControl.cs index 7bbbec327a3..da2bf44815f 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericControl.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericControl.cs @@ -53,7 +53,7 @@ protected override Vector3 GetPosition(IGUIState guiState, int index) if (position != null) return position(index); - return base.GetPosition(guiState,index); + return base.GetPosition(guiState, index); } protected override float GetDistance(IGUIState guiState, int index) @@ -69,7 +69,7 @@ protected override Vector3 GetForward(IGUIState guiState, int index) if (forward != null) return forward(index); - return base.GetForward(guiState,index); + return base.GetForward(guiState, index); } protected override Vector3 GetUp(IGUIState guiState, int index) @@ -77,7 +77,7 @@ protected override Vector3 GetUp(IGUIState guiState, int index) if (up != null) return up(index); - return base.GetUp(guiState,index); + return base.GetUp(guiState, index); } protected override Vector3 GetRight(IGUIState guiState, int index) @@ -85,15 +85,15 @@ protected override Vector3 GetRight(IGUIState guiState, int index) if (right != null) return right(index); - return base.GetRight(guiState,index); + return base.GetRight(guiState, index); } protected override object GetUserData(IGUIState guiState, int index) { if (userData != null) return userData(index); - - return base.GetUserData(guiState,index); + + return base.GetUserData(guiState, index); } } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericDefaultControl.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericDefaultControl.cs index 0ef2c901f8f..840d65fb1ba 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericDefaultControl.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/GenericDefaultControl.cs @@ -51,7 +51,7 @@ protected override object GetUserData(IGUIState guiState, int index) { if (userData != null) return userData(guiState); - + return base.GetUserData(guiState, index); } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/SliderAction.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/SliderAction.cs index 3eee43e5c80..1070dfc0486 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/SliderAction.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/GUIFramework/SliderAction.cs @@ -20,7 +20,6 @@ protected override bool GetFinishContidtion(IGUIState guiState) return guiState.eventType == EventType.MouseUp && guiState.mouseButton == 0; } - protected override void OnTrigger(IGUIState guiState) { base.OnTrigger(guiState); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/RectSelector.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/RectSelector.cs index 0475365bfec..4c4ec7e15e3 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/RectSelector.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/RectSelector.cs @@ -25,8 +25,8 @@ public Rect guiRect get { return m_GUIRect; } } - public RectSelector() : this(new GUISystem(new GUIState())) { } - + public RectSelector() : this(new GUISystem(new GUIState())) {} + public RectSelector(GUISystem guiSystem) { m_GUISystem = guiSystem; diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/SerializableSelection.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/SerializableSelection.cs index 2076340ec27..ace8e817184 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/SerializableSelection.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Selection/SerializableSelection.cs @@ -9,7 +9,7 @@ namespace UnityEditor.Experimental.Rendering.Universal.Path2D internal abstract class SerializableSelection : ISelection, ISerializationCallbackReceiver { internal readonly static int kInvalidID = -1; - + [SerializeField] private T[] m_Keys = new T[0]; @@ -42,7 +42,7 @@ public T[] elements { var union = new HashSet(m_Selection); union.UnionWith(m_TemporalSelection); - set = union; + set = union; } return new List(set).ToArray(); @@ -50,7 +50,7 @@ public T[] elements set { Clear(); - foreach(var element in value) + foreach (var element in value) Select(element, true); } } @@ -84,7 +84,7 @@ public bool Select(T element, bool select) { var changed = false; - if(EqualityComparer.Default.Equals(element, GetInvalidElement())) + if (EqualityComparer.Default.Equals(element, GetInvalidElement())) return changed; if (select) @@ -112,7 +112,7 @@ private T First() { T element = First(m_Selection); - if(EqualityComparer.Default.Equals(element, GetInvalidElement())) + if (EqualityComparer.Default.Equals(element, GetInvalidElement())) element = First(m_TemporalSelection); return element; @@ -120,9 +120,9 @@ private T First() private T First(HashSet set) { - if(set.Count == 0) + if (set.Count == 0) return GetInvalidElement(); - + using (var enumerator = set.GetEnumerator()) { Debug.Assert(enumerator.MoveNext()); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/ShapeExtensions.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/ShapeExtensions.cs index e0ff6c25d64..3bebcd3e7ea 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/ShapeExtensions.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/ShapeExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using UnityEngine; @@ -9,10 +9,10 @@ internal static class ShapeExtensions { public static Polygon ToPolygon(this Vector3[] points, bool isOpenEnded) { - return new Polygon() - { - isOpenEnded = isOpenEnded, - points = points + return new Polygon() + { + isOpenEnded = isOpenEnded, + points = points }; } @@ -25,13 +25,13 @@ public static Spline ToSpline(this Vector3[] points, bool isOpenEnded) if (isOpenEnded) { while (pointList.Count % 3 != 1) - pointList.RemoveAt(pointList.Count-1); + pointList.RemoveAt(pointList.Count - 1); points = pointList.ToArray(); } else { - var last = pointList[pointList.Count-1]; + var last = pointList[pointList.Count - 1]; var first = pointList[0]; var v = first - last; @@ -41,7 +41,7 @@ public static Spline ToSpline(this Vector3[] points, bool isOpenEnded) points = pointList.ToArray(); } } - + if (!points.IsSpline(isOpenEnded)) throw new Exception("The provided control point array can't conform a Spline."); diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/Spline.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/Spline.cs index 66019c75e55..5f7d0578d13 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/Spline.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/Shapes/Spline.cs @@ -20,7 +20,7 @@ ControlPoint[] IShape.ToControlPoints() if (points == null) throw new NullReferenceException("Points array is null"); - if (!points.IsSpline(isOpenEnded)) + if (!points.IsSpline(isOpenEnded)) throw new Exception("The provided control point array can't conform a Spline."); var controlPoints = new List(); @@ -37,11 +37,11 @@ ControlPoint[] IShape.ToControlPoints() else leftTangent = points[EditablePathUtility.Mod(-1, pointCount)]; } - + if (i == pointCount - 1 && isOpenEnded) rightTangent = points[i]; else - rightTangent = points[i+1]; + rightTangent = points[i + 1]; controlPoints.Add( @@ -56,15 +56,15 @@ ControlPoint[] IShape.ToControlPoints() if (i == pointCount - 1 && isOpenEnded) leftTangent = Vector3.zero; else - leftTangent = points[i+2]; + leftTangent = points[i + 2]; } pointCount = controlPoints.Count; - for (var i = 0; i < pointCount; ++i) + for (var i = 0; i < pointCount; ++i) { - var prevIndex = EditablePathUtility.Mod(i-1, pointCount); - var nextIndex = EditablePathUtility.Mod(i+1, pointCount); + var prevIndex = EditablePathUtility.Mod(i - 1, pointCount); + var nextIndex = EditablePathUtility.Mod(i + 1, pointCount); var controlPoint = controlPoints[i]; var prevControlPoint = controlPoints[prevIndex]; var nextControlPoint = controlPoints[nextIndex]; @@ -72,7 +72,7 @@ ControlPoint[] IShape.ToControlPoints() var liniarLeftPosition = (prevControlPoint.position - controlPoint.position) / 3f; var isLeftTangentLinear = (controlPoint.localLeftTangent - liniarLeftPosition).sqrMagnitude < 0.001f; - if (isLeftTangentLinear) + if (isLeftTangentLinear) controlPoint.localLeftTangent = Vector3.zero; var liniarRightPosition = (nextControlPoint.position - controlPoint.position) / 3f; diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/Drawer.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/Drawer.cs index ff96c884e6a..0efced26be0 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/Drawer.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/Drawer.cs @@ -118,7 +118,6 @@ public void DrawTangent(Vector3 position, Vector3 tangent) DrawGUIStyleCap(0, tangent, Quaternion.identity, m_GUIState.GetHandleSize(tangent), styles.tangentNormalStyle); } - private void DrawGUIStyleCap(int controlID, Vector3 position, Quaternion rotation, float size, GUIStyle guiStyle) { if (Camera.current && Vector3.Dot(position - Camera.current.transform.position, Camera.current.transform.forward) < 0f) diff --git a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/EditablePathView.cs b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/EditablePathView.cs index f6e8024f6c8..4a8726fee41 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/EditablePathView.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/ShapeEditor/View/EditablePathView.cs @@ -26,8 +26,8 @@ internal class EditablePathView : IEditablePathView private GUIAction m_MoveRightTangentAction; private IDrawer m_Drawer; - public EditablePathView() : this(new Drawer()) { } - + public EditablePathView() : this(new Drawer()) {} + public EditablePathView(IDrawer drawer) { m_Drawer = drawer; @@ -87,7 +87,7 @@ public EditablePathView(IDrawer drawer) var position = GetPoint(i).position; var leftTangent = GetLeftTangent(i); - + m_Drawer.DrawTangent(position, leftTangent); } }; @@ -98,12 +98,12 @@ public EditablePathView(IDrawer drawer) { if (GetShapeType() != ShapeType.Spline) return 0; - + return GetPointCount(); }, distance = (guiState, i) => { - if (!IsSelected(i) || IsOpenEnded() && i == GetPointCount()-1) + if (!IsSelected(i) || IsOpenEnded() && i == GetPointCount() - 1) return float.MaxValue; var position = GetRightTangent(i); @@ -115,9 +115,9 @@ public EditablePathView(IDrawer drawer) right = (i) => { return GetRight(); }, onRepaint = (guiState, control, i) => { - if (!IsSelected(i) || IsOpenEnded() && i == GetPointCount()-1) + if (!IsSelected(i) || IsOpenEnded() && i == GetPointCount() - 1) return; - + var position = GetPoint(i).position; var rightTangent = GetRightTangent(i); @@ -173,7 +173,7 @@ public EditablePathView(IDrawer drawer) if (!guiState.isActionKeyDown && !IsSelected(index)) controller.ClearSelection(); - + controller.SelectPoint(index, true); guiState.changed = true; }, @@ -201,14 +201,14 @@ public EditablePathView(IDrawer drawer) { var index = control.hotLayoutData.index; var delta = position - GetPoint(index).position; - + controller.MoveEdge(index, delta); } }; var cachedRightTangent = Vector3.zero; var cachedLeftTangent = Vector3.zero; - + m_MoveLeftTangentAction = new SliderAction(m_LeftTangentControl) { onSliderBegin = (guiState, control, position) => @@ -222,7 +222,6 @@ public EditablePathView(IDrawer drawer) var setToLinear = guiState.nearestControl == m_PointControl.ID && m_PointControl.layoutData.index == index; controller.SetLeftTangent(index, position, setToLinear, guiState.isShiftDown, cachedRightTangent); - }, onSliderEnd = (guiState, control, position) => { @@ -381,7 +380,7 @@ private Vector3 ClosestPointInEdge(IGUIState guiState, Vector2 mousePosition, in var dir1 = (mouseWorldPosition - p0); var dir2 = (p1 - p0); - + return Mathf.Clamp01(Vector3.Dot(dir1, dir2.normalized) / dir2.magnitude) * dir2 + p0; } else if (GetShapeType() == ShapeType.Spline) @@ -441,9 +440,9 @@ private void DrawEdge(IGUIState guiState, Control control, int index) var nextIndex = NextIndex(index); var color = Color.white; - if(guiState.nearestControl == control.ID && control.layoutData.index == index && guiState.hotControl == 0) + if (guiState.nearestControl == control.ID && control.layoutData.index == index && guiState.hotControl == 0) color = Color.yellow; - + m_Drawer.DrawLine(GetPoint(index).position, GetPoint(nextIndex).position, 5f, color); } else if (GetShapeType() == ShapeType.Spline) @@ -451,9 +450,9 @@ private void DrawEdge(IGUIState guiState, Control control, int index) var nextIndex = NextIndex(index); var color = Color.white; - if(guiState.nearestControl == control.ID && control.layoutData.index == index && guiState.hotControl == 0) + if (guiState.nearestControl == control.ID && control.layoutData.index == index && guiState.hotControl == 0) color = Color.yellow; - + m_Drawer.DrawBezier( GetPoint(index).position, GetRightTangent(index), @@ -467,23 +466,23 @@ private void DrawEdge(IGUIState guiState, Control control, int index) private bool EnableCreatePointRepaint(IGUIState guiState, GUIAction action) { return guiState.nearestControl != m_PointControl.ID && - guiState.hotControl == 0 && - (guiState.nearestControl != m_LeftTangentControl.ID) && - (guiState.nearestControl != m_RightTangentControl.ID); + guiState.hotControl == 0 && + (guiState.nearestControl != m_LeftTangentControl.ID) && + (guiState.nearestControl != m_RightTangentControl.ID); } private Vector3 SnapIfNeeded(Vector3 position) { if (!controller.enableSnapping || controller.snapping == null) return position; - + var guiPosition = HandleUtility.WorldToGUIPoint(position); var snappedGuiPosition = HandleUtility.WorldToGUIPoint(controller.snapping.Snap(position)); var sqrDistance = (guiPosition - snappedGuiPosition).sqrMagnitude; if (sqrDistance < kSnappingDistance * kSnappingDistance) position = controller.snapping.Snap(position); - + return position; } } diff --git a/com.unity.render-pipelines.universal/Editor/2D/SortingLayerDropDown.cs b/com.unity.render-pipelines.universal/Editor/2D/SortingLayerDropDown.cs index 074d2414f61..9284b61a800 100644 --- a/com.unity.render-pipelines.universal/Editor/2D/SortingLayerDropDown.cs +++ b/com.unity.render-pipelines.universal/Editor/2D/SortingLayerDropDown.cs @@ -46,7 +46,7 @@ public void OnEnable(SerializedObject serializedObject, string propertyName) void UpdateApplyToSortingLayersArray(object layerSelectionDataObject) { - LayerSelectionData layerSelectionData = (LayerSelectionData)layerSelectionDataObject; + LayerSelectionData layerSelectionData = (LayerSelectionData)layerSelectionDataObject; m_ApplyToSortingLayers.ClearArray(); for (int i = 0; i < m_ApplyToSortingLayersList.Count; ++i) @@ -57,7 +57,7 @@ void UpdateApplyToSortingLayersArray(object layerSelectionDataObject) if (layerSelectionData.onSelectionChanged != null) layerSelectionData.onSelectionChanged(layerSelectionData.serializedObject); - + layerSelectionData.serializedObject.ApplyModifiedProperties(); if (layerSelectionData.targets is Light2D[]) @@ -85,7 +85,6 @@ void OnAllSortingLayersSelected(object selectionData) void OnSortingLayerSelected(object layerSelectionDataObject) { - LayerSelectionData layerSelectionData = (LayerSelectionData)layerSelectionDataObject; int layerID = (int)layerSelectionData.layerID; diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/AutodeskInteractiveMaterialImport.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/AutodeskInteractiveMaterialImport.cs index a59cf3457bf..dbad7062f58 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/AutodeskInteractiveMaterialImport.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/AutodeskInteractiveMaterialImport.cs @@ -13,6 +13,7 @@ public override uint GetVersion() { return k_Version; } + public override int GetPostprocessOrder() { return k_Order; @@ -23,15 +24,15 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat var pipelineAsset = GraphicsSettings.currentRenderPipeline; if (!pipelineAsset || pipelineAsset.GetType() != typeof(UniversalRenderPipelineAsset)) return; - + if (IsAutodeskInteractiveMaterial(description)) { float floatProperty; Vector4 vectorProperty; TexturePropertyDescription textureProperty; - bool isMasked = description.TryGetProperty("mask_threshold",out floatProperty); - bool isTransparent = description.TryGetProperty("opacity",out floatProperty); + bool isMasked = description.TryGetProperty("mask_threshold", out floatProperty); + bool isTransparent = description.TryGetProperty("opacity", out floatProperty); Shader shader; if (isMasked) diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs index fcf15185f1b..96d7e25800d 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXArnoldSurfaceMaterialDescriptionPreprocessor.cs @@ -99,7 +99,6 @@ void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description { material.SetFloat("_OPACITY", opacity); } - } else { @@ -110,7 +109,7 @@ void CreateFromMayaArnoldStandardSurfaceMaterial(MaterialDescription description material.shader = shader; } - + foreach (var clip in clips) { clip.ClearCurves(); @@ -225,7 +224,6 @@ void CreateFrom3DsMaxArnoldStandardSurfaceMaterial(MaterialDescription descripti remapPropertyFloatOrTexture3DsMax(description, material, "specular_IOR", "_SPECULAR_IOR"); remapPropertyTexture(description, material, "normal_camera", "_NORMAL_MAP"); - } static void SetMaterialTextureProperty(string propertyName, Material material, diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXMaterialDescriptionPreprocessor.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXMaterialDescriptionPreprocessor.cs index f212c9a326d..ad88c40075b 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXMaterialDescriptionPreprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/FBXMaterialDescriptionPreprocessor.cs @@ -34,7 +34,7 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat var shader = AssetDatabase.LoadAssetAtPath(path); if (shader == null) return; - + material.shader = shader; @@ -91,7 +91,7 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat material.SetFloat("_Surface", 0.0f); } - if (description.TryGetProperty("DiffuseColor", out textureProperty) && textureProperty.texture!=null) + if (description.TryGetProperty("DiffuseColor", out textureProperty) && textureProperty.texture != null) { Color diffuseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); if (description.TryGetProperty("DiffuseFactor", out floatProperty)) @@ -164,7 +164,7 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat RemapColorCurves(description, clips, "EmissiveColor", "_EmissionColor"); } - + static void RemapTransparencyCurves(MaterialDescription description, AnimationClip[] clips) { // For some reason, Opacity is never animated, we have to use TransparencyFactor and TransparentColor diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs index 8a722052a85..0e05c256ec9 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs @@ -68,9 +68,9 @@ static void RegisterUpgraderReimport() if (!inTestSuite && fileExist) { EditorUtility.DisplayDialog("URP Material upgrade", "The Materials in your Project were created using an older version of the Universal Render Pipeline (URP)." + - " Unity must upgrade them to be compatible with your current version of URP. \n" + - " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + - " Please see the Material upgrade guide in the URP documentation for more information.", "Ok"); + " Unity must upgrade them to be compatible with your current version of URP. \n" + + " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + + " Please see the Material upgrade guide in the URP documentation for more information.", "Ok"); } ReimportAllMaterials(); @@ -188,7 +188,6 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse static void InitializeLatest(Material material, ShaderPathID id) { - } static void UpgradeV1(Material material, ShaderPathID shaderID) @@ -228,7 +227,7 @@ static void UpgradeV1(Material material, ShaderPathID shaderID) static void UpgradeV2(Material material, ShaderPathID shaderID) { // fix 50 offset on shaders - if(material.HasProperty("_QueueOffset")) + if (material.HasProperty("_QueueOffset")) BaseShaderGUI.SetupMaterialBlendMode(material); } @@ -269,11 +268,10 @@ public static void UpdateLitDetails(Material material) if (material == null) throw new ArgumentNullException("material"); - if(material.GetTexture("_MetallicGlossMap") || material.GetTexture("_SpecGlossMap") || material.GetFloat("_SmoothnessTextureChannel") >= 0.5f) + if (material.GetTexture("_MetallicGlossMap") || material.GetTexture("_SpecGlossMap") || material.GetFloat("_SmoothnessTextureChannel") >= 0.5f) material.SetFloat("_Smoothness", material.GetFloat("_GlossMapScale")); else material.SetFloat("_Smoothness", material.GetFloat("_Glossiness")); - } public LitUpdaterV1(string oldShaderName) @@ -340,7 +338,7 @@ public static void UpgradeToSimpleLit(Material material) throw new ArgumentNullException("material"); var smoothnessSource = 1 - (int)material.GetFloat("_GlossinessSource"); - material.SetFloat("_SmoothnessSource" ,smoothnessSource); + material.SetFloat("_SmoothnessSource" , smoothnessSource); if (material.GetTexture("_SpecGlossMap") == null) { var col = material.GetColor("_SpecColor"); @@ -390,4 +388,3 @@ public ParticleUpdaterV1(string shaderName) } #endregion } - diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/PhysicalMaterial3DsMaxPreprocessor.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/PhysicalMaterial3DsMaxPreprocessor.cs index e68fbdcff8e..30cf0936806 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/PhysicalMaterial3DsMaxPreprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/PhysicalMaterial3DsMaxPreprocessor.cs @@ -26,7 +26,7 @@ public override int GetPostprocessOrder() { return k_Order; } - + static bool Is3DsMaxPhysicalMaterial(MaterialDescription description) { float classIdA; @@ -43,8 +43,8 @@ static bool Is3DsMaxSimplifiedPhysicalMaterial(MaterialDescription description) float useGlossiness; description.TryGetProperty("ClassIDa", out classIdA); description.TryGetProperty("ClassIDb", out classIdB); - description.TryGetProperty("useGlossiness", out useGlossiness); - + description.TryGetProperty("useGlossiness", out useGlossiness); + return classIdA == -804315648 && classIdB == -1099438848 && useGlossiness == 2.0f; } @@ -71,11 +71,11 @@ void CreateFrom3DsSimplifiedPhysicalMaterial(MaterialDescription description, Ma TexturePropertyDescription textureProperty; description.TryGetProperty("basecolor", out vectorProperty); - bool hasTransparencyScalar = vectorProperty.w !=1.0f; + bool hasTransparencyScalar = vectorProperty.w != 1.0f; var hasTransparencyMap = description.TryGetProperty("opacity_map", out textureProperty); bool isTransparent = hasTransparencyMap | hasTransparencyScalar; - + Shader shader; if (isTransparent) shader = GraphicsSettings.currentRenderPipeline.autodeskInteractiveTransparentShader; @@ -282,7 +282,7 @@ static void RemapPropertyTextureOrColor(MaterialDescription description, Materia material.SetTexture(outPropName + "_MAP", textureProperty.texture); material.SetColor(outPropName, Color.white); } - else if(description.TryGetProperty(inPropName, out Vector4 color)) + else if (description.TryGetProperty(inPropName, out Vector4 color)) { material.SetColor(outPropName, color); } @@ -296,7 +296,7 @@ static void RemapPropertyTextureOrFloat(MaterialDescription description, Materia material.SetTexture(outPropName + "_MAP", textureProperty.texture); material.SetFloat(outPropName, 1.0f); } - else if(description.TryGetProperty(inPropName, out float floatProperty)) + else if (description.TryGetProperty(inPropName, out float floatProperty)) { material.SetFloat(outPropName, floatProperty); } diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/SketchupMaterialDescriptionPostprocessor.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/SketchupMaterialDescriptionPostprocessor.cs index 7d8bfc5d8dc..2c570eb4cf1 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/SketchupMaterialDescriptionPostprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/SketchupMaterialDescriptionPostprocessor.cs @@ -41,7 +41,7 @@ public void OnPreprocessMaterialDescription(MaterialDescription description, Mat Vector4 vectorProperty; TexturePropertyDescription textureProperty; - if (description.TryGetProperty("DiffuseMap", out textureProperty) && textureProperty.texture!=null) + if (description.TryGetProperty("DiffuseMap", out textureProperty) && textureProperty.texture != null) { SetMaterialTextureProperty("_BaseMap", material, textureProperty); SetMaterialTextureProperty("_MainTex", material, textureProperty); @@ -91,4 +91,3 @@ static void SetMaterialTextureProperty(string propertyName, Material material, T } } } - diff --git a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/ThreeDSMaterialDescriptionPostprocessor.cs b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/ThreeDSMaterialDescriptionPostprocessor.cs index 84ed0619f30..4559e9bc998 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/ThreeDSMaterialDescriptionPostprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/ThreeDSMaterialDescriptionPostprocessor.cs @@ -113,4 +113,3 @@ static void SetMaterialTextureProperty(string propertyName, Material material, T } } } - diff --git a/com.unity.render-pipelines.universal/Editor/AssetVersion.cs b/com.unity.render-pipelines.universal/Editor/AssetVersion.cs index efca04a3764..60ac5a7d7c3 100644 --- a/com.unity.render-pipelines.universal/Editor/AssetVersion.cs +++ b/com.unity.render-pipelines.universal/Editor/AssetVersion.cs @@ -1,4 +1,4 @@ -using UnityEngine; +using UnityEngine; namespace UnityEditor.Rendering.Universal { diff --git a/com.unity.render-pipelines.universal/Editor/Deprecated.cs b/com.unity.render-pipelines.universal/Editor/Deprecated.cs index 498a539c5f2..f9cfd9459cb 100644 --- a/com.unity.render-pipelines.universal/Editor/Deprecated.cs +++ b/com.unity.render-pipelines.universal/Editor/Deprecated.cs @@ -67,9 +67,9 @@ public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartition // From this point on, we move to non-layout based code. var sliderRect = GUILayoutUtility.GetRect(GUIContent.none - , s_CascadeSliderBG - , GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin) - , GUILayout.ExpandWidth(true)); + , s_CascadeSliderBG + , GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin) + , GUILayout.ExpandWidth(true)); GUI.Box(sliderRect, GUIContent.none); EditorGUILayout.EndHorizontal(); diff --git a/com.unity.render-pipelines.universal/Editor/LightExplorer.cs b/com.unity.render-pipelines.universal/Editor/LightExplorer.cs index 1cde4897e90..072f687caa9 100644 --- a/com.unity.render-pipelines.universal/Editor/LightExplorer.cs +++ b/com.unity.render-pipelines.universal/Editor/LightExplorer.cs @@ -5,53 +5,53 @@ namespace UnityEditor { - [LightingExplorerExtensionAttribute(typeof(UniversalRenderPipelineAsset))] - [MovedFrom("UnityEditor.Rendering.LWRP")] public class LightExplorer : DefaultLightingExplorerExtension - { - private static class Styles + [LightingExplorerExtensionAttribute(typeof(UniversalRenderPipelineAsset))] + [MovedFrom("UnityEditor.Rendering.LWRP")] public class LightExplorer : DefaultLightingExplorerExtension + { + private static class Styles { - public static readonly GUIContent Enabled = EditorGUIUtility.TrTextContent("Enabled"); - public static readonly GUIContent Name = EditorGUIUtility.TrTextContent("Name"); - public static readonly GUIContent Mode = EditorGUIUtility.TrTextContent("Mode"); + public static readonly GUIContent Enabled = EditorGUIUtility.TrTextContent("Enabled"); + public static readonly GUIContent Name = EditorGUIUtility.TrTextContent("Name"); + public static readonly GUIContent Mode = EditorGUIUtility.TrTextContent("Mode"); - public static readonly GUIContent HDR = EditorGUIUtility.TrTextContent("HDR"); - public static readonly GUIContent ShadowDistance = EditorGUIUtility.TrTextContent("Shadow Distance"); - public static readonly GUIContent NearPlane = EditorGUIUtility.TrTextContent("Near Plane"); - public static readonly GUIContent FarPlane = EditorGUIUtility.TrTextContent("Far Plane"); - public static readonly GUIContent Resolution = EditorGUIUtility.TrTextContent("Resolution"); + public static readonly GUIContent HDR = EditorGUIUtility.TrTextContent("HDR"); + public static readonly GUIContent ShadowDistance = EditorGUIUtility.TrTextContent("Shadow Distance"); + public static readonly GUIContent NearPlane = EditorGUIUtility.TrTextContent("Near Plane"); + public static readonly GUIContent FarPlane = EditorGUIUtility.TrTextContent("Far Plane"); + public static readonly GUIContent Resolution = EditorGUIUtility.TrTextContent("Resolution"); - public static readonly GUIContent[] ReflectionProbeModeTitles = { EditorGUIUtility.TrTextContent("Baked"), EditorGUIUtility.TrTextContent("Realtime"), EditorGUIUtility.TrTextContent("Custom") }; - public static readonly int[] ReflectionProbeModeValues = { (int)ReflectionProbeMode.Baked, (int)ReflectionProbeMode.Realtime, (int)ReflectionProbeMode.Custom }; - public static readonly GUIContent[] ReflectionProbeSizeTitles = { EditorGUIUtility.TrTextContent("16"), - EditorGUIUtility.TrTextContent("32"), - EditorGUIUtility.TrTextContent("64"), - EditorGUIUtility.TrTextContent("128"), - EditorGUIUtility.TrTextContent("256"), - EditorGUIUtility.TrTextContent("512"), - EditorGUIUtility.TrTextContent("1024"), - EditorGUIUtility.TrTextContent("2048") }; - public static readonly int[] ReflectionProbeSizeValues = { 16, 32, 64, 128, 256, 512, 1024, 2048 }; + public static readonly GUIContent[] ReflectionProbeModeTitles = { EditorGUIUtility.TrTextContent("Baked"), EditorGUIUtility.TrTextContent("Realtime"), EditorGUIUtility.TrTextContent("Custom") }; + public static readonly int[] ReflectionProbeModeValues = { (int)ReflectionProbeMode.Baked, (int)ReflectionProbeMode.Realtime, (int)ReflectionProbeMode.Custom }; + public static readonly GUIContent[] ReflectionProbeSizeTitles = { EditorGUIUtility.TrTextContent("16"), + EditorGUIUtility.TrTextContent("32"), + EditorGUIUtility.TrTextContent("64"), + EditorGUIUtility.TrTextContent("128"), + EditorGUIUtility.TrTextContent("256"), + EditorGUIUtility.TrTextContent("512"), + EditorGUIUtility.TrTextContent("1024"), + EditorGUIUtility.TrTextContent("2048") }; + public static readonly int[] ReflectionProbeSizeValues = { 16, 32, 64, 128, 256, 512, 1024, 2048 }; } - protected override LightingExplorerTableColumn[] GetReflectionProbeColumns() - { - return new[] - { - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.Enabled, "m_Enabled", 50), // 0: Enabled - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 1: Name - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, Styles.Mode, "m_Mode", 70, (r, prop, dep) => - { - EditorGUI.IntPopup(r, prop, Styles.ReflectionProbeModeTitles, Styles.ReflectionProbeModeValues, GUIContent.none); - }), // 2: Mode - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.HDR, "m_HDR", 35), // 3: HDR - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, Styles.Resolution, "m_Resolution", 100, (r, prop, dep) => - { - EditorGUI.IntPopup(r, prop, Styles.ReflectionProbeSizeTitles, Styles.ReflectionProbeSizeValues, GUIContent.none); - }), // 4: Probe Resolution - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, Styles.ShadowDistance, "m_ShadowDistance", 100), // 5: Shadow Distance - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, Styles.NearPlane, "m_NearClip", 70), // 6: Near Plane - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, Styles.FarPlane, "m_FarClip", 70), // 7: Far Plane - }; - } - } + protected override LightingExplorerTableColumn[] GetReflectionProbeColumns() + { + return new[] + { + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.Enabled, "m_Enabled", 50), // 0: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 1: Name + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, Styles.Mode, "m_Mode", 70, (r, prop, dep) => + { + EditorGUI.IntPopup(r, prop, Styles.ReflectionProbeModeTitles, Styles.ReflectionProbeModeValues, GUIContent.none); + }), // 2: Mode + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.HDR, "m_HDR", 35), // 3: HDR + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, Styles.Resolution, "m_Resolution", 100, (r, prop, dep) => + { + EditorGUI.IntPopup(r, prop, Styles.ReflectionProbeSizeTitles, Styles.ReflectionProbeSizeValues, GUIContent.none); + }), // 4: Probe Resolution + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, Styles.ShadowDistance, "m_ShadowDistance", 100), // 5: Shadow Distance + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, Styles.NearPlane, "m_NearClip", 70), // 6: Near Plane + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Float, Styles.FarPlane, "m_FarClip", 70), // 7: Far Plane + }; + } + } } diff --git a/com.unity.render-pipelines.universal/Editor/Overrides/MotionBlurEditor.cs b/com.unity.render-pipelines.universal/Editor/Overrides/MotionBlurEditor.cs index 15e646cdc73..a7f0c97b945 100644 --- a/com.unity.render-pipelines.universal/Editor/Overrides/MotionBlurEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/Overrides/MotionBlurEditor.cs @@ -26,9 +26,9 @@ public override void OnInspectorGUI() //if (m_Mode.value.intValue == (int)MotionBlurMode.CameraOnly) //{ - PropertyField(m_Quality); - PropertyField(m_Intensity); - PropertyField(m_Clamp); + PropertyField(m_Quality); + PropertyField(m_Intensity); + PropertyField(m_Clamp); //} //else //{ diff --git a/com.unity.render-pipelines.universal/Editor/RenderStateDataEditor.cs b/com.unity.render-pipelines.universal/Editor/RenderStateDataEditor.cs index 85d6af714b4..95501e1d2ba 100644 --- a/com.unity.render-pipelines.universal/Editor/RenderStateDataEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/RenderStateDataEditor.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering.Universal; @@ -56,7 +56,7 @@ void Init(SerializedProperty property) public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label) { - if(!m_properties.Contains(property.serializedObject)) + if (!m_properties.Contains(property.serializedObject)) Init(property); rect.height = EditorGUIUtility.singleLineHeight; diff --git a/com.unity.render-pipelines.universal/Editor/RendererFeatures/RenderObjectsPassFeatureEditor.cs b/com.unity.render-pipelines.universal/Editor/RendererFeatures/RenderObjectsPassFeatureEditor.cs index b6fc6154ad6..c0cb3674d0e 100644 --- a/com.unity.render-pipelines.universal/Editor/RendererFeatures/RenderObjectsPassFeatureEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/RendererFeatures/RenderObjectsPassFeatureEditor.cs @@ -8,76 +8,76 @@ namespace UnityEditor.Experimental.Rendering.Universal { - [CustomPropertyDrawer(typeof(RenderObjects.RenderObjectsSettings), true)] + [CustomPropertyDrawer(typeof(RenderObjects.RenderObjectsSettings), true)] internal class RenderObjectsPassFeatureEditor : PropertyDrawer { - internal class Styles - { - public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; - public static GUIContent callback = new GUIContent("Event", "Choose at which point this render pass is executed in the frame."); - - //Headers - public static GUIContent filtersHeader = new GUIContent("Filters", "Settings that control which objects should be rendered."); - public static GUIContent renderHeader = new GUIContent("Overrides", "Different parts of the rendering that you can choose to override."); - - //Filters - public static GUIContent renderQueueFilter = new GUIContent("Queue", "Only render objects in the selected render queue range."); - public static GUIContent layerMask = new GUIContent("Layer Mask", "Only render objects in a layer that match the given layer mask."); - public static GUIContent shaderPassFilter = new GUIContent("LightMode Tags", "Controls which shader passes to render by filtering by LightMode tag."); - - //Render Options - public static GUIContent overrideMaterial = new GUIContent("Material", "Choose an override material, every renderer will be rendered with this material."); - public static GUIContent overrideMaterialPass = new GUIContent("Pass Index", "The pass index for the override material to use."); - - //Depth Settings - public static GUIContent overrideDepth = new GUIContent("Depth", "Override depth rendering."); - public static GUIContent writeDepth = new GUIContent("Write Depth", "Choose to write depth to the screen."); - public static GUIContent depthState = new GUIContent("Depth Test", "Choose a new depth test function."); - - //Camera Settings + internal class Styles + { + public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; + public static GUIContent callback = new GUIContent("Event", "Choose at which point this render pass is executed in the frame."); + + //Headers + public static GUIContent filtersHeader = new GUIContent("Filters", "Settings that control which objects should be rendered."); + public static GUIContent renderHeader = new GUIContent("Overrides", "Different parts of the rendering that you can choose to override."); + + //Filters + public static GUIContent renderQueueFilter = new GUIContent("Queue", "Only render objects in the selected render queue range."); + public static GUIContent layerMask = new GUIContent("Layer Mask", "Only render objects in a layer that match the given layer mask."); + public static GUIContent shaderPassFilter = new GUIContent("LightMode Tags", "Controls which shader passes to render by filtering by LightMode tag."); + + //Render Options + public static GUIContent overrideMaterial = new GUIContent("Material", "Choose an override material, every renderer will be rendered with this material."); + public static GUIContent overrideMaterialPass = new GUIContent("Pass Index", "The pass index for the override material to use."); + + //Depth Settings + public static GUIContent overrideDepth = new GUIContent("Depth", "Override depth rendering."); + public static GUIContent writeDepth = new GUIContent("Write Depth", "Choose to write depth to the screen."); + public static GUIContent depthState = new GUIContent("Depth Test", "Choose a new depth test function."); + + //Camera Settings public static GUIContent overrideCamera = new GUIContent("Camera", "Override camera matrices. Toggling this setting will make camera use perspective projection."); - public static GUIContent cameraFOV = new GUIContent("Field Of View", "The camera's view angle measured in degrees along vertical axis."); - public static GUIContent positionOffset = new GUIContent("Position Offset", "Position offset to apply to the original camera's position."); - public static GUIContent restoreCamera = new GUIContent("Restore", "Restore to the original camera matrices after the execution of the render passes added by this feature."); + public static GUIContent cameraFOV = new GUIContent("Field Of View", "The camera's view angle measured in degrees along vertical axis."); + public static GUIContent positionOffset = new GUIContent("Position Offset", "Position offset to apply to the original camera's position."); + public static GUIContent restoreCamera = new GUIContent("Restore", "Restore to the original camera matrices after the execution of the render passes added by this feature."); } - //Headers and layout - private HeaderBool m_FiltersFoldout; - private int m_FilterLines = 3; - private HeaderBool m_RenderFoldout; - private int m_MaterialLines = 2; - private int m_DepthLines = 3; - private int m_CameraLines = 4; - - // Serialized Properties - private SerializedProperty m_Callback; - private SerializedProperty m_PassTag; - //Filter props - private SerializedProperty m_FilterSettings; - private SerializedProperty m_RenderQueue; - private SerializedProperty m_LayerMask; - private SerializedProperty m_ShaderPasses; - //Render props - private SerializedProperty m_OverrideMaterial; - private SerializedProperty m_OverrideMaterialPass; - //Depth props - private SerializedProperty m_OverrideDepth; - private SerializedProperty m_WriteDepth; - private SerializedProperty m_DepthState; - //Stencil props - private SerializedProperty m_OverrideStencil; - //Caemra props - private SerializedProperty m_CameraSettings; - private SerializedProperty m_OverrideCamera; - private SerializedProperty m_FOV; - private SerializedProperty m_CameraOffset; - private SerializedProperty m_RestoreCamera; + //Headers and layout + private HeaderBool m_FiltersFoldout; + private int m_FilterLines = 3; + private HeaderBool m_RenderFoldout; + private int m_MaterialLines = 2; + private int m_DepthLines = 3; + private int m_CameraLines = 4; + + // Serialized Properties + private SerializedProperty m_Callback; + private SerializedProperty m_PassTag; + //Filter props + private SerializedProperty m_FilterSettings; + private SerializedProperty m_RenderQueue; + private SerializedProperty m_LayerMask; + private SerializedProperty m_ShaderPasses; + //Render props + private SerializedProperty m_OverrideMaterial; + private SerializedProperty m_OverrideMaterialPass; + //Depth props + private SerializedProperty m_OverrideDepth; + private SerializedProperty m_WriteDepth; + private SerializedProperty m_DepthState; + //Stencil props + private SerializedProperty m_OverrideStencil; + //Caemra props + private SerializedProperty m_CameraSettings; + private SerializedProperty m_OverrideCamera; + private SerializedProperty m_FOV; + private SerializedProperty m_CameraOffset; + private SerializedProperty m_RestoreCamera; private List m_properties = new List(); static bool FilterRenderPassEvent(int evt) => // Return all events higher or equal than before rendering prepasses - evt >= (int) RenderPassEvent.BeforeRenderingPrepasses && + evt >= (int)RenderPassEvent.BeforeRenderingPrepasses && // filter obsolete events typeof(RenderPassEvent).GetField(Enum.GetName(typeof(RenderPassEvent), evt))?.GetCustomAttribute(typeof(ObsoleteAttribute)) == null; @@ -130,10 +130,10 @@ private void Init(SerializedProperty property) } public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label) - { + { rect.height = EditorGUIUtility.singleLineHeight; - EditorGUI.BeginChangeCheck(); - EditorGUI.BeginProperty(rect, label, property); + EditorGUI.BeginChangeCheck(); + EditorGUI.BeginProperty(rect, label, property); if (!m_properties.Contains(property.serializedObject)) { @@ -141,13 +141,13 @@ public override void OnGUI(Rect rect, SerializedProperty property, GUIContent la } var passName = property.serializedObject.FindProperty("m_Name").stringValue; - if (passName != m_PassTag.stringValue) - { - m_PassTag.stringValue = passName; - property.serializedObject.ApplyModifiedProperties(); - } + if (passName != m_PassTag.stringValue) + { + m_PassTag.stringValue = passName; + property.serializedObject.ApplyModifiedProperties(); + } - //Forward Callbacks + //Forward Callbacks EditorGUI.BeginChangeCheck(); int selectedValue = EditorGUI.IntPopup(rect, Styles.callback, m_Callback.intValue, m_EventOptionNames, m_EventOptionValues); if (EditorGUI.EndChangeCheck()) @@ -156,116 +156,116 @@ public override void OnGUI(Rect rect, SerializedProperty property, GUIContent la DoFilters(ref rect); - m_RenderFoldout.value = EditorGUI.Foldout(rect, m_RenderFoldout.value, Styles.renderHeader, true); - SaveHeaderBool(m_RenderFoldout); - rect.y += Styles.defaultLineSpace; - if (m_RenderFoldout.value) - { - EditorGUI.indentLevel++; - //Override material - DoMaterialOverride(ref rect); - rect.y += Styles.defaultLineSpace; - //Override depth - DoDepthOverride(ref rect); - rect.y += Styles.defaultLineSpace; - //Override stencil - EditorGUI.PropertyField(rect, m_OverrideStencil); - rect.y += EditorGUI.GetPropertyHeight(m_OverrideStencil); - //Override camera - DoCameraOverride(ref rect); - rect.y += Styles.defaultLineSpace; - - EditorGUI.indentLevel--; - } - - EditorGUI.EndProperty(); - if (EditorGUI.EndChangeCheck()) - property.serializedObject.ApplyModifiedProperties(); - } - - void DoFilters(ref Rect rect) - { - m_FiltersFoldout.value = EditorGUI.Foldout(rect, m_FiltersFoldout.value, Styles.filtersHeader, true); - SaveHeaderBool(m_FiltersFoldout); - rect.y += Styles.defaultLineSpace; - if (m_FiltersFoldout.value) - { - EditorGUI.indentLevel++; - //Render queue filter - EditorGUI.PropertyField(rect, m_RenderQueue, Styles.renderQueueFilter); - rect.y += Styles.defaultLineSpace; - //Layer mask - EditorGUI.PropertyField(rect, m_LayerMask, Styles.layerMask); - rect.y += Styles.defaultLineSpace; - //Shader pass list + m_RenderFoldout.value = EditorGUI.Foldout(rect, m_RenderFoldout.value, Styles.renderHeader, true); + SaveHeaderBool(m_RenderFoldout); + rect.y += Styles.defaultLineSpace; + if (m_RenderFoldout.value) + { + EditorGUI.indentLevel++; + //Override material + DoMaterialOverride(ref rect); + rect.y += Styles.defaultLineSpace; + //Override depth + DoDepthOverride(ref rect); + rect.y += Styles.defaultLineSpace; + //Override stencil + EditorGUI.PropertyField(rect, m_OverrideStencil); + rect.y += EditorGUI.GetPropertyHeight(m_OverrideStencil); + //Override camera + DoCameraOverride(ref rect); + rect.y += Styles.defaultLineSpace; + + EditorGUI.indentLevel--; + } + + EditorGUI.EndProperty(); + if (EditorGUI.EndChangeCheck()) + property.serializedObject.ApplyModifiedProperties(); + } + + void DoFilters(ref Rect rect) + { + m_FiltersFoldout.value = EditorGUI.Foldout(rect, m_FiltersFoldout.value, Styles.filtersHeader, true); + SaveHeaderBool(m_FiltersFoldout); + rect.y += Styles.defaultLineSpace; + if (m_FiltersFoldout.value) + { + EditorGUI.indentLevel++; + //Render queue filter + EditorGUI.PropertyField(rect, m_RenderQueue, Styles.renderQueueFilter); + rect.y += Styles.defaultLineSpace; + //Layer mask + EditorGUI.PropertyField(rect, m_LayerMask, Styles.layerMask); + rect.y += Styles.defaultLineSpace; + //Shader pass list EditorGUI.PropertyField(rect, m_ShaderPasses, Styles.shaderPassFilter, true); rect.y += EditorGUI.GetPropertyHeight(m_ShaderPasses); EditorGUI.indentLevel--; } - } - - void DoMaterialOverride(ref Rect rect) - { - //Override material - EditorGUI.PropertyField(rect, m_OverrideMaterial, Styles.overrideMaterial); - if (m_OverrideMaterial.objectReferenceValue) - { - rect.y += Styles.defaultLineSpace; - EditorGUI.indentLevel++; - EditorGUI.BeginChangeCheck(); - EditorGUI.PropertyField(rect, m_OverrideMaterialPass, Styles.overrideMaterialPass); - if (EditorGUI.EndChangeCheck()) - m_OverrideMaterialPass.intValue = Mathf.Max(0, m_OverrideMaterialPass.intValue); - EditorGUI.indentLevel--; - } - } - - void DoDepthOverride(ref Rect rect) - { - EditorGUI.PropertyField(rect, m_OverrideDepth, Styles.overrideDepth); - if (m_OverrideDepth.boolValue) - { - rect.y += Styles.defaultLineSpace; - EditorGUI.indentLevel++; - //Write depth - EditorGUI.PropertyField(rect, m_WriteDepth, Styles.writeDepth); - rect.y += Styles.defaultLineSpace; - //Depth testing options - EditorGUI.PropertyField(rect, m_DepthState, Styles.depthState); - EditorGUI.indentLevel--; - } - } - - void DoCameraOverride(ref Rect rect) - { - EditorGUI.PropertyField(rect, m_OverrideCamera, Styles.overrideCamera); - if (m_OverrideCamera.boolValue) - { - rect.y += Styles.defaultLineSpace; - EditorGUI.indentLevel++; - //FOV - EditorGUI.Slider(rect, m_FOV, 4f, 179f, Styles.cameraFOV); - rect.y += Styles.defaultLineSpace; - //Offset vector - var offset = m_CameraOffset.vector4Value; - EditorGUI.BeginChangeCheck(); - var newOffset = EditorGUI.Vector3Field(rect, Styles.positionOffset, new Vector3(offset.x, offset.y, offset.z)); - if(EditorGUI.EndChangeCheck()) - m_CameraOffset.vector4Value = new Vector4(newOffset.x, newOffset.y, newOffset.z, 1f); - rect.y += Styles.defaultLineSpace; - //Restore prev camera projections - EditorGUI.PropertyField(rect, m_RestoreCamera, Styles.restoreCamera); - rect.y += Styles.defaultLineSpace; - - EditorGUI.indentLevel--; - } - } - - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) - { - float height = Styles.defaultLineSpace; - - Init(property); + } + + void DoMaterialOverride(ref Rect rect) + { + //Override material + EditorGUI.PropertyField(rect, m_OverrideMaterial, Styles.overrideMaterial); + if (m_OverrideMaterial.objectReferenceValue) + { + rect.y += Styles.defaultLineSpace; + EditorGUI.indentLevel++; + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(rect, m_OverrideMaterialPass, Styles.overrideMaterialPass); + if (EditorGUI.EndChangeCheck()) + m_OverrideMaterialPass.intValue = Mathf.Max(0, m_OverrideMaterialPass.intValue); + EditorGUI.indentLevel--; + } + } + + void DoDepthOverride(ref Rect rect) + { + EditorGUI.PropertyField(rect, m_OverrideDepth, Styles.overrideDepth); + if (m_OverrideDepth.boolValue) + { + rect.y += Styles.defaultLineSpace; + EditorGUI.indentLevel++; + //Write depth + EditorGUI.PropertyField(rect, m_WriteDepth, Styles.writeDepth); + rect.y += Styles.defaultLineSpace; + //Depth testing options + EditorGUI.PropertyField(rect, m_DepthState, Styles.depthState); + EditorGUI.indentLevel--; + } + } + + void DoCameraOverride(ref Rect rect) + { + EditorGUI.PropertyField(rect, m_OverrideCamera, Styles.overrideCamera); + if (m_OverrideCamera.boolValue) + { + rect.y += Styles.defaultLineSpace; + EditorGUI.indentLevel++; + //FOV + EditorGUI.Slider(rect, m_FOV, 4f, 179f, Styles.cameraFOV); + rect.y += Styles.defaultLineSpace; + //Offset vector + var offset = m_CameraOffset.vector4Value; + EditorGUI.BeginChangeCheck(); + var newOffset = EditorGUI.Vector3Field(rect, Styles.positionOffset, new Vector3(offset.x, offset.y, offset.z)); + if (EditorGUI.EndChangeCheck()) + m_CameraOffset.vector4Value = new Vector4(newOffset.x, newOffset.y, newOffset.z, 1f); + rect.y += Styles.defaultLineSpace; + //Restore prev camera projections + EditorGUI.PropertyField(rect, m_RestoreCamera, Styles.restoreCamera); + rect.y += Styles.defaultLineSpace; + + EditorGUI.indentLevel--; + } + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + float height = Styles.defaultLineSpace; + + Init(property); height += Styles.defaultLineSpace * (m_FiltersFoldout.value ? m_FilterLines : 1); height += m_FiltersFoldout.value ? EditorGUI.GetPropertyHeight(m_ShaderPasses) : 0; @@ -279,27 +279,27 @@ public override float GetPropertyHeight(SerializedProperty property, GUIContent } return height; - } - - private void SaveHeaderBool(HeaderBool boolObj) - { - EditorPrefs.SetBool(boolObj.key, boolObj.value); - } - - class HeaderBool - { - public string key; - public bool value; - - public HeaderBool(string _key, bool _default = false) - { - key = _key; - if (EditorPrefs.HasKey(key)) - value = EditorPrefs.GetBool(key); - else - value = _default; - EditorPrefs.SetBool(key, value); - } - } + } + + private void SaveHeaderBool(HeaderBool boolObj) + { + EditorPrefs.SetBool(boolObj.key, boolObj.value); + } + + class HeaderBool + { + public string key; + public bool value; + + public HeaderBool(string _key, bool _default = false) + { + key = _key; + if (EditorPrefs.HasKey(key)) + value = EditorPrefs.GetBool(key); + else + value = _default; + EditorPrefs.SetBool(key, value); + } + } } } diff --git a/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceAmbientOcclusionEditor.cs b/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceAmbientOcclusionEditor.cs index b7e0cab89a3..3ccd9213113 100644 --- a/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceAmbientOcclusionEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceAmbientOcclusionEditor.cs @@ -15,7 +15,7 @@ internal class ScreenSpaceAmbientOcclusionEditor : Editor private SerializedProperty m_Radius; private SerializedProperty m_SampleCount; - #endregion + #endregion private bool m_IsInitialized = false; @@ -55,15 +55,15 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(m_Source, Styles.Source); // We only enable this field when depth source is selected - GUI.enabled = m_Source.enumValueIndex == (int) ScreenSpaceAmbientOcclusionSettings.DepthSource.Depth; + GUI.enabled = m_Source.enumValueIndex == (int)ScreenSpaceAmbientOcclusionSettings.DepthSource.Depth; EditorGUILayout.PropertyField(m_NormalQuality, Styles.NormalQuality); GUI.enabled = true; - m_Intensity.floatValue = EditorGUILayout.Slider(Styles.Intensity,m_Intensity.floatValue, 0f, 10f); - m_DirectLightingStrength.floatValue = EditorGUILayout.Slider(Styles.DirectLightingStrength,m_DirectLightingStrength.floatValue, 0f, 1f); + m_Intensity.floatValue = EditorGUILayout.Slider(Styles.Intensity, m_Intensity.floatValue, 0f, 10f); + m_DirectLightingStrength.floatValue = EditorGUILayout.Slider(Styles.DirectLightingStrength, m_DirectLightingStrength.floatValue, 0f, 1f); EditorGUILayout.PropertyField(m_Radius, Styles.Radius); m_Radius.floatValue = Mathf.Clamp(m_Radius.floatValue, 0f, m_Radius.floatValue); - m_SampleCount.intValue = EditorGUILayout.IntSlider(Styles.SampleCount,m_SampleCount.intValue, 4, 20); + m_SampleCount.intValue = EditorGUILayout.IntSlider(Styles.SampleCount, m_SampleCount.intValue, 4, 20); } } } diff --git a/com.unity.render-pipelines.universal/Editor/SavedParameter.cs b/com.unity.render-pipelines.universal/Editor/SavedParameter.cs index cebcb996ace..e087abd33b2 100644 --- a/com.unity.render-pipelines.universal/Editor/SavedParameter.cs +++ b/com.unity.render-pipelines.universal/Editor/SavedParameter.cs @@ -61,24 +61,24 @@ public T value sealed class SavedBool : SavedParameter { public SavedBool(string key, bool value) - : base(key, value, EditorPrefs.GetBool, EditorPrefs.SetBool) { } + : base(key, value, EditorPrefs.GetBool, EditorPrefs.SetBool) {} } sealed class SavedInt : SavedParameter { public SavedInt(string key, int value) - : base(key, value, EditorPrefs.GetInt, EditorPrefs.SetInt) { } + : base(key, value, EditorPrefs.GetInt, EditorPrefs.SetInt) {} } sealed class SavedFloat : SavedParameter { public SavedFloat(string key, float value) - : base(key, value, EditorPrefs.GetFloat, EditorPrefs.SetFloat) { } + : base(key, value, EditorPrefs.GetFloat, EditorPrefs.SetFloat) {} } sealed class SavedString : SavedParameter { public SavedString(string key, string value) - : base(key, value, EditorPrefs.GetString, EditorPrefs.SetString) { } + : base(key, value, EditorPrefs.GetString, EditorPrefs.SetString) {} } } diff --git a/com.unity.render-pipelines.universal/Editor/ScriptableRendererDataEditor.cs b/com.unity.render-pipelines.universal/Editor/ScriptableRendererDataEditor.cs index 8e153df81ac..9c017b77845 100644 --- a/com.unity.render-pipelines.universal/Editor/ScriptableRendererDataEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/ScriptableRendererDataEditor.cs @@ -142,7 +142,7 @@ private void DrawRendererFeature(int index, ref SerializedProperty renderFeature } else { - CoreEditorUtils.DrawHeaderToggle(Styles.MissingFeature,renderFeatureProperty, m_FalseBool,pos => OnContextClick(pos, index)); + CoreEditorUtils.DrawHeaderToggle(Styles.MissingFeature, renderFeatureProperty, m_FalseBool, pos => OnContextClick(pos, index)); m_FalseBool.boolValue = false; // always make sure false bool is false EditorGUILayout.HelpBox(Styles.MissingFeature.tooltip, MessageType.Error); if (GUILayout.Button("Attempt Fix", EditorStyles.miniButton)) diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs index fd45bc7ac1d..3ad8ec2f864 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/BaseShaderGUI.cs @@ -196,7 +196,8 @@ public void ShaderPropertiesGUI(Material material) EditorGUI.BeginChangeCheck(); m_SurfaceOptionsFoldout.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_SurfaceOptionsFoldout.value, Styles.SurfaceOptions); - if(m_SurfaceOptionsFoldout.value){ + if (m_SurfaceOptionsFoldout.value) + { DrawSurfaceOptions(material); EditorGUILayout.Space(); } @@ -298,7 +299,7 @@ protected void DrawQueueOffsetField() } } - public virtual void DrawAdditionalFoldouts(Material material){} + public virtual void DrawAdditionalFoldouts(Material material) {} public virtual void DrawBaseProperties(Material material) { @@ -398,7 +399,7 @@ public static void SetMaterialKeywords(Material material, Action shadi SetupMaterialBlendMode(material); // Receive Shadows - if(material.HasProperty("_ReceiveShadows")) + if (material.HasProperty("_ReceiveShadows")) CoreUtils.SetKeyword(material, "_RECEIVE_SHADOWS_OFF", material.GetFloat("_ReceiveShadows") == 0.0f); // Emission @@ -425,7 +426,7 @@ public static void SetupMaterialBlendMode(Material material) throw new ArgumentNullException("material"); bool alphaClip = false; - if(material.HasProperty("_AlphaClip")) + if (material.HasProperty("_AlphaClip")) alphaClip = material.GetFloat("_AlphaClip") >= 0.5; if (alphaClip) @@ -439,52 +440,52 @@ public static void SetupMaterialBlendMode(Material material) if (material.HasProperty("_Surface")) { - SurfaceType surfaceType = (SurfaceType) material.GetFloat("_Surface"); + SurfaceType surfaceType = (SurfaceType)material.GetFloat("_Surface"); if (surfaceType == SurfaceType.Opaque) { if (alphaClip) { - material.renderQueue = (int) RenderQueue.AlphaTest; + material.renderQueue = (int)RenderQueue.AlphaTest; material.SetOverrideTag("RenderType", "TransparentCutout"); } else { - material.renderQueue = (int) RenderQueue.Geometry; + material.renderQueue = (int)RenderQueue.Geometry; material.SetOverrideTag("RenderType", "Opaque"); } - material.renderQueue += material.HasProperty("_QueueOffset") ? (int) material.GetFloat("_QueueOffset") : 0; - material.SetFloat("_SrcBlend", (float) UnityEngine.Rendering.BlendMode.One); - material.SetFloat("_DstBlend", (float) UnityEngine.Rendering.BlendMode.Zero); + material.renderQueue += material.HasProperty("_QueueOffset") ? (int)material.GetFloat("_QueueOffset") : 0; + material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); + material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.Zero); material.SetFloat("_ZWrite", 1.0f); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.SetShaderPassEnabled("ShadowCaster", true); } else { - BlendMode blendMode = (BlendMode) material.GetFloat("_Blend"); + BlendMode blendMode = (BlendMode)material.GetFloat("_Blend"); // Specific Transparent Mode Settings switch (blendMode) { case BlendMode.Alpha: - material.SetFloat("_SrcBlend", (float) UnityEngine.Rendering.BlendMode.SrcAlpha); - material.SetFloat("_DstBlend", (float) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha); + material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); break; case BlendMode.Premultiply: - material.SetFloat("_SrcBlend", (float) UnityEngine.Rendering.BlendMode.One); - material.SetFloat("_DstBlend", (float) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); + material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); break; case BlendMode.Additive: - material.SetFloat("_SrcBlend", (float) UnityEngine.Rendering.BlendMode.SrcAlpha); - material.SetFloat("_DstBlend", (float) UnityEngine.Rendering.BlendMode.One); + material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha); + material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.One); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); break; case BlendMode.Multiply: - material.SetFloat("_SrcBlend", (float) UnityEngine.Rendering.BlendMode.DstColor); - material.SetFloat("_DstBlend", (float) UnityEngine.Rendering.BlendMode.Zero); + material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.DstColor); + material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.Zero); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.EnableKeyword("_ALPHAMODULATE_ON"); break; @@ -494,7 +495,7 @@ public static void SetupMaterialBlendMode(Material material) material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_ZWrite", 0.0f); material.renderQueue = (int)RenderQueue.Transparent; - material.renderQueue += material.HasProperty("_QueueOffset") ? (int) material.GetFloat("_QueueOffset") : 0; + material.renderQueue += material.HasProperty("_QueueOffset") ? (int)material.GetFloat("_QueueOffset") : 0; material.SetShaderPassEnabled("ShadowCaster", false); } } @@ -609,7 +610,7 @@ public static Rect TextureColorProps(MaterialEditor materialEditor, GUIContent l return properties[index]; } if (propertyIsMandatory) - throw new ArgumentException("Could not find MaterialProperty: '" + propertyName + "', Num properties: " + (object) properties.Length); + throw new ArgumentException("Could not find MaterialProperty: '" + propertyName + "', Num properties: " + (object)properties.Length); return null; } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ParticleGUI.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ParticleGUI.cs index 9d73964e6ad..61d380ca5be 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ParticleGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ParticleGUI.cs @@ -118,7 +118,7 @@ public ParticleProperties(MaterialProperty[] properties) public static void SetupMaterialWithColorMode(Material material) { - var colorMode = (ColorMode) material.GetFloat("_ColorMode"); + var colorMode = (ColorMode)material.GetFloat("_ColorMode"); switch (colorMode) { @@ -162,7 +162,7 @@ public static void FadingOptions(Material material, MaterialEditor materialEdito { // Z write doesn't work with fading bool hasZWrite = (material.GetFloat("_ZWrite") > 0.0f); - if(!hasZWrite) + if (!hasZWrite) { // Soft Particles { @@ -246,7 +246,7 @@ public static void FadingOptions(Material material, MaterialEditor materialEdito EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = properties.distortionStrength.hasMixedValue; var blend = EditorGUILayout.Slider(Styles.distortionBlend, properties.distortionBlend.floatValue, 0f, 1f); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) properties.distortionBlend.floatValue = blend; EditorGUI.indentLevel--; } @@ -262,7 +262,7 @@ public static void DoVertexStreamsArea(Material material, List 0.0f); - if(material.HasProperty("_BumpMap")) + if (material.HasProperty("_BumpMap")) useNormalMap = material.GetTexture("_BumpMap"); bool useGPUInstancing = ShaderUtil.HasProceduralInstancing(material.shader); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs index 7c1b7dfae3b..0cf3567e514 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/LitShader.cs @@ -83,7 +83,7 @@ public override void DrawAdvancedOptions(Material material) EditorGUI.BeginChangeCheck(); materialEditor.ShaderProperty(litProperties.highlights, LitGUI.Styles.highlightsText); materialEditor.ShaderProperty(litProperties.reflections, LitGUI.Styles.reflectionsText); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) { MaterialChanged(material); } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/BakedLitGUI.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/BakedLitGUI.cs index 103535c0533..8c7807748e2 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/BakedLitGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/BakedLitGUI.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Scripting.APIUpdating; diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/LitGUI.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/LitGUI.cs index a05e5a1c4b3..eda388c2188 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/LitGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/LitGUI.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Scripting.APIUpdating; @@ -145,16 +145,16 @@ public static void Inputs(LitProperties properties, MaterialEditor materialEdito private static bool ClearCoatAvailable(Material material) { - return material.HasProperty("_ClearCoat") - && material.HasProperty("_ClearCoatMap") - && material.HasProperty("_ClearCoatMask") - && material.HasProperty("_ClearCoatSmoothness"); + return material.HasProperty("_ClearCoat") + && material.HasProperty("_ClearCoatMap") + && material.HasProperty("_ClearCoatMask") + && material.HasProperty("_ClearCoatSmoothness"); } private static bool HeightmapAvailable(Material material) { - return material.HasProperty("_Parallax") - && material.HasProperty("_ParallaxMap"); + return material.HasProperty("_Parallax") + && material.HasProperty("_ParallaxMap"); } private static void DoHeightmapArea(LitProperties properties, MaterialEditor materialEditor) @@ -172,10 +172,10 @@ public static void DoClearCoat(LitProperties properties, MaterialEditor material { var coatEnabled = ClearCoatEnabled(material); EditorGUI.BeginChangeCheck(); - EditorGUI.Toggle(EditorGUILayout.GetControlRect(), Styles.clearCoatText, coatEnabled ); - if(EditorGUI.EndChangeCheck()) + EditorGUI.Toggle(EditorGUILayout.GetControlRect(), Styles.clearCoatText, coatEnabled); + if (EditorGUI.EndChangeCheck()) { - if(coatEnabled) + if (coatEnabled) material.SetFloat("_ClearCoat", 0); // Toggle off else material.SetFloat("_ClearCoat", 1); @@ -189,8 +189,8 @@ public static void DoClearCoat(LitProperties properties, MaterialEditor material EditorGUI.indentLevel += 2; - // Texture and HDR color controls - materialEditor.ShaderProperty(properties.clearCoatSmoothness , Styles.clearCoatSmoothnessText); + // Texture and HDR color controls + materialEditor.ShaderProperty(properties.clearCoatSmoothness , Styles.clearCoatSmoothnessText); EditorGUI.indentLevel -= 2; } @@ -202,7 +202,7 @@ public static void DoMetallicSpecularArea(LitProperties properties, MaterialEdit string[] smoothnessChannelNames; bool hasGlossMap = false; if (properties.workflowMode == null || - (WorkflowMode) properties.workflowMode.floatValue == WorkflowMode.Metallic) + (WorkflowMode)properties.workflowMode.floatValue == WorkflowMode.Metallic) { hasGlossMap = properties.metallicGlossMap.textureValue != null; smoothnessChannelNames = Styles.metallicSmoothnessChannelNames; @@ -223,8 +223,8 @@ public static void DoMetallicSpecularArea(LitProperties properties, MaterialEdit public static void DoSmoothness(LitProperties properties, Material material, string[] smoothnessChannelNames) { - var opaque = ((BaseShaderGUI.SurfaceType) material.GetFloat("_Surface") == - BaseShaderGUI.SurfaceType.Opaque); + var opaque = ((BaseShaderGUI.SurfaceType)material.GetFloat("_Surface") == + BaseShaderGUI.SurfaceType.Opaque); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = properties.smoothness.hasMixedValue; @@ -239,7 +239,7 @@ public static void DoSmoothness(LitProperties properties, Material material, str EditorGUI.BeginDisabledGroup(!opaque); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = properties.smoothnessMapChannel.hasMixedValue; - var smoothnessSource = (int) properties.smoothnessMapChannel.floatValue; + var smoothnessSource = (int)properties.smoothnessMapChannel.floatValue; if (opaque) smoothnessSource = EditorGUILayout.Popup(Styles.smoothnessMapChannelText, smoothnessSource, smoothnessChannelNames); @@ -256,8 +256,8 @@ public static void DoSmoothness(LitProperties properties, Material material, str public static SmoothnessMapChannel GetSmoothnessMapChannel(Material material) { - int ch = (int) material.GetFloat("_SmoothnessTextureChannel"); - if (ch == (int) SmoothnessMapChannel.AlbedoAlpha) + int ch = (int)material.GetFloat("_SmoothnessTextureChannel"); + if (ch == (int)SmoothnessMapChannel.AlbedoAlpha) return SmoothnessMapChannel.AlbedoAlpha; return SmoothnessMapChannel.SpecularMetallicAlpha; @@ -269,11 +269,11 @@ public static void SetMaterialKeywords(Material material) // (MaterialProperty value might come from renderer material property block) var hasGlossMap = false; var isSpecularWorkFlow = false; - var opaque = ((BaseShaderGUI.SurfaceType) material.GetFloat("_Surface") == - BaseShaderGUI.SurfaceType.Opaque); + var opaque = ((BaseShaderGUI.SurfaceType)material.GetFloat("_Surface") == + BaseShaderGUI.SurfaceType.Opaque); if (material.HasProperty("_WorkflowMode")) { - isSpecularWorkFlow = (WorkflowMode) material.GetFloat("_WorkflowMode") == WorkflowMode.Specular; + isSpecularWorkFlow = (WorkflowMode)material.GetFloat("_WorkflowMode") == WorkflowMode.Specular; if (isSpecularWorkFlow) hasGlossMap = material.GetTexture("_SpecGlossMap") != null; else @@ -326,7 +326,6 @@ public static void SetMaterialKeywords(Material material) CoreUtils.SetKeyword(material, "_CLEARCOAT", false); CoreUtils.SetKeyword(material, "_CLEARCOATMAP", false); } - } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/SimpleLitGUI.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/SimpleLitGUI.cs index a7a708a83c7..89f9e193f74 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/SimpleLitGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShadingModels/SimpleLitGUI.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Scripting.APIUpdating; @@ -78,15 +78,15 @@ public static void DoSpecularArea(SimpleLitProperties properties, MaterialEditor { SpecularSource specSource = (SpecularSource)properties.specHighlights.floatValue; EditorGUI.BeginDisabledGroup(specSource == SpecularSource.NoSpecular); - BaseShaderGUI.TextureColorProps(materialEditor, Styles.specularMapText, properties.specGlossMap,properties.specColor, true); + BaseShaderGUI.TextureColorProps(materialEditor, Styles.specularMapText, properties.specGlossMap, properties.specColor, true); DoSmoothness(properties, material); EditorGUI.EndDisabledGroup(); } public static void DoSmoothness(SimpleLitProperties properties, Material material) { - var opaque = ((BaseShaderGUI.SurfaceType) material.GetFloat("_Surface") == - BaseShaderGUI.SurfaceType.Opaque); + var opaque = ((BaseShaderGUI.SurfaceType)material.GetFloat("_Surface") == + BaseShaderGUI.SurfaceType.Opaque); EditorGUI.indentLevel += 2; EditorGUI.BeginChangeCheck(); @@ -104,7 +104,7 @@ public static void DoSmoothness(SimpleLitProperties properties, Material materia EditorGUI.BeginDisabledGroup(!opaque); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = properties.smoothnessMapChannel.hasMixedValue; - if(opaque) + if (opaque) smoothnessSource = EditorGUILayout.Popup(Styles.smoothnessMapChannelText, smoothnessSource, Enum.GetNames(typeof(SmoothnessMapChannel))); else EditorGUILayout.Popup(Styles.smoothnessMapChannelText, 0, Enum.GetNames(typeof(SmoothnessMapChannel))); @@ -122,8 +122,8 @@ public static void SetMaterialKeywords(Material material) private static void UpdateMaterialSpecularSource(Material material) { - var opaque = ((BaseShaderGUI.SurfaceType) material.GetFloat("_Surface") == - BaseShaderGUI.SurfaceType.Opaque); + var opaque = ((BaseShaderGUI.SurfaceType)material.GetFloat("_Surface") == + BaseShaderGUI.SurfaceType.Opaque); SpecularSource specSource = (SpecularSource)material.GetFloat("_SpecularHighlights"); if (specSource == SpecularSource.NoSpecular) { @@ -137,7 +137,7 @@ private static void UpdateMaterialSpecularSource(Material material) bool hasMap = material.GetTexture("_SpecGlossMap"); CoreUtils.SetKeyword(material, "_SPECGLOSSMAP", hasMap); CoreUtils.SetKeyword(material, "_SPECULAR_COLOR", !hasMap); - if(opaque) + if (opaque) CoreUtils.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", smoothnessSource == SmoothnessMapChannel.AlbedoAlpha); else CoreUtils.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", false); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs b/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs index 1b3ac08ecba..9173e4c03df 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs @@ -72,6 +72,7 @@ private static bool DoesTerrainUseMaskMaps(TerrainLayer[] terrainLayers) } return false; } + protected void FindMaterialProperties(MaterialProperty[] props) { enableHeightBlend = FindProperty(kEnableHeightBlend, props, false); @@ -129,7 +130,7 @@ public override void OnGUI(MaterialEditor materialEditorIn, MaterialProperty[] p } bool enablePerPixelNormalChanged = false; - + // Since Instanced Per-pixel normal is actually dependent on instancing enabled or not, it is not // important to check it in the GUI. The shader will make sure it is enabled/disabled properly.s if (enableInstancedPerPixelNormal != null) @@ -245,7 +246,7 @@ bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain min = maskMapRemapMin.y; max = maskMapRemapMax.y; EditorGUILayout.MinMaxSlider(s_Styles.ao, ref min, ref max, 0, 1); maskMapRemapMin.y = min; maskMapRemapMax.y = max; - + if (heightBlend) { EditorGUILayout.LabelField(styles.height); @@ -268,7 +269,7 @@ bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain } --EditorGUI.indentLevel; } - + min = maskMapRemapMin.w; max = maskMapRemapMax.w; EditorGUILayout.MinMaxSlider(s_Styles.smoothness, ref min, ref max, 0, 1); maskMapRemapMin.w = min; maskMapRemapMax.w = max; @@ -289,7 +290,7 @@ bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain // In the case of height (Z), we are trying to set min to no lower than zero value unless // max goes negative. Zero is a good sensible value for the minimum. For AO (Y), we // don't need this extra protection step because the UI blocks us from going negative - // anyway. In both cases, pushing the slider below the min value will lock them together, + // anyway. In both cases, pushing the slider below the min value will lock them together, // but min will be "left behind" if you go back up. maskMapRemapMin.y = Mathf.Min(maskMapRemapMin.y, maskMapRemapMax.y); maskMapRemapMin.z = Mathf.Min(Mathf.Max(0, maskMapRemapMin.z), maskMapRemapMax.z); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs index 9959dd93d9d..1b76bb4d2de 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateLitShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.Universal.ShaderGraph @@ -11,20 +11,20 @@ public static void CreateLitGraph() var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); target.TrySetActiveSubTarget(typeof(UniversalLitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, BlockFields.SurfaceDescription.BaseColor, - BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalTS, BlockFields.SurfaceDescription.Metallic, - BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Smoothness, BlockFields.SurfaceDescription.Emission, BlockFields.SurfaceDescription.Occlusion, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs index 85bc87c6737..61383f08633 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteLitShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.Universal.ShaderGraph @@ -11,18 +11,18 @@ public static void CreateSpriteLitGraph() var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); target.TrySetActiveSubTarget(typeof(UniversalSpriteLitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, BlockFields.SurfaceDescription.BaseColor, - UniversalBlockFields.SurfaceDescription.SpriteMask, + UniversalBlockFields.SurfaceDescription.SpriteMask, BlockFields.SurfaceDescription.NormalTS, BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs index 0b3ffb356fe..bcbae228c35 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateSpriteUnlitShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.Universal.ShaderGraph @@ -11,8 +11,8 @@ public static void CreateSpriteUnlitGraph() var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); target.TrySetActiveSubTarget(typeof(UniversalSpriteUnlitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, @@ -20,7 +20,7 @@ public static void CreateSpriteUnlitGraph() BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs index 2addc87e505..8d93aa9245f 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUnlitShaderGraph.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.Universal.ShaderGraph @@ -11,15 +11,15 @@ public static void CreateUnlitGraph() var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget)); target.TrySetActiveSubTarget(typeof(UniversalUnlitSubTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.VertexDescription.Position, BlockFields.VertexDescription.Normal, BlockFields.VertexDescription.Tangent, BlockFields.SurfaceDescription.BaseColor, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthNormalsOnlyPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthNormalsOnlyPass.hlsl index 9c979177551..8bd47488f54 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthNormalsOnlyPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthNormalsOnlyPass.hlsl @@ -22,7 +22,7 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET #if _AlphaClip clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold); #endif - + return float4(PackNormalOctRectEncode(TransformWorldToViewDir(unpacked.normalWS, true)), 0.0, 0.0); } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthOnlyPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthOnlyPass.hlsl index 1a6c61d212b..6c64ce7f090 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthOnlyPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthOnlyPass.hlsl @@ -10,8 +10,8 @@ PackedVaryings vert(Attributes input) return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl index d5a92431cb8..207a57f9c65 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl @@ -10,8 +10,8 @@ PackedVaryings vert(Attributes input) return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl index 260eb626d7f..3bdeb1a8e97 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl @@ -1,4 +1,4 @@ -PackedVaryings vert(Attributes input) +PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; output = BuildVaryings(input); @@ -7,8 +7,8 @@ return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl index e246e772680..7c1957b98b6 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBRGBufferPass.hlsl @@ -4,14 +4,14 @@ void BuildInputData(Varyings input, SurfaceDescription surfaceDescription, out I #ifdef _NORMALMAP #if _NORMAL_DROPOFF_TS - // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, half3x3(input.tangentWS.xyz, bitangent, input.normalWS.xyz)); #elif _NORMAL_DROPOFF_OS - inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); #elif _NORMAL_DROPOFF_WS - inputData.normalWS = surfaceDescription.NormalWS; + inputData.normalWS = surfaceDescription.NormalWS; #endif #else inputData.normalWS = input.normalWS; diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShadowCasterPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShadowCasterPass.hlsl index a8044650bdd..c94d16a9231 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShadowCasterPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShadowCasterPass.hlsl @@ -10,8 +10,8 @@ PackedVaryings vert(Attributes input) return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl index 2c9f492bb05..260ec7d1dd9 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteForwardPass.hlsl @@ -1,4 +1,4 @@ -PackedVaryings vert(Attributes input) +PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; output = BuildVaryings(input); @@ -6,8 +6,8 @@ return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl index 5b1e17281f0..ce92dbfa49f 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteLitPass.hlsl @@ -24,8 +24,8 @@ PackedVaryings vert(Attributes input) return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl index 46f73bf1206..8cd6accc5e0 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteNormalPass.hlsl @@ -6,8 +6,8 @@ PackedVaryings vert(Attributes input) return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl index 867de09758e..4a446540599 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SpriteUnlitPass.hlsl @@ -8,8 +8,8 @@ PackedVaryings vert(Attributes input) return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl index 701d77b29e5..e5343f3fd52 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl @@ -1,4 +1,4 @@ -PackedVaryings vert(Attributes input) +PackedVaryings vert(Attributes input) { Varyings output = (Varyings)0; output = BuildVaryings(input); @@ -6,8 +6,8 @@ return packedOutput; } -half4 frag(PackedVaryings packedInput) : SV_TARGET -{ +half4 frag(PackedVaryings packedInput) : SV_TARGET +{ Varyings unpacked = UnpackVaryings(packedInput); UNITY_SETUP_INSTANCE_ID(unpacked); UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl index 077086a63d5..8a6b8fa945f 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl @@ -14,7 +14,7 @@ Varyings BuildVaryings(Attributes input) // Evaluate Vertex Graph VertexDescriptionInputs vertexDescriptionInputs = BuildVertexDescriptionInputs(input); VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs); - + // Assign modified vertex attributes input.positionOS = vertexDescription.Position; #if defined(VARYINGS_NEED_NORMAL_WS) @@ -53,11 +53,11 @@ Varyings BuildVaryings(Attributes input) #endif #ifdef VARYINGS_NEED_NORMAL_WS - output.normalWS = normalWS; // normalized in TransformObjectToWorldNormal() + output.normalWS = normalWS; // normalized in TransformObjectToWorldNormal() #endif #ifdef VARYINGS_NEED_TANGENT_WS - output.tangentWS = tangentWS; // normalized in TransformObjectToWorldDir() + output.tangentWS = tangentWS; // normalized in TransformObjectToWorldDir() #endif #if (SHADERPASS == SHADERPASS_SHADOWCASTER) @@ -116,4 +116,3 @@ Varyings BuildVaryings(Attributes input) return output; } - diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs index fcfc4ca4077..33a2f9909ac 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs @@ -75,7 +75,7 @@ public override void Setup(ref TargetSetupContext context) SubShaderDescriptor[] subShaders = complexLit ? complexLitSubShaders : litSubShaders; - for(int i = 0; i < subShaders.Length; i++) + for (int i = 0; i < subShaders.Length; i++) { // Update Render State subShaders[i].renderType = target.renderType; @@ -103,8 +103,8 @@ public override void GetFields(ref TargetFieldContext context) context.AddField(UniversalFields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World); context.AddField(UniversalFields.SpecularSetup, workflowMode == WorkflowMode.Specular); context.AddField(UniversalFields.Normal, descs.Contains(BlockFields.SurfaceDescription.NormalOS) || - descs.Contains(BlockFields.SurfaceDescription.NormalTS) || - descs.Contains(BlockFields.SurfaceDescription.NormalWS)); + descs.Contains(BlockFields.SurfaceDescription.NormalTS) || + descs.Contains(BlockFields.SurfaceDescription.NormalWS)); // Complex Lit // Template Predicates @@ -123,8 +123,8 @@ public override void GetActiveBlocks(ref TargetActiveBlockContext context) context.AddBlock(BlockFields.SurfaceDescription.Metallic, workflowMode == WorkflowMode.Metallic); context.AddBlock(BlockFields.SurfaceDescription.Alpha, target.surfaceType == SurfaceType.Transparent || target.alphaClip); context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, target.alphaClip); - context.AddBlock(UniversalBlockFields.SurfaceDescription.CoatMask, clearCoat ); - context.AddBlock(UniversalBlockFields.SurfaceDescription.CoatSmoothness, clearCoat ); + context.AddBlock(UniversalBlockFields.SurfaceDescription.CoatMask, clearCoat); + context.AddBlock(UniversalBlockFields.SurfaceDescription.CoatSmoothness, clearCoat); } public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) @@ -203,7 +203,7 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is PBRMasterNode1 pbrMasterNode)) + if (!(masterNode is PBRMasterNode1 pbrMasterNode)) return false; m_WorkflowMode = (WorkflowMode)pbrMasterNode.m_Model; @@ -211,7 +211,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is SpriteLitMasterNode1 spriteLitMasterNode)) + if (!(masterNode is SpriteLitMasterNode1 spriteLitMasterNode)) return false; // Set blockmap @@ -73,7 +73,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is SpriteUnlitMasterNode1 spriteUnlitMasterNode)) + if (!(masterNode is SpriteUnlitMasterNode1 spriteUnlitMasterNode)) return false; // Set blockmap @@ -69,7 +69,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary x.descriptor); // Core fields context.AddField(Fields.GraphVertex, descs.Contains(BlockFields.VertexDescription.Position) || - descs.Contains(BlockFields.VertexDescription.Normal) || - descs.Contains(BlockFields.VertexDescription.Tangent)); + descs.Contains(BlockFields.VertexDescription.Normal) || + descs.Contains(BlockFields.VertexDescription.Tangent)); context.AddField(Fields.GraphPixel); context.AddField(Fields.AlphaClip, alphaClip); context.AddField(Fields.DoubleSided, twoSided); @@ -250,12 +250,12 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti public bool TrySetActiveSubTarget(Type subTargetType) { - if(!subTargetType.IsSubclassOf(typeof(SubTarget))) + if (!subTargetType.IsSubclassOf(typeof(SubTarget))) return false; - foreach(var subTarget in m_SubTargets) + foreach (var subTarget in m_SubTargets) { - if(subTarget.GetType().Equals(subTargetType)) + if (subTarget.GetType().Equals(subTargetType)) { m_ActiveSubTarget = subTarget; return true; @@ -272,18 +272,18 @@ void UpgradeAlphaClip() var clipThresholdId = 8; var node = masterNode as AbstractMaterialNode; var clipThresholdSlot = node.FindSlot(clipThresholdId); - if(clipThresholdSlot == null) + if (clipThresholdSlot == null) return; clipThresholdSlot.owner = node; - if(clipThresholdSlot.isConnected || clipThresholdSlot.value > 0.0f) + if (clipThresholdSlot.isConnected || clipThresholdSlot.value > 0.0f) { m_AlphaClip = true; } } // Upgrade Target - switch(masterNode) + switch (masterNode) { case PBRMasterNode1 pbrMasterNode: m_SurfaceType = (SurfaceType)pbrMasterNode.m_SurfaceType; @@ -308,12 +308,12 @@ void UpgradeAlphaClip() } // Upgrade SubTarget - foreach(var subTarget in m_SubTargets) + foreach (var subTarget in m_SubTargets) { - if(!(subTarget is ILegacyTarget legacySubTarget)) + if (!(subTarget is ILegacyTarget legacySubTarget)) continue; - if(legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) + if (legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) { m_ActiveSubTarget = subTarget; return true; @@ -330,7 +330,7 @@ public override bool WorksWithSRP(RenderPipelineAsset scriptableRenderPipeline) } } -#region Passes + #region Passes static class CorePasses { public static readonly PassDescriptor DepthOnly = new PassDescriptor() @@ -385,9 +385,9 @@ static class CorePasses includes = CoreIncludes.ShadowCaster, }; } -#endregion + #endregion -#region PortMasks + #region PortMasks class CoreBlockMasks { public static readonly BlockFieldDescriptor[] Vertex = new BlockFieldDescriptor[] @@ -410,9 +410,9 @@ class CoreBlockMasks BlockFields.SurfaceDescription.AlphaClipThreshold, }; } -#endregion + #endregion -#region StructCollections + #region StructCollections static class CoreStructCollections { public static readonly StructCollection Default = new StructCollection @@ -423,9 +423,9 @@ static class CoreStructCollections { Structs.VertexDescriptionInputs }, }; } -#endregion + #endregion -#region RequiredFields + #region RequiredFields static class CoreRequiredFields { public static readonly FieldCollection ShadowCaster = new FieldCollection() @@ -433,21 +433,21 @@ static class CoreRequiredFields StructFields.Attributes.normalOS, }; } -#endregion + #endregion -#region FieldDependencies + #region FieldDependencies static class CoreFieldDependencies { public static readonly DependencyCollection Default = new DependencyCollection() { { FieldDependencies.Default }, - new FieldDependency(UniversalStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx, StructFields.Attributes.instanceID ), - new FieldDependency(UniversalStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0, StructFields.Attributes.instanceID ), + new FieldDependency(UniversalStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx, StructFields.Attributes.instanceID), + new FieldDependency(UniversalStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0, StructFields.Attributes.instanceID), }; } -#endregion + #endregion -#region RenderStates + #region RenderStates static class CoreRenderStates { public static readonly RenderStateCollection Default = new RenderStateCollection @@ -510,9 +510,9 @@ static class CoreRenderStates { RenderState.Blend(Blend.DstColor, Blend.Zero), new FieldCondition(UniversalFields.BlendMultiply, true) }, }; } -#endregion + #endregion -#region Pragmas + #region Pragmas // TODO: should these be renamed and moved to UniversalPragmas/UniversalPragmas.cs ? // TODO: these aren't "core" as HDRP doesn't use them // TODO: and the same for the rest "Core" things @@ -521,7 +521,7 @@ static class CorePragmas public static readonly PragmaCollection Default = new PragmaCollection { { Pragma.Target(ShaderModel.Target20) }, - { Pragma.OnlyRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.OnlyRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.Vertex("vert") }, { Pragma.Fragment("frag") }, }; @@ -529,7 +529,7 @@ static class CorePragmas public static readonly PragmaCollection Instanced = new PragmaCollection { { Pragma.Target(ShaderModel.Target20) }, - { Pragma.OnlyRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.OnlyRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.MultiCompileInstancing }, { Pragma.Vertex("vert") }, { Pragma.Fragment("frag") }, @@ -538,7 +538,7 @@ static class CorePragmas public static readonly PragmaCollection Forward = new PragmaCollection { { Pragma.Target(ShaderModel.Target20) }, - { Pragma.OnlyRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.OnlyRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.MultiCompileInstancing }, { Pragma.MultiCompileFog }, { Pragma.Vertex("vert") }, @@ -548,7 +548,7 @@ static class CorePragmas public static readonly PragmaCollection _2DDefault = new PragmaCollection { { Pragma.Target(ShaderModel.Target20) }, - { Pragma.ExcludeRenderers(new[]{ Platform.D3D9 }) }, + { Pragma.ExcludeRenderers(new[] { Platform.D3D9 }) }, { Pragma.Vertex("vert") }, { Pragma.Fragment("frag") }, }; @@ -556,7 +556,7 @@ static class CorePragmas public static readonly PragmaCollection DOTSDefault = new PragmaCollection { { Pragma.Target(ShaderModel.Target45) }, - { Pragma.ExcludeRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.ExcludeRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.Vertex("vert") }, { Pragma.Fragment("frag") }, }; @@ -564,7 +564,7 @@ static class CorePragmas public static readonly PragmaCollection DOTSInstanced = new PragmaCollection { { Pragma.Target(ShaderModel.Target45) }, - { Pragma.ExcludeRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.ExcludeRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.MultiCompileInstancing }, { Pragma.DOTSInstancing }, { Pragma.Vertex("vert") }, @@ -574,7 +574,7 @@ static class CorePragmas public static readonly PragmaCollection DOTSForward = new PragmaCollection { { Pragma.Target(ShaderModel.Target45) }, - { Pragma.ExcludeRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.ExcludeRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.MultiCompileInstancing }, { Pragma.MultiCompileFog }, { Pragma.DOTSInstancing }, @@ -585,7 +585,7 @@ static class CorePragmas public static readonly PragmaCollection DOTSGBuffer = new PragmaCollection { { Pragma.Target(ShaderModel.Target45) }, - { Pragma.ExcludeRenderers(new[]{ Platform.GLES, Platform.GLES3, Platform.GLCore }) }, + { Pragma.ExcludeRenderers(new[] { Platform.GLES, Platform.GLES3, Platform.GLCore }) }, { Pragma.MultiCompileInstancing }, { Pragma.MultiCompileFog }, { Pragma.DOTSInstancing }, @@ -593,9 +593,9 @@ static class CorePragmas { Pragma.Fragment("frag") }, }; } -#endregion + #endregion -#region Includes + #region Includes static class CoreIncludes { const string kColor = "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"; @@ -661,19 +661,19 @@ static class CoreIncludes { kShadowCasterPass, IncludeLocation.Postgraph }, }; } -#endregion + #endregion -#region Defines - static class CoreDefines + #region Defines + static class CoreDefines + { + public static readonly DefineCollection UseLegacySpriteBlocks = new DefineCollection { - public static readonly DefineCollection UseLegacySpriteBlocks = new DefineCollection - { - { CoreKeywordDescriptors.UseLegacySpriteBlocks, 1, new FieldCondition(CoreFields.UseLegacySpriteBlocks, true) }, - }; - } -#endregion + { CoreKeywordDescriptors.UseLegacySpriteBlocks, 1, new FieldCondition(CoreFields.UseLegacySpriteBlocks, true) }, + }; + } + #endregion -#region KeywordDescriptors + #region KeywordDescriptors // TODO: should these be renamed and moved to UniversalKeywordDescriptors/UniversalKeywords.cs ? // TODO: these aren't "core" as they aren't used by HDRP static class CoreKeywordDescriptors @@ -835,12 +835,12 @@ static class CoreKeywordDescriptors type = KeywordType.Boolean, }; } -#endregion + #endregion -#region FieldDescriptors + #region FieldDescriptors static class CoreFields { public static readonly FieldDescriptor UseLegacySpriteBlocks = new FieldDescriptor("Universal", "UseLegacySpriteBlocks", "UNIVERSAL_USELEGACYSPRITEBLOCKS"); } -#endregion + #endregion } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs index 8bfc95910d2..a4b2dad2eb4 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs @@ -27,7 +27,7 @@ public override void Setup(ref TargetSetupContext context) // Process SubShaders SubShaderDescriptor[] subShaders = { SubShaders.Unlit, SubShaders.UnlitDOTS }; - for(int i = 0; i < subShaders.Length; i++) + for (int i = 0; i < subShaders.Length; i++) { // Update Render State subShaders[i].renderType = target.renderType; @@ -102,7 +102,7 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) { blockMap = null; - if(!(masterNode is UnlitMasterNode1 unlitMasterNode)) + if (!(masterNode is UnlitMasterNode1 unlitMasterNode)) return false; // Set blockmap @@ -119,7 +119,7 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary // It is only used to enable/disable in the tempalate -#region Predicates + #region Predicates //public static FieldDescriptor PredicateClearCoat = new FieldDescriptor(string.Empty, "ClearCoat", "_CLEARCOAT 1"); -#endregion + #endregion } } diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructFields.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructFields.cs index 27f54b2e75a..5c7611c6bdb 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructFields.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructFields.cs @@ -1,4 +1,4 @@ -using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.Universal.ShaderGraph { @@ -8,13 +8,13 @@ public struct Varyings { public static string name = "Varyings"; public static FieldDescriptor lightmapUV = new FieldDescriptor(Varyings.name, "lightmapUV", "", ShaderValueType.Float2, - preprocessor : "defined(LIGHTMAP_ON)", subscriptOptions : StructFieldOptions.Optional); + preprocessor: "defined(LIGHTMAP_ON)", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor sh = new FieldDescriptor(Varyings.name, "sh", "", ShaderValueType.Float3, - preprocessor : "!defined(LIGHTMAP_ON)", subscriptOptions : StructFieldOptions.Optional); + preprocessor: "!defined(LIGHTMAP_ON)", subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor fogFactorAndVertexLight = new FieldDescriptor(Varyings.name, "fogFactorAndVertexLight", "VARYINGS_NEED_FOG_AND_VERTEX_LIGHT", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor shadowCoord = new FieldDescriptor(Varyings.name, "shadowCoord", "VARYINGS_NEED_SHADOWCOORD", ShaderValueType.Float4, - subscriptOptions : StructFieldOptions.Optional); + subscriptOptions: StructFieldOptions.Optional); public static FieldDescriptor stereoTargetEyeIndexAsRTArrayIdx = new FieldDescriptor(Varyings.name, "stereoTargetEyeIndexAsRTArrayIdx", "", ShaderValueType.Uint, "SV_RenderTargetArrayIndex", "(defined(UNITY_STEREO_INSTANCING_ENABLED))", StructFieldOptions.Generated); public static FieldDescriptor stereoTargetEyeIndexAsBlendIdx0 = new FieldDescriptor(Varyings.name, "stereoTargetEyeIndexAsBlendIdx0", "", ShaderValueType.Uint, diff --git a/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructs.cs b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructs.cs index 22b33287f14..06a3fb964a1 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructs.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderGraph/UniversalStructs.cs @@ -1,4 +1,4 @@ -using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph; namespace UnityEditor.Rendering.Universal.ShaderGraph { diff --git a/com.unity.render-pipelines.universal/Editor/ShaderPreprocessor.cs b/com.unity.render-pipelines.universal/Editor/ShaderPreprocessor.cs index 38764b34e8e..d4799c85940 100644 --- a/com.unity.render-pipelines.universal/Editor/ShaderPreprocessor.cs +++ b/com.unity.render-pipelines.universal/Editor/ShaderPreprocessor.cs @@ -117,7 +117,7 @@ bool StripUnusedFeatures(ShaderFeatures features, Shader shader, ShaderSnippetDa // Strip here only if mixed lighting is disabled // No need to check here if actually used by scenes as this taken care by builtin stripper if ((compilerData.shaderKeywordSet.IsEnabled(m_LightmapShadowMixing) || - compilerData.shaderKeywordSet.IsEnabled(m_ShadowsShadowMask)) && + compilerData.shaderKeywordSet.IsEnabled(m_ShadowsShadowMask)) && !IsFeatureEnabled(features, ShaderFeatures.MixedLighting)) return true; @@ -250,10 +250,10 @@ void LogShaderVariants(Shader shader, ShaderSnippetData snippetData, ShaderVaria float percentageTotal = (float)m_TotalVariantsOutputCount / (float)m_TotalVariantsInputCount * 100f; string result = string.Format("STRIPPING: {0} ({1} pass) ({2}) -" + - " Remaining shader variants = {3}/{4} = {5}% - Total = {6}/{7} = {8}%", - shader.name, snippetData.passName, snippetData.shaderType.ToString(), currVariantsCount, - prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount, - percentageTotal); + " Remaining shader variants = {3}/{4} = {5}% - Total = {6}/{7} = {8}%", + shader.name, snippetData.passName, snippetData.shaderType.ToString(), currVariantsCount, + prevVariantsCount, percentageCurrent, m_TotalVariantsOutputCount, m_TotalVariantsInputCount, + percentageTotal); Debug.Log(result); } } @@ -276,7 +276,6 @@ public void OnProcessShader(Shader shader, ShaderSnippetData snippetData, IList< var inputShaderVariantCount = compilerDataList.Count; for (int i = 0; i < inputShaderVariantCount;) { - bool removeInput = StripUnused(ShaderBuildPreprocessor.supportedFeatures, shader, snippetData, compilerDataList[i]); if (removeInput) compilerDataList[i] = compilerDataList[--inputShaderVariantCount]; @@ -284,11 +283,11 @@ public void OnProcessShader(Shader shader, ShaderSnippetData snippetData, IList< ++i; } - if(compilerDataList is List inputDataList) + if (compilerDataList is List inputDataList) inputDataList.RemoveRange(inputShaderVariantCount, inputDataList.Count - inputShaderVariantCount); else { - for(int i = compilerDataList.Count -1; i >= inputShaderVariantCount; --i) + for (int i = compilerDataList.Count - 1; i >= inputShaderVariantCount; --i) compilerDataList.RemoveAt(i); } @@ -315,7 +314,8 @@ class ShaderBuildPreprocessor : IPreprocessBuildWithReport { public static ShaderFeatures supportedFeatures { - get { + get + { if (_supportedFeatures <= 0) { FetchAllSupportedFeatures(); @@ -331,6 +331,7 @@ public void OnPostprocessBuild(BuildReport report) { Profiler.enabled = false; } + #endif public void OnPreprocessBuild(BuildReport report) @@ -347,7 +348,7 @@ private static void FetchAllSupportedFeatures() { List urps = new List(); urps.Add(GraphicsSettings.defaultRenderPipeline as UniversalRenderPipelineAsset); - for(int i = 0; i < QualitySettings.names.Length; i++) + for (int i = 0; i < QualitySettings.names.Length; i++) { urps.Add(QualitySettings.GetRenderPipelineAssetAt(i) as UniversalRenderPipelineAsset); } @@ -384,7 +385,7 @@ private static ShaderFeatures GetSupportedShaderFeatures(UniversalRenderPipeline } bool anyShadows = pipelineAsset.supportsMainLightShadows || - (shaderFeatures & ShaderFeatures.AdditionalLightShadows) != 0; + (shaderFeatures & ShaderFeatures.AdditionalLightShadows) != 0; if (pipelineAsset.supportsSoftShadows && anyShadows) shaderFeatures |= ShaderFeatures.SoftShadows; diff --git a/com.unity.render-pipelines.universal/Editor/Shadow/ShadowCascadeSplitGUI.cs b/com.unity.render-pipelines.universal/Editor/Shadow/ShadowCascadeSplitGUI.cs index 82ed757c71d..dc8fe1b5e87 100644 --- a/com.unity.render-pipelines.universal/Editor/Shadow/ShadowCascadeSplitGUI.cs +++ b/com.unity.render-pipelines.universal/Editor/Shadow/ShadowCascadeSplitGUI.cs @@ -67,9 +67,9 @@ public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartition // From this point on, we move to non-layout based code. var sliderRect = GUILayoutUtility.GetRect(GUIContent.none - , s_CascadeSliderBG - , GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin) - , GUILayout.ExpandWidth(true)); + , s_CascadeSliderBG + , GUILayout.Height(kSliderbarTopMargin + kSliderbarHeight + kSliderbarBottomMargin) + , GUILayout.ExpandWidth(true)); GUI.Box(sliderRect, GUIContent.none); EditorGUILayout.EndHorizontal(); @@ -117,7 +117,7 @@ public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartition } else { - var m = currentPartition* distance; + var m = currentPartition * distance; cascadeText = $"{i+1}\n{m:F1}m"; } diff --git a/com.unity.render-pipelines.universal/Editor/UniversalAdditionalCameraDataEditor.cs b/com.unity.render-pipelines.universal/Editor/UniversalAdditionalCameraDataEditor.cs index eab8c3b8675..7bff64f6dbf 100644 --- a/com.unity.render-pipelines.universal/Editor/UniversalAdditionalCameraDataEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/UniversalAdditionalCameraDataEditor.cs @@ -10,6 +10,7 @@ class UniversalAdditionalCameraDataEditor : Editor public override void OnInspectorGUI() { } + [MenuItem("CONTEXT/UniversalAdditionalCameraData/Remove Component")] static void RemoveComponent(MenuCommand command) { diff --git a/com.unity.render-pipelines.universal/Editor/UniversalAnalytics.cs b/com.unity.render-pipelines.universal/Editor/UniversalAnalytics.cs index 14475656643..fc85f575ac3 100644 --- a/com.unity.render-pipelines.universal/Editor/UniversalAnalytics.cs +++ b/com.unity.render-pipelines.universal/Editor/UniversalAnalytics.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using UnityEngine.Analytics; diff --git a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAssetEditor.cs b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAssetEditor.cs index 57e80d397e7..12735cc9d69 100644 --- a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAssetEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAssetEditor.cs @@ -364,7 +364,7 @@ void DrawShadowSettings() EditorUtils.DrawCascadeSplitGUI(ref m_ShadowCascade2SplitProp, m_ShadowDistanceProp.floatValue, cascadeCount, unit); else if (cascadeCount == 1) EditorUtils.DrawCascadeSplitGUI(ref m_ShadowCascade2SplitProp, m_ShadowDistanceProp.floatValue, cascadeCount, unit); - + m_ShadowDepthBiasProp.floatValue = EditorGUILayout.Slider(Styles.shadowDepthBias, m_ShadowDepthBiasProp.floatValue, 0.0f, UniversalRenderPipeline.maxShadowBias); m_ShadowNormalBiasProp.floatValue = EditorGUILayout.Slider(Styles.shadowNormalBias, m_ShadowNormalBiasProp.floatValue, 0.0f, UniversalRenderPipeline.maxShadowBias); EditorGUILayout.PropertyField(m_SoftShadowsSupportedProp, Styles.supportsSoftShadows); @@ -445,13 +445,13 @@ void DrawRendererListLayout(ReorderableList list, SerializedProperty prop) EditorGUI.BeginChangeCheck(); EditorGUI.ObjectField(objRect, prop.GetArrayElementAtIndex(index), GUIContent.none); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) EditorUtility.SetDirty(target); Rect defaultButton = new Rect(rect.width - 90, rect.y, 86, EditorGUIUtility.singleLineHeight); var defaultRenderer = m_DefaultRendererProp.intValue; GUI.enabled = index != defaultRenderer; - if(GUI.Button(defaultButton, !GUI.enabled ? Styles.rendererDefaultText : Styles.rendererSetDefaultText)) + if (GUI.Button(defaultButton, !GUI.enabled ? Styles.rendererDefaultText : Styles.rendererSetDefaultText)) { m_DefaultRendererProp.intValue = index; EditorUtility.SetDirty(target); @@ -497,7 +497,7 @@ void DrawRendererListLayout(ReorderableList list, SerializedProperty prop) { if (li.serializedProperty.arraySize - 1 != m_DefaultRendererProp.intValue) { - if(li.serializedProperty.GetArrayElementAtIndex(li.serializedProperty.arraySize - 1).objectReferenceValue != null) + if (li.serializedProperty.GetArrayElementAtIndex(li.serializedProperty.arraySize - 1).objectReferenceValue != null) li.serializedProperty.DeleteArrayElementAtIndex(li.serializedProperty.arraySize - 1); li.serializedProperty.arraySize--; li.index = li.count - 1; diff --git a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineCameraEditor.cs b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineCameraEditor.cs index bf79f0e2004..41bf18d1b89 100644 --- a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineCameraEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineCameraEditor.cs @@ -37,7 +37,7 @@ static class Styles public static GUIContent requireDepthTexture = EditorGUIUtility.TrTextContent("Depth Texture", "On makes this camera create a _CameraDepthTexture, which is a copy of the rendered depth values.\nOff makes the camera not create a depth texture.\nUse Pipeline Settings applies settings from the Render Pipeline Asset."); public static GUIContent requireOpaqueTexture = EditorGUIUtility.TrTextContent("Opaque Texture", "On makes this camera create a _CameraOpaqueTexture, which is a copy of the rendered view.\nOff makes the camera not create an opaque texture.\nUse Pipeline Settings applies settings from the Render Pipeline Asset."); public static GUIContent allowMSAA = EditorGUIUtility.TrTextContent("MSAA", "Use Multi Sample Anti-Aliasing to reduce aliasing."); - public static GUIContent allowHDR = EditorGUIUtility.TrTextContent("HDR", "High Dynamic Range gives you a wider range of light intensities, so your lighting looks more realistic. With it, you can still see details and experience less saturation even with bright light.", (Texture) null); + public static GUIContent allowHDR = EditorGUIUtility.TrTextContent("HDR", "High Dynamic Range gives you a wider range of light intensities, so your lighting looks more realistic. With it, you can still see details and experience less saturation even with bright light.", (Texture)null); public static GUIContent priority = EditorGUIUtility.TrTextContent("Priority", "A camera with a higher priority is drawn on top of a camera with a lower priority [ -100, 100 ]."); public static GUIContent clearDepth = EditorGUIUtility.TrTextContent("Clear Depth", "If enabled, depth from the previous camera will be cleared."); @@ -108,7 +108,7 @@ static class Styles List validCameras = new List(); // This is the valid list of types, so if we need to add more types we just add it here. - List validCameraTypes = new List{CameraRenderType.Overlay}; + List validCameraTypes = new List {CameraRenderType.Overlay}; List errorCameras = new List(); Texture2D m_ErrorIcon; @@ -135,7 +135,7 @@ static class Styles SerializedProperty m_AdditionalCameraDataRenderOpaqueProp; SerializedProperty m_AdditionalCameraDataRendererProp; SerializedProperty m_AdditionalCameraDataCameraTypeProp; - SerializedProperty m_AdditionalCameraDataCameras; + SerializedProperty m_AdditionalCameraDataCameras; SerializedProperty m_AdditionalCameraDataVolumeLayerMask; SerializedProperty m_AdditionalCameraDataVolumeTrigger; SerializedProperty m_AdditionalCameraDataRenderPostProcessing; @@ -193,7 +193,7 @@ void UpdateCameraTypeIntPopupData() foreach (var cameraTarget in targets) { var additionData = (cameraTarget as Component).gameObject.GetComponent(); - if(additionData == null) + if (additionData == null) additionData = (cameraTarget as Component).gameObject.AddComponent(); m_AdditionalCameraDatas[cameraTarget] = additionData; additionalCameraList.Add(additionData); @@ -210,6 +210,7 @@ void UpdateCameraTypeIntPopupData() UpdateCameras(); } + void UpdateCameras() { var o = new PropertyFetcher(m_AdditionalCameraDataSO); @@ -380,7 +381,7 @@ void AddCameraToCameraList(Rect rect, ReorderableList list) var names = new GUIContent[validCameras.Count]; for (int i = 0; i < validCameras.Count; ++i) { - names[i] = new GUIContent((i+1) + " " + validCameras[i].name); + names[i] = new GUIContent((i + 1) + " " + validCameras[i].name); } if (!validCameras.Any()) @@ -393,7 +394,7 @@ void AddCameraToCameraList(Rect rect, ReorderableList list) void AddCameraToCameraListMenuSelected(object userData, string[] options, int selected) { - if(!validCameras.Any()) + if (!validCameras.Any()) return; var length = m_AdditionalCameraDataCameras.arraySize; @@ -405,7 +406,7 @@ void AddCameraToCameraListMenuSelected(object userData, string[] options, int se void init(List additionalCameraData) { - if(additionalCameraData == null) + if (additionalCameraData == null) return; m_AdditionalCameraDataSO = new SerializedObject(additionalCameraData.ToArray()); @@ -454,11 +455,11 @@ BackgroundType GetBackgroundType(CameraClearFlags clearFlags) public override void OnInspectorGUI() { var rpAsset = UniversalRenderPipeline.asset; - if(rpAsset == null) - { + if (rpAsset == null) + { base.OnInspectorGUI(); return; - } + } settings.Update(); m_AdditionalCameraDataSO.Update(); @@ -491,7 +492,7 @@ public override void OnInspectorGUI() } EditorGUI.indentLevel--; - settings.ApplyModifiedProperties(); + settings.ApplyModifiedProperties(); m_AdditionalCameraDataSO.ApplyModifiedProperties(); } @@ -664,7 +665,7 @@ void DrawCameraType() void DrawClearFlags() { // Converts between ClearFlags and Background Type. - BackgroundType backgroundType = GetBackgroundType((CameraClearFlags) settings.clearFlags.intValue); + BackgroundType backgroundType = GetBackgroundType((CameraClearFlags)settings.clearFlags.intValue); EditorGUI.showMixedValue = settings.clearFlags.hasMultipleDifferentValues; EditorGUI.BeginChangeCheck(); @@ -693,7 +694,7 @@ void DrawClearFlags() break; } - settings.clearFlags.intValue = (int) selectedClearFlags; + settings.clearFlags.intValue = (int)selectedClearFlags; } } @@ -729,6 +730,7 @@ void DrawXRRendering() m_AdditionalCameraDataAllowXRRendering.boolValue = EditorGUI.IntPopup(controlRect, Styles.xrTargetEye, selectedValue, Styles.xrTargetEyeOptions, Styles.xrTargetEyeValues) == 1; EditorGUI.EndProperty(); } + #endif void DrawTargetTexture(UniversalRenderPipelineAsset rpAsset) @@ -877,7 +879,7 @@ bool DrawObjectField(SerializedProperty prop, ref T value, GUIContent style) EndProperty(); return hasChanged; - } + } void DrawDepthTexture() { @@ -908,7 +910,7 @@ Rect BeginProperty(SerializedProperty prop, GUIContent style) var controlRect = EditorGUILayout.GetControlRect(true); EditorGUI.BeginProperty(controlRect, style, prop); return controlRect; - } + } void DrawRenderShadows() { diff --git a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs index afa81664fe0..4b6d5329e8f 100644 --- a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs +++ b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineLightEditor.cs @@ -92,7 +92,7 @@ protected override void OnEnable() void init(UniversalAdditionalLightData additionalLightData) { - if(additionalLightData == null) + if (additionalLightData == null) return; m_AdditionalLightDataSO = new SerializedObject(additionalLightData); m_UseAdditionalDataProp = m_AdditionalLightDataSO.FindProperty("m_UsePipelineSettings"); @@ -167,7 +167,7 @@ public override void OnInspectorGUI() EditorGUILayout.Space(); - if (SceneView.lastActiveSceneView != null ) + if (SceneView.lastActiveSceneView != null) { #if UNITY_2019_1_OR_NEWER var sceneLighting = SceneView.lastActiveSceneView.sceneLighting; @@ -238,7 +238,7 @@ void DrawAdditionalShadowData() } Rect controlRectAdditionalData = EditorGUILayout.GetControlRect(true); - if(m_AdditionalLightDataSO != null) + if (m_AdditionalLightDataSO != null) EditorGUI.BeginProperty(controlRectAdditionalData, Styles.shadowBias, m_UseAdditionalDataProp); EditorGUI.BeginChangeCheck(); @@ -247,7 +247,7 @@ void DrawAdditionalShadowData() { hasChanged = true; } - if(m_AdditionalLightDataSO != null) + if (m_AdditionalLightDataSO != null) EditorGUI.EndProperty(); if (selectedUseAdditionalData != 1 && m_AdditionalLightDataSO != null) @@ -284,7 +284,7 @@ void ShadowsGUI() // Shadows drop-down. Area lights can only be baked and always have shadows. float show = 1.0f - m_AnimAreaOptions.faded; - settings.DrawShadowsType(); + settings.DrawShadowsType(); EditorGUI.indentLevel += 1; show *= m_AnimShadowOptions.faded; diff --git a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs index 36ad2db2587..86c9e9ba7e6 100644 --- a/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs +++ b/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs @@ -272,7 +272,7 @@ public static void UpdateStandardMaterialKeywords(Material material) if (material == null) throw new ArgumentNullException("material"); - if(material.GetTexture("_MetallicGlossMap")) + if (material.GetTexture("_MetallicGlossMap")) material.SetFloat("_Smoothness", material.GetFloat("_GlossMapScale")); else material.SetFloat("_Smoothness", material.GetFloat("_Glossiness")); @@ -294,7 +294,7 @@ public static void UpdateStandardSpecularMaterialKeywords(Material material) if (material == null) throw new ArgumentNullException("material"); - if(material.GetTexture("_SpecGlossMap")) + if (material.GetTexture("_SpecGlossMap")) material.SetFloat("_Smoothness", material.GetFloat("_GlossMapScale")); else material.SetFloat("_Smoothness", material.GetFloat("_Glossiness")); diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Clipper.cs b/com.unity.render-pipelines.universal/Runtime/2D/Clipper.cs index 3dc1721e4a1..0b354eae917 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Clipper.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Clipper.cs @@ -55,7 +55,6 @@ namespace UnityEngine.Experimental.Rendering.Universal { - using ClipInt = Int64; using Path = List; using Paths = List>; @@ -358,7 +357,7 @@ public IntPoint(ClipInt X, ClipInt Y) this.NX = 0; this.NY = 0; this.N = -1; this.D = 0; } - + public IntPoint(double x, double y) { this.X = (ClipInt)x; this.Y = (ClipInt)y; @@ -591,16 +590,16 @@ internal bool PointOnLineSegment(IntPoint pt, return ((pt.X == linePt1.X) && (pt.Y == linePt1.Y)) || ((pt.X == linePt2.X) && (pt.Y == linePt2.Y)) || (((pt.X > linePt1.X) == (pt.X < linePt2.X)) && - ((pt.Y > linePt1.Y) == (pt.Y < linePt2.Y)) && - ((Int128.Int128Mul((pt.X - linePt1.X), (linePt2.Y - linePt1.Y)) == - Int128.Int128Mul((linePt2.X - linePt1.X), (pt.Y - linePt1.Y))))); + ((pt.Y > linePt1.Y) == (pt.Y < linePt2.Y)) && + ((Int128.Int128Mul((pt.X - linePt1.X), (linePt2.Y - linePt1.Y)) == + Int128.Int128Mul((linePt2.X - linePt1.X), (pt.Y - linePt1.Y))))); else return ((pt.X == linePt1.X) && (pt.Y == linePt1.Y)) || ((pt.X == linePt2.X) && (pt.Y == linePt2.Y)) || (((pt.X > linePt1.X) == (pt.X < linePt2.X)) && - ((pt.Y > linePt1.Y) == (pt.Y < linePt2.Y)) && - ((pt.X - linePt1.X) * (linePt2.Y - linePt1.Y) == - (linePt2.X - linePt1.X) * (pt.Y - linePt1.Y))); + ((pt.Y > linePt1.Y) == (pt.Y < linePt2.Y)) && + ((pt.X - linePt1.X) * (linePt2.Y - linePt1.Y) == + (linePt2.X - linePt1.X) * (pt.Y - linePt1.Y))); } //------------------------------------------------------------------------------ @@ -3171,7 +3170,7 @@ private void IntersectPoint(TEdge edge1, TEdge edge2, out IntPoint ip) pivotPoint = (edge2.Curr.N > 0) ? edge2.Curr.N - 1 : 0; } } - ip.D = 2; ip.N = isClamp ? pivotPoint : -1; + ip.D = 2; ip.N = isClamp ? pivotPoint : -1; //nb: with very large coordinate values, it's possible for SlopesEqual() to //return false but for the edge.Dx value be equal due to double precision rounding. @@ -3181,7 +3180,7 @@ private void IntersectPoint(TEdge edge1, TEdge edge2, out IntPoint ip) ip.X = TopX(edge1, ip.Y); return; } - + double b1, b2; if (edge1.Delta.X == 0) { @@ -3602,9 +3601,9 @@ bool JoinHorz(OutPt op1, OutPt op1b, OutPt op2, OutPt op2b, IntPoint Pt, bool DiscardLeft) { Direction Dir1 = (op1.Pt.X > op1b.Pt.X ? - Direction.dRightToLeft : Direction.dLeftToRight); + Direction.dRightToLeft : Direction.dLeftToRight); Direction Dir2 = (op2.Pt.X > op2b.Pt.X ? - Direction.dRightToLeft : Direction.dLeftToRight); + Direction.dRightToLeft : Direction.dLeftToRight); if (Dir1 == Dir2) return false; //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we @@ -3800,7 +3799,7 @@ private bool JoinPoints(Join j, OutRec outRec1, OutRec outRec2) op1b = op1.Next; while ((op1b.Pt == op1.Pt) && (op1b != op1)) op1b = op1b.Next; bool Reverse1 = ((op1b.Pt.Y > op1.Pt.Y) || - !SlopesEqual(op1.Pt, op1b.Pt, j.OffPt, m_UseFullRange)); + !SlopesEqual(op1.Pt, op1b.Pt, j.OffPt, m_UseFullRange)); if (Reverse1) { op1b = op1.Prev; @@ -3811,7 +3810,7 @@ private bool JoinPoints(Join j, OutRec outRec1, OutRec outRec2) op2b = op2.Next; while ((op2b.Pt == op2.Pt) && (op2b != op2)) op2b = op2b.Next; bool Reverse2 = ((op2b.Pt.Y > op2.Pt.Y) || - !SlopesEqual(op2.Pt, op2b.Pt, j.OffPt, m_UseFullRange)); + !SlopesEqual(op2.Pt, op2b.Pt, j.OffPt, m_UseFullRange)); if (Reverse2) { op2b = op2.Prev; @@ -4741,8 +4740,8 @@ private void DoOffset(double delta) for (int j = 1; j <= steps; j++) { m_destPoly.Add(new IntPoint( - Round(m_srcPoly[0].X + X * delta), - Round(m_srcPoly[0].Y + Y * delta))); + Round(m_srcPoly[0].X + X * delta), + Round(m_srcPoly[0].Y + Y * delta))); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; @@ -4754,8 +4753,8 @@ private void DoOffset(double delta) for (int j = 0; j < 4; ++j) { m_destPoly.Add(new IntPoint( - Round(m_srcPoly[0].X + X * delta), - Round(m_srcPoly[0].Y + Y * delta))); + Round(m_srcPoly[0].X + X * delta), + Round(m_srcPoly[0].Y + Y * delta))); if (X < 0) X = 1; else if (Y < 0) Y = 1; else X = -1; @@ -4805,7 +4804,7 @@ private void DoOffset(double delta) int k = 0; for (int j = 1; j < len - 1; ++j) OffsetPoint(j, ref k, node.m_jointype); - + { int j = len - 1; k = len - 2; @@ -4823,7 +4822,7 @@ private void DoOffset(double delta) k = len - 1; for (int j = k - 1; j > 0; --j) OffsetPoint(j, ref k, node.m_jointype); - + { k = 1; m_sinA = 0; @@ -4962,7 +4961,7 @@ void OffsetPoint(int j, ref int k, JoinType jointype) internal void DoSquare(int j, int k) { double dx = Math.Tan(Math.Atan2(m_sinA, - m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); + m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); var pt = new IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))); @@ -4991,7 +4990,7 @@ internal void DoMiter(int j, int k, double r) internal void DoRound(int j, int k) { double a = Math.Atan2(m_sinA, - m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); + m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); int steps = Math.Max((int)Round(m_StepsPerRad * Math.Abs(a)), 1); double X = m_normals[k].X, Y = m_normals[k].Y, X2; diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Light2D.cs b/com.unity.render-pipelines.universal/Runtime/2D/Light2D.cs index fdafff25239..71c292ff97d 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Light2D.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Light2D.cs @@ -18,7 +18,6 @@ namespace UnityEngine.Experimental.Rendering.Universal [HelpURL("https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@latest/index.html?subfolder=/manual/2DLightProperties.html")] public sealed partial class Light2D : MonoBehaviour { - public enum DeprecatedLightType { Parametric = 0, @@ -203,7 +202,6 @@ public LightType lightType public NormalMapQuality normalMapQuality => m_NormalMapQuality; - internal int GetTopMostLitLayer() { var largestIndex = Int32.MinValue; @@ -212,7 +210,7 @@ internal int GetTopMostLitLayer() var layers = Light2DManager.GetCachedSortingLayer(); for (var i = 0; i < m_ApplyToSortingLayers.Length; ++i) { - for(var layer = layers.Length - 1; layer >= largestLayer; --layer) + for (var layer = layers.Length - 1; layer >= largestLayer; --layer) { if (layers[layer].id == m_ApplyToSortingLayers[i]) { @@ -236,7 +234,7 @@ internal void UpdateMesh(bool forceUpdate) var shapePathHashChanged = LightUtility.CheckForChange(shapePathHash, ref m_PreviousShapePathHash); var lightTypeChanged = LightUtility.CheckForChange(m_LightType, ref m_PreviousLightType); var hashChanged = fallOffSizeChanged || parametricRadiusChanged || parametricSidesChanged || - parametricAngleOffsetChanged || spriteInstanceChanged || shapePathHashChanged || lightTypeChanged; + parametricAngleOffsetChanged || spriteInstanceChanged || shapePathHashChanged || lightTypeChanged; // Mesh Rebuilding if (hashChanged && forceUpdate) { @@ -279,7 +277,7 @@ internal bool IsLitLayer(int layer) if (m_ApplyToSortingLayers == null) return false; - for(var i = 0; i < m_ApplyToSortingLayers.Length; i++) + for (var i = 0; i < m_ApplyToSortingLayers.Length; i++) if (m_ApplyToSortingLayers[i] == layer) return true; diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Light2DAuthoring.cs b/com.unity.render-pipelines.universal/Runtime/2D/Light2DAuthoring.cs index f44298a7034..66ffd10ca79 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Light2DAuthoring.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Light2DAuthoring.cs @@ -4,10 +4,9 @@ namespace UnityEngine.Experimental.Rendering.Universal { public sealed partial class Light2D { - #if UNITY_EDITOR private const string s_IconsPath = "Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/SceneViewIcons/"; - private static readonly string[] s_LightIconFileNames = new [] + private static readonly string[] s_LightIconFileNames = new[] { "ParametricLight.png", "FreeformLight.png", @@ -31,7 +30,7 @@ internal List GetFalloffShape() { return LightUtility.GetOutlinePath(m_ShapePath, m_ShapeLightFalloffSize); } -#endif +#endif } } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Light2DBlendStyle.cs b/com.unity.render-pipelines.universal/Runtime/2D/Light2DBlendStyle.cs index 58cac4f1cea..ebcbc67246c 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Light2DBlendStyle.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Light2DBlendStyle.cs @@ -125,6 +125,5 @@ internal MaskChannelFilter maskTextureChannelFilter internal bool isDirty { get; set; } internal bool hasRenderTarget { get; set; } internal RenderTargetHandle renderTargetHandle; - } } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Light2DCullResult.cs b/com.unity.render-pipelines.universal/Runtime/2D/Light2DCullResult.cs index 62781ad5f8f..410dc79d20c 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Light2DCullResult.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Light2DCullResult.cs @@ -40,6 +40,7 @@ public bool IsSceneLit() return false; } + public LightStats GetLightStatsByLayer(int layer) { var returnStats = new LightStats(); diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Light2DManager.cs b/com.unity.render-pipelines.universal/Runtime/2D/Light2DManager.cs index 9876f5a5b5d..415afb78570 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Light2DManager.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Light2DManager.cs @@ -35,7 +35,7 @@ public static void ErrorIfDuplicateGlobalLight(Light2D light) foreach (var sortingLayer in light.affectedSortingLayers) { // should this really trigger at runtime? - if(ContainsDuplicateGlobalLight(sortingLayer, light.blendStyleIndex)) + if (ContainsDuplicateGlobalLight(sortingLayer, light.blendStyleIndex)) Debug.LogError("More than one global light on layer " + SortingLayer.IDToName(sortingLayer) + " for light blend style index " + light.blendStyleIndex); } } @@ -46,7 +46,7 @@ public static bool GetGlobalColor(int sortingLayerIndex, int blendStyleIndex, ou color = Color.black; // This should be rewritten to search only global lights - foreach(var light in lights) + foreach (var light in lights) { if (light.lightType != Light2D.LightType.Global || light.blendStyleIndex != blendStyleIndex || @@ -82,7 +82,7 @@ private static bool ContainsDuplicateGlobalLight(int sortingLayerIndex, int blen var globalLightCount = 0; // This should be rewritten to search only global lights - foreach(var light in lights) + foreach (var light in lights) { if (light.lightType == Light2D.LightType.Global && light.blendStyleIndex == blendStyleIndex && @@ -112,11 +112,10 @@ public static SortingLayer[] GetCachedSortingLayer() } #if UNITY_EDITOR // we should fix. Make a non allocating version of this - if(!Application.isPlaying) + if (!Application.isPlaying) s_SortingLayers = SortingLayer.layers; #endif return s_SortingLayers; } - } } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Light2DStub.cs b/com.unity.render-pipelines.universal/Runtime/2D/Light2DStub.cs index fee45d15027..0093483a128 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Light2DStub.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Light2DStub.cs @@ -4,5 +4,5 @@ namespace UnityEngine.Experimental.Rendering.LWRP { [Obsolete("LWRP -> Universal (UnityUpgradable) -> UnityEngine.Experimental.Rendering.Universal.Light2D", true)] public class Light2D - { } + {} } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/LightUtility.cs b/com.unity.render-pipelines.universal/Runtime/2D/LightUtility.cs index 00ae8f0a232..c7e2429d296 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/LightUtility.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/LightUtility.cs @@ -11,13 +11,13 @@ namespace UnityEngine.Experimental.Rendering.Universal { internal static class LightUtility { - public static bool CheckForChange(Light2D.LightType a, ref Light2D.LightType b) { var changed = a != b; b = a; return changed; } + public static bool CheckForChange(int a, ref int b) { var changed = a != b; @@ -73,7 +73,7 @@ static void Tessellate(Tess tess, ElementType boundaryType, NativeArray var tessVertices = tess.Vertices.Select(v => new LightMeshVertex() { position = new float3(v.Position.X, v.Position.Y, 0), color = c }); - foreach(var v in tessVertices) + foreach (var v in tessVertices) vertices[VCount++] = v; foreach (var i in tessIndices) indices[ICount++] = (ushort)(i + prevCount); @@ -219,7 +219,7 @@ internal static List GetOutlinePath(Vector3[] shapePath, float offsetDi for (var i = 0; i < shapePath.Length; ++i) { var newPoint = new Vector2(shapePath[i].x, shapePath[i].y) * kClipperScale; - path.Add(new IntPoint((System.Int64) (newPoint.x), (System.Int64) (newPoint.y))); + path.Add(new IntPoint((System.Int64)(newPoint.x), (System.Int64)(newPoint.y))); } List> solution = new List>(); ClipperOffset clipOffset = new ClipperOffset(2048.0f); @@ -235,7 +235,6 @@ internal static List GetOutlinePath(Vector3[] shapePath, float offsetDi public static Bounds GenerateShapeMesh(Light2D light, Vector3[] shapePath, float falloffDistance) { - var ix = 0; var vcount = 0; var icount = 0; @@ -243,8 +242,8 @@ public static Bounds GenerateShapeMesh(Light2D light, Vector3[] shapePath, float var mesh = light.lightMesh; // todo Revisit this while we do Batching. - var meshInteriorColor = new Color(0.0f,0,0,1.0f); - var meshExteriorColor = new Color(0.0f,0,0,0.0f); + var meshInteriorColor = new Color(0.0f, 0, 0, 1.0f); + var meshExteriorColor = new Color(0.0f, 0, 0, 0.0f); var vertices = new NativeArray(shapePath.Length * 256, Allocator.Temp); var indices = new NativeArray(shapePath.Length * 256, Allocator.Temp); @@ -264,7 +263,7 @@ public static Bounds GenerateShapeMesh(Light2D light, Vector3[] shapePath, float for (var i = 0; i < inputPointCount; ++i) { var newPoint = new Vector2(inner[i].Position.X, inner[i].Position.Y) * kClipperScale; - var addPoint = new IntPoint((System.Int64) (newPoint.x),(System.Int64) (newPoint.y)); + var addPoint = new IntPoint((System.Int64)(newPoint.x), (System.Int64)(newPoint.y)); addPoint.N = i; addPoint.D = -1; path.Add(addPoint); } @@ -282,7 +281,7 @@ public static Bounds GenerateShapeMesh(Light2D light, Vector3[] shapePath, float var outPath = solution[0]; var minPath = (long)inputPointCount; for (int i = 0; i < outPath.Count; ++i) - minPath = (outPath[i].N != -1 ) ? Math.Min(minPath, outPath[i].N) : minPath; + minPath = (outPath[i].N != -1) ? Math.Min(minPath, outPath[i].N) : minPath; var containsStart = minPath == 0; outPath = FixPivots(outPath, path); @@ -353,7 +352,6 @@ public static Bounds GenerateShapeMesh(Light2D light, Vector3[] shapePath, float return mesh.GetSubMesh(0).bounds; } - public static Bounds GenerateParametricMesh(Light2D light, float radius, float falloffDistance, float angle, int sides) { var angleOffset = Mathf.PI / 2.0f + Mathf.Deg2Rad * angle; @@ -363,7 +361,7 @@ public static Bounds GenerateParametricMesh(Light2D light, float radius, float f sides = 4; } - if(sides == 4) + if (sides == 4) { angleOffset = Mathf.PI / 4.0f + Mathf.Deg2Rad * angle; } @@ -448,7 +446,7 @@ public static Bounds GenerateSpriteMesh(Light2D light, Sprite sprite) var uvs = sprite.uv; var mesh = light.lightMesh; - if(sprite == null) + if (sprite == null) { mesh.Clear(); return new Bounds(Vector3.zero, Vector3.zero); @@ -460,7 +458,7 @@ public static Bounds GenerateSpriteMesh(Light2D light, Sprite sprite) var center = 0.5f * (sprite.bounds.min + sprite.bounds.max); var vertices = new NativeArray(srcIndices.Length, Allocator.Temp); - var color = new Color(0,0,0, 1); + var color = new Color(0, 0, 0, 1); for (var i = 0; i < srcVertices.Length; i++) { @@ -483,7 +481,6 @@ public static Bounds GenerateSpriteMesh(Light2D light, Sprite sprite) return mesh.GetSubMesh(0).bounds; } - public static int GetShapePathHash(Vector3[] path) { unchecked @@ -503,7 +500,5 @@ public static int GetShapePathHash(Vector3[] path) return hashCode; } } - } } - diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Passes/Render2DLightingPass.cs b/com.unity.render-pipelines.universal/Runtime/2D/Passes/Render2DLightingPass.cs index 311fa8c6eb6..052fd52fc4f 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Passes/Render2DLightingPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Passes/Render2DLightingPass.cs @@ -38,7 +38,7 @@ internal class Render2DLightingPass : ScriptableRenderPass, IRenderPass2D Material m_SamplingMaterial; private readonly Renderer2DData m_Renderer2DData; - + private bool m_HasValidDepth; public Render2DLightingPass(Renderer2DData rendererData, Material blitMaterial, Material samplingMaterial) @@ -104,7 +104,6 @@ private short GetCameraSortingLayerBoundsIndex() return short.MinValue; } - private int DrawLayerBatches( LayerBatch[] layerBatches, int batchCount, @@ -315,7 +314,7 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData CommandBufferPool.Release(cmd); Profiler.BeginSample("Render Sprites Unlit"); - context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings); + context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings); Profiler.EndSample(); } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/LayerUtility.cs b/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/LayerUtility.cs index 0f05f2892d6..55beaf0ca7b 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/LayerUtility.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/LayerUtility.cs @@ -6,7 +6,7 @@ namespace UnityEngine.Experimental.Rendering.Universal internal struct LayerBatch { public int startLayerID; - public int endLayerValue; + public int endLayerValue; public SortingLayerRange layerRange; public LightStats lightStats; private unsafe fixed int renderTargetIds[4]; @@ -78,12 +78,12 @@ private static bool CompareLightsInLayer(int layerIndex1, int layerIndex2, Sorti private static int FindUpperBoundInBatch(int startLayerIndex, SortingLayer[] sortingLayers, ILight2DCullResult lightCullResult) { // start checking at the next layer - for (var i = startLayerIndex+1; i < sortingLayers.Length; i++) + for (var i = startLayerIndex + 1; i < sortingLayers.Length; i++) { - if(!CompareLightsInLayer(startLayerIndex, i, sortingLayers, lightCullResult)) - return i-1; + if (!CompareLightsInLayer(startLayerIndex, i, sortingLayers, lightCullResult)) + return i - 1; } - return sortingLayers.Length-1; + return sortingLayers.Length - 1; } private static void InitializeBatchInfos(SortingLayer[] cachedSortingLayers) @@ -131,9 +131,9 @@ public static LayerBatch[] CalculateBatches(ILight2DCullResult lightCullResult, // Some renderers override their sorting layer value with short.MinValue or short.MaxValue. // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue. // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue. - var startLayerValue = (short) cachedSortingLayers[i].value; + var startLayerValue = (short)cachedSortingLayers[i].value; var lowerBound = (i == 0) ? short.MinValue : startLayerValue; - var endLayerValue = (short) cachedSortingLayers[upperLayerInBatch].value; + var endLayerValue = (short)cachedSortingLayers[upperLayerInBatch].value; var upperBound = (upperLayerInBatch == cachedSortingLayers.Length - 1) ? short.MaxValue : endLayerValue; // Renderer within this range share the same set of lights so they should be rendered together. diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs b/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs index bab2ce53f4f..5e78bf7d948 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs @@ -186,7 +186,7 @@ private static void RenderLightSet(IRenderPass2D pass, RenderingData renderingDa // Break up light rendering into batches for the purpose of shadow casting var lightIndex = 0; - while(lightIndex < lights.Count) + while (lightIndex < lights.Count) { var remainingLights = (uint)lights.Count - lightIndex; var batchedLights = 0; @@ -260,7 +260,7 @@ private static void RenderLightSet(IRenderPass2D pass, RenderingData renderingDa } // Release all of the temporary shadow textures - for (var releaseIndex = shadowLightCount-1; releaseIndex >= 0; releaseIndex--) + for (var releaseIndex = shadowLightCount - 1; releaseIndex >= 0; releaseIndex--) ShadowRendering.ReleaseShadowRenderTexture(cmd, releaseIndex); lightIndex += batchedLights; @@ -281,7 +281,7 @@ public static void RenderLightVolumes(this IRenderPass2D pass, RenderingData ren // Break up light rendering into batches for the purpose of shadow casting var lightIndex = 0; - while(lightIndex < lights.Count) + while (lightIndex < lights.Count) { var remainingLights = (uint)lights.Count - lightIndex; var batchedLights = 0; @@ -528,7 +528,7 @@ public static void RenderLights(this IRenderPass2D pass, RenderingData rendering i, cmd, layerToRender, - identifier, + identifier, pass.rendererData.lightCullResult.visibleLights ); } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs b/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs index dd2e8281a0a..ad6f99690b6 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs @@ -276,6 +276,7 @@ void OnGUI() GUI.color = oldColor; } + #endif #if UNITY_EDITOR @@ -288,6 +289,7 @@ void OnPlayModeChanged(UnityEditor.PlayModeStateChange state) OnDisable(); } } + #endif } } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCameraInternal.cs b/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCameraInternal.cs index 5ce63431f8f..d878268f2ad 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCameraInternal.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCameraInternal.cs @@ -17,10 +17,10 @@ internal interface IPixelPerfectCamera [Serializable] internal class PixelPerfectCameraInternal : ISerializationCallbackReceiver { - // Case 1061634: + // Case 1061634: // In order for this class to survive hot reloading, we need to make the fields serializable. - // Unity can't serialize an interface object, but does properly serialize UnityEngine.Object. - // So we cast the reference to PixelPerfectCamera (which inherits UnityEngine.Object) + // Unity can't serialize an interface object, but does properly serialize UnityEngine.Object. + // So we cast the reference to PixelPerfectCamera (which inherits UnityEngine.Object) // before serialization happens, and restore the interface reference after deserialization. [NonSerialized] IPixelPerfectCamera m_Component; diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs b/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs index f332b534aff..ae6f1188823 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs @@ -138,9 +138,9 @@ protected override void OnEnable() shadowsRenderTarget.Init("_ShadowTex"); const int totalMaterials = 256; - if(shadowMaterials == null || shadowMaterials.Length == 0) + if (shadowMaterials == null || shadowMaterials.Length == 0) shadowMaterials = new Material[totalMaterials]; - if(removeSelfShadowMaterials == null || removeSelfShadowMaterials.Length == 0) + if (removeSelfShadowMaterials == null || removeSelfShadowMaterials.Length == 0) removeSelfShadowMaterials = new Material[totalMaterials]; } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs b/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs index 9ab52a960e0..38ef093fb55 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs @@ -77,6 +77,7 @@ private void Awake() m_LightBlendStyles[i].blendMode = Light2DBlendStyle.BlendMode.Multiply; } } + #endif } } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/CompositeShadowCaster2D.cs b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/CompositeShadowCaster2D.cs index 15c551cac1b..c4823d06062 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/CompositeShadowCaster2D.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/CompositeShadowCaster2D.cs @@ -5,7 +5,6 @@ namespace UnityEngine.Experimental.Rendering.Universal { - [AddComponentMenu("Rendering/2D/Composite Shadow Caster 2D (Experimental)")] [ExecuteInEditMode] public class CompositeShadowCaster2D : ShadowCasterGroup2D diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs index 1bf4d44bf6b..4b6d057bb4a 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs @@ -5,7 +5,6 @@ namespace UnityEngine.Experimental.Rendering.Universal { - /// /// Class ShadowCaster2D contains properties used for shadow casting /// @@ -68,7 +67,7 @@ static int[] SetDefaultSortingLayers() int layerCount = SortingLayer.layers.Length; int[] allLayers = new int[layerCount]; - for(int layerIndex=0;layerIndex < layerCount;layerIndex++) + for (int layerIndex = 0; layerIndex < layerCount; layerIndex++) { allLayers[layerIndex] = SortingLayer.layers[layerIndex].id; } @@ -87,7 +86,7 @@ private void Awake() m_ApplyToSortingLayers = SetDefaultSortingLayers(); Bounds bounds = new Bounds(transform.position, Vector3.one); - + Renderer renderer = GetComponent(); if (renderer != null) { @@ -101,9 +100,9 @@ private void Awake() bounds = collider.bounds; } #endif - Vector3 inverseScale = Vector3.zero; + Vector3 inverseScale = Vector3.zero; Vector3 relOffset = transform.position; - + if (transform.lossyScale.x != 0 && transform.lossyScale.y != 0) { inverseScale = new Vector3(1 / transform.lossyScale.x, 1 / transform.lossyScale.y); @@ -168,7 +167,7 @@ public void Update() if (LightUtility.CheckForChange(m_CastsShadows, ref m_PreviousCastsShadows)) { - if(m_CastsShadows) + if (m_CastsShadows) ShadowCasterGroup2DManager.AddGroup(this); else ShadowCasterGroup2DManager.RemoveGroup(this); @@ -181,7 +180,7 @@ void Reset() Awake(); OnEnable(); } -#endif +#endif } } diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCasterGroup2DManager.cs b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCasterGroup2DManager.cs index e90acc09857..d89496aaa9b 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCasterGroup2DManager.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCasterGroup2DManager.cs @@ -78,6 +78,7 @@ public static void AddGroup(ShadowCasterGroup2D group) AddShadowCasterGroupToList(group, s_ShadowCasterGroups); } + public static void RemoveGroup(ShadowCasterGroup2D group) { if (group != null && s_ShadowCasterGroups != null) diff --git a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowUtility.cs b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowUtility.cs index 03f8b935447..22173eadf46 100644 --- a/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowUtility.cs +++ b/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowUtility.cs @@ -53,7 +53,7 @@ static Edge CreateEdge(int triangleIndexA, int triangleIndexB, List ver Edge retEdge = new Edge(); retEdge.AssignVertexIndices(triangles[triangleIndexA], triangles[triangleIndexB]); - + Vector3 vertex0 = vertices[retEdge.vertexIndex0]; vertex0.z = 0; Vector3 vertex1 = vertices[retEdge.vertexIndex1]; @@ -67,11 +67,11 @@ static Edge CreateEdge(int triangleIndexA, int triangleIndexB, List ver static void PopulateEdgeArray(List vertices, List triangles, List edges) { - for(int triangleIndex=0;triangleIndex edgesToProcess) static void CreateShadowTriangles(List vertices, List colors, List triangles, List tangents, List edges) { - for(int edgeIndex=0; edgeIndex(), "CustomPostProcessData.asset", null, null); } + #endif [Serializable, ReloadGroup] diff --git a/com.unity.render-pipelines.universal/Runtime/Data/RenderStateData.cs b/com.unity.render-pipelines.universal/Runtime/Data/RenderStateData.cs index b821e107387..3b23f12b3db 100644 --- a/com.unity.render-pipelines.universal/Runtime/Data/RenderStateData.cs +++ b/com.unity.render-pipelines.universal/Runtime/Data/RenderStateData.cs @@ -1,4 +1,4 @@ -using UnityEngine.Scripting.APIUpdating; +using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.Rendering.Universal { diff --git a/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs b/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs index e99d6f68dd0..c460b36ca9f 100644 --- a/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs +++ b/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs @@ -289,7 +289,7 @@ protected override RenderPipeline CreatePipeline() if (m_RendererDataList[0] == null) { // If previous version and current version are miss-matched then we are waiting for the upgrader to kick in - if(k_AssetPreviousVersion != k_AssetVersion) + if (k_AssetPreviousVersion != k_AssetVersion) return null; Debug.LogError( @@ -662,7 +662,7 @@ public ShaderVariantLogLevel shaderVariantLogLevel [Obsolete("PipelineDebugLevel is deprecated. Calling debugLevel is not necessary.", false)] public PipelineDebugLevel debugLevel { - get => PipelineDebugLevel.Disabled ; + get => PipelineDebugLevel.Disabled; } public bool useSRPBatcher @@ -683,10 +683,10 @@ public int colorGradingLutSize set { m_ColorGradingLutSize = Mathf.Clamp(value, k_MinLutSize, k_MaxLutSize); } } - /// - /// Set to true to allow Adaptive performance to modify graphics quality settings during runtime. - /// Only applicable when Adaptive performance package is available. - /// + /// + /// Set to true to allow Adaptive performance to modify graphics quality settings during runtime. + /// Only applicable when Adaptive performance package is available. + /// public bool useAdaptivePerformance { get { return m_UseAdaptivePerformance; } @@ -869,7 +869,7 @@ public void OnAfterDeserialize() #if UNITY_EDITOR static void UpgradeAsset(UniversalRenderPipelineAsset asset) { - if(asset.k_AssetPreviousVersion < 5) + if (asset.k_AssetPreviousVersion < 5) { if (asset.m_RendererType == RendererType.ForwardRenderer) { @@ -888,6 +888,7 @@ static void UpgradeAsset(UniversalRenderPipelineAsset asset) asset.k_AssetPreviousVersion = 5; } } + #endif float ValidateShadowBias(float value) diff --git a/com.unity.render-pipelines.universal/Runtime/Data/XRSystemData.cs b/com.unity.render-pipelines.universal/Runtime/Data/XRSystemData.cs index edbfae1fe63..e732129b9ed 100644 --- a/com.unity.render-pipelines.universal/Runtime/Data/XRSystemData.cs +++ b/com.unity.render-pipelines.universal/Runtime/Data/XRSystemData.cs @@ -27,6 +27,7 @@ static void CreateXRSystemData() { ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, CreateInstance(), "CustomXRSystemData.asset", null, null); } + #endif [Serializable, ReloadGroup] diff --git a/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs b/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs index 1b4b4482913..f94839518d7 100644 --- a/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs +++ b/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs @@ -31,9 +31,9 @@ internal static bool UseCBufferForDepthRange get { #if !UNITY_EDITOR && UNITY_SWITCH - return false; + return false; #else - return IsOpenGL; + return IsOpenGL; #endif } } @@ -43,9 +43,9 @@ internal static bool UseCBufferForTileList get { #if !UNITY_EDITOR && UNITY_SWITCH - return false; + return false; #else - return IsOpenGL; + return IsOpenGL; #endif } } @@ -63,9 +63,9 @@ internal static bool UseCBufferForLightList get { #if !UNITY_EDITOR && UNITY_SWITCH - return false; + return false; #else - return IsOpenGL; + return IsOpenGL; #endif } } @@ -233,12 +233,14 @@ struct DrawCall public int instanceCount; } - static readonly string[] k_TileDeferredPassNames = new string[] { + static readonly string[] k_TileDeferredPassNames = new string[] + { "Tiled Deferred Punctual Light (Lit)", "Tiled Deferred Punctual Light (SimpleLit)" }; - static readonly string[] k_StencilDeferredPassNames = new string[] { + static readonly string[] k_StencilDeferredPassNames = new string[] + { "Stencil Volume", "Deferred Punctual Light (Lit)", "Deferred Punctual Light (SimpleLit)", @@ -304,7 +306,7 @@ internal GraphicsFormat GetGBufferFormat(int index) if (index == GBufferAlbedoIndex) // sRGB albedo, materialFlags return QualitySettings.activeColorSpace == ColorSpace.Linear ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm; else if (index == GBufferSpecularMetallicIndex) // sRGB specular, [unused] - return QualitySettings.activeColorSpace == ColorSpace.Linear ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm; + return QualitySettings.activeColorSpace == ColorSpace.Linear ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm; else if (index == GBufferNormalSmoothnessIndex) return this.AccurateGbufferNormals ? GraphicsFormat.R8G8B8A8_UNorm : GraphicsFormat.R8G8B8A8_SNorm; // normal normal normal packedSmoothness else if (index == GBufferLightingIndex) // Emissive+baked: Most likely B10G11R11_UFloatPack32 or R16G16B16A16_SFloat @@ -326,12 +328,12 @@ internal GraphicsFormat GetGBufferFormat(int index) // This is an overlay camera being rendered. internal bool IsOverlay { get; set; } // Not all platforms support R8G8B8A8_SNorm, so we need to check for the support and force accurate GBuffer normals and relevant shader variants - private bool m_AccurateGbufferNormals; + private bool m_AccurateGbufferNormals; internal bool AccurateGbufferNormals - { - get { return m_AccurateGbufferNormals; } - set { m_AccurateGbufferNormals = value || !RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R8G8B8A8_SNorm, FormatUsage.Render); } - } + { + get { return m_AccurateGbufferNormals; } + set { m_AccurateGbufferNormals = value || !RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R8G8B8A8_SNorm, FormatUsage.Render); } + } // true: TileDeferred.shader used for some lights (currently: point/spot lights without shadows) - false: use StencilDeferred.shader for all lights internal bool TiledDeferredShading { get; set; } // We browse all visible lights and found the mixed lighting setup every frame. @@ -422,8 +424,8 @@ internal DeferredLights(Material tileDepthInfoMaterial, Material tileDeferredMat // Cache result for GL platform here. SystemInfo properties are in C++ land so repeated access will be unecessary penalized. // They can also only be called from main thread! DeferredConfig.IsOpenGL = SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore - || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES2 - || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3; + || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES2 + || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3; m_TileDepthInfoMaterial = tileDepthInfoMaterial; m_TileDeferredMaterial = tileDeferredMaterial; @@ -649,32 +651,32 @@ internal void SetupLights(ScriptableRenderContext context, ref RenderingData ren int fineStepY = coarseTiler.TilePixelHeight / fineTiler.TilePixelHeight; for (int j = 0; j < coarseTileYCount; ++j) - for (int i = 0; i < coarseTileXCount; ++i) - { - int fine_istart = i * fineStepX; - int fine_jstart = j * fineStepY; - int fine_iend = Mathf.Min(fine_istart + fineStepX, fineTileXCount); - int fine_jend = Mathf.Min(fine_jstart + fineStepY, fineTileYCount); - int coarseHeaderOffset = coarseTiler.GetTileHeaderOffset(i, j); - - CullLightsJob job = new CullLightsJob + for (int i = 0; i < coarseTileXCount; ++i) { - tiler = m_Tilers[t-1], - prePunctualLights = prePunctualLights, - coarseTiles = coarseTiles, - coarseTileHeaders = coarseTileHeaders, - coarseHeaderOffset = coarseHeaderOffset, - istart = fine_istart, - iend = fine_iend, - jstart = fine_jstart, - jend = fine_jend, - }; - - if (this.UseJobSystem) - jobHandles[jobCount++] = job.Schedule(jobHandles[jobOffset + (i / subdivX) + (j / subdivY) * superCoarseTileXCount]); - else - job.Execute(); - } + int fine_istart = i * fineStepX; + int fine_jstart = j * fineStepY; + int fine_iend = Mathf.Min(fine_istart + fineStepX, fineTileXCount); + int fine_jend = Mathf.Min(fine_jstart + fineStepY, fineTileYCount); + int coarseHeaderOffset = coarseTiler.GetTileHeaderOffset(i, j); + + CullLightsJob job = new CullLightsJob + { + tiler = m_Tilers[t - 1], + prePunctualLights = prePunctualLights, + coarseTiles = coarseTiles, + coarseTileHeaders = coarseTileHeaders, + coarseHeaderOffset = coarseHeaderOffset, + istart = fine_istart, + iend = fine_iend, + jstart = fine_jstart, + jend = fine_jend, + }; + + if (this.UseJobSystem) + jobHandles[jobCount++] = job.Schedule(jobHandles[jobOffset + (i / subdivX) + (j / subdivY) * superCoarseTileXCount]); + else + job.Execute(); + } jobOffset += superCoarseTileXCount * superCoarseTileYCount; } @@ -719,8 +721,8 @@ public void ResolveMixedLightingMode(ref RenderingData renderingData) Light light = visibleLights[lightIndex].light; if (light != null - && light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed - && light.shadows != LightShadows.None) + && light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed + && light.shadows != LightShadows.None) { switch (light.bakingOutput.mixedLightingMode) { @@ -795,8 +797,6 @@ public void Setup(ref RenderingData renderingData, for (int i = 0; i < this.GbufferAttachmentIdentifiers.Length; ++i) this.GbufferAttachmentIdentifiers[i] = new RenderTargetIdentifier(this.GbufferAttachmentIdentifiers[i], 0, CubemapFace.Unknown, -1); this.DepthAttachmentIdentifier = new RenderTargetIdentifier(this.DepthAttachmentIdentifier, 0, CubemapFace.Unknown, -1); - - } #endif @@ -812,7 +812,7 @@ public void OnCameraCleanup(CommandBuffer cmd) CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.ShadowsShadowMask, false); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.MixedLightingSubtractive, false); // Backward compatibility - for (int tilerIndex = 0; tilerIndex < m_Tilers.Length; ++ tilerIndex) + for (int tilerIndex = 0; tilerIndex < m_Tilers.Length; ++tilerIndex) { m_TileDataCapacities[tilerIndex] = max(m_TileDataCapacities[tilerIndex], m_Tilers[tilerIndex].TileDataCapacity); m_Tilers[tilerIndex].OnCameraCleanup(); @@ -1190,13 +1190,13 @@ bool CheckHasTileLights(ref NativeArray visibleLights) } void PrecomputeLights(out NativeArray prePunctualLights, - out NativeArray stencilVisLights, - out NativeArray stencilVisLightOffsets, - ref NativeArray visibleLights, - bool hasAdditionalLights, - Matrix4x4 view, - bool isOrthographic, - float zNear) + out NativeArray stencilVisLights, + out NativeArray stencilVisLightOffsets, + ref NativeArray visibleLights, + bool hasAdditionalLights, + Matrix4x4 view, + bool isOrthographic, + float zNear) { const int lightTypeCount = (int)LightType.Disc + 1; @@ -1758,34 +1758,36 @@ static Mesh CreateSphereMesh() // This icosaedron has been been slightly inflated to fit an unit sphere. // This is the same geometry as built-in deferred. - Vector3[] positions = { - new Vector3( 0.000f, 0.000f, -1.070f), new Vector3( 0.174f, -0.535f, -0.910f), - new Vector3(-0.455f, -0.331f, -0.910f), new Vector3( 0.562f, 0.000f, -0.910f), - new Vector3(-0.455f, 0.331f, -0.910f), new Vector3( 0.174f, 0.535f, -0.910f), - new Vector3(-0.281f, -0.865f, -0.562f), new Vector3( 0.736f, -0.535f, -0.562f), - new Vector3( 0.296f, -0.910f, -0.468f), new Vector3(-0.910f, 0.000f, -0.562f), - new Vector3(-0.774f, -0.562f, -0.478f), new Vector3( 0.000f, -1.070f, 0.000f), - new Vector3(-0.629f, -0.865f, 0.000f), new Vector3( 0.629f, -0.865f, 0.000f), - new Vector3(-1.017f, -0.331f, 0.000f), new Vector3( 0.957f, 0.000f, -0.478f), - new Vector3( 0.736f, 0.535f, -0.562f), new Vector3( 1.017f, -0.331f, 0.000f), - new Vector3( 1.017f, 0.331f, 0.000f), new Vector3(-0.296f, -0.910f, 0.478f), - new Vector3( 0.281f, -0.865f, 0.562f), new Vector3( 0.774f, -0.562f, 0.478f), - new Vector3(-0.736f, -0.535f, 0.562f), new Vector3( 0.910f, 0.000f, 0.562f), - new Vector3( 0.455f, -0.331f, 0.910f), new Vector3(-0.174f, -0.535f, 0.910f), - new Vector3( 0.629f, 0.865f, 0.000f), new Vector3( 0.774f, 0.562f, 0.478f), - new Vector3( 0.455f, 0.331f, 0.910f), new Vector3( 0.000f, 0.000f, 1.070f), + Vector3[] positions = + { + new Vector3(0.000f, 0.000f, -1.070f), new Vector3(0.174f, -0.535f, -0.910f), + new Vector3(-0.455f, -0.331f, -0.910f), new Vector3(0.562f, 0.000f, -0.910f), + new Vector3(-0.455f, 0.331f, -0.910f), new Vector3(0.174f, 0.535f, -0.910f), + new Vector3(-0.281f, -0.865f, -0.562f), new Vector3(0.736f, -0.535f, -0.562f), + new Vector3(0.296f, -0.910f, -0.468f), new Vector3(-0.910f, 0.000f, -0.562f), + new Vector3(-0.774f, -0.562f, -0.478f), new Vector3(0.000f, -1.070f, 0.000f), + new Vector3(-0.629f, -0.865f, 0.000f), new Vector3(0.629f, -0.865f, 0.000f), + new Vector3(-1.017f, -0.331f, 0.000f), new Vector3(0.957f, 0.000f, -0.478f), + new Vector3(0.736f, 0.535f, -0.562f), new Vector3(1.017f, -0.331f, 0.000f), + new Vector3(1.017f, 0.331f, 0.000f), new Vector3(-0.296f, -0.910f, 0.478f), + new Vector3(0.281f, -0.865f, 0.562f), new Vector3(0.774f, -0.562f, 0.478f), + new Vector3(-0.736f, -0.535f, 0.562f), new Vector3(0.910f, 0.000f, 0.562f), + new Vector3(0.455f, -0.331f, 0.910f), new Vector3(-0.174f, -0.535f, 0.910f), + new Vector3(0.629f, 0.865f, 0.000f), new Vector3(0.774f, 0.562f, 0.478f), + new Vector3(0.455f, 0.331f, 0.910f), new Vector3(0.000f, 0.000f, 1.070f), new Vector3(-0.562f, 0.000f, 0.910f), new Vector3(-0.957f, 0.000f, 0.478f), - new Vector3( 0.281f, 0.865f, 0.562f), new Vector3(-0.174f, 0.535f, 0.910f), - new Vector3( 0.296f, 0.910f, -0.478f), new Vector3(-1.017f, 0.331f, 0.000f), + new Vector3(0.281f, 0.865f, 0.562f), new Vector3(-0.174f, 0.535f, 0.910f), + new Vector3(0.296f, 0.910f, -0.478f), new Vector3(-1.017f, 0.331f, 0.000f), new Vector3(-0.736f, 0.535f, 0.562f), new Vector3(-0.296f, 0.910f, 0.478f), - new Vector3( 0.000f, 1.070f, 0.000f), new Vector3(-0.281f, 0.865f, -0.562f), + new Vector3(0.000f, 1.070f, 0.000f), new Vector3(-0.281f, 0.865f, -0.562f), new Vector3(-0.774f, 0.562f, -0.478f), new Vector3(-0.629f, 0.865f, 0.000f), }; - int[] indices = { - 0, 1, 2, 0, 3, 1, 2, 4, 0, 0, 5, 3, 0, 4, 5, 1, 6, 2, - 3, 7, 1, 1, 8, 6, 1, 7, 8, 9, 4, 2, 2, 6, 10, 10, 9, 2, - 8, 11, 6, 6, 12, 10, 11, 12, 6, 7, 13, 8, 8, 13, 11, 10, 14, 9, + int[] indices = + { + 0, 1, 2, 0, 3, 1, 2, 4, 0, 0, 5, 3, 0, 4, 5, 1, 6, 2, + 3, 7, 1, 1, 8, 6, 1, 7, 8, 9, 4, 2, 2, 6, 10, 10, 9, 2, + 8, 11, 6, 6, 12, 10, 11, 12, 6, 7, 13, 8, 8, 13, 11, 10, 14, 9, 10, 12, 14, 3, 15, 7, 5, 16, 3, 3, 16, 15, 15, 17, 7, 17, 13, 7, 16, 18, 15, 15, 18, 17, 11, 19, 12, 13, 20, 11, 11, 20, 19, 17, 21, 13, 13, 21, 20, 12, 19, 22, 12, 22, 14, 17, 23, 21, 18, 23, 17, 21, 24, 20, @@ -1795,7 +1797,7 @@ static Mesh CreateSphereMesh() 30, 29, 33, 33, 28, 32, 34, 26, 16, 5, 34, 16, 14, 31, 35, 14, 35, 9, 31, 30, 36, 30, 33, 36, 35, 31, 36, 37, 33, 32, 36, 33, 37, 38, 32, 26, 34, 38, 26, 38, 37, 32, 5, 39, 34, 39, 38, 34, 4, 39, 5, 9, 40, 4, - 9, 35, 40, 4, 40, 39, 35, 36, 41, 41, 36, 37, 41, 37, 38, 40, 35, 41, + 9, 35, 40, 4, 40, 39, 35, 36, 41, 41, 36, 37, 41, 37, 38, 40, 35, 41, 40, 41, 39, 41, 38, 39, }; @@ -1813,7 +1815,8 @@ static Mesh CreateHemisphereMesh() // TODO reorder for pre&post-transform cache optimisation. // This capped hemisphere shape is in unit dimensions. It will be slightly inflated in the vertex shader // to fit the cone analytical shape. - Vector3 [] positions = { + Vector3[] positions = + { new Vector3(0.000000f, 0.000000f, 0.000000f), new Vector3(1.000000f, 0.000000f, 0.000000f), new Vector3(0.923880f, 0.382683f, 0.000000f), new Vector3(0.707107f, 0.707107f, 0.000000f), new Vector3(0.382683f, 0.923880f, 0.000000f), new Vector3(-0.000000f, 1.000000f, 0.000000f), @@ -1837,7 +1840,8 @@ static Mesh CreateHemisphereMesh() new Vector3(-0.923880f, 0.000000f, 0.382683f), new Vector3(-0.382683f, 0.000000f, 0.923880f) }; - int [] indices = { + int[] indices = + { 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 5, 4, 0, 6, 5, 0, 7, 6, 0, 8, 7, 0, 9, 8, 0, 10, 9, 0, 11, 10, 0, 12, 11, 0, 13, 12, 0, 14, 13, 0, 15, 14, 0, 16, 15, 0, 1, 16, @@ -1867,13 +1871,14 @@ static Mesh CreateFullscreenMesh() { // TODO reorder for pre&post-transform cache optimisation. // Simple full-screen triangle. - Vector3 [] positions = { + Vector3[] positions = + { new Vector3(-1.0f, 1.0f, 0.0f), new Vector3(-1.0f, -3.0f, 0.0f), - new Vector3( 3.0f, 1.0f, 0.0f) + new Vector3(3.0f, 1.0f, 0.0f) }; - int [] indices = { 0, 1, 2 }; + int[] indices = { 0, 1, 2 }; Mesh mesh = new Mesh(); mesh.indexFormat = IndexFormat.UInt16; diff --git a/com.unity.render-pipelines.universal/Runtime/DeferredShaderData.cs b/com.unity.render-pipelines.universal/Runtime/DeferredShaderData.cs index f0da30f3f07..2c7d02897c0 100644 --- a/com.unity.render-pipelines.universal/Runtime/DeferredShaderData.cs +++ b/com.unity.render-pipelines.universal/Runtime/DeferredShaderData.cs @@ -153,7 +153,6 @@ void DisposeBuffers(ComputeBuffer[,] buffers) { for (int j = 0; j < buffers.GetLength(1); ++j) { - if (buffers[i, j] != null) { buffers[i, j].Dispose(); diff --git a/com.unity.render-pipelines.universal/Runtime/DeferredTiler.cs b/com.unity.render-pipelines.universal/Runtime/DeferredTiler.cs index aa3cdda0b8a..85e1df3d684 100644 --- a/com.unity.render-pipelines.universal/Runtime/DeferredTiler.cs +++ b/com.unity.render-pipelines.universal/Runtime/DeferredTiler.cs @@ -158,7 +158,6 @@ public int GetTileHeaderOffset(int i, int j) return (i + j * m_TileXCount) * m_TileHeaderSize; } - public void Setup(int tileDataCapacity) { if (tileDataCapacity <= 0) @@ -258,8 +257,8 @@ public void PrecomputeTiles(Matrix4x4 proj, bool isOrthographic, int renderWidth // - depth range of the light shape intersecting the tile-frustums is output in the tile list header section // - light indices written out are indexing visible_lights, rather than the array of PrePunctualLights. unsafe public void CullFinalLights(ref NativeArray punctualLights, - ref NativeArray lightIndices, int lightStartIndex, int lightCount, - int istart, int iend, int jstart, int jend) + ref NativeArray lightIndices, int lightStartIndex, int lightCount, + int istart, int iend, int jstart, int jend) { // Interestingly, 2-3% faster when using unsafe arrays. PrePunctualLight* _punctualLights = (PrePunctualLight*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(punctualLights); @@ -269,21 +268,21 @@ unsafe public void CullFinalLights(ref NativeArray punctualLig if (lightCount == 0) { for (int j = jstart; j < jend; ++j) - for (int i = istart; i < iend; ++i) - { - int headerOffset = GetTileHeaderOffset(i, j); - _tileHeaders[headerOffset + 0] = 0; - _tileHeaders[headerOffset + 1] = 0; - _tileHeaders[headerOffset + 2] = 0; - _tileHeaders[headerOffset + 3] = 0; - } + for (int i = istart; i < iend; ++i) + { + int headerOffset = GetTileHeaderOffset(i, j); + _tileHeaders[headerOffset + 0] = 0; + _tileHeaders[headerOffset + 1] = 0; + _tileHeaders[headerOffset + 2] = 0; + _tileHeaders[headerOffset + 3] = 0; + } return; } // Store culled lights in temporary buffer. Additionally store depth range of each light for a given tile too. // the depth range is a 32bit mask, but packed into a 16bits value since the range of the light is continuous // (only need to store first bit enabled, and count of enabled bits). - ushort* tiles = stackalloc ushort[lightCount*2]; + ushort* tiles = stackalloc ushort[lightCount * 2]; float2* depthRanges = stackalloc float2[lightCount]; int maxLightPerTile = 0; // for stats @@ -419,8 +418,8 @@ unsafe public void CullFinalLights(ref NativeArray punctualLig // TODO: finer culling for spot lights unsafe public void CullIntermediateLights(ref NativeArray punctualLights, - ref NativeArray lightIndices, int lightStartIndex, int lightCount, - int istart, int iend, int jstart, int jend) + ref NativeArray lightIndices, int lightStartIndex, int lightCount, + int istart, int iend, int jstart, int jend) { // Interestingly, 2-3% faster when using unsafe arrays. PrePunctualLight* _punctualLights = (PrePunctualLight*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(punctualLights); @@ -430,12 +429,12 @@ unsafe public void CullIntermediateLights(ref NativeArray punc if (lightCount == 0) { for (int j = jstart; j < jend; ++j) - for (int i = istart; i < iend; ++i) - { - int headerOffset = GetTileHeaderOffset(i, j); - _tileHeaders[headerOffset + 0] = 0; - _tileHeaders[headerOffset + 1] = 0; - } + for (int i = istart; i < iend; ++i) + { + int headerOffset = GetTileHeaderOffset(i, j); + _tileHeaders[headerOffset + 0] = 0; + _tileHeaders[headerOffset + 1] = 0; + } return; } @@ -534,9 +533,9 @@ unsafe static bool IntersectionLineSphere(float3 centre, float radius, float3 ra float A = dot(rayDirection, rayDirection); // always >= 0 float B = dot(raySource - centre, rayDirection); float C = dot(raySource, raySource) - + dot(centre, centre) - - (radius * radius) - - 2 * dot(raySource, centre); + + dot(centre, centre) + - (radius * radius) + - 2 * dot(raySource, centre); float discriminant = (B * B) - A * C; if (discriminant > 0) { @@ -560,7 +559,7 @@ static bool Clip(ref PreTile tile, float3 posVS, float radius) { // Simplified clipping code, only deals with 4 clipping planes. // zNear and zFar clipping planes are ignored as presumably the light is already visible to the camera frustum. - + float radiusSq = radius * radius; int insideCount = 0; ClipResult res; @@ -596,7 +595,7 @@ static ClipResult ClipPartial(float4 plane, float4 sidePlaneA, float4 sidePlaneB float3 p = posVS - plane.xyz * d; float rSq = radiusSq - d * d; if (SignedSq(DistanceToPlane(sidePlaneA, p)) >= -rSq - && SignedSq(DistanceToPlane(sidePlaneB, p)) >= -rSq) + && SignedSq(DistanceToPlane(sidePlaneB, p)) >= -rSq) return ClipResult.In; } else // consider as good as completely inside diff --git a/com.unity.render-pipelines.universal/Runtime/Deprecated.cs b/com.unity.render-pipelines.universal/Runtime/Deprecated.cs index f3d357bf119..7d16c82009f 100644 --- a/com.unity.render-pipelines.universal/Runtime/Deprecated.cs +++ b/com.unity.render-pipelines.universal/Runtime/Deprecated.cs @@ -31,13 +31,14 @@ public ShadowCascadesOption shadowCascadeOption { get { - switch(shadowCascadeCount) + switch (shadowCascadeCount) { case 1: return ShadowCascadesOption.NoCascades; case 2: return ShadowCascadesOption.TwoCascades; case 4: return ShadowCascadesOption.FourCascades; default: throw new InvalidOperationException("Cascade count is not compatible with obsolete API, please use shadowCascadeCount instead."); - }; + } + ; } set { diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Dict.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Dict.cs index fd27f9c38fb..957a08bc68d 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Dict.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Dict.cs @@ -35,75 +35,77 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -namespace LibTessDotNet -{ - internal class Dict where TValue : class + namespace LibTessDotNet { - public class Node - { - internal TValue _key; - internal Node _prev, _next; - - public TValue Key { get { return _key; } } - public Node Prev { get { return _prev; } } - public Node Next { get { return _next; } } - } - - public delegate bool LessOrEqual(TValue lhs, TValue rhs); - - private LessOrEqual _leq; - Node _head; - - public Dict(LessOrEqual leq) - { - _leq = leq; - - _head = new Node { _key = null }; - _head._prev = _head; - _head._next = _head; - } - - public Node Insert(TValue key) - { - return InsertBefore(_head, key); - } - - public Node InsertBefore(Node node, TValue key) - { - do { - node = node._prev; - } while (node._key != null && !_leq(node._key, key)); - - var newNode = new Node { _key = key }; - newNode._next = node._next; - node._next._prev = newNode; - newNode._prev = node; - node._next = newNode; - - return newNode; - } - - public Node Find(TValue key) - { - var node = _head; - do { - node = node._next; - } while (node._key != null && !_leq(key, node._key)); - return node; - } - - public Node Min() + internal class Dict where TValue : class { - return _head._next; - } - - public void Remove(Node node) - { - node._next._prev = node._prev; - node._prev._next = node._next; + public class Node + { + internal TValue _key; + internal Node _prev, _next; + + public TValue Key { get { return _key; } } + public Node Prev { get { return _prev; } } + public Node Next { get { return _next; } } + } + + public delegate bool LessOrEqual(TValue lhs, TValue rhs); + + private LessOrEqual _leq; + Node _head; + + public Dict(LessOrEqual leq) + { + _leq = leq; + + _head = new Node { _key = null }; + _head._prev = _head; + _head._next = _head; + } + + public Node Insert(TValue key) + { + return InsertBefore(_head, key); + } + + public Node InsertBefore(Node node, TValue key) + { + do + { + node = node._prev; + } + while (node._key != null && !_leq(node._key, key)); + + var newNode = new Node { _key = key }; + newNode._next = node._next; + node._next._prev = newNode; + newNode._prev = node; + node._next = newNode; + + return newNode; + } + + public Node Find(TValue key) + { + var node = _head; + do + { + node = node._next; + } + while (node._key != null && !_leq(key, node._key)); + return node; + } + + public Node Min() + { + return _head._next; + } + + public void Remove(Node node) + { + node._next._prev = node._prev; + node._prev._next = node._next; + } } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Geom.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Geom.cs index 12d02571946..3627076a464 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Geom.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Geom.cs @@ -1,5 +1,5 @@ /* -** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) +** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** @@ -9,10 +9,10 @@ ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: -** +** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be -** included in all copies or substantial portions of the Software. +** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A @@ -20,7 +20,7 @@ ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. -** +** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. @@ -36,266 +36,266 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -using Real = System.Single; -namespace LibTessDotNet -{ - internal static class Geom + using Real = System.Single; + namespace LibTessDotNet { - public static bool IsWindingInside(WindingRule rule, int n) + internal static class Geom { - switch (rule) + public static bool IsWindingInside(WindingRule rule, int n) { - case WindingRule.EvenOdd: - return (n & 1) == 1; - case WindingRule.NonZero: - return n != 0; - case WindingRule.Positive: - return n > 0; - case WindingRule.Negative: - return n < 0; - case WindingRule.AbsGeqTwo: - return n >= 2 || n <= -2; + switch (rule) + { + case WindingRule.EvenOdd: + return (n & 1) == 1; + case WindingRule.NonZero: + return n != 0; + case WindingRule.Positive: + return n > 0; + case WindingRule.Negative: + return n < 0; + case WindingRule.AbsGeqTwo: + return n >= 2 || n <= -2; + } + throw new Exception("Wrong winding rule"); } - throw new Exception("Wrong winding rule"); - } - public static bool VertCCW(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) - { - return (u._s * (v._t - w._t) + v._s * (w._t - u._t) + w._s * (u._t - v._t)) >= 0.0f; - } - public static bool VertEq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) - { - return lhs._s == rhs._s && lhs._t == rhs._t; - } - public static bool VertLeq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) - { - return (lhs._s < rhs._s) || (lhs._s == rhs._s && lhs._t <= rhs._t); - } + public static bool VertCCW(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) + { + return (u._s * (v._t - w._t) + v._s * (w._t - u._t) + w._s * (u._t - v._t)) >= 0.0f; + } - /// - /// Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), - /// evaluates the t-coord of the edge uw at the s-coord of the vertex v. - /// Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. - /// If uw is vertical (and thus passes thru v), the result is zero. - /// - /// The calculation is extremely accurate and stable, even when v - /// is very close to u or w. In particular if we set v->t = 0 and - /// let r be the negated result (this evaluates (uw)(v->s)), then - /// r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). - /// - public static Real EdgeEval(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) - { - Debug.Assert(VertLeq(u, v) && VertLeq(v, w)); + public static bool VertEq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) + { + return lhs._s == rhs._s && lhs._t == rhs._t; + } - var gapL = v._s - u._s; - var gapR = w._s - v._s; + public static bool VertLeq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) + { + return (lhs._s < rhs._s) || (lhs._s == rhs._s && lhs._t <= rhs._t); + } - if (gapL + gapR > 0.0f) + /// + /// Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), + /// evaluates the t-coord of the edge uw at the s-coord of the vertex v. + /// Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. + /// If uw is vertical (and thus passes thru v), the result is zero. + /// + /// The calculation is extremely accurate and stable, even when v + /// is very close to u or w. In particular if we set v->t = 0 and + /// let r be the negated result (this evaluates (uw)(v->s)), then + /// r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). + /// + public static Real EdgeEval(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { - if (gapL < gapR) - { - return (v._t - u._t) + (u._t - w._t) * (gapL / (gapL + gapR)); - } - else + Debug.Assert(VertLeq(u, v) && VertLeq(v, w)); + + var gapL = v._s - u._s; + var gapR = w._s - v._s; + + if (gapL + gapR > 0.0f) { - return (v._t - w._t) + (w._t - u._t) * (gapR / (gapL + gapR)); + if (gapL < gapR) + { + return (v._t - u._t) + (u._t - w._t) * (gapL / (gapL + gapR)); + } + else + { + return (v._t - w._t) + (w._t - u._t) * (gapR / (gapL + gapR)); + } } + /* vertical line */ + return 0; } - /* vertical line */ - return 0; - } - /// - /// Returns a number whose sign matches EdgeEval(u,v,w) but which - /// is cheaper to evaluate. Returns > 0, == 0 , or < 0 - /// as v is above, on, or below the edge uw. - /// - public static Real EdgeSign(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) - { - Debug.Assert(VertLeq(u, v) && VertLeq(v, w)); + /// + /// Returns a number whose sign matches EdgeEval(u,v,w) but which + /// is cheaper to evaluate. Returns > 0, == 0 , or < 0 + /// as v is above, on, or below the edge uw. + /// + public static Real EdgeSign(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) + { + Debug.Assert(VertLeq(u, v) && VertLeq(v, w)); - var gapL = v._s - u._s; - var gapR = w._s - v._s; + var gapL = v._s - u._s; + var gapR = w._s - v._s; - if (gapL + gapR > 0.0f) - { - return (v._t - w._t) * gapL + (v._t - u._t) * gapR; + if (gapL + gapR > 0.0f) + { + return (v._t - w._t) * gapL + (v._t - u._t) * gapR; + } + /* vertical line */ + return 0; } - /* vertical line */ - return 0; - } - public static bool TransLeq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) - { - return (lhs._t < rhs._t) || (lhs._t == rhs._t && lhs._s <= rhs._s); - } + public static bool TransLeq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) + { + return (lhs._t < rhs._t) || (lhs._t == rhs._t && lhs._s <= rhs._s); + } - public static Real TransEval(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) - { - Debug.Assert(TransLeq(u, v) && TransLeq(v, w)); + public static Real TransEval(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) + { + Debug.Assert(TransLeq(u, v) && TransLeq(v, w)); - var gapL = v._t - u._t; - var gapR = w._t - v._t; + var gapL = v._t - u._t; + var gapR = w._t - v._t; - if (gapL + gapR > 0.0f) - { - if (gapL < gapR) - { - return (v._s - u._s) + (u._s - w._s) * (gapL / (gapL + gapR)); - } - else + if (gapL + gapR > 0.0f) { - return (v._s - w._s) + (w._s - u._s) * (gapR / (gapL + gapR)); + if (gapL < gapR) + { + return (v._s - u._s) + (u._s - w._s) * (gapL / (gapL + gapR)); + } + else + { + return (v._s - w._s) + (w._s - u._s) * (gapR / (gapL + gapR)); + } } + /* vertical line */ + return 0; } - /* vertical line */ - return 0; - } - - public static Real TransSign(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) - { - Debug.Assert(TransLeq(u, v) && TransLeq(v, w)); - var gapL = v._t - u._t; - var gapR = w._t - v._t; - - if (gapL + gapR > 0.0f) + public static Real TransSign(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { - return (v._s - w._s) * gapL + (v._s - u._s) * gapR; - } - /* vertical line */ - return 0; - } + Debug.Assert(TransLeq(u, v) && TransLeq(v, w)); - public static bool EdgeGoesLeft(MeshUtils.Edge e) - { - return VertLeq(e._Dst, e._Org); - } - - public static bool EdgeGoesRight(MeshUtils.Edge e) - { - return VertLeq(e._Org, e._Dst); - } - - public static Real VertL1dist(MeshUtils.Vertex u, MeshUtils.Vertex v) - { - return Math.Abs(u._s - v._s) + Math.Abs(u._t - v._t); - } + var gapL = v._t - u._t; + var gapR = w._t - v._t; - public static void AddWinding(MeshUtils.Edge eDst, MeshUtils.Edge eSrc) - { - eDst._winding += eSrc._winding; - eDst._Sym._winding += eSrc._Sym._winding; - } + if (gapL + gapR > 0.0f) + { + return (v._s - w._s) * gapL + (v._s - u._s) * gapR; + } + /* vertical line */ + return 0; + } - public static Real Interpolate(Real a, Real x, Real b, Real y) - { - if (a < 0.0f) + public static bool EdgeGoesLeft(MeshUtils.Edge e) { - a = 0.0f; + return VertLeq(e._Dst, e._Org); } - if (b < 0.0f) + + public static bool EdgeGoesRight(MeshUtils.Edge e) { - b = 0.0f; + return VertLeq(e._Org, e._Dst); } - return ((a <= b) ? ((b == 0.0f) ? ((x+y) / 2.0f) - : (x + (y-x) * (a/(a+b)))) - : (y + (x-y) * (b/(a+b)))); - } - - static void Swap(ref MeshUtils.Vertex a, ref MeshUtils.Vertex b) - { - var tmp = a; - a = b; - b = tmp; - } - - /// - /// Given edges (o1,d1) and (o2,d2), compute their point of intersection. - /// The computed point is guaranteed to lie in the intersection of the - /// bounding rectangles defined by each edge. - /// - public static void EdgeIntersect(MeshUtils.Vertex o1, MeshUtils.Vertex d1, MeshUtils.Vertex o2, MeshUtils.Vertex d2, MeshUtils.Vertex v) - { - // This is certainly not the most efficient way to find the intersection - // of two line segments, but it is very numerically stable. - // - // Strategy: find the two middle vertices in the VertLeq ordering, - // and interpolate the intersection s-value from these. Then repeat - // using the TransLeq ordering to find the intersection t-value. - if (!VertLeq(o1, d1)) { Swap(ref o1, ref d1); } - if (!VertLeq(o2, d2)) { Swap(ref o2, ref d2); } - if (!VertLeq(o1, o2)) { Swap(ref o1, ref o2); Swap(ref d1, ref d2); } + public static Real VertL1dist(MeshUtils.Vertex u, MeshUtils.Vertex v) + { + return Math.Abs(u._s - v._s) + Math.Abs(u._t - v._t); + } - if (!VertLeq(o2, d1)) + public static void AddWinding(MeshUtils.Edge eDst, MeshUtils.Edge eSrc) { - // Technically, no intersection -- do our best - v._s = (o2._s + d1._s) / 2.0f; + eDst._winding += eSrc._winding; + eDst._Sym._winding += eSrc._Sym._winding; } - else if (VertLeq(d1, d2)) + + public static Real Interpolate(Real a, Real x, Real b, Real y) { - // Interpolate between o2 and d1 - var z1 = EdgeEval(o1, o2, d1); - var z2 = EdgeEval(o2, d1, d2); - if (z1 + z2 < 0.0f) + if (a < 0.0f) { - z1 = -z1; - z2 = -z2; + a = 0.0f; } - v._s = Interpolate(z1, o2._s, z2, d1._s); - } - else - { - // Interpolate between o2 and d2 - var z1 = EdgeSign(o1, o2, d1); - var z2 = -EdgeSign(o1, d2, d1); - if (z1 + z2 < 0.0f) + if (b < 0.0f) { - z1 = -z1; - z2 = -z2; + b = 0.0f; } - v._s = Interpolate(z1, o2._s, z2, d2._s); + return ((a <= b) ? ((b == 0.0f) ? ((x + y) / 2.0f) + : (x + (y - x) * (a / (a + b)))) + : (y + (x - y) * (b / (a + b)))); } - // Now repeat the process for t - - if (!TransLeq(o1, d1)) { Swap(ref o1, ref d1); } - if (!TransLeq(o2, d2)) { Swap(ref o2, ref d2); } - if (!TransLeq(o1, o2)) { Swap(ref o1, ref o2); Swap(ref d1, ref d2); } - - if (!TransLeq(o2, d1)) + static void Swap(ref MeshUtils.Vertex a, ref MeshUtils.Vertex b) { - // Technically, no intersection -- do our best - v._t = (o2._t + d1._t) / 2.0f; + var tmp = a; + a = b; + b = tmp; } - else if (TransLeq(d1, d2)) + + /// + /// Given edges (o1,d1) and (o2,d2), compute their point of intersection. + /// The computed point is guaranteed to lie in the intersection of the + /// bounding rectangles defined by each edge. + /// + public static void EdgeIntersect(MeshUtils.Vertex o1, MeshUtils.Vertex d1, MeshUtils.Vertex o2, MeshUtils.Vertex d2, MeshUtils.Vertex v) { - // Interpolate between o2 and d1 - var z1 = TransEval(o1, o2, d1); - var z2 = TransEval(o2, d1, d2); - if (z1 + z2 < 0.0f) + // This is certainly not the most efficient way to find the intersection + // of two line segments, but it is very numerically stable. + // + // Strategy: find the two middle vertices in the VertLeq ordering, + // and interpolate the intersection s-value from these. Then repeat + // using the TransLeq ordering to find the intersection t-value. + + if (!VertLeq(o1, d1)) { Swap(ref o1, ref d1); } + if (!VertLeq(o2, d2)) { Swap(ref o2, ref d2); } + if (!VertLeq(o1, o2)) { Swap(ref o1, ref o2); Swap(ref d1, ref d2); } + + if (!VertLeq(o2, d1)) { - z1 = -z1; - z2 = -z2; + // Technically, no intersection -- do our best + v._s = (o2._s + d1._s) / 2.0f; } - v._t = Interpolate(z1, o2._t, z2, d1._t); - } - else - { - // Interpolate between o2 and d2 - var z1 = TransSign(o1, o2, d1); - var z2 = -TransSign(o1, d2, d1); - if (z1 + z2 < 0.0f) + else if (VertLeq(d1, d2)) + { + // Interpolate between o2 and d1 + var z1 = EdgeEval(o1, o2, d1); + var z2 = EdgeEval(o2, d1, d2); + if (z1 + z2 < 0.0f) + { + z1 = -z1; + z2 = -z2; + } + v._s = Interpolate(z1, o2._s, z2, d1._s); + } + else { - z1 = -z1; - z2 = -z2; + // Interpolate between o2 and d2 + var z1 = EdgeSign(o1, o2, d1); + var z2 = -EdgeSign(o1, d2, d1); + if (z1 + z2 < 0.0f) + { + z1 = -z1; + z2 = -z2; + } + v._s = Interpolate(z1, o2._s, z2, d2._s); + } + + // Now repeat the process for t + + if (!TransLeq(o1, d1)) { Swap(ref o1, ref d1); } + if (!TransLeq(o2, d2)) { Swap(ref o2, ref d2); } + if (!TransLeq(o1, o2)) { Swap(ref o1, ref o2); Swap(ref d1, ref d2); } + + if (!TransLeq(o2, d1)) + { + // Technically, no intersection -- do our best + v._t = (o2._t + d1._t) / 2.0f; + } + else if (TransLeq(d1, d2)) + { + // Interpolate between o2 and d1 + var z1 = TransEval(o1, o2, d1); + var z2 = TransEval(o2, d1, d2); + if (z1 + z2 < 0.0f) + { + z1 = -z1; + z2 = -z2; + } + v._t = Interpolate(z1, o2._t, z2, d1._t); + } + else + { + // Interpolate between o2 and d2 + var z1 = TransSign(o1, o2, d1); + var z2 = -TransSign(o1, d2, d1); + if (z1 + z2 < 0.0f) + { + z1 = -z1; + z2 = -z2; + } + v._t = Interpolate(z1, o2._t, z2, d2._t); } - v._t = Interpolate(z1, o2._t, z2, d2._t); } } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Mesh.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Mesh.cs index a0736660f3f..f945c088e11 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Mesh.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Mesh.cs @@ -1,5 +1,5 @@ /* -** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) +** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** @@ -9,10 +9,10 @@ ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: -** +** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be -** included in all copies or substantial portions of the Software. +** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A @@ -20,7 +20,7 @@ ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. -** +** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. @@ -36,465 +36,468 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -namespace LibTessDotNet -{ - internal class Mesh : MeshUtils.Pooled + namespace LibTessDotNet { - internal MeshUtils.Vertex _vHead; - internal MeshUtils.Face _fHead; - internal MeshUtils.Edge _eHead, _eHeadSym; - - public Mesh() + internal class Mesh : MeshUtils.Pooled { - var v = _vHead = MeshUtils.Vertex.Create(); - var f = _fHead = MeshUtils.Face.Create(); - - var pair = MeshUtils.EdgePair.Create(); - var e = _eHead = pair._e; - var eSym = _eHeadSym = pair._eSym; - - v._next = v._prev = v; - v._anEdge = null; - - f._next = f._prev = f; - f._anEdge = null; - f._trail = null; - f._marked = false; - f._inside = false; - - e._next = e; - e._Sym = eSym; - e._Onext = null; - e._Lnext = null; - e._Org = null; - e._Lface = null; - e._winding = 0; - e._activeRegion = null; - - eSym._next = eSym; - eSym._Sym = e; - eSym._Onext = null; - eSym._Lnext = null; - eSym._Org = null; - eSym._Lface = null; - eSym._winding = 0; - eSym._activeRegion = null; - } - - public override void Reset() - { - _vHead = null; - _fHead = null; - _eHead = _eHeadSym = null; - } + internal MeshUtils.Vertex _vHead; + internal MeshUtils.Face _fHead; + internal MeshUtils.Edge _eHead, _eHeadSym; - public override void OnFree() - { - for (MeshUtils.Face f = _fHead._next, fNext = _fHead; f != _fHead; f = fNext) - { - fNext = f._next; - f.Free(); - } - for (MeshUtils.Vertex v = _vHead._next, vNext = _vHead; v != _vHead; v = vNext) - { - vNext = v._next; - v.Free(); - } - for (MeshUtils.Edge e = _eHead._next, eNext = _eHead; e != _eHead; e = eNext) + public Mesh() { - eNext = e._next; - e.Free(); + var v = _vHead = MeshUtils.Vertex.Create(); + var f = _fHead = MeshUtils.Face.Create(); + + var pair = MeshUtils.EdgePair.Create(); + var e = _eHead = pair._e; + var eSym = _eHeadSym = pair._eSym; + + v._next = v._prev = v; + v._anEdge = null; + + f._next = f._prev = f; + f._anEdge = null; + f._trail = null; + f._marked = false; + f._inside = false; + + e._next = e; + e._Sym = eSym; + e._Onext = null; + e._Lnext = null; + e._Org = null; + e._Lface = null; + e._winding = 0; + e._activeRegion = null; + + eSym._next = eSym; + eSym._Sym = e; + eSym._Onext = null; + eSym._Lnext = null; + eSym._Org = null; + eSym._Lface = null; + eSym._winding = 0; + eSym._activeRegion = null; } - } - - /// - /// Creates one edge, two vertices and a loop (face). - /// The loop consists of the two new half-edges. - /// - public MeshUtils.Edge MakeEdge() - { - var e = MeshUtils.MakeEdge(_eHead); - MeshUtils.MakeVertex(e, _vHead); - MeshUtils.MakeVertex(e._Sym, _vHead); - MeshUtils.MakeFace(e, _fHead); - - return e; - } - - /// - /// Splice is the basic operation for changing the - /// mesh connectivity and topology. It changes the mesh so that - /// eOrg->Onext = OLD( eDst->Onext ) - /// eDst->Onext = OLD( eOrg->Onext ) - /// where OLD(...) means the value before the meshSplice operation. - /// - /// This can have two effects on the vertex structure: - /// - if eOrg->Org != eDst->Org, the two vertices are merged together - /// - if eOrg->Org == eDst->Org, the origin is split into two vertices - /// In both cases, eDst->Org is changed and eOrg->Org is untouched. - /// - /// Similarly (and independently) for the face structure, - /// - if eOrg->Lface == eDst->Lface, one loop is split into two - /// - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one - /// In both cases, eDst->Lface is changed and eOrg->Lface is unaffected. - /// - /// Some special cases: - /// If eDst == eOrg, the operation has no effect. - /// If eDst == eOrg->Lnext, the new face will have a single edge. - /// If eDst == eOrg->Lprev, the old face will have a single edge. - /// If eDst == eOrg->Onext, the new vertex will have a single edge. - /// If eDst == eOrg->Oprev, the old vertex will have a single edge. - /// - public void Splice(MeshUtils.Edge eOrg, MeshUtils.Edge eDst) - { - if (eOrg == eDst) + public override void Reset() { - return; + _vHead = null; + _fHead = null; + _eHead = _eHeadSym = null; } - bool joiningVertices = false; - if (eDst._Org != eOrg._Org) + public override void OnFree() { - // We are merging two disjoint vertices -- destroy eDst->Org - joiningVertices = true; - MeshUtils.KillVertex(eDst._Org, eOrg._Org); + for (MeshUtils.Face f = _fHead._next, fNext = _fHead; f != _fHead; f = fNext) + { + fNext = f._next; + f.Free(); + } + for (MeshUtils.Vertex v = _vHead._next, vNext = _vHead; v != _vHead; v = vNext) + { + vNext = v._next; + v.Free(); + } + for (MeshUtils.Edge e = _eHead._next, eNext = _eHead; e != _eHead; e = eNext) + { + eNext = e._next; + e.Free(); + } } - bool joiningLoops = false; - if (eDst._Lface != eOrg._Lface) + + /// + /// Creates one edge, two vertices and a loop (face). + /// The loop consists of the two new half-edges. + /// + public MeshUtils.Edge MakeEdge() { - // We are connecting two disjoint loops -- destroy eDst->Lface - joiningLoops = true; - MeshUtils.KillFace(eDst._Lface, eOrg._Lface); - } + var e = MeshUtils.MakeEdge(_eHead); - // Change the edge structure - MeshUtils.Splice(eDst, eOrg); + MeshUtils.MakeVertex(e, _vHead); + MeshUtils.MakeVertex(e._Sym, _vHead); + MeshUtils.MakeFace(e, _fHead); - if (!joiningVertices) - { - // We split one vertex into two -- the new vertex is eDst->Org. - // Make sure the old vertex points to a valid half-edge. - MeshUtils.MakeVertex(eDst, eOrg._Org); - eOrg._Org._anEdge = eOrg; + return e; } - if (!joiningLoops) + + /// + /// Splice is the basic operation for changing the + /// mesh connectivity and topology. It changes the mesh so that + /// eOrg->Onext = OLD( eDst->Onext ) + /// eDst->Onext = OLD( eOrg->Onext ) + /// where OLD(...) means the value before the meshSplice operation. + /// + /// This can have two effects on the vertex structure: + /// - if eOrg->Org != eDst->Org, the two vertices are merged together + /// - if eOrg->Org == eDst->Org, the origin is split into two vertices + /// In both cases, eDst->Org is changed and eOrg->Org is untouched. + /// + /// Similarly (and independently) for the face structure, + /// - if eOrg->Lface == eDst->Lface, one loop is split into two + /// - if eOrg->Lface != eDst->Lface, two distinct loops are joined into one + /// In both cases, eDst->Lface is changed and eOrg->Lface is unaffected. + /// + /// Some special cases: + /// If eDst == eOrg, the operation has no effect. + /// If eDst == eOrg->Lnext, the new face will have a single edge. + /// If eDst == eOrg->Lprev, the old face will have a single edge. + /// If eDst == eOrg->Onext, the new vertex will have a single edge. + /// If eDst == eOrg->Oprev, the old vertex will have a single edge. + /// + public void Splice(MeshUtils.Edge eOrg, MeshUtils.Edge eDst) { - // We split one loop into two -- the new loop is eDst->Lface. - // Make sure the old face points to a valid half-edge. - MeshUtils.MakeFace(eDst, eOrg._Lface); - eOrg._Lface._anEdge = eOrg; - } - } + if (eOrg == eDst) + { + return; + } - /// - /// Removes the edge eDel. There are several cases: - /// if (eDel->Lface != eDel->Rface), we join two loops into one; the loop - /// eDel->Lface is deleted. Otherwise, we are splitting one loop into two; - /// the newly created loop will contain eDel->Dst. If the deletion of eDel - /// would create isolated vertices, those are deleted as well. - /// - public void Delete(MeshUtils.Edge eDel) - { - var eDelSym = eDel._Sym; + bool joiningVertices = false; + if (eDst._Org != eOrg._Org) + { + // We are merging two disjoint vertices -- destroy eDst->Org + joiningVertices = true; + MeshUtils.KillVertex(eDst._Org, eOrg._Org); + } + bool joiningLoops = false; + if (eDst._Lface != eOrg._Lface) + { + // We are connecting two disjoint loops -- destroy eDst->Lface + joiningLoops = true; + MeshUtils.KillFace(eDst._Lface, eOrg._Lface); + } - // First step: disconnect the origin vertex eDel->Org. We make all - // changes to get a consistent mesh in this "intermediate" state. + // Change the edge structure + MeshUtils.Splice(eDst, eOrg); - bool joiningLoops = false; - if (eDel._Lface != eDel._Rface) - { - // We are joining two loops into one -- remove the left face - joiningLoops = true; - MeshUtils.KillFace(eDel._Lface, eDel._Rface); + if (!joiningVertices) + { + // We split one vertex into two -- the new vertex is eDst->Org. + // Make sure the old vertex points to a valid half-edge. + MeshUtils.MakeVertex(eDst, eOrg._Org); + eOrg._Org._anEdge = eOrg; + } + if (!joiningLoops) + { + // We split one loop into two -- the new loop is eDst->Lface. + // Make sure the old face points to a valid half-edge. + MeshUtils.MakeFace(eDst, eOrg._Lface); + eOrg._Lface._anEdge = eOrg; + } } - if (eDel._Onext == eDel) + /// + /// Removes the edge eDel. There are several cases: + /// if (eDel->Lface != eDel->Rface), we join two loops into one; the loop + /// eDel->Lface is deleted. Otherwise, we are splitting one loop into two; + /// the newly created loop will contain eDel->Dst. If the deletion of eDel + /// would create isolated vertices, those are deleted as well. + /// + public void Delete(MeshUtils.Edge eDel) { - MeshUtils.KillVertex(eDel._Org, null); - } - else - { - // Make sure that eDel->Org and eDel->Rface point to valid half-edges - eDel._Rface._anEdge = eDel._Oprev; - eDel._Org._anEdge = eDel._Onext; + var eDelSym = eDel._Sym; - MeshUtils.Splice(eDel, eDel._Oprev); + // First step: disconnect the origin vertex eDel->Org. We make all + // changes to get a consistent mesh in this "intermediate" state. - if (!joiningLoops) + bool joiningLoops = false; + if (eDel._Lface != eDel._Rface) { - // We are splitting one loop into two -- create a new loop for eDel. - MeshUtils.MakeFace(eDel, eDel._Lface); + // We are joining two loops into one -- remove the left face + joiningLoops = true; + MeshUtils.KillFace(eDel._Lface, eDel._Rface); } - } - // Claim: the mesh is now in a consistent state, except that eDel->Org - // may have been deleted. Now we disconnect eDel->Dst. + if (eDel._Onext == eDel) + { + MeshUtils.KillVertex(eDel._Org, null); + } + else + { + // Make sure that eDel->Org and eDel->Rface point to valid half-edges + eDel._Rface._anEdge = eDel._Oprev; + eDel._Org._anEdge = eDel._Onext; + + MeshUtils.Splice(eDel, eDel._Oprev); - if (eDelSym._Onext == eDelSym) - { - MeshUtils.KillVertex(eDelSym._Org, null); - MeshUtils.KillFace(eDelSym._Lface, null); - } - else - { - // Make sure that eDel->Dst and eDel->Lface point to valid half-edges - eDel._Lface._anEdge = eDelSym._Oprev; - eDelSym._Org._anEdge = eDelSym._Onext; - MeshUtils.Splice(eDelSym, eDelSym._Oprev); - } + if (!joiningLoops) + { + // We are splitting one loop into two -- create a new loop for eDel. + MeshUtils.MakeFace(eDel, eDel._Lface); + } + } - // Any isolated vertices or faces have already been freed. - MeshUtils.KillEdge(eDel); - } + // Claim: the mesh is now in a consistent state, except that eDel->Org + // may have been deleted. Now we disconnect eDel->Dst. - /// - /// Creates a new edge such that eNew == eOrg.Lnext and eNew.Dst is a newly created vertex. - /// eOrg and eNew will have the same left face. - /// - public MeshUtils.Edge AddEdgeVertex(MeshUtils.Edge eOrg) - { - var eNew = MeshUtils.MakeEdge(eOrg); - var eNewSym = eNew._Sym; + if (eDelSym._Onext == eDelSym) + { + MeshUtils.KillVertex(eDelSym._Org, null); + MeshUtils.KillFace(eDelSym._Lface, null); + } + else + { + // Make sure that eDel->Dst and eDel->Lface point to valid half-edges + eDel._Lface._anEdge = eDelSym._Oprev; + eDelSym._Org._anEdge = eDelSym._Onext; + MeshUtils.Splice(eDelSym, eDelSym._Oprev); + } - // Connect the new edge appropriately - MeshUtils.Splice(eNew, eOrg._Lnext); + // Any isolated vertices or faces have already been freed. + MeshUtils.KillEdge(eDel); + } - // Set vertex and face information - eNew._Org = eOrg._Dst; - MeshUtils.MakeVertex(eNewSym, eNew._Org); - eNew._Lface = eNewSym._Lface = eOrg._Lface; + /// + /// Creates a new edge such that eNew == eOrg.Lnext and eNew.Dst is a newly created vertex. + /// eOrg and eNew will have the same left face. + /// + public MeshUtils.Edge AddEdgeVertex(MeshUtils.Edge eOrg) + { + var eNew = MeshUtils.MakeEdge(eOrg); + var eNewSym = eNew._Sym; - return eNew; - } + // Connect the new edge appropriately + MeshUtils.Splice(eNew, eOrg._Lnext); - /// - /// Splits eOrg into two edges eOrg and eNew such that eNew == eOrg.Lnext. - /// The new vertex is eOrg.Dst == eNew.Org. - /// eOrg and eNew will have the same left face. - /// - public MeshUtils.Edge SplitEdge(MeshUtils.Edge eOrg) - { - var eTmp = AddEdgeVertex(eOrg); - var eNew = eTmp._Sym; + // Set vertex and face information + eNew._Org = eOrg._Dst; + MeshUtils.MakeVertex(eNewSym, eNew._Org); + eNew._Lface = eNewSym._Lface = eOrg._Lface; - // Disconnect eOrg from eOrg->Dst and connect it to eNew->Org - MeshUtils.Splice(eOrg._Sym, eOrg._Sym._Oprev); - MeshUtils.Splice(eOrg._Sym, eNew); + return eNew; + } - // Set the vertex and face information - eOrg._Dst = eNew._Org; - eNew._Dst._anEdge = eNew._Sym; // may have pointed to eOrg->Sym - eNew._Rface = eOrg._Rface; - eNew._winding = eOrg._winding; // copy old winding information - eNew._Sym._winding = eOrg._Sym._winding; + /// + /// Splits eOrg into two edges eOrg and eNew such that eNew == eOrg.Lnext. + /// The new vertex is eOrg.Dst == eNew.Org. + /// eOrg and eNew will have the same left face. + /// + public MeshUtils.Edge SplitEdge(MeshUtils.Edge eOrg) + { + var eTmp = AddEdgeVertex(eOrg); + var eNew = eTmp._Sym; - return eNew; - } + // Disconnect eOrg from eOrg->Dst and connect it to eNew->Org + MeshUtils.Splice(eOrg._Sym, eOrg._Sym._Oprev); + MeshUtils.Splice(eOrg._Sym, eNew); - /// - /// Creates a new edge from eOrg->Dst to eDst->Org, and returns the corresponding half-edge eNew. - /// If eOrg->Lface == eDst->Lface, this splits one loop into two, - /// and the newly created loop is eNew->Lface. Otherwise, two disjoint - /// loops are merged into one, and the loop eDst->Lface is destroyed. - /// - /// If (eOrg == eDst), the new face will have only two edges. - /// If (eOrg->Lnext == eDst), the old face is reduced to a single edge. - /// If (eOrg->Lnext->Lnext == eDst), the old face is reduced to two edges. - /// - public MeshUtils.Edge Connect(MeshUtils.Edge eOrg, MeshUtils.Edge eDst) - { - var eNew = MeshUtils.MakeEdge(eOrg); - var eNewSym = eNew._Sym; + // Set the vertex and face information + eOrg._Dst = eNew._Org; + eNew._Dst._anEdge = eNew._Sym; // may have pointed to eOrg->Sym + eNew._Rface = eOrg._Rface; + eNew._winding = eOrg._winding; // copy old winding information + eNew._Sym._winding = eOrg._Sym._winding; - bool joiningLoops = false; - if (eDst._Lface != eOrg._Lface) - { - // We are connecting two disjoint loops -- destroy eDst->Lface - joiningLoops = true; - MeshUtils.KillFace(eDst._Lface, eOrg._Lface); + return eNew; } - // Connect the new edge appropriately - MeshUtils.Splice(eNew, eOrg._Lnext); - MeshUtils.Splice(eNewSym, eDst); + /// + /// Creates a new edge from eOrg->Dst to eDst->Org, and returns the corresponding half-edge eNew. + /// If eOrg->Lface == eDst->Lface, this splits one loop into two, + /// and the newly created loop is eNew->Lface. Otherwise, two disjoint + /// loops are merged into one, and the loop eDst->Lface is destroyed. + /// + /// If (eOrg == eDst), the new face will have only two edges. + /// If (eOrg->Lnext == eDst), the old face is reduced to a single edge. + /// If (eOrg->Lnext->Lnext == eDst), the old face is reduced to two edges. + /// + public MeshUtils.Edge Connect(MeshUtils.Edge eOrg, MeshUtils.Edge eDst) + { + var eNew = MeshUtils.MakeEdge(eOrg); + var eNewSym = eNew._Sym; - // Set the vertex and face information - eNew._Org = eOrg._Dst; - eNewSym._Org = eDst._Org; - eNew._Lface = eNewSym._Lface = eOrg._Lface; + bool joiningLoops = false; + if (eDst._Lface != eOrg._Lface) + { + // We are connecting two disjoint loops -- destroy eDst->Lface + joiningLoops = true; + MeshUtils.KillFace(eDst._Lface, eOrg._Lface); + } - // Make sure the old face points to a valid half-edge - eOrg._Lface._anEdge = eNewSym; + // Connect the new edge appropriately + MeshUtils.Splice(eNew, eOrg._Lnext); + MeshUtils.Splice(eNewSym, eDst); - if (!joiningLoops) - { - MeshUtils.MakeFace(eNew, eOrg._Lface); - } + // Set the vertex and face information + eNew._Org = eOrg._Dst; + eNewSym._Org = eDst._Org; + eNew._Lface = eNewSym._Lface = eOrg._Lface; - return eNew; - } + // Make sure the old face points to a valid half-edge + eOrg._Lface._anEdge = eNewSym; - /// - /// Destroys a face and removes it from the global face list. All edges of - /// fZap will have a NULL pointer as their left face. Any edges which - /// also have a NULL pointer as their right face are deleted entirely - /// (along with any isolated vertices this produces). - /// An entire mesh can be deleted by zapping its faces, one at a time, - /// in any order. Zapped faces cannot be used in further mesh operations! - /// - public void ZapFace(MeshUtils.Face fZap) - { - var eStart = fZap._anEdge; + if (!joiningLoops) + { + MeshUtils.MakeFace(eNew, eOrg._Lface); + } - // walk around face, deleting edges whose right face is also NULL - var eNext = eStart._Lnext; - MeshUtils.Edge e, eSym; - do { - e = eNext; - eNext = e._Lnext; + return eNew; + } - e._Lface = null; - if (e._Rface == null) + /// + /// Destroys a face and removes it from the global face list. All edges of + /// fZap will have a NULL pointer as their left face. Any edges which + /// also have a NULL pointer as their right face are deleted entirely + /// (along with any isolated vertices this produces). + /// An entire mesh can be deleted by zapping its faces, one at a time, + /// in any order. Zapped faces cannot be used in further mesh operations! + /// + public void ZapFace(MeshUtils.Face fZap) + { + var eStart = fZap._anEdge; + + // walk around face, deleting edges whose right face is also NULL + var eNext = eStart._Lnext; + MeshUtils.Edge e, eSym; + do { - // delete the edge -- see TESSmeshDelete above + e = eNext; + eNext = e._Lnext; - if (e._Onext == e) + e._Lface = null; + if (e._Rface == null) { - MeshUtils.KillVertex(e._Org, null); - } - else - { - // Make sure that e._Org points to a valid half-edge - e._Org._anEdge = e._Onext; - MeshUtils.Splice(e, e._Oprev); - } - eSym = e._Sym; - if (eSym._Onext == eSym) - { - MeshUtils.KillVertex(eSym._Org, null); - } - else - { - // Make sure that eSym._Org points to a valid half-edge - eSym._Org._anEdge = eSym._Onext; - MeshUtils.Splice(eSym, eSym._Oprev); + // delete the edge -- see TESSmeshDelete above + + if (e._Onext == e) + { + MeshUtils.KillVertex(e._Org, null); + } + else + { + // Make sure that e._Org points to a valid half-edge + e._Org._anEdge = e._Onext; + MeshUtils.Splice(e, e._Oprev); + } + eSym = e._Sym; + if (eSym._Onext == eSym) + { + MeshUtils.KillVertex(eSym._Org, null); + } + else + { + // Make sure that eSym._Org points to a valid half-edge + eSym._Org._anEdge = eSym._Onext; + MeshUtils.Splice(eSym, eSym._Oprev); + } + MeshUtils.KillEdge(e); } - MeshUtils.KillEdge(e); } - } while (e != eStart); + while (e != eStart); - /* delete from circular doubly-linked list */ - var fPrev = fZap._prev; - var fNext = fZap._next; - fNext._prev = fPrev; - fPrev._next = fNext; + /* delete from circular doubly-linked list */ + var fPrev = fZap._prev; + var fNext = fZap._next; + fNext._prev = fPrev; + fPrev._next = fNext; - fZap.Free(); - } + fZap.Free(); + } - public void MergeConvexFaces(int maxVertsPerFace) - { - for (var f = _fHead._next; f != _fHead; f = f._next) + public void MergeConvexFaces(int maxVertsPerFace) { - // Skip faces which are outside the result - if (!f._inside) + for (var f = _fHead._next; f != _fHead; f = f._next) { - continue; - } - - var eCur = f._anEdge; - var vStart = eCur._Org; + // Skip faces which are outside the result + if (!f._inside) + { + continue; + } - while (true) - { - var eNext = eCur._Lnext; - var eSym = eCur._Sym; + var eCur = f._anEdge; + var vStart = eCur._Org; - if (eSym != null && eSym._Lface != null && eSym._Lface._inside) + while (true) { - // Try to merge the neighbour faces if the resulting polygons - // does not exceed maximum number of vertices. - int curNv = f.VertsCount; - int symNv = eSym._Lface.VertsCount; - if ((curNv + symNv - 2) <= maxVertsPerFace) + var eNext = eCur._Lnext; + var eSym = eCur._Sym; + + if (eSym != null && eSym._Lface != null && eSym._Lface._inside) { - // Merge if the resulting poly is convex. - if (Geom.VertCCW(eCur._Lprev._Org, eCur._Org, eSym._Lnext._Lnext._Org) && - Geom.VertCCW(eSym._Lprev._Org, eSym._Org, eCur._Lnext._Lnext._Org)) + // Try to merge the neighbour faces if the resulting polygons + // does not exceed maximum number of vertices. + int curNv = f.VertsCount; + int symNv = eSym._Lface.VertsCount; + if ((curNv + symNv - 2) <= maxVertsPerFace) { - eNext = eSym._Lnext; - Delete(eSym); - eCur = null; + // Merge if the resulting poly is convex. + if (Geom.VertCCW(eCur._Lprev._Org, eCur._Org, eSym._Lnext._Lnext._Org) && + Geom.VertCCW(eSym._Lprev._Org, eSym._Org, eCur._Lnext._Lnext._Org)) + { + eNext = eSym._Lnext; + Delete(eSym); + eCur = null; + } } } - } - if (eCur != null && eCur._Lnext._Org == vStart) - break; + if (eCur != null && eCur._Lnext._Org == vStart) + break; - // Continue to next edge. - eCur = eNext; + // Continue to next edge. + eCur = eNext; + } } } - } - [Conditional("DEBUG")] - public void Check() - { - MeshUtils.Edge e; - - MeshUtils.Face fPrev = _fHead, f; - for (fPrev = _fHead; (f = fPrev._next) != _fHead; fPrev = f) + [Conditional("DEBUG")] + public void Check() { - e = f._anEdge; - do { - Debug.Assert(e._Sym != e); - Debug.Assert(e._Sym._Sym == e); - Debug.Assert(e._Lnext._Onext._Sym == e); - Debug.Assert(e._Onext._Sym._Lnext == e); - Debug.Assert(e._Lface == f); - e = e._Lnext; - } while (e != f._anEdge); - } - Debug.Assert(f._prev == fPrev && f._anEdge == null); + MeshUtils.Edge e; - MeshUtils.Vertex vPrev = _vHead, v; - for (vPrev = _vHead; (v = vPrev._next) != _vHead; vPrev = v) - { - Debug.Assert(v._prev == vPrev); - e = v._anEdge; - do + MeshUtils.Face fPrev = _fHead, f; + for (fPrev = _fHead; (f = fPrev._next) != _fHead; fPrev = f) + { + e = f._anEdge; + do + { + Debug.Assert(e._Sym != e); + Debug.Assert(e._Sym._Sym == e); + Debug.Assert(e._Lnext._Onext._Sym == e); + Debug.Assert(e._Onext._Sym._Lnext == e); + Debug.Assert(e._Lface == f); + e = e._Lnext; + } + while (e != f._anEdge); + } + Debug.Assert(f._prev == fPrev && f._anEdge == null); + + MeshUtils.Vertex vPrev = _vHead, v; + for (vPrev = _vHead; (v = vPrev._next) != _vHead; vPrev = v) + { + Debug.Assert(v._prev == vPrev); + e = v._anEdge; + do + { + Debug.Assert(e._Sym != e); + Debug.Assert(e._Sym._Sym == e); + Debug.Assert(e._Lnext._Onext._Sym == e); + Debug.Assert(e._Onext._Sym._Lnext == e); + Debug.Assert(e._Org == v); + e = e._Onext; + } + while (e != v._anEdge); + } + Debug.Assert(v._prev == vPrev && v._anEdge == null); + + MeshUtils.Edge ePrev = _eHead; + for (ePrev = _eHead; (e = ePrev._next) != _eHead; ePrev = e) { + Debug.Assert(e._Sym._next == ePrev._Sym); Debug.Assert(e._Sym != e); Debug.Assert(e._Sym._Sym == e); + Debug.Assert(e._Org != null); + Debug.Assert(e._Dst != null); Debug.Assert(e._Lnext._Onext._Sym == e); Debug.Assert(e._Onext._Sym._Lnext == e); - Debug.Assert(e._Org == v); - e = e._Onext; - } while (e != v._anEdge); - } - Debug.Assert(v._prev == vPrev && v._anEdge == null); - - MeshUtils.Edge ePrev = _eHead; - for (ePrev = _eHead; (e = ePrev._next) != _eHead; ePrev = e) - { - Debug.Assert(e._Sym._next == ePrev._Sym); - Debug.Assert(e._Sym != e); - Debug.Assert(e._Sym._Sym == e); - Debug.Assert(e._Org != null); - Debug.Assert(e._Dst != null); - Debug.Assert(e._Lnext._Onext._Sym == e); - Debug.Assert(e._Onext._Sym._Lnext == e); + } + Debug.Assert(e._Sym._next == ePrev._Sym + && e._Sym == _eHeadSym + && e._Sym._Sym == e + && e._Org == null && e._Dst == null + && e._Lface == null && e._Rface == null); } - Debug.Assert(e._Sym._next == ePrev._Sym - && e._Sym == _eHeadSym - && e._Sym._Sym == e - && e._Org == null && e._Dst == null - && e._Lface == null && e._Rface == null); } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/MeshUtils.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/MeshUtils.cs index 801215fdd22..0f86d004f65 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/MeshUtils.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/MeshUtils.cs @@ -38,86 +38,85 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -using Real = System.Single; -namespace LibTessDotNet -{ - internal struct Vec3 + using Real = System.Single; + namespace LibTessDotNet { - public readonly static Vec3 Zero = new Vec3(); + internal struct Vec3 + { + public readonly static Vec3 Zero = new Vec3(); - public Real X, Y, Z; + public Real X, Y, Z; - public Real this[int index] - { - get + public Real this[int index] { - if (index == 0) return X; - if (index == 1) return Y; - if (index == 2) return Z; - throw new IndexOutOfRangeException(); + get + { + if (index == 0) return X; + if (index == 1) return Y; + if (index == 2) return Z; + throw new IndexOutOfRangeException(); + } + set + { + if (index == 0) X = value; + else if (index == 1) Y = value; + else if (index == 2) Z = value; + else throw new IndexOutOfRangeException(); + } } - set + + public static void Sub(ref Vec3 lhs, ref Vec3 rhs, out Vec3 result) { - if (index == 0) X = value; - else if (index == 1) Y = value; - else if (index == 2) Z = value; - else throw new IndexOutOfRangeException(); + result.X = lhs.X - rhs.X; + result.Y = lhs.Y - rhs.Y; + result.Z = lhs.Z - rhs.Z; } - } - public static void Sub(ref Vec3 lhs, ref Vec3 rhs, out Vec3 result) - { - result.X = lhs.X - rhs.X; - result.Y = lhs.Y - rhs.Y; - result.Z = lhs.Z - rhs.Z; - } + public static void Neg(ref Vec3 v) + { + v.X = -v.X; + v.Y = -v.Y; + v.Z = -v.Z; + } - public static void Neg(ref Vec3 v) - { - v.X = -v.X; - v.Y = -v.Y; - v.Z = -v.Z; - } + public static void Dot(ref Vec3 u, ref Vec3 v, out Real dot) + { + dot = u.X * v.X + u.Y * v.Y + u.Z * v.Z; + } - public static void Dot(ref Vec3 u, ref Vec3 v, out Real dot) - { - dot = u.X * v.X + u.Y * v.Y + u.Z * v.Z; - } + public static void Normalize(ref Vec3 v) + { + var len = v.X * v.X + v.Y * v.Y + v.Z * v.Z; + Debug.Assert(len >= 0.0f); + len = 1.0f / (Real)Math.Sqrt(len); + v.X *= len; + v.Y *= len; + v.Z *= len; + } - public static void Normalize(ref Vec3 v) - { - var len = v.X * v.X + v.Y * v.Y + v.Z * v.Z; - Debug.Assert(len >= 0.0f); - len = 1.0f / (Real)Math.Sqrt(len); - v.X *= len; - v.Y *= len; - v.Z *= len; - } + public static int LongAxis(ref Vec3 v) + { + int i = 0; + if (Math.Abs(v.Y) > Math.Abs(v.X)) i = 1; + if (Math.Abs(v.Z) > Math.Abs(i == 0 ? v.X : v.Y)) i = 2; + return i; + } - public static int LongAxis(ref Vec3 v) - { - int i = 0; - if (Math.Abs(v.Y) > Math.Abs(v.X)) i = 1; - if (Math.Abs(v.Z) > Math.Abs(i == 0 ? v.X : v.Y)) i = 2; - return i; + public override string ToString() + { + return string.Format("{0}, {1}, {2}", X, Y, Z); + } } - public override string ToString() + internal static class MeshUtils { - return string.Format("{0}, {1}, {2}", X, Y, Z); - } - } - - internal static class MeshUtils - { - public const int Undef = ~0; + public const int Undef = ~0; public abstract class Pooled where T : Pooled, new() { private static Stack _stack; public abstract void Reset(); - public virtual void OnFree() { } + public virtual void OnFree() {} public static T Create() { @@ -141,326 +140,336 @@ public void Free() } public class Vertex : Pooled - { - internal Vertex _prev, _next; - internal Edge _anEdge; + { + internal Vertex _prev, _next; + internal Edge _anEdge; - internal Vec3 _coords; - internal Real _s, _t; - internal PQHandle _pqHandle; - internal int _n; - internal object _data; + internal Vec3 _coords; + internal Real _s, _t; + internal PQHandle _pqHandle; + internal int _n; + internal object _data; - public override void Reset() - { - _prev = _next = null; - _anEdge = null; - _coords = Vec3.Zero; - _s = 0; - _t = 0; - _pqHandle = new PQHandle(); - _n = 0; - _data = null; + public override void Reset() + { + _prev = _next = null; + _anEdge = null; + _coords = Vec3.Zero; + _s = 0; + _t = 0; + _pqHandle = new PQHandle(); + _n = 0; + _data = null; + } } - } - public class Face : Pooled - { - internal Face _prev, _next; - internal Edge _anEdge; + public class Face : Pooled + { + internal Face _prev, _next; + internal Edge _anEdge; - internal Face _trail; - internal int _n; - internal bool _marked, _inside; + internal Face _trail; + internal int _n; + internal bool _marked, _inside; - internal int VertsCount - { - get + internal int VertsCount { - int n = 0; - var eCur = _anEdge; - do { - n++; - eCur = eCur._Lnext; - } while (eCur != _anEdge); - return n; + get + { + int n = 0; + var eCur = _anEdge; + do + { + n++; + eCur = eCur._Lnext; + } + while (eCur != _anEdge); + return n; + } + } + + public override void Reset() + { + _prev = _next = null; + _anEdge = null; + _trail = null; + _n = 0; + _marked = false; + _inside = false; } } - public override void Reset() + public struct EdgePair { - _prev = _next = null; - _anEdge = null; - _trail = null; - _n = 0; - _marked = false; - _inside = false; + internal Edge _e, _eSym; + + public static EdgePair Create() + { + var pair = new MeshUtils.EdgePair(); + pair._e = MeshUtils.Edge.Create(); + pair._e._pair = pair; + pair._eSym = MeshUtils.Edge.Create(); + pair._eSym._pair = pair; + return pair; + } + + public void Reset() + { + _e = _eSym = null; + } } - } - public struct EdgePair - { - internal Edge _e, _eSym; + public class Edge : Pooled + { + internal EdgePair _pair; + internal Edge _next, _Sym, _Onext, _Lnext; + internal Vertex _Org; + internal Face _Lface; + internal Tess.ActiveRegion _activeRegion; + internal int _winding; + + internal Face _Rface { get { return _Sym._Lface; } set { _Sym._Lface = value; } } + internal Vertex _Dst { get { return _Sym._Org; } set { _Sym._Org = value; } } + + internal Edge _Oprev { get { return _Sym._Lnext; } set { _Sym._Lnext = value; } } + internal Edge _Lprev { get { return _Onext._Sym; } set { _Onext._Sym = value; } } + internal Edge _Dprev { get { return _Lnext._Sym; } set { _Lnext._Sym = value; } } + internal Edge _Rprev { get { return _Sym._Onext; } set { _Sym._Onext = value; } } + internal Edge _Dnext { get { return _Rprev._Sym; } set { _Rprev._Sym = value; } } + internal Edge _Rnext { get { return _Oprev._Sym; } set { _Oprev._Sym = value; } } + + internal static void EnsureFirst(ref Edge e) + { + if (e == e._pair._eSym) + { + e = e._Sym; + } + } - public static EdgePair Create() + public override void Reset() + { + _pair.Reset(); + _next = _Sym = _Onext = _Lnext = null; + _Org = null; + _Lface = null; + _activeRegion = null; + _winding = 0; + } + } + + /// + /// MakeEdge creates a new pair of half-edges which form their own loop. + /// No vertex or face structures are allocated, but these must be assigned + /// before the current edge operation is completed. + /// + public static Edge MakeEdge(Edge eNext) { - var pair = new MeshUtils.EdgePair(); - pair._e = MeshUtils.Edge.Create(); - pair._e._pair = pair; - pair._eSym = MeshUtils.Edge.Create(); - pair._eSym._pair = pair; - return pair; + Debug.Assert(eNext != null); + + var pair = EdgePair.Create(); + var e = pair._e; + var eSym = pair._eSym; + + // Make sure eNext points to the first edge of the edge pair + Edge.EnsureFirst(ref eNext); + + // Insert in circular doubly-linked list before eNext. + // Note that the prev pointer is stored in Sym->next. + var ePrev = eNext._Sym._next; + eSym._next = ePrev; + ePrev._Sym._next = e; + e._next = eNext; + eNext._Sym._next = eSym; + + e._Sym = eSym; + e._Onext = e; + e._Lnext = eSym; + e._Org = null; + e._Lface = null; + e._winding = 0; + e._activeRegion = null; + + eSym._Sym = e; + eSym._Onext = eSym; + eSym._Lnext = e; + eSym._Org = null; + eSym._Lface = null; + eSym._winding = 0; + eSym._activeRegion = null; + + return e; } - public void Reset() + /// + /// Splice( a, b ) is best described by the Guibas/Stolfi paper or the + /// CS348a notes (see Mesh.cs). Basically it modifies the mesh so that + /// a->Onext and b->Onext are exchanged. This can have various effects + /// depending on whether a and b belong to different face or vertex rings. + /// For more explanation see Mesh.Splice(). + /// + public static void Splice(Edge a, Edge b) { - _e = _eSym = null; + var aOnext = a._Onext; + var bOnext = b._Onext; + + aOnext._Sym._Lnext = b; + bOnext._Sym._Lnext = a; + a._Onext = bOnext; + b._Onext = aOnext; } - } - public class Edge : Pooled - { - internal EdgePair _pair; - internal Edge _next, _Sym, _Onext, _Lnext; - internal Vertex _Org; - internal Face _Lface; - internal Tess.ActiveRegion _activeRegion; - internal int _winding; - - internal Face _Rface { get { return _Sym._Lface; } set { _Sym._Lface = value; } } - internal Vertex _Dst { get { return _Sym._Org; } set { _Sym._Org = value; } } - - internal Edge _Oprev { get { return _Sym._Lnext; } set { _Sym._Lnext = value; } } - internal Edge _Lprev { get { return _Onext._Sym; } set { _Onext._Sym = value; } } - internal Edge _Dprev { get { return _Lnext._Sym; } set { _Lnext._Sym = value; } } - internal Edge _Rprev { get { return _Sym._Onext; } set { _Sym._Onext = value; } } - internal Edge _Dnext { get { return _Rprev._Sym; } set { _Rprev._Sym = value; } } - internal Edge _Rnext { get { return _Oprev._Sym; } set { _Oprev._Sym = value; } } - - internal static void EnsureFirst(ref Edge e) + /// + /// MakeVertex( eOrig, vNext ) attaches a new vertex and makes it the + /// origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives + /// a place to insert the new vertex in the global vertex list. We insert + /// the new vertex *before* vNext so that algorithms which walk the vertex + /// list will not see the newly created vertices. + /// + public static void MakeVertex(Edge eOrig, Vertex vNext) { - if (e == e._pair._eSym) + var vNew = MeshUtils.Vertex.Create(); + + // insert in circular doubly-linked list before vNext + var vPrev = vNext._prev; + vNew._prev = vPrev; + vPrev._next = vNew; + vNew._next = vNext; + vNext._prev = vNew; + + vNew._anEdge = eOrig; + // leave coords, s, t undefined + + // fix other edges on this vertex loop + var e = eOrig; + do { - e = e._Sym; + e._Org = vNew; + e = e._Onext; } + while (e != eOrig); } - public override void Reset() + /// + /// MakeFace( eOrig, fNext ) attaches a new face and makes it the left + /// face of all edges in the face loop to which eOrig belongs. "fNext" gives + /// a place to insert the new face in the global face list. We insert + /// the new face *before* fNext so that algorithms which walk the face + /// list will not see the newly created faces. + /// + public static void MakeFace(Edge eOrig, Face fNext) { - _pair.Reset(); - _next = _Sym = _Onext = _Lnext = null; - _Org = null; - _Lface = null; - _activeRegion = null; - _winding = 0; + var fNew = MeshUtils.Face.Create(); + + // insert in circular doubly-linked list before fNext + var fPrev = fNext._prev; + fNew._prev = fPrev; + fPrev._next = fNew; + fNew._next = fNext; + fNext._prev = fNew; + + fNew._anEdge = eOrig; + fNew._trail = null; + fNew._marked = false; + + // The new face is marked "inside" if the old one was. This is a + // convenience for the common case where a face has been split in two. + fNew._inside = fNext._inside; + + // fix other edges on this face loop + var e = eOrig; + do + { + e._Lface = fNew; + e = e._Lnext; + } + while (e != eOrig); } - } - /// - /// MakeEdge creates a new pair of half-edges which form their own loop. - /// No vertex or face structures are allocated, but these must be assigned - /// before the current edge operation is completed. - /// - public static Edge MakeEdge(Edge eNext) - { - Debug.Assert(eNext != null); - - var pair = EdgePair.Create(); - var e = pair._e; - var eSym = pair._eSym; - - // Make sure eNext points to the first edge of the edge pair - Edge.EnsureFirst(ref eNext); - - // Insert in circular doubly-linked list before eNext. - // Note that the prev pointer is stored in Sym->next. - var ePrev = eNext._Sym._next; - eSym._next = ePrev; - ePrev._Sym._next = e; - e._next = eNext; - eNext._Sym._next = eSym; - - e._Sym = eSym; - e._Onext = e; - e._Lnext = eSym; - e._Org = null; - e._Lface = null; - e._winding = 0; - e._activeRegion = null; - - eSym._Sym = e; - eSym._Onext = eSym; - eSym._Lnext = e; - eSym._Org = null; - eSym._Lface = null; - eSym._winding = 0; - eSym._activeRegion = null; - - return e; - } + /// + /// KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym), + /// and removes from the global edge list. + /// + public static void KillEdge(Edge eDel) + { + // Half-edges are allocated in pairs, see EdgePair above + Edge.EnsureFirst(ref eDel); - /// - /// Splice( a, b ) is best described by the Guibas/Stolfi paper or the - /// CS348a notes (see Mesh.cs). Basically it modifies the mesh so that - /// a->Onext and b->Onext are exchanged. This can have various effects - /// depending on whether a and b belong to different face or vertex rings. - /// For more explanation see Mesh.Splice(). - /// - public static void Splice(Edge a, Edge b) - { - var aOnext = a._Onext; - var bOnext = b._Onext; + // delete from circular doubly-linked list + var eNext = eDel._next; + var ePrev = eDel._Sym._next; + eNext._Sym._next = ePrev; + ePrev._Sym._next = eNext; - aOnext._Sym._Lnext = b; - bOnext._Sym._Lnext = a; - a._Onext = bOnext; - b._Onext = aOnext; - } + eDel.Free(); + } - /// - /// MakeVertex( eOrig, vNext ) attaches a new vertex and makes it the - /// origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives - /// a place to insert the new vertex in the global vertex list. We insert - /// the new vertex *before* vNext so that algorithms which walk the vertex - /// list will not see the newly created vertices. - /// - public static void MakeVertex(Edge eOrig, Vertex vNext) - { - var vNew = MeshUtils.Vertex.Create(); - - // insert in circular doubly-linked list before vNext - var vPrev = vNext._prev; - vNew._prev = vPrev; - vPrev._next = vNew; - vNew._next = vNext; - vNext._prev = vNew; - - vNew._anEdge = eOrig; - // leave coords, s, t undefined - - // fix other edges on this vertex loop - var e = eOrig; - do { - e._Org = vNew; - e = e._Onext; - } while (e != eOrig); - } + /// + /// KillVertex( vDel ) destroys a vertex and removes it from the global + /// vertex list. It updates the vertex loop to point to a given new vertex. + /// + public static void KillVertex(Vertex vDel, Vertex newOrg) + { + var eStart = vDel._anEdge; - /// - /// MakeFace( eOrig, fNext ) attaches a new face and makes it the left - /// face of all edges in the face loop to which eOrig belongs. "fNext" gives - /// a place to insert the new face in the global face list. We insert - /// the new face *before* fNext so that algorithms which walk the face - /// list will not see the newly created faces. - /// - public static void MakeFace(Edge eOrig, Face fNext) - { - var fNew = MeshUtils.Face.Create(); - - // insert in circular doubly-linked list before fNext - var fPrev = fNext._prev; - fNew._prev = fPrev; - fPrev._next = fNew; - fNew._next = fNext; - fNext._prev = fNew; - - fNew._anEdge = eOrig; - fNew._trail = null; - fNew._marked = false; - - // The new face is marked "inside" if the old one was. This is a - // convenience for the common case where a face has been split in two. - fNew._inside = fNext._inside; - - // fix other edges on this face loop - var e = eOrig; - do { - e._Lface = fNew; - e = e._Lnext; - } while (e != eOrig); - } + // change the origin of all affected edges + var e = eStart; + do + { + e._Org = newOrg; + e = e._Onext; + } + while (e != eStart); - /// - /// KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel->Sym), - /// and removes from the global edge list. - /// - public static void KillEdge(Edge eDel) - { - // Half-edges are allocated in pairs, see EdgePair above - Edge.EnsureFirst(ref eDel); + // delete from circular doubly-linked list + var vPrev = vDel._prev; + var vNext = vDel._next; + vNext._prev = vPrev; + vPrev._next = vNext; - // delete from circular doubly-linked list - var eNext = eDel._next; - var ePrev = eDel._Sym._next; - eNext._Sym._next = ePrev; - ePrev._Sym._next = eNext; + vDel.Free(); + } - eDel.Free(); - } + /// + /// KillFace( fDel ) destroys a face and removes it from the global face + /// list. It updates the face loop to point to a given new face. + /// + public static void KillFace(Face fDel, Face newLFace) + { + var eStart = fDel._anEdge; - /// - /// KillVertex( vDel ) destroys a vertex and removes it from the global - /// vertex list. It updates the vertex loop to point to a given new vertex. - /// - public static void KillVertex(Vertex vDel, Vertex newOrg) - { - var eStart = vDel._anEdge; - - // change the origin of all affected edges - var e = eStart; - do { - e._Org = newOrg; - e = e._Onext; - } while (e != eStart); - - // delete from circular doubly-linked list - var vPrev = vDel._prev; - var vNext = vDel._next; - vNext._prev = vPrev; - vPrev._next = vNext; - - vDel.Free(); - } + // change the left face of all affected edges + var e = eStart; + do + { + e._Lface = newLFace; + e = e._Lnext; + } + while (e != eStart); - /// - /// KillFace( fDel ) destroys a face and removes it from the global face - /// list. It updates the face loop to point to a given new face. - /// - public static void KillFace(Face fDel, Face newLFace) - { - var eStart = fDel._anEdge; - - // change the left face of all affected edges - var e = eStart; - do { - e._Lface = newLFace; - e = e._Lnext; - } while (e != eStart); - - // delete from circular doubly-linked list - var fPrev = fDel._prev; - var fNext = fDel._next; - fNext._prev = fPrev; - fPrev._next = fNext; - - fDel.Free(); - } + // delete from circular doubly-linked list + var fPrev = fDel._prev; + var fNext = fDel._next; + fNext._prev = fPrev; + fPrev._next = fNext; - /// - /// Return signed area of face. - /// - public static Real FaceArea(Face f) - { - Real area = 0; - var e = f._anEdge; - do + fDel.Free(); + } + + /// + /// Return signed area of face. + /// + public static Real FaceArea(Face f) { - area += (e._Org._s - e._Dst._s) * (e._Org._t + e._Dst._t); - e = e._Lnext; - } while (e != f._anEdge); - return area; + Real area = 0; + var e = f._anEdge; + do + { + area += (e._Org._s - e._Dst._s) * (e._Org._t + e._Dst._t); + e = e._Lnext; + } + while (e != f._anEdge); + return area; + } } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityHeap.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityHeap.cs index 8c6980afea2..a012e22b114 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityHeap.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityHeap.cs @@ -1,5 +1,5 @@ /* -** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) +** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** @@ -9,10 +9,10 @@ ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: -** +** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be -** included in all copies or substantial portions of the Software. +** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A @@ -20,7 +20,7 @@ ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. -** +** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. @@ -36,211 +36,209 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -namespace LibTessDotNet -{ - internal struct PQHandle - { - public static readonly int Invalid = 0x0fffffff; - internal int _handle; - } - - internal class PriorityHeap where TValue : class + namespace LibTessDotNet { - public delegate bool LessOrEqual(TValue lhs, TValue rhs); - - protected class HandleElem + internal struct PQHandle { - internal TValue _key; - internal int _node; + public static readonly int Invalid = 0x0fffffff; + internal int _handle; } - private LessOrEqual _leq; - private int[] _nodes; - private HandleElem[] _handles; - private int _size, _max; - private int _freeList; - private bool _initialized; - - public bool Empty { get { return _size == 0; } } - - public PriorityHeap(int initialSize, LessOrEqual leq) + internal class PriorityHeap where TValue : class { - _leq = leq; + public delegate bool LessOrEqual(TValue lhs, TValue rhs); - _nodes = new int[initialSize + 1]; - _handles = new HandleElem[initialSize + 1]; + protected class HandleElem + { + internal TValue _key; + internal int _node; + } - _size = 0; - _max = initialSize; - _freeList = 0; - _initialized = false; + private LessOrEqual _leq; + private int[] _nodes; + private HandleElem[] _handles; + private int _size, _max; + private int _freeList; + private bool _initialized; - _nodes[1] = 1; - _handles[1] = new HandleElem { _key = null }; - } - - private void FloatDown(int curr) - { - int child; - int hCurr, hChild; + public bool Empty { get { return _size == 0; } } - hCurr = _nodes[curr]; - while (true) + public PriorityHeap(int initialSize, LessOrEqual leq) { - child = curr << 1; - if (child < _size && _leq(_handles[_nodes[child + 1]]._key, _handles[_nodes[child]]._key)) - { - ++child; - } + _leq = leq; - Debug.Assert(child <= _max); + _nodes = new int[initialSize + 1]; + _handles = new HandleElem[initialSize + 1]; - hChild = _nodes[child]; - if (child > _size || _leq(_handles[hCurr]._key, _handles[hChild]._key)) - { - _nodes[curr] = hCurr; - _handles[hCurr]._node = curr; - break; - } + _size = 0; + _max = initialSize; + _freeList = 0; + _initialized = false; - _nodes[curr] = hChild; - _handles[hChild]._node = curr; - curr = child; + _nodes[1] = 1; + _handles[1] = new HandleElem { _key = null }; } - } - private void FloatUp(int curr) - { - int parent; - int hCurr, hParent; - - hCurr = _nodes[curr]; - while (true) + private void FloatDown(int curr) { - parent = curr >> 1; - hParent = _nodes[parent]; - if (parent == 0 || _leq(_handles[hParent]._key, _handles[hCurr]._key)) + int child; + int hCurr, hChild; + + hCurr = _nodes[curr]; + while (true) { - _nodes[curr] = hCurr; - _handles[hCurr]._node = curr; - break; + child = curr << 1; + if (child < _size && _leq(_handles[_nodes[child + 1]]._key, _handles[_nodes[child]]._key)) + { + ++child; + } + + Debug.Assert(child <= _max); + + hChild = _nodes[child]; + if (child > _size || _leq(_handles[hCurr]._key, _handles[hChild]._key)) + { + _nodes[curr] = hCurr; + _handles[hCurr]._node = curr; + break; + } + + _nodes[curr] = hChild; + _handles[hChild]._node = curr; + curr = child; } - _nodes[curr] = hParent; - _handles[hParent]._node = curr; - curr = parent; } - } - public void Init() - { - for (int i = _size; i >= 1; --i) + private void FloatUp(int curr) { - FloatDown(i); - } - _initialized = true; - } + int parent; + int hCurr, hParent; - public PQHandle Insert(TValue value) - { - int curr = ++_size; - if ((curr * 2) > _max) - { - _max <<= 1; - Array.Resize(ref _nodes, _max + 1); - Array.Resize(ref _handles, _max + 1); + hCurr = _nodes[curr]; + while (true) + { + parent = curr >> 1; + hParent = _nodes[parent]; + if (parent == 0 || _leq(_handles[hParent]._key, _handles[hCurr]._key)) + { + _nodes[curr] = hCurr; + _handles[hCurr]._node = curr; + break; + } + _nodes[curr] = hParent; + _handles[hParent]._node = curr; + curr = parent; + } } - int free; - if (_freeList == 0) - { - free = curr; - } - else + public void Init() { - free = _freeList; - _freeList = _handles[free]._node; + for (int i = _size; i >= 1; --i) + { + FloatDown(i); + } + _initialized = true; } - _nodes[curr] = free; - if (_handles[free] == null) + public PQHandle Insert(TValue value) { - _handles[free] = new HandleElem { _key = value, _node = curr }; - } - else - { - _handles[free]._node = curr; - _handles[free]._key = value; - } + int curr = ++_size; + if ((curr * 2) > _max) + { + _max <<= 1; + Array.Resize(ref _nodes, _max + 1); + Array.Resize(ref _handles, _max + 1); + } - if (_initialized) - { - FloatUp(curr); - } + int free; + if (_freeList == 0) + { + free = curr; + } + else + { + free = _freeList; + _freeList = _handles[free]._node; + } - Debug.Assert(free != PQHandle.Invalid); - return new PQHandle { _handle = free }; - } + _nodes[curr] = free; + if (_handles[free] == null) + { + _handles[free] = new HandleElem { _key = value, _node = curr }; + } + else + { + _handles[free]._node = curr; + _handles[free]._key = value; + } - public TValue ExtractMin() - { - Debug.Assert(_initialized); + if (_initialized) + { + FloatUp(curr); + } - int hMin = _nodes[1]; - TValue min = _handles[hMin]._key; + Debug.Assert(free != PQHandle.Invalid); + return new PQHandle { _handle = free }; + } - if (_size > 0) + public TValue ExtractMin() { - _nodes[1] = _nodes[_size]; - _handles[_nodes[1]]._node = 1; + Debug.Assert(_initialized); - _handles[hMin]._key = null; - _handles[hMin]._node = _freeList; - _freeList = hMin; + int hMin = _nodes[1]; + TValue min = _handles[hMin]._key; - if (--_size > 0) + if (_size > 0) { - FloatDown(1); + _nodes[1] = _nodes[_size]; + _handles[_nodes[1]]._node = 1; + + _handles[hMin]._key = null; + _handles[hMin]._node = _freeList; + _freeList = hMin; + + if (--_size > 0) + { + FloatDown(1); + } } - } - return min; - } + return min; + } - public TValue Minimum() - { - Debug.Assert(_initialized); - return _handles[_nodes[1]]._key; - } + public TValue Minimum() + { + Debug.Assert(_initialized); + return _handles[_nodes[1]]._key; + } - public void Remove(PQHandle handle) - { - Debug.Assert(_initialized); + public void Remove(PQHandle handle) + { + Debug.Assert(_initialized); - int hCurr = handle._handle; - Debug.Assert(hCurr >= 1 && hCurr <= _max && _handles[hCurr]._key != null); + int hCurr = handle._handle; + Debug.Assert(hCurr >= 1 && hCurr <= _max && _handles[hCurr]._key != null); - int curr = _handles[hCurr]._node; - _nodes[curr] = _nodes[_size]; - _handles[_nodes[curr]]._node = curr; + int curr = _handles[hCurr]._node; + _nodes[curr] = _nodes[_size]; + _handles[_nodes[curr]]._node = curr; - if (curr <= --_size) - { - if (curr <= 1 || _leq(_handles[_nodes[curr >> 1]]._key, _handles[_nodes[curr]]._key)) + if (curr <= --_size) { - FloatDown(curr); - } - else - { - FloatUp(curr); + if (curr <= 1 || _leq(_handles[_nodes[curr >> 1]]._key, _handles[_nodes[curr]]._key)) + { + FloatDown(curr); + } + else + { + FloatUp(curr); + } } - } - _handles[hCurr]._key = null; - _handles[hCurr]._node = _freeList; - _freeList = hCurr; + _handles[hCurr]._key = null; + _handles[hCurr]._node = _freeList; + _freeList = hCurr; + } } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityQueue.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityQueue.cs index 5f90e3428a7..9ef3f5d76d7 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityQueue.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/PriorityQueue.cs @@ -1,5 +1,5 @@ /* -** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) +** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** @@ -9,10 +9,10 @@ ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: -** +** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be -** included in all copies or substantial portions of the Software. +** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A @@ -20,7 +20,7 @@ ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. -** +** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. @@ -37,195 +37,197 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -namespace LibTessDotNet -{ - internal class PriorityQueue where TValue : class + namespace LibTessDotNet { - private PriorityHeap.LessOrEqual _leq; - private PriorityHeap _heap; - private TValue[] _keys; - private int[] _order; - - private int _size, _max; - private bool _initialized; + internal class PriorityQueue where TValue : class + { + private PriorityHeap.LessOrEqual _leq; + private PriorityHeap _heap; + private TValue[] _keys; + private int[] _order; - public bool Empty { get { return _size == 0 && _heap.Empty; } } + private int _size, _max; + private bool _initialized; - public PriorityQueue(int initialSize, PriorityHeap.LessOrEqual leq) - { - _leq = leq; - _heap = new PriorityHeap(initialSize, leq); + public bool Empty { get { return _size == 0 && _heap.Empty; } } - _keys = new TValue[initialSize]; + public PriorityQueue(int initialSize, PriorityHeap.LessOrEqual leq) + { + _leq = leq; + _heap = new PriorityHeap(initialSize, leq); - _size = 0; - _max = initialSize; - _initialized = false; - } + _keys = new TValue[initialSize]; - class StackItem - { - internal int p, r; - }; + _size = 0; + _max = initialSize; + _initialized = false; + } - static void Swap(ref int a, ref int b) - { - int tmp = a; - a = b; - b = tmp; - } + class StackItem + { + internal int p, r; + }; - public void Init() - { - var stack = new Stack(); - int p, r, i, j, piv; - uint seed = 2016473283; - - p = 0; - r = _size - 1; - _order = new int[_size + 1]; - for (piv = 0, i = p; i <= r; ++piv, ++i) + static void Swap(ref int a, ref int b) { - _order[i] = piv; + int tmp = a; + a = b; + b = tmp; } - stack.Push(new StackItem { p = p, r = r }); - while (stack.Count > 0) + public void Init() { - var top = stack.Pop(); - p = top.p; - r = top.r; + var stack = new Stack(); + int p, r, i, j, piv; + uint seed = 2016473283; + + p = 0; + r = _size - 1; + _order = new int[_size + 1]; + for (piv = 0, i = p; i <= r; ++piv, ++i) + { + _order[i] = piv; + } - while (r > p + 10) + stack.Push(new StackItem { p = p, r = r }); + while (stack.Count > 0) { - seed = seed * 1539415821 + 1; - i = p + (int)(seed % (r - p + 1)); - piv = _order[i]; - _order[i] = _order[p]; - _order[p] = piv; - i = p - 1; - j = r + 1; - do { - do { ++i; } while (!_leq(_keys[_order[i]], _keys[piv])); - do { --j; } while (!_leq(_keys[piv], _keys[_order[j]])); - Swap(ref _order[i], ref _order[j]); - } while (i < j); - Swap(ref _order[i], ref _order[j]); - if (i - p < r - j) - { - stack.Push(new StackItem { p = j + 1, r = r }); - r = i - 1; - } - else + var top = stack.Pop(); + p = top.p; + r = top.r; + + while (r > p + 10) { - stack.Push(new StackItem { p = p, r = i - 1 }); - p = j + 1; + seed = seed * 1539415821 + 1; + i = p + (int)(seed % (r - p + 1)); + piv = _order[i]; + _order[i] = _order[p]; + _order[p] = piv; + i = p - 1; + j = r + 1; + do + { + do { ++i; } while (!_leq(_keys[_order[i]], _keys[piv])); + do { --j; } while (!_leq(_keys[piv], _keys[_order[j]])); + Swap(ref _order[i], ref _order[j]); + } + while (i < j); + Swap(ref _order[i], ref _order[j]); + if (i - p < r - j) + { + stack.Push(new StackItem { p = j + 1, r = r }); + r = i - 1; + } + else + { + stack.Push(new StackItem { p = p, r = i - 1 }); + p = j + 1; + } } - } - for (i = p + 1; i <= r; ++i) - { - piv = _order[i]; - for (j = i; j > p && !_leq(_keys[piv], _keys[_order[j - 1]]); --j) + for (i = p + 1; i <= r; ++i) { - _order[j] = _order[j - 1]; + piv = _order[i]; + for (j = i; j > p && !_leq(_keys[piv], _keys[_order[j - 1]]); --j) + { + _order[j] = _order[j - 1]; + } + _order[j] = piv; } - _order[j] = piv; } - } #if DEBUG - p = 0; - r = _size - 1; - for (i = p; i < r; ++i) - { - Debug.Assert(_leq(_keys[_order[i + 1]], _keys[_order[i]]), "Wrong sort"); - } + p = 0; + r = _size - 1; + for (i = p; i < r; ++i) + { + Debug.Assert(_leq(_keys[_order[i + 1]], _keys[_order[i]]), "Wrong sort"); + } #endif - _max = _size; - _initialized = true; - _heap.Init(); - } - - public PQHandle Insert(TValue value) - { - if (_initialized) - { - return _heap.Insert(value); + _max = _size; + _initialized = true; + _heap.Init(); } - int curr = _size; - if (++_size >= _max) + public PQHandle Insert(TValue value) { - _max <<= 1; - Array.Resize(ref _keys, _max); - } - - _keys[curr] = value; - return new PQHandle { _handle = -(curr + 1) }; - } + if (_initialized) + { + return _heap.Insert(value); + } - public TValue ExtractMin() - { - Debug.Assert(_initialized); + int curr = _size; + if (++_size >= _max) + { + _max <<= 1; + Array.Resize(ref _keys, _max); + } - if (_size == 0) - { - return _heap.ExtractMin(); + _keys[curr] = value; + return new PQHandle { _handle = -(curr + 1) }; } - TValue sortMin = _keys[_order[_size - 1]]; - if (!_heap.Empty) - { - TValue heapMin = _heap.Minimum(); - if (_leq(heapMin, sortMin)) - return _heap.ExtractMin(); - } - do { - --_size; - } while (_size > 0 && _keys[_order[_size - 1]] == null); - return sortMin; - } + public TValue ExtractMin() + { + Debug.Assert(_initialized); - public TValue Minimum() - { - Debug.Assert(_initialized); + if (_size == 0) + { + return _heap.ExtractMin(); + } + TValue sortMin = _keys[_order[_size - 1]]; + if (!_heap.Empty) + { + TValue heapMin = _heap.Minimum(); + if (_leq(heapMin, sortMin)) + return _heap.ExtractMin(); + } + do + { + --_size; + } + while (_size > 0 && _keys[_order[_size - 1]] == null); - if (_size == 0) - { - return _heap.Minimum(); + return sortMin; } - TValue sortMin = _keys[_order[_size - 1]]; - if (!_heap.Empty) - { - TValue heapMin = _heap.Minimum(); - if (_leq(heapMin, sortMin)) - return heapMin; - } - return sortMin; - } - - public void Remove(PQHandle handle) - { - Debug.Assert(_initialized); - int curr = handle._handle; - if (curr >= 0) + public TValue Minimum() { - _heap.Remove(handle); - return; + Debug.Assert(_initialized); + + if (_size == 0) + { + return _heap.Minimum(); + } + TValue sortMin = _keys[_order[_size - 1]]; + if (!_heap.Empty) + { + TValue heapMin = _heap.Minimum(); + if (_leq(heapMin, sortMin)) + return heapMin; + } + return sortMin; } - curr = -(curr + 1); - Debug.Assert(curr < _max && _keys[curr] != null); - _keys[curr] = null; - while (_size > 0 && _keys[_order[_size - 1]] == null) + public void Remove(PQHandle handle) { - --_size; + Debug.Assert(_initialized); + + int curr = handle._handle; + if (curr >= 0) + { + _heap.Remove(handle); + return; + } + curr = -(curr + 1); + Debug.Assert(curr < _max && _keys[curr] != null); + + _keys[curr] = null; + while (_size > 0 && _keys[_order[_size - 1]] == null) + { + --_size; + } } } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Sweep.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Sweep.cs index 2061fa5a2a0..056f2fa2eca 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Sweep.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Sweep.cs @@ -1,5 +1,5 @@ /* -** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) +** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** @@ -9,10 +9,10 @@ ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: -** +** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be -** included in all copies or substantial portions of the Software. +** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A @@ -20,7 +20,7 @@ ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. -** +** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. @@ -36,1203 +36,1207 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -using Real = System.Single; -namespace LibTessDotNet -{ - internal partial class Tess + using Real = System.Single; + namespace LibTessDotNet { - internal class ActiveRegion - { - internal MeshUtils.Edge _eUp; - internal Dict.Node _nodeUp; - internal int _windingNumber; - internal bool _inside, _sentinel, _dirty, _fixUpperEdge; - } - - private ActiveRegion RegionBelow(ActiveRegion reg) + internal partial class Tess { - return reg._nodeUp._prev._key; - } + internal class ActiveRegion + { + internal MeshUtils.Edge _eUp; + internal Dict.Node _nodeUp; + internal int _windingNumber; + internal bool _inside, _sentinel, _dirty, _fixUpperEdge; + } - private ActiveRegion RegionAbove(ActiveRegion reg) - { - return reg._nodeUp._next._key; - } + private ActiveRegion RegionBelow(ActiveRegion reg) + { + return reg._nodeUp._prev._key; + } - /// - /// Both edges must be directed from right to left (this is the canonical - /// direction for the upper edge of each region). - /// - /// The strategy is to evaluate a "t" value for each edge at the - /// current sweep line position, given by tess->event. The calculations - /// are designed to be very stable, but of course they are not perfect. - /// - /// Special case: if both edge destinations are at the sweep event, - /// we sort the edges by slope (they would otherwise compare equally). - /// - private bool EdgeLeq(ActiveRegion reg1, ActiveRegion reg2) - { - var e1 = reg1._eUp; - var e2 = reg2._eUp; + private ActiveRegion RegionAbove(ActiveRegion reg) + { + return reg._nodeUp._next._key; + } - if (e1._Dst == _event) + /// + /// Both edges must be directed from right to left (this is the canonical + /// direction for the upper edge of each region). + /// + /// The strategy is to evaluate a "t" value for each edge at the + /// current sweep line position, given by tess->event. The calculations + /// are designed to be very stable, but of course they are not perfect. + /// + /// Special case: if both edge destinations are at the sweep event, + /// we sort the edges by slope (they would otherwise compare equally). + /// + private bool EdgeLeq(ActiveRegion reg1, ActiveRegion reg2) { - if (e2._Dst == _event) + var e1 = reg1._eUp; + var e2 = reg2._eUp; + + if (e1._Dst == _event) { - // Two edges right of the sweep line which meet at the sweep event. - // Sort them by slope. - if (Geom.VertLeq(e1._Org, e2._Org)) + if (e2._Dst == _event) { - return Geom.EdgeSign(e2._Dst, e1._Org, e2._Org) <= 0.0f; + // Two edges right of the sweep line which meet at the sweep event. + // Sort them by slope. + if (Geom.VertLeq(e1._Org, e2._Org)) + { + return Geom.EdgeSign(e2._Dst, e1._Org, e2._Org) <= 0.0f; + } + return Geom.EdgeSign(e1._Dst, e2._Org, e1._Org) >= 0.0f; } - return Geom.EdgeSign(e1._Dst, e2._Org, e1._Org) >= 0.0f; + return Geom.EdgeSign(e2._Dst, _event, e2._Org) <= 0.0f; + } + if (e2._Dst == _event) + { + return Geom.EdgeSign(e1._Dst, _event, e1._Org) >= 0.0f; } - return Geom.EdgeSign(e2._Dst, _event, e2._Org) <= 0.0f; + + // General case - compute signed distance *from* e1, e2 to event + var t1 = Geom.EdgeEval(e1._Dst, _event, e1._Org); + var t2 = Geom.EdgeEval(e2._Dst, _event, e2._Org); + return (t1 >= t2); } - if (e2._Dst == _event) + + private void DeleteRegion(ActiveRegion reg) { - return Geom.EdgeSign(e1._Dst, _event, e1._Org) >= 0.0f; + if (reg._fixUpperEdge) + { + // It was created with zero winding number, so it better be + // deleted with zero winding number (ie. it better not get merged + // with a real edge). + Debug.Assert(reg._eUp._winding == 0); + } + reg._eUp._activeRegion = null; + _dict.Remove(reg._nodeUp); } - // General case - compute signed distance *from* e1, e2 to event - var t1 = Geom.EdgeEval(e1._Dst, _event, e1._Org); - var t2 = Geom.EdgeEval(e2._Dst, _event, e2._Org); - return (t1 >= t2); - } - - private void DeleteRegion(ActiveRegion reg) - { - if (reg._fixUpperEdge) + /// + /// Replace an upper edge which needs fixing (see ConnectRightVertex). + /// + private void FixUpperEdge(ActiveRegion reg, MeshUtils.Edge newEdge) { - // It was created with zero winding number, so it better be - // deleted with zero winding number (ie. it better not get merged - // with a real edge). - Debug.Assert(reg._eUp._winding == 0); + Debug.Assert(reg._fixUpperEdge); + _mesh.Delete(reg._eUp); + reg._fixUpperEdge = false; + reg._eUp = newEdge; + newEdge._activeRegion = reg; } - reg._eUp._activeRegion = null; - _dict.Remove(reg._nodeUp); - } - /// - /// Replace an upper edge which needs fixing (see ConnectRightVertex). - /// - private void FixUpperEdge(ActiveRegion reg, MeshUtils.Edge newEdge) - { - Debug.Assert(reg._fixUpperEdge); - _mesh.Delete(reg._eUp); - reg._fixUpperEdge = false; - reg._eUp = newEdge; - newEdge._activeRegion = reg; - } + private ActiveRegion TopLeftRegion(ActiveRegion reg) + { + var org = reg._eUp._Org; - private ActiveRegion TopLeftRegion(ActiveRegion reg) - { - var org = reg._eUp._Org; + // Find the region above the uppermost edge with the same origin + do + { + reg = RegionAbove(reg); + } + while (reg._eUp._Org == org); - // Find the region above the uppermost edge with the same origin - do { - reg = RegionAbove(reg); - } while (reg._eUp._Org == org); + // If the edge above was a temporary edge introduced by ConnectRightVertex, + // now is the time to fix it. + if (reg._fixUpperEdge) + { + var e = _mesh.Connect(RegionBelow(reg)._eUp._Sym, reg._eUp._Lnext); + FixUpperEdge(reg, e); + reg = RegionAbove(reg); + } - // If the edge above was a temporary edge introduced by ConnectRightVertex, - // now is the time to fix it. - if (reg._fixUpperEdge) - { - var e = _mesh.Connect(RegionBelow(reg)._eUp._Sym, reg._eUp._Lnext); - FixUpperEdge(reg, e); - reg = RegionAbove(reg); + return reg; } - return reg; - } - - private ActiveRegion TopRightRegion(ActiveRegion reg) - { - var dst = reg._eUp._Dst; - - // Find the region above the uppermost edge with the same destination - do { - reg = RegionAbove(reg); - } while (reg._eUp._Dst == dst); + private ActiveRegion TopRightRegion(ActiveRegion reg) + { + var dst = reg._eUp._Dst; - return reg; - } + // Find the region above the uppermost edge with the same destination + do + { + reg = RegionAbove(reg); + } + while (reg._eUp._Dst == dst); - /// - /// Add a new active region to the sweep line, *somewhere* below "regAbove" - /// (according to where the new edge belongs in the sweep-line dictionary). - /// The upper edge of the new region will be "eNewUp". - /// Winding number and "inside" flag are not updated. - /// - private ActiveRegion AddRegionBelow(ActiveRegion regAbove, MeshUtils.Edge eNewUp) - { - var regNew = new ActiveRegion(); + return reg; + } - regNew._eUp = eNewUp; - regNew._nodeUp = _dict.InsertBefore(regAbove._nodeUp, regNew); - regNew._fixUpperEdge = false; - regNew._sentinel = false; - regNew._dirty = false; + /// + /// Add a new active region to the sweep line, *somewhere* below "regAbove" + /// (according to where the new edge belongs in the sweep-line dictionary). + /// The upper edge of the new region will be "eNewUp". + /// Winding number and "inside" flag are not updated. + /// + private ActiveRegion AddRegionBelow(ActiveRegion regAbove, MeshUtils.Edge eNewUp) + { + var regNew = new ActiveRegion(); - eNewUp._activeRegion = regNew; + regNew._eUp = eNewUp; + regNew._nodeUp = _dict.InsertBefore(regAbove._nodeUp, regNew); + regNew._fixUpperEdge = false; + regNew._sentinel = false; + regNew._dirty = false; - return regNew; - } + eNewUp._activeRegion = regNew; - private void ComputeWinding(ActiveRegion reg) - { - reg._windingNumber = RegionAbove(reg)._windingNumber + reg._eUp._winding; - reg._inside = Geom.IsWindingInside(_windingRule, reg._windingNumber); - } + return regNew; + } - /// - /// Delete a region from the sweep line. This happens when the upper - /// and lower chains of a region meet (at a vertex on the sweep line). - /// The "inside" flag is copied to the appropriate mesh face (we could - /// not do this before -- since the structure of the mesh is always - /// changing, this face may not have even existed until now). - /// - private void FinishRegion(ActiveRegion reg) - { - var e = reg._eUp; - var f = e._Lface; + private void ComputeWinding(ActiveRegion reg) + { + reg._windingNumber = RegionAbove(reg)._windingNumber + reg._eUp._winding; + reg._inside = Geom.IsWindingInside(_windingRule, reg._windingNumber); + } - f._inside = reg._inside; - f._anEdge = e; - DeleteRegion(reg); - } + /// + /// Delete a region from the sweep line. This happens when the upper + /// and lower chains of a region meet (at a vertex on the sweep line). + /// The "inside" flag is copied to the appropriate mesh face (we could + /// not do this before -- since the structure of the mesh is always + /// changing, this face may not have even existed until now). + /// + private void FinishRegion(ActiveRegion reg) + { + var e = reg._eUp; + var f = e._Lface; - /// - /// We are given a vertex with one or more left-going edges. All affected - /// edges should be in the edge dictionary. Starting at regFirst->eUp, - /// we walk down deleting all regions where both edges have the same - /// origin vOrg. At the same time we copy the "inside" flag from the - /// active region to the face, since at this point each face will belong - /// to at most one region (this was not necessarily true until this point - /// in the sweep). The walk stops at the region above regLast; if regLast - /// is null we walk as far as possible. At the same time we relink the - /// mesh if necessary, so that the ordering of edges around vOrg is the - /// same as in the dictionary. - /// - private MeshUtils.Edge FinishLeftRegions(ActiveRegion regFirst, ActiveRegion regLast) - { - var regPrev = regFirst; - var ePrev = regFirst._eUp; + f._inside = reg._inside; + f._anEdge = e; + DeleteRegion(reg); + } - while (regPrev != regLast) + /// + /// We are given a vertex with one or more left-going edges. All affected + /// edges should be in the edge dictionary. Starting at regFirst->eUp, + /// we walk down deleting all regions where both edges have the same + /// origin vOrg. At the same time we copy the "inside" flag from the + /// active region to the face, since at this point each face will belong + /// to at most one region (this was not necessarily true until this point + /// in the sweep). The walk stops at the region above regLast; if regLast + /// is null we walk as far as possible. At the same time we relink the + /// mesh if necessary, so that the ordering of edges around vOrg is the + /// same as in the dictionary. + /// + private MeshUtils.Edge FinishLeftRegions(ActiveRegion regFirst, ActiveRegion regLast) { - regPrev._fixUpperEdge = false; // placement was OK - var reg = RegionBelow(regPrev); - var e = reg._eUp; - if (e._Org != ePrev._Org) + var regPrev = regFirst; + var ePrev = regFirst._eUp; + + while (regPrev != regLast) { - if (!reg._fixUpperEdge) + regPrev._fixUpperEdge = false; // placement was OK + var reg = RegionBelow(regPrev); + var e = reg._eUp; + if (e._Org != ePrev._Org) + { + if (!reg._fixUpperEdge) + { + // Remove the last left-going edge. Even though there are no further + // edges in the dictionary with this origin, there may be further + // such edges in the mesh (if we are adding left edges to a vertex + // that has already been processed). Thus it is important to call + // FinishRegion rather than just DeleteRegion. + FinishRegion(regPrev); + break; + } + // If the edge below was a temporary edge introduced by + // ConnectRightVertex, now is the time to fix it. + e = _mesh.Connect(ePrev._Lprev, e._Sym); + FixUpperEdge(reg, e); + } + + // Relink edges so that ePrev.Onext == e + if (ePrev._Onext != e) { - // Remove the last left-going edge. Even though there are no further - // edges in the dictionary with this origin, there may be further - // such edges in the mesh (if we are adding left edges to a vertex - // that has already been processed). Thus it is important to call - // FinishRegion rather than just DeleteRegion. - FinishRegion(regPrev); - break; + _mesh.Splice(e._Oprev, e); + _mesh.Splice(ePrev, e); } - // If the edge below was a temporary edge introduced by - // ConnectRightVertex, now is the time to fix it. - e = _mesh.Connect(ePrev._Lprev, e._Sym); - FixUpperEdge(reg, e); + FinishRegion(regPrev); // may change reg.eUp + ePrev = reg._eUp; + regPrev = reg; } - // Relink edges so that ePrev.Onext == e - if (ePrev._Onext != e) - { - _mesh.Splice(e._Oprev, e); - _mesh.Splice(ePrev, e); - } - FinishRegion(regPrev); // may change reg.eUp - ePrev = reg._eUp; - regPrev = reg; + return ePrev; } - return ePrev; - } - - /// - /// Purpose: insert right-going edges into the edge dictionary, and update - /// winding numbers and mesh connectivity appropriately. All right-going - /// edges share a common origin vOrg. Edges are inserted CCW starting at - /// eFirst; the last edge inserted is eLast.Oprev. If vOrg has any - /// left-going edges already processed, then eTopLeft must be the edge - /// such that an imaginary upward vertical segment from vOrg would be - /// contained between eTopLeft.Oprev and eTopLeft; otherwise eTopLeft - /// should be null. - /// - private void AddRightEdges(ActiveRegion regUp, MeshUtils.Edge eFirst, MeshUtils.Edge eLast, MeshUtils.Edge eTopLeft, bool cleanUp) - { - bool firstTime = true; - - var e = eFirst; do - { - Debug.Assert(Geom.VertLeq(e._Org, e._Dst)); - AddRegionBelow(regUp, e._Sym); - e = e._Onext; - } while (e != eLast); - - // Walk *all* right-going edges from e.Org, in the dictionary order, - // updating the winding numbers of each region, and re-linking the mesh - // edges to match the dictionary ordering (if necessary). - if (eTopLeft == null) + /// + /// Purpose: insert right-going edges into the edge dictionary, and update + /// winding numbers and mesh connectivity appropriately. All right-going + /// edges share a common origin vOrg. Edges are inserted CCW starting at + /// eFirst; the last edge inserted is eLast.Oprev. If vOrg has any + /// left-going edges already processed, then eTopLeft must be the edge + /// such that an imaginary upward vertical segment from vOrg would be + /// contained between eTopLeft.Oprev and eTopLeft; otherwise eTopLeft + /// should be null. + /// + private void AddRightEdges(ActiveRegion regUp, MeshUtils.Edge eFirst, MeshUtils.Edge eLast, MeshUtils.Edge eTopLeft, bool cleanUp) { - eTopLeft = RegionBelow(regUp)._eUp._Rprev; - } + bool firstTime = true; - ActiveRegion regPrev = regUp, reg; - var ePrev = eTopLeft; - while (true) - { - reg = RegionBelow(regPrev); - e = reg._eUp._Sym; - if (e._Org != ePrev._Org) break; + var e = eFirst; do + { + Debug.Assert(Geom.VertLeq(e._Org, e._Dst)); + AddRegionBelow(regUp, e._Sym); + e = e._Onext; + } + while (e != eLast); - if (e._Onext != ePrev) + // Walk *all* right-going edges from e.Org, in the dictionary order, + // updating the winding numbers of each region, and re-linking the mesh + // edges to match the dictionary ordering (if necessary). + if (eTopLeft == null) { - // Unlink e from its current position, and relink below ePrev - _mesh.Splice(e._Oprev, e); - _mesh.Splice(ePrev._Oprev, e); + eTopLeft = RegionBelow(regUp)._eUp._Rprev; } - // Compute the winding number and "inside" flag for the new regions - reg._windingNumber = regPrev._windingNumber - e._winding; - reg._inside = Geom.IsWindingInside(_windingRule, reg._windingNumber); - // Check for two outgoing edges with same slope -- process these - // before any intersection tests (see example in tessComputeInterior). + ActiveRegion regPrev = regUp, reg; + var ePrev = eTopLeft; + while (true) + { + reg = RegionBelow(regPrev); + e = reg._eUp._Sym; + if (e._Org != ePrev._Org) break; + + if (e._Onext != ePrev) + { + // Unlink e from its current position, and relink below ePrev + _mesh.Splice(e._Oprev, e); + _mesh.Splice(ePrev._Oprev, e); + } + // Compute the winding number and "inside" flag for the new regions + reg._windingNumber = regPrev._windingNumber - e._winding; + reg._inside = Geom.IsWindingInside(_windingRule, reg._windingNumber); + + // Check for two outgoing edges with same slope -- process these + // before any intersection tests (see example in tessComputeInterior). + regPrev._dirty = true; + if (!firstTime && CheckForRightSplice(regPrev)) + { + Geom.AddWinding(e, ePrev); + DeleteRegion(regPrev); + _mesh.Delete(ePrev); + } + firstTime = false; + regPrev = reg; + ePrev = e; + } regPrev._dirty = true; - if (!firstTime && CheckForRightSplice(regPrev)) + Debug.Assert(regPrev._windingNumber - e._winding == reg._windingNumber); + + if (cleanUp) { - Geom.AddWinding(e, ePrev); - DeleteRegion(regPrev); - _mesh.Delete(ePrev); + // Check for intersections between newly adjacent edges. + WalkDirtyRegions(regPrev); } - firstTime = false; - regPrev = reg; - ePrev = e; } - regPrev._dirty = true; - Debug.Assert(regPrev._windingNumber - e._winding == reg._windingNumber); - if (cleanUp) + /// + /// Two vertices with idential coordinates are combined into one. + /// e1.Org is kept, while e2.Org is discarded. + /// + private void SpliceMergeVertices(MeshUtils.Edge e1, MeshUtils.Edge e2) { - // Check for intersections between newly adjacent edges. - WalkDirtyRegions(regPrev); + _mesh.Splice(e1, e2); } - } - - /// - /// Two vertices with idential coordinates are combined into one. - /// e1.Org is kept, while e2.Org is discarded. - /// - private void SpliceMergeVertices(MeshUtils.Edge e1, MeshUtils.Edge e2) - { - _mesh.Splice(e1, e2); - } - - /// - /// Find some weights which describe how the intersection vertex is - /// a linear combination of "org" and "dest". Each of the two edges - /// which generated "isect" is allocated 50% of the weight; each edge - /// splits the weight between its org and dst according to the - /// relative distance to "isect". - /// - private void VertexWeights(MeshUtils.Vertex isect, MeshUtils.Vertex org, MeshUtils.Vertex dst, out Real w0, out Real w1) - { - var t1 = Geom.VertL1dist(org, isect); - var t2 = Geom.VertL1dist(dst, isect); - - w0 = (t2 / (t1 + t2)) / 2.0f; - w1 = (t1 / (t1 + t2)) / 2.0f; - isect._coords.X += w0 * org._coords.X + w1 * dst._coords.X; - isect._coords.Y += w0 * org._coords.Y + w1 * dst._coords.Y; - isect._coords.Z += w0 * org._coords.Z + w1 * dst._coords.Z; - } + /// + /// Find some weights which describe how the intersection vertex is + /// a linear combination of "org" and "dest". Each of the two edges + /// which generated "isect" is allocated 50% of the weight; each edge + /// splits the weight between its org and dst according to the + /// relative distance to "isect". + /// + private void VertexWeights(MeshUtils.Vertex isect, MeshUtils.Vertex org, MeshUtils.Vertex dst, out Real w0, out Real w1) + { + var t1 = Geom.VertL1dist(org, isect); + var t2 = Geom.VertL1dist(dst, isect); - /// - /// We've computed a new intersection point, now we need a "data" pointer - /// from the user so that we can refer to this new vertex in the - /// rendering callbacks. - /// - private void GetIntersectData(MeshUtils.Vertex isect, MeshUtils.Vertex orgUp, MeshUtils.Vertex dstUp, MeshUtils.Vertex orgLo, MeshUtils.Vertex dstLo) - { - isect._coords = Vec3.Zero; - Real w0, w1, w2, w3; - VertexWeights(isect, orgUp, dstUp, out w0, out w1); - VertexWeights(isect, orgLo, dstLo, out w2, out w3); + w0 = (t2 / (t1 + t2)) / 2.0f; + w1 = (t1 / (t1 + t2)) / 2.0f; - if (_combineCallback != null) - { - isect._data = _combineCallback( - isect._coords, - new object[] { orgUp._data, dstUp._data, orgLo._data, dstLo._data }, - new Real[] { w0, w1, w2, w3 } - ); + isect._coords.X += w0 * org._coords.X + w1 * dst._coords.X; + isect._coords.Y += w0 * org._coords.Y + w1 * dst._coords.Y; + isect._coords.Z += w0 * org._coords.Z + w1 * dst._coords.Z; } - } - - /// - /// Check the upper and lower edge of "regUp", to make sure that the - /// eUp->Org is above eLo, or eLo->Org is below eUp (depending on which - /// origin is leftmost). - /// - /// The main purpose is to splice right-going edges with the same - /// dest vertex and nearly identical slopes (ie. we can't distinguish - /// the slopes numerically). However the splicing can also help us - /// to recover from numerical errors. For example, suppose at one - /// point we checked eUp and eLo, and decided that eUp->Org is barely - /// above eLo. Then later, we split eLo into two edges (eg. from - /// a splice operation like this one). This can change the result of - /// our test so that now eUp->Org is incident to eLo, or barely below it. - /// We must correct this condition to maintain the dictionary invariants. - /// - /// One possibility is to check these edges for intersection again - /// (ie. CheckForIntersect). This is what we do if possible. However - /// CheckForIntersect requires that tess->event lies between eUp and eLo, - /// so that it has something to fall back on when the intersection - /// calculation gives us an unusable answer. So, for those cases where - /// we can't check for intersection, this routine fixes the problem - /// by just splicing the offending vertex into the other edge. - /// This is a guaranteed solution, no matter how degenerate things get. - /// Basically this is a combinatorial solution to a numerical problem. - /// - private bool CheckForRightSplice(ActiveRegion regUp) - { - var regLo = RegionBelow(regUp); - var eUp = regUp._eUp; - var eLo = regLo._eUp; - if (Geom.VertLeq(eUp._Org, eLo._Org)) + /// + /// We've computed a new intersection point, now we need a "data" pointer + /// from the user so that we can refer to this new vertex in the + /// rendering callbacks. + /// + private void GetIntersectData(MeshUtils.Vertex isect, MeshUtils.Vertex orgUp, MeshUtils.Vertex dstUp, MeshUtils.Vertex orgLo, MeshUtils.Vertex dstLo) { - if (Geom.EdgeSign(eLo._Dst, eUp._Org, eLo._Org) > 0.0f) + isect._coords = Vec3.Zero; + Real w0, w1, w2, w3; + VertexWeights(isect, orgUp, dstUp, out w0, out w1); + VertexWeights(isect, orgLo, dstLo, out w2, out w3); + + if (_combineCallback != null) { - return false; + isect._data = _combineCallback( + isect._coords, + new object[] { orgUp._data, dstUp._data, orgLo._data, dstLo._data }, + new Real[] { w0, w1, w2, w3 } + ); } + } - // eUp.Org appears to be below eLo - if (!Geom.VertEq(eUp._Org, eLo._Org)) + /// + /// Check the upper and lower edge of "regUp", to make sure that the + /// eUp->Org is above eLo, or eLo->Org is below eUp (depending on which + /// origin is leftmost). + /// + /// The main purpose is to splice right-going edges with the same + /// dest vertex and nearly identical slopes (ie. we can't distinguish + /// the slopes numerically). However the splicing can also help us + /// to recover from numerical errors. For example, suppose at one + /// point we checked eUp and eLo, and decided that eUp->Org is barely + /// above eLo. Then later, we split eLo into two edges (eg. from + /// a splice operation like this one). This can change the result of + /// our test so that now eUp->Org is incident to eLo, or barely below it. + /// We must correct this condition to maintain the dictionary invariants. + /// + /// One possibility is to check these edges for intersection again + /// (ie. CheckForIntersect). This is what we do if possible. However + /// CheckForIntersect requires that tess->event lies between eUp and eLo, + /// so that it has something to fall back on when the intersection + /// calculation gives us an unusable answer. So, for those cases where + /// we can't check for intersection, this routine fixes the problem + /// by just splicing the offending vertex into the other edge. + /// This is a guaranteed solution, no matter how degenerate things get. + /// Basically this is a combinatorial solution to a numerical problem. + /// + private bool CheckForRightSplice(ActiveRegion regUp) + { + var regLo = RegionBelow(regUp); + var eUp = regUp._eUp; + var eLo = regLo._eUp; + + if (Geom.VertLeq(eUp._Org, eLo._Org)) { - // Splice eUp._Org into eLo - _mesh.SplitEdge(eLo._Sym); - _mesh.Splice(eUp, eLo._Oprev); - regUp._dirty = regLo._dirty = true; + if (Geom.EdgeSign(eLo._Dst, eUp._Org, eLo._Org) > 0.0f) + { + return false; + } + + // eUp.Org appears to be below eLo + if (!Geom.VertEq(eUp._Org, eLo._Org)) + { + // Splice eUp._Org into eLo + _mesh.SplitEdge(eLo._Sym); + _mesh.Splice(eUp, eLo._Oprev); + regUp._dirty = regLo._dirty = true; + } + else if (eUp._Org != eLo._Org) + { + // merge the two vertices, discarding eUp.Org + _pq.Remove(eUp._Org._pqHandle); + SpliceMergeVertices(eLo._Oprev, eUp); + } } - else if (eUp._Org != eLo._Org) + else { - // merge the two vertices, discarding eUp.Org - _pq.Remove(eUp._Org._pqHandle); - SpliceMergeVertices(eLo._Oprev, eUp); + if (Geom.EdgeSign(eUp._Dst, eLo._Org, eUp._Org) < 0.0f) + { + return false; + } + + // eLo.Org appears to be above eUp, so splice eLo.Org into eUp + RegionAbove(regUp)._dirty = regUp._dirty = true; + _mesh.SplitEdge(eUp._Sym); + _mesh.Splice(eLo._Oprev, eUp); } + return true; } - else + + /// + /// Check the upper and lower edge of "regUp", to make sure that the + /// eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which + /// destination is rightmost). + /// + /// Theoretically, this should always be true. However, splitting an edge + /// into two pieces can change the results of previous tests. For example, + /// suppose at one point we checked eUp and eLo, and decided that eUp->Dst + /// is barely above eLo. Then later, we split eLo into two edges (eg. from + /// a splice operation like this one). This can change the result of + /// the test so that now eUp->Dst is incident to eLo, or barely below it. + /// We must correct this condition to maintain the dictionary invariants + /// (otherwise new edges might get inserted in the wrong place in the + /// dictionary, and bad stuff will happen). + /// + /// We fix the problem by just splicing the offending vertex into the + /// other edge. + /// + private bool CheckForLeftSplice(ActiveRegion regUp) { - if (Geom.EdgeSign(eUp._Dst, eLo._Org, eUp._Org) < 0.0f) + var regLo = RegionBelow(regUp); + var eUp = regUp._eUp; + var eLo = regLo._eUp; + + Debug.Assert(!Geom.VertEq(eUp._Dst, eLo._Dst)); + + if (Geom.VertLeq(eUp._Dst, eLo._Dst)) { - return false; + if (Geom.EdgeSign(eUp._Dst, eLo._Dst, eUp._Org) < 0.0f) + { + return false; + } + + // eLo.Dst is above eUp, so splice eLo.Dst into eUp + RegionAbove(regUp)._dirty = regUp._dirty = true; + var e = _mesh.SplitEdge(eUp); + _mesh.Splice(eLo._Sym, e); + e._Lface._inside = regUp._inside; } + else + { + if (Geom.EdgeSign(eLo._Dst, eUp._Dst, eLo._Org) > 0.0f) + { + return false; + } - // eLo.Org appears to be above eUp, so splice eLo.Org into eUp - RegionAbove(regUp)._dirty = regUp._dirty = true; - _mesh.SplitEdge(eUp._Sym); - _mesh.Splice(eLo._Oprev, eUp); + // eUp.Dst is below eLo, so splice eUp.Dst into eLo + regUp._dirty = regLo._dirty = true; + var e = _mesh.SplitEdge(eLo); + _mesh.Splice(eUp._Lnext, eLo._Sym); + e._Rface._inside = regUp._inside; + } + return true; } - return true; - } - - /// - /// Check the upper and lower edge of "regUp", to make sure that the - /// eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which - /// destination is rightmost). - /// - /// Theoretically, this should always be true. However, splitting an edge - /// into two pieces can change the results of previous tests. For example, - /// suppose at one point we checked eUp and eLo, and decided that eUp->Dst - /// is barely above eLo. Then later, we split eLo into two edges (eg. from - /// a splice operation like this one). This can change the result of - /// the test so that now eUp->Dst is incident to eLo, or barely below it. - /// We must correct this condition to maintain the dictionary invariants - /// (otherwise new edges might get inserted in the wrong place in the - /// dictionary, and bad stuff will happen). - /// - /// We fix the problem by just splicing the offending vertex into the - /// other edge. - /// - private bool CheckForLeftSplice(ActiveRegion regUp) - { - var regLo = RegionBelow(regUp); - var eUp = regUp._eUp; - var eLo = regLo._eUp; - - Debug.Assert(!Geom.VertEq(eUp._Dst, eLo._Dst)); - if (Geom.VertLeq(eUp._Dst, eLo._Dst)) + /// + /// Check the upper and lower edges of the given region to see if + /// they intersect. If so, create the intersection and add it + /// to the data structures. + /// + /// Returns TRUE if adding the new intersection resulted in a recursive + /// call to AddRightEdges(); in this case all "dirty" regions have been + /// checked for intersections, and possibly regUp has been deleted. + /// + private bool CheckForIntersect(ActiveRegion regUp) { - if (Geom.EdgeSign(eUp._Dst, eLo._Dst, eUp._Org) < 0.0f) + var regLo = RegionBelow(regUp); + var eUp = regUp._eUp; + var eLo = regLo._eUp; + var orgUp = eUp._Org; + var orgLo = eLo._Org; + var dstUp = eUp._Dst; + var dstLo = eLo._Dst; + + Debug.Assert(!Geom.VertEq(dstLo, dstUp)); + Debug.Assert(Geom.EdgeSign(dstUp, _event, orgUp) <= 0.0f); + Debug.Assert(Geom.EdgeSign(dstLo, _event, orgLo) >= 0.0f); + Debug.Assert(orgUp != _event && orgLo != _event); + Debug.Assert(!regUp._fixUpperEdge && !regLo._fixUpperEdge); + + if (orgUp == orgLo) { + // right endpoints are the same return false; } - // eLo.Dst is above eUp, so splice eLo.Dst into eUp - RegionAbove(regUp)._dirty = regUp._dirty = true; - var e = _mesh.SplitEdge(eUp); - _mesh.Splice(eLo._Sym, e); - e._Lface._inside = regUp._inside; - } - else - { - if (Geom.EdgeSign(eLo._Dst, eUp._Dst, eLo._Org) > 0.0f) + var tMinUp = Math.Min(orgUp._t, dstUp._t); + var tMaxLo = Math.Max(orgLo._t, dstLo._t); + if (tMinUp > tMaxLo) { + // t ranges do not overlap return false; } - // eUp.Dst is below eLo, so splice eUp.Dst into eLo - regUp._dirty = regLo._dirty = true; - var e = _mesh.SplitEdge(eLo); - _mesh.Splice(eUp._Lnext, eLo._Sym); - e._Rface._inside = regUp._inside; - } - return true; - } - - /// - /// Check the upper and lower edges of the given region to see if - /// they intersect. If so, create the intersection and add it - /// to the data structures. - /// - /// Returns TRUE if adding the new intersection resulted in a recursive - /// call to AddRightEdges(); in this case all "dirty" regions have been - /// checked for intersections, and possibly regUp has been deleted. - /// - private bool CheckForIntersect(ActiveRegion regUp) - { - var regLo = RegionBelow(regUp); - var eUp = regUp._eUp; - var eLo = regLo._eUp; - var orgUp = eUp._Org; - var orgLo = eLo._Org; - var dstUp = eUp._Dst; - var dstLo = eLo._Dst; - - Debug.Assert(!Geom.VertEq(dstLo, dstUp)); - Debug.Assert(Geom.EdgeSign(dstUp, _event, orgUp) <= 0.0f); - Debug.Assert(Geom.EdgeSign(dstLo, _event, orgLo) >= 0.0f); - Debug.Assert(orgUp != _event && orgLo != _event); - Debug.Assert(!regUp._fixUpperEdge && !regLo._fixUpperEdge); - - if( orgUp == orgLo ) - { - // right endpoints are the same - return false; - } - - var tMinUp = Math.Min(orgUp._t, dstUp._t); - var tMaxLo = Math.Max(orgLo._t, dstLo._t); - if( tMinUp > tMaxLo ) - { - // t ranges do not overlap - return false; - } - - if (Geom.VertLeq(orgUp, orgLo)) - { - if (Geom.EdgeSign( dstLo, orgUp, orgLo ) > 0.0f) + if (Geom.VertLeq(orgUp, orgLo)) { - return false; + if (Geom.EdgeSign(dstLo, orgUp, orgLo) > 0.0f) + { + return false; + } } - } - else - { - if (Geom.EdgeSign( dstUp, orgLo, orgUp ) < 0.0f) + else { - return false; + if (Geom.EdgeSign(dstUp, orgLo, orgUp) < 0.0f) + { + return false; + } } - } - // At this point the edges intersect, at least marginally + // At this point the edges intersect, at least marginally - var isect = MeshUtils.Vertex.Create(); - Geom.EdgeIntersect(dstUp, orgUp, dstLo, orgLo, isect); - // The following properties are guaranteed: - Debug.Assert(Math.Min(orgUp._t, dstUp._t) <= isect._t); - Debug.Assert(isect._t <= Math.Max(orgLo._t, dstLo._t)); - Debug.Assert(Math.Min(dstLo._s, dstUp._s) <= isect._s); - Debug.Assert(isect._s <= Math.Max(orgLo._s, orgUp._s)); + var isect = MeshUtils.Vertex.Create(); + Geom.EdgeIntersect(dstUp, orgUp, dstLo, orgLo, isect); + // The following properties are guaranteed: + Debug.Assert(Math.Min(orgUp._t, dstUp._t) <= isect._t); + Debug.Assert(isect._t <= Math.Max(orgLo._t, dstLo._t)); + Debug.Assert(Math.Min(dstLo._s, dstUp._s) <= isect._s); + Debug.Assert(isect._s <= Math.Max(orgLo._s, orgUp._s)); - if (Geom.VertLeq(isect, _event)) - { - // The intersection point lies slightly to the left of the sweep line, - // so move it until it''s slightly to the right of the sweep line. - // (If we had perfect numerical precision, this would never happen - // in the first place). The easiest and safest thing to do is - // replace the intersection by tess._event. - isect._s = _event._s; - isect._t = _event._t; - } - // Similarly, if the computed intersection lies to the right of the - // rightmost origin (which should rarely happen), it can cause - // unbelievable inefficiency on sufficiently degenerate inputs. - // (If you have the test program, try running test54.d with the - // "X zoom" option turned on). - var orgMin = Geom.VertLeq(orgUp, orgLo) ? orgUp : orgLo; - if (Geom.VertLeq(orgMin, isect)) - { - isect._s = orgMin._s; - isect._t = orgMin._t; - } - - if (Geom.VertEq(isect, orgUp) || Geom.VertEq(isect, orgLo)) - { - // Easy case -- intersection at one of the right endpoints - CheckForRightSplice(regUp); - return false; - } - - if ( (! Geom.VertEq(dstUp, _event) - && Geom.EdgeSign(dstUp, _event, isect) >= 0.0f) - || (! Geom.VertEq(dstLo, _event) - && Geom.EdgeSign(dstLo, _event, isect) <= 0.0f)) - { - // Very unusual -- the new upper or lower edge would pass on the - // wrong side of the sweep event, or through it. This can happen - // due to very small numerical errors in the intersection calculation. - if (dstLo == _event) + if (Geom.VertLeq(isect, _event)) { - // Splice dstLo into eUp, and process the new region(s) - _mesh.SplitEdge(eUp._Sym); - _mesh.Splice(eLo._Sym, eUp); - regUp = TopLeftRegion(regUp); - eUp = RegionBelow(regUp)._eUp; - FinishLeftRegions(RegionBelow(regUp), regLo); - AddRightEdges(regUp, eUp._Oprev, eUp, eUp, true); - return true; + // The intersection point lies slightly to the left of the sweep line, + // so move it until it''s slightly to the right of the sweep line. + // (If we had perfect numerical precision, this would never happen + // in the first place). The easiest and safest thing to do is + // replace the intersection by tess._event. + isect._s = _event._s; + isect._t = _event._t; } - if( dstUp == _event ) { - /* Splice dstUp into eLo, and process the new region(s) */ - _mesh.SplitEdge(eLo._Sym); - _mesh.Splice(eUp._Lnext, eLo._Oprev); - regLo = regUp; - regUp = TopRightRegion(regUp); - var e = RegionBelow(regUp)._eUp._Rprev; - regLo._eUp = eLo._Oprev; - eLo = FinishLeftRegions(regLo, null); - AddRightEdges(regUp, eLo._Onext, eUp._Rprev, e, true); - return true; + // Similarly, if the computed intersection lies to the right of the + // rightmost origin (which should rarely happen), it can cause + // unbelievable inefficiency on sufficiently degenerate inputs. + // (If you have the test program, try running test54.d with the + // "X zoom" option turned on). + var orgMin = Geom.VertLeq(orgUp, orgLo) ? orgUp : orgLo; + if (Geom.VertLeq(orgMin, isect)) + { + isect._s = orgMin._s; + isect._t = orgMin._t; } - // Special case: called from ConnectRightVertex. If either - // edge passes on the wrong side of tess._event, split it - // (and wait for ConnectRightVertex to splice it appropriately). - if (Geom.EdgeSign( dstUp, _event, isect ) >= 0.0f) + + if (Geom.VertEq(isect, orgUp) || Geom.VertEq(isect, orgLo)) { - RegionAbove(regUp)._dirty = regUp._dirty = true; - _mesh.SplitEdge(eUp._Sym); - eUp._Org._s = _event._s; - eUp._Org._t = _event._t; + // Easy case -- intersection at one of the right endpoints + CheckForRightSplice(regUp); + return false; } - if (Geom.EdgeSign(dstLo, _event, isect) <= 0.0f) + + if ((!Geom.VertEq(dstUp, _event) + && Geom.EdgeSign(dstUp, _event, isect) >= 0.0f) + || (!Geom.VertEq(dstLo, _event) + && Geom.EdgeSign(dstLo, _event, isect) <= 0.0f)) { - regUp._dirty = regLo._dirty = true; - _mesh.SplitEdge(eLo._Sym); - eLo._Org._s = _event._s; - eLo._Org._t = _event._t; + // Very unusual -- the new upper or lower edge would pass on the + // wrong side of the sweep event, or through it. This can happen + // due to very small numerical errors in the intersection calculation. + if (dstLo == _event) + { + // Splice dstLo into eUp, and process the new region(s) + _mesh.SplitEdge(eUp._Sym); + _mesh.Splice(eLo._Sym, eUp); + regUp = TopLeftRegion(regUp); + eUp = RegionBelow(regUp)._eUp; + FinishLeftRegions(RegionBelow(regUp), regLo); + AddRightEdges(regUp, eUp._Oprev, eUp, eUp, true); + return true; + } + if (dstUp == _event) + { + /* Splice dstUp into eLo, and process the new region(s) */ + _mesh.SplitEdge(eLo._Sym); + _mesh.Splice(eUp._Lnext, eLo._Oprev); + regLo = regUp; + regUp = TopRightRegion(regUp); + var e = RegionBelow(regUp)._eUp._Rprev; + regLo._eUp = eLo._Oprev; + eLo = FinishLeftRegions(regLo, null); + AddRightEdges(regUp, eLo._Onext, eUp._Rprev, e, true); + return true; + } + // Special case: called from ConnectRightVertex. If either + // edge passes on the wrong side of tess._event, split it + // (and wait for ConnectRightVertex to splice it appropriately). + if (Geom.EdgeSign(dstUp, _event, isect) >= 0.0f) + { + RegionAbove(regUp)._dirty = regUp._dirty = true; + _mesh.SplitEdge(eUp._Sym); + eUp._Org._s = _event._s; + eUp._Org._t = _event._t; + } + if (Geom.EdgeSign(dstLo, _event, isect) <= 0.0f) + { + regUp._dirty = regLo._dirty = true; + _mesh.SplitEdge(eLo._Sym); + eLo._Org._s = _event._s; + eLo._Org._t = _event._t; + } + // leave the rest for ConnectRightVertex + return false; } - // leave the rest for ConnectRightVertex + + // General case -- split both edges, splice into new vertex. + // When we do the splice operation, the order of the arguments is + // arbitrary as far as correctness goes. However, when the operation + // creates a new face, the work done is proportional to the size of + // the new face. We expect the faces in the processed part of + // the mesh (ie. eUp._Lface) to be smaller than the faces in the + // unprocessed original contours (which will be eLo._Oprev._Lface). + _mesh.SplitEdge(eUp._Sym); + _mesh.SplitEdge(eLo._Sym); + _mesh.Splice(eLo._Oprev, eUp); + eUp._Org._s = isect._s; + eUp._Org._t = isect._t; + eUp._Org._pqHandle = _pq.Insert(eUp._Org); + if (eUp._Org._pqHandle._handle == PQHandle.Invalid) + { + throw new InvalidOperationException("PQHandle should not be invalid"); + } + GetIntersectData(eUp._Org, orgUp, dstUp, orgLo, dstLo); + RegionAbove(regUp)._dirty = regUp._dirty = regLo._dirty = true; return false; } - // General case -- split both edges, splice into new vertex. - // When we do the splice operation, the order of the arguments is - // arbitrary as far as correctness goes. However, when the operation - // creates a new face, the work done is proportional to the size of - // the new face. We expect the faces in the processed part of - // the mesh (ie. eUp._Lface) to be smaller than the faces in the - // unprocessed original contours (which will be eLo._Oprev._Lface). - _mesh.SplitEdge(eUp._Sym); - _mesh.SplitEdge(eLo._Sym); - _mesh.Splice(eLo._Oprev, eUp); - eUp._Org._s = isect._s; - eUp._Org._t = isect._t; - eUp._Org._pqHandle = _pq.Insert(eUp._Org); - if (eUp._Org._pqHandle._handle == PQHandle.Invalid) + /// + /// When the upper or lower edge of any region changes, the region is + /// marked "dirty". This routine walks through all the dirty regions + /// and makes sure that the dictionary invariants are satisfied + /// (see the comments at the beginning of this file). Of course + /// new dirty regions can be created as we make changes to restore + /// the invariants. + /// + private void WalkDirtyRegions(ActiveRegion regUp) { - throw new InvalidOperationException("PQHandle should not be invalid"); - } - GetIntersectData(eUp._Org, orgUp, dstUp, orgLo, dstLo); - RegionAbove(regUp)._dirty = regUp._dirty = regLo._dirty = true; - return false; - } - - /// - /// When the upper or lower edge of any region changes, the region is - /// marked "dirty". This routine walks through all the dirty regions - /// and makes sure that the dictionary invariants are satisfied - /// (see the comments at the beginning of this file). Of course - /// new dirty regions can be created as we make changes to restore - /// the invariants. - /// - private void WalkDirtyRegions(ActiveRegion regUp) - { - var regLo = RegionBelow(regUp); - MeshUtils.Edge eUp, eLo; + var regLo = RegionBelow(regUp); + MeshUtils.Edge eUp, eLo; - while (true) - { - // Find the lowest dirty region (we walk from the bottom up). - while (regLo._dirty) - { - regUp = regLo; - regLo = RegionBelow(regLo); - } - if (!regUp._dirty) + while (true) { - regLo = regUp; - regUp = RegionAbove( regUp ); - if(regUp == null || !regUp._dirty) + // Find the lowest dirty region (we walk from the bottom up). + while (regLo._dirty) { - // We've walked all the dirty regions - return; + regUp = regLo; + regLo = RegionBelow(regLo); } - } - regUp._dirty = false; - eUp = regUp._eUp; - eLo = regLo._eUp; - - if (eUp._Dst != eLo._Dst) - { - // Check that the edge ordering is obeyed at the Dst vertices. - if (CheckForLeftSplice(regUp)) + if (!regUp._dirty) { - - // If the upper or lower edge was marked fixUpperEdge, then - // we no longer need it (since these edges are needed only for - // vertices which otherwise have no right-going edges). - if (regLo._fixUpperEdge) + regLo = regUp; + regUp = RegionAbove(regUp); + if (regUp == null || !regUp._dirty) { - DeleteRegion(regLo); - _mesh.Delete(eLo); - regLo = RegionBelow(regUp); - eLo = regLo._eUp; + // We've walked all the dirty regions + return; } - else if( regUp._fixUpperEdge ) + } + regUp._dirty = false; + eUp = regUp._eUp; + eLo = regLo._eUp; + + if (eUp._Dst != eLo._Dst) + { + // Check that the edge ordering is obeyed at the Dst vertices. + if (CheckForLeftSplice(regUp)) { - DeleteRegion(regUp); - _mesh.Delete(eUp); - regUp = RegionAbove(regLo); - eUp = regUp._eUp; + // If the upper or lower edge was marked fixUpperEdge, then + // we no longer need it (since these edges are needed only for + // vertices which otherwise have no right-going edges). + if (regLo._fixUpperEdge) + { + DeleteRegion(regLo); + _mesh.Delete(eLo); + regLo = RegionBelow(regUp); + eLo = regLo._eUp; + } + else if (regUp._fixUpperEdge) + { + DeleteRegion(regUp); + _mesh.Delete(eUp); + regUp = RegionAbove(regLo); + eUp = regUp._eUp; + } } } - } - if (eUp._Org != eLo._Org) - { - if( eUp._Dst != eLo._Dst - && ! regUp._fixUpperEdge && ! regLo._fixUpperEdge - && (eUp._Dst == _event || eLo._Dst == _event) ) + if (eUp._Org != eLo._Org) { - // When all else fails in CheckForIntersect(), it uses tess._event - // as the intersection location. To make this possible, it requires - // that tess._event lie between the upper and lower edges, and also - // that neither of these is marked fixUpperEdge (since in the worst - // case it might splice one of these edges into tess.event, and - // violate the invariant that fixable edges are the only right-going - // edge from their associated vertex). - if (CheckForIntersect(regUp)) + if (eUp._Dst != eLo._Dst + && !regUp._fixUpperEdge && !regLo._fixUpperEdge + && (eUp._Dst == _event || eLo._Dst == _event)) { - // WalkDirtyRegions() was called recursively; we're done - return; + // When all else fails in CheckForIntersect(), it uses tess._event + // as the intersection location. To make this possible, it requires + // that tess._event lie between the upper and lower edges, and also + // that neither of these is marked fixUpperEdge (since in the worst + // case it might splice one of these edges into tess.event, and + // violate the invariant that fixable edges are the only right-going + // edge from their associated vertex). + if (CheckForIntersect(regUp)) + { + // WalkDirtyRegions() was called recursively; we're done + return; + } + } + else + { + // Even though we can't use CheckForIntersect(), the Org vertices + // may violate the dictionary edge ordering. Check and correct this. + CheckForRightSplice(regUp); } } - else + if (eUp._Org == eLo._Org && eUp._Dst == eLo._Dst) { - // Even though we can't use CheckForIntersect(), the Org vertices - // may violate the dictionary edge ordering. Check and correct this. - CheckForRightSplice(regUp); + // A degenerate loop consisting of only two edges -- delete it. + Geom.AddWinding(eLo, eUp); + DeleteRegion(regUp); + _mesh.Delete(eUp); + regUp = RegionAbove(regLo); } } - if (eUp._Org == eLo._Org && eUp._Dst == eLo._Dst) - { - // A degenerate loop consisting of only two edges -- delete it. - Geom.AddWinding(eLo, eUp); - DeleteRegion(regUp); - _mesh.Delete(eUp); - regUp = RegionAbove(regLo); - } } - } - - /// - /// Purpose: connect a "right" vertex vEvent (one where all edges go left) - /// to the unprocessed portion of the mesh. Since there are no right-going - /// edges, two regions (one above vEvent and one below) are being merged - /// into one. "regUp" is the upper of these two regions. - /// - /// There are two reasons for doing this (adding a right-going edge): - /// - if the two regions being merged are "inside", we must add an edge - /// to keep them separated (the combined region would not be monotone). - /// - in any case, we must leave some record of vEvent in the dictionary, - /// so that we can merge vEvent with features that we have not seen yet. - /// For example, maybe there is a vertical edge which passes just to - /// the right of vEvent; we would like to splice vEvent into this edge. - /// - /// However, we don't want to connect vEvent to just any vertex. We don''t - /// want the new edge to cross any other edges; otherwise we will create - /// intersection vertices even when the input data had no self-intersections. - /// (This is a bad thing; if the user's input data has no intersections, - /// we don't want to generate any false intersections ourselves.) - /// - /// Our eventual goal is to connect vEvent to the leftmost unprocessed - /// vertex of the combined region (the union of regUp and regLo). - /// But because of unseen vertices with all right-going edges, and also - /// new vertices which may be created by edge intersections, we don''t - /// know where that leftmost unprocessed vertex is. In the meantime, we - /// connect vEvent to the closest vertex of either chain, and mark the region - /// as "fixUpperEdge". This flag says to delete and reconnect this edge - /// to the next processed vertex on the boundary of the combined region. - /// Quite possibly the vertex we connected to will turn out to be the - /// closest one, in which case we won''t need to make any changes. - /// - private void ConnectRightVertex(ActiveRegion regUp, MeshUtils.Edge eBottomLeft) - { - var eTopLeft = eBottomLeft._Onext; - var regLo = RegionBelow(regUp); - var eUp = regUp._eUp; - var eLo = regLo._eUp; - bool degenerate = false; - if (eUp._Dst != eLo._Dst) + /// + /// Purpose: connect a "right" vertex vEvent (one where all edges go left) + /// to the unprocessed portion of the mesh. Since there are no right-going + /// edges, two regions (one above vEvent and one below) are being merged + /// into one. "regUp" is the upper of these two regions. + /// + /// There are two reasons for doing this (adding a right-going edge): + /// - if the two regions being merged are "inside", we must add an edge + /// to keep them separated (the combined region would not be monotone). + /// - in any case, we must leave some record of vEvent in the dictionary, + /// so that we can merge vEvent with features that we have not seen yet. + /// For example, maybe there is a vertical edge which passes just to + /// the right of vEvent; we would like to splice vEvent into this edge. + /// + /// However, we don't want to connect vEvent to just any vertex. We don''t + /// want the new edge to cross any other edges; otherwise we will create + /// intersection vertices even when the input data had no self-intersections. + /// (This is a bad thing; if the user's input data has no intersections, + /// we don't want to generate any false intersections ourselves.) + /// + /// Our eventual goal is to connect vEvent to the leftmost unprocessed + /// vertex of the combined region (the union of regUp and regLo). + /// But because of unseen vertices with all right-going edges, and also + /// new vertices which may be created by edge intersections, we don''t + /// know where that leftmost unprocessed vertex is. In the meantime, we + /// connect vEvent to the closest vertex of either chain, and mark the region + /// as "fixUpperEdge". This flag says to delete and reconnect this edge + /// to the next processed vertex on the boundary of the combined region. + /// Quite possibly the vertex we connected to will turn out to be the + /// closest one, in which case we won''t need to make any changes. + /// + private void ConnectRightVertex(ActiveRegion regUp, MeshUtils.Edge eBottomLeft) { - CheckForIntersect(regUp); - } + var eTopLeft = eBottomLeft._Onext; + var regLo = RegionBelow(regUp); + var eUp = regUp._eUp; + var eLo = regLo._eUp; + bool degenerate = false; - // Possible new degeneracies: upper or lower edge of regUp may pass - // through vEvent, or may coincide with new intersection vertex - if (Geom.VertEq(eUp._Org, _event)) - { - _mesh.Splice(eTopLeft._Oprev, eUp); - regUp = TopLeftRegion(regUp); - eTopLeft = RegionBelow(regUp)._eUp; - FinishLeftRegions(RegionBelow(regUp), regLo); - degenerate = true; - } - if (Geom.VertEq(eLo._Org, _event)) - { - _mesh.Splice(eBottomLeft, eLo._Oprev); - eBottomLeft = FinishLeftRegions(regLo, null); - degenerate = true; - } - if (degenerate) - { - AddRightEdges(regUp, eBottomLeft._Onext, eTopLeft, eTopLeft, true); - return; - } + if (eUp._Dst != eLo._Dst) + { + CheckForIntersect(regUp); + } - // Non-degenerate situation -- need to add a temporary, fixable edge. - // Connect to the closer of eLo.Org, eUp.Org. - MeshUtils.Edge eNew; - if (Geom.VertLeq(eLo._Org, eUp._Org)) - { - eNew = eLo._Oprev; - } - else - { - eNew = eUp; - } - eNew = _mesh.Connect(eBottomLeft._Lprev, eNew); + // Possible new degeneracies: upper or lower edge of regUp may pass + // through vEvent, or may coincide with new intersection vertex + if (Geom.VertEq(eUp._Org, _event)) + { + _mesh.Splice(eTopLeft._Oprev, eUp); + regUp = TopLeftRegion(regUp); + eTopLeft = RegionBelow(regUp)._eUp; + FinishLeftRegions(RegionBelow(regUp), regLo); + degenerate = true; + } + if (Geom.VertEq(eLo._Org, _event)) + { + _mesh.Splice(eBottomLeft, eLo._Oprev); + eBottomLeft = FinishLeftRegions(regLo, null); + degenerate = true; + } + if (degenerate) + { + AddRightEdges(regUp, eBottomLeft._Onext, eTopLeft, eTopLeft, true); + return; + } - // Prevent cleanup, otherwise eNew might disappear before we've even - // had a chance to mark it as a temporary edge. - AddRightEdges(regUp, eNew, eNew._Onext, eNew._Onext, false); - eNew._Sym._activeRegion._fixUpperEdge = true; - WalkDirtyRegions(regUp); - } + // Non-degenerate situation -- need to add a temporary, fixable edge. + // Connect to the closer of eLo.Org, eUp.Org. + MeshUtils.Edge eNew; + if (Geom.VertLeq(eLo._Org, eUp._Org)) + { + eNew = eLo._Oprev; + } + else + { + eNew = eUp; + } + eNew = _mesh.Connect(eBottomLeft._Lprev, eNew); - /// - /// The event vertex lies exacty on an already-processed edge or vertex. - /// Adding the new vertex involves splicing it into the already-processed - /// part of the mesh. - /// - private void ConnectLeftDegenerate(ActiveRegion regUp, MeshUtils.Vertex vEvent) - { - var e = regUp._eUp; - if (Geom.VertEq(e._Org, vEvent)) - { - // e.Org is an unprocessed vertex - just combine them, and wait - // for e.Org to be pulled from the queue - // C# : in the C version, there is a flag but it was never implemented - // the vertices are before beginning the tessellation - throw new InvalidOperationException("Vertices should have been merged before"); + // Prevent cleanup, otherwise eNew might disappear before we've even + // had a chance to mark it as a temporary edge. + AddRightEdges(regUp, eNew, eNew._Onext, eNew._Onext, false); + eNew._Sym._activeRegion._fixUpperEdge = true; + WalkDirtyRegions(regUp); } - if (!Geom.VertEq(e._Dst, vEvent)) + /// + /// The event vertex lies exacty on an already-processed edge or vertex. + /// Adding the new vertex involves splicing it into the already-processed + /// part of the mesh. + /// + private void ConnectLeftDegenerate(ActiveRegion regUp, MeshUtils.Vertex vEvent) { - // General case -- splice vEvent into edge e which passes through it - _mesh.SplitEdge(e._Sym); - if (regUp._fixUpperEdge) + var e = regUp._eUp; + if (Geom.VertEq(e._Org, vEvent)) { - // This edge was fixable -- delete unused portion of original edge - _mesh.Delete(e._Onext); - regUp._fixUpperEdge = false; + // e.Org is an unprocessed vertex - just combine them, and wait + // for e.Org to be pulled from the queue + // C# : in the C version, there is a flag but it was never implemented + // the vertices are before beginning the tessellation + throw new InvalidOperationException("Vertices should have been merged before"); } - _mesh.Splice(vEvent._anEdge, e); - SweepEvent(vEvent); // recurse - return; - } - - // See above - throw new InvalidOperationException("Vertices should have been merged before"); - } - /// - /// Purpose: connect a "left" vertex (one where both edges go right) - /// to the processed portion of the mesh. Let R be the active region - /// containing vEvent, and let U and L be the upper and lower edge - /// chains of R. There are two possibilities: - /// - /// - the normal case: split R into two regions, by connecting vEvent to - /// the rightmost vertex of U or L lying to the left of the sweep line - /// - /// - the degenerate case: if vEvent is close enough to U or L, we - /// merge vEvent into that edge chain. The subcases are: - /// - merging with the rightmost vertex of U or L - /// - merging with the active edge of U or L - /// - merging with an already-processed portion of U or L - /// - private void ConnectLeftVertex(MeshUtils.Vertex vEvent) - { - var tmp = new ActiveRegion(); + if (!Geom.VertEq(e._Dst, vEvent)) + { + // General case -- splice vEvent into edge e which passes through it + _mesh.SplitEdge(e._Sym); + if (regUp._fixUpperEdge) + { + // This edge was fixable -- delete unused portion of original edge + _mesh.Delete(e._Onext); + regUp._fixUpperEdge = false; + } + _mesh.Splice(vEvent._anEdge, e); + SweepEvent(vEvent); // recurse + return; + } - // Get a pointer to the active region containing vEvent - tmp._eUp = vEvent._anEdge._Sym; - var regUp = _dict.Find(tmp).Key; - var regLo = RegionBelow(regUp); - if (regLo == null) - { - // This may happen if the input polygon is coplanar. - return; + // See above + throw new InvalidOperationException("Vertices should have been merged before"); } - var eUp = regUp._eUp; - var eLo = regLo._eUp; - // Try merging with U or L first - if (Geom.EdgeSign(eUp._Dst, vEvent, eUp._Org) == 0.0f) + /// + /// Purpose: connect a "left" vertex (one where both edges go right) + /// to the processed portion of the mesh. Let R be the active region + /// containing vEvent, and let U and L be the upper and lower edge + /// chains of R. There are two possibilities: + /// + /// - the normal case: split R into two regions, by connecting vEvent to + /// the rightmost vertex of U or L lying to the left of the sweep line + /// + /// - the degenerate case: if vEvent is close enough to U or L, we + /// merge vEvent into that edge chain. The subcases are: + /// - merging with the rightmost vertex of U or L + /// - merging with the active edge of U or L + /// - merging with an already-processed portion of U or L + /// + private void ConnectLeftVertex(MeshUtils.Vertex vEvent) { - ConnectLeftDegenerate(regUp, vEvent); - return; - } - - // Connect vEvent to rightmost processed vertex of either chain. - // e._Dst is the vertex that we will connect to vEvent. - var reg = Geom.VertLeq(eLo._Dst, eUp._Dst) ? regUp : regLo; + var tmp = new ActiveRegion(); - if (regUp._inside || reg._fixUpperEdge) - { - MeshUtils.Edge eNew; - if (reg == regUp) + // Get a pointer to the active region containing vEvent + tmp._eUp = vEvent._anEdge._Sym; + var regUp = _dict.Find(tmp).Key; + var regLo = RegionBelow(regUp); + if (regLo == null) { - eNew = _mesh.Connect(vEvent._anEdge._Sym, eUp._Lnext); + // This may happen if the input polygon is coplanar. + return; } - else + var eUp = regUp._eUp; + var eLo = regLo._eUp; + + // Try merging with U or L first + if (Geom.EdgeSign(eUp._Dst, vEvent, eUp._Org) == 0.0f) { - eNew = _mesh.Connect(eLo._Dnext, vEvent._anEdge)._Sym; + ConnectLeftDegenerate(regUp, vEvent); + return; } - if (reg._fixUpperEdge) + + // Connect vEvent to rightmost processed vertex of either chain. + // e._Dst is the vertex that we will connect to vEvent. + var reg = Geom.VertLeq(eLo._Dst, eUp._Dst) ? regUp : regLo; + + if (regUp._inside || reg._fixUpperEdge) { - FixUpperEdge(reg, eNew); + MeshUtils.Edge eNew; + if (reg == regUp) + { + eNew = _mesh.Connect(vEvent._anEdge._Sym, eUp._Lnext); + } + else + { + eNew = _mesh.Connect(eLo._Dnext, vEvent._anEdge)._Sym; + } + if (reg._fixUpperEdge) + { + FixUpperEdge(reg, eNew); + } + else + { + ComputeWinding(AddRegionBelow(regUp, eNew)); + } + SweepEvent(vEvent); } else { - ComputeWinding(AddRegionBelow(regUp, eNew)); + // The new vertex is in a region which does not belong to the polygon. + // We don't need to connect this vertex to the rest of the mesh. + AddRightEdges(regUp, vEvent._anEdge, vEvent._anEdge, null, true); } - SweepEvent(vEvent); } - else + + /// + /// Does everything necessary when the sweep line crosses a vertex. + /// Updates the mesh and the edge dictionary. + /// + private void SweepEvent(MeshUtils.Vertex vEvent) { - // The new vertex is in a region which does not belong to the polygon. - // We don't need to connect this vertex to the rest of the mesh. - AddRightEdges(regUp, vEvent._anEdge, vEvent._anEdge, null, true); - } - } + _event = vEvent; - /// - /// Does everything necessary when the sweep line crosses a vertex. - /// Updates the mesh and the edge dictionary. - /// - private void SweepEvent(MeshUtils.Vertex vEvent) - { - _event = vEvent; + // Check if this vertex is the right endpoint of an edge that is + // already in the dictionary. In this case we don't need to waste + // time searching for the location to insert new edges. + var e = vEvent._anEdge; + while (e._activeRegion == null) + { + e = e._Onext; + if (e == vEvent._anEdge) + { + // All edges go right -- not incident to any processed edges + ConnectLeftVertex(vEvent); + return; + } + } - // Check if this vertex is the right endpoint of an edge that is - // already in the dictionary. In this case we don't need to waste - // time searching for the location to insert new edges. - var e = vEvent._anEdge; - while (e._activeRegion == null) - { - e = e._Onext; - if (e == vEvent._anEdge) + // Processing consists of two phases: first we "finish" all the + // active regions where both the upper and lower edges terminate + // at vEvent (ie. vEvent is closing off these regions). + // We mark these faces "inside" or "outside" the polygon according + // to their winding number, and delete the edges from the dictionary. + // This takes care of all the left-going edges from vEvent. + var regUp = TopLeftRegion(e._activeRegion); + var reg = RegionBelow(regUp); + var eTopLeft = reg._eUp; + var eBottomLeft = FinishLeftRegions(reg, null); + + // Next we process all the right-going edges from vEvent. This + // involves adding the edges to the dictionary, and creating the + // associated "active regions" which record information about the + // regions between adjacent dictionary edges. + if (eBottomLeft._Onext == eTopLeft) { - // All edges go right -- not incident to any processed edges - ConnectLeftVertex(vEvent); - return; + // No right-going edges -- add a temporary "fixable" edge + ConnectRightVertex(regUp, eBottomLeft); + } + else + { + AddRightEdges(regUp, eBottomLeft._Onext, eTopLeft, eTopLeft, true); } } - // Processing consists of two phases: first we "finish" all the - // active regions where both the upper and lower edges terminate - // at vEvent (ie. vEvent is closing off these regions). - // We mark these faces "inside" or "outside" the polygon according - // to their winding number, and delete the edges from the dictionary. - // This takes care of all the left-going edges from vEvent. - var regUp = TopLeftRegion(e._activeRegion); - var reg = RegionBelow(regUp); - var eTopLeft = reg._eUp; - var eBottomLeft = FinishLeftRegions(reg, null); - - // Next we process all the right-going edges from vEvent. This - // involves adding the edges to the dictionary, and creating the - // associated "active regions" which record information about the - // regions between adjacent dictionary edges. - if (eBottomLeft._Onext == eTopLeft) + /// + /// Make the sentinel coordinates big enough that they will never be + /// merged with real input features. + /// + /// We add two sentinel edges above and below all other edges, + /// to avoid special cases at the top and bottom. + /// + private void AddSentinel(Real smin, Real smax, Real t) { - // No right-going edges -- add a temporary "fixable" edge - ConnectRightVertex(regUp, eBottomLeft); + var e = _mesh.MakeEdge(); + e._Org._s = smax; + e._Org._t = t; + e._Dst._s = smin; + e._Dst._t = t; + _event = e._Dst; // initialize it + + var reg = new ActiveRegion(); + reg._eUp = e; + reg._windingNumber = 0; + reg._inside = false; + reg._fixUpperEdge = false; + reg._sentinel = true; + reg._dirty = false; + reg._nodeUp = _dict.Insert(reg); } - else - { - AddRightEdges(regUp, eBottomLeft._Onext, eTopLeft, eTopLeft, true); - } - } - - /// - /// Make the sentinel coordinates big enough that they will never be - /// merged with real input features. - /// - /// We add two sentinel edges above and below all other edges, - /// to avoid special cases at the top and bottom. - /// - private void AddSentinel(Real smin, Real smax, Real t) - { - var e = _mesh.MakeEdge(); - e._Org._s = smax; - e._Org._t = t; - e._Dst._s = smin; - e._Dst._t = t; - _event = e._Dst; // initialize it - - var reg = new ActiveRegion(); - reg._eUp = e; - reg._windingNumber = 0; - reg._inside = false; - reg._fixUpperEdge = false; - reg._sentinel = true; - reg._dirty = false; - reg._nodeUp = _dict.Insert(reg); - } - /// - /// We maintain an ordering of edge intersections with the sweep line. - /// This order is maintained in a dynamic dictionary. - /// - private void InitEdgeDict() - { - _dict = new Dict(EdgeLeq); - - AddSentinel(-SentinelCoord, SentinelCoord, -SentinelCoord); - AddSentinel(-SentinelCoord, SentinelCoord, +SentinelCoord); - } + /// + /// We maintain an ordering of edge intersections with the sweep line. + /// This order is maintained in a dynamic dictionary. + /// + private void InitEdgeDict() + { + _dict = new Dict(EdgeLeq); - private void DoneEdgeDict() - { - int fixedEdges = 0; + AddSentinel(-SentinelCoord, SentinelCoord, -SentinelCoord); + AddSentinel(-SentinelCoord, SentinelCoord, +SentinelCoord); + } - ActiveRegion reg; - while ((reg = _dict.Min().Key) != null) + private void DoneEdgeDict() { - // At the end of all processing, the dictionary should contain - // only the two sentinel edges, plus at most one "fixable" edge - // created by ConnectRightVertex(). - if (!reg._sentinel) + int fixedEdges = 0; + + ActiveRegion reg; + while ((reg = _dict.Min().Key) != null) { - Debug.Assert(reg._fixUpperEdge); - Debug.Assert(++fixedEdges == 1); + // At the end of all processing, the dictionary should contain + // only the two sentinel edges, plus at most one "fixable" edge + // created by ConnectRightVertex(). + if (!reg._sentinel) + { + Debug.Assert(reg._fixUpperEdge); + Debug.Assert(++fixedEdges == 1); + } + Debug.Assert(reg._windingNumber == 0); + DeleteRegion(reg); } - Debug.Assert(reg._windingNumber == 0); - DeleteRegion(reg); - } - _dict = null; - } - - /// - /// Remove zero-length edges, and contours with fewer than 3 vertices. - /// - private void RemoveDegenerateEdges() - { - MeshUtils.Edge eHead = _mesh._eHead, e, eNext, eLnext; + _dict = null; + } - for (e = eHead._next; e != eHead; e = eNext) + /// + /// Remove zero-length edges, and contours with fewer than 3 vertices. + /// + private void RemoveDegenerateEdges() { - eNext = e._next; - eLnext = e._Lnext; + MeshUtils.Edge eHead = _mesh._eHead, e, eNext, eLnext; - if (Geom.VertEq(e._Org, e._Dst) && e._Lnext._Lnext != e) + for (e = eHead._next; e != eHead; e = eNext) { - // Zero-length edge, contour has at least 3 edges - - SpliceMergeVertices(eLnext, e); // deletes e.Org - _mesh.Delete(e); // e is a self-loop - e = eLnext; + eNext = e._next; eLnext = e._Lnext; - } - if (eLnext._Lnext == e) - { - // Degenerate contour (one or two edges) - if (eLnext != e) + if (Geom.VertEq(e._Org, e._Dst) && e._Lnext._Lnext != e) { - if (eLnext == eNext || eLnext == eNext._Sym) + // Zero-length edge, contour has at least 3 edges + + SpliceMergeVertices(eLnext, e); // deletes e.Org + _mesh.Delete(e); // e is a self-loop + e = eLnext; + eLnext = e._Lnext; + } + if (eLnext._Lnext == e) + { + // Degenerate contour (one or two edges) + + if (eLnext != e) + { + if (eLnext == eNext || eLnext == eNext._Sym) + { + eNext = eNext._next; + } + _mesh.Delete(eLnext); + } + if (e == eNext || e == eNext._Sym) { eNext = eNext._next; } - _mesh.Delete(eLnext); + _mesh.Delete(e); } - if (e == eNext || e == eNext._Sym) - { - eNext = eNext._next; - } - _mesh.Delete(e); } } - } - /// - /// Insert all vertices into the priority queue which determines the - /// order in which vertices cross the sweep line. - /// - private void InitPriorityQ() - { - MeshUtils.Vertex vHead = _mesh._vHead, v; - int vertexCount = 0; - - for (v = vHead._next; v != vHead; v = v._next) + /// + /// Insert all vertices into the priority queue which determines the + /// order in which vertices cross the sweep line. + /// + private void InitPriorityQ() { - vertexCount++; - } - // Make sure there is enough space for sentinels. - vertexCount += 8; - - _pq = new PriorityQueue(vertexCount, Geom.VertLeq); - - vHead = _mesh._vHead; - for( v = vHead._next; v != vHead; v = v._next ) { - v._pqHandle = _pq.Insert(v); - if (v._pqHandle._handle == PQHandle.Invalid) + MeshUtils.Vertex vHead = _mesh._vHead, v; + int vertexCount = 0; + + for (v = vHead._next; v != vHead; v = v._next) { - throw new InvalidOperationException("PQHandle should not be invalid"); + vertexCount++; } - } - _pq.Init(); - } + // Make sure there is enough space for sentinels. + vertexCount += 8; - private void DonePriorityQ() - { - _pq = null; - } + _pq = new PriorityQueue(vertexCount, Geom.VertLeq); - /// - /// Delete any degenerate faces with only two edges. WalkDirtyRegions() - /// will catch almost all of these, but it won't catch degenerate faces - /// produced by splice operations on already-processed edges. - /// The two places this can happen are in FinishLeftRegions(), when - /// we splice in a "temporary" edge produced by ConnectRightVertex(), - /// and in CheckForLeftSplice(), where we splice already-processed - /// edges to ensure that our dictionary invariants are not violated - /// by numerical errors. - /// - /// In both these cases it is *very* dangerous to delete the offending - /// edge at the time, since one of the routines further up the stack - /// will sometimes be keeping a pointer to that edge. - /// - private void RemoveDegenerateFaces() - { - MeshUtils.Face f, fNext; - MeshUtils.Edge e; + vHead = _mesh._vHead; + for (v = vHead._next; v != vHead; v = v._next) + { + v._pqHandle = _pq.Insert(v); + if (v._pqHandle._handle == PQHandle.Invalid) + { + throw new InvalidOperationException("PQHandle should not be invalid"); + } + } + _pq.Init(); + } - for (f = _mesh._fHead._next; f != _mesh._fHead; f = fNext) + private void DonePriorityQ() { - fNext = f._next; - e = f._anEdge; - Debug.Assert(e._Lnext != e); + _pq = null; + } + + /// + /// Delete any degenerate faces with only two edges. WalkDirtyRegions() + /// will catch almost all of these, but it won't catch degenerate faces + /// produced by splice operations on already-processed edges. + /// The two places this can happen are in FinishLeftRegions(), when + /// we splice in a "temporary" edge produced by ConnectRightVertex(), + /// and in CheckForLeftSplice(), where we splice already-processed + /// edges to ensure that our dictionary invariants are not violated + /// by numerical errors. + /// + /// In both these cases it is *very* dangerous to delete the offending + /// edge at the time, since one of the routines further up the stack + /// will sometimes be keeping a pointer to that edge. + /// + private void RemoveDegenerateFaces() + { + MeshUtils.Face f, fNext; + MeshUtils.Edge e; - if (e._Lnext._Lnext == e) + for (f = _mesh._fHead._next; f != _mesh._fHead; f = fNext) { - // A face with only two edges - Geom.AddWinding(e._Onext, e); - _mesh.Delete(e); + fNext = f._next; + e = f._anEdge; + Debug.Assert(e._Lnext != e); + + if (e._Lnext._Lnext == e) + { + // A face with only two edges + Geom.AddWinding(e._Onext, e); + _mesh.Delete(e); + } } } - } - /// - /// ComputeInterior computes the planar arrangement specified - /// by the given contours, and further subdivides this arrangement - /// into regions. Each region is marked "inside" if it belongs - /// to the polygon, according to the rule given by windingRule. - /// Each interior region is guaranteed to be monotone. - /// - protected void ComputeInterior() - { - // Each vertex defines an event for our sweep line. Start by inserting - // all the vertices in a priority queue. Events are processed in - // lexicographic order, ie. - // - // e1 < e2 iff e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y) - RemoveDegenerateEdges(); - InitPriorityQ(); - RemoveDegenerateFaces(); - InitEdgeDict(); - - MeshUtils.Vertex v, vNext; - while ((v = _pq.ExtractMin()) != null) + /// + /// ComputeInterior computes the planar arrangement specified + /// by the given contours, and further subdivides this arrangement + /// into regions. Each region is marked "inside" if it belongs + /// to the polygon, according to the rule given by windingRule. + /// Each interior region is guaranteed to be monotone. + /// + protected void ComputeInterior() { - while (true) - { - vNext = _pq.Minimum(); - if (vNext == null || !Geom.VertEq(vNext, v)) + // Each vertex defines an event for our sweep line. Start by inserting + // all the vertices in a priority queue. Events are processed in + // lexicographic order, ie. + // + // e1 < e2 iff e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y) + RemoveDegenerateEdges(); + InitPriorityQ(); + RemoveDegenerateFaces(); + InitEdgeDict(); + + MeshUtils.Vertex v, vNext; + while ((v = _pq.ExtractMin()) != null) + { + while (true) { - break; - } + vNext = _pq.Minimum(); + if (vNext == null || !Geom.VertEq(vNext, v)) + { + break; + } - // Merge together all vertices at exactly the same location. - // This is more efficient than processing them one at a time, - // simplifies the code (see ConnectLeftDegenerate), and is also - // important for correct handling of certain degenerate cases. - // For example, suppose there are two identical edges A and B - // that belong to different contours (so without this code they would - // be processed by separate sweep events). Suppose another edge C - // crosses A and B from above. When A is processed, we split it - // at its intersection point with C. However this also splits C, - // so when we insert B we may compute a slightly different - // intersection point. This might leave two edges with a small - // gap between them. This kind of error is especially obvious - // when using boundary extraction (BoundaryOnly). - vNext = _pq.ExtractMin(); - SpliceMergeVertices(v._anEdge, vNext._anEdge); + // Merge together all vertices at exactly the same location. + // This is more efficient than processing them one at a time, + // simplifies the code (see ConnectLeftDegenerate), and is also + // important for correct handling of certain degenerate cases. + // For example, suppose there are two identical edges A and B + // that belong to different contours (so without this code they would + // be processed by separate sweep events). Suppose another edge C + // crosses A and B from above. When A is processed, we split it + // at its intersection point with C. However this also splits C, + // so when we insert B we may compute a slightly different + // intersection point. This might leave two edges with a small + // gap between them. This kind of error is especially obvious + // when using boundary extraction (BoundaryOnly). + vNext = _pq.ExtractMin(); + SpliceMergeVertices(v._anEdge, vNext._anEdge); + } + SweepEvent(v); } - SweepEvent(v); - } - DoneEdgeDict(); - DonePriorityQ(); + DoneEdgeDict(); + DonePriorityQ(); - RemoveDegenerateFaces(); - _mesh.Check(); + RemoveDegenerateFaces(); + _mesh.Check(); + } } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Tess.cs b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Tess.cs index 78b1bb51e2d..6395ff770d7 100644 --- a/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Tess.cs +++ b/com.unity.render-pipelines.universal/Runtime/External/LibTessDotNet/Tess.cs @@ -1,5 +1,5 @@ /* -** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) +** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** @@ -9,10 +9,10 @@ ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: -** +** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be -** included in all copies or substantial portions of the Software. +** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A @@ -20,7 +20,7 @@ ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. -** +** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. @@ -36,715 +36,717 @@ namespace UnityEngine.Experimental.Rendering.Universal { - -using Real = System.Single; -namespace LibTessDotNet -{ - internal enum WindingRule - { - EvenOdd, - NonZero, - Positive, - Negative, - AbsGeqTwo - } - - internal enum ElementType + using Real = System.Single; + namespace LibTessDotNet { - Polygons, - ConnectedPolygons, - BoundaryContours - } + internal enum WindingRule + { + EvenOdd, + NonZero, + Positive, + Negative, + AbsGeqTwo + } - internal enum ContourOrientation - { - Original, - Clockwise, - CounterClockwise - } + internal enum ElementType + { + Polygons, + ConnectedPolygons, + BoundaryContours + } - internal struct ContourVertex - { - public Vec3 Position; - public object Data; + internal enum ContourOrientation + { + Original, + Clockwise, + CounterClockwise + } - public override string ToString() + internal struct ContourVertex { - return string.Format("{0}, {1}", Position, Data); + public Vec3 Position; + public object Data; + + public override string ToString() + { + return string.Format("{0}, {1}", Position, Data); + } } - } - internal delegate object CombineCallback(Vec3 position, object[] data, Real[] weights); + internal delegate object CombineCallback(Vec3 position, object[] data, Real[] weights); - internal partial class Tess - { - private Mesh _mesh; - private Vec3 _normal; - private Vec3 _sUnit; - private Vec3 _tUnit; + internal partial class Tess + { + private Mesh _mesh; + private Vec3 _normal; + private Vec3 _sUnit; + private Vec3 _tUnit; - private Real _bminX, _bminY, _bmaxX, _bmaxY; + private Real _bminX, _bminY, _bmaxX, _bmaxY; - private WindingRule _windingRule; + private WindingRule _windingRule; - private Dict _dict; - private PriorityQueue _pq; - private MeshUtils.Vertex _event; + private Dict _dict; + private PriorityQueue _pq; + private MeshUtils.Vertex _event; - private CombineCallback _combineCallback; + private CombineCallback _combineCallback; - private ContourVertex[] _vertices; - private int _vertexCount; - private int[] _elements; - private int _elementCount; + private ContourVertex[] _vertices; + private int _vertexCount; + private int[] _elements; + private int _elementCount; - public Vec3 Normal { get { return _normal; } set { _normal = value; } } + public Vec3 Normal { get { return _normal; } set { _normal = value; } } - public Real SUnitX = 1; - public Real SUnitY = 0; + public Real SUnitX = 1; + public Real SUnitY = 0; #if DOUBLE - public Real SentinelCoord = 4e150; + public Real SentinelCoord = 4e150; #else - public Real SentinelCoord = 4e30f; + public Real SentinelCoord = 4e30f; #endif - /// - /// If true, will remove empty (zero area) polygons. - /// - public bool NoEmptyPolygons = false; + /// + /// If true, will remove empty (zero area) polygons. + /// + public bool NoEmptyPolygons = false; - /// - /// If true, will use pooling to reduce GC (compare performance with/without, can vary wildly). - /// - public bool UsePooling = false; + /// + /// If true, will use pooling to reduce GC (compare performance with/without, can vary wildly). + /// + public bool UsePooling = false; - public ContourVertex[] Vertices { get { return _vertices; } } - public int VertexCount { get { return _vertexCount; } } + public ContourVertex[] Vertices { get { return _vertices; } } + public int VertexCount { get { return _vertexCount; } } - public int[] Elements { get { return _elements; } } - public int ElementCount { get { return _elementCount; } } + public int[] Elements { get { return _elements; } } + public int ElementCount { get { return _elementCount; } } - public Tess() - { - _normal = Vec3.Zero; - _bminX = _bminY = _bmaxX = _bmaxY = 0; + public Tess() + { + _normal = Vec3.Zero; + _bminX = _bminY = _bmaxX = _bmaxY = 0; - _windingRule = WindingRule.EvenOdd; - _mesh = null; + _windingRule = WindingRule.EvenOdd; + _mesh = null; - _vertices = null; - _vertexCount = 0; - _elements = null; - _elementCount = 0; - } + _vertices = null; + _vertexCount = 0; + _elements = null; + _elementCount = 0; + } - private void ComputeNormal(ref Vec3 norm) - { - var v = _mesh._vHead._next; + private void ComputeNormal(ref Vec3 norm) + { + var v = _mesh._vHead._next; - var minVal = new Real[3] { v._coords.X, v._coords.Y, v._coords.Z }; - var minVert = new MeshUtils.Vertex[3] { v, v, v }; - var maxVal = new Real[3] { v._coords.X, v._coords.Y, v._coords.Z }; - var maxVert = new MeshUtils.Vertex[3] { v, v, v }; + var minVal = new Real[3] { v._coords.X, v._coords.Y, v._coords.Z }; + var minVert = new MeshUtils.Vertex[3] { v, v, v }; + var maxVal = new Real[3] { v._coords.X, v._coords.Y, v._coords.Z }; + var maxVert = new MeshUtils.Vertex[3] { v, v, v }; - for (; v != _mesh._vHead; v = v._next) - { - if (v._coords.X < minVal[0]) { minVal[0] = v._coords.X; minVert[0] = v; } - if (v._coords.Y < minVal[1]) { minVal[1] = v._coords.Y; minVert[1] = v; } - if (v._coords.Z < minVal[2]) { minVal[2] = v._coords.Z; minVert[2] = v; } - if (v._coords.X > maxVal[0]) { maxVal[0] = v._coords.X; maxVert[0] = v; } - if (v._coords.Y > maxVal[1]) { maxVal[1] = v._coords.Y; maxVert[1] = v; } - if (v._coords.Z > maxVal[2]) { maxVal[2] = v._coords.Z; maxVert[2] = v; } - } + for (; v != _mesh._vHead; v = v._next) + { + if (v._coords.X < minVal[0]) { minVal[0] = v._coords.X; minVert[0] = v; } + if (v._coords.Y < minVal[1]) { minVal[1] = v._coords.Y; minVert[1] = v; } + if (v._coords.Z < minVal[2]) { minVal[2] = v._coords.Z; minVert[2] = v; } + if (v._coords.X > maxVal[0]) { maxVal[0] = v._coords.X; maxVert[0] = v; } + if (v._coords.Y > maxVal[1]) { maxVal[1] = v._coords.Y; maxVert[1] = v; } + if (v._coords.Z > maxVal[2]) { maxVal[2] = v._coords.Z; maxVert[2] = v; } + } - // Find two vertices separated by at least 1/sqrt(3) of the maximum - // distance between any two vertices - int i = 0; - if (maxVal[1] - minVal[1] > maxVal[0] - minVal[0]) { i = 1; } - if (maxVal[2] - minVal[2] > maxVal[i] - minVal[i]) { i = 2; } - if (minVal[i] >= maxVal[i]) - { - // All vertices are the same -- normal doesn't matter - norm = new Vec3 { X = 0, Y = 0, Z = 1 }; - return; - } + // Find two vertices separated by at least 1/sqrt(3) of the maximum + // distance between any two vertices + int i = 0; + if (maxVal[1] - minVal[1] > maxVal[0] - minVal[0]) { i = 1; } + if (maxVal[2] - minVal[2] > maxVal[i] - minVal[i]) { i = 2; } + if (minVal[i] >= maxVal[i]) + { + // All vertices are the same -- normal doesn't matter + norm = new Vec3 { X = 0, Y = 0, Z = 1 }; + return; + } - // Look for a third vertex which forms the triangle with maximum area - // (Length of normal == twice the triangle area) - Real maxLen2 = 0, tLen2; - var v1 = minVert[i]; - var v2 = maxVert[i]; - Vec3 d1, d2, tNorm; - Vec3.Sub(ref v1._coords, ref v2._coords, out d1); - for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) - { - Vec3.Sub(ref v._coords, ref v2._coords, out d2); - tNorm.X = d1.Y * d2.Z - d1.Z * d2.Y; - tNorm.Y = d1.Z * d2.X - d1.X * d2.Z; - tNorm.Z = d1.X * d2.Y - d1.Y * d2.X; - tLen2 = tNorm.X*tNorm.X + tNorm.Y*tNorm.Y + tNorm.Z*tNorm.Z; - if (tLen2 > maxLen2) + // Look for a third vertex which forms the triangle with maximum area + // (Length of normal == twice the triangle area) + Real maxLen2 = 0, tLen2; + var v1 = minVert[i]; + var v2 = maxVert[i]; + Vec3 d1, d2, tNorm; + Vec3.Sub(ref v1._coords, ref v2._coords, out d1); + for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) { - maxLen2 = tLen2; - norm = tNorm; + Vec3.Sub(ref v._coords, ref v2._coords, out d2); + tNorm.X = d1.Y * d2.Z - d1.Z * d2.Y; + tNorm.Y = d1.Z * d2.X - d1.X * d2.Z; + tNorm.Z = d1.X * d2.Y - d1.Y * d2.X; + tLen2 = tNorm.X * tNorm.X + tNorm.Y * tNorm.Y + tNorm.Z * tNorm.Z; + if (tLen2 > maxLen2) + { + maxLen2 = tLen2; + norm = tNorm; + } } - } - if (maxLen2 <= 0.0f) - { - // All points lie on a single line -- any decent normal will do - norm = Vec3.Zero; - i = Vec3.LongAxis(ref d1); - norm[i] = 1; + if (maxLen2 <= 0.0f) + { + // All points lie on a single line -- any decent normal will do + norm = Vec3.Zero; + i = Vec3.LongAxis(ref d1); + norm[i] = 1; + } } - } - private void CheckOrientation() - { - // When we compute the normal automatically, we choose the orientation - // so that the the sum of the signed areas of all contours is non-negative. - Real area = 0.0f; - for (var f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) + private void CheckOrientation() { - if (f._anEdge._winding <= 0) + // When we compute the normal automatically, we choose the orientation + // so that the the sum of the signed areas of all contours is non-negative. + Real area = 0.0f; + for (var f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) { - continue; + if (f._anEdge._winding <= 0) + { + continue; + } + area += MeshUtils.FaceArea(f); } - area += MeshUtils.FaceArea(f); - } - if (area < 0.0f) - { - // Reverse the orientation by flipping all the t-coordinates - for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) + if (area < 0.0f) { - v._t = -v._t; + // Reverse the orientation by flipping all the t-coordinates + for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) + { + v._t = -v._t; + } + Vec3.Neg(ref _tUnit); } - Vec3.Neg(ref _tUnit); } - } - - private void ProjectPolygon() - { - var norm = _normal; - bool computedNormal = false; - if (norm.X == 0.0f && norm.Y == 0.0f && norm.Z == 0.0f) + private void ProjectPolygon() { - ComputeNormal(ref norm); - _normal = norm; - computedNormal = true; - } + var norm = _normal; - int i = Vec3.LongAxis(ref norm); + bool computedNormal = false; + if (norm.X == 0.0f && norm.Y == 0.0f && norm.Z == 0.0f) + { + ComputeNormal(ref norm); + _normal = norm; + computedNormal = true; + } - _sUnit[i] = 0; - _sUnit[(i + 1) % 3] = SUnitX; - _sUnit[(i + 2) % 3] = SUnitY; + int i = Vec3.LongAxis(ref norm); - _tUnit[i] = 0; - _tUnit[(i + 1) % 3] = norm[i] > 0.0f ? -SUnitY : SUnitY; - _tUnit[(i + 2) % 3] = norm[i] > 0.0f ? SUnitX : -SUnitX; + _sUnit[i] = 0; + _sUnit[(i + 1) % 3] = SUnitX; + _sUnit[(i + 2) % 3] = SUnitY; - // Project the vertices onto the sweep plane - for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) - { - Vec3.Dot(ref v._coords, ref _sUnit, out v._s); - Vec3.Dot(ref v._coords, ref _tUnit, out v._t); - } - if (computedNormal) - { - CheckOrientation(); - } + _tUnit[i] = 0; + _tUnit[(i + 1) % 3] = norm[i] > 0.0f ? -SUnitY : SUnitY; + _tUnit[(i + 2) % 3] = norm[i] > 0.0f ? SUnitX : -SUnitX; - // Compute ST bounds. - bool first = true; - for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) - { - if (first) + // Project the vertices onto the sweep plane + for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) { - _bminX = _bmaxX = v._s; - _bminY = _bmaxY = v._t; - first = false; + Vec3.Dot(ref v._coords, ref _sUnit, out v._s); + Vec3.Dot(ref v._coords, ref _tUnit, out v._t); } - else + if (computedNormal) { - if (v._s < _bminX) _bminX = v._s; - if (v._s > _bmaxX) _bmaxX = v._s; - if (v._t < _bminY) _bminY = v._t; - if (v._t > _bmaxY) _bmaxY = v._t; + CheckOrientation(); } - } - } - - /// - /// TessellateMonoRegion( face ) tessellates a monotone region - /// (what else would it do??) The region must consist of a single - /// loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this - /// case means that any vertical line intersects the interior of the - /// region in a single interval. - /// - /// Tessellation consists of adding interior edges (actually pairs of - /// half-edges), to split the region into non-overlapping triangles. - /// - /// The basic idea is explained in Preparata and Shamos (which I don't - /// have handy right now), although their implementation is more - /// complicated than this one. The are two edge chains, an upper chain - /// and a lower chain. We process all vertices from both chains in order, - /// from right to left. - /// - /// The algorithm ensures that the following invariant holds after each - /// vertex is processed: the untessellated region consists of two - /// chains, where one chain (say the upper) is a single edge, and - /// the other chain is concave. The left vertex of the single edge - /// is always to the left of all vertices in the concave chain. - /// - /// Each step consists of adding the rightmost unprocessed vertex to one - /// of the two chains, and forming a fan of triangles from the rightmost - /// of two chain endpoints. Determining whether we can add each triangle - /// to the fan is a simple orientation test. By making the fan as large - /// as possible, we restore the invariant (check it yourself). - /// - private void TessellateMonoRegion(MeshUtils.Face face) - { - // All edges are oriented CCW around the boundary of the region. - // First, find the half-edge whose origin vertex is rightmost. - // Since the sweep goes from left to right, face->anEdge should - // be close to the edge we want. - var up = face._anEdge; - Debug.Assert(up._Lnext != up && up._Lnext._Lnext != up); - - while (Geom.VertLeq(up._Dst, up._Org)) up = up._Lprev; - while (Geom.VertLeq(up._Org, up._Dst)) up = up._Lnext; - var lo = up._Lprev; - - while (up._Lnext != lo) - { - if (Geom.VertLeq(up._Dst, lo._Org)) + // Compute ST bounds. + bool first = true; + for (var v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) { - // up.Dst is on the left. It is safe to form triangles from lo.Org. - // The EdgeGoesLeft test guarantees progress even when some triangles - // are CW, given that the upper and lower chains are truly monotone. - while (lo._Lnext != up && (Geom.EdgeGoesLeft(lo._Lnext) - || Geom.EdgeSign(lo._Org, lo._Dst, lo._Lnext._Dst) <= 0.0f)) + if (first) + { + _bminX = _bmaxX = v._s; + _bminY = _bmaxY = v._t; + first = false; + } + else { - lo = _mesh.Connect(lo._Lnext, lo)._Sym; + if (v._s < _bminX) _bminX = v._s; + if (v._s > _bmaxX) _bmaxX = v._s; + if (v._t < _bminY) _bminY = v._t; + if (v._t > _bmaxY) _bmaxY = v._t; } - lo = lo._Lprev; } - else + } + + /// + /// TessellateMonoRegion( face ) tessellates a monotone region + /// (what else would it do??) The region must consist of a single + /// loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this + /// case means that any vertical line intersects the interior of the + /// region in a single interval. + /// + /// Tessellation consists of adding interior edges (actually pairs of + /// half-edges), to split the region into non-overlapping triangles. + /// + /// The basic idea is explained in Preparata and Shamos (which I don't + /// have handy right now), although their implementation is more + /// complicated than this one. The are two edge chains, an upper chain + /// and a lower chain. We process all vertices from both chains in order, + /// from right to left. + /// + /// The algorithm ensures that the following invariant holds after each + /// vertex is processed: the untessellated region consists of two + /// chains, where one chain (say the upper) is a single edge, and + /// the other chain is concave. The left vertex of the single edge + /// is always to the left of all vertices in the concave chain. + /// + /// Each step consists of adding the rightmost unprocessed vertex to one + /// of the two chains, and forming a fan of triangles from the rightmost + /// of two chain endpoints. Determining whether we can add each triangle + /// to the fan is a simple orientation test. By making the fan as large + /// as possible, we restore the invariant (check it yourself). + /// + private void TessellateMonoRegion(MeshUtils.Face face) + { + // All edges are oriented CCW around the boundary of the region. + // First, find the half-edge whose origin vertex is rightmost. + // Since the sweep goes from left to right, face->anEdge should + // be close to the edge we want. + var up = face._anEdge; + Debug.Assert(up._Lnext != up && up._Lnext._Lnext != up); + + while (Geom.VertLeq(up._Dst, up._Org)) up = up._Lprev; + while (Geom.VertLeq(up._Org, up._Dst)) up = up._Lnext; + + var lo = up._Lprev; + + while (up._Lnext != lo) { - // lo.Org is on the left. We can make CCW triangles from up.Dst. - while (lo._Lnext != up && (Geom.EdgeGoesRight(up._Lprev) - || Geom.EdgeSign(up._Dst, up._Org, up._Lprev._Org) >= 0.0f)) + if (Geom.VertLeq(up._Dst, lo._Org)) + { + // up.Dst is on the left. It is safe to form triangles from lo.Org. + // The EdgeGoesLeft test guarantees progress even when some triangles + // are CW, given that the upper and lower chains are truly monotone. + while (lo._Lnext != up && (Geom.EdgeGoesLeft(lo._Lnext) + || Geom.EdgeSign(lo._Org, lo._Dst, lo._Lnext._Dst) <= 0.0f)) + { + lo = _mesh.Connect(lo._Lnext, lo)._Sym; + } + lo = lo._Lprev; + } + else { - up = _mesh.Connect(up, up._Lprev)._Sym; + // lo.Org is on the left. We can make CCW triangles from up.Dst. + while (lo._Lnext != up && (Geom.EdgeGoesRight(up._Lprev) + || Geom.EdgeSign(up._Dst, up._Org, up._Lprev._Org) >= 0.0f)) + { + up = _mesh.Connect(up, up._Lprev)._Sym; + } + up = up._Lnext; } - up = up._Lnext; } - } - // Now lo.Org == up.Dst == the leftmost vertex. The remaining region - // can be tessellated in a fan from this leftmost vertex. - Debug.Assert(lo._Lnext != up); - while (lo._Lnext._Lnext != up) - { - lo = _mesh.Connect(lo._Lnext, lo)._Sym; + // Now lo.Org == up.Dst == the leftmost vertex. The remaining region + // can be tessellated in a fan from this leftmost vertex. + Debug.Assert(lo._Lnext != up); + while (lo._Lnext._Lnext != up) + { + lo = _mesh.Connect(lo._Lnext, lo)._Sym; + } } - } - /// - /// TessellateInterior( mesh ) tessellates each region of - /// the mesh which is marked "inside" the polygon. Each such region - /// must be monotone. - /// - private void TessellateInterior() - { - MeshUtils.Face f, next; - for (f = _mesh._fHead._next; f != _mesh._fHead; f = next) + /// + /// TessellateInterior( mesh ) tessellates each region of + /// the mesh which is marked "inside" the polygon. Each such region + /// must be monotone. + /// + private void TessellateInterior() { - // Make sure we don't try to tessellate the new triangles. - next = f._next; - if (f._inside) + MeshUtils.Face f, next; + for (f = _mesh._fHead._next; f != _mesh._fHead; f = next) { - TessellateMonoRegion(f); + // Make sure we don't try to tessellate the new triangles. + next = f._next; + if (f._inside) + { + TessellateMonoRegion(f); + } } } - } - - /// - /// DiscardExterior zaps (ie. sets to null) all faces - /// which are not marked "inside" the polygon. Since further mesh operations - /// on NULL faces are not allowed, the main purpose is to clean up the - /// mesh so that exterior loops are not represented in the data structure. - /// - private void DiscardExterior() - { - MeshUtils.Face f, next; - for (f = _mesh._fHead._next; f != _mesh._fHead; f = next) + /// + /// DiscardExterior zaps (ie. sets to null) all faces + /// which are not marked "inside" the polygon. Since further mesh operations + /// on NULL faces are not allowed, the main purpose is to clean up the + /// mesh so that exterior loops are not represented in the data structure. + /// + private void DiscardExterior() { - // Since f will be destroyed, save its next pointer. - next = f._next; - if( ! f._inside ) { - _mesh.ZapFace(f); + MeshUtils.Face f, next; + + for (f = _mesh._fHead._next; f != _mesh._fHead; f = next) + { + // Since f will be destroyed, save its next pointer. + next = f._next; + if (!f._inside) + { + _mesh.ZapFace(f); + } } } - } - - /// - /// SetWindingNumber( value, keepOnlyBoundary ) resets the - /// winding numbers on all edges so that regions marked "inside" the - /// polygon have a winding number of "value", and regions outside - /// have a winding number of 0. - /// - /// If keepOnlyBoundary is TRUE, it also deletes all edges which do not - /// separate an interior region from an exterior one. - /// - private void SetWindingNumber(int value, bool keepOnlyBoundary) - { - MeshUtils.Edge e, eNext; - for (e = _mesh._eHead._next; e != _mesh._eHead; e = eNext) + /// + /// SetWindingNumber( value, keepOnlyBoundary ) resets the + /// winding numbers on all edges so that regions marked "inside" the + /// polygon have a winding number of "value", and regions outside + /// have a winding number of 0. + /// + /// If keepOnlyBoundary is TRUE, it also deletes all edges which do not + /// separate an interior region from an exterior one. + /// + private void SetWindingNumber(int value, bool keepOnlyBoundary) { - eNext = e._next; - if (e._Rface._inside != e._Lface._inside) - { + MeshUtils.Edge e, eNext; - /* This is a boundary edge (one side is interior, one is exterior). */ - e._winding = (e._Lface._inside) ? value : -value; - } - else + for (e = _mesh._eHead._next; e != _mesh._eHead; e = eNext) { - - /* Both regions are interior, or both are exterior. */ - if (!keepOnlyBoundary) + eNext = e._next; + if (e._Rface._inside != e._Lface._inside) { - e._winding = 0; + /* This is a boundary edge (one side is interior, one is exterior). */ + e._winding = (e._Lface._inside) ? value : -value; } else { - _mesh.Delete(e); + /* Both regions are interior, or both are exterior. */ + if (!keepOnlyBoundary) + { + e._winding = 0; + } + else + { + _mesh.Delete(e); + } } } } - } - - private int GetNeighbourFace(MeshUtils.Edge edge) - { - if (edge._Rface == null) - return MeshUtils.Undef; - if (!edge._Rface._inside) - return MeshUtils.Undef; - return edge._Rface._n; - } - - private void OutputPolymesh(ElementType elementType, int polySize) - { - MeshUtils.Vertex v; - MeshUtils.Face f; - MeshUtils.Edge edge; - int maxFaceCount = 0; - int maxVertexCount = 0; - int faceVerts, i; - - if (polySize < 3) + private int GetNeighbourFace(MeshUtils.Edge edge) { - polySize = 3; + if (edge._Rface == null) + return MeshUtils.Undef; + if (!edge._Rface._inside) + return MeshUtils.Undef; + return edge._Rface._n; } - // Assume that the input data is triangles now. - // Try to merge as many polygons as possible - if (polySize > 3) + + private void OutputPolymesh(ElementType elementType, int polySize) { - _mesh.MergeConvexFaces(polySize); - } + MeshUtils.Vertex v; + MeshUtils.Face f; + MeshUtils.Edge edge; + int maxFaceCount = 0; + int maxVertexCount = 0; + int faceVerts, i; - // Mark unused - for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) - v._n = MeshUtils.Undef; + if (polySize < 3) + { + polySize = 3; + } + // Assume that the input data is triangles now. + // Try to merge as many polygons as possible + if (polySize > 3) + { + _mesh.MergeConvexFaces(polySize); + } - // Create unique IDs for all vertices and faces. - for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) - { - f._n = MeshUtils.Undef; - if (!f._inside) continue; + // Mark unused + for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) + v._n = MeshUtils.Undef; - if (NoEmptyPolygons) + // Create unique IDs for all vertices and faces. + for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) { - var area = MeshUtils.FaceArea(f); - if (Math.Abs(area) < Real.Epsilon) + f._n = MeshUtils.Undef; + if (!f._inside) continue; + + if (NoEmptyPolygons) { - continue; + var area = MeshUtils.FaceArea(f); + if (Math.Abs(area) < Real.Epsilon) + { + continue; + } } - } - edge = f._anEdge; - faceVerts = 0; - do { - v = edge._Org; - if (v._n == MeshUtils.Undef) + edge = f._anEdge; + faceVerts = 0; + do { - v._n = maxVertexCount; - maxVertexCount++; + v = edge._Org; + if (v._n == MeshUtils.Undef) + { + v._n = maxVertexCount; + maxVertexCount++; + } + faceVerts++; + edge = edge._Lnext; } - faceVerts++; - edge = edge._Lnext; - } - while (edge != f._anEdge); + while (edge != f._anEdge); - Debug.Assert(faceVerts <= polySize); + Debug.Assert(faceVerts <= polySize); - f._n = maxFaceCount; - ++maxFaceCount; - } - - _elementCount = maxFaceCount; - if (elementType == ElementType.ConnectedPolygons) - maxFaceCount *= 2; - _elements = new int[maxFaceCount * polySize]; - - _vertexCount = maxVertexCount; - _vertices = new ContourVertex[_vertexCount]; - - // Output vertices. - for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) - { - if (v._n != MeshUtils.Undef) - { - // Store coordinate - _vertices[v._n].Position = v._coords; - _vertices[v._n].Data = v._data; + f._n = maxFaceCount; + ++maxFaceCount; } - } - // Output indices. - int elementIndex = 0; - for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) - { - if (!f._inside) continue; + _elementCount = maxFaceCount; + if (elementType == ElementType.ConnectedPolygons) + maxFaceCount *= 2; + _elements = new int[maxFaceCount * polySize]; - if (NoEmptyPolygons) + _vertexCount = maxVertexCount; + _vertices = new ContourVertex[_vertexCount]; + + // Output vertices. + for (v = _mesh._vHead._next; v != _mesh._vHead; v = v._next) { - var area = MeshUtils.FaceArea(f); - if (Math.Abs(area) < Real.Epsilon) + if (v._n != MeshUtils.Undef) { - continue; + // Store coordinate + _vertices[v._n].Position = v._coords; + _vertices[v._n].Data = v._data; } } - // Store polygon - edge = f._anEdge; - faceVerts = 0; - do { - v = edge._Org; - _elements[elementIndex++] = v._n; - faceVerts++; - edge = edge._Lnext; - } while (edge != f._anEdge); - // Fill unused. - for (i = faceVerts; i < polySize; ++i) + // Output indices. + int elementIndex = 0; + for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) { - _elements[elementIndex++] = MeshUtils.Undef; - } + if (!f._inside) continue; - // Store polygon connectivity - if (elementType == ElementType.ConnectedPolygons) - { + if (NoEmptyPolygons) + { + var area = MeshUtils.FaceArea(f); + if (Math.Abs(area) < Real.Epsilon) + { + continue; + } + } + + // Store polygon edge = f._anEdge; + faceVerts = 0; do { - _elements[elementIndex++] = GetNeighbourFace(edge); + v = edge._Org; + _elements[elementIndex++] = v._n; + faceVerts++; edge = edge._Lnext; - } while (edge != f._anEdge); + } + while (edge != f._anEdge); // Fill unused. for (i = faceVerts; i < polySize; ++i) { _elements[elementIndex++] = MeshUtils.Undef; } + + // Store polygon connectivity + if (elementType == ElementType.ConnectedPolygons) + { + edge = f._anEdge; + do + { + _elements[elementIndex++] = GetNeighbourFace(edge); + edge = edge._Lnext; + } + while (edge != f._anEdge); + // Fill unused. + for (i = faceVerts; i < polySize; ++i) + { + _elements[elementIndex++] = MeshUtils.Undef; + } + } } } - } - - private void OutputContours() - { - MeshUtils.Face f; - MeshUtils.Edge edge, start; - int startVert = 0; - int vertCount = 0; - - _vertexCount = 0; - _elementCount = 0; - for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) + private void OutputContours() { - if (!f._inside) continue; + MeshUtils.Face f; + MeshUtils.Edge edge, start; + int startVert = 0; + int vertCount = 0; - start = edge = f._anEdge; - do + _vertexCount = 0; + _elementCount = 0; + + for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) { - ++_vertexCount; - edge = edge._Lnext; - } - while (edge != start); + if (!f._inside) continue; - ++_elementCount; - } + start = edge = f._anEdge; + do + { + ++_vertexCount; + edge = edge._Lnext; + } + while (edge != start); - _elements = new int[_elementCount * 2]; - _vertices = new ContourVertex[_vertexCount]; + ++_elementCount; + } - int vertIndex = 0; - int elementIndex = 0; + _elements = new int[_elementCount * 2]; + _vertices = new ContourVertex[_vertexCount]; - startVert = 0; + int vertIndex = 0; + int elementIndex = 0; - for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) - { - if (!f._inside) continue; - - vertCount = 0; - start = edge = f._anEdge; - do { - _vertices[vertIndex].Position = edge._Org._coords; - _vertices[vertIndex].Data = edge._Org._data; - ++vertIndex; - ++vertCount; - edge = edge._Lnext; - } while (edge != start); - - _elements[elementIndex++] = startVert; - _elements[elementIndex++] = vertCount; - - startVert += vertCount; - } - } + startVert = 0; - private Real SignedArea(ContourVertex[] vertices) - { - Real area = 0.0f; + for (f = _mesh._fHead._next; f != _mesh._fHead; f = f._next) + { + if (!f._inside) continue; - for (int i = 0; i < vertices.Length; i++) - { - var v0 = vertices[i]; - var v1 = vertices[(i + 1) % vertices.Length]; + vertCount = 0; + start = edge = f._anEdge; + do + { + _vertices[vertIndex].Position = edge._Org._coords; + _vertices[vertIndex].Data = edge._Org._data; + ++vertIndex; + ++vertCount; + edge = edge._Lnext; + } + while (edge != start); + + _elements[elementIndex++] = startVert; + _elements[elementIndex++] = vertCount; - area += v0.Position.X * v1.Position.Y; - area -= v0.Position.Y * v1.Position.X; + startVert += vertCount; + } } - return 0.5f * area; - } + private Real SignedArea(ContourVertex[] vertices) + { + Real area = 0.0f; - public void AddContour(ContourVertex[] vertices) - { - AddContour(vertices, ContourOrientation.Original); - } + for (int i = 0; i < vertices.Length; i++) + { + var v0 = vertices[i]; + var v1 = vertices[(i + 1) % vertices.Length]; - public void AddContour(ContourVertex[] vertices, ContourOrientation forceOrientation) - { - if (_mesh == null) - { - _mesh = new Mesh(); + area += v0.Position.X * v1.Position.Y; + area -= v0.Position.Y * v1.Position.X; + } + + return 0.5f * area; } - bool reverse = false; - if (forceOrientation != ContourOrientation.Original) + public void AddContour(ContourVertex[] vertices) { - var area = SignedArea(vertices); - reverse = (forceOrientation == ContourOrientation.Clockwise && area < 0.0f) || (forceOrientation == ContourOrientation.CounterClockwise && area > 0.0f); + AddContour(vertices, ContourOrientation.Original); } - MeshUtils.Edge e = null; - for (int i = 0; i < vertices.Length; ++i) + public void AddContour(ContourVertex[] vertices, ContourOrientation forceOrientation) { - if (e == null) + if (_mesh == null) { - e = _mesh.MakeEdge(); - _mesh.Splice(e, e._Sym); + _mesh = new Mesh(); } - else + + bool reverse = false; + if (forceOrientation != ContourOrientation.Original) { - // Create a new vertex and edge which immediately follow e - // in the ordering around the left face. - _mesh.SplitEdge(e); - e = e._Lnext; + var area = SignedArea(vertices); + reverse = (forceOrientation == ContourOrientation.Clockwise && area < 0.0f) || (forceOrientation == ContourOrientation.CounterClockwise && area > 0.0f); } - int index = reverse ? vertices.Length - 1 - i : i; - // The new vertex is now e._Org. - e._Org._coords = vertices[index].Position; - e._Org._data = vertices[index].Data; + MeshUtils.Edge e = null; + for (int i = 0; i < vertices.Length; ++i) + { + if (e == null) + { + e = _mesh.MakeEdge(); + _mesh.Splice(e, e._Sym); + } + else + { + // Create a new vertex and edge which immediately follow e + // in the ordering around the left face. + _mesh.SplitEdge(e); + e = e._Lnext; + } - // The winding of an edge says how the winding number changes as we - // cross from the edge's right face to its left face. We add the - // vertices in such an order that a CCW contour will add +1 to - // the winding number of the region inside the contour. - e._winding = 1; - e._Sym._winding = -1; + int index = reverse ? vertices.Length - 1 - i : i; + // The new vertex is now e._Org. + e._Org._coords = vertices[index].Position; + e._Org._data = vertices[index].Data; + + // The winding of an edge says how the winding number changes as we + // cross from the edge's right face to its left face. We add the + // vertices in such an order that a CCW contour will add +1 to + // the winding number of the region inside the contour. + e._winding = 1; + e._Sym._winding = -1; + } } - } - - public void Tessellate(WindingRule windingRule, ElementType elementType, int polySize) - { - Tessellate(windingRule, elementType, polySize, null); - } - - public void Tessellate(WindingRule windingRule, ElementType elementType, int polySize, CombineCallback combineCallback) - { - _normal = Vec3.Zero; - _vertices = null; - _elements = null; - - _windingRule = windingRule; - _combineCallback = combineCallback; - if (_mesh == null) + public void Tessellate(WindingRule windingRule, ElementType elementType, int polySize) { - return; + Tessellate(windingRule, elementType, polySize, null); } - // Determine the polygon normal and project vertices onto the plane - // of the polygon. - ProjectPolygon(); - - // ComputeInterior computes the planar arrangement specified - // by the given contours, and further subdivides this arrangement - // into regions. Each region is marked "inside" if it belongs - // to the polygon, according to the rule given by windingRule. - // Each interior region is guaranteed be monotone. - ComputeInterior(); - - // If the user wants only the boundary contours, we throw away all edges - // except those which separate the interior from the exterior. - // Otherwise we tessellate all the regions marked "inside". - if (elementType == ElementType.BoundaryContours) + public void Tessellate(WindingRule windingRule, ElementType elementType, int polySize, CombineCallback combineCallback) { - SetWindingNumber(1, true); - } - else - { - TessellateInterior(); - } + _normal = Vec3.Zero; + _vertices = null; + _elements = null; - _mesh.Check(); + _windingRule = windingRule; + _combineCallback = combineCallback; - if (elementType == ElementType.BoundaryContours) - { - OutputContours(); - } - else - { - OutputPolymesh(elementType, polySize); - } + if (_mesh == null) + { + return; + } - if (UsePooling) - { - _mesh.Free(); + // Determine the polygon normal and project vertices onto the plane + // of the polygon. + ProjectPolygon(); + + // ComputeInterior computes the planar arrangement specified + // by the given contours, and further subdivides this arrangement + // into regions. Each region is marked "inside" if it belongs + // to the polygon, according to the rule given by windingRule. + // Each interior region is guaranteed be monotone. + ComputeInterior(); + + // If the user wants only the boundary contours, we throw away all edges + // except those which separate the interior from the exterior. + // Otherwise we tessellate all the regions marked "inside". + if (elementType == ElementType.BoundaryContours) + { + SetWindingNumber(1, true); + } + else + { + TessellateInterior(); + } + + _mesh.Check(); + + if (elementType == ElementType.BoundaryContours) + { + OutputContours(); + } + else + { + OutputPolymesh(elementType, polySize); + } + + if (UsePooling) + { + _mesh.Free(); + } + _mesh = null; } - _mesh = null; } } } - -} diff --git a/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs b/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs index 36b292b8502..8f384cd78db 100644 --- a/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs +++ b/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs @@ -53,18 +53,18 @@ public ForwardLights() } else { - LightConstantBuffer._AdditionalLightsPosition = Shader.PropertyToID("_AdditionalLightsPosition"); - LightConstantBuffer._AdditionalLightsColor = Shader.PropertyToID("_AdditionalLightsColor"); - LightConstantBuffer._AdditionalLightsAttenuation = Shader.PropertyToID("_AdditionalLightsAttenuation"); - LightConstantBuffer._AdditionalLightsSpotDir = Shader.PropertyToID("_AdditionalLightsSpotDir"); - LightConstantBuffer._AdditionalLightOcclusionProbeChannel = Shader.PropertyToID("_AdditionalLightsOcclusionProbes"); - - int maxLights = UniversalRenderPipeline.maxVisibleAdditionalLights; - m_AdditionalLightPositions = new Vector4[maxLights]; - m_AdditionalLightColors = new Vector4[maxLights]; - m_AdditionalLightAttenuations = new Vector4[maxLights]; - m_AdditionalLightSpotDirections = new Vector4[maxLights]; - m_AdditionalLightOcclusionProbeChannels = new Vector4[maxLights]; + LightConstantBuffer._AdditionalLightsPosition = Shader.PropertyToID("_AdditionalLightsPosition"); + LightConstantBuffer._AdditionalLightsColor = Shader.PropertyToID("_AdditionalLightsColor"); + LightConstantBuffer._AdditionalLightsAttenuation = Shader.PropertyToID("_AdditionalLightsAttenuation"); + LightConstantBuffer._AdditionalLightsSpotDir = Shader.PropertyToID("_AdditionalLightsSpotDir"); + LightConstantBuffer._AdditionalLightOcclusionProbeChannel = Shader.PropertyToID("_AdditionalLightsOcclusionProbes"); + + int maxLights = UniversalRenderPipeline.maxVisibleAdditionalLights; + m_AdditionalLightPositions = new Vector4[maxLights]; + m_AdditionalLightColors = new Vector4[maxLights]; + m_AdditionalLightAttenuations = new Vector4[maxLights]; + m_AdditionalLightSpotDirections = new Vector4[maxLights]; + m_AdditionalLightOcclusionProbeChannels = new Vector4[maxLights]; } } diff --git a/com.unity.render-pipelines.universal/Runtime/ForwardRenderer.cs b/com.unity.render-pipelines.universal/Runtime/ForwardRenderer.cs index 4bf83292331..eab93b9e680 100644 --- a/com.unity.render-pipelines.universal/Runtime/ForwardRenderer.cs +++ b/com.unity.render-pipelines.universal/Runtime/ForwardRenderer.cs @@ -149,7 +149,8 @@ public ForwardRenderer(ForwardRendererData data) : base(data) // - Legacy materials have unamed pass, which is implicitely renamed as SRPDefaultUnlit. In that case, they are considered forward-only too. // TO declare a material with unnamed pass and UniversalForward/UniversalForwardOnly pass is an ERROR, as the material will be rendered twice. StencilState forwardOnlyStencilState = DeferredLights.OverwriteStencil(m_DefaultStencilState, (int)StencilUsage.MaterialMask); - ShaderTagId[] forwardOnlyShaderTagIds = new ShaderTagId[] { + ShaderTagId[] forwardOnlyShaderTagIds = new ShaderTagId[] + { new ShaderTagId("UniversalForwardOnly"), new ShaderTagId("SRPDefaultUnlit"), // Legacy shaders (do not have a gbuffer pass) are considered forward-only for backward compatibility new ShaderTagId("LightweightForward") // Legacy shaders (do not have a gbuffer pass) are considered forward-only for backward compatibility @@ -218,7 +219,8 @@ public ForwardRenderer(ForwardRendererData data) : base(data) this.supportedRenderingFeatures.msaa = false; // Avoid legacy platforms: use vulkan instead. - unsupportedGraphicsDeviceTypes = new GraphicsDeviceType[] { + unsupportedGraphicsDeviceTypes = new GraphicsDeviceType[] + { GraphicsDeviceType.OpenGLCore, GraphicsDeviceType.OpenGLES2, GraphicsDeviceType.OpenGLES3 @@ -435,9 +437,9 @@ public override void Setup(ScriptableRenderContext context, ref RenderingData re // If a depth texture was created we necessarily need to copy it, otherwise we could have render it to a renderbuffer. // If deferred rendering path was selected, it has already made a copy. bool requiresDepthCopyPass = !requiresDepthPrepass - && renderingData.cameraData.requiresDepthTexture - && createDepthTexture - && this.actualRenderingMode != RenderingMode.Deferred; + && renderingData.cameraData.requiresDepthTexture + && createDepthTexture + && this.actualRenderingMode != RenderingMode.Deferred; if (requiresDepthCopyPass) { m_CopyDepthPass.Setup(m_ActiveCameraDepthAttachment, m_DepthTexture); @@ -474,7 +476,7 @@ public override void Setup(ScriptableRenderContext context, ref RenderingData re bool lastCameraInTheStack = cameraData.resolveFinalTarget; bool hasCaptureActions = renderingData.cameraData.captureActions != null && lastCameraInTheStack; bool applyFinalPostProcessing = anyPostProcessing && lastCameraInTheStack && - renderingData.cameraData.antialiasing == AntialiasingMode.FastApproximateAntialiasing; + renderingData.cameraData.antialiasing == AntialiasingMode.FastApproximateAntialiasing; // When post-processing is enabled we can use the stack to resolve rendering to camera target (screen or RT). // However when there are render passes executing after post we avoid resolving to screen so rendering continues (before sRGBConvertion etc) @@ -539,7 +541,6 @@ public override void Setup(ScriptableRenderContext context, ref RenderingData re } #endif } - // stay in RT so we resume rendering on stack after post-processing else if (applyPostProcessing) { @@ -727,14 +728,14 @@ void CreateCameraRenderTarget(ScriptableRenderContext context, ref RenderTexture bool PlatformRequiresExplicitMsaaResolve() { #if UNITY_EDITOR - // In the editor play-mode we use a Game View Render Texture, with - // samples count forced to 1 so we always need to do an explicit MSAA resolve. - return true; + // In the editor play-mode we use a Game View Render Texture, with + // samples count forced to 1 so we always need to do an explicit MSAA resolve. + return true; #else - // On Metal/iOS the MSAA resolve is done implicitly as part of the renderpass, so we do not need an extra intermediate pass for the explicit autoresolve. - // TODO: should also be valid on Metal MacOS/Editor, but currently not working as expected. Remove the "mobile only" requirement once trunk has a fix. - return !SystemInfo.supportsMultisampleAutoResolve - && !(SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal && Application.isMobilePlatform); + // On Metal/iOS the MSAA resolve is done implicitly as part of the renderpass, so we do not need an extra intermediate pass for the explicit autoresolve. + // TODO: should also be valid on Metal MacOS/Editor, but currently not working as expected. Remove the "mobile only" requirement once trunk has a fix. + return !SystemInfo.supportsMultisampleAutoResolve + && !(SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal && Application.isMobilePlatform); #endif } @@ -779,7 +780,7 @@ bool RequiresIntermediateColorTexture(ref CameraData cameraData) return requiresBlitForOffscreenCamera; return requiresBlitForOffscreenCamera || isSceneViewCamera || isScaledRender || cameraData.isHdrEnabled || - !isCompatibleBackbufferTextureDimension || isCapturing || cameraData.requireSrgbConversion; + !isCompatibleBackbufferTextureDimension || isCapturing || cameraData.requireSrgbConversion; } bool CanCopyDepth(ref CameraData cameraData) diff --git a/com.unity.render-pipelines.universal/Runtime/ForwardRendererData.cs b/com.unity.render-pipelines.universal/Runtime/ForwardRendererData.cs index 3cc1f560112..9a210d2478b 100644 --- a/com.unity.render-pipelines.universal/Runtime/ForwardRendererData.cs +++ b/com.unity.render-pipelines.universal/Runtime/ForwardRendererData.cs @@ -29,6 +29,7 @@ static void CreateForwardRendererData() { ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, CreateInstance(), "CustomForwardRendererData.asset", null, null); } + #endif [Serializable, ReloadGroup] diff --git a/com.unity.render-pipelines.universal/Runtime/Overrides/ColorCurves.cs b/com.unity.render-pipelines.universal/Runtime/Overrides/ColorCurves.cs index 2b7985afc6b..a0c12cdc721 100644 --- a/com.unity.render-pipelines.universal/Runtime/Overrides/ColorCurves.cs +++ b/com.unity.render-pipelines.universal/Runtime/Overrides/ColorCurves.cs @@ -10,10 +10,10 @@ public sealed class ColorCurves : VolumeComponent, IPostProcessComponent public TextureCurveParameter green = new TextureCurveParameter(new TextureCurve(new[] { new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f) }, 0f, false, new Vector2(0f, 1f))); public TextureCurveParameter blue = new TextureCurveParameter(new TextureCurve(new[] { new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f) }, 0f, false, new Vector2(0f, 1f))); - public TextureCurveParameter hueVsHue = new TextureCurveParameter(new TextureCurve(new Keyframe[] { }, 0.5f, true, new Vector2(0f, 1f))); - public TextureCurveParameter hueVsSat = new TextureCurveParameter(new TextureCurve(new Keyframe[] { }, 0.5f, true, new Vector2(0f, 1f))); - public TextureCurveParameter satVsSat = new TextureCurveParameter(new TextureCurve(new Keyframe[] { }, 0.5f, false, new Vector2(0f, 1f))); - public TextureCurveParameter lumVsSat = new TextureCurveParameter(new TextureCurve(new Keyframe[] { }, 0.5f, false, new Vector2(0f, 1f))); + public TextureCurveParameter hueVsHue = new TextureCurveParameter(new TextureCurve(new Keyframe[] {}, 0.5f, true, new Vector2(0f, 1f))); + public TextureCurveParameter hueVsSat = new TextureCurveParameter(new TextureCurve(new Keyframe[] {}, 0.5f, true, new Vector2(0f, 1f))); + public TextureCurveParameter satVsSat = new TextureCurveParameter(new TextureCurve(new Keyframe[] {}, 0.5f, false, new Vector2(0f, 1f))); + public TextureCurveParameter lumVsSat = new TextureCurveParameter(new TextureCurve(new Keyframe[] {}, 0.5f, false, new Vector2(0f, 1f))); public bool IsActive() => true; diff --git a/com.unity.render-pipelines.universal/Runtime/Overrides/ColorLookup.cs b/com.unity.render-pipelines.universal/Runtime/Overrides/ColorLookup.cs index 4542c149cb5..d4448701ed6 100644 --- a/com.unity.render-pipelines.universal/Runtime/Overrides/ColorLookup.cs +++ b/com.unity.render-pipelines.universal/Runtime/Overrides/ColorLookup.cs @@ -32,12 +32,12 @@ public bool ValidateLUT() { case Texture2D t: valid |= t.width == lutSize * lutSize - && !GraphicsFormatUtility.IsSRGBFormat(t.graphicsFormat); + && !GraphicsFormatUtility.IsSRGBFormat(t.graphicsFormat); break; case RenderTexture rt: valid |= rt.dimension == TextureDimension.Tex2D - && rt.width == lutSize * lutSize - && !rt.sRGB; + && rt.width == lutSize * lutSize + && !rt.sRGB; break; } diff --git a/com.unity.render-pipelines.universal/Runtime/Overrides/DepthOfField.cs b/com.unity.render-pipelines.universal/Runtime/Overrides/DepthOfField.cs index 3a8d7afae76..75cafe27288 100644 --- a/com.unity.render-pipelines.universal/Runtime/Overrides/DepthOfField.cs +++ b/com.unity.render-pipelines.universal/Runtime/Overrides/DepthOfField.cs @@ -57,5 +57,5 @@ public bool IsActive() } [Serializable] - public sealed class DepthOfFieldModeParameter : VolumeParameter { public DepthOfFieldModeParameter(DepthOfFieldMode value, bool overrideState = false) : base(value, overrideState) { } } + public sealed class DepthOfFieldModeParameter : VolumeParameter { public DepthOfFieldModeParameter(DepthOfFieldMode value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.universal/Runtime/Overrides/FilmGrain.cs b/com.unity.render-pipelines.universal/Runtime/Overrides/FilmGrain.cs index bbaca2b74f6..fa0dd76b36d 100644 --- a/com.unity.render-pipelines.universal/Runtime/Overrides/FilmGrain.cs +++ b/com.unity.render-pipelines.universal/Runtime/Overrides/FilmGrain.cs @@ -38,5 +38,5 @@ public sealed class FilmGrain : VolumeComponent, IPostProcessComponent } [Serializable] - public sealed class FilmGrainLookupParameter : VolumeParameter { public FilmGrainLookupParameter(FilmGrainLookup value, bool overrideState = false) : base(value, overrideState) { } } + public sealed class FilmGrainLookupParameter : VolumeParameter { public FilmGrainLookupParameter(FilmGrainLookup value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.universal/Runtime/Overrides/MotionBlur.cs b/com.unity.render-pipelines.universal/Runtime/Overrides/MotionBlur.cs index df01a4b13ec..96dae158a1a 100644 --- a/com.unity.render-pipelines.universal/Runtime/Overrides/MotionBlur.cs +++ b/com.unity.render-pipelines.universal/Runtime/Overrides/MotionBlur.cs @@ -36,8 +36,8 @@ public sealed class MotionBlur : VolumeComponent, IPostProcessComponent } [Serializable] - public sealed class MotionBlurModeParameter : VolumeParameter { public MotionBlurModeParameter(MotionBlurMode value, bool overrideState = false) : base(value, overrideState) { } } + public sealed class MotionBlurModeParameter : VolumeParameter { public MotionBlurModeParameter(MotionBlurMode value, bool overrideState = false) : base(value, overrideState) {} } [Serializable] - public sealed class MotionBlurQualityParameter : VolumeParameter { public MotionBlurQualityParameter(MotionBlurQuality value, bool overrideState = false) : base(value, overrideState) { } } + public sealed class MotionBlurQualityParameter : VolumeParameter { public MotionBlurQualityParameter(MotionBlurQuality value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.universal/Runtime/Overrides/Tonemapping.cs b/com.unity.render-pipelines.universal/Runtime/Overrides/Tonemapping.cs index 980554fe696..059d3a64d49 100644 --- a/com.unity.render-pipelines.universal/Runtime/Overrides/Tonemapping.cs +++ b/com.unity.render-pipelines.universal/Runtime/Overrides/Tonemapping.cs @@ -21,5 +21,5 @@ public sealed class Tonemapping : VolumeComponent, IPostProcessComponent } [Serializable] - public sealed class TonemappingModeParameter : VolumeParameter { public TonemappingModeParameter(TonemappingMode value, bool overrideState = false) : base(value, overrideState) { } } + public sealed class TonemappingModeParameter : VolumeParameter { public TonemappingModeParameter(TonemappingMode value, bool overrideState = false) : base(value, overrideState) {} } } diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs index ad0f219f9c2..34111aaccf3 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs @@ -313,12 +313,12 @@ void RenderAdditionalShadowmapAtlas(ref ScriptableRenderContext context, ref Cul // to enable the keyword. // TODO: In PC and Consoles we can upload shadow data per light and branch on shader. That will be more likely way faster. bool mainLightHasSoftShadows = shadowData.supportsMainLightShadows && - lightData.mainLightIndex != -1 && - visibleLights[lightData.mainLightIndex].light.shadows == - LightShadows.Soft; + lightData.mainLightIndex != -1 && + visibleLights[lightData.mainLightIndex].light.shadows == + LightShadows.Soft; bool softShadows = shadowData.supportsSoftShadows && - (mainLightHasSoftShadows || additionalLightHasSoftShadows); + (mainLightHasSoftShadows || additionalLightHasSoftShadows); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.AdditionalLightShadows, anyShadowSliceRenderer); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.SoftShadows, softShadows); diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs index 1c7378eb2a5..81267d899aa 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs @@ -100,19 +100,19 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData shadowsMidtonesHighlights.highlightsEnd.value ); - var (shadows, midtones, highlights) = ColorUtils.PrepareShadowsMidtonesHighlights( + var(shadows, midtones, highlights) = ColorUtils.PrepareShadowsMidtonesHighlights( shadowsMidtonesHighlights.shadows.value, shadowsMidtonesHighlights.midtones.value, shadowsMidtonesHighlights.highlights.value ); - var (lift, gamma, gain) = ColorUtils.PrepareLiftGammaGain( + var(lift, gamma, gain) = ColorUtils.PrepareLiftGammaGain( liftGammaGain.lift.value, liftGammaGain.gamma.value, liftGammaGain.gain.value ); - var (splitShadows, splitHighlights) = ColorUtils.PrepareSplitToning( + var(splitShadows, splitHighlights) = ColorUtils.PrepareSplitToning( splitToning.shadows.value, splitToning.highlights.value, splitToning.balance.value diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs index cc7e81d90ea..bc5cb06284e 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs @@ -51,7 +51,7 @@ public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderin ConfigureTarget( new RenderTargetIdentifier(normalHandle.Identifier(), 0, CubemapFace.Unknown, -1), new RenderTargetIdentifier(depthHandle.Identifier(), 0, CubemapFace.Unknown, -1) - ); + ); ConfigureClear(ClearFlag.All, Color.black); } @@ -74,7 +74,6 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData Camera camera = cameraData.camera; context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref m_FilteringSettings); - } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs index 4b805838c43..63a5832861f 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs @@ -67,7 +67,6 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData drawSettings.perObjectData = PerObjectData.None; context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref m_FilteringSettings); - } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs index d04ba87033f..30c6cd821e6 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs @@ -44,8 +44,8 @@ public DrawObjectsPass(string profilerTag, ShaderTagId[] shaderTagIds, bool opaq public DrawObjectsPass(string profilerTag, bool opaque, RenderPassEvent evt, RenderQueueRange renderQueueRange, LayerMask layerMask, StencilState stencilState, int stencilReference) : this(profilerTag, - new ShaderTagId[] { new ShaderTagId("SRPDefaultUnlit"), new ShaderTagId("UniversalForward"), new ShaderTagId("UniversalForwardOnly"), new ShaderTagId("LightweightForward")}, - opaque, evt, renderQueueRange, layerMask, stencilState, stencilReference) + new ShaderTagId[] { new ShaderTagId("SRPDefaultUnlit"), new ShaderTagId("UniversalForward"), new ShaderTagId("UniversalForwardOnly"), new ShaderTagId("LightweightForward")}, + opaque, evt, renderQueueRange, layerMask, stencilState, stencilReference) {} internal DrawObjectsPass(URPProfileId profileId, bool opaque, RenderPassEvent evt, RenderQueueRange renderQueueRange, LayerMask layerMask, StencilState stencilState, int stencilReference) diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs index 653228218f2..d39ad1de5a2 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs @@ -48,7 +48,6 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData CommandBuffer cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.FinalBlit))) { - CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.LinearToSRGBConversion, cameraData.requireSrgbConversion); diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs index 33062048f5f..a3f5c9f9a56 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/MainLightShadowCasterPass.cs @@ -119,7 +119,7 @@ public bool Setup(ref RenderingData renderingData) public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor) { m_MainLightShadowmapTexture = ShadowUtils.GetTemporaryShadowTexture(m_ShadowmapWidth, - m_ShadowmapHeight, k_ShadowmapBufferBits); + m_ShadowmapHeight, k_ShadowmapBufferBits); ConfigureTarget(new RenderTargetIdentifier(m_MainLightShadowmapTexture)); ConfigureClear(ClearFlag.All, Color.black); } @@ -221,7 +221,7 @@ void SetupMainLightShadowReceiverConstants(CommandBuffer cmd, VisibleLight shado //To make the shadow fading fit into a single MAD instruction: //distanceCamToPixel2 * oneOverFadeDist + minusStartFade (single MAD) float startFade = m_MaxShadowDistance * 0.9f; - float oneOverFadeDist = 1/(m_MaxShadowDistance - startFade); + float oneOverFadeDist = 1 / (m_MaxShadowDistance - startFade); float minusStartFade = -startFade * oneOverFadeDist; diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPass.cs index 6ae5ed4efe0..36dcede60a3 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPass.cs @@ -350,7 +350,6 @@ int GetDestination() // Anti-aliasing if (cameraData.antialiasing == AntialiasingMode.SubpixelMorphologicalAntiAliasing && SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLES2) { - using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.SMAA))) { DoSubpixelMorphologicalAntialiasing(ref cameraData, cmd, GetSource(), GetDestination()); @@ -440,7 +439,7 @@ int GetDestination() if (cameraData.xr.enabled) { cmd.SetRenderTarget(new RenderTargetIdentifier(cameraTarget, 0, CubemapFace.Unknown, -1), - colorLoadAction, RenderBufferStoreAction.Store, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare); + colorLoadAction, RenderBufferStoreAction.Store, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare); bool isRenderToBackBufferTarget = cameraTarget == cameraData.xr.renderTarget && !cameraData.xr.renderTargetIsRenderTexture; if (isRenderToBackBufferTarget) @@ -463,7 +462,7 @@ int GetDestination() cmd.SetRenderTarget(new RenderTargetIdentifier(m_Source.id, 0, CubemapFace.Unknown, -1), colorLoadAction, RenderBufferStoreAction.Store, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare); - scaleBias = new Vector4(1, 1, 0, 0); ; + scaleBias = new Vector4(1, 1, 0, 0);; cmd.SetGlobalVector(ShaderPropertyId.scaleBias, scaleBias); cmd.DrawProcedural(Matrix4x4.identity, m_BlitMaterial, 0, MeshTopology.Quads, 4, 1, null); } @@ -1117,9 +1116,9 @@ void SetupColorGrading(CommandBuffer cmd, ref RenderingData renderingData, Mater material.SetVector(ShaderConstants._UserLut_Params, !m_ColorLookup.IsActive() ? Vector4.zero : new Vector4(1f / m_ColorLookup.texture.value.width, - 1f / m_ColorLookup.texture.value.height, - m_ColorLookup.texture.value.height - 1f, - m_ColorLookup.contribution.value) + 1f / m_ColorLookup.texture.value.height, + m_ColorLookup.texture.value.height - 1f, + m_ColorLookup.contribution.value) ); if (hdr) diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs index 2a6f0ab8a5a..4efdf2be7e8 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs @@ -70,11 +70,10 @@ public RenderObjectsPass(string profilerTag, RenderPassEvent renderPassEvent, st m_RenderStateBlock = new RenderStateBlock(RenderStateMask.Nothing); m_CameraSettings = cameraSettings; - } internal RenderObjectsPass(URPProfileId profileId, RenderPassEvent renderPassEvent, string[] shaderTags, RenderQueueType renderQueueType, int layerMask, RenderObjects.CustomCameraSettings cameraSettings) - : this(profileId.GetType().Name, renderPassEvent, shaderTags, renderQueueType, layerMask, cameraSettings) + : this(profileId.GetType().Name, renderPassEvent, shaderTags, renderQueueType, layerMask, cameraSettings) { m_ProfilingSampler = ProfilingSampler.Get(profileId); } @@ -94,7 +93,7 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData // In case of camera stacking we need to take the viewport rect from base camera Rect pixelRect = renderingData.cameraData.pixelRect; - float cameraAspect = (float) pixelRect.width / (float) pixelRect.height; + float cameraAspect = (float)pixelRect.width / (float)pixelRect.height; // NOTE: Do NOT mix ProfilingScope with named CommandBuffers i.e. CommandBufferPool.Get("name"). // Currently there's an issue which results in mismatched markers. diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs index 065cfe5ac30..fce918dda68 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/ScriptableRenderPass.cs @@ -148,7 +148,7 @@ public Color clearColor internal bool overrideCameraTarget { get; set; } internal bool isBlitRenderPass { get; set; } - RenderTargetIdentifier[] m_ColorAttachments = new RenderTargetIdentifier[]{BuiltinRenderTextureType.CameraTarget}; + RenderTargetIdentifier[] m_ColorAttachments = new RenderTargetIdentifier[] {BuiltinRenderTextureType.CameraTarget}; RenderTargetIdentifier m_DepthAttachment = BuiltinRenderTextureType.CameraTarget; ScriptableRenderPassInput m_Input = ScriptableRenderPassInput.None; ClearFlag m_ClearFlag = ClearFlag.None; @@ -157,7 +157,7 @@ public Color clearColor public ScriptableRenderPass() { renderPassEvent = RenderPassEvent.AfterRenderingOpaques; - m_ColorAttachments = new RenderTargetIdentifier[]{BuiltinRenderTextureType.CameraTarget, 0, 0, 0, 0, 0, 0, 0}; + m_ColorAttachments = new RenderTargetIdentifier[] {BuiltinRenderTextureType.CameraTarget, 0, 0, 0, 0, 0, 0, 0}; m_DepthAttachment = BuiltinRenderTextureType.CameraTarget; m_ClearFlag = ClearFlag.None; m_ClearColor = Color.black; @@ -202,7 +202,7 @@ public void ConfigureTarget(RenderTargetIdentifier[] colorAttachments, RenderTar overrideCameraTarget = true; uint nonNullColorBuffers = RenderingUtils.GetValidColorBufferCount(colorAttachments); - if( nonNullColorBuffers > SystemInfo.supportedRenderTargetCount) + if (nonNullColorBuffers > SystemInfo.supportedRenderTargetCount) Debug.LogError("Trying to set " + nonNullColorBuffers + " renderTargets, which is more than the maximum supported:" + SystemInfo.supportedRenderTargetCount); m_ColorAttachments = colorAttachments; @@ -283,7 +283,6 @@ public virtual void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraT /// Use this CommandBuffer to cleanup any generated data public virtual void OnCameraCleanup(CommandBuffer cmd) { - } /// @@ -367,12 +366,12 @@ public DrawingSettings CreateDrawingSettings(List shaderTagIdList, return settings; } - public static bool operator <(ScriptableRenderPass lhs, ScriptableRenderPass rhs) + public static bool operator<(ScriptableRenderPass lhs, ScriptableRenderPass rhs) { return lhs.renderPassEvent < rhs.renderPassEvent; } - public static bool operator >(ScriptableRenderPass lhs, ScriptableRenderPass rhs) + public static bool operator>(ScriptableRenderPass lhs, ScriptableRenderPass rhs) { return lhs.renderPassEvent > rhs.renderPassEvent; } diff --git a/com.unity.render-pipelines.universal/Runtime/Passes/TransparentSettingsPass.cs b/com.unity.render-pipelines.universal/Runtime/Passes/TransparentSettingsPass.cs index 452bf39c5e4..787d1b7269b 100644 --- a/com.unity.render-pipelines.universal/Runtime/Passes/TransparentSettingsPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/Passes/TransparentSettingsPass.cs @@ -32,12 +32,10 @@ public override void Execute(ScriptableRenderContext context, ref RenderingData CommandBuffer cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, m_ProfilingSampler)) { - // Toggle light shadows enabled based on the renderer setting set in the constructor CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.MainLightShadows, m_shouldReceiveShadows); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.MainLightShadowCascades, m_shouldReceiveShadows); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.AdditionalLightShadows, m_shouldReceiveShadows); - } // Execute and release the command buffer... diff --git a/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DisallowMultipleRendererFeature.cs b/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DisallowMultipleRendererFeature.cs index b2f03c75493..cc8bb08cf78 100644 --- a/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DisallowMultipleRendererFeature.cs +++ b/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DisallowMultipleRendererFeature.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEngine.Rendering.Universal { diff --git a/com.unity.render-pipelines.universal/Runtime/RendererFeatures/RenderObjects.cs b/com.unity.render-pipelines.universal/Runtime/RendererFeatures/RenderObjects.cs index 5e12bbf457e..0e355c6fe2f 100644 --- a/com.unity.render-pipelines.universal/Runtime/RendererFeatures/RenderObjects.cs +++ b/com.unity.render-pipelines.universal/Runtime/RendererFeatures/RenderObjects.cs @@ -5,14 +5,14 @@ namespace UnityEngine.Experimental.Rendering.Universal { - [MovedFrom("UnityEngine.Experimental.Rendering.LWRP")]public enum RenderQueueType + [MovedFrom("UnityEngine.Experimental.Rendering.LWRP")] public enum RenderQueueType { Opaque, Transparent, } [ExcludeFromPreset] - [MovedFrom("UnityEngine.Experimental.Rendering.LWRP")]public class RenderObjects : ScriptableRendererFeature + [MovedFrom("UnityEngine.Experimental.Rendering.LWRP")] public class RenderObjects : ScriptableRendererFeature { [System.Serializable] public class RenderObjectsSettings @@ -95,4 +95,3 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD } } } - diff --git a/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceAmbientOcclusion.cs b/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceAmbientOcclusion.cs index be3be8a2e24..524bffbf9d2 100644 --- a/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceAmbientOcclusion.cs +++ b/com.unity.render-pipelines.universal/Runtime/RendererFeatures/ScreenSpaceAmbientOcclusion.cs @@ -164,9 +164,9 @@ internal bool Setup(ScreenSpaceAmbientOcclusionSettings featureSettings) throw new ArgumentOutOfRangeException(); } return material != null - && m_CurrentSettings.Intensity > 0.0f - && m_CurrentSettings.Radius > 0.0f - && m_CurrentSettings.SampleCount > 0; + && m_CurrentSettings.Intensity > 0.0f + && m_CurrentSettings.Radius > 0.0f + && m_CurrentSettings.SampleCount > 0; } /// @@ -286,7 +286,7 @@ private void Render(CommandBuffer cmd, RenderTargetIdentifier target, ShaderPass RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare ); - cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, material, 0, (int) pass); + cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, material, 0, (int)pass); } private void RenderAndSetBaseMap(CommandBuffer cmd, RenderTargetIdentifier baseMap, RenderTargetIdentifier target, ShaderPasses pass) diff --git a/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs b/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs index 05975e7404f..37a644f35f9 100644 --- a/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs +++ b/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs @@ -91,7 +91,7 @@ static Material errorMaterial { s_ErrorMaterial = new Material(Shader.Find("Hidden/Universal Render Pipeline/FallbackError")); } - catch { } + catch {} } return s_ErrorMaterial; @@ -125,7 +125,6 @@ public static void SetViewAndProjectionMatrices(CommandBuffer cmd, Matrix4x4 vie } } - #if ENABLE_VR && ENABLE_XR_MODULE internal static readonly int UNITY_STEREO_MATRIX_V = Shader.PropertyToID("unity_StereoMatrixV"); internal static readonly int UNITY_STEREO_MATRIX_IV = Shader.PropertyToID("unity_StereoMatrixInvV"); @@ -178,7 +177,7 @@ internal static void SetStereoViewAndProjectionMatrices(CommandBuffer cmd, Matri cmd.SetGlobalMatrixArray(UNITY_STEREO_MATRIX_VP, stereoConstants.viewProjMatrix); cmd.SetGlobalMatrixArray(UNITY_STEREO_CAMERA_PROJECTION, cameraProjMatrix); - + if (setInverseMatrices) { cmd.SetGlobalMatrixArray(UNITY_STEREO_MATRIX_IV, stereoConstants.invViewMatrix); @@ -189,6 +188,7 @@ internal static void SetStereoViewAndProjectionMatrices(CommandBuffer cmd, Matri } cmd.SetGlobalVectorArray(UNITY_STEREO_VECTOR_CAMPOS, stereoConstants.worldSpaceCameraPos); } + #endif internal static void Blit(CommandBuffer cmd, @@ -246,7 +246,7 @@ internal static void RenderObjectsWithError(ScriptableRenderContext context, ref // Caches render texture format support. SystemInfo.SupportsRenderTextureFormat and IsFormatSupported allocate memory due to boxing. static Dictionary m_RenderTextureFormatSupport = new Dictionary(); - static Dictionary > m_GraphicsFormatSupport = new Dictionary >(); + static Dictionary> m_GraphicsFormatSupport = new Dictionary>(); internal static void ClearSystemInfoCache() { @@ -308,7 +308,7 @@ public static bool SupportsGraphicsFormat(GraphicsFormat format, FormatUsage usa internal static int GetLastValidColorBufferIndex(RenderTargetIdentifier[] colorBuffers) { int i = colorBuffers.Length - 1; - for(; i>=0; --i) + for (; i >= 0; --i) { if (colorBuffers[i] != 0) break; @@ -401,7 +401,7 @@ internal static uint CountDistinct(RenderTargetIdentifier[] source, RenderTarget /// internal static int LastValid(RenderTargetIdentifier[] source) { - for (int i = source.Length-1; i >= 0; --i) + for (int i = source.Length - 1; i >= 0; --i) { if (source[i] != 0) return i; diff --git a/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs b/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs index 14b38d5c64e..bb8c1fa2387 100644 --- a/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs +++ b/com.unity.render-pipelines.universal/Runtime/SceneViewDrawMode.cs @@ -34,7 +34,7 @@ static void UpdateSceneViewStates() { if (sceneViewHaveValidateFunction.Contains(sceneView)) continue; - + sceneView.onValidateCameraMode += RejectDrawMode; sceneViewHaveValidateFunction.Add(sceneView); @@ -50,7 +50,7 @@ public static void SetupDrawMode() public static void ResetDrawMode() { EditorApplication.update -= UpdateSceneViewStates; - + foreach (var sceneView in sceneViewHaveValidateFunction) sceneView.onValidateCameraMode -= RejectDrawMode; sceneViewHaveValidateFunction.Clear(); diff --git a/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs b/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs index cc4de8f6756..16176a1bbf8 100644 --- a/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs +++ b/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs @@ -151,7 +151,7 @@ void SetPerCameraShaderVariables(CommandBuffer cmd, ref CameraData cameraData) float cameraHeight = (float)pixelRect.height; // Use eye texture's width and height as screen params when XR is enabled - if(cameraData.xr.enabled) + if (cameraData.xr.enabled) { scaledCameraWidth = (float)cameraData.cameraTargetDescriptor.width; scaledCameraHeight = (float)cameraData.cameraTargetDescriptor.height; @@ -336,7 +336,7 @@ static class RenderPassBlock // This should be removed when early camera color target assignment is removed. internal bool isCameraColorTargetValid = false; - static RenderTargetIdentifier[] m_ActiveColorAttachments = new RenderTargetIdentifier[]{0, 0, 0, 0, 0, 0, 0, 0 }; + static RenderTargetIdentifier[] m_ActiveColorAttachments = new RenderTargetIdentifier[] {0, 0, 0, 0, 0, 0, 0, 0 }; static RenderTargetIdentifier m_ActiveDepthAttachment; // CommandBuffer.SetRenderTarget(RenderTargetIdentifier[] colors, RenderTargetIdentifier depth, int mipLevel, CubemapFace cubemapFace, int depthSlice); @@ -346,14 +346,14 @@ static class RenderPassBlock static RenderTargetIdentifier[][] m_TrimmedColorAttachmentCopies = new RenderTargetIdentifier[][] { new RenderTargetIdentifier[0], // m_TrimmedColorAttachmentCopies[0] is an array of 0 RenderTargetIdentifier - only used to make indexing code easier to read - new RenderTargetIdentifier[]{0}, // m_TrimmedColorAttachmentCopies[1] is an array of 1 RenderTargetIdentifier - new RenderTargetIdentifier[]{0, 0}, // m_TrimmedColorAttachmentCopies[2] is an array of 2 RenderTargetIdentifiers - new RenderTargetIdentifier[]{0, 0, 0}, // m_TrimmedColorAttachmentCopies[3] is an array of 3 RenderTargetIdentifiers - new RenderTargetIdentifier[]{0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[4] is an array of 4 RenderTargetIdentifiers - new RenderTargetIdentifier[]{0, 0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[5] is an array of 5 RenderTargetIdentifiers - new RenderTargetIdentifier[]{0, 0, 0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[6] is an array of 6 RenderTargetIdentifiers - new RenderTargetIdentifier[]{0, 0, 0, 0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[7] is an array of 7 RenderTargetIdentifiers - new RenderTargetIdentifier[]{0, 0, 0, 0, 0, 0, 0, 0 }, // m_TrimmedColorAttachmentCopies[8] is an array of 8 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0}, // m_TrimmedColorAttachmentCopies[1] is an array of 1 RenderTargetIdentifier + new RenderTargetIdentifier[] {0, 0}, // m_TrimmedColorAttachmentCopies[2] is an array of 2 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0, 0, 0}, // m_TrimmedColorAttachmentCopies[3] is an array of 3 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[4] is an array of 4 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0, 0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[5] is an array of 5 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0, 0, 0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[6] is an array of 6 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0, 0, 0, 0, 0, 0, 0}, // m_TrimmedColorAttachmentCopies[7] is an array of 7 RenderTargetIdentifiers + new RenderTargetIdentifier[] {0, 0, 0, 0, 0, 0, 0, 0 }, // m_TrimmedColorAttachmentCopies[8] is an array of 8 RenderTargetIdentifiers }; internal static void ConfigureActiveTarget(RenderTargetIdentifier colorAttachment, @@ -479,7 +479,7 @@ public void Execute(ScriptableRenderContext context, ref RenderingData rendering #if UNITY_EDITOR float time = Application.isPlaying ? Time.time : Time.realtimeSinceStartup; #else - float time = Time.time; + float time = Time.time; #endif float deltaTime = Time.deltaTime; float smoothDeltaTime = Time.smoothDeltaTime; @@ -528,8 +528,8 @@ public void Execute(ScriptableRenderContext context, ref RenderingData rendering SetShaderTimeValues(cmd, time, deltaTime, smoothDeltaTime); #if VISUAL_EFFECT_GRAPH_0_0_1_OR_NEWER - //Triggers dispatch per camera, all global parameters should have been setup at this stage. - VFX.VFXManager.ProcessCameraCommand(camera, cmd); + //Triggers dispatch per camera, all global parameters should have been setup at this stage. + VFX.VFXManager.ProcessCameraCommand(camera, cmd); #endif } @@ -988,7 +988,7 @@ static void SetRenderTarget( else { CoreUtils.SetRenderTarget(cmd, colorAttachment, colorLoadAction, colorStoreAction, - depthAttachment, depthLoadAction, depthStoreAction, clearFlags, clearColor); + depthAttachment, depthLoadAction, depthStoreAction, clearFlags, clearColor); } } @@ -1035,7 +1035,6 @@ void InternalFinishRendering(ScriptableRenderContext context, bool resolveFinalT CommandBuffer cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, Profiling.internalFinishRendering)) { - for (int i = 0; i < m_ActiveRenderPassQueue.Count; ++i) m_ActiveRenderPassQueue[i].FrameCleanup(cmd); @@ -1086,7 +1085,7 @@ public RenderBlocks(List activeRenderPassQueue) m_BlockEventLimits[RenderPassBlock.BeforeRendering] = RenderPassEvent.BeforeRenderingPrepasses; m_BlockEventLimits[RenderPassBlock.MainRenderingOpaque] = RenderPassEvent.AfterRenderingOpaques; m_BlockEventLimits[RenderPassBlock.MainRenderingTransparent] = RenderPassEvent.AfterRenderingPostProcessing; - m_BlockEventLimits[RenderPassBlock.AfterRendering] = (RenderPassEvent) Int32.MaxValue; + m_BlockEventLimits[RenderPassBlock.AfterRendering] = (RenderPassEvent)Int32.MaxValue; // blockRanges[0] is always 0 // blockRanges[i] is the index of the first RenderPass found in m_ActiveRenderPassQueue that has a ScriptableRenderPass.renderPassEvent higher than blockEventLimits[i] (i.e, should be executed after blockEventLimits[i]) diff --git a/com.unity.render-pipelines.universal/Runtime/ScriptableRendererData.cs b/com.unity.render-pipelines.universal/Runtime/ScriptableRendererData.cs index 0b803d4628e..19753c7cace 100644 --- a/com.unity.render-pipelines.universal/Runtime/ScriptableRendererData.cs +++ b/com.unity.render-pipelines.universal/Runtime/ScriptableRendererData.cs @@ -116,11 +116,11 @@ internal bool ValidateRendererFeatures() { var localId = m_RendererFeatureMap[i]; loadedAssets.TryGetValue(localId, out var asset); - m_RendererFeatures[i] = (ScriptableRendererFeature) asset; + m_RendererFeatures[i] = (ScriptableRendererFeature)asset; } else { - m_RendererFeatures[i] = (ScriptableRendererFeature) GetUnusedAsset(ref linkedIds, ref loadedAssets); + m_RendererFeatures[i] = (ScriptableRendererFeature)GetUnusedAsset(ref linkedIds, ref loadedAssets); } } @@ -168,13 +168,13 @@ private void UpdateMap() for (int i = 0; i < rendererFeatures.Count; i++) { - if(m_RendererFeatures[i] == null) continue; + if (m_RendererFeatures[i] == null) continue; if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(m_RendererFeatures[i], out var guid, out long localId)) continue; m_RendererFeatureMap[i] = localId; } } + #endif } } - diff --git a/com.unity.render-pipelines.universal/Runtime/ShaderUtils.cs b/com.unity.render-pipelines.universal/Runtime/ShaderUtils.cs index 93d1471019b..b86968f1206 100644 --- a/com.unity.render-pipelines.universal/Runtime/ShaderUtils.cs +++ b/com.unity.render-pipelines.universal/Runtime/ShaderUtils.cs @@ -84,6 +84,7 @@ internal static string GetShaderGUID(ShaderPathID id) Debug.LogError("Trying to access universal shader GUID out of bounds: (" + id + ": " + index + ")"); return ""; } + #endif } } diff --git a/com.unity.render-pipelines.universal/Runtime/StencilUsage.cs b/com.unity.render-pipelines.universal/Runtime/StencilUsage.cs index db831e7b03b..cda2dd1d719 100644 --- a/com.unity.render-pipelines.universal/Runtime/StencilUsage.cs +++ b/com.unity.render-pipelines.universal/Runtime/StencilUsage.cs @@ -1,4 +1,3 @@ - namespace UnityEngine.Rendering.Universal.Internal { // Stencil usage for deferred renderer. @@ -16,6 +15,6 @@ enum StencilUsage MaterialLit = 0b_0010_0000, MaterialSimpleLit = 0b_0100_0000 - // Bit [7] is reserved. + // Bit [7] is reserved. } } diff --git a/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs b/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs index d24d12a5b22..7c17881aedf 100644 --- a/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs +++ b/com.unity.render-pipelines.universal/Runtime/UniversalAdditionalCameraData.cs @@ -123,8 +123,8 @@ public static string GetName(this CameraRenderType type) CameraOverrideOption m_RequiresOpaqueTextureOption = CameraOverrideOption.UsePipelineSettings; [SerializeField] CameraRenderType m_CameraType = CameraRenderType.Base; - [SerializeField] List m_Cameras = new List(); - [SerializeField] int m_RendererIndex = -1; + [SerializeField] List m_Cameras = new List(); + [SerializeField] int m_RendererIndex = -1; [SerializeField] LayerMask m_VolumeLayerMask = 1; // "Default" [SerializeField] Transform m_VolumeTrigger = null; @@ -144,7 +144,7 @@ public static string GetName(this CameraRenderType type) [FormerlySerializedAs("requiresColorTexture"), SerializeField] bool m_RequiresColorTexture = false; - [HideInInspector] [SerializeField] float m_Version = 2; + [HideInInspector][SerializeField] float m_Version = 2; public float version => m_Version; diff --git a/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs b/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs index a587bbad7e5..7c4f7f31f2c 100644 --- a/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs +++ b/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs @@ -36,18 +36,18 @@ private static class Profiling public static ProfilingSampler TryGetOrAddCameraSampler(Camera camera) { #if UNIVERSAL_PROFILING_NO_ALLOC - return unknownSampler; + return unknownSampler; #else - ProfilingSampler ps = null; - int cameraId = camera.GetHashCode(); - bool exists = s_HashSamplerCache.TryGetValue(cameraId, out ps); - if (!exists) - { - // NOTE: camera.name allocates! - ps = new ProfilingSampler( $"{nameof(UniversalRenderPipeline)}.{nameof(RenderSingleCamera)}: {camera.name}"); - s_HashSamplerCache.Add(cameraId, ps); - } - return ps; + ProfilingSampler ps = null; + int cameraId = camera.GetHashCode(); + bool exists = s_HashSamplerCache.TryGetValue(cameraId, out ps); + if (!exists) + { + // NOTE: camera.name allocates! + ps = new ProfilingSampler($"{nameof(UniversalRenderPipeline)}.{nameof(RenderSingleCamera)}: {camera.name}"); + s_HashSamplerCache.Add(cameraId, ps); + } + return ps; #endif } @@ -136,7 +136,7 @@ public static int maxVisibleAdditionalLights // GLES can be selected as platform on Windows (not a mobile platform) but uniform buffer size so we must use a low light count. return (isMobile || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES2 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3) - ? k_MaxVisibleAdditionalLightsMobile : k_MaxVisibleAdditionalLightsNonMobile; + ? k_MaxVisibleAdditionalLightsMobile : k_MaxVisibleAdditionalLightsNonMobile; } } @@ -191,6 +191,7 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] { Render(renderContext, new List(cameras)); } + #endif #if UNITY_2021_1_OR_NEWER @@ -209,7 +210,7 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c BeginContextRendering(renderContext, cameras); } #else - using(new ProfilingScope(null, Profiling.Pipeline.beginFrameRendering)) + using (new ProfilingScope(null, Profiling.Pipeline.beginFrameRendering)) { BeginFrameRendering(renderContext, cameras); } @@ -243,8 +244,8 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c BeginCameraRendering(renderContext, camera); } #if VISUAL_EFFECT_GRAPH_0_0_1_OR_NEWER - //It should be called before culling to prepare material. When there isn't any VisualEffect component, this method has no effect. - VFX.VFXManager.PrepareCamera(camera); + //It should be called before culling to prepare material. When there isn't any VisualEffect component, this method has no effect. + VFX.VFXManager.PrepareCamera(camera); #endif UpdateVolumeFramework(camera, null); @@ -262,7 +263,7 @@ protected override void Render(ScriptableRenderContext renderContext, Camera[] c EndContextRendering(renderContext, cameras); } #else - using(new ProfilingScope(null, Profiling.Pipeline.endFrameRendering)) + using (new ProfilingScope(null, Profiling.Pipeline.endFrameRendering)) { EndFrameRendering(renderContext, cameras); } @@ -348,7 +349,7 @@ static void RenderSingleCamera(ScriptableRenderContext context, CameraData camer { renderer.Clear(cameraData.renderType); - using (new ProfilingScope( cmd, Profiling.Pipeline.Renderer.setupCullingParameters)) + using (new ProfilingScope(cmd, Profiling.Pipeline.Renderer.setupCullingParameters)) { renderer.SetupCullingParameters(ref cullingParameters, ref cameraData); } @@ -379,7 +380,6 @@ static void RenderSingleCamera(ScriptableRenderContext context, CameraData camer // Timing scope inside renderer.Execute(context, ref renderingData); - } // When ProfilingSample goes out of scope, an "EndSample" command is enqueued into CommandBuffer cmd cameraData.xr.EndCamera(cmd, cameraData); @@ -460,7 +460,7 @@ static void RenderCameraStack(ScriptableRenderContext context, Camera baseCamera lastActiveOverlayCameraIndex = i; } } - if(shouldUpdateCameraStack) + if (shouldUpdateCameraStack) { baseCameraAdditionalData.UpdateCameraStack(); } @@ -493,84 +493,84 @@ static void RenderCameraStack(ScriptableRenderContext context, Camera baseCamera m_XRSystem.UpdateCameraData(ref baseCameraData, baseCameraData.xr); } #endif - using(new ProfilingScope(null, Profiling.Pipeline.beginCameraRendering)) - { - BeginCameraRendering(context, baseCamera); - } + using (new ProfilingScope(null, Profiling.Pipeline.beginCameraRendering)) + { + BeginCameraRendering(context, baseCamera); + } #if VISUAL_EFFECT_GRAPH_0_0_1_OR_NEWER - //It should be called before culling to prepare material. When there isn't any VisualEffect component, this method has no effect. - VFX.VFXManager.PrepareCamera(baseCamera); + //It should be called before culling to prepare material. When there isn't any VisualEffect component, this method has no effect. + VFX.VFXManager.PrepareCamera(baseCamera); #endif - UpdateVolumeFramework(baseCamera, baseCameraAdditionalData); + UpdateVolumeFramework(baseCamera, baseCameraAdditionalData); #if ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER - if (asset.useAdaptivePerformance) - ApplyAdaptivePerformance(ref baseCameraData); + if (asset.useAdaptivePerformance) + ApplyAdaptivePerformance(ref baseCameraData); #endif - RenderSingleCamera(context, baseCameraData, anyPostProcessingEnabled); - using (new ProfilingScope(null, Profiling.Pipeline.endCameraRendering)) - { - EndCameraRendering(context, baseCamera); - } + RenderSingleCamera(context, baseCameraData, anyPostProcessingEnabled); + using (new ProfilingScope(null, Profiling.Pipeline.endCameraRendering)) + { + EndCameraRendering(context, baseCamera); + } - if (isStackedRendering) + if (isStackedRendering) + { + for (int i = 0; i < cameraStack.Count; ++i) { - for (int i = 0; i < cameraStack.Count; ++i) + var currCamera = cameraStack[i]; + if (!currCamera.isActiveAndEnabled) + continue; + + currCamera.TryGetComponent(out var currCameraData); + // Camera is overlay and enabled + if (currCameraData != null) { - var currCamera = cameraStack[i]; - if (!currCamera.isActiveAndEnabled) - continue; + // Copy base settings from base camera data and initialize initialize remaining specific settings for this camera type. + CameraData overlayCameraData = baseCameraData; + bool lastCamera = i == lastActiveOverlayCameraIndex; - currCamera.TryGetComponent(out var currCameraData); - // Camera is overlay and enabled - if (currCameraData != null) + using (new ProfilingScope(null, Profiling.Pipeline.beginCameraRendering)) { - // Copy base settings from base camera data and initialize initialize remaining specific settings for this camera type. - CameraData overlayCameraData = baseCameraData; - bool lastCamera = i == lastActiveOverlayCameraIndex; - - using (new ProfilingScope(null, Profiling.Pipeline.beginCameraRendering)) - { - BeginCameraRendering(context, currCamera); - } + BeginCameraRendering(context, currCamera); + } #if VISUAL_EFFECT_GRAPH_0_0_1_OR_NEWER - //It should be called before culling to prepare material. When there isn't any VisualEffect component, this method has no effect. - VFX.VFXManager.PrepareCamera(currCamera); + //It should be called before culling to prepare material. When there isn't any VisualEffect component, this method has no effect. + VFX.VFXManager.PrepareCamera(currCamera); #endif - UpdateVolumeFramework(currCamera, currCameraData); - InitializeAdditionalCameraData(currCamera, currCameraData, lastCamera, ref overlayCameraData); + UpdateVolumeFramework(currCamera, currCameraData); + InitializeAdditionalCameraData(currCamera, currCameraData, lastCamera, ref overlayCameraData); #if ENABLE_VR && ENABLE_XR_MODULE - if (baseCameraData.xr.enabled) - m_XRSystem.UpdateFromCamera(ref overlayCameraData.xr, overlayCameraData); + if (baseCameraData.xr.enabled) + m_XRSystem.UpdateFromCamera(ref overlayCameraData.xr, overlayCameraData); #endif - RenderSingleCamera(context, overlayCameraData, anyPostProcessingEnabled); + RenderSingleCamera(context, overlayCameraData, anyPostProcessingEnabled); - using (new ProfilingScope(null, Profiling.Pipeline.endCameraRendering)) - { - EndCameraRendering(context, currCamera); - } + using (new ProfilingScope(null, Profiling.Pipeline.endCameraRendering)) + { + EndCameraRendering(context, currCamera); } } } + } #if ENABLE_VR && ENABLE_XR_MODULE - if (baseCameraData.xr.enabled) - baseCameraData.cameraTargetDescriptor = originalTargetDesc; - } + if (baseCameraData.xr.enabled) + baseCameraData.cameraTargetDescriptor = originalTargetDesc; + } - if (xrActive) + if (xrActive) + { + CommandBuffer cmd = CommandBufferPool.Get(); + using (new ProfilingScope(cmd, Profiling.Pipeline.XR.mirrorView)) { - CommandBuffer cmd = CommandBufferPool.Get(); - using (new ProfilingScope(cmd, Profiling.Pipeline.XR.mirrorView)) - { - m_XRSystem.RenderMirrorView(cmd, baseCamera); - } - - context.ExecuteCommandBuffer(cmd); - context.Submit(); - CommandBufferPool.Release(cmd); + m_XRSystem.RenderMirrorView(cmd, baseCamera); } - m_XRSystem.ReleaseFrame(); + context.ExecuteCommandBuffer(cmd); + context.Submit(); + CommandBufferPool.Release(cmd); + } + + m_XRSystem.ReleaseFrame(); #endif } @@ -855,7 +855,7 @@ static void InitializeRenderingData(UniversalRenderPipelineAsset settings, ref C if (cameraData.maxShadowDistance > 0.0f) { mainLightCastShadows = (mainLightIndex != -1 && visibleLights[mainLightIndex].light != null && - visibleLights[mainLightIndex].light.shadows != LightShadows.None); + visibleLights[mainLightIndex].light.shadows != LightShadows.None); // If additional lights are shaded per-pixel they cannot cast shadows if (settings.additionalLightsRenderingMode == LightRenderingMode.PerPixel) @@ -1087,6 +1087,7 @@ static void ApplyAdaptivePerformance(ref CameraData cameraData) cameraData.antialiasing = AntialiasingMode.None; cameraData.antialiasingQuality = (AntialiasingQuality)Mathf.Clamp(antialiasingQualityIndex, (int)AntialiasingQuality.Low, (int)AntialiasingQuality.High); } + static void ApplyAdaptivePerformance(ref RenderingData renderingData) { if (AdaptivePerformance.AdaptivePerformanceRenderSettings.SkipDynamicBatching) @@ -1126,6 +1127,7 @@ static void ApplyAdaptivePerformance(ref RenderingData renderingData) if (AdaptivePerformance.AdaptivePerformanceRenderSettings.LutBias >= 1 && renderingData.postProcessingData.lutSize == 32) renderingData.postProcessingData.lutSize = 16; } + #endif } } diff --git a/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs b/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs index 0bfa98a13eb..183cb5eebed 100644 --- a/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs +++ b/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs @@ -418,19 +418,21 @@ static bool IsMultiPassStereoEnabled(Camera camera) return false; } - Comparison cameraComparison = (camera1, camera2) => { return (int) camera1.depth - (int) camera2.depth; }; + Comparison cameraComparison = (camera1, camera2) => { return (int)camera1.depth - (int)camera2.depth; }; #if UNITY_2021_1_OR_NEWER void SortCameras(List cameras) { if (cameras.Count > 1) cameras.Sort(cameraComparison); } + #else void SortCameras(Camera[] cameras) { if (cameras.Length > 1) Array.Sort(cameras, cameraComparison); } + #endif static RenderTextureDescriptor CreateRenderTextureDescriptor(Camera camera, float renderScale, diff --git a/com.unity.render-pipelines.universal/Runtime/XR/XRPass.cs b/com.unity.render-pipelines.universal/Runtime/XR/XRPass.cs index 8881dab6405..092d525d31a 100644 --- a/com.unity.render-pipelines.universal/Runtime/XR/XRPass.cs +++ b/com.unity.render-pipelines.universal/Runtime/XR/XRPass.cs @@ -233,7 +233,7 @@ internal static void Release(XRPass xrPass) internal void AddViewInternal(XRView xrView) { // XRTODO: Fix hard coded max views - int maxSupportedViews = Math.Min(TextureXR.slices, 2/*ShaderConfig.s_XrMaxViews*/); + int maxSupportedViews = Math.Min(TextureXR.slices, 2 /*ShaderConfig.s_XrMaxViews*/); if (views.Count < maxSupportedViews) { @@ -277,7 +277,7 @@ private bool TryGetOcclusionMeshCombinedHashCode(out int hashCode) { hashCode = 0; return false; - } + } } return true; @@ -330,7 +330,7 @@ private void CreateOcclusionMeshCombined() indices[indexStart + i] = (ushort)newIndex; } - + vertexStart += mesh.vertexCount; indexStart += meshIndices.Length; } @@ -463,10 +463,10 @@ internal class XRPass internal static readonly XRPass emptyPass = new XRPass(); internal bool enabled { get => false; } - internal void StartSinglePass(CommandBuffer cmd) { } - internal void StopSinglePass(CommandBuffer cmd) { } - internal void EndCamera(CommandBuffer cmd, CameraData camera) { } - internal void RenderOcclusionMesh(CommandBuffer cmd) { } + internal void StartSinglePass(CommandBuffer cmd) {} + internal void StopSinglePass(CommandBuffer cmd) {} + internal void EndCamera(CommandBuffer cmd, CameraData camera) {} + internal void RenderOcclusionMesh(CommandBuffer cmd) {} } } #endif diff --git a/com.unity.render-pipelines.universal/Runtime/XR/XRSystem.cs b/com.unity.render-pipelines.universal/Runtime/XR/XRSystem.cs index fce0f5043e1..ec9330113d3 100644 --- a/com.unity.render-pipelines.universal/Runtime/XR/XRSystem.cs +++ b/com.unity.render-pipelines.universal/Runtime/XR/XRSystem.cs @@ -175,7 +175,7 @@ internal List SetupFrame(CameraData cameraData) // On Android and iOS, vSyncCount is ignored and all frame rate control is done using Application.targetFrameRate. // Set targetFrameRate to XR refresh rate (round up) float frameRate = 120.0f; - frameRate = display.TryGetDisplayRefreshRate(out float refreshRate)? refreshRate : frameRate; + frameRate = display.TryGetDisplayRefreshRate(out float refreshRate) ? refreshRate : frameRate; Application.targetFrameRate = Mathf.CeilToInt(frameRate); CreateLayoutFromXrSdk(camera, singlePassAllowed: true); @@ -227,24 +227,24 @@ internal bool RefreshXrSdk() return false; } - // Used for updating URP cameraData data struct with XRPass data. + // Used for updating URP cameraData data struct with XRPass data. internal void UpdateCameraData(ref CameraData baseCameraData, in XRPass xr) { // Update cameraData viewport for XR Rect cameraRect = baseCameraData.camera.rect; Rect xrViewport = xr.GetViewport(); baseCameraData.pixelRect = new Rect(cameraRect.x * xrViewport.width + xrViewport.x, - cameraRect.y * xrViewport.height + xrViewport.y, - cameraRect.width * xrViewport.width, - cameraRect.height * xrViewport.height); + cameraRect.y * xrViewport.height + xrViewport.y, + cameraRect.width * xrViewport.width, + cameraRect.height * xrViewport.height); Rect camPixelRect = baseCameraData.pixelRect; baseCameraData.pixelWidth = (int)System.Math.Round(camPixelRect.width + camPixelRect.x) - (int)System.Math.Round(camPixelRect.x); baseCameraData.pixelHeight = (int)System.Math.Round(camPixelRect.height + camPixelRect.y) - (int)System.Math.Round(camPixelRect.y); baseCameraData.aspectRatio = (float)baseCameraData.pixelWidth / (float)baseCameraData.pixelHeight; bool isDefaultXRViewport = (!(Math.Abs(xrViewport.x) > 0.0f || Math.Abs(xrViewport.y) > 0.0f || - Math.Abs(xrViewport.width) < xr.renderTargetDesc.width || - Math.Abs(xrViewport.height) < xr.renderTargetDesc.height)); + Math.Abs(xrViewport.width) < xr.renderTargetDesc.width || + Math.Abs(xrViewport.height) < xr.renderTargetDesc.height)); baseCameraData.isDefaultViewport = baseCameraData.isDefaultViewport && isDefaultXRViewport; // Update cameraData cameraTargetDescriptor for XR. This descriptor is mainly used for configuring intermediate screen space textures @@ -291,7 +291,6 @@ internal void UpdateFromCamera(ref XRPass xrPass, CameraData cameraData) xrPass.UpdateCullingParams(cullingPassId: renderPass.cullingPassIndex, cullingParams); if (xrPass.singlePassEnabled) { - for (int renderParamIndex = 0; renderParamIndex < renderPass.GetRenderParameterCount(); ++renderParamIndex) { renderPass.GetRenderParameter(cameraData.camera, renderParamIndex, out var renderParam); @@ -409,7 +408,7 @@ internal void RenderMirrorView(CommandBuffer cmd, Camera camera) blitDesc.GetBlitParameter(i, out var blitParam); Vector4 scaleBias = yflip ? new Vector4(blitParam.srcRect.width, -blitParam.srcRect.height, blitParam.srcRect.x, blitParam.srcRect.height + blitParam.srcRect.y) : - new Vector4(blitParam.srcRect.width, blitParam.srcRect.height, blitParam.srcRect.x, blitParam.srcRect.y); + new Vector4(blitParam.srcRect.width, blitParam.srcRect.height, blitParam.srcRect.x, blitParam.srcRect.y); Vector4 scaleBiasRt = new Vector4(blitParam.destRect.width, blitParam.destRect.height, blitParam.destRect.x, blitParam.destRect.y); // Eye texture is always gamma corrected, use explicit sRGB read in shader if srcTex formats is not sRGB format. sRGB format will have implicit sRGB read so it is already handled. @@ -544,6 +543,7 @@ bool LayoutSinglePassTestMode(CameraData cameraData, XRLayout frameLayout) return false; } + #endif } } diff --git a/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl b/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl index 800acfa51fa..2b4069d593d 100644 --- a/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl +++ b/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl @@ -77,7 +77,7 @@ float3x3 BuildTangentToWorld(float4 tangentWS, float3 normalWS) // by uniformly scaling all 3 vectors since normalization of the perturbed normal will cancel it. tangentToWorld[0] = tangentToWorld[0] * renormFactor; tangentToWorld[1] = tangentToWorld[1] * renormFactor; - tangentToWorld[2] = tangentToWorld[2] * renormFactor; // normalizes the interpolated vertex normal + tangentToWorld[2] = tangentToWorld[2] * renormFactor; // normalizes the interpolated vertex normal return tangentToWorld; } diff --git a/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl b/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl index 202173d5b18..dcf68fca20e 100644 --- a/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl +++ b/com.unity.render-pipelines.universal/ShaderLibrary/UniversalDOTSInstancing.hlsl @@ -1,4 +1,4 @@ -#ifndef UNIVERSAL_DOTS_INSTANCING_INCLUDED +#ifndef UNIVERSAL_DOTS_INSTANCING_INCLUDED #define UNIVERSAL_DOTS_INSTANCING_INCLUDED #ifdef UNITY_DOTS_INSTANCING_ENABLED @@ -48,4 +48,3 @@ UNITY_DOTS_INSTANCING_END(BuiltinPropertyMetadata) #endif #endif - diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl b/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl index 533332997d5..dad92d6ae01 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl +++ b/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl @@ -7,8 +7,8 @@ half4 _RendererColor; half4 CombinedShapeLightShared(half4 color, half4 mask, half2 lightingUV) { - if (color.a == 0.0) - discard; + if (color.a == 0.0) + discard; color = color * _RendererColor; // This is needed for sprite shape diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl b/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl index 9a49bfc4889..6a25b7ec9a2 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl +++ b/com.unity.render-pipelines.universal/Shaders/2D/Include/LightingUtility.hlsl @@ -1,8 +1,8 @@ #if USE_NORMAL_MAP #if LIGHT_QUALITY_FAST #define NORMALS_LIGHTING_COORDS(TEXCOORDA, TEXCOORDB) \ - half4 lightDirection : TEXCOORDA;\ - half2 screenUV : TEXCOORDB; + half4 lightDirection : TEXCOORDA;\ + half2 screenUV : TEXCOORDB; #define TRANSFER_NORMALS_LIGHTING(output, worldSpacePos)\ float4 clipVertex = output.positionCS / output.positionCS.w;\ @@ -11,15 +11,15 @@ output.lightDirection.z = _LightZDistance;\ output.lightDirection.w = 0;\ output.lightDirection.xyz = normalize(output.lightDirection.xyz); - + #define APPLY_NORMALS_LIGHTING(input, lightColor)\ half4 normal = SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, input.screenUV);\ half3 normalUnpacked = UnpackNormalRGBNoScale(normal);\ lightColor = lightColor * saturate(dot(input.lightDirection.xyz, normalUnpacked)); #else #define NORMALS_LIGHTING_COORDS(TEXCOORDA, TEXCOORDB) \ - half4 positionWS : TEXCOORDA;\ - half2 screenUV : TEXCOORDB; + half4 positionWS : TEXCOORDA;\ + half2 screenUV : TEXCOORDB; #define TRANSFER_NORMALS_LIGHTING(output, worldSpacePos) \ float4 clipVertex = output.positionCS / output.positionCS.w;\ @@ -39,8 +39,8 @@ #define NORMALS_LIGHTING_VARIABLES \ TEXTURE2D(_NormalMap); \ SAMPLER(sampler_NormalMap); \ - half4 _LightPosition;\ - half _LightZDistance; + half4 _LightPosition;\ + half _LightZDistance; #else #define NORMALS_LIGHTING_COORDS(TEXCOORDA, TEXCOORDB) #define NORMALS_LIGHTING_VARIABLES @@ -65,7 +65,7 @@ color.rgb = (color.rgb * shadowIntensity) + (color.rgb * intensity*(1 - shadowIntensity));\ } - + #define TRANSFER_SHADOWS(output)\ output.shadowUV = ComputeScreenPos(output.positionCS / output.positionCS.w).xy; @@ -76,4 +76,3 @@ half2 _ShapeLightBlendFactors##index;\ half4 _ShapeLightMaskFilter##index;\ half4 _ShapeLightInvertedFilter##index; - diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl b/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl index 28367c07a04..9a3fecd310f 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl +++ b/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl @@ -7,7 +7,7 @@ half4 NormalsRenderingShared(half4 color, half3 normalTS, half3 tangent, half3 b half3 normalWS = TransformTangentToWorld(normalTS, half3x3(tangent.xyz, bitangent.xyz, normal.xyz)); half3 normalVS = TransformWorldToViewDir(normalWS); - + normalColor.rgb = 0.5 * ((normalVS)+1); normalColor.a = color.a; // used for blending diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point-Volumetric.shader b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point-Volumetric.shader index 637a323a3c6..4d375b9e5ea 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point-Volumetric.shader +++ b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point-Volumetric.shader @@ -29,13 +29,13 @@ Shader "Hidden/Light2d-Point-Volumetric" { float4 positionCS : SV_POSITION; half2 uv : TEXCOORD0; - half2 screenUV : TEXCOORD1; - half2 lookupUV : TEXCOORD2; // This is used for light relative direction + half2 screenUV : TEXCOORD1; + half2 lookupUV : TEXCOORD2; // This is used for light relative direction #if LIGHT_QUALITY_FAST - half4 lightDirection : TEXCOORD4; + half4 lightDirection : TEXCOORD4; #else - half4 positionWS : TEXCOORD4; + half4 positionWS : TEXCOORD4; #endif SHADOW_COORDS(TEXCOORD5) }; @@ -59,9 +59,9 @@ Shader "Hidden/Light2d-Point-Volumetric" float4x4 _LightInvMatrix; float4x4 _LightNoRotInvMatrix; half _LightZDistance; - half _OuterAngle; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees - half _InnerAngleMult; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees - half _InnerRadiusMult; // 1-0 where 1 is the value at the center and 0 is the value at the outer radius + half _OuterAngle; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees + half _InnerAngleMult; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees + half _InnerRadiusMult; // 1-0 where 1 is the value at the center and 0 is the value at the outer radius half _InverseHDREmulationScale; half _IsFullSpotlight; diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point.shader b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point.shader index 0260c06f7c0..548876f748c 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point.shader +++ b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Point.shader @@ -37,7 +37,7 @@ Shader "Hidden/Light2D-Point" { float4 positionCS : SV_POSITION; half2 uv : TEXCOORD0; - half2 lookupUV : TEXCOORD2; // This is used for light relative direction + half2 lookupUV : TEXCOORD2; // This is used for light relative direction NORMALS_LIGHTING_COORDS(TEXCOORD4, TEXCOORD5) SHADOW_COORDS(TEXCOORD6) @@ -59,13 +59,13 @@ Shader "Hidden/Light2D-Point" NORMALS_LIGHTING_VARIABLES SHADOW_VARIABLES - half4 _LightColor; + half4 _LightColor; float4x4 _LightInvMatrix; float4x4 _LightNoRotInvMatrix; - half _OuterAngle; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees - half _InnerAngleMult; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees - half _InnerRadiusMult; // 1-0 where 1 is the value at the center and 0 is the value at the outer radius - half _InverseHDREmulationScale; + half _OuterAngle; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees + half _InnerAngleMult; // 1-0 where 1 is the value at 0 degrees and 1 is the value at 180 degrees + half _InnerRadiusMult; // 1-0 where 1 is the value at the center and 0 is the value at the outer radius + half _InverseHDREmulationScale; half _IsFullSpotlight; Varyings vert(Attributes input) diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape-Volumetric.shader b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape-Volumetric.shader index 41bd6e039da..a9f9f0c5297 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape-Volumetric.shader +++ b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape-Volumetric.shader @@ -41,7 +41,7 @@ Shader "Hidden/Light2D-Shape-Volumetric" half _InverseHDREmulationScale; #ifdef SPRITE_LIGHT - TEXTURE2D(_CookieTex); // This can either be a sprite texture uv or a falloff texture + TEXTURE2D(_CookieTex); // This can either be a sprite texture uv or a falloff texture SAMPLER(sampler_CookieTex); #else uniform half _FalloffIntensity; diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape.shader b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape.shader index 8dd4e76de48..e513286e3c9 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape.shader +++ b/com.unity.render-pipelines.universal/Shaders/2D/Light2D-Shape.shader @@ -48,7 +48,7 @@ Shader "Hidden/Light2D-Shape" half _FalloffDistance; #ifdef SPRITE_LIGHT - TEXTURE2D(_CookieTex); // This can either be a sprite texture uv or a falloff texture + TEXTURE2D(_CookieTex); // This can either be a sprite texture uv or a falloff texture SAMPLER(sampler_CookieTex); #else half _FalloffIntensity; diff --git a/com.unity.render-pipelines.universal/Shaders/2D/ShadowGroup2D.shader b/com.unity.render-pipelines.universal/Shaders/2D/ShadowGroup2D.shader index bdfc6843425..f7d363a30c8 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/ShadowGroup2D.shader +++ b/com.unity.render-pipelines.universal/Shaders/2D/ShadowGroup2D.shader @@ -60,7 +60,7 @@ Shader "Hidden/ShadowGroup2D" lightDir.z = 0; // Start of code to see if this point should be extruded - float3 lightDirection = normalize(lightDir); + float3 lightDirection = normalize(lightDir); float3 endpoint = vertexWS + (_ShadowRadius * -lightDirection); @@ -147,7 +147,7 @@ Shader "Hidden/ShadowGroup2D" o.vertex = TransformObjectToHClip(v.vertex); // RGB - R is shadow value (to support soft shadows), G is Self Shadow Mask, B is No Shadow Mask - o.color = 1; + o.color = 1; o.color.g = 0.5; o.color.b = 1; diff --git a/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader b/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader index d57bd918e62..009c8995663 100644 --- a/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader +++ b/com.unity.render-pipelines.universal/Shaders/2D/Sprite-Lit-Default.shader @@ -49,8 +49,8 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" { float4 positionCS : SV_POSITION; half4 color : COLOR; - float2 uv : TEXCOORD0; - half2 lightingUV : TEXCOORD1; + float2 uv : TEXCOORD0; + half2 lightingUV : TEXCOORD1; UNITY_VERTEX_OUTPUT_STEREO }; @@ -114,20 +114,20 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" struct Attributes { float3 positionOS : POSITION; - float4 color : COLOR; - float2 uv : TEXCOORD0; + float4 color : COLOR; + float2 uv : TEXCOORD0; float4 tangent : TANGENT; UNITY_VERTEX_INPUT_INSTANCE_ID }; struct Varyings { - float4 positionCS : SV_POSITION; - half4 color : COLOR; - float2 uv : TEXCOORD0; - half3 normalWS : TEXCOORD1; - half3 tangentWS : TEXCOORD2; - half3 bitangentWS : TEXCOORD3; + float4 positionCS : SV_POSITION; + half4 color : COLOR; + float2 uv : TEXCOORD0; + half3 normalWS : TEXCOORD1; + half3 tangentWS : TEXCOORD2; + half3 bitangentWS : TEXCOORD3; UNITY_VERTEX_OUTPUT_STEREO }; @@ -173,16 +173,16 @@ Shader "Universal Render Pipeline/2D/Sprite-Lit-Default" struct Attributes { float3 positionOS : POSITION; - float4 color : COLOR; - float2 uv : TEXCOORD0; + float4 color : COLOR; + float2 uv : TEXCOORD0; UNITY_VERTEX_INPUT_INSTANCE_ID }; struct Varyings { - float4 positionCS : SV_POSITION; - float4 color : COLOR; - float2 uv : TEXCOORD0; + float4 positionCS : SV_POSITION; + float4 color : COLOR; + float2 uv : TEXCOORD0; UNITY_VERTEX_OUTPUT_STEREO }; diff --git a/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader b/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader index 0893dc76360..105eb6d9efb 100644 --- a/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader +++ b/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLit.shader @@ -119,7 +119,7 @@ Shader "Universal Render Pipeline/Particles/Lit" #include "Packages/com.unity.render-pipelines.universal/Shaders/Particles/ParticlesLitForwardPass.hlsl" ENDHLSL } - // ------------------------------------------------------------------ + // ------------------------------------------------------------------ // GBuffer pass. Pass { diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/FinalPost.shader b/com.unity.render-pipelines.universal/Shaders/PostProcessing/FinalPost.shader index 5f5d901e965..9a68a78a32b 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/FinalPost.shader +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/FinalPost.shader @@ -118,8 +118,8 @@ Shader "Hidden/Universal Render Pipeline/FinalPost" color = ApplyGrain(color, positionNDC, TEXTURE2D_ARGS(_Grain_Texture, sampler_LinearRepeat), GrainIntensity, GrainResponse, GrainScale, GrainOffset); } #endif - - #if _LINEAR_TO_SRGB_CONVERSION + + #if _LINEAR_TO_SRGB_CONVERSION { color = LinearToSRGB(color); } diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderHdr.shader b/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderHdr.shader index 23188a58651..e2911452b13 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderHdr.shader +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderHdr.shader @@ -4,7 +4,7 @@ Shader "Hidden/Universal Render Pipeline/LutBuilderHdr" #pragma exclude_renderers gles #pragma multi_compile_local _ _TONEMAP_ACES _TONEMAP_NEUTRAL - + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/Common.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ACES.hlsl" @@ -62,7 +62,7 @@ Shader "Hidden/Universal Render Pipeline/LutBuilderHdr" #endif colorLog = (colorLog - ACEScc_MIDGRAY) * _HueSatCon.z + ACEScc_MIDGRAY; - + #if _TONEMAP_ACES colorLinear = ACES_to_ACEScg(ACEScc_to_ACES(colorLog)); #else diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderLdr.shader b/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderLdr.shader index 959441c4a58..e922783da95 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderLdr.shader +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/LutBuilderLdr.shader @@ -3,7 +3,7 @@ Shader "Hidden/Universal Render Pipeline/LutBuilderLdr" HLSLINCLUDE #pragma exclude_renderers gles - + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/Shaders/PostProcessing/Common.hlsl" #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl" diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/PaniniProjection.shader b/com.unity.render-pipelines.universal/Shaders/PostProcessing/PaniniProjection.shader index 77608a435e2..36c7e73346b 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/PaniniProjection.shader +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/PaniniProjection.shader @@ -73,7 +73,7 @@ Shader "Hidden/Universal Render Pipeline/PaniniProjection" // d | / // | / , // |/ . - // P + // P // | ´ // | , ´ // +- ´ diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.hlsl b/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.hlsl index 6cae25b95e8..7ab0f5bce1a 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.hlsl +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.hlsl @@ -50,7 +50,7 @@ * * The shader has three passes, chained together as follows: * - * |input|------------------ + * |input|------------------ * v | * [ SMAA*EdgeDetection ] | * v | @@ -60,7 +60,7 @@ * v | * |blendTex| | * v | - * [ SMAANeighborhoodBlending ] <------ + * [ SMAANeighborhoodBlending ] <------ * v * |output| * @@ -559,7 +559,7 @@ #define SMAATexturePass2D(tex) tex #define SMAASampleLevelZero(tex, coord) SAMPLE_TEXTURE2D_X_LOD(tex, LinearSampler, coord, 0) #define SMAASampleLevelZeroNoRescale(tex, coord) tex.SampleLevel(LinearSampler, coord, 0) -#define SMAASampleLevelZeroPoint(tex, coord) SAMPLE_TEXTURE2D_X_LOD(tex, PointSampler, coord, 0) +#define SMAASampleLevelZeroPoint(tex, coord) SAMPLE_TEXTURE2D_X_LOD(tex, PointSampler, coord, 0) #define SMAASampleLevelZeroOffset(tex, coord, offset) SAMPLE_TEXTURE2D_X_LOD(tex, LinearSampler, coord + offset * SMAA_RT_METRICS.xy, 0) #define SMAASample(tex, coord) SAMPLE_TEXTURE2D_X(tex, LinearSampler, coord) #define SMAASamplePoint(tex, coord) SAMPLE_TEXTURE2D_X(tex, PointSampler, coord) diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.shader b/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.shader index 8eeae8d1225..132340687ca 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.shader +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasing.shader @@ -18,7 +18,7 @@ Shader "Hidden/Universal Render Pipeline/SubpixelMorphologicalAntialiasing" { Cull Off ZWrite Off ZTest Always - // Edge detection + // Edge detection Pass { Stencil diff --git a/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasingBridge.hlsl b/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasingBridge.hlsl index b0fa5966298..1e60dac7fd4 100644 --- a/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasingBridge.hlsl +++ b/com.unity.render-pipelines.universal/Shaders/PostProcessing/SubpixelMorphologicalAntialiasingBridge.hlsl @@ -57,7 +57,7 @@ VaryingsEdge VertEdge(Attributes input) #else output.positionCS = TransformFullscreenMesh(input.positionOS.xyz); output.uv = UnityStereoTransformScreenSpaceTex(input.uv); -#endif +#endif SMAAEdgeDetectionVS(output.uv, output.offsets); return output; } @@ -90,7 +90,7 @@ VaryingsBlend VertBlend(Attributes input) #else output.positionCS = TransformFullscreenMesh(input.positionOS.xyz); output.uv = UnityStereoTransformScreenSpaceTex(input.uv); -#endif +#endif SMAABlendingWeightCalculationVS(output.uv, output.pixcoord, output.offsets); return output; } @@ -122,7 +122,7 @@ VaryingsNeighbor VertNeighbor(Attributes input) #else output.positionCS = TransformFullscreenMesh(input.positionOS.xyz); output.uv = UnityStereoTransformScreenSpaceTex(input.uv); -#endif +#endif SMAANeighborhoodBlendingVS(output.uv, output.offset); return output; } diff --git a/com.unity.render-pipelines.universal/Shaders/Shaders.cs b/com.unity.render-pipelines.universal/Shaders/Shaders.cs index 56a2462e855..b76a9056b52 100644 --- a/com.unity.render-pipelines.universal/Shaders/Shaders.cs +++ b/com.unity.render-pipelines.universal/Shaders/Shaders.cs @@ -1,3 +1,3 @@ // UniversalPR Shaders folder need an Assembly Definition files to create a .cs project // This is a dummy shader file so the Shaders assembly is not empty. -class ShadersDummy { } +class ShadersDummy {} diff --git a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader index e063c9f771f..a27b5b5c63e 100644 --- a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader +++ b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLit.shader @@ -35,16 +35,16 @@ Shader "Universal Render Pipeline/Terrain/Lit" [HideInInspector] _MainTex("BaseMap (RGB)", 2D) = "grey" {} [HideInInspector] _BaseColor("Main Color", Color) = (1,1,1,1) - [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} + [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} [ToggleUI] _EnableInstancedPerPixelNormal("Enable Instanced per-pixel normal", Float) = 1.0 } - HLSLINCLUDE + HLSLINCLUDE - #pragma multi_compile_fragment __ _ALPHATEST_ON + #pragma multi_compile_fragment __ _ALPHATEST_ON - ENDHLSL + ENDHLSL SubShader { diff --git a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader index 80700e71837..74b4f70672c 100644 --- a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader +++ b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitAdd.shader @@ -33,14 +33,14 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Add Pass)" [HideInInspector] _BaseMap("BaseMap (RGB)", 2D) = "white" {} [HideInInspector] _BaseColor("Main Color", Color) = (1,1,1,1) - [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} + [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} } - HLSLINCLUDE + HLSLINCLUDE - #pragma multi_compile_fragment __ _ALPHATEST_ON + #pragma multi_compile_fragment __ _ALPHATEST_ON - ENDHLSL + ENDHLSL SubShader { diff --git a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader index 48c3732706b..576b0bd1000 100644 --- a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader +++ b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitBase.shader @@ -5,14 +5,14 @@ Shader "Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)" [MainColor] _BaseColor("Color", Color) = (1,1,1,1) _MainTex("Albedo(RGB), Smoothness(A)", 2D) = "white" {} _MetallicTex ("Metallic (R)", 2D) = "black" {} - [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} + [HideInInspector] _TerrainHolesTexture("Holes Map (RGB)", 2D) = "white" {} } - HLSLINCLUDE + HLSLINCLUDE - #pragma multi_compile_fragment __ _ALPHATEST_ON + #pragma multi_compile_fragment __ _ALPHATEST_ON - ENDHLSL + ENDHLSL SubShader { diff --git a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl index 4756688f5e5..195ab01ee07 100644 --- a/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl +++ b/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitPasses.hlsl @@ -25,8 +25,8 @@ SAMPLER(sampler_TerrainHolesTexture); void ClipHoles(float2 uv) { - float hole = SAMPLE_TEXTURE2D(_TerrainHolesTexture, sampler_TerrainHolesTexture, uv).r; - clip(hole == 0.0f ? -1 : 1); + float hole = SAMPLE_TEXTURE2D(_TerrainHolesTexture, sampler_TerrainHolesTexture, uv).r; + clip(hole == 0.0f ? -1 : 1); } #endif @@ -426,7 +426,7 @@ struct AttributesLean float4 position : POSITION; float3 normalOS : NORMAL; #ifdef _ALPHATEST_ON - float2 texcoord : TEXCOORD0; + float2 texcoord : TEXCOORD0; #endif UNITY_VERTEX_INPUT_INSTANCE_ID }; @@ -457,19 +457,19 @@ VaryingsLean ShadowPassVertex(AttributesLean v) clipPos.z = max(clipPos.z, clipPos.w * UNITY_NEAR_CLIP_VALUE); #endif - o.clipPos = clipPos; + o.clipPos = clipPos; #ifdef _ALPHATEST_ON - o.texcoord = v.texcoord; + o.texcoord = v.texcoord; #endif - return o; + return o; } half4 ShadowPassFragment(VaryingsLean IN) : SV_TARGET { #ifdef _ALPHATEST_ON - ClipHoles(IN.texcoord); + ClipHoles(IN.texcoord); #endif return 0; } @@ -484,15 +484,15 @@ VaryingsLean DepthOnlyVertex(AttributesLean v) TerrainInstancing(v.position, v.normalOS); o.clipPos = TransformObjectToHClip(v.position.xyz); #ifdef _ALPHATEST_ON - o.texcoord = v.texcoord; + o.texcoord = v.texcoord; #endif - return o; + return o; } half4 DepthOnlyFragment(VaryingsLean IN) : SV_TARGET { #ifdef _ALPHATEST_ON - ClipHoles(IN.texcoord); + ClipHoles(IN.texcoord); #endif #ifdef SCENESELECTIONPASS // We use depth prepass for scene selection in the editor, this code allow to output the outline correctly diff --git a/com.unity.render-pipelines.universal/Shaders/Utils/MaterialError.shader b/com.unity.render-pipelines.universal/Shaders/Utils/MaterialError.shader index 313e0fbb72c..bc74f604aaf 100644 --- a/com.unity.render-pipelines.universal/Shaders/Utils/MaterialError.shader +++ b/com.unity.render-pipelines.universal/Shaders/Utils/MaterialError.shader @@ -1,4 +1,4 @@ -Shader "Hidden/Universal Render Pipeline/MaterialError" +Shader "Hidden/Universal Render Pipeline/MaterialError" { SubShader { diff --git a/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs b/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs index 971e5dc5662..5fe7212f55b 100644 --- a/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs +++ b/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs @@ -105,7 +105,7 @@ public void LightIsNotInVisibleListIfNotInCameraView() [Test] public void CachedMeshDataIsUpdatedOnChange() { - var shapePath = new Vector3[4] { new Vector3( 0, 0, 0), new Vector3(1,0,0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) }; + var shapePath = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) }; var light = m_TestObjectCached.AddComponent(); light.lightType = Light2D.LightType.Freeform; @@ -118,7 +118,7 @@ public void CachedMeshDataIsUpdatedOnChange() [Test] public void CachedMeshDataIsOverriddenByRuntimeChanges() { - var shapePath = new Vector3[4] { new Vector3( 0, 0, 0), new Vector3(1,0,0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) }; + var shapePath = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) }; var light = m_TestObjectCached.AddComponent(); light.lightType = Light2D.LightType.Freeform; light.SetShapePath(shapePath); @@ -132,7 +132,7 @@ public void CachedMeshDataIsOverriddenByRuntimeChanges() triangleCount = light.lightMesh.vertices.Length; // Simulate Runtime Behavior. - var shapePathChanged = new Vector3[5] { new Vector3( 0, 0, 0), new Vector3(1,0,0), new Vector3(1, 1, 0), new Vector3(0.5f, 1.5f, 0), new Vector3(0, 1, 0) }; + var shapePathChanged = new Vector3[5] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0.5f, 1.5f, 0), new Vector3(0, 1, 0) }; light.SetShapePath(shapePathChanged); light.UpdateMesh(true); diff --git a/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs b/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs index 7abe290ae8e..88b64e8951e 100644 --- a/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs +++ b/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs @@ -59,13 +59,14 @@ public IEnumerator PipelineSetsAndRestoreGlobalShaderTagCorrectly() Assert.AreEqual("", Shader.globalRenderPipeline, "Render Pipeline shader tag is not restored."); } + #endif void AssetCheck() { //Assert.IsNotNull(currentAsset, "Render Pipeline Asset is Null"); // Temp fix, test passes if project isnt setup for Universal RP - if(currentAsset == null) + if (currentAsset == null) Assert.Pass("Render Pipeline Asset is Null, test pass by default"); Assert.AreEqual(currentAsset.GetType(), typeof(UniversalRenderPipelineAsset), diff --git a/com.unity.shaderanalysis/Editor/API/AsyncBuildReportJob.cs b/com.unity.shaderanalysis/Editor/API/AsyncBuildReportJob.cs index e3daa18efe6..233056fd6e6 100644 --- a/com.unity.shaderanalysis/Editor/API/AsyncBuildReportJob.cs +++ b/com.unity.shaderanalysis/Editor/API/AsyncBuildReportJob.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEditor.Build.Reporting; namespace UnityEditor.ShaderAnalysis diff --git a/com.unity.shaderanalysis/Editor/API/AsyncJob.cs b/com.unity.shaderanalysis/Editor/API/AsyncJob.cs index 0f4e49981c3..b36ee515d18 100644 --- a/com.unity.shaderanalysis/Editor/API/AsyncJob.cs +++ b/com.unity.shaderanalysis/Editor/API/AsyncJob.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderAnalysis { @@ -28,6 +28,7 @@ public bool Tick() #endif return Internal_Tick(); } + protected abstract bool Internal_Tick(); /// @@ -39,8 +40,9 @@ public void Cancel() Progress.Cancel(m_TaskId); else #endif - Internal_Cancel(); + Internal_Cancel(); } + protected abstract void Internal_Cancel(); /// diff --git a/com.unity.shaderanalysis/Editor/API/BuildReportFeature.cs b/com.unity.shaderanalysis/Editor/API/BuildReportFeature.cs index 155aeee9cef..edee9319234 100644 --- a/com.unity.shaderanalysis/Editor/API/BuildReportFeature.cs +++ b/com.unity.shaderanalysis/Editor/API/BuildReportFeature.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderAnalysis { diff --git a/com.unity.shaderanalysis/Editor/API/EditorShaderTools.cs b/com.unity.shaderanalysis/Editor/API/EditorShaderTools.cs index ae9c3a5b430..fdbf025c1ef 100644 --- a/com.unity.shaderanalysis/Editor/API/EditorShaderTools.cs +++ b/com.unity.shaderanalysis/Editor/API/EditorShaderTools.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using UnityEditor.ShaderAnalysis.Internal; @@ -29,7 +29,7 @@ public static IAsyncJob GenerateBuildReportAsync(ShaderAnalysisReport New( bool logCommandLines = false ) => new ShaderAnalysisReport + { + asset = asset, + common = new ShaderAnalysisReport { - asset = asset, - common = new ShaderAnalysisReport - { - targetPlatform = currentPlatform, - filter = filter, - features = features, - logCommandLines = logCommandLines - } - }; + targetPlatform = currentPlatform, + filter = filter, + features = features, + logCommandLines = logCommandLines + } + }; public BuildTarget targetPlatform; public ShaderProgramFilter filter; @@ -38,9 +38,9 @@ public struct ShaderAnalysisReport public ShaderAnalysisReport Into() => new ShaderAnalysisReport - { - asset = (TAsset2)Convert.ChangeType(asset, typeof(TAsset2)), - common = common - }; + { + asset = (TAsset2)Convert.ChangeType(asset, typeof(TAsset2)), + common = common + }; } } diff --git a/com.unity.shaderanalysis/Editor/API/ShaderBuildReport.cs b/com.unity.shaderanalysis/Editor/API/ShaderBuildReport.cs index 8377ad385bb..3f354c814f3 100644 --- a/com.unity.shaderanalysis/Editor/API/ShaderBuildReport.cs +++ b/com.unity.shaderanalysis/Editor/API/ShaderBuildReport.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; diff --git a/com.unity.shaderanalysis/Editor/API/ShaderCompilationUtility.cs b/com.unity.shaderanalysis/Editor/API/ShaderCompilationUtility.cs index 838b87871b2..2d926e7d15a 100644 --- a/com.unity.shaderanalysis/Editor/API/ShaderCompilationUtility.cs +++ b/com.unity.shaderanalysis/Editor/API/ShaderCompilationUtility.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; using UnityEngine; diff --git a/com.unity.shaderanalysis/Editor/API/ShaderCompilerOptions.cs b/com.unity.shaderanalysis/Editor/API/ShaderCompilerOptions.cs index 9f8b6642a59..16278f6f4b2 100644 --- a/com.unity.shaderanalysis/Editor/API/ShaderCompilerOptions.cs +++ b/com.unity.shaderanalysis/Editor/API/ShaderCompilerOptions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace UnityEditor.ShaderAnalysis diff --git a/com.unity.shaderanalysis/Editor/API/ShaderProfile.cs b/com.unity.shaderanalysis/Editor/API/ShaderProfile.cs index 63a1be5a7d4..525bdcbe4a1 100644 --- a/com.unity.shaderanalysis/Editor/API/ShaderProfile.cs +++ b/com.unity.shaderanalysis/Editor/API/ShaderProfile.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderAnalysis { diff --git a/com.unity.shaderanalysis/Editor/API/ShaderProgramFilter.cs b/com.unity.shaderanalysis/Editor/API/ShaderProgramFilter.cs index c44e3ce08c6..13bec41493d 100644 --- a/com.unity.shaderanalysis/Editor/API/ShaderProgramFilter.cs +++ b/com.unity.shaderanalysis/Editor/API/ShaderProgramFilter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -16,6 +16,7 @@ public KeywordSet(IEnumerable values) foreach (var value in values) m_Values.Add(value); } + public bool Contains(string value) => m_Values?.Contains(value) ?? false; public void Add(string value) => m_Values?.Add(value); public bool IsSubsetOf(HashSet entry) => m_Values?.IsSubsetOf(entry) ?? true; diff --git a/com.unity.shaderanalysis/Editor/Internal/AssemblyProperties.cs b/com.unity.shaderanalysis/Editor/Internal/AssemblyProperties.cs index e36394239a0..bbf2a78a1e8 100644 --- a/com.unity.shaderanalysis/Editor/Internal/AssemblyProperties.cs +++ b/com.unity.shaderanalysis/Editor/Internal/AssemblyProperties.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Unity.ShaderAnalysis.Tests.Editor")] diff --git a/com.unity.shaderanalysis/Editor/Internal/AssetMetadata.cs b/com.unity.shaderanalysis/Editor/Internal/AssetMetadata.cs index 174eae366ec..0c3be5fddee 100644 --- a/com.unity.shaderanalysis/Editor/Internal/AssetMetadata.cs +++ b/com.unity.shaderanalysis/Editor/Internal/AssetMetadata.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEngine; diff --git a/com.unity.shaderanalysis/Editor/Internal/EditorUpdateManager.cs b/com.unity.shaderanalysis/Editor/Internal/EditorUpdateManager.cs index 619f31e545f..c78168f5828 100644 --- a/com.unity.shaderanalysis/Editor/Internal/EditorUpdateManager.cs +++ b/com.unity.shaderanalysis/Editor/Internal/EditorUpdateManager.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderAnalysis.Internal { diff --git a/com.unity.shaderanalysis/Editor/Internal/Export/CSV/CSVReportExport.cs b/com.unity.shaderanalysis/Editor/Internal/Export/CSV/CSVReportExport.cs index a9215679958..ec60d2cd632 100644 --- a/com.unity.shaderanalysis/Editor/Internal/Export/CSV/CSVReportExport.cs +++ b/com.unity.shaderanalysis/Editor/Internal/Export/CSV/CSVReportExport.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; namespace UnityEditor.ShaderAnalysis.Internal { diff --git a/com.unity.shaderanalysis/Editor/Internal/ExporterUtilities.cs b/com.unity.shaderanalysis/Editor/Internal/ExporterUtilities.cs index 4fe676f5d37..93b63af5816 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ExporterUtilities.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ExporterUtilities.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq; diff --git a/com.unity.shaderanalysis/Editor/Internal/PackagesUtilities.cs b/com.unity.shaderanalysis/Editor/Internal/PackagesUtilities.cs index 06a783dcda1..65418385e4f 100644 --- a/com.unity.shaderanalysis/Editor/Internal/PackagesUtilities.cs +++ b/com.unity.shaderanalysis/Editor/Internal/PackagesUtilities.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Linq.Expressions; using System.Reflection; diff --git a/com.unity.shaderanalysis/Editor/Internal/ProcessManager.cs b/com.unity.shaderanalysis/Editor/Internal/ProcessManager.cs index ff5a57005ea..66c19e1a2ba 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ProcessManager.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ProcessManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; @@ -109,7 +109,7 @@ void DoCancel(IProcess process) void Update() { - for (var i = m_RunningProcesses.Count - 1; i >= 0 ; --i) + for (var i = m_RunningProcesses.Count - 1; i >= 0; --i) { var proc = m_RunningProcesses[i]; if (proc.process.HasExited) diff --git a/com.unity.shaderanalysis/Editor/Internal/ProcessOperationBase.cs b/com.unity.shaderanalysis/Editor/Internal/ProcessOperationBase.cs index 923248e520c..12869de638b 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ProcessOperationBase.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ProcessOperationBase.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; diff --git a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisInspectorWindow.cs b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisInspectorWindow.cs index b853aa0a266..322338e2235 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisInspectorWindow.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisInspectorWindow.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -72,8 +72,8 @@ static void DefaultOnGUI_UnitToolbar( ShaderBuildReport reference, string assetGUID) { - } + #endregion public static string referenceFolderPath @@ -325,14 +325,14 @@ public GUIAction(GUIActionKind kind, Object asset) } public GUIAction(GUIActionKind kind, string assetGUID, ShaderBuildReport report) - : this(kind) + : this(kind) { this.report = report; this.assetGUID = assetGUID; } public GUIAction(GUIActionKind kind, ShaderBuildReport report, ShaderBuildReport reportReference, string assetGUID) - : this(kind) + : this(kind) { this.report = report; this.reportReference = reportReference; @@ -562,7 +562,7 @@ void OnGUI_DisplayLogResults(Object asset) m_BuildScrollPosition = GUILayout.BeginScrollView(m_BuildScrollPosition); EditorGUILayout.LabelField(UIUtils.Text(String.Format("Passes: {0}, MultiCompiles: {1}", report.programs.Count, report.compileUnits.Count))); - for (var i = 0 ; i < report.programs.Count ; ++i) + for (var i = 0; i < report.programs.Count; ++i) { var program = report.programs[i]; var programHash = ComputeProgramHash(i); diff --git a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisMenu.cs b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisMenu.cs index 29a6c0b626c..47a88250a4a 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisMenu.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisMenu.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; namespace UnityEditor.ShaderAnalysis.Internal diff --git a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisReport.cs b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisReport.cs index d12cfb74b4d..1f7860bad6c 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisReport.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisReport.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; diff --git a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisUtils.cs b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisUtils.cs index 3d367f257da..5dcfa3a7fbf 100644 --- a/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisUtils.cs +++ b/com.unity.shaderanalysis/Editor/Internal/ShaderAnalysisUtils.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -94,6 +94,7 @@ public static FileInfo GetWorkingAssetMetaDataBaseFile(DirectoryInfo sourceDir) var fileInfo = new FileInfo(Path.Combine(sourceDir.FullName, "AssetMetaDataBase.asset")); return fileInfo; } + #endregion #region Shader Code @@ -286,6 +287,7 @@ static FileInfo GetAssetMetadataFileFor(BuildTarget target, DirectoryInfo rootFo { return new FileInfo(Path.Combine(rootFolder.FullName, string.Format("AssetMetaData_{0}.asset", target))); } + #endregion #region Basic Utils @@ -321,6 +323,7 @@ public static string Join(this List strings, string separator) return builder.ToString(); } + #endregion public static ShaderBuildReportDiff DiffReports(ShaderBuildReport source, ShaderBuildReport reference) @@ -405,10 +408,10 @@ public static ShaderCompilerOptions DefaultCompileOptions( // add include folders of playback engines foreach (var playbackEnginePath in new[] - { - "../..", - "PlaybackEngines" - }) + { + "../..", + "PlaybackEngines" + }) { var directory = new DirectoryInfo(Path.Combine(EditorApplication.applicationContentsPath, playbackEnginePath)); if (directory.Exists) diff --git a/com.unity.shaderanalysis/Editor/Internal/SimpleDataCache.cs b/com.unity.shaderanalysis/Editor/Internal/SimpleDataCache.cs index d41a1b6619f..864416647d5 100644 --- a/com.unity.shaderanalysis/Editor/Internal/SimpleDataCache.cs +++ b/com.unity.shaderanalysis/Editor/Internal/SimpleDataCache.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.InteropServices; diff --git a/com.unity.shaderanalysis/Editor/Internal/SymbolicLinkUtilities.cs b/com.unity.shaderanalysis/Editor/Internal/SymbolicLinkUtilities.cs index 75f04aa2cad..a89e62bd7bb 100644 --- a/com.unity.shaderanalysis/Editor/Internal/SymbolicLinkUtilities.cs +++ b/com.unity.shaderanalysis/Editor/Internal/SymbolicLinkUtilities.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.IO; using System.Security.Principal; diff --git a/com.unity.shaderanalysis/Editor/Internal/UIUtils.cs b/com.unity.shaderanalysis/Editor/Internal/UIUtils.cs index 08739b2c871..3070ec77d57 100644 --- a/com.unity.shaderanalysis/Editor/Internal/UIUtils.cs +++ b/com.unity.shaderanalysis/Editor/Internal/UIUtils.cs @@ -1,4 +1,4 @@ -using System; +using System; using UnityEngine; namespace UnityEditor.ShaderAnalysis.Internal diff --git a/com.unity.shaderanalysis/Editor/Platforms/BuildReportJobAsync.cs b/com.unity.shaderanalysis/Editor/Platforms/BuildReportJobAsync.cs index 74f3dcfdc8d..26f374dabb8 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/BuildReportJobAsync.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/BuildReportJobAsync.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; diff --git a/com.unity.shaderanalysis/Editor/Platforms/ComputeShaderReportBuildData.cs b/com.unity.shaderanalysis/Editor/Platforms/ComputeShaderReportBuildData.cs index 75214d275d2..0fb22d35efd 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/ComputeShaderReportBuildData.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/ComputeShaderReportBuildData.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; diff --git a/com.unity.shaderanalysis/Editor/Platforms/Internal/Utility.cs b/com.unity.shaderanalysis/Editor/Platforms/Internal/Utility.cs index 3bc9285dbd1..f2d40e9f4bd 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/Internal/Utility.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/Internal/Utility.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using UnityEditor.ShaderAnalysis.Internal; diff --git a/com.unity.shaderanalysis/Editor/Platforms/ProgressWrapper.cs b/com.unity.shaderanalysis/Editor/Platforms/ProgressWrapper.cs index f9de5eb0996..582f343578d 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/ProgressWrapper.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/ProgressWrapper.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderAnalysis { @@ -39,7 +39,7 @@ public void SetProgressRange(float start, float end) /// /// Send the progress to the job in the provided range. - /// + /// /// Example: /// if the range is [0.5..0.75], /// then setting the progress to 0.5 will actually set in the job the progress value of 0.625. diff --git a/com.unity.shaderanalysis/Editor/Platforms/ReportBuildData.cs b/com.unity.shaderanalysis/Editor/Platforms/ReportBuildData.cs index d53e3b8c348..2b69fe3af37 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/ReportBuildData.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/ReportBuildData.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -173,7 +173,7 @@ protected IEnumerator CompileCompileUnits_Internal(ShaderCompiler compiler) // Try to enqueue jobs while (m_CompileJobMap.Count < k_MaxParallelCompilation && compileUnitToProcess.Count > 0) { - var (unit, unitIndex) = compileUnitToProcess[0]; + var(unit, unitIndex) = compileUnitToProcess[0]; compileUnitToProcess.RemoveAt(0); var job = compiler.Compile(unit.sourceCodeFile, temporaryDirectory, unit.compiledFile, unit.compileOptions, unit.compileProfile, unit.compileTarget); if (logCommandLine) diff --git a/com.unity.shaderanalysis/Editor/Platforms/ShaderCompiler.cs b/com.unity.shaderanalysis/Editor/Platforms/ShaderCompiler.cs index ec52b4b2de8..4d107a4c219 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/ShaderCompiler.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/ShaderCompiler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.IO; using System.Text; @@ -128,7 +128,7 @@ void ProcessOnExited(object sender, EventArgs eventArgs) } /// Initialize the compiler. - public virtual void Initialize() { } + public virtual void Initialize() {} /// Start a compile operation. /// Path of the file to compile. diff --git a/com.unity.shaderanalysis/Editor/Platforms/ShaderReportBuildData.cs b/com.unity.shaderanalysis/Editor/Platforms/ShaderReportBuildData.cs index 266bcfadcf2..9dd0f363653 100644 --- a/com.unity.shaderanalysis/Editor/Platforms/ShaderReportBuildData.cs +++ b/com.unity.shaderanalysis/Editor/Platforms/ShaderReportBuildData.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -84,7 +84,7 @@ public void BuildPassesData() { var passData = activeSubshader.GetPass(i); if (filter != null && (filter.includedPassNames.Count > 0 && !filter.includedPassNames.Contains(passData.Name) - || filter.excludedPassNames.Contains(passData.Name))) + || filter.excludedPassNames.Contains(passData.Name))) { m_SkippedPassesFromFilter.Add(i); continue; diff --git a/com.unity.shaderanalysis/Tests/Editor/EditMode/SymbolicLinkUtilitiesTests.cs b/com.unity.shaderanalysis/Tests/Editor/EditMode/SymbolicLinkUtilitiesTests.cs index e1e7f839c40..db2348be178 100644 --- a/com.unity.shaderanalysis/Tests/Editor/EditMode/SymbolicLinkUtilitiesTests.cs +++ b/com.unity.shaderanalysis/Tests/Editor/EditMode/SymbolicLinkUtilitiesTests.cs @@ -1,4 +1,4 @@ -using NUnit.Framework; +using NUnit.Framework; using System.Diagnostics; using System.IO; using UnityEditor.ShaderAnalysis.Internal; diff --git a/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs b/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs index 9a491707b5a..84fd6ad5134 100644 --- a/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs +++ b/com.unity.shadergraph/Editor/AssetCallbacks/CreateVFXShaderGraph.cs @@ -10,13 +10,13 @@ public static void CreateVFXGraph() { var target = (VFXTarget)Activator.CreateInstance(typeof(VFXTarget)); - var blockDescriptors = new [] - { + var blockDescriptors = new[] + { BlockFields.SurfaceDescription.BaseColor, BlockFields.SurfaceDescription.Alpha, }; - GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors); } } } diff --git a/com.unity.shadergraph/Editor/Data/Attributes/InspectableAttribute.cs b/com.unity.shadergraph/Editor/Data/Attributes/InspectableAttribute.cs index f70d75ebce3..23d7af8630b 100644 --- a/com.unity.shadergraph/Editor/Data/Attributes/InspectableAttribute.cs +++ b/com.unity.shadergraph/Editor/Data/Attributes/InspectableAttribute.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderGraph.Drawing { diff --git a/com.unity.shadergraph/Editor/Data/Attributes/SGPropertyDrawerAttribute.cs b/com.unity.shadergraph/Editor/Data/Attributes/SGPropertyDrawerAttribute.cs index 3b94e243260..ddef623d5fc 100644 --- a/com.unity.shadergraph/Editor/Data/Attributes/SGPropertyDrawerAttribute.cs +++ b/com.unity.shadergraph/Editor/Data/Attributes/SGPropertyDrawerAttribute.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace UnityEditor.ShaderGraph.Drawing { diff --git a/com.unity.shadergraph/Editor/Data/ContextData.cs b/com.unity.shadergraph/Editor/Data/ContextData.cs index 3b2ee039224..7b20326bd08 100644 --- a/com.unity.shadergraph/Editor/Data/ContextData.cs +++ b/com.unity.shadergraph/Editor/Data/ContextData.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEngine; using UnityEditor.Graphing; diff --git a/com.unity.shadergraph/Editor/Data/Graphs/AbstractShaderProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/AbstractShaderProperty.cs index 4f93cca6e30..d7a3e9b23de 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/AbstractShaderProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/AbstractShaderProperty.cs @@ -19,7 +19,7 @@ public abstract class AbstractShaderProperty : ShaderInput public bool gpuInstanced { get { return false; } - set { } + set {} } // NOTE: this does not tell you the HLSLDeclaration of the entire property... @@ -101,11 +101,11 @@ internal virtual void AppendPropertyBlockStrings(ShaderStringBuilder builder) public virtual string GetPropertyTypeString() { - string depString = $" (Deprecated{(ShaderGraphPreferences.allowDeprecatedBehaviors ? " V" + sgVersion : "" )})" ; + string depString = $" (Deprecated{(ShaderGraphPreferences.allowDeprecatedBehaviors ? " V" + sgVersion : "" )})"; return propertyType.ToString() + (sgVersion < latestVersion ? depString : ""); } } - + [Serializable] public abstract class AbstractShaderProperty : AbstractShaderProperty { @@ -199,20 +199,20 @@ public HLSLProperty(HLSLType type, string name, HLSLDeclaration declaration, Con static string[,] kValueTypeStrings = new string[(int)HLSLType.FirstObjectType, 2] { - {"float", "half"}, - {"float2", "half2"}, - {"float3", "half3"}, - {"float4", "half4"}, - {"float4x4", "half4x4"} + {"float", "half"}, + {"float2", "half2"}, + {"float3", "half3"}, + {"float4", "half4"}, + {"float4x4", "half4x4"} }; static string[] kObjectTypeStrings = new string[(int)HLSLType._CUSTOM - (int)HLSLType.FirstObjectType] { - "TEXTURE2D", - "TEXTURE3D", - "TEXTURECUBE", - "TEXTURE2D_ARRAY", - "SAMPLER", + "TEXTURE2D", + "TEXTURE3D", + "TEXTURECUBE", + "TEXTURE2D_ARRAY", + "SAMPLER", }; public string GetValueTypeString() diff --git a/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs index 85578e0fb45..0bdb479985a 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/BooleanMaterialSlot.cs @@ -101,6 +101,5 @@ public override void CopyDefaultValue(MaterialSlot other) m_DefaultValue = ms.defaultValue; } } - } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/ColorShaderProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/ColorShaderProperty.cs index 617a2a6ccae..030f7331158 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/ColorShaderProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/ColorShaderProperty.cs @@ -26,12 +26,12 @@ internal ColorShaderProperty(int version) : this() { this.sgVersion = version; } - + public override PropertyType propertyType => PropertyType.Color; - + internal override bool isExposable => true; internal override bool isRenamable => true; - + internal string hdrTagString => colorMode == ColorMode.HDR ? "[HDR]" : ""; internal override string GetPropertyBlockString() @@ -54,7 +54,7 @@ public override string GetDefaultReferenceName() { return $"Color_{objectId}"; } - + [SerializeField] ColorMode m_ColorMode; @@ -88,8 +88,7 @@ internal override PreviewProperty GetPreviewMaterialProperty() name = referenceName, vector4Value = propColor }; - - } + } internal override ShaderInput Copy() { diff --git a/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs index b19cca41d00..a72c679ecda 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs @@ -141,6 +141,5 @@ public override void CopyDefaultValue(MaterialSlot other) m_DefaultValue = ms.defaultValue; } } - } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GraphConcretization.cs b/com.unity.shadergraph/Editor/Data/Graphs/GraphConcretization.cs index b7528a80e69..96ff391cca0 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GraphConcretization.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GraphConcretization.cs @@ -11,12 +11,14 @@ public static void ConcretizeNode(AbstractMaterialNode node) { node.Concretize(); } + public static void ConcretizeProperties(GraphData graph) { var propertyNodes = graph.GetNodes().Where(n => !graph.m_Properties.Any(p => p == n.property)).ToArray(); foreach (var pNode in propertyNodes) graph.ReplacePropertyNodeWithConcreteNodeNoValidate(pNode); } + public static void ConcretizeGraph(GraphData graph) { ConcretizeProperties(graph); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs b/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs index 67dfcce7910..b7935c169ea 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GraphData.cs @@ -24,7 +24,6 @@ namespace UnityEditor.ShaderGraph [FormerName("UnityEditor.ShaderGraph.AbstractMaterialGraph")] sealed partial class GraphData : JsonObject { - public override int latestVersion => 2; public GraphObject owner { get; set; } @@ -266,7 +265,7 @@ public string path if (m_Path == value) return; m_Path = value; - if(owner != null) + if (owner != null) owner.RegisterCompleteObjectUndo("Change Path"); } } @@ -320,7 +319,7 @@ public PotentialTarget(Target target) if (target is MultiJsonInternal.UnknownTargetType) { - m_UnknownTarget = (MultiJsonInternal.UnknownTargetType) target; + m_UnknownTarget = (MultiJsonInternal.UnknownTargetType)target; m_KnownType = null; } else @@ -490,9 +489,9 @@ public void InitializeOutputs(Target[] targets, BlockFieldDescriptor[] blockDesc } SortActiveTargets(); - if(blockDescriptors != null) + if (blockDescriptors != null) { - foreach(var descriptor in blockDescriptors) + foreach (var descriptor in blockDescriptors) { var contextData = descriptor.shaderStage == ShaderStage.Fragment ? m_FragmentContext : m_VertexContext; var block = (BlockNode)Activator.CreateInstance(typeof(BlockNode)); @@ -540,12 +539,12 @@ void AddKnownTargetsToPotentialTargets() var targetTypes = TypeCache.GetTypesDerivedFrom(); foreach (var type in targetTypes) { - if(type.IsAbstract || type.IsGenericType || !type.IsClass) + if (type.IsAbstract || type.IsGenericType || !type.IsClass) continue; // create a new instance of the Target, to represent the potential Target // NOTE: this instance may be replaced later if we serialize in an Active Target of that type - var target = (Target) Activator.CreateInstance(type); + var target = (Target)Activator.CreateInstance(type); if (!target.isHidden) { m_AllPotentialTargets.Add(new PotentialTarget(target)); @@ -595,7 +594,7 @@ public void AddNode(AbstractMaterialNode node) // If adding a Sub Graph node whose asset contains Keywords // Need to restest Keywords against the variant limit - if(node is SubGraphNode subGraphNode && + if (node is SubGraphNode subGraphNode && subGraphNode.asset != null && subGraphNode.asset.keywords.Any()) { @@ -740,7 +739,7 @@ void AddBlockNoValidate(BlockNode blockNode, ContextData contextData, int index) blockNode.contextData = contextData; // Add to ContextData - if(index == -1 || index >= contextData.blocks.Count()) + if (index == -1 || index >= contextData.blocks.Count()) { contextData.blocks.Add(blockNode); } @@ -755,7 +754,7 @@ public List GetActiveBlocksForAllActiveTargets() // Get list of active Block types var currentBlocks = GetNodes(); var context = new TargetActiveBlockContext(currentBlocks.Select(x => x.descriptor).ToList(), null); - foreach(var target in activeTargets) + foreach (var target in activeTargets) { target.GetActiveBlocks(ref context); } @@ -767,7 +766,7 @@ public void UpdateActiveBlocks(List activeBlockDescriptors { // Set Blocks as active based on supported Block list //Note: we never want unknown blocks to be active, so explicitly set them to inactive always - foreach(var vertexBlock in vertexContext.blocks) + foreach (var vertexBlock in vertexContext.blocks) { if (vertexBlock.value?.descriptor?.isUnknown == true) { @@ -776,10 +775,10 @@ public void UpdateActiveBlocks(List activeBlockDescriptors else { vertexBlock.value.SetOverrideActiveState(activeBlockDescriptors.Contains(vertexBlock.value.descriptor) ? AbstractMaterialNode.ActiveState.ExplicitActive - : AbstractMaterialNode.ActiveState.ExplicitInactive); + : AbstractMaterialNode.ActiveState.ExplicitInactive); } } - foreach(var fragmentBlock in fragmentContext.blocks) + foreach (var fragmentBlock in fragmentContext.blocks) { if (fragmentBlock.value?.descriptor?.isUnknown == true) { @@ -788,7 +787,7 @@ public void UpdateActiveBlocks(List activeBlockDescriptors else { fragmentBlock.value.SetOverrideActiveState(activeBlockDescriptors.Contains(fragmentBlock.value.descriptor) ? AbstractMaterialNode.ActiveState.ExplicitActive - : AbstractMaterialNode.ActiveState.ExplicitInactive); + : AbstractMaterialNode.ActiveState.ExplicitInactive); } } } @@ -799,14 +798,14 @@ public void AddRemoveBlocksFromActiveList(List activeBlock void GetBlocksToRemoveForContext(ContextData contextData) { - for(int i = 0; i < contextData.blocks.Count; i++) + for (int i = 0; i < contextData.blocks.Count; i++) { var block = contextData.blocks[i]; - if(!activeBlockDescriptors.Contains(block.value.descriptor)) + if (!activeBlockDescriptors.Contains(block.value.descriptor)) { var slot = block.value.FindSlot(0); //Need to check if a slot is not default value OR is an untracked unknown block type - if(slot.IsUsingDefaultValue() || block.value.descriptor.isUnknown) // TODO: How to check default value + if (slot.IsUsingDefaultValue() || block.value.descriptor.isUnknown) // TODO: How to check default value { blocksToRemove.Add(block); } @@ -816,10 +815,10 @@ void GetBlocksToRemoveForContext(ContextData contextData) void TryAddBlockToContext(BlockFieldDescriptor descriptor, ContextData contextData) { - if(descriptor.shaderStage != contextData.shaderStage) + if (descriptor.shaderStage != contextData.shaderStage) return; - if(contextData.blocks.Any(x => x.value.descriptor.Equals(descriptor))) + if (contextData.blocks.Any(x => x.value.descriptor.Equals(descriptor))) return; var node = (BlockNode)Activator.CreateInstance(typeof(BlockNode)); @@ -832,13 +831,13 @@ void TryAddBlockToContext(BlockFieldDescriptor descriptor, ContextData contextDa GetBlocksToRemoveForContext(fragmentContext); // Remove blocks - foreach(var block in blocksToRemove) + foreach (var block in blocksToRemove) { RemoveNodeNoValidate(block); } // Add active Blocks not currently in Contexts - foreach(var descriptor in activeBlockDescriptors) + foreach (var descriptor in activeBlockDescriptors) { TryAddBlockToContext(descriptor, vertexContext); TryAddBlockToContext(descriptor, fragmentContext); @@ -847,7 +846,7 @@ void TryAddBlockToContext(BlockFieldDescriptor descriptor, ContextData contextDa void AddNodeNoValidate(AbstractMaterialNode node) { - if (node.group !=null && !m_GroupItems.ContainsKey(node.group)) + if (node.group != null && !m_GroupItems.ContainsKey(node.group)) { throw new InvalidOperationException("Cannot add a node whose group doesn't exist."); } @@ -867,7 +866,7 @@ public void RemoveNode(AbstractMaterialNode node) RemoveNodeNoValidate(node); ValidateGraph(); - if(node is BlockNode blockNode) + if (node is BlockNode blockNode) { var activeBlocks = GetActiveBlocksForAllActiveTargets(); UpdateActiveBlocks(activeBlocks); @@ -892,7 +891,7 @@ void RemoveNodeNoValidate(AbstractMaterialNode node) groupItems.Remove(node); } - if(node is BlockNode blockNode && blockNode.contextData != null) + if (node is BlockNode blockNode && blockNode.contextData != null) { // Remove from ContextData blockNode.contextData.blocks.Remove(blockNode); @@ -1023,7 +1022,7 @@ public void RemoveElements(AbstractMaterialNode[] nodes, IEdge[] edges, GroupDat ValidateGraph(); - if(nodes.Any(x => x is BlockNode)) + if (nodes.Any(x => x is BlockNode)) { var activeBlocks = GetActiveBlocksForAllActiveTargets(); UpdateActiveBlocks(activeBlocks); @@ -1039,7 +1038,7 @@ void RemoveEdgeNoValidate(IEdge e, bool reevaluateActivity = true) BlockNode b = null; AbstractMaterialNode input = e.inputSlot.node, output = e.outputSlot.node; - if(input != null && ShaderGraphPreferences.autoAddRemoveBlocks) + if (input != null && ShaderGraphPreferences.autoAddRemoveBlocks) { b = input as BlockNode; } @@ -1053,13 +1052,13 @@ void RemoveEdgeNoValidate(IEdge e, bool reevaluateActivity = true) outputNodeEdges.Remove(e); m_RemovedEdges.Add(e); - if(b != null) + if (b != null) { var activeBlockDescriptors = GetActiveBlocksForAllActiveTargets(); - if(!activeBlockDescriptors.Contains(b.descriptor)) + if (!activeBlockDescriptors.Contains(b.descriptor)) { var slot = b.FindSlot(0); - if(slot.IsUsingDefaultValue()) // TODO: How to check default value + if (slot.IsUsingDefaultValue()) // TODO: How to check default value { RemoveNodeNoValidate(b); input = null; @@ -1079,7 +1078,6 @@ void RemoveEdgeNoValidate(IEdge e, bool reevaluateActivity = true) NodeUtils.ReevaluateActivityOfConnectedNodes(output); } } - } public AbstractMaterialNode GetNodeFromId(string nodeId) @@ -1096,7 +1094,7 @@ public T GetNodeFromId(string nodeId) where T : class public bool ContainsNode(AbstractMaterialNode node) { - if(node == null) + if (node == null) return false; return m_NodeDictionary.TryGetValue(node.objectId, out var foundNode) && node == foundNode; @@ -1136,7 +1134,7 @@ public void CollectShaderProperties(PropertyCollector collector, GenerationMode foreach (var prop in properties) { // ugh, this needs to be moved to the gradient property implementation - if(prop is GradientShaderProperty gradientProp && generationMode == GenerationMode.Preview) + if (prop is GradientShaderProperty gradientProp && generationMode == GenerationMode.Preview) { GradientUtil.GetGradientPropertiesForPreview(collector, gradientProp.referenceName, gradientProp.value); continue; @@ -1162,7 +1160,7 @@ public void AddGraphInput(ShaderInput input, int index = -1) if (input == null) return; - switch(input) + switch (input) { case AbstractShaderProperty property: if (m_Properties.Contains(property)) @@ -1213,7 +1211,7 @@ public List BuildPropertyDisplayNameList(AbstractShaderProperty ignorePr } } } - + return result; } @@ -1271,7 +1269,7 @@ public void SanitizeGraphInputReferenceName(ShaderInput input, string newName) name = "_" + name; name = Regex.Replace(name, @"(?:[^A-Za-z_0-9])|(?:\s)", "_"); - switch(input) + switch (input) { case AbstractShaderProperty property: property.overrideReferenceName = GraphUtil.SanitizeName(properties.Where(p => p != property).Select(p => p.referenceName), "{0}_{1}", name); @@ -1286,7 +1284,7 @@ public void SanitizeGraphInputReferenceName(ShaderInput input, string newName) public void RemoveGraphInput(ShaderInput input) { - switch(input) + switch (input) { case AbstractShaderProperty property: var propertyNodes = GetNodes().Where(x => x.property == input).ToList(); @@ -1343,7 +1341,7 @@ public void MoveKeyword(ShaderKeyword keyword, int newIndex) public int GetGraphInputIndex(ShaderInput input) { - switch(input) + switch (input) { case AbstractShaderProperty property: return m_Properties.IndexOf(property); @@ -1381,7 +1379,7 @@ void ReplacePropertyNodeWithConcreteNodeNoValidate(PropertyNode propertyNode, bo var node = property.ToConcreteNode() as AbstractMaterialNode; if (node == null) // Some nodes have no concrete form - { + { if (deleteNodeIfNoConcreteFormExists) RemoveNodeNoValidate(propertyNode); return; @@ -1411,7 +1409,7 @@ public void OnKeywordChanged() public void OnKeywordChangedNoValidate() { var allNodes = GetNodes(); - foreach(AbstractMaterialNode node in allNodes) + foreach (AbstractMaterialNode node in allNodes) { node.Dirty(ModificationScope.Topological); node.ValidateNode(); @@ -1590,7 +1588,7 @@ public void ReplaceWith(GraphData other) foreach (var node in other.GetNodes()) { - if(node is BlockNode blockNode) + if (node is BlockNode blockNode) { var contextData = blockNode.descriptor.shaderStage == ShaderStage.Vertex ? vertexContext : fragmentContext; AddBlockNoValidate(blockNode, contextData, blockNode.index); @@ -1680,8 +1678,8 @@ internal void PasteGraph(CopyPasteGraph graphToPaste, List // If the property is not in the current graph, do check if the // property can be made into a concrete node. var property = m_Properties.SelectValue().FirstOrDefault(x => x.objectId == propertyNode.property.objectId - || (x.propertyType == propertyNode.property.propertyType && x.referenceName == propertyNode.property.referenceName)); - if(property != null) + || (x.propertyType == propertyNode.property.propertyType && x.referenceName == propertyNode.property.referenceName)); + if (property != null) { propertyNode.property = property; } @@ -1733,7 +1731,7 @@ internal void PasteGraph(CopyPasteGraph graphToPaste, List if (node is KeywordNode keywordNode) { var keyword = m_Keywords.SelectValue().FirstOrDefault(x => x.objectId == keywordNode.keyword.objectId - || (x.keywordType == keywordNode.keyword.keywordType && x.referenceName == keywordNode.keyword.referenceName)); + || (x.keywordType == keywordNode.keyword.keywordType && x.referenceName == keywordNode.keyword.referenceName)); if (keyword != null) { keywordNode.keyword = keyword; @@ -1794,7 +1792,7 @@ static AbstractMaterialNode DeserializeLegacyNode(string typeString, string json var value = jsonObj as AbstractMaterialNode; if (value == null) { - //Special case - want to support nodes of unknwon type for cross pipeline compatability + //Special case - want to support nodes of unknwon type for cross pipeline compatability value = new LegacyUnknownTypeNode(typeString, json); if (overrideObjectId.HasValue) value.OverrideObjectId(overrideObjectId.Value.ToString("N")); @@ -1808,17 +1806,15 @@ static AbstractMaterialNode DeserializeLegacyNode(string typeString, string json MultiJsonInternal.Enqueue(value, json); return value as AbstractMaterialNode; } - } public override void OnAfterDeserialize(string json) { - if (sgVersion == 0) { var graphData0 = JsonUtility.FromJson(json); //If a graph was previously updated to V2, since we had to rename m_Version to m_SGVersion to avoid collision with an upgrade system from - //HDRP, we have to handle the case that our version might not be correct - + //HDRP, we have to handle the case that our version might not be correct - if (graphData0.m_Version > 0) { sgVersion = graphData0.m_Version; @@ -1996,7 +1992,7 @@ public override void OnAfterDeserialize(string json) // This is because we need access to m_OutputNode to convert it to Targets and Stacks // The JsonObject will not be fully deserialized until OnAfterMultiDeserialize bool deferredUpgrades = sgVersion < 2; - if(!deferredUpgrades) + if (!deferredUpgrades) { ChangeVersion(latestVersion); } @@ -2005,22 +2001,22 @@ public override void OnAfterDeserialize(string json) public override void OnAfterMultiDeserialize(string json) { // Deferred upgrades - if(sgVersion != latestVersion) + if (sgVersion != latestVersion) { - if(sgVersion < 2) + if (sgVersion < 2) { var addedBlocks = ListPool.Get(); void UpgradeFromBlockMap(Dictionary blockMap) { // Map master node ports to blocks - if(blockMap != null) + if (blockMap != null) { - foreach(var blockMapping in blockMap) + foreach (var blockMapping in blockMap) { // Create a new BlockNode for each unique map entry var descriptor = blockMapping.Key; - if(addedBlocks.Contains(descriptor)) + if (addedBlocks.Contains(descriptor)) continue; addedBlocks.Add(descriptor); @@ -2038,7 +2034,7 @@ void UpgradeFromBlockMap(Dictionary blockMap) var slotId = blockMapping.Value; var oldSlot = m_OutputNode.value.FindSlot(slotId); var newSlot = block.FindSlot(0); - if(oldSlot == null) + if (oldSlot == null) continue; var oldInputSlotRef = m_OutputNode.value.GetSlotReference(slotId); @@ -2047,12 +2043,12 @@ void UpgradeFromBlockMap(Dictionary blockMap) // Always copy the value over for convenience newSlot.CopyValuesFrom(oldSlot); - for(int i = 0; i < m_Edges.Count; i++) + for (int i = 0; i < m_Edges.Count; i++) { // Find all edges connected to the master node using slot ID from the block map // Remove them and replace them with new edges connected to the block nodes var edge = m_Edges[i]; - if(edge.inputSlot.Equals(oldInputSlotRef)) + if (edge.inputSlot.Equals(oldInputSlotRef)) { var outputSlot = edge.outputSlot; m_Edges.Remove(edge); @@ -2114,13 +2110,13 @@ void UpgradeFromBlockMap(Dictionary blockMap) } // Clean up after upgrade - if(!isSubGraph) + if (!isSubGraph) { m_OutputNode = null; } var masterNodes = GetNodes().ToArray(); - for(int i = 0; i < masterNodes.Length; i++) + for (int i = 0; i < masterNodes.Length; i++) { var node = masterNodes.ElementAt(i) as AbstractMaterialNode; m_Nodes.Remove(node); @@ -2132,10 +2128,10 @@ void UpgradeFromBlockMap(Dictionary blockMap) ChangeVersion(latestVersion); } - PooledList<(LegacyUnknownTypeNode, AbstractMaterialNode)> updatedNodes = PooledList<(LegacyUnknownTypeNode,AbstractMaterialNode)>.Get(); - foreach(var node in m_Nodes.SelectValue()) + PooledList<(LegacyUnknownTypeNode, AbstractMaterialNode)> updatedNodes = PooledList<(LegacyUnknownTypeNode, AbstractMaterialNode)>.Get(); + foreach (var node in m_Nodes.SelectValue()) { - if(node is LegacyUnknownTypeNode lNode && lNode.foundType != null) + if (node is LegacyUnknownTypeNode lNode && lNode.foundType != null) { AbstractMaterialNode legacyNode = (AbstractMaterialNode)Activator.CreateInstance(lNode.foundType); JsonUtility.FromJsonOverwrite(lNode.serializedData, legacyNode); @@ -2143,7 +2139,7 @@ void UpgradeFromBlockMap(Dictionary blockMap) updatedNodes.Add((lNode, legacyNode)); } } - foreach(var nodePair in updatedNodes) + foreach (var nodePair in updatedNodes) { m_Nodes.Add(nodePair.Item2); ReplaceNodeWithNode(nodePair.Item1, nodePair.Item2); @@ -2199,22 +2195,22 @@ void DeserializeContextData(ContextData contextData, ShaderStage stage) var blocks = contextData.blocks.SelectValue().ToList(); var blockCount = blocks.Count; - for(int i = 0; i < blockCount; i++) + for (int i = 0; i < blockCount; i++) { // Update NonSerialized data on the BlockNode var block = blocks[i]; block.descriptor = m_BlockFieldDescriptors.FirstOrDefault(x => $"{x.tag}.{x.name}" == block.serializedDescriptor); - if(block.descriptor == null) + if (block.descriptor == null) { //Hit a descriptor that was not recognized from the assembly (likely from a different SRP) //create a new entry for it and continue on - if(string.IsNullOrEmpty(block.serializedDescriptor)) + if (string.IsNullOrEmpty(block.serializedDescriptor)) { throw new Exception($"Block {block} had no serialized descriptor"); } var tmp = block.serializedDescriptor.Split('.'); - if(tmp.Length != 2) + if (tmp.Length != 2) { throw new Exception($"Block {block}'s serialized descriptor {block.serializedDescriptor} did not match expected format {{x.tag}}.{{x.name}}"); } @@ -2259,13 +2255,13 @@ private void ReplaceNodeWithNode(LegacyUnknownTypeNode nodeToReplace, AbstractMa var newSlots = new List(); nodeReplacement.GetSlots(newSlots); - for(int i = 0; i < oldSlots.Count; i++) + for (int i = 0; i < oldSlots.Count; i++) { newSlots[i].CopyValuesFrom(oldSlots[i]); var oldSlotRef = nodeToReplace.GetSlotReference(oldSlots[i].id); var newSlotRef = nodeReplacement.GetSlotReference(newSlots[i].id); - for(int x = 0; x < m_Edges.Count; x++) + for (int x = 0; x < m_Edges.Count; x++) { var edge = m_Edges[x]; if (edge.inputSlot.Equals(oldSlotRef)) diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GraphSetup.cs b/com.unity.shadergraph/Editor/Data/Graphs/GraphSetup.cs index ca33133215a..b8884822693 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GraphSetup.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GraphSetup.cs @@ -4,8 +4,8 @@ namespace UnityEditor.ShaderGraph { sealed partial class GraphData : ISerializationCallbackReceiver { - public static class GraphSetup - { + public static class GraphSetup + { public static void SetupNode(AbstractMaterialNode node) { node.Setup(); @@ -15,6 +15,6 @@ public static void SetupGraph(GraphData graph) { GraphDataUtils.ApplyActionLeafFirst(graph, SetupNode); } - } + } } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs b/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs index e706949a38d..6caefbc8235 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GraphValidation.cs @@ -20,7 +20,7 @@ public static void ValidateNode(AbstractMaterialNode node) bool disallowedByAnyTargets = false; bool disallowedByAllTargets = true; IEnumerable targets = node.owner.activeTargets; - if(node.owner.isSubGraph) + if (node.owner.isSubGraph) { targets = node.owner.allPotentialTargets; } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/GroupData.cs b/com.unity.shadergraph/Editor/Data/Graphs/GroupData.cs index cb2b0d78013..55d2ba8f26f 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/GroupData.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/GroupData.cs @@ -5,14 +5,14 @@ namespace UnityEditor.ShaderGraph { [Serializable] - public class GroupData : JsonObject + public class GroupData : JsonObject { [SerializeField] string m_Title; public string title { - get{ return m_Title; } + get { return m_Title; } set { m_Title = value; } } @@ -21,18 +21,16 @@ public string title public Vector2 position { - get{ return m_Position; } + get { return m_Position; } set { m_Position = value; } } - public GroupData() : base() { } + public GroupData() : base() {} public GroupData(string title, Vector2 position) { m_Title = title; m_Position = position; } - } } - diff --git a/com.unity.shadergraph/Editor/Data/Graphs/LightmappingShaderProperties.cs b/com.unity.shadergraph/Editor/Data/Graphs/LightmappingShaderProperties.cs index 30df089b895..6a29d03f7e0 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/LightmappingShaderProperties.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/LightmappingShaderProperties.cs @@ -30,15 +30,15 @@ internal override string GetPropertyAsArgumentString() }; public static readonly LightmapTextureArrayProperty kLightmapsIndirectionArray = new LightmapTextureArrayProperty() - { - displayName = "unity_LightmapsInd", - generatePropertyBlock = true, - overrideHLSLDeclaration = false, - hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare, - hidden = true, - modifiable = true, - overrideReferenceName = "unity_LightmapsInd", - precision = Precision.Single + { + displayName = "unity_LightmapsInd", + generatePropertyBlock = true, + overrideHLSLDeclaration = false, + hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare, + hidden = true, + modifiable = true, + overrideReferenceName = "unity_LightmapsInd", + precision = Precision.Single }; public static readonly LightmapTextureArrayProperty kShadowMasksArray = new LightmapTextureArrayProperty() diff --git a/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs index f0f26e1ed83..a8730f1172d 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/MaterialSlot.cs @@ -251,8 +251,8 @@ public bool IsCompatibleWith(MaterialSlot otherSlot) && otherSlot.owner != owner && otherSlot.isInputSlot != isInputSlot && ((isInputSlot - ? SlotValueHelper.AreCompatible(valueType, otherSlot.concreteValueType) - : SlotValueHelper.AreCompatible(otherSlot.valueType, concreteValueType))); + ? SlotValueHelper.AreCompatible(valueType, otherSlot.concreteValueType) + : SlotValueHelper.AreCompatible(otherSlot.valueType, concreteValueType))); } public bool IsCompatibleStageWith(MaterialSlot otherSlot) diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs index 8a4880c537a..52c4d48d128 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Matrix2MaterialSlot.cs @@ -99,6 +99,5 @@ public override void CopyDefaultValue(MaterialSlot other) m_DefaultValue = ms.defaultValue; } } - } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Matrix4ShaderProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/Matrix4ShaderProperty.cs index fa87cd33cae..63e0eec8cfc 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Matrix4ShaderProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Matrix4ShaderProperty.cs @@ -14,7 +14,7 @@ public Matrix4ShaderProperty() displayName = "Matrix4x4"; value = Matrix4x4.identity; } - + public override PropertyType propertyType => PropertyType.Matrix4; internal override string GetPropertyAsArgumentString() diff --git a/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs b/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs index 9a5565f69ea..5b23af9434e 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/MinimalGraphData.cs @@ -71,7 +71,7 @@ public static bool GatherMinimalDependenciesFromFile(string assetPath, AssetColl entries.Add(new MultiJsonEntry(node.typeInfo.fullName, null, node.JSONnodeData)); AbstractMaterialNode0 amn = new AbstractMaterialNode0(); JsonUtility.FromJsonOverwrite(node.JSONnodeData, amn); - foreach(var slot in amn.m_SerializableSlots) + foreach (var slot in amn.m_SerializableSlots) { entries.Add(new MultiJsonEntry(slot.typeInfo.fullName, null, slot.JSONnodeData)); } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/ParentGroupChange.cs b/com.unity.shadergraph/Editor/Data/Graphs/ParentGroupChange.cs index aacdb62414d..8ab3cc68ff6 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/ParentGroupChange.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/ParentGroupChange.cs @@ -10,4 +10,3 @@ struct ParentGroupChange public GroupData newGroup; } } - diff --git a/com.unity.shadergraph/Editor/Data/Graphs/PreviewProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/PreviewProperty.cs index af843523b38..1c7a0da1ee6 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/PreviewProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/PreviewProperty.cs @@ -31,7 +31,6 @@ struct ClassData [StructLayout(LayoutKind.Explicit)] struct StructData { - [FieldOffset(0)] public Color colorValue; [FieldOffset(0)] diff --git a/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs index 75a559d8ef5..c18501761ac 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/SamplerStateMaterialSlot.cs @@ -33,7 +33,7 @@ public override string GetDefaultValue(GenerationMode generationMode) public override SlotValueType valueType { get { return SlotValueType.SamplerState; } } public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.SamplerState; } } public override bool isDefaultValue => true; - + public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode) { var matOwner = owner as AbstractMaterialNode; @@ -54,6 +54,5 @@ public override void AddDefaultProperty(PropertyCollector properties, Generation public override void CopyValuesFrom(MaterialSlot foundSlot) {} - } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/SerializableVirtualTexture.cs b/com.unity.shadergraph/Editor/Data/Graphs/SerializableVirtualTexture.cs index 4e03f002efe..d99c7231e5e 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/SerializableVirtualTexture.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/SerializableVirtualTexture.cs @@ -59,4 +59,3 @@ internal sealed class SerializableVirtualTexture public bool procedural; } } - diff --git a/com.unity.shadergraph/Editor/Data/Graphs/ShaderKeyword.cs b/com.unity.shadergraph/Editor/Data/Graphs/ShaderKeyword.cs index a4756b7a097..cb63022080f 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/ShaderKeyword.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/ShaderKeyword.cs @@ -22,7 +22,7 @@ public ShaderKeyword(KeywordType keywordType) this.keywordType = keywordType; // Add sensible default entries for Enum type - if(keywordType == KeywordType.Enum) + if (keywordType == KeywordType.Enum) { m_Entries = new List(); m_Entries.Add(new KeywordEntry(1, "A", "A")); @@ -33,11 +33,11 @@ public ShaderKeyword(KeywordType keywordType) public static ShaderKeyword CreateBuiltInKeyword(KeywordDescriptor descriptor) { - if(descriptor.entries != null) + if (descriptor.entries != null) { - for(int i = 0; i < descriptor.entries.Length; i++) + for (int i = 0; i < descriptor.entries.Length; i++) { - if(descriptor.entries[i].id == -1) + if (descriptor.entries[i].id == -1) descriptor.entries[i].id = i + 1; } } @@ -110,7 +110,7 @@ public bool isBuiltIn } internal override bool isExposable => !isBuiltIn - && (keywordType == KeywordType.Enum || referenceName.EndsWith("_ON")); + && (keywordType == KeywordType.Enum || referenceName.EndsWith("_ON")); internal override bool isRenamable => !isBuiltIn; @@ -120,7 +120,7 @@ public override string GetDefaultReferenceName() { // _ON suffix is required for exposing Boolean type to Material var suffix = string.Empty; - if(keywordType == KeywordType.Boolean) + if (keywordType == KeywordType.Boolean) { suffix = "_ON"; } @@ -130,14 +130,14 @@ public override string GetDefaultReferenceName() public string GetPropertyBlockString() { - switch(keywordType) + switch (keywordType) { case KeywordType.Enum: string enumTagString = $"[KeywordEnum({string.Join(", ", entries.Select(x => x.displayName))})]"; return $"{enumTagString}{referenceName}(\"{displayName}\", Float) = {value}"; case KeywordType.Boolean: // Reference name must be appended with _ON but must be removed when generating block - if(referenceName.EndsWith("_ON")) + if (referenceName.EndsWith("_ON")) return $"[Toggle]{referenceName.Remove(referenceName.Length - 3, 3)}(\"{displayName}\", Float) = {value}"; else return string.Empty; @@ -149,14 +149,14 @@ public string GetPropertyBlockString() public string GetKeywordDeclarationString() { // Predefined keywords do not need to be defined - if(keywordDefinition == KeywordDefinition.Predefined) + if (keywordDefinition == KeywordDefinition.Predefined) return string.Empty; // Get definition type using scope string scopeString = keywordScope == KeywordScope.Local ? "_local" : string.Empty; string definitionString = $"{keywordDefinition.ToDeclarationString()}{scopeString}"; - switch(keywordType) + switch (keywordType) { case KeywordType.Boolean: return $"#pragma {definitionString} _ {referenceName}"; @@ -171,7 +171,7 @@ public string GetKeywordDeclarationString() public string GetKeywordPreviewDeclarationString() { - switch(keywordType) + switch (keywordType) { case KeywordType.Boolean: return value == 1 ? $"#define {referenceName}" : string.Empty; diff --git a/com.unity.shadergraph/Editor/Data/Graphs/StickyNoteData.cs b/com.unity.shadergraph/Editor/Data/Graphs/StickyNoteData.cs index 52933ad8cdf..a05036e9c20 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/StickyNoteData.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/StickyNoteData.cs @@ -7,7 +7,6 @@ namespace UnityEditor.ShaderGraph [Serializable] class StickyNoteData : JsonObject, IGroupItem { - [SerializeField] string m_Title; @@ -76,7 +75,5 @@ public StickyNoteData(string title, string content, Rect position) m_Position = position; m_Content = content; } - } } - diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs index b730cec9dc3..c08dd1690e5 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Texture2DArrayMaterialSlot.cs @@ -28,6 +28,5 @@ public override void AddDefaultProperty(PropertyCollector properties, Generation public override void CopyValuesFrom(MaterialSlot foundSlot) {} - } } diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs index 2d848df759c..69588881abf 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector1MaterialSlot.cs @@ -109,6 +109,7 @@ public override void CopyValuesFrom(MaterialSlot foundSlot) if (slot != null) value = slot.value; } + public override void CopyDefaultValue(MaterialSlot other) { base.CopyDefaultValue(other); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector1ShaderProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector1ShaderProperty.cs index 4b94a0f6b76..2f9ca1af339 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector1ShaderProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector1ShaderProperty.cs @@ -17,9 +17,9 @@ internal Vector1ShaderProperty() { displayName = "Float"; } - + public override PropertyType propertyType => PropertyType.Float; - + internal override bool isExposable => true; internal override bool isRenamable => true; @@ -27,7 +27,7 @@ string enumTagString { get { - switch(enumType) + switch (enumType) { case EnumType.CSharpEnum: return $"[Enum({m_CSharpEnumType.ToString()})]"; @@ -49,7 +49,7 @@ internal override string GetPropertyBlockString() { string valueString = NodeUtils.FloatToShaderValueShaderLabSafe(value); - switch(floatType) + switch (floatType) { case FloatType.Slider: return $"{hideTagString}{referenceName}(\"{displayName}\", Range({NodeUtils.FloatToShaderValue(m_RangeValues.x)}, {NodeUtils.FloatToShaderValue(m_RangeValues.y)})) = {valueString}"; @@ -98,7 +98,7 @@ public EnumType enumType get => m_EnumType; set => m_EnumType = value; } - + Type m_CSharpEnumType; public Type cSharpEnumType @@ -108,7 +108,7 @@ public Type cSharpEnumType } List m_EnumNames = new List(); - + public List enumNames { get => m_EnumNames; @@ -122,7 +122,7 @@ public List enumValues get => m_EnumValues; set => m_EnumValues = value; } - + internal override AbstractMaterialNode ToConcreteNode() { switch (m_FloatType) diff --git a/com.unity.shadergraph/Editor/Data/Graphs/Vector4ShaderProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/Vector4ShaderProperty.cs index 004344337e7..766e53b2996 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/Vector4ShaderProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/Vector4ShaderProperty.cs @@ -13,9 +13,9 @@ internal Vector4ShaderProperty() { displayName = "Vector4"; } - + public override PropertyType propertyType => PropertyType.Vector4; - + internal override AbstractMaterialNode ToConcreteNode() { var node = new Vector4Node(); diff --git a/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureShaderProperty.cs b/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureShaderProperty.cs index 9d405d07cdd..4e74d8f8e79 100644 --- a/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureShaderProperty.cs +++ b/com.unity.shadergraph/Editor/Data/Graphs/VirtualTextureShaderProperty.cs @@ -37,6 +37,7 @@ internal override void GetPropertyReferenceNames(List result) result.Add(value.layers[layer].layerRefName); } } + internal override void GetPropertyDisplayNames(List result) { result.Add(displayName); diff --git a/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs b/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs index 90d4f41d3f8..ec7e534f54a 100644 --- a/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs +++ b/com.unity.shadergraph/Editor/Data/Implementation/NodeUtils.cs @@ -92,7 +92,7 @@ public static SlotReference DepthFirstCollectRedirectNodeFromNode(RedirectNodeDa // If this is a redirect node we continue to look for the top one if (inputNode is RedirectNodeData redirectNode) { - return DepthFirstCollectRedirectNodeFromNode( redirectNode ); + return DepthFirstCollectRedirectNodeFromNode(redirectNode); } return outputSlotRef; } @@ -115,7 +115,7 @@ public static void DepthFirstCollectNodesFromNode(List nod // If this node is a keyword node and we have an active keyword permutation // The only valid port id is the port that corresponds to that keywords value in the active permutation - if(node is KeywordNode keywordNode && keywordPermutation != null) + if (node is KeywordNode keywordNode && keywordPermutation != null) { var valueInPermutation = keywordPermutation.Where(x => x.Key == keywordNode.keyword).FirstOrDefault(); ids = new int[] { keywordNode.GetSlotIdForPermutation(valueInPermutation) }; @@ -171,20 +171,19 @@ private static bool ActiveLeafExists(AbstractMaterialNode node) } - List parentNodes = GetParentNodes(node); //at this point we know we are not explicitly set to a state, //so there is no reason to be inactive - if(parentNodes.Count == 0) + if (parentNodes.Count == 0) { return true; } bool output = false; - foreach(var parent in parentNodes) + foreach (var parent in parentNodes) { output |= ActiveLeafExists(parent); - if(output) + if (output) { break; } @@ -192,7 +191,6 @@ private static bool ActiveLeafExists(AbstractMaterialNode node) return output; } - private static List GetChildNodes(AbstractMaterialNode node) { List nodeList = new List(); @@ -242,7 +240,6 @@ private static bool ActiveRootExists(AbstractMaterialNode node) } } return output; - } private static void ActiveTreeExists(AbstractMaterialNode node, out bool activeLeaf, out bool activeRoot, out bool activeTree) @@ -267,18 +264,17 @@ public static void ReevaluateActivityOfConnectedNodes(AbstractMaterialNode node, public static void ReevaluateActivityOfNodeList(IEnumerable nodes, PooledHashSet changedNodes = null) { bool getChangedNodes = changedNodes != null; - foreach(AbstractMaterialNode n in nodes) + foreach (AbstractMaterialNode n in nodes) { if (n.activeState != AbstractMaterialNode.ActiveState.Implicit) continue; ActiveTreeExists(n, out _, out _, out bool at); - if(n.isActive != at && getChangedNodes) + if (n.isActive != at && getChangedNodes) { changedNodes.Add(n); } n.SetActive(at, false); } - } //Go to the leaves of the node, then get all trees with those leaves @@ -286,15 +282,15 @@ private static List GetForest(AbstractMaterialNode node) { List leaves = GetLeaves(node); List forrest = new List(); - foreach(var leaf in leaves) + foreach (var leaf in leaves) { - if(!forrest.Contains(leaf)) + if (!forrest.Contains(leaf)) { forrest.Add(leaf); } - foreach(var child in GetChildNodesRecursive(leaf)) + foreach (var child in GetChildNodesRecursive(leaf)) { - if(!forrest.Contains(child)) + if (!forrest.Contains(child)) { forrest.Add(child); } @@ -307,15 +303,15 @@ private static List GetChildNodesRecursive(AbstractMateria { List output = new List() { node }; List children = GetChildNodes(node); - foreach(var child in children) + foreach (var child in children) { - if(!output.Contains(child)) + if (!output.Contains(child)) { output.Add(child); } - foreach(var descendent in GetChildNodesRecursive(child)) + foreach (var descendent in GetChildNodesRecursive(child)) { - if(!output.Contains(descendent)) + if (!output.Contains(descendent)) { output.Add(descendent); } @@ -328,17 +324,17 @@ private static List GetLeaves(AbstractMaterialNode node) { List parents = GetParentNodes(node); List output = new List(); - if(parents.Count == 0) + if (parents.Count == 0) { output.Add(node); } else { - foreach(var parent in parents) + foreach (var parent in parents) { - foreach(var leaf in GetLeaves(parent)) + foreach (var leaf in GetLeaves(parent)) { - if(!output.Contains(leaf)) + if (!output.Contains(leaf)) { output.Add(leaf); } @@ -352,7 +348,7 @@ public static void GetDownsteamNodesForNode(List nodeList, { // no where to start if (node == null) - return; + return; // Recursively traverse downstream from the original node // Traverse down each edge and continue on any connected downstream nodes @@ -373,7 +369,7 @@ public static void GetDownsteamNodesForNode(List nodeList, } // No more nodes downstream from here - if(!hasDownstream) + if (!hasDownstream) nodeList.Add(node); } @@ -750,7 +746,6 @@ public static bool IsHLSLKeyword(string id) return isHLSLKeyword; } - public static string ConvertToValidHLSLIdentifier(string originalId) { // Converts " 1 var * q-30 ( 0 ) (1) " to "_1_var_q_30_0_1" diff --git a/com.unity.shadergraph/Editor/Data/Interfaces/IMayRequireVertexSkinning.cs b/com.unity.shadergraph/Editor/Data/Interfaces/IMayRequireVertexSkinning.cs index e5d98e7eca9..c32a8a315c2 100644 --- a/com.unity.shadergraph/Editor/Data/Interfaces/IMayRequireVertexSkinning.cs +++ b/com.unity.shadergraph/Editor/Data/Interfaces/IMayRequireVertexSkinning.cs @@ -1,4 +1,4 @@ -using UnityEditor.Graphing; +using UnityEditor.Graphing; namespace UnityEditor.ShaderGraph { diff --git a/com.unity.shadergraph/Editor/Data/Interfaces/IPropertyDrawer.cs b/com.unity.shadergraph/Editor/Data/Interfaces/IPropertyDrawer.cs index b333efbefb2..b43a4ab3ef1 100644 --- a/com.unity.shadergraph/Editor/Data/Interfaces/IPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Data/Interfaces/IPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEngine.UIElements; diff --git a/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs b/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs index b15906d0ff4..8556f6fb6f4 100644 --- a/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs +++ b/com.unity.shadergraph/Editor/Data/Legacy/ILegacyTarget.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace UnityEditor.ShaderGraph.Legacy { diff --git a/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs index e780021561b..b4ec9948662 100644 --- a/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs +++ b/com.unity.shadergraph/Editor/Data/Legacy/IMasterNode1.cs @@ -1,4 +1,4 @@ -namespace UnityEditor.ShaderGraph.Legacy +namespace UnityEditor.ShaderGraph.Legacy { public interface IMasterNode1 { diff --git a/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs index 7e5dcef55e2..cceea250907 100644 --- a/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs +++ b/com.unity.shadergraph/Editor/Data/Legacy/SpriteLitMasterNode1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEditor.Graphing; diff --git a/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs index bb6bfe9daf7..62d09141f5c 100644 --- a/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs +++ b/com.unity.shadergraph/Editor/Data/Legacy/SpriteUnlitMasterNode1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEditor.Graphing; diff --git a/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs b/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs index c27d84718a8..9d255bb926a 100644 --- a/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs +++ b/com.unity.shadergraph/Editor/Data/Legacy/VisualEffectMasterNode1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UnityEditor.Graphing; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs index 8a9e4ad92ab..41d94621583 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/AbstractMaterialNode.cs @@ -185,7 +185,7 @@ public ActiveState activeState public void SetOverrideActiveState(ActiveState overrideState, bool updateConnections = true) { - if(m_ActiveState == overrideState) + if (m_ActiveState == overrideState) { return; } @@ -200,7 +200,7 @@ public void SetOverrideActiveState(ActiveState overrideState, bool updateConnect } break; case ActiveState.ExplicitInactive: - if(m_IsActive == false) + if (m_IsActive == false) { break; } @@ -215,7 +215,7 @@ public void SetOverrideActiveState(ActiveState overrideState, bool updateConnect break; } case ActiveState.ExplicitActive: - if(m_IsActive == true) + if (m_IsActive == true) { break; } @@ -237,7 +237,7 @@ public void SetActive(bool value, bool updateConnections = true) if (m_IsActive == value) return; - if(m_ActiveState != ActiveState.Implicit) + if (m_ActiveState != ActiveState.Implicit) { Debug.LogError($"Cannot set IsActive on Node {this} when value is explicitly overriden by ActiveState {m_ActiveState}"); return; @@ -251,16 +251,14 @@ public void SetActive(bool value, bool updateConnections = true) { NodeUtils.ReevaluateActivityOfConnectedNodes(this); } - } - public virtual bool isValid { get { return m_IsValid; } set { - if(m_IsValid == value) + if (m_IsValid == value) return; m_IsValid = value; @@ -268,7 +266,6 @@ public virtual bool isValid } - string m_DefaultVariableName; string m_NameForDefaultVariableName; @@ -304,6 +301,7 @@ public void SetColor(string provider, Color color) { m_CustomColors.Set(provider, color); } + #endregion protected AbstractMaterialNode() @@ -424,10 +422,10 @@ protected internal virtual string GetOutputForSlot(SlotReference fromSocketRef, if (slot == null) return string.Empty; - if (fromSocketRef.node.isActive) - return GenerationUtils.AdaptNodeOutput(this, slot.id, valueType); - else - return slot.GetDefaultValue(generationMode); + if (fromSocketRef.node.isActive) + return GenerationUtils.AdaptNodeOutput(this, slot.id, valueType); + else + return slot.GetDefaultValue(generationMode); } public AbstractMaterialNode GetInputNodeFromSlot(int inputSlotId) @@ -452,7 +450,7 @@ public static ConcreteSlotValueType ConvertDynamicVectorInputTypeToConcrete(IEnu case 0: return ConcreteSlotValueType.Vector1; case 1: - if(SlotValueHelper.AreCompatible(SlotValueType.DynamicVector, inputTypesDistinct.First())) + if (SlotValueHelper.AreCompatible(SlotValueType.DynamicVector, inputTypesDistinct.First())) return inputTypesDistinct.First(); break; default: @@ -498,7 +496,7 @@ public virtual void EvaluateConcretePrecision() } // Get inputs - using(var tempSlots = PooledList.Get()) + using (var tempSlots = PooledList.Get()) { GetInputSlots(tempSlots); @@ -615,7 +613,7 @@ public virtual void EvaluateDynamicMaterialSlots() tempSlots.Clear(); GetInputSlots(tempSlots); bool inputError = tempSlots.Any(x => x.hasError); - if(inputError) + if (inputError) { owner.AddConcretizationError(objectId, string.Format("Node {0} had input error", objectId)); hasError = true; @@ -652,7 +650,7 @@ public virtual void EvaluateDynamicMaterialSlots() tempSlots.Clear(); GetOutputSlots(tempSlots); - if(tempSlots.Any(x => x.hasError)) + if (tempSlots.Any(x => x.hasError)) { owner.AddConcretizationError(objectId, string.Format("Node {0} had output error", objectId)); hasError = true; @@ -677,7 +675,6 @@ public virtual void Concretize() public virtual void ValidateNode() { - } public virtual bool canCutNode => true; @@ -744,7 +741,7 @@ public virtual string GetVariableNameForNode() public MaterialSlot AddSlot(MaterialSlot slot, bool attemptToModifyExistingInstance = true) { - if(slot == null) + if (slot == null) { throw new ArgumentException($"Trying to add null slot to node {this}"); } @@ -912,7 +909,7 @@ public virtual void Setup() {} protected void EnqueSlotsForSerialization() { - foreach(var slot in m_Slots) + foreach (var slot in m_Slots) { slot.OnBeforeSerialize(); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs index 39e5e859cee..d1552983044 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs @@ -136,17 +136,17 @@ public override void CollectShaderProperties(PropertyCollector properties, Gener public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0} ({1} In, $precision3 Red, $precision3 Green, $precision3 Blue, out {2} Out)", + GetFunctionName(), + FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0} ({1} In, $precision3 Red, $precision3 Green, $precision3 Blue, out {2} Out)", - GetFunctionName(), - FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + s.AppendLine("Out = {0}(dot(In, Red), dot(In, Green), dot(In, Blue));", FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) - { - s.AppendLine("Out = {0}(dot(In, Red), dot(In, Green), dot(In, Blue));", - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - } - }); + } + }); } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ContrastNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ContrastNode.cs index d49b2a18350..005d321dfd2 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ContrastNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ContrastNode.cs @@ -23,7 +23,7 @@ static string Unity_Contrast( { Out = Vector2.zero; return - @" +@" { $precision midpoint = pow(0.5, 2.2); Out = (In - midpoint) * Contrast + midpoint; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/HueNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/HueNode.cs index 871b840a2b0..cb7535e6172 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/HueNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/HueNode.cs @@ -54,7 +54,7 @@ static string Unity_Hue_Degrees( { Out = Vector3.zero; return - @" +@" { // RGB to HSV $precision4 K = $precision4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); @@ -85,7 +85,7 @@ static string Unity_Hue_Normalized( { Out = Vector3.zero; return - @" +@" { // RGB to HSV $precision4 K = $precision4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs index e7885f4d08f..ec580555042 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs @@ -155,17 +155,17 @@ public override void CollectShaderProperties(PropertyCollector properties, Gener public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0}({1} In, {2} InvertColors, out {3} Out)", + GetFunctionName(), + FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0}({1} In, {2} InvertColors, out {3} Out)", - GetFunctionName(), - FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), - FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) - { - s.AppendLine("Out = abs(InvertColors - In);"); - } - }); + s.AppendLine("Out = abs(InvertColors - In);"); + } + }); } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs index 03611572c13..4fcfe035a7c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs @@ -26,7 +26,7 @@ static string Unity_ReplaceColor( { Out = Vector3.zero; return - @" +@" { $precision Distance = distance(From, In); Out = lerp(To, In, saturate((Distance - Range) / max(Fuzziness, 1e-5f))); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Blend/BlendNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Blend/BlendNode.cs index 61d3d113e91..b6916881a98 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Blend/BlendNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Blend/BlendNode.cs @@ -48,7 +48,7 @@ static string Unity_Blend_Burn( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 1.0 - (1.0 - Blend)/(Base + 0.000000000001); Out = lerp(Base, Out, Opacity); @@ -62,7 +62,7 @@ static string Unity_Blend_Darken( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = min(Blend, Base); Out = lerp(Base, Out, Opacity); @@ -76,7 +76,7 @@ static string Unity_Blend_Difference( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = abs(Blend - Base); Out = lerp(Base, Out, Opacity); @@ -90,7 +90,7 @@ static string Unity_Blend_Dodge( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Base / (1.0 - clamp(Blend, 0.000001, 0.999999)); Out = lerp(Base, Out, Opacity); @@ -104,7 +104,7 @@ static string Unity_Blend_Divide( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Base / (Blend + 0.000000000001); Out = lerp(Base, Out, Opacity); @@ -118,7 +118,7 @@ static string Unity_Blend_Exclusion( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Blend + Base - (2.0 * Blend * Base); Out = lerp(Base, Out, Opacity); @@ -132,7 +132,7 @@ static string Unity_Blend_HardLight( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { $precision{slot2dimension} result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend); $precision{slot2dimension} result2 = 2.0 * Base * Blend; @@ -149,7 +149,7 @@ static string Unity_Blend_HardMix( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = step(1 - Base, Blend); Out = lerp(Base, Out, Opacity); @@ -163,7 +163,7 @@ static string Unity_Blend_Lighten( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = max(Blend, Base); Out = lerp(Base, Out, Opacity); @@ -177,7 +177,7 @@ static string Unity_Blend_LinearBurn( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Base + Blend - 1.0; Out = lerp(Base, Out, Opacity); @@ -191,7 +191,7 @@ static string Unity_Blend_LinearDodge( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Base + Blend; Out = lerp(Base, Out, Opacity); @@ -205,7 +205,7 @@ static string Unity_Blend_LinearLight( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Blend < 0.5 ? max(Base + (2 * Blend) - 1, 0) : min(Base + 2 * (Blend - 0.5), 1); Out = lerp(Base, Out, Opacity); @@ -219,7 +219,7 @@ static string Unity_Blend_LinearLightAddSub( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Blend + 2.0 * Base - 1.0; Out = lerp(Base, Out, Opacity); @@ -233,7 +233,7 @@ static string Unity_Blend_Multiply( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Base * Blend; Out = lerp(Base, Out, Opacity); @@ -247,7 +247,7 @@ static string Unity_Blend_Negation( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 1.0 - abs(1.0 - Blend - Base); Out = lerp(Base, Out, Opacity); @@ -261,7 +261,7 @@ static string Unity_Blend_Screen( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 1.0 - (1.0 - Blend) * (1.0 - Base); Out = lerp(Base, Out, Opacity); @@ -275,7 +275,7 @@ static string Unity_Blend_Overlay( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { $precision{slot2dimension} result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend); $precision{slot2dimension} result2 = 2.0 * Base * Blend; @@ -293,7 +293,7 @@ static string Unity_Blend_PinLight( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { $precision{slot2dimension} check = step (0.5, Blend); $precision{slot2dimension} result1 = check * max(2.0 * (Base - 0.5), Blend); @@ -310,7 +310,7 @@ static string Unity_Blend_SoftLight( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { $precision{slot2dimension} result1 = 2.0 * Base * Blend + Base * Base * (1.0 - 2.0 * Blend); $precision{slot2dimension} result2 = sqrt(Base) * (2.0 * Blend - 1.0) + 2.0 * Base * (1.0 - Blend); @@ -328,7 +328,7 @@ static string Unity_Blend_VividLight( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Base = clamp(Base, 0.000001, 0.999999); $precision{slot2dimension} result1 = 1.0 - (1.0 - Blend) / (2.0 * Base); @@ -347,7 +347,7 @@ static string Unity_Blend_Subtract( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Base - Blend; Out = lerp(Base, Out, Opacity); @@ -362,7 +362,7 @@ static string Unity_Blend_Overwrite( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = lerp(Base, Blend, Opacity); }"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Filter/DitherNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Filter/DitherNode.cs index f659958dd08..98ac5125306 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Filter/DitherNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Filter/DitherNode.cs @@ -23,7 +23,7 @@ static string Unity_Dither( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { $precision2 uv = ScreenPosition.xy * _ScreenParams.xy; $precision DITHER_THRESHOLDS[16] = diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ChannelMaskNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ChannelMaskNode.cs index a067974eba5..8c9b55eaebe 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ChannelMaskNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ChannelMaskNode.cs @@ -107,45 +107,45 @@ public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode gener { ValidateChannelCount(); registry.ProvideFunction(GetFunctionName(), s => + { + int channelCount = SlotValueHelper.GetChannelCount(FindSlot(InputSlotId).concreteValueType); + s.AppendLine(GetFunctionPrototype("In", "Out")); + using (s.BlockScope()) { - int channelCount = SlotValueHelper.GetChannelCount(FindSlot(InputSlotId).concreteValueType); - s.AppendLine(GetFunctionPrototype("In", "Out")); - using (s.BlockScope()) + if (channelMask == 0) + s.AppendLine("Out = 0;"); + else if (channelMask == -1) + s.AppendLine("Out = In;"); + else { - if (channelMask == 0) - s.AppendLine("Out = 0;"); - else if (channelMask == -1) - s.AppendLine("Out = In;"); - else + bool red = (channelMask & 1) != 0; + bool green = (channelMask & 2) != 0; + bool blue = (channelMask & 4) != 0; + bool alpha = (channelMask & 8) != 0; + + switch (channelCount) { - bool red = (channelMask & 1) != 0; - bool green = (channelMask & 2) != 0; - bool blue = (channelMask & 4) != 0; - bool alpha = (channelMask & 8) != 0; - - switch (channelCount) - { - case 1: - s.AppendLine("Out = In.r;"); - break; - case 2: - s.AppendLine(string.Format("Out = $precision2({0}, {1});", - red ? "In.r" : "0", green ? "In.g" : "0")); - break; - case 3: - s.AppendLine(string.Format("Out = $precision3({0}, {1}, {2});", - red ? "In.r" : "0", green ? "In.g" : "0", blue ? "In.b" : "0")); - break; - case 4: - s.AppendLine(string.Format("Out = $precision4({0}, {1}, {2}, {3});", - red ? "In.r" : "0", green ? "In.g" : "0", blue ? "In.b" : "0", alpha ? "In.a" : "0")); - break; - default: - throw new ArgumentOutOfRangeException(); - } + case 1: + s.AppendLine("Out = In.r;"); + break; + case 2: + s.AppendLine(string.Format("Out = $precision2({0}, {1});", + red ? "In.r" : "0", green ? "In.g" : "0")); + break; + case 3: + s.AppendLine(string.Format("Out = $precision3({0}, {1}, {2});", + red ? "In.r" : "0", green ? "In.g" : "0", blue ? "In.b" : "0")); + break; + case 4: + s.AppendLine(string.Format("Out = $precision4({0}, {1}, {2}, {3});", + red ? "In.r" : "0", green ? "In.g" : "0", blue ? "In.b" : "0", alpha ? "In.a" : "0")); + break; + default: + throw new ArgumentOutOfRangeException(); } } - }); + } + }); } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ColorMaskNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ColorMaskNode.cs index 8d9dbf10f2c..3673c214f5b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ColorMaskNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Mask/ColorMaskNode.cs @@ -24,7 +24,7 @@ static string Unity_ColorMask( [Slot(3, Binding.None)] out Vector1 Out) { return - @" +@" { $precision Distance = distance(MaskColor, In); Out = saturate(1 - (Distance - Range) / max(Fuzziness, 1e-5)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs index 0fc0af74a55..2d4efdb7137 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromHeightNode.cs @@ -7,7 +7,6 @@ namespace UnityEditor.ShaderGraph { - enum OutputSpace { Tangent, @@ -79,32 +78,32 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0}({1} In, {2} Strength, $precision3 Position, $precision3x3 TangentMatrix, out {3} Out)", + GetFunctionName(), + FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + FindInputSlot(StrengthSlotId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0}({1} In, {2} Strength, $precision3 Position, $precision3x3 TangentMatrix, out {3} Out)", - GetFunctionName(), - FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), - FindInputSlot(StrengthSlotId).concreteValueType.ToShaderString(), - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) - { - s.AppendLine("$precision3 worldDerivativeX = ddx(Position);"); - s.AppendLine("$precision3 worldDerivativeY = ddy(Position);"); - s.AppendNewLine(); - s.AppendLine("$precision3 crossX = cross(TangentMatrix[2].xyz, worldDerivativeX);"); - s.AppendLine("$precision3 crossY = cross(worldDerivativeY, TangentMatrix[2].xyz);"); - s.AppendLine("$precision d = dot(worldDerivativeX, crossY);"); - s.AppendLine("$precision sgn = d < 0.0 ? (-1.0f) : 1.0f;"); - s.AppendLine("$precision surface = sgn / max(0.000000000000001192093f, abs(d));"); - s.AppendNewLine(); - s.AppendLine("$precision dHdx = ddx(In);"); - s.AppendLine("$precision dHdy = ddy(In);"); - s.AppendLine("$precision3 surfGrad = surface * (dHdx*crossY + dHdy*crossX);"); - s.AppendLine("Out = SafeNormalize(TangentMatrix[2].xyz - (Strength * surfGrad));"); - - if(outputSpace == OutputSpace.Tangent) - s.AppendLine("Out = TransformWorldToTangent(Out, TangentMatrix);"); - } - }); + s.AppendLine("$precision3 worldDerivativeX = ddx(Position);"); + s.AppendLine("$precision3 worldDerivativeY = ddy(Position);"); + s.AppendNewLine(); + s.AppendLine("$precision3 crossX = cross(TangentMatrix[2].xyz, worldDerivativeX);"); + s.AppendLine("$precision3 crossY = cross(worldDerivativeY, TangentMatrix[2].xyz);"); + s.AppendLine("$precision d = dot(worldDerivativeX, crossY);"); + s.AppendLine("$precision sgn = d < 0.0 ? (-1.0f) : 1.0f;"); + s.AppendLine("$precision surface = sgn / max(0.000000000000001192093f, abs(d));"); + s.AppendNewLine(); + s.AppendLine("$precision dHdx = ddx(In);"); + s.AppendLine("$precision dHdy = ddy(In);"); + s.AppendLine("$precision3 surfGrad = surface * (dHdx*crossY + dHdy*crossX);"); + s.AppendLine("Out = SafeNormalize(TangentMatrix[2].xyz - (Strength * surfGrad));"); + + if (outputSpace == OutputSpace.Tangent) + s.AppendLine("Out = TransformWorldToTangent(Out, TangentMatrix);"); + } + }); } public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) @@ -121,9 +120,10 @@ public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapabilit { return NeededCoordinateSpace.World; } + public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) { return NeededCoordinateSpace.World; } - } + } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromTextureNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromTextureNode.cs index 91d84cfa49d..68d345228f3 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromTextureNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalFromTextureNode.cs @@ -70,29 +70,29 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0}({1} Texture, {2} Sampler, {3} UV, {4} Offset, {5} Strength, out {6} Out)", GetFunctionName(), + FindInputSlot(TextureInputId).concreteValueType.ToShaderString(), + FindInputSlot(SamplerInputId).concreteValueType.ToShaderString(), + FindInputSlot(UVInputId).concreteValueType.ToShaderString(), + FindInputSlot(OffsetInputId).concreteValueType.ToShaderString(), + FindInputSlot(StrengthInputId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0}({1} Texture, {2} Sampler, {3} UV, {4} Offset, {5} Strength, out {6} Out)", GetFunctionName(), - FindInputSlot(TextureInputId).concreteValueType.ToShaderString(), - FindInputSlot(SamplerInputId).concreteValueType.ToShaderString(), - FindInputSlot(UVInputId).concreteValueType.ToShaderString(), - FindInputSlot(OffsetInputId).concreteValueType.ToShaderString(), - FindInputSlot(StrengthInputId).concreteValueType.ToShaderString(), - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) - { - s.AppendLine("Offset = pow(Offset, 3) * 0.1;"); - s.AppendLine("$precision2 offsetU = $precision2(UV.x + Offset, UV.y);"); - s.AppendLine("$precision2 offsetV = $precision2(UV.x, UV.y + Offset);"); + s.AppendLine("Offset = pow(Offset, 3) * 0.1;"); + s.AppendLine("$precision2 offsetU = $precision2(UV.x + Offset, UV.y);"); + s.AppendLine("$precision2 offsetV = $precision2(UV.x, UV.y + Offset);"); - s.AppendLine("$precision normalSample = Texture.Sample(Sampler, UV);"); - s.AppendLine("$precision uSample = Texture.Sample(Sampler, offsetU);"); - s.AppendLine("$precision vSample = Texture.Sample(Sampler, offsetV);"); + s.AppendLine("$precision normalSample = Texture.Sample(Sampler, UV);"); + s.AppendLine("$precision uSample = Texture.Sample(Sampler, offsetU);"); + s.AppendLine("$precision vSample = Texture.Sample(Sampler, offsetV);"); - s.AppendLine("$precision3 va = $precision3(1, 0, (uSample - normalSample) * Strength);"); - s.AppendLine("$precision3 vb = $precision3(0, 1, (vSample - normalSample) * Strength);"); - s.AppendLine("Out = normalize(cross(va, vb));"); - } - }); + s.AppendLine("$precision3 va = $precision3(1, 0, (uSample - normalSample) * Strength);"); + s.AppendLine("$precision3 vb = $precision3(0, 1, (vSample - normalSample) * Strength);"); + s.AppendLine("Out = normalize(cross(va, vb));"); + } + }); } public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs index 36876b391a1..7685e6338fd 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalReconstructZNode.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using UnityEngine; namespace UnityEditor.ShaderGraph @@ -22,7 +22,7 @@ static string NormalReconstructZ( { Out = Vector3.zero; return - @" +@" { $precision reconstructZ = sqrt(1.0 - saturate(dot(In.xy, In.xy))); $precision3 normalVector = $precision3(In.x, In.y, reconstructZ); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs index fb1b7fae3e6..22e75a38118 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs @@ -11,7 +11,6 @@ public NormalStrengthNode() name = "Normal Strength"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_NormalStrength", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_NormalStrength( { Out = Vector3.up; return - @" +@" { Out = $precision3(In.rg * Strength, lerp(1, In.b, saturate(Strength))); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs index 6a952bf32be..ab2f1a4ebb7 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs @@ -13,7 +13,6 @@ public NormalUnpackNode() name = "Normal Unpack"; } - [SerializeField] private NormalMapSpace m_NormalMapSpace = NormalMapSpace.Tangent; @@ -43,7 +42,7 @@ static string Unity_NormalUnpack( Out = Vector3.up; return - @" +@" { Out = UnpackNormal(In); } @@ -57,7 +56,7 @@ static string Unity_NormalUnpackRGB( Out = Vector3.up; return - @" +@" { Out = UnpackNormalRGB(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Utility/ColorspaceConversion.cs b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Utility/ColorspaceConversion.cs index 9d3ad16907f..3af7b63f47e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Utility/ColorspaceConversion.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Artistic/Utility/ColorspaceConversion.cs @@ -46,7 +46,6 @@ public ColorspaceConversionNode() name = "Colorspace Conversion"; } - [SerializeField] ColorspaceConversion m_Conversion = new ColorspaceConversion(Colorspace.RGB, Colorspace.RGB); @@ -85,7 +84,7 @@ static string Unity_ColorspaceConversion_RGB_RGB( { Out = Vector3.zero; return - @" +@" { Out = In; } @@ -98,7 +97,7 @@ static string Unity_ColorspaceConversion_RGB_Linear( { Out = Vector3.zero; return - @" +@" { $precision3 linearRGBLo = In / 12.92; $precision3 linearRGBHi = pow(max(abs((In + 0.055) / 1.055), 1.192092896e-07), $precision3(2.4, 2.4, 2.4)); @@ -113,7 +112,7 @@ static string Unity_ColorspaceConversion_RGB_HSV( { Out = Vector3.zero; return - @" +@" { $precision4 K = $precision4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); $precision4 P = lerp($precision4(In.bg, K.wz), $precision4(In.gb, K.xy), step(In.b, In.g)); @@ -131,7 +130,7 @@ static string Unity_ColorspaceConversion_Linear_RGB( { Out = Vector3.zero; return - @" +@" { $precision3 sRGBLo = In * 12.92; $precision3 sRGBHi = (pow(max(abs(In), 1.192092896e-07), $precision3(1.0 / 2.4, 1.0 / 2.4, 1.0 / 2.4)) * 1.055) - 0.055; @@ -146,7 +145,7 @@ static string Unity_ColorspaceConversion_Linear_Linear( { Out = Vector3.zero; return - @" +@" { Out = In; } @@ -159,7 +158,7 @@ static string Unity_ColorspaceConversion_Linear_HSV( { Out = Vector3.zero; return - @" +@" { $precision3 sRGBLo = In * 12.92; $precision3 sRGBHi = (pow(max(abs(In), 1.192092896e-07), $precision3(1.0 / 2.4, 1.0 / 2.4, 1.0 / 2.4)) * 1.055) - 0.055; @@ -180,7 +179,7 @@ static string Unity_ColorspaceConversion_HSV_RGB( { Out = Vector3.zero; return - @" +@" { $precision4 K = $precision4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); $precision3 P = abs(frac(In.xxx + K.xyz) * 6.0 - K.www); @@ -195,7 +194,7 @@ static string Unity_ColorspaceConversion_HSV_Linear( { Out = Vector3.zero; return - @" +@" { $precision4 K = $precision4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); $precision3 P = abs(frac(In.xxx + K.xyz) * 6.0 - K.www); @@ -213,7 +212,7 @@ static string Unity_ColorspaceConversion_HSV_HSV( { Out = Vector3.zero; return - @" +@" { Out = In; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs index 63d4886abf8..a416d7f42b0 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/BlockNode.cs @@ -27,7 +27,7 @@ class BlockNode : AbstractMaterialNode public BlockNode() { } - + public override bool canCutNode => false; public override bool canCopyNode => false; @@ -58,7 +58,7 @@ public void Init(BlockFieldDescriptor fieldDescriptor) // TODO: This exposes the MaterialSlot API // TODO: This needs to be removed but is currently required by HDRP for DiffusionProfileInputMaterialSlot - if(m_Descriptor is CustomSlotBlockFieldDescriptor customSlotDescriptor) + if (m_Descriptor is CustomSlotBlockFieldDescriptor customSlotDescriptor) { var newSlot = customSlotDescriptor.createSlot(); AddSlot(newSlot); @@ -73,7 +73,7 @@ void AddSlotFromControlType() { // TODO: this should really just use callbacks like the CustomSlotBlockFieldDescriptor.. then we wouldn't need this switch to make a copy var stageCapability = m_Descriptor.shaderStage.GetShaderStageCapability(); - switch(descriptor.control) + switch (descriptor.control) { case PositionControl positionControl: AddSlot(new PositionMaterialSlot(0, descriptor.displayName, descriptor.name, positionControl.space, stageCapability)); @@ -113,22 +113,22 @@ public override string GetVariableNameForNode() public NeededCoordinateSpace RequiresNormal(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return NeededCoordinateSpace.None; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return NeededCoordinateSpace.None; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresNormal; } public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return NeededCoordinateSpace.None; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return NeededCoordinateSpace.None; var requirements = m_Descriptor.control.GetRequirements(); @@ -137,72 +137,72 @@ public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCa public NeededCoordinateSpace RequiresPosition(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return NeededCoordinateSpace.None; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return NeededCoordinateSpace.None; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresPosition; } public NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return NeededCoordinateSpace.None; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return NeededCoordinateSpace.None; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresTangent; } public NeededCoordinateSpace RequiresBitangent(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return NeededCoordinateSpace.None; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return NeededCoordinateSpace.None; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresBitangent; } public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return false; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return false; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresMeshUVs.Contains(channel); } public bool RequiresScreenPosition(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return false; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return false; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresScreenPosition; } public bool RequiresVertexColor(ShaderStageCapability stageCapability) { - if(stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) + if (stageCapability != m_Descriptor.shaderStage.GetShaderStageCapability()) return false; - if(m_Descriptor.control == null) + if (m_Descriptor.control == null) return false; - + var requirements = m_Descriptor.control.GetRequirements(); return requirements.requiresVertexColor; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Channel/CombineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Channel/CombineNode.cs index e3b17250f29..c34bc6bf8ff 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Channel/CombineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Channel/CombineNode.cs @@ -12,7 +12,6 @@ public CombineNode() name = "Combine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Combine", BindingFlags.Static | BindingFlags.NonPublic); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Channel/FlipNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Channel/FlipNode.cs index 55b18692614..335b14096ab 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Channel/FlipNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Channel/FlipNode.cs @@ -16,7 +16,6 @@ public FlipNode() UpdateNodeAfterDeserialization(); } - const int InputSlotId = 0; const int OutputSlotId = 1; const string kInputSlotName = "In"; @@ -157,17 +156,17 @@ public override void CollectShaderProperties(PropertyCollector properties, Gener public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0}({1} In, {2} Flip, out {3} Out)", + GetFunctionName(), + FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0}({1} In, {2} Flip, out {3} Out)", - GetFunctionName(), - FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), - FindInputSlot(InputSlotId).concreteValueType.ToShaderString(), - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) - { - s.AppendLine("Out = (Flip * -2 + 1) * In;"); - } - }); + s.AppendLine("Out = (Flip * -2 + 1) * In;"); + } + }); } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Channel/SplitNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Channel/SplitNode.cs index 605f8de8e35..a9e31d596b3 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Channel/SplitNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Channel/SplitNode.cs @@ -26,7 +26,6 @@ public SplitNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new DynamicVectorMaterialSlot(InputSlotId, kInputSlotName, kInputSlotName, SlotType.Input, Vector4.zero)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Channel/SwizzleNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Channel/SwizzleNode.cs index ffe7477458d..5ffe8dfa2b6 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Channel/SwizzleNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Channel/SwizzleNode.cs @@ -17,7 +17,6 @@ public SwizzleNode() UpdateNodeAfterDeserialization(); } - const int InputSlotId = 0; const int OutputSlotId = 1; const string kInputSlotName = "In"; @@ -135,13 +134,13 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo sb.AppendLine(string.Format("{0} {1} = {2};", outputSlotType, outputName, inputValue)); else if (generationMode == GenerationMode.ForReals) sb.AppendLine("{0} {1} = {2}.{3}{4}{5}{6};", - outputSlotType, - outputName, - inputValue, - s_ComponentList[m_RedChannel].ToString(CultureInfo.InvariantCulture), - s_ComponentList[m_GreenChannel].ToString(CultureInfo.InvariantCulture), - s_ComponentList[m_BlueChannel].ToString(CultureInfo.InvariantCulture), - s_ComponentList[m_AlphaChannel].ToString(CultureInfo.InvariantCulture)); + outputSlotType, + outputName, + inputValue, + s_ComponentList[m_RedChannel].ToString(CultureInfo.InvariantCulture), + s_ComponentList[m_GreenChannel].ToString(CultureInfo.InvariantCulture), + s_ComponentList[m_BlueChannel].ToString(CultureInfo.InvariantCulture), + s_ComponentList[m_AlphaChannel].ToString(CultureInfo.InvariantCulture)); else sb.AppendLine("{0} {1} = {0}({3}[((int){2} >> 0) & 3], {3}[((int){2} >> 2) & 3], {3}[((int){2} >> 4) & 3], {3}[((int){2} >> 6) & 3]);", outputSlotType, outputName, GetVariableNameForNode(), inputValue); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs index 39a532f6835..b278561e5f9 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/CodeFunctionNode.cs @@ -259,14 +259,14 @@ public sealed override void UpdateNodeAfterDeserialization() s = new ColorRGBMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, ColorMode.Default, stageCapability: attribute.stageCapability, hidden: attribute.hidden); else if (attribute.binding == Binding.None || par.IsOut) s = MaterialSlot.CreateMaterialSlot( - ConvertTypeToSlotValueType(par), - attribute.slotId, - name, - par.Name, - par.IsOut ? SlotType.Output : SlotType.Input, - attribute.defaultValue ?? Vector4.zero, - shaderStageCapability: attribute.stageCapability, - hidden: attribute.hidden); + ConvertTypeToSlotValueType(par), + attribute.slotId, + name, + par.Name, + par.IsOut ? SlotType.Output : SlotType.Input, + attribute.defaultValue ?? Vector4.zero, + shaderStageCapability: attribute.stageCapability, + hidden: attribute.hidden); else s = CreateBoundSlot(attribute.binding, attribute.slotId, name, par.Name, attribute.stageCapability, attribute.hidden); slots.Add(s); @@ -444,12 +444,12 @@ private string GetFunctionBody(MethodInfo info) public virtual void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => - { - s.AppendLine(GetFunctionHeader()); - var functionBody = GetFunctionBody(GetFunctionToConvert()); - var lines = functionBody.Trim('\r', '\n', '\t', ' '); - s.AppendLines(lines); - }); + { + s.AppendLine(GetFunctionHeader()); + var functionBody = GetFunctionBody(GetFunctionToConvert()); + var lines = functionBody.Trim('\r', '\n', '\t', ' '); + s.AppendLines(lines); + }); } private static SlotAttribute GetSlotAttribute([NotNull] ParameterInfo info) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/GeometryNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/GeometryNode.cs index 19c5051aad2..4a7a0f8f043 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/GeometryNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/GeometryNode.cs @@ -17,9 +17,9 @@ abstract class GeometryNode : AbstractMaterialNode private CoordinateSpace m_Space = CoordinateSpace.World; [PopupControl("Space")] - public PopupList spacePopup + public PopupList spacePopup { - get + get { var names = validSpaces.Select(cs => cs.ToString().PascalToLabel()).ToArray(); return new PopupList(names, (int)m_Space); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/BooleanNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/BooleanNode.cs index 95913ee6248..bafc7484cb6 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/BooleanNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/BooleanNode.cs @@ -21,7 +21,6 @@ public BooleanNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new BooleanMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, false)); @@ -58,7 +57,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo { if (generationMode.IsPreview()) return; - + sb.AppendLine("$precision {0} = {1};", GetVariableNameForNode(), (m_Value ? 1 : 0)); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/ColorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/ColorNode.cs index bd023c77f4c..d5445f85d8e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/ColorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/ColorNode.cs @@ -30,7 +30,6 @@ public ColorNode() UpdateNodeAfterDeserialization(); } - [SerializeField] Color m_Color = new Color(UnityEngine.Color.clear, ColorMode.Default); @@ -107,7 +106,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo break; case 1: //HDR color picker assumes Linear space, regular color picker assumes SRGB. Handle both cases - if(color.mode == ColorMode.Default) + if (color.mode == ColorMode.Default) { sb.AppendLine(@"$precision4 {0} = IsGammaSpace() ? $precision4({1}, {2}, {3}, {4}) : $precision4(SRGBToLinear($precision3({1}, {2}, {3})), {4});" , GetVariableNameForNode() @@ -147,7 +146,7 @@ public override void CollectPreviewMaterialProperties(List prop switch (sgVersion) { case 0: - if(PlayerSettings.colorSpace == ColorSpace.Linear) + if (PlayerSettings.colorSpace == ColorSpace.Linear) propColor = propColor.linear; break; case 1: diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/IntegerNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/IntegerNode.cs index 21bd4001d29..5f85763830c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/IntegerNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/IntegerNode.cs @@ -21,7 +21,6 @@ public IntegerNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, 0)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/SliderNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/SliderNode.cs index bc16cad9785..480656ebd60 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/SliderNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/SliderNode.cs @@ -22,7 +22,6 @@ public SliderNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, 0)); @@ -64,7 +63,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo if (generationMode.IsPreview()) return; - sb.AppendLine(string.Format(CultureInfo.InvariantCulture,"$precision {0} = {1};", GetVariableNameForNode(), m_Value.x)); + sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "$precision {0} = {1};", GetVariableNameForNode(), m_Value.x)); } public override string GetVariableNameForSlot(int slotId) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/TimeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/TimeNode.cs index f84041b2a8e..6d5d1a6f2b8 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/TimeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/TimeNode.cs @@ -24,7 +24,6 @@ public TimeNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, 0)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector1Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector1Node.cs index 8006538d330..7fd91f47609 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector1Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector1Node.cs @@ -22,11 +22,10 @@ class Vector1Node : AbstractMaterialNode, IGeneratesBodyCode, IPropertyFromNode public Vector1Node() { name = "Float"; - synonyms = new string[]{"Vector 1"}; + synonyms = new string[] {"Vector 1"}; UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(InputSlotXId, kInputSlotXName, kInputSlotXName, SlotType.Input, m_Value)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector2Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector2Node.cs index 2e417205cfa..a2a7a47b52d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector2Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector2Node.cs @@ -28,7 +28,6 @@ public Vector2Node() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(InputSlotXId, kInputSlotXName, kInputSlotXName, SlotType.Input, m_Value.x)); @@ -44,9 +43,9 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo var outputName = GetVariableNameForSlot(OutputSlotId); var s = string.Format("$precision2 {0} = $precision2({1}, {2});", - outputName, - inputXValue, - inputYValue); + outputName, + inputXValue, + inputYValue); sb.AppendLine(s); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector3Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector3Node.cs index e39f3e7f7db..e2085b3f210 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector3Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector3Node.cs @@ -29,7 +29,6 @@ public Vector3Node() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(InputSlotXId, kInputSlotXName, kInputSlotXName, SlotType.Input, m_Value.x)); @@ -47,10 +46,10 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo var outputName = GetVariableNameForSlot(outputSlotId); var s = string.Format("$precision3 {0} = $precision3({1}, {2}, {3});", - outputName, - inputXValue, - inputYValue, - inputZValue); + outputName, + inputXValue, + inputYValue, + inputZValue); sb.AppendLine(s); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector4Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector4Node.cs index 204ddb2c38e..353133efc9f 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector4Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Basic/Vector4Node.cs @@ -31,7 +31,6 @@ public Vector4Node() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(InputSlotXId, kInputSlotXName, kInputSlotXName, SlotType.Input, m_Value.x)); @@ -51,11 +50,11 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo var outputName = GetVariableNameForSlot(outputSlotId); var s = string.Format("$precision4 {0} = $precision4({1}, {2}, {3}, {4});", - outputName, - inputXValue, - inputYValue, - inputZValue, - inputWValue); + outputName, + inputXValue, + inputYValue, + inputZValue, + inputWValue); sb.AppendLine(s); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/BitangentVectorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/BitangentVectorNode.cs index 4b730680878..d5b8ae804b2 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/BitangentVectorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/BitangentVectorNode.cs @@ -16,7 +16,6 @@ public BitangentVectorNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, new Vector4(0, 0, 1))); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/NormalVectorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/NormalVectorNode.cs index 62365d0193e..53f9a342de3 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/NormalVectorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/NormalVectorNode.cs @@ -17,7 +17,6 @@ public NormalVectorNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, new Vector4(0, 0, 1))); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/PositionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/PositionNode.cs index c1f80132278..87f1595d7da 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/PositionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/PositionNode.cs @@ -25,15 +25,14 @@ public PositionNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot( - kOutputSlotId, - kOutputSlotName, - kOutputSlotName, - SlotType.Output, - Vector3.zero)); + kOutputSlotId, + kOutputSlotName, + kOutputSlotName, + SlotType.Output, + Vector3.zero)); RemoveSlotsNameNotMatching(new[] { kOutputSlotId }); } @@ -51,7 +50,7 @@ public override void OnAfterMultiDeserialize(string json) { base.OnAfterMultiDeserialize(json); //required update - if(sgVersion < 1) + if (sgVersion < 1) { ChangeVersion(1); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs index 8a766b902c0..1eb13f73d97 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs @@ -13,7 +13,6 @@ public ScreenPositionNode() UpdateNodeAfterDeserialization(); } - [SerializeField] private ScreenSpaceType m_ScreenSpaceType = ScreenSpaceType.Default; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/TangentVectorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/TangentVectorNode.cs index 27c39f864bf..a2c0d9333f2 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/TangentVectorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/TangentVectorNode.cs @@ -16,7 +16,6 @@ public TangentVectorNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, new Vector4(0, 0, 1, 1))); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/UVNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/UVNode.cs index 291bcdd960e..e82efd3e912 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/UVNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/UVNode.cs @@ -36,7 +36,6 @@ public UVNode() UpdateNodeAfterDeserialization(); } - public override void UpdateNodeAfterDeserialization() { AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector2.zero)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/VertexColorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/VertexColorNode.cs index 594133fa46b..d5d65201720 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/VertexColorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/VertexColorNode.cs @@ -22,7 +22,6 @@ public VertexColorNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector4MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.one)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ViewDirectionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ViewDirectionNode.cs index d859a3d4779..0d023d52d4d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ViewDirectionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Geometry/ViewDirectionNode.cs @@ -17,15 +17,14 @@ public ViewDirectionNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot( - kOutputSlotId, - kOutputSlotName, - kOutputSlotName, - SlotType.Output, - Vector4.zero)); + kOutputSlotId, + kOutputSlotName, + kOutputSlotName, + SlotType.Output, + Vector4.zero)); RemoveSlotsNameNotMatching(new[] { kOutputSlotId }); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/GradientNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/GradientNode.cs index c34e035b678..986fea26c5e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/GradientNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/GradientNode.cs @@ -120,7 +120,7 @@ public override void CollectPreviewMaterialProperties(List prop public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode) { - if(!generationMode.IsPreview()) + if (!generationMode.IsPreview()) return; base.CollectShaderProperties(properties, generationMode); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/SampleGradientNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/SampleGradientNode.cs index 2bfe8830cc5..726aee51fee 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/SampleGradientNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Gradient/SampleGradientNode.cs @@ -28,7 +28,7 @@ static string Unity_SampleGradient( { Out = Vector4.zero; return - @" +@" { $precision3 color = Gradient.colors[0].rgb; [unroll] diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/AmbientNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/AmbientNode.cs index 16c758a60af..bf055590600 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/AmbientNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/AmbientNode.cs @@ -21,7 +21,6 @@ public AmbientNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new ColorRGBMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero, ColorMode.Default)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/BakedGINode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/BakedGINode.cs index 9b683c4dfbc..18677fa2e75 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/BakedGINode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/BakedGINode.cs @@ -17,10 +17,9 @@ public BakedGINode() name = "Baked GI"; } - protected override MethodInfo GetFunctionToConvert() { - if(applyScaling.isOn) + if (applyScaling.isOn) return GetType().GetMethod("Unity_BakedGIScale", BindingFlags.Static | BindingFlags.NonPublic); else return GetType().GetMethod("Unity_BakedGI", BindingFlags.Static | BindingFlags.NonPublic); @@ -43,15 +42,15 @@ public ToggleData applyScaling } static string Unity_BakedGI( - [Slot(2, Binding.WorldSpacePosition)] Vector3 Position, - [Slot(0, Binding.WorldSpaceNormal)] Vector3 Normal, - [Slot(3, Binding.MeshUV1)] Vector2 StaticUV, - [Slot(4, Binding.MeshUV2)] Vector2 DynamicUV, - [Slot(1, Binding.None)] out Vector3 Out) + [Slot(2, Binding.WorldSpacePosition)] Vector3 Position, + [Slot(0, Binding.WorldSpaceNormal)] Vector3 Normal, + [Slot(3, Binding.MeshUV1)] Vector2 StaticUV, + [Slot(4, Binding.MeshUV2)] Vector2 DynamicUV, + [Slot(1, Binding.None)] out Vector3 Out) { Out = Vector3.one; return - @" +@" { Out = SHADERGRAPH_BAKED_GI(Position, Normal, StaticUV, DynamicUV, false); } @@ -59,15 +58,15 @@ static string Unity_BakedGI( } static string Unity_BakedGIScale( - [Slot(2, Binding.WorldSpacePosition)] Vector3 Position, - [Slot(0, Binding.WorldSpaceNormal)] Vector3 Normal, - [Slot(3, Binding.MeshUV1)] Vector2 StaticUV, - [Slot(4, Binding.MeshUV2)] Vector2 DynamicUV, - [Slot(1, Binding.None)] out Vector3 Out) + [Slot(2, Binding.WorldSpacePosition)] Vector3 Position, + [Slot(0, Binding.WorldSpaceNormal)] Vector3 Normal, + [Slot(3, Binding.MeshUV1)] Vector2 StaticUV, + [Slot(4, Binding.MeshUV2)] Vector2 DynamicUV, + [Slot(1, Binding.None)] out Vector3 Out) { Out = Vector3.one; return - @" +@" { Out = SHADERGRAPH_BAKED_GI(Position, Normal, StaticUV, DynamicUV, true); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/ReflectionProbeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/ReflectionProbeNode.cs index 940a0c4d66f..ddbdd8bf441 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/ReflectionProbeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Lighting/ReflectionProbeNode.cs @@ -11,7 +11,6 @@ public ReflectionProbeNode() name = "Reflection Probe"; } - public override bool hasPreview { get { return false; } } protected override MethodInfo GetFunctionToConvert() @@ -27,7 +26,7 @@ static string Unity_ReflectionProbe( { Out = Vector3.one; return - @" +@" { Out = SHADERGRAPH_REFLECTION_PROBE(ViewDir, Normal, LOD); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix2Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix2Node.cs index ceba44b8d97..b9f51d89398 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix2Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix2Node.cs @@ -46,7 +46,6 @@ public Matrix2Node() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Matrix2MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix3Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix3Node.cs index 6e6e7530449..59916cb65f1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix3Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix3Node.cs @@ -56,7 +56,6 @@ public Matrix3Node() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Matrix3MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix4Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix4Node.cs index 12e8dbde328..7f498be1adb 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix4Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/Matrix4Node.cs @@ -66,7 +66,6 @@ public Matrix4Node() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Matrix4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs index 8ff80b40845..0d94fee1642 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs @@ -89,10 +89,9 @@ public TransformationMatrixNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { - if(m_matrix != TransformationMatrixType.None) + if (m_matrix != TransformationMatrixType.None) { m_MatrixType = m_MatrixUpgrade[m_matrix]; m_matrix = TransformationMatrixType.None; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/DielectricSpecularNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/DielectricSpecularNode.cs index a42f48284e6..bc55af711ff 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/DielectricSpecularNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/DielectricSpecularNode.cs @@ -27,7 +27,6 @@ public DielectricSpecularNode() UpdateNodeAfterDeserialization(); } - [SerializeField] DielectricMaterial m_Material = new DielectricMaterial(DielectricMaterialType.Common, 0.5f, 1.0f); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs index 7e6c4cdefe6..abf8fc44fa4 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs @@ -29,7 +29,6 @@ public MetalReflectanceNode() UpdateNodeAfterDeserialization(); } - [SerializeField] private MetalMaterialType m_Material = MetalMaterialType.Iron; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs index 3ccba73e770..7c326307072 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/PropertyNode.cs @@ -69,7 +69,7 @@ void AddOutputSlot() // keep existing slots, don't modify them return; } - switch(property.concreteShaderValueType) + switch (property.concreteShaderValueType) { case ConcreteSlotValueType.Boolean: AddSlot(new BooleanMaterialSlot(OutputSlotId, property.displayName, "Out", SlotType.Output, false)); @@ -192,9 +192,9 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo sb.AppendLine($"SamplerState {GetVariableNameForSlot(OutputSlotId)} = {property.referenceName};"); break; case PropertyType.Gradient: - if(generationMode == GenerationMode.Preview) + if (generationMode == GenerationMode.Preview) sb.AppendLine($"Gradient {GetVariableNameForSlot(OutputSlotId)} = {GradientUtil.GetGradientForPreview(property.referenceName)};"); - else + else sb.AppendLine($"Gradient {GetVariableNameForSlot(OutputSlotId)} = {property.referenceName};"); break; } @@ -202,7 +202,6 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public override string GetVariableNameForSlot(int slotId) { - // TODO: I don't like this exception list being buried in PropertyNode.cs, should be something on the ShaderProperty themselves... if (!(property is Texture2DShaderProperty) && !(property is Texture2DArrayShaderProperty) && diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/CameraNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/CameraNode.cs index 18e2eb370b8..a619d8e0151 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/CameraNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/CameraNode.cs @@ -30,7 +30,6 @@ public CameraNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector3.zero)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/FogNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/FogNode.cs index 5eec5424e6f..ad0822b8a3a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/FogNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/FogNode.cs @@ -11,7 +11,6 @@ public FogNode() name = "Fog"; } - public override bool hasPreview { get { return false; } } protected override MethodInfo GetFunctionToConvert() @@ -26,7 +25,7 @@ static string Unity_Fog( { Color = Vector4.zero; return - @" +@" { SHADERGRAPH_FOG(Position, Color, Density); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ObjectNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ObjectNode.cs index d2a3b719865..695e09fe261 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ObjectNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ObjectNode.cs @@ -18,7 +18,6 @@ public ObjectNode() UpdateNodeAfterDeserialization(); } - public override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector3.zero)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneColorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneColorNode.cs index 9e5c94c66f2..e038f51b0bb 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneColorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneColorNode.cs @@ -32,7 +32,7 @@ static string Unity_SceneColor( { Out = Vector3.one; return - @" +@" { Out = SHADERGRAPH_SAMPLE_SCENE_COLOR(UV.xy); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneDepthNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneDepthNode.cs index c37a18a5105..ebbfd44bf30 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneDepthNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/SceneDepthNode.cs @@ -31,7 +31,7 @@ public DepthSamplingMode depthSamplingMode set { if (m_DepthSamplingMode == value) - return ; + return; m_DepthSamplingMode = value; Dirty(ModificationScope.Graph); @@ -66,7 +66,7 @@ static string Unity_SceneDepth_Linear01( [Slot(1, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out) { return - @" +@" { Out = Linear01Depth(SHADERGRAPH_SAMPLE_SCENE_DEPTH(UV.xy), _ZBufferParams); } @@ -78,7 +78,7 @@ static string Unity_SceneDepth_Raw( [Slot(1, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out) { return - @" +@" { Out = SHADERGRAPH_SAMPLE_SCENE_DEPTH(UV.xy); } @@ -90,7 +90,7 @@ static string Unity_SceneDepth_Eye( [Slot(1, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out) { return - @" +@" { Out = LinearEyeDepth(SHADERGRAPH_SAMPLE_SCENE_DEPTH(UV.xy), _ZBufferParams); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ScreenNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ScreenNode.cs index 08e01ff9631..d8fd8a1ae63 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ScreenNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Scene/ScreenNode.cs @@ -18,7 +18,6 @@ public ScreenNode() UpdateNodeAfterDeserialization(); } - public override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, 0)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs index cd5b5e936d8..234b003ae49 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs @@ -20,7 +20,6 @@ public CubemapAssetNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new CubemapMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/ProceduralVirtualTextureNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/ProceduralVirtualTextureNode.cs index 04f8aa4bf76..0800d3be4ee 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/ProceduralVirtualTextureNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/ProceduralVirtualTextureNode.cs @@ -104,4 +104,3 @@ public AbstractShaderProperty AsShaderProperty() } #endif // PROCEDURAL_VT_IN_GRAPH } - diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs index c5d8d99dd42..bb03823aaf5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs @@ -30,7 +30,6 @@ public SampleCubemapNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero)); @@ -56,12 +55,12 @@ public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode gene var id = GetSlotValue(CubemapInputId, generationMode); string result = string.Format("$precision4 {0} = SAMPLE_TEXTURECUBE_LOD({1}, {2}, reflect(-{3}, {4}), {5});" - , GetVariableNameForSlot(OutputSlotId) - , id - , edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id - , GetSlotValue(ViewDirInputId, generationMode) - , GetSlotValue(NormalInputId, generationMode) - , GetSlotValue(LODInputId, generationMode)); + , GetVariableNameForSlot(OutputSlotId) + , id + , edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id + , GetSlotValue(ViewDirInputId, generationMode) + , GetSlotValue(NormalInputId, generationMode) + , GetSlotValue(LODInputId, generationMode)); sb.AppendLine(result); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleRawCubemapNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleRawCubemapNode.cs index 65c5025421f..9ba8594f09f 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleRawCubemapNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleRawCubemapNode.cs @@ -27,7 +27,6 @@ public SampleRawCubemapNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero)); @@ -52,11 +51,11 @@ public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode gene var id = GetSlotValue(CubemapInputId, generationMode); string result = string.Format("$precision4 {0} = SAMPLE_TEXTURECUBE_LOD({1}, {2}, {3}, {4});" - , GetVariableNameForSlot(OutputSlotId) - , id - , edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id - , GetSlotValue(NormalInputId, generationMode) - , GetSlotValue(LODInputId, generationMode)); + , GetVariableNameForSlot(OutputSlotId) + , id + , edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id + , GetSlotValue(NormalInputId, generationMode) + , GetSlotValue(LODInputId, generationMode)); sb.AppendLine(result); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DArrayNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DArrayNode.cs index 9cf55fca464..2dcf506f461 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DArrayNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DArrayNode.cs @@ -37,7 +37,6 @@ public SampleTexture2DArrayNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector4MaterialSlot(OutputSlotRGBAId, kOutputSlotRGBAName, kOutputSlotRGBAName, SlotType.Output, Vector4.zero, ShaderStageCapability.Fragment)); @@ -64,11 +63,11 @@ public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode gene var id = GetSlotValue(TextureInputId, generationMode); var result = string.Format("$precision4 {0} = SAMPLE_TEXTURE2D_ARRAY({1}, {2}, {3}, {4});" - , GetVariableNameForSlot(OutputSlotRGBAId) - , id - , edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id - , uvName - , indexName); + , GetVariableNameForSlot(OutputSlotRGBAId) + , id + , edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id + , uvName + , indexName); sb.AppendLine(result); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DLODNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DLODNode.cs index 5bf5af3b4e9..85ea9245b52 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DLODNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DLODNode.cs @@ -39,7 +39,6 @@ public SampleTexture2DLODNode() UpdateNodeAfterDeserialization(); } - [SerializeField] private TextureType m_TextureType = TextureType.Default; @@ -118,11 +117,11 @@ public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode gene sb.AppendLine("#else"); { var result = string.Format(" $precision4 {0} = SAMPLE_TEXTURE2D_LOD({1}, {2}, {3}, {4});" - , GetVariableNameForSlot(OutputSlotRGBAId) - , id - , edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id - , uvName - , lodSlot); + , GetVariableNameForSlot(OutputSlotRGBAId) + , id + , edgesSampler.Any() ? GetSlotValue(SamplerInputId, generationMode) : "sampler" + id + , uvName + , lodSlot); sb.AppendLine(result); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs index 7b49cc78a44..822fded228a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs @@ -42,7 +42,6 @@ public SampleTexture2DNode() UpdateNodeAfterDeserialization(); } - [SerializeField] private TextureType m_TextureType = TextureType.Default; @@ -110,10 +109,10 @@ public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode gene var id = GetSlotValue(TextureInputId, generationMode); var result = string.Format("$precision4 {0} = SAMPLE_TEXTURE2D({1}, {2}, {3});" - , GetVariableNameForSlot(OutputSlotRGBAId) - , id - , edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id - , uvName); + , GetVariableNameForSlot(OutputSlotRGBAId) + , id + , edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id + , uvName); sb.AppendLine(result); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture3DNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture3DNode.cs index 61855dca003..94a211d61cc 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture3DNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleTexture3DNode.cs @@ -26,7 +26,6 @@ public SampleTexture3DNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero, ShaderStageCapability.Fragment)); @@ -47,10 +46,10 @@ public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode gene var id = GetSlotValue(TextureInputId, generationMode); var result = string.Format("$precision4 {0} = SAMPLE_TEXTURE3D({1}, {2}, {3});" - , GetVariableNameForSlot(OutputSlotId) - , id - , edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id - , uvName); + , GetVariableNameForSlot(OutputSlotId) + , id + , edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id + , uvName); sb.AppendLine(result); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs index 9966eaa77b9..01572353d48 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SampleVirtualTextureNode.cs @@ -162,7 +162,7 @@ public bool noFeedback } public SampleVirtualTextureNode() : this(false, false) - { } + {} public SampleVirtualTextureNode(bool isLod = false, bool noResolve = false) { diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SamplerStateNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SamplerStateNode.cs index 8482b67af56..a8f67d46a0c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SamplerStateNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/SamplerStateNode.cs @@ -49,7 +49,6 @@ public SamplerStateNode() UpdateNodeAfterDeserialization(); } - public override bool hasPreview { get { return false; } } private const int kOutputSlotId = 0; @@ -83,15 +82,15 @@ public override void CollectShaderProperties(PropertyCollector properties, Gener public override string GetVariableNameForNode() { - return string.Format(@"{0}_{1}_{2}", NodeUtils.GetHLSLSafeName(name), - Enum.GetName(typeof(TextureSamplerState.FilterMode), filter), + return string.Format(@"{0}_{1}_{2}", NodeUtils.GetHLSLSafeName(name), + Enum.GetName(typeof(TextureSamplerState.FilterMode), filter), Enum.GetName(typeof(TextureSamplerState.WrapMode), wrap)); } public AbstractShaderProperty AsShaderProperty() { - return new SamplerStateShaderProperty - { + return new SamplerStateShaderProperty + { value = new TextureSamplerState() { filter = this.filter, diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs index 88605fb24ab..a25606a523e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/TexelSizeNode.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using UnityEngine; using UnityEditor.Graphing; using UnityEditor.ShaderGraph.Drawing.Controls; @@ -6,7 +6,6 @@ namespace UnityEditor.ShaderGraph { - [Title("Input", "Texture", "Texel Size")] class Texture2DPropertiesNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireMeshUV { @@ -25,7 +24,6 @@ public Texture2DPropertiesNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector1MaterialSlot(OutputSlotWId, kOutputSlotWName, kOutputSlotWName, SlotType.Output, 0, ShaderStageCapability.Fragment)); @@ -37,8 +35,8 @@ public sealed override void UpdateNodeAfterDeserialization() // Node generations public virtual void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { - sb.AppendLine(string.Format("$precision {0} = {1}_TexelSize.z;", GetVariableNameForSlot(OutputSlotWId), GetSlotValue(TextureInputId, generationMode))); - sb.AppendLine(string.Format("$precision {0} = {1}_TexelSize.w;", GetVariableNameForSlot(OutputSlotHId), GetSlotValue(TextureInputId, generationMode))); + sb.AppendLine(string.Format("$precision {0} = {1}_TexelSize.z;", GetVariableNameForSlot(OutputSlotWId), GetSlotValue(TextureInputId, generationMode))); + sb.AppendLine(string.Format("$precision {0} = {1}_TexelSize.w;", GetVariableNameForSlot(OutputSlotHId), GetSlotValue(TextureInputId, generationMode))); } public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs index 25cd7729554..a4a09021549 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DArrayAssetNode.cs @@ -20,7 +20,6 @@ public Texture2DArrayAssetNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Texture2DArrayMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs index bbb905af1a4..364840c731c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs @@ -20,7 +20,6 @@ public Texture2DAssetNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Texture2DMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture3DAssetNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture3DAssetNode.cs index c3b9585439f..6f8ffccc141 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture3DAssetNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Input/Texture/Texture3DAssetNode.cs @@ -20,7 +20,6 @@ public Texture3DAssetNode() UpdateNodeAfterDeserialization(); } - public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Texture3DMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs index f2b2da68515..734cc0ff270 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/LegacyUnknownTypeNode.cs @@ -27,6 +27,7 @@ public LegacyUnknownTypeNode() : base() serializedData = null; isValid = false; } + public LegacyUnknownTypeNode(string typeData, string serializedNodeData) : base() { serializedType = typeData; @@ -37,7 +38,6 @@ public LegacyUnknownTypeNode(string typeData, string serializedNodeData) : base( public override void OnAfterDeserialize(string json) { base.OnAfterDeserialize(json); - } public override void ValidateNode() @@ -47,4 +47,3 @@ public override void ValidateNode() } } } - diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/AbsoluteNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/AbsoluteNode.cs index 536213c8a1b..1f8095b69a1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/AbsoluteNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/AbsoluteNode.cs @@ -10,7 +10,6 @@ public AbsoluteNode() name = "Absolute"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Absolute", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Absolute( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = abs(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ExponentialNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ExponentialNode.cs index 56856bfc58c..c9a387884f1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ExponentialNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ExponentialNode.cs @@ -19,7 +19,6 @@ public ExponentialNode() name = "Exponential"; } - [SerializeField] private ExponentialBase m_ExponentialBase = ExponentialBase.BaseE; @@ -53,7 +52,7 @@ static string Unity_Exponential( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = exp(In); } @@ -65,7 +64,7 @@ static string Unity_Exponential2( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = exp2(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LengthNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LengthNode.cs index 4b9c63cc0ba..5c431994b47 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LengthNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LengthNode.cs @@ -10,7 +10,6 @@ public LengthNode() name = "Length"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Length", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Length( [Slot(1, Binding.None)] out Vector1 Out) { return - @" +@" { Out = length(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LogNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LogNode.cs index d6af2508a19..a3e3ac503e1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LogNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/LogNode.cs @@ -20,7 +20,6 @@ public LogNode() name = "Log"; } - [SerializeField] private LogBase m_LogBase = LogBase.BaseE; @@ -56,7 +55,7 @@ static string Unity_Log( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = log(In); } @@ -68,7 +67,7 @@ static string Unity_Log2( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = log2(In); } @@ -80,7 +79,7 @@ static string Unity_Log10( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = log10(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ModuloNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ModuloNode.cs index 33da66c667c..35c3379883b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ModuloNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ModuloNode.cs @@ -10,7 +10,6 @@ public ModuloNode() name = "Modulo"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Modulo", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Modulo( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = fmod(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NegateNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NegateNode.cs index daf3d19ed6c..023a25baae5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NegateNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NegateNode.cs @@ -10,7 +10,6 @@ public NegateNode() name = "Negate"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Negate", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Negate( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = -1 * In; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NormalizeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NormalizeNode.cs index d58ad2523f2..fa4bbfabce0 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NormalizeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/NormalizeNode.cs @@ -10,7 +10,6 @@ public NormalizeNode() name = "Normalize"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Normalize", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Normalize( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = normalize(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/PosterizeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/PosterizeNode.cs index cbf2127bf82..204bf62a6da 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/PosterizeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/PosterizeNode.cs @@ -10,7 +10,6 @@ public PosterizeNode() name = "Posterize"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Posterize", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Posterize( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = floor(In / (1 / Steps)) * (1 / Steps); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalNode.cs index 133fa5e1f6c..5d835ab7e5c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalNode.cs @@ -19,7 +19,6 @@ public ReciprocalNode() name = "Reciprocal"; } - [SerializeField] private ReciprocalMethod m_ReciprocalMethod = ReciprocalMethod.Default; @@ -53,7 +52,7 @@ static string Unity_Reciprocal( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 1.0/In; } @@ -65,7 +64,7 @@ static string Unity_Reciprocal_Fast( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = rcp(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalSquareRootNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalSquareRootNode.cs index c176c31860e..121b0a4db3b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalSquareRootNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Advanced/ReciprocalSquareRootNode.cs @@ -10,7 +10,6 @@ public ReciprocalSquareRootNode() name = "Reciprocal Square Root"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Rsqrt", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Rsqrt( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = rsqrt(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/AddNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/AddNode.cs index b43908e7937..4bb4f5ee174 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/AddNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/AddNode.cs @@ -21,7 +21,7 @@ static string Unity_Add( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = A + B; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/DivideNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/DivideNode.cs index 04f61eee311..fcd70719199 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/DivideNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/DivideNode.cs @@ -10,7 +10,6 @@ public DivideNode() name = "Divide"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Divide", BindingFlags.Static | BindingFlags.NonPublic); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs index 862454adf29..f36d4d0441a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs @@ -17,7 +17,6 @@ public MultiplyNode() UpdateNodeAfterDeserialization(); } - const int Input1SlotId = 0; const int Input2SlotId = 1; const int OutputSlotId = 2; @@ -69,25 +68,25 @@ string GetFunctionName() public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0}({1} A, {2} B, out {3} Out)", + GetFunctionHeader(), + FindInputSlot(Input1SlotId).concreteValueType.ToShaderString(), + FindInputSlot(Input2SlotId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0}({1} A, {2} B, out {3} Out)", - GetFunctionHeader(), - FindInputSlot(Input1SlotId).concreteValueType.ToShaderString(), - FindInputSlot(Input2SlotId).concreteValueType.ToShaderString(), - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) + switch (m_MultiplyType) { - switch (m_MultiplyType) - { - case MultiplyType.Vector: - s.AppendLine("Out = A * B;"); - break; - default: - s.AppendLine("Out = mul(A, B);"); - break; - } + case MultiplyType.Vector: + s.AppendLine("Out = A * B;"); + break; + default: + s.AppendLine("Out = mul(A, B);"); + break; } - }); + } + }); } // Internal validation @@ -95,7 +94,6 @@ public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode gener public override void EvaluateDynamicMaterialSlots() { - var dynamicInputSlotsToCompare = DictionaryPool.Get(); var skippedDynamicSlots = ListPool.Get(); @@ -241,7 +239,7 @@ public override void EvaluateDynamicMaterialSlots() tempSlots.Clear(); GetOutputSlots(tempSlots); - if(tempSlots.Any(x => x.hasError)) + if (tempSlots.Any(x => x.hasError)) { owner.AddConcretizationError(objectId, string.Format("Node {0} had output error", objectId)); hasError = true; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/PowerNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/PowerNode.cs index a303e0afa0a..457d946f9fc 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/PowerNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/PowerNode.cs @@ -10,7 +10,6 @@ public PowerNode() name = "Power"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Power", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Power( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = pow(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SquareRootNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SquareRootNode.cs index c439a397a00..48467bea054 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SquareRootNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SquareRootNode.cs @@ -10,7 +10,6 @@ public SquareRootNode() name = "Square Root"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_SquareRoot", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_SquareRoot( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = sqrt(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SubtractNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SubtractNode.cs index e4c7c7d3a14..70a3e5adcc1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SubtractNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Basic/SubtractNode.cs @@ -10,7 +10,6 @@ public SubtractNode() name = "Subtract"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Subtract", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Subtract( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = A - B; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXNode.cs index 45436948e38..c194eb35989 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXNode.cs @@ -11,7 +11,6 @@ public DDXNode() name = "DDX"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_DDX", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_DDX( [Slot(1, Binding.None, ShaderStageCapability.Fragment)] out DynamicDimensionVector Out) { return - @" +@" { Out = ddx(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXYNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXYNode.cs index 0325116d8d3..659961ee970 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXYNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDXYNode.cs @@ -11,7 +11,6 @@ public DDXYNode() name = "DDXY"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_DDXY", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_DDXY( [Slot(1, Binding.None, ShaderStageCapability.Fragment)] out DynamicDimensionVector Out) { return - @" +@" { Out = abs(ddx(In)) + abs(ddy(In)); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDYNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDYNode.cs index 55f09ca0a8d..b61baa8964c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDYNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Derivative/DDYNode.cs @@ -11,7 +11,6 @@ public DDYNode() name = "DDY"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_DDY", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_DDY( [Slot(1, Binding.None, ShaderStageCapability.Fragment)] out DynamicDimensionVector Out) { return - @" +@" { Out = ddy(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs index ffb5f57aa64..3a5156dc1e1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs @@ -10,7 +10,6 @@ public InverseLerpNode() name = "Inverse Lerp"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_InverseLerp", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string Unity_InverseLerp( [Slot(3, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = (T - A)/(B - A); }"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs index 448f484c5ad..720dc2a8ab3 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs @@ -10,7 +10,6 @@ public LerpNode() name = "Lerp"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Lerp", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string Unity_Lerp( [Slot(3, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = lerp(A, B, T); }"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs index a529627f3e4..7717d19cdaa 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs @@ -10,7 +10,6 @@ public SmoothstepNode() name = "Smoothstep"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Smoothstep", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string Unity_Smoothstep( [Slot(3, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = smoothstep(Edge1, Edge2, In); }"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixConstructionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixConstructionNode.cs index 90fda665287..3f06c5d6fa6 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixConstructionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixConstructionNode.cs @@ -30,7 +30,6 @@ public MatrixConstructionNode() UpdateNodeAfterDeserialization(); } - [SerializeField] MatrixAxis m_Axis; @@ -88,30 +87,30 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0} ({1} M0, {1} M1, {1} M2, {1} M3, out {2} Out4x4, out {3} Out3x3, out {4} Out2x2)", + GetFunctionName(), + FindInputSlot(InputSlotM0Id).concreteValueType.ToShaderString(), + FindOutputSlot(Output4x4SlotId).concreteValueType.ToShaderString(), + FindOutputSlot(Output3x3SlotId).concreteValueType.ToShaderString(), + FindOutputSlot(Output2x2SlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0} ({1} M0, {1} M1, {1} M2, {1} M3, out {2} Out4x4, out {3} Out3x3, out {4} Out2x2)", - GetFunctionName(), - FindInputSlot(InputSlotM0Id).concreteValueType.ToShaderString(), - FindOutputSlot(Output4x4SlotId).concreteValueType.ToShaderString(), - FindOutputSlot(Output3x3SlotId).concreteValueType.ToShaderString(), - FindOutputSlot(Output2x2SlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) + switch (m_Axis) { - switch (m_Axis) - { - case MatrixAxis.Column: - s.AppendLine("Out4x4 = $precision4x4(M0.x, M1.x, M2.x, M3.x, M0.y, M1.y, M2.y, M3.y, M0.z, M1.z, M2.z, M3.z, M0.w, M1.w, M2.w, M3.w);"); - s.AppendLine("Out3x3 = $precision3x3(M0.x, M1.x, M2.x, M0.y, M1.y, M2.y, M0.z, M1.z, M2.z);"); - s.AppendLine("Out2x2 = $precision2x2(M0.x, M1.x, M0.y, M1.y);"); - break; - default: - s.AppendLine("Out4x4 = $precision4x4(M0.x, M0.y, M0.z, M0.w, M1.x, M1.y, M1.z, M1.w, M2.x, M2.y, M2.z, M2.w, M3.x, M3.y, M3.z, M3.w);"); - s.AppendLine("Out3x3 = $precision3x3(M0.x, M0.y, M0.z, M1.x, M1.y, M1.z, M2.x, M2.y, M2.z);"); - s.AppendLine("Out2x2 = $precision2x2(M0.x, M0.y, M1.x, M1.y);"); - break; - } + case MatrixAxis.Column: + s.AppendLine("Out4x4 = $precision4x4(M0.x, M1.x, M2.x, M3.x, M0.y, M1.y, M2.y, M3.y, M0.z, M1.z, M2.z, M3.z, M0.w, M1.w, M2.w, M3.w);"); + s.AppendLine("Out3x3 = $precision3x3(M0.x, M1.x, M2.x, M0.y, M1.y, M2.y, M0.z, M1.z, M2.z);"); + s.AppendLine("Out2x2 = $precision2x2(M0.x, M1.x, M0.y, M1.y);"); + break; + default: + s.AppendLine("Out4x4 = $precision4x4(M0.x, M0.y, M0.z, M0.w, M1.x, M1.y, M1.z, M1.w, M2.x, M2.y, M2.z, M2.w, M3.x, M3.y, M3.z, M3.w);"); + s.AppendLine("Out3x3 = $precision3x3(M0.x, M0.y, M0.z, M1.x, M1.y, M1.z, M2.x, M2.y, M2.z);"); + s.AppendLine("Out2x2 = $precision2x2(M0.x, M0.y, M1.x, M1.y);"); + break; } - }); + } + }); } } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixDeterminantNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixDeterminantNode.cs index 9e93272623d..27f5dc18d07 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixDeterminantNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixDeterminantNode.cs @@ -23,7 +23,7 @@ static string Unity_MatrixDeterminant( [Slot(1, Binding.None)] out Vector1 Out) { return - @" +@" { Out = determinant(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixSplitNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixSplitNode.cs index a90ed726a03..f1c5ff8e101 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixSplitNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixSplitNode.cs @@ -35,7 +35,6 @@ public MatrixSplitNode() UpdateNodeAfterDeserialization(); } - [SerializeField] MatrixAxis m_Axis; @@ -239,7 +238,7 @@ public override void EvaluateDynamicMaterialSlots() tempSlots.Clear(); GetOutputSlots(tempSlots); - if(tempSlots.Any(x => x.hasError)) + if (tempSlots.Any(x => x.hasError)) { owner.AddConcretizationError(objectId, string.Format("Node {0} had output error", objectId)); hasError = true; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixTransposeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixTransposeNode.cs index 348319cc662..6a68bb6a62b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixTransposeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Matrix/MatrixTransposeNode.cs @@ -11,7 +11,6 @@ public MatrixTransposeNode() name = "Matrix Transpose"; } - public override bool hasPreview { get { return false; } @@ -27,7 +26,7 @@ static string Unity_MatrixTranspose( [Slot(1, Binding.None)] out DynamicDimensionMatrix Out) { return - @" +@" { Out = transpose(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/ClampNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/ClampNode.cs index c0ed1ddc64f..2e85890cee2 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/ClampNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/ClampNode.cs @@ -10,7 +10,6 @@ public ClampNode() name = "Clamp"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Clamp", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string Unity_Clamp( [Slot(3, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = clamp(In, Min, Max); }"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/FractionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/FractionNode.cs index 90dfc94f08e..e969b193e14 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/FractionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/FractionNode.cs @@ -10,7 +10,6 @@ public FractionNode() name = "Fraction"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Fraction", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Fraction( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = frac(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MaximumNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MaximumNode.cs index dd3ebfb4d4c..56b94d64921 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MaximumNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MaximumNode.cs @@ -10,7 +10,6 @@ public MaximumNode() name = "Maximum"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Maximum", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Maximum( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = max(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MinimumNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MinimumNode.cs index 4307c2778f8..5c2bb82697a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MinimumNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/MinimumNode.cs @@ -10,7 +10,6 @@ public MinimumNode() name = "Minimum"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Minimum", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Minimum( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = min(A, B); };"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/OneMinusNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/OneMinusNode.cs index cd358b3536b..2c9be9a84b5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/OneMinusNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/OneMinusNode.cs @@ -10,7 +10,6 @@ public OneMinusNode() name = "One Minus"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_OneMinus", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_OneMinus( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 1 - In; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RandomRangeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RandomRangeNode.cs index d532d2bc6e5..875c9bc205d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RandomRangeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RandomRangeNode.cs @@ -11,7 +11,6 @@ public RandomRangeNode() name = "Random Range"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_RandomRange", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_RandomRange( [Slot(3, Binding.None)] out Vector1 Out) { return - @" +@" { $precision randomno = frac(sin(dot(Seed, $precision2(12.9898, 78.233)))*43758.5453); Out = lerp(Min, Max, randomno); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RemapNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RemapNode.cs index 379d599384b..1c6c8421071 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RemapNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/RemapNode.cs @@ -11,7 +11,6 @@ public RemapNode() name = "Remap"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Remap", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_Remap( [Slot(3, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = OutMinMax.x + (In - InMinMax.x) * (OutMinMax.y - OutMinMax.x) / (InMinMax.y - InMinMax.x); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/SaturateNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/SaturateNode.cs index 1e0ea802d0c..d378d6d3bc0 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/SaturateNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Range/SaturateNode.cs @@ -10,7 +10,6 @@ public SaturateNode() name = "Saturate"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Saturate", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Saturate( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = saturate(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/CeilingNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/CeilingNode.cs index a345fbc4f7d..a7d029107be 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/CeilingNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/CeilingNode.cs @@ -10,7 +10,6 @@ public CeilingNode() name = "Ceiling"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Ceiling", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Ceiling( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = ceil(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/FloorNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/FloorNode.cs index 4d5c807cf39..c05d1821950 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/FloorNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/FloorNode.cs @@ -10,7 +10,6 @@ public FloorNode() name = "Floor"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Floor", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Floor( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = floor(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/RoundNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/RoundNode.cs index 7b5b3e3c070..b843948c79d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/RoundNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/RoundNode.cs @@ -10,7 +10,6 @@ public RoundNode() name = "Round"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Round", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Round( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = round(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/SignNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/SignNode.cs index 045d2e65e6d..25d549cf9ea 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/SignNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/SignNode.cs @@ -10,7 +10,6 @@ public SignNode() name = "Sign"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Sign", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Sign( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = sign(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/StepNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/StepNode.cs index efb60069d29..6c2beb04c3e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/StepNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/StepNode.cs @@ -10,7 +10,6 @@ public StepNode() name = "Step"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Step", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Step( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = step(Edge, In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/TruncateNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/TruncateNode.cs index ceb1834e4d0..083b028e477 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/TruncateNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/TruncateNode.cs @@ -10,7 +10,6 @@ public TruncateNode() name = "Truncate"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Truncate", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Truncate( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = trunc(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArccosineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArccosineNode.cs index 6aa1c8477b3..dad2b3e1343 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArccosineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArccosineNode.cs @@ -10,7 +10,6 @@ public ArccosineNode() name = "Arccosine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Arccosine", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Arccosine( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = acos(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArcsineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArcsineNode.cs index 8643d047c00..f45503f616a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArcsineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArcsineNode.cs @@ -10,7 +10,6 @@ public ArcsineNode() name = "Arcsine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Arcsine", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Arcsine( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = asin(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/Arctangent2Node.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/Arctangent2Node.cs index d20fa848d8b..c59e3b133c7 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/Arctangent2Node.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/Arctangent2Node.cs @@ -10,7 +10,6 @@ public Arctangent2Node() name = "Arctangent2"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Arctangent2", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Arctangent2( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = atan2(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArctangentNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArctangentNode.cs index 0b1b0dbfa0f..18a1d4b098e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArctangentNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/ArctangentNode.cs @@ -10,7 +10,6 @@ public ArctangentNode() name = "Arctangent"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Arctangent", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Arctangent( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = atan(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/CosineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/CosineNode.cs index 4470554625d..95330cb8ccb 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/CosineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/CosineNode.cs @@ -10,7 +10,6 @@ public CosineNode() name = "Cosine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Cosine", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Cosine( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = cos(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/DegreesToRadiansNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/DegreesToRadiansNode.cs index a06f72b70c9..ae14acdc574 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/DegreesToRadiansNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/DegreesToRadiansNode.cs @@ -10,7 +10,6 @@ public DegreesToRadiansNode() name = "Degrees To Radians"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_DegreesToRadians", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_DegreesToRadians( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = radians(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicCosineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicCosineNode.cs index b9bf706617d..e62ad0f465d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicCosineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicCosineNode.cs @@ -10,7 +10,6 @@ public HyperbolicCosineNode() name = "Hyperbolic Cosine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_HyperbolicCosine", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_HyperbolicCosine( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = sinh(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicSineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicSineNode.cs index 0985705be38..50fdaacd2da 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicSineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicSineNode.cs @@ -10,7 +10,6 @@ public HyperbolicSineNode() name = "Hyperbolic Sine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_HyperbolicSine", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_HyperbolicSine( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = sinh(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicTangentNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicTangentNode.cs index 31bf63c247e..ad8602cdb4e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicTangentNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/HyperbolicTangentNode.cs @@ -10,7 +10,6 @@ public HyperbolicTangentNode() name = "Hyperbolic Tangent"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_HyperbolicTangent", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_HyperbolicTangent( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = tanh(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/RadiansToDegreesNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/RadiansToDegreesNode.cs index c782546c7fc..97bb38a4291 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/RadiansToDegreesNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/RadiansToDegreesNode.cs @@ -10,7 +10,6 @@ public RadiansToDegreesNode() name = "Radians To Degrees"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_RadiansToDegrees", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_RadiansToDegrees( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = degrees(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/SineNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/SineNode.cs index 313f0ef0751..d1db2ce4089 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/SineNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/SineNode.cs @@ -10,7 +10,6 @@ public SineNode() name = "Sine"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Sine", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Sine( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = sin(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/TangentNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/TangentNode.cs index 1c1d6a98973..106a8c37e5a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/TangentNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Trigonometry/TangentNode.cs @@ -10,7 +10,6 @@ public TangentNode() name = "Tangent"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Tangent", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string Unity_Tangent( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = tan(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/CrossProductNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/CrossProductNode.cs index 254e27c5531..60c765e309d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/CrossProductNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/CrossProductNode.cs @@ -11,7 +11,6 @@ public CrossProductNode() name = "Cross Product"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_CrossProduct", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_CrossProduct( { Out = Vector3.zero; return - @" +@" { Out = cross(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DistanceNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DistanceNode.cs index ab7eded00e9..f0a61f95eaa 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DistanceNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DistanceNode.cs @@ -10,7 +10,6 @@ public DistanceNode() name = "Distance"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Distance", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Distance( [Slot(2, Binding.None)] out Vector1 Out) { return - @" +@" { Out = distance(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DotProductNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DotProductNode.cs index 17517d3849f..95657ca205a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DotProductNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/DotProductNode.cs @@ -11,7 +11,6 @@ public DotProductNode() name = "Dot Product"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_DotProduct", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string Unity_DotProduct( [Slot(2, Binding.None)] out Vector1 Out) { return - @" +@" { Out = dot(A, B); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/FresnelEffectNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/FresnelEffectNode.cs index ad4777be9e6..9b7ebc6d98e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/FresnelEffectNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/FresnelEffectNode.cs @@ -11,7 +11,6 @@ public FresnelNode() name = "Fresnel Effect"; } - public override PreviewMode previewMode { get { return PreviewMode.Preview3D; } @@ -29,7 +28,7 @@ static string Unity_FresnelEffect( [Slot(3, Binding.None)] out Vector1 Out) { return - @" +@" { Out = pow((1.0 - saturate(dot(normalize(Normal), normalize(ViewDir)))), Power); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ProjectionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ProjectionNode.cs index fe7db9499e2..50deb4c18ae 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ProjectionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ProjectionNode.cs @@ -10,7 +10,6 @@ public ProjectionNode() name = "Projection"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Projection", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Projection( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = B * dot(A, B) / dot(B, B); }"; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ReflectionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ReflectionNode.cs index 2ac330ccdb3..edfe340f463 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ReflectionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/ReflectionNode.cs @@ -11,7 +11,6 @@ public ReflectionNode() name = "Reflection"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Reflection", BindingFlags.Static | BindingFlags.NonPublic); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RejectionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RejectionNode.cs index a74c5fd687d..a9988ef9d4c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RejectionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RejectionNode.cs @@ -10,7 +10,6 @@ public RejectionNode() name = "Rejection"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Rejection", BindingFlags.Static | BindingFlags.NonPublic); @@ -22,7 +21,7 @@ static string Unity_Rejection( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = A - (B * dot(A, B) / dot(B, B)); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RotateAboutAxisNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RotateAboutAxisNode.cs index 7d2e743d0ef..9856dae5685 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RotateAboutAxisNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/RotateAboutAxisNode.cs @@ -30,7 +30,6 @@ public RotateAboutAxisNode() name = "Rotate About Axis"; } - protected override MethodInfo GetFunctionToConvert() { if (m_Unit == RotationUnit.Radians) @@ -47,14 +46,14 @@ static string Unity_Rotate_About_Axis_Degrees( { Out = In; return - @" +@" { Rotation = radians(Rotation); $precision s = sin(Rotation); $precision c = cos(Rotation); $precision one_minus_c = 1.0 - c; - + Axis = normalize(Axis); $precision3x3 rot_mat = { one_minus_c * Axis.x * Axis.x + c, one_minus_c * Axis.x * Axis.y - Axis.z * s, one_minus_c * Axis.z * Axis.x + Axis.y * s, @@ -75,12 +74,12 @@ static string Unity_Rotate_About_Axis_Radians( { Out = In; return - @" +@" { $precision s = sin(Rotation); $precision c = cos(Rotation); $precision one_minus_c = 1.0 - c; - + Axis = normalize(Axis); $precision3x3 rot_mat = { one_minus_c * Axis.x * Axis.x + c, one_minus_c * Axis.x * Axis.y - Axis.z * s, one_minus_c * Axis.z * Axis.x + Axis.y * s, diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/TransformNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/TransformNode.cs index 96f3a28e501..728e6a30d0b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/TransformNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Vector/TransformNode.cs @@ -51,7 +51,6 @@ public TransformNode() UpdateNodeAfterDeserialization(); } - [SerializeField] CoordinateSpaceConversion m_Conversion = new CoordinateSpaceConversion(CoordinateSpace.Object, CoordinateSpace.World); @@ -238,14 +237,14 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo else if (requiresTangentTransform) sb.AppendLine(string.Format("$precision3x3 {0} = $precision3x3(IN.{1}SpaceTangent, IN.{1}SpaceBiTangent, IN.{1}SpaceNormal);", targetTransformString, tangentTransformSpace)); sb.AppendLine("{0} {1} = {2};", FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString(), - GetVariableNameForSlot(OutputSlotId), - transformString); + GetVariableNameForSlot(OutputSlotId), + transformString); } bool RequiresWorldSpaceTangentTransform() { if (conversion.from == CoordinateSpace.View && conversion.to == CoordinateSpace.Tangent - || conversion.from == CoordinateSpace.AbsoluteWorld + || conversion.from == CoordinateSpace.AbsoluteWorld || conversion.from == CoordinateSpace.Object && conversion.to == CoordinateSpace.Tangent || conversion.from == CoordinateSpace.Tangent) return true; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/NoiseSineWaveNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/NoiseSineWaveNode.cs index aa99d62627e..c81e493498b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/NoiseSineWaveNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/NoiseSineWaveNode.cs @@ -1,4 +1,4 @@ -using UnityEngine; +using UnityEngine; using System.Reflection; namespace UnityEditor.ShaderGraph @@ -11,7 +11,6 @@ public NoiseSineWaveNode() name = "Noise Sine Wave"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("NoiseSineWave", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string NoiseSineWave( [Slot(2, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { $precision sinIn = sin(In); $precision sinInOffset = sin(In + 1.0); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SawtoothWaveNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SawtoothWaveNode.cs index 1410274cefa..3917283c36e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SawtoothWaveNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SawtoothWaveNode.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; namespace UnityEditor.ShaderGraph { @@ -10,7 +10,6 @@ public SawtoothWaveNode() name = "Sawtooth Wave"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("SawtoothWave", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string SawtoothWave( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 2 * (In - floor(0.5 + In)); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SquareWaveNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SquareWaveNode.cs index 759de6027ea..18fc61f922e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SquareWaveNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/SquareWaveNode.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; namespace UnityEditor.ShaderGraph { @@ -10,7 +10,6 @@ public SquareWaveNode() name = "Square Wave"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("SquareWave", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string SquareWave( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 1.0 - 2.0 * round(frac(In)); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/TriangleWaveNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/TriangleWaveNode.cs index 03c5876c50a..c68b707479d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/TriangleWaveNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Math/Wave/TriangleWaveNode.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; namespace UnityEditor.ShaderGraph { @@ -10,7 +10,6 @@ public TriangleWaveNode() name = "Triangle Wave"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("TriangleWave", BindingFlags.Static | BindingFlags.NonPublic); @@ -21,7 +20,7 @@ static string TriangleWave( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = 2.0 * abs( 2 * (In - floor(0.5 + In)) ) - 1.0; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/ComputeDeformNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/ComputeDeformNode.cs index 52d68ca293b..4acf1f6326a 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/ComputeDeformNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/ComputeDeformNode.cs @@ -98,10 +98,10 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo if (generationMode == GenerationMode.ForReals) { sb.AppendLine($"{GetFunctionName()}(" + - $"IN.VertexID, " + - $"{GetVariableNameForSlot(kPositionOutputSlotId)}, " + - $"{GetVariableNameForSlot(kNormalOutputSlotId)}, " + - $"{GetVariableNameForSlot(kTangentOutputSlotId)});"); + $"IN.VertexID, " + + $"{GetVariableNameForSlot(kPositionOutputSlotId)}, " + + $"{GetVariableNameForSlot(kNormalOutputSlotId)}, " + + $"{GetVariableNameForSlot(kTangentOutputSlotId)});"); } #if ENABLE_HYBRID_RENDERER_V2 sb.AppendLine("#else"); @@ -131,10 +131,10 @@ public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode gener registry.ProvideFunction(GetFunctionName(), sb => { sb.AppendLine($"void {GetFunctionName()}(" + - "uint vertexID, " + - "out $precision3 positionOut, " + - "out $precision3 normalOut, " + - "out $precision3 tangentOut)"); + "uint vertexID, " + + "out $precision3 positionOut, " + + "out $precision3 normalOut, " + + "out $precision3 tangentOut)"); sb.AppendLine("{"); using (sb.IndentScope()) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/LinearBlendSkinningNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/LinearBlendSkinningNode.cs index 07ef17636dd..41c67d8364d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/LinearBlendSkinningNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/MeshDeformation/LinearBlendSkinningNode.cs @@ -110,14 +110,14 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo if (generationMode == GenerationMode.ForReals) { sb.AppendLine($"{GetFunctionName()}(" + - $"IN.BoneIndices, " + - $"IN.BoneWeights, " + - $"{GetSlotValue(kPositionSlotId, generationMode)}, " + - $"{GetSlotValue(kNormalSlotId, generationMode)}, " + - $"{GetSlotValue(kTangentSlotId, generationMode)}, " + - $"{GetVariableNameForSlot(kPositionOutputSlotId)}, " + - $"{GetVariableNameForSlot(kNormalOutputSlotId)}, " + - $"{GetVariableNameForSlot(kTangentOutputSlotId)});"); + $"IN.BoneIndices, " + + $"IN.BoneWeights, " + + $"{GetSlotValue(kPositionSlotId, generationMode)}, " + + $"{GetSlotValue(kNormalSlotId, generationMode)}, " + + $"{GetSlotValue(kTangentSlotId, generationMode)}, " + + $"{GetVariableNameForSlot(kPositionOutputSlotId)}, " + + $"{GetVariableNameForSlot(kNormalOutputSlotId)}, " + + $"{GetVariableNameForSlot(kTangentOutputSlotId)});"); } #if ENABLE_HYBRID_RENDERER_V2 sb.AppendLine("#else"); @@ -138,21 +138,21 @@ public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode gener registry.ProvideFunction(GetFunctionName(), sb => { sb.AppendLine($"void {GetFunctionName()}(" + - "uint4 indices, " + - "$precision4 weights, " + - "$precision3 positionIn, " + - "$precision3 normalIn, " + - "$precision3 tangentIn, " + - "out $precision3 positionOut, " + - "out $precision3 normalOut, " + - "out $precision3 tangentOut)"); + "uint4 indices, " + + "$precision4 weights, " + + "$precision3 positionIn, " + + "$precision3 normalIn, " + + "$precision3 tangentIn, " + + "out $precision3 positionOut, " + + "out $precision3 normalOut, " + + "out $precision3 tangentOut)"); sb.AppendLine("{"); using (sb.IndentScope()) { sb.AppendLine("for (int i = 0; i < 4; ++i)"); sb.AppendLine("{"); using (sb.IndentScope()) - { + { #if HYBRID_RENDERER_0_6_0_OR_NEWER sb.AppendLine("$precision3x4 skinMatrix = _SkinMatrices[indices[i] + asint(_SkinMatrixIndex)];"); #else diff --git a/com.unity.shadergraph/Editor/Data/Nodes/NodeClassCache.cs b/com.unity.shadergraph/Editor/Data/Nodes/NodeClassCache.cs index d6548b312fe..3b45a9d30e3 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/NodeClassCache.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/NodeClassCache.cs @@ -9,7 +9,7 @@ namespace UnityEditor.ShaderGraph [InitializeOnLoad] internal static class NodeClassCache { - private static Dictionary> m_KnownTypeLookupTable; + private static Dictionary> m_KnownTypeLookupTable; public static IEnumerable knownNodeTypes { @@ -36,9 +36,9 @@ public static IEnumerable GetFilterableAttributesOnN public static T GetAttributeOnNodeType(Type nodeType) where T : ContextFilterableAttribute { var filterableAttributes = GetFilterableAttributesOnNodeType(nodeType); - foreach(var attr in filterableAttributes) + foreach (var attr in filterableAttributes) { - if(attr is T searchTypeAttr) + if (attr is T searchTypeAttr) { return searchTypeAttr; } @@ -51,32 +51,32 @@ private static void ReCacheKnownNodeTypes() Profiler.BeginSample("NodeClassCache: Re-caching all known node types"); m_KnownTypeLookupTable = new Dictionary>(); foreach (Type nodeType in TypeCache.GetTypesDerivedFrom()) - { - if (!nodeType.IsAbstract) - { - List filterableAttributes = new List(); - foreach(Attribute attribute in Attribute.GetCustomAttributes(nodeType)) - { - Type attributeType = attribute.GetType(); - if(!attributeType.IsAbstract && attribute is ContextFilterableAttribute contextFilterableAttribute) - { - filterableAttributes.Add(contextFilterableAttribute); - } - } - m_KnownTypeLookupTable.Add(nodeType,filterableAttributes); - } + { + if (!nodeType.IsAbstract) + { + List filterableAttributes = new List(); + foreach (Attribute attribute in Attribute.GetCustomAttributes(nodeType)) + { + Type attributeType = attribute.GetType(); + if (!attributeType.IsAbstract && attribute is ContextFilterableAttribute contextFilterableAttribute) + { + filterableAttributes.Add(contextFilterableAttribute); + } + } + m_KnownTypeLookupTable.Add(nodeType, filterableAttributes); + } } Profiler.EndSample(); } private static void DebugPrintKnownNodes() { - foreach(var entry in m_KnownTypeLookupTable) + foreach (var entry in m_KnownTypeLookupTable) { var nodeType = entry.Key; var filterableAttributes = entry.Value; String attrs = ""; - foreach(var filterable in filterableAttributes) + foreach (var filterable in filterableAttributes) { attrs += filterable.ToString() + ", "; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/CheckerboardNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/CheckerboardNode.cs index 1b1105bbd35..34f16fe19e4 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/CheckerboardNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/CheckerboardNode.cs @@ -11,7 +11,6 @@ public CheckerboardNode() name = "Checkerboard"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Checkerboard", BindingFlags.Static | BindingFlags.NonPublic); @@ -26,7 +25,7 @@ static string Unity_Checkerboard( { Out = Vector2.zero; return - @" +@" { UV = (UV.xy + 0.5) * Frequency; $precision4 derivatives = $precision4(ddx(UV), ddy(UV)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/GradientNoiseNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/GradientNoiseNode.cs index 79a74d53a20..0f43cf276ee 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/GradientNoiseNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/GradientNoiseNode.cs @@ -11,7 +11,6 @@ public GradientNoiseNode() name = "Gradient Noise"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_GradientNoise", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,8 +22,8 @@ static string Unity_GradientNoise( [Slot(2, Binding.None)] out Vector1 Out) { return - @" -{ +@" +{ $precision2 p = UV * Scale; $precision2 ip = floor(p); $precision2 fp = frac(p); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/SimpleNoiseNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/SimpleNoiseNode.cs index 654c5a6dbec..8ab49320628 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/SimpleNoiseNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/SimpleNoiseNode.cs @@ -11,7 +11,6 @@ public NoiseNode() name = "Simple Noise"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_SimpleNoise", BindingFlags.Static | BindingFlags.NonPublic); @@ -23,7 +22,7 @@ static string Unity_SimpleNoise( [Slot(2, Binding.None)] out Vector1 Out) { return - @" +@" { $precision t = 0.0; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/VoronoiNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/VoronoiNode.cs index a9a82084fc7..e33469299a1 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/VoronoiNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Noise/VoronoiNode.cs @@ -25,7 +25,7 @@ static string Unity_Voronoi( [Slot(4, Binding.None)] out Vector1 Cells) { return - @" +@" { $precision2 g = floor(UV * CellDensity); $precision2 f = frac(UV * CellDensity); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/EllipseNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/EllipseNode.cs index 7d7d5563872..c3c1fcc8757 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/EllipseNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/EllipseNode.cs @@ -11,7 +11,6 @@ public EllipseNode() name = "Ellipse"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Ellipse", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_Ellipse( [Slot(4, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out) { return - @" +@" { $precision d = length((UV * 2 - 1) / $precision2(Width, Height)); Out = saturate((1 - d) / fwidth(d)); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/PolygonNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/PolygonNode.cs index 2e4933d7c4d..e88ea336f0d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/PolygonNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/PolygonNode.cs @@ -11,7 +11,6 @@ public PolygonNode() name = "Polygon"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Polygon", BindingFlags.Static | BindingFlags.NonPublic); @@ -25,7 +24,7 @@ static string Unity_Polygon( [Slot(4, Binding.None, ShaderStageCapability.Fragment)] out DynamicDimensionVector Out) { return - @" +@" { $precision pi = 3.14159265359; $precision aWidth = Width * cos(pi / Sides); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RectangleNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RectangleNode.cs index 2d67f3a4dc3..b96ddda6c45 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RectangleNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RectangleNode.cs @@ -11,7 +11,6 @@ public RectangleNode() name = "Rectangle"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Rectangle", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_Rectangle( [Slot(3, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out) { return - @" +@" { $precision2 d = abs(UV * 2 - 1) - $precision2(Width, Height); d = 1 - d / fwidth(d); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RoundedRectangleNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RoundedRectangleNode.cs index 4a88cfbe261..0f16e323af5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RoundedRectangleNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Procedural/Shape/RoundedRectangleNode.cs @@ -11,7 +11,6 @@ public RoundedRectangleNode() name = "Rounded Rectangle"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_RoundedRectangle", BindingFlags.Static | BindingFlags.NonPublic); @@ -25,7 +24,7 @@ static string Unity_RoundedRectangle( [Slot(4, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out) { return - @" +@" { Radius = max(min(min(abs(Radius * 2), abs(Width)), abs(Height)), 1e-5); $precision2 uv = abs(UV * 2 - 1) - $precision2(Width, Height) + Radius; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs b/com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs index a7014d16e90..320b653c964 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/SlotValue.cs @@ -138,11 +138,11 @@ public static bool AreCompatible(SlotValueType inputType, ConcreteSlotValueType {ConcreteSlotValueType.Vector3, validVectors}, {ConcreteSlotValueType.Vector4, validVectors}, {ConcreteSlotValueType.Matrix2, new List() - {SlotValueType.Dynamic, SlotValueType.DynamicMatrix, SlotValueType.Matrix2}}, + {SlotValueType.Dynamic, SlotValueType.DynamicMatrix, SlotValueType.Matrix2}}, {ConcreteSlotValueType.Matrix3, new List() - {SlotValueType.Dynamic, SlotValueType.DynamicMatrix, SlotValueType.Matrix2, SlotValueType.Matrix3}}, + {SlotValueType.Dynamic, SlotValueType.DynamicMatrix, SlotValueType.Matrix2, SlotValueType.Matrix3}}, {ConcreteSlotValueType.Matrix4, new List() - {SlotValueType.Dynamic, SlotValueType.DynamicMatrix, SlotValueType.Matrix2, SlotValueType.Matrix3, SlotValueType.Matrix4}}, + {SlotValueType.Dynamic, SlotValueType.DynamicMatrix, SlotValueType.Matrix2, SlotValueType.Matrix3, SlotValueType.Matrix4}}, {ConcreteSlotValueType.Texture2D, new List() {SlotValueType.Texture2D}}, {ConcreteSlotValueType.Texture3D, new List() {SlotValueType.Texture3D}}, {ConcreteSlotValueType.Texture2DArray, new List() {SlotValueType.Texture2DArray}}, @@ -153,7 +153,7 @@ public static bool AreCompatible(SlotValueType inputType, ConcreteSlotValueType }; } - if(s_ValidConversions.TryGetValue(outputType, out s_ValidSlotTypes)) + if (s_ValidConversions.TryGetValue(outputType, out s_ValidSlotTypes)) { return s_ValidSlotTypes.Contains(inputType); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/FlipbookNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/FlipbookNode.cs index 379c37081de..69f08059935 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/FlipbookNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/FlipbookNode.cs @@ -17,7 +17,6 @@ public FlipbookNode() UpdateNodeAfterDeserialization(); } - const int UVSlotId = 0; const int WidthSlotId = 1; const int HeightSlotId = 2; @@ -38,11 +37,11 @@ string GetFunctionName() { string invertText = string.Empty; - if(m_InvertX && m_InvertY) + if (m_InvertX && m_InvertY) invertText = "InvertXY_"; - else if(m_InvertX) + else if (m_InvertX) invertText = "InvertX_"; - else if(m_InvertY) + else if (m_InvertY) invertText = "InvertY_"; return $"Unity_Flipbook_{invertText}{concretePrecision.ToShaderString()}"; @@ -134,39 +133,38 @@ public override void CollectShaderProperties(PropertyCollector properties, Gener public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("void {0} ({1} UV, {2} Width, {3} Height, {4} Tile, $precision2 Invert, out {5} Out)", + GetFunctionName(), + FindInputSlot(UVSlotId).concreteValueType.ToShaderString(), + FindInputSlot(WidthSlotId).concreteValueType.ToShaderString(), + FindInputSlot(HeightSlotId).concreteValueType.ToShaderString(), + FindInputSlot(TileSlotId).concreteValueType.ToShaderString(), + FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); + using (s.BlockScope()) { - s.AppendLine("void {0} ({1} UV, {2} Width, {3} Height, {4} Tile, $precision2 Invert, out {5} Out)", - GetFunctionName(), - FindInputSlot(UVSlotId).concreteValueType.ToShaderString(), - FindInputSlot(WidthSlotId).concreteValueType.ToShaderString(), - FindInputSlot(HeightSlotId).concreteValueType.ToShaderString(), - FindInputSlot(TileSlotId).concreteValueType.ToShaderString(), - FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString()); - using (s.BlockScope()) + string offset; + if (concretePrecision == ConcretePrecision.Half) { - string offset; - if (concretePrecision == ConcretePrecision.Half) - { - offset = "0.00001h"; - } - else - { - offset = "0.000001"; - } - - s.AppendLine("Tile = floor(fmod(Tile + " + offset + ", Width*Height));"); - s.AppendLine("$precision2 tileCount = $precision2(1.0, 1.0) / $precision2(Width, Height);"); - - AppendInvertSpecificLines(s); - - s.AppendLine("Out = (UV + $precision2(tileX, tileY)) * tileCount;"); + offset = "0.00001h"; } - }); + else + { + offset = "0.000001"; + } + + s.AppendLine("Tile = floor(fmod(Tile + " + offset + ", Width*Height));"); + s.AppendLine("$precision2 tileCount = $precision2(1.0, 1.0) / $precision2(Width, Height);"); + + AppendInvertSpecificLines(s); + + s.AppendLine("Out = (UV + $precision2(tileX, tileY)) * tileCount;"); + } + }); } private void AppendInvertSpecificLines(ShaderStringBuilder stringBuilder) { - if (m_InvertX) { stringBuilder.AppendLine("$precision tileX = (Invert.x * Width - ((Tile - Width * floor(Tile * tileCount.x)) + Invert.x * 1));"); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxMappingNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxMappingNode.cs index 73137640e6b..0cb102e4b5d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxMappingNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxMappingNode.cs @@ -40,7 +40,8 @@ public sealed override void UpdateNodeAfterDeserialization() AddSlot(new UVMaterialSlot(kUVsSlotId, kUVsSlotName, kUVsSlotName, UVChannel.UV0, ShaderStageCapability.Fragment)); AddSlot(new Vector2MaterialSlot(kParallaxUVsOutputSlotId, kParallaxUVsOutputSlotName, kParallaxUVsOutputSlotName, SlotType.Output, Vector2.zero, ShaderStageCapability.Fragment)); - RemoveSlotsNameNotMatching(new[] { + RemoveSlotsNameNotMatching(new[] + { kParallaxUVsOutputSlotId, kHeightmapSlotId, kHeightmapSamplerSlotId, @@ -85,7 +86,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo amplitude, // cm in the interface so we multiply by 0.01 in the shader to convert in meter uvs, GetSlotValue(kParallaxUVsOutputSlotId, generationMode) - )); + )); } public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCapability = ShaderStageCapability.All) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxOcclusionMappingNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxOcclusionMappingNode.cs index e13b123c939..263bd9b3ba0 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxOcclusionMappingNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/ParallaxOcclusionMappingNode.cs @@ -53,7 +53,8 @@ public sealed override void UpdateNodeAfterDeserialization() AddSlot(new Vector1MaterialSlot(kPixelDepthOffsetOutputSlotId, kPixelDepthOffsetOutputSlotName, kPixelDepthOffsetOutputSlotName, SlotType.Output, 0.0f, ShaderStageCapability.Fragment)); AddSlot(new Vector2MaterialSlot(kParallaxUVsOutputSlotId, kParallaxUVsOutputSlotName, kParallaxUVsOutputSlotName, SlotType.Output, Vector2.zero, ShaderStageCapability.Fragment)); - RemoveSlotsNameNotMatching(new[] { + RemoveSlotsNameNotMatching(new[] + { kPixelDepthOffsetOutputSlotId, kParallaxUVsOutputSlotId, kHeightmapSlotId, @@ -109,26 +110,26 @@ public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode gener // Then we add the functions that are specific to this node registry.ProvideFunction(GetFunctionName(), s => + { + s.AppendLine("// Required struct and function for the ParallaxOcclusionMapping function:"); + s.AppendLine($"$precision ComputePerPixelHeightDisplacement_{GetVariableNameForNode()}($precision2 texOffsetCurrent, $precision lod, PerPixelHeightDisplacementParam param, TEXTURE2D_PARAM(heightTexture, heightSampler))"); + using (s.BlockScope()) { - s.AppendLine("// Required struct and function for the ParallaxOcclusionMapping function:"); - s.AppendLine($"$precision ComputePerPixelHeightDisplacement_{GetVariableNameForNode()}($precision2 texOffsetCurrent, $precision lod, PerPixelHeightDisplacementParam param, TEXTURE2D_PARAM(heightTexture, heightSampler))"); - using (s.BlockScope()) - { - s.AppendLine("return SAMPLE_TEXTURE2D_LOD(heightTexture, heightSampler, param.uv + texOffsetCurrent, lod).r;"); - } - // heightmap, - // edgesSampler.Any() ? GetSlotValue(kHeightmapSamplerSlotId, generationMode) : "sampler" + heightmap); - - s.AppendLine($"#define ComputePerPixelHeightDisplacement ComputePerPixelHeightDisplacement_{GetVariableNameForNode()}"); - s.AppendLine($"#define POM_NAME_ID {GetVariableNameForNode()}"); - s.AppendLine($"#define POM_USER_DATA_PARAMETERS , TEXTURE2D_PARAM(heightTexture, samplerState)"); - s.AppendLine($"#define POM_USER_DATA_ARGUMENTS , TEXTURE2D_ARGS(heightTexture, samplerState)"); - s.AppendLine(perPixelDisplacementInclude); - s.AppendLine($"#undef ComputePerPixelHeightDisplacement"); - s.AppendLine($"#undef POM_NAME_ID"); - s.AppendLine($"#undef POM_USER_DATA_PARAMETERS"); - s.AppendLine($"#undef POM_USER_DATA_ARGUMENTS"); - }); + s.AppendLine("return SAMPLE_TEXTURE2D_LOD(heightTexture, heightSampler, param.uv + texOffsetCurrent, lod).r;"); + } + // heightmap, + // edgesSampler.Any() ? GetSlotValue(kHeightmapSamplerSlotId, generationMode) : "sampler" + heightmap); + + s.AppendLine($"#define ComputePerPixelHeightDisplacement ComputePerPixelHeightDisplacement_{GetVariableNameForNode()}"); + s.AppendLine($"#define POM_NAME_ID {GetVariableNameForNode()}"); + s.AppendLine($"#define POM_USER_DATA_PARAMETERS , TEXTURE2D_PARAM(heightTexture, samplerState)"); + s.AppendLine($"#define POM_USER_DATA_ARGUMENTS , TEXTURE2D_ARGS(heightTexture, samplerState)"); + s.AppendLine(perPixelDisplacementInclude); + s.AppendLine($"#undef ComputePerPixelHeightDisplacement"); + s.AppendLine($"#undef POM_NAME_ID"); + s.AppendLine($"#undef POM_USER_DATA_PARAMETERS"); + s.AppendLine($"#undef POM_USER_DATA_ARGUMENTS"); + }); } public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/PolarCoordinatesNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/PolarCoordinatesNode.cs index bc655bc279a..9c63432fe4f 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/PolarCoordinatesNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/PolarCoordinatesNode.cs @@ -11,7 +11,6 @@ public PolarCoordinatesNode() name = "Polar Coordinates"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_PolarCoordinates", BindingFlags.Static | BindingFlags.NonPublic); @@ -26,7 +25,7 @@ static string Unity_PolarCoordinates( { Out = Vector2.zero; return - @" +@" { $precision2 delta = UV - Center; $precision radius = length(delta) * 2 * RadialScale; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/RadialShearNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/RadialShearNode.cs index 232462cab27..ffa6e909be5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/RadialShearNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/RadialShearNode.cs @@ -11,7 +11,6 @@ public RadialShearNode() name = "Radial Shear"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_RadialShear", BindingFlags.Static | BindingFlags.NonPublic); @@ -26,7 +25,7 @@ static string Unity_RadialShear( { Out = Vector2.zero; return - @" +@" { $precision2 delta = UV - Center; $precision delta2 = dot(delta.xy, delta.xy); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/RotateNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/RotateNode.cs index 5be3cbaceae..2f98f068004 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/RotateNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/RotateNode.cs @@ -36,7 +36,6 @@ public RotateNode() name = "Rotate"; } - protected override MethodInfo GetFunctionToConvert() { if (m_Unit == RotationUnit.Radians) @@ -55,7 +54,7 @@ static string Unity_Rotate_Radians( return - @" +@" { //rotation matrix UV -= Center; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/SpherizeNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/SpherizeNode.cs index 7f4ec5accc7..c2f470cc44e 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/SpherizeNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/SpherizeNode.cs @@ -11,7 +11,6 @@ public SpherizeNode() name = "Spherize"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Spherize", BindingFlags.Static | BindingFlags.NonPublic); @@ -26,7 +25,7 @@ static string Unity_Spherize( { Out = Vector2.zero; return - @" +@" { $precision2 delta = UV - Center; $precision delta2 = dot(delta.xy, delta.xy); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/TilingAndOffsetNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/TilingAndOffsetNode.cs index dc8ab41fa8d..4c34a870d06 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/TilingAndOffsetNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/TilingAndOffsetNode.cs @@ -11,7 +11,6 @@ public TilingAndOffsetNode() name = "Tiling And Offset"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_TilingAndOffset", BindingFlags.Static | BindingFlags.NonPublic); @@ -25,7 +24,7 @@ static string Unity_TilingAndOffset( { Out = Vector2.zero; return - @" +@" { Out = UV * Tiling + Offset; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/TriplanarNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/TriplanarNode.cs index 0c72358ee20..ce535c869e4 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/TriplanarNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/TriplanarNode.cs @@ -5,7 +5,7 @@ using UnityEditor.ShaderGraph.Internal; namespace UnityEditor.ShaderGraph -{ +{ [Title("UV", "Triplanar")] class TriplanarNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequirePosition, IMayRequireNormal, IMayRequireTangent, IMayRequireBitangent { @@ -36,7 +36,6 @@ public TriplanarNode() UpdateNodeAfterDeserialization(); } - [SerializeField] private TextureType m_TextureType = TextureType.Default; diff --git a/com.unity.shadergraph/Editor/Data/Nodes/UV/TwirlNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/UV/TwirlNode.cs index 51a62b8653b..d65f8c2d5d9 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/UV/TwirlNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/UV/TwirlNode.cs @@ -11,7 +11,6 @@ public TwirlNode() name = "Twirl"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Twirl", BindingFlags.Static | BindingFlags.NonPublic); @@ -27,7 +26,7 @@ static string Unity_Twirl( Out = Vector2.zero; return - @" +@" { $precision2 delta = UV - Center; $precision angle = Strength * length(delta); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs index 6b02f2ef11e..bf7304204d5 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/CustomFunctionNode.cs @@ -106,9 +106,9 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo List slots = new List(); GetOutputSlots(slots); - if(!IsValidFunction()) + if (!IsValidFunction()) { - if(generationMode == GenerationMode.Preview && slots.Count != 0) + if (generationMode == GenerationMode.Preview && slots.Count != 0) { slots.OrderBy(s => s.id); sb.AppendLine("{0} {1};", @@ -151,7 +151,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) { - if(!IsValidFunction()) + if (!IsValidFunction()) return; switch (sourceType) @@ -162,7 +162,7 @@ public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode gener string path = AssetDatabase.GUIDToAssetPath(functionSource); // This is required for upgrading without console errors - if(string.IsNullOrEmpty(path)) + if (string.IsNullOrEmpty(path)) path = functionSource; string hash; @@ -247,18 +247,18 @@ static bool IsValidFunction(HlslSourceType sourceType, string functionName, stri { bool validFunctionName = !string.IsNullOrEmpty(functionName) && functionName != k_DefaultFunctionName; - if(sourceType == HlslSourceType.String) + if (sourceType == HlslSourceType.String) { bool validFunctionBody = !string.IsNullOrEmpty(functionBody) && functionBody != k_DefaultFunctionBody; return validFunctionName & validFunctionBody; } else { - if(!validFunctionName || string.IsNullOrEmpty(functionSource) || functionSource == k_DefaultFunctionSource) + if (!validFunctionName || string.IsNullOrEmpty(functionSource) || functionSource == k_DefaultFunctionSource) return false; string path = AssetDatabase.GUIDToAssetPath(functionSource); - if(string.IsNullOrEmpty(path)) + if (string.IsNullOrEmpty(path)) path = functionSource; string extension = Path.GetExtension(path); @@ -284,15 +284,15 @@ void ValidateSlotName() public override void ValidateNode() { - if(sourceType == HlslSourceType.File) + if (sourceType == HlslSourceType.File) { - if(!string.IsNullOrEmpty(functionSource)) + if (!string.IsNullOrEmpty(functionSource)) { string path = AssetDatabase.GUIDToAssetPath(functionSource); - if(!string.IsNullOrEmpty(path)) + if (!string.IsNullOrEmpty(path)) { string extension = path.Substring(path.LastIndexOf('.')); - if(!s_ValidExtensions.Contains(extension)) + if (!s_ValidExtensions.Contains(extension)) { owner.AddValidationError(objectId, k_InvalidFileType, ShaderCompilerMessageSeverity.Error); } @@ -331,11 +331,11 @@ public static string UpgradeFunctionSource(string functionSource) // If asset can be loaded from path then get its guid // Otherwise it was the default string so set to empty Guid guid; - if(!string.IsNullOrEmpty(functionSource) && !Guid.TryParse(functionSource, out guid)) + if (!string.IsNullOrEmpty(functionSource) && !Guid.TryParse(functionSource, out guid)) { string guidString = string.Empty; TextAsset textAsset = AssetDatabase.LoadAssetAtPath(functionSource); - if(textAsset != null) + if (textAsset != null) { long localId; AssetDatabase.TryGetGUIDAndLocalFileIdentifier(textAsset, out guidString, out localId); diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/KeywordNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/KeywordNode.cs index 2160904d635..942fe192682 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/KeywordNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/KeywordNode.cs @@ -53,14 +53,14 @@ public void UpdateNode() void UpdatePorts() { - switch(keyword.keywordType) + switch (keyword.keywordType) { case KeywordType.Boolean: { // Boolean type has preset slots PooledList temp = PooledList.Get(); GetInputSlots(temp); - if(temp.Any()) + if (temp.Any()) { temp.Dispose(); break; @@ -87,7 +87,7 @@ void UpdatePorts() edgeDict.Add(slot, (List)slot.owner.owner.GetEdges(slot.slotReference)); // Remove old slots - for(int i = 0; i < inputSlots.Count; i++) + for (int i = 0; i < inputSlots.Count; i++) { RemoveSlot(inputSlots[i].id); } @@ -98,7 +98,7 @@ void UpdatePorts() // Add input slots int[] slotIds = new int[keyword.entries.Count + 1]; slotIds[keyword.entries.Count] = OutputSlotId; - for(int i = 0; i < keyword.entries.Count; i++) + for (int i = 0; i < keyword.entries.Count; i++) { // Get slot based on entry id MaterialSlot slot = inputSlots.Where(x => @@ -107,7 +107,7 @@ void UpdatePorts() x.shaderOutputName == keyword.entries[i].referenceName).FirstOrDefault(); // If slot doesnt exist its new so create it - if(slot == null) + if (slot == null) { slot = new DynamicVectorMaterialSlot(keyword.entries[i].id, keyword.entries[i].displayName, keyword.entries[i].referenceName, SlotType.Input, Vector4.zero); } @@ -135,7 +135,7 @@ void UpdatePorts() public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) { var outputSlot = FindOutputSlot(OutputSlotId); - switch(keyword.keywordType) + switch (keyword.keywordType) { case KeywordType.Boolean: { @@ -154,14 +154,14 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo case KeywordType.Enum: { // Iterate all entries in the keyword - for(int i = 0; i < keyword.entries.Count; i++) + for (int i = 0; i < keyword.entries.Count; i++) { // Insert conditional - if(i == 0) + if (i == 0) { sb.AppendLine($"#if defined({keyword.referenceName}_{keyword.entries[i].referenceName})"); } - else if(i == keyword.entries.Count - 1) + else if (i == keyword.entries.Count - 1) { sb.AppendLine("#else"); } @@ -186,7 +186,7 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo public int GetSlotIdForPermutation(KeyValuePair permutation) { - switch(permutation.Key.keywordType) + switch (permutation.Key.keywordType) { // Slot 0 is output case KeywordType.Boolean: diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AllNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AllNode.cs index 651bf64a303..aefe4053f1d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AllNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AllNode.cs @@ -11,7 +11,6 @@ public AllNode() name = "All"; } - public override bool hasPreview { get { return false; } @@ -27,7 +26,7 @@ static string Unity_All( [Slot(1, Binding.None)] out Boolean Out) { return - @" +@" { Out = all(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AndNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AndNode.cs index 29dda6c613b..1953961ea4b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AndNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AndNode.cs @@ -11,7 +11,6 @@ public AndNode() name = "And"; } - public override bool hasPreview { get { return false; } @@ -28,7 +27,7 @@ static string Unity_And( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A && B; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AnyNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AnyNode.cs index 465995b8373..0246e5f0e4c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AnyNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/AnyNode.cs @@ -11,7 +11,6 @@ public AnyNode() name = "Any"; } - public override bool hasPreview { get { return false; } @@ -27,7 +26,7 @@ static string Unity_Any( [Slot(1, Binding.None)] out Boolean Out) { return - @" +@" { Out = any(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/BranchNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/BranchNode.cs index 3b44be662dd..d36996597ae 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/BranchNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/BranchNode.cs @@ -11,7 +11,6 @@ public BranchNode() name = "Branch"; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Branch", BindingFlags.Static | BindingFlags.NonPublic); @@ -24,7 +23,7 @@ static string Unity_Branch( [Slot(3, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = Predicate ? True : False; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/ComparisonNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/ComparisonNode.cs index 997dfa78584..106fb6222b4 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/ComparisonNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/ComparisonNode.cs @@ -23,7 +23,6 @@ public ComparisonNode() name = "Comparison"; } - [SerializeField] private ComparisonType m_ComparisonType = ComparisonType.Equal; @@ -71,7 +70,7 @@ static string Unity_Comparison_Equal( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A == B ? 1 : 0; } @@ -84,7 +83,7 @@ static string Unity_Comparison_NotEqual( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A != B ? 1 : 0; } @@ -97,7 +96,7 @@ static string Unity_Comparison_Less( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A < B ? 1 : 0; } @@ -110,7 +109,7 @@ static string Unity_Comparison_LessOrEqual( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A <= B ? 1 : 0; } @@ -123,7 +122,7 @@ static string Unity_Comparison_Greater( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A > B ? 1 : 0; } @@ -136,7 +135,7 @@ static string Unity_Comparison_GreaterOrEqual( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A >= B ? 1 : 0; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsFrontFaceNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsFrontFaceNode.cs index d682340f177..53cb801eadf 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsFrontFaceNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsFrontFaceNode.cs @@ -1,23 +1,23 @@ -using UnityEngine; +using UnityEngine; using UnityEditor.Graphing; namespace UnityEditor.ShaderGraph { - [Title("Utility", "Logic", "Is Front Face")] - class IsFrontFaceNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireFaceSign - { - public IsFrontFaceNode() - { - name = "Is Front Face"; - UpdateNodeAfterDeserialization(); - } + [Title("Utility", "Logic", "Is Front Face")] + class IsFrontFaceNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireFaceSign + { + public IsFrontFaceNode() + { + name = "Is Front Face"; + UpdateNodeAfterDeserialization(); + } - public override bool hasPreview { get { return false; } } + public override bool hasPreview { get { return false; } } - public const int OutputSlotId = 0; + public const int OutputSlotId = 0; private const string kOutputSlotName = "Out"; - public override void UpdateNodeAfterDeserialization() + public override void UpdateNodeAfterDeserialization() { AddSlot(new BooleanMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, true, ShaderStageCapability.Fragment)); RemoveSlotsNameNotMatching(new[] { OutputSlotId }); @@ -28,9 +28,9 @@ public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMo sb.AppendLine(string.Format("$precision {0} = max(0, IN.{1});", GetVariableNameForSlot(OutputSlotId), ShaderGeneratorNames.FaceSign)); } - public bool RequiresFaceSign(ShaderStageCapability stageCapability = ShaderStageCapability.Fragment) - { - return true; - } - } + public bool RequiresFaceSign(ShaderStageCapability stageCapability = ShaderStageCapability.Fragment) + { + return true; + } + } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsInfiniteNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsInfiniteNode.cs index fd876f8b31e..c95551fffcd 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsInfiniteNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsInfiniteNode.cs @@ -11,7 +11,6 @@ public IsInfiniteNode() name = "Is Infinite"; } - public override bool hasPreview { get { return false; } @@ -27,7 +26,7 @@ static string Unity_IsInfinite( [Slot(1, Binding.None)] out Boolean Out) { return - @" +@" { Out = isinf(In); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsNanNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsNanNode.cs index dce69233525..c0cc825c2c6 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsNanNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/IsNanNode.cs @@ -11,7 +11,6 @@ public IsNanNode() name = "Is NaN"; } - public override bool hasPreview { get { return false; } @@ -27,7 +26,7 @@ static string Unity_IsNaN( [Slot(1, Binding.None)] out Boolean Out) { return - @" +@" { Out = (In < 0.0 || In > 0.0 || In == 0.0) ? 0 : 1; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NandNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NandNode.cs index 7447d8ba435..f58559072bc 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NandNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NandNode.cs @@ -11,7 +11,6 @@ public NandNode() name = "Nand"; } - public override bool hasPreview { get { return false; } @@ -28,7 +27,7 @@ static string Unity_Nand( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = !A && !B; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NotNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NotNode.cs index 9dd8d959319..366bf85932c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NotNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/NotNode.cs @@ -11,7 +11,6 @@ public NotNode() name = "Not"; } - public override bool hasPreview { get { return false; } @@ -27,7 +26,7 @@ static string Unity_Not( [Slot(1, Binding.None)] out Boolean Out) { return - @" +@" { Out = !In; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/OrNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/OrNode.cs index 2f0df10fd3c..f63273e984f 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/OrNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/Logic/OrNode.cs @@ -11,7 +11,6 @@ public OrNode() name = "Or"; } - public override bool hasPreview { get { return false; } @@ -28,7 +27,7 @@ static string Unity_Or( [Slot(2, Binding.None)] out Boolean Out) { return - @" +@" { Out = A || B; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/PreviewNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/PreviewNode.cs index 9060be75379..74f2d62fa4b 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/PreviewNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/PreviewNode.cs @@ -40,7 +40,6 @@ public PreviewNode() m_Height = 208f; } - protected override MethodInfo GetFunctionToConvert() { return GetType().GetMethod("Unity_Preview", BindingFlags.Static | BindingFlags.NonPublic); @@ -51,7 +50,7 @@ static string Unity_Preview( [Slot(1, Binding.None)] out DynamicDimensionVector Out) { return - @" +@" { Out = In; } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeData.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeData.cs index c6d97a33fa2..4f75e52ee7d 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeData.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeData.cs @@ -41,7 +41,7 @@ public static RedirectNodeData Create(GraphData graph, SlotValueType edgeType, V void AddSlots(SlotValueType edgeType) { // Valuetype gets the type should be the type for input and output - switch(edgeType) + switch (edgeType) { case SlotValueType.Boolean: AddSlot(new BooleanMaterialSlot(kInputSlotID, "", "", SlotType.Input, false)); @@ -179,7 +179,7 @@ public override void ValidateNode() noOutputs = !edges.Any(); } - if(noInputs && !noOutputs) + if (noInputs && !noOutputs) { owner.AddValidationError(objectId, "Node has no inputs and default value will be 0.", ShaderCompilerMessageSeverity.Warning); } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeView.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeView.cs index df3800456d3..e2a25d1aeeb 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeView.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/RedirectNodeView.cs @@ -148,7 +148,7 @@ public void AttachMessage(string errString, ShaderCompilerMessageSeverity severi public void ClearMessage() { var badge = this.Q(); - if(badge != null) + if (badge != null) { badge.Detach(); badge.RemoveFromHierarchy(); @@ -157,13 +157,12 @@ public void ClearMessage() public void SetColor(Color newColor) { - } public void ResetColor() { - } + #endregion } } diff --git a/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs b/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs index 4143e7baa8f..b11836cb39c 100644 --- a/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs +++ b/com.unity.shadergraph/Editor/Data/Nodes/Utility/SubGraphNode.cs @@ -313,112 +313,112 @@ public virtual void UpdateSlots() switch (prop.concreteShaderValueType) { case ConcreteSlotValueType.Matrix4: - { - var tSlot = slot as Matrix4MaterialSlot; - var tProp = prop as Matrix4ShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as Matrix4MaterialSlot; + var tProp = prop as Matrix4ShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Matrix3: - { - var tSlot = slot as Matrix3MaterialSlot; - var tProp = prop as Matrix3ShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as Matrix3MaterialSlot; + var tProp = prop as Matrix3ShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Matrix2: - { - var tSlot = slot as Matrix2MaterialSlot; - var tProp = prop as Matrix2ShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as Matrix2MaterialSlot; + var tProp = prop as Matrix2ShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Texture2D: - { - var tSlot = slot as Texture2DInputMaterialSlot; - var tProp = prop as Texture2DShaderProperty; - if (tSlot != null && tProp != null) - tSlot.texture = tProp.value.texture; - } - break; + { + var tSlot = slot as Texture2DInputMaterialSlot; + var tProp = prop as Texture2DShaderProperty; + if (tSlot != null && tProp != null) + tSlot.texture = tProp.value.texture; + } + break; case ConcreteSlotValueType.Texture2DArray: - { - var tSlot = slot as Texture2DArrayInputMaterialSlot; - var tProp = prop as Texture2DArrayShaderProperty; - if (tSlot != null && tProp != null) - tSlot.textureArray = tProp.value.textureArray; - } - break; + { + var tSlot = slot as Texture2DArrayInputMaterialSlot; + var tProp = prop as Texture2DArrayShaderProperty; + if (tSlot != null && tProp != null) + tSlot.textureArray = tProp.value.textureArray; + } + break; case ConcreteSlotValueType.Texture3D: - { - var tSlot = slot as Texture3DInputMaterialSlot; - var tProp = prop as Texture3DShaderProperty; - if (tSlot != null && tProp != null) - tSlot.texture = tProp.value.texture; - } - break; + { + var tSlot = slot as Texture3DInputMaterialSlot; + var tProp = prop as Texture3DShaderProperty; + if (tSlot != null && tProp != null) + tSlot.texture = tProp.value.texture; + } + break; case ConcreteSlotValueType.Cubemap: - { - var tSlot = slot as CubemapInputMaterialSlot; - var tProp = prop as CubemapShaderProperty; - if (tSlot != null && tProp != null) - tSlot.cubemap = tProp.value.cubemap; - } - break; + { + var tSlot = slot as CubemapInputMaterialSlot; + var tProp = prop as CubemapShaderProperty; + if (tSlot != null && tProp != null) + tSlot.cubemap = tProp.value.cubemap; + } + break; case ConcreteSlotValueType.Gradient: - { - var tSlot = slot as GradientInputMaterialSlot; - var tProp = prop as GradientShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as GradientInputMaterialSlot; + var tProp = prop as GradientShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Vector4: - { - var tSlot = slot as Vector4MaterialSlot; - var vector4Prop = prop as Vector4ShaderProperty; - var colorProp = prop as ColorShaderProperty; - if (tSlot != null && vector4Prop != null) - tSlot.value = vector4Prop.value; - else if (tSlot != null && colorProp != null) - tSlot.value = colorProp.value; - } - break; + { + var tSlot = slot as Vector4MaterialSlot; + var vector4Prop = prop as Vector4ShaderProperty; + var colorProp = prop as ColorShaderProperty; + if (tSlot != null && vector4Prop != null) + tSlot.value = vector4Prop.value; + else if (tSlot != null && colorProp != null) + tSlot.value = colorProp.value; + } + break; case ConcreteSlotValueType.Vector3: - { - var tSlot = slot as Vector3MaterialSlot; - var tProp = prop as Vector3ShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as Vector3MaterialSlot; + var tProp = prop as Vector3ShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Vector2: - { - var tSlot = slot as Vector2MaterialSlot; - var tProp = prop as Vector2ShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as Vector2MaterialSlot; + var tProp = prop as Vector2ShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Vector1: - { - var tSlot = slot as Vector1MaterialSlot; - var tProp = prop as Vector1ShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as Vector1MaterialSlot; + var tProp = prop as Vector1ShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; case ConcreteSlotValueType.Boolean: - { - var tSlot = slot as BooleanMaterialSlot; - var tProp = prop as BooleanShaderProperty; - if (tSlot != null && tProp != null) - tSlot.value = tProp.value; - } - break; + { + var tSlot = slot as BooleanMaterialSlot; + var tProp = prop as BooleanShaderProperty; + if (tSlot != null && tProp != null) + tSlot.value = tProp.value; + } + break; } AddSlot(slot); @@ -486,7 +486,7 @@ public override void ValidateNode() hasError = true; owner.AddValidationError(objectId, $"Invalid Sub Graph asset at \"{AssetDatabase.GUIDToAssetPath(subGraphGuid)}\" with GUID {subGraphGuid}."); } - else if(!owner.isSubGraph && owner.activeTargets.Any(x => asset.unsupportedTargets.Contains(x))) + else if (!owner.isSubGraph && owner.activeTargets.Any(x => asset.unsupportedTargets.Contains(x))) { SetOverrideActiveState(ActiveState.ExplicitInactive); owner.AddValidationError(objectId, $"Subgraph asset at \"{AssetDatabase.GUIDToAssetPath(subGraphGuid)}\" with GUID {subGraphGuid} contains nodes that are unsuported by the current active targets"); diff --git a/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs b/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs index 3ee8141732a..bd296a4d068 100644 --- a/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs +++ b/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphAsset.cs @@ -83,7 +83,7 @@ class SubGraphAsset : ScriptableObject, ISerializationCallbackReceiver public void WriteData(IEnumerable inputs, IEnumerable keywords, IEnumerable nodeProperties, IEnumerable outputs, IEnumerable unsupportedTargets) { - if(m_SubGraphData == null) + if (m_SubGraphData == null) { m_SubGraphData = new SubGraphData(); m_SubGraphData.OverrideObjectId(assetGuid, "_subGraphData"); @@ -95,27 +95,27 @@ public void WriteData(IEnumerable inputs, IEnumerable Documentation.GetPageLink("Sub-graph"); void ValidateShaderStage() - { - List slots = new List(); - GetInputSlots(slots); + { + List slots = new List(); + GetInputSlots(slots); - foreach(MaterialSlot slot in slots) + foreach (MaterialSlot slot in slots) slot.stageCapability = ShaderStageCapability.All; var effectiveStage = ShaderStageCapability.All; foreach (var slot in slots) - { + { var stage = NodeUtils.GetEffectiveShaderStageCapability(slot, true); if (stage != ShaderStageCapability.All) { effectiveStage = stage; break; + } } - } - foreach(MaterialSlot slot in slots) + foreach (MaterialSlot slot in slots) slot.stageCapability = effectiveStage; } diff --git a/com.unity.shadergraph/Editor/Data/Util/GradientUtil.cs b/com.unity.shadergraph/Editor/Data/Util/GradientUtil.cs index f33b59489e0..95a6b8a2d2b 100644 --- a/com.unity.shadergraph/Editor/Data/Util/GradientUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/GradientUtil.cs @@ -1,4 +1,4 @@ -using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.Internal; using UnityEditor.Graphing; using UnityEngine; @@ -9,27 +9,27 @@ static class GradientUtil public static string GetGradientValue(Gradient gradient, string delimiter = ";") { string colorKeys = ""; - for(int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { - if(i < gradient.colorKeys.Length) + if (i < gradient.colorKeys.Length) colorKeys += $"$precision4({NodeUtils.FloatToShaderValue(gradient.colorKeys[i].color.r)}, " + - $"{NodeUtils.FloatToShaderValue(gradient.colorKeys[i].color.g)}, " + - $"{NodeUtils.FloatToShaderValue(gradient.colorKeys[i].color.b)}, " + - $"{NodeUtils.FloatToShaderValue(gradient.colorKeys[i].time)})"; + $"{NodeUtils.FloatToShaderValue(gradient.colorKeys[i].color.g)}, " + + $"{NodeUtils.FloatToShaderValue(gradient.colorKeys[i].color.b)}, " + + $"{NodeUtils.FloatToShaderValue(gradient.colorKeys[i].time)})"; else colorKeys += "$precision4(0, 0, 0, 0)"; - if(i < 7) + if (i < 7) colorKeys += ","; } string alphaKeys = ""; - for(int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { - if(i < gradient.alphaKeys.Length) + if (i < gradient.alphaKeys.Length) alphaKeys += $"$precision2({NodeUtils.FloatToShaderValue(gradient.alphaKeys[i].alpha)}, {NodeUtils.FloatToShaderValue(gradient.alphaKeys[i].time)})"; else alphaKeys += "$precision2(0, 0)"; - if(i < 7) + if (i < 7) alphaKeys += ","; } @@ -39,18 +39,18 @@ static class GradientUtil public static string GetGradientForPreview(string name) { string colorKeys = ""; - for(int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { colorKeys += $"{name}_ColorKey{i}"; - if(i < 7) + if (i < 7) colorKeys += ","; } string alphaKeys = ""; - for(int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { alphaKeys += $"{name}_AlphaKey{i}"; - if(i < 7) + if (i < 7) alphaKeys += ","; } diff --git a/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs b/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs index d6d433481ea..a26eef75521 100644 --- a/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/GraphUtil.cs @@ -120,7 +120,7 @@ public override void Action(int instanceId, string pathName, string resourceFile var graph = new GraphData(); graph.AddContexts(); graph.InitializeOutputs(m_Targets, m_Blocks); - + graph.path = "Shader Graphs"; FileUtilities.WriteShaderGraphToDisk(pathName, graph); AssetDatabase.Refresh(); @@ -202,7 +202,7 @@ public static void CreateNewGraphWithOutputs(Target[] targets, BlockFieldDescrip public static bool TryGetMetadataOfType(this Shader shader, out T obj) where T : ScriptableObject { obj = null; - if(!shader.IsShaderGraph()) + if (!shader.IsShaderGraph()) return false; var path = AssetDatabase.GetAssetPath(shader); @@ -390,7 +390,7 @@ public static void OpenFile(string path) p.EnableRaisingEvents = true; p.Exited += (Object obj, EventArgs args) => { - if(p.ExitCode != 0) + if (p.ExitCode != 0) Debug.LogWarningFormat("Unable to open {0}: Check external editor in preferences", filePath); }; p.Start(); diff --git a/com.unity.shadergraph/Editor/Data/Util/KeywordCollector.cs b/com.unity.shadergraph/Editor/Data/Util/KeywordCollector.cs index b466b983081..66197f998af 100644 --- a/com.unity.shadergraph/Editor/Data/Util/KeywordCollector.cs +++ b/com.unity.shadergraph/Editor/Data/Util/KeywordCollector.cs @@ -20,23 +20,23 @@ public void AddShaderKeyword(ShaderKeyword chunk) { if (keywords.Any(x => x.referenceName == chunk.referenceName)) return; - + keywords.Add(chunk); } public void GetKeywordsDeclaration(ShaderStringBuilder builder, GenerationMode mode) { - if(keywords.Count == 0) + if (keywords.Count == 0) return; // Declare keywords foreach (var keyword in keywords) { // Hardcode active keywords in preview to reduce compiled variants - if(mode == GenerationMode.Preview) + if (mode == GenerationMode.Preview) { string declaration = keyword.GetKeywordPreviewDeclarationString(); - if(!string.IsNullOrEmpty(declaration)) + if (!string.IsNullOrEmpty(declaration)) { builder.AppendLine(declaration); } @@ -44,7 +44,7 @@ public void GetKeywordsDeclaration(ShaderStringBuilder builder, GenerationMode m else { string declaration = keyword.GetKeywordDeclarationString(); - if(!string.IsNullOrEmpty(declaration)) + if (!string.IsNullOrEmpty(declaration)) { builder.AppendLine(declaration); } @@ -63,7 +63,7 @@ public void CalculateKeywordPermutations() // Initialize current permutation List> currentPermutation = new List>(); - for(int i = 0; i < keywords.Count; i++) + for (int i = 0; i < keywords.Count; i++) { currentPermutation.Add(new KeyValuePair(keywords[i], 0)); } @@ -74,18 +74,18 @@ public void CalculateKeywordPermutations() void PermuteKeywords(List keywords, List> currentPermutation, int currentIndex) { - if(currentIndex == keywords.Count) + if (currentIndex == keywords.Count) return; // Iterate each possible keyword at the current index int entryCount = keywords[currentIndex].keywordType == KeywordType.Enum ? keywords[currentIndex].entries.Count : 2; - for(int i = 0; i < entryCount; i++) + for (int i = 0; i < entryCount; i++) { // Set the index in the current permutation to the correct value currentPermutation[currentIndex] = new KeyValuePair(keywords[currentIndex], i); // If the current index is the last keyword we are finished with this permutation - if(currentIndex == keywords.Count - 1) + if (currentIndex == keywords.Count - 1) { permutations.Add(currentPermutation); } diff --git a/com.unity.shadergraph/Editor/Data/Util/KeywordDependentCollection.cs b/com.unity.shadergraph/Editor/Data/Util/KeywordDependentCollection.cs index 365bfa27fee..5940da95e4b 100644 --- a/com.unity.shadergraph/Editor/Data/Util/KeywordDependentCollection.cs +++ b/com.unity.shadergraph/Editor/Data/Util/KeywordDependentCollection.cs @@ -25,13 +25,13 @@ public interface IInstance } public abstract class KeywordDependentCollection - where TAll: TISet - where TAllPermutations: TISet - where TForPermutation: TISet, TIInstance - where TBase: TISet, TIInstance - where TISet: KeywordDependentCollection.ISet - where TIInstance: KeywordDependentCollection.IInstance - where TStorage: new() + where TAll : TISet + where TAllPermutations : TISet + where TForPermutation : TISet, TIInstance + where TBase : TISet, TIInstance + where TISet : KeywordDependentCollection.ISet + where TIInstance : KeywordDependentCollection.IInstance + where TStorage : new() { TStorage m_Base = new TStorage(); List m_PerPermutationIndex = new List(); @@ -65,7 +65,7 @@ protected TStorage baseStorage protected TStorage GetOrCreateForPermutationIndex(int index) { - while(index >= m_PerPermutationIndex.Count) + while (index >= m_PerPermutationIndex.Count) m_PerPermutationIndex.Add(new TStorage()); return m_PerPermutationIndex[index]; @@ -73,7 +73,7 @@ protected TStorage GetOrCreateForPermutationIndex(int index) protected void SetForPermutationIndex(int index, TStorage value) { - while(index >= m_PerPermutationIndex.Count) + while (index >= m_PerPermutationIndex.Count) m_PerPermutationIndex.Add(new TStorage()); m_PerPermutationIndex[index] = value; diff --git a/com.unity.shadergraph/Editor/Data/Util/KeywordUtil.cs b/com.unity.shadergraph/Editor/Data/Util/KeywordUtil.cs index 4cd748d2c63..e5350917ee2 100644 --- a/com.unity.shadergraph/Editor/Data/Util/KeywordUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/KeywordUtil.cs @@ -35,13 +35,13 @@ static class KeywordUtil { public static IEnumerable GetBuiltinKeywordDescriptors() => TypeCache.GetMethodsWithAttribute() - .Where(method => method.IsStatic && method.ReturnType == typeof(KeywordDescriptor)) - .Select(method => - (KeywordDescriptor) method.Invoke(null, new object[0] { })); + .Where(method => method.IsStatic && method.ReturnType == typeof(KeywordDescriptor)) + .Select(method => + (KeywordDescriptor)method.Invoke(null, new object[0] {})); public static ConcreteSlotValueType ToConcreteSlotValueType(this KeywordType keywordType) { - switch(keywordType) + switch (keywordType) { case KeywordType.Boolean: return ConcreteSlotValueType.Boolean; @@ -54,7 +54,7 @@ public static ConcreteSlotValueType ToConcreteSlotValueType(this KeywordType key public static string ToDeclarationString(this KeywordDefinition keywordDefinition) { - switch(keywordDefinition) + switch (keywordDefinition) { case KeywordDefinition.MultiCompile: return "multi_compile"; @@ -71,7 +71,7 @@ public static string ToDeclarationString(this KeywordDescriptor keyword) string scopeString = keyword.scope == KeywordScope.Local ? "_local" : string.Empty; string definitionString = $"{keyword.definition.ToDeclarationString()}{scopeString}"; - switch(keyword.type) + switch (keyword.type) { case KeywordType.Boolean: return $"#pragma {definitionString} _ {keyword.referenceName}"; @@ -86,7 +86,7 @@ public static string ToDeclarationString(this KeywordDescriptor keyword) public static string ToDefineString(this KeywordDescriptor keyword, int value) { - switch(keyword.type) + switch (keyword.type) { case KeywordType.Boolean: return value == 1 ? $"#define {keyword.referenceName}" : string.Empty; @@ -102,7 +102,7 @@ public static int GetKeywordPermutationCount(this GraphData graph) // Gather all unique keywords from the Graph including Sub Graphs IEnumerable allKeywords = graph.keywords; var subGraphNodes = graph.GetNodes(); - foreach(SubGraphNode subGraphNode in subGraphNodes) + foreach (SubGraphNode subGraphNode in subGraphNodes) { if (subGraphNode.asset == null) { @@ -114,9 +114,9 @@ public static int GetKeywordPermutationCount(this GraphData graph) // Get permutation count for all Keywords int permutationCount = 1; - foreach(ShaderKeyword keyword in allKeywords) + foreach (ShaderKeyword keyword in allKeywords) { - if(keyword.keywordType == KeywordType.Boolean) + if (keyword.keywordType == KeywordType.Boolean) permutationCount *= 2; else permutationCount *= keyword.entries.Count; @@ -130,10 +130,10 @@ public static string GetKeywordPermutationSetConditional(List permutationSe StringBuilder sb = new StringBuilder(); sb.Append("#if "); - for(int i = 0; i < permutationSet.Count; i++) + for (int i = 0; i < permutationSet.Count; i++) { // Subsequent permutation predicates require || - if(i != 0) + if (i != 0) sb.Append(" || "); // Append permutation @@ -153,18 +153,18 @@ public static void GetKeywordPermutationDeclarations(ShaderStringBuilder sb, Lis if (permutations.Count == 0) return; - for(int p = 0; p < permutations.Count; p++) + for (int p = 0; p < permutations.Count; p++) { // ShaderStringBuilder.Append doesnt apply indentation sb.AppendIndentation(); // Append correct if bool isLast = false; - if(p == 0) + if (p == 0) { sb.Append("#if "); } - else if(p == permutations.Count - 1) + else if (p == permutations.Count - 1) { sb.Append("#else"); isLast = true; @@ -175,18 +175,18 @@ public static void GetKeywordPermutationDeclarations(ShaderStringBuilder sb, Lis } // Last permutation is always #else - if(!isLast) + if (!isLast) { // Track whether && is required bool appendAnd = false; // Iterate all keywords that are part of the permutation - for(int i = 0; i < permutations[p].Count; i++) + for (int i = 0; i < permutations[p].Count; i++) { // When previous keyword was inserted subsequent requires && string and = appendAnd ? " && " : string.Empty; - switch(permutations[p][i].Key.keywordType) + switch (permutations[p][i].Key.keywordType) { case KeywordType.Enum: { @@ -197,7 +197,7 @@ public static void GetKeywordPermutationDeclarations(ShaderStringBuilder sb, Lis case KeywordType.Boolean: { // HLSL does not support a !value predicate - if(permutations[p][i].Value != 0) + if (permutations[p][i].Value != 0) { continue; } diff --git a/com.unity.shadergraph/Editor/Data/Util/PooledHashSet.cs b/com.unity.shadergraph/Editor/Data/Util/PooledHashSet.cs index d842359a2b5..c8460f4c5bc 100644 --- a/com.unity.shadergraph/Editor/Data/Util/PooledHashSet.cs +++ b/com.unity.shadergraph/Editor/Data/Util/PooledHashSet.cs @@ -43,6 +43,7 @@ public void Dispose() { throw new InvalidOperationException($"{nameof(PooledHashSet)} must be disposed manually."); } + #endif } } diff --git a/com.unity.shadergraph/Editor/Data/Util/PooledList.cs b/com.unity.shadergraph/Editor/Data/Util/PooledList.cs index 8ac77929611..ea2be0fb6fb 100644 --- a/com.unity.shadergraph/Editor/Data/Util/PooledList.cs +++ b/com.unity.shadergraph/Editor/Data/Util/PooledList.cs @@ -43,6 +43,7 @@ public void Dispose() { throw new InvalidOperationException($"{nameof(PooledList)} must be disposed manually."); } + #endif } } diff --git a/com.unity.shadergraph/Editor/Data/Util/PrecisionUtil.cs b/com.unity.shadergraph/Editor/Data/Util/PrecisionUtil.cs index ed6d3ed1580..c93253d85d4 100644 --- a/com.unity.shadergraph/Editor/Data/Util/PrecisionUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/PrecisionUtil.cs @@ -8,7 +8,7 @@ internal static class PrecisionUtil internal static string ToShaderString(this ConcretePrecision precision) { - switch(precision) + switch (precision) { case ConcretePrecision.Single: return "float"; @@ -21,7 +21,7 @@ internal static string ToShaderString(this ConcretePrecision precision) internal static ConcretePrecision ToConcrete(this Precision precision) { - switch(precision) + switch (precision) { case Precision.Single: return ConcretePrecision.Single; diff --git a/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs b/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs index d73226e75d5..0a0f25c82a0 100644 --- a/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs +++ b/com.unity.shadergraph/Editor/Data/Util/SerializationHelper.cs @@ -65,7 +65,7 @@ static Type GetTypeFromSerializedString(TypeSerializationInfo typeInfo) public static JSONSerializedElement Serialize(T item) { - if(item is JsonObject jsonObject) + if (item is JsonObject jsonObject) return new JSONSerializedElement() { JSONnodeData = jsonObject.Serialize() }; if (item == null) @@ -78,7 +78,7 @@ public static JSONSerializedElement Serialize(T item) if (string.IsNullOrEmpty(data)) throw new ArgumentException(string.Format("Can not serialize {0}", item)); - + return new JSONSerializedElement { @@ -128,7 +128,7 @@ public static T Deserialize(JSONSerializedElement item, Dictionary { - public interface IRequirements: KeywordDependentCollection.IInstance, KeywordDependentCollection.ISet + public interface IRequirements : KeywordDependentCollection.IInstance, KeywordDependentCollection.ISet { void SetRequirements(ShaderGraphRequirements value); ShaderGraphRequirements requirements { get; set; } } - public interface IRequirementsSet: KeywordDependentCollection.ISet + public interface IRequirementsSet : KeywordDependentCollection.ISet { } - public struct ForPermutationIndex: IRequirements, IRequirementsSet + public struct ForPermutationIndex : IRequirements, IRequirementsSet { private ShaderGraphRequirementsPerKeyword m_Source; private int m_PermutationIndex; @@ -55,7 +55,7 @@ public struct Base : IRequirements, IRequirementsSet private ShaderGraphRequirementsPerKeyword m_Source; public int instanceCount => 1; - public int permutationIndex => -1; + public int permutationIndex => - 1; public KeywordDependentCollection.KeywordPermutationInstanceType type => KeywordDependentCollection.KeywordPermutationInstanceType.Base; public IEnumerable instances => Enumerable.Repeat(this, 1); diff --git a/com.unity.shadergraph/Editor/Data/Util/SlotValueTypeUtil.cs b/com.unity.shadergraph/Editor/Data/Util/SlotValueTypeUtil.cs index 37d367267cd..1bfa1189094 100644 --- a/com.unity.shadergraph/Editor/Data/Util/SlotValueTypeUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/SlotValueTypeUtil.cs @@ -8,7 +8,7 @@ static class SlotValueTypeUtil { public static SlotValueType ToSlotValueType(this ConcreteSlotValueType concreteValueType) { - switch(concreteValueType) + switch (concreteValueType) { case ConcreteSlotValueType.SamplerState: return SlotValueType.SamplerState; diff --git a/com.unity.shadergraph/Editor/Data/Util/TextUtil.cs b/com.unity.shadergraph/Editor/Data/Util/TextUtil.cs index 3c345545cc5..914b4b97c9a 100644 --- a/com.unity.shadergraph/Editor/Data/Util/TextUtil.cs +++ b/com.unity.shadergraph/Editor/Data/Util/TextUtil.cs @@ -1,4 +1,4 @@ -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; namespace UnityEditor.ShaderGraph { diff --git a/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardFieldView.cs b/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardFieldView.cs index 71a8c6819ce..f121aa02e13 100644 --- a/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardFieldView.cs +++ b/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardFieldView.cs @@ -30,11 +30,11 @@ class BlackboardFieldView : BlackboardField, IInspectable private void DirtyNodes(ModificationScope modificationScope = ModificationScope.Node) { - switch(m_Input) + switch (m_Input) { case AbstractShaderProperty property: var graphEditorView = GetFirstAncestorOfType(); - if(graphEditorView == null) + if (graphEditorView == null) return; var colorManager = graphEditorView.colorManager; var nodes = graphEditorView.graphView.Query().ToList(); @@ -74,7 +74,7 @@ public string inspectorTitle { get { - switch(m_Input) + switch (m_Input) { case AbstractShaderProperty property: return $"{m_Input.displayName} (Property)"; @@ -94,14 +94,14 @@ public void InspectorUpdateTrigger() private void UpdateTypeText() { - if(shaderInput is AbstractShaderProperty asp) + if (shaderInput is AbstractShaderProperty asp) { typeText = asp.GetPropertyTypeString(); } } public BlackboardFieldView(GraphData graph, ShaderInput input, BlackBoardCallback updateBlackboardView, - Texture icon, string text, string typeText) : base(icon, text, typeText) + Texture icon, string text, string typeText) : base(icon, text, typeText) { styleSheets.Add(Resources.Load("Styles/ShaderGraphBlackboard")); m_Graph = graph; @@ -137,17 +137,17 @@ void UpdateReferenceNameResetMenu() void BuildContextualMenu(ContextualMenuPopulateEvent evt) { evt.menu.AppendAction("Reset Reference", e => - { - m_Input.overrideReferenceName = null; - m_resetReferenceNameTrigger(shaderInput.referenceName); - DirtyNodes(ModificationScope.Graph); - }, DropdownMenuAction.AlwaysEnabled); + { + m_Input.overrideReferenceName = null; + m_resetReferenceNameTrigger(shaderInput.referenceName); + DirtyNodes(ModificationScope.Graph); + }, DropdownMenuAction.AlwaysEnabled); } -#region PropertyDrawers + #region PropertyDrawers public void SupplyDataToPropertyDrawer(IPropertyDrawer propertyDrawer, Action inspectorUpdateDelegate) { - if(propertyDrawer is ShaderInputPropertyDrawer shaderInputPropertyDrawer) + if (propertyDrawer is ShaderInputPropertyDrawer shaderInputPropertyDrawer) { shaderInputPropertyDrawer.GetPropertyData( m_Graph.isSubGraph, @@ -173,6 +173,7 @@ void ChangeExposedField(bool newValue) m_Input.generatePropertyBlock = newValue; icon = m_Input.generatePropertyBlock ? BlackboardProvider.exposedIcon : null; } + void ChangeDisplayNameField(string newValue) { if (newValue != m_Input.displayName) @@ -199,62 +200,62 @@ void RegisterPropertyChangeUndo(string actionName) void MarkNodesAsDirty(bool triggerPropertyViewUpdate = false, ModificationScope modificationScope = ModificationScope.Node) { DirtyNodes(modificationScope); - if(triggerPropertyViewUpdate) + if (triggerPropertyViewUpdate) m_inspectorUpdateTrigger(); } void ChangePropertyValue(object newValue) { var property = m_Input as AbstractShaderProperty; - if(property == null) + if (property == null) return; - switch(property) + switch (property) { case BooleanShaderProperty booleanProperty: booleanProperty.value = ((ToggleData)newValue).isOn; break; case Vector1ShaderProperty vector1Property: - vector1Property.value = (float) newValue; + vector1Property.value = (float)newValue; break; case Vector2ShaderProperty vector2Property: - vector2Property.value = (Vector2) newValue; + vector2Property.value = (Vector2)newValue; break; case Vector3ShaderProperty vector3Property: - vector3Property.value = (Vector3) newValue; + vector3Property.value = (Vector3)newValue; break; case Vector4ShaderProperty vector4Property: - vector4Property.value = (Vector4) newValue; + vector4Property.value = (Vector4)newValue; break; case ColorShaderProperty colorProperty: - colorProperty.value = (Color) newValue; + colorProperty.value = (Color)newValue; break; case Texture2DShaderProperty texture2DProperty: - texture2DProperty.value.texture = (Texture) newValue; + texture2DProperty.value.texture = (Texture)newValue; break; case Texture2DArrayShaderProperty texture2DArrayProperty: - texture2DArrayProperty.value.textureArray = (Texture2DArray) newValue; + texture2DArrayProperty.value.textureArray = (Texture2DArray)newValue; break; case Texture3DShaderProperty texture3DProperty: - texture3DProperty.value.texture = (Texture3D) newValue; + texture3DProperty.value.texture = (Texture3D)newValue; break; case CubemapShaderProperty cubemapProperty: - cubemapProperty.value.cubemap = (Cubemap) newValue; + cubemapProperty.value.cubemap = (Cubemap)newValue; break; case Matrix2ShaderProperty matrix2Property: - matrix2Property.value = (Matrix4x4) newValue; + matrix2Property.value = (Matrix4x4)newValue; break; case Matrix3ShaderProperty matrix3Property: - matrix3Property.value = (Matrix4x4) newValue; + matrix3Property.value = (Matrix4x4)newValue; break; case Matrix4ShaderProperty matrix4Property: - matrix4Property.value = (Matrix4x4) newValue; + matrix4Property.value = (Matrix4x4)newValue; break; case SamplerStateShaderProperty samplerStateProperty: - samplerStateProperty.value = (TextureSamplerState) newValue; + samplerStateProperty.value = (TextureSamplerState)newValue; break; case GradientShaderProperty gradientProperty: - gradientProperty.value = (Gradient) newValue; + gradientProperty.value = (Gradient)newValue; break; default: throw new ArgumentOutOfRangeException(); @@ -262,6 +263,7 @@ void ChangePropertyValue(object newValue) MarkDirtyRepaint(); } -#endregion + + #endregion } } diff --git a/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs b/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs index fbe3218cc20..eae8230512c 100644 --- a/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs +++ b/com.unity.shadergraph/Editor/Drawing/Blackboard/BlackboardProvider.cs @@ -179,7 +179,7 @@ void MoveItemRequested(Blackboard blackboard, int newIndex, VisualElement visual return; m_Graph.owner.RegisterCompleteObjectUndo("Move Graph Input"); - switch(input) + switch (input) { case AbstractShaderProperty property: m_Graph.MoveProperty(property, newIndex); @@ -208,7 +208,7 @@ void AddPropertyItems(GenericMenu gm) shaderInputTypes.Sort((s1, s2) => { var info1 = Attribute.GetCustomAttribute(s1, typeof(BlackboardInputInfo)) as BlackboardInputInfo; var info2 = Attribute.GetCustomAttribute(s2, typeof(BlackboardInputInfo)) as BlackboardInputInfo; - + if (info1.priority == info2.priority) return (info1.name ?? s1.Name).CompareTo(info2.name ?? s2.Name); else @@ -225,7 +225,7 @@ void AddPropertyItems(GenericMenu gm) ShaderInput si = Activator.CreateInstance(t, true) as ShaderInput; gm.AddItem(new GUIContent(name), false, () => AddInputRow(si, true)); //QUICK FIX TO DEAL WITH DEPRECATED COLOR PROPERTY - if(ShaderGraphPreferences.allowDeprecatedBehaviors && si is ColorShaderProperty csp) + if (ShaderGraphPreferences.allowDeprecatedBehaviors && si is ColorShaderProperty csp) { gm.AddItem(new GUIContent($"Color (Deprecated)"), false, () => AddInputRow(new ColorShaderProperty(ColorShaderProperty.deprecatedVersion), true)); } @@ -247,7 +247,7 @@ void AddKeywordItems(GenericMenu gm) void AddBuiltinKeyword(GenericMenu gm, ShaderKeyword keyword) { - if(m_Graph.keywords.Where(x => x.referenceName == keyword.referenceName).Any()) + if (m_Graph.keywords.Where(x => x.referenceName == keyword.referenceName).Any()) { gm.AddDisabledItem(new GUIContent($"Keyword/{keyword.displayName}")); } @@ -281,7 +281,7 @@ void UpdateBlackboardView() { //update property pill blackboardFieldView.text = blackboardFieldView.shaderInput.displayName; - // for some reason doesn't work from the inspector calls so need it here + // for some reason doesn't work from the inspector calls so need it here DirtyNodes(); } } @@ -356,7 +356,7 @@ void AddInputRow(ShaderInput input, bool create = false, int index = -1) BlackboardFieldView field = null; BlackboardRow row = null; - switch(input) + switch (input) { case AbstractShaderProperty property: { @@ -369,6 +369,7 @@ void UpdateField() field.typeText = property.GetPropertyTypeString(); field.InspectorUpdateTrigger(); } + property.onAfterVersionChange += UpdateField; row = new BlackboardRow(field, null); @@ -428,7 +429,7 @@ void UpdateField() m_Graph.AddGraphInput(input); field.OpenTextEditor(); - if(input as ShaderKeyword != null) + if (input as ShaderKeyword != null) { m_Graph.OnKeywordChangedNoValidate(); } @@ -473,7 +474,7 @@ void OnMouseHover(EventBase evt, ShaderInput input) { foreach (var node in graphView.nodes.ToList()) { - if(input is AbstractShaderProperty property) + if (input is AbstractShaderProperty property) { if (node.userData is PropertyNode propertyNode) { @@ -484,7 +485,7 @@ void OnMouseHover(EventBase evt, ShaderInput input) } } } - else if(input is ShaderKeyword keyword) + else if (input is ShaderKeyword keyword) { if (node.userData is KeywordNode keywordNode) { diff --git a/com.unity.shadergraph/Editor/Drawing/Colors/ColorManager.cs b/com.unity.shadergraph/Editor/Drawing/Colors/ColorManager.cs index 6357fb286e4..f7a0d9a6469 100644 --- a/com.unity.shadergraph/Editor/Drawing/Colors/ColorManager.cs +++ b/com.unity.shadergraph/Editor/Drawing/Colors/ColorManager.cs @@ -11,9 +11,9 @@ namespace UnityEditor.ShaderGraph.Drawing.Colors class ColorManager { static string DefaultProvider = NoColors.Title; - + List m_Providers; - + int m_ActiveIndex = 0; public int activeIndex { @@ -22,7 +22,7 @@ private set { if (!IsValidIndex(value)) return; - + m_ActiveIndex = value; } } @@ -36,10 +36,10 @@ public ColorManager(string activeProvider) foreach (var colorType in TypeCache.GetTypesDerivedFrom().Where(t => !t.IsAbstract)) { - var provider = (IColorProvider) Activator.CreateInstance(colorType); + var provider = (IColorProvider)Activator.CreateInstance(colorType); m_Providers.Add(provider); } - + m_Providers.Sort((p1, p2) => string.Compare(p1.GetTitle(), p2.GetTitle(), StringComparison.InvariantCulture)); activeIndex = m_Providers.FindIndex(provider => provider.GetTitle() == activeProvider); } @@ -54,12 +54,12 @@ public void SetNodesDirty(IEnumerable nodeViews) } } } - + public void SetActiveProvider(int newIndex, IEnumerable nodeViews) { if (newIndex == activeIndex || !IsValidIndex(newIndex)) return; - + var oldProvider = activeProvider; activeIndex = newIndex; @@ -77,7 +77,7 @@ public void UpdateNodeViews(IEnumerable nodeViews) UpdateNodeView(view); } } - + public void UpdateNodeView(IShaderNodeView nodeView) { activeProvider.ApplyColor(nodeView); @@ -90,7 +90,7 @@ public void UpdateNodeView(IShaderNodeView nodeView) public bool activeSupportsCustom => activeProvider.AllowCustom(); IColorProvider activeProvider => m_Providers[activeIndex]; - + bool IsValidIndex(int index) => index >= 0 && index < m_Providers.Count; } } diff --git a/com.unity.shadergraph/Editor/Drawing/Colors/CustomColorData.cs b/com.unity.shadergraph/Editor/Drawing/Colors/CustomColorData.cs index 819c0b4b8fd..dc23a0340d0 100644 --- a/com.unity.shadergraph/Editor/Drawing/Colors/CustomColorData.cs +++ b/com.unity.shadergraph/Editor/Drawing/Colors/CustomColorData.cs @@ -12,9 +12,9 @@ class SerializableUserColor public Color Value = Color.black; public SerializableUserColor(KeyValuePair pair) { Key = pair.Key; Value = pair.Value; } - + // Empty constructor required by serialization system - public SerializableUserColor() { } + public SerializableUserColor() {} } [Serializable] @@ -28,7 +28,7 @@ public bool TryGetColor(string provider, out Color color) { return m_CustomColors.TryGetValue(provider, out color); } - + public void Set(string provider, Color color) { m_CustomColors[provider] = color; diff --git a/com.unity.shadergraph/Editor/Drawing/Colors/PrecisionColors.cs b/com.unity.shadergraph/Editor/Drawing/Colors/PrecisionColors.cs index bfcbf4a3195..cc69dfc99b8 100644 --- a/com.unity.shadergraph/Editor/Drawing/Colors/PrecisionColors.cs +++ b/com.unity.shadergraph/Editor/Drawing/Colors/PrecisionColors.cs @@ -13,7 +13,7 @@ class PrecisionColors : ColorProviderFromStyleSheet public override bool AllowCustom() => false; public override bool ClearOnDirty() => true; - + protected override bool GetClassFromNode(AbstractMaterialNode node, out string ussClass) { ussClass = node.concretePrecision.ToString(); diff --git a/com.unity.shadergraph/Editor/Drawing/Colors/UserColors.cs b/com.unity.shadergraph/Editor/Drawing/Colors/UserColors.cs index ea5e255e8d9..8208d8b2f2d 100644 --- a/com.unity.shadergraph/Editor/Drawing/Colors/UserColors.cs +++ b/com.unity.shadergraph/Editor/Drawing/Colors/UserColors.cs @@ -3,7 +3,7 @@ namespace UnityEditor.ShaderGraph.Drawing.Colors { - class UserColors : ColorProviderFromCode + class UserColors : ColorProviderFromCode { const string m_Title = "User Defined"; public override string GetTitle() => m_Title; diff --git a/com.unity.shadergraph/Editor/Drawing/Controls/DielectricSpecularControl.cs b/com.unity.shadergraph/Editor/Drawing/Controls/DielectricSpecularControl.cs index 47419377f4c..c2eba2b5e09 100644 --- a/com.unity.shadergraph/Editor/Drawing/Controls/DielectricSpecularControl.cs +++ b/com.unity.shadergraph/Editor/Drawing/Controls/DielectricSpecularControl.cs @@ -132,25 +132,25 @@ FloatField AddField(VisualElement panel, Slider slider, int index, DielectricSpe field.RegisterCallback(Repaint); field.RegisterCallback(Repaint); field.RegisterValueChangedCallback(evt => - { - var fieldValue = (float)evt.newValue; - if (index == 1) - m_DielectricMaterial.indexOfRefraction = fieldValue; - else - m_DielectricMaterial.range = fieldValue; - - m_PropertyInfo.SetValue(m_Node, m_DielectricMaterial, null); - this.MarkDirtyRepaint(); - }); + { + var fieldValue = (float)evt.newValue; + if (index == 1) + m_DielectricMaterial.indexOfRefraction = fieldValue; + else + m_DielectricMaterial.range = fieldValue; + + m_PropertyInfo.SetValue(m_Node, m_DielectricMaterial, null); + this.MarkDirtyRepaint(); + }); field.Q("unity-text-input").RegisterCallback(evt => - { - if (index == 1) - RedrawIORControls(m_DielectricMaterial.indexOfRefraction); - else - RedrawRangeControls(m_DielectricMaterial.range); + { + if (index == 1) + RedrawIORControls(m_DielectricMaterial.indexOfRefraction); + else + RedrawRangeControls(m_DielectricMaterial.range); - this.MarkDirtyRepaint(); - }); + this.MarkDirtyRepaint(); + }); panel.Add(field); return field; } diff --git a/com.unity.shadergraph/Editor/Drawing/Controls/VectorControl.cs b/com.unity.shadergraph/Editor/Drawing/Controls/VectorControl.cs index 6330ecd7d63..c81320c44f8 100644 --- a/com.unity.shadergraph/Editor/Drawing/Controls/VectorControl.cs +++ b/com.unity.shadergraph/Editor/Drawing/Controls/VectorControl.cs @@ -79,39 +79,39 @@ void AddField(int index, string subLabel) field.RegisterCallback(Repaint); field.RegisterCallback(Repaint); field.RegisterValueChangedCallback(evt => - { - var value = GetValue(); - value[index] = (float)evt.newValue; - SetValue(value); - m_UndoGroup = -1; - this.MarkDirtyRepaint(); - }); + { + var value = GetValue(); + value[index] = (float)evt.newValue; + SetValue(value); + m_UndoGroup = -1; + this.MarkDirtyRepaint(); + }); field.Q("unity-text-input").RegisterCallback(evt => + { + if (m_UndoGroup == -1) { - if (m_UndoGroup == -1) - { - m_UndoGroup = Undo.GetCurrentGroup(); - m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name); - } - float newValue; - if (!float.TryParse(evt.newData, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out newValue)) - newValue = 0f; - var value = GetValue(); - value[index] = newValue; - SetValue(value); - this.MarkDirtyRepaint(); - }); + m_UndoGroup = Undo.GetCurrentGroup(); + m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name); + } + float newValue; + if (!float.TryParse(evt.newData, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out newValue)) + newValue = 0f; + var value = GetValue(); + value[index] = newValue; + SetValue(value); + this.MarkDirtyRepaint(); + }); field.Q("unity-text-input").RegisterCallback(evt => + { + if (evt.keyCode == KeyCode.Escape && m_UndoGroup > -1) { - if (evt.keyCode == KeyCode.Escape && m_UndoGroup > -1) - { - Undo.RevertAllDownToGroup(m_UndoGroup); - m_UndoGroup = -1; - m_Value = GetValue(); - evt.StopPropagation(); - } - this.MarkDirtyRepaint(); - }); + Undo.RevertAllDownToGroup(m_UndoGroup); + m_UndoGroup = -1; + m_Value = GetValue(); + evt.StopPropagation(); + } + this.MarkDirtyRepaint(); + }); Add(field); } diff --git a/com.unity.shadergraph/Editor/Drawing/EdgeConnectorListener.cs b/com.unity.shadergraph/Editor/Drawing/EdgeConnectorListener.cs index 38a5e425aa7..e5644756e29 100644 --- a/com.unity.shadergraph/Editor/Drawing/EdgeConnectorListener.cs +++ b/com.unity.shadergraph/Editor/Drawing/EdgeConnectorListener.cs @@ -23,7 +23,7 @@ public void OnDropOutsidePort(Edge edge, Vector2 position) var draggedPort = (edge.output != null ? edge.output.edgeConnector.edgeDragHelper.draggedPort : null) ?? (edge.input != null ? edge.input.edgeConnector.edgeDragHelper.draggedPort : null); m_SearchWindowProvider.connectedPort = (ShaderPort)draggedPort; m_SearchWindowProvider.regenerateEntries = true;//need to be sure the entires are relevant to the edge we are dragging - SearcherWindow.Show(m_editorWindow, (m_SearchWindowProvider as SearcherProvider).LoadSearchWindow(), + SearcherWindow.Show(m_editorWindow, (m_SearchWindowProvider as SearcherProvider).LoadSearchWindow(), item => (m_SearchWindowProvider as SearcherProvider).OnSearcherSelectEntry(item, position), position, null); m_SearchWindowProvider.regenerateEntries = true;//entries no longer necessarily relevant, need to regenerate diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs index 89196d4531d..9331f52b11c 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/InspectorView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -87,7 +87,6 @@ public void InitializeGraphSettings() ShowGraphSettings_Internal(m_GraphSettingsContainer); } - // If any of the selected items are no longer selected, inspector requires an update public bool DoesInspectorNeedUpdate() { @@ -106,7 +105,7 @@ public void Update() //m_GraphInspectorView.Activate(m_NodeSettingsTab); foreach (var selectable in selection) { - if(selectable is IInspectable inspectable) + if (selectable is IInspectable inspectable) DrawInspectable(m_NodeSettingsContainer, inspectable); } } @@ -140,7 +139,7 @@ void TriggerInspectorUpdate() protected virtual void ShowGraphSettings_Internal(VisualElement contentContainer) { var graphEditorView = m_GraphView.GetFirstAncestorOfType(); - if(graphEditorView == null) + if (graphEditorView == null) return; contentContainer.Clear(); @@ -177,7 +176,7 @@ internal static void GatherInspectorContent( if (IsPropertyTypeHandled(propertyDrawerList, propertyType, out var propertyDrawerTypeToUse)) { var propertyDrawerInstance = propertyDrawerToUse ?? - (IPropertyDrawer) Activator.CreateInstance(propertyDrawerTypeToUse); + (IPropertyDrawer)Activator.CreateInstance(propertyDrawerTypeToUse); // Assign the inspector update delegate so any property drawer can trigger an inspector update if it needs it propertyDrawerInstance.inspectorUpdateDelegate = propertyChangeCallback; // Supply any required data to this particular kind of property drawer @@ -223,4 +222,3 @@ static bool IsPropertyTypeHandled( } } } - diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawerUtils.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawerUtils.cs index 7d7cca55769..15c870e838e 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawerUtils.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawerUtils.cs @@ -1,4 +1,4 @@ -using UnityEngine.UIElements; +using UnityEngine.UIElements; using UnityEngine; namespace UnityEditor.ShaderGraph.Drawing.Inspector diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/AbstractMaterialNodePropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/AbstractMaterialNodePropertyDrawer.cs index e5f3d281857..b873d4b56d3 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/AbstractMaterialNodePropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/AbstractMaterialNodePropertyDrawer.cs @@ -42,14 +42,14 @@ VisualElement CreateGUI(AbstractMaterialNode node, InspectableAttribute attribut m_updateNodeViewsCallback?.Invoke(); node.Dirty(ModificationScope.Graph); }); - + if (help != null) { nodeSettings.Insert(0, help); } } EnumField precisionField = null; - if(node.canSetPrecision) + if (node.canSetPrecision) { precisionField = new EnumField(node.precision); var propertyRow = new PropertyRow(new Label("Precision")); @@ -75,10 +75,11 @@ VisualElement CreateGUI(AbstractMaterialNode node, InspectableAttribute attribut propertyVisualElement = precisionField; return nodeSettings; } + public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject, InspectableAttribute attribute) { return this.CreateGUI( - (AbstractMaterialNode) actualObject, + (AbstractMaterialNode)actualObject, attribute, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/BoolPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/BoolPropertyDrawer.cs index 589950bea84..57b4fb70017 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/BoolPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/BoolPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.Graphing.Util; using UnityEditor.ShaderGraph.Drawing; @@ -29,7 +29,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - var toggle = (Toggle) propertyToggle; + var toggle = (Toggle)propertyToggle; toggle.OnToggleChanged(evt => valueChangedCallback(evt.newValue)); } @@ -47,7 +47,7 @@ public VisualElement DrawProperty( return this.CreateGUI( // Use the setter from the provided property as the callback newBoolValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newBoolValue}), - (bool) propertyInfo.GetValue(actualObject), + (bool)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ColorPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ColorPropertyDrawer.cs index a72688c9dc2..37f121f740e 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ColorPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ColorPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -23,7 +23,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - colorField.RegisterValueChangedCallback(evt => { valueChangedCallback((Color) evt.newValue); }); + colorField.RegisterValueChangedCallback(evt => { valueChangedCallback((Color)evt.newValue); }); } propertyColorField = colorField; @@ -40,7 +40,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Color) propertyInfo.GetValue(actualObject), + (Color)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CubemapPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CubemapPropertyDrawer.cs index 3d3e72ab531..095df8dc999 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CubemapPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CubemapPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -23,7 +23,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Cubemap) evt.newValue); }); + objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Cubemap)evt.newValue); }); } propertyCubemapField = objectField; @@ -41,7 +41,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Cubemap) propertyInfo.GetValue(actualObject), + (Cubemap)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CustomFunctionNodePropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CustomFunctionNodePropertyDrawer.cs index 52ebf2a4127..bdb572763a8 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CustomFunctionNodePropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/CustomFunctionNodePropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.Graphing; using UnityEditor.ShaderGraph; @@ -37,7 +37,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject InspectableAttribute attribute) { return this.CreateGUI( - (CustomFunctionNode) actualObject, + (CustomFunctionNode)actualObject, attribute, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/DropdownPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/DropdownPropertyDrawer.cs index 9274f22d43c..d335bd2a37c 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/DropdownPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/DropdownPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -24,7 +24,7 @@ internal VisualElement CreateGUI( var propertyRow = new PropertyRow(PropertyDrawerUtils.CreateLabel(labelName, indentLevel)); textArrayField = new PopupField(fieldToDraw.ToList(), 0); propertyRow.Add(textArrayField); - var popupField = (PopupField) textArrayField; + var popupField = (PopupField)textArrayField; popupField.RegisterValueChangedCallback(evt => { valueChangedCallback(popupField.index); @@ -41,7 +41,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newSelectedIndex => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newSelectedIndex}), - (IEnumerable) propertyInfo.GetValue(actualObject), + (IEnumerable)propertyInfo.GetValue(actualObject), attribute.labelName, out var textArrayField); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/EnumPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/EnumPropertyDrawer.cs index 83d4aa55ae3..d24b0233895 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/EnumPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/EnumPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.Graphing.Util; using UnityEditor.ShaderGraph.Drawing; @@ -29,7 +29,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - var enumField = (EnumField) propertyVisualElement; + var enumField = (EnumField)propertyVisualElement; enumField.RegisterValueChangedCallback(evt => valueChangedCallback(evt.newValue)); } @@ -44,10 +44,10 @@ public VisualElement DrawProperty( InspectableAttribute attribute) { return this.CreateGUI(newEnumValue => - propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newEnumValue}), - (Enum) propertyInfo.GetValue(actualObject), + propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newEnumValue}), + (Enum)propertyInfo.GetValue(actualObject), attribute.labelName, - (Enum) attribute.defaultValue, + (Enum)attribute.defaultValue, out var propertyVisualElement); } } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/FloatPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/FloatPropertyDrawer.cs index 873c0b949c3..b3aa31fcb88 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/FloatPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/FloatPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEngine; @@ -22,7 +22,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - floatField.RegisterValueChangedCallback(evt => { valueChangedCallback((float) evt.newValue); }); + floatField.RegisterValueChangedCallback(evt => { valueChangedCallback((float)evt.newValue); }); } propertyFloatField = floatField; @@ -40,7 +40,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (float) propertyInfo.GetValue(actualObject), + (float)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GradientPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GradientPropertyDrawer.cs index 530dfed104e..5eddbe9c7e3 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GradientPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GradientPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -23,7 +23,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Gradient) evt.newValue); }); + objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Gradient)evt.newValue); }); } propertyGradientField = objectField; @@ -42,7 +42,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Gradient) propertyInfo.GetValue(actualObject), + (Gradient)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GraphDataPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GraphDataPropertyDrawer.cs index 9d1e9ac3d18..f4d8d84c7a2 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GraphDataPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/GraphDataPropertyDrawer.cs @@ -36,7 +36,7 @@ VisualElement GetSettings(GraphData graphData, Action onChange) { var element = new VisualElement() { name = "graphSettings" }; - if(graphData.isSubGraph) + if (graphData.isSubGraph) return element; void RegisterActionToUndo(string actionName) @@ -59,24 +59,24 @@ void RegisterActionToUndo(string actionName) targetList.OnAddMenuItemCallback += (list, addMenuOptionIndex, addMenuOption) => - { - RegisterActionToUndo("Add Target"); - graphData.SetTargetActive(addMenuOptionIndex); - m_postChangeTargetSettingsCallback(); - }; + { + RegisterActionToUndo("Add Target"); + graphData.SetTargetActive(addMenuOptionIndex); + m_postChangeTargetSettingsCallback(); + }; targetList.RemoveItemCallback += (list, itemIndex) => - { - RegisterActionToUndo("Remove Target"); - graphData.SetTargetInactive(list[itemIndex].value); - m_postChangeTargetSettingsCallback(); - }; + { + RegisterActionToUndo("Remove Target"); + graphData.SetTargetInactive(list[itemIndex].value); + m_postChangeTargetSettingsCallback(); + }; element.Add(targetList); // Iterate active TargetImplementations - foreach(var target in graphData.activeTargets) + foreach (var target in graphData.activeTargets) { // Ensure enabled state is being tracked and get value bool foldoutActive; @@ -122,7 +122,7 @@ internal VisualElement CreateGUI(GraphData graphData) var enumPropertyDrawer = new EnumPropertyDrawer(); propertySheet.Add(enumPropertyDrawer.CreateGUI( - newValue => { m_postChangeConcretePrecisionCallback((ConcretePrecision) newValue); }, + newValue => { m_postChangeConcretePrecisionCallback((ConcretePrecision)newValue); }, graphData.concretePrecision, "Precision", ConcretePrecision.Single, diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IShaderPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IShaderPropertyDrawer.cs index 5bacaf60e85..23da36a3896 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IShaderPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IShaderPropertyDrawer.cs @@ -6,4 +6,4 @@ interface IShaderPropertyDrawer { internal void HandlePropertyField(PropertySheet propertySheet, PreChangeValueCallback preChangeValueCallback, PostChangeValueCallback postChangeValueCallback); } -} +} diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IntegerPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IntegerPropertyDrawer.cs index bfc793833f3..1bdfed9f3ed 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IntegerPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/IntegerPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -42,7 +42,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (int) propertyInfo.GetValue(actualObject), + (int)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/MatrixPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/MatrixPropertyDrawer.cs index 92906244aed..ec18f3419d7 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/MatrixPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/MatrixPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEngine; @@ -64,7 +64,7 @@ void HandleMatrix2Property( matrix2Property.GetRow(0), labelName, out var row0Field - )); + )); propertySheet.Add(vector2PropertyDrawer.CreateGUI( newValue => @@ -134,7 +134,7 @@ void HandleMatrix3Property( matrix3Property.GetRow(0), labelName, out var row0Field - )); + )); propertySheet.Add(vector3PropertyDrawer.CreateGUI( newValue => @@ -236,7 +236,7 @@ void HandleMatrix4Property( matrix4Property.GetRow(0), labelName, out var row0Field - )); + )); propertySheet.Add(vector4PropertyDrawer.CreateGUI( newValue => @@ -364,7 +364,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Matrix4x4) propertyInfo.GetValue(actualObject), + (Matrix4x4)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SampleVirtualTextureNodePropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SampleVirtualTextureNodePropertyDrawer.cs index e84f5aacc64..bb4eff6d014 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SampleVirtualTextureNodePropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SampleVirtualTextureNodePropertyDrawer.cs @@ -24,39 +24,39 @@ VisualElement CreateGUI(SampleVirtualTextureNode node, InspectableAttribute attr var enumPropertyDrawer = new EnumPropertyDrawer(); propertySheet.Add(enumPropertyDrawer.CreateGUI((newValue) => - { - if (node.addressMode == (SampleVirtualTextureNode.AddressMode) newValue) - return; + { + if (node.addressMode == (SampleVirtualTextureNode.AddressMode)newValue) + return; - node.owner.owner.RegisterCompleteObjectUndo("Address Mode Change"); - node.addressMode = (SampleVirtualTextureNode.AddressMode) newValue; - }, + node.owner.owner.RegisterCompleteObjectUndo("Address Mode Change"); + node.addressMode = (SampleVirtualTextureNode.AddressMode)newValue; + }, node.addressMode, "Address Mode", SampleVirtualTextureNode.AddressMode.VtAddressMode_Wrap, out var addressModeVisualElement)); propertySheet.Add(enumPropertyDrawer.CreateGUI((newValue) => - { - if (node.lodCalculation == (SampleVirtualTextureNode.LodCalculation) newValue) - return; + { + if (node.lodCalculation == (SampleVirtualTextureNode.LodCalculation)newValue) + return; - node.owner.owner.RegisterCompleteObjectUndo("Lod Mode Change"); - node.lodCalculation = (SampleVirtualTextureNode.LodCalculation) newValue; - }, + node.owner.owner.RegisterCompleteObjectUndo("Lod Mode Change"); + node.lodCalculation = (SampleVirtualTextureNode.LodCalculation)newValue; + }, node.lodCalculation, "Lod Mode", SampleVirtualTextureNode.LodCalculation.VtLevel_Automatic, out var lodCalculationVisualElement)); propertySheet.Add(enumPropertyDrawer.CreateGUI((newValue) => - { - if (node.sampleQuality == (SampleVirtualTextureNode.QualityMode) newValue) - return; + { + if (node.sampleQuality == (SampleVirtualTextureNode.QualityMode)newValue) + return; - node.owner.owner.RegisterCompleteObjectUndo("Quality Change"); - node.sampleQuality = (SampleVirtualTextureNode.QualityMode) newValue; - }, + node.owner.owner.RegisterCompleteObjectUndo("Quality Change"); + node.sampleQuality = (SampleVirtualTextureNode.QualityMode)newValue; + }, node.sampleQuality, "Quality", SampleVirtualTextureNode.QualityMode.VtSampleQuality_High, @@ -64,13 +64,13 @@ VisualElement CreateGUI(SampleVirtualTextureNode node, InspectableAttribute attr var boolPropertyDrawer = new BoolPropertyDrawer(); propertySheet.Add(boolPropertyDrawer.CreateGUI((newValue) => - { - if (node.noFeedback == !newValue) - return; + { + if (node.noFeedback == !newValue) + return; - node.owner.owner.RegisterCompleteObjectUndo("Feedback Settings Change"); - node.noFeedback = !newValue; - }, + node.owner.owner.RegisterCompleteObjectUndo("Feedback Settings Change"); + node.noFeedback = !newValue; + }, !node.noFeedback, "Automatic Streaming", out var propertyToggle)); @@ -117,7 +117,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject InspectableAttribute attribute) { return this.CreateGUI( - (SampleVirtualTextureNode) actualObject, + (SampleVirtualTextureNode)actualObject, attribute, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs index bb476a62ab9..88d9b4a643b 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs @@ -59,7 +59,7 @@ public ShaderInputPropertyDrawer() } GraphData graphData; - bool isSubGraph { get ; set; } + bool isSubGraph { get; set; } ChangeExposedFieldCallback _exposedFieldChangedCallback; ChangeDisplayNameCallback _displayNameChangedCallback; ChangeReferenceNameCallback _referenceNameChangedCallback; @@ -119,7 +119,7 @@ void BuildPropertyNameLabel(PropertySheet propertySheet) void BuildExposedField(PropertySheet propertySheet) { - if(!isSubGraph) + if (!isSubGraph) { var toggleDataPropertyDrawer = new ToggleDataPropertyDrawer(); propertySheet.Add(toggleDataPropertyDrawer.CreateGUI( @@ -145,7 +145,7 @@ void BuildDisplayNameField(PropertySheet propertySheet) "Name", out var propertyVisualElement)); - m_DisplayNameField = (TextField) propertyVisualElement; + m_DisplayNameField = (TextField)propertyVisualElement; m_DisplayNameField.RegisterValueChangedCallback( evt => { @@ -160,7 +160,7 @@ void BuildDisplayNameField(PropertySheet propertySheet) this._postChangeValueCallback(true, ModificationScope.Topological); }); - if(!string.IsNullOrEmpty(shaderInput.displayName)) + if (!string.IsNullOrEmpty(shaderInput.displayName)) propertyVisualElement.AddToClassList("modified"); propertyVisualElement.SetEnabled(shaderInput.isRenamable); propertyVisualElement.styleSheets.Add(Resources.Load("Styles/PropertyNameReferenceField")); @@ -177,7 +177,7 @@ void BuildReferenceNameField(PropertySheet propertySheet) "Reference", out var propertyVisualElement)); - m_ReferenceNameField = (TextField) propertyVisualElement; + m_ReferenceNameField = (TextField)propertyVisualElement; m_ReferenceNameField.RegisterValueChangedCallback( evt => { @@ -198,7 +198,7 @@ void BuildReferenceNameField(PropertySheet propertySheet) m_ReferenceNameField.RemoveFromClassList("modified"); }; - if(!string.IsNullOrEmpty(shaderInput.overrideReferenceName)) + if (!string.IsNullOrEmpty(shaderInput.overrideReferenceName)) propertyVisualElement.AddToClassList("modified"); propertyVisualElement.SetEnabled(shaderInput.isRenamable); propertyVisualElement.styleSheets.Add(Resources.Load("Styles/PropertyNameReferenceField")); @@ -208,7 +208,7 @@ void BuildReferenceNameField(PropertySheet propertySheet) void BuildPropertyFields(PropertySheet propertySheet) { var property = shaderInput as AbstractShaderProperty; - if(property == null) + if (property == null) return; if (property.sgVersion < property.latestVersion) @@ -223,62 +223,62 @@ void BuildPropertyFields(PropertySheet propertySheet) switch (property) { - case IShaderPropertyDrawer propDrawer: - propDrawer.HandlePropertyField(propertySheet, _preChangeValueCallback, _postChangeValueCallback); - break; - case UnityEditor.ShaderGraph.Serialization.MultiJsonInternal.UnknownShaderPropertyType unknownProperty: - var helpBox = new HelpBoxRow(MessageType.Warning); - helpBox.Add(new Label("Cannot find the code for this Property, a package may be missing.")); - propertySheet.Add(helpBox); - break; - case Vector1ShaderProperty vector1Property: - HandleVector1ShaderProperty(propertySheet, vector1Property); - break; - case Vector2ShaderProperty vector2Property: - HandleVector2ShaderProperty(propertySheet, vector2Property); - break; - case Vector3ShaderProperty vector3Property: - HandleVector3ShaderProperty(propertySheet, vector3Property); - break; - case Vector4ShaderProperty vector4Property: - HandleVector4ShaderProperty(propertySheet, vector4Property); - break; - case ColorShaderProperty colorProperty: - HandleColorProperty(propertySheet, colorProperty); - break; - case Texture2DShaderProperty texture2DProperty: - HandleTexture2DProperty(propertySheet, texture2DProperty); - break; - case Texture2DArrayShaderProperty texture2DArrayProperty: - HandleTexture2DArrayProperty(propertySheet, texture2DArrayProperty); - break; - case VirtualTextureShaderProperty virtualTextureProperty: - HandleVirtualTextureProperty(propertySheet, virtualTextureProperty); - break; - case Texture3DShaderProperty texture3DProperty: - HandleTexture3DProperty(propertySheet, texture3DProperty); - break; - case CubemapShaderProperty cubemapProperty: - HandleCubemapProperty(propertySheet, cubemapProperty); - break; - case BooleanShaderProperty booleanProperty: - HandleBooleanProperty(propertySheet, booleanProperty); - break; - case Matrix2ShaderProperty matrix2Property: - HandleMatrix2PropertyField(propertySheet, matrix2Property); - break; - case Matrix3ShaderProperty matrix3Property: - HandleMatrix3PropertyField(propertySheet, matrix3Property); - break; - case Matrix4ShaderProperty matrix4Property: - HandleMatrix4PropertyField(propertySheet, matrix4Property); - break; - case SamplerStateShaderProperty samplerStateProperty: - HandleSamplerStatePropertyField(propertySheet, samplerStateProperty); - break; - case GradientShaderProperty gradientProperty: - HandleGradientPropertyField(propertySheet, gradientProperty); - break; + case IShaderPropertyDrawer propDrawer: + propDrawer.HandlePropertyField(propertySheet, _preChangeValueCallback, _postChangeValueCallback); + break; + case UnityEditor.ShaderGraph.Serialization.MultiJsonInternal.UnknownShaderPropertyType unknownProperty: + var helpBox = new HelpBoxRow(MessageType.Warning); + helpBox.Add(new Label("Cannot find the code for this Property, a package may be missing.")); + propertySheet.Add(helpBox); + break; + case Vector1ShaderProperty vector1Property: + HandleVector1ShaderProperty(propertySheet, vector1Property); + break; + case Vector2ShaderProperty vector2Property: + HandleVector2ShaderProperty(propertySheet, vector2Property); + break; + case Vector3ShaderProperty vector3Property: + HandleVector3ShaderProperty(propertySheet, vector3Property); + break; + case Vector4ShaderProperty vector4Property: + HandleVector4ShaderProperty(propertySheet, vector4Property); + break; + case ColorShaderProperty colorProperty: + HandleColorProperty(propertySheet, colorProperty); + break; + case Texture2DShaderProperty texture2DProperty: + HandleTexture2DProperty(propertySheet, texture2DProperty); + break; + case Texture2DArrayShaderProperty texture2DArrayProperty: + HandleTexture2DArrayProperty(propertySheet, texture2DArrayProperty); + break; + case VirtualTextureShaderProperty virtualTextureProperty: + HandleVirtualTextureProperty(propertySheet, virtualTextureProperty); + break; + case Texture3DShaderProperty texture3DProperty: + HandleTexture3DProperty(propertySheet, texture3DProperty); + break; + case CubemapShaderProperty cubemapProperty: + HandleCubemapProperty(propertySheet, cubemapProperty); + break; + case BooleanShaderProperty booleanProperty: + HandleBooleanProperty(propertySheet, booleanProperty); + break; + case Matrix2ShaderProperty matrix2Property: + HandleMatrix2PropertyField(propertySheet, matrix2Property); + break; + case Matrix3ShaderProperty matrix3Property: + HandleMatrix3PropertyField(propertySheet, matrix3Property); + break; + case Matrix4ShaderProperty matrix4Property: + HandleMatrix4PropertyField(propertySheet, matrix4Property); + break; + case SamplerStateShaderProperty samplerStateProperty: + HandleSamplerStatePropertyField(propertySheet, samplerStateProperty); + break; + case GradientShaderProperty gradientProperty: + HandleGradientPropertyField(propertySheet, gradientProperty); + break; } BuildPrecisionField(propertySheet, property); @@ -304,7 +304,7 @@ void BuildHLSLDeclarationOverrideFields(PropertySheet propertySheet, AbstractSha bool anyAllowed = false; for (int i = 0; i < hlslDecls.Length; i++) { - HLSLDeclaration decl = (HLSLDeclaration) hlslDecls.GetValue(i); + HLSLDeclaration decl = (HLSLDeclaration)hlslDecls.GetValue(i); var allowed = property.AllowHLSLDeclaration(decl); anyAllowed = anyAllowed || allowed; if (allowed) @@ -317,8 +317,8 @@ void BuildHLSLDeclarationOverrideFields(PropertySheet propertySheet, AbstractSha var popupField = new PopupField( allowedDecls, property.GetDefaultHLSLDeclaration(), - (h => allHLSLDeclarationStrings[(int) h]), - (h => allHLSLDeclarationStrings[(int) h])); + (h => allHLSLDeclarationStrings[(int)h]), + (h => allHLSLDeclarationStrings[(int)h])); popupField.RegisterValueChangedCallback( evt => @@ -372,14 +372,14 @@ void BuildPrecisionField(PropertySheet propertySheet, AbstractShaderProperty pro { var enumPropertyDrawer = new EnumPropertyDrawer(); propertySheet.Add(enumPropertyDrawer.CreateGUI(newValue => - { - this._preChangeValueCallback("Change Precision"); - if (property.precision == (Precision) newValue) - return; - property.precision = (Precision)newValue; - this._precisionChangedCallback(); - this._postChangeValueCallback(); - }, property.precision, "Precision", Precision.Inherit, out var precisionField)); + { + this._preChangeValueCallback("Change Precision"); + if (property.precision == (Precision)newValue) + return; + property.precision = (Precision)newValue; + this._precisionChangedCallback(); + this._postChangeValueCallback(); + }, property.precision, "Precision", Precision.Inherit, out var precisionField)); if (property is Serialization.MultiJsonInternal.UnknownShaderPropertyType) precisionField.SetEnabled(false); } @@ -431,9 +431,9 @@ void HandleVector1ShaderProperty(PropertySheet propertySheet, Vector1ShaderPrope "Max", out var maxFloatField)); - var defaultField = (FloatField) propertyFloatField; - var minField = (FloatField) minFloatField; - var maxField = (FloatField) maxFloatField; + var defaultField = (FloatField)propertyFloatField; + var minField = (FloatField)minFloatField; + var maxField = (FloatField)maxFloatField; minField.Q("unity-text-input").RegisterCallback(evt => { @@ -495,7 +495,7 @@ void HandleVector1ShaderProperty(PropertySheet propertySheet, Vector1ShaderPrope }, vector1ShaderProperty.floatType, "Mode", - FloatType.Default, + FloatType.Default, out var modePropertyEnumField)); } } @@ -507,7 +507,7 @@ void HandleVector2ShaderProperty(PropertySheet propertySheet, Vector2ShaderPrope vector2PropertyDrawer.postValueChangeCallback = () => this._postChangeValueCallback(); propertySheet.Add(vector2PropertyDrawer.CreateGUI( - newValue=> _changeValueCallback(newValue), + newValue => _changeValueCallback(newValue), vector2ShaderProperty.value, "Default", out var propertyVec2Field)); @@ -554,7 +554,7 @@ void HandleColorProperty(PropertySheet propertySheet, ColorShaderProperty colorP "Default", out var propertyColorField)); - var colorField = (ColorField) propertyColorField; + var colorField = (ColorField)propertyColorField; colorField.hdr = colorProperty.colorMode == ColorMode.HDR; if (!isSubGraph) @@ -573,7 +573,6 @@ void HandleColorProperty(PropertySheet propertySheet, ColorShaderProperty colorP ColorMode.Default, out var colorModeField)); } - } void HandleTexture2DProperty(PropertySheet propertySheet, Texture2DShaderProperty texture2DProperty) @@ -581,11 +580,11 @@ void HandleTexture2DProperty(PropertySheet propertySheet, Texture2DShaderPropert var texture2DPropertyDrawer = new Texture2DPropertyDrawer(); propertySheet.Add(texture2DPropertyDrawer.CreateGUI( newValue => - { - this._preChangeValueCallback("Change property value"); - this._changeValueCallback(newValue); - this._postChangeValueCallback(); - }, + { + this._preChangeValueCallback("Change property value"); + this._changeValueCallback(newValue); + this._postChangeValueCallback(); + }, texture2DProperty.value.texture, "Default", out var texture2DField @@ -596,13 +595,13 @@ out var texture2DField var enumPropertyDrawer = new EnumPropertyDrawer(); propertySheet.Add(enumPropertyDrawer.CreateGUI( newValue => - { - this._preChangeValueCallback("Change Texture mode"); - if(texture2DProperty.defaultType == (Texture2DShaderProperty.DefaultType)newValue) - return; - texture2DProperty.defaultType = (Texture2DShaderProperty.DefaultType) newValue; - this._postChangeValueCallback(false, ModificationScope.Graph); - }, + { + this._preChangeValueCallback("Change Texture mode"); + if (texture2DProperty.defaultType == (Texture2DShaderProperty.DefaultType)newValue) + return; + texture2DProperty.defaultType = (Texture2DShaderProperty.DefaultType)newValue; + this._postChangeValueCallback(false, ModificationScope.Graph); + }, texture2DProperty.defaultType, "Mode", Texture2DShaderProperty.DefaultType.White, @@ -627,7 +626,8 @@ void HandleTexture2DArrayProperty(PropertySheet propertySheet, Texture2DArraySha out var texture2DArrayField )); } -#region VT reorderable list handler + + #region VT reorderable list handler void HandleVirtualTextureProperty(PropertySheet propertySheet, VirtualTextureShaderProperty virtualTextureProperty) { var container = new IMGUIContainer(() => OnVTGUIHandler(virtualTextureProperty)) {name = "ListContainer"}; @@ -703,7 +703,7 @@ void HandleVirtualTextureProperty(PropertySheet propertySheet, VirtualTextureSha int index = m_VTReorderableList.index; if (index >= 0 && index < m_VTReorderableList.list.Count) - (m_VTReorderableList.list[index] as SerializableVirtualTextureLayer).layerTextureType = (LayerTextureType) evt.newValue; + (m_VTReorderableList.list[index] as SerializableVirtualTextureLayer).layerTextureType = (LayerTextureType)evt.newValue; this._postChangeValueCallback(false, ModificationScope.Graph); }); @@ -712,7 +712,7 @@ void HandleVirtualTextureProperty(PropertySheet propertySheet, VirtualTextureSha private void OnVTGUIHandler(VirtualTextureShaderProperty property) { - if(m_VTReorderableList == null) + if (m_VTReorderableList == null) { VTRecreateList(property); VTAddCallbacks(property); @@ -865,7 +865,8 @@ private void VTReorderEntries(ReorderableList list) { this._postChangeValueCallback(true); } -#endregion + + #endregion void HandleTexture3DProperty(PropertySheet propertySheet, Texture3DShaderProperty texture3DShaderProperty) { var texture3DPropertyDrawer = new Texture3DPropertyDrawer(); @@ -895,7 +896,7 @@ void HandleCubemapProperty(PropertySheet propertySheet, CubemapShaderProperty cu cubemapProperty.value.cubemap, "Default", out var propertyCubemapField - )); + )); } void HandleBooleanProperty(PropertySheet propertySheet, BooleanShaderProperty booleanProperty) @@ -973,7 +974,7 @@ void HandleSamplerStatePropertyField(PropertySheet propertySheet, SamplerStateSh { this._preChangeValueCallback("Change property value"); TextureSamplerState state = samplerStateShaderProperty.value; - state.filter = (TextureSamplerState.FilterMode) newValue; + state.filter = (TextureSamplerState.FilterMode)newValue; samplerStateShaderProperty.value = state; this._postChangeValueCallback(false, ModificationScope.Graph); this.inspectorUpdateDelegate(); @@ -988,7 +989,7 @@ void HandleSamplerStatePropertyField(PropertySheet propertySheet, SamplerStateSh { this._preChangeValueCallback("Change property value"); TextureSamplerState state = samplerStateShaderProperty.value; - state.wrap = (TextureSamplerState.WrapMode) newValue; + state.wrap = (TextureSamplerState.WrapMode)newValue; samplerStateShaderProperty.value = state; this._postChangeValueCallback(false, ModificationScope.Graph); this.inspectorUpdateDelegate(); @@ -1017,7 +1018,7 @@ void HandleGradientPropertyField(PropertySheet propertySheet, GradientShaderProp void BuildKeywordFields(PropertySheet propertySheet, ShaderInput shaderInput) { var keyword = shaderInput as ShaderKeyword; - if(keyword == null) + if (keyword == null) return; var enumPropertyDrawer = new EnumPropertyDrawer(); @@ -1025,9 +1026,9 @@ void BuildKeywordFields(PropertySheet propertySheet, ShaderInput shaderInput) newValue => { this._preChangeValueCallback("Change Keyword type"); - if (keyword.keywordDefinition == (KeywordDefinition) newValue) + if (keyword.keywordDefinition == (KeywordDefinition)newValue) return; - keyword.keywordDefinition = (KeywordDefinition) newValue; + keyword.keywordDefinition = (KeywordDefinition)newValue; }, keyword.keywordDefinition, "Definition", @@ -1042,9 +1043,9 @@ void BuildKeywordFields(PropertySheet propertySheet, ShaderInput shaderInput) newValue => { this._preChangeValueCallback("Change Keyword scope"); - if (keyword.keywordScope == (KeywordScope) newValue) + if (keyword.keywordScope == (KeywordScope)newValue) return; - keyword.keywordScope = (KeywordScope) newValue; + keyword.keywordScope = (KeywordScope)newValue; }, keyword.keywordScope, "Scope", @@ -1112,7 +1113,7 @@ static void AddPropertyRowToSheet(PropertySheet propertySheet, VisualElement con void OnKeywordGUIHandler() { - if(m_KeywordReorderableList == null) + if (m_KeywordReorderableList == null) { KeywordRecreateList(); KeywordAddCallbacks(); @@ -1124,7 +1125,7 @@ void OnKeywordGUIHandler() internal void KeywordRecreateList() { - if(!(shaderInput is ShaderKeyword keyword)) + if (!(shaderInput is ShaderKeyword keyword)) return; // Create reorderable list from entries @@ -1133,7 +1134,7 @@ internal void KeywordRecreateList() void KeywordAddCallbacks() { - if(!(shaderInput is ShaderKeyword keyword)) + if (!(shaderInput is ShaderKeyword keyword)) return; // Draw Header @@ -1152,14 +1153,14 @@ void KeywordAddCallbacks() KeywordEntry entry = ((KeywordEntry)m_KeywordReorderableList.list[index]); EditorGUI.BeginChangeCheck(); - var displayName = EditorGUI.DelayedTextField( new Rect(rect.x, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), entry.displayName, EditorStyles.label); - var referenceName = EditorGUI.TextField( new Rect(rect.x + rect.width / 2, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), entry.referenceName, + var displayName = EditorGUI.DelayedTextField(new Rect(rect.x, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), entry.displayName, EditorStyles.label); + var referenceName = EditorGUI.TextField(new Rect(rect.x + rect.width / 2, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), entry.referenceName, keyword.isBuiltIn ? EditorStyles.label : greyLabel); displayName = GetDuplicateSafeDisplayName(entry.id, displayName); referenceName = GetDuplicateSafeReferenceName(entry.id, displayName.ToUpper()); - if(EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck()) { keyword.entries[index] = new KeywordEntry(index + 1, displayName, referenceName); @@ -1201,7 +1202,7 @@ void KeywordSelectEntry(ReorderableList list) // Allowed indicies are 1-MAX_ENUM_ENTRIES int GetFirstUnusedID() { - if(!(shaderInput is ShaderKeyword keyword)) + if (!(shaderInput is ShaderKeyword keyword)) return 0; List unusedIDs = new List(); @@ -1223,7 +1224,7 @@ int GetFirstUnusedID() void KeywordAddEntry(ReorderableList list) { - if(!(shaderInput is ShaderKeyword keyword)) + if (!(shaderInput is ShaderKeyword keyword)) return; this._preChangeValueCallback("Add Keyword Entry"); @@ -1246,7 +1247,7 @@ void KeywordAddEntry(ReorderableList list) void KeywordRemoveEntry(ReorderableList list) { - if(!(shaderInput is ShaderKeyword keyword)) + if (!(shaderInput is ShaderKeyword keyword)) return; this._preChangeValueCallback("Remove Keyword Entry"); diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SubGraphOutputNodePropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SubGraphOutputNodePropertyDrawer.cs index f6efeb5255d..da12594c0c6 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SubGraphOutputNodePropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/SubGraphOutputNodePropertyDrawer.cs @@ -32,7 +32,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject InspectableAttribute attribute) { return this.CreateGUI( - (SubGraphOutputNode) actualObject, + (SubGraphOutputNode)actualObject, attribute, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/TextPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/TextPropertyDrawer.cs index 6b59e33c9df..af4e21a3ead 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/TextPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/TextPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.Graphing.Util; using UnityEditor.ShaderGraph.Drawing; @@ -29,7 +29,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - var textField = (TextField) propertyTextField; + var textField = (TextField)propertyTextField; textField.RegisterValueChangedCallback(evt => valueChangedCallback(evt.newValue)); } @@ -44,7 +44,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newStringValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newStringValue}), - (string) propertyInfo.GetValue(actualObject), + (string)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DArrayPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DArrayPropertyDrawer.cs index 6a906189500..d6cf498b952 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DArrayPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DArrayPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -23,7 +23,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture2DArray) evt.newValue); }); + objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture2DArray)evt.newValue); }); } propertyColorField = objectField; @@ -41,7 +41,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Texture2DArray) propertyInfo.GetValue(actualObject), + (Texture2DArray)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DPropertyDrawer.cs index 638bf528ed6..79e0a841860 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture2DPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -23,7 +23,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture) evt.newValue); }); + objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture)evt.newValue); }); } propertyColorField = objectField; @@ -41,7 +41,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Texture) propertyInfo.GetValue(actualObject), + (Texture)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture3DPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture3DPropertyDrawer.cs index 9f2f51b1744..922086d9bfa 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture3DPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Texture3DPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.ShaderGraph.Drawing; using UnityEditor.UIElements; @@ -23,7 +23,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture3D) evt.newValue); }); + objectField.RegisterValueChangedCallback(evt => { valueChangedCallback((Texture3D)evt.newValue); }); } propertyColorField = objectField; @@ -41,7 +41,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Texture3D) propertyInfo.GetValue(actualObject), + (Texture3D)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ToggleDataPropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ToggleDataPropertyDrawer.cs index 7caef400863..9512a370fcc 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ToggleDataPropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ToggleDataPropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor.Graphing.Util; using UnityEditor.ShaderGraph.Drawing; @@ -30,7 +30,7 @@ internal VisualElement CreateGUI( if (valueChangedCallback != null) { - var toggle = (Toggle) propertyToggle; + var toggle = (Toggle)propertyToggle; toggle.OnToggleChanged(evt => valueChangedCallback(new ToggleData(evt.newValue))); } @@ -48,7 +48,7 @@ public VisualElement DrawProperty( return this.CreateGUI( // Use the setter from the provided property as the callback newBoolValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newBoolValue}), - (ToggleData) propertyInfo.GetValue(actualObject), + (ToggleData)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector2PropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector2PropertyDrawer.cs index 2ff415b2f5e..008f0901f37 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector2PropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector2PropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor; using UnityEditor.ShaderGraph.Drawing; @@ -52,7 +52,6 @@ void CreateCallbacks() // Reset UndoGroup when done editing input field mUndoGroup = -1; }); - } internal VisualElement CreateGUI( @@ -97,7 +96,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Vector2) propertyInfo.GetValue(actualObject), + (Vector2)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector3PropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector3PropertyDrawer.cs index 9089aa6bfa5..8fccd632d2c 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector3PropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector3PropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; @@ -48,7 +48,6 @@ void CreateCallbacks() // Reset UndoGroup when done editing input field mUndoGroup = -1; }); - } public Vector3PropertyDrawer() @@ -98,7 +97,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Vector3) propertyInfo.GetValue(actualObject), + (Vector3)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector4PropertyDrawer.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector4PropertyDrawer.cs index fd34d665f86..322b1ecbfe3 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector4PropertyDrawer.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/Vector4PropertyDrawer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using UnityEditor; using UnityEditor.ShaderGraph.Drawing; @@ -47,7 +47,6 @@ void CreateCallbacks() // Reset UndoGroup when done editing input field mUndoGroup = -1; }); - } public Vector4PropertyDrawer() @@ -97,7 +96,7 @@ public VisualElement DrawProperty(PropertyInfo propertyInfo, object actualObject return this.CreateGUI( // Use the setter from the provided property as the callback newValue => propertyInfo.GetSetMethod(true).Invoke(actualObject, new object[] {newValue}), - (Vector4) propertyInfo.GetValue(actualObject), + (Vector4)propertyInfo.GetValue(actualObject), attribute.labelName, out var propertyVisualElement); } diff --git a/com.unity.shadergraph/Editor/Drawing/Inspector/TabbedView/TabButton.cs b/com.unity.shadergraph/Editor/Drawing/Inspector/TabbedView/TabButton.cs index 0611a47f199..35e9e8fb5b2 100644 --- a/com.unity.shadergraph/Editor/Drawing/Inspector/TabbedView/TabButton.cs +++ b/com.unity.shadergraph/Editor/Drawing/Inspector/TabbedView/TabButton.cs @@ -4,7 +4,7 @@ public class TabButton : VisualElement { - internal new class UxmlFactory : UxmlFactory { } + internal new class UxmlFactory : UxmlFactory {} internal new class UxmlTraits : VisualElement.UxmlTraits { @@ -25,16 +25,16 @@ public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext static readonly string UxmlName = "TabButton"; static readonly string s_UssClassName = "unity-tab-button"; static readonly string s_UssActiveClassName = s_UssClassName + "--active"; - + private Label m_Label; - + public bool IsCloseable { get; set; } public string TargetId { get; private set; } public VisualElement Target { get; set; } public event Action OnSelect; public event Action OnClose; - + public TabButton() { Init(); @@ -46,17 +46,17 @@ public TabButton(string text, VisualElement target) m_Label.text = text; Target = target; } - + private void PopulateContextMenu(ContextualMenuPopulateEvent populateEvent) { DropdownMenu dropdownMenu = populateEvent.menu; - if(IsCloseable) + if (IsCloseable) { dropdownMenu.AppendAction("Close Tab", e => OnClose(this)); } } - + private void CreateContextMenu(VisualElement visualElement) { ContextualMenuManipulator menuManipulator = new ContextualMenuManipulator(PopulateContextMenu); @@ -77,7 +77,7 @@ private void Init() visualTree.CloneTree(this); m_Label = this.Q