Files
EonaCat.XSBox/crates/graphics/src/host/panel.rs
T
EonaCat 1b0d534e6c
Rust validation / Formatting (push) Failing after 27s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s
Rust validation / Windows x64 build and tests (push) Canceled after 0s
Initial
2026-12-04 21:03:25 +01:00

1414 lines
51 KiB
Rust

use std::sync::{Once, OnceLock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_F11, VK_F7, VK_F8};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
use super::font::{Canvas, Face, Rgb, border, bpp, layout_scale, s, shadow, text_px, theme, ui_scale};
use super::{Host, HostList, transition};
const EVERY: Duration = Duration::from_millis(500);
const COLUMNS: u32 = 40;
const GRAPHS: usize = 4;
const HISTORY: usize = 240;
const GRAPH_NAMES: [&str; GRAPHS] = ["FPS/60", "CPU", "RAM/PC", "VRAM"];
const GRAPH_COLOURS: [Rgb; GRAPHS] = [theme::CYAN, theme::PINK, theme::AMBER, theme::MINT];
const UPLOADS: usize = 4;
fn asked() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| crate::switch::on("EONACAT_XS_PANEL"))
}
pub(super) fn shown() -> &'static AtomicBool {
static SHOWN: OnceLock<AtomicBool> = OnceLock::new();
SHOWN.get_or_init(|| AtomicBool::new(asked()))
}
fn pressed() -> bool {
static DOWN: AtomicBool = AtomicBool::new(false);
let down = unsafe { GetAsyncKeyState(i32::from(VK_F11)) } < 0;
if DOWN.swap(down, Ordering::Relaxed) || !down {
return false;
}
let mut process = 0;
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
process == std::process::id()
}
fn watch_f3() {
static WATCH: Once = Once::new();
WATCH.call_once(|| {
let _ = std::thread::Builder::new().name("panel keys".into()).spawn(|| loop {
std::thread::sleep(Duration::from_millis(10));
if pressed() {
shown().fetch_xor(true, Ordering::Relaxed);
}
});
});
}
fn flush_pressed() -> Option<u8> {
static DOWN: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2];
let mut asked = None;
let keys = [
(VK_F8, crate::resource::FLUSH_SOFT),
(VK_F7, crate::resource::FLUSH_HARD),
];
for (was, (key, kind)) in DOWN.iter().zip(keys) {
let down = unsafe { GetAsyncKeyState(i32::from(key)) } < 0;
if !was.swap(down, Ordering::Relaxed) && down {
asked = Some(kind);
}
}
let kind = asked?;
let mut process = 0;
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
(process == std::process::id()).then_some(kind)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
Stats,
Notice(u32, u32),
Advisor,
}
const STATS_WIDTH: u32 = 280;
struct StatsMost {
rows: u32,
meters: u32,
small: u32,
sections: u32,
}
const STATS_MOST: StatsMost = StatsMost { rows: 17, meters: 5, small: 6, sections: 8 };
fn box_size(kind: Kind, pct: u32) -> (u32, u32) {
let lp = layout_scale(pct);
match kind {
Kind::Stats => {
let m = stats_measures(pct);
let most = STATS_MOST;
let graphs = GRAPHS as u32 * (m.graph + m.graph_gap) - m.graph_gap;
let body = m.hero + m.hero_gap + most.rows * m.step + most.meters * m.meter_extra + most.small * m.small_step + most.sections * m.section;
(m.width, m.top + body + graphs + m.bottom)
}
Kind::Notice(columns, lines) => {
let (_, top, _, step) = notice_measures(pct);
(s((columns.max(20) * 9 + 28).min(560), lp), top + lines.max(1) * step + s(6, lp))
}
Kind::Advisor => {
let (_, top, _, step) = advisor_measures(pct);
(s(610, lp), top + (ADVICE_LINES + FIRST_START.len()) as u32 * step + s(6, lp))
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Parts {
fps: bool,
game: bool,
picture: bool,
gpu: bool,
memory: bool,
cpu: bool,
specs: bool,
cost: bool,
graphs: bool,
}
fn parts() -> Parts {
let on = |var: &str, default: bool| match std::env::var(var).as_deref() {
Ok("0") => false,
Ok("1") => true,
_ => default,
};
Parts {
fps: on("EONACAT_XS_PANEL_FPS", true),
game: on("EONACAT_XS_PANEL_GAME", true),
picture: on("EONACAT_XS_PANEL_PICTURE", true),
gpu: on("EONACAT_XS_PANEL_GPU", true),
memory: on("EONACAT_XS_PANEL_MEMORY", true),
cpu: on("EONACAT_XS_PANEL_CPU", true),
specs: on("EONACAT_XS_PANEL_SPECS", true),
cost: on("EONACAT_XS_PANEL_COST", false),
graphs: on("EONACAT_XS_PANEL_GRAPHS", true),
}
}
#[derive(Clone, Copy, Default)]
struct Counters([u64; COUNTERS]);
const COUNTERS: usize = 11;
impl Counters {
fn now() -> Counters {
use super::{CARD_CLOCK_US, COPY_BACK, PREPARING};
#[cfg(feature = "diagnostics")]
let recording = crate::copystat::peek(crate::copystat::C::RecordNs);
#[cfg(not(feature = "diagnostics"))]
let recording = 0;
let get = |a: &std::sync::atomic::AtomicU64| a.load(Ordering::Relaxed);
Counters([
super::worked(),
get(&CARD_CLOCK_US[0]),
get(&CARD_CLOCK_US[1]),
get(&CARD_CLOCK_US[2]),
get(&PREPARING[3]),
get(&COPY_BACK[0]),
get(&COPY_BACK[1]),
get(&crate::shadow::CARD_STATS[0]),
crate::draw::dropped_now(),
recording,
crate::draw::drawn(),
])
}
fn since(self, before: Counters, frames: f64) -> [f64; COUNTERS] {
let mut out = [0.0; COUNTERS];
for (i, out) in out.iter_mut().enumerate() {
let (was, is) = (before.0[i], self.0[i]);
*out = if is >= was { is - was } else { is } as f64 / frames;
}
out
}
}
pub(super) fn process_memory() -> (u64, u64) {
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut c = PROCESS_MEMORY_COUNTERS {
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
..Default::default()
};
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
(c.WorkingSetSize as u64, c.PagefileUsage as u64)
}
pub(super) fn pc_memory() -> (u64, u64, u64) {
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
m.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
unsafe { GlobalMemoryStatusEx(&mut m) };
(m.ullAvailPhys, m.ullTotalPhys, m.ullAvailPageFile)
}
fn cpu_times() -> (u64, u64, u64) {
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes, GetSystemTimes};
let t = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32) | u64::from(f.dwLowDateTime);
let z = || FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
let (mut created, mut exited, mut kernel, mut user) = (z(), z(), z(), z());
unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) };
let (mut idle, mut sys_kernel, mut sys_user) = (z(), z(), z());
unsafe { GetSystemTimes(&mut idle, &mut sys_kernel, &mut sys_user) };
(t(kernel) + t(user), t(idle), t(sys_kernel) + t(sys_user))
}
fn cpu_percent(before: (u64, u64, u64), now: (u64, u64, u64), seconds: f64, cores: f64) -> (f64, f64) {
let ours = now.0.saturating_sub(before.0) as f64 / 1e7;
let game = 100.0 * ours / (seconds * cores).max(1e-9);
let (idle, all) = (now.1.saturating_sub(before.1) as f64, now.2.saturating_sub(before.2) as f64);
let pc = if all > 0.0 { 100.0 * (all - idle) / all } else { 0.0 };
(game.clamp(0.0, 100.0), pc.clamp(0.0, 100.0))
}
#[derive(Clone, Copy, Default)]
struct Pc {
cpu_game: f64,
cpu_pc: f64,
free: u64,
total: u64,
commit_left: u64,
}
#[derive(Clone, Debug, PartialEq)]
enum StatRow {
Hero { fps: String, color: Rgb, frame: String, longest: String },
Metric { label: String, value: String, color: Rgb, bold: bool, small: bool, meter: Option<f32> },
Line(String),
Section(&'static str),
}
fn metric(label: &str, value: String, color: Rgb) -> StatRow {
StatRow::Metric { label: label.to_owned(), value, color, bold: false, small: false, meter: None }
}
fn metered(label: &str, value: String, color: Rgb, ratio: f64) -> StatRow {
let ratio = if ratio.is_finite() { ratio.clamp(0.0, 1.0) as f32 } else { 0.0 };
StatRow::Metric { label: label.to_owned(), value, color, bold: false, small: false, meter: Some(ratio) }
}
fn fps_colour(fps: f64) -> Rgb {
if fps >= 55.0 {
theme::TEXT
} else if fps >= 30.0 {
theme::CYAN
} else if fps >= 20.0 {
theme::AMBER
} else {
theme::CORAL
}
}
fn generated(fps: f64, reading: crate::streamline::FramegenReading) -> StatRow {
use crate::streamline::FramegenReading;
let (label, value, color) = match reading {
FramegenReading::Off => ("FRAME GEN".to_owned(), "OFF".to_owned(), theme::MUTED),
FramegenReading::Dlss(None) => ("FRAME GEN".to_owned(), "WAITING FOR PRESENT".to_owned(), theme::AMBER),
FramegenReading::Dlss(Some(per)) => (format!("FRAME GEN {per}X"), format!("SHOWN {:.1} FPS", fps * f64::from(per)), theme::MINT),
FramegenReading::Fsr => ("FSR 3 FRAME GEN".to_owned(), "TARGET 2X".to_owned(), theme::MINT),
};
StatRow::Metric { label, value, color, bold: true, small: false, meter: None }
}
fn upscaler(dlss: Option<(&str, Option<char>)>) -> StatRow {
match dlss {
Some((mode, Some(preset))) => metric("DLSS", format!("{mode} PRESET {preset}").to_uppercase(), theme::CYAN),
Some((mode, None)) => metric("DLSS", mode.to_uppercase(), theme::CYAN),
None => metric("DLSS", "OFF THE TITLE UPSCALES".to_owned(), theme::MUTED),
}
}
struct Numbers {
ms: f64,
worst: f64,
cost: f64,
c: [f64; COUNTERS],
pc: Pc,
private: u64,
budget: u64,
used: u64,
shared: u64,
console: &'static str,
build: String,
scene: Option<[u32; 2]>,
output: [u32; 2],
upscaler: StatRow,
framegen: StatRow,
rays: (&'static str, bool),
specs: Vec<String>,
}
fn rows(n: &Numbers, parts: Parts) -> Vec<StatRow> {
let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64;
let size = |[w, h]: [u32; 2]| format!("{w}X{h}");
let (ms, c, pc) = (n.ms, &n.c, n.pc);
let idle = (c[1] / 1e3).min(ms);
let fps = 1e3 / ms.max(0.001);
let small = |label: &str, value: String| StatRow::Metric { label: label.to_owned(), value, color: theme::MUTED, bold: false, small: true, meter: None };
let mut groups: Vec<(Option<&'static str>, Vec<StatRow>)> = Vec::new();
if parts.fps {
groups.push((
None,
vec![StatRow::Hero { fps: format!("{fps:.1}"), color: fps_colour(fps), frame: format!("{ms:.1} MS"), longest: format!("{:.0} MS", n.worst) }],
));
}
if parts.game {
groups.push((Some("SESSION"), vec![metric("CONSOLE", n.console.to_owned(), theme::TEXT), metric("BUILD", n.build.to_uppercase().chars().take(28).collect(), theme::MUTED)]));
}
if parts.picture {
let mut group = Vec::new();
if let Some(scene) = n.scene {
group.push(metric("SCENE", size(scene), theme::TEXT));
}
group.push(metric("OUTPUT", size(n.output), theme::TEXT));
group.push(n.upscaler.clone());
group.push(n.framegen.clone());
let (rays, on) = n.rays;
group.push(StatRow::Metric { label: "RAY TRACING".to_owned(), value: rays.to_owned(), color: if on { theme::PINK } else { theme::MUTED }, bold: on, small: false, meter: None });
groups.push((Some("PICTURE"), group));
}
if parts.gpu {
let dropped = if c[8] >= 1.0 { theme::CORAL } else { theme::MINT };
groups.push((
Some("GPU"),
vec![
metered("GPU BUSY", format!("{:.1} MS", ms - idle), theme::TEXT, (ms - idle) / ms.max(0.001)),
metric("WAITS FOR GPU", format!("{:.1} MS", c[3] / 1e3), theme::TEXT),
metric("DRAWS", format!("{:.0}", c[10]), theme::TEXT),
metric("DROPPED", format!("{:.0}", c[8]), dropped),
],
));
}
if parts.memory {
let vram = if n.budget > 0 && n.used as f64 > n.budget as f64 * 0.85 { theme::CORAL } else { theme::TEXT };
let share = |a: u64, b: u64| if b == 0 { 0.0 } else { a as f64 / b as f64 };
groups.push((
Some("MEMORY"),
vec![
metered("GAME RAM", format!("{:.1} GB", gb(n.private)), theme::TEXT, share(n.private, pc.total)),
metered("VRAM", format!("{:.1}/{:.1} GB", gb(n.used), gb(n.budget)), vram, share(n.used, n.budget)),
metric("SHARED", format!("{:.1} GB", gb(n.shared)), theme::MUTED),
],
));
}
if parts.cpu {
let free = if pc.free < (3u64 << 30) { theme::AMBER } else { theme::TEXT };
groups.push((
Some("PROCESSOR"),
vec![
metered("CPU GAME", format!("{:.0}%", pc.cpu_game), theme::TEXT, pc.cpu_game / 100.0),
metered("CPU PC", format!("{:.0}%", pc.cpu_pc), theme::TEXT, pc.cpu_pc / 100.0),
metric("FREE RAM", format!("{:.1}/{:.0} GB", gb(pc.free), gb(pc.total)), free),
small("RAM + PAGE FILE LEFT", format!("{:.1} GB", gb(pc.commit_left))),
],
));
}
if parts.specs && !n.specs.is_empty() {
groups.push((Some("YOUR PC"), n.specs.iter().map(|line| StatRow::Line(line.chars().take(COLUMNS as usize).collect())).collect()));
}
if parts.cost {
groups.push((Some("OVERHEAD"), vec![small("THIS PANEL", format!("{:.0} US A FRAME", n.cost))]));
}
let mut out = Vec::new();
for (title, group) in groups {
if let Some(title) = title {
out.push(StatRow::Section(title));
}
out.extend(group);
}
out
}
#[allow(clippy::too_many_arguments)]
fn numbers(c: [f64; COUNTERS], ms: f64, worst: f64, cost: f64, pc: Pc, output: (u32, u32), host: &Host, parts: Parts) -> Numbers {
let (_, private) = process_memory();
let [budget, used, _, shared] = host.video_memory().unwrap_or_default();
let console = match crate::console::current() {
crate::console::Console::SeriesS => "SERIES S",
crate::console::Console::SeriesX => "SERIES X",
};
let dlss = crate::streamline::upscaled_lately();
let rays = if crate::hwrt::active() {
("HARDWARE (DXR)", true)
} else if std::env::var_os("EONACAT_XS_BVH_BUILDER").is_some_and(|v| v == "1") {
("SOFTWARE", true)
} else {
("OFF", false)
};
Numbers {
ms,
worst,
cost,
c,
pc,
private,
budget,
used,
shared,
console,
build: env!("EONACAT_XS_BUILD").to_owned(),
scene: dlss.map(|(_, scene, ..)| scene),
output: dlss.map_or([output.0, output.1], |(_, _, out, _)| out),
upscaler: upscaler(dlss.map(|(mode, _, _, preset)| (mode, preset))),
framegen: generated(1e3 / ms.max(0.001), crate::streamline::framegen_reading()),
rays,
specs: if parts.specs { super::specs::lines(host, COLUMNS as usize) } else { Vec::new() },
}
}
#[derive(Clone, Copy)]
struct StatsMeasures {
width: u32,
pad: u32,
title: u32,
top: u32,
bottom: u32,
face: u32,
step: u32,
small_face: u32,
small_step: u32,
hero: u32,
hero_face: u32,
hero_side: u32,
hero_caption: u32,
hero_gap: u32,
section: u32,
section_face: u32,
meter: u32,
meter_extra: u32,
graph: u32,
graph_gap: u32,
}
fn stats_measures(pct: u32) -> StatsMeasures {
let lp = layout_scale(pct);
let title = s(24, lp);
StatsMeasures {
width: s(STATS_WIDTH, lp),
pad: s(12, lp),
title,
top: bar(pct) + title,
bottom: s(10, lp),
face: text_px(12, pct),
step: s(16, lp),
small_face: text_px(10, pct),
small_step: s(14, lp),
hero: s(54, lp),
hero_face: text_px(34, pct),
hero_side: text_px(12, pct),
hero_caption: text_px(9, pct),
hero_gap: s(2, lp),
section: s(26, lp),
section_face: text_px(9, pct),
meter: s(3, lp).max(2),
meter_extra: s(7, lp),
graph: s(26, lp),
graph_gap: s(5, lp),
}
}
fn row_height(row: &StatRow, m: &StatsMeasures) -> u32 {
match row {
StatRow::Hero { .. } => m.hero + m.hero_gap,
StatRow::Metric { small: false, meter: Some(_), .. } => m.step + m.meter_extra,
StatRow::Metric { small: false, .. } => m.step,
StatRow::Metric { small: true, .. } | StatRow::Line(_) => m.small_step,
StatRow::Section(_) => m.section,
}
}
#[derive(Debug, PartialEq)]
struct StatsPlaces {
rows: Vec<u32>,
graphs: Vec<u32>,
height: u32,
}
fn stats_places(rows: &[StatRow], graphs: bool, pct: u32) -> StatsPlaces {
let m = stats_measures(pct);
let mut y = m.top;
let mut tops = Vec::with_capacity(rows.len());
for row in rows {
tops.push(y);
y += row_height(row, &m);
}
let mut graph_tops = Vec::new();
if graphs {
if !rows.is_empty() {
y += m.section;
}
for _ in 0..GRAPHS {
graph_tops.push(y);
y += m.graph + m.graph_gap;
}
y -= m.graph_gap;
}
StatsPlaces { rows: tops, graphs: graph_tops, height: y + m.bottom }
}
fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
let t = t.clamp(0.0, 1.0);
let part = |x: u8, y: u8| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8;
(part(a.0, b.0), part(a.1, b.1), part(a.2, b.2))
}
fn sweep(c: &mut Canvas, x0: u32, y0: u32, x1: u32, y1: u32, a: Rgb, b: Rgb) {
let span = x1.saturating_sub(x0).saturating_sub(1).max(1) as f32;
for x in x0..x1 {
c.fill_rect(x, y0, x + 1, y1, mix(a, b, (x - x0) as f32 / span));
}
}
fn meter_colour(ratio: f32, t: f32) -> Rgb {
if ratio >= 0.9 {
mix(theme::AMBER, theme::CORAL, t)
} else if ratio >= 0.75 {
mix(theme::BORDER, theme::AMBER, t)
} else {
mix(theme::BORDER, theme::CYAN, t)
}
}
fn graph_value(index: usize, sample: f32) -> String {
if index == 0 { format!("{:.0}", sample * 60.0) } else { format!("{:.0}%", sample * 100.0) }
}
fn lowered(y: u32, big: u32, small: u32) -> i32 {
(y + big.saturating_sub(small)) as i32
}
fn render_stats(rows: &[StatRow], graphs: Option<&[Vec<f32>]>, pct: u32) -> Option<(Canvas, u32)> {
let (w, most) = box_size(Kind::Stats, pct);
let mut c = Canvas::new(w, most)?;
let m = stats_measures(pct);
let places = stats_places(rows, graphs.is_some(), pct);
let height = places.height.min(most);
let line = border(pct);
let shade = shadow(pct);
let (left, right) = (m.pad as i32, (w - m.pad) as i32);
c.clear(theme::BG);
let bar_h = bar(pct);
c.fill_rect(0, bar_h, w, m.top, theme::GRAPH_BG);
c.fill_rect(0, m.top - line, w, m.top, theme::DIVIDER);
let head = Face::head(text_px(12, pct));
let name_y = (bar_h + m.title.saturating_sub(head.px) / 2) as i32 - 1;
c.text(left, name_y, "EONACAT", head, theme::TEXT, shade);
let after = c.text_width("EONACAT ", head);
c.text(left + after, name_y, "XS", head, theme::PINK, shade);
let hint = Face::mono(m.hero_caption, false);
c.text_right(right, (bar_h + m.title.saturating_sub(hint.px) / 2) as i32, "F11 HIDES", hint, theme::MUTED, 0);
for (row, &y) in rows.iter().zip(&places.rows) {
match row {
StatRow::Hero { fps, color, frame, longest } => {
sweep(&mut c, 0, y, w, y + m.hero, theme::ROW_HI, theme::BG);
c.fill_rect(0, y + m.hero - line, w, y + m.hero, theme::DIVIDER);
let big = Face::mono(m.hero_face, true);
let number_y = y + m.hero.saturating_sub(m.hero_face) / 2;
c.text(left, number_y as i32, fps, big, *color, shade);
let caption = Face::mono(m.hero_caption, true);
let unit_x = left + c.text_width(fps, big) + m.pad as i32 / 2;
c.text(unit_x, lowered(number_y, m.hero_face, m.hero_caption), "FPS", caption, theme::MUTED, shade);
let side = Face::mono(m.hero_side, true);
let lines = [("FRAME TIME", frame, theme::TEXT), ("LONGEST", longest, theme::MUTED)];
let block = 2 * m.hero_side + m.hero_side / 2;
let first = y + m.hero.saturating_sub(block) / 2;
for (i, (name, value, tint)) in lines.into_iter().enumerate() {
let top = first + i as u32 * (m.hero_side + m.hero_side / 2);
let room = right - unit_x - c.text_width("FPS", caption) - m.pad as i32;
let value = c.fitted(value, side, room.max(0));
let at = right - c.text_width(value, side);
c.text_right(right, top as i32, value, side, tint, shade);
c.text_right(at - m.pad as i32 / 2, lowered(top, m.hero_side, m.hero_caption), name, caption, theme::MUTED, shade);
}
}
StatRow::Metric { label, value, color, bold, small, meter } => {
let px = if *small { m.small_face } else { m.face };
let name = if *small { theme::MUTED } else { theme::LABEL };
c.text(left, y as i32, label, Face::mono(px, false), name, shade);
let room = right - left - c.text_width(label, Face::mono(px, false)) - c.text_width(" ", Face::mono(px, false));
let value = c.fitted(value, Face::mono(px, *bold), room);
c.text_right(right, y as i32, value, Face::mono(px, *bold), *color, shade);
if let (Some(ratio), false) = (*meter, *small) {
let (x0, x1) = (m.pad, w - m.pad);
let at = y + m.step;
c.fill_rect(x0, at, x1, at + m.meter, theme::DIVIDER);
let filled = ((x1 - x0) as f32 * ratio).round() as u32;
if filled > 0 {
sweep_with(&mut c, x0, at, x0 + filled, at + m.meter, ratio, x1 - x0);
let tip = (2 * line).min(filled);
c.fill_rect(x0 + filled - tip, at, x0 + filled, at + m.meter, mix(meter_colour(ratio, 1.0), theme::TEXT, 0.55));
}
}
}
StatRow::Line(text) => {
let face = Face::mono(m.small_face, false);
let text = c.fitted(text, face, right - left);
c.text(left, y as i32, text, face, theme::MUTED, shade);
}
StatRow::Section(title) => {
let face = Face::mono(m.section_face, true);
let text_y = y + m.section.saturating_sub(face.px + m.section / 8);
c.fill_rect(m.pad, text_y + 1, m.pad + (2 * line).max(2), text_y + face.px, theme::PINK);
let x = left + (2 * line).max(2) as i32 + m.pad as i32 / 2;
c.text(x, text_y as i32, title, face, theme::MUTED, 0);
let from = (x + c.text_width(title, face) + m.pad as i32 / 2).max(0) as u32;
c.fill_rect(from, text_y + face.px / 2, w - m.pad, text_y + face.px / 2 + line, theme::DIVIDER);
}
}
}
if let Some(history) = graphs {
if let (Some(&first), false) = (places.graphs.first(), rows.is_empty()) {
let face = Face::mono(m.section_face, true);
let text_y = first - m.section + m.section.saturating_sub(face.px + m.section / 8);
c.fill_rect(m.pad, text_y + 1, m.pad + (2 * line).max(2), text_y + face.px, theme::PINK);
let x = left + (2 * line).max(2) as i32 + m.pad as i32 / 2;
c.text(x, text_y as i32, "HISTORY", face, theme::MUTED, 0);
let from = (x + c.text_width("HISTORY", face) + m.pad as i32 / 2).max(0) as u32;
c.fill_rect(from, text_y + face.px / 2, w - m.pad, text_y + face.px / 2 + line, theme::DIVIDER);
}
let (x0, x1) = (m.pad, w - m.pad);
let across = x1 - x0;
let cap = (2 * line).max(2);
for (i, &top) in places.graphs.iter().enumerate() {
let bottom = top + m.graph;
c.fill_rect(x0, top, x1, bottom, theme::GRAPH_BG);
c.fill_rect(x0, top + m.graph / 2, x1, top + m.graph / 2 + line, theme::DIVIDER);
let samples = history.get(i).map_or(&[][..], Vec::as_slice);
let body = mix(theme::GRAPH_BG, GRAPH_COLOURS[i], 0.28);
let mut before: Option<u32> = None;
for dx in 0..across {
let back = ((across - 1 - dx) as usize * HISTORY) / across as usize;
let Some(&value) = samples.len().checked_sub(1 + back).and_then(|k| samples.get(k)) else { continue };
let high = (value.clamp(0.0, 1.0) * m.graph as f32).round() as u32;
c.fill_rect(x0 + dx, bottom - high, x0 + dx + 1, bottom, body);
let (low, up) = match before {
Some(b) => (high.min(b), high.max(b)),
None => (high, high),
};
let line_top = (bottom - up).min(bottom - cap);
let line_bottom = (bottom - low).max(line_top + cap).min(bottom);
c.fill_rect(x0 + dx, line_top, x0 + dx + 1, line_bottom, GRAPH_COLOURS[i]);
before = Some(high);
}
let face = Face::mono(text_px(9, pct), true);
let name = GRAPH_NAMES[i];
let patch = c.text_width(name, face).max(0) as u32 + 2 * line + 2;
c.fill_rect(x0, top, (x0 + patch).min(x1), top + (face.px + 2 * line).min(m.graph), theme::GRAPH_BG);
c.text(x0 as i32 + 2, top as i32, name, face, theme::MUTED, 0);
if let Some(&latest) = samples.last() {
let text = graph_value(i, latest);
let wide = c.text_width(&text, face).max(0) as u32 + 2 * line + 2;
c.fill_rect(x1.saturating_sub(wide).max(x0), top, x1, top + (face.px + 2 * line).min(m.graph), theme::GRAPH_BG);
c.text_right(x1 as i32 - 2, top as i32, &text, face, GRAPH_COLOURS[i], 0);
}
}
}
c.stroke_border(line, height, theme::BORDER);
c.top_gradient_bar(w, bar(pct), theme::PINK, theme::CYAN);
Some((c, height))
}
fn sweep_with(c: &mut Canvas, x0: u32, y0: u32, x1: u32, y1: u32, ratio: f32, whole: u32) {
let span = whole.saturating_sub(1).max(1) as f32;
for x in x0..x1 {
c.fill_rect(x, y0, x + 1, y1, meter_colour(ratio, (x - x0) as f32 / span));
}
}
fn bar(pct: u32) -> u32 {
s(3, layout_scale(pct))
}
fn notice_measures(pct: u32) -> (u32, u32, u32, u32) {
let lp = layout_scale(pct);
(s(14, lp), bar(pct) + s(9, lp), text_px(13, pct), s(18, lp))
}
fn advisor_measures(pct: u32) -> (u32, u32, u32, u32) {
let lp = layout_scale(pct);
(s(14, lp), bar(pct) + s(34, lp), text_px(12, pct), s(17, lp))
}
fn render_notice(lines: &[String], kind: Kind, pct: u32) -> Option<Canvas> {
let (w, h) = box_size(kind, pct);
let columns = match kind {
Kind::Notice(columns, _) => columns as usize,
_ => NOTICE_COLUMNS as usize,
};
let mut c = Canvas::new(w, h)?;
let (left, top, px, step) = notice_measures(pct);
c.clear(theme::BG);
c.stroke_border(border(pct), h, theme::BORDER);
c.top_gradient_bar(w, bar(pct), theme::PINK, theme::CYAN);
for (i, line) in lines.iter().enumerate() {
let text: String = line.chars().take(columns).collect();
let face = Face::mono(px, i == 0);
let text = c.fitted(&text, face, (w - 2 * left) as i32);
let color = if i == 0 { theme::CYAN } else { theme::TEXT };
c.text(left as i32, (top + i as u32 * step) as i32, text, face, color, shadow(pct));
}
Some(c)
}
fn advice_look(index: usize, line: &str) -> (Rgb, bool) {
if index == 0 {
(theme::CYAN, true)
} else if line.starts_with("LIMIT:") || line.starts_with("ALSO:") {
(theme::CORAL, true)
} else if line.starts_with(" TRY:") {
(theme::MINT, false)
} else if line.starts_with("NOTE:") {
(theme::AMBER, false)
} else {
(theme::MUTED, false)
}
}
fn advisor_height(lines: usize, pct: u32) -> u32 {
let (_, top, _, step) = advisor_measures(pct);
(top + lines.max(1) as u32 * step + s(6, layout_scale(pct))).min(box_size(Kind::Advisor, pct).1)
}
fn render_advisor(lines: &[String], pct: u32) -> Option<(Canvas, u32)> {
let (w, most) = box_size(Kind::Advisor, pct);
let mut c = Canvas::new(w, most)?;
let (left, top, px, step) = advisor_measures(pct);
let height = advisor_height(lines.len(), pct);
c.clear(theme::BG);
let bar_h = bar(pct);
let lp = layout_scale(pct);
let strip_bottom = bar_h + s(26, lp);
let line = border(pct);
c.fill_rect(0, bar_h, w, strip_bottom, theme::GRAPH_BG);
c.fill_rect(0, strip_bottom.saturating_sub(line), w, strip_bottom, theme::DIVIDER);
c.stroke_border(line, height, theme::BORDER);
c.top_gradient_bar(w, bar_h, theme::PINK, theme::CYAN);
let head = Face::head(text_px(12, pct));
let name_y = (bar_h + s(26, lp).saturating_sub(head.px) / 2) as i32 - 1;
c.text(left as i32, name_y, "EONACAT", head, theme::TEXT, shadow(pct));
let brand_x = left as i32 + c.text_width("EONACAT ", head);
c.text(brand_x, name_y, "XS", head, theme::PINK, shadow(pct));
let descriptor = Face::mono(text_px(10, pct), false);
let descriptor_x = brand_x + c.text_width("XS", head) + s(10, lp) as i32;
c.text(descriptor_x, name_y, "FRAME ADVISOR", descriptor, theme::MUTED, shadow(pct));
let hint = Face::mono(text_px(10, pct), false);
c.text_right((w - left) as i32, (bar_h + s(26, lp).saturating_sub(hint.px) / 2) as i32, "F10 HIDES", hint, theme::CYAN, 0);
for (i, line) in lines.iter().enumerate() {
let (color, bold) = advice_look(i, line);
let face = Face::mono(px, bold);
let line = c.fitted(line, face, (w - 2 * left) as i32);
c.text(left as i32, (top + i as u32 * step) as i32, line, face, color, shadow(pct));
}
Some((c, height))
}
struct Buffers {
blend: bool,
format: DXGI_FORMAT,
pct: u32,
width: u32,
height: u32,
drawn: u32,
pitch: u32,
uploads: Vec<(ID3D12Resource, *mut u8)>,
card: ID3D12Resource,
turn: usize,
fresh: bool,
}
unsafe impl Send for Buffers {}
impl Buffers {
fn new(host: &Host, kind: Kind, format: DXGI_FORMAT, pct: u32) -> Option<Buffers> {
Self::new_for(host, kind, format, pct, false)
}
fn new_for(host: &Host, kind: Kind, format: DXGI_FORMAT, pct: u32, blend: bool) -> Option<Buffers> {
let (width, height) = box_size(kind, pct);
let bytes_each = if blend { 4 } else { bpp(format)? };
let pitch = (width * bytes_each).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;
unsafe {
host.device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card)
.ok()?;
}
let card = card?;
Some(Buffers { blend, format, pct, width, height, drawn: height, pitch, uploads, card, turn: 0, fresh: false })
}
fn write(&mut self, canvas: &Canvas, drawn: u32) {
if (canvas.width, canvas.height) != (self.width, self.height) {
return;
}
let picture = if self.blend { canvas.pack_see(self.pitch as usize, theme::BG) } else { canvas.pack(self.format, self.pitch as usize) };
let Some(picture) = picture else { return };
self.drawn = drawn.min(self.height);
self.turn = (self.turn + 1) % UPLOADS;
unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) };
self.fresh = true;
}
fn copy(&mut self, list: &ID3D12GraphicsCommandList, back: &ID3D12Resource, at: (u32, u32), (width, height): (u32, u32)) {
let (w, h) = (self.width, self.drawn);
if at.0 >= width || at.1 >= height {
return;
}
unsafe {
if std::mem::take(&mut self.fresh) {
list.CopyResource(&self.card, &self.uploads[self.turn].0);
crate::barstat::rb(list, &[transition(&self.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
}
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&self.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: self.format,
Width: self.width,
Height: self.height,
Depth: 1,
RowPitch: self.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.min(width - at.0), bottom: h.min(height - at.1), back: 1 };
list.CopyTextureRegion(&to, at.0, at.1, 0, &from, Some(&part));
}
}
}
fn corner(pct: u32, (w, h): (u32, u32), (width, height): (u32, u32)) -> (u32, u32) {
let margin = s(10, layout_scale(pct));
(margin.min(width.saturating_sub(w)), margin.min(height.saturating_sub(h)))
}
pub(super) struct Panel {
since: Instant,
frames: u32,
last: Instant,
worst: f64,
cost: Duration,
before: Counters,
rows: Vec<StatRow>,
graphs: bool,
made: bool,
changed: bool,
buffers: Option<Buffers>,
failed: bool,
failed_at: Option<(DXGI_FORMAT, u32)>,
output: (u32, u32),
history: Vec<Vec<f32>>,
cpu: Option<((u64, u64, u64), Instant)>,
}
impl Panel {
pub(super) fn new() -> Panel {
watch_f3();
let now = Instant::now();
Panel {
since: now,
frames: 0,
last: now,
worst: 0.0,
cost: Duration::ZERO,
before: Counters::default(),
rows: Vec::new(),
graphs: false,
made: false,
changed: false,
buffers: None,
failed: false,
failed_at: None,
output: (0, 0),
history: vec![Vec::new(); GRAPHS],
cpu: None,
}
}
fn sample(&mut self, fps: f64, host: &Host) -> Pc {
let now = (cpu_times(), Instant::now());
let cores = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64;
let (cpu_game, cpu_pc) = match self.cpu.replace(now) {
Some((before, at)) => cpu_percent(before, now.0, (now.1 - at).as_secs_f64(), cores),
None => (0.0, 0.0),
};
let (free, total, commit_left) = pc_memory();
let (_, private) = process_memory();
let [budget, used, ..] = host.video_memory().unwrap_or_default();
let ratio = |a: u64, b: u64| if b == 0 { 0.0 } else { a as f32 / b as f32 };
let samples = [(fps / 60.0) as f32, (cpu_game / 100.0) as f32, ratio(private, total), ratio(used, budget)];
for (graph, sample) in self.history.iter_mut().zip(samples) {
if graph.len() == HISTORY {
graph.remove(0);
}
graph.push(sample);
}
Pc { cpu_game, cpu_pc, free, total, commit_left }
}
pub(super) fn frame(&mut self, line: bool) {
if let Some(kind) = flush_pressed() {
crate::resource::ask_flush(kind);
}
if !shown().load(Ordering::Relaxed) {
self.frames = 0;
return;
}
let now = Instant::now();
if self.frames == 0 {
(self.since, self.last, self.worst, self.before) = (now, now, 0.0, Counters::now());
}
self.frames += 1;
self.worst = self.worst.max((now - self.last).as_secs_f64() * 1e3);
self.last = now;
let elapsed = now - self.since;
if elapsed < EVERY && !(line && elapsed * 2 >= EVERY) {
return;
}
let Some(host) = super::host() else { return };
let frames = f64::from(self.frames);
let counters = Counters::now();
let c = counters.since(self.before, frames);
self.before = counters;
let cost = self.cost.as_secs_f64() * 1e6 / frames;
let ms = elapsed.as_secs_f64() * 1e3 / frames;
let pc = self.sample(1e3 / ms.max(0.001), host);
let parts = parts();
self.rows = rows(&numbers(c, ms, self.worst, cost, pc, self.output, host, parts), parts);
self.graphs = parts.graphs;
self.made = true;
self.changed = true;
(self.since, self.frames, self.worst) = (now, 0, 0.0);
self.cost = now.elapsed();
}
pub(super) fn draw(
&mut self,
host: &Host,
list: &HostList,
back: &ID3D12Resource,
(width, height): (u32, u32),
format: DXGI_FORMAT,
) {
let pct = ui_scale(height);
if self.failed && self.failed_at == Some((format, pct)) {
return;
}
if !shown().load(Ordering::Relaxed) || !self.made || (self.rows.is_empty() && !self.graphs) {
return;
}
let began = Instant::now();
self.output = (width, height);
#[cfg(feature = "diagnostics")]
let _ours = crate::replay::record::unrecorded();
let solid = super::overlay::solid().filter(|_| super::overlay::takes(format));
let blend = solid.is_some();
if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct, b.blend) != (format, pct, blend)) {
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new_for(host, Kind::Stats, format, pct, blend);
self.failed = self.buffers.is_none();
self.failed_at = self.failed.then_some((format, pct));
self.changed = true;
}
let Some(buffers) = &mut self.buffers else { return };
if std::mem::take(&mut self.changed)
&& let Some((canvas, drawn)) = render_stats(&self.rows, self.graphs.then_some(&self.history[..]), pct)
{
buffers.write(&canvas, drawn);
}
let size = (buffers.width, buffers.drawn);
let at = corner(pct, size, (width, height));
match solid {
Some(solid) => {
unsafe {
if std::mem::take(&mut buffers.fresh) {
list.list.CopyResource(&buffers.card, &buffers.uploads[buffers.turn].0);
crate::barstat::rb(&list.list, &[transition(&buffers.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)]);
}
}
if !super::overlay::draw(host, list, back, format, (width, height), &buffers.card, buffers.pitch, at, size, solid) {
unsafe { std::env::remove_var("EONACAT_XS_PANEL_SEE") };
self.changed = true;
}
}
None => buffers.copy(&list.list, back, at, (width, height)),
}
self.cost += began.elapsed();
}
}
const NOTICE_FOR: Duration = Duration::from_secs(30);
const NOTICE_COLUMNS: u32 = 52;
pub(super) struct Notice {
lines: Vec<String>,
kind: Kind,
since: Option<Instant>,
buffers: Option<Buffers>,
written: bool,
done: bool,
}
impl Notice {
pub(super) fn new() -> Notice {
let warmup = super::menu::warmup_seconds().map(super::menu::warmup_notice).unwrap_or_default();
let mut start = crate::start_notice::lines();
if !start.is_empty() {
start.push(String::new());
}
let lines: Vec<String> =
start.into_iter().chain(warmup).chain(crate::streamline::notice()).map(|l| l.to_ascii_uppercase()).collect();
let columns = lines.iter().map(|l| l.chars().count() as u32).max().unwrap_or(0).min(NOTICE_COLUMNS);
let kind = Kind::Notice(columns, lines.len() as u32);
Notice { done: lines.is_empty(), lines, kind, since: None, buffers: None, written: false }
}
pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) {
if self.done {
return;
}
let since = *self.since.get_or_insert_with(Instant::now);
if since.elapsed() > NOTICE_FOR {
std::mem::forget(self.buffers.take());
self.done = true;
return;
}
#[cfg(feature = "diagnostics")]
let _ours = crate::replay::record::unrecorded();
let pct = ui_scale(height);
if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct) != (format, pct)) {
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new(host, self.kind, format, pct);
self.written = false;
if self.buffers.is_none() {
self.done = true;
return;
}
}
let Some(buffers) = &mut self.buffers else { return };
if !std::mem::replace(&mut self.written, true)
&& let Some(canvas) = render_notice(&self.lines, self.kind, pct)
{
buffers.write(&canvas, canvas.height);
}
let at = (width.saturating_sub(buffers.width) / 2, s(18, layout_scale(pct)));
buffers.copy(&list.list, back, at, (width, height));
}
}
pub(super) fn advisor_shown() -> &'static AtomicBool {
static SHOWN: OnceLock<AtomicBool> = OnceLock::new();
SHOWN.get_or_init(|| AtomicBool::new(crate::switch::on("EONACAT_XS_ADVISOR")))
}
const ADVICE_LINES: usize = 7;
fn f2_pressed() -> bool {
use windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_F10;
static DOWN: AtomicBool = AtomicBool::new(false);
let down = unsafe { GetAsyncKeyState(i32::from(VK_F10)) } < 0;
if DOWN.swap(down, Ordering::Relaxed) || !down {
return false;
}
let mut process = 0;
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
process == std::process::id()
}
const FIRST_START_FOR: Duration = Duration::from_secs(60);
const FIRST_START: [&str; 2] = [
"SHOWN FOR 1 MINUTE ON THE FIRST START OF A NEW BUILD, TO SAY WHAT",
"THE GAME IS DOING. KEEP IT ON: F10, OR F9 > WHAT LIMITS FPS (F10)",
];
fn first_start_of_build() -> bool {
if std::env::var_os("EONACAT_XS_ADVISOR_FIRST").is_some_and(|v| v == "0") {
return false;
}
let home = std::env::var_os("EONACAT_XS_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("LOCALAPPDATA").map(|base| std::path::PathBuf::from(base).join("EonaCat").join("XS")));
let Some(home) = home else { return false };
let build: String = env!("EONACAT_XS_BUILD").chars().map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' }).collect();
let mark = home.join("advisor-shown").join(build);
if mark.exists() {
return false;
}
let _ = std::fs::create_dir_all(mark.parent().unwrap_or(&mark));
let _ = std::fs::write(&mark, "the performance explainer was shown on this build's first start\r\n");
true
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Sample {
fps: f64,
ms: f64,
gpu_ms: f64,
wait_ms: f64,
making: u64,
dropped: f64,
vram: f64,
budget: f64,
cap: f64,
rays: bool,
dlss: Option<&'static str>,
framegen: u32,
}
fn advice(s: &Sample) -> Vec<String> {
let mut out = vec![format!("{:.0} FPS ({:.1} MS PER FRAME)", s.fps, s.ms)];
let mut add = |what: String, help: &str| {
if out.len() + 2 <= ADVICE_LINES {
out.push(what);
out.push(format!(" TRY: {help}"));
}
};
let capped = s.cap > 0.0 && s.fps >= s.cap * 0.95;
let gpu = s.gpu_ms >= s.ms * 0.85 || s.wait_ms >= s.ms * 0.25;
let gpu_help = if s.rays {
"TURN OFF RAY TRACING IN F9, OR PICK A LOWER DLSS MODE"
} else if matches!(s.dlss, Some("quality" | "dlaa") | None) {
"SET DLSS TO BALANCED OR PERFORMANCE IN F9"
} else if s.framegen < 2 {
"TURN ON FRAME GENERATION IN F9"
} else {
"PICK A LOWER DLSS MODE OR A SMALLER RESOLUTION"
};
let gpu_line = |lead: &str| format!("{lead}: YOUR GPU IS FULLY BUSY ({:.0} OF EVERY {:.0} MS)", s.gpu_ms, s.ms);
if s.making > 0 {
add(
format!("LIMIT: {} SHADERS STILL COMPILING (STUTTER, MISSING OBJECTS)", s.making),
"WAIT, IT CLEARS BY ITSELF. RUN THE PRELOAD BEFORE PLAYING",
);
if gpu {
add(gpu_line("ALSO"), gpu_help);
}
} else if capped {
add(format!("LIMIT: THE FRAME RATE CAP ({:.0} FPS)", s.cap), "RAISE FRAME RATE CAP IN F9");
} else if gpu {
add(gpu_line("LIMIT"), gpu_help);
} else {
let help = if s.framegen < 2 {
"TURN ON FRAME GENERATION IN F9. LOWER GRAPHICS WILL NOT HELP"
} else {
"CLOSE BACKGROUND APPS. LOWER GRAPHICS WILL NOT HELP"
};
let idle = (s.ms - s.gpu_ms).max(0.0);
add(format!("LIMIT: YOUR CPU (THE GPU WAITS {idle:.0} OF EVERY {:.0} MS)", s.ms), help);
}
if s.budget > 0.0 && s.vram >= s.budget * 0.97 {
add(
format!("ALSO: VIDEO MEMORY IS FULL ({:.1} OF {:.1} GB)", s.vram, s.budget),
"A LOWER DLSS MODE, OR CLOSE APPS THAT USE THE GPU",
);
}
out
}
pub(super) struct Advisor {
since: Instant,
frames: u32,
before: Counters,
lines: Vec<String>,
changed: bool,
buffers: Option<Buffers>,
failed: bool,
first: bool,
first_since: Option<Instant>,
}
impl Advisor {
fn on(&self) -> bool {
advisor_shown().load(Ordering::Relaxed) || self.first
}
pub(super) fn new() -> Advisor {
Advisor {
since: Instant::now(),
frames: 0,
before: Counters::default(),
lines: Vec::new(),
changed: false,
buffers: None,
failed: false,
first: first_start_of_build(),
first_since: None,
}
}
pub(super) fn frame(&mut self) {
if f2_pressed() {
let on = !self.on();
advisor_shown().store(on, Ordering::Relaxed);
self.first = false;
self.changed = true;
}
if self.first_since.is_some_and(|at| at.elapsed() >= FIRST_START_FOR) {
self.first = false;
self.changed = true;
}
if !self.on() {
self.frames = 0;
return;
}
let now = Instant::now();
if self.frames == 0 {
(self.since, self.before) = (now, Counters::now());
}
self.frames += 1;
let elapsed = now - self.since;
if elapsed < EVERY || self.frames < 2 {
return;
}
let Some(host) = super::host() else { return };
let frames = f64::from(self.frames - 1);
let counters = Counters::now();
let c = counters.since(self.before, frames);
self.before = counters;
let ms = elapsed.as_secs_f64() * 1e3 / frames;
let [budget, used, _, _] = host.video_memory().unwrap_or_default();
let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64;
let dlss = crate::streamline::upscaled_lately().map(|(mode, ..)| mode);
let dlss = dlss.and_then(|m| {
["quality", "balanced", "performance", "ultraperformance", "dlaa"].into_iter().find(|k| m.eq_ignore_ascii_case(k))
});
let cap = std::env::var("EONACAT_XS_MENU_FPS").ok().and_then(|v| v.parse::<f64>().ok()).filter(|&c| c < 1000.0);
let sample = Sample {
fps: 1e3 / ms.max(0.001),
ms,
gpu_ms: ms - (c[1] / 1e3).min(ms),
wait_ms: c[3] / 1e3,
making: crate::pipeline::making(),
dropped: c[8],
vram: gb(used),
budget: gb(budget),
cap: cap.unwrap_or(0.0),
rays: std::env::var_os("EONACAT_XS_BVH_BUILDER").is_some_and(|v| v == "1"),
dlss,
framegen: crate::streamline::shown_per_frame(),
};
self.lines = advice(&sample);
self.changed = true;
(self.since, self.frames) = (now, 1);
}
pub(super) fn draw(
&mut self,
host: &Host,
list: &HostList,
back: &ID3D12Resource,
(width, height): (u32, u32),
format: DXGI_FORMAT,
notice: bool,
) {
if notice || !self.on() || self.lines.is_empty() || self.failed {
return;
}
if self.first && self.first_since.is_none() {
self.first_since = Some(Instant::now());
}
#[cfg(feature = "diagnostics")]
let _ours = crate::replay::record::unrecorded();
let pct = ui_scale(height);
if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct) != (format, pct)) {
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new(host, Kind::Advisor, format, pct);
self.failed = self.buffers.is_none();
self.changed = true;
}
let Some(buffers) = &mut self.buffers else { return };
if std::mem::take(&mut self.changed) {
let mut lines = self.lines.clone();
lines.truncate(ADVICE_LINES);
if self.first && !advisor_shown().load(Ordering::Relaxed) {
lines.extend(FIRST_START.map(str::to_owned));
}
if let Some((canvas, drawn)) = render_advisor(&lines, pct) {
buffers.write(&canvas, drawn);
}
}
let at = (width.saturating_sub(buffers.width) / 2, s(10, layout_scale(pct)).min(height.saturating_sub(buffers.drawn)));
buffers.copy(&list.list, back, at, (width, height));
}
}
impl Notice {
pub(super) fn showing(&self) -> bool {
!self.done
}
}