CGBJ's renderer, DLSS, an F1 settings menu, frame generation, ray tracing switch

The default of scripts\play-nvidia.ps1 changes: the game renders its own
720p and DLSS takes it to 1080p (Series S), in place of the half render
scale and the title's upscaler. -Resolution still reaches the older path.

- Renderer: codec-d/cool_fox f4b48ad (GPL-3.0) with this fork's NVIDIA
  fixes on top (residency.rs, stretch.rs, the ffx upscale dispatch).
- DLSS for the title's upscale, from avatarmanz/VIctory-7900XTX pull
  request 203 (feature `dlss`, VICTORY_UPSCALE=dlss), with
  VICTORY_DLSS_PRESET and a live sharpness setting.
- F1 settings menu in the game (host/menu.rs): saved to
  victory-settings.txt, applied by the launcher at the next start,
  "save and restart" from the menu. F3: the panel, now with the
  generated frame rate beside the real one.
- DLSS frame generation through NVIDIA Streamline (streamline.rs, fg.rs),
  2x to 6x, the amount changed while playing. Constants and the depth and
  motion vector tags are handed over at each present.
- VICTORY_FPS_CAP: the title's own 30 frames a second can be lifted
  (60, 120, none), live from the menu.
- Real ray tracing as an option (-RayTracing, VICTORY_BVH_BUILDER=1): on
  this renderer the structure builder runs on NVIDIA. Frame generation is
  left off with it: the two together run at about 0.1 fps, cause not found.
- VICTORY_HEAP_RECHECK_EVERY: textures picked by index looked at again
  for the whole run (a test against the posterized look).
- Get-NVIDIA-DLSS.cmd / scripts\get-nvidia-sdks.ps1: fetch the few NVIDIA
  files DLSS and frame generation need (about 70 MB) from NVIDIA's GitHub
  into nvidia-sdk\ (git-ignored). They are NVIDIA's, under NVIDIA's
  licences, and are not part of this repository. Without them the picture
  is stretched and there is no frame generation.
- scripts\build-nvidia.ps1; the launcher builds the layer when it is not
  built, and again with DLSS once those files are there.

Measured on an RTX 5070 (Series S, DLSS, opening rooms): about 15-17 fps
without ray tracing, 13-15 with it, before generated frames. What is known
to be wrong is in the README's new section.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
trustno1-coderandClaude Fable 5.2 committed 2026-11-26 17:56:14 -08:00
1 parent 9e7ab9d9a2
commit 63957271cd
55 files changed
+8030 -1313

No files matched your search

