Skip to content

Commit b881c40

Browse files
authored
Batman Arkham Knight: engine motion vectors and jitter, DLSS/FSR upscaling, FSR 3 (#234)
* fix(Batman Arkham Knight): engine-driven velocities and jitter for DLSS - Always compute the engine's velocities (camera and objects): remove the motion blur setting gates and the "camera barely moved" early out of the camera velocity pass, by signature, while the motion blur effect itself still follows the user setting. - Replace the camera velocity compute shader: reproject with a single matrix built on the CPU in double precision (inverse current translated view projection, camera translation since last frame, previous translated view projection). The original used different units than the object velocities, no jitter and an approximated camera translation, which made DLSS reject history (shimmering and aliasing while moving). - Jitter the main view projection in the engine's own view jitter function, before all the derived view matrices, and read the jitter back from the rendered view for DLSS (same frame, no game/render thread mismatch). Views built from an already jittered view keep its jitter. - MVs are "previous UV - current UV": scale by the render resolution. - Reset DLSS when the camera velocity pass was skipped (camera cuts) or has no previous frame. - Find all patch sites by signature (no Steam/GOG offsets). * feat(Batman Arkham Knight): enable FSR 3 (tested at native resolution) * feat(Batman Arkham Knight): DLSS/FSR upscaling (quality modes) - Render at a lower resolution through the engine's ScreenPercentage view scaling, read from a mod owned value (the game setting is never touched, so it can't be saved to the game config). Quality modes: Native (DLAA), Quality, Balanced, Performance, Ultra Performance. - Fix the engine's broken ScreenPercentage path on PC: keep the scaled view rect at the top left (it was centered for compute passes only), and disable the engine upscale (it read black, the texture being still bound as UAV). - After super resolution, switch the view to the output rect before the first post process, so bloom, tonemapping, DOF and motion blur run at the output resolution. Replace the two post shaders that still read the render resolution depth/velocity (Gather<0>, RockOn preamble) to scale their load coordinates. - Pick the screen percentages so that the HUD canvas unscales back to exactly the output size (the engine truncates both ways). - More jitter phases when upscaling (8 * ratio^2), mip bias from the render scale, plus a user mip bias offset. * fix(Batman Arkham Knight): camera velocity pixel NDC from the view rect when upscaling The camera velocity pass constants have the full buffer size, not the (smaller) view rect, so camera motion vectors were scaled wrong when upscaling (up to ~2 px off near the screen edges, making DLSS reject history on the floor while moving). Measured in game: static pixels now match the reprojected geometry within 0.02 px at Quality. * feat(Batman Arkham Knight): game exposure for SR, single reset on camera cuts - Feed DLSS/FSR the game's eye adaptation exposure (1 / the 1x1 divisor written by TRockToneMap, converted by a 1x1 compute pass) instead of their auto exposure (option, on by default; DLSS uses it with presets J and K). - Run the camera velocity pass on engine flagged camera cut frames too (bPrevTransformsReset, bCameraCut, bInstantlySwitchPostProcessVolume): it writes no motion and resets SR, but stores the camera so the next frame has history again (it reset twice before). - Delete the game device data with its real type (its resources leaked). * style(Batman Arkham Knight): apply the repository clang-format rules * fix(Batman Arkham Knight): give super resolution unjittered motion vectors All the game velocities (the replaced camera velocity and the materials' object velocities) come from the jittered current and previous projections, so they contain "previous jitter - current jitter". They were passed with MVJittered. A small compute pass now removes that jitter change (the same for every pixel) into a separate texture for DLSS/FSR, and mvs_jittered is false, so the result doesn't depend on how each SR implementation cancels jitter. The engine motion blur still reads the original velocities. Verified with the DLSS debug overlay: the input motion vectors of a static scene are now zero (they shook before). An in-game A/B against MVJittered showed no visible difference in the DLSS output. * fix(Batman Arkham Knight): remove the jitter from the decal position reconstruction The decal pixel shaders (FRockDecalPixelShader, 1084 variants in the combined shader cache) rebuild the view position as "ndc * (1 / projection scale) * depth", which is only right for a centered projection. With the jittered projection it's off by the jitter (up to half a pixel, different every frame). FRockDecalVertexShader (0x52595883) is replaced: it passes the pixel shaders the clip position with the jitter removed. The jitter is taken from the view projection in cb1[0..3], so views without jitter are unaffected. SV_Position is unchanged. Checked statically only: same signatures as the original, and a float32 simulation of the vertex + pixel shader math (8-72 jitter phases, 360p-4K) gives a position error below 0.001 px (0.44-0.49 px before) with the same depth pixel. In game there was no visible difference before and after in the places tried. * fix(Batman Arkham Knight): keep the game anti aliasing when the engine patches can't be applied - The velocity and jitter patches are now all or nothing (like the upscaling ones). Without them super resolution isn't used and SMAA stays, instead of running with unusable velocities and a reset every frame. - The replaced camera velocity shader runs even without its hook: the reprojection matrix and view rect now default to "no motion" instead of zeroes (0 / 0 velocities). - The projection is only jittered after a frame where super resolution ran: it doesn't run with the game anti aliasing off, and nothing else resolves the jitter. Only compiled: the unsupported executable path can't be reached on the Steam build. * fix(Batman Arkham Knight): keep the render width even when upscaling The engine lighting is checkerboarded: FTileShadingComputeShader shades every other pixel (x = 2 * thread x + (y & 1)) and FRecomposeComputeShader fills in the rest. The two packed outputs sit side by side, the second "int(view width * 0.5)" columns to the right, so with an odd view width the last column of the first one lands on the first column of the second one. Odd widths came up at e.g. 1920x1080 Balanced (1113) and 3440x1440 Quality (2293). From the shader disassembly, the effect in game wasn't observed. The percentage search was checked for 15 output resolutions x 4 modes: always an even width, at most 0.53 percentage points above the nominal scale. * fix(Batman Arkham Knight): make the depth position reconstruction jitter aware in all shaders The game shaders that rebuild a position from the scene depth turn NDC into a view ray with the projection scale only, which is only right for a centered projection. With the jittered one the position is off by the jitter, differently every frame, so decals, lighting, shadows and AO shimmer. They are now live patched when the game creates them (jitter_patch.h), 2073 shaders in the shader caches: - 1084 deferred decal pixel shaders and 741 material pixel shaders: "ndc * scale" becomes "(ndc - jitter) * scale" - 248 compute shaders (tiled lighting, reflections, AO): "ndc / projection" becomes "(ndc - jitter) / projection", and the opposite where a view position is projected back to the screen The jitter is derived in the shader from the view constants it already has (cb1[0..2] and cb1[17]), so it's zero for views without jitter. Nothing is patched if the engine jitter patch couldn't be applied. This replaces the FRockDecalVertexShader replacement (0x52595883): the decals are now fixed in their pixel shaders, which also keeps the depth pixel coordinates untouched. OnBindPatchedShader() returns false so the game's own (in place patched) shader objects stay bound instead of Luma's later clones. 74 of the patched compute shaders use NVIDIA shader extensions (NV_EXTN_OP_VOTE_BALLOT through the fake UAV at u7), which only work in shaders created while the game has the extension slot set: with the clones whole lighting tiles flickered. These are the same rewrites as the "Dlss Anti Aliasing" mod on Nexus (3530) does: the patcher output was compared with it for the 29936 pixel and compute shaders of the game caches, the same 2073 are patched, with identical instructions. In game (RTX 5070 Ti, 4K): the jitter derived from the constants matches the one we set in 900 sampled dispatches and decal draws. The tile flicker is gone on the spot it was found on (16x16 blocks changing between frames: 0.6%, 4-12% with the clones, 0.2% unpatched). Whether distant lighting is visibly calmer wasn't compared, and other GPU vendors weren't tried.
1 parent 80936e7 commit b881c40

10 files changed

Lines changed: 1703 additions & 312 deletions
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Batman: Arkham Knight - FCameraVelocityComputeShader (CRC32 0x47811EB4), replaced.
2+
//
3+
// Writes camera-only motion for every pixel into the R16G16_FLOAT velocity
4+
// target before the base pass; moving objects later overwrite their pixels
5+
// with (curNDC - prevNDC) * (-0.5, 0.5), computed by the material shaders
6+
// with the jittered current and previous translated view projections.
7+
// The original shader reprojected through an approximated, projection divided matrix,
8+
// which gave velocities in different units than the objects, with a different jitter
9+
// and a wrong camera translation.
10+
// Here the jittered pixel NDC and depth go through a single matrix built on the CPU in double precision
11+
// (inverse current translated view projection, camera translation since last frame, previous translated view projection),
12+
// in homogeneous coordinates so that infinitely far pixels (sky, depth 1) work too.
13+
// The pixel NDC comes from the view rect we provide: the pass's own constants have the full buffer size,
14+
// which is wrong when upscaling (the view rect is smaller).
15+
// Bindings and thread layout are identical to the original.
16+
17+
#include "Includes/Common.hlsl"
18+
19+
cbuffer CameraVelocityCB : register(b0)
20+
{
21+
float4 c0[15];
22+
}
23+
24+
Texture2D<float4> SceneDepth : register(t0);
25+
RWTexture2D<float4> Velocity : register(u0);
26+
27+
[numthreads(16, 16, 1)] void main(uint3 id : SV_DispatchThreadID) {
28+
float device_depth = min(SceneDepth.Load(int3(id.xy, 0)).x, 1.0);
29+
30+
// Jittered NDC of the pixel center (the jitter is part of the matrices, like for the objects)
31+
float4 view_rect = LumaData.GameData.CameraVelocityViewRect; // Size (xy), origin (zw)
32+
float2 ndc = (float2(id.xy) - view_rect.zw + 0.5) * (float2(2.0, -2.0) / view_rect.xy) + float2(-1.0, 1.0);
33+
34+
float4x4 reprojection = float4x4(LumaData.GameData.ReprojectionMatrix[0], LumaData.GameData.ReprojectionMatrix[1], LumaData.GameData.ReprojectionMatrix[2], LumaData.GameData.ReprojectionMatrix[3]);
35+
float4 prev_clip = mul(float4(ndc, device_depth, 1.0), reprojection);
36+
float2 prev_ndc = prev_clip.xy / prev_clip.w;
37+
38+
float2 velocity = (ndc - prev_ndc) * float2(-0.5, 0.5);
39+
Velocity[id.xy] = float4(velocity, velocity.x, velocity.x);
40+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Batman: Arkham Knight - FGatherComputeShader<0> (CRC32 0xB2A276FD), replaced.
2+
//
3+
// First post process level: 2x2 downsample of the scene color, with the DOF near/far circle of confusion from the depth.
4+
// Same as the original, except that the depth is loaded at the render resolution: after super resolution upscaling
5+
// the post processes run at the output resolution, while the depth is still at the render resolution (top left of the texture).
6+
7+
#include "Includes/Common.hlsl"
8+
9+
cbuffer GatherCB : register(b0)
10+
{
11+
float4 c0[12];
12+
// c0[6].x: DOF focus distance, c0[6].y: DOF scale, c0[6].z: whether to apply the t2 lens effect
13+
// c0[7].x: scene color scale, c0[7].z: lens effect scale
14+
// c0[8].xy: half view size, c0[8].zw: view origin
15+
// c0[10].x, c0[11].y: projection scale
16+
}
17+
18+
cbuffer ViewCB : register(b1)
19+
{
20+
float4 c1[21];
21+
// c1[20].zw: depth linearisation (1 / (d * z - w))
22+
}
23+
24+
SamplerState Sampler : register(s0);
25+
Texture2D<float4> SceneDepth : register(t0);
26+
Texture2D<float4> SceneColor : register(t1);
27+
Texture2D<float4> LensEffect : register(t2);
28+
RWTexture2D<float4> Downsampled : register(u0);
29+
RWTexture2D<float4> DownsampledNear : register(u1);
30+
RWTexture2D<float4> DownsampledFar : register(u2);
31+
32+
// Color (rgb) and near/far circle of confusion of one full resolution pixel
33+
void GatherPixel(float2 pixel, float2 max_pixel, float2 ndc_scale, out float3 color, out float near_coc, out float far_coc)
34+
{
35+
int2 coords = int2(min(pixel, max_pixel));
36+
color = SceneColor.Load(int3(coords, 0)).rgb;
37+
// Identical to "coords" when not upscaling
38+
int2 depth_coords = int2((float2(coords) + 0.5) * LumaData.GameData.PostRenderScale.xy);
39+
float device_depth = min(SceneDepth.Load(int3(depth_coords, 0)).x, 1.0);
40+
float view_depth = 1.0 / (device_depth * c1[20].z - c1[20].w);
41+
42+
float2 ndc = (pixel - c0[8].zw + 0.5) * ndc_scale + float2(-2.0, 2.0);
43+
float3 view_position = view_depth * float3(ndc.x / c0[10].x, ndc.y / c0[11].y, 1.0);
44+
float coc = (1.0 - c0[6].x / length(view_position)) * c0[6].y;
45+
near_coc = saturate(-coc);
46+
far_coc = saturate(coc);
47+
}
48+
49+
[numthreads(16, 16, 1)] void main(uint3 thread_id : SV_DispatchThreadID) {
50+
float2 ndc_scale = float2(2.0, -2.0) / c0[8].xy;
51+
float2 max_pixel = c0[8].xy * 2.0 - 1.0;
52+
float2 pixel = float2(thread_id.xy * 2);
53+
54+
float3 color_sum = 0.0;
55+
float near_sum = 0.0;
56+
float far_sum = 0.0;
57+
const float2 offsets[4] = {float2(0.0, 0.0), float2(1.0, 0.0), float2(0.0, 1.0), float2(1.0, 1.0)};
58+
[unroll] for (int i = 0; i < 4; i++)
59+
{
60+
float3 color;
61+
float near_coc, far_coc;
62+
GatherPixel(pixel + offsets[i], max_pixel, ndc_scale, color, near_coc, far_coc);
63+
color_sum += color;
64+
near_sum += near_coc;
65+
far_sum += far_coc;
66+
}
67+
float4 near_output = float4(color_sum, near_sum) * 0.25;
68+
float4 far_output = float4(color_sum, far_sum) * 0.25;
69+
float3 output = far_output.rgb;
70+
71+
if (asuint(c0[6].z) != 0)
72+
{
73+
float4 lens_effect = LensEffect.SampleLevel(Sampler, float2(thread_id.xy) / c0[8].xy, 0.0);
74+
float scene_scale = 1.0 - saturate(lens_effect.a);
75+
float3 lens_color = lens_effect.rgb * c0[7].z;
76+
output = far_output.rgb * c0[7].x * scene_scale + lens_color;
77+
near_output.rgb = near_output.rgb * c0[7].x * scene_scale + lens_color;
78+
far_output.rgb = output;
79+
}
80+
81+
DownsampledNear[thread_id.xy] = near_output;
82+
DownsampledFar[thread_id.xy] = far_output;
83+
Downsampled[thread_id.xy] = output.rgbr;
84+
}

‎Shaders/Batman Arkham Knight/Includes/GameCBuffers.hlsl‎

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,26 @@
99
// Mirrors c++ name spaces.
1010
namespace CB
1111
{
12-
// Define the game specific cbuffer settings here. They don't need 4 bytes alignment.
13-
struct LumaGameSettings
14-
{
15-
float GameSetting01;
16-
uint GameSetting02;
17-
};
18-
19-
// Define the game specific cbuffer (instance/pass) data here
20-
struct LumaGameData
21-
{
22-
float Dummy; // hlsl doesn't support empty structs
23-
};
24-
}
12+
// Define the game specific cbuffer settings here. They don't need 4 bytes alignment.
13+
struct LumaGameSettings
14+
{
15+
float GameSetting01;
16+
uint GameSetting02;
17+
};
18+
19+
// Define the game specific cbuffer (instance/pass) data here
20+
struct LumaGameData
21+
{
22+
// Rows (row vector convention) of the matrix taking the current jittered NDC + device depth (camera velocity pass) to the previous frame's jittered clip space.
23+
// The previous view projection is relative to the previous view origin, so the camera translation is baked in here.
24+
float4 ReprojectionMatrix[4];
25+
// xy: render resolution / output resolution, for the post processes that run at output resolution after super resolution upscaling,
26+
// but still read the render resolution depth and velocity (1 when not upscaling). zw: unused.
27+
float4 PostRenderScale;
28+
// xy: size, zw: origin of the view rect rendered by the camera velocity pass (render resolution).
29+
// Its own constants have the full buffer size instead, which only matches when not upscaling.
30+
float4 CameraVelocityViewRect;
31+
};
32+
} // namespace CB
2533

2634
#endif // LUMA_GAME_CB_STRUCTS
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Batman: Arkham Knight - super resolution exposure.
2+
// The game's eye adaptation writes a 1x1 exposure divisor (the tonemapper input is scene color / value),
3+
// DLSS/FSR want the multiplier instead.
4+
5+
Texture2D<float> EngineExposure : register(t0);
6+
RWTexture2D<float> SRExposure : register(u0);
7+
8+
[numthreads(1, 1, 1)] void main() {
9+
SRExposure[uint2(0, 0)] = 1.0 / max(EngineExposure.Load(int3(0, 0, 0)), 0.0001);
10+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Batman: Arkham Knight - unjittered motion vectors for super resolution.
2+
// All the game velocities (our replaced camera velocity and the materials' object velocities) are computed
3+
// from the jittered current and previous view projections, so they include the jitter change since the previous frame.
4+
// That change is the same for every pixel, this removes it, so super resolution gets fully unjittered motion vectors
5+
// (zero on static geometry with a static camera).
6+
7+
cbuffer UnjitterCB : register(b0)
8+
{
9+
float4 Params; // xy: jitter change in UV (previous minus current frame), zw: render size in pixels
10+
}
11+
12+
Texture2D<float2> Velocity : register(t0);
13+
RWTexture2D<float2> UnjitteredVelocity : register(u0);
14+
15+
[numthreads(8, 8, 1)] void main(uint3 id : SV_DispatchThreadID) {
16+
if (any(float2(id.xy) >= Params.zw))
17+
{
18+
return;
19+
}
20+
UnjitteredVelocity[id.xy] = Velocity.Load(int3(id.xy, 0)) - Params.xy;
21+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Batman: Arkham Knight - TRockOnPreambleComputeShader (CRC32 0xF98BC308), replaced.
2+
//
3+
// Motion blur/DOF setup: writes the clamped velocity and linear depth of each pixel (u0), and the largest velocity of each 16x16 tile (u1).
4+
// Same as the original, except that the depth and velocity are loaded at the render resolution: after super resolution upscaling
5+
// the post processes run at the output resolution, while these buffers are still at the render resolution (top left of the textures).
6+
7+
#include "Includes/Common.hlsl"
8+
9+
cbuffer PreambleCB : register(b0)
10+
{
11+
float4 c0[8];
12+
// c0[6].xy: view size (output resolution after upscaling)
13+
// c0[7].zw: view origin
14+
}
15+
16+
cbuffer ViewCB : register(b1)
17+
{
18+
float4 c1[21];
19+
// c1[20].zw: depth linearisation (1 / (d * z - w))
20+
}
21+
22+
Texture2D<float4> SceneDepth : register(t0);
23+
Texture2D<float4> Velocity : register(t1);
24+
RWTexture2D<float4> VelocityAndDepth : register(u0);
25+
RWTexture2D<float4> TileMaxVelocity : register(u1);
26+
27+
groupshared uint MaxVelocityLengthSquared;
28+
29+
[numthreads(16, 16, 1)] void main(uint3 group_id : SV_GroupID, uint3 group_thread_id : SV_GroupThreadID, uint3 thread_id : SV_DispatchThreadID) {
30+
if (group_thread_id.y * 16 + group_thread_id.x == 0)
31+
{
32+
MaxVelocityLengthSquared = 0;
33+
}
34+
GroupMemoryBarrierWithGroupSync();
35+
36+
float2 pixel = float2(thread_id.xy) + c0[7].zw;
37+
uint2 coords = uint2(pixel);
38+
// Identical to "coords" when not upscaling
39+
uint2 render_coords = uint2((pixel + 0.5) * LumaData.GameData.PostRenderScale.xy);
40+
41+
float2 velocity = Velocity.Load(int3(render_coords, 0)).xy * -0.25;
42+
float2 max_velocity = 16.0 / c0[6].xy;
43+
velocity = min(max_velocity * 2.0, max(velocity, max_velocity * -2.0));
44+
45+
// Velocity lengths are positive floats, so they compare like their bits
46+
float velocity_length_squared = dot(velocity, velocity);
47+
InterlockedMax(MaxVelocityLengthSquared, asuint(velocity_length_squared));
48+
GroupMemoryBarrierWithGroupSync();
49+
if (MaxVelocityLengthSquared == asuint(velocity_length_squared))
50+
{
51+
TileMaxVelocity[group_id.xy] = float4(velocity, 0.0, 0.0);
52+
}
53+
54+
float device_depth = min(SceneDepth.Load(int3(render_coords, 0)).x, 1.0);
55+
float view_depth = 1.0 / (device_depth * c1[20].z - c1[20].w);
56+
VelocityAndDepth[coords] = float4(velocity, view_depth, 0.0);
57+
}

‎Source/Games/Batman Arkham Knight/Batman Arkham Knight.vcxproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
</ItemGroup>
6464
<PropertyGroup>
6565
<UseLumaNGX>true</UseLumaNGX>
66+
<UseLumaFSR>true</UseLumaFSR>
6667
<LumaPackage>false</LumaPackage>
6768
</PropertyGroup>
6869
<ImportGroup Label="ExtensionSettings">
@@ -302,6 +303,9 @@
302303
<ClCompile Include="..\..\Core\unity_build.cpp" />
303304
<ClCompile Include="main.cpp" />
304305
</ItemGroup>
306+
<ItemGroup>
307+
<ClInclude Include="jitter_patch.h" />
308+
</ItemGroup>
305309
<!-- Apply feature settings after the final per-configuration properties. -->
306310
<Import Project="..\Luma.DXP.props" Condition="Exists('..\Luma.DXP.props')" />
307311
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

‎Source/Games/Batman Arkham Knight/Batman Arkham Knight.vcxproj.filters‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,7 @@
44
<ClCompile Include="main.cpp" />
55
<ClCompile Include="..\..\Core\unity_build.cpp" />
66
</ItemGroup>
7+
<ItemGroup>
8+
<ClInclude Include="jitter_patch.h" />
9+
</ItemGroup>
710
</Project>

0 commit comments

Comments
 (0)