Update: FSR black in release builds fixed, frame generation in release, keyboard and mouse

- FSR: the host gets the whole description in every build; release builds
  drew a black picture with it
- Frame generation works in builds without diagnostics
- Keyboard and mouse play with a settings menu on F1 (docs/keyboard-mouse.md)
- Saves: a damaged newest version never costs an older whole one (after
  HexNomad23/victory-rdna4-0326 by lgtlgt0015-code)
- Ultra Performance: a third at 4K, 37.5% at 1440p, else 50%; 1664x936 in
  the launcher in place of 1600x900
- Dynamic descriptor slots of lists that ran go back many at a time
- The write-watch texture test asks whole 64 KiB pages (failed on Windows)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Slaktarn700andClaude Opus 5.5 committed 2026-11-30 11:54:31 +01:00
1 parent 6990246842
commit 3b5c751339
37 files changed
+9187 -1168

No files matched your search

+12 -3
View File
@@ -22,6 +22,13 @@ fps for a second or more. The goal is a steady 30 real fps without ray tracing f
it. The S70 preset turns ray tracing on, which costs a lot more: turn it off in the
launcher first, or run `OVERRIDE="RT=0" ./linux/s70.sh`.
New on 2026-11-30: **FSR drew a black picture in release builds** (the host's library got only
the first part of its description; builds with diagnostics hid it): fixed. Frame generation
works in release builds too. Keyboard and mouse play with a settings menu on F1
(`docs/keyboard-mouse.md`; the pad buttons behind some actions are guesses, change them there).
Saves: a damaged newest version never costs an older whole one. Ultra Performance works at 3840x2160
(a third) and 2560x1440 (37.5%), else as Performance. A little CPU work less per frame.
New in the second update of 2026-11-29: the shore's sand and the plants on the water are drawn
(`VICTORY_MESH_ONE_DIM`, after ReTerryDavis/ReVIctory), several fixes to textures that arrived
late or were lost, no error when pipelines are prepared on an empty cache, a crash dumper and a
@@ -126,9 +133,11 @@ GAME_EXE=<the executable's name> ./linux/s70.sh
second, `linux/hw-log.py`). `linux/ab-report.py` sums up an in-run A/B
(`VICTORY_AB=<seconds>,<switch>`).
Keyboard stand-in for the pad: W/A/S/D left stick, I/J/K/L right stick, Z and C the
triggers, Enter A, Backspace B, X and Y, Q and E the shoulders, Esc menu, Tab view; F3
shows or hides the info panel, F4 saves the next frame (with `VICTORY_CAPTURE`).
Keyboard and mouse: the launcher turns it on (`VICTORY_KBM=1`); click into the window to hold
the mouse, F1 for the settings menu and the keys. Without it the keyboard is a plain stand-in for
the pad (W/A/S/D left stick, I/J/K/L right stick, Z and C the triggers, Enter A, Backspace B, X
and Y, Q and E the shoulders, Esc menu, Tab view). In diagnostics builds F3 shows or hides the
info panel and F4 saves the next frame (with `VICTORY_CAPTURE`).
## Windows
+1 -1
View File
@@ -235,7 +235,7 @@ pub fn run(
if execute {
let size = image.info().size_of_image as usize;
// SAFETY: the image stays mapped and nothing of it has run yet.
unsafe { victory_loader::resolution::apply_asked(image.base(), size) };
unsafe { victory_loader::resolution::apply_asked(image.base(), size, victory_hle::modules::fidelityfx::serving()) };
}
if !execute {
println!("not executing (pass --execute to start the title)");
+13 -20
View File
@@ -14,10 +14,11 @@
//! the title's executable sections. Another build of the title, where it does
//! not, is left alone. With both set, both are found before either is
//! written, and the scale goes first, since the picker alone renders at full
//! size.
//! size. What `victory_loader::resolution` wrote already (it compares whole
//! places of the one known build, earlier) is left out here.
use anyhow::{Result, bail};
use victory_loader::{CodeWrite, LoadedImage};
use victory_loader::{CodeWrite, LoadedImage, resolution};
/// Locates the picker by its conditional selection between the title's
/// upscaler and FidelityFX. The call and global addresses may vary.
@@ -43,14 +44,15 @@ const SCALE_SPAN: usize = 0x68;
/// a write that went in but whose page protection or instruction cache could
/// not be settled, or only the scale taking of the two.
pub(crate) fn apply(image: &LoadedImage) -> Result<()> {
let kind = requested(
"VICTORY_UPSCALER",
"<kind> (decimal, 7 for FidelityFX)",
|s| s.parse::<u32>().ok(),
);
let scale = requested("VICTORY_FFX_SCALE", "<scale in (0, 1]>", |s| {
s.parse::<f32>().ok().filter(|s| *s > 0.0 && *s <= 1.0)
});
// A kind the loader refused stays refused (`Some(None)`).
let kind = (!resolution::picker_written() && std::env::var_os("VICTORY_UPSCALER").is_some())
.then(resolution::asked_upscaler);
// Always a scale if one is asked for (`resolution::ffx_scale`). This runs
// only with the host's upscaler serving.
let scale = (!resolution::ffx_scale_written())
.then(|| resolution::asked_ffx_scale(resolution::asked_output(), true))
.flatten()
.map(Some);
// Everything asked for is found before anything is written.
let picker = kind.map(|kind| kind.and_then(|kind| picker_patch(image, kind)));
let scale = scale.map(|scale| scale.and_then(|scale| scale_patch(image, scale)));
@@ -64,6 +66,7 @@ pub(crate) fn apply(image: &LoadedImage) -> Result<()> {
(None, Some(picker)) => {
if let Some(picker) = picker
&& picker.write(image)?
&& !resolution::ffx_scale_written()
{
eprintln!(
"VIctory: without VICTORY_FFX_SCALE, Series X renders FidelityFX at full output size"
@@ -86,16 +89,6 @@ pub(crate) fn apply(image: &LoadedImage) -> Result<()> {
Ok(())
}
/// Switch `name`: `None` if unset, `Some(None)` (said why) if malformed.
fn requested<T>(name: &str, form: &str, parse: impl Fn(&str) -> Option<T>) -> Option<Option<T>> {
let spec = std::env::var(name).ok()?;
let value = parse(spec.trim());
if value.is_none() {
eprintln!("VIctory: {name}={spec}: expected {form}");
}
Some(value)
}
/// Code to write at title+`rva`, found and checked.
struct Patch {
what: String,
+46
View File
@@ -3174,6 +3174,27 @@ impl HostHeap {
}
}
/// As [`Self::release`] of each of `ranges`, not confirmed, with the
/// allocator's lock taken once for many of them.
pub(crate) fn release_many(&self, ranges: &[(u32, u32)]) {
for some in ranges.chunks(256) {
let mut given = 0;
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
for &(first, n) in some {
let Some(at) = first.checked_sub(self.count) else {
continue;
};
let end = at.saturating_add(n).min(self.dynamic) as usize;
if let Some(slots) = guard.1.get_mut(at as usize..end) {
given += slots.iter().filter(|taken| **taken).count() as u32;
slots.fill(false);
}
}
self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
}
}
fn note_release_view(&self, index: u32, dimension: u8) {
if let Some(slot) = self.release_views.get(index.wrapping_sub(self.count) as usize) {
slot.store(dimension, std::sync::atomic::Ordering::Relaxed);
@@ -7859,6 +7880,31 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) {
assert_eq!(device_removed(), None);
}
/// Many ranges at once leave the allocator as one after another does:
/// what is free, what is taken, and what it gives next; also ranges that
/// end past its end, that are its neighbours and that are free already.
#[test]
fn many_ranges_go_back_as_one_by_one() {
let heaps = || Some((HostHeap::new(false, 4)?, HostHeap::new(false, 4)?));
let Some((one, many)) = heaps() else { return };
for heap in [&one, &many] {
assert_eq!(heap.dynamic(2000), Some(4));
}
let ranges: Vec<(u32, u32)> = (0..600).map(|i| (4 + i * 3, 1 + i % 3)).chain([(0, 2), (40, 5), (4 + one.dynamic - 2, 9)]).collect();
for &(first, n) in &ranges {
one.release(first, n, false);
}
many.release_many(&ranges);
let state = |heap: &HostHeap| {
let taken: Vec<bool> = heap.next.lock().unwrap().1.iter().copied().take(4000).collect();
(heap.free.load(std::sync::atomic::Ordering::Relaxed), taken)
};
assert!(state(&one) == state(&many));
for n in [1, 2, 3, 1, 7] {
assert_eq!(one.dynamic(n), many.dynamic(n));
}
}
#[test]
fn dynamic_slots_are_held_until_released() {
let Some(heap) = HostHeap::new(false, 4) else {
+30 -10
View File
@@ -612,6 +612,36 @@ impl State {
}
}
/// The submission of a list taken from its title's list has run: its
/// dynamic slots go back, many at a time. What else it remembers of its
/// tables is dropped with it, by the thread that resets such lists, not
/// by the one that lands flights.
pub(crate) fn slots_done(&mut self) {
if self.tables_gone || crate::descriptor::host::reclaim_dynamic() {
return self.tables_done();
}
let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.dynamic.len());
let mut of: Option<std::sync::Weak<crate::descriptor::host::HostHeap>> = None;
let give = |heap: Option<std::sync::Weak<crate::descriptor::host::HostHeap>>, ranges: &mut Vec<(u32, u32)>| {
if let Some(heap) = heap.and_then(|heap| heap.upgrade()) {
heap.release_many(ranges);
}
ranges.clear();
};
for (heap, first, n) in self.dynamic.drain(..) {
if of.as_ref().is_none_or(|of| !of.ptr_eq(&heap)) {
give(of.replace(heap), &mut ranges);
}
// (Made one after another, they mostly lie so.)
match ranges.last_mut() {
Some((from, len)) if *from + *len == first => *len += n,
_ => ranges.push((first, n)),
}
}
give(of, &mut ranges);
self.tables_gone = true;
}
/// The list's submission has run (submissions are waited for): the
/// dynamic slots its tables were made in are given back, not kept
/// until the title resets the list. A frame of the opening cutscene
@@ -3898,15 +3928,9 @@ impl State {
}
}
/// What a draw or dispatch runs, for the device-removed report
/// (diagnostics): the pipeline, then per stage the user data it gets
/// (with the view at that heap index, if one is), the host addresses
/// of its root views and the views its tables name.
#[cfg(feature = "diagnostics")]
/// Frame generation: at a full-screen draw that lays the UI layer over
/// the frame ([`crate::pipeline::host::HostPipeline::over`]), the target
/// as it is before it ([`crate::framegen::keep_before_ui`]).
#[cfg(feature = "diagnostics")]
fn keep_frame_before_ui(&self, list: &HostList) {
const COPY_SOURCE: u32 = 0x800;
if !crate::framegen::enabled() || self.targets.len() != 1 {
@@ -3927,7 +3951,6 @@ impl State {
/// Frame generation: the UI layer that draw lays over the frame goes to
/// the proxy swap chain instead ([`crate::framegen::keep_ui_layer`]);
/// true if the draw is to be left out.
#[cfg(feature = "diagnostics")]
fn ui_layer_to_proxy(&self, list: &HostList) -> bool {
const SHADER_READ: u32 = 0x40 | 0x80;
if !crate::framegen::enabled() || self.targets.len() != 1 {
@@ -4783,7 +4806,6 @@ impl State {
out
}
#[cfg(feature = "diagnostics")]
fn record_framegen_camera(&self, list: &HostList) {
if !crate::framegen::ml_enabled() {
return;
@@ -4813,7 +4835,6 @@ impl State {
self.window = None;
#[cfg(feature = "diagnostics")]
self.trace("draw", vertices, first);
#[cfg(feature = "diagnostics")]
if vertices == 3 && instances == 1 {
self.keep_frame_before_ui(list);
if self.ui_layer_to_proxy(list) {
@@ -4834,7 +4855,6 @@ impl State {
};
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
#[cfg(feature = "diagnostics")]
if count == 3 && instances == 1 {
self.record_framegen_camera(list);
}
+8 -9
View File
@@ -22,17 +22,18 @@ pub(crate) fn host_fidelityfx_enabled() -> bool {
HOST_FIDELITYFX.load(Ordering::Acquire)
}
/// The host upscaler's provider name ("4.1.1 *" and the like), for the panel.
static UPSCALER: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
/// The host upscaler's provider name ("4.1.1 *" and the like) and its render
/// width over its output width, for the panel.
static UPSCALER: std::sync::Mutex<Option<(String, f64)>> = std::sync::Mutex::new(None);
/// The host made an upscaler context with this provider.
pub fn note_upscaler(provider: &str) {
*UPSCALER.lock().unwrap_or_else(|e| e.into_inner()) = Some(provider.to_owned());
/// The host made an upscaler context with this provider, at this scale.
pub fn note_upscaler(provider: &str, scale: f64) {
*UPSCALER.lock().unwrap_or_else(|e| e.into_inner()) = Some((provider.to_owned(), scale));
}
/// The host upscaler's provider name, once one was made.
/// The host upscaler's provider name and render scale, once one was made.
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(crate) fn upscaler() -> Option<String> {
pub(crate) fn upscaler() -> Option<(String, f64)> {
UPSCALER.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
@@ -110,7 +111,6 @@ pub struct FrameInputs {
/// Turns on AMD frame generation for upscaled frames (diagnostics) with
/// `amd_fidelityfx_framegeneration_dx12.dll` from `dir`: the presenter's
/// swap chain becomes its proxy. The DLL's path, or why not.
#[cfg(feature = "diagnostics")]
pub fn use_frame_generation(dir: &std::path::Path, ml: bool) -> Result<String, String> {
crate::framegen::load(dir, ml)
}
@@ -118,7 +118,6 @@ pub fn use_frame_generation(dir: &std::path::Path, ml: bool) -> Result<String, S
/// At a host upscale recorded into the title list `list`: its depth and
/// motion textures (title resources) and constants feed frame generation
/// for the next present, once the list has run. Nothing when it is off.
#[cfg(feature = "diagnostics")]
pub fn frame_generation_inputs(list: *const Object, depth: *const Object, motion: *const Object, frame: FrameInputs) {
if !crate::framegen::enabled() {
return;
+16 -2
View File
@@ -217,6 +217,7 @@ impl PacingTuning {
/// Whether the proxy's threads wait on fence events instead of spinning
/// (`VICTORY_FG_FENCE_WAIT=1`; off by default until measured; A/B-able).
fn fence_waits() -> bool {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_FG_FENCE_WAIT") {
return on;
}
@@ -531,6 +532,7 @@ impl Ahead {
/// or as an A/B switch; off by default: the order it rests on is not proven).
/// Off, they stay for a later present. The counters count either way.
fn ui_drop() -> bool {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_FG_UI_DROP") {
return on;
}
@@ -1098,6 +1100,7 @@ impl Presentation {
}
// `VICTORY_AB=<s>,VICTORY_FIDELITYFX_FRAMEGEN`: generation off in
// the A phases (the proxy still presents), for its cost in one run.
#[cfg(feature = "diagnostics")]
if crate::ab::pick("VICTORY_FIDELITYFX_FRAMEGEN") == Some(false) {
let _ = take_inputs();
return self.not_generated(chain);
@@ -1334,7 +1337,7 @@ fn read(list: &HostList, copy: &Arc<HostTexture>, description: [u32; 8], barrier
}
#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
#[test]
@@ -1466,11 +1469,22 @@ mod tests {
}
/// The tests that use this module's statics, one at a time.
pub(super) fn alone() -> std::sync::MutexGuard<'static, ()> {
pub(crate) fn alone() -> std::sync::MutexGuard<'static, ()> {
static ALONE: Mutex<()> = Mutex::new(());
ALONE.lock().unwrap_or_else(|e| e.into_inner())
}
/// `from` as the title's UI layer, for tests of what is drawn onto it.
#[cfg(feature = "diagnostics")]
pub(crate) fn keep_as_ui_layer(device: &ID3D12Device, list: &HostList, from: &ID3D12Resource, size: [u32; 2]) {
assert!(copy_layer(&UI_LAYER, UI_READ, device, list, from, size));
}
#[cfg(feature = "diagnostics")]
pub(crate) fn no_ui_layer() {
*UI_LAYER.lock().unwrap() = None;
}
/// What the stand-in library was last told of a UI resource, and the
/// codes it answers a generator's configure and prepare with.
static TOLD_UI: Mutex<Option<bool>> = Mutex::new(None);
+2 -1
View File
@@ -28,6 +28,7 @@ const COPY_SOURCE: u32 = 0x800;
/// Whether depth and motion are kept at the upscale.
pub(super) fn kept() -> bool {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_FG_INPUTS_KEPT") {
return on;
}
@@ -254,5 +255,5 @@ impl Span {
}
}
#[cfg(test)]
#[cfg(all(test, feature = "diagnostics"))]
mod tests;
+60 -31
View File
@@ -2763,17 +2763,17 @@ fn late_exact() -> bool {
/// Frame generation's presents sent ahead as others are: under Wine
/// unless `VICTORY_FG_SENT_AHEAD=0` (`=1` elsewhere), or as an A/B switch;
/// diagnostics.
#[cfg(feature = "diagnostics")]
fn framegen_sent_ahead() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
crate::ab::pick("VICTORY_FG_SENT_AHEAD")
.unwrap_or_else(|| {
*ON.get_or_init(|| match std::env::var("VICTORY_FG_SENT_AHEAD").as_deref() {
Ok("0") => false,
Ok("1") => true,
_ => crate::shadow::on_wine(),
})
})
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_FG_SENT_AHEAD") {
return on;
}
*ON.get_or_init(|| match std::env::var("VICTORY_FG_SENT_AHEAD").as_deref() {
Ok("0") => false,
Ok("1") => true,
_ => crate::shadow::on_wine(),
})
}
pub(crate) fn late_free_present() -> bool {
@@ -4082,10 +4082,14 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
WHY_FENCE => "waiting for landings: a blocking fence wait",
_ => "waiting for landings: another reason",
});
#[cfg(feature = "diagnostics")]
let parts = phases::begin(line.line.len());
while !done(&line) {
line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
}
drop(line);
#[cfg(feature = "diagnostics")]
phases::end(parts, why == WHY_READ);
stood(waiting);
working(was_working);
let us = waiting.elapsed().as_micros() as u64;
@@ -4138,6 +4142,8 @@ fn relay_worker() {
let mut line = line();
loop {
if line.line.is_empty() {
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Idle);
line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner());
continue;
}
@@ -4182,6 +4188,8 @@ fn relay_worker() {
match next {
Ok(items) => host.relay_land(items, &mut fetch),
Err(target) => {
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Card);
let waiting = std::time::Instant::now();
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(Some(target));
@@ -4370,6 +4378,8 @@ fn late_line(frames: f64) {
);
}
if relay() {
#[cfg(feature = "diagnostics")]
phases::report(frames);
let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
tracing::info!(
"the relay per frame (VICTORY_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \
@@ -4462,13 +4472,17 @@ mod alone;
pub(crate) mod aside;
pub(crate) mod awake;
mod card_steps;
mod dots;
mod fronts;
mod gather;
pub(crate) mod guide;
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(crate) mod indirects;
pub(crate) mod known;
#[cfg(feature = "diagnostics")]
mod panel;
#[cfg(feature = "diagnostics")]
pub use panel::panel_keys;
mod place;
pub(crate) mod rec;
mod send;
@@ -4500,6 +4514,8 @@ mod rtbench;
#[cfg(test)]
mod stockbench;
#[cfg(feature = "diagnostics")]
mod phases;
#[cfg(feature = "diagnostics")]
mod stamps;
mod stock;
#[cfg(feature = "diagnostics")]
@@ -5662,6 +5678,8 @@ impl Host {
f.sent += 1;
let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
let copy_queue = f.queue.clone();
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Fetch);
let waiting = std::time::Instant::now();
// The flights the fetch runs behind: those in the line by now have
// been given to the queue. On the copy queue, those landed here.
@@ -5717,6 +5735,8 @@ impl Host {
Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")),
};
let us = waiting.elapsed().as_micros() as u64;
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Merge);
RELAY_STATS[3].fetch_add(us, Ordering::Relaxed);
{
use crate::shadow::CARD_STATS;
@@ -5801,6 +5821,8 @@ impl Host {
/// is complete before the title is told anything.
fn relay_land(&self, mut items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
let landing = std::time::Instant::now();
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Look);
let mut stage = crate::timeline::span("landing: what is to be looked through");
// What title memory holds where the fills of card steps read, before
// anything of this landing goes in: their compare below comes after
@@ -5848,6 +5870,8 @@ impl Host {
}
});
stage.next("landing: copies in the PC's memory");
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Merge);
if let Some(put) = put.as_mut() {
for (from, to) in hand_back.pieces() {
put.wrote(from, to);
@@ -5873,6 +5897,8 @@ impl Host {
}
// In the order given: what tells the title the card is done.
stage.next("landing: read-backs, telling the title");
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Rest);
let mut last = 0;
let mut landed = Vec::new();
let mut telling = std::time::Instant::now();
@@ -5884,12 +5910,18 @@ impl Host {
telling = match item {
Late::Run(mut flight) => {
last = flight.number;
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::ReadBack);
for &i in &flight.order {
read_backs(flight.lists[i].host());
}
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Lists);
if let Some(card) = flight.card {
self.card_done(card);
}
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Steps);
if let Some(own) = flight.own {
// (What follows it in this landing was sent after it.)
own.landed(put.as_ref(), &flight.did, ahead, flight.number, items.as_slice());
@@ -5900,11 +5932,15 @@ impl Host {
// Nothing looks at what its prepare did any more.
card_steps::Prepared::landed(std::mem::take(&mut flight.did));
ahead = true;
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Lists);
// Its lists have run: their dynamic slots go back now.
for detached in &mut flight.lists {
detached.release_tables();
}
landed.push((flight.lists, flight.order));
#[cfg(feature = "diagnostics")]
phases::enter(phases::Phase::Rest);
crate::land::spent(crate::land::stat::READ_BACKS, telling)
}
Late::Write(at, what, bytes) => {
@@ -5966,6 +6002,8 @@ impl Host {
// by the helper thread (they take locks a waiter may hold).
*poke = true;
}
#[cfg(feature = "diagnostics")]
phases::told();
LINE_MOVED.notify_all();
LINE_LANDED.notify_all();
}
@@ -6704,7 +6742,6 @@ impl Host {
list.cast().ok()
};
for (run, list) in runs.iter().enumerate() {
#[cfg(feature = "diagnostics")]
crate::framegen::inputs::submitting(list);
let at = run.checked_sub(usize::from(own.is_some())).filter(|_| record);
let uploads = list.run_deferred(&mut batch, &air, at.map(|k| (&card_steps::UNDER_WAY, k)), |i| {
@@ -7682,7 +7719,6 @@ impl HostList {
/// The states this list has `copy` in at its start and where it is now,
/// if it names it.
#[cfg(feature = "diagnostics")]
pub(crate) fn states_of(&self, copy: &std::sync::Arc<crate::resource::HostTexture>) -> Option<(u32, u32)> {
let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
states.get(&(std::sync::Arc::as_ptr(copy) as usize)).map(|(first, last, _)| (*first, *last))
@@ -7690,7 +7726,6 @@ impl HostList {
/// As [`HostList::settle`], returning the barrier to record instead of
/// recording it (frame generation batches its own).
#[cfg(feature = "diagnostics")]
pub(crate) fn move_texture(
&self,
copy: &std::sync::Arc<crate::resource::HostTexture>,
@@ -10636,9 +10671,9 @@ struct Presenter {
composer: Option<crate::compose::Composer>,
#[cfg(feature = "diagnostics")]
panel: panel::Panel,
guide: guide::Boxes,
/// AMD frame generation, when on: `swap_chain` is then its proxy
/// (`crate::framegen`).
#[cfg(feature = "diagnostics")]
framegen: Option<crate::framegen::Presentation>,
}
@@ -11065,10 +11100,7 @@ impl Meter {
// 2026-11-27): with frame generation's frames, where it runs. The
// log's line has the real rate and the draws, as before.
static SHOWN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[cfg(feature = "diagnostics")]
let shown_now = crate::framegen::shown_total();
#[cfg(not(feature = "diagnostics"))]
let shown_now = 0u64;
let shown = shown_now.saturating_sub(SHOWN.swap(shown_now, Ordering::Relaxed)) as f64;
let rate = if shown > 0.0 { shown / (ms * frames / 1000.0) } else { fps };
let _ = draws;
@@ -11182,7 +11214,6 @@ impl Host {
}
}
if (p.width, p.height, p.format) != (width, height, format) {
#[cfg(feature = "diagnostics")]
if let Some(fg) = &mut p.framegen {
fg.disable(&p.swap_chain);
}
@@ -11246,7 +11277,6 @@ impl Host {
// frame in a 9-minute A/B walk (2026-11-26, 4.5 minutes of it
// sent ahead, without that crash). `VICTORY_FG_SENT_AHEAD=0`:
// the one list again (or in `VICTORY_AB`).
#[cfg(feature = "diagnostics")]
let read_now = read_now || (p.framegen.is_some() && !framegen_sent_ahead());
let slot = if late_free_present() && !read_now {
let finished = FINISHED.load(Ordering::Acquire);
@@ -11259,7 +11289,6 @@ impl Host {
} else {
None
};
#[cfg(feature = "diagnostics")]
if p.framegen.is_some() {
crate::framegen::inputs::empty_idle(&mut p.ahead, slot, FINISHED.load(Ordering::Acquire));
}
@@ -11375,12 +11404,12 @@ impl Host {
crate::popwatch::take(&self.device, list, texture)
};
// Frame generation's HUD-less colour: the frame before the panel.
#[cfg(feature = "diagnostics")]
if let Some(fg) = &mut p.framegen {
fg.keep_hudless(&self.device, copy, &back, [width, height]);
}
#[cfg(feature = "diagnostics")]
p.panel.draw(self, copy, &back, (width, height), format);
p.guide.draw(self, copy, &back, (width, height), format);
#[cfg(not(feature = "diagnostics"))]
let _ = frame;
if composed {
@@ -11403,13 +11432,10 @@ impl Host {
}
// Frame generation reads the last submitted upscale's depth and
// motion in this list, before the present inserts its frames.
#[cfg(feature = "diagnostics")]
let generated = match &mut p.framegen {
Some(fg) => fg.prepare(&p.swap_chain, &self.device, copy, [width, height], frame),
None => false,
};
#[cfg(not(feature = "diagnostics"))]
let generated = false;
copy.close();
let flown = match slot {
Some(i) => {
@@ -11437,11 +11463,9 @@ impl Host {
let mut showing = crate::timeline::span("the host's Present");
// The proxy paces generated frames against the display.
let status = p.swap_chain.Present(u32::from(generated), DXGI_PRESENT(0));
#[cfg(feature = "diagnostics")]
if let Some(fg) = &mut p.framegen {
fg.count_shown(&p.swap_chain);
}
#[cfg(feature = "diagnostics")]
if generated && let Some(fg) = &mut p.framegen {
if status.is_ok() {
fg.presented(&p.swap_chain, frame);
@@ -11475,6 +11499,16 @@ impl Host {
Some(hwnd) => hwnd,
None => window(width, height)?,
};
self.presenter_on(hwnd, width, height, format)
}
fn presenter_on(
&self,
hwnd: HWND,
width: u32,
height: u32,
format: DXGI_FORMAT,
) -> windows::core::Result<Presenter> {
self.log_video_memory("right before the swap chain is made");
// SAFETY: plain object creation for our window.
unsafe {
@@ -11492,7 +11526,6 @@ impl Host {
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
..Default::default()
};
#[cfg(feature = "diagnostics")]
let (swap_chain, framegen) = match crate::framegen::enabled()
.then(|| crate::framegen::Presentation::create(&factory, &self.device, &self.queue, hwnd, &desc))
.flatten()
@@ -11505,10 +11538,6 @@ impl Host {
None,
),
};
#[cfg(not(feature = "diagnostics"))]
let swap_chain = factory
.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
.cast::<IDXGISwapChain3>()?;
let copy = self.new_list()?;
copy.close();
tracing::info!(width, height, format = format.0, "presenting to a window");
@@ -11525,7 +11554,7 @@ impl Host {
composer: None,
#[cfg(feature = "diagnostics")]
panel: panel::Panel::new(),
#[cfg(feature = "diagnostics")]
guide: guide::Boxes::default(),
framegen,
})
}
+265
View File
@@ -0,0 +1,265 @@
//! What the text boxes on the picture are made of ([`super::panel`],
//! [`super::guide`]): a font of five by seven dots, the colours in a swap
//! chain's format, and the copy of a box onto a picture.
use std::sync::atomic::{AtomicBool, Ordering};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
use super::Host;
/// A character's dots, and with the space beside and below it.
pub(super) const GLYPH: (u32, u32) = (5, 7);
pub(super) const CELL: (u32, u32) = (6, 10);
/// The colours of a dot: the box, values, names, the rate.
pub(super) const BOX: u8 = 0;
pub(super) const VALUE: u8 = 1;
pub(super) const NAME: u8 = 2;
pub(super) const RATE: u8 = 3;
const SHADES: [[f32; 3]; 4] = [[0.06, 0.06, 0.07], [1.0, 1.0, 1.0], [0.62, 0.63, 0.66], [0.95, 0.26, 0.24]];
/// That key was pressed since the last call (`down` its last state), with
/// one of our windows in front.
pub(super) fn key_pressed(key: u16, last: &AtomicBool) -> bool {
// SAFETY: a plain query.
let down = unsafe { GetAsyncKeyState(i32::from(key)) } < 0;
if last.swap(down, Ordering::Relaxed) || !down {
return false;
}
let mut process = 0;
// SAFETY: plain queries; room for the answer.
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
process == std::process::id()
}
/// Seven rows of five dots, the leftmost the highest bit.
#[rustfmt::skip]
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],
b'2' => [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111],
b'3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],
b'4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
b'5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
b'6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
b'7' => [0b11111, 0b00001, 0b00010, 0b00010, 0b00100, 0b00100, 0b00100],
b'8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
b'9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
b'A' => [0b00100, 0b01010, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001],
b'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
b'C' => [0b01111, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b01111],
b'D' => [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110],
b'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
b'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
b'G' => [0b01111, 0b10000, 0b10000, 0b10011, 0b10001, 0b10001, 0b01111],
b'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
b'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
b'J' => [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
b'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
b'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
b'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
b'N' => [0b10001, 0b11001, 0b11001, 0b10101, 0b10011, 0b10011, 0b10001],
b'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
b'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
b'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
b'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
b'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
b'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
b'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
b'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
b'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],
b'X' => [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
b'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
b'Z' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
b'%' => [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
b',' => [0, 0, 0, 0, 0b01100, 0b00100, 0b01000],
b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b00100, 0b01000],
b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
b'`' => [0b01000, 0b00100, 0b00010, 0, 0, 0, 0],
b'"' => [0b01010, 0b01010, 0b01010, 0, 0, 0, 0],
b'~' => [0, 0, 0b01000, 0b10101, 0b00010, 0, 0],
b'(' => [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
b')' => [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000],
b'[' => [0b01110, 0b01000, 0b01000, 0b01000, 0b01000, 0b01000, 0b01110],
b']' => [0b01110, 0b00010, 0b00010, 0b00010, 0b00010, 0b00010, 0b01110],
b'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010],
b'>' => [0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000],
b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
b'\\' => [0b10000, 0b01000, 0b01000, 0b00100, 0b00010, 0b00010, 0b00001],
b'|' => [0b00100, 0b00100, 0b00100, 0, 0b00100, 0b00100, 0b00100],
b'&' => [0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101],
b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
b'!' => [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0, 0b00100],
b'?' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0, 0b00100],
b'#' => [0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010],
b'_' => [0, 0, 0, 0, 0, 0, 0b11111],
b' ' => [0; 7],
_ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111],
}
}
/// A character's picture, the few key names need beyond [`glyph`]'s too: the
/// arrows and the letters of Nordic and German keyboards. Others are a box.
#[rustfmt::skip]
const fn letter(c: char) -> [u8; 7] {
match c {
'\u{2190}' => [0, 0b00100, 0b01000, 0b11111, 0b01000, 0b00100, 0],
'\u{2192}' => [0, 0b00100, 0b00010, 0b11111, 0b00010, 0b00100, 0],
'\u{2191}' => [0b00100, 0b01110, 0b10101, 0b00100, 0b00100, 0b00100, 0b00100],
'\u{2193}' => [0b00100, 0b00100, 0b00100, 0b00100, 0b10101, 0b01110, 0b00100],
'\u{C5}' | '\u{E5}' => [0b00100, 0, 0b01110, 0b10001, 0b11111, 0b10001, 0b10001],
'\u{C4}' | '\u{E4}' => [0b01010, 0, 0b01110, 0b10001, 0b11111, 0b10001, 0b10001],
'\u{D6}' | '\u{F6}' => [0b01010, 0, 0b01110, 0b10001, 0b10001, 0b10001, 0b01110],
'\u{DC}' | '\u{FC}' => [0b01010, 0, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
c if c.is_ascii() => glyph((c as u8).to_ascii_uppercase()),
_ => glyph(0),
}
}
/// Puts `text` into a box's `out` (`width` by `height` dots, a colour of
/// [`SHADES`] each) from dot (`x`, `y`) on, `k` dots to a glyph's dot; what
/// would reach into the rim on the right or past the foot is left out.
pub(super) fn put(out: &mut [u8], (width, height): (u32, u32), rim: u32, text: &str, (x, y): (u32, u32), k: u32, colour: u8) {
for (i, c) in text.chars().enumerate() {
for (gy, bits) in letter(c).iter().enumerate() {
for gx in 0..GLYPH.0 {
if (bits >> (GLYPH.0 - 1 - gx)) & 1 == 0 {
continue;
}
for (dx, dy) in (0..k).flat_map(|dx| (0..k).map(move |dy| (dx, dy))) {
let (px, py) = (x + (i as u32 * CELL.0 + gx) * k + dx, y + gy as u32 * k + dy);
if px < width - rim && py < height {
out[(py * width + px) as usize] = colour;
}
}
}
}
}
}
/// A float as a half (for the few shades of the box: finite, 0 to 1).
pub(super) fn half(v: f32) -> u16 {
if v <= 0.0 {
return 0;
}
let bits = v.to_bits();
let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
if exponent <= 0 {
return 0;
}
((exponent as u16) << 10) | ((bits >> 13) & 0x3FF) as u16
}
/// The bytes of a pixel of each of [`SHADES`] in a swap chain's format.
pub(super) fn colours(format: DXGI_FORMAT) -> Option<[Vec<u8>; 4]> {
let byte = |v: f32| (v * 255.0 + 0.5) as u8;
let of = |make: &dyn Fn([f32; 3]) -> Vec<u8>| SHADES.map(make);
Some(match format {
DXGI_FORMAT_R8G8B8A8_UNORM => of(&|[r, g, b]| vec![byte(r), byte(g), byte(b), 0xFF]),
DXGI_FORMAT_B8G8R8A8_UNORM => of(&|[r, g, b]| vec![byte(b), byte(g), byte(r), 0xFF]),
DXGI_FORMAT_R10G10B10A2_UNORM => of(&|[r, g, b]| {
let ten = |v: f32| (v * 1023.0 + 0.5) as u32;
(ten(r) | ten(g) << 10 | ten(b) << 20 | 3 << 30).to_le_bytes().to_vec()
}),
DXGI_FORMAT_R16G16B16A16_FLOAT => of(&|[r, g, b]| [r, g, b, 1.0].into_iter().flat_map(|v| half(v).to_le_bytes()).collect()),
_ => return None,
})
}
/// A box's dots, `width` by `height`, as pixels (`scale` to a dot each way) in
/// rows of `pitch` bytes: each is given to `write` with where it begins, in order.
pub(super) fn expand(picture: &[u8], (width, height): (u32, u32), scale: u32, colours: &[Vec<u8>; 4], pitch: usize, mut write: impl FnMut(usize, &[u8])) {
let bytes = colours[0].len();
let mut row = vec![0; pitch];
let mut at = 0;
for dots in picture.chunks_exact(width as usize).take(height as usize) {
for (dot, pixels) in dots.iter().zip(row.chunks_exact_mut(bytes * scale as usize)) {
for pixel in pixels.chunks_exact_mut(bytes) {
pixel.copy_from_slice(&colours[usize::from(*dot)]);
}
}
for _ in 0..scale {
write(at, &row);
at += pitch;
}
}
}
/// [`expand`] into memory of its own.
#[cfg(feature = "diagnostics")]
pub(super) fn expanded(picture: &[u8], size: (u32, u32), scale: u32, colours: &[Vec<u8>; 4], pitch: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(pitch * (size.1 * scale) as usize);
expand(picture, size, scale, colours, pitch, |_, row| out.extend_from_slice(row));
out
}
/// A buffer in the card's memory, to be copied into first.
pub(super) fn card_buffer(host: &Host, bytes: u64) -> Option<ID3D12Resource> {
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 = 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()?;
}
card
}
/// Records the copy of a box of `w` by `h` pixels in `from` (rows of `pitch`
/// bytes) onto `picture` (`width` by `height`) at (`x`, `y`), which lies in it;
/// what reaches past its edges is left out.
///
/// # Safety
/// An open list; `from` holds the box and can be copied from, `picture` can
/// be copied into, both live until the list has run.
#[allow(clippy::too_many_arguments)]
pub(super) unsafe fn copy_box(
list: &super::rec::Rec,
from: &ID3D12Resource,
format: DXGI_FORMAT,
(w, h): (u32, u32),
pitch: u32,
picture: &ID3D12Resource,
(x, y): (u32, u32),
(width, height): (u32, u32),
) {
let part = D3D12_BOX { left: 0, top: 0, front: 0, right: w.min(width - x), bottom: h.min(height - y), back: 1 };
let footprint = D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: w, Height: h, Depth: 1, RowPitch: pitch };
// SAFETY: the caller's word; the locations borrow both resources.
unsafe {
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(from),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: 0, Footprint: footprint },
},
};
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(picture),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
list.CopyTextureRegion(&to, x, y, 0, &from, Some(&part));
}
}
File diff suppressed because it is too large. Load diff
+42 -199
View File
@@ -14,17 +14,14 @@ 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_F3, VK_F4};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_F3, VK_F4};
use super::dots::{BOX, CELL, GLYPH, NAME, RATE, VALUE, card_buffer, colours, copy_box, expanded, key_pressed, put};
use super::{Host, HostList, transition};
/// How often the numbers change.
const EVERY: Duration = Duration::from_millis(500);
/// A character's dots, and with the space beside and below it.
const GLYPH: (u32, u32) = (5, 7);
const CELL: (u32, u32) = (6, 10);
/// Characters in a line, lines, and the box's rim in dots.
const COLUMNS: u32 = 36;
/// The rows below the head: nine pairs, a rule, three lines of the PC's own.
@@ -50,77 +47,26 @@ fn shown() -> &'static AtomicBool {
SHOWN.get_or_init(|| AtomicBool::new(asked()))
}
static KEYS: std::sync::Mutex<Option<&str>> = std::sync::Mutex::new(None);
/// The key layout in use (keyboard and mouse play), for the panel's last line.
pub fn panel_keys(layout: &'static str) {
*KEYS.lock().unwrap_or_else(|e| e.into_inner()) = Some(layout);
}
/// The last line with the key layout in place of the PC's memory, which a
/// row above has too; the build stays.
fn with_keys(last: &str, layout: &str) -> String {
let build = last.split_once(" - ").map_or(last, |(_, build)| build);
format!("KEYS {layout} - {build}").chars().take(COLUMNS as usize).collect()
}
/// F3 was pressed since the last call, with one of our windows in front.
fn pressed() -> bool {
static DOWN: AtomicBool = AtomicBool::new(false);
key_pressed(VK_F3, &DOWN)
}
/// That key was pressed since the last call (`down` its last state), with
/// one of our windows in front.
fn key_pressed(key: u16, last: &AtomicBool) -> bool {
// SAFETY: a plain query.
let down = unsafe { GetAsyncKeyState(i32::from(key)) } < 0;
if last.swap(down, Ordering::Relaxed) || !down {
return false;
}
let mut process = 0;
// SAFETY: plain queries; room for the answer.
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
process == std::process::id()
}
/// Seven rows of five dots, the leftmost the highest bit.
#[rustfmt::skip]
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],
b'2' => [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111],
b'3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],
b'4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
b'5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
b'6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
b'7' => [0b11111, 0b00001, 0b00010, 0b00010, 0b00100, 0b00100, 0b00100],
b'8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
b'9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
b'A' => [0b00100, 0b01010, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001],
b'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
b'C' => [0b01111, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b01111],
b'D' => [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110],
b'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
b'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
b'G' => [0b01111, 0b10000, 0b10000, 0b10011, 0b10001, 0b10001, 0b01111],
b'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
b'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
b'J' => [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
b'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
b'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
b'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
b'N' => [0b10001, 0b11001, 0b11001, 0b10101, 0b10011, 0b10011, 0b10001],
b'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
b'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
b'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
b'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
b'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
b'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
b'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
b'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
b'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],
b'X' => [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
b'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
b'Z' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
b'%' => [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
b' ' => [0; 7],
_ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111],
}
}
/// The box's size in dots.
const fn dots() -> (u32, u32) {
(COLUMNS * CELL.0 + 2 * RIM, HEAD + (PAIRS + NOTES) * CELL.1 + RULE + 2 * RIM)
@@ -137,6 +83,11 @@ fn scale(height: u32) -> u32 {
(height / 540).max(1)
}
/// What the box takes of a picture that high, in pixels.
pub(super) fn taken(height: u32) -> (u32, u32) {
size(scale(height))
}
/// A row of the box.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum Row {
@@ -150,35 +101,12 @@ pub(super) enum Row {
Note(String),
}
/// The colours of a dot: the box, values, names, the rate.
const BOX: u8 = 0;
const VALUE: u8 = 1;
const NAME: u8 = 2;
const RATE: u8 = 3;
const SHADES: [[f32; 3]; 4] = [[0.06, 0.06, 0.07], [1.0, 1.0, 1.0], [0.62, 0.63, 0.66], [0.95, 0.26, 0.24]];
/// The dots of the box, a colour each ([`SHADES`]), row by row.
fn drawn(rows: &[Row]) -> Vec<u8> {
let (width, height) = dots();
let mut out = vec![BOX; (width * height) as usize];
// `text` from dot (x, y) on, `k` dots to a glyph's dot.
let mut put = |text: &str, x: u32, y: u32, k: u32, colour: u8| {
for (i, c) in text.bytes().enumerate() {
let rows = glyph(c.to_ascii_uppercase());
for (gy, bits) in rows.iter().enumerate() {
for gx in 0..GLYPH.0 {
if (bits >> (GLYPH.0 - 1 - gx)) & 1 == 0 {
continue;
}
for (dx, dy) in (0..k).flat_map(|dx| (0..k).map(move |dy| (dx, dy))) {
let (px, py) = (x + (i as u32 * CELL.0 + gx) * k + dx, y + gy as u32 * k + dy);
if px < width - RIM && py < height {
out[(py * width + px) as usize] = colour;
}
}
}
}
}
put(&mut out, (width, height), RIM, text, (x, y), k, colour);
};
let wide = |text: &str, k: u32| (text.len() as u32 * CELL.0).saturating_sub(1) * k;
let right = |text: &str| (width - RIM).saturating_sub(wide(text, 1)).max(RIM);
@@ -227,56 +155,9 @@ fn drawn(rows: &[Row]) -> Vec<u8> {
out
}
/// A float as a half (for the few shades of the box: finite, 0 to 1).
fn half(v: f32) -> u16 {
if v <= 0.0 {
return 0;
}
let bits = v.to_bits();
let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
if exponent <= 0 {
return 0;
}
((exponent as u16) << 10) | ((bits >> 13) & 0x3FF) as u16
}
/// The bytes of a pixel of each of [`SHADES`] in a swap chain's format.
fn colours(format: DXGI_FORMAT) -> Option<[Vec<u8>; 4]> {
let byte = |v: f32| (v * 255.0 + 0.5) as u8;
let of = |make: &dyn Fn([f32; 3]) -> Vec<u8>| SHADES.map(make);
Some(match format {
DXGI_FORMAT_R8G8B8A8_UNORM => of(&|[r, g, b]| vec![byte(r), byte(g), byte(b), 0xFF]),
DXGI_FORMAT_B8G8R8A8_UNORM => of(&|[r, g, b]| vec![byte(b), byte(g), byte(r), 0xFF]),
DXGI_FORMAT_R10G10B10A2_UNORM => of(&|[r, g, b]| {
let ten = |v: f32| (v * 1023.0 + 0.5) as u32;
(ten(r) | ten(g) << 10 | ten(b) << 20 | 3 << 30).to_le_bytes().to_vec()
}),
DXGI_FORMAT_R16G16B16A16_FLOAT => of(&|[r, g, b]| [r, g, b, 1.0].into_iter().flat_map(|v| half(v).to_le_bytes()).collect()),
_ => return None,
})
}
/// The box as rows of `pitch` bytes.
fn painted(rows: &[Row], scale: u32, colours: &[Vec<u8>; 4], pitch: usize) -> Vec<u8> {
let (width, height) = size(scale);
let bytes = colours[0].len();
let dots_wide = dots().0;
let picture = drawn(rows);
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(picture[(y * dots_wide + x) as usize])];
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
expanded(&drawn(rows), dots(), scale, colours, pitch)
}
/// The counters read for it. They grow, and go back to 0 with the frame-rate
@@ -441,6 +322,11 @@ fn text(c: &[f64; COUNTERS], ms: f64, rates: [(f64, f64, f64); 2], busy: f64, ho
Row::Rule,
];
rows.extend(pc(host).iter().cloned().map(Row::Note));
if let Some(layout) = *KEYS.lock().unwrap_or_else(|e| e.into_inner())
&& let Some(Row::Note(last)) = rows.last_mut()
{
*last = with_keys(last, layout);
}
// With switches that change in the run (`VICTORY_AB`): which are on now,
// on the last line, for whoever watches the picture.
#[cfg(feature = "diagnostics")]
@@ -459,13 +345,12 @@ const DISPLAYED: &str = "DISPLAYED";
/// The upscaler, short: the host's FidelityFX by its version and the
/// render scale's preset ("FSR 4.1 QUALITY"), or the title's own.
fn upscaler() -> String {
let Some(provider) = crate::external::upscaler() else {
let Some((provider, scale)) = crate::external::upscaler() else {
return "THE TITLES OWN".into();
};
// "4.1.1 *": major and minor.
let version: String = provider.split(['.', ' ']).filter(|p| !p.is_empty()).take(2).collect::<Vec<_>>().join(".");
let scale = std::env::var("VICTORY_FFX_SCALE").ok().and_then(|v| v.trim().parse::<f64>().ok());
format!("FSR {version} {}", preset(scale))
format!("FSR {version} {}", preset(Some(scale)))
}
/// FidelityFX's name for a render scale (render size over output size).
@@ -511,28 +396,8 @@ impl Buffers {
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, uploaded: false })
let card = card_buffer(host, bytes)?;
Some(Buffers { format, scale, pitch, uploads, card, turn: 0, fresh: false, uploaded: false })
}
fn write(&mut self, lines: &[Row]) {
@@ -708,36 +573,7 @@ impl Panel {
)]);
buffers.uploaded = true;
}
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: w,
Height: h,
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.min(width),
bottom: h.min(height),
back: 1,
};
list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&part));
copy_box(list, &buffers.card, format, (w, h), buffers.pitch, back, (0, 0), (width, height));
}
true
}
@@ -745,15 +581,16 @@ impl Panel {
#[cfg(test)]
mod tests {
use super::super::dots::{glyph, half};
use super::*;
/// Every character the lines use has its own picture, and no two look
/// alike.
#[test]
fn characters_differ() {
let used: Vec<u8> = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./-%:+ ").collect();
let used: Vec<u8> = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./-%:+ ,;'`~()[]<>=\\&*!?#_\"|").collect();
for (i, a) in used.iter().enumerate() {
assert_ne!(glyph(*a), glyph(b'#'), "{} has a picture", *a as char);
assert_ne!(glyph(*a), glyph(0), "{} has a picture", *a as char);
assert!(glyph(*a).iter().all(|row| row >> GLYPH.0 == 0));
for b in &used[i + 1..] {
assert_ne!(glyph(*a), glyph(*b), "{} {}", *a as char, *b as char);
@@ -761,6 +598,12 @@ mod tests {
}
}
#[test]
fn the_key_layout_keeps_the_build_on_the_last_line() {
assert_eq!(with_keys("32 GB RAM - BUILD 1 T2", "on foot"), "KEYS on foot - BUILD 1 T2");
assert!(with_keys(&"x".repeat(99), "vehicle").len() <= COLUMNS as usize);
}
fn rows() -> Vec<Row> {
let mut rows = vec![Row::Head("48".into(), "96".into())];
rows.extend((0..PAIRS).map(|i| Row::Pair(format!("NAME {i}"), "1.0 FPS".into())));
+213
View File
@@ -0,0 +1,213 @@
//! Diagnostics: what the waits for landings are made of. One thread lands
//! flights; it says which phase it is in, and a wait takes how much of each
//! phase passed meanwhile. So the parts of a wait are all of it.
use std::sync::{Mutex, MutexGuard};
use std::time::Instant;
/// What the thread that lands flights does.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Phase {
/// Nothing in the line.
Idle,
/// The card runs the line's first flight.
Card,
/// Looks through what is to come back.
Look,
/// The card copies what is to come back.
Fetch,
/// What came goes into title memory.
Merge,
/// The title is told, and what is left.
Rest,
/// Textures' and buffers' read-backs.
ReadBack,
/// The fills and copies of card steps are looked at and let go.
Steps,
/// The plans and the lists' tables are given back.
Lists,
}
const PHASES: usize = 9;
pub(super) type Parts = [u64; PHASES];
/// Nanoseconds of each phase so far; the one it is in, and since when.
struct Clock {
done: Parts,
now: Phase,
since: u64,
/// When waiters were last woken.
told: u64,
}
impl Clock {
const fn new() -> Clock {
Clock { done: [0; PHASES], now: Phase::Idle, since: 0, told: 0 }
}
fn enter(&mut self, phase: Phase, at: u64) {
self.done[self.now as usize] += at.saturating_sub(self.since);
(self.now, self.since) = (phase, at.max(self.since));
}
fn at(&self, at: u64) -> Parts {
let mut parts = self.done;
parts[self.now as usize] += at.saturating_sub(self.since);
parts
}
}
/// The waits' sums since the last line of the log, for a reason to wait.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub(super) struct Sums {
waits: u64,
parts: Parts,
/// From the last waking to the waiter's going on (in the parts, too).
woken: u64,
/// Flights in the line when the wait began.
ahead: u64,
}
impl Sums {
fn add(&mut self, from: &Parts, to: &Parts, woken: u64, ahead: u64) {
self.waits += 1;
for (sum, (from, to)) in self.parts.iter_mut().zip(from.iter().zip(to)) {
*sum += to - from;
}
self.woken += woken;
self.ahead += ahead;
}
}
/// Waits for title memory read (learned pages), and all others.
const KINDS: usize = 2;
static CLOCK: Mutex<Clock> = Mutex::new(Clock::new());
static SUMS: Mutex<[Sums; KINDS]> = Mutex::new([Sums { waits: 0, parts: [0; PHASES], woken: 0, ahead: 0 }; KINDS]);
fn lock<T>(of: &'static Mutex<T>) -> MutexGuard<'static, T> {
of.lock().unwrap_or_else(|e| e.into_inner())
}
fn ns() -> u64 {
static START: std::sync::LazyLock<Instant> = std::sync::LazyLock::new(Instant::now);
START.elapsed().as_nanos() as u64
}
/// The thread that lands flights is in this phase from now on.
pub(super) fn enter(phase: Phase) {
let mut clock = lock(&CLOCK);
// (The time is taken behind the lock: it never goes back.)
let at = ns();
clock.enter(phase, at);
}
/// Waiters are woken now.
pub(super) fn told() {
let mut clock = lock(&CLOCK);
clock.told = ns();
}
/// A wait that began.
pub(super) struct Wait {
from: Parts,
began: u64,
ahead: u64,
}
pub(super) fn begin(ahead: usize) -> Wait {
let clock = lock(&CLOCK);
let began = ns();
Wait { from: clock.at(began), began, ahead: ahead as u64 }
}
pub(super) fn end(wait: Wait, read: bool) {
let (to, woken) = {
let clock = lock(&CLOCK);
let at = ns();
(clock.at(at), at.saturating_sub(clock.told.max(wait.began)))
};
lock(&SUMS)[usize::from(!read)].add(&wait.from, &to, woken, wait.ahead);
}
/// A line for each kind of wait, a frame's share.
pub(super) fn report(frames: f64) {
let sums = std::mem::take(&mut *lock(&SUMS));
for (sums, kind) in sums.iter().zip(["title memory read", "all else"]) {
tracing::info!("{}", said(sums, kind, frames));
}
}
fn said(sums: &Sums, kind: &str, frames: f64) -> String {
let p = sums.parts.map(|ns| ns as f64 / 1e6 / frames);
let all: f64 = p.iter().sum();
format!(
"waits for landings, {kind}, per frame: {:.1} waits, {all:.1} ms, of it the card running {:.1}, looking through {:.1}, \
the card fetching {:.1}, merging {:.1}, the rest {:.1}, nothing in the line {:.1} (and read-backs {:.1}, steps {:.1}, lists {:.1}); {:.1} of it after the waking; \
{:.1} flights in the line when it began",
sums.waits as f64 / frames,
p[Phase::Card as usize],
p[Phase::Look as usize],
p[Phase::Fetch as usize],
p[Phase::Merge as usize],
p[Phase::Rest as usize],
p[Phase::Idle as usize],
p[Phase::ReadBack as usize],
p[Phase::Steps as usize],
p[Phase::Lists as usize],
sums.woken as f64 / 1e6 / frames,
sums.ahead as f64 / sums.waits.max(1) as f64,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_parts_are_all_of_a_wait() {
let mut clock = Clock::new();
clock.enter(Phase::Card, 100);
// It begins in the middle of a phase and ends in the middle of one.
let from = clock.at(150);
clock.enter(Phase::Look, 400);
clock.enter(Phase::Fetch, 450);
clock.enter(Phase::Merge, 700);
clock.enter(Phase::Rest, 800);
clock.enter(Phase::Idle, 850);
let to = clock.at(900);
let mut sums = Sums::default();
sums.add(&from, &to, 50, 3);
let of = |p: Phase| sums.parts[p as usize];
assert_eq!(sums.parts.iter().sum::<u64>(), 900 - 150);
assert_eq!((of(Phase::Card), of(Phase::Look), of(Phase::Fetch)), (250, 50, 250));
assert_eq!((of(Phase::Merge), of(Phase::Rest), of(Phase::Idle)), (100, 50, 50));
}
#[test]
fn a_phase_twice_is_added_up_and_one_in_one_phase_is_all_that() {
let mut clock = Clock::new();
clock.enter(Phase::Card, 0);
let from = clock.at(10);
for i in 0..5 {
clock.enter(Phase::Look, 100 + i * 100);
clock.enter(Phase::Card, 150 + i * 100);
}
let to = clock.at(700);
assert_eq!(to[Phase::Look as usize] - from[Phase::Look as usize], 250);
assert_eq!(to.iter().sum::<u64>() - from.iter().sum::<u64>(), 690);
let (from, to) = (clock.at(700), clock.at(760));
assert_eq!(to[Phase::Card as usize] - from[Phase::Card as usize], 60);
}
#[test]
fn the_line_says_a_frames_share() {
let mut sums = Sums::default();
sums.add(&[0; PHASES], &[0, 30_000_000, 2_000_000, 4_000_000, 3_000_000, 1_000_000, 0, 0, 0], 500_000, 4);
sums.add(&[0; PHASES], &[0; PHASES], 0, 2);
let line = said(&sums, "x", 2.0);
assert!(line.contains("1.0 waits, 20.0 ms, of it the card running 15.0, looking through 1.0"), "{line}");
assert!(line.contains("fetching 2.0, merging 1.5, the rest 0.5, nothing in the line 0.0"), "{line}");
assert!(line.contains("3.0 flights in the line"), "{line}");
}
}
+45 -1
View File
@@ -50,7 +50,7 @@ pub mod frame;
mod book;
#[cfg(windows)]
mod blocked;
#[cfg(all(windows, feature = "diagnostics"))]
#[cfg(windows)]
mod framegen;
#[cfg(windows)]
mod host;
@@ -148,6 +148,50 @@ mod test_display;
#[cfg(windows)]
pub use host::on_failure;
#[cfg(all(windows, feature = "diagnostics"))]
pub use host::panel_keys;
/// Gives the key guide its text: a box in the lower right corner of what is
/// shown, over the title's picture. F1 shows and hides it while one of our
/// windows has the focus; it starts hidden. With `VICTORY_KEY_GUIDE=1` it is
/// shown for the first 15 s of rows, and `title` alone for 4 s after each
/// change of it; `always` shows it until F1 hides it. [`key_guide_notice`]
/// shows `title` alone whatever it says, but for `0`.
///
/// `title` names the layout ("Keyboard and mouse, on foot"). A row is the
/// pad's button ("RB"), the key ("Q") and what it does; the first 24 are
/// shown, with a "..." line if there are more. Letters are shown as capitals,
/// and texts too long for their column (12, 18 and 36 letters) are cut. No
/// rows: nothing is shown.
///
/// Any thread may call it at any time, as often as it likes: the same text
/// again is compared and no more, other text is copied and shown within a
/// tenth of a second. It never waits for the card or for a frame. Before the
/// first call with rows nothing of the guide runs. The key is only looked at
/// here; `victory-hle` keeps it from the title. (Does nothing on other systems than Windows.)
pub fn key_guide(title: &str, rows: &[(String, String, String)]) {
#[cfg(windows)]
host::guide::key_guide(title, rows);
#[cfg(not(windows))]
let _ = (title, rows);
}
/// Shows the key guide's title alone for 4 s, for a change nobody may miss (the
/// keys do something else now), unless the whole guide is shown or
/// `VICTORY_KEY_GUIDE` is `0`. Any thread, as [`key_guide`].
pub fn key_guide_notice() {
#[cfg(windows)]
host::guide::notice();
}
/// The whole guide is shown for a menu of the caller's, or no longer. From the
/// first call on F1 is the caller's alone. Any thread, as [`key_guide`].
pub fn key_guide_menu(open: bool) {
#[cfg(windows)]
host::guide::menu(open);
#[cfg(not(windows))]
let _ = open;
}
/// Whether `switch` is on now, if it is one of those `VICTORY_AB` turns on and
/// off while the title runs (`ab`).
+12 -1
View File
@@ -214,7 +214,11 @@ impl Detached {
/// fps (session 7900-play, 2026-11-27).
pub(crate) fn release_tables(&mut self) {
if early_tables() {
self._state.tables_done();
if tables_once() {
self._state.slots_done();
} else {
self._state.tables_done();
}
}
}
@@ -232,6 +236,13 @@ fn early_tables() -> bool {
crate::toggled!("VICTORY_EARLY_TABLES")
}
/// Dynamic slots of lists that ran go back many at a time (on unless
/// `VICTORY_TABLES_ONCE=0`: table by table, each behind the allocator's lock).
#[cfg(windows)]
fn tables_once() -> bool {
crate::toggled!("VICTORY_TABLES_ONCE")
}
/// A host list that has run and waits to be used again, and the bytes of
/// upload memory it keeps.
#[cfg(windows)]
+9 -4
View File
@@ -214,6 +214,7 @@ pub(crate) fn take(start: u64) -> Option<Vec<(u32, u32)>> {
TAKEN[0].fetch_add(n, Relaxed);
TAKEN[1].fetch_add(1, Relaxed);
TAKEN[2].fetch_add(began.elapsed().as_nanos() as u64, Relaxed);
TAKEN[3].fetch_add(runs.len() as u64, Relaxed);
Some(runs)
}
@@ -626,8 +627,8 @@ fn mark_slot(slot: usize) {
/// Our own calls' marks since the last line.
static MARKED_BY_US: AtomicU64 = AtomicU64::new(0);
/// Since the last line: slots taken, takings, nanoseconds taking.
static TAKEN: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// Since the last line: slots taken, takings, nanoseconds taking, runs of slots.
static TAKEN: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
/// Since the last line, of the fallback: pages looked at whole, view records
/// no mark told of, other records changed (not views), view records told and
/// not taken yet; nanoseconds.
@@ -645,7 +646,7 @@ pub(crate) fn line(frames: f64) {
if !on() {
return;
}
let [taken, takings, ns] = [0, 1, 2].map(|i| TAKEN[i].swap(0, Relaxed));
let [taken, takings, ns, runs] = [0, 1, 2, 3].map(|i| TAKEN[i].swap(0, Relaxed));
let ours = MARKED_BY_US.swap(0, Relaxed);
let [pages, missed, other, pending, check_ns, tabled] = [0, 1, 2, 3, 4, 5].map(|i| CHECKED[i].swap(0, Relaxed));
let copies = [0, 1].map(|i| COPIES[i].swap(0, Relaxed));
@@ -664,7 +665,7 @@ pub(crate) fn line(frames: f64) {
v.iter().take(6).map(|(w, n)| format!("{w} {n}")).collect::<Vec<_>>().join(", ")
};
tracing::info!(
"renderer port 2 (VICTORY_PORT_DESCRIPTORS=1) per frame: {:.0} slots told (of them {:.0} marked by our calls, the rest by the title's {} patched stores) in {:.1} takings, {:.3} ms taking; \
"renderer port 2 (VICTORY_PORT_DESCRIPTORS=1) per frame: {:.0} slots told (of them {:.0} marked by our calls, the rest by the title's {} patched stores) in {:.1} takings, {:.3} ms taking, {:.0} runs of slots; \
of the title's memcpy/memmove calls into the heap {:.0}, {:.0} records they marked; its own memcpy's table copies {:.0}, {:.0} slots they marked; fallback: {:.1} pages looked at whole, {:.2} view records no store told of ({:.2} of them of draws' tables), {:.0} other records changed, {:.1} told and not taken yet, {:.2} ms; \
since the start: {} slots told ({} by our calls), {} pages looked at, {} view records missed; their writers: {}",
taken as f64 / frames,
@@ -672,6 +673,7 @@ pub(crate) fn line(frames: f64) {
IMAGE[2].load(Relaxed),
takings as f64 / frames,
ns as f64 / 1e6 / frames,
runs as f64 / frames,
copies[0] as f64 / frames,
copies[1] as f64 / frames,
title_copies[0] as f64 / frames,
@@ -783,8 +785,11 @@ mod tests {
store(999);
mark(start - 32);
mark(start + 1000 * 32);
let counted = || [0, 3].map(|i| TAKEN[i].load(Relaxed));
let before = counted();
assert_eq!(take(start).unwrap(), [(5, 2), (300, 1), (999, 1)]);
assert_eq!(take(start).unwrap(), []);
assert_eq!(counted(), [before[0] + 4, before[1] + 3], "slots, runs");
assert!(take(start + 32).is_none());
let_go(start);
mark(start + 5 * 32);
+1 -1
View File
@@ -953,7 +953,7 @@ extern "system" fn present(
release_held(forces());
}
let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
if frame.is_power_of_two() {
if frame.is_power_of_two() || frame.is_multiple_of(256) {
let (draws, dispatches) = crate::list::take_counts();
#[cfg(windows)]
let (drawn, dispatched) = {
+6 -2
View File
@@ -2832,10 +2832,14 @@ mod held_tests {
return;
}
let len = crate::resource::placed_bytes(&DESC).unwrap() as usize;
// Whole pages of 64 KiB, as the title's reservations logged so far:
// the texture ends within one (0x156000 bytes), and the write-watch
// need not answer past a reservation's end (see `watch::kernel_once`).
let room = len.next_multiple_of(crate::watch::PAGE);
// SAFETY: memory of our own that stays.
let at = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>();
let at = unsafe { VirtualAlloc(std::ptr::null(), room, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>();
assert!(!at.is_null());
crate::watch::title_memory_made_anew(at as usize, len);
crate::watch::title_memory_made_anew(at as usize, room);
// SAFETY: as above.
unsafe { (0..len).for_each(|i| at.add(i).write((i * 13 + i / 509) as u8 | 1)) };
let texture = crate::resource::texture_at(at as u64, &DESC).unwrap();
+284 -15
View File
@@ -183,11 +183,15 @@ impl Notes {
/// The notes of pages `[first, last)` in page order, `each` of them
/// until it says no: whether it never did. A part at a time.
fn each(&self, first: usize, last: usize, mut each: impl FnMut(usize, u64) -> bool) -> bool {
let walk = |(from, to): (usize, usize)| {
let s = self.read(shard_of(from));
s.written.range(from..to).all(|(&p, &w)| each(p, w))
};
if watch_lean() && let Some(mut pieces) = pieces_of(first, last) {
return pieces.all(walk);
}
match pieces(first, last) {
Some(pieces) => pieces.into_iter().all(|(from, to)| {
let s = self.read(shard_of(from));
s.written.range(from..to).all(|(&p, &w)| each(p, w))
}),
Some(pieces) => pieces.into_iter().all(walk),
None => {
let mut all: Vec<(usize, u64)> = Vec::new();
for shard in 0..SHARDS {
@@ -243,14 +247,54 @@ impl Notes {
/// `None` for a range of more pieces than is worth walking (then each part
/// is looked at once).
fn pieces(first: usize, last: usize) -> Option<Vec<(usize, usize)>> {
if first >= last {
return Some(Vec::new());
}
let (a, b) = (first >> SHARD_SHIFT, (last - 1) >> SHARD_SHIFT);
if b - a >= 4 * SHARDS {
#[cfg(test)]
LISTS_IN_TEST.set(LISTS_IN_TEST.get() + 1);
Some(pieces_of(first, last)?.collect())
}
/// [`pieces`], none of them kept.
fn pieces_of(first: usize, last: usize) -> Option<impl Iterator<Item = (usize, usize)>> {
// (An empty range has no piece: the one past its last is its first.)
let (a, b) = if first < last { (first >> SHARD_SHIFT, ((last - 1) >> SHARD_SHIFT) + 1) } else { (0, 0) };
if b - a > 4 * SHARDS {
return None;
}
Some((a..=b).map(|piece| (first.max(piece << SHARD_SHIFT), last.min((piece + 1) << SHARD_SHIFT))).collect())
Some((a..b).map(move |piece| (first.max(piece << SHARD_SHIFT), last.min((piece + 1) << SHARD_SHIFT))))
}
/// Whether a look at the journal ([`Notes::each`]) keeps no list of the
/// pieces of its range, and [`nothing_new`] first looks whether the copy has
/// every page at all (`VICTORY_WATCH_LEAN=1`, off by default; A/B-able by
/// that name). After HexNomad23/victory-rdna4-0326 ba05097d by Jefry Local.
///
/// 27 ns of 94 a look on one thread, 16-20 of 145 with seven looking: for
/// 8,078 looks a frame 0.21-0.22 ms on one thread, 0.13-0.16 of all seven's
/// time, 0.02 of each. The last is the one to expect: a long run had 7,360
/// of its 8,078 refreshes a frame on several threads. Too little (under 0.1)
/// to be on, or for a run of its own. Of a look at a copy that lacks a page, 3-4 ns of 10 on
/// one thread, 22-57 of 38-73 with seven (`bench_lean`).
fn watch_lean() -> bool {
#[cfg(test)]
if let Some(on) = LEAN_IN_TEST.get() {
return on;
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
#[cfg(feature = "diagnostics")]
{
static BIT: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
if let Some(bit) = *BIT.get_or_init(|| crate::ab::bit("VICTORY_WATCH_LEAN")) {
return crate::ab::on(bit);
}
}
*ON.get_or_init(|| std::env::var("VICTORY_WATCH_LEAN").is_ok_and(|v| v.trim() == "1"))
}
#[cfg(test)]
thread_local! {
/// [`watch_lean`], for what this thread does.
static LEAN_IN_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
/// Lists of pieces ([`pieces`]) asked for on this thread.
static LISTS_IN_TEST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Parts of [`Notes`] held ([`Notes::hold`]).
@@ -851,7 +895,13 @@ fn one_view(start: usize, end: usize) -> bool {
/// One kernel call: the pages of `[first, last)` written since the last
/// asking, in order, each once, with their written parts, and reset; `None`
/// if the kernel refuses the range.
/// if the kernel refuses the range. Unpatched Wine refuses one that runs past
/// the end of its reservation, be it by the rest of the last 64 KiB (tested;
/// Windows' rule is that the range lies in the reservation, and its run of
/// the tests fits that); Wine with
/// `keep/wine-placeholder-map-and-view-write-watch.patch` answers for what is
/// there. The title's reservations logged so far are whole pages of 64 KiB;
/// nothing makes them so, and one that is not is hashed or copied whole.
fn kernel_once(first: usize, last: usize) -> Option<Vec<(usize, u16)>> {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
@@ -1752,8 +1802,29 @@ pub(crate) fn known(start: usize, end: usize) -> bool {
/// by their bits. `false` if something would have to be asked.
pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool {
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
nothing_new_of((first, last), base, copied, ranged, || published(start, end), journal)
}
/// [`nothing_new`] of pages `[first, last)`: `published`, whether their
/// blocks are known by their bits, `journal`, the journal.
fn nothing_new_of<J: std::ops::Deref<Target = Journal>>(
(first, last): (usize, usize),
base: usize,
copied: &[u64],
ranged: u64,
published: impl FnOnce() -> bool,
journal: impl FnOnce() -> J,
) -> bool {
let of_copy = || first.checked_sub(base).and_then(|from| copied.get(from..last - base));
let has_all = |taken: &[u64]| ranged != 0 || taken.iter().all(|&at| at != 0);
let lean = watch_lean();
// Pages the copy never took: whatever the bits and the journal say, the
// answer is no.
if lean && !of_copy().is_some_and(has_all) {
return false;
}
// The bits first, then the journal, as in `writes`.
let known = published(start, end);
let known = published();
#[cfg(feature = "diagnostics")]
if known {
crate::faultbook::note(crate::faultbook::What::Known, first, last, 1);
@@ -1762,11 +1833,10 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64],
if !known && !j.ahead.holds(first, last) {
return false;
}
let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
let Some(taken) = of_copy() else {
return false;
};
(ranged != 0 || taken.iter().all(|&at| at != 0))
&& j.notes.each(first, last, |page, write| write <= taken[page - first].max(ranged))
(lean || has_all(taken)) && j.notes.each(first, last, |page, write| write <= taken[page - first].max(ranged))
}
impl Tracked {
@@ -6885,6 +6955,9 @@ mod port7_tests {
assert_eq!(shards_of(5, 5 + SHARDS * P), u64::MAX);
assert_eq!(pieces(P - 2, 2 * P + 3), Some(vec![(P - 2, P), (P, 2 * P), (2 * P, 2 * P + 3)]));
assert_eq!(pieces(0, 1 << 40), None);
assert_eq!(pieces(P - 1, 4 * SHARDS * P).map(|p| p.len()), Some(4 * SHARDS));
assert_eq!(pieces(P - 1, 4 * SHARDS * P + 1), None);
assert_eq!((pieces(5, 5), pieces(6, 5)), (Some(vec![]), Some(vec![])));
let notes = Notes::new();
let mut want: BTreeMap<usize, u64> = BTreeMap::new();
let mut seed = 7;
@@ -6906,6 +6979,202 @@ mod port7_tests {
assert_eq!(notes.hold(u64::MAX, false).range(0, usize::MAX / 2).len(), want.len());
}
/// [`watch_lean`] on this thread.
fn lean<T>(on: bool, f: impl FnOnce() -> T) -> T {
LEAN_IN_TEST.set(Some(on));
let out = f();
LEAN_IN_TEST.set(None);
out
}
/// With no list of pieces kept (and none is, where the range is walked by
/// pieces), a range's notes are walked as with one: the same notes, in
/// page order, until the walker says no; over one
/// page, several parts, the most pieces walked and one more, empty
/// ranges and ones that end before they begin.
#[test]
fn the_lean_walk_is_the_walk() {
const P: usize = 1 << SHARD_SHIFT;
let most = 4 * SHARDS * P;
let mut notes = Notes::new();
let mut want: BTreeMap<usize, u64> = BTreeMap::new();
let mut seed = 21;
for n in 1..6000u64 {
let page = rng(&mut seed, 2 * most);
notes.note(page, WHOLE, n);
want.insert(page, n);
}
let mut ranges = vec![(0, 0), (9, 3), (7 * P, 7 * P), (P - 1, P), (P, P + 1), (P - 1, P + 1), (0, usize::MAX / 2)];
for k in [0, 1, P - 1] {
ranges.extend([(k, k + most - P), (k, k + most - 1), (k, k + most), (k, k + most + 1), (k, k + most + P)]);
}
ranges.extend(want.keys().take(50).map(|&p| (p, p + 1)));
for n in 0..3000 {
let first = rng(&mut seed, 2 * most);
ranges.push((first, first + rng(&mut seed, [3, 20, 3 * P, 2 * most][n % 4])));
}
for (first, last) in ranges {
let expected: Vec<(usize, u64)> = if first < last { want.range(first..last).map(|(&p, &w)| (p, w)).collect() } else { Vec::new() };
for stop in [usize::MAX, 0, rng(&mut seed, expected.len() + 1)] {
let mut walks = [false, true].map(|on| {
lean(on, || {
let mut seen = Vec::new();
let lists = LISTS_IN_TEST.get();
let all = notes.each(first, last, |p, w| {
seen.push((p, w));
seen.len() <= stop
});
let by_pieces = pieces_of(first, last).is_some();
assert_eq!(LISTS_IN_TEST.get() - lists, usize::from(!on || !by_pieces), "{first}..{last}, lean {on}");
(all, seen)
})
});
assert_eq!(walks[0], walks[1], "{first}..{last}, no after {stop}");
assert_eq!(walks[1].0, expected.len() <= stop, "{first}..{last}, no after {stop}");
walks[1].1.truncate(stop.saturating_add(1));
assert_eq!(walks[1].1, expected[..expected.len().min(stop.saturating_add(1))], "{first}..{last}");
}
}
}
/// What [`nothing_new`] answered before [`watch_lean`].
fn nothing_new_before((first, last): (usize, usize), base: usize, copied: &[u64], ranged: u64, published: bool, j: &Journal) -> bool {
if !published && !j.ahead.holds(first, last) {
return false;
}
let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
return false;
};
(ranged != 0 || taken.iter().all(|&at| at != 0)) && j.notes.range(first, last).into_iter().all(|(page, write)| write <= taken[page - first].max(ranged))
}
fn random_notes(seed: &mut u64, from: usize, pages: usize, most: usize) -> Journal {
let mut j = Journal { notes: Notes::new(), ahead: Ahead::new(), ahead_asked: 0, kept: false };
for _ in 0..rng(seed, most + 1) {
let (page, at) = (from + rng(seed, pages), 1 + rng(seed, 20) as u64);
j.notes.note(page, WHOLE, at);
}
let ranges = (0..rng(seed, 4))
.map(|_| {
let first = from + rng(seed, pages);
(first, first + rng(seed, pages))
})
.collect();
j.ahead.set(ranges);
j
}
/// Over random copies and journals every answer is the one before, with
/// the switch and without: with it the bits and the journal are not
/// looked at for a copy that lacks a page, whose answer is no.
#[test]
fn nothing_new_answers_the_same_lean() {
// (Over the end of a part.)
const FROM: usize = (1 << SHARD_SHIFT) - 20;
let mut seed = 5;
// Answers yes, no; looks not made.
let (mut answers, mut early) = ([0; 2], 0);
for _ in 0..60_000 {
let j = random_notes(&mut seed, FROM, 40, 12);
let base = FROM + rng(&mut seed, 6);
let holes = rng(&mut seed, 3) == 0;
let copied: Vec<u64> = (0..rng(&mut seed, 40))
.map(|_| if holes && rng(&mut seed, 8) == 0 { 0 } else { 8 + rng(&mut seed, 20) as u64 })
.collect();
// (Some outside the copy.)
let first = FROM + rng(&mut seed, 40);
let last = first + rng(&mut seed, 12);
let ranged = if rng(&mut seed, 3) == 0 { rng(&mut seed, 25) as u64 } else { 0 };
let published = rng(&mut seed, 2) == 0;
let before = nothing_new_before((first, last), base, &copied, ranged, published, &j);
for on in [false, true] {
let looked = std::cell::Cell::new(0);
let asked = || {
looked.set(looked.get() + 1);
published
};
let journal = || {
looked.set(looked.get() + 1);
&j
};
let now = lean(on, || nothing_new_of((first, last), base, &copied, ranged, asked, journal));
assert_eq!(now, before, "lean {on}: {first}..{last} of {base} {copied:?}, {ranged}, {published}");
assert!(on || looked.get() == 2);
if looked.get() == 0 {
early += 1;
}
}
answers[usize::from(before)] += 1;
}
assert!(answers.iter().all(|&n| n > 3000) && early > 3000, "{answers:?} {early}");
}
/// What looks cost with the switch and without, per look and for as many
/// as a frame has (8,078, of which 6,974 walk the journal to the end;
/// here all do, or none); ranges of about 5 pages (a frame's are 2,374 MB
/// in all), on one thread and on 7.
#[test]
#[ignore = "benchmark"]
fn bench_lean() {
const PAGES: usize = 160_000;
const LOOKS: usize = 8078;
let mut seed = 9;
let mut j = Journal { notes: Notes::new(), ahead: Ahead::new(), ahead_asked: 0, kept: false };
for _ in 0..40_000 {
let page = rng(&mut seed, PAGES);
j.notes.note(page, WHOLE, 5);
}
j.ahead.set((0..400).map(|k| (k * PAGES / 400, (k + 1) * PAGES / 400 + 100)).collect());
let looks: Vec<(usize, Vec<u64>, Vec<u64>)> = (0..LOOKS)
.map(|_| {
let n = 1 + rng(&mut seed, 9);
let mut holed = vec![9; n];
holed[rng(&mut seed, n)] = 0;
(rng(&mut seed, PAGES - 20), vec![9; n], holed)
})
.collect();
let j = RwLock::new(j);
for threads in [1usize, 7] {
for what in ["all copied", "one page never copied"] {
let mut times = [Vec::new(), Vec::new()];
for round in 0..400 {
let on = round % 2 == 1;
let spent: u64 = std::thread::scope(|s| {
let (looks, j) = (&looks, &j);
let all: Vec<_> = (0..threads)
.map(|t| {
s.spawn(move || {
lean(on, || {
let began = std::time::Instant::now();
for (first, copied, holed) in looks[t..].iter().step_by(threads) {
let of = if what == "all copied" { copied } else { holed };
let same = nothing_new_of((*first, first + of.len()), *first, of, 0, || true, || j.read().unwrap());
assert_eq!(std::hint::black_box(same), what == "all copied");
}
began.elapsed().as_nanos() as u64
})
})
})
.collect();
all.into_iter().map(|t| t.join().unwrap()).sum()
});
times[usize::from(on)].push(spent as f64 / LOOKS as f64);
}
let [old, new] = times.map(|mut v| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
});
println!(
"{what}, {threads} threads: {old:.1} ns a look before, {new:.1} lean; {LOOKS} looks {:.3} ms of all threads before, {:.3} lean; a thread {:.3} / {:.3}",
old * LOOKS as f64 / 1e6,
new * LOOKS as f64 / 1e6,
old * LOOKS as f64 / 1e6 / threads as f64,
new * LOOKS as f64 / 1e6 / threads as f64
);
}
}
}
/// Noted out of order (shared noters' numbers may come in any order): a
/// page's note, and its parts', only go up.
#[test]
+1
View File
@@ -31,6 +31,7 @@ windows-sys = { workspace = true, features = [
"Win32_System_Power",
"Win32_System_ProcessStatus",
"Win32_System_Threading",
"Win32_UI_Input",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Input_XboxController",
"Win32_UI_WindowsAndMessaging",
+296 -15
View File
@@ -52,6 +52,11 @@ const GET_VERSIONS: u64 = 4;
const OVERRIDE_VERSION: u64 = 5;
const GET_PROVIDER_VERSION: u64 = 6;
const MEMORY_USAGE_WITH_DEVICE: u64 = 0x1_0009;
const GLOBAL_DEBUG: u64 = 1;
const UPSCALE_RATIO: u64 = 0x1_0002;
const RENDER_SIZE: u64 = 0x1_0003;
const JITTER_PHASES: u64 = 0x1_0004;
const JITTER_OFFSET: u64 = 0x1_0005;
#[repr(C)]
#[derive(Clone, Copy)]
@@ -142,6 +147,64 @@ struct OverrideVersion {
const _: () = assert!(size_of::<OverrideVersion>() == 0x18);
/// The jitter phase count query. The title divides by the answer every frame
/// and looks at no return code (`victory_loader::resolution`'s notes).
#[repr(C)]
struct JitterPhases {
header: Header,
render_width: u32,
output_width: u32,
count: *mut i32,
}
/// The jitter offset query: the frame's place among the phases, two floats.
#[repr(C)]
struct JitterOffset {
header: Header,
index: i32,
phases: i32,
x: *mut f32,
y: *mut f32,
}
const _: () = assert!(size_of::<JitterPhases>() == 0x20 && size_of::<JitterOffset>() == 0x28);
/// FidelityFX's phase count, 8 x (output / render)^2 cut to a whole number,
/// but never below 1.
fn phase_count(render_width: u32, output_width: u32) -> i32 {
if render_width == 0 {
return 1;
}
let ratio = output_width as f32 / render_width as f32;
((8.0 * ratio * ratio) as i32).max(1)
}
/// FidelityFX's jitter: Halton sequences of bases 2 and 3, less a half.
fn jitter(index: i32, phases: i32) -> [f32; 2] {
let at = index.rem_euclid(phases.max(1)) as u32 + 1;
let halton = |base: u32| {
let (mut i, mut f, mut r) = (at, 1.0f32, 0.0f32);
while i > 0 {
f /= base as f32;
r += f * (i % base) as f32;
i /= base;
}
r - 0.5
};
[halton(2), halton(3)]
}
/// The host's answer to a phase count query (`code`, and what it wrote to
/// `count`) kept if it is one the title can divide by; else ours. Whether the
/// host's was kept.
fn settle_phases(code: u32, count: &mut i32, render_width: u32, output_width: u32) -> bool {
let kept = code == OK && *count >= 1;
if !kept {
*count = phase_count(render_width, output_width);
}
kept
}
/// The upscaler version asked for: `VICTORY_FSR_VERSION` (`4`, `3`, or a
/// full one such as `3.1.6`), else FSR 4 with the launcher's FSR 4
/// (`FSR4_UPGRADE=1`) and FSR 3 without it.
@@ -215,7 +278,6 @@ pub fn use_host_dir(dir: Option<&Path>) {
tracing::info!(folder = %dir.display(), versions, "FidelityFX: the host's upscaler serves the title's");
let _ = HOST.set(host);
victory_gpu::external::enable_host_fidelityfx();
#[cfg(feature = "diagnostics")]
if let Ok(mode) = std::env::var("VICTORY_FIDELITYFX_FRAMEGEN")
&& matches!(mode.as_str(), "1" | "4")
{
@@ -413,6 +475,8 @@ extern "C" fn ffxCreateContext(
// SAFETY: a PC chain; the title's later descriptions live for the call.
let code = unsafe { (host.create)(context, &mut upscale.header, memory) };
if code != OK {
// SAFETY: the title passes its context slot.
unsafe { no_context(context) };
tracing::error!(code, render = ?upscale.max_render, output = ?upscale.max_output, flags = format_args!("{:#x}", upscale.flags), "FidelityFX: the host refused the title's upscaler");
return code;
}
@@ -429,7 +493,10 @@ extern "C" fn ffxCreateContext(
// SAFETY: a NUL-terminated name the DLL keeps, if any.
let name = (!version.name.is_null())
.then(|| unsafe { CStr::from_ptr(version.name) }.to_string_lossy());
victory_gpu::external::note_upscaler(name.as_deref().unwrap_or("?"));
victory_gpu::external::note_upscaler(
name.as_deref().unwrap_or("?"),
f64::from(upscale.max_render[0]) / f64::from(upscale.max_output[0].max(1)),
);
tracing::info!(
provider = name.as_deref().unwrap_or("?"),
id = format_args!("{:#x}", version.id),
@@ -439,25 +506,42 @@ extern "C" fn ffxCreateContext(
"FidelityFX: upscaler context on the host"
);
// SAFETY: a successful create wrote the context.
#[cfg(feature = "diagnostics")]
context_flags(|f| f.insert(unsafe { *context } as usize, upscale.flags));
OK
}
/// The creation flags of each upscaler context, for frame generation's
/// (diagnostics).
#[cfg(feature = "diagnostics")]
fn context_flags<R>(f: impl FnOnce(&mut std::collections::HashMap<usize, u32>) -> R) -> R {
static FLAGS: std::sync::Mutex<Option<std::collections::HashMap<usize, u32>>> = std::sync::Mutex::new(None);
f(FLAGS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
}
extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 {
#[cfg(feature = "diagnostics")]
/// Empties the slot after a refused create. The title looks at no code: what
/// it calls next must find no context.
///
/// # Safety
/// `context` is null or writable.
unsafe fn no_context(context: *mut *mut c_void) {
if !context.is_null() {
// SAFETY: the title passes its context slot.
context_flags(|f| f.remove(&(unsafe { *context } as usize)));
// SAFETY: the caller's promise.
unsafe { *context = null_mut() };
}
}
/// Whether the title's context slot holds a context. A create that failed left
/// none, the title calls on all the same, and the host reads through it.
fn made(context: *mut *mut c_void) -> bool {
// SAFETY: the title passes its context slot, or null.
!context.is_null() && !unsafe { *context }.is_null()
}
extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 {
if !made(context) {
return PARAMETER;
}
// SAFETY: the title passes its context slot.
context_flags(|f| f.remove(&(unsafe { *context } as usize)));
// SAFETY: the title passes its context.
HOST.get()
.map_or(NO_PROVIDER, |h| unsafe { (h.destroy)(context, memory) })
@@ -465,9 +549,32 @@ extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void
/// Settings (key-value pairs, debug messages) name nothing console-specific.
extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 {
let Some(host) = HOST.get() else {
return NO_PROVIDER;
};
let Some(context) = context_for(context, desc) else {
return PARAMETER;
};
// SAFETY: the title passes its context and descriptions.
HOST.get()
.map_or(NO_PROVIDER, |h| unsafe { (h.configure)(context, desc) })
unsafe { (host.configure)(context, desc) }
}
/// The context slot to give the host for a query or a setting: the title's;
/// without a context none, for the kinds that need none, else not at all.
fn context_for(context: *mut *mut c_void, desc: *const Header) -> Option<*mut *mut c_void> {
if desc.is_null() {
return None;
}
if made(context) {
return Some(context);
}
// SAFETY: the title passes a description.
let kind = unsafe { (*desc).kind };
if matches!(kind, GLOBAL_DEBUG | UPSCALE_RATIO | RENDER_SIZE) {
return Some(null_mut());
}
once!(warn, kind = format_args!("{kind:#x}"), "FidelityFX: a call without a context (its create was refused); it did not run");
None
}
extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 {
@@ -488,10 +595,68 @@ extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 {
);
return PARAMETER;
}
// SAFETY: as above.
// The title uses the answers of these two whatever the return code says.
if kind == JITTER_PHASES || kind == JITTER_OFFSET {
// SAFETY: the title passes its context slot.
let ask = |desc| if made(context) { unsafe { (host.query)(context, desc) } } else { PARAMETER };
// SAFETY: the title's query, by its type.
return unsafe { answer_jitter(desc, ask) };
}
let Some(context) = context_for(context, desc) else {
return PARAMETER;
};
// SAFETY: the title passes its context and descriptions.
unsafe { (host.query)(context, desc) }
}
/// Answers a jitter query with `ask` (the host); if that fails, as FidelityFX
/// would. The code is the host's.
///
/// # Safety
/// `desc` is a jitter query whose result pointers are null or writable.
unsafe fn answer_jitter(desc: *mut Header, ask: impl FnOnce(*mut Header) -> u32) -> u32 {
// SAFETY: the caller's promise, also for what follows.
if unsafe { (*desc).kind } == JITTER_PHASES {
let (slot, render, output) = unsafe {
let q = &*desc.cast::<JitterPhases>();
(q.count, q.render_width, q.output_width)
};
if slot.is_null() {
return PARAMETER;
}
// What was there before is no answer of the host's.
unsafe { *slot = 0 };
let code = ask(desc);
let count = unsafe { &mut *slot };
let host_said = *count;
if settle_phases(code, count, render, output) {
once!(info, count = *count, render, output, "FidelityFX: jitter phases");
} else {
once!(warn, code, host_said, used = *count, render, output, "FidelityFX: the host gave no jitter phase count; ours is used");
}
return code;
}
let code = ask(desc);
if code != OK {
let q = unsafe { &*desc.cast::<JitterOffset>() };
let [x, y] = jitter(q.index, q.phases);
if !q.x.is_null() {
unsafe { *q.x = x };
}
if !q.y.is_null() {
unsafe { *q.y = y };
}
once!(warn, code, "FidelityFX: the host gave no jitter offset; ours is used");
}
code
}
/// A description as the host takes it: its header's address, with all of it
/// behind.
fn whole(dispatch: &mut DispatchUpscale) -> *mut Header {
std::ptr::from_mut(dispatch).cast()
}
extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
let Some(host) = HOST.get() else {
return NO_PROVIDER;
@@ -509,6 +674,10 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
);
return UNKNOWN_TYPE;
}
if !made(context) {
once!(warn, "FidelityFX: an upscaling without a context (its create was refused); it did not run");
return PARAMETER;
}
// SAFETY: an upscaling, by its type.
let mut dispatch = unsafe { desc.cast::<DispatchUpscale>().read() };
let title_list = dispatch.list.cast::<Object>().cast_const();
@@ -518,7 +687,6 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
// the upscaling never ran (a black screen).
let run = move |list: *const Object| -> u32 {
// Depth and motion as the title names them, for frame generation.
#[cfg(feature = "diagnostics")]
let title = dispatch;
// Alive for the call (the list holds them too).
let mut textures = Vec::new();
@@ -555,10 +723,11 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
let code = victory_gpu::external::record(list, |host_list| {
dispatch.list = host_list.as_raw();
// SAFETY: the PC dispatch on host objects; the context is the host's.
unsafe { (host.dispatch)(context, &raw mut dispatch.header) }
// (The whole description: a closure that names one field has that
// field alone, and the host would read past it.)
unsafe { (host.dispatch)(context, whole(&mut dispatch)) }
})
.unwrap_or(PARAMETER);
#[cfg(feature = "diagnostics")]
if code == OK && !context.is_null() {
// SAFETY: the title passes its context slot.
let flags = context_flags(|f| f.get(&(unsafe { *context } as usize)).copied()).unwrap_or(0);
@@ -586,7 +755,6 @@ extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
/// `ffxDispatchDescUpscale`: jitter, motion-vector scale, render size,
/// output size, sharpening, sharpness, frame time, pre-exposure, reset,
/// camera, flags) and its context's creation `flags`.
#[cfg(feature = "diagnostics")]
fn frame_inputs(d: &DispatchUpscale, flags: u32) -> victory_gpu::external::FrameInputs {
let f = |i: usize| f32::from_bits(d.rest[i]);
victory_gpu::external::FrameInputs {
@@ -692,6 +860,119 @@ mod tests {
assert_eq!(asked.header.next, &raw mut rest);
}
/// The launcher's output widths and render scales (a third exact).
const OUTPUTS: [u32; 5] = [1280, 1664, 1920, 2560, 3840];
const SCALES: [(f32, i32); 5] = [(1.0, 8), (0.6667, 18), (0.5882, 23), (0.5, 32), (1.0 / 3.0, 72)];
/// The count at each, and never 0 at any sizes.
#[test]
fn the_phase_count_is_never_0() {
for output in OUTPUTS {
for (scale, want) in SCALES {
let render = (output as f32 * scale) as u32;
let got = phase_count(render, output);
// The render width is cut to a whole number: a count or so more.
assert!((want..=want + 1).contains(&got), "{render} -> {output}: {got}, not {want}");
}
for render in 0..=3 * output {
assert!(phase_count(render, output) >= 1, "{render} -> {output}");
}
}
assert_eq!(phase_count(1280, 3840), 72);
assert_eq!(phase_count(0, 1920), 1);
assert_eq!(phase_count(1920, 0), 1);
assert_eq!(phase_count(u32::MAX, 1), 1);
assert!(phase_count(1, u32::MAX) >= 1);
}
fn phases_asked(render: u32, output: u32, before: i32, ask: impl FnOnce(*mut Header) -> u32) -> (u32, i32) {
let mut count = before;
let mut q = JitterPhases { header: header(JITTER_PHASES, null_mut()), render_width: render, output_width: output, count: &mut count };
// SAFETY: a whole query of ours.
let code = unsafe { answer_jitter(&raw mut q.header, ask) };
(code, count)
}
/// What the host wrote, as a query does.
fn wrote(value: i32, code: u32) -> impl FnOnce(*mut Header) -> u32 {
move |q| {
// SAFETY: the query `phases_asked` made.
unsafe { *(*q.cast::<JitterPhases>()).count = value };
code
}
}
/// The crash: the title's count began at 0, a refused query left it there.
#[test]
fn the_title_never_gets_a_phase_count_it_cannot_divide_by() {
// The host's answer is kept, whatever the formula says.
assert_eq!(phases_asked(960, 1920, 0, wrote(32, OK)), (OK, 32));
assert_eq!(phases_asked(960, 1920, 0, wrote(7, OK)), (OK, 7));
// Refused and not written; an old value is no answer either.
assert_eq!(phases_asked(960, 1920, 0, |_| PARAMETER), (PARAMETER, 32));
assert_eq!(phases_asked(960, 1920, 5, |_| OK), (OK, 32));
assert_eq!(phases_asked(640, 1920, 5, |_| PARAMETER), (PARAMETER, 72));
// Written, but 0, negative, or with a failure.
assert_eq!(phases_asked(853, 2560, 0, wrote(0, OK)), (OK, 72));
assert_eq!(phases_asked(960, 1920, 0, wrote(-3, OK)), (OK, 32));
assert_eq!(phases_asked(960, 1920, 0, wrote(9, PARAMETER)), (PARAMETER, 32));
}
/// Without a context only what needs none goes to the host.
#[test]
fn no_context_is_never_read_through() {
let (mut none, mut one): (*mut c_void, *mut c_void) = (null_mut(), std::ptr::dangling_mut());
for kind in [GLOBAL_DEBUG, UPSCALE_RATIO, RENDER_SIZE] {
let h = header(kind, null_mut());
assert_eq!(context_for(&mut none, &h), Some(null_mut()));
assert_eq!(context_for(null_mut(), &h), Some(null_mut()));
assert_eq!(context_for(&mut one, &h), Some(&raw mut one));
}
for kind in [0, 2, GET_PROVIDER_VERSION, 0x1_0008, 0x1_000a] {
let h = header(kind, null_mut());
assert_eq!(context_for(&mut none, &h), None, "{kind:#x}");
assert_eq!(context_for(null_mut(), &h), None, "{kind:#x}");
assert_eq!(context_for(&mut one, &h), Some(&raw mut one));
}
assert_eq!(context_for(&mut one, null()), None);
// After a refused create, whatever the slot held.
// SAFETY: a slot of ours, and none.
unsafe {
no_context(null_mut());
no_context(&mut one);
}
assert!(!made(&mut one) && !made(null_mut()));
}
/// The offsets are FidelityFX's, inside half a pixel, for any index.
#[test]
fn a_refused_jitter_offset_is_answered() {
assert_eq!(jitter(0, 8), [0.0, 1.0 / 3.0 - 0.5]);
assert_eq!(jitter(1, 8)[0], -0.25);
assert_eq!(jitter(8, 8), jitter(0, 8));
for phases in [0, 1, 8, 72, -1] {
for index in [-5, 0, 1, 71, i32::MAX] {
assert!(jitter(index, phases).iter().all(|v| v.abs() <= 0.5));
}
}
let (mut x, mut y) = (f32::NAN, f32::NAN);
let mut q = JitterOffset { header: header(JITTER_OFFSET, null_mut()), index: 1, phases: 32, x: &mut x, y: &mut y };
// SAFETY: a whole query of ours.
assert_eq!(unsafe { answer_jitter(&raw mut q.header, |_| PARAMETER) }, PARAMETER);
assert_eq!([x, y], jitter(1, 32));
// The host's are kept.
let ask = |q: *mut Header| {
// SAFETY: the query below.
unsafe { *(*q.cast::<JitterOffset>()).x = 0.125 };
OK
};
(x, y) = (0.0, 0.0);
let mut q = JitterOffset { header: header(JITTER_OFFSET, null_mut()), index: 1, phases: 32, x: &mut x, y: &mut y };
// SAFETY: as above.
assert_eq!(unsafe { answer_jitter(&raw mut q.header, ask) }, OK);
assert_eq!([x, y], [0.125, 0.0]);
}
/// Without the PC build the title's own DLL serves its imports.
#[test]
fn without_the_dll_the_titles_own_runs() {
+268 -438
View File
@@ -1,13 +1,23 @@
//! `gameinput.dll`: input devices from the host. Gamepads come from XInput
//! (host slots 0-3); while none is connected, the keyboard drives one
//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own
//! too. A poll thread turns host state into readings (a new one per change)
//! too; with `VICTORY_KBM=1` the stand-in is keyboard and mouse play (`kbm`).
//! A poll thread turns host state into readings (a new one per change)
//! and runs device callbacks on connect and disconnect.
#![allow(non_snake_case)]
// Title code calls these through the objects, passing pointers the real API
// would trust.
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#[cfg(any(windows, test))]
mod guide;
#[cfg(any(windows, test))]
mod hold;
#[cfg(any(windows, test))]
mod kbm;
#[cfg(any(windows, test))]
mod menu;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::ops::Deref;
@@ -80,55 +90,49 @@ const FALLBACK_BUTTONS: [(u8, u32); 14] = [
(b'H', RIGHT_STICK),
];
/// Opt-in PC-style keyboard bindings for the stand-in gamepad
/// (`VICTORY_KBM_PC=1`). Left stick stays W/A/S/D; right stick is driven by
/// mouse look (toggled with F2 or `` ` `` / `~`) plus I/J/K/L fallback;
/// triggers come from LMB (RT) and RMB (LT). `Host::keys()` reports specific
/// left/right modifiers (`0xA0..=0xA5`) rather than generic `0x10..=0x12`.
const PC_BUTTONS: [(u8, u32); 26] = [
(0x1B, MENU), // Esc (also unlocks mouse look)
(b'P', MENU), // Pause / Map
(b'V', VIEW), // Change camera perspective
(0xA0, A), // Left Shift: Sprint
(0xA1, A), // Right Shift: Sprint
(0x0D, A), // Enter: Confirm (menus)
(0x20, X), // Space: Jump / Climb / Vault
(b'X', X), // X fallback
(b'R', B), // Reload / Melee
(0x08, B), // Backspace: Back / Cancel (menus)
(b'F', Y), // Enter / Exit vehicle
(0x09, LEFT_SHOULDER), // Tab: Weapon wheel (LB)
(b'Q', RIGHT_SHOULDER), // Q: Take cover / Handbrake (RB)
(0xA2, LEFT_STICK), // Left Ctrl: Crouch / Stealth / Horn (L3)
(0xA3, LEFT_STICK), // Right Ctrl: Crouch / Stealth / Horn (L3)
(b'C', RIGHT_STICK), // C: Look behind / Special (R3)
(0x14, RIGHT_STICK), // Caps Lock: Special (R3)
(b'H', RIGHT_STICK), // H fallback (R3)
(b'E', RIGHT), // E: Interact / Talk (D-pad Right)
(0x27, RIGHT), // Right arrow (D-pad Right)
(0x26, UP), // Up arrow: Phone (D-pad Up)
(b'M', UP), // M: Phone / Menu (D-pad Up)
(0x28, DOWN), // Down arrow: Character wheel / Minimap (D-pad Down)
(b'Z', DOWN), // Z: Expand minimap / Character wheel (D-pad Down)
(0x25, LEFT), // Left arrow (D-pad Left)
(b'G', LEFT), // G: Throw / Context left (D-pad Left)
];
/// Whether mouse-look lock (`~` / `F2`) is currently active; read by
/// `lifecycle` on `WM_SETCURSOR` to auto-hide the Windows cursor inside the
/// game window's client area while locked.
/// Whether the window holds the mouse; read by `lifecycle` on `WM_SETCURSOR`
/// to hide the cursor over the window's picture meanwhile.
#[cfg(windows)]
static CURSOR_LOCKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Returns true while mouse-look lock (`~` / `F2`) is active and the
/// cursor should be hidden inside the client area.
/// Whether the window holds the mouse: the cursor is hidden over its picture.
#[cfg(windows)]
pub(crate) fn cursor_locked() -> bool {
CURSOR_LOCKED.load(Ordering::Relaxed)
}
#[cfg(all(windows, test))]
pub(crate) fn set_cursor_locked(locked: bool) {
CURSOR_LOCKED.store(locked, Ordering::Relaxed);
}
/// The title's window got a wheel message (120 a notch, up positive).
#[cfg(windows)]
pub(crate) fn wheel_moved(by: i16) {
if kbm::live::enabled() && cursor_locked() {
kbm::WHEEL.fetch_add(i32::from(by), Ordering::Relaxed);
}
}
/// Whether a key message of the title's window is ours: F1, which shows the
/// key guide while keyboard and mouse play is on.
#[cfg(windows)]
pub(crate) fn takes_key(virtual_key: usize) -> bool {
#[cfg(test)]
if PLAYING.get() {
return virtual_key == usize::from(kbm::F1);
}
virtual_key == usize::from(kbm::F1) && kbm::live::enabled()
}
#[cfg(all(windows, test))]
thread_local! {
pub(crate) static PLAYING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// Parses an opt-in boolean environment variable (`1`, `true`, `yes`, `on`,
/// ignoring surrounding whitespace and ASCII case).
#[cfg(any(windows, test))]
fn parse_env_flag(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
@@ -136,28 +140,6 @@ fn parse_env_flag(value: &str) -> bool {
)
}
/// PC-style keyboard + mouse stand-in pad (`VICTORY_KBM_PC=1`).
/// Off by default so the existing keyboard table and tests stay unchanged.
fn pc_kbm() -> bool {
static ENABLED: LazyLock<bool> =
LazyLock::new(|| std::env::var("VICTORY_KBM_PC").is_ok_and(|v| parse_env_flag(&v)));
*ENABLED
}
/// Mouse-look sensitivity multiplier for `VICTORY_KBM_PC=1`
/// (`VICTORY_MOUSE_SENS`, default `1.0`).
#[cfg(windows)]
fn mouse_sens() -> f32 {
static SENS: LazyLock<f32> = LazyLock::new(|| {
std::env::var("VICTORY_MOUSE_SENS")
.ok()
.and_then(|s| s.trim().parse::<f32>().ok())
.filter(|v| v.is_finite() && *v > 0.0)
.unwrap_or(1.0)
});
*SENS
}
/// The dead zone of a pad's sticks, a share of their travel
/// (`VICTORY_PAD_DEADZONE`, 0 up to 1; 0 unless set: titles apply their own).
#[cfg(windows)]
@@ -187,94 +169,6 @@ fn apply_pad_deadzone(v: f32, deadzone: f32) -> f32 {
}
}
/// Invert mouse Y axis for `VICTORY_KBM_PC=1` (`VICTORY_MOUSE_INVERT_Y=1`).
#[cfg(windows)]
fn mouse_invert_y() -> bool {
static INVERT: LazyLock<bool> =
LazyLock::new(|| std::env::var("VICTORY_MOUSE_INVERT_Y").is_ok_and(|v| parse_env_flag(&v)));
*INVERT
}
/// Exponentially smoothed mouse-delta to right-stick velocity converter.
///
/// The poll loop runs at 125 Hz (8 ms) while 3D gameplay may render at low
/// framerates (~5 FPS). A 45 ms half-life keeps flicks alive long enough for
/// the next rendered frame to sample them while settling cleanly to zero.
#[cfg(any(windows, test))]
#[derive(Default)]
struct MouseLook {
vx: f32,
vy: f32,
}
#[cfg(any(windows, test))]
impl MouseLook {
const BASE_SENS: f32 = 0.022;
const HALF_LIFE_SECS: f32 = 0.045;
const DEADZONE: f32 = 0.015;
fn reset(&mut self) {
self.vx = 0.0;
self.vy = 0.0;
}
fn step(&mut self, dx: i32, dy: i32, dt: Duration, sens: f32, invert_y: bool) -> (f32, f32) {
let dt_secs = dt.as_secs_f32().clamp(0.001, 0.25);
let decay = 0.5_f32.powf(dt_secs / Self::HALF_LIFE_SECS);
let scale = Self::BASE_SENS * sens;
let y_sign = if invert_y { 1.0 } else { -1.0 };
self.vx = (self.vx * decay + dx as f32 * scale).clamp(-1.0, 1.0);
self.vy = (self.vy * decay + dy as f32 * scale * y_sign).clamp(-1.0, 1.0);
// Only snap tiny residual decay to zero at rest so low-sensitivity
// 1-pixel movements are never dropped.
if dx == 0 && self.vx.abs() < Self::DEADZONE {
self.vx = 0.0;
}
if dy == 0 && self.vy.abs() < Self::DEADZONE {
self.vy = 0.0;
}
(self.vx, self.vy)
}
}
/// Edge-captured state for `[LMB, RMB, MMB]` so holding a button on window
/// chrome or in another app and dragging into the client area never fires
/// triggers or buttons.
#[cfg(any(windows, test))]
#[derive(Default)]
struct MouseButtons {
seeded: bool,
prev: [bool; 3],
captured: [bool; 3],
}
#[cfg(any(windows, test))]
impl MouseButtons {
fn reset(&mut self) {
self.seeded = false;
self.prev = [false; 3];
self.captured = [false; 3];
}
fn update(&mut self, down: [bool; 3], eligible: bool) -> [bool; 3] {
if !self.seeded {
self.seeded = true;
self.prev = down;
self.captured = [false; 3];
return self.captured;
}
for ((&is_down, prev), captured) in down.iter().zip(&mut self.prev).zip(&mut self.captured) {
if !is_down {
*captured = false;
} else if !*prev && eligible {
*captured = true;
}
*prev = is_down;
}
self.captured
}
}
/// A gamepad reading: triggers 0 to 1, sticks -1 to 1 (up positive).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
@@ -308,19 +202,15 @@ trait Source: Send {
fn keys(&mut self) -> Vec<KeyState>;
/// Motor speeds: low frequency (left), high frequency (right).
fn rumble(&mut self, slot: usize, low: u16, high: u16);
/// Extra stand-in pad input from the mouse when `VICTORY_KBM_PC=1`.
/// When `active` is false (a physical controller owns input), any active
/// mouse-look capture must be released without warping the cursor.
fn mouse_pad(&mut self, _active: bool) -> PadState {
PadState::default()
/// The stand-in pad, with `keys` held. Not `active` (a controller plays in
/// its place), a mouse we hold is given back. `_pad`: the controllers as
/// one, if there are any.
fn stand_in(&mut self, keys: &[KeyState], _pad: Option<PadState>, _active: bool) -> PadState {
fallback(keys)
}
}
fn fallback(keys: &[KeyState]) -> PadState {
fallback_for(keys, pc_kbm())
}
fn fallback_for(keys: &[KeyState], pc_style: bool) -> PadState {
let on = |vk: u8| {
if keys.iter().any(|k| k.virtual_key == vk) {
1.0
@@ -328,14 +218,13 @@ fn fallback_for(keys: &[KeyState], pc_style: bool) -> PadState {
0.0
}
};
let table: &[(u8, u32)] = if pc_style { &PC_BUTTONS } else { &FALLBACK_BUTTONS };
PadState {
buttons: table
buttons: FALLBACK_BUTTONS
.iter()
.filter(|(vk, _)| on(*vk) != 0.0)
.fold(0, |all, (_, bit)| all | bit),
left_trigger: if pc_style { 0.0 } else { on(b'Z') },
right_trigger: if pc_style { 0.0 } else { on(b'C') },
left_trigger: on(b'Z'),
right_trigger: on(b'C'),
left_x: on(b'D') - on(b'A'),
left_y: on(b'W') - on(b'S'),
right_x: on(b'L') - on(b'J'),
@@ -636,17 +525,18 @@ impl Hub {
/// Reads the host once; device callbacks run on the calling thread.
fn poll(&self) {
let (pads, keys, mouse) = {
let (pads, keys, stand_in) = {
let mut source = lock(&self.source);
let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot));
let keys = source.keys();
let stand_in_active = self.one_pad || pads.iter().all(Option::is_none);
let mouse = source.mouse_pad(stand_in_active);
(pads, keys, mouse)
let active = self.one_pad || pads.iter().all(Option::is_none);
let pad = pads.into_iter().flatten().reduce(merged);
let stand_in = source.stand_in(&keys, pad, active);
(pads, keys, stand_in)
};
let events = self
.state()
.poll(&self.devices, self.one_pad, pads, keys, mouse);
.poll(&self.devices, self.one_pad, pads, keys, stand_in);
self.deliver(events);
}
@@ -692,11 +582,10 @@ impl State {
one_pad: bool,
pads: [Option<PadState>; PADS],
keys: Vec<KeyState>,
mouse: PadState,
stand_in: PadState,
) -> Vec<Event> {
let now = now();
let mut events = std::mem::take(&mut self.pending);
let stand_in = merged(fallback(&keys), mouse);
if one_pad {
let pad = pads.into_iter().flatten().fold(stand_in, merged);
self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events);
@@ -835,12 +724,38 @@ extern "system" fn timestamp(_: This) -> u64 {
now()
}
/// The title's looks at the pad and the time of the last one.
#[cfg(windows)]
static READS: Mutex<(kbm::Reads, f64)> = Mutex::new((kbm::Reads { count: 0, every: 0.0 }, 0.0));
#[cfg(windows)]
fn title_looked() {
let now = now() as f64 / 1e6;
let mut reads = lock(&READS);
let after = (now - reads.1) as f32;
if reads.0.look(after) {
reads.1 = now;
if matches!(reads.0.count, 600 | 6000) {
tracing::info!(ms = reads.0.every * 1e3, "the title looks at the pad every");
}
}
}
#[cfg(windows)]
fn title_reads() -> kbm::Reads {
lock(&READS).0
}
extern "system" fn current_reading(
this: This,
kind: u32,
device: *const Device,
out: Out,
) -> HRESULT {
#[cfg(windows)]
if kind & GAMEPAD_KIND != 0 && kbm::live::enabled() {
title_looked();
}
let hub = hub(this);
let state = hub.state();
let newest = |i: usize| {
@@ -1332,7 +1247,7 @@ pub(crate) fn module() -> HleModule {
mod host {
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{HWND, POINT};
use windows_sys::Win32::Foundation::{HWND, POINT, RECT};
use windows_sys::Win32::System::Threading::GetCurrentProcessId;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW,
@@ -1346,8 +1261,9 @@ mod host {
XInputSetState,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
GetCursorPos, GetForegroundWindow, GetWindowInfo, GetWindowThreadProcessId, HTCLIENT,
PostMessageW, SetCursorPos, WINDOWINFO, WM_MOUSEMOVE, WM_SETCURSOR,
ClipCursor, GA_ROOT, GW_OWNER, GetAncestor, GetClassNameW, GetClipCursor, GetCursorPos,
GetForegroundWindow, GetWindow, GetWindowInfo, GetWindowThreadProcessId, HTCLIENT, PostMessageW,
SetCursorPos, WINDOWINFO, WM_MOUSEMOVE, WM_SETCURSOR, WindowFromPoint,
};
use super::*;
@@ -1392,44 +1308,130 @@ mod host {
#[derive(Default)]
pub(super) struct Host {
empty_until: [Option<Instant>; PADS],
mouse_locked: bool,
just_locked: bool,
toggle_was_down: bool,
anchor: (i32, i32),
mouse_last_poll: Option<Instant>,
mouse_look: MouseLook,
mouse_buttons: MouseButtons,
/// Keys really held, and those of a script (diagnostics).
held: Vec<u8>,
scripted: Vec<u8>,
/// With `VICTORY_KBM=1`.
play: Option<hold::Play<Screen>>,
}
impl Host {
fn set_mouse_locked(&mut self, locked: bool, hwnd: Option<HWND>) {
if self.mouse_locked == locked {
return;
/// The real screen, for keyboard and mouse play.
struct Screen {
keys: kbm::live::Watch,
}
impl hold::Desk for Screen {
fn window(&mut self) -> Option<(usize, hold::Rect)> {
let hwnd = foreground_window().filter(|&hwnd| shows_the_title(hwnd))?;
Some((hwnd as usize, client_rect_screen(hwnd)?))
}
fn cursor(&mut self) -> Option<(i32, i32)> {
let mut pos = POINT::default();
// SAFETY: room for a point.
(unsafe { GetCursorPos(&mut pos) } != 0).then_some((pos.x, pos.y))
}
fn over(&mut self, window: usize, at: (i32, i32)) -> bool {
// SAFETY: plain queries.
let root = unsafe { GetAncestor(WindowFromPoint(POINT { x: at.0, y: at.1 }), GA_ROOT) };
root as usize == window
}
fn mouse(&mut self) -> [bool; 5] {
// SAFETY: plain queries.
kbm::MOUSE_KEYS.map(|vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0)
}
fn raw(&mut self) -> Option<(i32, i32)> {
kbm::live::raw_moved()
}
fn reads(&mut self) -> kbm::Reads {
super::title_reads()
}
fn raw_failed(&mut self) -> bool {
kbm::live::raw_failed()
}
fn wheel(&mut self) -> i32 {
kbm::WHEEL.swap(0, Ordering::Relaxed)
}
fn place(&mut self, at: (i32, i32)) -> Option<(i32, i32)> {
// SAFETY: the cursor inside our own window in front.
if unsafe { SetCursorPos(at.0, at.1) } == 0 {
return None;
}
self.mouse_locked = locked;
CURSOR_LOCKED.store(locked, Ordering::Release);
if let Some(hwnd) = hwnd {
// Prompt the window's UI thread to run WM_SETCURSOR right away
// so the cursor hides/reappears the instant `~`/`F2`/`Esc`/`P`
// is pressed, even before moving the mouse.
// (Read back: fractional DPI scaling may put it next to that.)
self.cursor()
}
fn clip(&mut self) -> Option<hold::Rect> {
let mut is = RECT::default();
// SAFETY: room for a rectangle.
(unsafe { GetClipCursor(&mut is) } != 0).then_some((is.left, is.top, is.right, is.bottom))
}
fn set_clip(&mut self, to: Option<hold::Rect>) {
let wanted = to.map(|(left, top, right, bottom)| RECT { left, top, right, bottom });
// SAFETY: a valid rectangle, or none: the cursor goes anywhere.
unsafe { ClipCursor(wanted.as_ref().map_or(std::ptr::null(), std::ptr::from_ref)) };
}
fn hide(&mut self, hidden: bool, window: Option<usize>) {
CURSOR_LOCKED.store(hidden, Ordering::Release);
if let Some(window) = window {
// Prompt the window's thread to hide or show the cursor now,
// not at the next movement.
let lparam = (HTCLIENT as isize) | ((WM_MOUSEMOVE as isize) << 16);
// SAFETY: asynchronous post to our own process's foreground window.
// SAFETY: asynchronous post to our own process's window.
unsafe {
let _ = PostMessageW(hwnd, WM_SETCURSOR, hwnd as usize, lparam);
let _ = PostMessageW(window as HWND, WM_SETCURSOR, window, lparam);
}
}
}
fn now(&mut self) -> Duration {
START.elapsed()
}
fn layer(&mut self, layer: kbm::Layer) {
panel_layer(layer);
}
fn guide(&mut self, title: &str, rows: &[guide::Row]) {
victory_gpu::key_guide(title, rows);
}
fn notice(&mut self) {
victory_gpu::key_guide_notice();
}
fn keep(&mut self, feel: kbm::Feel) {
kbm::live::keep(feel);
}
fn menu(&mut self, open: bool) {
victory_gpu::key_guide_menu(open);
}
fn keys_text(&mut self) -> Option<String> {
kbm::live::keys_text()
}
fn write_keys(&mut self, text: &str) -> bool {
kbm::live::write_keys(text)
}
fn rebound(&mut self, now: Duration) -> Option<kbm::Bindings> {
self.keys.rebound(now)
}
}
fn disarm_mouse(&mut self, hwnd: Option<HWND>, reason: &'static str) {
if self.mouse_locked {
self.set_mouse_locked(false, hwnd);
tracing::info!(reason, "mouse look unlocked");
}
self.just_locked = false;
self.mouse_look.reset();
self.mouse_last_poll = None;
self.toggle_was_down = false;
self.mouse_buttons.reset();
/// Keyboard and mouse play as the environment asks for it.
fn play() -> hold::Play<Screen> {
let motion = kbm::Motion::new(std::env::var("VICTORY_MOUSE_RAW").ok().as_deref());
if motion.way != Some(kbm::Way::Warp) {
kbm::live::start_raw();
}
let (kbm, keys) = kbm::live::load();
hold::Play::new(kbm, motion, Screen { keys })
}
/// The panel exists in diagnostics builds alone; the log has it in all.
fn panel_layer(layer: kbm::Layer) {
#[cfg(feature = "diagnostics")]
victory_gpu::panel_keys(layer.name());
#[cfg(not(feature = "diagnostics"))]
let _ = layer;
}
#[cfg(test)]
impl Host {
pub(super) fn plays(&self) -> bool {
self.play.is_some()
}
}
@@ -1479,17 +1481,21 @@ mod host {
let mut down = scripted();
#[cfg(not(feature = "diagnostics"))]
let mut down = Vec::new();
self.scripted.clone_from(&down);
self.held.clear();
if focused() {
// Left/right modifier keys only, as devices report them; no
// mouse buttons (below 0x08).
let held: Vec<u8> = (0x08..=0xFE_u8)
.filter(|vk| !(0x10..=0x12).contains(vk) && !down.contains(vk))
self.held = (0x08..=0xFE_u8)
.filter(|vk| !(0x10..=0x12).contains(vk))
// SAFETY: plain queries.
.filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0)
.collect();
down.extend(held);
down.extend(self.held.iter().filter(|vk| !self.scripted.contains(vk)));
}
down.into_iter()
hold::for_title(down, kbm::live::enabled())
.into_iter()
.filter(|&vk| self.scripted.contains(&vk) || !self.play.as_ref().is_some_and(|p| p.hides(vk)))
.map(|vk| KeyState {
// SAFETY: plain query.
scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) },
@@ -1510,121 +1516,18 @@ mod host {
unsafe { XInputSetState(slot as u32, &speeds) };
}
fn mouse_pad(&mut self, active: bool) -> PadState {
if !pc_kbm() || !active {
self.disarm_mouse(foreground_window(), "stand-in inactive");
return PadState::default();
fn stand_in(&mut self, keys: &[KeyState], pad: Option<PadState>, active: bool) -> PadState {
if !kbm::live::enabled() {
return fallback(keys);
}
let Some(hwnd) = foreground_window() else {
self.disarm_mouse(None, "focus lost");
return PadState::default();
};
let key_down = |vk: i32| {
// SAFETY: plain async key state query.
unsafe { GetAsyncKeyState(vk) < 0 }
};
// Toggle mouse-look lock with F2 (0x71, layout-independent) or
// VK_OEM_3 (0xC0, `` ` `` / `~` on US layouts).
let toggle_down = key_down(0x71) || key_down(0xC0);
if toggle_down && !self.toggle_was_down {
let next = !self.mouse_locked;
self.set_mouse_locked(next, Some(hwnd));
self.just_locked = next;
self.mouse_look.reset();
tracing::info!(locked = next, "mouse look toggled");
}
self.toggle_was_down = toggle_down;
// Esc (0x1B) or P opens the pause menu and frees the mouse so the
// user is never trapped in mouse-look mode.
if self.mouse_locked && (key_down(0x1B) || key_down(i32::from(b'P'))) {
self.set_mouse_locked(false, Some(hwnd));
self.just_locked = false;
self.mouse_look.reset();
tracing::info!("mouse look unlocked (menu key)");
}
let Some((c_left, c_top, c_right, c_bottom)) = client_rect_screen(hwnd) else {
self.disarm_mouse(Some(hwnd), "client unavailable");
return PadState::default();
};
let mut pos = POINT::default();
// SAFETY: valid pointer to our initialized POINT.
if unsafe { GetCursorPos(&mut pos) } == 0 {
self.disarm_mouse(Some(hwnd), "cursor query failed");
return PadState::default();
}
let now = Instant::now();
let dt = self
.mouse_last_poll
.replace(now)
.map_or(POLL, |prev| now.saturating_duration_since(prev));
let (right_x, right_y) = if self.mouse_locked {
let cx = c_left + (c_right - c_left) / 2;
let cy = c_top + (c_bottom - c_top) / 2;
let (dx, dy) = if self.just_locked {
self.just_locked = false;
if let Some(anchor) = recenter_cursor(cx, cy) {
self.anchor = anchor;
} else {
self.set_mouse_locked(false, Some(hwnd));
self.mouse_look.reset();
tracing::warn!("mouse look unlocked (cursor warp failed)");
}
(0, 0)
} else {
let dx = pos.x - self.anchor.0;
let dy = pos.y - self.anchor.1;
if dx != 0 || dy != 0 {
if let Some(anchor) = recenter_cursor(cx, cy) {
self.anchor = anchor;
(dx, dy)
} else {
self.set_mouse_locked(false, Some(hwnd));
self.mouse_look.reset();
tracing::warn!("mouse look unlocked (cursor warp failed)");
(0, 0)
}
} else {
(0, 0)
}
};
if self.mouse_locked {
self.mouse_look
.step(dx, dy, dt, mouse_sens(), mouse_invert_y())
} else {
(0.0, 0.0)
}
} else {
self.mouse_look.reset();
(0.0, 0.0)
};
let in_client =
(c_left..c_right).contains(&pos.x) && (c_top..c_bottom).contains(&pos.y);
let [lmb, rmb, mmb] = self.mouse_buttons.update(
[key_down(0x01), key_down(0x02), key_down(0x04)],
self.mouse_locked || in_client,
);
let mut pad = PadState {
right_x,
right_y,
..Default::default()
};
if lmb {
pad.right_trigger = 1.0; // LMB: Shoot / Attack / Gas (RT)
}
if rmb {
pad.left_trigger = 1.0; // RMB: Aim / Brake-Reverse (LT)
}
if mmb {
pad.buttons |= RIGHT_STICK; // MMB: Look behind / Special (R3)
}
pad
let pad = self.play.get_or_insert_with(play).step(&self.held, pad, active);
// A script's keys mean what they mean without the switch.
let script: Vec<KeyState> = keys
.iter()
.filter(|k| self.scripted.contains(&k.virtual_key))
.copied()
.collect();
merged(pad, fallback(&script))
}
}
@@ -1689,20 +1592,20 @@ mod host {
foreground_window().is_some()
}
/// Recenters the cursor at `(cx, cy)` and reads back its actual screen
/// position so fractional DPI scaling never introduces phantom drift.
/// Returns `None` if either Win32 call fails.
fn recenter_cursor(cx: i32, cy: i32) -> Option<(i32, i32)> {
// SAFETY: recenters the cursor inside our own foreground window.
if unsafe { SetCursorPos(cx, cy) } == 0 {
return None;
}
let mut settled = POINT::default();
// SAFETY: valid pointer to our initialized POINT.
if unsafe { GetCursorPos(&mut settled) } == 0 {
return None;
}
Some((settled.x, settled.y))
/// The window is one whose picture is the title's: the title's own, or
/// the one made for it. Not a message or an error of our process.
fn shows_the_title(hwnd: HWND) -> bool {
let mut class = [0; 16];
// SAFETY: plain queries; the buffer holds 16 characters.
let (owned, n) = unsafe {
(
!GetWindow(hwnd, GW_OWNER).is_null(),
GetClassNameW(hwnd, class.as_mut_ptr(), class.len() as i32),
)
};
// (victory-gpu's, where the title has no window of its own.)
let made = class[..n.max(0) as usize].iter().copied().eq("Valhalla".encode_utf16());
!owned && (made || crate::modules::lifecycle::is_title_window(hwnd))
}
/// Client area in screen coordinates directly from Win32 `GetWindowInfo`.
@@ -1774,7 +1677,8 @@ mod tests {
pads: [Option<PadState>; PADS],
keys: Vec<KeyState>,
mouse: PadState,
mouse_active_log: Vec<bool>,
active_log: Vec<bool>,
seen_pad: Option<PadState>,
rumble: Vec<(usize, u16, u16)>,
}
@@ -1790,11 +1694,12 @@ mod tests {
fn rumble(&mut self, slot: usize, low: u16, high: u16) {
self.0.lock().unwrap().rumble.push((slot, low, high));
}
fn mouse_pad(&mut self, active: bool) -> PadState {
fn stand_in(&mut self, keys: &[KeyState], pad: Option<PadState>, active: bool) -> PadState {
let mut host = self.0.lock().unwrap();
host.mouse_active_log.push(active);
host.active_log.push(active);
host.seen_pad = pad;
if active {
host.mouse
merged(fallback(keys), host.mouse)
} else {
PadState::default()
}
@@ -2027,6 +1932,16 @@ mod tests {
assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND));
}
#[test]
fn the_stand_in_hears_of_the_controllers() {
let (hub, host) = fake_with(true);
assert_eq!(host.lock().unwrap().seen_pad, None);
host.lock().unwrap().pads[2] = Some(PadState { buttons: A, ..Default::default() });
host.lock().unwrap().pads[3] = Some(PadState { buttons: B, ..Default::default() });
hub.poll();
assert_eq!(host.lock().unwrap().seen_pad.unwrap().buttons, A | B);
}
#[test]
fn a_host_pad_feeds_the_one_pad_which_never_goes() {
let (hub, host) = fake_with(true);
@@ -2163,42 +2078,7 @@ mod tests {
}
#[test]
fn pc_kbm_maps_pc_style_keys_and_smooths_mouse_look() {
let keys = vec![
key(b'W'),
key(0xA0), // Left Shift -> A (Sprint)
key(0x20), // Space -> X (Jump)
key(b'R'), // R -> B (Reload)
key(b'F'), // F -> Y (Enter/Exit vehicle)
key(0x09), // Tab -> LB (Weapon wheel)
key(b'Q'), // Q -> RB (Cover)
key(0xA2), // Left Ctrl -> L3 (Crouch)
key(b'C'), // C -> R3 (Look behind), not RT
key(b'E'), // E -> D-pad Right (Interact)
key(b'Z'), // Z -> D-pad Down (Minimap), not LT
key(b'V'), // V -> View (Camera)
key(0x1B), // Esc -> Menu
];
let mapped = fallback_for(&keys, true);
assert_eq!(
mapped.buttons,
A | X
| B
| Y
| LEFT_SHOULDER
| RIGHT_SHOULDER
| LEFT_STICK
| RIGHT_STICK
| RIGHT
| DOWN
| VIEW
| MENU
);
assert_eq!(mapped.left_y, 1.0);
assert_eq!(mapped.left_trigger, 0.0);
assert_eq!(mapped.right_trigger, 0.0);
// Mouse pad merges cleanly into the stand-in pad.
fn mouse_play_merges_into_the_stand_in_pad() {
let (hub, host) = fake_with(true);
{
let mut h = host.lock().unwrap();
@@ -2217,84 +2097,34 @@ mod tests {
let got = pad(r);
assert_eq!(got.buttons, RIGHT_STICK);
assert_eq!(
(
got.left_y,
got.left_trigger,
got.right_trigger,
got.right_x,
got.right_y
),
(got.left_y, got.left_trigger, got.right_trigger, got.right_x, got.right_y),
(1.0, 1.0, 1.0, 0.75, -0.25)
);
release(r);
let mut look = MouseLook::default();
let (rx, ry) = look.step(20, -10, POLL, 1.0, false);
assert!(
(0.3..=1.0).contains(&rx),
"mouse right should push +right_x, got {rx}"
);
assert!(
(0.15..=1.0).contains(&ry),
"mouse up (-dy) should push +right_y, got {ry}"
);
// Inverted Y flips the vertical axis.
look.reset();
let (_, ry_inv) = look.step(0, -10, POLL, 1.0, true);
assert!(ry_inv < -0.15, "invert_y should flip right_y, got {ry_inv}");
// Decays back to zero when the mouse stops moving.
for _ in 0..40 {
look.step(0, 0, POLL, 1.0, false);
}
assert_eq!(look.step(0, 0, POLL, 1.0, false), (0.0, 0.0));
// Low-sensitivity 1-pixel movement is not swallowed by the rest deadzone.
let (fine_x, _) = look.step(1, 0, POLL, 0.3, false);
assert!(
fine_x > 0.0,
"1px low-sens motion should stay non-zero, got {fine_x}"
);
// Strict boolean env parsing rejects "false", "0", " 0 ", and "".
assert!(parse_env_flag("1"));
assert!(parse_env_flag(" true "));
assert!(parse_env_flag("YES"));
assert!(!parse_env_flag("0"));
assert!(!parse_env_flag(" 0 "));
assert!(!parse_env_flag("false"));
assert!(!parse_env_flag(""));
// Dragging a held button from outside (chrome / another app) into the
// client area must not fire triggers until released and pressed fresh.
let mut buttons = MouseButtons::default();
assert_eq!(buttons.update([true, false, false], true), [false; 3]);
assert_eq!(buttons.update([true, false, false], true), [false; 3]);
assert_eq!(buttons.update([false, false, false], true), [false; 3]);
assert_eq!(buttons.update([true, false, false], false), [false; 3]);
assert_eq!(buttons.update([true, false, false], true), [false; 3]);
assert_eq!(buttons.update([false, false, false], true), [false; 3]);
assert_eq!(
buttons.update([true, false, true], true),
[true, false, true]
);
assert_eq!(
buttons.update([true, false, true], false),
[true, false, true]
);
assert_eq!(buttons.update([false, false, false], false), [false; 3]);
}
#[test]
fn physical_controller_takeover_disarms_mouse_pad_when_not_one_pad() {
fn flags_are_read_strictly() {
for on in ["1", " true ", "YES", "on"] {
assert!(parse_env_flag(on), "{on:?}");
}
for off in ["0", " 0 ", "false", "", "2"] {
assert!(!parse_env_flag(off), "{off:?}");
}
}
#[test]
fn a_controller_takes_over_from_keyboard_and_mouse_when_not_one_pad() {
let (hub, host) = fake_with(false);
host.lock().unwrap().pads[0] = Some(PadState {
buttons: A,
..Default::default()
});
hub.poll();
assert_eq!(host.lock().unwrap().mouse_active_log.last(), Some(&false));
assert_eq!(host.lock().unwrap().active_log.last(), Some(&false));
host.lock().unwrap().pads[0] = None;
hub.poll();
assert_eq!(host.lock().unwrap().mouse_active_log.last(), Some(&true));
assert_eq!(host.lock().unwrap().active_log.last(), Some(&true));
}
}
@@ -0,0 +1,281 @@
//! What the key guide says (`victory_gpu::key_guide`): which key is which
//! button of the pad, for the keys in use or for a controller, whichever was
//! used last. Nothing here asks the host.
use std::time::Duration;
use super::PadState;
use super::kbm::{Bindings, Layer, Pad};
/// The pad's button, the key and what it does.
pub(super) type Row = (String, String, String);
/// What was used last.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Device {
Keys,
Controller,
}
/// Button, what it does on foot and in a vehicle, as common third-person pad
/// layouts have it (docs/keyboard-mouse.md).
#[rustfmt::skip]
pub(super) const MEANS: [(Pad, &str, &str, &str); 18] = [
(Pad::LeftStick, "L stick", "Move", "Steer"),
(Pad::RightStick, "R stick", "Look", "Look"),
(Pad::Named("RT"), "RT", "Fire", "Accelerate"),
(Pad::Named("LT"), "LT", "Aim", "Brake, reverse"),
(Pad::Named("RB"), "RB", "Cover", "Handbrake"),
(Pad::Named("LB"), "LB", "Weapon wheel (hold)", "Weapon wheel (hold)"),
(Pad::Named("A"), "A", "Jump, accept", "Boost"),
(Pad::Named("B"), "B", "Reload, back", "Reload, back"),
(Pad::Named("X"), "X", "Run", "X button"),
(Pad::Named("Y"), "Y", "Interact, enter", "Leave"),
(Pad::Named("L3"), "L3", "Crouch", "Horn"),
(Pad::Named("R3"), "R3", "Look behind, special", "Look behind, special"),
(Pad::Named("Up"), "D-pad up", "Phone", "Phone"),
(Pad::Named("Down"), "D-pad down", "Radar", "Radar"),
(Pad::Named("Left"), "D-pad left", "Throw", "D-pad left"),
(Pad::Named("Right"), "D-pad right", "Interact", "D-pad right"),
(Pad::Named("View"), "View", "Map", "Map"),
(Pad::Named("Menu"), "Menu", "Pause", "Pause"),
];
/// The guide's title and rows.
pub(super) fn text(device: Device, layer: Layer, bindings: &Bindings) -> (String, Vec<Row>) {
let row = |button: &str, key: &str, does: &str| (button.to_owned(), key.to_owned(), does.to_owned());
let mut rows: Vec<Row> = MEANS
.iter()
.map(|&(pad, button, foot, vehicle)| match device {
Device::Keys => {
let does = if layer == Layer::Foot { foot } else { vehicle };
row(button, &bindings.keys_of(layer, pad), does)
}
// (A controller's player changes no layout: both are told.)
Device::Controller if foot == vehicle => row(button, "", foot),
Device::Controller => row(button, "", &format!("{foot} / {vehicle}")),
})
.collect();
let title = match device {
Device::Keys => {
rows.push(row("", "Caps Lock", "On foot or vehicle, by hand"));
rows.push(row("", "F2", "Holds or frees the mouse"));
let phone = bindings.keys_of(layer, Pad::Named("Phone"));
rows.push(row("", &phone, "Phone, out and away"));
let map = bindings.keys_of(layer, Pad::Named("Map"));
rows.push(row("", &map, "Map (wheel zooms, click: marker)"));
rows.push(row("", "PgUp PgDn", "Mouse sensitivity, more or less"));
format!("Keyboard and mouse, {}", layer.name())
}
Device::Controller => "Controller".to_owned(),
};
rows.push(row("", "F1", "Keys and mouse settings"));
(title, rows)
}
/// What somebody at the keyboard did since the last step; nothing while
/// another window is in front.
#[derive(Clone, Debug, Default)]
pub(super) struct Hand {
/// Keys and mouse buttons down that do something.
pub down: Vec<u8>,
/// Counts moved, while the mouse turns the view.
pub moved: (i32, i32),
pub wheel: i32,
}
/// Finds out what was used last. Only a clear input changes it: a press that
/// begins, a stick that leaves the middle, a hand's movement of the mouse.
/// What lies still, trembles or is held already does not.
pub(super) struct Used {
pub(super) device: Device,
/// Down at the last step; `None`: not in front then.
down: Option<Vec<u8>>,
/// Pushed at the last step (the sticks and triggers), and the buttons;
/// `None`: no controller then.
pushed: Option<([bool; 4], u32)>,
/// Movement of the mouse and the wheel since.
moved: (i32, i32),
wheel: i32,
since: Duration,
}
impl Used {
/// A push of a stick or a trigger counts from here on, and is over below
/// that: one that stays between does nothing.
const PUSHED: f32 = 0.45;
const OVER: f32 = 0.3;
/// Counts (3 mm of a mouse of 800 DPI) within that time are a movement.
const COUNTS: f32 = 100.0;
const WITHIN: Duration = Duration::from_millis(300);
pub(super) fn new() -> Used {
Used { device: Device::Keys, down: None, pushed: None, moved: (0, 0), wheel: 0, since: Duration::ZERO }
}
pub(super) fn step(&mut self, hand: Option<&Hand>, pad: Option<PadState>, now: Duration) {
let keys = self.hand(hand, now);
// (Both at once: the controller's press is as clear, and it stays.)
if self.controller(pad) {
self.device = Device::Controller;
} else if keys {
self.device = Device::Keys;
}
}
fn hand(&mut self, hand: Option<&Hand>, now: Duration) -> bool {
let Some(hand) = hand else {
self.down = None;
(self.moved, self.wheel) = ((0, 0), 0);
return false;
};
let still = self.moved == (0, 0) && self.wheel == 0;
if still || now.saturating_sub(self.since) > Self::WITHIN {
(self.moved, self.wheel) = ((0, 0), 0);
self.since = now;
}
// (Fine wheels tell parts of a notch; back again is no notch.)
if self.wheel.signum() * hand.wheel.signum() < 0 {
self.wheel = 0;
}
self.wheel += hand.wheel;
self.moved = (self.moved.0 + hand.moved.0, self.moved.1 + hand.moved.1);
let moved = (self.moved.0 as f32).hypot(self.moved.1 as f32) >= Self::COUNTS;
let notch = self.wheel.abs() >= 120;
if moved || notch {
(self.moved, self.wheel) = ((0, 0), 0);
}
// What is held when the window comes to the front was for another one.
let was = self.down.replace(hand.down.clone());
let pressed = was.is_some_and(|was| hand.down.iter().any(|key| !was.contains(key)));
pressed || moved || notch
}
fn controller(&mut self, pad: Option<PadState>) -> bool {
let Some(pad) = pad else {
self.pushed = None;
return false;
};
let push = [
pad.left_x.hypot(pad.left_y),
pad.right_x.hypot(pad.right_y),
pad.left_trigger,
pad.right_trigger,
];
let was = self.pushed;
let on = std::array::from_fn(|i| {
let held = was.is_some_and(|(was, _)| was[i]);
push[i] >= if held { Self::OVER } else { Self::PUSHED }
});
self.pushed = Some((on, pad.buttons));
was.is_some_and(|(was, buttons)| {
pad.buttons & !buttons != 0 || on.iter().zip(was).any(|(on, was)| *on && !was)
})
}
}
/// What the guide says now, told once for each change of it.
pub(super) struct Told {
used: Used,
last: Option<(String, Vec<Row>)>,
/// What `last` was made for.
of: Option<(Device, Layer)>,
/// How often the rows were put together.
#[cfg(test)]
made: u32,
}
impl Told {
pub(super) fn new() -> Told {
Told {
used: Used::new(),
last: None,
of: None,
#[cfg(test)]
made: 0,
}
}
/// The keys are others now.
pub(super) fn rebound(&mut self) {
self.of = None;
}
/// Something else was shown: it is told anew.
pub(super) fn again(&mut self) {
(self.of, self.last) = (None, None);
}
pub(super) fn device(&self) -> Device {
self.used.device
}
/// What is to be told now, if it changed.
pub(super) fn step(
&mut self,
hand: Option<&Hand>,
pad: Option<PadState>,
now: Duration,
layer: Layer,
bindings: &Bindings,
) -> Option<&(String, Vec<Row>)> {
self.used.step(hand, pad, now);
let of = (self.used.device, layer);
if self.of == Some(of) {
return None;
}
self.of = Some(of);
#[cfg(test)]
{
self.made += 1;
}
let text = text(self.used.device, layer, bindings);
if self.last.as_ref() == Some(&text) {
return None;
}
self.last = Some(text);
self.last.as_ref()
}
}
/// Whether what is looked at now and then (a file's time and size) has
/// changed and stays so: not while it is being written.
pub(super) struct Settled<T> {
known: T,
seen: T,
next: Duration,
again: bool,
}
impl<T: PartialEq + Clone> Settled<T> {
const LOOK: Duration = Duration::from_secs(1);
pub(super) fn new(known: T) -> Settled<T> {
Settled { seen: known.clone(), known, next: Duration::ZERO, again: false }
}
pub(super) fn changed(&mut self, now: Duration, look: impl FnOnce() -> T) -> bool {
if now < self.next {
return false;
}
self.next = now + Self::LOOK;
let is = look();
let stays = is == self.seen;
let changed = stays && (is != self.known || self.again);
if changed {
self.again = false;
self.known = is.clone();
}
self.seen = is;
changed
}
/// What changed could not be read: it counts as changed at the next look.
pub(super) fn again(&mut self) {
self.again = true;
}
}
#[cfg(test)]
#[path = "guide_tests.rs"]
mod tests;
@@ -0,0 +1,276 @@
use super::super::{A, KeyState, RIGHT_STICK, Y};
use super::*;
const MS: fn(u64) -> Duration = Duration::from_millis;
fn keys_in(device: Device, layer: Layer, file: &str) -> impl Fn(&str) -> (String, String) {
let (bindings, unknown) = Bindings::new(file);
assert!(unknown.is_empty(), "{unknown:?}");
let (_, rows) = text(device, layer, &bindings);
move |button| {
let mut found = rows.iter().filter(|r| r.0 == button);
let row = found.next().unwrap_or_else(|| panic!("no row {button}"));
(row.1.clone(), row.2.clone())
}
}
fn is(key: &str, does: &str) -> (String, String) {
(key.into(), does.into())
}
#[test]
fn the_rows_are_the_keys_in_use() {
let foot = keys_in(Device::Keys, Layer::Foot, "");
assert_eq!(foot("L stick"), is("W A S D", "Move"));
assert_eq!(foot("R stick"), is("Mouse I J K L", "Look"));
assert_eq!(foot("RT"), is("LMB", "Fire"));
assert_eq!(foot("LT"), is("RMB", "Aim"));
assert_eq!(foot("LB"), is("Tab", "Weapon wheel (hold)"));
assert_eq!(foot("A"), is("Space Enter", "Jump, accept"));
assert_eq!(foot("Y"), is("F", "Interact, enter"));
assert_eq!(foot("L3"), is("Ctrl", "Crouch"));
assert_eq!(foot("Menu"), is("Esc", "Pause"));
assert_eq!(foot("D-pad right"), is("4 E \u{2192}", "Interact"));
let vehicle = keys_in(Device::Keys, Layer::Vehicle, "");
assert_eq!(vehicle("L stick"), is("A D Num8 Num5", "Steer"));
assert_eq!(vehicle("RT"), is("W", "Accelerate"));
assert_eq!(vehicle("LT"), is("S", "Brake, reverse"));
assert_eq!(vehicle("RB"), is("Space", "Handbrake"));
assert_eq!(vehicle("LB"), is("Tab", "Weapon wheel (hold)"));
assert_eq!(vehicle("Y").1, "Leave");
// Own keys; one side of two; a key without a name; none at all.
let own = keys_in(
Device::Keys,
Layer::Foot,
"foot.Q = None\nfoot.F9 = RB\nfoot.RShift = X\nall.0xBC = L3\nall.V = None\nall.C = None",
);
assert_eq!(own("RB").0, "F9");
assert_eq!(own("A").0, "Space Enter");
assert_eq!(own("X").0, "X Shift");
assert_eq!(own("L3").0, "Ctrl 0xBC");
assert_eq!(own("LB").0, "Tab");
assert_eq!(own("View").0, "-");
}
#[test]
fn a_controllers_rows_name_no_keys_and_both_layouts() {
let (bindings, _) = Bindings::new("");
let foot = text(Device::Controller, Layer::Foot, &bindings);
assert_eq!(foot, text(Device::Controller, Layer::Vehicle, &bindings));
assert_eq!(foot.0, "Controller");
let pad = keys_in(Device::Controller, Layer::Foot, "");
assert_eq!(pad("RT"), is("", "Fire / Accelerate"));
assert_eq!(pad("Menu"), is("", "Pause"));
}
/// The guide shows 24 rows, and cuts what is longer than its columns.
#[test]
fn every_row_fits_the_guide() {
for device in [Device::Keys, Device::Controller] {
for layer in [Layer::Foot, Layer::Vehicle] {
let (title, rows) = text(device, layer, &Bindings::new("").0);
assert!(rows.len() <= 24 && title.len() <= 36);
for (button, key, does) in rows {
let long = [(&button, 12), (&key, 18), (&does, 36)];
assert!(long.iter().all(|(t, most)| t.chars().count() <= *most), "{button} {key} {does}");
assert!(device == Device::Controller && !button.is_empty() || !key.is_empty());
}
}
}
}
struct Hands {
used: Used,
now: Duration,
}
impl Hands {
fn new(device: Device) -> Hands {
let mut hands = Hands { used: Used::new(), now: MS(5000) };
hands.step(Some(Hand::default()), Some(PadState::default()));
hands.used.device = device;
hands
}
fn step(&mut self, hand: Option<Hand>, pad: Option<PadState>) -> Device {
self.now += MS(8);
self.used.step(hand.as_ref(), pad, self.now);
self.used.device
}
fn pad(&mut self, pad: PadState) -> Device {
self.step(Some(Hand::default()), Some(pad))
}
fn keys(&mut self, down: &[u8]) -> Device {
self.step(Some(Hand { down: down.to_vec(), ..Default::default() }), Some(PadState::default()))
}
fn mouse(&mut self, moved: (i32, i32)) -> Device {
self.step(Some(Hand { moved, ..Default::default() }), Some(PadState::default()))
}
}
fn stick(x: f32, y: f32) -> PadState {
PadState { left_x: x, left_y: y, ..Default::default() }
}
#[test]
fn a_resting_pad_changes_nothing() {
let mut hands = Hands::new(Device::Keys);
for i in 0..5000 {
// Off the middle, and trembling around every mark there is.
let v = [0.02, 0.2, 0.24, 0.29, 0.31, 0.44][i % 6];
let rests = PadState { left_trigger: v, right_x: -v, ..stick(v * 0.7, -v * 0.7) };
assert_eq!(hands.pad(rests), Device::Keys);
}
}
#[test]
fn every_clear_push_of_a_pad_is_the_controller() {
for pad in [
stick(0.5, 0.0),
stick(-0.4, -0.4),
PadState { right_y: -0.6, ..Default::default() },
PadState { left_trigger: 0.5, ..Default::default() },
PadState { right_trigger: 1.0, ..Default::default() },
PadState { buttons: A, ..Default::default() },
] {
let mut hands = Hands::new(Device::Keys);
assert_eq!(hands.pad(pad), Device::Controller, "{pad:?}");
}
}
#[test]
fn what_stays_pushed_counts_once() {
let mut hands = Hands::new(Device::Keys);
let stuck = PadState { buttons: Y, ..stick(0.8, 0.0) };
assert_eq!(hands.pad(stuck), Device::Controller);
let key = Hand { down: vec![b'W'], ..Default::default() };
assert_eq!(hands.step(Some(key.clone()), Some(stuck)), Device::Keys);
for v in [0.8, 0.44, 0.46, 0.31, 0.5] {
// Held, it trembles around the mark without being a push again.
let stuck = PadState { left_x: v, ..stuck };
assert_eq!(hands.step(Some(key.clone()), Some(stuck)), Device::Keys);
}
assert_eq!(hands.step(Some(key.clone()), Some(stick(0.0, 0.0))), Device::Keys);
assert_eq!(hands.step(Some(key), Some(stuck)), Device::Controller);
}
#[test]
fn a_controller_that_connects_changes_nothing_until_it_is_used() {
let mut hands = Hands::new(Device::Keys);
hands.step(Some(Hand::default()), None);
let held = PadState { buttons: A, ..stick(0.9, 0.0) };
assert_eq!(hands.pad(held), Device::Keys);
// And one that goes changes nothing either.
hands.used.device = Device::Controller;
assert_eq!(hands.step(Some(Hand::default()), None), Device::Controller);
}
#[test]
fn a_nudged_mouse_changes_nothing() {
let mut hands = Hands::new(Device::Controller);
for i in 0..5000 {
// A trembling desk, a sensor that creeps, a nudge each second.
let moved = match i % 125 {
0 => (60, 30),
n if n % 2 == 0 => (1, 0),
_ => (-1, 1),
};
assert_eq!(hands.mouse(moved), Device::Controller, "{i}");
}
}
#[test]
fn a_moved_mouse_a_notch_a_button_and_a_key_are_the_keys() {
let mut hands = Hands::new(Device::Controller);
let moved: Vec<_> = (0..8).map(|_| hands.mouse((-10, 10))).collect();
assert_eq!((moved[2], moved[7]), (Device::Controller, Device::Keys));
let mut hands = Hands::new(Device::Controller);
let notch = |wheel| Some(Hand { wheel, ..Default::default() });
assert_eq!(hands.step(notch(30), None), Device::Controller);
assert_eq!(hands.step(notch(-90), None), Device::Controller, "back is not on");
assert_eq!(hands.step(notch(-30), None), Device::Keys);
// Fine wheels: parts of a notch, close together.
let mut hands = Hands::new(Device::Controller);
for (part, device) in [(40, Device::Controller), (40, Device::Controller), (40, Device::Keys)] {
assert_eq!(hands.step(notch(part), None), device);
}
let mut hands = Hands::new(Device::Controller);
for _ in 0..100 {
hands.now += MS(400);
assert_eq!(hands.step(notch(100), None), Device::Controller);
}
for key in [b'W', 0x01] {
assert_eq!(Hands::new(Device::Controller).keys(&[key]), Device::Keys);
}
}
#[test]
fn keys_held_from_another_window_or_held_on_change_nothing() {
let mut hands = Hands::new(Device::Controller);
hands.step(None, None);
for _ in 0..50 {
assert_eq!(hands.keys(b"W"), Device::Controller);
}
assert_eq!(hands.keys(b"WD"), Device::Keys);
hands.used.device = Device::Controller;
assert_eq!(hands.keys(b"WD"), Device::Controller);
assert_eq!(hands.keys(b"D"), Device::Controller);
}
#[test]
fn only_changes_are_told() {
let (bindings, _) = Bindings::new("");
let mut told = Told::new();
let tell = |told: &mut Told, hand: Hand, pad: PadState, layer, at: u64| {
told.step(Some(&hand), Some(pad), MS(at), layer, &bindings).map(|t| t.0.clone())
};
let (hand, rest) = (Hand::default, PadState::default);
assert_eq!(tell(&mut told, hand(), rest(), Layer::Foot, 0).unwrap(), "Keyboard and mouse, on foot");
for i in 1..1000 {
assert_eq!(tell(&mut told, hand(), stick(0.1, 0.1), Layer::Foot, i), None);
}
assert_eq!(tell(&mut told, hand(), rest(), Layer::Vehicle, 1001).unwrap(), "Keyboard and mouse, vehicle");
let push = PadState { buttons: RIGHT_STICK, ..Default::default() };
assert_eq!(tell(&mut told, hand(), push, Layer::Vehicle, 1002).unwrap(), "Controller");
// A controller's rows are the same in both layouts.
assert_eq!(tell(&mut told, hand(), push, Layer::Foot, 1003), None);
let press = Hand { down: vec![b'W'], ..Default::default() };
assert_eq!(tell(&mut told, press, rest(), Layer::Foot, 1004).unwrap(), "Keyboard and mouse, on foot");
// Keys read again that are the same tell nothing.
told.rebound();
assert_eq!(tell(&mut told, hand(), rest(), Layer::Foot, 1005), None);
// The rows are put together for a change alone, not at each poll.
assert_eq!(told.made, 6);
}
#[test]
fn a_file_is_read_once_when_it_was_written() {
let mut file = Settled::new(1);
let mut at = 0;
let mut look = |is| {
at += 1000;
file.changed(MS(at), || is)
};
assert_eq!([1, 1, 2, 3, 3, 3].map(&mut look), [false, false, false, false, true, false]);
// Written and put back; looked at once a second.
assert_eq!([4, 3, 3].map(&mut look), [false; 3]);
assert!(!file.changed(MS(at), || panic!("too early")));
// It could not be read: once more, when it lies still.
file.again();
let mut look = |is| {
at += 1000;
file.changed(MS(at), || is)
};
assert_eq!([3, 3, 4, 4, 4].map(&mut look), [true, false, false, true, false]);
}
/// Not asked for (the tests' environment does not): nothing of it begins.
#[cfg(windows)]
#[test]
fn nothing_is_told_without_the_switch() {
use super::super::{Source, host::Host, kbm};
assert!(!kbm::live::enabled());
let mut host = Host::default();
let key = KeyState { virtual_key: b'W', ..Default::default() };
assert_eq!(host.stand_in(&[key], Some(stick(1.0, 0.0)), true).left_y, 1.0);
assert!(!host.plays());
}
@@ -0,0 +1,386 @@
//! What keyboard and mouse play does to the host's cursor: held inside the
//! picture and hidden while the mouse turns the view, given back when the
//! rules ([`Kbm`]) or the host say so. The host is behind [`Desk`], so that
//! holding and giving back are tested.
use std::time::Duration;
use super::PadState;
use super::guide::{Hand, Row, Told};
use super::menu::{Do, Menu};
use super::kbm::{
ALT, Bindings, F1, Feel, Input, Kbm, Layer, MOUSE_KEYS, Motion, PAGE_DOWN, PAGE_UP, Reads, TAB, WHEEL_DOWN, WHEEL_UP, Way,
with_lines,
};
/// Left, top, right, bottom, on the screen.
pub(super) type Rect = (i32, i32, i32, i32);
/// The screen, or a fake in tests.
pub(super) trait Desk {
/// The window with the title's picture, if it is in front, and the picture.
fn window(&mut self) -> Option<(usize, Rect)>;
fn cursor(&mut self) -> Option<(i32, i32)>;
/// The window is the one at `at`, not one lying over it.
fn over(&mut self, window: usize, at: (i32, i32)) -> bool;
/// The mouse buttons held, as `kbm::MOUSE_KEYS`.
fn mouse(&mut self) -> [bool; 5];
/// Raw counts since the last call, if any event came.
fn raw(&mut self) -> Option<(i32, i32)>;
fn raw_failed(&mut self) -> bool;
/// How the title looks at the pad.
fn reads(&mut self) -> Reads {
Reads::default()
}
/// Wheel movement since the last call.
fn wheel(&mut self) -> i32;
/// Puts the cursor there; where it says it is then, `None` if it cannot.
fn place(&mut self, at: (i32, i32)) -> Option<(i32, i32)>;
/// What the cursor is held in.
fn clip(&mut self) -> Option<Rect>;
fn set_clip(&mut self, to: Option<Rect>);
/// Hides or shows the cursor over the picture; `window` is told now.
fn hide(&mut self, hidden: bool, window: Option<usize>);
/// Since some fixed time.
fn now(&mut self) -> Duration;
/// The key layout is this one now.
fn layer(&mut self, _layer: Layer) {}
/// What the key guide says from now on.
fn guide(&mut self, _title: &str, _rows: &[Row]) {}
/// The guide's title is shown for a moment: the keys changed.
fn notice(&mut self) {}
/// The sensitivity was set; for the next start, too.
fn keep(&mut self, _feel: Feel) {}
/// The whole guide is shown for the menu, or no longer.
fn menu(&mut self, _open: bool) {}
fn keys_text(&mut self) -> Option<String> {
None
}
fn write_keys(&mut self, _text: &str) -> bool {
false
}
/// The keys, if the player wrote others meanwhile.
fn rebound(&mut self, _now: Duration) -> Option<Bindings> {
None
}
}
/// The keys the title sees: with keyboard and mouse play, Caps Lock, F1 (the
/// key guide), F2 and the sensitivity's keys are ours.
pub(super) fn for_title(mut down: Vec<u8>, playing: bool) -> Vec<u8> {
down.retain(|vk| !(playing && matches!(*vk, 0x14 | F1 | 0x71 | PAGE_UP | PAGE_DOWN)));
down
}
/// Keyboard and mouse play: the rules and what they need of the host.
pub(super) struct Play<D> {
kbm: Kbm,
motion: Motion,
desk: D,
told: Option<Way>,
/// The window the cursor is held in.
holding: Option<usize>,
clip_checked: Duration,
/// Mouse buttons pressed outside the picture and not let go.
outside: [bool; 5],
told_guide: Told,
/// The sensitivity's key held, and when it counts again.
sliding: Option<(u8, Duration)>,
/// The guide's title is the slider until then.
slider_until: Option<Duration>,
changed: bool,
menu: Menu,
/// Keys and buttons down at the last step, and those pressed in the menu
/// and not let go.
held: Vec<u8>,
veiled: Vec<u8>,
wheel: i32,
}
impl<D: Desk> Play<D> {
pub(super) fn new(kbm: Kbm, motion: Motion, mut desk: D) -> Play<D> {
desk.layer(kbm.layer);
let mut play = Play {
kbm,
motion,
desk,
told: None,
holding: None,
clip_checked: Duration::ZERO,
outside: [false; 5],
told_guide: Told::new(),
sliding: None,
slider_until: None,
changed: false,
menu: Menu::default(),
held: Vec::new(),
veiled: Vec::new(),
wheel: 0,
};
play.tell(None, None, Duration::ZERO);
play
}
/// Tells the key guide what changed, if anything did.
fn tell(&mut self, hand: Option<&Hand>, pad: Option<PadState>, now: Duration) {
let told = self.told_guide.step(hand, pad, now, self.kbm.layer, &self.kbm.bindings);
if let Some((title, rows)) = told {
self.desk.guide(title, rows);
}
}
/// The title is to see no keys at all, or not this one.
pub(super) fn hides(&self, key: u8) -> bool {
self.menu.open || self.veiled.contains(&key)
}
/// The settings menu: `held`, the keys and buttons down now.
fn menu(&mut self, held: &[u8], wheel: i32, here: bool) {
let before = std::mem::replace(&mut self.held, held.to_vec());
self.veiled.retain(|key| held.contains(key));
let pressed: Vec<u8> = held.iter().copied().filter(|key| !before.contains(key)).collect();
if !self.menu.open {
if here && pressed.contains(&F1) {
self.menu.opened();
self.wheel = 0;
self.kbm.swallow(held);
self.desk.menu(true);
self.show_menu();
}
return;
}
if !here || pressed.contains(&F1) {
return self.close_menu(held);
}
self.wheel += wheel;
let notch = match self.wheel {
120.. => Some(WHEEL_UP),
..=-120 => Some(WHEEL_DOWN),
_ => None,
};
if notch.is_some() {
self.wheel = 0;
}
let presses: Vec<u8> = pressed.into_iter().chain(notch).collect();
for &key in &presses {
let asked = self.menu.press(key, self.kbm.feel, self.kbm.layer, &self.kbm.bindings);
match asked {
Do::Nothing => {}
Do::Close => return self.close_menu(held),
Do::Layer => {
self.kbm.by_hand();
self.desk.layer(self.kbm.layer);
}
Do::Feel(feel) => {
self.kbm.feel = feel;
self.desk.keep(feel);
}
Do::Keys(lines) => {
let text = self.desk.keys_text().map(|text| with_lines(&text, &lines));
self.write(text);
}
Do::Reset => {
self.write(Some("# All keys as they come.\n".to_owned()));
}
}
}
if !presses.is_empty() {
self.show_menu();
}
}
fn write(&mut self, text: Option<String>) {
match text {
Some(text) if self.desk.write_keys(&text) => {
self.kbm.rebind(Bindings::new(&text).0);
self.told_guide.rebound();
}
_ => self.menu.say("The key file cannot be written"),
}
}
fn show_menu(&mut self) {
let (title, rows) = self.menu.text(self.kbm.feel, self.kbm.layer, &self.kbm.bindings);
self.desk.guide(&title, &rows);
}
fn close_menu(&mut self, held: &[u8]) {
self.menu.open = false;
self.veiled = held.to_vec();
self.kbm.swallow(held);
self.told_guide.again();
self.desk.menu(false);
}
/// The sensitivity's keys: a step a press, and on while held.
fn slide(&mut self, keys: &[u8], focused: bool, now: Duration) {
let key = [PAGE_UP, PAGE_DOWN]
.into_iter()
.find(|key| focused && keys.contains(key) && !self.kbm.bindings.used(*key));
let Some(key) = key else {
self.sliding = None;
if std::mem::take(&mut self.changed) {
self.desk.keep(self.kbm.feel);
}
if self.slider_until.is_some_and(|until| now >= until) {
self.slider_until = None;
self.told_guide.again();
}
return;
};
let first = match self.sliding {
Some((held, _)) if held != key => true,
Some((_, at)) if now < at => return,
Some(_) => false,
None => true,
};
self.sliding = Some((key, now + Duration::from_millis(if first { 400 } else { 80 })));
self.kbm.feel.sens = self.kbm.feel.sens.moved(key == PAGE_UP);
self.changed = true;
self.slider_until = Some(now + Duration::from_secs(4));
let rows = super::guide::text(self.told_guide.device(), self.kbm.layer, &self.kbm.bindings).1;
self.desk.guide(&self.kbm.feel.sens.slider("Mouse sensitivity"), &rows);
self.desk.notice();
}
/// `keys`: held, by virtual key; `pad`: the controllers, if there are any.
/// Not `active`: something else plays.
pub(super) fn step(&mut self, keys: &[u8], pad: Option<PadState>, active: bool) -> PadState {
let now = self.desk.now();
if let Some(bindings) = self.desk.rebound(now) {
self.kbm.rebind(bindings);
self.told_guide.rebound();
}
// Another window of the title in front is a lost focus, too.
let window = self
.desk
.window()
.filter(|&(window, _)| active && self.holding.is_none_or(|held| held == window));
let cursor = self.desk.cursor();
let place = window.zip(cursor);
let raw = self.desk.raw();
let wheel = self.desk.wheel();
if self.desk.raw_failed() {
self.motion.way = Some(Way::Warp);
} else if raw.is_some() {
self.motion.raw_came();
}
// (What came while the mouse was free moved nothing.)
let moved = match place {
Some((_, at)) if self.holding.is_some() => self.motion.step(raw, at, now),
_ => (0, 0),
};
if self.holding.is_some() && self.motion.way != self.told {
self.told = self.motion.way;
tracing::info!(way = ?self.told, "mouse movement (raw input, or the cursor put back)");
}
let inside = place.is_some_and(|((window, (left, top, right, bottom)), at)| {
(left..right).contains(&at.0)
&& (top..bottom).contains(&at.1)
&& (self.kbm.locked || self.desk.over(window, at))
});
let mouse = self.desk.mouse();
// (A click outside the picture is none of ours, also when dragged in.)
for (outside, held) in self.outside.iter_mut().zip(mouse) {
*outside = held && (*outside || !inside);
}
let clicks = MOUSE_KEYS.into_iter().zip(mouse).zip(self.outside);
let clicks = clicks.filter(|&((_, held), outside)| held && !outside).map(|((key, _), _)| key);
// (Nor is Tab with Alt: that goes to another window.)
let leaving = ALT.iter().any(|alt| keys.contains(alt));
let hand = place.is_some().then(|| Hand {
down: keys
.iter()
.copied()
.filter(|&key| self.kbm.bindings.used(key) && !(leaving && key == TAB))
.chain(clicks)
.collect(),
moved,
wheel: if self.holding.is_some() { wheel } else { 0 },
});
let held: Vec<u8> = keys
.iter()
.copied()
.chain(MOUSE_KEYS.into_iter().zip(mouse).filter(|&(_, down)| down).map(|(key, _)| key))
.collect();
let was_open = self.menu.open;
self.menu(&held, wheel, place.is_some());
// (What is pressed in the menu, and what closed it, is the menu's.)
let ours = was_open || self.menu.open;
let layer = self.kbm.layer;
let plays = self.kbm.step(&Input {
focused: place.is_some(),
keys: if ours { Vec::new() } else { keys.to_vec() },
mouse: if ours { [false; 5] } else { mouse },
inside,
moved: if ours { (0, 0) } else { moved },
wheel: if ours { 0 } else { wheel },
reads: self.desk.reads(),
now,
});
if ours {
// (The rules saw nothing down: what is, is not pressed later.)
self.kbm.swallow(&held);
}
if !ours {
self.slide(keys, place.is_some(), now);
self.tell(hand.as_ref(), pad, now);
}
if self.kbm.layer != layer {
self.desk.layer(self.kbm.layer);
self.desk.notice();
}
self.hold(place, moved, now);
plays
}
/// Holds the cursor in the picture or lets it go, as the rules say.
fn hold(&mut self, place: Option<((usize, Rect), (i32, i32))>, moved: (i32, i32), now: Duration) {
if self.kbm.locked
&& let Some(((_, picture), at)) = place
{
let (left, top, right, bottom) = picture;
let middle = (left + (right - left) / 2, top + (bottom - top) / 2);
let first = self.holding.is_none();
if first {
self.motion.start(at);
}
// Put to the middle at first, and back to it once it went far
// from it where that is how movement is found (not after each
// movement: a put must not look like one).
let far = (right - left).min(bottom - top) / 4;
let went = (at.0 - middle.0).abs().max((at.1 - middle.1).abs()) > far;
if first || (went && moved != (0, 0) && self.motion.way == Some(Way::Warp)) {
match self.desk.place(middle) {
Some(is) => self.motion.placed(at, middle, is, now),
None if self.motion.way == Some(Way::Warp) => {
self.kbm.cannot_hold();
}
// Raw input needs no cursor, and may be what works.
None => {}
}
}
// The system drops a clip by itself now and then.
if self.kbm.locked && (first || now.saturating_sub(self.clip_checked) > Duration::from_secs(1)) {
self.clip_checked = now;
if first || self.desk.clip() != Some(picture) {
self.desk.set_clip(Some(picture));
}
}
}
let held = self.holding.is_some();
if held == self.kbm.locked {
return;
}
let window = place.map(|((window, _), _)| window);
self.holding = window.filter(|_| self.kbm.locked);
if held {
self.desk.set_clip(None);
}
self.desk.hide(!held, window);
}
}
#[cfg(test)]
#[path = "hold_tests.rs"]
mod tests;
@@ -0,0 +1,652 @@
use std::sync::{Arc, Mutex};
use super::super::kbm::{Bindings, MouseSettings};
use super::super::{B, MENU, RIGHT_STICK};
use super::*;
const ESC: u8 = 0x1B;
const F2: u8 = 0x71;
const WINDOW: usize = 7;
const PICTURE: Rect = (100, 200, 1380, 920);
const MIDDLE: (i32, i32) = (740, 560);
struct World {
/// In front, with a picture.
front: Option<(usize, Rect)>,
/// Lying over the picture.
covered: bool,
cursor: Option<(i32, i32)>,
mouse: [bool; 5],
raw: Option<(i32, i32)>,
raw_failed: bool,
wheel: i32,
can_place: bool,
places: u32,
clip: Option<Rect>,
hidden: bool,
hides: Vec<(bool, Option<usize>)>,
layers: Vec<&'static str>,
guides: Vec<(String, Vec<Row>)>,
/// The title of each notice.
notices: Vec<String>,
kept: Vec<u32>,
menus: Vec<bool>,
keys_file: Option<String>,
written: bool,
file: Option<&'static str>,
pad: Option<PadState>,
now: Duration,
}
struct Fake(Arc<Mutex<World>>);
impl Desk for Fake {
fn window(&mut self) -> Option<(usize, Rect)> {
self.0.lock().unwrap().front
}
fn cursor(&mut self) -> Option<(i32, i32)> {
self.0.lock().unwrap().cursor
}
fn over(&mut self, window: usize, _: (i32, i32)) -> bool {
assert_eq!(window, WINDOW);
!self.0.lock().unwrap().covered
}
fn mouse(&mut self) -> [bool; 5] {
self.0.lock().unwrap().mouse
}
fn raw(&mut self) -> Option<(i32, i32)> {
self.0.lock().unwrap().raw.take()
}
fn raw_failed(&mut self) -> bool {
self.0.lock().unwrap().raw_failed
}
fn wheel(&mut self) -> i32 {
std::mem::take(&mut self.0.lock().unwrap().wheel)
}
fn place(&mut self, at: (i32, i32)) -> Option<(i32, i32)> {
let mut world = self.0.lock().unwrap();
world.places += 1;
if !world.can_place {
return None;
}
world.cursor = Some(at);
world.cursor
}
fn clip(&mut self) -> Option<Rect> {
self.0.lock().unwrap().clip
}
fn set_clip(&mut self, to: Option<Rect>) {
self.0.lock().unwrap().clip = to;
}
fn hide(&mut self, hidden: bool, window: Option<usize>) {
let mut world = self.0.lock().unwrap();
world.hidden = hidden;
world.hides.push((hidden, window));
}
fn now(&mut self) -> Duration {
let mut world = self.0.lock().unwrap();
world.now += Duration::from_millis(8);
world.now
}
fn layer(&mut self, layer: Layer) {
self.0.lock().unwrap().layers.push(layer.name());
}
fn guide(&mut self, title: &str, rows: &[Row]) {
self.0.lock().unwrap().guides.push((title.to_owned(), rows.to_vec()));
}
fn notice(&mut self) {
let mut world = self.0.lock().unwrap();
let title = world.guides.last().unwrap().0.clone();
world.notices.push(title);
}
fn keep(&mut self, feel: Feel) {
self.0.lock().unwrap().kept.push(feel.sens.percent());
}
fn menu(&mut self, open: bool) {
self.0.lock().unwrap().menus.push(open);
}
fn keys_text(&mut self) -> Option<String> {
self.0.lock().unwrap().keys_file.clone()
}
fn write_keys(&mut self, text: &str) -> bool {
let mut world = self.0.lock().unwrap();
if world.written {
world.keys_file = Some(text.to_owned());
}
world.written
}
fn rebound(&mut self, _: Duration) -> Option<Bindings> {
self.0.lock().unwrap().file.take().map(|file| Bindings::new(file).0)
}
}
struct Run {
play: Play<Fake>,
world: Arc<Mutex<World>>,
active: bool,
}
impl Run {
fn new(way: Option<&str>) -> Run {
let world = Arc::new(Mutex::new(World {
front: Some((WINDOW, PICTURE)),
covered: false,
cursor: Some((400, 400)),
mouse: [false; 5],
raw: None,
raw_failed: false,
wheel: 0,
can_place: true,
places: 0,
clip: None,
hidden: false,
hides: Vec::new(),
layers: Vec::new(),
guides: Vec::new(),
notices: Vec::new(),
kept: Vec::new(),
menus: Vec::new(),
keys_file: Some(String::new()),
written: true,
file: None,
pad: None,
now: Duration::from_secs(5),
}));
let kbm = Kbm::new(Bindings::new("").0, MouseSettings::new(|_| None));
let mut run = Run {
play: Play::new(kbm, Motion::new(way), Fake(Arc::clone(&world))),
world,
active: true,
};
assert_eq!(run.world.lock().unwrap().guides.len(), 1, "before the first step");
run.step(&[]);
run
}
/// The mouse held by a click, and the button let go.
fn held(way: Option<&str>) -> Run {
let mut run = Run::new(way);
run.click();
run.assert_held();
run
}
fn step(&mut self, keys: &[u8]) -> PadState {
let pad = self.world.lock().unwrap().pad;
let pad = self.play.step(keys, pad, self.active);
// The three never part: that is what traps a pointer.
let world = self.world.lock().unwrap();
assert_eq!(self.play.holding.is_some(), self.play.kbm.locked);
assert_eq!(world.hidden, self.play.kbm.locked);
assert!(self.play.kbm.locked || world.clip.is_none(), "clipped, but not held");
pad
}
fn click(&mut self) {
self.set(|w| w.mouse[0] = true);
self.step(&[]);
self.set(|w| w.mouse[0] = false);
for _ in 0..20 {
self.step(&[]);
}
}
fn set(&mut self, change: impl FnOnce(&mut World)) {
change(&mut self.world.lock().unwrap());
}
fn assert_held(&self) {
let world = self.world.lock().unwrap();
assert_eq!((world.clip, world.hidden), (Some(PICTURE), true));
}
fn assert_free(&self) {
let world = self.world.lock().unwrap();
assert_eq!((world.clip, world.hidden), (None, false));
assert_eq!(world.hides.last().map(|h| h.0), Some(false));
assert!(!self.play.kbm.locked && self.play.holding.is_none());
}
/// Counts of raw movement turn the view.
fn turns(&mut self) -> bool {
self.set(|w| w.raw = Some((50, 0)));
self.step(&[]).right_x > 0.0
}
}
#[test]
fn a_click_holds_hides_and_clips_once() {
let mut run = Run::held(None);
run.set(|w| {
assert_eq!((w.cursor, w.places), (Some(MIDDLE), 1));
assert_eq!(w.hides, [(true, Some(WINDOW))]);
});
assert!(run.turns());
// A dropped clip is put back within about a second.
run.set(|w| w.clip = Some((0, 0, 5000, 5000)));
for _ in 0..130 {
run.step(&[]);
}
run.assert_held();
}
#[test]
fn everything_that_must_gives_the_pointer_back_at_once() {
type Change = fn(&mut Run);
let cases: [(&str, Change); 6] = [
("another program in front", |r| r.set(|w| w.front = None)),
("another window of ours in front", |r| r.set(|w| w.front = Some((WINDOW + 1, PICTURE)))),
("no cursor", |r| r.set(|w| w.cursor = None)),
("a controller plays", |r| r.active = false),
("Esc", |_| ()),
("F2", |_| ()),
];
for (why, change) in cases {
let mut run = Run::held(Some("1"));
assert!(run.turns(), "{why}");
change(&mut run);
// (Whatever is held at that moment.)
run.set(|w| w.mouse[0] = true);
let pad = run.step(match why {
"Esc" => &[ESC],
"F2" => &[F2],
_ => b"R",
});
run.assert_free();
assert_eq!((pad.right_x, pad.right_trigger), (0.0, 0.0), "{why}");
// And it stays free, with no more asked of the host.
run.set(|w| w.mouse[0] = false);
run.active = true;
run.set(|w| {
w.front = Some((WINDOW, PICTURE));
w.cursor = Some(MIDDLE);
});
for _ in 0..200 {
run.step(&[]);
run.assert_free();
}
run.set(|w| assert_eq!((w.places, w.hides.len()), (1, 2), "{why}"));
// What the mouse moves meanwhile turns nothing, then or later.
assert!(!run.turns(), "{why}");
run.click();
run.assert_held();
assert_eq!(run.step(&[]).right_x, 0.0, "{why}");
assert!(run.turns(), "{why}");
}
}
#[test]
fn a_lost_focus_asks_nothing_of_the_window_in_front() {
let mut run = Run::held(None);
run.set(|w| w.front = None);
run.step(&[]);
run.set(|w| assert_eq!(w.hides, [(true, Some(WINDOW)), (false, None)]));
}
#[test]
fn a_controller_that_plays_keeps_keys_and_mouse_out() {
let mut run = Run::new(None);
run.active = false;
run.set(|w| w.mouse = [true; 5]);
for _ in 0..50 {
assert_eq!(run.step(b"RF"), PadState::default());
}
run.set(|w| assert!(w.hides.is_empty() && w.clip.is_none() && w.places == 0));
}
#[test]
fn a_click_on_a_window_over_the_picture_takes_nothing() {
let mut run = Run::new(None);
run.set(|w| w.covered = true);
run.click();
run.set(|w| assert!(w.hides.is_empty() && w.places == 0 && w.clip.is_none()));
run.set(|w| w.covered = false);
run.click();
run.assert_held();
}
#[test]
fn a_click_outside_the_picture_takes_nothing() {
for at in [(99, 400), (1380, 400), (400, 199), (400, 920)] {
let mut run = Run::new(None);
run.set(|w| w.cursor = Some(at));
run.click();
run.set(|w| assert!(w.hides.is_empty() && w.places == 0, "{at:?}"));
}
}
#[test]
fn mouse_buttons_and_the_wheel_count_only_while_it_is_held() {
let mut run = Run::new(None);
run.set(|w| {
w.mouse[2] = true;
w.wheel = 120;
});
assert_eq!(run.step(b"R").buttons, B, "the keys do");
run.set(|w| w.mouse[2] = false);
let mut run = Run::held(None);
run.set(|w| w.mouse[2] = true);
assert_eq!(run.step(&[]).buttons, RIGHT_STICK);
assert_eq!(run.step(&[ESC]).buttons & MENU, MENU);
}
#[test]
fn raw_input_needs_no_cursor() {
// The cursor cannot be put anywhere: held all the same, raw input turns.
let mut run = Run::new(None);
run.set(|w| w.can_place = false);
run.click();
run.assert_held();
assert!(run.turns());
assert_eq!(run.play.motion.way, Some(Way::Raw));
// With raw input gone as well there is nothing to hold it for.
for way in [None, Some("0"), Some("1")] {
let mut run = Run::new(way);
run.set(|w| {
w.can_place = false;
w.raw_failed = true;
});
run.click();
run.set(|w| assert!(w.clip.is_none() && !w.hidden && w.hides.is_empty(), "{way:?}"));
}
}
#[test]
fn raw_events_seen_while_the_mouse_is_free_settle_the_way() {
let mut run = Run::new(None);
run.turns();
assert_eq!(run.play.motion.way, Some(Way::Raw));
let mut run = Run::new(Some("0"));
run.turns();
assert_eq!(run.play.motion.way, Some(Way::Warp), "asked for");
}
#[test]
fn a_cursor_moving_freely_decides_nothing() {
let mut run = Run::new(None);
for i in 0..200 {
run.set(|w| w.cursor = Some((400 + i, 400)));
run.step(&[]);
}
assert_eq!(run.play.motion.way, None);
}
#[test]
fn the_fallback_counts_every_movement_and_puts_the_cursor_back_now_and_then() {
let mut run = Run::held(Some("0"));
let (mut turned, mut moved) = (0, 0);
for _ in 0..300 {
run.set(|w| {
let at = w.cursor.unwrap();
w.cursor = Some((at.0 + 7, at.1));
});
moved += 1;
turned += i32::from(run.step(&[]).right_x > 0.0);
run.set(|w| assert!(w.cursor.unwrap().0 <= MIDDLE.0 + 720 / 4 + 7));
}
assert_eq!(turned, moved);
// The middle at first, and after each quarter of the picture's height.
run.set(|w| assert_eq!(w.places, 1 + 300 / 26));
// Nothing turns once it is still.
for _ in 0..20 {
run.step(&[]);
}
assert_eq!(run.step(&[]).right_x, 0.0);
}
#[test]
fn a_cursor_that_will_not_be_put_turns_no_still_view() {
// The host says the cursor is in the middle; it is not.
for way in [None, Some("0")] {
let mut run = Run::held(way);
run.set(|w| w.cursor = Some((400, 400)));
for i in 0..500 {
assert_eq!(run.step(&[]).right_x, 0.0, "{way:?} {i}");
}
if way.is_none() {
assert_eq!(run.play.motion.way, None);
// And raw input works when the hand moves.
assert!(run.turns());
}
}
}
#[test]
fn the_panel_is_told_the_layout() {
let mut run = Run::new(None);
run.step(&[0x14]);
run.step(&[]);
run.set(|w| assert_eq!(w.layers, ["on foot", "vehicle"]));
}
#[test]
fn caps_lock_f1_and_f2_are_not_the_titles_while_playing() {
let down = vec![0x14, b'W', F2, ESC, 0x70, 0x72];
assert_eq!(for_title(down.clone(), true), [b'W', ESC, 0x72]);
assert_eq!(for_title(down.clone(), false), down);
}
fn titles(run: &Run) -> Vec<String> {
run.world.lock().unwrap().guides.iter().map(|g| g.0.clone()).collect()
}
const FOOT: &str = "Keyboard and mouse, on foot";
const VEHICLE: &str = "Keyboard and mouse, vehicle";
#[test]
fn the_guide_is_told_each_change_once() {
let mut run = Run::new(None);
assert_eq!(titles(&run), [FOOT], "at the start");
// Caps Lock; the enter key, when it is let go.
run.step(&[0x14]);
assert_eq!(titles(&run), [FOOT, VEHICLE], "a layer change is told at once");
for keys in [&b""[..], b"F", b"F"] {
run.step(keys);
}
assert_eq!(titles(&run).len(), 2);
run.step(&[]);
assert_eq!(titles(&run), [FOOT, VEHICLE, FOOT]);
// A controller; then keys again.
let push = PadState { buttons: B, ..Default::default() };
run.set(|w| w.pad = Some(PadState::default()));
run.step(&[]);
run.set(|w| w.pad = Some(push));
run.step(&[]);
run.step(&[]);
run.set(|w| w.pad = None);
run.step(b"W");
run.step(b"W");
assert_eq!(titles(&run), [FOOT, VEHICLE, FOOT, "Controller", FOOT]);
// Shown for a moment at each change of the layer alone, with its new name.
run.set(|w| assert_eq!(w.notices, [VEHICLE, FOOT]));
}
#[test]
fn polls_alone_tell_the_guide_nothing() {
let mut run = Run::held(None);
for i in 0..2000_i32 {
let drift = 0.1 + 0.3 * (i % 2) as f32;
run.set(|w| {
w.pad = Some(PadState { left_x: drift, right_y: -drift, ..Default::default() });
w.raw = Some((i % 3 - 1, 1 - i % 3));
});
run.step(&[]);
}
assert_eq!(titles(&run), [FOOT]);
}
#[test]
fn other_keys_are_told_the_guide() {
let mut run = Run::new(None);
run.set(|w| w.file = Some("foot.Q = None\nfoot.F9 = RB"));
run.step(&[]);
run.step(&[]);
let guides = run.world.lock().unwrap().guides.clone();
assert_eq!(guides.len(), 2);
let key = |i: usize| guides[i].1.iter().find(|r| r.0 == "RB").unwrap().1.clone();
assert_eq!((key(0), key(1)), ("Q".to_owned(), "F9".to_owned()));
// Written without a change of any key: nothing to tell.
run.set(|w| w.file = Some("foot.Q = None\n# the same\nfoot.F9 = RB"));
run.step(&[]);
assert_eq!(titles(&run).len(), 2);
}
/// The whole way a controller's player goes: the mouse lies there, held.
#[test]
fn only_a_hand_takes_the_guide_back_from_a_controller() {
let mut run = Run::held(None);
run.set(|w| w.pad = Some(PadState::default()));
run.step(&[]);
run.set(|w| w.pad = Some(PadState { right_trigger: 1.0, ..Default::default() }));
run.step(&[]);
assert_eq!(titles(&run), [FOOT, "Controller"]);
// F3 shows the panel; unbound keys, a nudge, an unheld wheel.
for keys in [&[0x72][..], &[], &[0xA5]] {
run.step(keys);
}
run.set(|w| w.raw = Some((20, 20)));
run.step(&[]);
// Another window's keys, and a click beside the picture.
run.set(|w| w.front = None);
run.step(b"W");
run.set(|w| (w.front, w.cursor) = (Some((WINDOW, PICTURE)), Some((1, 1))));
run.step(&[]);
run.set(|w| w.mouse[0] = true);
run.step(&[]);
run.step(&[]);
// (Dragged in.)
run.set(|w| w.cursor = Some(MIDDLE));
run.step(&[]);
run.set(|w| w.mouse[0] = false);
run.step(&[]);
// Away with Alt and Tab.
run.step(&[0xA4]);
run.step(&[0xA4, 0x09]);
run.step(&[]);
assert_eq!(titles(&run), [FOOT, "Controller"]);
run.click();
assert_eq!(titles(&run), [FOOT, "Controller", FOOT]);
}
#[test]
fn page_up_and_down_slide_the_sensitivity() {
let mut run = Run::new(Some("1"));
let percent = |run: &Run| run.play.kbm.feel.sens.percent();
// A press is a step, and is kept once it is let go.
run.step(&[PAGE_UP]);
run.step(&[PAGE_UP]);
assert_eq!((percent(&run), run.world.lock().unwrap().kept.len()), (110, 0));
assert_eq!(run.world.lock().unwrap().notices, ["Mouse sensitivity [###-------] 110%"]);
run.step(&[]);
assert_eq!(run.world.lock().unwrap().kept, [110]);
// Held it goes on; the other way back.
for _ in 0..150 {
run.step(&[PAGE_DOWN]);
}
assert!((10..=60).contains(&percent(&run)), "{}", percent(&run));
run.step(&[]);
// The guide's own title comes back, once.
let before = run.world.lock().unwrap().guides.len();
for _ in 0..600 {
run.step(&[]);
}
let guides = run.world.lock().unwrap().guides[before..].to_vec();
assert_eq!(guides.len(), 1);
assert!(guides[0].0.starts_with("Keyboard and mouse"));
assert_eq!(run.world.lock().unwrap().kept.len(), 2);
// Not for another window, and not where the key file has them.
let now = percent(&run);
run.set(|w| w.front = None);
run.step(&[PAGE_UP]);
run.set(|w| {
w.front = Some((WINDOW, PICTURE));
w.file = Some("all.PageUp = A");
});
run.step(&[]);
run.step(&[PAGE_UP]);
assert_eq!(percent(&run), now);
assert_eq!(for_title(vec![PAGE_UP, b'W'], true), [b'W']);
assert_eq!(for_title(vec![PAGE_UP, b'W'], false), [PAGE_UP, b'W']);
}
#[test]
fn nothing_reaches_the_title_while_the_menu_is_open() {
let mut run = Run::held(Some("1"));
assert!(run.step(b"W").left_y > 0.0);
// Opened with W held: let go at once.
assert_eq!(run.step(&[b'W', F1]), PadState::default());
run.step(&[b'W', F1]);
assert_eq!(run.world.lock().unwrap().menus, [true]);
for _ in 0..20 {
run.set(|w| {
w.mouse = [true, true, false, false, false];
w.raw = Some((100, 100));
w.wheel = 120;
});
assert_eq!(run.step(&[b'W', b' ', b'R', 0x0D]), PadState::default());
assert!(run.play.hides(b'W') && run.play.hides(b'X'));
}
run.set(|w| (w.mouse, w.raw) = ([false; 5], None));
run.step(b"W");
// Esc closes it, and pauses nothing; held keys wait for a new press.
for _ in 0..30 {
assert_eq!(run.step(&[b'W', ESC]), PadState::default());
assert!(run.play.hides(ESC) && run.play.hides(b'W'));
}
assert_eq!(run.world.lock().unwrap().menus, [true, false]);
run.assert_held();
assert_eq!(run.step(b"W"), PadState::default());
assert!(!run.play.hides(ESC));
run.step(&[]);
assert!(run.step(b"W").left_y > 0.0);
assert!(!run.play.hides(b'W'));
// The guide is the keys' again.
assert!(run.world.lock().unwrap().guides.last().unwrap().0.starts_with("Keyboard and mouse"));
}
#[test]
fn the_menu_closes_with_f1_and_when_another_window_comes() {
let mut run = Run::held(Some("1"));
for close in [true, false] {
run.step(&[]);
run.step(&[F1]);
run.step(&[]);
assert!(run.play.menu.open);
if close {
run.step(&[F1]);
} else {
run.set(|w| w.front = None);
run.step(&[]);
}
assert!(!run.play.menu.open);
run.step(&[]);
}
run.assert_free();
// Not opened for another program.
run.step(&[F1]);
assert!(!run.play.menu.open);
}
#[test]
fn a_key_given_in_the_menu_counts_at_once_and_is_written() {
let mut run = Run::held(Some("1"));
let tap = |run: &mut Run, key: u8| {
run.step(&[key]);
run.step(&[]);
};
tap(&mut run, F1);
// To the line of A: five lines, then RT LT RB LB A.
(0..9).for_each(|_| tap(&mut run, 0x28));
tap(&mut run, 0x0D);
tap(&mut run, b'O');
assert!(run.world.lock().unwrap().keys_file.as_deref().unwrap().contains("foot.O = A"));
tap(&mut run, F1);
assert_eq!(run.step(b"O").buttons, super::super::A);
// Not written: said, and nothing changed.
run.step(&[]);
run.set(|w| w.written = false);
tap(&mut run, F1);
(0..9).for_each(|_| tap(&mut run, 0x28));
tap(&mut run, 0x0D);
tap(&mut run, b'U');
let said = run.world.lock().unwrap().guides.last().unwrap().1.last().unwrap().2.clone();
assert_eq!(said, "The key file cannot be written");
tap(&mut run, F1);
for _ in 0..20 {
run.step(&[]);
}
assert_eq!(run.step(b"U").buttons, 0);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,172 @@
//! The settings menu of keyboard and mouse play, in the key guide's box
//! (F1): the mouse's feel and the keys. One list; nothing here asks the host.
use super::guide::{MEANS, Row};
use super::kbm::{Bindings, Feel, Layer, Pad, WHEEL_DOWN, WHEEL_UP, action_of, file_key, fixed};
const ESC: u8 = 0x1B;
const ENTER: u8 = 0x0D;
const UP: u8 = 0x26;
const DOWN: u8 = 0x28;
const LEFT: u8 = 0x25;
const RIGHT: u8 = 0x27;
const CAPS: u8 = 0x14;
const CLICK: u8 = 0x01;
/// The lines before the keys: sensitivity, up and down, aiming, invert, reset.
const FIRST: usize = 5;
/// What the keys can be given to: name, and what it does in the two layers.
fn actions() -> impl Iterator<Item = (&'static str, &'static str, &'static str, &'static str)> {
let pad = MEANS.iter().filter_map(|&(pad, shown, foot, vehicle)| match pad {
Pad::Named(name) => Some((name, shown, foot, vehicle)),
_ => None,
});
pad.chain([("Phone", "", "Phone, out and away", "Phone, out and away"), ("Map", "", "Map, in and out", "Map, in and out")])
}
/// What the host is to do.
#[derive(Debug, PartialEq)]
pub(super) enum Do {
Nothing,
Close,
Layer,
/// The feel changed.
Feel(Feel),
/// These lines go into the key file.
Keys(Vec<String>),
/// The key file's own keys go: the defaults again.
Reset,
}
#[derive(Default)]
pub(super) struct Menu {
pub(super) open: bool,
row: usize,
/// The next key pressed is for this line.
waiting: bool,
/// Asked once more before all keys are reset.
sure: bool,
said: String,
}
impl Menu {
pub(super) fn opened(&mut self) {
*self = Menu { open: true, ..Menu::default() };
}
pub(super) fn say(&mut self, what: &str) {
self.said = what.to_owned();
}
fn lines() -> usize {
FIRST + actions().count()
}
/// A key, mouse button or wheel notch that was just pressed.
pub(super) fn press(&mut self, key: u8, feel: Feel, layer: Layer, bindings: &Bindings) -> Do {
self.said.clear();
if std::mem::take(&mut self.waiting) {
return self.bind(key, layer, bindings);
}
let sure = std::mem::take(&mut self.sure);
match key {
ESC => return Do::Close,
CAPS => return Do::Layer,
UP | WHEEL_UP => self.row = (self.row + Self::lines() - 1) % Self::lines(),
DOWN | WHEEL_DOWN => self.row = (self.row + 1) % Self::lines(),
LEFT | RIGHT if self.row < 4 => return Do::Feel(self.moved(feel, key == RIGHT)),
ENTER | CLICK => match self.row {
3 => return Do::Feel(self.moved(feel, true)),
4 if sure => return Do::Reset,
4 => {
self.sure = true;
self.say("All keys to the defaults? Enter again");
}
0..=2 => self.say("Left and right change it"),
_ => {
self.waiting = true;
self.say("Press the new key (Esc: no change)");
}
},
_ => self.say("Arrows choose, Enter changes"),
}
Do::Nothing
}
fn moved(&self, mut feel: Feel, up: bool) -> Feel {
match self.row {
0 => feel.sens = feel.sens.moved(up),
1 => feel.y = feel.y.moved(up),
2 => feel.aim = feel.aim.moved(up),
_ => feel.invert = !feel.invert,
}
feel
}
fn bind(&mut self, key: u8, layer: Layer, bindings: &Bindings) -> Do {
if key == ESC {
self.say("No change");
return Do::Nothing;
}
let Some(name) = file_key(key).filter(|_| !fixed(key)) else {
self.say("That key cannot be changed");
return Do::Nothing;
};
let Some((action, ..)) = actions().nth(self.row - FIRST) else { return Do::Nothing };
let bit = action_of(action);
// The keys it had, and all they did (a key that enters a vehicle also
// changes the layer).
let had: Vec<u8> =
(0x01..=0xFE_u8).filter(|&k| !fixed(k) && bindings.of(layer, k) & bit != 0).collect();
if had == [key] {
self.say("It has that key already");
return Do::Nothing;
}
let does = had.iter().map(|&k| bindings.of(layer, k)).max_by_key(|d| d.count_ones()).unwrap_or(bit);
let before = bindings.of(layer, key);
let of = layer.file_name();
let mut lines: Vec<String> = had
.iter()
.filter(|&&k| k != key)
.filter_map(|&k| Some(format!("{of}.{} = None", file_key(k)?)))
.collect();
lines.push(format!("{of}.{name} = {}", super::kbm::action_names(does)));
self.said = match before & !does {
0 => format!("{name} it is"),
other => format!("{name} it is, no longer {}", super::kbm::action_names(other)),
};
Do::Keys(lines)
}
/// The menu's title and rows.
pub(super) fn text(&self, feel: Feel, layer: Layer, bindings: &Bindings) -> (String, Vec<Row>) {
let mark = |i: usize, name: &str| format!("{}{name}", if i == self.row { ">" } else { " " });
let row = |i: usize, name: &str, key: &str, does: String| (mark(i, name), key.to_owned(), does);
let mut rows = vec![
row(0, "Mouse", "", feel.sens.slider("Sensitivity")),
row(1, "Mouse", "", feel.y.slider("Up and down")),
row(2, "Mouse", "", feel.aim.slider("While aiming")),
row(3, "Mouse", "", format!("Up looks down: {}", if feel.invert { "yes" } else { "no" })),
row(4, "Keys", "", "All to the defaults".to_owned()),
];
rows.extend(actions().enumerate().map(|(n, (action, shown, foot, vehicle))| {
let i = FIRST + n;
let keys = match self.waiting && i == self.row {
true => "...".to_owned(),
false => bindings.keys_of(layer, Pad::Named(action)),
};
row(i, shown, &keys, if layer == Layer::Foot { foot } else { vehicle }.to_owned())
}));
let said = match self.said.as_str() {
"" => "F1 or Esc closes, Caps Lock: layout",
said => said,
};
rows.push((String::new(), String::new(), said.to_owned()));
(format!("Settings, {}", layer.name()), rows)
}
}
#[cfg(test)]
#[path = "menu_tests.rs"]
mod tests;
@@ -0,0 +1,118 @@
use super::super::kbm::{Sens, with_lines};
use super::*;
fn keys(file: &str) -> Bindings {
Bindings::new(file).0
}
fn opened(row: usize) -> Menu {
let mut menu = Menu::default();
menu.opened();
for _ in 0..row {
assert_eq!(menu.press(DOWN, Feel::default(), Layer::Foot, &keys("")), Do::Nothing);
}
menu
}
fn row_of(action: &str) -> usize {
FIRST + actions().position(|a| a.0 == action).unwrap()
}
#[test]
fn the_menu_fits_its_box() {
for layer in [Layer::Foot, Layer::Vehicle] {
let (title, rows) = opened(0).text(Feel::default(), layer, &keys(""));
assert!(rows.len() <= 24 && title.len() <= 36, "{}", rows.len());
for (a, b, c) in rows {
assert!(a.chars().count() <= 12 && b.chars().count() <= 18 && c.chars().count() <= 36, "{a} {b} {c}");
}
}
}
#[test]
fn the_choice_goes_round() {
let mut menu = opened(0);
menu.press(UP, Feel::default(), Layer::Foot, &keys(""));
assert_eq!(menu.row, Menu::lines() - 1);
menu.press(WHEEL_DOWN, Feel::default(), Layer::Foot, &keys(""));
assert_eq!(menu.row, 0);
}
#[test]
fn left_and_right_move_the_sliders() {
let feel = Feel::default();
let of = |row, key| match opened(row).press(key, feel, Layer::Foot, &keys("")) {
Do::Feel(feel) => feel,
other => panic!("{other:?}"),
};
assert_eq!(of(0, RIGHT).sens.percent(), 110);
assert_eq!(of(1, LEFT).y.percent(), 90);
assert_eq!(of(2, RIGHT).aim.percent(), 110);
assert!(of(3, ENTER).invert);
assert_eq!(of(0, RIGHT).y, Sens::default());
}
#[test]
fn a_new_key_takes_the_old_ones_place() {
let mut menu = opened(row_of("A"));
menu.press(ENTER, Feel::default(), Layer::Foot, &keys(""));
let Do::Keys(lines) = menu.press(b'O', Feel::default(), Layer::Foot, &keys("")) else { panic!() };
let after = keys(&with_lines("", &lines));
assert_eq!(after.keys_of(Layer::Foot, Pad::Named("A")), "O Enter");
// Only there.
assert_eq!(after.keys_of(Layer::Vehicle, Pad::Named("A")), keys("").keys_of(Layer::Vehicle, Pad::Named("A")));
// The mouse's buttons and the wheel, too.
for (key, name) in [(0x05, "Mouse4"), (WHEEL_UP, "Wheel up")] {
let mut menu = opened(row_of("B"));
menu.press(ENTER, Feel::default(), Layer::Foot, &keys(""));
let Do::Keys(lines) = menu.press(key, Feel::default(), Layer::Foot, &keys("")) else { panic!() };
let after = keys(&with_lines("", &lines));
assert!(after.keys_of(Layer::Foot, Pad::Named("B")).contains(name));
}
}
#[test]
fn the_vehicles_key_still_changes_the_layer() {
let mut menu = opened(row_of("Y"));
menu.press(ENTER, Feel::default(), Layer::Foot, &keys(""));
let Do::Keys(lines) = menu.press(b'O', Feel::default(), Layer::Foot, &keys("")) else { panic!() };
assert!(lines.contains(&"foot.O = Y+Layer".to_owned()), "{lines:?}");
assert!(lines.contains(&"foot.F = None".to_owned()), "{lines:?}");
}
#[test]
fn a_taken_key_says_what_it_no_longer_does() {
let mut menu = opened(row_of("A"));
menu.press(ENTER, Feel::default(), Layer::Foot, &keys(""));
assert!(matches!(menu.press(b'Q', Feel::default(), Layer::Foot, &keys("")), Do::Keys(_)));
assert_eq!(menu.said, "Q it is, no longer RB");
}
#[test]
fn keys_that_must_stay_cannot_be_given_away() {
for key in [UP, DOWN, ENTER, 0x08, CAPS, 0x70, 0x71, ESC] {
let mut menu = opened(row_of("A"));
menu.press(ENTER, Feel::default(), Layer::Foot, &keys(""));
assert_eq!(menu.press(key, Feel::default(), Layer::Foot, &keys("")), Do::Nothing, "{key:#x}");
assert!(!menu.waiting && menu.open);
}
}
#[test]
fn resetting_asks_twice() {
let mut menu = opened(4);
let press = |menu: &mut Menu, key| menu.press(key, Feel::default(), Layer::Foot, &keys(""));
assert_eq!(press(&mut menu, ENTER), Do::Nothing);
assert_eq!(press(&mut menu, ENTER), Do::Reset);
assert_eq!(press(&mut menu, ENTER), Do::Nothing);
press(&mut menu, DOWN);
press(&mut menu, UP);
assert_eq!(press(&mut menu, ENTER), Do::Nothing, "asked anew");
}
#[test]
fn the_players_own_lines_stay_in_the_file() {
let file = "# mine\nfoot.Q = RB # cover\nall.V = X\nstrange line\n";
let after = with_lines(file, &["foot.q = A".to_owned()]);
assert_eq!(after, "# mine\nall.V = X\nstrange line\nfoot.q = A\n");
}
+68 -3
View File
@@ -240,6 +240,12 @@ fn hook(hwnd: HWND) {
}
}
/// Whether the title made the window (and not the system, for a message).
pub(crate) fn is_title_window(hwnd: HWND) -> bool {
// SAFETY: plain query.
!unsafe { wm::GetPropW(hwnd, TITLE_PROC) }.is_null()
}
extern "system" fn window_proc(
hwnd: HWND,
message: u32,
@@ -261,9 +267,16 @@ extern "system" fn window_proc(
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize {
return 0;
}
// Auto-hide the Windows cursor inside the game window's client area while
// mouse-look lock (`~` / `F2`) is active, and restore it immediately
// when unlocked (`~` / `F2` / `Esc` / `P`).
// F1 shows the key guide (it looks at the key itself).
if matches!(message, wm::WM_KEYDOWN | wm::WM_KEYUP) && super::gameinput::takes_key(wparam) {
return 0;
}
// The wheel, for keyboard and mouse play (the title reads no mouse).
if message == wm::WM_MOUSEWHEEL {
super::gameinput::wheel_moved((wparam >> 16) as u16 as i16);
}
// The cursor is hidden over the window's picture while the window holds
// the mouse (`VICTORY_KBM`), and back when it is freed.
if message == wm::WM_SETCURSOR && (lparam as u32 & 0xFFFF) == wm::HTCLIENT {
static CURSOR_HIDDEN: AtomicBool = AtomicBool::new(false);
if super::gameinput::cursor_locked() {
@@ -590,6 +603,58 @@ mod tests {
}
}
/// Stands in for a title's procedure that would show its own cursor.
extern "system" fn shows_a_cursor(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
if matches!(message, wm::WM_SETCURSOR | wm::WM_KEYDOWN | wm::WM_KEYUP) {
return 77;
}
// SAFETY: the system's default procedure, called as the system would.
unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) }
}
#[test]
fn the_cursor_is_hidden_over_the_picture_only_while_the_mouse_is_held() {
let null = std::ptr::null_mut();
let class = w!("STATIC");
let hwnd = CreateWindowExW(0, class, class, 0, 0, 0, 10, 10, null, null, null, std::ptr::null());
assert!(!hwnd.is_null() && is_title_window(hwnd));
// SAFETY: our own window, never shown, owned by this thread; the
// original procedure is put back before it is destroyed.
unsafe {
let title = wm::GetPropW(hwnd, TITLE_PROC);
wm::SetPropW(hwnd, TITLE_PROC, shows_a_cursor as *const () as *mut c_void);
let set = |place: u32| wm::SendMessageW(hwnd, wm::WM_SETCURSOR, hwnd as usize, place as isize);
assert_eq!(set(wm::HTCLIENT), 77);
// F1 is the title's without keyboard and mouse play only.
let key = |message: u32, key: usize| wm::SendMessageW(hwnd, message, key, 0);
for playing in [false, true] {
crate::modules::gameinput::PLAYING.set(playing);
let f1 = if playing { 0 } else { 77 };
assert_eq!((key(wm::WM_KEYDOWN, 0x70), key(wm::WM_KEYUP, 0x70)), (f1, f1));
assert_eq!((key(wm::WM_KEYDOWN, 0x72), key(wm::WM_KEYUP, 0x57)), (77, 77));
}
crate::modules::gameinput::PLAYING.set(false);
crate::modules::gameinput::set_cursor_locked(true);
assert_eq!(set(wm::HTCLIENT), 1, "hidden");
assert!(wm::GetCursor().is_null());
assert_eq!(set(wm::HTCLOSE), 77, "not over the frame");
crate::modules::gameinput::set_cursor_locked(false);
assert_eq!(set(wm::HTCLIENT), 77, "back");
assert!(!wm::GetCursor().is_null());
wm::SetPropW(hwnd, TITLE_PROC, title);
wm::DestroyWindow(hwnd);
// A window the title did not make: a message, say.
let other = wm::CreateWindowExW(0, class, class, 0, 0, 0, 10, 10, null, null, null, std::ptr::null());
assert!(!other.is_null() && !is_title_window(other));
wm::DestroyWindow(other);
}
}
thread_local! {
/// The system commands `recording` received, low four bits cleared.
static COMMANDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
File diff suppressed because it is too large. Load diff
+400 -325
View File
@@ -1,4 +1,5 @@
//! The host's FidelityFX through our entry points, called as the title calls the console's: the title's descriptions, console objects,
//! The host's FidelityFX through our entry points, called as the title calls
//! the console's: the title's descriptions, console objects,
//! one upscaling of a flat colour, the output read back. Needs the PC build
//! (`VICTORY_FIDELITYFX_DIR`) and a host GPU; skipped without them.
#![cfg(windows)]
@@ -191,12 +192,13 @@ fn the_titles_upscaler_runs_on_the_host() {
type Destroy = extern "C" fn(*mut *mut c_void, *const c_void) -> u32;
type Call = extern "C" fn(*mut *mut c_void, *mut Header) -> u32;
// SAFETY: our exports, with the API's signatures.
let (create, destroy, query, dispatch) = unsafe {
let (create, destroy, query, dispatch, configure) = unsafe {
(
std::mem::transmute::<usize, Create>(export("ffxCreateContext")),
std::mem::transmute::<usize, Destroy>(export("ffxDestroyContext")),
std::mem::transmute::<usize, Call>(export("ffxQuery")),
std::mem::transmute::<usize, Call>(export("ffxDispatch")),
std::mem::transmute::<usize, Call>(export("ffxConfigure")),
)
};
@@ -225,343 +227,416 @@ fn the_titles_upscaler_runs_on_the_host() {
*const Iid,
*mut This,
) -> i32;
let (mut queue, mut allocator, mut list) = (null(), null(), null());
let queue_desc = [0u32; 4];
assert_eq!(
slot::<MakeQueue>(device, 0x40)(
device,
queue_desc.as_ptr(),
&iid(&ID3D12CommandQueue::IID),
&mut queue
),
0
);
assert_eq!(
slot::<MakeAllocator>(device, 0x48)(
device,
0,
&iid(&ID3D12CommandAllocator::IID),
&mut allocator
),
0
);
assert_eq!(
slot::<MakeList>(device, 0x60)(
device,
0,
0,
allocator,
null(),
&iid(&ID3D12GraphicsCommandList::IID),
&mut list
),
0
);
let make = |desc: D3D12_RESOURCE_DESC| {
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let mut out = null();
const READ: u32 = 0xc0;
// One upscaling at these sizes, from its context to its pixels.
let run = |render: [u32; 2], output: [u32; 2]| {
let (mut queue, mut allocator, mut list) = (null(), null(), null());
let queue_desc = [0u32; 4];
assert_eq!(
slot::<MakeTexture>(device, 0xd8)(
slot::<MakeQueue>(device, 0x40)(
device,
&heap,
0,
&desc,
READ,
null(),
&iid(&ID3D12Resource::IID),
&mut out
queue_desc.as_ptr(),
&iid(&ID3D12CommandQueue::IID),
&mut queue
),
0
);
out
};
// The title's sizes on Series S (FSR 4 wrote zeros at 64x64 to 128x128).
let (render, output) = ([1280u32, 720], [1920u32, 1080]);
let at = |size: [u32; 2], format, flags| make(texture(size[0].into(), size[1], format, flags));
let target = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
let color = at(render, DXGI_FORMAT_R16G16B16A16_FLOAT, target);
let depth = at(
render,
DXGI_FORMAT_D32_FLOAT,
D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
);
let motion = at(render, DXGI_FORMAT_R16G16_FLOAT, target);
let upscaled = at(
output,
DXGI_FORMAT_R16G16B16A16_FLOAT,
target | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
);
// A flat colour in, another colour where the output should be written.
// SAFETY: plain host objects.
let targets: ID3D12DescriptorHeap = unsafe {
host.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
NumDescriptors: 2,
..Default::default()
})
}
.unwrap();
// SAFETY: as above.
let (first, step) = unsafe {
(
targets.GetCPUDescriptorHandleForHeapStart(),
host.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize,
)
};
const RENDER_TARGET: u32 = 0x4;
const COPY_SOURCE: u32 = 0x800;
let flat = [0.25f32, 0.5, 0.75, 1.0];
for (i, (resource, value)) in [(color, flat), (upscaled, [0.0, 1.0, 0.0, 1.0])]
.into_iter()
.enumerate()
{
let (texture, state) =
victory_gpu::external::host_texture(list, resource, RENDER_TARGET).unwrap();
assert_eq!(state, RENDER_TARGET);
let at = D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: first.ptr + i * step,
assert_eq!(
slot::<MakeAllocator>(device, 0x48)(
device,
0,
&iid(&ID3D12CommandAllocator::IID),
&mut allocator
),
0
);
assert_eq!(
slot::<MakeList>(device, 0x60)(
device,
0,
0,
allocator,
null(),
&iid(&ID3D12GraphicsCommandList::IID),
&mut list
),
0
);
let make = |desc: D3D12_RESOURCE_DESC| {
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let mut out = null();
const READ: u32 = 0xc0;
assert_eq!(
slot::<MakeTexture>(device, 0xd8)(
device,
&heap,
0,
&desc,
READ,
null(),
&iid(&ID3D12Resource::IID),
&mut out
),
0
);
out
};
// SAFETY: a live texture and our heap; the list is open.
unsafe { host.CreateRenderTargetView(&texture, None, at) };
// SAFETY: an open list and the view just made.
victory_gpu::external::record(list, |l| unsafe {
l.ClearRenderTargetView(at, &value, None)
})
.unwrap();
}
let at = |size: [u32; 2], format, flags| make(texture(size[0].into(), size[1], format, flags));
let target = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
let color = at(render, DXGI_FORMAT_R16G16B16A16_FLOAT, target);
let depth = at(
render,
DXGI_FORMAT_D32_FLOAT,
D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
);
let motion = at(render, DXGI_FORMAT_R16G16_FLOAT, target);
let upscaled = at(
output,
DXGI_FORMAT_R16G16B16A16_FLOAT,
target | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
);
// The title's context: HDR, inverted depth, auto exposure; its device;
// the API version it was built against (4.1.1).
let mut version = Version {
header: header(0x1_000b),
version: 0x0100_1001,
};
let mut console = Device {
header: Header {
kind: 0x100_0002,
next: &raw mut version.header,
},
device,
};
let mut upscale = CreateUpscale {
header: Header {
kind: 0x1_0000,
next: &raw mut console.header,
},
flags: 0x29,
max_render: render,
max_output: output,
message: 0,
};
let mut context = null_mut();
assert_eq!(create(&mut context, &mut upscale.header, null()), 0);
assert!(!context.is_null());
// Its queries: phase count, the first jitter offset, memory.
let mut phases = 0;
let mut count = PhaseCount {
header: header(0x1_0004),
render_width: render[0],
output_width: output[0],
count: &mut phases,
};
assert_eq!(query(&mut context, &mut count.header), 0);
assert!(phases > 0, "{phases} phases");
let (mut x, mut y) = (f32::NAN, f32::NAN);
let mut offset = JitterOffset {
header: header(0x1_0005),
index: 0,
phases,
x: &mut x,
y: &mut y,
};
assert_eq!(query(&mut context, &mut offset.header), 0);
assert!(x.abs() <= 0.5 && y.abs() <= 0.5, "jitter {x} {y}");
let mut usage = [0u64; 2];
let mut memory = MemoryUsage {
header: header(0x1_0008),
usage: &mut usage,
};
assert_eq!(query(&mut context, &mut memory.header), 0);
assert!(usage[0] > 0);
// Its dispatch: its resource descriptions (type, format, size, depth,
// mips, flags, usage) in the states it gives (read 0xc, written 0x2).
let described = |resource, format, size: [u32; 2], usage, state| Resource {
resource,
description: [2, format, size[0], size[1], 1, 1, 0, usage],
state,
};
let none = Resource {
resource: null(),
description: [0; 8],
state: 0,
};
let mut upscaling = DispatchUpscale {
header: header(0x1_0001),
list,
resources: [
described(color, 4, render, 0, 0xc),
described(depth, 28, render, 4, 0xc),
described(motion, 18, render, 0, 0xc),
none,
none,
none,
described(upscaled, 4, output, 2, 0x2),
],
jitter: [-x, -y],
motion_scale: [1.0, 1.0],
render,
output,
sharpen: 0,
sharpness: 0.0,
frame_ms: 33.3,
pre_exposure: 1.0,
reset: 1,
// Swapped for inverted depth, as the title passes them.
near: 1000.0,
far: 0.1,
fov: 1.0,
meters: 0.0,
flags: 0,
};
#[repr(C)]
struct Provider {
header: Header,
id: u64,
name: *const std::ffi::c_char,
}
let mut provider = Provider {
header: header(6),
id: 0,
name: null(),
};
assert_eq!(query(&mut context, &mut provider.header), 0);
// SAFETY: a name the DLL keeps.
eprintln!("provider {:#x} {:?}", provider.id, unsafe {
std::ffi::CStr::from_ptr(provider.name)
});
// Two frames: the first resets the history.
for reset in [1, 0] {
upscaling.reset = reset;
assert_eq!(dispatch(&mut context, &mut upscaling.header), 0);
}
// Read the output back in the same list, run it as the title would.
let (texture, state) =
victory_gpu::external::host_texture(list, upscaled, COPY_SOURCE).unwrap();
assert_eq!(state, COPY_SOURCE);
let (pitch, rows) = (
u64::from(output[0]).next_multiple_of(32) * 8,
u64::from(output[1]),
);
// SAFETY: plain creation of a read-back buffer.
let readback: ID3D12Resource = unsafe {
let mut buffer = None;
host.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_READBACK,
// A flat colour in, another colour where the output should be written.
// SAFETY: plain host objects.
let targets: ID3D12DescriptorHeap = unsafe {
host.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
NumDescriptors: 2,
..Default::default()
})
}
.unwrap();
// SAFETY: as above.
let (first, step) = unsafe {
(
targets.GetCPUDescriptorHandleForHeapStart(),
host.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize,
)
};
const RENDER_TARGET: u32 = 0x4;
const COPY_SOURCE: u32 = 0x800;
let flat = [0.25f32, 0.5, 0.75, 1.0];
for (i, (resource, value)) in [(color, flat), (upscaled, [0.0, 1.0, 0.0, 1.0])]
.into_iter()
.enumerate()
{
let (texture, state) =
victory_gpu::external::host_texture(list, resource, RENDER_TARGET).unwrap();
assert_eq!(state, RENDER_TARGET);
let at = D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: first.ptr + i * step,
};
// SAFETY: a live texture and our heap; the list is open.
unsafe { host.CreateRenderTargetView(&texture, None, at) };
// SAFETY: an open list and the view just made.
victory_gpu::external::record(list, |l| unsafe {
l.ClearRenderTargetView(at, &value, None)
})
.unwrap();
}
// The title's context: HDR, inverted depth, auto exposure; its device;
// the API version it was built against (4.1.1).
let mut version = Version {
header: header(0x1_000b),
version: 0x0100_1001,
};
let mut console = Device {
header: Header {
kind: 0x100_0002,
next: &raw mut version.header,
},
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: pitch * rows,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
device,
};
let mut upscale = CreateUpscale {
header: Header {
kind: 0x1_0000,
next: &raw mut console.header,
},
flags: 0x29,
max_render: render,
max_output: output,
message: 0,
};
let mut context = null_mut();
assert_eq!(create(&mut context, &mut upscale.header, null()), 0);
assert!(!context.is_null());
// Its queries: phase count, the first jitter offset, memory.
let mut phases = 0;
let mut count = PhaseCount {
header: header(0x1_0004),
render_width: render[0],
output_width: output[0],
count: &mut phases,
};
assert_eq!(query(&mut context, &mut count.header), 0);
// The formula, cut to a whole number; what the title divides by.
let ratio = output[0] as f32 / render[0] as f32;
eprintln!("{render:?} -> {output:?}: {phases} phases");
assert!(phases >= 1 && (phases - (8.0 * ratio * ratio) as i32).abs() <= 1, "{phases} phases");
// Every frame's offset, as the title asks them.
for index in (0..phases).rev() {
let (mut x, mut y) = (f32::NAN, f32::NAN);
let mut offset = JitterOffset { header: header(0x1_0005), index, phases, x: &mut x, y: &mut y };
assert_eq!(query(&mut context, &mut offset.header), 0);
assert!(x.abs() <= 0.5 && y.abs() <= 0.5, "jitter {index}: {x} {y}");
}
let (mut x, mut y) = (f32::NAN, f32::NAN);
let mut offset = JitterOffset {
header: header(0x1_0005),
index: 0,
phases,
x: &mut x,
y: &mut y,
};
assert_eq!(query(&mut context, &mut offset.header), 0);
assert!(x.abs() <= 0.5 && y.abs() <= 0.5, "jitter {x} {y}");
let mut usage = [0u64; 2];
let mut memory = MemoryUsage {
header: header(0x1_0008),
usage: &mut usage,
};
assert_eq!(query(&mut context, &mut memory.header), 0);
assert!(usage[0] > 0);
// Its dispatch: its resource descriptions (type, format, size, depth,
// mips, flags, usage) in the states it gives (read 0xc, written 0x2).
let described = |resource, format, size: [u32; 2], usage, state| Resource {
resource,
description: [2, format, size[0], size[1], 1, 1, 0, usage],
state,
};
let none = Resource {
resource: null(),
description: [0; 8],
state: 0,
};
let mut upscaling = DispatchUpscale {
header: header(0x1_0001),
list,
resources: [
described(color, 4, render, 0, 0xc),
described(depth, 28, render, 4, 0xc),
described(motion, 18, render, 0, 0xc),
none,
none,
none,
described(upscaled, 4, output, 2, 0x2),
],
jitter: [-x, -y],
motion_scale: [1.0, 1.0],
render,
output,
sharpen: 0,
sharpness: 0.0,
frame_ms: 33.3,
pre_exposure: 1.0,
reset: 1,
// Swapped for inverted depth, as the title passes them.
near: 1000.0,
far: 0.1,
fov: 1.0,
meters: 0.0,
flags: 0,
};
#[repr(C)]
struct Provider {
header: Header,
id: u64,
name: *const std::ffi::c_char,
}
let mut provider = Provider {
header: header(6),
id: 0,
name: null(),
};
assert_eq!(query(&mut context, &mut provider.header), 0);
// SAFETY: a name the DLL keeps.
eprintln!("provider {:#x} {:?}", provider.id, unsafe {
std::ffi::CStr::from_ptr(provider.name)
});
// Two frames: the first resets the history.
for reset in [1, 0] {
upscaling.reset = reset;
assert_eq!(dispatch(&mut context, &mut upscaling.header), 0);
}
// Read the output back in the same list, run it as the title would.
let (texture, state) =
victory_gpu::external::host_texture(list, upscaled, COPY_SOURCE).unwrap();
assert_eq!(state, COPY_SOURCE);
let (pitch, rows) = (
u64::from(output[0]).next_multiple_of(32) * 8,
u64::from(output[1]),
);
// SAFETY: plain creation of a read-back buffer.
let readback: ID3D12Resource = unsafe {
let mut buffer = None;
host.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_READBACK,
..Default::default()
},
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut buffer,
)
.unwrap();
buffer.unwrap()
};
victory_gpu::external::record(list, |l| {
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: borrowed; the location never releases it.
pResource: unsafe { std::mem::transmute_copy(&readback) },
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: DXGI_FORMAT_R16G16B16A16_FLOAT,
Width: output[0],
Height: output[1],
Depth: 1,
RowPitch: pitch as u32,
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: pitch * rows,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut buffer,
)
.unwrap();
buffer.unwrap()
};
victory_gpu::external::record(list, |l| {
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: borrowed; the location never releases it.
pResource: unsafe { std::mem::transmute_copy(&readback) },
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: DXGI_FORMAT_R16G16B16A16_FLOAT,
Width: output[0],
Height: output[1],
Depth: 1,
RowPitch: pitch as u32,
},
},
},
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: 0,
},
};
// SAFETY: an open list and live resources.
unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
})
.unwrap();
slot::<extern "system" fn(This) -> i32>(list, 0x48)(list);
slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list);
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: 0,
},
};
// SAFETY: an open list and live resources.
unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
})
.unwrap();
slot::<extern "system" fn(This) -> i32>(list, 0x48)(list);
slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list);
// SAFETY: the list ran (submissions are waited for).
let pixels = unsafe {
let mut mapped = null_mut();
readback.Map(0, None, Some(&mut mapped)).unwrap();
std::slice::from_raw_parts(mapped.cast::<u16>(), (pitch * rows / 2) as usize).to_vec()
// Submissions are not waited for: read until the output is there (two
// reads alike, something in them), ten seconds at most.
let mut pixels = Vec::new();
for _ in 0..200 {
std::thread::sleep(std::time::Duration::from_millis(50));
// SAFETY: mapped for the read; the card writes it at most once more.
let now = unsafe {
let mut mapped = null_mut();
readback.Map(0, None, Some(&mut mapped)).unwrap();
let now = std::slice::from_raw_parts(mapped.cast::<u16>(), (pitch * rows / 2) as usize).to_vec();
readback.Unmap(0, None);
now
};
let there = now.iter().any(|&p| p != 0) && now == pixels;
pixels = now;
if there {
break;
}
}
// No state the debug layer found wrong (if it is installed).
if let Ok(messages) = host.cast::<ID3D12InfoQueue>() {
// SAFETY: plain queries of the stored messages.
let errors: Vec<String> = unsafe {
(0..messages.GetNumStoredMessages())
.filter_map(|i| {
let mut size = 0;
messages.GetMessage(i, None, &mut size).ok()?;
let mut bytes = vec![0u64; size.div_ceil(8)];
let message = bytes.as_mut_ptr().cast::<D3D12_MESSAGE>();
messages.GetMessage(i, Some(message), &mut size).ok()?;
let m = &*message;
let text = std::ffi::CStr::from_ptr(m.pDescription.cast()).to_string_lossy();
eprintln!("debug layer {}: {text}", m.Severity.0);
(m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0).then(|| text.into_owned())
})
.collect()
};
assert!(errors.is_empty(), "debug layer: {errors:#?}");
}
// SAFETY: plain query.
assert!(unsafe { host.GetDeviceRemovedReason() }.is_ok());
eprintln!(
"first pixels: {:?}",
pixels[..16].iter().map(|&h| half(h)).collect::<Vec<_>>()
);
for (i, pixel) in pixels.chunks(4).enumerate() {
let rgb: Vec<f32> = pixel[..3].iter().map(|&h| half(h)).collect();
for (c, (&got, &want)) in rgb.iter().zip(&flat).enumerate() {
assert!(
(got - want).abs() < 0.05,
"pixel {i} channel {c}: {got}, not {want}"
);
}
}
assert_eq!(destroy(&mut context, null()), 0);
};
// No state the debug layer found wrong (if it is installed).
if let Ok(messages) = host.cast::<ID3D12InfoQueue>() {
// SAFETY: plain queries of the stored messages.
let errors: Vec<String> = unsafe {
(0..messages.GetNumStoredMessages())
.filter_map(|i| {
let mut size = 0;
messages.GetMessage(i, None, &mut size).ok()?;
let mut bytes = vec![0u64; size.div_ceil(8)];
let message = bytes.as_mut_ptr().cast::<D3D12_MESSAGE>();
messages.GetMessage(i, Some(message), &mut size).ok()?;
let m = &*message;
let text = std::ffi::CStr::from_ptr(m.pDescription.cast()).to_string_lossy();
eprintln!("debug layer {}: {text}", m.Severity.0);
(m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0).then(|| text.into_owned())
})
.collect()
};
assert!(errors.is_empty(), "debug layer: {errors:#?}");
}
// SAFETY: plain query.
assert!(unsafe { host.GetDeviceRemovedReason() }.is_ok());
eprintln!(
"first pixels: {:?}",
pixels[..16].iter().map(|&h| half(h)).collect::<Vec<_>>()
);
for (i, pixel) in pixels.chunks(4).enumerate() {
let rgb: Vec<f32> = pixel[..3].iter().map(|&h| half(h)).collect();
for (c, (&got, &want)) in rgb.iter().zip(&flat).enumerate() {
assert!(
(got - want).abs() < 0.05,
"pixel {i} channel {c}: {got}, not {want}"
);
// The title's sizes on Series S (FSR 4 wrote zeros at 64x64 to 128x128).
let mut sizes = vec![([1280u32, 720], [1920u32, 1080])];
// The launcher's scales at the title's modes, as the loader makes them,
// and a third at each, allowed there or not.
for output in victory_loader::resolution::MODES {
for scale in ["1", "0.6667", "0.5882", "0.5", "0.3333"] {
let (allowed, _) = victory_loader::resolution::ffx_scale(scale, Some(output), true);
for scale in [allowed, if scale == "0.3333" { victory_loader::resolution::FFX_MIN } else { allowed }] {
let render = victory_loader::resolution::ffx_render_size(scale, output);
let pair = ([render.0, render.1], [output.0, output.1]);
if !sizes.contains(&pair) {
sizes.push(pair);
}
}
}
}
assert_eq!(destroy(&mut context, null()), 0);
eprintln!("{} size pairs", sizes.len());
for (render, output) in sizes {
run(render, output);
}
// What the title would have divided by had its create been refused: our
// answer, and the upscaling refused, not a fault.
let mut none: *mut c_void = null_mut();
let mut phases = 0;
let mut count = PhaseCount { header: header(0x1_0004), render_width: 640, output_width: 1920, count: &mut phases };
assert_ne!(query(&mut none, &mut count.header), 0);
assert_eq!(phases, 72);
let mut dispatched = header(0x1_0001);
assert_ne!(dispatch(&mut none, &mut dispatched), 0);
// Anything else it might call then: refused, or asked of the host with no
// context (the render size of a preset needs none), not a fault.
let mut usage = [0u64; 2];
let mut memory = MemoryUsage { header: header(0x1_0008), usage: &mut usage };
assert_ne!(query(&mut none, &mut memory.header), 0);
let mut setting = [header(0x1_0007), header(0), header(0)];
assert_ne!(configure(&mut none, &mut setting[0]), 0);
assert_ne!(destroy(&mut none, null()), 0);
#[repr(C)]
struct Ratio {
header: Header,
quality: u32,
ratio: *mut f32,
}
let mut ratio = 0.0;
let mut of = Ratio { header: header(0x1_0002), quality: 4, ratio: &mut ratio };
let code = query(&mut none, &mut of.header);
eprintln!("ratio without a context: code {code}, {ratio}");
assert!(code != 0 || ratio == 3.0, "{ratio}");
}
+235 -17
View File
@@ -32,9 +32,18 @@
//! `VICTORY_RENDER_SCALE` replaces that constant (Series X; run res-4 at
//! 1.0). FidelityFX's (+0x28ef680, Series S) multiplies by 1.0 on Series X,
//! 2/3 on Series S; `VICTORY_FFX_SCALE` points its two loads at a constant
//! in its padding (as pull request #53 did). That one is not safe: at 0.5
//! on Series S (run res-6) FidelityFX's jitter phase count came back 0 and
//! the title divided by it (+0x28f03e8) 49 s in.
//! in its padding (as pull request #53 did). [`ffx_scale`] says which
//! values it takes and what is used instead of the others.
//!
//! Its method clamps nothing (the title's own, +0x7e9440, takes 0.2 to 1).
//! At 0.5 on Series S with the console's DLL (run res-6, no host upscaler)
//! the title divided by a jitter phase count of 0 (+0x28f03e8) 49 s in. The
//! count, at +0x10c of the upscaler, is written by one query (0x10004) when
//! the context is made (+0x28ef1d0); the title looks at neither the
//! create's nor the query's code, so a create or a query that fails leaves
//! the 0 it began with. The formula itself, 8 x (output / render)^2, gives 0
//! only when the render is more than 2.8 times wider than the output. The
//! host's module (`victory_hle`'s fidelityfx) now always writes 1 or more.
//! - **Upscaler.** `VICTORY_UPSCALER=<kind>` makes the picker return
//! `kind` (pull request #53): 6 the title's own, 7 FidelityFX.
@@ -78,15 +87,104 @@ pub fn parse_render_scale(spec: &str) -> Option<f32> {
spec.trim().parse::<f32>().ok().filter(|s| (0.5..=1.0).contains(s))
}
/// `VICTORY_FFX_SCALE=<s>`, 0.5 to 1.0: FidelityFX's render scale (Series
/// S). Crashed at 0.5 (run res-6); see the module's notes.
pub fn asked_ffx_scale() -> Option<f32> {
let spec = std::env::var("VICTORY_FFX_SCALE").ok()?;
let scale = parse_render_scale(&spec);
if scale.is_none() {
eprintln!("VIctory: VICTORY_FFX_SCALE={spec}: expected 0.5 to 1.0");
/// FidelityFX's smallest render scale with the host's upscaler: a third, the
/// "Ultra Performance" of its presets.
pub const FFX_MIN: f32 = 1.0 / 3.0;
/// Its smallest without the host's upscaler (the console's DLL then runs;
/// 0.5 itself crashed there once, run res-6) or with the output not known.
pub const FFX_MIN_CONSOLE: f32 = 0.5;
/// What is used for something that is no scale, and for one too low for the
/// console's DLL: the title's own on Series S.
pub const FFX_DEFAULT: f32 = 2.0 / 3.0;
/// The smallest render size a scale below [`FFX_MIN_CONSOLE`] may give: the
/// smallest the whole title was run at (1920x1080 at 0.5, host's upscaler).
/// FidelityFX itself was tested at a third of every mode; what the title's
/// own passes and pools do under this size is not known.
pub const FFX_MIN_RENDER: (u32, u32) = (960, 540);
/// The size FidelityFX's method (+0x28ef680) gives: each side times the
/// scale as an f32, cut to a whole number.
pub fn ffx_render_size(scale: f32, output: (u32, u32)) -> (u32, u32) {
((output.0 as f32 * scale) as u32, (output.1 as f32 * scale) as u32)
}
/// The smallest scale allowed: for `output` (`None`: not known), with or
/// without the host's upscaler.
fn ffx_smallest(output: Option<(u32, u32)>, host: bool) -> f32 {
match output {
Some((w, h)) if host => {
let fits = (FFX_MIN_RENDER.0 as f32 / w as f32).max(FFX_MIN_RENDER.1 as f32 / h as f32);
fits.clamp(FFX_MIN, FFX_MIN_CONSOLE)
}
_ => FFX_MIN_CONSOLE,
}
scale
}
/// The scale used for `VICTORY_FFX_SCALE=spec`, always one; and, if it is not
/// the one asked for, why. (Without one the title would render FidelityFX at
/// the full output size on Series X, the opposite of a low scale.)
///
/// A third written short (0.333, 0.3333) is the third: 3840x2160 then gives
/// 1280x720, not 1279x719.
pub fn ffx_scale(spec: &str, output: Option<(u32, u32)>, host: bool) -> (f32, Option<String>) {
let Some(asked) = spec.trim().parse::<f32>().ok().filter(|s| s.is_finite() && *s > 0.0) else {
return (FFX_DEFAULT, Some("not a scale above 0".into()));
};
if asked > 1.0 {
return (1.0, Some("above 1".into()));
}
let asked = if (asked - FFX_MIN).abs() < 0.0005 { FFX_MIN } else { asked };
let smallest = ffx_smallest(output, host);
if asked >= smallest {
return (asked, None);
}
if !host {
// Not 0.5: the value that crashed with the console's DLL.
return (FFX_DEFAULT, Some("below 0.5 without the host's upscaler (VICTORY_FIDELITYFX_DIR)".into()));
}
let why = if asked < FFX_MIN {
"below a third".into()
} else if let Some((w, h)) = output {
let (rw, rh) = ffx_render_size(asked, (w, h));
format!("{rw}x{rh} for an output of {w}x{h}, under {}x{}", FFX_MIN_RENDER.0, FFX_MIN_RENDER.1)
} else {
"below 0.5 with no accepted VICTORY_OUTPUT".into()
};
(smallest, Some(why))
}
/// `VICTORY_FFX_SCALE=<s>`: FidelityFX's render scale, [`ffx_scale`]'s rules;
/// what is used instead of another value is said. `None` if unset.
pub fn asked_ffx_scale(output: Option<(u32, u32)>, host: bool) -> Option<f32> {
let spec = std::env::var("VICTORY_FFX_SCALE").ok()?;
let (scale, instead) = ffx_scale(&spec, output, host);
if let Some(why) = instead {
tracing::warn!(asked = spec, why, used = scale, "resolution: VICTORY_FFX_SCALE not taken as asked; the upscaler stays on at another scale");
eprintln!("VIctory: VICTORY_FFX_SCALE={spec}: {why}; the upscaler stays on at {scale}");
}
if !host && scale <= FFX_MIN_CONSOLE {
tracing::warn!(scale, "resolution: without the host's upscaler the title crashed at this scale once (run res-6)");
}
Some(scale)
}
/// Sites written by [`apply_asked`]: bit 0 [`FFX_SCALE`], bit 1 [`PICKER`].
static WRITTEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
/// Whether [`FFX_SCALE`] was written.
pub fn ffx_scale_written() -> bool {
WRITTEN.load(std::sync::atomic::Ordering::Relaxed) & 1 != 0
}
/// Whether [`PICKER`] was written.
pub fn picker_written() -> bool {
WRITTEN.load(std::sync::atomic::Ordering::Relaxed) & 2 != 0
}
/// Whether the picker may be written: not to FidelityFX when a scale was asked
/// for and could not be (it would render at the full output size).
fn picker_allowed(kind: u32, scale_asked: bool, scale_written: bool) -> bool {
kind != 7 || !scale_asked || scale_written
}
/// `VICTORY_UPSCALER=<kind>`: 6 (the title's own) or 7 (FidelityFX).
@@ -290,15 +388,16 @@ pub unsafe fn write(base: usize, size: usize, site: &Site, code: &[u8]) -> Patch
}
/// Applies what the switches ask for; a line each in the log and on
/// standard output.
/// standard output. `host_ffx`: the host's upscaler serves the title's.
///
/// # Safety
/// The image of `size` bytes at `base` stays mapped and no thread runs its
/// code yet.
#[cfg(windows)]
pub unsafe fn apply_asked(base: usize, size: usize) {
pub unsafe fn apply_asked(base: usize, size: usize, host_ffx: bool) {
let mut asked: Vec<(&Site, Vec<u8>, String)> = Vec::new();
if let Some((w, h)) = asked_output() {
let output = asked_output();
if let Some((w, h)) = output {
asked.push((&OUTPUT, output_code(w, h), format!("{w}x{h}")));
if (w, h) != (3840, 2160) {
asked.push((&POOL_CHECK, pool_check_code(), format!("{w}x{h}")));
@@ -307,16 +406,28 @@ pub unsafe fn apply_asked(base: usize, size: usize) {
if let Some(s) = asked_render_scale() {
asked.push((&OWN_SCALE, own_scale_code(s), format!("{s}")));
}
if let Some(s) = asked_ffx_scale() {
let scale = asked_ffx_scale(output, host_ffx);
if let Some(s) = scale {
asked.push((&FFX_SCALE, ffx_scale_code(s), format!("{s}")));
}
if let Some(kind) = asked_upscaler() {
let kind = asked_upscaler();
if let Some(kind) = kind {
asked.push((&PICKER, picker_code(kind), format!("returns {kind}")));
}
for (site, code, value) in asked {
let offset = format!("{:#x}", site.at);
// The scale comes before it.
if site.at == PICKER.at && !picker_allowed(kind.unwrap_or(0), scale.is_some(), ffx_scale_written()) {
tracing::warn!(site = %offset, what = site.what, "resolution: not patched, the render scale that goes with it could not be; the title's own choice stays");
println!("resolution: {} ({value}) at title+{offset}: left alone without its render scale", site.what);
continue;
}
// SAFETY: the caller's promise.
let done = unsafe { write(base, size, site, &code) };
let offset = format!("{:#x}", site.at);
if done == Patched::Done {
let bit = if site.at == FFX_SCALE.at { 1 } else if site.at == PICKER.at { 2 } else { 0 };
WRITTEN.fetch_or(bit, std::sync::atomic::Ordering::Relaxed);
}
match done {
Patched::Done => tracing::info!(site = %offset, what = site.what, value, "resolution: patched"),
Patched::Differs => tracing::warn!(site = %offset, what = site.what, "resolution: not patched, the title's bytes there are not the ones expected (another build?)"),
@@ -343,6 +454,113 @@ mod tests {
assert_eq!(parse_render_scale("1.5"), None);
}
/// The launcher's scales (name, as it writes it, the preset's ratio).
const LAUNCHER: [(&str, f64); 5] = [("1", 1.0), ("0.6667", 1.5), ("0.5882", 1.7), ("0.5", 2.0), ("0.3333", 3.0)];
/// Each at each output size: passed through, or the smallest that fits
/// where a third would be too small, and then said.
#[test]
fn the_launchers_scales_pass_through() {
for output in MODES {
for (spec, ratio) in LAUNCHER {
let (scale, instead) = ffx_scale(spec, Some(output), true);
let small = spec == "0.3333" && output.1 < 2160;
if small {
assert_eq!(scale, if output.1 == 1440 { 0.375 } else { 0.5 }, "{output:?}");
assert!(instead.unwrap().contains("under 960x540"));
continue;
}
assert_eq!(instead, None, "{spec} {output:?}");
assert!((f64::from(scale) - 1.0 / ratio).abs() < 1e-4, "{spec}: {scale}");
let (w, h) = ffx_render_size(scale, output);
// Within a pixel of the preset's size, never 0, never larger.
assert!((f64::from(w) - f64::from(output.0) / ratio).abs() <= 1.01, "{spec} {output:?}: {w}");
assert!((f64::from(h) - f64::from(output.1) / ratio).abs() <= 1.01, "{spec} {output:?}: {h}");
assert!(w >= 640 && h >= 360 && w <= output.0 && h <= output.1);
}
}
// As seen in the logs of runs (1440p), and the third, exact.
assert_eq!(ffx_render_size(0.6667, (2560, 1440)), (1706, 960));
assert_eq!(ffx_render_size(0.5882, (2560, 1440)), (1505, 847));
assert_eq!(ffx_render_size(0.5, (2560, 1440)), (1280, 720));
for (output, render) in [((1920, 1080), (960, 540)), ((2560, 1440), (960, 540)), ((3840, 2160), (1280, 720))] {
assert_eq!(ffx_render_size(ffx_scale("0.3333", Some(output), true).0, output), render);
}
}
/// A scale always comes out, inside the bounds, whatever is asked.
#[test]
fn a_scale_not_taken_is_replaced_and_said() {
let hd = Some((3840, 2160));
let said = |spec: &str, output, host| {
let (scale, why) = ffx_scale(spec, output, host);
(scale, why.unwrap_or_else(|| panic!("{spec}: taken as {scale}")))
};
for (spec, scale, why) in [
("0.3", FFX_MIN, "below a third"),
("0.332", FFX_MIN, "below a third"),
("0.0001", FFX_MIN, "below a third"),
("1.0001", 1.0, "above 1"),
("2", 1.0, "above 1"),
("0", FFX_DEFAULT, "not a scale"),
("-1", FFX_DEFAULT, "not a scale"),
("nan", FFX_DEFAULT, "not a scale"),
("inf", FFX_DEFAULT, "not a scale"),
("", FFX_DEFAULT, "not a scale"),
("half", FFX_DEFAULT, "not a scale"),
] {
let (got, reason) = said(spec, hd, true);
assert_eq!(got, scale, "{spec}");
assert!(reason.contains(why), "{spec}: {reason}");
}
assert_eq!(FFX_DEFAULT, 0.666_666_7);
// Whatever is asked, where the output is known: a size FidelityFX's
// method gives that is no smaller than 0.5's at the smallest mode.
for output in MODES {
for step in -100..3000 {
for host in [true, false] {
let (scale, _) = ffx_scale(&format!("{}", step as f32 / 1000.0), Some(output), host);
let (w, h) = ffx_render_size(scale, output);
assert!((640..=output.0).contains(&w) && (360..=output.1).contains(&h), "{step} {output:?}: {w}x{h}");
// Below 0.5 only sizes the title was run at.
assert!(scale >= 0.5 || (host && w >= 960 && h >= 540), "{step} {output:?}: {w}x{h}");
}
}
}
// No host upscaler, or an output not known: nothing below 0.5.
for spec in ["0.3333", "0.49", "0.1"] {
// Not 0.5, which crashed there.
assert_eq!(said(spec, hd, false).0, FFX_DEFAULT);
}
assert!(said("0.3333", hd, false).1.contains("VICTORY_FIDELITYFX_DIR"));
assert_eq!(said("0.3333", None, true).0, 0.5);
assert!(said("0.49", None, true).1.contains("VICTORY_OUTPUT"));
// The bounds themselves.
assert_eq!(ffx_scale("0.5", None, false), (0.5, None));
assert_eq!(ffx_scale("1.0", None, false), (1.0, None));
assert_eq!(ffx_scale(" 0.333 ", hd, true), (FFX_MIN, None));
assert_eq!(ffx_scale("0.334", hd, true), (0.334, None));
assert_eq!(ffx_scale("0.4", hd, true), (0.4, None));
// Judged by the size it gives, replaced by the nearest that fits.
let (qhd, small) = (Some((2560, 1440)), Some((1664, 936)));
assert_eq!(ffx_scale("0.4", qhd, true), (0.4, None));
assert_eq!(ffx_scale("0.375", qhd, true), (0.375, None));
let (scale, why) = said("0.37", qhd, true);
assert_eq!(scale, 0.375);
assert_eq!(why, "947x532 for an output of 2560x1440, under 960x540");
assert_eq!(said("0.4", small, true).0, 0.5);
assert_eq!(said("0.1", qhd, true).0, 0.375);
}
/// FidelityFX is not picked without the scale asked for.
#[test]
fn the_picker_goes_with_its_scale() {
assert!(picker_allowed(7, true, true));
assert!(!picker_allowed(7, true, false));
assert!(picker_allowed(7, false, false));
assert!(picker_allowed(6, true, false));
}
/// The calls and loads in the bytes compared are the ones the
/// replacement keeps.
#[test]
+9 -3
View File
@@ -89,8 +89,9 @@ the frame now is the one thread that submits the title's work to the card
| `VICTORY_FRAME_INTERVAL_MS=16.667` | Lets the title go above 30 fps (menus and videos reach 60; the game's clock stays right) |
| `VICTORY_BINK_TICK_CLOCK=0` | Turns off the clock that steps Bink's videos with the frame clock's ticks (on by default: without it a 30 fps video judders, held 1, 2 or 3 frames) |
| `VICTORY_AMBIENT_SETTLE` | How fast light settles after walking indoors (on by default, `250,3`; `0` turns it off) |
| `VICTORY_KEY_GUIDE=1` | Shows the key guide (the pad's button, the key and what it does, lower right corner) for the first 15 s and the layout's name for 4 s when it changes; `always` shows it until `F1` hides it. Unless it is `0`, the name of the key layout shows for 4 s when the layout changes (`layout` or unset: that alone). The rows come with `VICTORY_KBM=1`. `F1` shows and hides the guide with or without it; the numbers' panel is `VICTORY_PANEL=1` |
| `VICTORY_TEXTURE_STORE=1` | Converted textures kept between runs (about 8 ms a frame for now: off) |
| `VICTORY_KBM_PC=1` | Optional PC-style keyboard and mouse mapping on the stand-in pad: `F2` or `` ` `` (`~`) toggles mouse-look and auto-hides the cursor while locked (`Esc`/`P`/focus loss unlocks and restores it), LMB/RMB = RT/LT, MMB/`C` = R3, `Shift` = A, `Space` = X, `R` = B, `F` = Y, `Tab` = LB, `Q` = RB, `Ctrl` = L3, `E` = D-pad Right, `V` = View. Tune with `VICTORY_MOUSE_SENS` (default `1.0`) and `VICTORY_MOUSE_INVERT_Y=1` (or pass via `scripts\play.ps1 -More @{VICTORY_KBM_PC='1'}`) |
| `VICTORY_KBM=1` | Keyboard and mouse as the pad (`VICTORY_KBM_PC=1`: the old name): click into the window to hold the mouse, `Esc`, `Alt+Tab` or `F2` frees it. On foot: `WASD`, `Shift` sprint, `Space` jump, `Ctrl` crouch, `Q` cover, `R` reload, `F` enter, `Tab` weapon wheel, left and right mouse fire and aim. Vehicle: `W`/`S` accelerate and brake, `Space` handbrake. `Caps Lock` changes between the two by hand. Tune with `VICTORY_MOUSE_SENS` and more; own keys in `keys.txt`: [docs/keyboard-mouse.md](docs/keyboard-mouse.md) |
What is known to be wrong:
@@ -161,8 +162,13 @@ In short; the reasons and the measurements are in [docs/findings.md](docs/findin
- **Series X can upscale with AMD FidelityFX on the host** (diagnostics build):
`VICTORY_UPSCALER=7` switches the title's upscaler to it and
`VICTORY_FFX_SCALE=<scale>` sets the render scale (`0.5` renders 1080p for a
4K output). Run with `--console series-x` and point `VICTORY_FIDELITYFX_DIR`
at the FidelityFX SDK's `Kits/FidelityFX/signedbin` folder.
4K output). It takes 0.5 to 1, and below 0.5 down to `0.3333` where the
render stays at 960x540 or more with `VICTORY_OUTPUT` set: all of that at
3840x2160, 0.375 at 2560x1440. A third was tested with FidelityFX alone, not
yet run in the title. A scale too low or above 1 becomes the nearest allowed
one, anything that is no scale (or too low without the host's upscaler) 2/3;
the log says which. Run with `--console series-x` and point
`VICTORY_FIDELITYFX_DIR` at the FidelityFX SDK's `Kits/FidelityFX/signedbin` folder.
The Series X patches, extra device feature answers and compiler-crash
guard take effect only after a host upscaler loads from that folder.
`VICTORY_FIDELITYFX_FRAMEGEN=1` adds AMD frame generation with the built-in
+109
View File
@@ -0,0 +1,109 @@
# Keyboard and mouse
The title knows game pads only. With `VICTORY_KBM=1` (in the launcher: Controls, on by
default) the keyboard and the mouse are that pad. A connected controller works as before.
The old name `VICTORY_KBM_PC=1` turns the same thing on when `VICTORY_KBM` is not set.
With `VICTORY_KBM=0` the plain stand-in keys of `README-fxceless.md` are in use.
## The mouse
Click into the window and it holds the mouse: the cursor is hidden and moving turns the
view. That click does nothing else. `F2` does the same. `Esc`, whatever key, button or wheel means Menu, `Alt+Tab`, the Windows key,
`F2` again or any other window in front frees it at once. Mouse buttons and the wheel reach the title only while the mouse is held.
## Keys
| Key | On foot | Vehicle |
|---|---|---|
| W S | move | accelerate (RT), brake and reverse (LT) |
| A D | move | steer |
| Shift | run (X) | boost (A) |
| Space | jump (A) | handbrake (RB) |
| Ctrl | crouch (L3) | horn (L3) |
| H | special (R3) | horn (L3) |
| Q | cover (RB; a tab while the weapon wheel is open) | D-pad left |
| E | interact (D-pad right) | D-pad right |
| left mouse | fire (RT) | |
| right mouse | aim (LT) | |
| wheel | (phone and map) | D-pad right and left |
| middle mouse | look behind, special (R3) | the same |
| Tab | weapon wheel, hold (LB) | the same |
| F | enter, mount (Y) | leave (Y) |
| R, X | reload (B), X | the same |
| G, Z | throw (D-pad left), radar (D-pad down) | the same |
| P | phone out (D-pad up), and away (B) at the next press; the wheel scrolls in it | the same |
| 1 2 3 4 | D-pad up, down, left, right | the same |
| C | look behind (R3) | the same |
| I J K L | right stick | the same |
| Num 8, Num 5 | | left stick up and down |
| M | map (View), and away (B) at the next press: the mouse moves it (left stick), the wheel zooms (RT, LT), left click is A, right click leaves | the same |
| Esc | pause (Menu) | the same |
| F1 | the settings menu; the title does not see it | the same |
| Enter, Backspace, arrows | A, B, D-pad (menus) | the same |
What a pad button does is the title's choice. The lines above follow common third-person
pad layouts; the vehicle's LB and D-pad lines are the least certain. If one is wrong, change
it in the key file.
## Which layout is in use
The title does not say whether the player drives. Letting go of `F` changes the layout,
and `Caps Lock` changes it by hand when that was wrong (no vehicle near, a cutscene that
puts the player into one). `F` pressed while the mouse is free (a menu) changes no layout,
unless the mouse was never held since the start. At each change the layout's name is shown
for 4 s in the lower right corner (not with `VICTORY_KEY_GUIDE=0`). `Caps Lock` does nothing else then. The log says `key layout`
at each change; in diagnostics builds the on-screen panel (F3) shows it on its last line.
## The settings menu
`F1` opens a menu in the lower right corner: the mouse's sensitivity, up and down, while aiming
and invert (left and right), and every button's keys. Up and down or the wheel choose, `Enter` or
a click changes: press the new key, `Esc` for no change. `Caps Lock` shows the other layout. `F1`
or `Esc` closes it. The title sees no keys and no mouse meanwhile (a controller plays on). Keys go
into the key file (the one before stays as `keys.txt.old`), the mouse into `mouse.txt`. The
movement keys (W A S D) are changed in the key file alone.
The name of the layout is shown for 4 s at each change (not with `VICTORY_KEY_GUIDE=0`); `always`
shows the keys in use until the menu is closed. Without `VICTORY_KBM=1` there is no menu and `F1`
is the title's.
## The sensitivity while playing
`Page Up` and `Page Down` slide the mouse's sensitivity (10 to 500 %, on top of the launcher's);
the slider is shown for 4 s and the value kept in `mouse.txt` beside the key file. A key file
that binds these keys has them instead.
## The key file
`keys.txt` in the store folder (beside `victory-data`), or `VICTORY_KBM_FILE`. Only what
differs from the defaults has to be in it:
foot.Space = X
vehicle.MouseLeft = RB
all.0xBC = Left
`VICTORY_KBM_WRITE=1` writes all defaults with an explanation, if there is no file yet.
Lines that say nothing known are named once in the log (the first 20) and ignored; a file
larger than 64 KB is not read. The file is looked at once a second: changes count while
the title runs, without a restart. One that cannot be read (held by an editor) is tried
again each second; the keys stay as they were until then.
## Tuning
| Variable | Default | What it does |
|---|---|---|
| `VICTORY_MOUSE_SENS` | 1.0 | How far the view turns |
| `VICTORY_MOUSE_SENS_Y` | 1.0 | Up and down, on top |
| `VICTORY_MOUSE_AIM` | 1.0 | While aiming, on top |
| `VICTORY_MOUSE_INVERT_Y` | 0 | `1`: mouse up looks down |
| `VICTORY_MOUSE_DPI` | 800 | The mouse's own DPI: the same hand movement turns the same |
| `VICTORY_MOUSE_FULL_SPEED` | 2200 | Counts a second that push the stick all the way (at 800 DPI: 7 cm a second) |
| `VICTORY_MOUSE_DEADZONE` | 0.24 | The stick's shortest push. Raise it if small movements do nothing, lower it if they jump |
| `VICTORY_MOUSE_SETTLE_MS` | 67 | Only for a title that does not look at the pad once a frame (one that does is told at each look what the mouse moved since the last): how long a movement is spread over: two frames at 30 a second. Shorter than a frame loses small movements |
| `VICTORY_MOUSE_QUEUE_MS` | 67 | How long the view may turn on after a movement faster than the stick goes |
| `VICTORY_MOUSE_RAW` | auto | `1`: raw input only, `0`: the cursor put back to the middle, else found out: raw input whenever it comes, the cursor when it moved for 0.3 s and no raw event came |
The title turns the view at a speed, not by an angle, and no faster than its own stick
speed. Of movement faster than that, 67 ms are turned late and the rest is dropped, so that
the view stops with the hand. Raise the title's own camera speed and lower the sensitivity
here if fast turns come out too short; raise the sensitivity if every turn does.
+128 -9
View File
@@ -32,6 +32,7 @@ BASE = HERE.parent # the folder with run-7900.sh, game/, the Proton copy
STORE = (Path(os.environ.get("VALHALLA_HOME") or Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share") / "valhalla")
if (BASE.parent / ".victory-root").exists() else BASE)
SETTINGS_FILE = STORE / "victory-data" / "launcher.json"
KEYS_FILE = STORE / "keys.txt" # the user's own keys, if there are any
LOG_FILE = BASE / "valhalla.log"
# The program: bin/ in a package, else this tree's build.
EXE = next((p for p in (BASE / "bin" / "valhalla.exe",
@@ -56,7 +57,7 @@ def shaders_prepared() -> bool:
def key_art(game_dir: Path) -> list[Path]:
return [game_dir / "xbs_splash.png", game_dir / "xbs_logo_480.png"]
RESOLUTIONS = ["1280x720", "1600x900", "1920x1080", "2560x1440", "3840x2160"]
RESOLUTIONS = ["1280x720", "1664x936", "1920x1080", "2560x1440", "3840x2160"]
# Name, render scale (of the output) for AMD FSR.
FSR_QUALITY = [
("Native AA", 1.0),
@@ -71,6 +72,25 @@ FSR_QUALITY = [
FRAME_CAPS = [("30 fps", "33.333"), ("60 fps", "16.667"), ("120 fps", "8.333"), ("Unlimited", "0")]
# Name, VICTORY_KEY_GUIDE: the box on the screen that names the keys.
# (The layout's name: the keys mean other things on foot and in a vehicle.)
KEY_GUIDE = [("Layout name at changes", "layout"), ("Only with F1", "0"), ("Always on", "always")]
# The keys in short (docs/keyboard-mouse.md has all of them).
KEY_LIST = [
("Mouse", "Click into the game's window to hold the mouse. Esc, Alt+Tab or F2 frees it."),
("On foot", "W A S D move · Shift run · Space jump · Ctrl crouch · Q cover · R reload · "
"Tab weapon wheel (hold) · E pick up · F interact, enter · G throw · left mouse fire · "
"right mouse aim"),
("Vehicle", "W accelerate · S brake, reverse · A D steer · Space handbrake · Shift boost · Ctrl or H horn · "
"F leave"),
("Both", "C look behind · P phone, out and away · M map (wheel zooms, click marks) · Esc pause · Page Up and Down mouse sensitivity · Z radar · 1 2 3 4 or arrows D-pad · Enter accept · "
"Backspace back"),
("Layout", "F changes between on foot and vehicle. Caps Lock changes it by hand when it guessed wrong."),
("F1", "The settings menu in the game: mouse sliders and every key. F1 or Esc closes it."),
]
@dataclass
class Settings:
preset: str = "High"
@@ -91,6 +111,12 @@ class Settings:
skip_intro: bool = True
f4_capture: bool = False # F4 saves the next frame (for bug reports)
hw_log: bool = True
keyboard_mouse: bool = True # keyboard and mouse as the game's pad
mouse_sens: float = 1.0
mouse_sens_y: float = 1.0 # up and down, on top of mouse_sens
mouse_aim: float = 1.0 # while aiming, on top
mouse_invert_y: bool = False
key_guide: str = KEY_GUIDE[0][0] # the keys on the screen (KEY_GUIDE)
game_dir: str = "" # the game's folder (its own files); empty: game/ beside Valhalla
def game_path(self) -> Path:
@@ -146,6 +172,11 @@ def apply_preset(s: Settings, name: str) -> Settings:
return s
def mouse_range(v: float) -> float:
"""A mouse sensitivity within the sliders' range."""
return min(5.0, max(0.2, v))
def windows_path(p: Path) -> str:
"""The Wine drive Z: path of a Linux path."""
return "Z:" + str(p).replace("/", "\\")
@@ -166,6 +197,16 @@ def launch_env(s: Settings) -> dict[str, str]:
"VICTORY_CARD_BUFFERS_MIN_KB": "64",
"GAME_DIR": str(s.game_path()),
}
if s.keyboard_mouse:
env["VICTORY_KBM"] = "1"
env["VICTORY_KBM_FILE"] = windows_path(KEYS_FILE)
env["VICTORY_MOUSE_SENS"] = f"{mouse_range(s.mouse_sens):g}"
env["VICTORY_MOUSE_SENS_Y"] = f"{mouse_range(s.mouse_sens_y):g}"
env["VICTORY_MOUSE_AIM"] = f"{mouse_range(s.mouse_aim):g}"
env["VICTORY_MOUSE_INVERT_Y"] = "1" if s.mouse_invert_y else "0"
env["VICTORY_KEY_GUIDE"] = dict(KEY_GUIDE).get(s.key_guide, KEY_GUIDE[0][1])
else:
env["VICTORY_KBM"] = "0"
if s.console == "series-s":
env["CONSOLE"] = "series-s"
if s.upscaler == "fsr":
@@ -573,7 +614,7 @@ def run_window() -> int:
bar.addSpacing(34)
self.stack = QStackedWidget()
self.nav = QButtonGroup(self)
for i, name in enumerate(["PLAY", "GRAPHICS", "PERFORMANCE", "SYSTEM", "TOOLS"]):
for i, name in enumerate(["PLAY", "GRAPHICS", "PERFORMANCE", "SYSTEM", "TOOLS", "CONTROLS"]):
b = QPushButton(name)
b.setObjectName("nav")
b.setCheckable(True)
@@ -594,6 +635,7 @@ def run_window() -> int:
self.build_performance()
self.build_system()
self.build_tools()
self.build_controls()
self.nav.button(0).setChecked(True)
self.show_settings()
@@ -679,7 +721,7 @@ def run_window() -> int:
self.fsr_quality = QComboBox()
for name, scale in FSR_QUALITY:
self.fsr_quality.addItem(f"{name} ({scale * 100:.0f}%)", name)
rows.add("FSR quality", "The share of the output the game renders before upscaling.", self.fsr_quality)
rows.add("FSR quality", "The share of the output the game renders before upscaling. Ultra Performance gives a third at 3840x2160, 38% at 2560x1440 and 50% below that.", self.fsr_quality)
self.fsr4 = Toggle()
rows.add("FSR 4", "Machine-learning upscaling on Radeon RX 9000 cards.", self.fsr4)
self.frame_generation = Toggle()
@@ -798,17 +840,57 @@ def run_window() -> int:
v.addWidget(self.console_out, 1)
self.stack.addWidget(area)
def build_controls(self) -> None:
area, v = page("Controls", "A connected controller works as before. "
"Changes apply the next time the game starts.")
rows = group(v, "Keyboard and mouse")
self.keyboard_mouse = Toggle()
rows.add("Play with keyboard and mouse", "The game sees them as a controller.", self.keyboard_mouse)
def slider() -> tuple[QWidget, QSlider, QLabel]:
cell = QWidget()
h = QHBoxLayout(cell)
h.setContentsMargins(0, 0, 0, 0)
bar = QSlider(Qt.Horizontal)
bar.setRange(20, 500)
bar.setFixedWidth(150)
value = label("", "rowdesc")
value.setFixedWidth(34)
h.addWidget(bar)
h.addWidget(value)
return cell, bar, value
cell, self.mouse_sens, self.mouse_sens_label = slider()
rows.add("Mouse sensitivity", "How far the view turns. Lower for mice with a high DPI.", cell)
cell, self.mouse_sens_y, self.mouse_sens_y_label = slider()
rows.add("Vertical sensitivity", "Up and down, on top of the mouse sensitivity.", cell)
cell, self.mouse_aim, self.mouse_aim_label = slider()
rows.add("Aim sensitivity", "On top while the aim button (right mouse) is held.", cell)
self.mouse_invert_y = Toggle()
rows.add("Invert up and down", "Mouse up looks down.", self.mouse_invert_y)
rows = group(v, "Keys")
self.key_guide = QComboBox()
self.key_guide.addItems([name for name, _ in KEY_GUIDE])
rows.add("Key guide", "Names the keys in the lower right corner. F1 shows or hides it. The layout (on foot, vehicle) is named for 4 s when it changes.", self.key_guide)
for what, keys in KEY_LIST:
rows.add(what, keys, QWidget())
rows.add("Your own keys", f"Change keys in {KEYS_FILE} (how: docs/keyboard-mouse.md).", QWidget())
v.addStretch(1)
self.stack.addWidget(area)
# Settings <-> widgets.
def toggles(self) -> list:
return [self.fsr4, self.frame_generation, self.reflections_hold, self.ray_tracing, self.safe_mode,
self.low_memory, self.stats_overlay, self.skip_intro, self.f4_capture, self.hw_log]
self.low_memory, self.stats_overlay, self.skip_intro, self.f4_capture, self.hw_log,
self.keyboard_mouse, self.mouse_invert_y]
def connect_changes(self) -> None:
for w in (self.resolution, self.frame_cap, self.upscaler, self.fsr_quality):
for w in (self.resolution, self.frame_cap, self.upscaler, self.fsr_quality, self.key_guide):
w.currentIndexChanged.connect(self.changed)
for w in self.toggles() + [self.series_x, self.series_s]:
w.toggled.connect(self.changed)
self.ambient.valueChanged.connect(self.changed)
for w in (self.ambient, self.mouse_sens, self.mouse_sens_y, self.mouse_aim):
w.valueChanged.connect(self.changed)
self.pipeline_wait.valueChanged.connect(self.changed)
def show_settings(self) -> None:
@@ -831,6 +913,12 @@ def run_window() -> int:
self.skip_intro.setChecked(s.skip_intro)
self.f4_capture.setChecked(s.f4_capture)
self.hw_log.setChecked(s.hw_log)
self.keyboard_mouse.setChecked(s.keyboard_mouse)
self.mouse_sens.setValue(int(round(s.mouse_sens * 100)))
self.mouse_sens_y.setValue(int(round(s.mouse_sens_y * 100)))
self.mouse_aim.setValue(int(round(s.mouse_aim * 100)))
self.mouse_invert_y.setChecked(s.mouse_invert_y)
self.key_guide.setCurrentIndex(max(0, self.key_guide.findText(s.key_guide)))
for b in self.preset_buttons.buttons():
b.setChecked(b.property("preset") == s.preset)
self.refresh()
@@ -855,6 +943,12 @@ def run_window() -> int:
s.skip_intro = self.skip_intro.isChecked()
s.f4_capture = self.f4_capture.isChecked()
s.hw_log = self.hw_log.isChecked()
s.keyboard_mouse = self.keyboard_mouse.isChecked()
s.mouse_sens = self.mouse_sens.value() / 100
s.mouse_sens_y = self.mouse_sens_y.value() / 100
s.mouse_aim = self.mouse_aim.value() / 100
s.mouse_invert_y = self.mouse_invert_y.isChecked()
s.key_guide = self.key_guide.currentText()
def refresh(self) -> None:
s = self.s
@@ -862,6 +956,11 @@ def run_window() -> int:
for w in (self.fsr_quality, self.fsr4, self.frame_generation):
w.setEnabled(fsr)
self.ambient_label.setText(f"{self.ambient.value() / 100:.2f}")
for bar, value in ((self.mouse_sens, self.mouse_sens_label), (self.mouse_sens_y, self.mouse_sens_y_label),
(self.mouse_aim, self.mouse_aim_label)):
value.setText(f"{bar.value() / 100:.2f}")
for w in (self.mouse_sens, self.mouse_sens_y, self.mouse_aim, self.mouse_invert_y, self.key_guide):
w.setEnabled(self.keyboard_mouse.isChecked())
up = f"FSR {'4' if s.fsr4 else '3.1'} {s.fsr_quality}" if s.upscaler == "fsr" else "GAME UPSCALER"
chips = [s.resolution, up.upper(),
"FRAME GENERATION" if s.upscaler == "fsr" and s.frame_generation else "NO FRAME GENERATION",
@@ -1048,16 +1147,36 @@ def selftest() -> int:
assert "VICTORY_FSR_VERSION" not in launch_env(Settings(upscaler="game"))
assert s70["VICTORY_FRAME_INTERVAL_MS"] == "16.667" and "CONSOLE" not in s70 and "VICTORY_WINDOW_PLAIN" not in s70, s70
assert s70["RT"] == "1", s70
# Keyboard and mouse: on unless turned off, kept by presets, no preset's business.
keys = launch_env(Settings(mouse_sens=1.5, mouse_sens_y=0.8, mouse_aim=0.5, mouse_invert_y=True))
assert Settings().keyboard_mouse and keys["VICTORY_KBM"] == "1" and keys["VICTORY_MOUSE_SENS"] == "1.5", keys
assert keys["VICTORY_MOUSE_SENS_Y"] == "0.8" and keys["VICTORY_MOUSE_AIM"] == "0.5", keys
assert keys["VICTORY_MOUSE_INVERT_Y"] == "1" and keys["VICTORY_KBM_FILE"].endswith("\\keys.txt"), keys
assert launch_env(Settings(mouse_sens=99))["VICTORY_MOUSE_SENS"] == "5"
off = launch_env(Settings(keyboard_mouse=False))
assert off["VICTORY_KBM"] == "0" and not any(k.startswith("VICTORY_MOUSE") for k in off), off
# The key guide: the layout's name at its changes and F1 unless asked for; nothing without the keys.
assert keys["VICTORY_KEY_GUIDE"] == "layout" and "VICTORY_KEY_GUIDE" not in off
assert launch_env(Settings(key_guide="Always on"))["VICTORY_KEY_GUIDE"] == "always"
assert launch_env(Settings(key_guide="Only with F1"))["VICTORY_KEY_GUIDE"] == "0"
# (Settings saved with a name that is no more.)
assert launch_env(Settings(key_guide="F1 only"))["VICTORY_KEY_GUIDE"] == "layout"
for name in PRESETS:
assert apply_preset(Settings(key_guide="Always on"), name).key_guide == "Always on"
assert apply_preset(Settings(mouse_sens=2.0, keyboard_mouse=False), name).mouse_sens == 2.0
assert not apply_preset(Settings(keyboard_mouse=False), name).keyboard_mouse
# Every variable any setting sets is read: by the runtime's sources, the
# launch scripts, or Proton (the FSR 4 upgrade).
every = Settings(upscaler="fsr", fsr4=True, frame_generation=True, console="series-s", ray_tracing=True,
safe_mode=True, low_memory=True, f4_capture=False, stats_overlay=False, skip_intro=False)
names = set(launch_env(every)) | {"NO_HW_LOG", "VICTORY_CAPTURE", "VICTORY_DUMP_TARGETS"}
sources = [BASE / "run-7900.sh", BASE / "run-victory.sh"] + list((BASE / "victory7900" / "crates").rglob("*.rs")) \
+ list((BASE / "victory7900" / "apps").rglob("*.rs"))
# (VALHALLA_SOURCE: another checkout, for a branch that is not merged yet.)
tree = Path(os.environ.get("VALHALLA_SOURCE") or BASE / "victory7900")
sources = [BASE / "run-7900.sh", BASE / "run-victory.sh"] + list((tree / "crates").rglob("*.rs")) \
+ list((tree / "apps").rglob("*.rs"))
text = "\n".join(p.read_text(errors="replace") for p in sources if p.exists())
proton_read = {"FSR4_UPGRADE", "PROTON_FSR4_UPGRADE"}
if (BASE / "victory7900" / "crates").exists(): # (a package has no sources)
if (tree / "crates").exists(): # (a package has no sources)
unread = sorted(n for n in names - proton_read if n not in text)
assert not unread, f"set by the launcher, read nowhere: {unread}"
assert "VICTORY_FRAME_INTERVAL_MS" in launch_env(Settings(frame_cap="Unlimited")) and \