diff --git a/crates/metal2vulkan-runtime/src/pass_log.rs b/crates/metal2vulkan-runtime/src/pass_log.rs index dc9c63c74..ee81a044b 100644 --- a/crates/metal2vulkan-runtime/src/pass_log.rs +++ b/crates/metal2vulkan-runtime/src/pass_log.rs @@ -1,22 +1,24 @@ //! The pass log: a default-off diagnostic, `METAL2VULKAN_LOG_PASSES` (`metal2vulkan::env_vars`), //! that names each render pass that renders into a texture it watches, binds one to its fragment -//! stage or makes one resident: what such a pass does with its attachments, and what its draws -//! read. +//! stage or makes one resident, or draws with a pipeline state it watches: what such a pass does +//! with its attachments, and what its draws read. //! //! - **What it watches.** The switch's value: a comma-separated list of `FORMAT:WIDTHxHEIGHT`, -//! for example `RGBA16Float:128x128,BGRA8Unorm:224x128`. `FORMAT` is a pixel format's name as -//! the notices print it (`RGBA16Float`, `BGRA8UnormSRGB`) or as Metal names it -//! (`MTLPixelFormatRGBA16Float`, `BGRA8Unorm_sRGB`); `*` stands for any format, and a size of -//! `*` for any size. Unset, empty or `0`, the log is off; a value it cannot read turns it off -//! and says why once, on stderr. +//! for example `RGBA16Float:128x128,BGRA8Unorm:224x128`, and of `state:HASH`. `FORMAT` is a +//! pixel format's name as the notices print it (`RGBA16Float`, `BGRA8UnormSRGB`) or as Metal +//! names it (`MTLPixelFormatRGBA16Float`, `BGRA8Unorm_sRGB`); `*` stands for any format, and a +//! size of `*` for any size. `HASH` is a render pipeline state's label hash, 16 hex digits, as +//! the encoder times name its rows by (`encoder_trail::label_hash`, `encoder_times.rs`): a pass +//! one of whose draws drew with that state. Unset, empty or `0`, the log is off; a value it +//! cannot read turns it off and says why once, on stderr. //! - **What it prints.** At the end of a render encoder that names a watched texture, one line //! through the device's message sink at `Info` severity (id name `metal2vulkan-passes`), else //! on stderr: the render area, its Vulkan render pass instances (more than one where the pass //! split) and its draw calls; each color attachment (index, format, size, object ID and label, //! whether its texture took its storage form, level and slice, load and store actions as the //! pass ends, and the stand-in it renders through, with its cause); the depth/stencil -//! attachment with each aspect's actions; the pipeline states its draws drew with (label and -//! functions); the textures bound to the fragment stage at a draw (index, format, size, object +//! attachment with each aspect's actions; the pipeline states its draws drew with (label, +//! functions and label hash); the textures bound to the fragment stage at a draw (index, format, size, object //! ID and label); the count of textures it made resident and the watched ones among them, with //! their stages; and what it watched. A line lists at most [`KEPT`] states and fragment //! textures, each once. @@ -24,11 +26,13 @@ //! counts of draw calls and resident textures, prints none, so a pass a frame repeats prints //! once; and the process prints at most [`LINES`] lines, the last saying so. //! - **Off, it costs nothing.** The switch is read once; an encoder notes nothing and no line is -//! formatted. On, every render encoder notes its draws' states and fragment textures, and one -//! that names a watched texture formats its line. +//! formatted. On, every render encoder notes its draws' states and fragment textures, works out +//! its states' label hashes where the log watches a state, and one that names a watched texture +//! or state formats its line. use super::device::lock; use super::driver_facts::inform_through; +use super::encoder_trail::label_hash; use super::render_pass::{AspectTarget, PassLayout}; use super::residency::Residency; use super::{Device, RenderPipelineState, Texture}; @@ -46,19 +50,46 @@ pub(crate) const LINES: usize = 256; /// The most pipeline states, and the most fragment textures, a pass's line lists. const KEPT: usize = 32; -/// A texture the log watches: of `format` and `size`, `None` for any. +/// What the log watches (the module docs). #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Watched { - pub(crate) format: Option, - pub(crate) size: Option<[u64; 2]>, +pub(crate) enum Watched { + /// A texture of `format` and `size`, `None` for any. + Texture { + format: Option, + size: Option<[u64; 2]>, + }, + /// A render pipeline state of this label hash, its 16 hex digits read as a number. + State(u64), } impl Watched { /// Whether it watches a texture of `format`, `width` by `height`. pub(crate) fn watches(&self, format: PixelFormat, [width, height]: [u64; 2]) -> bool { - self.format.is_none_or(|watched| watched == format) - && self.size.is_none_or(|size| size == [width, height]) + match *self { + Watched::Texture { + format: watched, + size, + } => { + watched.is_none_or(|watched| watched == format) + && size.is_none_or(|size| size == [width, height]) + } + Watched::State(_) => false, + } } + + /// Whether it watches the pipeline state of label hash `hash` (`encoder_trail::label_hash`). + pub(crate) fn watches_state(&self, hash: &str) -> bool { + match *self { + Watched::State(watched) => state_hash(hash) == Some(watched), + Watched::Texture { .. } => false, + } + } +} + +/// A label hash's 16 hex digits as a number, `None` where it is not one. +fn state_hash(hash: &str) -> Option { + let digits = hash.len() == 16 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()); + digits.then(|| u64::from_str_radix(hash, 16).ok()).flatten() } /// The textures `value` watches (the module docs), or why it names none. @@ -66,11 +97,16 @@ pub(crate) fn parse(value: &str) -> Result, String> { value.split(',').map(str::trim).map(entry).collect() } -/// The texture one entry of the switch's list watches. +/// What one entry of the switch's list watches. fn entry(entry: &str) -> Result { let (format, size) = entry .split_once(':') - .ok_or_else(|| format!("`{entry}` is not FORMAT:WIDTHxHEIGHT"))?; + .ok_or_else(|| format!("`{entry}` is not FORMAT:WIDTHxHEIGHT or state:HASH"))?; + if format == "state" { + let hash = state_hash(size) + .ok_or_else(|| format!("`{entry}`: `{size}` is not a label hash (16 hex digits)"))?; + return Ok(Watched::State(hash)); + } let format = match format { "*" => None, name => { @@ -87,7 +123,7 @@ fn entry(entry: &str) -> Result { Some(parsed.ok_or_else(|| format!("`{entry}`: `{size}` is not WIDTHxHEIGHT"))?) } }; - Ok(Watched { format, size }) + Ok(Watched::Texture { format, size }) } /// The pixel format named `name`: as the notices print it (its `Debug` name), or as Metal names @@ -132,6 +168,18 @@ fn watches(texture: &Texture) -> bool { (watched().iter()).any(|watched| watched.watches(texture.pixel_format(), size)) } +/// Whether the log watches a pipeline state. +fn watches_states() -> bool { + (watched().iter()).any(|watched| matches!(watched, Watched::State(_))) +} + +/// `state`'s label hash, as the encoder times name it (`encoder_trail::label_hash`). +fn state_label_hash(state: &RenderPipelineState) -> String { + let names = state.function_names(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + label_hash(state.label(), &names) +} + /// What a render encoder's draws named, for its line at its end, while the log is on. #[derive(Default)] pub(crate) struct PassNotes { @@ -185,12 +233,13 @@ fn named(texture: &Texture) -> String { ) } -/// A pipeline state as a line names it: its label and its functions' names. -fn state_named(state: &RenderPipelineState) -> String { +/// A pipeline state of label hash `hash` as a line names it: its label, its functions' names and +/// the hash. +fn state_named(state: &RenderPipelineState, hash: &str) -> String { let label = state .label() .map_or_else(String::new, |label| format!("{label:?} ")); - format!("{label}({})", state.function_names().join(", ")) + format!("{label}({}) [{hash}]", state.function_names().join(", ")) } /// At the end of a render encoder whose draws `notes` noted, rendering into `layout` in @@ -265,10 +314,26 @@ pub(crate) fn ended( if !resident_watched.is_empty() { seen.push(format!("{} resident texture(s)", resident_watched.len())); } + // The states' label hashes: worked out where the log watches a state, else only for a line. + let hashes = + |notes: &PassNotes| -> Vec { notes.states.iter().map(state_label_hash).collect() }; + let mut hashed = None; + if watches_states() { + let hashes = hashed.insert(hashes(notes)); + for hash in hashes.iter() { + if (watched().iter()).any(|watched| watched.watches_state(hash)) { + seen.push(format!("state {hash}")); + } + } + } if seen.is_empty() { return; } - let states: Vec = notes.states.iter().map(state_named).collect(); + let hashes = hashed.unwrap_or_else(|| hashes(notes)); + let states: Vec = (notes.states.iter()) + .zip(&hashes) + .map(|(state, hash)| state_named(state, hash)) + .collect(); let [width, height] = layout.extent; // The pass as a line names it but for its counts, which a frame's repeat of it may change: // what tells it from the lines printed before. diff --git a/crates/metal2vulkan-runtime/src/render/draw_again.rs b/crates/metal2vulkan-runtime/src/render/draw_again.rs index 67eba66c4..808726521 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again.rs @@ -1314,6 +1314,9 @@ impl RenderLowering { let (rasterizes, depth_writes) = (kept.rasterizes, kept.depth_writes); self.keep_draw(again, (call, assembly, *draw), buffers.index.as_ref()); self.draw_calls += 1; + if let Some(times) = self.core.times() { + times.worked(); + } self.last_draw_empty = false; self.command_encoded(reads); self.called = true; diff --git a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs index 7fb909345..0d336b026 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs @@ -1856,6 +1856,9 @@ impl RenderLowering { kept.under = under; } self.draw_calls += 1; + if let Some(times) = self.core.times() { + times.worked(); + } self.last_draw_empty = false; self.command_encoded(reads); self.called = true; diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_times.rs b/crates/metal2vulkan-runtime/src/tests/encoder_times.rs index 53d65fa44..5fc3d8642 100644 --- a/crates/metal2vulkan-runtime/src/tests/encoder_times.rs +++ b/crates/metal2vulkan-runtime/src/tests/encoder_times.rs @@ -7,6 +7,11 @@ //! its pipelines made: its line names the three encoders in order, each under its state's label //! hash, the long one of more GPU time than either short one, and the summary the device's //! teardown prints ranks the long one's row first of the three. +//! - **Draws again**: a render encoder of [`DRAWS`] draws of one rectangle, warmed, the draws after +//! the first drawn again as before (`render/draw_again.rs`, `WorkCounts::draws_as_before`) or, +//! other bytes bound before each, rebound (`render/draw_again/rebound.rs`, +//! `WorkCounts::draws_rebound`): its command buffer's line names its every draw, the draws +//! again among them. //! - **Off**: a command buffer of a compute encoder, a render pass of one draw recorded inline and //! a blit encoder, its pipelines made by one run before, makes no timestamp query pool and //! begins as many `VkCommandBuffer`s as the same one did before; switched on, the same one @@ -17,12 +22,14 @@ //! of device the cfg selects. use super::blit_holds::{options, Scratch, WAIT}; -use super::encoder_holds::{library, pass, render_state}; +use super::draw_again::{adding_state, rectangle, run as run_pass, set_rectangle, warm, DRAWS}; +use super::encoder_holds::{bytes_of, library, pass, render_state}; +use super::plan_room::device_with_room; use crate::encoder_times::ID_NAME; use crate::encoder_trail::label_hash; use crate::{ Buffer, CommandBuffer, CommandBufferStatus, ComputePipelineState, Device, MessageSink, - PipelineOptions, ResourceOptions, Size, TextureDescriptor, + PipelineOptions, RenderCommandEncoder, ResourceOptions, Size, TextureDescriptor, WorkCounts, }; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use std::sync::{Arc, Mutex}; @@ -208,6 +215,74 @@ fn a_command_buffer_s_encoders_are_timed_apart_under_their_states_label_hashes() ); } +/// A render encoder's draws again count among its draws: [`DRAWS`] draws of one rectangle, each +/// after the first drawn again as before, or rebound where `rebound` binds other bytes before +/// each, name `DRAWS` draws in their command buffer's line (the module docs). +#[test] +fn an_encoder_s_draws_again_count_among_its_draws() { + let scratch = Scratch::new("encoder-times-again"); + let heard = Arc::new(Mutex::new(Vec::new())); + let hearing = Arc::clone(&heard); + let mut options = options(&scratch.0); + options.messages = Some(MessageSink::new(move |message| { + if message.id_name == ID_NAME { + hearing.lock().unwrap().push(message.text.clone()); + } + })); + let device = device_with_room(&options).unwrap(); + let name = device.name().to_owned(); + let state = adding_state(&device); + let names = state.function_names(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let hash = label_hash(state.label(), &names); + let rectangles = |encoder: &mut RenderCommandEncoder, rebound: bool| { + set_rectangle(encoder, &state); + for at in 0..DRAWS { + if rebound && at > 0 { + let color = bytes_of(&[(at + 1) as f32 / 64.0; 4], f32::to_le_bytes); + encoder.set_fragment_bytes(&color, 0).unwrap(); + } + rectangle(encoder); + } + }; + for rebound in [false, true] { + warm(&device, |encoder| rectangles(encoder, rebound)); + } + (device.shared().timing.encoders()).time_encoders(Some(Duration::ZERO)); + let again: [(&str, fn(&WorkCounts) -> u64); 2] = [ + ("drawn again as before", |counts| counts.draws_as_before), + ("rebound", |counts| counts.draws_rebound), + ]; + for (rebound, (how, count)) in [false, true].into_iter().zip(again) { + heard.lock().unwrap().clear(); + let ran = run_pass(&device, |encoder| rectangles(encoder, rebound)); + // The draws again ran: without them, every draw takes every step and counts there. + assert!( + ran.counted(count) > 0, + "{name}: no draw {how}: {}", + ran.moved() + ); + let render = format!("Render [{hash}] "); + let deadline = Instant::now() + WAIT; + let line = loop { + let found = (heard.lock().unwrap().iter()) + .find(|line| line.contains(&render)) + .cloned(); + match found { + Some(line) => break line, + None if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)), + None => panic!("{name}: no line names the render encoder of {hash}"), + } + }; + println!("ENCODER-TIMES {name} ({how}): {line}"); + assert!( + line.contains(&format!("{render}{DRAWS} dispatch(es)/draw(s)")), + "{name}: the {} draw(s) {how} are not all among the encoder's {DRAWS}: {line}", + ran.counted(count), + ); + } +} + /// The `VkCommandBuffer`s encoders began, the pools' slots, as a command buffer of `device` of a /// compute encoder, a render pass of one draw and a blit encoder ran. fn mixed(device: &Device) -> (u64, u64, usize) { diff --git a/crates/metal2vulkan-runtime/src/tests/pass_log.rs b/crates/metal2vulkan-runtime/src/tests/pass_log.rs index 504746cc8..2d9836ac9 100644 --- a/crates/metal2vulkan-runtime/src/tests/pass_log.rs +++ b/crates/metal2vulkan-runtime/src/tests/pass_log.rs @@ -1,5 +1,6 @@ //! The pass log's filter and its volume (`pass_log.rs`). +use crate::encoder_trail::label_hash; use crate::pass_log::{fresh_in, parse, Watched, LINES}; use metal2vulkan::metal::PixelFormat; use std::collections::BTreeSet; @@ -9,7 +10,7 @@ use std::sync::Mutex; /// as Metal names it, `*` for any; spaces around an entry are left out. #[test] fn the_filter_reads_formats_and_sizes() { - let watched = |format, size| Watched { format, size }; + let watched = |format, size| Watched::Texture { format, size }; let rgba16f = Some(PixelFormat::RGBA16Float); assert_eq!( parse("RGBA16Float:128x128"), @@ -53,7 +54,10 @@ fn the_filter_reads_formats_and_sizes() { #[test] fn the_filter_refuses_what_it_cannot_read() { for (value, why) in [ - ("RGBA16Float", "`RGBA16Float` is not FORMAT:WIDTHxHEIGHT"), + ( + "RGBA16Float", + "`RGBA16Float` is not FORMAT:WIDTHxHEIGHT or state:HASH", + ), ( "RGBA16:128x128", "`RGBA16:128x128`: no pixel format `RGBA16`", @@ -70,7 +74,22 @@ fn the_filter_refuses_what_it_cannot_read() { "RGBA16Float:128x", "`RGBA16Float:128x`: `128x` is not WIDTHxHEIGHT", ), - ("RGBA16Float:128x128,", "`` is not FORMAT:WIDTHxHEIGHT"), + ( + "RGBA16Float:128x128,", + "`` is not FORMAT:WIDTHxHEIGHT or state:HASH", + ), + ( + "state:3c1ab914c5068a5", + "`state:3c1ab914c5068a5`: `3c1ab914c5068a5` is not a label hash (16 hex digits)", + ), + ( + "state:3c1ab914c5068a5g", + "`state:3c1ab914c5068a5g`: `3c1ab914c5068a5g` is not a label hash (16 hex digits)", + ), + ( + "state:+c1ab914c5068a5f", + "`state:+c1ab914c5068a5f`: `+c1ab914c5068a5f` is not a label hash (16 hex digits)", + ), ] { assert_eq!(parse(value), Err(why.to_owned()), "{value}"); } @@ -98,6 +117,32 @@ fn an_entry_watches_its_format_and_size() { assert!(!any_size.watches(PixelFormat::RGBA8Unorm, [1, 4096])); } +/// A `state:HASH` entry watches the render pipeline state of that label hash, as the encoder times +/// name it, beside texture entries: none of the textures, and a texture entry no state. +#[test] +fn a_state_entry_watches_the_state_of_its_label_hash() { + let hash = label_hash(Some("a state"), &["vertex_main", "fragment_main"]); + let other = label_hash(Some("another state"), &["vertex_main", "fragment_main"]); + let unlabeled = label_hash(None, &["vertex_main", "fragment_main"]); + let entries = parse(&format!("state:{hash}, BGRA8Unorm:*, state:{unlabeled}")).unwrap(); + assert_eq!(entries.len(), 3); + let watching = |hash: &str| entries.iter().any(|entry| entry.watches_state(hash)); + assert!(watching(&hash)); + assert!(watching(&unlabeled)); + assert!(!watching(&other)); + assert_eq!( + entries[0], + Watched::State(u64::from_str_radix(&hash, 16).unwrap()) + ); + // Upper-case digits read the same hash. + let upper = parse(&format!("state:{}", hash.to_uppercase())).unwrap(); + assert!(upper[0].watches_state(&hash)); + // A state entry watches no texture, a texture entry no state. + assert!(!entries[0].watches(PixelFormat::BGRA8Unorm, [128, 128])); + assert!(entries[1].watches(PixelFormat::BGRA8Unorm, [128, 128])); + assert!(!entries[1].watches_state(&hash)); +} + /// A pass the same as one printed before prints no line again, whatever its counts, and no more /// than [`LINES`] lines are printed, the last saying so. #[test] diff --git a/crates/metal2vulkan/src/env_vars.rs b/crates/metal2vulkan/src/env_vars.rs index 2b2632840..b0ad1c448 100644 --- a/crates/metal2vulkan/src/env_vars.rs +++ b/crates/metal2vulkan/src/env_vars.rs @@ -130,15 +130,18 @@ pub const REGISTRY: &[EnvVar] = &[ EnvVar { name: "METAL2VULKAN_LOG_PASSES", default: "unset (off)", - effect: "metal2vulkan-runtime's diagnostics: the textures to watch, a comma-separated \ - list of FORMAT:WIDTHxHEIGHT (FORMAT as the notices print it or as Metal names \ - it; `*` for any format or any size), for example RGBA16Float:128x128; at the \ - end of each render pass that renders into a watched texture, binds one to its \ - fragment stage or makes one resident, one line through the device's message \ - sink or on stderr: the pass's attachments (format, size, level, slice, object \ - ID and label, load and store actions, stand-in, storage form), its Vulkan \ - render pass instances and draws, its draws' pipeline states and the textures \ - bound to their fragment stage, and what it watched; a pass the same as one \ + effect: "metal2vulkan-runtime's diagnostics: the textures and pipeline states to watch, \ + a comma-separated list of FORMAT:WIDTHxHEIGHT (FORMAT as the notices print it \ + or as Metal names it; `*` for any format or any size), for example \ + RGBA16Float:128x128, and of state:HASH (a render pipeline state's label hash, \ + the 16 hex digits METAL2VULKAN_ENCODER_TIMES names its rows by); at the end of \ + each render pass that renders into a watched texture, binds one to its \ + fragment stage, makes one resident or draws with a watched state, one line \ + through the device's message sink or on stderr: the pass's attachments \ + (format, size, level, slice, object ID and label, load and store actions, \ + stand-in, storage form), its Vulkan render pass instances and draws, its draws' \ + pipeline states (with their label hashes) and the textures bound to their \ + fragment stage, and what it watched; a pass the same as one \ printed before but for its counts prints no line again, and at most 256 lines \ are printed; empty or 0 is off", }, diff --git a/docs/API.md b/docs/API.md index 6ed5a587c..843c34e97 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2226,12 +2226,14 @@ shadow, whose own line, under the call `make_twin_texture`, names the twin's byt full; or the making's error). With `METAL2VULKAN_LOG_PASSES` set to a comma-separated list of `FORMAT:WIDTHxHEIGHT` (the format as the notices print it or as Metal names it, `*` for any format or any size, for example -`RGBA16Float:128x128`), a device logs a line at the end of each render pass that renders into a -texture of the list, binds one to its fragment stage or makes one resident (id name +`RGBA16Float:128x128`) and of `state:HASH` (a render pipeline state's label hash, the 16 hex +digits `METAL2VULKAN_ENCODER_TIMES` names its rows by), a device logs a line at the end of each +render pass that renders into a texture of the list, binds one to its fragment stage, makes one +resident or draws with a state of the list (id name `metal2vulkan-passes`, `Info` severity): its render area, Vulkan render pass instances and draw calls; each attachment's format, size, object ID, label, level, slice, load and store actions, whether its texture took its storage form, and the stand-in it renders through with its cause; -the pipeline states its draws drew with (label and functions); the textures bound to the fragment +the pipeline states its draws drew with (label, functions and label hash); the textures bound to the fragment stage at a draw; the watched textures among those it made resident, with their stages; and what it watched. A pass the same as one a line was printed of before, but for its counts of draw calls and resident textures, prints no line again, and a process prints at most 256. Empty or `0` is