A least amount of indirect light where the title's ray-traced probes have none

After CS_ScreenProbes_TemporalResolve, the diffuse light (R9G9B9E5 image) is
raised to a constant floor; the title's lighting applies it. Level 0.6,
VICTORY_AMBIENT=<level>, 0 off. Runs a1 (too strong, scaled by exposure) and
a2 (balanced). a2 ended in a GPU page fault ("inside freed" staging buffers,
indirect mesh draw 21bd00836e1dfae5/a88fe11942146689): cause unknown.
Diagnostics: captures say where textures are and which host texture a placed
view is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
beloooo
2026-11-24 19:25:02 -05:00
parent beffaea675
commit 0603123774
6 changed files with 330 additions and 12 deletions

View File

@ -0,0 +1,239 @@
//! A least amount of indirect light.
//!
//! Grand Theft Auto VI's indirect diffuse light comes from probes it fills
//! by tracing rays, which do not run here yet: its program that resolves
//! them (`CS_ScreenProbes_TemporalResolve_*`) leaves next to nothing, and
//! whatever the sun does not reach directly is black. Right after that
//! program, pixels darker than a soft floor are raised to it. The floor is a
//! constant: the light in these images does not go with the title's exposure
//! (well-lit surfaces hold about the same in a shot at -5.5 EV and in one at
//! -9.75). The title's own lighting then applies it with the surfaces'
//! colors. Raised, not added: the result is the next frame's history.
//!
//! `VICTORY_AMBIENT=<level>` sets it (0 turns it off).
//! shortcut: the same light everywhere, from everywhere; gone once rays run.
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU32, Ordering};
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
use windows::Win32::Graphics::Direct3D::ID3DBlob;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::core::s;
use crate::host::{HostList, host};
use crate::object::This;
/// The programs it follows, by the start of their name.
pub(crate) const PROGRAM: &[u8] = b"CS_ScreenProbes_TemporalResolve";
/// Where they write the indirect diffuse light (R9G9B9E5 as 32-bit
/// integers): root parameter and place in its table.
pub(crate) const LIGHT: (u8, u32) = (1, 176);
const DEFAULT: f32 = 0.6;
/// The floor; `None` if off.
pub(crate) fn level() -> Option<f32> {
static LEVEL: OnceLock<f32> = OnceLock::new();
let level = *LEVEL.get_or_init(|| {
std::env::var("VICTORY_AMBIENT")
.ok()
.and_then(|v| v.trim().parse().ok())
.filter(|l: &f32| l.is_finite() && *l >= 0.0)
.unwrap_or(DEFAULT)
});
(level > 0.0).then_some(level)
}
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=4, b0), DescriptorTable(UAV(u0))"
cbuffer Floor : register(b0) { float level; float3 tint; };
RWTexture2D<uint> light : register(u0);
float3 unpack(uint v) {
return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0);
}
uint pack(float3 c) {
c = clamp(c, 0.0, 65408.0);
float most = max(c.r, max(c.g, c.b));
int e = clamp(int(floor(log2(max(most, 1e-9)))) + 16, 0, 31);
float scale = exp2(float(24 - e));
if (most * scale >= 511.5) { e = min(e + 1, 31); scale = exp2(float(24 - e)); }
uint3 m = min(uint3(c * scale + 0.5), 511u);
return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27);
}
[RootSignature(RS)]
[numthreads(8, 8, 1)]
void main(uint3 at : SV_DispatchThreadID) {
uint w, h;
light.GetDimensions(w, h);
if (at.x >= w || at.y >= h) return;
float3 least = tint * level;
float3 c = unpack(light[at.xy]);
const float3 weights = float3(0.2126, 0.7152, 0.0722);
float missing = saturate(1.0 - dot(c, weights) / dot(least, weights));
if (missing > 0.0) light[at.xy] = pack(c + least * missing);
}
"#;
/// Views, used in turn: more than the passes of every list in flight.
const SLOTS: u32 = 1024;
struct Pass {
root: ID3D12RootSignature,
pso: ID3D12PipelineState,
views: ID3D12DescriptorHeap,
step: u32,
next: AtomicU32,
}
// SAFETY: D3D12 objects are free-threaded.
unsafe impl Send for Pass {}
// SAFETY: as above.
unsafe impl Sync for Pass {}
fn make(device: &ID3D12Device) -> windows::core::Result<Pass> {
let mut code: Option<ID3DBlob> = None;
let mut errors: Option<ID3DBlob> = None;
// SAFETY: the source and names live through the call; out pointers ours.
let compiled = unsafe {
D3DCompile(
SOURCE.as_ptr().cast(),
SOURCE.len(),
s!("ambient"),
None,
None,
s!("main"),
s!("cs_5_1"),
0,
0,
&mut code,
Some(&mut errors),
)
};
let text = |b: &ID3DBlob| {
// SAFETY: the blob's own bytes.
unsafe { std::slice::from_raw_parts(b.GetBufferPointer().cast::<u8>(), b.GetBufferSize()) }
.to_vec()
};
if let Err(e) = compiled {
if let Some(errors) = errors {
tracing::warn!("ambient light: {}", String::from_utf8_lossy(&text(&errors)));
}
return Err(e);
}
let code = text(&code.ok_or_else(windows::core::Error::empty)?);
// SAFETY: the root signature is inside the shader; plain creations.
unsafe {
let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?;
let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})?;
let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
let views = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: kind,
NumDescriptors: SLOTS,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})?;
Ok(Pass {
root,
pso,
views,
step: device.GetDescriptorHandleIncrementSize(kind),
next: AtomicU32::new(0),
})
}
}
fn uav_barrier(list: &ID3D12GraphicsCommandList) {
let barrier = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
..Default::default()
};
// SAFETY: an open list; the barrier names no resource.
unsafe { list.ResourceBarrier(&[barrier]) };
}
/// Raises what `light` holds to the floor, in `list`, after the program that
/// wrote it as an image. Whether it recorded anything (the list's bindings
/// are then ours).
pub(crate) fn raise(list: &HostList, light: This) -> bool {
let (Some(level), Some(host)) = (level(), host()) else {
return false;
};
let Some(light) = crate::resource::host_resource(light) else {
return false;
};
static PASS: OnceLock<Option<Pass>> = OnceLock::new();
let Some(pass) = PASS
.get_or_init(|| {
make(&host.device)
.inspect_err(|e| tracing::warn!(error = %e, "no ambient light"))
.ok()
})
.as_ref()
else {
return false;
};
// SAFETY: a live resource.
let d = unsafe { light.GetDesc() };
static ONCE: std::sync::Once = std::sync::Once::new();
if d.Format != DXGI_FORMAT_R32_UINT {
ONCE.call_once(|| tracing::warn!(format = d.Format.0, "no ambient light: another format"));
return false;
}
ONCE.call_once(|| {
tracing::info!(level, width = d.Width, height = d.Height, "ambient light");
});
let slot = pass.next.fetch_add(1, Ordering::Relaxed) % SLOTS;
list.keep(light);
let l = &list.list;
uav_barrier(l);
// SAFETY: an open list; a live texture the list keeps, in the
// unordered-access state as the program before left it; a view in a slot
// no list in flight reads.
unsafe {
let cpu = pass.views.GetCPUDescriptorHandleForHeapStart();
let gpu = pass.views.GetGPUDescriptorHandleForHeapStart();
let at = D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: cpu.ptr + (slot * pass.step) as usize,
};
let view = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R32_UINT,
ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
..Default::default()
};
host.device
.CreateUnorderedAccessView(light, None::<&ID3D12Resource>, Some(&view), at);
l.SetDescriptorHeaps(&[Some(pass.views.clone())]);
l.SetComputeRootSignature(&pass.root);
l.SetPipelineState(&pass.pso);
let constants = [level, 1.0f32, 0.98, 0.94];
l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0);
l.SetComputeRootDescriptorTable(
1,
D3D12_GPU_DESCRIPTOR_HANDLE {
ptr: gpu.ptr + u64::from(slot * pass.step),
},
);
l.Dispatch((d.Width as u32).div_ceil(8), d.Height.div_ceil(8), 1);
}
uav_barrier(l);
true
}
#[cfg(test)]
mod tests {
/// The pass compiles with the system's compiler and the host takes it.
#[test]
fn ambient_pass_builds() {
let Some(host) = crate::host::host() else {
return;
};
super::make(&host.device).expect("the ambient pass");
}
}

