Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions crates/victory-gpu/src/pipeline/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,33 @@ impl GraphicsState {
}
}

/// Whether this state describes a pass over the screen: no vertex input,
/// no depth or stencil testing, triangle topology. Such passes fill
/// lighting tables once at world entry; their shaders are few.
pub(crate) fn screen_pass(&self) -> bool {
self.inputs.is_empty()
&& (self.depth_format == DXGI_FORMAT_UNKNOWN
|| !self.depth_bounds
&& !self.depth.DepthEnable.as_bool()
&& !self.depth.StencilEnable.as_bool())
&& self.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
}

/// A screen-pass state like the lighting tables' fills, for tests of
/// the routing to the screen pool in `make`.
#[cfg(test)]
pub(crate) fn screen_triangle_state() -> GraphicsState {
GraphicsState {
topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
depth: D3D12_DEPTH_STENCIL_DESC {
DepthEnable: false.into(),
StencilEnable: false.into(),
..Default::default()
},
..GraphicsState::default()
}
}

/// Everything the state holds, as text: part of a pipeline's name in
/// the library and of the key a title pipeline is started early by.
pub(crate) fn describe(&self) -> String {
Expand Down Expand Up @@ -1462,6 +1489,31 @@ mod tests {

use super::*;

#[test]
fn screen_pass_requires_triangle_without_inputs_or_depth() {
let mut g = GraphicsState {
topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
depth_format: DXGI_FORMAT_UNKNOWN,
..Default::default()
};
assert!(g.screen_pass());

g.depth_format = DXGI_FORMAT_D32_FLOAT;
g.depth.DepthEnable = true.into();
assert!(!g.screen_pass());

g.depth.DepthEnable = false.into();
g.depth.StencilEnable = false.into();
assert!(g.screen_pass());

g.depth_bounds = true;
assert!(!g.screen_pass());
g.depth_bounds = false;

g.inputs.push(D3D12_INPUT_ELEMENT_DESC::default());
assert!(!g.screen_pass());
}

/// A triangle mesh shader of our own and a pixel shader for it.
const MS: &str = "struct V { float4 p : SV_Position; };
[outputtopology(\"triangle\")] [numthreads(1, 1, 1)]
Expand Down
109 changes: 73 additions & 36 deletions crates/victory-gpu/src/pipeline/make.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,15 @@
//! bake) are there at once as before; past the budget a draw or dispatch
//! whose pipeline is not ready is dropped, as an untranslated one is.
//!
//! The default budget is half a second per title frame. A pass the title
//! runs only once and whose pipeline takes longer is lost.
//! Passes over the screen (no vertex input, no depth) have workers of
//! their own: the title fills its lighting tables with such draws once, at
//! the world's first frame, and behind a world's worth of pipelines they
//! could wait out their frame budget before a worker ever reached them.
//! Each kind keeps its own budget, but both use the same limit: a
//! misclassified pass can only move to the other pool, never wait longer.
//!
//! The default budget is half a second per title frame and kind. A pass the
//! title runs only once and whose pipeline takes longer is lost.

use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
Expand All @@ -29,6 +36,8 @@ pub(crate) struct Pending {
pub(crate) graphics: Option<Box<GraphicsState>>,
queue_state: AtomicU8,
made: OnceLock<Option<HostPipeline>>,
/// A pass over the screen (see [`GraphicsState::screen_pass`]).
screen: bool,
/// What identifies it across runs (shader containers and state), and
/// whether a draw or dispatch has requested it yet.
key: String,
Expand Down Expand Up @@ -56,6 +65,7 @@ impl Pending {
.as_bytes(),
);
Pending {
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
shaders,
graphics,
queue_state: AtomicU8::new(NOT_QUEUED),
Expand Down Expand Up @@ -172,11 +182,14 @@ fn wait(p: &Pending, frame: u64) {
return;
}
// The frame the budget belongs to, and what was waited of it (or is
// taken by a thread waiting now).
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
// taken by a thread waiting now), per pipeline kind. Screen passes keep
// a budget of their own so a world's ordinary pipelines cannot spend it.
static SPENT: [Mutex<(u64, Duration)>; 2] =
[const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2];
let shared = shared_budget();
let spent_for_kind = &SPENT[usize::from(p.screen)];
Comment on lines +187 to +190

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Pipeline wait setting understates frame delay

wait can spend the full budget on each pool in one frame. At the default, sequential waits can total 1,000 ms, twice the documented limit.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in b1ac1fb: VICTORY_PIPELINE_WAIT_MS is now described as per pipeline kind, so a frame can spend the limit once in the ordinary pool and once in the screen pool.

let left = {
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
let mut spent = spent_for_kind.lock().unwrap_or_else(|e| e.into_inner());
if spent.0 != frame {
*spent = (frame, Duration::ZERO);
}
Expand Down Expand Up @@ -205,7 +218,7 @@ fn wait(p: &Pending, frame: u64) {
drop(held);
let waited = started.elapsed().min(left);
{
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
let mut spent = spent_for_kind.lock().unwrap_or_else(|e| e.into_inner());
// A frame that began meanwhile has its own budget.
if spent.0 == frame {
if shared {
Expand Down Expand Up @@ -271,68 +284,80 @@ impl Queue {
}
}

static QUEUE: Mutex<Queue> = Mutex::new(Queue::new());
static AVAILABLE: Condvar = Condvar::new();
static QUEUES: [Mutex<Queue>; 2] = [const { Mutex::new(Queue::new()) }; 2];
static AVAILABLE: [Condvar; 2] = [const { Condvar::new() }; 2];

/// Start or promote work for a draw without waiting behind the entire early
/// list. Queue changes and worker claims happen under the same lock.
fn start(p: &Arc<Pending>, priority: u8) {
if p.queue_state.load(Ordering::Relaxed) >= priority {
return;
}
if !workers() {
let kind = usize::from(p.screen);
if !workers(p.screen) {
if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED {
p.make();
}
return;
}
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
let mut queue = QUEUES[kind].lock().unwrap_or_else(|e| e.into_inner());
if let Some(new) = queue.push(p, priority) {
if new {
PEAK.fetch_max(
WAITING.fetch_add(1, Ordering::Relaxed) + 1,
Ordering::Relaxed,
);
}
AVAILABLE.notify_one();
AVAILABLE[kind].notify_one();
}
}

fn next() -> Arc<Pending> {
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
fn next(screen: bool) -> Arc<Pending> {
let kind = usize::from(screen);
let mut queue = QUEUES[kind].lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(p) = queue.pop() {
return p;
}
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
queue = AVAILABLE[kind]
.wait(queue)
.unwrap_or_else(|e| e.into_inner());
}
}

/// Starts the workers (half the logical processors, 2 to 8) on first use.
fn workers() -> bool {
static RUNNING: OnceLock<bool> = OnceLock::new();
*RUNNING.get_or_init(|| {
/// Starts the workers of one pipeline kind on first use: half the logical
/// processors (2 to 8) for ordinary pipelines, and two for screen passes.
fn workers(screen: bool) -> bool {
static RUNNING: [OnceLock<bool>; 2] = [const { OnceLock::new() }; 2];
*RUNNING[usize::from(screen)].get_or_init(|| {
let mut running = false;
let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
let workers = if screen {
2
} else {
std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8))
};
for i in 0..workers {
let spawned = std::thread::Builder::new()
.name(format!("victory-pipelines-{i}"))
.spawn(|| {
// Below the title's own threads (loading, recording).
// SAFETY: a plain call on our own thread.
unsafe {
use windows::Win32::System::Threading::*;
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
loop {
next().make();
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
drained();
} else {
super::library::save(false);
}
let name = if screen {
format!("victory-pipelines-screen-{i}")
} else {
format!("victory-pipelines-{i}")
};
let spawned = std::thread::Builder::new().name(name).spawn(move || {
// Below the title's own threads (loading, recording).
// SAFETY: a plain call on our own thread.
unsafe {
use windows::Win32::System::Threading::*;
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
loop {
next(screen).make();
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
drained();
} else {
super::library::save(false);
}
});
}
});
if let Err(e) = spawned {
tracing::warn!(error = %e, "no pipeline worker");
} else {
Expand Down Expand Up @@ -379,6 +404,18 @@ mod tests {
assert!(matches!(p.made.get(), Some(None)));
}

#[test]
fn screen_passes_are_classified_for_their_own_pool() {
let ordinary = Pending::new(Vec::new(), None);
assert!(!ordinary.screen);

let screen = Pending::new(
Vec::new(),
Some(Box::new(GraphicsState::screen_triangle_state())),
);
assert!(screen.screen);
}
Comment on lines +407 to +417

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Screen worker isolation goes untested

screen_passes_are_classified_for_their_own_pool checks the flag without queuing work. It would pass even if screen jobs stopped progressing while ordinary workers were busy.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged. I kept the deterministic coverage at classification plus the direct routing in start/next; an end-to-end isolation test would need control over pipeline compilation time, but the shared static worker pools make that inherently order-dependent in the current test harness.


#[test]
fn pending_pipeline_is_recorded_for_the_next_launch() {
let mut p = Pending::new(Vec::new(), None);
Expand Down
5 changes: 3 additions & 2 deletions docs/linux-proton.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ In every build, a draw of depth-tested geometry whose pixel shader does
not translate (or that the host refuses) is drawn with that debug shader
instead of dropped; `VICTORY_PS_FALLBACK=0` turns that off.
`VICTORY_PIPELINE_WAIT_MS` sets how long a frame may wait for pipelines
being made (500 by default; 0 never waits, pipelines then appear a few
frames later).
of each kind being made (500 by default; ordinary and screen-pass pipelines
have separate pools, so sequential waits can total twice that; 0 never
waits, pipelines then appear a few frames later).

## Tests

Expand Down
Loading