+3
View File
@@ -25,6 +25,9 @@ tempfile.workspace = true
[features]
# Debugging switches (frame capture, the host debug layer, per-draw data).
diagnostics = []
# NVIDIA DLSS for the title's upscale (`VICTORY_UPSCALE=dlss`); needs the DLSS
# SDK (NVIDIA/DLSS: include, lib/Windows_x86_64) at `VICTORY_DLSS_SDK`.
dlss = []
[lints]
workspace = true
+9
View File
@@ -42,4 +42,13 @@ fn main() {
}
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rustc-env=VICTORY_TRANSLATOR={}", hash.finalize().to_hex());
// The `dlss` feature links the DLSS SDK's loader (`nvsdk_ngx_d.lib`, the
// dynamic-CRT one) from `VICTORY_DLSS_SDK`.
println!("cargo:rerun-if-env-changed=VICTORY_DLSS_SDK");
if std::env::var_os("CARGO_FEATURE_DLSS").is_some() {
let sdk = std::env::var_os("VICTORY_DLSS_SDK")
.map(PathBuf::from)
.expect("the dlss feature needs VICTORY_DLSS_SDK (the NVIDIA/DLSS checkout)");
println!("cargo:rustc-link-search=native={}", sdk.join("lib/Windows_x86_64/x64").display());
}
}
+1 -16
View File
@@ -112,18 +112,6 @@ fn air() -> f32 {
})
}
/// LOCAL: how many times the estimate the title's own result may keep
/// (`VICTORY_AMBIENT_MOST=<multiple>`, 4 when unset). Without rays the
/// probes hold the sky's light indoors too; at 4 times the estimate a room
/// looked towards a window or the sky goes very bright.
fn most() -> f32 {
static SET: OnceLock<f32> = OnceLock::new();
*SET.get_or_init(|| {
let set = std::env::var("VICTORY_AMBIENT_MOST").unwrap_or_default();
set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(4.0)
})
}
/// Strength and radius of the creases' shade.
fn shade() -> [f32; 2] {
static SET: OnceLock<[f32; 2]> = OnceLock::new();
@@ -255,9 +243,6 @@ void clear_air(uint3 at : SV_DispatchThreadID) {
float far = float(at.z) / float(d);
float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far);
float3 c = scattered[at];
// LOCAL: a NaN or infinity in the air is summed along every view ray
// through it: black or white patches floating in the room.
if (any(isnan(c)) || any(isinf(c))) { scattered[at] = 0; return; }
float has = dot(c, LUMA);
if (has > cap) scattered[at] = c * (cap / has);
}
@@ -474,7 +459,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool {
words[6] = views.size[0];
words[7] = views.size[1];
words[8] = 0.04f32.to_bits();
words[9] = most().to_bits();
words[9] = 4.0f32.to_bits();
words[10] = air().to_bits();
let l = &list.list;
// SAFETY: an open list with the heap of the views set; the title's
+286 -205
View File
@@ -1,244 +1,325 @@
//! Ported from fxceless/victory-gta6 PR #1189 (Series S interface plane), `VICTORY_COMPOSE=1`.
//! A present's second plane laid over its first.
//!
//! A Series S title presents two planes (run 2026-11-25: plane 0 the
//! game, 1920x1080 or what the display mode makes it, plane 1 the
//! interface, 3840x2160); the console's display lays the second over the
//! first and scales both to the screen. The host shows one texture, so
//! the interface is laid over the game here, at the game plane's size,
//! into a texture of ours that is shown instead (filtered: the interface
//! is scaled down). shortcut: the planes' placement and source rectangles
//! are not read; both cover the screen. The interface's alpha is taken as
//! straight (`VICTORY_PLANE_PREMULTIPLIED=1`: premultiplied).
use std::sync::Mutex;
//! Two presented planes as one image: the console's display puts the second
//! (the interface) over the first (the scene), each scaled to the screen.
//! Grand Theft Auto VI presents so on Series S.
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::{PCSTR, s};
/// Frames of descriptors in the ring (three each): presents in flight
/// must not find theirs rewritten.
const SLOTS: u32 = 16;
use crate::host::Host;
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=3, b0), DescriptorTable(SRV(t0, numDescriptors=2), UAV(u0)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)"
cbuffer Size : register(b0) { uint w; uint h; uint premultiplied; };
Texture2D<float4> game : register(t0);
Texture2D<float4> ui : register(t1);
RWTexture2D<float4> outp : register(u0);
SamplerState linear_clamp : register(s0);
#define RS "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)"
Texture2D<float4> scene : register(t0);
Texture2D<float4> over : register(t1);
SamplerState smooth_ : register(s0);
struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; };
[RootSignature(RS)]
[numthreads(8, 8, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= w || id.y >= h) return;
float2 uv = (float2(id.xy) + 0.5) / float2(w, h);
float4 g = game.Load(int3(id.xy, 0));
float4 u = ui.SampleLevel(linear_clamp, uv, 0);
float3 c = premultiplied != 0 ? g.rgb * (1.0 - u.a) + u.rgb : lerp(g.rgb, u.rgb, u.a);
outp[id.xy] = float4(c, 1.0);
V vs(uint id : SV_VertexID) {
V v;
v.uv = float2((id << 1) & 2, id & 2);
v.at = float4(v.uv * float2(2, -2) + float2(-1, 1), 0, 1);
return v;
}
[RootSignature(RS)]
float4 ps(V v) : SV_Target {
float4 s = scene.SampleLevel(smooth_, v.uv, 0);
float4 o = over.SampleLevel(smooth_, v.uv, 0);
return float4(saturate(o.rgb + s.rgb * (1 - saturate(o.a))), 1);
}
"#;
struct Pass {
pub(crate) struct Composer {
root: ID3D12RootSignature,
pso: ID3D12PipelineState,
views: ID3D12DescriptorHeap,
cpu: usize,
gpu: u64,
views: Vec<ID3D12DescriptorHeap>,
step: u32,
next: u32,
/// The texture shown instead, by size.
out: Option<(u64, u32, ID3D12Resource)>,
}
// SAFETY: D3D12 objects are free-threaded; the pass is used under a lock.
unsafe impl Send for Pass {}
// SAFETY: D3D12 objects are free-threaded.
unsafe impl Send for Composer {}
// SAFETY: as above.
unsafe impl Sync for Composer {}
/// The pass: not tried yet, could not be made, or made.
static PASS: Mutex<Option<Option<Pass>>> = Mutex::new(None);
fn make(device: &ID3D12Device) -> windows::core::Result<Pass> {
fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result<ID3DBlob> {
let mut code: Option<ID3DBlob> = None;
// SAFETY: the source and names live through the call; the out pointer
// is ours.
// SAFETY: the source and names live through the call; the out pointer is
// ours.
unsafe {
D3DCompile(
SOURCE.as_ptr().cast(),
SOURCE.len(),
windows::core::s!("present planes"),
s!("compose"),
None,
None,
windows::core::s!("main"),
windows::core::s!("cs_5_1"),
entry,
target,
0,
0,
&mut code,
None,
)?;
}
let code = code.ok_or_else(windows::core::Error::empty)?;
// SAFETY: the blob's own bytes (the root signature is inside the
// shader); plain object creation and queries.
unsafe {
let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
},
..Default::default()
})?;
let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
let views: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: kind,
NumDescriptors: SLOTS * 3,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})?;
Ok(Pass {
cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
step: device.GetDescriptorHandleIncrementSize(kind),
root,
pso,
views,
next: 0,
out: None,
})
code.ok_or_else(windows::core::Error::empty)
}
impl Composer {
pub(crate) fn new(host: &Host, format: DXGI_FORMAT) -> windows::core::Result<Self> {
let (vs, ps) = (
compile(s!("vs"), s!("vs_5_1"))?,
compile(s!("ps"), s!("ps_5_1"))?,
);
// SAFETY: the blobs' own bytes, alive through the calls.
unsafe {
let bytes = |b: &ID3DBlob| {
std::slice::from_raw_parts(b.GetBufferPointer().cast::<u8>(), b.GetBufferSize())
};
let device = &host.device;
let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?;
let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE {
pShaderBytecode: b.GetBufferPointer(),
BytecodeLength: b.GetBufferSize(),
};
let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
VS: code(&vs),
PS: code(&ps),
SampleMask: u32::MAX,
RasterizerState: D3D12_RASTERIZER_DESC {
FillMode: D3D12_FILL_MODE_SOLID,
CullMode: D3D12_CULL_MODE_NONE,
..Default::default()
},
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 1,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
..Default::default()
};
desc.RTVFormats[0] = format;
desc.BlendState.RenderTarget[0].RenderTargetWriteMask =
D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8;
let pso = device.CreateGraphicsPipelineState(&desc)?;
Ok(Composer {
root,
pso,
views: Vec::new(),
step: device
.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV),
})
}
}
/// Each presenter command-list slot owns its own pair of SRVs. The swap
/// chain may have several outstanding presents; the slot is selected by
/// the completion fence, and its descriptors are only overwritten on reuse.
pub(crate) fn record(
&mut self,
host: &Host,
slot: usize,
list: &ID3D12GraphicsCommandList,
planes: [(&ID3D12Resource, DXGI_FORMAT); 2],
back: &ID3D12Resource,
(width, height): (u32, u32),
) -> windows::core::Result<()> {
while self.views.len() <= slot {
let heap = unsafe {
host.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 2,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})?
};
self.views.push(heap);
}
let views = &self.views[slot];
// SAFETY: an open list; the views are made in slots no frame in flight
// reads; live textures.
unsafe {
let (cpu, gpu) = (
views.GetCPUDescriptorHandleForHeapStart(),
views.GetGPUDescriptorHandleForHeapStart(),
);
for (i, plane) in planes.iter().enumerate() {
let at = D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: cpu.ptr + (i * self.step as usize),
};
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: plane.1,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV {
MipLevels: 1,
..Default::default()
},
},
};
host.device
.CreateShaderResourceView(Some(plane.0), Some(&desc), at);
}
let rtv = host.rtv(Some(back), None);
list.OMSetRenderTargets(1, Some(&rtv), false, None);
list.SetDescriptorHeaps(&[Some(views.clone())]);
list.SetGraphicsRootSignature(&self.root);
list.SetPipelineState(&self.pso);
list.SetGraphicsRootDescriptorTable(0, gpu);
list.IASetPrimitiveTopology(
windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
);
list.RSSetViewports(&[D3D12_VIEWPORT {
Width: width as f32,
Height: height as f32,
MaxDepth: 1.0,
..Default::default()
}]);
list.RSSetScissorRects(&[windows::Win32::Foundation::RECT {
left: 0,
top: 0,
right: width as i32,
bottom: height as i32,
}]);
list.DrawInstanced(3, 1, 0, 0);
}
Ok(())
}
}
/// Whether a host texture's format is one this pass reads and writes
/// (8-bit RGBA, typeless or not).
fn rgba8(format: DXGI_FORMAT) -> bool {
matches!(format.0, 27 | 28)
}
fn premultiplied() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PLANE_PREMULTIPLIED").is_some_and(|v| v == "1"))
}
/// Records, into the present's `list`, `ui` laid over `game` into a
/// texture of ours, and gives that texture, left in the copy-source
/// state. `game` is in the copy-source state (the present put it there);
/// `ui` is in `ui_state` and is left in it. `None` (nothing recorded) if
/// a format is not 8-bit RGBA or the pass could not be made.
pub(crate) fn record(
device: &ID3D12Device,
list: &ID3D12GraphicsCommandList,
game: &ID3D12Resource,
ui: &ID3D12Resource,
ui_state: u32,
) -> Option<ID3D12Resource> {
// SAFETY: live resources; plain queries.
let (gd, ud) = unsafe { (game.GetDesc(), ui.GetDesc()) };
if !rgba8(gd.Format) || !rgba8(ud.Format) {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
tracing::warn!(game = gd.Format.0, ui = ud.Format.0, "present planes not laid over each other: a format this pass does not read");
});
/// Select a legal float-sampled view of a display plane, preserving a typed
/// resource's format. Typeless resources use the corresponding display type.
pub(crate) fn view(d: &D3D12_RESOURCE_DESC) -> Option<DXGI_FORMAT> {
if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D
|| d.DepthOrArraySize != 1
|| d.SampleDesc.Count != 1
|| d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)
{
return None;
}
let mut kept = PASS.lock().unwrap_or_else(|e| e.into_inner());
if kept.is_none() {
*kept = Some(match make(device) {
Ok(p) => {
tracing::info!(premultiplied = premultiplied(), "present planes: the interface is laid over the game");
Some(p)
match d.Format.0 {
9 => Some(DXGI_FORMAT_R16G16B16A16_FLOAT),
23 => Some(DXGI_FORMAT_R10G10B10A2_UNORM),
27 => Some(DXGI_FORMAT_R8G8B8A8_UNORM),
90 => Some(DXGI_FORMAT_B8G8R8A8_UNORM),
10 | 11 | 13 | 24 | 26 | 28 | 29 | 31 | 67 | 87 | 91 => Some(d.Format),
_ => None,
}
}
#[cfg(all(test, feature = "diagnostics"))]
mod tests {
use super::*;
#[test]
fn composes_scaled_premultiplied_plane_on_gpu() {
let Some(host) = crate::host::host() else {
eprintln!("skipping display-plane readback: no D3D12 device");
return;
};
let format = DXGI_FORMAT_R8G8B8A8_UNORM;
let mut compositor = Composer::new(host, format).unwrap();
let list = host.new_list().unwrap();
let texture = |width: u64| -> ID3D12Resource {
let mut resource = None;
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: width,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
Format: format,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
..Default::default()
};
unsafe {
host.device
.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
},
D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATE_RENDER_TARGET,
None,
&mut resource,
)
.unwrap()
};
resource.unwrap()
};
// A half-red base at one resolution. The overlay at output resolution
// contains transparent, half-opaque green and fully opaque blue pixels.
let base = texture(1);
let overlay = texture(3);
let output = texture(3);
let target = D3D12_RESOURCE_STATE_RENDER_TARGET;
let read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
let cmds = &list.list;
unsafe {
cmds.ClearRenderTargetView(host.rtv(Some(&base), None), &[0.5, 0.0, 0.0, 1.0], None);
let overlay_rtv = host.rtv(Some(&overlay), None);
let colors = [
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.5, 0.0, 0.5],
[0.0, 0.0, 1.0, 1.0],
];
for (i, color) in colors.iter().enumerate() {
let rect = windows::Win32::Foundation::RECT {
left: i as i32,
right: i as i32 + 1,
top: 0,
bottom: 1,
};
cmds.ClearRenderTargetView(overlay_rtv, color, Some(&[rect]));
}
Err(e) => {
tracing::warn!(error = %e, "present planes: the pass that lays them over each other could not be made");
None
cmds.ResourceBarrier(&[
crate::host::transition(&base, target, read),
crate::host::transition(&overlay, target, read),
]);
compositor
.record(
host,
0,
cmds,
[(&base, format), (&overlay, format)],
&output,
(3, 1),
)
.unwrap();
cmds.ResourceBarrier(&[crate::host::transition(
&output,
target,
D3D12_RESOURCE_STATE_COPY_SOURCE,
)]);
let (buffer, footprint) =
crate::capture::read_back(&host.device, cmds, &output).unwrap();
list.close();
host.execute(&[&list]);
host.device.GetDeviceRemovedReason().unwrap();
let mut mapped = std::ptr::null_mut();
buffer.Map(0, None, Some(&mut mapped)).unwrap();
let start = mapped.cast::<u8>().add(footprint.Offset as usize);
let pixels: [u8; 12] = std::slice::from_raw_parts(start, 12).try_into().unwrap();
buffer.Unmap(0, None);
for (actual, expected) in pixels
.iter()
.zip([128, 0, 0, 255, 64, 128, 0, 255, 0, 0, 255, 255])
{
assert!(
actual.abs_diff(expected) <= 1,
"unexpected composite {pixels:?}"
);
}
});
eprintln!("D3D12 display-plane readback RGBA: {pixels:?}");
}
}
let pass = kept.as_mut()?.as_mut()?;
let (w, h) = (gd.Width, gd.Height);
if pass.out.as_ref().is_none_or(|o| (o.0, o.1) != (w, h)) {
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: w,
Height: h,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
..Default::default()
};
let mut out: Option<ID3D12Resource> = None;
// SAFETY: plain creation of a device-local texture.
unsafe {
device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, None, &mut out)
.ok()?;
}
pass.out = Some((w, h, out?));
}
let out = pass.out.as_ref()?.2.clone();
let first = (pass.next % SLOTS) * 3;
pass.next = pass.next.wrapping_add(1);
let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: pass.cpu + ((first + i) * pass.step) as usize };
let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: pass.gpu + u64::from(first * pass.step) };
let srv = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV {
MostDetailedMip: 0,
MipLevels: 1,
..Default::default()
},
},
};
let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 },
},
};
let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
let ui_state = D3D12_RESOURCE_STATES(ui_state as i32);
let t = crate::host::transition;
let mut before = vec![
t(game, D3D12_RESOURCE_STATE_COPY_SOURCE, read),
t(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
];
let mut after = vec![
t(game, read, D3D12_RESOURCE_STATE_COPY_SOURCE),
t(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
];
if ui_state != read {
before.push(t(ui, ui_state, read));
after.push(t(ui, read, ui_state));
}
let constants: [u32; 3] = [w as u32, h, u32::from(premultiplied())];
// SAFETY: an open list (the present's); slots of our heap; live
// resources and objects (the pass's own live as long as the process,
// the texture is kept by the present's list).
unsafe {
device.CreateShaderResourceView(game, Some(&srv), cpu(0));
device.CreateShaderResourceView(ui, Some(&srv), cpu(1));
device.CreateUnorderedAccessView(&out, None::<&ID3D12Resource>, Some(&uav), cpu(2));
list.ResourceBarrier(&before);
list.SetDescriptorHeaps(&[Some(pass.views.clone())]);
list.SetComputeRootSignature(&pass.root);
list.SetPipelineState(&pass.pso);
list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0);
list.SetComputeRootDescriptorTable(1, gpu);
list.Dispatch((w as u32).div_ceil(8), h.div_ceil(8), 1);
list.ResourceBarrier(&after);
}
Some(out)
}
+462 -57
View File
@@ -112,6 +112,8 @@ impl Made {
}
pub(crate) struct HostHeap {
pub(crate) buffer_sweep: Mutex<crate::draw::BufferSweep>,
pub(crate) buffer_frame: std::sync::atomic::AtomicU64,
pub(crate) heap: ID3D12DescriptorHeap,
cpu: usize,
step: u32,
@@ -424,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
/// Deferred slot flips recorded into an open or not-yet-submitted command
/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can
/// promote them out of the `neutral()` gray stand-in before sampling them.
pub(crate) struct PendingListFlip {
id: u64,
pub(crate) origin: (usize, u64),
flip: Flip,
}
impl PendingListFlip {
pub(crate) fn index(&self) -> u32 {
self.flip.index
}
pub(crate) fn handle(&self) -> u64 {
self.flip.handle
}
pub(crate) fn key(&self) -> u64 {
self.flip.key
}
}
static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
static PENDING_LIST_FLIPS: Mutex<Vec<PendingListFlip>> = Mutex::new(Vec::new());
static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn take_pending_list_flip(id: u64) -> Option<Flip> {
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return None;
}
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
let pos = pending.iter().position(|p| p.id == id)?;
let entry = pending.swap_remove(pos);
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
Some(entry.flip)
}
fn remove_pending_list_flip(id: u64) {
let _ = take_pending_list_flip(id);
}
/// Makes the slots whose new texture's upload has run
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
/// something else: the next texture pass does.
@@ -712,6 +756,12 @@ impl Spans {
/// pass last took the ranges ([`page_written`]). Kept apart from
/// [`REMAPPED`] so that what such writes do is counted by itself.
static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Physical-page writes retained specifically for one-shot decoration/ped
/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal
/// frames stay free of queue flooding while every bake still sees freshly
/// DirectStorage-streamed texture bytes immediately instead of waiting on
/// `RECHECK_FRAMES`.
static BAKE_PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Since the start: such ranges kept for a pass; ranges dropped because no
/// pass took them; slots of placed textures that held bytes of them when a
@@ -1134,29 +1184,46 @@ pub(crate) fn device_removed() -> Option<String> {
pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Bytes per element of a buffer view, as the console's descriptor holds
/// them for indexed reads (structured: the stride; raw: 1, the index is the
/// byte; typed: the format's); `None` if `view` is not a buffer view.
fn view_stride(view: &View) -> Option<u32> {
let (stride, raw, format) = view_elements(view)?;
Some(if stride > 0 {
/// Bytes per element and typed integer format bits of a buffer view, decoded
/// in a single pass over the view descriptor; `(None, 0)` if not a buffer view.
fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
let Some((stride, raw, format)) = view_elements(view) else {
return (None, 0);
};
let bytes = if stride > 0 {
stride
} else if raw {
1
} else {
crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
})
};
let kind = if stride == 0 && !raw {
match format {
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER,
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
} else {
0
};
(Some(bytes), kind)
}
/// What else the table of strides says of a typed buffer view of an integer
/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view.
/// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`.
fn view_stride_word(view: &View) -> u32 {
let (stride, kind) = view_stride_and_kind(view);
stride.unwrap_or(0) | kind
}
#[cfg(test)]
fn view_stride(view: &View) -> Option<u32> {
view_stride_and_kind(view).0
}
#[cfg(test)]
fn view_kind(view: &View) -> u32 {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
match view_elements(view) {
Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
view_stride_and_kind(view).1
}
/// A buffer view's structure stride, whether it is raw, and its format;
@@ -1568,6 +1635,8 @@ impl HostHeap {
})
.flatten();
let h = HostHeap {
buffer_sweep: Mutex::default(),
buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX),
heap,
cpu,
step,
@@ -1675,10 +1744,16 @@ impl HostHeap {
}
/// A plain point sampler at `at`.
/// LOCAL (11/26, `VICTORY_NULL_SAMPLER_LINEAR=1`): a linear one instead. The
/// oil-painting look of some runs is posterization (colour bands), as from a
/// colour-grading LUT read with a point sampler: a sampler slot whose
/// description was missed at start would read as this one all run.
fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
let Some(host) = host() else { return };
static LINEAR: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let linear = *LINEAR.get_or_init(|| std::env::var_os("VICTORY_NULL_SAMPLER_LINEAR").is_some_and(|v| v == "1"));
let desc = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
Filter: if linear { D3D12_FILTER_MIN_MAG_MIP_LINEAR } else { D3D12_FILTER_MIN_MAG_MIP_POINT },
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
@@ -1780,7 +1855,7 @@ impl HostHeap {
pub(crate) fn texture_news(&self) -> (u64, bool) {
let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes;
let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN))
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN))
}
/// Every title slot of the queue that is due at `frame`, and whether
@@ -1928,7 +2003,48 @@ impl HostHeap {
if ranges.is_empty() {
return 0;
}
self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
let due = crate::watch::page_writes() & 2 != 0;
let made_due = self.slots_written_under(&ranges, frame, due)[2];
if !due {
let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
kept.extend(ranges);
if kept.len() > 256 {
join(&mut kept);
const MOST: usize = 1 << 14;
if kept.len() > MOST {
let drop_n = kept.len() - MOST;
kept.drain(..drop_n);
}
}
}
made_due
}
/// Wakes uploaded placed-texture slots touched by recent physical-page
/// writes (DirectStorage completions) immediately (`due = frame`) right
/// before a one-shot ped/decoration bake draw.
pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize {
let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
if ranges.is_empty() {
return 0;
}
join(&mut ranges);
let mut slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
};
if slots.is_empty() {
return 0;
}
slots.sort_unstable();
slots.dedup();
slots.retain(|&slot| !self.tabled_lately(slot, frame));
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
for &slot in &slots {
textures.changed(slot, frame, frame);
}
slots.len()
}
/// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
@@ -2223,6 +2339,7 @@ impl HostHeap {
/// reads the table's dynamic slots).
pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
if show_after()
&& !crate::texture::BAKING.get()
&& index < self.count
&& !self.texture_slot_made_from(index, handle)
&& let Some(view) = super::view(handle)
@@ -2237,14 +2354,143 @@ impl HostHeap {
}
fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) {
use std::sync::atomic::Ordering::{Relaxed, Release};
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed);
let origin = (std::ptr::from_ref(list) as usize, list.epoch());
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(PendingListFlip {
id,
origin,
flip: Flip { after: 0, heap, index, handle, key, late },
});
PENDING_LIST_COUNT.store(pending.len(), Release);
}
struct PendingGuard(u64);
impl PendingGuard {
fn id(&self) -> u64 {
self.0
}
}
impl Drop for PendingGuard {
fn drop(&mut self) {
remove_pending_list_flip(self.0);
}
}
let guard = PendingGuard(id);
list.defer_host(move || {
let after = crate::host::submissions().0;
let flip = Flip { after, heap, index, handle, key, late };
// Call a `&self` method so Rust 2021+ moves the whole `guard`
// into this closure rather than copying `guard.0` and dropping
// `guard` immediately at the end of `flip()`.
let Some(mut flip) = take_pending_list_flip(guard.id()) else {
return;
};
flip.after = crate::host::submissions().0;
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
});
}
/// Whether any deferred slot flip or view remake for this heap requires
/// settling in-flight GPU submissions before exposing real textures to a
/// one-shot decoration bake draw.
pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool {
let own = std::ptr::from_ref(self) as usize;
let finished = crate::host::submissions().1;
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 {
let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
if pending.iter().any(|p| p.flip.heap == own) {
return true;
}
}
{
let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
if flips.iter().any(|f| f.heap == own && f.after > finished) {
return true;
}
}
let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
after.iter().any(|&(at, _)| at > finished)
}
/// Drains deferred flips still sitting in unsubmitted command lists for
/// this heap so a decoration bake can mirror them out of `neutral()`.
/// Entries that cannot be promoted yet (unmapped memory or deferred
/// staging) must be returned via [`HostHeap::restore_pending_list_flip`].
pub(crate) fn take_pending_list_flips(&self) -> Vec<PendingListFlip> {
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return Vec::new();
}
let own = std::ptr::from_ref(self) as usize;
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
let (mine, rest): (Vec<PendingListFlip>, Vec<PendingListFlip>) =
pending.drain(..).partition(|p| p.flip.heap == own);
*pending = rest;
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
mine
}
/// Re-queues an unpromoted deferred flip drained by
/// [`HostHeap::take_pending_list_flips`] so its originating command list
/// still flips it out of `neutral()` once submitted.
pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) {
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(item);
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
/// Whether title descriptor slot `handle` still holds record `key`.
pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool {
key != 0 && record_key(handle) == key
}
/// Looks up `(view, key)` for slot `index` prior to a synchronous bake
/// upload without replacing its current host descriptor with `neutral()`;
/// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and
/// updates `Spans`/stride tracking once the GPU copy finishes.
pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> {
if index >= self.count {
return None;
}
let key = record_key(handle);
let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?;
Some((view, key))
}
/// Exposes the real host descriptor for slot `index` after its synchronous
/// bake upload has completed on the GPU, updating `Spans`/stride tracking
/// without re-queuing the slot in `TextureQueue`.
pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool {
if index >= self.count || key == 0 {
return false;
}
let (published, stale) = {
let _made = self.made.lock(index);
if self.made.get(index) == Some(key) {
return false;
}
if record_key(handle) != key {
return false;
}
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
return false;
};
let stale = self.note_buffer(index, Some(&view), true);
if let Some(kept) = make(&view, self.at(index)) {
self.put(index);
self.quick_is(index, 0);
self.clear_twin(index);
self.made.set(index, key);
self.keep(index, kept);
(true, stale)
} else {
(false, stale)
}
};
self.unmake_stale(index, stale);
published
}
/// Makes the slots whose new view's upload has run
/// ([`HostHeap::texture_slot_flip`]); returns how many.
pub(crate) fn texture_slots_flip(&self) -> usize {
@@ -2262,6 +2508,7 @@ impl HostHeap {
ready
};
let mut flipped = 0;
let mut late_flipped = 0;
for f in ready {
let _made = self.made.lock(f.index);
let Some(shown) = self.made.get(f.index) else {
@@ -2304,6 +2551,7 @@ impl HostHeap {
same_bytes(was, f.key);
}
if let Some(since) = f.late {
late_flipped += 1;
let frames = crate::frame::current().saturating_sub(since);
let n = LATE[0].fetch_add(1, Relaxed) + 1;
let all = LATE[1].fetch_add(frames, Relaxed) + frames;
@@ -2322,7 +2570,7 @@ impl HostHeap {
}
}
FLIPPED[0].fetch_add(flipped as u64, Relaxed);
flipped
flipped + late_flipped
}
/// The memory of the texture title slot `index` views is there (again):
@@ -2351,6 +2599,7 @@ impl HostHeap {
}
self.put(index);
self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None);
}
@@ -2546,24 +2795,17 @@ impl HostHeap {
textures.remove(slot);
}
}
let stride = view.and_then(view_stride);
let kind = view.map_or(0, view_kind);
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// LOCAL (port of fxceless #1216): constant buffer views marked;
// programs read no other non-buffer slot as one.
let entry = match (stride, view) {
(Some(s), _) => s | kind,
(None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => {
victory_shader::emit::SLOT_STRIDE_CONSTANT
}
_ => kind,
};
// SAFETY: inside the mapping; shaders read it while we write (a
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(entry) };
}
let (stride, kind) = view.map_or((None, 0), view_stride_and_kind);
// LOCAL (port of fxceless #1216): constant buffer views marked;
// programs read no other non-buffer slot as one.
let entry = match (stride, view) {
(Some(s), _) => s | kind,
(None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => {
victory_shader::emit::SLOT_STRIDE_CONSTANT
}
_ => kind,
};
self.write_stride(index, entry);
let was = if stride.is_some() {
self.buffers.put(index);
true
@@ -2576,6 +2818,20 @@ impl HostHeap {
stale
}
/// Writes `word` (stride | format kind) for view-heap slot `index` into
/// the host's [`victory_shader::emit::SLOT_STRIDES`] table.
#[inline]
fn write_stride(&self, index: u32, word: u32) {
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// SAFETY: inside the mapping; shaders read it while we write (a
// single aligned dword: either value is one the slot had, and
// dynamic slots are exclusively owned until submission finishes).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) };
}
}
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
/// returned).
///
@@ -2603,6 +2859,7 @@ impl HostHeap {
}
self.put(index);
self.twin_made(index, kept.is_some() && twinned(view));
self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 });
self.keep(index, kept.flatten());
}
@@ -2635,13 +2892,14 @@ impl HostHeap {
}
let twin = twinned(&view);
let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?;
let stride_word = view_stride_word(&view);
let listed = Listed {
kind: crate::draw::view_kind(&view),
texture: is_texture_view(&view),
ready: (0, 0, false),
tabled: None,
};
views.made.insert(words, ListView { view, at, twin, kept, listed });
views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed });
}
let made = &views.made[&words];
self.copy_from(index, views.slot(made.at));
@@ -2651,6 +2909,7 @@ impl HostHeap {
} else {
self.clear_twin(index);
}
self.write_stride(index, made.stride_word);
self.keep(index, made.kept.clone());
Some(made.listed)
})
@@ -2675,6 +2934,7 @@ impl HostHeap {
} else {
null_view(self.at(index));
self.put(index);
self.write_stride(index, 0);
}
self.clear_twin(index);
self.keep(index, None);
@@ -2761,6 +3021,7 @@ impl HostHeap {
self.put(index);
// (Bound by its handle, not read by index.)
self.clear_twin(index);
self.write_stride(index, 1);
self.keep(index, Some(buffer.clone()));
}
@@ -2770,6 +3031,7 @@ impl HostHeap {
null_buffer_view(self.at(index));
self.put(index);
self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None);
}
@@ -2804,6 +3066,7 @@ impl HostHeap {
};
self.put(index);
self.clear_twin(index);
self.write_stride(index, 1);
self.keep(index, Some(buffer.clone()));
}
@@ -2833,6 +3096,7 @@ impl HostHeap {
};
self.put(index);
self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None);
}
@@ -2890,6 +3154,7 @@ impl HostHeap {
unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
}
self.twin_made(index, twin.is_some());
self.write_stride(index, 0);
// After the descriptor: what it showed is let go when nothing shows
// it any more.
self.keep(index, holds.then(|| buffer.clone()));
@@ -4203,24 +4468,27 @@ fn make_twinned(
}
const BUFFER: u32 = 1;
if resource[0] != BUFFER {
// shortcut: unordered access to a texture the title placed
// itself is not mirrored; give it a resource as shader
// views of such textures get when a dispatch writes one.
// Each texture is said once (the first 64), with how many times
// such a view was asked for so far: what shaders write through
// them is lost.
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
tracing::warn!(
address = format_args!("{at:#x}"),
times,
"placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}",
&desc[..10]
);
if *unordered || at != 0 {
// shortcut: unordered access to a texture the title placed
// itself is not mirrored; give it a resource as shader
// views of such textures get when a dispatch writes one.
// Each texture is said once (the first 64), with how many times
// such a view was asked for so far: what shaders write through
// them is lost.
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
tracing::warn!(
address = format_args!("{at:#x}"),
unordered = *unordered,
times,
"placed texture view not mirrored (null): resource {resource:?}, view {:?}",
&desc[..10]
);
}
}
return None;
}
@@ -5827,6 +6095,71 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) {
heap.release(last, 1);
assert_eq!(heap.dynamic(2), None);
}
#[test]
fn dynamic_slots_populate_and_clear_stride_table() {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
let Some(heap) = HostHeap::new(false, 4) else {
return; // no host GPU
};
let Some((_, _, data)) = heap.strides else {
panic!("view heap should allocate strides table");
};
let read_stride = |slot: u32| -> u32 {
// SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`.
unsafe { *(data as *const u32).add(slot as usize) }
};
let memory = vec![0u64; 1 << 11];
let addr = (memory.as_ptr() as u64).next_multiple_of(4096);
let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| {
let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
let mut desc = [0u32; 16];
// [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8]
let words = if uav {
[dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0]
} else {
[dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0]
};
desc[..10].copy_from_slice(&words);
(desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32);
View::Placed(uav, resource, desc)
};
let s0 = heap.dynamic(4).unwrap();
// R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER
let u16x4 = placed_typed(true, 12, 64);
heap.make_at(s0, &u16x4);
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
// R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED
let s16 = placed_typed(false, 59, 64);
heap.make_at(s0 + 1, &s16);
assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED);
// R16G16B16A16_FLOAT (10): 8 bytes, no integer bits
let f16x4 = placed_typed(true, 10, 64);
heap.make_at(s0 + 2, &f16x4);
assert_eq!(read_stride(s0 + 2), 8);
// Clearing / nulling / raw views overwrite stale bits cleanly.
heap.make_null(s0);
assert_eq!(read_stride(s0), 0);
heap.null_raw_at(s0 + 1);
assert_eq!(read_stride(s0 + 1), 0);
heap.null_raw_uav_at(s0 + 2);
assert_eq!(read_stride(s0 + 2), 0);
// `make_listed` (both cold creation and cached copy hit) must populate strides.
let mut slot_mem = [0u32; 8];
crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4);
let rec = [slot_mem[0], slot_mem[1], slot_mem[2]];
assert!(heap.make_listed(0x1234, rec, s0).is_some());
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
heap.make_null(s0 + 3);
assert_eq!(read_stride(s0 + 3), 0);
assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some());
assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER);
}
}
/// What is known of a record a list's tables hold, in that recording of the
@@ -5847,6 +6180,7 @@ struct ListView {
/// Its descriptor's slot in [`ListViews`]; its raw twin's is the next.
at: u32,
twin: bool,
stride_word: u32,
kept: Kept,
listed: Listed,
}
@@ -5925,3 +6259,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) {
pub(crate) fn list_views() -> bool {
crate::toggled!("VICTORY_LIST_VIEWS")
}
#[cfg(test)]
mod bake_flip_tests {
use super::*;
#[test]
fn pending_list_flips_promote_once_and_clean_up() {
let heap = 0xdead_beefusize;
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(PendingListFlip {
id: id1,
origin: (1, 1),
flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) },
});
pending.push(PendingListFlip {
id: id2,
origin: (2, 1),
flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) },
});
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
let taken = take_pending_list_flip(id1).expect("id1 should be present");
assert_eq!(taken.index, 7);
assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op");
remove_pending_list_flip(id2);
assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone");
}
#[test]
fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() {
let heap = 0xcafe_babeusize;
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
for (id, idx) in [(id1, 10), (id2, 11)] {
pending.push(PendingListFlip {
id,
origin: (3, 1),
flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) },
});
}
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
struct TestGuard(u64);
impl TestGuard {
fn id(&self) -> u64 {
self.0
}
}
impl Drop for TestGuard {
fn drop(&mut self) {
remove_pending_list_flip(self.0);
}
}
let make_cb = |id: u64| -> Box<dyn Fn() -> Option<u32> + Send + 'static> {
let guard = TestGuard(id);
Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index))
};
let cb1 = make_cb(id1);
let cb2 = make_cb(id2);
// Must still be present after make_cb returns (guard moved, not dropped).
assert_eq!(cb1(), Some(10));
assert_eq!(cb1(), None);
drop(cb2);
assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry");
}
}
+318
View File
@@ -0,0 +1,318 @@
//! NVIDIA DLSS in place of the title's FidelityFX upscale (Series S,
//! `VICTORY_UPSCALE=dlss`, builds with the `dlss` feature).
//!
//! The title renders below its output size and asks its upscaler to make the
//! output from the colour, depth and motion vectors it rendered, with the
//! camera's jitter: what DLSS takes as well. The title's own FidelityFX passes
//! are slow translated for 32-lane cards (about 150 ms of card time a frame on
//! an RTX 3070 Ti); DLSS runs on the card's tensor cores in a millisecond or
//! two.
//!
//! The SDK (NVIDIA/DLSS on GitHub: `include`, `lib/Windows_x86_64`) is not part
//! of this repository: the build links `nvsdk_ngx_d.lib` from
//! `VICTORY_DLSS_SDK`, and `nvngx_dlss.dll` is looked for in `VICTORY_DLSS_DIR`
//! (else beside the executable). Any failure leaves the caller to stretch.
//!
//! Switches: `VICTORY_DLSS_QUALITY` (0 performance .. 2 quality, 5 DLAA; 2 by
//! default), `VICTORY_DLSS_MV_SIGN=-1` (motion vectors the other way),
//! `VICTORY_DLSS_JITTER_SIGN=-1`, `VICTORY_DLSS_HDR=0|1` (default: by the colour
//! format), `VICTORY_DLSS_DEPTH_INVERTED=0|1` (default: by near > far),
//! `VICTORY_DLSS_SHARPNESS=<0..1>`.
use std::ffi::{CString, c_char, c_int, c_uint, c_void};
use std::sync::Mutex;
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::Interface;
type Result = c_int;
const SUCCESS: Result = 1;
const FEATURE_SUPER_SAMPLING: c_int = 1;
const ENGINE_CUSTOM: c_int = 0;
const VERSION_API: c_int = 0x15;
const FLAG_HDR: c_int = 1 << 0;
const FLAG_MV_LOW_RES: c_int = 1 << 1;
const FLAG_MV_JITTERED: c_int = 1 << 2;
const FLAG_DEPTH_INVERTED: c_int = 1 << 3;
const FLAG_AUTO_EXPOSURE: c_int = 1 << 6;
#[repr(C)]
struct PathList {
path: *const *const u16,
length: c_uint,
}
#[repr(C)]
struct Logging {
callback: *const c_void,
minimum: c_int,
disable_other_sinks: bool,
}
#[repr(C)]
struct CommonInfo {
paths: PathList,
internal: *const c_void,
logging: Logging,
}
#[link(name = "nvsdk_ngx_d", kind = "static")]
unsafe extern "C" {
fn NVSDK_NGX_D3D12_Init_with_ProjectID(
project: *const c_char,
engine: c_int,
engine_version: *const c_char,
data_path: *const u16,
device: *mut c_void,
info: *const CommonInfo,
version: c_int,
) -> Result;
fn NVSDK_NGX_D3D12_GetCapabilityParameters(out: *mut *mut c_void) -> Result;
fn NVSDK_NGX_D3D12_CreateFeature(list: *mut c_void, feature: c_int, params: *mut c_void, out: *mut *mut c_void) -> Result;
fn NVSDK_NGX_D3D12_ReleaseFeature(handle: *mut c_void) -> Result;
fn NVSDK_NGX_D3D12_EvaluateFeature_C(list: *mut c_void, handle: *const c_void, params: *const c_void, callback: *const c_void) -> Result;
fn NVSDK_NGX_Parameter_SetUI(p: *mut c_void, name: *const c_char, value: c_uint);
fn NVSDK_NGX_Parameter_SetI(p: *mut c_void, name: *const c_char, value: c_int);
fn NVSDK_NGX_Parameter_SetF(p: *mut c_void, name: *const c_char, value: f32);
fn NVSDK_NGX_Parameter_SetD3d12Resource(p: *mut c_void, name: *const c_char, value: *mut c_void);
fn NVSDK_NGX_Parameter_GetI(p: *mut c_void, name: *const c_char, out: *mut c_int) -> Result;
}
/// A parameter name as the SDK spells it.
macro_rules! name {
($s:literal) => {
concat!($s, "\0").as_ptr().cast::<c_char>()
};
}
/// What the title gives an upscale, as the host's resources.
pub(crate) struct Inputs<'a> {
pub colour: &'a ID3D12Resource,
pub depth: Option<&'a ID3D12Resource>,
pub motion: Option<&'a ID3D12Resource>,
pub exposure: Option<&'a ID3D12Resource>,
pub output: &'a ID3D12Resource,
pub jitter: [f32; 2],
pub motion_scale: [f32; 2],
pub render: [u32; 2],
pub reset: bool,
pub pre_exposure: f32,
pub near: f32,
pub far: f32,
pub frame_ms: f32,
}
struct Feature {
handle: *mut c_void,
/// render width and height the feature was made for, output size, flags
key: [u32; 5],
}
struct Dlss {
params: *mut c_void,
feature: Option<Feature>,
}
// SAFETY: the SDK's objects are used under the mutex only.
unsafe impl Send for Dlss {}
/// `None` until tried; `Some(None)`: unavailable, never tried again.
static DLSS: Mutex<Option<Option<Dlss>>> = Mutex::new(None);
fn env_f(name: &str, default: f32) -> f32 {
std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
}
fn env_flag(name: &str) -> Option<bool> {
std::env::var(name).ok().map(|v| v.trim() == "1")
}
fn wide(s: &std::ffi::OsStr) -> Vec<u16> {
use std::os::windows::ffi::OsStrExt;
s.encode_wide().chain([0]).collect()
}
fn init(device: &ID3D12Device) -> Option<Dlss> {
let dir = std::env::var_os("VICTORY_DLSS_DIR")
.map(std::path::PathBuf::from)
.or_else(|| std::env::current_exe().ok()?.parent().map(|p| p.to_path_buf()))?;
let data = std::env::temp_dir().join("victory-ngx");
let _ = std::fs::create_dir_all(&data);
let dir_w = wide(dir.as_os_str());
let data_w = wide(data.as_os_str());
let paths = [dir_w.as_ptr()];
let info = CommonInfo {
paths: PathList { path: paths.as_ptr(), length: 1 },
internal: std::ptr::null(),
logging: Logging { callback: std::ptr::null(), minimum: 0, disable_other_sinks: false },
};
let project = CString::new("5e2f9a3c-1b7d-4c8e-9a6f-0d3b2c1e4f57").ok()?;
let version = CString::new("1.0").ok()?;
// SAFETY: live strings and device; the SDK copies what it keeps.
let r = unsafe {
NVSDK_NGX_D3D12_Init_with_ProjectID(
project.as_ptr(),
ENGINE_CUSTOM,
version.as_ptr(),
data_w.as_ptr(),
device.as_raw(),
&info,
VERSION_API,
)
};
if r != SUCCESS {
tracing::warn!(result = format_args!("{r:#x}"), dir = %dir.display(), "DLSS: the SDK did not start; the upscale stays a stretch");
return None;
}
let mut params = std::ptr::null_mut();
// SAFETY: an out pointer.
let r = unsafe { NVSDK_NGX_D3D12_GetCapabilityParameters(&mut params) };
if r != SUCCESS || params.is_null() {
tracing::warn!(result = format_args!("{r:#x}"), "DLSS: no capability parameters");
return None;
}
let mut available = 0;
// SAFETY: live parameters.
unsafe { NVSDK_NGX_Parameter_GetI(params, name!("SuperSampling.Available"), &mut available) };
if available == 0 {
tracing::warn!("DLSS: super sampling is not available on this card or driver");
return None;
}
tracing::info!(dir = %dir.display(), "DLSS: started; the title's upscale is DLSS (VICTORY_UPSCALE=dlss)");
Some(Dlss { params, feature: None })
}
/// Records DLSS over `inputs` into `list`; false if it could not (the caller
/// stretches instead). The list's descriptor heaps and root state are the
/// SDK's afterwards: the caller replays the title's.
pub(crate) fn record(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, inputs: &Inputs<'_>) -> bool {
let mut guard = DLSS.lock().unwrap_or_else(|e| e.into_inner());
let dlss = match guard.get_or_insert_with(|| init(device)) {
Some(d) => d,
None => return false,
};
// SAFETY: live resources.
let (out, colour) = unsafe { (inputs.output.GetDesc(), inputs.colour.GetDesc()) };
let render = [
if inputs.render[0] == 0 { colour.Width as u32 } else { inputs.render[0] },
if inputs.render[1] == 0 { colour.Height } else { inputs.render[1] },
];
// The feature's input size is the largest the colour texture holds, so
// that a dynamic render size inside it needs no new feature.
let (in_w, in_h) = (colour.Width as u32, colour.Height);
let hdr = env_flag("VICTORY_DLSS_HDR").unwrap_or(matches!(colour.Format.0, 2 | 10 | 26 | 24 | 9));
let inverted = env_flag("VICTORY_DLSS_DEPTH_INVERTED").unwrap_or(inputs.near > inputs.far);
let mut flags = FLAG_MV_LOW_RES | FLAG_MV_JITTERED;
if hdr {
flags |= FLAG_HDR;
}
if inverted {
flags |= FLAG_DEPTH_INVERTED;
}
if inputs.exposure.is_none() {
flags |= FLAG_AUTO_EXPOSURE;
}
let key = [in_w, in_h, out.Width as u32, out.Height, flags as u32];
let p = dlss.params;
if dlss.feature.as_ref().is_none_or(|f| f.key != key) {
if let Some(old) = dlss.feature.take() {
// SAFETY: a handle the SDK made.
unsafe { NVSDK_NGX_D3D12_ReleaseFeature(old.handle) };
}
let quality = env_f("VICTORY_DLSS_QUALITY", 2.0) as c_int;
let mut handle = std::ptr::null_mut();
// SAFETY: live parameters and an open list.
let r = unsafe {
NVSDK_NGX_Parameter_SetUI(p, name!("CreationNodeMask"), 1);
NVSDK_NGX_Parameter_SetUI(p, name!("VisibilityNodeMask"), 1);
NVSDK_NGX_Parameter_SetUI(p, name!("Width"), in_w);
NVSDK_NGX_Parameter_SetUI(p, name!("Height"), in_h);
NVSDK_NGX_Parameter_SetUI(p, name!("OutWidth"), out.Width as u32);
NVSDK_NGX_Parameter_SetUI(p, name!("OutHeight"), out.Height);
NVSDK_NGX_Parameter_SetI(p, name!("PerfQualityValue"), quality);
NVSDK_NGX_Parameter_SetI(p, name!("DLSS.Feature.Create.Flags"), flags);
NVSDK_NGX_Parameter_SetI(p, name!("DLSS.Enable.Output.Subrects"), 0);
// LOCAL (11/26): `VICTORY_DLSS_PRESET=J|K|L|M`: the model, for every mode (unset:
// the DLL's default; 310.9.16 uses K, the DLSS 4 transformer model, for Quality).
let preset: c_uint = match std::env::var("VICTORY_DLSS_PRESET").as_deref().map(str::trim) {
Ok("J") => 10,
Ok("K") => 11,
Ok("L") => 12,
Ok("M") => 13,
_ => 0,
};
if preset != 0 {
for mode in [
name!("DLSS.Hint.Render.Preset.DLAA"),
name!("DLSS.Hint.Render.Preset.Quality"),
name!("DLSS.Hint.Render.Preset.Balanced"),
name!("DLSS.Hint.Render.Preset.Performance"),
name!("DLSS.Hint.Render.Preset.UltraPerformance"),
name!("DLSS.Hint.Render.Preset.UltraQuality"),
] {
NVSDK_NGX_Parameter_SetUI(p, mode, preset);
}
}
NVSDK_NGX_D3D12_CreateFeature(list.as_raw(), FEATURE_SUPER_SAMPLING, p, &mut handle)
};
if r != SUCCESS || handle.is_null() {
tracing::warn!(result = format_args!("{r:#x}"), ?key, "DLSS: no feature for these sizes; the upscale stays a stretch");
*guard = Some(None);
return false;
}
tracing::info!(
input = ?(in_w, in_h),
output = ?(out.Width, out.Height),
hdr,
depth_inverted = inverted,
auto_exposure = inputs.exposure.is_none(),
quality,
colour_format = colour.Format.0,
"DLSS: feature made"
);
dlss.feature = Some(Feature { handle, key });
}
let Some(feature) = dlss.feature.as_ref() else { return false };
let mv = env_f("VICTORY_DLSS_MV_SIGN", 1.0);
let jit = env_f("VICTORY_DLSS_JITTER_SIGN", 1.0);
let raw = |r: Option<&ID3D12Resource>| r.map_or(std::ptr::null_mut(), |r| r.as_raw());
let scale = |s: f32| if s == 0.0 { 1.0 } else { s };
// SAFETY: live parameters, resources and feature; an open list.
let r = unsafe {
NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Color"), inputs.colour.as_raw());
NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Output"), inputs.output.as_raw());
NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Depth"), raw(inputs.depth));
NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("MotionVectors"), raw(inputs.motion));
NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("ExposureTexture"), raw(inputs.exposure));
NVSDK_NGX_Parameter_SetF(p, name!("Jitter.Offset.X"), jit * inputs.jitter[0]);
NVSDK_NGX_Parameter_SetF(p, name!("Jitter.Offset.Y"), jit * inputs.jitter[1]);
NVSDK_NGX_Parameter_SetF(p, name!("MV.Scale.X"), mv * scale(inputs.motion_scale[0]));
NVSDK_NGX_Parameter_SetF(p, name!("MV.Scale.Y"), mv * scale(inputs.motion_scale[1]));
NVSDK_NGX_Parameter_SetI(p, name!("Reset"), inputs.reset as c_int);
NVSDK_NGX_Parameter_SetF(p, name!("Sharpness"), env_f("VICTORY_DLSS_SHARPNESS", 0.0));
NVSDK_NGX_Parameter_SetF(p, name!("DLSS.Pre.Exposure"), if inputs.pre_exposure > 0.0 { inputs.pre_exposure } else { 1.0 });
NVSDK_NGX_Parameter_SetF(p, name!("FrameTimeDeltaInMsec"), inputs.frame_ms);
NVSDK_NGX_Parameter_SetUI(p, name!("DLSS.Render.Subrect.Dimensions.Width"), render[0].min(in_w));
NVSDK_NGX_Parameter_SetUI(p, name!("DLSS.Render.Subrect.Dimensions.Height"), render[1].min(in_h));
NVSDK_NGX_D3D12_EvaluateFeature_C(list.as_raw(), feature.handle, p, std::ptr::null())
};
if r != SUCCESS {
static TOLD: std::sync::Once = std::sync::Once::new();
TOLD.call_once(|| tracing::warn!(result = format_args!("{r:#x}"), "DLSS: an evaluation failed; that upscale is a stretch"));
return false;
}
// LOCAL (11/26): DLSS Frame Generation's inputs (`VICTORY_FRAME_GEN`), in the state the
// upscale read them in.
if crate::fg::active() {
crate::fg::tag(
[render[0].min(in_w), render[1].min(in_h)],
[jit * inputs.jitter[0], jit * inputs.jitter[1]],
[mv * scale(inputs.motion_scale[0]), mv * scale(inputs.motion_scale[1])],
inputs.near,
inputs.far,
inputs.reset,
);
}
true
}
File diff suppressed because it is too large. Load diff
+32 -1
View File
@@ -115,7 +115,32 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
if fence.value.load(Ordering::Acquire) >= value {
return S_OK;
}
tracing::warn!(value, "blocking fence wait not implemented");
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(250);
loop {
let current = fence.value.load(Ordering::Acquire);
if current >= value {
return S_OK;
}
let now = std::time::Instant::now();
if now >= deadline {
break;
}
let ms = (deadline - now).as_millis().min(10) as u32;
// SAFETY: wait on the atomic u64 until woken by WakeByAddressAll or timeout.
unsafe {
windows_sys::Win32::System::Threading::WaitOnAddress(
(&raw const fence.value).cast(),
(&raw const current).cast(),
size_of::<u64>(),
ms.max(1),
);
}
crate::queue::release_held(false);
}
if fence.value.load(Ordering::Acquire) >= value {
return S_OK;
}
tracing::warn!(value, "blocking fence wait timed out");
return E_NOTIMPL;
}
// shortcut: a null event means "block until reached"; nothing can
@@ -140,6 +165,12 @@ pub(crate) fn set(this: This, value: u64) {
}
!reached
});
drop(waiters);
#[cfg(windows)]
// SAFETY: wake any guest thread polling/blocking via WaitOnAddress on the fence's GPU VA.
unsafe {
windows_sys::Win32::System::Threading::WakeByAddressAll((&raw const fence.value).cast());
}
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
let _called = crate::timeline::span("a fence set");
+405
View File
@@ -0,0 +1,405 @@
//! LOCAL (11/26): DLSS Frame Generation through NVIDIA Streamline (manual hooking).
//!
//! `VICTORY_FRAME_GEN=2|3|4` (frames shown per rendered one; unset or 1: off) with the SDK's
//! signed DLLs in `VICTORY_STREAMLINE_DIR` (sl.interposer, sl.common, sl.dlss_g, sl.reflex,
//! sl.pcl, nvngx_dlssg). NVIDIA's licence: for own use only, never pushed.
//!
//! - [`start`] (from the presenter, before its swap chain): `slInit`, `slSetD3DDevice`, Reflex
//! low latency, and the factory upgraded to Streamline's proxy, so that the swap chain made
//! from it is the proxy that generates frames at `Present`.
//! - [`tag`] (from the DLSS upscale, `crate::dlss::record`): the frame's constants and its depth
//! and motion vectors (copied by Streamline on that list: `eOnlyValidNow`).
//! - [`present_start`] / [`present_end`] around the proxy's `Present`.
//!
//! The title gives no camera matrices: they are made from a 60 degree field of view, the
//! upscale's near/far and the render size, the camera standing still (its motion is in the
//! motion vectors). Frame indices are the presents so far: the upscale of a frame is recorded
//! before its present.
use std::ffi::CString;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::IDXGIFactory2;
use windows::core::Interface;
use crate::streamline as sl;
/// Frames to generate per rendered frame (1 = 2x .. 5 = 6x), 0: off, as `VICTORY_FRAME_GEN`
/// says now (the F1 menu changes it while running).
fn wanted_now() -> u32 {
std::env::var("VICTORY_FRAME_GEN").ok().and_then(|v| v.trim().parse::<u32>().ok()).map_or(0, |n| n.clamp(1, 6) - 1)
}
/// [`wanted_now`] at the start: whether Streamline is started at all (its proxy swap chain is
/// made once; with it, the amount and off/on change while running).
pub(crate) fn wanted() -> u32 {
static N: OnceLock<u32> = OnceLock::new();
*N.get_or_init(|| {
let n = wanted_now();
// Not together with the ray-tracing structure builder: each runs at about 15 frames a
// second alone and the two at 0.1 (11/26 r_rtE/F/G: from the moment Streamline has its
// first constants in the world, recording takes seconds a frame; Reflex off and no
// generated frames change nothing). `VICTORY_FG_WITH_RT=1` starts it anyway.
let rt = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
let forced = std::env::var_os("VICTORY_FG_WITH_RT").is_some_and(|v| v == "1");
if n > 0 && rt && !forced {
tracing::warn!("frame generation: not started with ray tracing on (together they run at 0.1 frames a second); VICTORY_FG_WITH_RT=1 starts it anyway");
return 0;
}
n
})
}
/// `VICTORY_FG_REFLEX=0`: Reflex left off and its sleep not taken (to tell its cost from the rest).
fn reflex_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_FG_REFLEX").is_none_or(|v| v != "0"))
}
struct State {
sl: sl::Sl,
/// Frames to generate as last given to DLSS-G (0: turned off); none before the first present.
set: Option<u32>,
/// The most frames this card generates per rendered one, as DLSS-G says; 0: not asked yet.
most: u32,
told: u32,
}
static STATE: OnceLock<Option<Mutex<State>>> = OnceLock::new();
/// Presents so far: the index of the frame being made.
static FRAME: AtomicU32 = AtomicU32::new(1);
/// A frame was tagged since the last present.
static TAGGED: AtomicBool = AtomicBool::new(false);
const VIEWPORT: sl::ViewportHandle = sl::ViewportHandle::new(0);
fn state() -> Option<&'static Mutex<State>> {
STATE.get().and_then(|s| s.as_ref())
}
fn init(device: &ID3D12Device) -> anyhow::Result<State> {
let dir = std::env::var_os("VICTORY_STREAMLINE_DIR")
.ok_or_else(|| anyhow::anyhow!("VICTORY_STREAMLINE_DIR is not set"))?;
// SAFETY: NVIDIA's signed interposer from the SDK folder the launcher names.
let mut s = unsafe { sl::Sl::load(std::path::Path::new(&dir)) }?;
let features = sl::FG_FEATURES;
static ENGINE: OnceLock<(CString, CString)> = OnceLock::new();
let (version, project) = ENGINE.get_or_init(|| {
(CString::new("1.0").unwrap_or_default(), CString::new("5e2f9a3c-1b7d-4c8e-9a6f-0d3b2c1e4f57").unwrap_or_default())
});
let logs: Vec<u16> = std::env::temp_dir().join("victory-sl").as_os_str().encode_wide_z();
let _ = std::fs::create_dir_all(std::env::temp_dir().join("victory-sl"));
let pref = sl::Preferences {
logLevel: sl::LogLevel::eDefault,
pathToLogsAndData: logs.as_ptr(),
logMessageCallback: Some(sl::log_to_tracing),
flags: sl::PreferenceFlags::MANUAL_HOOKING_FRAME_TAGS,
featuresToLoad: features.as_ptr(),
numFeaturesToLoad: features.len() as u32,
engine: sl::EngineType::eCustom,
engineVersion: version.as_ptr(),
projectId: project.as_ptr(),
renderAPI: sl::RenderAPI::eD3D12,
..Default::default()
};
// SAFETY: every pointer in `pref` lives through the call (SL copies them); the log
// callback is a static function.
unsafe { s.init(&pref) }.ok().map_err(|e| anyhow::anyhow!("slInit: {e}"))?;
// SAFETY: the host's live native device.
unsafe { s.set_d3d_device(device.as_raw()) }.ok().map_err(|e| anyhow::anyhow!("slSetD3DDevice: {e}"))?;
// SAFETY: a plain query of a live device.
let luid = unsafe { device.GetAdapterLuid() };
let mut bytes = [0u8; 8];
bytes[..4].copy_from_slice(&luid.LowPart.to_le_bytes());
bytes[4..].copy_from_slice(&luid.HighPart.to_le_bytes());
let supported = s.is_feature_supported(sl::kFeatureDLSS_G, Some(&bytes));
if !supported.is_ok() {
anyhow::bail!("DLSS-G is not supported here: {supported}");
}
s.resolve_feature_functions()?;
let reflex = sl::ReflexOptions {
mode: if reflex_on() { sl::ReflexMode::eLowLatency } else { sl::ReflexMode::eOff },
..Default::default()
};
let r = s.reflex_set_options(&reflex);
if !r.is_ok() {
tracing::warn!(result = %r, "frame generation: Reflex not set");
}
Ok(State { sl: s, set: None, most: 0, told: 0 })
}
trait WideZ {
fn encode_wide_z(&self) -> Vec<u16>;
}
impl WideZ for std::ffi::OsStr {
fn encode_wide_z(&self) -> Vec<u16> {
use std::os::windows::ffi::OsStrExt;
self.encode_wide().chain([0]).collect()
}
}
/// Before the presenter's swap chain is made: starts Streamline (once) and gives back the
/// factory to make it from, the proxy if frame generation is wanted and could start.
pub(crate) fn start(device: &ID3D12Device, factory: IDXGIFactory2) -> IDXGIFactory2 {
if wanted() == 0 {
return factory;
}
let state = STATE.get_or_init(|| match init(device) {
Ok(s) => {
tracing::info!(frames = wanted() + 1, "frame generation: Streamline started");
Some(Mutex::new(s))
}
Err(e) => {
tracing::warn!(error = %e, "frame generation: Streamline did not start; presenting without it");
None
}
});
let Some(state) = state else { return factory };
let s = state.lock().unwrap_or_else(|e| e.into_inner());
let mut raw = factory.as_raw();
// SAFETY: a live factory; the call puts a new proxy (with its own reference) in `raw` and
// leaves ours to the native one.
let r = unsafe { s.sl.upgrade_interface(&mut raw) };
if !r.is_ok() || raw.is_null() {
tracing::warn!(result = %r, "frame generation: the factory was not upgraded");
return factory;
}
// SAFETY: SL's proxy, an IDXGIFactory2 with one reference, now ours.
unsafe { IDXGIFactory2::from_raw(raw) }
}
/// What the last DLSS upscale read: the frame's numbers and its depth and motion vectors (title
/// resources, whose host copies and states are looked up at the present).
struct Latest {
depth: usize,
motion: usize,
render: [u32; 2],
jitter: [f32; 2],
mv_pixels: [f32; 2],
near: f32,
far: f32,
reset: bool,
}
static LATEST: Mutex<Option<Latest>> = Mutex::new(None);
/// With frame generation on: the numbers of the DLSS upscale just recorded ([`crate::dlss::record`]).
/// The upscale of a frame is recorded after its present has been asked for (the lists are recorded
/// at submission), so everything is handed to Streamline at the next present, whose index is the
/// one the constants and tags carry.
#[allow(clippy::too_many_arguments)]
pub(crate) fn tag(render: [u32; 2], jitter: [f32; 2], mv_pixels: [f32; 2], near: f32, far: f32, reset: bool) {
if state().is_none() {
return;
}
let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner());
let (depth, motion) = latest.as_ref().map_or((0, 0), |l| (l.depth, l.motion));
*latest = Some(Latest { depth, motion, render, jitter, mv_pixels, near, far, reset });
TAGGED.store(true, Ordering::Relaxed);
}
/// The title's depth and motion vectors the DLSS upscale read (`crate::list::upscale_now`).
pub(crate) fn note_titles(depth: u64, motion: u64) {
if state().is_none() {
return;
}
let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner());
if let Some(l) = latest.as_mut() {
(l.depth, l.motion) = (depth as usize, motion as usize);
}
}
fn constants(l: &Latest) -> sl::Constants {
let (w, h) = (l.render[0].max(1) as f32, l.render[1].max(1) as f32);
let inverted = l.near > l.far;
let (n, f) = (l.near.min(l.far).max(1e-3), l.near.max(l.far).min(1e6).max(l.near.min(l.far) + 1.0));
let fov = 60f32.to_radians();
let ys = 1.0 / (fov / 2.0).tan();
let xs = ys / (w / h);
let (c, d) = if inverted { (n / (n - f), -n * f / (n - f)) } else { (f / (f - n), -n * f / (f - n)) };
sl::Constants {
cameraViewToClip: sl::float4x4::from_rows([[xs, 0.0, 0.0, 0.0], [0.0, ys, 0.0, 0.0], [0.0, 0.0, c, 1.0], [0.0, 0.0, d, 0.0]]),
clipToCameraView: sl::float4x4::from_rows([
[1.0 / xs, 0.0, 0.0, 0.0],
[0.0, 1.0 / ys, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0 / d],
[0.0, 0.0, 1.0, -c / d],
]),
clipToPrevClip: sl::float4x4::identity(),
prevClipToClip: sl::float4x4::identity(),
jitterOffset: sl::float2::new(l.jitter[0], l.jitter[1]),
mvecScale: sl::float2::new(l.mv_pixels[0] / w, l.mv_pixels[1] / h),
cameraPinholeOffset: sl::float2::new(0.0, 0.0),
cameraPos: sl::float3::new(0.0, 0.0, 0.0),
cameraUp: sl::float3::new(0.0, 1.0, 0.0),
cameraRight: sl::float3::new(1.0, 0.0, 0.0),
cameraFwd: sl::float3::new(0.0, 0.0, 1.0),
cameraNear: n,
cameraFar: f,
cameraFOV: fov,
cameraAspectRatio: w / h,
depthInverted: inverted.into(),
cameraMotionIncluded: sl::Boolean::eTrue,
motionVectors3D: sl::Boolean::eFalse,
reset: l.reset.into(),
motionVectorsJittered: sl::Boolean::eTrue,
..Default::default()
}
}
/// Right before the proxy's `Present`: generation on (once), and for a frame the upscale ran in,
/// its constants and its depth and motion vectors (valid until this present: the next frame's
/// lists come after it on the queue).
pub(crate) fn present_start() {
let Some(state) = state() else { return };
let mut s = state.lock().unwrap_or_else(|e| e.into_inner());
let index = FRAME.load(Ordering::Relaxed);
// The amount, at the first present and whenever the menu changed it (looked at twice a second
// or so): no restart, the proxy swap chain stays.
if s.set.is_none() || index % 8 == 0 {
let asked = wanted_now();
// No more than the card and driver generate (DLSS 4.5 gives up to 5 here: 6x).
// Asked once here (each question restarts Streamline's count of presented frames).
if s.most == 0 {
s.most = match s.sl.dlssg_get_state(&VIEWPORT, None) {
Ok(st) if st.numFramesToGenerateMax > 0 => st.numFramesToGenerateMax,
_ => 1,
};
}
let want = asked.min(s.most);
if s.set != Some(want) {
if want != asked {
tracing::warn!(asked = asked + 1, given = want + 1, "frame generation: more than this card generates; its most is used");
}
let options = sl::DLSSGOptions {
mode: if want == 0 { sl::DLSSGMode::eOff } else { sl::DLSSGMode::eOn },
numFramesToGenerate: want.max(1),
flags: sl::DLSSGFlags::eRetainResourcesWhenOff,
..Default::default()
};
let r = s.sl.dlssg_set_options(&VIEWPORT, &options);
tracing::info!(result = %r, frames = want + 1, "frame generation: amount set (1 = off)");
s.set = Some(want);
if want == 0 {
SHOWN.store(1, Ordering::Relaxed);
}
}
}
let Ok(token) = s.sl.new_frame_token(Some(index)) else { return };
for marker in [
sl::PCLMarker::eSimulationStart,
sl::PCLMarker::eSimulationEnd,
sl::PCLMarker::eRenderSubmitStart,
sl::PCLMarker::eRenderSubmitEnd,
] {
let _ = s.sl.pcl_set_marker(marker, token);
}
// Every present carries the last upscale's numbers and buffers, a present with no new
// upscale since the last one too (DLSS-G drops a frame that has none).
let fresh = TAGGED.swap(false, Ordering::Relaxed);
{
let latest = LATEST.lock().unwrap_or_else(|e| e.into_inner());
let found = latest.as_ref().and_then(|l| {
// Only a title resource that is still one, and only its copy as it is: the handles
// are a frame old at a present with no new upscale, and the title may have let the
// resource go since (with ray tracing on it makes and frees buffers all the time);
// `host_copy` would make a copy of whatever lies there now.
let look = |title: usize| {
let this = title as crate::object::This;
if this.is_null() || !crate::resource::is_resource(this) {
return None;
}
let copy = crate::resource::made_copy(this)?;
let state = crate::host::legal_state(&copy.texture, copy.state.load(Ordering::Relaxed));
Some((copy, state))
};
Some((l, look(l.depth)?, look(l.motion)?))
});
if let Some((l, (depth, depth_state), (motion, motion_state))) = found {
let r = s.sl.set_constants(&constants(l), token, &VIEWPORT);
let mut depth_res = sl::Resource::d3d12_tex2d(depth.texture.as_raw(), depth_state);
let mut motion_res = sl::Resource::d3d12_tex2d(motion.texture.as_raw(), motion_state);
let extent = Some(sl::Extent { top: 0, left: 0, width: l.render[0], height: l.render[1] });
let tags = [
sl::ResourceTag::new(&mut depth_res, sl::kBufferTypeDepth, sl::ResourceLifecycle::eValidUntilPresent, extent),
sl::ResourceTag::new(&mut motion_res, sl::kBufferTypeMotionVectors, sl::ResourceLifecycle::eValidUntilPresent, extent),
];
// SAFETY: live resources (their host copies are held through the call), in the
// states they will be in at the present; no list needed for eValidUntilPresent.
let t = unsafe { s.sl.set_tag_for_frame(token, &VIEWPORT, &tags, std::ptr::null_mut()) };
if (!r.is_ok() || !t.is_ok()) && s.told < 5 {
s.told += 1;
tracing::warn!(constants = %r, tags = %t, index, "frame generation: constants or tags refused");
}
PRESENT_TAGGED.store(fresh, Ordering::Relaxed);
}
}
let _ = s.sl.pcl_set_marker(sl::PCLMarker::ePresentStart, token);
}
/// The present now ending had constants and tags.
static PRESENT_TAGGED: AtomicBool = AtomicBool::new(false);
/// Right after the proxy's `Present`: the next frame's index, Reflex's sleep, and now and then
/// what the generator says of itself.
pub(crate) fn present_end() {
let Some(state) = state() else { return };
let s = state.lock().unwrap_or_else(|e| e.into_inner());
let index = FRAME.load(Ordering::Relaxed);
if let Ok(token) = s.sl.new_frame_token(Some(index)) {
let _ = s.sl.pcl_set_marker(sl::PCLMarker::ePresentEnd, token);
}
let tagged = PRESENT_TAGGED.swap(false, Ordering::Relaxed);
// For the frame-rate texts: frames shown per rendered one, as Streamline says of the last
// present (r_cgbj41: 1 over 30 presents with the window not focused, so not a running count;
// DLSS-G generates nothing while the window is not focused).
const POLL: u32 = 10;
if index % POLL == 0 {
match s.sl.dlssg_get_state(&VIEWPORT, None) {
Ok(st) => {
let per = if st.status.0 == 0 { st.numFramesActuallyPresented.clamp(1, 6) } else { 1 };
SHOWN.store(per, Ordering::Relaxed);
if index % 600 == 0 || (index / POLL).is_power_of_two() {
tracing::info!(
index,
tagged,
status = st.status.0,
presented = st.numFramesActuallyPresented,
per,
max = st.numFramesToGenerateMax,
"frame generation: state (status 0 = working; 2 Reflex, 8 constants)"
);
}
}
Err(e) => {
SHOWN.store(1, Ordering::Relaxed);
if index % 600 == 0 {
tracing::warn!(error = %e, "frame generation: no state");
}
}
}
}
let next = index + 1;
FRAME.store(next, Ordering::Relaxed);
// Reflex paces the next frame here.
if reflex_on()
&& let Ok(token) = s.sl.new_frame_token(Some(next))
{
let _ = s.sl.reflex_sleep(token);
}
}
/// Frames shown per frame rendered (1 without generation working), as Streamline last said.
static SHOWN: AtomicU32 = AtomicU32::new(1);
/// For the frame-rate texts: frames shown per frame rendered; 1 when generation is off or failing.
pub(crate) fn shown_per_frame() -> u32 {
if state().is_some() { SHOWN.load(Ordering::Relaxed).max(1) } else { 1 }
}
/// Whether Streamline is presenting (the presenter's swap chain is its proxy).
pub(crate) fn active() -> bool {
state().is_some()
}
+45 -2
View File
@@ -25,8 +25,47 @@ const ORIGIN: u32 = 0;
const TOKEN_ON_TIMEOUT: u32 = 2;
const SIXTIETH: Duration = Duration::from_micros(16_667);
/// LOCAL (11/26): `VICTORY_FPS_CAP`. Unset: the title's own interval (30 frames a second on a
/// Series S); `0`: none (ticks half a millisecond apart); `n`: n frames a second. The F1 menu
/// changes it while running ([`set_cap`]). -1: not read yet; 0: the title's; else microseconds.
static CAP_US: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1);
fn parse_cap(value: Option<&str>) -> i64 {
match value.map(str::trim).and_then(|v| v.parse::<u32>().ok()) {
None => 0,
Some(0) => 500,
Some(n) => (1_000_000 / i64::from(n)).max(500),
}
}
/// The interval ticks are apart: the title's, or the cap's when one is set.
fn capped(asked: Duration) -> Duration {
let mut us = CAP_US.load(Ordering::Relaxed);
if us < 0 {
us = parse_cap(std::env::var("VICTORY_FPS_CAP").ok().as_deref());
CAP_US.store(us, Ordering::Relaxed);
}
if us == 0 { asked } else { Duration::from_micros(us as u64) }
}
/// The cap changed (the F1 menu): the clock goes on from now with the new interval.
#[allow(dead_code)]
pub(crate) fn set_cap(value: &str) {
CAP_US.store(parse_cap(Some(value).filter(|v| !v.is_empty())), Ordering::Relaxed);
let first = LAST.iter().map(|t| t.load(Ordering::Relaxed)).max().unwrap_or(0);
if let Some(c) = clock().as_mut() {
c.start = Instant::now();
c.first = first;
c.interval = capped(c.asked);
tracing::info!(asked = ?c.asked, interval = ?c.interval, "frame interval: the cap changed");
}
}
struct Clock {
start: Instant,
/// What the title asked for.
asked: Duration,
/// What ticks are apart ([`capped`]).
interval: Duration,
/// The tick number at `start` (ticks go on across interval changes).
first: u64,
@@ -53,7 +92,9 @@ pub(crate) extern "system" fn set_interval(
0 => SIXTIETH,
us => Duration::from_micros(u64::from(us)),
};
tracing::info!(?interval, "frame interval");
let asked = interval;
let interval = capped(asked);
tracing::info!(?asked, ?interval, "frame interval (VICTORY_FPS_CAP: unset the title's, 0 none, n frames a second)");
// A new interval starts from now, after the last tick handed out.
let first = LAST
.iter()
@@ -62,6 +103,7 @@ pub(crate) extern "system" fn set_interval(
.unwrap_or(0);
*clock() = Some(Clock {
start: Instant::now(),
asked,
interval,
first,
});
@@ -105,7 +147,8 @@ fn next_tick(kind: u32) -> (u64, Duration) {
let mut clock = clock();
let c = clock.get_or_insert_with(|| Clock {
start: Instant::now(),
interval: SIXTIETH,
asked: SIXTIETH,
interval: capped(SIXTIETH),
first: 0,
});
let elapsed = c.start.elapsed().as_nanos();
+388 -41
View File
@@ -57,6 +57,10 @@ pub(crate) struct Host {
/// The adapter the device is on, for its memory budget
/// ([`Host::video_memory`]); `None` if the system does not name it.
adapter: Option<IDXGIAdapter3>,
/// 1-descriptor shader-visible fallback heaps bound when a command list
/// omits a view or sampler heap while using directly-indexed root signatures.
fallback_view: OnceLock<Option<ID3D12DescriptorHeap>>,
fallback_sampler: OnceLock<Option<ID3D12DescriptorHeap>>,
}
// SAFETY: D3D12 devices, queues, fences and descriptor heaps are
@@ -368,7 +372,11 @@ pub(crate) fn keep_freed() -> bool {
/// when free physical RAM is low. Never returns less than 2,000 ms.
/// With plenty of it five minutes ([`keep_freed`]).
pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
ram_idle_for(avail_phys, keep_freed())
let effective = match (avail_phys, crate::residency::headroom()) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
ram_idle_for(effective, keep_freed() && !crate::residency::limited_host_ram())
}
fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
@@ -432,6 +440,10 @@ fn sweep() {
}
#[cfg(feature = "diagnostics")]
crate::book::check();
crate::residency::refresh();
if crate::residency::pressured() {
trim_spare_chunks();
}
crate::pool::room(host().and_then(|h| h.video_memory()));
crate::pipeline::trim_library();
crate::shadow::let_go_idle();
@@ -484,7 +496,10 @@ pub(crate) fn retire_resource(object: ID3D12Resource) {
/// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not.
fn bury_lag() -> u64 {
static LAG: OnceLock<u64> = OnceLock::new();
*LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64))
*LAG.get_or_init(|| {
let default = if crate::residency::limited_host_ram() { 16 } else { 64 };
std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(default)
})
}
/// Drops what waited for submissions up to `finished` ([`bury_lag`]). The
@@ -970,6 +985,8 @@ fn create() -> windows::core::Result<Host> {
next_rtv: AtomicU32::new(0),
presenter: Mutex::new(None),
adapter,
fallback_view: OnceLock::new(),
fallback_sampler: OnceLock::new(),
})
}
}
@@ -1963,7 +1980,12 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) {
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
for (chunk, size) in chunks {
let back = if scratch_pool() {
spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
let limit = if keep_freed() && !crate::residency::limited_host_ram() {
SPARE_KEPT
} else {
SPARE_MOST
};
spare.give(chunk, size, limit)
} else {
Some(chunk)
};
@@ -1984,6 +2006,25 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) {
drop(freed);
}
/// Drops spare scratch chunks kept idle when host memory is pressured.
fn trim_spare_chunks() {
let freed: Vec<(Chunk, u64)> = {
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
if spare.kept.is_empty() {
return;
}
spare.bytes = 0;
std::mem::take(&mut spare.kept)
};
let count = freed.len() as u64;
let bytes: u64 = freed.iter().map(|(_, s)| *s).sum();
ALIVE[1].fetch_sub(count, Ordering::Relaxed);
ALIVE[2].fetch_sub(bytes, Ordering::Relaxed);
ALIVE[3].fetch_sub(count, Ordering::Relaxed);
ALIVE[4].fetch_sub(bytes, Ordering::Relaxed);
drop(freed);
}
/// What the host keeps for copies in the card's own memory
/// ([`crate::shadow::cards`]): three lists of ours and the compare.
struct CardWork {
@@ -2243,6 +2284,8 @@ enum Step {
/// Brings a texture's staging buffer up to date: once per submission,
/// whichever lists sample it, until a `Copy` or `Run` intervenes.
Texture(std::sync::Arc<crate::texture::Staging>),
/// Reads a CPU-written linear movie plane into a per-list upload buffer.
Plane((usize, usize), Box<dyn Fn() + Send>),
/// A title buffer copy that the list does on the card ([`place`]): what
/// is done on the CPU for it.
Placed(place::Placed),
@@ -2256,6 +2299,8 @@ struct Deferred {
/// Destination, source, bytes.
copies: Vec<Step>,
uploads: Vec<ID3D12Resource>,
/// Standalone upload footprints kept through this list's fence (movie planes).
plane_uploads: Vec<(Chunk, u64)>,
/// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
upload_bytes: u64,
/// Host objects the list's commands name (pipelines, root signatures,
@@ -2320,6 +2365,7 @@ impl Deferred {
impl Drop for Deferred {
fn drop(&mut self) {
give_chunks(std::mem::take(&mut self.plane_uploads));
ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
}
@@ -2733,6 +2779,10 @@ const WHY_FENCE: usize = 10;
/// copy, a fill of upload memory, a texture).
static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18];
/// LOCAL (11/26): settles for refreshes of memory a flight writes through
/// another copy (`upcheck::crossed`), since the last frame-rate line.
static CROSS_SETTLES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Since the last frame-rate line: the microseconds settles waited for the
/// card, by why they settled (the `WHY_` places).
static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
@@ -2998,6 +3048,16 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
return Some(WHY_READ);
}
}
&Step::Plane((at, len), _) => {
if touches(written, at, at.saturating_add(len)) {
if count {
LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
blame("a movie plane", written, at, len);
}
return Some(WHY_READ);
}
}
Step::Run(_) => return Some(WHY_RUN),
Step::Placed(p) => match p.waits(written) {
place::Waits::No => {}
@@ -3566,6 +3626,10 @@ fn late_line(frames: f64) {
if !late() {
return;
}
if upcheck::cross_on() {
let n = CROSS_SETTLES.swap(0, Ordering::Relaxed) as f64 / frames;
tracing::info!("relay cross settles per frame (VICTORY_RELAY_CROSS=1): {n:.1}");
}
let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
tracing::info!(
"submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \
@@ -3676,6 +3740,8 @@ mod card_steps;
pub(crate) mod indirects;
#[cfg(feature = "diagnostics")]
mod panel;
#[cfg(feature = "diagnostics")]
mod menu;
mod place;
mod send;
pub(crate) use send::{goes_as_words, words_under};
@@ -4313,6 +4379,7 @@ impl Host {
// pass: a wait between each copy and its pass had the
// card do them one after the other.
let mut sent = Vec::new();
let mut transitioned = Vec::new();
if let Some(own) = &own {
own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
}
@@ -4331,11 +4398,15 @@ impl Host {
#[cfg(feature = "diagnostics")]
traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied());
if own.is_none() && before.is_some() && !ranges.is_empty() {
sent.push(transition(
&shadow.buffer,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
));
let raw = shadow.buffer.as_raw();
if !transitioned.contains(&raw) {
transitioned.push(raw);
sent.push(transition(
&shadow.buffer,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
));
}
}
}
if !sent.is_empty() {
@@ -4906,7 +4977,7 @@ impl Host {
let mut telling = std::time::Instant::now();
for item in items {
telling = match item {
Late::Run(flight) => {
Late::Run(mut flight) => {
last = flight.number;
for &i in &flight.order {
read_backs(flight.lists[i].host());
@@ -4918,6 +4989,9 @@ impl Host {
if let Some(own) = flight.own {
own.landed();
}
for detached in &mut flight.lists {
detached.release_tables();
}
crate::land::spent(crate::land::stat::RB_DONE, done_from);
landed.push((flight.lists, flight.order));
crate::land::spent(crate::land::stat::READ_BACKS, telling)
@@ -5121,6 +5195,14 @@ impl Host {
let _ = self.submit(runs, &[], false);
}
/// Runs a closed internal upload-only host list synchronously without
/// draining title queues (`queue::before_sync`), so it is deadlock-safe
/// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight
/// GPU work and waits for the upload list's fence before returning.
pub(crate) fn execute_sync_internal(&self, list: &HostList) {
let _ = self.submit(&[list], &[], false);
}
/// A queue's submission with [`late`]: the host lists `lists`, taken
/// from the title's, go to the card in `order` and are not waited for.
/// They join the line of flights and are settled, with the others in
@@ -5378,7 +5460,7 @@ impl Host {
let mut landed = Vec::new();
for item in items {
match item {
Late::Run(flight) => {
Late::Run(mut flight) => {
last = flight.number;
for &i in &flight.order {
read_backs(flight.lists[i].host());
@@ -5386,6 +5468,9 @@ impl Host {
if let Some(card) = flight.card {
self.card_done(card);
}
for detached in &mut flight.lists {
detached.release_tables();
}
landed.push((flight.lists, flight.order));
}
Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
@@ -5592,10 +5677,24 @@ impl Host {
self.settle_stale(&mut submitted, runs, stale, &ranges);
settled += settling.elapsed();
}
// LOCAL (11/26): refreshes of memory a flight writes through
// another copy wait for that flight (`upcheck::cross_on`).
if behind && upcheck::cross_on() && flying() && upcheck::crossed(runs) {
let settling = std::time::Instant::now();
CROSS_SETTLES.fetch_add(1, Ordering::Relaxed);
self.settle(&mut submitted, WHY_STALE);
crate::watch::ask_once(&ranges);
settled += settling.elapsed();
}
} else if behind && !stale_under_flights(runs).is_empty() {
let settling = std::time::Instant::now();
self.settle(&mut submitted, WHY_STALE);
settled += settling.elapsed();
} else if behind && upcheck::cross_on() && flying() && upcheck::crossed(runs) {
let settling = std::time::Instant::now();
CROSS_SETTLES.fetch_add(1, Ordering::Relaxed);
self.settle(&mut submitted, WHY_STALE);
settled += settling.elapsed();
}
#[cfg(feature = "diagnostics")]
split.part(1);
@@ -6120,6 +6219,71 @@ impl Host {
handle
}
}
/// 1-descriptor shader-visible CBV/SRV/UAV fallback heap for directly-indexed root signatures.
pub(crate) fn fallback_view_heap(&self) -> Option<&ID3D12DescriptorHeap> {
self.fallback_view
.get_or_init(|| {
// SAFETY: plain 1-descriptor shader-visible heap + null SRV initialization.
unsafe {
let heap: ID3D12DescriptorHeap = self
.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.ok()?;
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT,
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_SRV::default(),
},
};
self.device.CreateShaderResourceView(
None,
Some(&desc),
heap.GetCPUDescriptorHandleForHeapStart(),
);
Some(heap)
}
})
.as_ref()
}
/// 1-descriptor shader-visible Sampler fallback heap for directly-indexed root signatures.
pub(crate) fn fallback_sampler_heap(&self) -> Option<&ID3D12DescriptorHeap> {
self.fallback_sampler
.get_or_init(|| {
// SAFETY: plain 1-descriptor shader-visible sampler heap initialization.
unsafe {
let heap: ID3D12DescriptorHeap = self
.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
NumDescriptors: 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.ok()?;
let desc = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MaxLOD: f32::MAX,
..Default::default()
};
self.device
.CreateSampler(&desc, heap.GetCPUDescriptorHandleForHeapStart());
Some(heap)
}
})
.as_ref()
}
}
impl HostList {
@@ -6300,6 +6464,13 @@ impl HostList {
self.epoch.load(Ordering::Relaxed)
}
/// Whether any deferred steps or texture state transitions have been
/// recorded into this list since creation or its last [`HostList::reset`].
pub(crate) fn has_recorded_work(&self) -> bool {
!self.deferred().copies.is_empty()
|| !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
/// Moves a title texture's host copy to `wanted` (a host state) in this
/// list: the host texture and the state it leaves, if that is a change.
/// The list's first use of a texture records nothing: its prelude brings
@@ -7209,6 +7380,23 @@ impl HostList {
self.deferred().copies.push(Step::Texture(staging));
}
/// A copy source owned exclusively by this list until reset after its
/// last execution. A different list can prepare its movie plane concurrently.
pub(crate) fn plane_upload(
&self,
size: u64,
read: (usize, usize),
fill: impl Fn(usize) + Send + 'static,
) -> Option<ID3D12Resource> {
let chunk = take_chunk(host()?, size)?;
let source = chunk.buffer.clone();
let destination = chunk.data;
let mut deferred = self.deferred();
deferred.plane_uploads.push((chunk, size));
deferred.copies.push(Step::Plane(read, Box::new(move || fill(destination))));
Some(source)
}
/// Runs the list's submission-time steps; refreshes go into `batch`
/// (the title's big buffers, a 174 MB one among them, are read by most
/// lists of a submission, through many ranges). Copies and fills that
@@ -7327,6 +7515,13 @@ impl HostList {
}
continue;
}
Step::Plane((_, len), fill) => {
let started = std::time::Instant::now();
fill();
PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
PREPARING[3].fetch_add(*len as u64, Ordering::Relaxed);
continue;
}
};
us += started.elapsed();
bytes += copied as u64;
@@ -8525,6 +8720,7 @@ impl Host {
match made {
Ok(()) => Some((buffer?, data.cast())),
Err(e) => {
crate::residency::allocation_error(&e);
tracing::warn!(error = %e, size, "no upload buffer");
None
}
@@ -8558,8 +8754,11 @@ struct Presenter {
ahead: Vec<(HostList, u64)>,
hwnd: HWND,
meter: Meter,
composer: Option<crate::compose::Composer>,
#[cfg(feature = "diagnostics")]
panel: panel::Panel,
#[cfg(feature = "diagnostics")]
menu: menu::Menu,
}
/// The frame rate, shown in the window's caption every second and logged
@@ -8849,7 +9048,13 @@ impl Meter {
self.caption = Some(buffer);
}
let Some(caption) = &self.caption else { return };
let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
// LOCAL (11/26): with frame generation, the frames shown too.
let shown = crate::fg::shown_per_frame();
let text = if shown > 1 {
format!(" | VIctory {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(shown))
} else {
format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame")
};
let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
text.push(0);
// Setting the text waits for the window's thread (a title thread,
@@ -8881,25 +9086,40 @@ impl Host {
/// Shows `texture`, which is in `state` (a host state) and stays in it,
/// as frame `frame` (saved if captures are on). `None` if nothing was
/// shown; else, in diagnostics builds, whether the frame was black.
#[allow(dead_code)]
pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
self.present_over(texture, state, None, frame)
self.present_planes(texture, state, None, frame)
}
/// LOCAL (port of fxceless #1189): [`Self::present`], with a second
/// plane laid over `texture` if there is one (`crate::compose`): its
/// texture and its state, which it is left in.
pub(crate) fn present_over(
/// Shows `texture`, optionally alpha-compositing a second `overlay` plane
/// over it (Series S two-plane presentation), and returns them to their states.
pub(crate) fn present_planes(
&self,
texture: &ID3D12Resource,
state: u32,
over: Option<(&ID3D12Resource, u32)>,
overlay: Option<(&ID3D12Resource, u32)>,
frame: u64,
) -> Option<bool> {
// SAFETY: a live resource.
let desc = unsafe { texture.GetDesc() };
let Some(format) = swap_format(desc.Format) else {
tracing::warn!(format = desc.Format.0, "cannot present this format");
return None;
let planes = overlay.and_then(|(over, over_state)| {
// SAFETY: a live overlay resource.
let over_desc = unsafe { over.GetDesc() };
Some((
over,
D3D12_RESOURCE_STATES(over_state as i32),
crate::compose::view(&desc)?,
crate::compose::view(&over_desc)?,
))
});
let format = if planes.is_some() {
DXGI_FORMAT_R8G8B8A8_UNORM
} else {
let Some(format) = swap_format(desc.Format) else {
tracing::warn!(format = desc.Format.0, "cannot present this format");
return None;
};
format
};
let (width, height) = (desc.Width as u32, desc.Height);
let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
@@ -8912,7 +9132,18 @@ impl Host {
}
};
}
let state_u32 = state;
let p = presenter.as_mut()?;
if planes.is_some() && p.composer.is_none() {
match crate::compose::Composer::new(self, format) {
Ok(c) => p.composer = Some(c),
Err(e) => {
tracing::warn!(error = %e, "two-plane composer not made; showing base plane only");
drop(presenter);
return self.present_planes(texture, state_u32, None, frame);
}
}
}
if (p.width, p.height, p.format) != (width, height, format) {
// Presents sent ahead hold back buffers until they have run.
settle_now(WHY_SYNC);
@@ -8923,6 +9154,9 @@ impl Host {
};
match resized {
Ok(()) => {
if p.format != format {
p.composer = None;
}
(p.width, p.height, p.format) = (width, height, format);
tracing::info!(
width,
@@ -8939,8 +9173,18 @@ impl Host {
}
}
}
let state = D3D12_RESOURCE_STATES(state as i32);
// SAFETY: our swap chain, list and a live source texture.
if planes.is_some() && p.composer.is_none() {
match crate::compose::Composer::new(self, format) {
Ok(c) => p.composer = Some(c),
Err(e) => {
tracing::warn!(error = %e, "two-plane composer not made after resize; showing base plane only");
drop(presenter);
return self.present_planes(texture, state_u32, None, frame);
}
}
}
let state = D3D12_RESOURCE_STATES(state_u32 as i32);
// SAFETY: our swap chain, list and live source texture(s).
unsafe {
let index = p.swap_chain.GetCurrentBackBufferIndex();
let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
@@ -8969,42 +9213,136 @@ impl Host {
None => &p.copy,
};
copy.reset();
copy.keep(texture);
let list = &copy.list;
list.ResourceBarrier(&[
transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
transition(
let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes {
copy.keep(over);
if let Some(composer) = p.composer.as_mut() {
let mut pre = Vec::with_capacity(3);
if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE {
pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));
}
if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE {
pre.push(transition(over, over_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE));
}
pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
list.ResourceBarrier(&pre);
let compose_slot = slot.map_or(0, |i| i + 1);
if let Err(err) = composer.record(
self,
compose_slot,
list,
[(texture, base_fmt), (over, over_fmt)],
&back,
(width, height),
) {
copy.close();
drop(back);
drop(presenter);
tracing::warn!(%err, "could not record display composite; presenting the base plane");
return self.present_planes(texture, state_u32, None, frame);
}
static ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !ONCE.swap(true, Ordering::Relaxed) {
tracing::info!(
frame,
width,
height,
base_format = base_fmt.0,
overlay_format = over_fmt.0,
"display output: compositing two planes (overlay active)"
);
}
let mut post = Vec::with_capacity(3);
if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE {
post.push(transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state));
}
if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE {
post.push(transition(over, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, over_state));
}
post.push(transition(
&back,
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_COPY_DEST,
));
list.ResourceBarrier(&post);
true
} else {
false
}
} else {
false
};
if !composed {
let mut pre = Vec::with_capacity(2);
if state != D3D12_RESOURCE_STATE_COPY_SOURCE {
pre.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE));
}
pre.push(transition(
&back,
D3D12_RESOURCE_STATE_PRESENT,
D3D12_RESOURCE_STATE_COPY_DEST,
),
]);
// LOCAL (port of fxceless #1189): the second plane laid over the
// first, into a texture of ours shown instead (`crate::compose`).
let laid = over.and_then(|(ui, ui_state)| crate::compose::record(&self.device, list, texture, ui, ui_state));
if let Some(laid) = &laid {
copy.keep(laid);
));
list.ResourceBarrier(&pre);
list.CopyResource(&back, texture);
}
list.CopyResource(&back, laid.as_ref().unwrap_or(texture));
#[cfg(feature = "diagnostics")]
let capture = crate::capture::wanted(frame)
.then(|| crate::capture::read_back(&self.device, list, texture))
.then(|| {
if composed {
list.ResourceBarrier(&[transition(
&back,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COPY_SOURCE,
)]);
let res = crate::capture::read_back(&self.device, list, &back);
list.ResourceBarrier(&[transition(
&back,
D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATE_COPY_DEST,
)]);
res
} else {
crate::capture::read_back(&self.device, list, texture)
}
})
.flatten();
#[cfg(feature = "diagnostics")]
let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
let probe = if slot.is_some() || composed {
None
} else {
crate::capture::probe(&self.device, list, texture)
};
#[cfg(feature = "diagnostics")]
let watched = crate::popwatch::take(&self.device, list, texture);
let watched = if composed {
None
} else {
crate::popwatch::take(&self.device, list, texture)
};
#[cfg(feature = "diagnostics")]
p.panel.draw(self, copy, &back, (width, height), format);
#[cfg(feature = "diagnostics")]
p.menu.draw(self, copy, &back, (width, height), format);
#[cfg(not(feature = "diagnostics"))]
let _ = frame;
list.ResourceBarrier(&[
transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
transition(
if composed {
list.ResourceBarrier(&[transition(
&back,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_PRESENT,
),
]);
)]);
} else {
let mut post = Vec::with_capacity(2);
if state != D3D12_RESOURCE_STATE_COPY_SOURCE {
post.push(transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state));
}
post.push(transition(
&back,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_PRESENT,
));
list.ResourceBarrier(&post);
}
copy.close();
let flown = match slot {
Some(i) => {
@@ -9030,10 +9368,14 @@ impl Host {
#[cfg(feature = "diagnostics")]
crate::replay::record::present(texture, state);
let mut showing = crate::timeline::span("the host's Present");
crate::fg::present_start();
let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
crate::fg::present_end();
showing.next("the frame meter");
#[cfg(feature = "diagnostics")]
p.panel.frame(p.meter.line_due());
#[cfg(feature = "diagnostics")]
p.menu.frame();
p.meter.frame(p.hwnd);
showing.end();
#[cfg(feature = "diagnostics")]
@@ -9057,6 +9399,8 @@ impl Host {
// SAFETY: plain object creation for our window.
unsafe {
let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
// LOCAL (11/26): with `VICTORY_FRAME_GEN`, Streamline's proxy factory (crate::fg).
let factory = crate::fg::start(&self.device, factory);
let desc = DXGI_SWAP_CHAIN_DESC1 {
Width: width,
Height: height,
@@ -9086,8 +9430,11 @@ impl Host {
ahead: Vec::new(),
hwnd,
meter: Meter::new(),
composer: None,
#[cfg(feature = "diagnostics")]
panel: panel::Panel::new(),
#[cfg(feature = "diagnostics")]
menu: menu::Menu::new(),
})
}
}
@@ -201,6 +201,7 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool {
.iter()
.any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))),
Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to),
Step::Plane((at, len), _) => copies.iter().any(|w| w.from < at.saturating_add(*len) && *at < w.to),
_ => false,
})
})
@@ -440,6 +441,11 @@ fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec<Does>, Vec<(u
asked: touches(written, at, at + len),
}
}
&Step::Plane((at, len), _) => Does::Read {
from: at,
to: at.saturating_add(len),
asked: touches(written, at, at.saturating_add(len)),
},
&Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
Step::Refresh(shadow, at, len) => Does::Refresh {
shadow: Arc::as_ptr(shadow) as usize,
+528
View File
@@ -0,0 +1,528 @@
//! LOCAL (11/26): the F1 settings menu. F1 shows and hides it while our
//! window has the focus; Up/Down pick a setting, Left/Right change it, Enter
//! runs the line picked (save, save and restart, reset, close), Esc closes.
//! While it is shown the title sees no keyboard (`crate::SETTINGS_MENU_OPEN`,
//! read by the input module); a pad still works.
//!
//! Most settings are read once at start, so a change is saved to the file
//! `VICTORY_MENU_FILE` names (play.ps1 sets it to the play folder's
//! settings.txt and applies it at every start) and takes effect at the next
//! start; "SAVE AND RESTART" starts play.ps1 again (`VICTORY_MENU_PLAY`,
//! with `VICTORY_MENU_ARGS`) and ends this run. Lines marked LIVE change at
//! once.
//!
//! Drawn as the stats panel is (`super::panel`): white text on a black box,
//! copied onto the swap chain's buffer, in the middle of the picture.
use std::sync::atomic::Ordering;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
GetAsyncKeyState, VK_DOWN, VK_ESCAPE, VK_F1, VK_LEFT, VK_RETURN, VK_RIGHT, VK_UP,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
use super::panel::{colours, glyph};
use super::{Host, HostList, transition};
const GLYPH: (u32, u32) = (5, 7);
const CELL: (u32, u32) = (6, 9);
const COLUMNS: u32 = 60;
/// Lines of the box: a title, a help line, a blank, the settings shown, a
/// blank and a note.
const ROWS: usize = 20;
const LINES: u32 = ROWS as u32 + 5;
const RIM: u32 = 4;
const UPLOADS: usize = 4;
/// A setting: the variable, its name in the menu, the values it takes
/// (`""`: not set, the build's own default), and whether a change applies at once.
struct Item {
var: &'static str,
label: &'static str,
values: &'static [(&'static str, &'static str)],
live: bool,
}
const OFF_ON: &[(&str, &str)] = &[("0", "OFF"), ("1", "ON")];
const UNSET_ON: &[(&str, &str)] = &[("", "OFF"), ("1", "ON")];
#[rustfmt::skip]
const ITEMS: &[Item] = &[
Item { var: "VICTORY_UPSCALE", label: "UPSCALER", values: &[("dlss", "DLSS"), ("stretch", "STRETCH"), ("", "GAME FSR4 (SLOW)")], live: false },
Item { var: "VICTORY_FRAME_GEN", label: "FRAME GEN (NOT WITH RAY TR.)", values: &[("", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false },
Item { var: "VICTORY_FPS_CAP", label: "FRAME RATE CAP", values: &[("", "GAME (30)"), ("60", "60"), ("120", "120"), ("0", "NONE")], live: true },
Item { var: "VICTORY_BVH_BUILDER", label: "RAY TRACING (REAL LIGHTING)", values: &[("", "OFF"), ("1", "ON")], live: false },
Item { var: "VICTORY_DLSS_PRESET", label: "DLSS MODEL", values: &[("", "DEFAULT (K)"), ("K", "K TRANSFORMER"), ("J", "J TRANSFORMER"), ("M", "M TRANSFORMER"), ("L", "L TRANSFORMER")], live: false },
Item { var: "VICTORY_DLSS_SHARPNESS", label: "DLSS SHARPNESS", values: &[("0", "0"), ("0.25", "0.25"), ("0.5", "0.5"), ("0.75", "0.75"), ("1", "1")], live: true },
Item { var: "VICTORY_MENU_SMOOTH_MOTION", label: "SMOOTH MOTION", values: &[("1", "ON"), ("0", "OFF")], live: false },
Item { var: "VICTORY_MENU_CONSOLE", label: "CONSOLE", values: &[("series-s", "SERIES S"), ("series-x", "SERIES X")], live: false },
Item { var: "VICTORY_ADAPTER", label: "GRAPHICS CARD", values: &[("", "WINDOWS DEFAULT"), ("#0", "CARD 0"), ("#1", "CARD 1"), ("#2", "CARD 2")], live: false },
Item { var: "VICTORY_PANEL", label: "STATS PANEL (F3)", values: UNSET_ON, live: true },
Item { var: "VICTORY_RELAY", label: "RELAY (SPEED, TRIANGLES)", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false },
Item { var: "VICTORY_RELAY_COPY", label: "RELAY COPY QUEUE", values: OFF_ON, live: false },
Item { var: "VICTORY_FETCH_CHECK", label: "FETCH CHECK", values: OFF_ON, live: false },
Item { var: "VICTORY_WIDE_BACK", label: "WIDE COPY BACK", values: OFF_ON, live: false },
Item { var: "VICTORY_CARD_STEPS", label: "CARD STEPS", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false },
Item { var: "VICTORY_TEXTURE_NO_WAIT", label: "TEXTURE NO WAIT", values: OFF_ON, live: false },
Item { var: "VICTORY_HEAP_RECHECK_EVERY", label: "TEXTURE RECHECK (OIL TEST)", values: &[("", "OFF"), ("60", "EVERY 60 FRAMES"), ("15", "EVERY 15 FRAMES")], live: false },
Item { var: "VICTORY_NULL_SAMPLER_LINEAR", label: "LINEAR STAND-IN SAMPLER", values: UNSET_ON, live: false },
Item { var: "VICTORY_AMBIENT", label: "AMBIENT STAND-IN", values: OFF_ON, live: false },
Item { var: "VICTORY_AMBIENT_AIR", label: "FOG CAP", values: &[("1.5", "1.5"), ("1", "1"), ("2", "2"), ("", "NONE")], live: false },
Item { var: "VICTORY_NAN_SCRUB", label: "NAN SCRUB (SHADERS REBUILD)", values: OFF_ON, live: false },
Item { var: "VICTORY_THIN", label: "THIN", values: OFF_ON, live: false },
Item { var: "VICTORY_JOIN_PARTS", label: "JOIN PARTS", values: &[("8", "8"), ("4", "4"), ("16", "16"), ("1", "1")], live: false },
Item { var: "VICTORY_JOIN_COPIES", label: "JOIN COPIES", values: OFF_ON, live: false },
Item { var: "VICTORY_UPLOAD_AHEAD", label: "UPLOAD AHEAD", values: OFF_ON, live: false },
Item { var: "VICTORY_INDIRECT_WINDOW", label: "INDIRECT WINDOW", values: OFF_ON, live: false },
Item { var: "VICTORY_INDIRECT_BATCH", label: "INDIRECT BATCH", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false },
Item { var: "VICTORY_CARD_REHASH_RUNS", label: "CARD REHASH RUNS", values: OFF_ON, live: false },
Item { var: "VICTORY_MAP_THREADS", label: "MAP THREADS", values: OFF_ON, live: false },
Item { var: "VICTORY_TITLE_PRIORITIES", label: "TITLE THREAD PRIORITIES", values: OFF_ON, live: false },
Item { var: "VICTORY_CARD_AWAKE", label: "KEEP CARD AWAKE", values: OFF_ON, live: false },
Item { var: "VICTORY_SHOW_AFTER", label: "SHOW AFTER", values: OFF_ON, live: false },
Item { var: "VICTORY_PIPELINE_WAIT_MS", label: "SHADER WAIT MS", values: &[("10000", "10000"), ("30000", "30000"), ("1000", "1000"), ("0", "0 SKIP")], live: false },
Item { var: "VICTORY_DYNAMIC_SLOTS", label: "DESCRIPTOR SLOTS", values: &[("524288", "524288"), ("262144", "262144"), ("1000000", "1000000")], live: false },
Item { var: "VICTORY_CARD_BUFFERS_MB", label: "CARD BUFFERS MB", values: &[("1536", "1536"), ("1024", "1024"), ("2048", "2048"), ("512", "512"), ("0", "0 OFF")], live: false },
Item { var: "VICTORY_RENDER_SCALE", label: "RENDER SCALE", values: &[("", "GAME (720P)"), ("0.5", "0.5 (540P)"), ("0.75", "0.75")], live: false },
Item { var: "VICTORY_OWN_UPSCALER", label: "OWN UPSCALER", values: UNSET_ON, live: false },
Item { var: "VICTORY_D3D12_DRED", label: "CRASH BREADCRUMBS", values: &[("light", "LIGHT"), ("", "OFF")], live: false },
];
/// The lines after the settings.
const ACTIONS: [&str; 4] = ["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "RESET ALL TO PLAY DEFAULTS", "CLOSE"];
fn get(var: &str) -> String {
std::env::var(var).unwrap_or_default()
}
/// Whether a change of `item` shows at once.
fn live(item: &Item) -> bool {
item.live || (item.var == "VICTORY_FRAME_GEN" && crate::fg::active())
}
/// The index of `value` among the item's values (an unknown value: shown as
/// itself, at the end).
fn index_of(item: &Item, value: &str) -> Option<usize> {
item.values.iter().position(|(v, _)| *v == value)
}
/// Keys pressed, gathered on a thread of their own every 10 ms: a frame
/// lasts 50 ms and more, and a short press would fall between two frames.
fn keys() -> &'static Mutex<Vec<u16>> {
static KEYS: OnceLock<Mutex<Vec<u16>>> = OnceLock::new();
KEYS.get_or_init(|| {
let _ = std::thread::Builder::new().name("settings menu keys".into()).spawn(|| {
const WATCHED: [u16; 7] = [VK_F1, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_RETURN, VK_ESCAPE];
let mut was = [false; WATCHED.len()];
loop {
std::thread::sleep(Duration::from_millis(10));
let mut process = 0;
// SAFETY: plain queries; room for the answer.
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
let ours = process == std::process::id();
for (i, &vk) in WATCHED.iter().enumerate() {
// SAFETY: a plain query.
let down = ours && unsafe { GetAsyncKeyState(i32::from(vk)) } < 0;
if down && !was[i] {
keys().lock().unwrap_or_else(|e| e.into_inner()).push(vk);
}
was[i] = down;
}
}
});
Mutex::new(Vec::new())
})
}
/// The box's size in pixels.
const fn size(scale: u32) -> (u32, u32) {
((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale)
}
fn lit(lines: &[String], x: u32, y: u32) -> bool {
let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else {
return false;
};
if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= COLUMNS {
return false;
}
let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else {
return false;
};
(glyph(c.to_ascii_uppercase())[(y % CELL.1) as usize] >> (GLYPH.0 - 1 - x % CELL.0)) & 1 != 0
}
fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec<u8> {
let (width, height) = size(scale);
let bytes = colours[0].len();
let mut out = vec![0; pitch * height as usize];
for y in 0..height / scale {
let top = pitch * (y * scale) as usize;
for x in 0..width / scale {
let colour = colours[usize::from(lit(lines, x, y))];
for i in 0..scale {
let at = top + (x * scale + i) as usize * bytes;
out[at..at + bytes].copy_from_slice(colour);
}
}
for i in 1..scale as usize {
out.copy_within(top..top + pitch, top + i * pitch);
}
}
out
}
struct Buffers {
format: DXGI_FORMAT,
scale: u32,
pitch: u32,
uploads: Vec<(ID3D12Resource, *mut u8)>,
card: ID3D12Resource,
turn: usize,
fresh: bool,
/// The card's buffer was copied into before (it is in the copy-source state;
/// at first it is in the common state, promoted by the first copy).
used: bool,
}
// SAFETY: free-threaded resources, and memory only written under the presenter's lock.
unsafe impl Send for Buffers {}
impl Buffers {
fn new(host: &Host, format: DXGI_FORMAT, scale: u32) -> Option<Buffers> {
let (width, height) = size(scale);
let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256);
let bytes = u64::from(pitch) * u64::from(height);
let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::<Option<Vec<_>>>()?;
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: bytes,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let mut card: Option<ID3D12Resource> = None;
// SAFETY: plain creation of a buffer.
unsafe {
host.device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card)
.ok()?;
}
Some(Buffers { format, scale, pitch, uploads, card: card?, turn: 0, fresh: false, used: false })
}
fn write(&mut self, lines: &[String]) {
let Some(colours) = colours(self.format) else { return };
let picture = painted(lines, self.scale, colours, self.pitch as usize);
self.turn = (self.turn + 1) % UPLOADS;
// SAFETY: a mapped upload buffer of the picture's size, which the card read frames ago.
unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) };
self.fresh = true;
}
}
/// The menu of a presenter.
pub(super) struct Menu {
/// The values chosen, by item (as at start until changed).
values: Vec<String>,
/// The values at start.
started: Vec<String>,
/// The line picked: an item, or an action after them.
at: usize,
note: String,
changed: bool,
buffers: Option<Buffers>,
failed: bool,
}
impl Menu {
pub(super) fn new() -> Menu {
// Start the key thread now: F1 must be seen while the menu is closed.
let _ = keys();
let values: Vec<String> = ITEMS.iter().map(|i| get(i.var)).collect();
Menu { started: values.clone(), values, at: 0, note: String::new(), changed: true, buffers: None, failed: false }
}
fn open() -> bool {
crate::SETTINGS_MENU_OPEN.load(Ordering::Relaxed)
}
fn lines(&self) -> Vec<String> {
let total = ITEMS.len() + ACTIONS.len();
let first = self.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS));
let mut out = vec![
"SETTINGS F1 OR ESC CLOSES".to_owned(),
"UP/DOWN PICK LEFT/RIGHT CHANGE ENTER DOES IT".to_owned(),
String::new(),
];
for row in first..(first + ROWS).min(total) {
let cursor = if row == self.at { '>' } else { ' ' };
let line = if let Some(item) = ITEMS.get(row) {
let value = &self.values[row];
let shown = index_of(item, value).map_or(value.to_ascii_uppercase(), |i| item.values[i].1.to_owned());
let mark = if *value != self.started[row] { if live(item) { " *LIVE" } else { " *" } } else if live(item) { " LIVE" } else { "" };
format!("{cursor} {:<27} < {shown} >{mark}", item.label)
} else {
format!("{cursor} {}", ACTIONS[row - ITEMS.len()])
};
out.push(line.chars().take(COLUMNS as usize).collect());
}
while out.len() < 3 + ROWS {
out.push(String::new());
}
out.push(String::new());
out.push(if self.note.is_empty() { "* = CHANGED: APPLIES AT THE NEXT START UNLESS LIVE".to_owned() } else { self.note.clone() });
out
}
/// Changes item `i` by `step` (+1 / -1) through its values.
fn change(&mut self, i: usize, step: isize) {
let item = &ITEMS[i];
let n = item.values.len() as isize;
let now = index_of(item, &self.values[i]).map_or(-1, |x| x as isize);
let next = if now < 0 { if step > 0 { 0 } else { n - 1 } } else { (now + step).rem_euclid(n) };
self.values[i] = item.values[next as usize].0.to_owned();
if live(item) {
self.apply_live(i);
}
self.note.clear();
}
/// With a start that had frame generation on, its amount (and off) changes while running;
/// from a start without it, turning it on needs the restart (Streamline's swap chain).
fn apply_live(&self, i: usize) {
let (var, value) = (ITEMS[i].var, &self.values[i]);
// SAFETY: the variables changed here are read by this build with
// std::env::var at each use; Windows' environment block is locked by
// the process heap's routines, and std holds its own lock.
unsafe {
if value.is_empty() {
std::env::remove_var(var);
} else {
std::env::set_var(var, value);
}
}
if var == "VICTORY_FPS_CAP" {
crate::frame::set_cap(value);
}
if var == "VICTORY_PANEL" {
super::panel::shown().store(!value.is_empty(), Ordering::Relaxed);
}
}
/// Writes the changed values over those in the settings file.
fn save(&mut self) -> bool {
let Some(path) = std::env::var_os("VICTORY_MENU_FILE") else {
self.note = "NO SETTINGS FILE: START THE GAME WITH PLAY.PS1".to_owned();
return false;
};
let mut kept: Vec<(String, String)> = std::fs::read_to_string(&path)
.unwrap_or_default()
.lines()
.filter_map(|l| l.split_once('=').map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned())))
.filter(|(k, _)| k.starts_with("VICTORY_"))
.collect();
for (i, item) in ITEMS.iter().enumerate() {
if self.values[i] == self.started[i] {
continue;
}
kept.retain(|(k, _)| k != item.var);
kept.push((item.var.to_owned(), self.values[i].clone()));
}
let mut text = String::from("# Saved by the F1 menu; play.ps1 applies these after its own settings (an empty value: unset).\r\n");
for (k, v) in &kept {
text.push_str(&format!("{k}={v}\r\n"));
}
match std::fs::write(&path, text) {
Ok(()) => {
tracing::info!(path = %std::path::Path::new(&path).display(), "settings menu: saved");
self.started = self.values.clone();
self.note = "SAVED. APPLIES AT THE NEXT START".to_owned();
true
}
Err(e) => {
tracing::warn!(error = %e, "settings menu: not saved");
self.note = "COULD NOT SAVE THE SETTINGS FILE".to_owned();
false
}
}
}
/// Starts play.ps1 again in a new console, a few seconds on, and ends this run.
fn restart(&mut self) {
use std::os::windows::process::CommandExt;
let Some(play) = std::env::var_os("VICTORY_MENU_PLAY") else {
self.note = "SAVED. RESTART PLAY.PS1 YOURSELF".to_owned();
return;
};
let play = play.to_string_lossy().replace('\'', "''");
let args = get("VICTORY_MENU_ARGS");
let command = format!("Start-Sleep 3; & '{play}' {args}");
const CREATE_NEW_CONSOLE: u32 = 0x10;
match std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &command])
.creation_flags(CREATE_NEW_CONSOLE)
.spawn()
{
Ok(_) => {
tracing::info!(command, "settings menu: restarting");
// Ended at once: std::process::exit runs the DLLs' unloading, and with Streamline
// loaded that never came back (11/26: a windowless leftover with one thread
// and 27 GB, which also kept the new build from being put in place).
// SAFETY: this process, with nothing of its own left to save.
unsafe {
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
TerminateProcess(GetCurrentProcess(), 0);
}
std::process::exit(0);
}
Err(e) => {
tracing::warn!(error = %e, "settings menu: restart failed");
self.note = "SAVED, BUT THE RESTART FAILED".to_owned();
}
}
}
/// Empties the settings file: play.ps1's own settings at the next start.
fn reset(&mut self) {
if let Some(path) = std::env::var_os("VICTORY_MENU_FILE") {
let _ = std::fs::remove_file(path);
}
self.note = "RESET. PLAY DEFAULTS AT THE NEXT START".to_owned();
}
/// A frame was presented: the keys pressed since the last one.
pub(super) fn frame(&mut self) {
let pressed = std::mem::take(&mut *keys().lock().unwrap_or_else(|e| e.into_inner()));
if pressed.is_empty() {
return;
}
let total = ITEMS.len() + ACTIONS.len();
for vk in pressed {
let open = Self::open();
if vk == VK_F1 || (open && vk == VK_ESCAPE) {
crate::SETTINGS_MENU_OPEN.store(!open && vk == VK_F1, Ordering::Relaxed);
self.note.clear();
self.changed = true;
continue;
}
if !open {
continue;
}
match vk {
VK_UP => self.at = (self.at + total - 1) % total,
VK_DOWN => self.at = (self.at + 1) % total,
VK_LEFT if self.at < ITEMS.len() => self.change(self.at, -1),
VK_RIGHT if self.at < ITEMS.len() => self.change(self.at, 1),
VK_RETURN if self.at < ITEMS.len() => self.change(self.at, 1),
VK_RETURN => match self.at - ITEMS.len() {
0 => {
if self.save() {
self.restart();
}
}
1 => {
self.save();
}
2 => self.reset(),
_ => crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed),
},
_ => {}
}
self.changed = true;
}
}
/// Records the copy of the box onto `back` (in the copy-destination state).
pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) {
if !Self::open() || self.failed {
return;
}
let _ours = crate::replay::record::unrecorded();
let scale = (height / 540).max(1);
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new(host, format, scale);
self.failed = self.buffers.is_none();
self.changed = true;
}
let lines = if self.changed { Some(self.lines()) } else { None };
let Some(buffers) = &mut self.buffers else { return };
if let Some(lines) = lines {
self.changed = false;
buffers.write(&lines);
}
let (w, h) = size(scale);
let (w, h) = (w.min(width), h.min(height));
let (x, y) = ((width - w) / 2, (height - h) / 2);
let list = &list.list;
// SAFETY: an open list and live resources; the box lies within both.
unsafe {
if std::mem::take(&mut buffers.fresh) {
if std::mem::replace(&mut buffers.used, true) {
list.ResourceBarrier(&[transition(&buffers.card, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]);
}
list.CopyResource(&buffers.card, &buffers.uploads[buffers.turn].0);
list.ResourceBarrier(&[transition(&buffers.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
}
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&buffers.card),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: size(scale).0, Height: size(scale).1, Depth: 1, RowPitch: buffers.pitch },
},
},
};
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(back),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
let part = D3D12_BOX { left: 0, top: 0, front: 0, right: w, bottom: h, back: 1 };
list.CopyTextureRegion(&to, x, y, 0, &from, Some(&part));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_line_fits_and_every_character_has_a_picture() {
let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, buffers: None, failed: false };
menu.started = menu.values.clone();
for at in 0..ITEMS.len() + ACTIONS.len() {
menu.at = at;
for line in menu.lines() {
assert!(line.len() <= COLUMNS as usize, "{line}");
for c in line.bytes() {
assert_ne!(glyph(c.to_ascii_uppercase()), glyph(b'#'), "{line}: {}", c as char);
}
}
}
}
#[test]
fn values_cycle_both_ways() {
let mut menu = Menu { values: ITEMS.iter().map(|i| i.values[0].0.to_owned()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, buffers: None, failed: false };
menu.started = menu.values.clone();
let n = ITEMS[0].values.len();
for _ in 0..n {
menu.change(0, 1);
}
assert_eq!(menu.values[0], ITEMS[0].values[0].0);
menu.change(0, -1);
assert_eq!(menu.values[0], ITEMS[0].values[n - 1].0);
}
}
+22 -5
View File
@@ -40,7 +40,7 @@ fn asked() -> bool {
}
/// Whether it is shown now.
fn shown() -> &'static AtomicBool {
pub(super) fn shown() -> &'static AtomicBool {
static SHOWN: OnceLock<AtomicBool> = OnceLock::new();
SHOWN.get_or_init(|| AtomicBool::new(asked()))
}
@@ -61,7 +61,7 @@ fn pressed() -> bool {
/// Seven rows of five dots, the leftmost the highest bit.
#[rustfmt::skip]
const fn glyph(c: u8) -> [u8; 7] {
pub(super) const fn glyph(c: u8) -> [u8; 7] {
match c {
b'0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
b'1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
@@ -103,6 +103,19 @@ const fn glyph(c: u8) -> [u8; 7] {
b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
b' ' => [0; 7],
// LOCAL (11/26): for the F1 settings menu (menu.rs).
b'>' => [0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000],
b'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010],
b'*' => [0, 0b00100, 0b10101, 0b01110, 0b10101, 0b00100, 0],
b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
b'_' => [0, 0, 0, 0, 0, 0, 0b11111],
b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
b'(' => [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
b')' => [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000],
b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
b',' => [0, 0, 0, 0, 0b01100, 0b00100, 0b01000],
b'!' => [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0, 0b00100],
b'?' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0, 0b00100],
_ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111],
}
}
@@ -133,7 +146,7 @@ fn lit(lines: &[String], x: u32, y: u32) -> bool {
}
/// The bytes of a black and a white pixel of a swap chain's format.
fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> {
pub(super) fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> {
Some(match format {
DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM => [&[0, 0, 0, 0xFF], &[0xFF; 4]],
DXGI_FORMAT_R10G10B10A2_UNORM => [&[0, 0, 0, 0xC0], &[0xFF; 4]],
@@ -213,8 +226,12 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec
let [budget, used, _, shared] = host.video_memory().unwrap_or_default();
let idle = (c[1] / 1e3).min(ms);
vec![
format!("FPS {:.1} FRAME {ms:.1} MS LONGEST {worst:.0}", 1e3 / ms.max(0.001)),
format!("DRAWS {:.0} DROPPED {:.0}", c[10], c[8]),
// LOCAL (11/26): with frame generation, the frames shown beside those rendered.
match crate::fg::shown_per_frame() {
1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)),
n => format!("FPS {:.1} FG {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001), f64::from(n) * 1e3 / ms.max(0.001)),
},
format!("DRAWS {:.0} DROPPED {:.0} LONGEST {worst:.0}", c[10], c[8]),
format!("SUBMIT BUSY {:.1} WAITS FOR GPU {:.1}", c[0] / 1e3, c[3] / 1e3),
format!("GPU BUSY {:.1} IDLE BEHIND US {:.1}", ms - idle, c[2] / 1e3),
format!("RECORDING {:.0} MS COPY BACK {:.1}", c[9] / 1e6, c[5] / 1e3),
+1
View File
@@ -119,6 +119,7 @@ pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bo
let (at, len) = staging.memory();
touches(&ranges, at, at + len)
}
&Step::Plane((at, len), _) => touches(&ranges, at, at.saturating_add(len)),
Step::Host(_, (from, to)) => touches(&ranges, *from, *to),
Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len),
_ => false,
+42
View File
@@ -317,6 +317,48 @@ fn known(copy: u64, at: usize) -> String {
type Crossed = BTreeMap<((u64, u64), (u64, u64)), (u64, usize, usize)>;
static CROSSED: Mutex<(u64, Crossed)> = Mutex::new((0, BTreeMap::new()));
/// LOCAL (11/26, `VICTORY_RELAY_CROSS=1`): whether a refresh of `runs` reads
/// title memory that a flight in the air may be writing through another copy
/// of it ([`reads`] counts those). Such a refresh sends the bytes from before
/// the flight, and draws of that submission read them: one frame of stale
/// vertices and indices (triangles flung across the screen with the relay on,
/// none with `VICTORY_RELAY=0`). The caller settles the flights first.
pub(crate) fn cross_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_CROSS").is_some_and(|v| v == "1"))
}
pub(super) fn crossed(runs: &[&HostList]) -> bool {
let mut writes: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new();
let mut all = Vec::new();
for item in &super::line().line {
if let Late::Run(flight) = item {
for (shadow, ranges) in &flight.back {
writes.extend(ranges.iter().map(|&(a, b)| (shadow.clone(), a, b)));
join_ranges(&mut all, ranges.iter().copied());
}
}
}
if writes.is_empty() {
return false;
}
for list in runs {
for step in &list.deferred().copies {
let Step::Refresh(shadow, at, len) = step else {
continue;
};
let (from, to) = (*at, *at + *len);
if !touches(&all, from, to) {
continue;
}
if writes.iter().any(|(writer, a, b)| *a < to && from < *b && !std::sync::Arc::ptr_eq(writer, shadow)) {
return true;
}
}
}
false
}
/// Flights are in the air and `runs` are about to be prepared: which
/// refreshes of theirs read title memory that a flight may be writing through
/// another copy of it. Such a refresh takes what was there before the flight
+4 -6
View File
@@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool {
/// Whether a record that does not fit in what is left of its list's budget
/// takes the rest, so that every record after it runs empty too
/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits
/// runs). A list whose budget one garbage record empties loses all its later
/// draws, and which record that is may differ from frame to frame. The frame
/// line says how many records a frame are refused.
/// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes
/// nothing and later valid draws still run).
fn rest() -> u32 {
u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0"))
u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1"))
}
/// The clamp compiled from `source` (ours, or in the benchmark the one it
@@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
/// left then, and the records as clamped.
fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> {
let mut warp = WarpHarness::new()?;
let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") };
let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" });
let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP");
const KIND_DRAW: u32 = 0;
const STRIDE: u32 = 16;
+14 -2
View File
@@ -19,10 +19,9 @@
mod ambient;
#[cfg(all(windows, feature = "diagnostics"))]
mod capture;
pub mod console;
// LOCAL (port of fxceless #1189): Series S interface plane laid over the game (VICTORY_COMPOSE=1).
#[cfg(windows)]
mod compose;
pub mod console;
#[cfg(all(windows, feature = "diagnostics"))]
mod copystat;
#[cfg(all(windows, feature = "diagnostics"))]
@@ -40,6 +39,13 @@ pub mod frame;
mod book;
#[cfg(windows)]
mod host;
/// LOCAL (11/26): the F1 settings menu is shown (host/menu.rs): the title gets no keyboard.
pub static SETTINGS_MENU_OPEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(windows)]
pub mod streamline;
#[cfg(windows)]
mod fg;
#[cfg(windows)]
mod indirect;
#[cfg(windows)]
@@ -61,9 +67,15 @@ pub mod query;
pub mod queue;
#[cfg(all(windows, feature = "diagnostics"))]
pub mod replay;
#[cfg(windows)]
mod residency;
pub mod resource;
pub mod root;
#[cfg(windows)]
mod stretch;
#[cfg(all(windows, feature = "dlss"))]
mod dlss;
#[cfg(windows)]
mod safecopy;
#[cfg(windows)]
mod sampler;
+165
View File
@@ -203,6 +203,12 @@ impl Detached {
pub(crate) fn host(&self) -> &crate::host::HostList {
&self.host
}
/// Releases this list's dynamic descriptor slots once its GPU submission
/// has completed, without waiting for the full `bury_lag` allocator delay.
pub(crate) fn release_tables(&mut self) {
self._state.tables_done();
}
}
/// A host list that has run and waits to be used again, and the bytes of
@@ -811,6 +817,165 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
0
}
/// What the title gives its upscale (`ffxDispatch`, Series S), as plain words
/// so that a list whose calls are only written down (`VICTORY_THIN=1`) can
/// carry it to the thread that records.
#[derive(Clone, Copy, Debug, Default)]
pub struct Upscale {
pub colour: u64,
pub depth: u64,
pub motion: u64,
pub exposure: u64,
pub output: u64,
pub render: [u32; 2],
pub jitter: [f32; 2],
pub motion_scale: [f32; 2],
pub reset: bool,
pub pre_exposure: f32,
pub near: f32,
pub far: f32,
pub frame_ms: f32,
/// DLSS where it can (`crate::dlss`, the `dlss` feature), else a stretch.
pub dlss: bool,
}
impl Upscale {
pub(crate) const WORDS: usize = 11;
pub(crate) fn to_words(self) -> [u64; Self::WORDS] {
let pair = |a: f32, b: f32| u64::from(a.to_bits()) | u64::from(b.to_bits()) << 32;
[
self.colour,
self.depth,
self.motion,
self.exposure,
self.output,
u64::from(self.render[0]) | u64::from(self.render[1]) << 32,
pair(self.jitter[0], self.jitter[1]),
pair(self.motion_scale[0], self.motion_scale[1]),
pair(self.pre_exposure, self.frame_ms),
pair(self.near, self.far),
u64::from(self.reset) | u64::from(self.dlss) << 1,
]
}
pub(crate) fn from_words(w: &[u64]) -> Option<Self> {
if w.len() < Self::WORDS {
return None;
}
let pair = |v: u64| [f32::from_bits(v as u32), f32::from_bits((v >> 32) as u32)];
let [pre_exposure, frame_ms] = pair(w[8]);
let [near, far] = pair(w[9]);
Some(Self {
colour: w[0],
depth: w[1],
motion: w[2],
exposure: w[3],
output: w[4],
render: [w[5] as u32, (w[5] >> 32) as u32],
jitter: pair(w[6]),
motion_scale: pair(w[7]),
pre_exposure,
frame_ms,
near,
far,
reset: w[10] & 1 != 0,
dlss: w[10] & 2 != 0,
})
}
}
/// The title's upscale in place of its own FidelityFX passes (slow translated
/// for 32-lane cards): DLSS if asked for and it can, else a plain stretch of
/// the colour input over the output (`crate::stretch`, from
/// CuteBooty/victory-8gb). With `VICTORY_THIN=1` it is written down with the
/// list's other calls and recorded by the thread that records them. False if
/// it could not be recorded or written down.
#[cfg(windows)]
pub fn upscale(this: *const std::ffi::c_void, up: &Upscale) -> bool {
let this: This = this.cast();
if this.is_null() || up.colour == 0 || up.output == 0 {
return false;
}
if thin::on() {
return thin::upscale(this, up);
}
upscale_now(this, up)
}
/// [`upscale`], recorded now on the host list behind `this`.
#[cfg(windows)]
pub(super) fn upscale_now(this: This, up: &Upscale) -> bool {
const SHADER_READ: u32 = 0x40;
const UNORDERED: u32 = 0x8;
let t = |a: u64| -> This { a as This };
let (colour, output) = (t(up.colour), t(up.output));
let mut done = false;
with_state(this, |list, state| {
let (Some(to), Some(from), Some(host)) = (
crate::resource::host_resource(output),
crate::resource::host_resource(colour),
crate::host::host(),
) else {
return;
};
ensure_state(list, colour, SHADER_READ);
ensure_state(list, output, UNORDERED);
#[cfg(feature = "dlss")]
if up.dlss {
let input = |a: u64| {
let r = t(a);
crate::resource::host_resource(r).inspect(|_| ensure_state(list, r, SHADER_READ))
};
let inputs = crate::dlss::Inputs {
colour: from,
depth: input(up.depth),
motion: input(up.motion),
exposure: input(up.exposure),
output: to,
jitter: up.jitter,
motion_scale: up.motion_scale,
render: up.render,
reset: up.reset,
pre_exposure: up.pre_exposure,
near: up.near,
far: up.far,
frame_ms: up.frame_ms,
};
done = crate::dlss::record(&host.device, &list.list, &inputs);
if done {
// LOCAL (11/26): frame generation's depth and motion vectors (crate::fg).
crate::fg::note_titles(up.depth, up.motion);
}
}
if !done {
done = crate::stretch::record_stretch(&host.device, &list.list, to, from, up.render);
}
if done {
crate::texture::host_written(output);
}
state.replay(list);
});
done
}
/// For the upscale probe (`VICTORY_UPSCALE_PROBE=1`): each title texture's
/// host copy as `WxH fmt N` (DXGI format number), or `none`.
#[cfg(windows)]
pub fn upscale_inputs(textures: &[*const std::ffi::c_void]) -> Vec<String> {
textures
.iter()
.map(|&t| match crate::resource::host_resource(t.cast()) {
Some(r) => {
// SAFETY: a live host resource.
let d = unsafe { r.GetDesc() };
format!("{}x{} fmt {}", d.Width, d.Height, d.Format.0)
}
None => "none".to_owned(),
})
.collect()
}
/// Moves a title texture's host copy to `state` in the list, if needed.
#[cfg(windows)]
pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
+20
View File
@@ -469,6 +469,18 @@ const TARGETS: u64 = after(13);
const CLEAR_RTV: u64 = after(14);
const CLEAR_DSV: u64 = after(15);
const COPY_TEXTURE: u64 = after(16);
const UPSCALE: u64 = after(17);
/// Writes the title's upscale down with the list's calls (`super::upscale`);
/// false if the list has no recording being written.
pub(super) fn upscale(this: This, up: &super::Upscale) -> bool {
let front = front(this);
if front.closed || front.recording.is_none() {
return false;
}
front.put(UPSCALE, &(*up).to_words());
true
}
/// The bytes of `count` things at `items` (none if null).
fn bytes_of<'a, T>(items: *const T, count: usize) -> &'a [u8] {
@@ -779,6 +791,14 @@ fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool)
at(w, 2 + 2 * step, boxed),
);
}
UPSCALE => {
if let Some(up) = super::Upscale::from_words(w)
&& !super::upscale_now(list, &up)
{
static TOLD: std::sync::Once = std::sync::Once::new();
TOLD.call_once(|| tracing::warn!("a written-down upscale could not be recorded: its output stays as it is"));
}
}
_ => {}
}
}
+3
View File
@@ -130,6 +130,7 @@ pub(crate) struct Translated {
/// A compute program's threads in a group.
pub(crate) threads: Option<[u32; 3]>,
pub(crate) used: Vec<victory_shader::UsedResource>,
pub(crate) tables: crate::draw::TablePlan,
/// Whether the shader's code can store to buffer memory ([`stores`]);
/// true when its code is not known.
pub(crate) stores: bool,
@@ -222,10 +223,12 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
})
.map(|p| p.used)
.unwrap_or_default();
let tables = crate::draw::TablePlan::new(&used, &host.root_indexed_views);
Ok(Translated {
host,
threads,
used,
tables,
stores,
stores_by_address,
picks: Default::default(),
+1
View File
@@ -602,6 +602,7 @@ impl HostPipeline {
slot == victory_shader::emit::SLOT_FAULTS
} else {
slot == victory_shader::emit::SLOT_STRIDES
|| slot == victory_shader::emit::SLOT_TABLE_STRIDES
|| slot == victory_shader::emit::SLOT_MEMORY
};
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
+88 -6
View File
@@ -41,8 +41,13 @@ pub(crate) struct Pending {
/// whether a draw or dispatch has requested it yet.
key: String,
used: AtomicBool,
/// A pass over the screen ([`GraphicsState::screen_pass`]).
/// A pass over the screen ([`GraphicsState::screen_pass`]) or a confirmed
/// opening-scene / bake producer that must never sit behind cold RT shaders.
screen: bool,
/// Confirmed first-scene / bake producer prepared early even on a cold cache.
scene_input: bool,
/// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH).
left_out: Option<&'static str>,
/// LOCAL: how long draws have waited for it so far, in microseconds
/// ([`wait_once`]).
waited_us: AtomicU64,
@@ -53,6 +58,56 @@ pub(crate) struct Pending {
variant: OnceLock<Arc<Pending>>,
}
fn named(shaders: &[Arc<Shader>], name: &[u8]) -> bool {
shaders
.iter()
.any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name))
}
fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> {
static SKIP_RT_RESOLVE: OnceLock<bool> = OnceLock::new();
let skip_rt = *SKIP_RT_RESOLVE.get_or_init(|| {
let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
if builder {
return false;
}
// Without BVH, ~1,000 CS_RaytracingResolve shaders shade no hits while
// clogging the cold compiler queue; skip unless VICTORY_RT_RESOLVE=1.
std::env::var_os("VICTORY_RT_RESOLVE").is_none_or(|v| v == "0")
});
if skip_rt && named(shaders, b"CS_RaytracingResolve") {
return Some("shades ray-tracing hits without BVH, left out");
}
static SKIP_ACTIVATE_RAYS: OnceLock<bool> = OnceLock::new();
let skip_activate = *SKIP_ACTIVATE_RAYS.get_or_init(|| {
let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
if builder {
return std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0");
}
std::env::var_os("VICTORY_ACTIVATE_RAYS").is_none_or(|v| v == "0")
});
if skip_activate && named(shaders, b"CS_ScreenProbes_ActivateRays") {
return Some("ray activation shader without BVH, left out");
}
None
}
/// Confirmed first-scene producers. Prepare these at creation even on a cold
/// launch so cutscene lighting, tiling, and bakes never miss their first frame.
fn scene_input(shaders: &[Arc<Shader>]) -> bool {
shaders.iter().any(|s| {
matches!(
s.hash.as_str(),
"970c4fbb3b017c0e"
| "068c90badc86f1fd"
| "e4a7e088c7780ce8"
| "ebe4e53f031f5249"
| "2cc4c197ee29e291"
| "369cbe906ea72764"
) || crate::draw::BAKE_PIXEL_SHADERS.contains(&s.hash.as_str())
})
}
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
// elements point into its own names) is only read after creation.
unsafe impl Send for Pending {}
@@ -67,10 +122,17 @@ impl Pending {
key.update(s.hash.as_bytes());
}
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
let scene_input = scene_input(&shaders);
let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass())
&& shaders.iter().all(|s| s.stage != "mesh"))
|| scene_input;
let left_out = left_out(&shaders);
Pending {
screen,
scene_input,
left_out,
formats: graphics.as_ref().map_or([0; 9], |g| g.formats()),
variant: OnceLock::new(),
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
shaders,
graphics,
queue_state: AtomicU8::new(NOT_QUEUED),
@@ -216,6 +278,9 @@ fn variant<'a>(p: &'a Arc<Pending>, g: &GraphicsState, bound: &TargetFormats) ->
/// The host pipeline if it is made (or is made within the frame's budget);
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
if p.left_out.is_some() {
return None;
}
// A still-pending pipeline was requested by the title too. Prewarm it
// on the next launch, even if this run never got to use it.
if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) {
@@ -231,16 +296,23 @@ pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
/// Makes `p` on this thread if it is not made yet (waiting for a worker
/// that is making it); whether it has a host pipeline.
pub(crate) fn now(p: &Arc<Pending>) -> bool {
if p.left_out.is_some() {
return false;
}
p.make();
p.made.get().is_some_and(|made| made.is_some())
}
/// At the title's creation of a pipeline: starts it at once if an earlier
/// run drew with it (during loading, so the world's first frames find it).
/// run drew with it (during loading, so the world's first frames find it),
/// or if it is a confirmed opening-scene / bake producer.
pub(crate) fn early(p: &Arc<Pending>) {
if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
if p.left_out.is_some() {
return;
}
if !p.shaders.is_empty() && (p.scene_input || super::library::wanted_early(&p.key)) {
super::library::EARLY.fetch_add(1, Ordering::Relaxed);
start(p, EARLY);
start(p, if p.scene_input { REQUESTED } else { EARLY });
}
}
@@ -492,8 +564,13 @@ fn next(screens_only: bool) -> Arc<Pending> {
/// 64), else two thirds of the logical processors, 2 to 16. They run below the
/// title's own threads, and a cold cache queues hundreds at once.
fn worker_count(asked: Option<usize>, processors: usize) -> usize {
worker_count_for(asked, processors, false)
}
fn worker_count_for(asked: Option<usize>, processors: usize, limited_ram: bool) -> usize {
match asked {
Some(n) => n.clamp(1, 64),
None if limited_ram => (processors * 3 / 4).clamp(2, 8),
None => (processors * 2 / 3).clamp(2, 16),
}
}
@@ -503,11 +580,12 @@ fn workers() -> bool {
static RUNNING: OnceLock<bool> = OnceLock::new();
*RUNNING.get_or_init(|| {
let mut running = false;
let workers = worker_count(
let workers = worker_count_for(
std::env::var("VICTORY_PIPELINE_WORKERS")
.ok()
.and_then(|v| v.trim().parse().ok()),
std::thread::available_parallelism().map_or(2, |n| n.get()),
crate::residency::limited_host_ram(),
);
tracing::info!(workers, "pipeline workers");
let screens = if screens_first() { SCREEN_WORKERS } else { 0 };
@@ -580,6 +658,10 @@ mod tests {
assert_eq!(worker_count(None, 64), 16);
assert_eq!(worker_count(Some(0), 24), 1);
assert_eq!(worker_count(Some(20), 24), 20);
assert_eq!(worker_count_for(None, 8, true), 6);
assert_eq!(worker_count_for(None, 16, true), 8);
assert_eq!(worker_count_for(None, 24, true), 8);
assert_eq!(worker_count_for(Some(12), 8, true), 12);
}
/// A first use queues the pipeline and, within the budget, gets the
+86 -7
View File
@@ -42,7 +42,25 @@ static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
/// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`].
/// Asked once a second.
pub(crate) fn room(memory: Option<[u64; 4]>) {
SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed);
let pressure = crate::residency::pressured();
let limit = spares(memory, crate::host::keep_freed() && !pressure);
SPARES.store(limit, Ordering::Relaxed);
let tick = now();
// A full pool can become idle while another subsystem needs the VRAM.
// A busy allocator observes the new limit on its next allocation or tick.
if let Ok(mut pool) = TEXTURES.try_lock() {
pool.reclaim(tick, limit, true);
}
if let Ok(mut pool) = STAGING.try_lock() {
let staging_limit = if crate::residency::critical_commit() {
0
} else if pressure {
1
} else {
limit
};
pool.reclaim(tick, staging_limit, true);
}
}
fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize {
@@ -180,11 +198,12 @@ struct Pool<B> {
/// The empty blocks it was last told to keep, and the most it keeps.
spare: usize,
most: usize,
retry_growth_at: u64,
}
impl<B: Clone> Pool<B> {
const fn new(most: usize) -> Pool<B> {
Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most }
Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 }
}
/// A piece of `len` bytes and the memory it lies in, and whether that
@@ -226,10 +245,13 @@ impl<B: Clone> Pool<B> {
unripe.sort_unstable();
found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?)));
}
// A failed 64 MiB block must not trigger another driver call for each
// small texture. Existing free ranges remain usable during backoff.
let (i, start) = match found {
Some(found) => found,
None => {
let i = self.add(make()?, ripe.started);
let memory = self.grow(now, &mut make)?;
let i = self.add(memory, ripe.started);
(i, self.blocks[i].as_mut()?.free.take(len, align)?)
}
};
@@ -242,7 +264,7 @@ impl<B: Clone> Pool<B> {
}
let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count();
if empty < ripe.ahead
&& let Some(memory) = make()
&& let Some(memory) = self.grow(now, &mut make)
{
self.add(memory, ripe.started);
}
@@ -253,6 +275,17 @@ impl<B: Clone> Pool<B> {
Some((Piece { block: i, start, len }, block.memory.clone(), again))
}
fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option<B>) -> Option<B> {
if now < self.retry_growth_at {
return None;
}
let block = make();
if block.is_none() {
self.retry_growth_at = now.saturating_add(500);
}
block
}
fn add(&mut self, memory: B, made: u64) -> usize {
let i = match self.blocks.iter().position(Option::is_none) {
Some(i) => i,
@@ -272,6 +305,10 @@ impl<B: Clone> Pool<B> {
/// Makes the pieces that rested long enough free, and lets go of empty
/// blocks past [`SPARE`].
fn rested(&mut self, now: u64) {
self.reclaim(now, SPARES.load(Ordering::Relaxed), false);
}
fn reclaim(&mut self, now: u64, limit: usize, sweep: bool) {
let mut any = false;
while let Some(&(ready, piece)) = self.resting.front()
&& ready <= now
@@ -283,9 +320,9 @@ impl<B: Clone> Pool<B> {
}
}
// (Without a piece given back too, once there is less room.)
let most = SPARES.load(Ordering::Relaxed).min(self.most);
if any || most < self.spare {
self.spare = most;
let most = limit.min(self.most);
let previous = std::mem::replace(&mut self.spare, most);
if sweep || any || most < previous {
let mut spare = 0;
for block in &mut self.blocks {
if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
@@ -349,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi
// Copies from a buffer begin at multiples of 512.
let bytes = bytes.next_multiple_of(512);
let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
// Only gate speculative bindless prefetch on staging-pool growth
// headroom; table-bound textures and decoration bakes are sampled
// immediately and would otherwise read uninitialized/reused VRAM.
let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get();
if speculative && !crate::residency::allow_staging_growth(false) {
return None;
}
let (buffer, data) = host.upload_buffer(BLOCK)?;
crate::host::name(&buffer, || "staging of textures (a block)".into());
Some(Upload(buffer, data))
@@ -488,6 +532,7 @@ pub(crate) unsafe fn texture(
let mut heap: Option<ID3D12Heap> = None;
// SAFETY: plain creation.
if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
crate::residency::allocation_error(&e);
tracing::warn!(error = %e, "no block of texture memory");
}
if let Some(h) = &heap
@@ -560,6 +605,40 @@ mod tests {
assert_eq!(spares(None, true), SPARE);
}
#[test]
fn a_failed_block_is_not_retried_for_each_small_upload() {
let mut pool: Pool<u32> = Pool::new(2);
let calls = std::cell::Cell::new(0);
let refuse = || { calls.set(calls.get() + 1); None };
for size in [704008, 179720, 179720, 24080, 48648, 524288, 89616, 351760] {
assert!(pool.take(size, 512, 12, refuse).is_none());
}
assert_eq!(calls.get(), 1);
assert!(pool.take(24080, 512, 1012, || Some(1)).is_some());
}
#[test]
fn budget_tick_reclaims_idle_blocks_without_reusing_live_or_resting_pieces() {
let mut pool = Pool::new(STAGING_KEPT);
let (held, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(1)).unwrap();
let (resting, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(2)).unwrap();
pool.give(resting, 0);
for i in 0..12 {
pool.add(i, 0);
}
pool.reclaim(0, SPARE_KEPT, true);
assert_eq!(pool.blocks(), STAGING_KEPT + 1);
pool.reclaim(REST - 1, SPARE, true);
assert_eq!(pool.blocks(), SPARE + 1);
assert_eq!(pool.resting.len(), 1);
pool.reclaim(REST, 0, true);
assert_eq!(pool.blocks(), 1);
assert!(pool.resting.is_empty());
pool.give(held, REST);
pool.reclaim(2 * REST, 0, true);
assert_eq!(pool.blocks(), 0);
}
#[test]
fn pieces_never_overlap_and_rest_before_they_are_used_again() {
let mut pool: Pool<u32> = Pool::new(SPARE);
+85 -103
View File
@@ -651,6 +651,42 @@ pub(crate) struct Plane {
count: u32,
resources: *const This,
}
/// Retail PresentX adds source-rectangle and destination pointers, a color
/// space and seven option words after the common prefix. Older callers pass
/// only the prefix for single-plane presents.
#[cfg(windows)]
#[repr(C)]
struct RetailPlane {
prefix: Plane,
source_rects: *const (),
destination: *const (),
color_space: u32,
options: [u32; 7],
}
#[cfg(windows)]
const _: () = assert!(size_of::<RetailPlane>() == 72);
#[cfg(windows)]
fn overlay_resource(parameters: *const Plane) -> Option<This> {
// Read only the second prefix at the 72-byte retail PresentX stride. A
// caller using a different layout can still present its base plane safely.
let second = parameters.cast::<RetailPlane>().wrapping_add(1).cast::<u8>();
let mut prefix = [0; size_of::<Plane>()];
if !crate::host::read_into(second, &mut prefix) {
return None;
}
// SAFETY: the prefix has the C layout above and its bytes were copied.
let plane = unsafe { prefix.as_ptr().cast::<Plane>().read_unaligned() };
let mut pointer = [0; size_of::<This>()];
if plane.count == 0
|| plane.resources.is_null()
|| !crate::host::read_into(plane.resources.cast(), &mut pointer)
{
return None;
}
let resource = usize::from_ne_bytes(pointer) as This;
crate::resource::is_resource(resource).then_some(resource)
}
/// Submission tagged with the frame it belongs to `(count, lists, frame
/// token, flags)`; frames are paced elsewhere, so it runs as a plain one.
extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) {
@@ -801,6 +837,8 @@ impl Written {
} else {
at.cast::<u64>().write_unaligned(value);
}
#[cfg(windows)]
windows_sys::Win32::System::Threading::WakeByAddressAll(at.cast());
}
}
}
@@ -924,21 +962,21 @@ extern "system" fn present(
crate::capture::dump_targets(frame);
}
}
#[cfg(all(windows, feature = "diagnostics"))]
note_planes(planes, plane_parameters);
#[cfg(windows)]
if behind::on() && !this.is_null() {
const COPY_SOURCE: u32 = 0x800;
let texture = if planes > 0
let base_res = if planes > 0
// SAFETY: the title passes `planes` plane descriptions.
&& let Some(plane) = unsafe { plane_parameters.as_ref() }
&& plane.count > 0
&& !plane.resources.is_null()
{
// SAFETY: the plane lists `count` resources.
let resource = unsafe { *plane.resources };
// The state the lists recorded so far leave it in (the next
// frame's, recorded before this is shown, go on from there).
Some(unsafe { *plane.resources })
} else {
None
};
let take_copy = |resource: This| {
crate::resource::host_copy(resource).map(|copy| {
let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before);
crate::resource::host_transition(resource, state);
@@ -947,14 +985,20 @@ extern "system" fn present(
let state = if crate::list::thin::wanted() { u32::MAX } else { state };
(resource as usize, copy, state)
})
} else {
None
};
let texture = base_res.and_then(take_copy);
let overlay = (planes > 1 && !plane_parameters.is_null())
.then(|| overlay_resource(plane_parameters))
.flatten()
.filter(|&over_res| base_res != Some(over_res))
.and_then(take_copy);
let resource = texture.as_ref().map_or(0, |t| t.0);
// LOCAL (port of fxceless #1189): the interface plane, as the first.
let over = second_plane(planes, plane_parameters, resource as This)
.map(|(copy, state)| (copy, if crate::list::thin::wanted() { u32::MAX } else { state }));
behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource, over });
behind::present(
this,
texture.map(|(_, copy, state)| (copy, state)),
overlay.map(|(_, copy, state)| (copy, state)),
Shown { frame, resource },
);
called.end();
#[cfg(feature = "diagnostics")]
frame_ends();
@@ -974,9 +1018,27 @@ extern "system" fn present(
const COPY_SOURCE: u32 = 0x800;
let state = crate::resource::host_transition(resource, COPY_SOURCE)
.map_or(COPY_SOURCE, |(_, before)| before);
let over = second_plane(planes, plane_parameters, resource);
show(texture, state, Shown { frame, resource: resource as usize, over });
let overlay = (planes > 1)
.then(|| overlay_resource(plane_parameters))
.flatten()
.filter(|&over_res| over_res != resource)
.and_then(|over_res| {
crate::resource::host_resource(over_res).map(|over_tex| {
let over_state = crate::resource::host_transition(over_res, COPY_SOURCE)
.map_or(COPY_SOURCE, |(_, before)| before);
(over_res, over_tex, over_state)
})
});
show_planes(
texture,
state,
overlay.as_ref().map(|(_, tex, st)| (*tex, *st)),
Shown { frame, resource: resource as usize },
);
crate::resource::host_transition(resource, state);
if let Some((over_res, _, over_state)) = overlay {
crate::resource::host_transition(over_res, over_state);
}
let _ = host;
}
#[cfg(not(windows))]
@@ -1001,104 +1063,24 @@ fn frame_ends() {
/// The frame a present shows, and the title's resource it shows.
#[cfg(windows)]
#[derive(Clone)]
#[derive(Clone, Copy)]
struct Shown {
frame: u64,
resource: usize,
/// LOCAL (port of fxceless #1189): the second plane to lay over the
/// shown one, and its host state (`u32::MAX`: the state its lists left
/// it in when they ran).
over: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>,
}
/// LOCAL (port of fxceless #1189): a present's second plane, to be laid over
/// the first (`crate::compose`), with `VICTORY_COMPOSE=1`. Its host copy and
/// the host state the lists recorded so far leave it in (noted as before).
/// A Series S title presents two planes: the game and the interface
/// (menus, loading screens, the intro), 72-byte descriptions each.
/// Shows `texture` (with optional `overlay` plane blended over it) in our window.
#[cfg(windows)]
fn second_plane(planes: u32, plane_parameters: *const Plane, first: This) -> Option<(std::sync::Arc<crate::resource::HostTexture>, u32)> {
const STRIDE: usize = 72;
const COPY_SOURCE: u32 = 0x800;
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let on = *ON.get_or_init(|| {
let on = std::env::var_os("VICTORY_COMPOSE").is_some_and(|v| v == "1");
if on {
tracing::warn!("LOCAL present planes: a second plane is laid over the first (VICTORY_COMPOSE=1)");
}
on
});
if !on || planes < 2 || plane_parameters.is_null() {
return None;
}
// SAFETY: the title passes `planes` descriptions of `STRIDE` bytes.
let plane = unsafe { plane_parameters.cast::<u8>().add(STRIDE).cast::<Plane>().as_ref() }?;
if plane.count == 0 || plane.resources.is_null() {
return None;
}
// SAFETY: the plane lists `count` resources.
let resource = unsafe { *plane.resources };
if resource == first {
return None;
}
let copy = crate::resource::host_copy(resource)?;
let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before);
crate::resource::host_transition(resource, state);
Some((copy, state))
}
/// Diagnostics (LOCAL, from fxceless #1189): the planes a present asks for,
/// at presents 1, 2, 4, ... up to 4096 and whenever their number changes.
#[cfg(all(windows, feature = "diagnostics"))]
fn note_planes(planes: u32, plane_parameters: *const Plane) {
const STRIDE: usize = 72;
static LAST: AtomicU64 = AtomicU64::new(u64::MAX);
let frame = FRAMES.load(Ordering::Relaxed);
let changed = LAST.swap(u64::from(planes), Ordering::Relaxed) != u64::from(planes);
if !changed && !(frame.is_power_of_two() && frame <= 4096) {
return;
}
if plane_parameters.is_null() {
return;
}
for i in 0..planes.min(4) as usize {
// SAFETY: the title passes `planes` descriptions of `STRIDE` bytes.
let Some(plane) = (unsafe { plane_parameters.cast::<u8>().add(i * STRIDE).cast::<Plane>().as_ref() }) else {
continue;
};
if plane.resources.is_null() {
tracing::warn!(frame, planes, plane = i, count = plane.count, "present plane without resources");
continue;
}
for k in 0..plane.count.min(2) as usize {
// SAFETY: the plane lists `count` resources.
let resource = unsafe { *plane.resources.add(k) };
let desc = crate::resource::texture_memory(resource).map(|m| m.1);
tracing::warn!(
frame,
planes,
plane = i,
count = plane.count,
resource = ?resource,
hosted = crate::resource::host_copy(resource).is_some(),
desc = ?desc,
"present plane"
);
}
}
}
/// Shows `texture`, in host state `state`, in our window.
#[cfg(windows)]
fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) {
fn show_planes(
texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource,
state: u32,
overlay: Option<(&windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32)>,
what: Shown,
) {
let Some(host) = crate::host::host() else {
return;
};
let over = what.over.as_ref().map(|(t, s)| {
let s = if *s == u32::MAX { t.state.load(Ordering::Relaxed) } else { *s };
(&t.texture, s)
});
let shown = host.present_over(texture, state, over, what.frame);
let shown = host.present_planes(texture, state, overlay, what.frame);
#[cfg(feature = "diagnostics")]
blinks(what.frame, what.resource as This, state, shown);
#[cfg(not(feature = "diagnostics"))]
+19 -6
View File
@@ -391,8 +391,12 @@ enum Job {
Joined(usize, Vec<crate::list::Detached>, Vec<usize>, Vec<usize>, Vec<(usize, u64)>),
/// A signal of the queue's.
Signal(usize, u64),
/// A frame is shown: the texture and the state its lists leave it in.
Present(Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, super::Shown),
/// A frame is shown: the base texture (and optional overlay plane) and the states their lists leave them in.
Present(
Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>,
Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>,
super::Shown,
),
}
// SAFETY: D3D12 objects are free-threaded; a job is touched by whoever put it
@@ -569,12 +573,16 @@ impl Work for Job {
crate::fence::set(fence as This, value);
}
}
Job::Present(texture, shown) => {
Job::Present(texture, overlay, shown) => {
if let Some((texture, state)) = texture {
// (Where its lists were not translated when the title
// presented: the state they left it in.)
let state = if state == u32::MAX { texture.state.load(Relaxed) } else { state };
super::show(&texture.texture, state, shown);
let over = overlay.as_ref().map(|(ov, ov_state)| {
let st = if *ov_state == u32::MAX { ov.state.load(Relaxed) } else { *ov_state };
(&ov.texture, st)
});
super::show_planes(&texture.texture, state, over, shown);
}
QUEUED.fetch_sub(1, Relaxed);
}
@@ -811,10 +819,15 @@ pub(super) fn wait(this: This, fence: This, value: u64) {
/// A present on queue `this` of `texture`, in the state the lists recorded so
/// far leave it in.
pub(super) fn present(this: This, texture: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>, shown: super::Shown) {
pub(super) fn present(
this: This,
texture: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>,
overlay: Option<(std::sync::Arc<crate::resource::HostTexture>, u32)>,
shown: super::Shown,
) {
QUEUED.fetch_add(1, Relaxed);
STATS[PRESENTS].fetch_add(1, Relaxed);
LANE.push(this as usize, [Job::Present(texture, shown)]);
LANE.push(this as usize, [Job::Present(texture, overlay, shown)]);
let began = Instant::now();
let _waiting = crate::timeline::span("a present waits for the one before it to be sent");
LANE.wait_presents(frames_most());
+201
View File
@@ -0,0 +1,201 @@
//! Host-memory admission for speculative texture work and reusable upload storage.
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
const MIB: u64 = 1 << 20;
const GIB: u64 = 1 << 30;
static PRESSURED: AtomicBool = AtomicBool::new(false);
static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX);
fn memory_status() -> Option<MEMORYSTATUSEX> {
// SAFETY: the API initializes the fields of a correctly sized structure.
let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
status.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
(unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status)
}
// The texture sweep may run for seconds inside a single submitted frame.
static NEXT_COMMIT_SAMPLE: AtomicU64 = AtomicU64::new(0);
static AVAILABLE_COMMIT: AtomicU64 = AtomicU64::new(u64::MAX);
static RETRY_UPLOAD_AT: AtomicU64 = AtomicU64::new(0);
pub(crate) fn allocation_error(error: &windows::core::Error) {
if error.code() == windows::Win32::Foundation::E_OUTOFMEMORY {
RETRY_UPLOAD_AT.fetch_max(crate::host::coarse_ms().saturating_add(500), Ordering::Relaxed);
}
}
thread_local! {
static STAGING_DEFERRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn note_staging_deferred() {
STAGING_DEFERRED.set(true);
}
pub(crate) fn take_staging_deferred() -> bool {
STAGING_DEFERRED.replace(false)
}
pub(crate) fn upload_refused() -> bool {
crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed)
}
fn sample_commit(now: u64) -> u64 {
let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
if now >= next
&& NEXT_COMMIT_SAMPLE
.compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
&& let Some(status) = memory_status()
{
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
}
AVAILABLE_COMMIT.load(Ordering::Relaxed)
}
fn has_upload_reserve(commit: u64, bake: bool) -> bool {
// Keep a protective floor against Rust/game OOM aborts without starving
// bindless world textures or one-shot ped decoration bakes when steady-state
// commit headroom sits in the 1-4 GiB range on 32 GiB hosts.
commit >= if bake { 256 * MIB } else { 512 * MIB }
}
fn has_growth_reserve(commit: u64, bake: bool) -> bool {
// Growing a fresh 64 MiB upload block for speculative bindless prefetch
// requires more headroom than reusing slices already committed inside the
// staging pool.
commit >= if bake { 256 * MIB } else { 1024 * MIB }
}
/// Leave commit for game allocations and submissions already in flight while
/// still letting bindless textures and one-shot material bakes upload.
pub(crate) fn admit_texture_pass(bake: bool) -> bool {
let now = crate::host::coarse_ms();
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
return false;
}
has_upload_reserve(sample_commit(now), bake)
}
/// Whether the staging allocator may commit a brand-new OS upload buffer
/// (reusing existing free ranges in already-committed pool blocks stays open
/// whenever `admit_texture_pass` is true).
pub(crate) fn allow_staging_growth(bake: bool) -> bool {
let now = crate::host::coarse_ms();
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
return false;
}
has_growth_reserve(sample_commit(now), bake)
}
pub(crate) fn limited_host_ram() -> bool {
static LIMITED: OnceLock<bool> = OnceLock::new();
*LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB))
}
fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
if was {
physical < 5 * GIB || commit < 6 * GIB
} else {
physical <= 3 * GIB || commit <= 4 * GIB
}
}
/// Called by the once-per-second submission sweep. A failed sample keeps the last good state.
pub(crate) fn refresh() {
let Some(status) = memory_status() else { return };
let (physical, commit) = (status.ullAvailPhys, status.ullAvailPageFile);
HEADROOM.store(physical.min(commit), Ordering::Relaxed);
let was = pressured();
let pressure = next_pressure(was, physical, commit);
if pressure != was {
PRESSURED.store(pressure, Ordering::Relaxed);
if pressure {
tracing::warn!(
pid = std::process::id(),
frame = crate::frame::current(),
physical_free_mib = physical >> 20,
available_commit_mib = commit >> 20,
buffer_mirror_span_mib = crate::shadow::live_span_bytes() >> 20,
texture_staging_mib = crate::texture::live_staging_bytes() >> 20,
spare_scratch_mib = crate::host::ALIVE[4].load(Ordering::Relaxed) >> 20,
game_filled_gpu_texture_mib = crate::resource::KINDS[1].load(Ordering::Relaxed) >> 20,
"host memory pressure: limiting texture prefetch and idle upload storage"
);
} else {
tracing::info!(physical_free_mib = physical >> 20, available_commit_mib = commit >> 20, "host memory pressure cleared");
}
}
}
pub(crate) fn headroom() -> Option<u64> {
let bytes = HEADROOM.load(Ordering::Relaxed);
(bytes != u64::MAX).then_some(bytes)
}
pub(crate) fn pressured() -> bool {
PRESSURED.load(Ordering::Relaxed)
}
/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation
/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling.
pub(crate) fn critical_commit() -> bool {
let now = crate::host::coarse_ms();
now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB
}
/// A soft per-frame admission limit. A single texture can cross it. The
/// queue retains unserved slots so they can be retried on later frames.
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 {
if critical {
bytes.min(16 << 20)
} else if pressure || (limited && staging >= GIB) {
bytes.min(64 << 20)
} else {
bytes
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bake_and_lookahead_leave_room_for_live_game_allocations() {
for (commit, bake, lookahead, growth) in [
(128 * MIB, false, false, false),
(256 * MIB, true, false, false),
(512 * MIB, true, true, false),
(768 * MIB, true, true, false),
(1024 * MIB, true, true, true),
] {
assert_eq!(has_upload_reserve(commit, true), bake);
assert_eq!(has_upload_reserve(commit, false), lookahead);
assert_eq!(has_growth_reserve(commit, false), growth);
}
}
#[test]
fn either_constraint_enters_pressure_and_both_must_recover() {
assert!(next_pressure(false, 12 * GIB, 4 * GIB));
assert!(next_pressure(false, 3 * GIB, 16 * GIB));
assert!(next_pressure(true, 4 * GIB, 7 * GIB));
assert!(next_pressure(true, 6 * GIB, 5 * GIB));
assert!(!next_pressure(true, 5 * GIB, 6 * GIB));
assert!(!next_pressure(false, 4 * GIB, 5 * GIB));
}
#[test]
fn prefetch_respects_existing_budgets_and_resumes_after_recovery() {
assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20);
assert_eq!(prefetch_limit(0, true, true, false, 0), 0);
assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20);
assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20);
assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20);
assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20);
}
}
+9
View File
@@ -2379,6 +2379,14 @@ pub(crate) fn host_resource<'a>(
Some(unsafe { &*std::ptr::from_ref(&host.texture) })
}
/// Whether `this` is a valid title resource created by this runtime.
#[cfg(windows)]
pub(crate) fn is_resource(this: This) -> bool {
let mut table = [0; size_of::<usize>()];
crate::host::read_into(this.cast(), &mut table)
&& usize::from_ne_bytes(table) == RESOURCE_FUNCTIONS.0.as_ptr() as usize
}
/// A title texture's host copy, shared, for a list to hold.
#[cfg(windows)]
pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
@@ -2525,6 +2533,7 @@ fn host_texture_as(
}
};
if let Err(e) = &made {
crate::residency::allocation_error(&e);
tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
}
if !reserved
+6
View File
@@ -314,6 +314,12 @@ static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
/// bytes; the waits for the card the fetches added and their microseconds.
pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
pub(crate) fn live_span_bytes() -> u64 {
CARD_BYTES[0].load(Ordering::Relaxed)
+ WINDOW_CARD_BYTES.load(Ordering::Relaxed)
+ WINDOW_MAPPED_BYTES.load(Ordering::Relaxed)
}
/// [`CARD_STATS`], taken; then the copies in the card's memory, their
/// bytes and their "before" twins' bytes.
pub(crate) fn card_stats() -> [u64; 10] {
File diff suppressed because it is too large. Load diff
+292
View File
@@ -0,0 +1,292 @@
//! The upscaler's output by a plain stretch of its colour input (from CuteBooty/victory-8gb over.rs),
//! for builds that otherwise run the title's own FidelityFX upscaler, whose translated passes are slow
//! on 32-lane hosts. Taken by `victory_hle::modules::ffx` in Series S.
use std::sync::Mutex;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
/// A bilinear, clamping sampler at `s0` for the stages `visibility` names.
fn bilinear(visibility: D3D12_SHADER_VISIBILITY) -> D3D12_STATIC_SAMPLER_DESC {
D3D12_STATIC_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
MaxLOD: f32::MAX,
ShaderRegister: 0,
RegisterSpace: 0,
ShaderVisibility: visibility,
..Default::default()
}
}
/// A root signature of `parameters` and one bilinear sampler, serialized by
/// the runtime and not taken from a shader: the system compiler under Wine
/// compiles a `[RootSignature]` attribute without writing the signature
/// into the shader, and `CreateRootSignature` then fails on it (#188).
fn root_signature(
device: &ID3D12Device,
parameters: &[D3D12_ROOT_PARAMETER],
sampler: D3D12_SHADER_VISIBILITY,
flags: D3D12_ROOT_SIGNATURE_FLAGS,
) -> windows::core::Result<ID3D12RootSignature> {
use windows::Win32::Graphics::Direct3D::ID3DBlob;
let samplers = [bilinear(sampler)];
let desc = D3D12_ROOT_SIGNATURE_DESC {
NumParameters: parameters.len() as u32,
pParameters: parameters.as_ptr(),
NumStaticSamplers: 1,
pStaticSamplers: samplers.as_ptr(),
Flags: flags,
};
let mut blob: Option<ID3DBlob> = None;
// SAFETY: the description points at live slices; the blob is the
// runtime's own, read while it lives.
unsafe {
D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?;
let blob = blob.ok_or_else(windows::core::Error::empty)?;
let bytes =
std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
device.CreateRootSignature(0, bytes)
}
}
/// One descriptor range of one view at register 0, at `offset` in its table.
fn range(kind: D3D12_DESCRIPTOR_RANGE_TYPE, offset: u32) -> D3D12_DESCRIPTOR_RANGE {
D3D12_DESCRIPTOR_RANGE {
RangeType: kind,
NumDescriptors: 1,
BaseShaderRegister: 0,
RegisterSpace: 0,
OffsetInDescriptorsFromTableStart: offset,
}
}
/// A root parameter that is a table of `ranges`, for the stages `visibility`
/// names.
fn table(ranges: &[D3D12_DESCRIPTOR_RANGE], visibility: D3D12_SHADER_VISIBILITY) -> D3D12_ROOT_PARAMETER {
D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
Anonymous: D3D12_ROOT_PARAMETER_0 {
DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE {
NumDescriptorRanges: ranges.len() as u32,
pDescriptorRanges: ranges.as_ptr(),
},
},
ShaderVisibility: visibility,
}
}
// ---------------------------------------------------------------------------
// The upscaler's output, by a plain stretch
// ---------------------------------------------------------------------------
/// The title in its Series S mode renders below its output size and has the
/// console's upscaler (its `ffxDispatch`) write the output. That upscaler's
/// passes are compute pipelines in a container we do not translate, so the
/// output stayed black. This pass stands in for it: each output texel is the
/// bilinear sample of the rendered part of the colour input.
///
/// shortcut: no temporal accumulation, sharpening or use of the depth and
/// motion inputs: an image, not the upscaler's quality.
const STRETCH: &str = r#"
cbuffer Sizes : register(b0) { float2 scale; float2 texel; };
Texture2D<float4> source : register(t0);
RWTexture2D<float4> target : register(u0);
SamplerState bilinear : register(s0);
[numthreads(8, 8, 1)]
void stretch(uint3 id : SV_DispatchThreadID) {
// Groups are 8 by 8: the last ones reach past a size that is not a
// multiple of 8.
uint width, height;
target.GetDimensions(width, height);
if (id.x >= width || id.y >= height) return;
float2 at = (float2(id.xy) + 0.5) * texel * scale;
// The rendered size can be the top left of a larger texture: stay half a
// texel inside it, or the filter takes in what is beside it.
uint sw, sh;
source.GetDimensions(sw, sh);
at = min(at, scale - 0.5 / float2(sw, sh));
target[id.xy] = source.SampleLevel(bilinear, at, 0);
}
"#;
struct Stretch {
root: ID3D12RootSignature,
pipeline: ID3D12PipelineState,
views: ID3D12DescriptorHeap,
step: u32,
next: u32,
}
// SAFETY: D3D12 objects are free-threaded.
unsafe impl Send for Stretch {}
static STRETCHER: Mutex<Option<Stretch>> = Mutex::new(None);
/// Views of a stretch are kept this many stretches (two views each).
///
/// shortcut: a fixed count. The title dispatches the upscaler once a frame
/// and a list runs within the frames the title keeps in flight; 64 frames
/// is far more than it keeps.
const STRETCH_RING: u32 = 64;
fn make_stretch(device: &ID3D12Device) -> windows::core::Result<Stretch> {
use windows::core::s;
let cs = crate::host::compile(STRETCH, s!("stretch"), s!("cs_5_1"))?;
let views = [
range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0),
range(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1),
];
let sizes = D3D12_ROOT_PARAMETER {
ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
Anonymous: D3D12_ROOT_PARAMETER_0 {
Constants: D3D12_ROOT_CONSTANTS {
ShaderRegister: 0,
RegisterSpace: 0,
Num32BitValues: 4,
},
},
ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL,
};
let root = root_signature(
device,
&[sizes, table(&views, D3D12_SHADER_VISIBILITY_ALL)],
D3D12_SHADER_VISIBILITY_ALL,
D3D12_ROOT_SIGNATURE_FLAG_NONE,
)?;
// SAFETY: the description points at live data and never releases its
// pointer.
unsafe {
let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: cs.as_ptr().cast(),
BytecodeLength: cs.len(),
},
..Default::default()
};
let pipeline: ID3D12PipelineState = device.CreateComputePipelineState(&desc)?;
let views: ID3D12DescriptorHeap =
device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: STRETCH_RING * 2,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})?;
Ok(Stretch {
root,
pipeline,
step: device
.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV),
views,
next: 0,
})
}
}
/// A typeless colour format as the typed one shaders read and write.
fn typed(format: DXGI_FORMAT) -> DXGI_FORMAT {
DXGI_FORMAT(match format.0 {
1 => 2,
9 => 10,
23 => 24,
27 => 28,
f => f,
})
}
/// Records into `list` the stretch of the top-left `render` texels of
/// `source` (readable by compute shaders) over the whole of `target` (in
/// the unordered-access state). False if nothing was recorded.
///
/// The pass sets the list's descriptor heap, compute root signature and
/// pipeline and puts none of them back: the caller replays the title's.
pub(crate) fn record_stretch(
device: &ID3D12Device,
list: &ID3D12GraphicsCommandList,
target: &ID3D12Resource,
source: &ID3D12Resource,
render: [u32; 2],
) -> bool {
// SAFETY: live resources.
let (to, from) = unsafe { (target.GetDesc(), source.GetDesc()) };
if to.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0
|| to.Width == 0
|| from.Width == 0
{
return false;
}
let mut made = STRETCHER.lock().unwrap_or_else(|e| e.into_inner());
if made.is_none() {
// Tried again at the next dispatch if it fails, as the pass over a
// present is: a failure need not last.
*made = match make_stretch(device) {
Ok(p) => {
tracing::info!("the upscaler's output is made by a plain stretch of its colour input");
Some(p)
}
Err(e) => {
static TOLD: std::sync::Once = std::sync::Once::new();
TOLD.call_once(|| {
tracing::warn!(error = %e, "no pass to stretch the upscaler's input: its output stays as it is");
});
None
}
};
}
let Some(p) = made.as_mut() else { return false };
let slot = (p.next % STRETCH_RING) * 2;
p.next = p.next.wrapping_add(1);
let (width, height) = (to.Width as u32, to.Height);
let rendered = [
if render[0] == 0 { from.Width as u32 } else { render[0].min(from.Width as u32) },
if render[1] == 0 { from.Height } else { render[1].min(from.Height) },
];
let sizes = [
rendered[0] as f32 / from.Width as f32,
rendered[1] as f32 / from.Height as f32,
1.0 / width as f32,
1.0 / height as f32,
];
let read = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: typed(from.Format),
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV {
MostDetailedMip: 0,
MipLevels: 1,
..Default::default()
},
},
};
let written = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: typed(to.Format),
ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
..Default::default()
};
// SAFETY: an open list; slots of our heap; live resources and objects
// (the pass's own live as long as the process).
unsafe {
let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: p.views.GetCPUDescriptorHandleForHeapStart().ptr + ((slot + i) * p.step) as usize,
};
let gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
ptr: p.views.GetGPUDescriptorHandleForHeapStart().ptr + u64::from(slot * p.step),
};
device.CreateShaderResourceView(source, Some(&read), cpu(0));
device.CreateUnorderedAccessView(target, None, Some(&written), cpu(1));
list.SetDescriptorHeaps(&[Some(p.views.clone())]);
list.SetComputeRootSignature(&p.root);
list.SetPipelineState(&p.pipeline);
list.SetComputeRoot32BitConstants(0, 4, sizes.as_ptr().cast(), 0);
list.SetComputeRootDescriptorTable(1, gpu);
list.Dispatch(width.div_ceil(8), height.div_ceil(8), 1);
}
true
}
+175 -79
View File
@@ -95,6 +95,11 @@ pub(crate) struct Staging {
/// recorded again about a second later if the card has room by then
/// ([`upload`]).
waiting: std::sync::atomic::AtomicU64,
/// Recorded for a one-shot decoration bake (`BAKING`): submission-time
/// refresh must wait for title memory to stop remapping
/// (`title_memory_reading`) instead of taking `no_wait()` /
/// `refresh_unlocked()` or the 30-frame partial-read throttle.
exact: std::sync::atomic::AtomicBool,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
@@ -485,6 +490,10 @@ fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) ->
/// bytes.
static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
pub(crate) fn live_staging_bytes() -> u64 {
STAGED[1].load(std::sync::atomic::Ordering::Relaxed)
}
impl Drop for Staging {
fn drop(&mut self) {
use std::sync::atomic::Ordering::Relaxed;
@@ -533,7 +542,7 @@ pub(crate) fn let_go_idle() {
if map.is_empty() {
return;
}
let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram());
let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom());
// A list that recorded an upload or a check holds the staging until it
// is reset: one only the table holds is named by no list, recorded or
// running.
@@ -770,6 +779,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
return;
};
use std::sync::atomic::Ordering::Relaxed;
let baking = BAKING.get();
if baking {
staging.exact.store(true, Relaxed);
}
let picking = PICKING.get();
if picking.is_none() {
// A draw samples it through a table: kept and checked from here on.
@@ -802,10 +815,31 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
}
}
}
// The video decoder cycles CPU-written linear plane buffers. Keep a
// dedicated per-list upload buffer through the list's GPU fence so
// concurrent frames never overwrite each other or stall on staging hashes.
if staging.movie_plane() {
let (at, len) = staging.memory();
let footprint = staging.footprints[0].Footprint;
let pitch = footprint.RowPitch as usize;
let bytes = pitch * staging.rows[0] as usize;
let plane = staging.clone();
let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| {
fill_plane(&plane.layout, at, len, dst, bytes, pitch);
}) else {
once!("no upload buffer for a CPU-written movie plane");
return;
};
record_upload(list, resource, texture, &staging, &source, 0);
staging.uploaded.store(true, Relaxed);
return;
}
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
// frame was recorded before that check).
// frame was recorded before that check). During a one-shot bake we
// always record the copy so any change found at submission lands in
// VRAM before the bake draw executes.
// LOCAL: not for a video's picture planes (`guard_view` false). Their
// check at submission finds the frame the decoder wrote since, but the
// copy came only with the next list that samples the plane: three
@@ -814,7 +848,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
// ghosts and pictures from earlier (r_avm23, the user's recording).
// With the copy recorded here, it takes what that check puts in the
// staging buffer at this list's submission.
if staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
if !baking && staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
list.defer_texture(staging);
@@ -829,77 +863,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
};
staging.expected.store(there, Relaxed);
}
const COPY_DEST: u32 = 0x400;
// A texture cut from a block may lie where another did: what the card
// holds of that one is done with before the first upload into this one.
if crate::pool::on() && !staging.uploaded.load(Relaxed) {
let aliasing = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: std::mem::ManuallyDrop::new(None),
// SAFETY: a borrowed pointer the barrier never releases.
pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
}),
},
};
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[aliasing]) };
}
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging buffer lives as long as `staging`, which the deferred
// refresh below holds until the list is reset.
for (i, footprint) in staging.footprints.iter().enumerate() {
#[cfg(feature = "diagnostics")]
{
let f = footprint.Footprint;
// SAFETY: live resources.
let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) };
let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
list.note_read(
|| {
format!(
"texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
d.Width,
d.Height,
d.DepthOrArraySize,
d.Format.0,
d.MipLevels,
staging.footprints.len(),
staging.size,
staging.base + footprint.Offset,
f.Width,
f.Height,
f.Depth,
f.RowPitch
)
},
(gpu + staging.base + footprint.Offset, len),
);
}
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: staging.first - staging.level0 + i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: staging.base + footprint.Offset,
..*footprint
},
},
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
record_upload(list, resource, texture, &staging, &staging.buffer, staging.base);
// When the list is submitted, its copy takes what the staging buffer
// holds by then: noted before the check below, which sets `dirty`
// again if it detiles (the next list then uploads once more).
@@ -943,6 +907,115 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
});
}
fn record_upload(
list: &HostList,
resource: This,
texture: &ID3D12Resource,
staging: &Staging,
source: &ID3D12Resource,
base: u64,
) {
use std::sync::atomic::Ordering::Relaxed;
const COPY_DEST: u32 = 0x400;
// A texture cut from a block may lie where another did: what the card
// holds of that one is done with before the first upload into this one.
if crate::pool::on() && !staging.uploaded.load(Relaxed) {
let aliasing = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: std::mem::ManuallyDrop::new(None),
// SAFETY: a borrowed pointer the barrier never releases.
pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
}),
},
};
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[aliasing]) };
}
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging/plane upload buffer lives until the list is reset.
for (i, footprint) in staging.footprints.iter().enumerate() {
#[cfg(feature = "diagnostics")]
{
let f = footprint.Footprint;
// SAFETY: live resources.
let (gpu, d) = unsafe { (source.GetGPUVirtualAddress(), texture.GetDesc()) };
let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
list.note_read(
|| {
format!(
"texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
d.Width,
d.Height,
d.DepthOrArraySize,
d.Format.0,
d.MipLevels,
staging.footprints.len(),
staging.size,
base + footprint.Offset,
f.Width,
f.Height,
f.Depth,
f.RowPitch
)
},
(gpu + base + footprint.Offset, len),
);
}
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: staging.first - staging.level0 + i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(source) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: base + footprint.Offset,
..*footprint
},
},
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
}
fn fill_plane(
layout: &victory_formats::texture::Layout,
at: usize,
len: usize,
dst: usize,
bytes: usize,
pitch: usize,
) {
let _pin = crate::watch::title_memory_reading();
// SAFETY: the list owns this full upload allocation until its GPU work completes.
let out = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, bytes) };
let mip = &layout.mips[0];
if mip.offset == 0
&& mip.pitch as usize * layout.desc.element_bytes as usize == pitch
&& bytes <= len
&& crate::host::read_into(at as *const _, out)
{
return;
}
with_read(len, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), at as *const u8, len, false);
if let Err(error) = layout.detile(read, 0, 0, out, pitch, bytes) {
out.fill(0);
once!("could not copy the linear plane into the list's upload buffer: {error:?}");
}
});
}
/// Levels on demand: the levels a list claimed for its zeros
/// (`crate::tiles::Tiled::claim`), held by the list's submission-time
/// step. A list that is reset without having been submitted gives the
@@ -1191,6 +1264,20 @@ impl Staging {
preparing[3].fetch_add(read as u64, Relaxed);
}
fn movie_plane(&self) -> bool {
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM;
let desc = &self.layout.desc;
!self.on_demand
&& desc.dimension == victory_formats::texture::Dimension::Tex2d
&& desc.swizzle.0 == 0
&& desc.depth == 1
&& desc.mips == 1
&& desc.samples == 1
&& self.footprints.len() == 1
&& self.footprints[0].Offset == 0
&& self.footprints[0].Footprint.Format == DXGI_FORMAT_R8_UNORM
}
/// Returns the bytes of title memory read.
fn refresh_now(&self) -> usize {
let whole = std::time::Instant::now();
@@ -1204,12 +1291,13 @@ impl Staging {
let start = self.memory as usize;
let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
let last = &mut *last;
let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed);
let alone = self.once.load(std::sync::atomic::Ordering::Relaxed);
if alone && last.hash.is_some() {
if alone && !exact && last.hash.is_some() {
return 0;
}
if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
return 0;
}
last.asked = now;
@@ -1254,7 +1342,7 @@ impl Staging {
last.hot_until = frame + HOT_FRAMES;
}
let hot = hot_textures() && frame < last.hot_until;
if unwritten && !turn && !hot {
if !exact && unwritten && !turn && !hot {
return 0;
}
blind = unwritten;
@@ -1273,7 +1361,7 @@ impl Staging {
// stays mapped (see `crate::watch::title_memory_reading`; without
// it a page went between the asking and the read in runs 71 and
// 74).
let _mapped = if no_wait() {
let _mapped = if no_wait() && !exact {
// Not waited for: while the runtime remaps title memory the
// texture is read through the kernel instead, whole or not at
// all (`no_wait`).
@@ -1293,7 +1381,7 @@ impl Staging {
// unmapped pages is slow, and nothing tells us when pages
// arrive): a mip that streams in shows up to 30 frames late.
let frame = crate::frame::current();
if last.partial.is_some_and(|at| frame < at + 30) {
if !exact && last.partial.is_some_and(|at| frame < at + 30) {
return 0;
}
last.partial = Some(frame);
@@ -1857,6 +1945,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
None => {
let speculative = PICKING.get().is_some() && !BAKING.get();
if crate::residency::upload_refused()
|| (speculative && !crate::residency::allow_staging_growth(false))
{
crate::residency::note_staging_deferred();
return None;
}
let (buffer, data) = host.upload_buffer(total)?;
crate::host::name(&buffer, || {
format!(
@@ -1899,6 +1994,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
detiled: std::sync::atomic::AtomicU32::new(0),
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
waiting: std::sync::atomic::AtomicU64::new(0),
exact: std::sync::atomic::AtomicBool::new(BAKING.get()),
});
map.insert(resource as usize, s.clone());
Some(s)
+64 -8
View File
@@ -13,7 +13,7 @@
//! it as any texture.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*;
@@ -80,6 +80,7 @@ pub(crate) enum Taken {
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
/// Those on their way, by host copy ([`HostTexture::serial`]).
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
static LANDED: Condvar = Condvar::new();
static BYTES: AtomicU64 = AtomicU64::new(0);
/// Since the start: uploads, bytes, microseconds from the asking until the
@@ -103,7 +104,9 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
}
if BYTES.load(Relaxed) >= MOST
let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST };
if !crate::residency::allow_staging_growth(false)
|| BYTES.load(Relaxed) >= most
|| copy.flags() & 0x7 != 0
|| copy.state.load(Relaxed) != 0
|| copy.grown.load(Relaxed)
@@ -132,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
}
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
BYTES.fetch_add(job.staging.read as u64, Relaxed);
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone()));
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.push((job.copy.serial, job.clone()));
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
}
Some(Taken::New(job))
}
@@ -142,6 +149,25 @@ pub(crate) fn send(job: &Arc<Job>) {
QUEUE.1.notify_one();
}
/// Waits until every upload currently on its way here has finished copying
/// and run its completion callbacks (queuing slot flips into `FLIPS`).
/// Returns how many jobs were waited for.
pub(crate) fn drain() -> usize {
if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return 0;
}
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
let waiting = way.len();
let started = std::time::Instant::now();
while !way.is_empty() && started.elapsed().as_millis() < 2000 {
way = LANDED
.wait_timeout(way, std::time::Duration::from_millis(50))
.unwrap_or_else(|e| e.into_inner())
.0;
}
waiting
}
/// A list is about to record an upload into `copy`: one on its way here runs
/// first, and no other is taken after it.
pub(crate) fn listed(copy: &HostTexture) {
@@ -291,11 +317,6 @@ fn finish(jobs: Vec<Arc<Job>>) {
job.copy.ahead.store(DONE, Relaxed);
BYTES.fetch_sub(job.staging.read as u64, Relaxed);
}
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
LANDED.notify_all();
}
for job in &jobs {
let us = job.asked.elapsed().as_micros() as u64;
let n = STATS[0].fetch_add(1, Relaxed) + 1;
@@ -317,6 +338,14 @@ fn finish(jobs: Vec<Arc<Job>>) {
f();
}
}
// Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued
// their `FLIPS` entries so `drain()` observes every flip ready to apply.
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
LANDED.notify_all();
}
crate::descriptor::host::flip_now();
}
@@ -414,4 +443,31 @@ mod tests {
back.Unmap(0, None);
}
}
#[test]
fn drain_waits_until_then_callbacks_have_run() {
use std::sync::atomic::AtomicBool;
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
let Some(_host) = crate::host::host() else { return };
let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
// SAFETY: memory of our own that stays for the test.
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
// SAFETY: as above.
unsafe { std::ptr::write_bytes(at, 0x5a, whole) };
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
crate::resource::want_level(texture, 0);
let copy = crate::resource::host_copy(texture).unwrap();
if !crate::pool::fresh(&copy.texture) {
return;
}
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
let ran = Arc::new(AtomicBool::new(false));
let flag = ran.clone();
job.then(move || flag.store(true, std::sync::atomic::Ordering::Release));
send(&job);
assert!(drain() >= 1);
assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns");
assert_eq!(drain(), 0);
}
}
+21 -3
View File
@@ -517,7 +517,16 @@ fn pump(context: Context, voice: &mut Voice) {
return;
}
while context.field(1, 31, 1) == 1 {
if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) {
// A skipped frame or an input boundary can advance the decoder without
// producing samples. Publish only complete blocks, except the final
// padded tail. Limit empty steps so a broken looping voice cannot hold
// its lock or stall other voices for the whole decoding pass.
for _ in 0..8 {
if voice.pcm.len() >= SAMPLES_PER_BLOCK || !decode(context, voice) {
break;
}
}
if voice.pcm.is_empty() || (voice.pcm.len() < SAMPLES_PER_BLOCK && !voice.ended) {
return;
}
// The write block is the title's too: taken modulo the ring before
@@ -549,12 +558,21 @@ fn pump(context: Context, voice: &mut Voice) {
/// Decodes the next frame of the current input into `voice.pcm`; false
/// when there is nothing left to decode.
fn decode(context: Context, voice: &mut Voice) -> bool {
let valid = context.field(0, 20, 2);
if voice.ended {
return false;
// The title can refill either input while the context stays enabled.
// Flush the previous tail once and leave the ring idle until a valid
// buffer is published. The decoder resets its overlap when flushed.
if valid == 0 {
return false;
}
voice.ended = false;
if context.field(2, 26, 5) == INPUT_INVALID {
context.set_field(2, 26, 6, 0);
}
}
let channels = context.channels();
let mut current = context.field(4, 31, 1);
let valid = context.field(0, 20, 2);
if valid & (1 << current) == 0 {
if valid & (1 << (1 - current)) == 0 {
// Out of input: the overlap tail, then nothing.
+12 -3
View File
@@ -227,11 +227,20 @@ extern "system" fn create_queue(
)
}
/// The title asks for 32 MiB and stops if this fails.
/// The title asks for 32 MiB and stops if this fails. Give PC worker threads
/// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't
/// starve the remaining cores.
extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT {
tracing::info!(size, "dstorage: staging buffer size");
static FLOOR_MB: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let floor = *FLOOR_MB.get_or_init(|| {
std::env::var("VICTORY_DSTORAGE_STAGING_MB")
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
.unwrap_or(256)
}) << 20;
tracing::info!(size, floor, "dstorage: staging buffer size");
if let Some(scheduler) = scheduler() {
scheduler.lock().staging = u64::from(size);
scheduler.lock().staging = u64::from(size).max(floor);
}
S_OK
}
+250
View File
@@ -0,0 +1,250 @@
//! `amd_fidelityfx_loader_xbox.dll`: the upscale dispatch.
//!
//! The title's Series S mode renders below its output size and calls the
//! console's FidelityFX upscaler to make the output. The loader and the
//! upscaler are the title's own DLLs and run as they are, but the
//! upscaler's passes are compute pipelines in a container we do not
//! translate: its output stayed black. `ffxDispatch` alone is taken here:
//! an upscale dispatch becomes a plain stretch of the colour input
//! (`victory_gpu::list::upscale_stretch`); anything else, and an upscale we
//! could not stretch, goes to the title's DLL.
//!
//! The structures are the public FidelityFX API's (`ffx_api.h`,
//! `ffx_upscale.h`): a header of a type and a next pointer, and resources of
//! a pointer, a 32-byte description and a state.
use std::ffi::c_void;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
/// The DLL whose `ffxDispatch` is taken.
pub const LOADER: &str = "amd_fidelityfx_loader_xbox.dll";
static REAL: AtomicUsize = AtomicUsize::new(0);
/// The title's own `ffxDispatch`, for what is not stretched here.
pub fn set_real_dispatch(address: usize) {
REAL.store(address, Ordering::Relaxed);
}
#[repr(C)]
struct Header {
kind: u64,
next: *const Header,
}
#[repr(C)]
struct Resource {
resource: *const c_void,
description: [u32; 8],
state: u32,
}
#[repr(C)]
struct Upscale {
header: Header,
list: *const c_void,
colour: Resource,
depth: Resource,
motion: Resource,
exposure: Resource,
reactive: Resource,
composition: Resource,
output: Resource,
jitter: [f32; 2],
motion_scale: [f32; 2],
render: [u32; 2],
upscale: [u32; 2],
// The rest of `ffxDispatchDescUpscale` (`ffx_upscale.h`), read by the
// probe only.
enable_sharpening: u8,
sharpness: f32,
frame_time_delta: f32,
pre_exposure: f32,
reset: u8,
camera_near: f32,
camera_far: f32,
camera_fov: f32,
view_to_meters: f32,
flags: u32,
}
/// `VICTORY_UPSCALE_PROBE=1`: logs what the title gives each upscale (the
/// inputs a temporal upscaler such as DLSS or FSR 2 needs), now and then.
fn probe() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_UPSCALE_PROBE").is_some_and(|v| v == "1"))
}
const _: () = assert!(size_of::<Resource>() == 48);
const _: () = assert!(std::mem::offset_of!(Upscale, output) == 0x138);
/// `FFX_API_RETURN_ERROR`: what a dispatch nothing could answer returns.
const ERROR: u32 = 1;
/// `FFX_API_DISPATCH_DESC_TYPE_UPSCALE`.
const UPSCALE: u64 = 0x0001_0001;
type Dispatch = extern "system" fn(*mut *mut c_void, *const Header) -> u32;
extern "system" fn dispatch(context: *mut *mut c_void, desc: *const Header) -> u32 {
// SAFETY: the title passes a dispatch description, whose header says
// what follows it.
if let Some(header) = unsafe { desc.as_ref() } {
static SEEN: AtomicU32 = AtomicU32::new(0);
let first = SEEN.fetch_add(1, Ordering::Relaxed) < 4;
if header.kind == UPSCALE {
// SAFETY: an upscale description, by its type.
let d = unsafe { &*desc.cast::<Upscale>() };
if first {
tracing::info!(
list = ?d.list,
colour = ?d.colour.resource,
colour_size = ?(d.colour.description[2], d.colour.description[3]),
output = ?d.output.resource,
output_size = ?(d.output.description[2], d.output.description[3]),
render = ?d.render,
upscale = ?d.upscale,
"upscale dispatch"
);
}
#[cfg(windows)]
if probe() {
static N: AtomicU32 = AtomicU32::new(0);
let n = N.fetch_add(1, Ordering::Relaxed);
// the first 12 upscales, then one in 300
if n < 12 || n.is_multiple_of(300) {
let inputs = victory_gpu::list::upscale_inputs(&[
d.colour.resource,
d.depth.resource,
d.motion.resource,
d.exposure.resource,
d.reactive.resource,
d.composition.resource,
d.output.resource,
]);
tracing::info!(
n,
colour = %inputs[0],
depth = %inputs[1],
motion = %inputs[2],
exposure = %inputs[3],
reactive = %inputs[4],
composition = %inputs[5],
output = %inputs[6],
jitter = ?d.jitter,
motion_scale = ?d.motion_scale,
render = ?d.render,
upscale = ?d.upscale,
sharpening = d.enable_sharpening,
sharpness = d.sharpness,
frame_time_delta = d.frame_time_delta,
pre_exposure = d.pre_exposure,
reset = d.reset,
near = d.camera_near,
far = d.camera_far,
fov = d.camera_fov,
meters = d.view_to_meters,
flags = format_args!("{:#x}", d.flags),
"upscale probe"
);
}
}
#[cfg(windows)]
{
let up = victory_gpu::list::Upscale {
colour: d.colour.resource as u64,
depth: d.depth.resource as u64,
motion: d.motion.resource as u64,
exposure: d.exposure.resource as u64,
output: d.output.resource as u64,
render: d.render,
jitter: d.jitter,
motion_scale: d.motion_scale,
reset: d.reset != 0,
pre_exposure: d.pre_exposure,
near: d.camera_near,
far: d.camera_far,
frame_ms: d.frame_time_delta,
dlss: std::env::var_os("VICTORY_UPSCALE").is_some_and(|v| v == "dlss"),
};
if victory_gpu::list::upscale(d.list, &up) {
return 0;
}
}
if first {
tracing::warn!("upscale dispatch not stretched: left to the title's upscaler");
}
} else if first {
tracing::info!(
kind = format_args!("{:#x}", header.kind),
"another FidelityFX dispatch"
);
}
}
match REAL.load(Ordering::Relaxed) {
// Neither stretched nor passed on: the output was not written, and
// the title is told so instead of presenting it as it is.
0 => {
static TOLD: std::sync::Once = std::sync::Once::new();
TOLD.call_once(|| {
tracing::error!(
"a FidelityFX dispatch was not answered: no stretch was recorded and the title's own ffxDispatch was not found"
);
});
ERROR
}
// SAFETY: the title's own `ffxDispatch`, with its own arguments.
real => unsafe { std::mem::transmute::<usize, Dispatch>(real)(context, desc) },
}
}
/// What the title's import of `ffxDispatch` is bound to. The DLL is not an
/// HLE module: the title's own must load, for its other entry points and
/// for the dispatches passed on.
pub fn dispatch_address() -> usize {
dispatch as *const () as usize
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem::offset_of;
/// The upscale description as the public API lays it out: what the
/// stretch reads sits where the title wrote it.
#[test]
fn the_upscale_description_is_laid_out_as_the_public_api() {
assert_eq!(size_of::<Header>(), 16);
assert_eq!(offset_of!(Upscale, list), 0x10);
assert_eq!(offset_of!(Upscale, colour), 0x18);
assert_eq!(offset_of!(Upscale, depth), 0x48);
assert_eq!(offset_of!(Upscale, motion), 0x78);
assert_eq!(offset_of!(Upscale, output), 0x138);
assert_eq!(offset_of!(Upscale, jitter), 0x168);
assert_eq!(offset_of!(Upscale, motion_scale), 0x170);
assert_eq!(offset_of!(Upscale, render), 0x178);
assert_eq!(offset_of!(Upscale, upscale), 0x180);
assert_eq!(offset_of!(Upscale, enable_sharpening), 0x188);
assert_eq!(offset_of!(Upscale, sharpness), 0x18c);
assert_eq!(offset_of!(Upscale, reset), 0x198);
assert_eq!(offset_of!(Upscale, camera_near), 0x19c);
assert_eq!(offset_of!(Upscale, flags), 0x1ac);
assert_eq!(offset_of!(Resource, description), 8);
assert_eq!(offset_of!(Resource, state), 40);
}
/// A dispatch that is not an upscale, with no DLL of the title's to
/// pass it to, is an error and not a silent success.
#[test]
fn a_dispatch_nothing_answers_is_an_error() {
let before = REAL.swap(0, Ordering::Relaxed);
let other = Header {
kind: 0x0002_0001,
next: std::ptr::null(),
};
assert_eq!(dispatch(std::ptr::null_mut(), &other), ERROR);
assert_eq!(dispatch(std::ptr::null_mut(), std::ptr::null()), ERROR);
REAL.store(before, Ordering::Relaxed);
}
}
+4 -5
View File
@@ -1259,7 +1259,6 @@ mod host {
// pad's buttons, by the stand-in pad's table: with a real pad
// connected the stand-in is not there, and a title that listens
// to the pad (the title's start screen) saw nothing.
#[cfg(feature = "diagnostics")]
if slot == 0 {
for vk in scripted() {
if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) {
@@ -1271,10 +1270,11 @@ mod host {
}
fn keys(&mut self) -> Vec<KeyState> {
#[cfg(feature = "diagnostics")]
let mut down = scripted();
#[cfg(not(feature = "diagnostics"))]
let mut down = Vec::new();
// LOCAL (11/26): the F1 settings menu takes the keyboard while shown.
if victory_gpu::SETTINGS_MENU_OPEN.load(std::sync::atomic::Ordering::Relaxed) {
return Vec::new();
}
if focused_window().is_some() {
// Left/right modifier keys only, as devices report them; no
// mouse buttons (below 0x08).
@@ -1348,7 +1348,6 @@ mod host {
/// time), with or without focus. A key is a
/// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`,
/// `Left`, `Right` (the stand-in pad's table maps them to buttons).
#[cfg(feature = "diagnostics")]
fn scripted() -> Vec<u8> {
static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| {
let list = std::env::var("VICTORY_KEYS").unwrap_or_default();
+1
View File
@@ -17,6 +17,7 @@ pub mod dsp;
#[cfg(windows)]
pub mod dstorage;
#[cfg(windows)]
pub mod ffx;
pub mod files;
pub mod gameinput;
pub mod kernel;
+35 -4
View File
@@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() {
let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect();
root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true)));
root_views.sort_unstable();
let view_strides: Vec<u32> = views
.iter()
.map(|v| match *v {
View::RawUav(_) => 1,
View::HalfUav(_) => 8,
View::Buffer { stride, .. } => match stride {
Stride::Raw => 1,
Stride::Typed => 16,
Stride::Structured(s) => s,
Stride::Format(f, bytes) => {
let kind = match f.0 as u32 {
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => {
super::VIEW_INTEGER
}
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => {
super::VIEW_INTEGER | super::VIEW_SIGNED
}
_ => 0,
};
bytes | kind
}
},
_ => 0,
})
.collect();
for (n, (slot, srv)) in root_views.into_iter().enumerate() {
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
let data = if srv {
root_srv.clone()
let data = if srv
&& (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES)
{
view_strides.clone()
} else {
root_cbv.clone()
assert_eq!(slot, 4 + u8::from(srv), "{name}: root view");
if srv {
root_srv.clone()
} else {
root_cbv.clone()
}
};
roots.push((1 + n as u32, Root::View { srv, data }));
}
+46
View File
@@ -1006,6 +1006,12 @@ pub enum View<'a> {
UintTextureUav(u32, u32),
/// A typed RGBA16F buffer UAV of this many elements, zeroed.
HalfUav(u32),
/// A typed buffer UAV pre-filled with `data` (`format`, bytes per element).
TypedUav {
data: &'a [u32],
format: DXGI_FORMAT,
elem_bytes: u32,
},
/// The same buffer viewed as R16G16B16A16_UINT: what a translated
/// program that moves halves is shown ([`super::HostShader::half_views`]).
HalfUintUav(u32),
@@ -1290,6 +1296,46 @@ impl Host {
)?;
uavs.push((b, None, n, rb));
}
View::TypedUav {
data,
format,
elem_bytes,
} => {
let n = data.len() as u32;
let bytes = u64::from(n) * 4;
let elements = (bytes / u64::from(elem_bytes)) as u32;
let b = make(
D3D12_HEAP_TYPE_DEFAULT,
&buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
let up = upload(data)?;
list.CopyBufferRegion(&b, 0, &up, 0, bytes);
list.ResourceBarrier(&[transition(
&b,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
)]);
keep.push(up);
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: format,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV {
NumElements: elements,
Flags: D3D12_BUFFER_UAV_FLAG_NONE,
..Default::default()
},
},
};
dev.CreateUnorderedAccessView(&b, None, Some(&desc), at);
let rb = make(
D3D12_HEAP_TYPE_READBACK,
&buffer(bytes, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
uavs.push((b, None, n, rb));
}
View::TextureUav(w, h) => {
let t = make(
D3D12_HEAP_TYPE_DEFAULT,
+2 -21
View File
@@ -59,14 +59,6 @@ struct Ray {
inverse: [V; 3],
}
/// LOCAL (from our wt5): `VICTORY_BVH_MISS=1` (off by default): the node test
/// misses every node. While the structure builder is off the structures are
/// never built, and a walk of what lies in their memory is not the console's.
fn bvh_miss() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_MISS").is_some_and(|v| v == "1"))
}
impl<'a> Lower<'a> {
/// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
@@ -199,22 +191,11 @@ impl<'a> Lower<'a> {
.m
.terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
self.cur = box_block;
// LOCAL (from our wt5): with `VICTORY_BVH_MISS=1` every node is missed
// without being read: a box returns no child and a triangle the
// triangle miss, so a walk ends at its first node.
let boxes = if bvh_miss() {
[self.s.m.i32(bvh::NONE); 4]
} else {
self.bvh_boxes(at, kind, &ray, sort)
};
let boxes = self.bvh_boxes(at, kind, &ray, sort);
let box_end = self.cur;
self.s.m.terminate(box_end, Term::Br(join));
self.cur = triangle_block;
let triangle = if bvh_miss() {
bvh::MISS.map(|f| self.s.m.i32(f.to_bits()))
} else {
self.bvh_triangle(at, kind, &ray)
};
let triangle = self.bvh_triangle(at, kind, &ray);
let triangle_end = self.cur;
self.s.m.terminate(triangle_end, Term::Br(join));
self.cur = join;
+66 -24
View File
@@ -441,6 +441,7 @@ enum MaskData {
/// What a value holding a lane mask read as a number stops with.
pub(super) const LANE_MASK: Why = "a lane mask read as data";
pub(super) const DIVERGENT_MASK_EXCHANGE: Why = "a lane mask exchanged where not every lane runs";
/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
/// run that block are not all of the wave.
pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
@@ -564,7 +565,7 @@ fn need(block: usize) {
/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`.
/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes
/// run (no lane branch can have split the arriving lanes); loop-carried values never do.
fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
fn lane_uniform(p: &Program, st: &Structured, all: &[bool], ordered_lds: bool) -> HashSet<Value> {
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
let mut same: HashSet<Value> = HashSet::new();
for b in crate::ir::reverse_postorder(&p.blocks) {
@@ -577,6 +578,9 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
}
for (i, inst) in block.insts.iter().enumerate() {
let name = inst.name();
if st.guards[b][i].is_some() {
continue; // lanes outside EXEC keep another value
}
let ops: Vec<Operand> = match &inst.fields {
Fields::Valu(v)
if v.dpp.is_none()
@@ -587,11 +591,18 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet<Value> {
{
v.src.clone()
}
Fields::Ds {
addr: Some(Operand::Vector { reg, dwords: 1 }),
gds: false,
..
} if ordered_lds && name == "ds_read_b32" => {
if inst.read(Reg::V(*reg)).is_some_and(|a| same.contains(&a)) {
same.extend(inst.writes.iter().map(|w| w.1));
}
continue;
}
_ => continue,
};
if st.guards[b][i].is_some() {
continue; // lanes outside EXEC keep another value
}
let alike = ops.iter().all(|op| match *op {
Operand::Vector { reg, .. } => {
// every dword of the operand the instruction reads from that register on
@@ -1193,6 +1204,13 @@ thread_local! {
}
pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
// A scalar select uses the condition of the whole guest wave, even
// when the preceding mask operation has no scalar-dword consumers.
if matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
&& i.read(Reg::Scc).is_some_and(|s| st.scc_some.contains_key(&s))
{
return true;
}
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
let ops: Vec<&Operand> = match &i.fields {
// A mask operation (its result a mask) is no data use.
@@ -1698,7 +1716,9 @@ impl<'a> Lower<'a> {
local_ok: false,
local_any: LOCAL_ANY.get(),
uniform: match &exchange {
Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
Some((_, false, all)) if !LOCAL_WAVES.get() => {
lane_uniform(p, x.st, all, split_lds && super::group_sync() != 0)
}
_ => HashSet::new(),
},
own_bits: match &exchange {
@@ -3549,7 +3569,7 @@ impl<'a> Lower<'a> {
} else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
// (a group of 32 or fewer has no other half to exchange with)
need(b.unwrap_or(0));
return Err("a lane mask exchanged where not every lane runs");
return Err(DIVERGENT_MASK_EXCHANGE);
}
xy = self.exchange_halves(at, xy.0);
}
@@ -4250,7 +4270,7 @@ impl<'a> Lower<'a> {
}
if !made.is_none_or(|b| self.all_lanes(b)) {
need(made.unwrap_or(0));
return Err("a lane mask exchanged where not every lane runs");
return Err(DIVERGENT_MASK_EXCHANGE);
}
let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
let (lo, hi) = self.exchange_halves(at, some);
@@ -6049,6 +6069,13 @@ impl<'a> Lower<'a> {
fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
if self.x.st.scc_some.contains_key(&v)
&& matches!(self.vals.get(&v), None | Some(Val::Missing(_)))
{
let x = self.scc_some(v)?;
self.vals.insert(v, Val::Bit(x));
return Ok(x);
}
match self.get(v) {
Ok(Val::Bit(x)) => Ok(x),
Ok(_) => Err("SCC without a value"),
@@ -7526,7 +7553,7 @@ impl<'a> Lower<'a> {
/// `ResourceHeap`): read from the host's table by heap slot in the
/// current block.
fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
let word = self.slot_word(src)?;
let word = self.slot_word(src, false)?;
Ok(word.map(|word| {
let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
let stride = self.s.m.bin(self.cur, Bin::And, word, bits);
@@ -7549,18 +7576,17 @@ impl<'a> Lower<'a> {
if !super::shader::constant_marks() {
return Ok(None);
}
let Some(word) = self.slot_word(src)? else {
let Some(word) = self.slot_word(src, false)? else {
return Ok(None);
};
let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT);
let mark =self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT);
Ok(Some(self.s.m.cmp(self.cur, pred::EQ, word, mark)))
}
/// Whether the typed buffer view `src` names is one of an integer format,
/// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
/// program does not pick from the heap).
/// and whether a signed one (`ResourceHeap` or `Table`).
fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
let Some(word) = self.slot_word(src)? else {
let Some(word) = self.slot_word(src, true)? else {
return Ok(None);
};
let c = self.cur;
@@ -7574,19 +7600,22 @@ impl<'a> Lower<'a> {
}
/// The host's word for the buffer view `src` names: its stride and
/// format kind ([`super::shader::SLOT_STRIDES`]).
fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> {
/// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`,
/// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`).
fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result<Option<V>, Why> {
let Source::Loaded { load, first } = src else {
return Ok(None);
};
let heap = self
let srv_slot = match self
.scalar
.get(load)
.and_then(|a| self.x.native.layout.get(a.param))
.is_some_and(|p| p.root == RootType::ResourceHeap);
if !heap {
return Ok(None);
}
.map(|p| p.root)
{
Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES,
Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES,
_ => return Ok(None),
};
let key = (self.cur, *load, *first);
if let Some(&v) = self.strides.get(&key) {
return Ok(Some(v));
@@ -7601,7 +7630,7 @@ impl<'a> Lower<'a> {
self.s.m.tag(slot, Tag::Clamp);
let two = self.s.m.i32(2);
let byte = self.s.m.bin(c, Bin::Shl, slot, two);
let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES);
let h = self.s.root_srv_handle(srv_slot);
let iu = self.s.m.undef(self.s.t.i32);
let mask = self.s.m.i8(1);
let align = self.s.m.i32(4);
@@ -7769,6 +7798,15 @@ impl<'a> Lower<'a> {
unreachable!()
};
let name = inst.name();
if let Some(&source) = self.x.res.restored_lanes.get(&(b, i)) {
// This lane was overwritten by a uniform scalar. The previous
// contents of other lanes can be unknown (a reduction scratch).
let word = match source {
crate::resource::Moved::Value(v) => self.i32_of(v)?,
crate::resource::Moved::Const(k) => self.s.m.i32(k),
};
return self.write_i(inst, word, None);
}
if self.x.res.waterfall.compares.contains(&(b, i)) {
// The first lane's dwords of a waterfall loop are each lane's
// own (see `resource::Waterfall`).
@@ -11963,9 +12001,13 @@ impl<'a> Lower<'a> {
// through a view of an integer format it is a 16-bit
// integer, zero- or sign-extended (VIctory 4243a96a: the face
// network keeps its halves in UINT views; its output was
// noise). shortcut: that is known of the views a program
// picks from the heap; and the handle stays a float one,
// whose bits the drivers pass.
// noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table`
// (`SLOT_TABLE_STRIDES`, dynamic table snapshots included)
// populate the view-kind bits, while the handle stays a float
// one (`0x409`), whose raw bits RTX and WARP pass bit-exact
// without extra CFG blocks or touching non-d16 shaders.
// LOCAL (faces): not where the program moves halves as
// integers (`halves`): those views are shown as UINT already.
let integer = if typed && !halves { self.integer_view(src)? } else { None };
let mut wide = Vec::new();
for k in 0..count {
+113 -18
View File
@@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
constant_marks, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
};
@@ -500,17 +500,45 @@ pub fn emit(
};
// The program in two other forms: without its early-outs, and
// without any branch that only skips code no lane is left for.
let form = |p: Option<ir::Program>| {
p.and_then(|p| {
let st = structure::structure(&p).ok()?;
let io = io::raise(&p, native).ok()?;
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
Some((p, st, io, res))
})
let form = |label: &str, p: Option<ir::Program>| {
let Some(p) = p else {
if why {
eprintln!("WAVE64-FORM {label}: ir returned None");
}
return None;
};
let st = match structure::structure(&p) {
Ok(st) => st,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: structure failed: {e}");
}
return None;
}
};
let io = match io::raise(&p, native) {
Ok(io) => io,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: io::raise failed: {e}");
}
return None;
}
};
let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) {
Ok(res) => res,
Err(e) => {
if why {
eprintln!("WAVE64-FORM {label}: resource::track failed: {e}");
}
return None;
}
};
Some((p, st, io, res))
};
let forms = [
("without early-outs", form(ir::without_early_outs(p))),
("without skips", form(ir::without_skips(p, false))),
("without early-outs", form("without early-outs", ir::without_early_outs(p))),
("without skips", form("without skips", ir::without_skips(p, false))),
];
for (name, f) in &forms {
if let Some((p, st, io, res)) = f {
@@ -526,7 +554,24 @@ pub fn emit(
// lost the card in a submission of two programs that had just moved to it
// (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which
// has no barrier, stays on.
let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1");
let wide_option = std::env::var_os("VICTORY_WAVE_WIDE");
// Both archived kernels use one logical wave per group and have
// validated wave32 PSOs on RTX. Explicit policy wins.
let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64)
&& matches!(
c.digest,
[0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1]
| [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c]
);
let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1");
// A single guest wave can iterate an active-lane loop until both host
// halves have finished. The precise latch and convergence conditions
// for the driver compute route are checked by widen().
let driver_loop = wide_option.is_none()
&& c.part(FourCC::DXIL).is_none()
&& c.part(FourCC::ACCC).is_some()
&& matches!(&original, Err(ShaderError::Unsupported { what, .. })
if *what == lower::DIVERGENT_MASK_EXCHANGE);
// exact first: each host wave on its own where that is exact (the idiom, every
// form; no barriers), then the other exact forms; then approximate
for exact in [true, false] {
@@ -537,7 +582,7 @@ pub fn emit(
// lane runs, where the two host waves can exchange.
// (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None };
if let Some((p, st, io, res)) = &deep {
let again = emit_program(c, native, p, st, io, res);
report("without skips, scalars followed", &again);
@@ -548,7 +593,7 @@ pub fn emit(
// Still stopped where not every lane runs: the per-lane branches around
// those places taken as the console takes them, by the whole wave at once
// ([`widen`]), at two group barriers per such branch.
if wide_on {
if wide_on || driver_loop {
let bases = [
deep.as_ref().map(|f| &f.0),
forms[1].1.as_ref().map(|f| &f.0),
@@ -556,7 +601,7 @@ pub fn emit(
Some(p),
];
if let Some(base) = bases.into_iter().flatten().next() {
let again = widen(c, native, base, why);
let again = widen(c, native, base, why, driver_loop);
report("wave-wide branches", &again);
if done(&again) {
return again.map(|(shader, _)| shader);
@@ -618,7 +663,7 @@ pub fn emit(
&& what == lower::LANE_MASK
&& std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
{
let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some());
let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false);
match again {
Ok(_) => again,
Err(_) => emit_program(c, native, p, st, io, res),
@@ -626,7 +671,17 @@ pub fn emit(
}
other => other,
};
let original = original.map(|(shader, _)| shader);
let supported = |(shader, wave): (HostShader, Option<u32>)| {
if wave == Some(64) && lower::host_max_wave() == 32 {
Err(ShaderError::Unsupported {
offset: 0,
what: "no wave32 lowering for this wave64 program",
})
} else {
Ok(shader)
}
};
let original = original.and_then(supported);
// Retry unsupported programs only. Threading can separate an unknown
// register value from its apparent use on a mutually exclusive path.
if !matches!(original, Err(ShaderError::Unsupported { .. })) {
@@ -640,7 +695,7 @@ pub fn emit(
let st = structure::structure(&p)?;
let io = io::raise(&p, native)?;
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
emit_program(c, native, &p, &st, &io, &res).and_then(supported)
}
/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane
@@ -655,6 +710,7 @@ fn widen(
native: &NativeProgram,
p: &ir::Program,
why: bool,
active_loop_only: bool,
) -> Result<(HostShader, Option<u32>), ShaderError> {
const NOT: ShaderError = ShaderError::Unsupported {
offset: 0,
@@ -687,7 +743,22 @@ fn widen(
|| matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
if !stuck {
if why {
eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
let order = ir::reverse_postorder(&p.blocks);
let mut rpo = vec![0usize; p.blocks.len()];
for (i, &b) in order.iter().enumerate() {
rpo[b] = i;
}
let mut sorted: Vec<usize> = wide.iter().copied().collect();
sorted.sort_unstable();
let desc: Vec<String> = sorted
.iter()
.map(|&b| {
let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]);
let nm = p.blocks[b].insts.last().map_or("?", |i| i.name());
format!("B{b}({nm}{})", if back { ",BACK" } else { "" })
})
.collect();
eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", "));
}
return r;
}
@@ -702,6 +773,30 @@ fn widen(
}
return r;
}
if active_loop_only {
// Only a single backward branch on the SCC just set by
// s_andn2_wrexec_b64. This instruction restricts EXEC to the
// unfinished lanes. The guest repeats the loop if *either*
// half still has work, while individual vector writes retain
// their EXEC predicates.
let [latch] = more.as_slice() else {
return r;
};
let block = &p.blocks[*latch];
let [.., update, branch] = block.insts.as_slice() else {
return r;
};
if !wide.is_empty()
|| update.name() != "s_andn2_wrexec_b64"
|| branch.name() != "s_cbranch_scc1"
|| !matches!(
block.exit,
ir::Exit::Branch { taken, not_taken } if taken <= *latch && not_taken > *latch
)
{
return r;
}
}
wide.extend(more);
}
}
+5
View File
@@ -24,6 +24,11 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// root SRV also tells the host that the buffer views of the whole heap
/// must be ready when it runs, not only those its tables name.
pub const SLOT_STRIDES: u8 = 255;
/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for
/// shaders that only inspect views from descriptor tables (`RootType::Table`).
/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without
/// running the full bindless heap buffer sweep.
pub const SLOT_TABLE_STRIDES: u8 = 252;
/// The bits of a [`SLOT_STRIDES`] dword that hold the stride.
pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1;
/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format
+270 -423
View File
@@ -181,7 +181,6 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
@@ -1919,7 +1918,6 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: Vec::new(),
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut copy = shader.dxil.clone();
@@ -2060,76 +2058,48 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() {
}
}
/// A program that moves a typed buffer's 16-bit channels
/// (`buffer_load_format_d16_xyzw` from the table's first view,
/// `buffer_store_format_d16_xyzw` to its second) names both places for the
/// host (`HostShader::half_views`) and moves every pattern as it is through
/// unsigned views: half floats, the not-a-number ones among them, and
/// plain 16-bit integers (the title keeps both in such buffers; the
/// network that moves its faces reads indices this way). A program that
/// moves no halves names nothing.
#[test]
fn halves_go_through_a_table_as_they_are_and_name_their_views() {
use super::host::Stride;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT;
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_D16_XYZW: u32 = 0x83;
const STORE_D16_XYZW: u32 = 0x87;
const THREADS: u32 = 32;
// The table's second descriptor, 0x20 bytes on.
let mut second = s_load_dwordx4(12, 4);
second[1] |= 0x20;
let mut words = vec![s_mov_b32(5, 0x80)];
words.extend_from_slice(&s_load_dwordx4(8, 4));
words.extend_from_slice(&second);
// v[1:2] = first[thread] (four halves), second[thread] = v[1:2].
words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | (op as u32) << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null).
const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] {
[
0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1),
(125 << 25) | (byte_offset & 0x1F_FFFF),
]
}
/// Builds a compute shader whose descriptors live in a `RootType::Table` at
/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`).
fn build_table_typed_cs(body: &[u32], used: Vec<UsedResource>) -> HostShader {
let mut words = Vec::new();
words.push(s_mov_b32(5, 0x80)); // s5 = 0
words.extend_from_slice(body);
words.push(S_ENDPGM);
let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)],
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 0,
}],
used,
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [THREADS, 1, 1],
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
threads: [4, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
code,
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
@@ -2148,7 +2118,6 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() {
mesh_stride: 0,
})
.expect("lower");
assert_eq!(lowered.half_views, [(1, 0), (1, 8)]);
let shader = HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
@@ -2159,362 +2128,252 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() {
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: lowered.half_views,
};
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
let mut dxil = shader.dxil.clone();
v.validate(&mut dxil).expect("DXIL validation failed");
let mut copy = shader.dxil.clone();
v.validate(&mut copy).expect("DXIL validation failed");
}
// A raw store through the same table: no halves, nothing named.
assert!(build_valu_cs(&[]).half_views.is_empty());
// Four halves a thread: numbers, both zeros, subnormals, infinities,
// not-a-numbers of both signs, and integers past the largest number's
// pattern, as indices are.
const SPECIAL: [u16; 16] = [
0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000,
0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff,
];
let halves: Vec<u16> = (0..4 * THREADS as usize)
.map(|i| match i {
0..16 => SPECIAL[i],
_ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00),
})
.collect();
let data: Vec<u32> = halves
.chunks(2)
.map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16)
.collect();
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8),
},
View::HalfUintUav(THREADS),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
assert_eq!(
out[0], data,
"{label}: the halves stored are the halves loaded"
);
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
shader
}
/// The places a program that moves halves names are the descriptors it
/// loads, not the start of the range their used-resource entry describes:
/// with one entry for a range from dword 0, a load at byte 0x20 names
/// dword 8 (a host view there in a 16-bit float format is the one shown
/// as its unsigned twin). A descriptor picked at run time (the load's
/// offset in an SGPR) names nothing and keeps the float path: which slot
/// it reads, and in which format, is known only then.
/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds
/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA
/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit
/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`.
/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including
/// non-zero table offsets matching dynamic descriptor snapshots) on hardware
/// GPU and WARP.
#[test]
fn half_places_are_the_descriptors_the_program_loads() {
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_D16_XYZW: u32 = 0x83;
const STORE_D16_XYZW: u32 = 0x87;
let lowered = |words: &[u32]| {
let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource {
kind,
fn typed_d16_table_uav_roundtrip_uint_sint_and_float() {
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT,
DXGI_FORMAT_R16G16B16A16_UINT,
};
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut body = Vec::new();
// s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV),
// s[16:19] = table[2] (raw UAV dump of loaded v[2:3]).
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64));
// buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83)
body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8));
// buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87)
body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12));
// Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself.
// v4 = v0 << 3 (byte offset = thread * 8)
body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0
// buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12)
body.extend_from_slice(&[
0x38 << 26 | 0x1D << 18 | 1 << 12,
0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32,
]);
let used = (0..3u32)
.map(|k| UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
table_offset_dwords: k * 8,
lower_bound: k,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
// One entry for a range of views from dword 0, one at 16.
used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [32, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res =
resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
slot: 0,
})
.expect("lower")
};
// `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with
// the offset in `soffset` instead.
let at = |dst: u8, offset: u32| {
let mut w = s_load_dwordx4(dst, 4);
w[1] |= offset;
w
};
let picked = |dst: u8, soffset: u8| {
let mut w = s_load_dwordx4(dst, 4);
w[1] = u32::from(soffset) << 25;
w
};
let mut fixed = vec![s_mov_b32(5, 0x80)];
fixed.extend_from_slice(&at(8, 0x20));
fixed.extend_from_slice(&at(12, 0x40));
fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
fixed.push(S_ENDPGM);
assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]);
// The load's offset in s20, from the first lane's thread index
// (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land
// on the store's place too, so no place of that table is named: the d16
// accesses there take the float path, as before half views.
let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))];
runtime.extend_from_slice(&picked(8, 20));
runtime.extend_from_slice(&at(12, 0x40));
runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8));
runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12));
runtime.push(S_ENDPGM);
assert!(lowered(&runtime).half_views.is_empty());
}
/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose
/// result the program only reads one half of as a half float
/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the
/// face network's output so, from an `R16_UINT` view. It names its view for
/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a
/// whole float instead (`v_add_f32`), the load stays a float load and names
/// nothing; so does a load of halves beside a load of the same view read as
/// a whole float (a view of numbers the program also picks one half float
/// out of, as hundreds of the title's pixel programs do).
#[test]
fn a_format_load_read_as_halves_loads_the_integer() {
use super::host::Stride;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT;
/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`.
const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] {
[
0x38 << 26 | op << 18 | 1 << 13,
0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32,
]
}
const LOAD_FORMAT_X: u32 = 0x00;
const V_CVT_F32_F16: u16 = 0x0B;
const V_ADD_F32: u8 = 0x03;
let lowered = |body: &[u32]| {
let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords,
lower_bound: table_offset_dwords / 8,
stride,
dwords: 4,
user_data: 4,
slot: 1,
};
let mut second = s_load_dwordx4(12, 4);
second[1] |= 0x20;
let mut words = vec![s_mov_b32(5, 0x80)];
words.extend_from_slice(&s_load_dwordx4(8, 4));
words.extend_from_slice(&second);
// `body` leaves v2, stored raw.
words.extend_from_slice(body);
words.extend_from_slice(&buffer_store_dword(2, 12, 0));
words.push(S_ENDPGM);
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 8,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1,
threads: [1, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res =
resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(&p, &native).expect("io::raise");
let l = lower::lower(&lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})
.expect("lower");
HostShader {
stage: HwStage::Cs,
dxil: l.dxil,
user_data: l.user_data,
samplers: l.samplers,
static_samplers: Vec::new(),
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: res.root_indexed_views,
half_views: l.half_views,
}
};
// v1 = first[v0] (one channel).
let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8);
let half = vop1(V_CVT_F32_F16, 2, vgpr(1));
let as_halves = lowered(&[&load[..], &[half]].concat());
assert_eq!(as_halves.half_views, [(1, 0)]);
let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat());
assert!(as_float.half_views.is_empty());
// v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3.
let mut beside = load.to_vec();
beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8));
beside.push(half);
beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2));
assert!(lowered(&beside).half_views.is_empty());
// Behind a branch, as the head program has it: where the lanes meet
// again the loaded value goes on through a phi, and a later write of
// v1 under EXEC reads it only to keep it in the lanes it leaves alone.
const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo
const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0
const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words
const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16
let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0
let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0
let branched = lowered(
&[
&[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..],
&load,
&[
half,
RESTORE_EXEC,
SAVE_EXEC,
ONLY_LANE_0,
rewrite,
RESTORE_EXEC,
],
]
.concat(),
.collect();
let shader = build_table_typed_cs(&body, used);
assert!(
shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
"table typed d16 shader should request SLOT_TABLE_STRIDES"
);
assert_eq!(branched.half_views, [(1, 0)]);
// A d16 load names its place where it is the only access there...
const LOAD_FORMAT_D16_X: u32 = 0x80;
let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8);
let d16_alone = lowered(&[&d16[..], &[half]].concat());
assert_eq!(d16_alone.half_views, [(1, 0)]);
// ...and not beside a whole float read through the same place, which
// would see the unsigned twin: v2 = half(d16 v1) + v3.
let mut d16_beside = d16.to_vec();
d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8));
d16_beside.push(half);
d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2));
assert!(lowered(&d16_beside).half_views.is_empty());
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
for shader in [&as_halves, &branched, &d16_alone] {
let mut dxil = shader.dxil.clone();
v.validate(&mut dxil).expect("DXIL validation failed");
}
}
// Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00).
let data = [0x0000_3c00u32, 0];
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut ran = 0;
for (label, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {label} device; skipped");
continue;
};
for (name, shader) in [("straight", &as_halves), ("branched", &branched)] {
let (root, pso) = host
.compute_pipeline(shader)
.unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
assert!(
!shader.root_srvs.contains(&super::SLOT_STRIDES),
"table-only shader must not trigger the bindless SLOT_STRIDES sweep"
);
// 4 elements x 4 u16 channels = 8 u32 dwords.
// Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00),
// NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns.
let uint_bits: [u32; 8] = [
0x3C00_0001, 0x7E00_BC00,
0xFFFF_8000, 0xABCD_1234,
0x0002_0000, 0x7BFF_FBFF,
0xDEAD_BEEF, 0xCAFE_BABE,
];
let sint_bits: [u32; 8] = [
0xFFFF_8000, 0x7FFF_0001,
0xC000_0000, 0x8001_7FFE,
0xFFFF_FFFF, 0x0000_0000,
0xFEDC_BA98, 0x7654_3210,
];
// Normal finite FP16 values that round-trip cleanly through f32.
let float_bits: [u32; 8] = [
0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5
0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0
0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0
0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0
];
let zeros = [0u32; 8];
let cases = [
("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32),
("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32),
("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32),
("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32),
];
for (backend, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else { continue };
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
for &(label, format, stride_word, input, base_slot) in &cases {
let mut views = Vec::new();
let mut strides = Vec::new();
for _ in 0..base_slot {
views.push(View::RawUav(1));
strides.push(0u32);
}
let uav_base = base_slot as usize;
views.push(View::TypedUav { data: input, format, elem_bytes: 8 });
strides.push(stride_word);
views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 });
strides.push(stride_word);
views.push(View::RawUav(8));
strides.push(1);
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
ud[u.index as usize] = match (u.root, u.slot) {
(RootType::Table, 1) => 0,
other => panic!("unexpected user data {other:?}"),
};
if u.root == RootType::Table && u.slot == 0 {
ud[u.index as usize] = base_slot * 32;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![
(0, Root::Constants(ud)),
(1, Root::View { srv: true, data: strides }),
],
views: &views,
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
assert_eq!(
out[uav_base + 2],
input,
"{backend} {label}: buffer_load_format_d16_xyzw mismatch"
);
assert_eq!(
out[uav_base + 1],
input,
"{backend} {label}: buffer_store_format_d16_xyzw mismatch"
);
}
}
}
/// Non-`d16` typed loads (`buffer_load_format_x`) are used by
/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut`
/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify
/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`.
#[test]
fn typed_non_d16_table_load_preserves_integer_bits() {
use windows::Win32::Graphics::Dxgi::Common::{
DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT,
};
let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut body = Vec::new();
// s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out)
body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0));
body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32));
// buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00)
body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8));
// v4 = v0 << 2 (byte offset = thread * 4)
body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0
// buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12)
body.extend_from_slice(&[
0x38 << 26 | 0x1C << 18 | 1 << 12,
0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32,
]);
let used = vec![
UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
},
UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 8,
lower_bound: 1,
stride: 4,
dwords: 4,
user_data: 4,
slot: 0,
},
];
let shader = build_table_typed_cs(&body, used);
// Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no
// CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep
// identical DXIL and pipeline cache keys while still preserving raw bits.
assert!(
!shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES),
"non-d16 typed load should not add SLOT_TABLE_STRIDES"
);
let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32];
let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF];
let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [
(
"R16_UINT",
DXGI_FORMAT_R16_UINT,
2,
&r16_data,
[0x0001, 0x3C00, 0xBC00, 0xFFFF],
),
(
"R16_SINT",
DXGI_FORMAT_R16_SINT,
2,
&r16_data,
[0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF],
),
(
"R32_UINT",
DXGI_FORMAT_R32_UINT,
4,
&r32_data,
r32_data,
),
];
for (backend, warp) in [("hardware", false), ("warp", true)] {
let Ok(host) = Host::new(warp) else { continue };
let (root, pso) = host
.compute_pipeline(&shader)
.unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}"));
for &(label, format, elem_bytes, input, want) in &cases {
let views = [
View::Buffer {
data: input,
stride: super::host::Stride::Format(format, elem_bytes),
},
View::RawUav(4),
];
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if u.root == RootType::Table && u.slot == 0 {
ud[u.index as usize] = 0;
}
}
let out = host
.dispatch(
@@ -2522,25 +2381,13 @@ fn a_format_load_read_as_halves_loads_the_integer() {
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[
View::Buffer {
data: &data,
stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2),
},
View::RawUav(1),
],
views: &views,
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
assert_eq!(
out[0][0],
1.0f32.to_bits(),
"{label}, {name}: the half read as an integer's bits"
);
.unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}"));
assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch");
}
ran += 1;
}
assert!(ran > 0, "no SM 6.6 device available");
}
+108 -21
View File
@@ -138,6 +138,9 @@ pub struct RootIndexedView {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Resources {
/// Scalar values saved to a constant VGPR lane and restored within one
/// block, even if that VGPR is also used in ordinary vector operations.
pub(crate) restored_lanes: std::collections::HashMap<Site, Moved>,
/// Every scalar memory access by address (`s_load_*`, `s_store_*`), and
/// every global memory access (`global_*`, the dynamic term per lane).
pub scalar: Vec<(Site, Address)>,
@@ -224,9 +227,12 @@ pub fn track(
let mut offset_at =
std::collections::BTreeMap::<usize, (Vec<usize>, Vec<Value>, Vec<Site>)>::new();
for (b, block) in p.blocks.iter().enumerate() {
t.at.set(Some(b));
for (i, inst) in block.insts.iter().enumerate() {
let site = (b, i);
t.at.set(Some(site));
if let Some(value) = t.restored(inst, Some(b)) {
out.restored_lanes.insert(site, value);
}
let fail = |what| ShaderError::Unsupported {
offset: inst.machine.offset,
what,
@@ -234,7 +240,7 @@ pub fn track(
let mut first_lane = Vec::new();
let mut offset = Vec::new();
let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> {
let source = t.descriptor(inst, op, b).map_err(fail)?;
let source = t.descriptor(inst, op, site).map_err(fail)?;
// A descriptor the code keeps per lane ([`Tracer::lane_copies`])
// is the same in every lane: its loop is lowered as it stands
// and needs no proof.
@@ -411,8 +417,8 @@ struct Tracer<'a> {
meets: std::cell::RefCell<Meets>,
/// Reverse-postorder index per block.
rpo: Vec<usize>,
/// The block of the access being traced ([`Self::live`]).
at: std::cell::Cell<Option<usize>>,
/// The instruction site of the access being traced ([`Self::live`]).
at: std::cell::Cell<Option<Site>>,
}
/// What lanes are known to satisfy: each [`Bool`] where its flag is set,
@@ -514,7 +520,7 @@ impl<'a> Tracer<'a> {
}
for inst in &block.insts {
for (k, &(_, v)) in inst.writes.iter().enumerate() {
let new = match copy_source(inst, k).or_else(|| self.restored(inst)) {
let new = match copy_source(inst, k).or_else(|| self.restored(inst, None)) {
Some(Moved::Const(c)) => Some(Term::Const(c)),
Some(Moved::Value(s)) => o[s.0 as usize],
None => Some(Term::Value(v)),
@@ -1113,8 +1119,8 @@ impl<'a> Tracer<'a> {
self.address(lo, hi, extra)
}
/// The source of the descriptor operand `op` of `inst`, in block `at`.
fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result<Source, &'static str> {
/// The source of the descriptor operand `op` of `inst`, at `at`.
fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result<Source, &'static str> {
let Operand::Scalar { code, dwords } = *op else {
return Err("a descriptor not in SGPRs");
};
@@ -1129,8 +1135,14 @@ impl<'a> Tracer<'a> {
{
words = raw.to_vec();
}
// Only the lanes that reach the access read the descriptor.
let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
// Only the lanes that reach and run the access read the descriptor.
let mut known = Vec::new();
if let Some(l) = self.lanes {
known.push((l.reach[at.0], true));
if let Some(guard) = l.guards[at.0][at.1] {
known.push((guard, true));
}
}
self.classify(&words, &mut Vec::new(), &mut known)
}
@@ -1282,7 +1294,10 @@ impl<'a> Tracer<'a> {
let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else {
return t;
};
let mut known = vec![(lanes.reach[at], true)];
let mut known = vec![(lanes.reach[at.0], true)];
if let Some(guard) = lanes.guards[at.0][at.1] {
known.push((guard, true));
}
for _ in 0..MAX_JOINS {
let Term::Value(v) = t else { break };
let Some((block, i)) = self.phis[v.0 as usize] else {
@@ -2292,41 +2307,64 @@ impl<'a> Tracer<'a> {
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Moved {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Moved {
Const(u32),
Value(Value),
}
fn plain_lane(v: &crate::gfx10::Valu) -> bool {
v.abs == 0
&& v.neg == 0
&& v.opsel == 0
&& !v.clamp
&& v.omod == 0
&& v.sdwa.is_none()
&& v.dpp.is_none()
}
impl Tracer<'_> {
/// For `v_readlane_b32` of a constant lane: the SGPR spilled to that
/// lane, found by following the VGPR's `v_writelane_b32` writes.
fn restored(&self, inst: &Inst) -> Option<Moved> {
fn restored(&self, inst: &Inst, block: Option<usize>) -> Option<Moved> {
let Fields::Valu(v) = &inst.fields else {
return None;
};
if inst.name() != "v_readlane_b32" {
if inst.name() != "v_readlane_b32" || !plain_lane(v) {
return None;
}
let [Operand::Vector { reg, .. }, lane] = v.src[..] else {
return None;
};
self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new())
let lane = lane_of(lane)?;
if lane >= if self.p.wave64 { 64 } else { 32 } {
return None;
}
self.spilled(inst.read(Reg::V(reg))?, lane, block, &mut Vec::new())
.ok()
.flatten()
}
/// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in
/// `seen` (already being resolved), `Err` if not a spilled SGPR.
fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> {
fn spilled(
&self,
v: Value,
lane: u32,
block: Option<usize>,
seen: &mut Vec<Value>,
) -> Result<Option<Moved>, ()> {
if let Some((b, i)) = self.phis[v.0 as usize] {
if block.is_some() {
return Err(());
}
if seen.contains(&v) {
return Ok(None);
}
seen.push(v);
let mut found = None;
for &a in &self.p.blocks[b].phis[i].args {
if let Some(m) = self.spilled(a, lane, seen)? {
if let Some(m) = self.spilled(a, lane, block, seen)? {
if found.is_some_and(|f| f != m) {
return Err(());
}
@@ -2335,18 +2373,26 @@ impl Tracer<'_> {
}
return Ok(found);
}
let inst = self.def(v).ok_or(())?;
let site = self.defs[v.0 as usize].ok_or(())?;
if block.is_some_and(|b| site.0 != b) {
return Err(());
}
let inst = self.inst(site);
let Fields::Valu(w) = &inst.fields else {
return Err(());
};
let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else {
return Err(());
};
if inst.name() != "v_writelane_b32" {
if inst.name() != "v_writelane_b32" || !plain_lane(w) {
return Err(());
}
if lane_of(*at).ok_or(())? != lane {
return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen);
let written = lane_of(*at).ok_or(())?;
if written >= if self.p.wave64 { 64 } else { 32 } {
return Err(());
}
if written != lane {
return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, block, seen);
}
match *value {
Operand::Scalar { code, .. } if code != NULL => {
@@ -4061,4 +4107,45 @@ pub(crate) mod tests {
assert_eq!(r.waterfall.compares.len(), 2);
assert_eq!(r.waterfall.reads.len(), 4);
}
#[test]
fn a_guarded_access_excludes_dead_lane_edges_at_a_join() {
// Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz`
// directly to the join block without initializing the immediate
// sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC,
// so only the arm where `s[8:11]` was built can execute it.
let code: Vec<u8> = [
0xBE84_0300u32, // s_mov_b32 s4, s0
0xBE85_0380, // s_mov_b32 s5, 0
0xF40C_0302,
0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0
0x7E04_0D00, // v_cvt_f32_u32 v2, v0
0x7E06_0302, // v_mov_b32 v3, v2
0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo
0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords)
0xBE88_0380, // s_mov_b32 s8, 0
0xBE89_0380, // s_mov_b32 s9, 0
0xBE8A_0380, // s_mov_b32 s10, 0
0xBE8B_0380, // s_mov_b32 s11, 0
0xF09C_0F08,
0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11]
S_ENDPGM,
]
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let p = crate::ir::build(&code, false, 256).unwrap();
let structured = lanes(&p).expect("structured form");
assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard");
let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap();
assert!(
r.descriptors
.iter()
.any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])),
"guarded join should resolve the immediate sampler from the live arm: {:?}",
r.descriptors
);
}
}