View File

@ -462,6 +462,7 @@ pub(crate) fn dump_targets(frame: u64) {
));
}
}
args.push_str(&crate::resource::targets_text());
let _ = std::fs::write(folder.join("args.txt"), args);
let _ = std::fs::write(folder.join("passes.txt"), text.join("
"));

View File

@ -485,6 +485,34 @@ impl State {
Some(heap.memory())
}
/// After a dispatch of `p`: the least indirect light, if it is the
/// program that resolves that.
fn ambient(&self, list: &HostList, p: &crate::pipeline::host::HostPipeline) -> bool {
let Some(stage) = p.stages.first().filter(|s| s.shader.resolves_light) else {
return false;
};
let view = |kind: ResourceType, (slot, offset): (u8, u32)| {
let u = stage.translated().used.iter().find(|u| {
u.kind == kind
&& u.root == RootType::Table
&& (u.slot, u.table_offset_dwords) == (slot, offset)
})?;
let Some(Root::Table(table)) = self.roots_ref(true).get(usize::from(u.slot)) else {
return None;
};
crate::descriptor::view(table + u64::from(u.table_offset_dwords) * 4)
};
let light = match view(ResourceType::Uav, crate::ambient::LIGHT) {
Some(View::Unordered(r, ..)) => r,
_ => 0,
};
if light == 0 {
once!("no ambient light: other tables");
return false;
}
crate::ambient::raise(list, light as This)
}
/// The bound heap holding `handle`.
fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
self.heaps
@ -836,7 +864,8 @@ impl State {
DISPATCHED.fetch_add(1, Ordering::Relaxed);
// Depth textures it wrote as images get what it wrote; then the
// title's state goes back on the list.
if crate::twin::resolve(list) {
let lit = self.ambient(list, p);
if crate::twin::resolve(list) | lit {
self.continue_in(list);
}
}
@ -1690,8 +1719,8 @@ fn describe(view: Option<&View>) -> String {
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
format!(
"{}x{} f{} flags {:#x}",
d.Width, d.Height, d.Format.0, d.Flags.0
"{}x{} f{} flags {:#x} data {:#x}",
d.Width, d.Height, d.Format.0, d.Flags.0, crate::resource::data_of(r)
)
})
};
@ -1706,15 +1735,27 @@ fn describe(view: Option<&View>) -> String {
crate::descriptor::host::buffer_range(v)
))
),
Some(View::Placed(u, r, d)) => format!(
"placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
r[0],
u64::from(r[4]) | u64::from(r[5]) << 32,
r[6],
r[8],
r[11],
u64::from(d[10]) | u64::from(d[11]) << 32
),
Some(v @ View::Placed(u, r, d)) => {
let is = (!*u && r[0] != 1)
.then(|| crate::descriptor::host::placed_texture(v))
.flatten();
let is = match is {
Some(View::Shader(t, _)) => format!(
" is {t:#x} {}",
texture(t as This).unwrap_or_else(|| "no host texture".into())
),
_ => String::new(),
};
format!(
"placed uav={u} dim {} {}x{} f{} layout {:#x}{is} at {:#x}",
r[0],
u64::from(r[4]) | u64::from(r[5]) << 32,
r[6],
r[8],
r[11],
u64::from(d[10]) | u64::from(d[11]) << 32
)
}
// The first four values, as a colour rectangle's constants are.
Some(View::Constant(address, size))
if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>

