Merge agent/textures: bake sources, exact refreshes without waiting, target reserve

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
readmet3xt-labandClaude Opus 5.5 committed 2026-11-26 16:51:20 +05:30
commit dfb76df595
4 files changed
+562 -7

No files matched your search

+316 -4
View File
@@ -217,6 +217,80 @@ const BAKE_AHEAD: [u64; 2] = [12, 2];
/// until something is new, the next bakes of the frame need no pass.
static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
/// The counts [`State::bring_bake_sources`] keeps, since the start: bake
/// draws; sources found; of them, already what title memory holds; slots
/// that showed another view; textures without a host copy yet; host
/// written textures published; sources whose memory is not mapped; host
/// copies that held other bytes; uploads that could not be made.
const BAKE_SOURCE_COUNTS: usize = 9;
static BAKE_SOURCES: [AtomicU64; BAKE_SOURCE_COUNTS] = [const { AtomicU64::new(0) }; BAKE_SOURCE_COUNTS];
/// The records of its decorations a bake reads ([`State::bake_sources`]),
/// from the words of a constant buffer of its: the first and the end record
/// at byte 0x78, if they make a range of at most 256 records.
fn bake_record_range(constants: &[u32]) -> Option<(u32, u32)> {
const RANGE_AT: usize = 0x78 / 4;
const MOST_RECORDS: u32 = 256;
match constants.get(RANGE_AT..RANGE_AT + 2) {
Some(&[first, end]) if end > first && end - first <= MOST_RECORDS => Some((first, end)),
_ => None,
}
}
/// The slot numbers among `words` (each once, in the order they come: the
/// constants' first, at most 1,024): those not 0 that `names_texture` says
/// hold a texture view.
fn bake_candidates(words: Vec<u32>, names_texture: impl Fn(u32) -> bool) -> Vec<u32> {
const MOST_SOURCES: usize = 1024;
let mut seen = std::collections::HashSet::new();
words
.into_iter()
.filter(|&w| w != 0 && seen.insert(w) && names_texture(w))
.take(MOST_SOURCES)
.collect()
}
/// Adds one bake's counts to [`BAKE_SOURCES`] and says them: every bake
/// that found a source not up to date (the first 256), and the totals at
/// bakes 1, 2, 4, 8 ...
fn note_bake_sources(frame: u64, n: [u64; BAKE_SOURCE_COUNTS]) {
static SAID: AtomicU64 = AtomicU64::new(0);
let all: Vec<u64> = BAKE_SOURCES
.iter()
.zip(n)
.map(|(total, one)| total.fetch_add(one, Ordering::Relaxed) + one)
.collect();
let stale = n[3] + n[4] + n[7] + n[5];
if stale > 0 && SAID.fetch_add(1, Ordering::Relaxed) < 256 {
tracing::info!(
frame,
sources = n[1],
current = n[2],
showed_another_view = n[3],
no_host_copy = n[4],
other_bytes = n[7],
host_written_published = n[5],
not_mapped = n[6],
failed = n[8],
"a decoration bake's sources were not what title memory holds: brought up to date before the bake (VICTORY_BAKE_SOURCES=0: not)"
);
}
if all[0].is_power_of_two() {
tracing::info!(
bakes = all[0],
sources = all[1],
current = all[2],
showed_another_view = all[3],
no_host_copy = all[4],
other_bytes = all[7],
host_written_published = all[5],
not_mapped = all[6],
failed = all[8],
"decoration bakes' sources, since the start"
);
}
}
/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected
/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM
/// resources are free-threaded when externally synchronized.
@@ -807,6 +881,24 @@ pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(
/// the ones whose first page was not there (asked by the first page alone,
/// as before, they counted as not there at all).
pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// Microseconds the pass over textures picked by index spent, since the
/// last 5-second line, on: looks again at slots uploaded whole (a
/// fingerprint of 48 KiB), asking how much of a texture's memory is mapped,
/// asking whether a host copy holds what memory holds (a digest of all of
/// it), and making host copies and staging their uploads (`readable`); and
/// the passes in all. The pass stops at `VICTORY_TEXTURE_STAGE_MS` (16 in
/// the launcher), and in play it ran 18-20 ms a frame for about 20
/// textures: these say what took the time.
pub(crate) static HEAP_TEXTURE_MICROS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
/// `f`'s result, its time added to [`HEAP_TEXTURE_MICROS`]' place `slot`.
fn timed<T>(slot: usize, f: impl FnOnce() -> T) -> T {
let started = std::time::Instant::now();
let out = f();
HEAP_TEXTURE_MICROS[slot].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
out
}
static DROPPED: AtomicU64 = AtomicU64::new(0);
/// Marks the last traced draw as not run on the host.
@@ -2277,6 +2369,182 @@ impl State {
.is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h))
}
/// The title slots a draw of the title's bake can pick textures from.
///
/// The bake programs (`PS_BakeDecorations_*`, `PS_DecorationBlend_*`,
/// from their native code) name no texture in a table: the skin's own
/// texture is the heap slot at byte 0x20 of the constants at table 1,
/// and each decoration's textures are slots named in its record of the
/// structured buffer at table 1 (304 bytes a record), the records from
/// the one the constants hold at 0x78 to the one at 0x7c. So: every
/// word of the draw's constants (root and table) and of the records of
/// its buffers that is the number of a slot holding a texture view. The
/// records of a buffer are those the constants' words at 0x78 and 0x7c
/// name when they make a range of a few records inside it; else its
/// first 64 KiB. A word that is a slot number by chance costs one look
/// at that texture's memory (and its upload if the card's copy is not
/// what that memory holds).
fn bake_sources(&self, p: &HostPipeline, heap: &crate::descriptor::Heap) -> Vec<u32> {
const MOST_BYTES: u64 = 64 << 10;
let read = |address: u64, len: u64, words: &mut Vec<u32>| {
let mut bytes = vec![0u8; (len.min(MOST_BYTES) as usize) & !3];
if !bytes.is_empty() && crate::host::read_into(address as *const u8, &mut bytes) {
words.extend(bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])));
}
};
let roots = self.roots_ref(false);
let entry = |slot: u8, dwords: u32| -> Option<View> {
let Some(Root::Table(table)) = roots.get(usize::from(slot)) else {
return None;
};
crate::descriptor::view(table + u64::from(dwords) * 4)
};
let mut words = Vec::new();
// (Vertex or mesh stage, then the pixel stage: the one that samples.)
let last = p.stages.len().saturating_sub(1);
for (i, stage) in p.stages.iter().enumerate() {
let t = stage.translated();
// Constants first: they say which records the buffers' are.
let mut range = None;
for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind == ResourceType::Cbv) {
let Some(View::Constant(address, size)) = entry(u.slot, u.table_offset_dwords) else {
continue;
};
let from = words.len();
read(address, u64::from(size), &mut words);
range = bake_record_range(&words[from..]).or(range);
}
for u in t.used.iter().filter(|u| u.root == RootType::Constants) {
if let Some(Root::Constants(constants)) = roots.get(usize::from(u.slot)) {
words.extend_from_slice(constants);
}
}
// The pixel stage's buffers alone: a mesh stage's are vertices and
// meshlets, whose small integers would name slots by the hundred.
if i != last {
continue;
}
for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind == ResourceType::Srv) {
let Some((address, len)) = entry(u.slot, u.table_offset_dwords)
.as_ref()
.and_then(crate::descriptor::host::buffer_range)
else {
continue;
};
let stride = u64::from(u.stride);
match range {
Some((first, end)) if stride > 0 && u64::from(end) * stride <= len => {
let at = u64::from(first) * stride;
read(address + at, u64::from(end - first) * stride, &mut words);
}
_ => read(address, len, &mut words),
}
}
}
bake_candidates(words, |w| {
heap.handle(w)
.and_then(crate::descriptor::view)
.as_ref()
.is_some_and(crate::descriptor::host::is_texture_view)
})
}
/// Before a draw of the title's bake: every slot it can pick a texture
/// from ([`State::bake_sources`]) shows that texture as title memory
/// holds it now, whatever the pass over the queue got to. That pass
/// serves due slots newest write first within a budget, refuses new
/// host copies while the card has no room (and holds such slots back
/// for about four seconds), and does not look at a slot it served
/// before unless something told of a change: a bake that ran with one
/// of its sources missed baked that slot's stand-in (another texture of
/// the same kind, `VICTORY_KEEP_SHOWN`) or the texture's old bytes, for
/// good. Here, a source whose host slot is not made from its present
/// view, or whose host copy was not filled from the bytes its memory
/// holds now (`crate::texture::unchanged`), is uploaded on `list` (the
/// bake's own, run before the bake) whatever the card's room and the
/// pass's budget, and published with the others in `sync`. Returns
/// the counts for the line ([`BAKE_SOURCES`]). `VICTORY_BAKE_SOURCES=0`:
/// not done (only the pass, as before).
fn bring_bake_sources(
&self,
list: &HostList,
p: &HostPipeline,
heap: &crate::descriptor::Heap,
host: &crate::descriptor::host::HostHeap,
sync: &mut BakeSync,
) -> Option<[u64; BAKE_SOURCE_COUNTS]> {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_SOURCES").is_none_or(|v| v != "0")) {
return None;
}
let mut n = [0u64; BAKE_SOURCE_COUNTS];
n[0] = 1;
for index in self.bake_sources(p, heap) {
let Some(handle) = heap.handle(index) else { continue };
let Some((view, key)) = host.prepare_bake_slot(index, handle) else { continue };
n[1] += 1;
let placed = crate::descriptor::host::placed_texture(&view);
let resource = match placed.as_ref().or(Some(&view)) {
Some(&View::Shader(resource, _)) => resource as This,
_ => continue,
};
let mut first = 0;
if let View::Placed(false, desc_words, desc) = &view {
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
first = crate::resource::first_mip(desc);
let len = crate::resource::placed_bytes_from(desc_words, first).unwrap_or(1);
if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 {
// Not there (yet): what the console reads there is no
// texture either.
n[6] += 1;
continue;
}
}
let shown = host.texture_slot_made_from(index, handle);
let had_copy = crate::resource::made_copy(resource).is_some();
let Some(texture) = crate::resource::host_resource(resource) else {
// The host refused it (its creation failed).
n[8] += 1;
continue;
};
if !crate::texture::title_written(texture) || crate::texture::host_wrote(resource as usize) {
// A texture the host renders to, writes or copied into: its
// contents are the host's own; the slot only has to show it.
if shown {
n[2] += 1;
} else {
n[5] += 1;
sync.publish.push((index, handle, key));
}
continue;
}
if shown && crate::texture::unchanged(resource, first) {
n[2] += 1;
continue;
}
// Why it is not what the bake must read: the slot shows
// another view; the texture has no host copy yet; its host copy
// holds other bytes than its memory now.
n[if !shown { 3 } else if !had_copy { 4 } else { 7 }] += 1;
let was_staged = crate::texture::is_staged(resource);
let _ = crate::residency::take_staging_deferred();
readable(list, ResourceType::Srv, &view);
let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused();
if !was_staged {
crate::texture::unstage(resource);
}
if failed {
n[8] += 1;
continue;
}
if let Some(copy) = crate::resource::host_copy(resource) {
sync.keep.push(copy);
}
sync.publish.push((index, handle, key));
}
Some(n)
}
/// Runs the pass that uploads textures picked by index
/// ([`State::heap_textures`]) where nothing has asked for it yet
/// ([`early_budgets`]): once a frame for a few milliseconds, at the
@@ -2360,6 +2628,12 @@ impl State {
served = self.heap_textures(bake_list, heap, host, Some(&mut sync));
PASS_BUDGET.set(None);
}
// Whatever the pass got to: the slots this very draw picks
// from are what title memory holds (still uploading with
// `BAKING`, on the bake's own list).
if let Some(n) = self.bring_bake_sources(bake_list, p, heap, host, &mut sync) {
note_bake_sources(frame, n);
}
crate::texture::BAKING.set(false);
if bake_list.has_recorded_work() {
bake_list.close();
@@ -2693,7 +2967,8 @@ impl State {
// was shown four frames late, over and over.
let mut again_in = RECHECK_FRAMES[0];
if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
if crate::texture::fingerprint(at, len) == print {
let looked = timed(0, || crate::texture::fingerprint(at, len));
if looked == print {
HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
match RECHECK_FRAMES.get(usize::from(looks) + 1) {
Some(wait) => {
@@ -2734,7 +3009,7 @@ impl State {
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let first = crate::resource::first_mip(&desc);
let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1);
let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
let mapped = timed(1, || crate::texture::mapped_bytes(address as *const u8, len as usize));
if mapped == 0 {
HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
// Streamed out: what the slot showed is let go.
@@ -2879,7 +3154,7 @@ impl State {
(Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc),
_ => 0,
};
let same = !tabled && crate::texture::unchanged(resource, first);
let same = !tabled && timed(2, || crate::texture::unchanged(resource, first));
if same {
HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
@@ -2940,7 +3215,7 @@ impl State {
// (What was found mapped of it a moment ago is not asked
// again, unless the host copy may need more.)
crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
readable(list, sampled.kind, view);
timed(3, || readable(list, sampled.kind, view));
crate::texture::PICKING.set(None);
}
// A failed or deferred staging allocation leaves this slot due.
@@ -3044,6 +3319,7 @@ impl State {
if sync.is_none() && baking && served {
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
}
HEAP_TEXTURE_MICROS[4].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
served
}
@@ -4952,6 +5228,42 @@ mod tests {
assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB);
assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB);
}
/// The bake's decoration records: the range at byte 0x78 of its
/// constants, only a plausible one.
#[test]
fn a_bakes_record_range_is_read_at_0x78() {
use super::bake_record_range;
let mut constants = vec![0u32; 0x80 / 4];
assert_eq!(bake_record_range(&constants), None);
constants[0x78 / 4] = 3;
constants[0x7c / 4] = 7;
assert_eq!(bake_record_range(&constants), Some((3, 7)));
// Empty, reversed, implausibly long, or not there.
constants[0x7c / 4] = 3;
assert_eq!(bake_record_range(&constants), None);
constants[0x7c / 4] = 2;
assert_eq!(bake_record_range(&constants), None);
constants[0x7c / 4] = 3 + 257;
assert_eq!(bake_record_range(&constants), None);
constants[0x7c / 4] = 3 + 256;
assert_eq!(bake_record_range(&constants), Some((3, 259)));
assert_eq!(bake_record_range(&constants[..0x78 / 4 + 1]), None);
}
/// Slot numbers among a bake's words: each once in the order they come,
/// not 0, only those that hold a texture view, at most 1,024.
#[test]
fn bake_candidates_are_texture_slots_once() {
use super::bake_candidates;
let words = vec![12, 0, 9, 12, 0x3f80_0000, 5, 9, 7];
assert_eq!(bake_candidates(words, |w| w < 1000 && w != 7), vec![12, 9, 5]);
let many: Vec<u32> = (1..3000).rev().collect();
let got = bake_candidates(many, |_| true);
assert_eq!(got.len(), 1024);
assert_eq!(got.first(), Some(&2999));
assert!(bake_candidates(vec![0, 0], |_| true).is_empty());
}
}
#[cfg(test)]
+31
View File
@@ -8776,6 +8776,15 @@ impl Meter {
with less than was mapped (looked at again)"
);
}
let [read, waited] =
[0, 1].map(|i| crate::texture::EXACT_UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames);
if read + waited > 0.0 {
tracing::info!(
"exact texture refreshes (uploads before a bake) that found title memory being remapped, per frame: \
{read:.1} read whole through the kernel without waiting, {waited:.1} waited (a page was not there) \
(VICTORY_EXACT_NO_WAIT=0: all wait)"
);
}
}
{
let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames);
@@ -8832,6 +8841,28 @@ impl Meter {
crate::descriptor::host::STALE[3].load(Ordering::Relaxed),
crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
);
// What the queue's room test (`crate::resource::room`) weighs.
if let Some([budget, used, blocks, buffers, targets, line]) =
crate::resource::room_terms(host().and_then(|h| h.video_memory()))
{
let weighed = used.saturating_sub(blocks) + buffers + targets;
tracing::info!(
"the texture queue's room: {used} MB in use - {blocks} MB free in texture blocks + {buffers} MB kept for \
card copies of title buffers + {targets} MB kept for render targets = {weighed} MB against a line of \
{line} MB ({} % of a budget of {budget} MB): {}",
crate::resource::room_percent(),
if weighed < line { "room" } else { "no room, new textures wait" }
);
}
let [looks, mapped, same, made, all] =
[0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURE_MICROS[i].swap(0, Ordering::Relaxed) / 1000);
if all > 0 {
tracing::info!(
"the pass over textures picked by index, in the last 5 seconds: {all} ms in all, of them {looks} ms looking again at slots uploaded whole, {mapped} ms asking what of a texture's memory is mapped, {same} ms asking whether a host copy holds what memory holds, {made} ms making host copies and staging uploads; uploaded since the start: {} textures, {} MB",
crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20
);
}
}
if crate::resource::held_only() {
let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
+155 -3
View File
@@ -1556,6 +1556,55 @@ pub(crate) fn alias_of(this: This) -> Option<This> {
same.then_some(other)
}
/// Says (once per kind of pair, at most 64 lines) that the texture the
/// title placed at `address` ([`texture_at`]), `this`, lies inside the
/// memory of a texture the host renders to or writes without starting
/// where that texture starts. [`alias_of`] finds only a view at the very
/// start; one placed further in (a level, a layer, a corner of an atlas) is
/// filled from title memory, which the host's writes never reach: what
/// lay there before (another texture's bytes) or zeros. Diagnostics for
/// textures that read as noise or black where the title rendered them.
#[cfg(windows)]
fn placed_inside_target(address: u64, this: This) {
let hit = {
let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
targets.range(..address).next_back().map(|(&start, &other)| (start, other))
};
let Some((start, other)) = hit else {
return;
};
let (r, o) = (resource(this), resource(other as This));
let Some(size) = footprint(&o.desc).map(|f| f.size) else {
return;
};
if address >= start.saturating_add(size) {
return;
}
static SAID: std::sync::Mutex<std::collections::BTreeSet<[u32; 8]>> =
std::sync::Mutex::new(std::collections::BTreeSet::new());
let pair = [
r.desc.width as u32,
r.desc.height,
r.desc.format,
u32::from(r.desc.mip_levels),
o.desc.width as u32,
o.desc.height,
o.desc.format,
u32::from(o.desc.mip_levels),
];
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if said.len() < 64 && said.insert(pair) {
tracing::warn!(
view = ?this,
texture = ?other,
offset = format_args!("{:#x}", address - start),
target_bytes = size,
target_flags = format_args!("{:#x}", o.desc.flags),
"a placed texture lies inside the memory of a texture the host writes, not at its start: it is filled from title memory, which the host's writes never reach (width, height, format, levels of each): {pair:?}"
);
}
}
/// Whether host copies are made on first use. On by default;
/// `VICTORY_LAZY_TEXTURES=0` makes each when the title creates its texture,
/// as before.
@@ -1799,9 +1848,19 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
/// 238), and the queue was refused from the first world frame on. With
/// their room kept, the queue stops that much earlier while the world
/// loads and gets it back as the targets are made.
///
/// Once the world's targets are made (half of the reserve or more) and
/// have not grown by 64 MiB for `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS`
/// (20,000; 0: kept for the run, as before), nothing is kept: at 1440p the
/// targets level off at 2.1-2.9 GB, and the rest of the 3,072 MB (990 MB
/// at the first world frame, 160-640 MB in play) stayed reserved for
/// targets that never came while thousands of textures waited for room
/// (2026-11-26 diag run 16:28, 10:59:54: 8,722 MB in use + 836 MB kept
/// for targets against a line of 9,527 MB). The reserve comes back when
/// the targets grow by 64 MiB again (a new scene's), for as long again.
#[cfg(windows)]
pub(crate) fn targets_room_kept() -> u64 {
use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let most = *MOST.get_or_init(|| {
std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB")
@@ -1809,9 +1868,76 @@ pub(crate) fn targets_room_kept() -> u64 {
.and_then(|v| v.trim().parse::<u64>().ok())
.map_or(3072 << 20, |mb| mb.min(8192) << 20)
});
static SETTLE: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let settle = *SETTLE.get_or_init(|| {
std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS")
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
.unwrap_or(20_000)
});
// Every host texture's bytes less those of the copies the title fills.
let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed));
most.saturating_sub(targets)
// The targets' bytes at their last change of 64 MiB or more, and when
// they last grew by that much.
static GREW: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
let now = crate::host::now_ms();
let (last, since) = (GREW[0].load(Relaxed), GREW[1].load(Relaxed));
let (last, since) = targets_seen(last, since, targets, now);
GREW[0].store(last, Relaxed);
GREW[1].store(since, Relaxed);
targets_kept(most, targets, now.saturating_sub(since), settle)
}
/// [`targets_room_kept`]'s record of the targets' bytes (`last`) and of
/// when they last grew by 64 MiB (`since`, ms), with `targets` now: a fall
/// of 64 MiB lowers the record (so that growing back counts as growth), a
/// growth of 64 MiB raises it and restarts the clock.
#[cfg(any(windows, test))]
fn targets_seen(last: u64, since: u64, targets: u64, now: u64) -> (u64, u64) {
const STEP: u64 = 64 << 20;
if targets >= last.saturating_add(STEP) {
(targets, now)
} else if targets.saturating_add(STEP) <= last {
(targets, since)
} else {
(last, since)
}
}
/// What [`targets_room_kept`] keeps of `most`: what the targets do not
/// hold yet, or nothing once they hold half of it or more and have not
/// grown for `settle` ms (`still_ms`; `settle` 0: always kept).
#[cfg(any(windows, test))]
fn targets_kept(most: u64, targets: u64, still_ms: u64, settle: u64) -> u64 {
if settle > 0 && targets >= most / 2 && still_ms >= settle {
0
} else {
most.saturating_sub(targets)
}
}
/// What [`room`] weighs now, in MB, for the log: the card's budget, its
/// use, the free part of the texture blocks, what is kept for card copies
/// of title buffers and for render targets, and the line. `None` without
/// the system's numbers, or under `VICTORY_TEXTURE_BUDGET_MB` (which
/// weighs the textures' own bytes instead).
#[cfg(windows)]
pub(crate) fn room_terms(memory: Option<[u64; 4]>) -> Option<[u64; 6]> {
if std::env::var_os("VICTORY_TEXTURE_BUDGET_MB").is_some() {
return None;
}
let [budget, used, ..] = memory?;
Some(
[
budget,
used,
crate::pool::texture_room(),
crate::shadow::card_room_kept(),
targets_room_kept(),
budget / 100 * room_percent(),
]
.map(|bytes| bytes >> 20),
)
}
/// [`room`] as it was at most a tenth of a second ago, for a question
@@ -1840,7 +1966,7 @@ pub(crate) fn room_lately() -> bool {
/// 1 MiB up take 449 MB more of the card than before (941 against 492),
/// and 94 gives the textures about that much back.
#[cfg(windows)]
fn room_percent() -> u64 {
pub(crate) fn room_percent() -> u64 {
static PERCENT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
*PERCENT.get_or_init(|| {
std::env::var("VICTORY_TEXTURE_ROOM_PERCENT")
@@ -3159,6 +3285,7 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
}
map.insert((address, *desc), out as usize);
crate::texture::placed_in_host_written(address, desc);
placed_inside_target(address, out);
resource(out)
.host
.placed
@@ -4623,6 +4750,31 @@ float4 lit() : SV_Target { return 1.0; }
assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB);
}
/// The room kept for render targets goes once the world's targets are
/// made and have stopped growing, and comes back when they grow again.
#[test]
fn room_for_targets_is_given_up_once_they_settle() {
const MIB: u64 = 1 << 20;
let most = 3072 * MIB;
// Before the world: kept, however long.
assert_eq!(targets_kept(most, 652 * MIB, 60_000, 20_000), 2420 * MIB);
// The world's first frames: still growing.
assert_eq!(targets_kept(most, 2083 * MIB, 5_000, 20_000), 989 * MIB);
// Settled: nothing kept.
assert_eq!(targets_kept(most, 2432 * MIB, 20_000, 20_000), 0);
// `VICTORY_CARD_ROOM_FOR_TARGETS_SETTLE_MS=0`: kept as before.
assert_eq!(targets_kept(most, 2432 * MIB, 600_000, 0), 640 * MIB);
// Growth of 64 MiB restarts the clock; less does not.
assert_eq!(targets_seen(2000 * MIB, 1_000, 2050 * MIB, 9_000), (2000 * MIB, 1_000));
assert_eq!(targets_seen(2000 * MIB, 1_000, 2064 * MIB, 9_000), (2064 * MIB, 9_000));
// A fall lowers the record without restarting it, so growing back
// counts as growth.
let (last, since) = targets_seen(2400 * MIB, 1_000, 1000 * MIB, 9_000);
assert_eq!((last, since), (1000 * MIB, 1_000));
assert_eq!(targets_seen(last, since, 2400 * MIB, 30_000), (2400 * MIB, 30_000));
}
/// A placed texture viewed from a later level has a host copy of that
/// and the smaller levels; a view from an earlier one gets another.
#[cfg(windows)]
+60
View File
@@ -401,6 +401,27 @@ fn fill_unlocked() -> bool {
/// got less than was mapped (their slots are looked at again).
pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// Since the last frame-rate line, exact refreshes (for a bake) that found
/// the runtime remapping title memory ([`exact_unlocked`]): read whole
/// through the kernel without waiting, and those that had to wait (a page
/// was not there).
pub(crate) static EXACT_UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
/// Whether an exact refresh (the uploads before a bake, `BAKING`) that
/// finds the runtime remapping title memory first reads the texture whole
/// through the kernel, and waits for the remapping to end only if a page of
/// it is not there (`VICTORY_EXACT_NO_WAIT=0`: it always waits, as before).
/// A read through the kernel that succeeds got every byte as title memory
/// holds it at that moment, which is what waiting gave; it fails, rather
/// than reading something else, where a page is away. Waiting made the
/// texture refreshes of a cutscene second 866 ms a frame, 808 of them
/// waiting for title memory to hold still (diag run of 2026-11-26 15:58,
/// with `VICTORY_TEXTURE_NO_WAIT=1`, where only exact refreshes wait).
fn exact_unlocked() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_NO_WAIT").is_none_or(|v| v != "0"))
}
/// Since the last frame-rate line, of texture refreshes on every thread, in
/// microseconds: waiting for the texture's own lock (another thread is
/// refreshing the same texture), asking the write watch and the guards,
@@ -1342,6 +1363,19 @@ impl Staging {
return self.refresh_unlocked(last, size);
};
mapped
} else if exact && exact_unlocked() {
match crate::watch::title_memory_reading_now() {
Some(mapped) => mapped,
None => match self.refresh_exact_unlocked(last, size) {
Some(read) => {
if read {
found_blind(last);
}
return size;
}
None => waited(2, crate::watch::title_memory_reading),
},
}
} else {
waited(2, crate::watch::title_memory_reading)
};
@@ -1447,6 +1481,32 @@ impl Staging {
}
}
/// An exact refresh (for a bake) that finds the runtime remapping
/// title memory ([`exact_unlocked`]): the texture is read whole through
/// the kernel, which needs no lock and fails if a page of it is not
/// there; read, it is what title memory holds now, as a read under the
/// lock would be. `Some(changed)` if read (and detiled if it changed),
/// `None` if a page was missing: then the refresh waits for the lock
/// as before.
fn refresh_exact_unlocked(&self, last: &mut Last, size: usize) -> Option<bool> {
use std::sync::atomic::Ordering::Relaxed;
let mut changed = false;
let read = with_read(size, |read| {
if !crate::host::read_into(self.memory, read) {
return false;
}
let hash = digest(read);
if last.hash != Some(hash) {
last.hash = Some(hash);
self.detile(read);
changed = true;
}
true
});
EXACT_UNLOCKED[usize::from(!read)].fetch_add(1, Relaxed);
read.then_some(changed)
}
/// The first filling of the staging buffer while the runtime is
/// remapping title memory, of a texture not all of which can be read:
/// with the pages that are there, zeros for the others, as a partly