View File

@ -56,6 +56,8 @@ pub mod shader_cache;
mod shadow;
pub mod signature;
#[cfg(windows)]
mod ambient;
#[cfg(windows)]
mod compose;
#[cfg(windows)]
mod twin;

View File

@ -64,6 +64,9 @@ pub(crate) struct Shader {
/// It animates or draws hair strands ([`hair_strands`]).
#[cfg(windows)]
hair: bool,
/// Its result gets the least indirect light ([`crate::ambient`]).
#[cfg(windows)]
pub(crate) resolves_light: bool,
#[cfg(windows)]
translated: OnceLock<Option<Translated>>,
}
@ -152,6 +155,10 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
#[cfg(windows)]
hair: hair_strands(bytes),
#[cfg(windows)]
resolves_light: bytes
.windows(crate::ambient::PROGRAM.len())
.any(|w| w == crate::ambient::PROGRAM),
#[cfg(windows)]
translated: OnceLock::new(),
})
})

View File

@ -891,6 +891,34 @@ fn target_at(address: u64, d: &ResourceDesc) -> Option<This> {
})
}
/// Every texture the host GPU writes, by title address (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn targets_text() -> String {
let targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
let mut text = String::new();
for (at, list) in targets.iter() {
for &r in list {
let o = &resource(r as This).desc;
let written = resource(r as This)
.host
.as_ref()
.map_or(0, |h| h.written.load(std::sync::atomic::Ordering::Relaxed));
text.push_str(&format!(
"target {at:#x} {r:#x} {}x{}x{} mips {} f{} flags {:#x} layout {:#x} written {written}
",
o.width, o.height, o.depth_or_array_size, o.mip_levels, o.format, o.flags, o.layout
));
}
}
text
}
/// Where the title has the texture `r`, and the host resource object (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn data_of(r: This) -> u64 {
resource(r).data() as u64
}
/// A list moves `texture` to `state`.
#[cfg(windows)]
pub(crate) fn note_written(resource_: This, state: u32) {