diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 129b7cc68..5911b119d 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2662,7 +2662,6 @@ impl CommandBuffer { owner: self.0.address(), part: state.recorded.len(), bound_heaps: state.heaps.bound(), - logs_kept: state.ended.iter().any(|record| record.replay.is_some()), } } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 8775e7e4e..dc171a938 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -43,6 +43,10 @@ //! its host step needs. Work a host step recorded again since (with the barriers between its //! commands, `gpu_execute::Rerecord`, or as a route outgrew it, `DeferredPass::outgrown`) //! keeps that step's recording. +//! - **Faces as first met.** Each encoding again (and each recording again on the GPU alone) +//! meets the faces of the command buffer's turns as its first encoding met them: a texture a +//! later pass of the command buffer turned presents the face from before the turn, and the +//! turning pass takes its turn again (`texture/faces.rs`, **Encoded again**). //! - **Copies taken at use.** A tiled texture's copy of its bytes taken at use (`shadow.rs`) is //! taken by the first use encoded after its mark was set, which clears it. An encoder encoded //! again takes it where the use in its place in its first encoding took it, whose recording is @@ -72,6 +76,7 @@ use crate::pipeline::budget::Urgency; use crate::replay::Replay; use crate::residency::Residency; use crate::resource::ResourceKey; +use crate::texture::faces::with_faces_as_of; use crate::used_resources::EncoderKind; use std::collections::BTreeSet; use std::sync::atomic::Ordering; @@ -151,7 +156,7 @@ impl CommandBufferShared { // (`Predication::replaying`). // The merges its first encoding left to runs of passes (`pass_runs.rs`): encoded again, // it leaves them, and keeps after itself what a later pass of a run went on over. - let (residency, runs) = { + let (residency, runs, parts) = { let mut state = lock(&self.state); state.replaying_predication = match state.predicated { true => state.predication.replaying(at), @@ -169,9 +174,18 @@ impl CommandBufferShared { // Its first encoding's takes of copies taken at use, taken again where they were: // that encoding's recording is never submitted (`shadow::Takes`). state.replaying_takes = state.ended[at].takes.clone(); - (state.residency_before(at, replay.kind()), runs) + // Its parts, by which the encoding again meets the faces of the command buffer's + // turns as its first encoding met them (`texture/faces.rs`, **Encoded again**). + let mut parts = (state.recorded.iter().enumerate()) + .filter(|(_, part)| part.encoder == at) + .map(|(index, _)| index); + let first = parts.next().unwrap_or(state.recorded.len()); + let parts = first..parts.last().map_or(first + 1, |last| last + 1); + (state.residency_before(at, replay.kind()), runs, parts) }; - let run = replay.run(&handle, residency); + let run = with_faces_as_of(device, (self.address(), parts), || { + replay.run(&handle, residency) + }); { let mut state = lock(&self.state); state.replaying_keeps.clear(); @@ -295,7 +309,10 @@ impl CommandBufferShared { for (place, work) in alone { // Its notices were announced as it committed (`replay::is_replaying`), and its // commands take what they use without holding it. - let again = crate::replay::replaying(|| work.record_on_gpu(&handle)); + let (part, _) = place; + let again = with_faces_as_of(device, (self.address(), part..part + 1), || { + crate::replay::replaying(|| work.record_on_gpu(&handle)) + }); let counts = &device.shared().counts; let Ok(Some((recorded, inputs))) = again else { counts.reencode_refused(); diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 5e5bc2a43..3e9fd813b 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -2231,8 +2231,14 @@ impl CommandBuffer { // A color's texture with faces that the pass renders whole without loading it turns to // its other face here, before anything of the pass names its image; the kept draw the // last render encoder carried bound the face presented before (`render/face_swap.rs`). - let passes = again.is_some() || groups > 1 || rate_map.is_some() || log.is_some(); - let turns = face_swap::Turns::open(&mut core, &layout, passes.then_some(Unturned::Pass)); + // A pass encoded again takes again the turns its first encoding took. + let passes = groups > 1 || rate_map.is_some(); + let turns = face_swap::Turns::open( + &mut core, + &layout, + passes.then_some(Unturned::Pass), + again.is_some(), + ); let carried = match carried { Some(carried) if turns.turned() => { carried.let_go(device); @@ -9529,6 +9535,9 @@ impl RenderLowering { binding::command_uses_into(call, parts, sources, &mut live.uses)?; } self.count_narrowed(narrowed_slots, written); + // The shadowed textures the draw binds, at the first draw of each, its shadow made now + // (`shadow_log.rs`). + crate::shadow_log::drew(&device, variant.pipeline(), &stages); let resident_made = live.uses.made() as u64; let counts = self.core.counts(); if resident_made > 0 { diff --git a/crates/metal2vulkan-runtime/src/render/face_swap.rs b/crates/metal2vulkan-runtime/src/render/face_swap.rs index 427483a0e..cdb91c292 100644 --- a/crates/metal2vulkan-runtime/src/render/face_swap.rs +++ b/crates/metal2vulkan-runtime/src/render/face_swap.rs @@ -4,14 +4,18 @@ //! (`WorkCounts::attached_read_unswapped_*`). //! //! - **At the open** ([`Turns::open`]). A color whose texture has faces turns it where the pass -//! turns textures at all (it encodes no encoder again, draws its colors in one group, over no -//! rasterization-rate map, logs none of its calls, and no ended encoder of its command buffer -//! keeps a log a rebind encodes again: each would record commands again that name the face -//! presented on one side of the turn on the other), and the color loads `Clear` or `DontCare` -//! and renders the whole texture: level 0 and slice 0, one layer, the render area the texture's -//! extent, single-sampled, resolving nowhere, no other attachment of the pass the same texture, -//! and the pass failing no command buffer. The turn checks the rest -//! ([`Texture::turn_face`](crate::Texture)). A turned texture's faces' shadows are carried no +//! turns textures at all (it draws its colors in one group, over no rasterization-rate map: each +//! records the pass's calls again, a later group's or a reset map's, after the turn), and the +//! color loads `Clear` or `DontCare` and renders the whole texture: level 0 and slice 0, one +//! layer, the render area the texture's extent, single-sampled, resolving nowhere, no other +//! attachment of the pass the same texture, and the pass failing no command buffer. The turn +//! checks the rest ([`Texture::turn_face`](crate::Texture)). A pass that logs its calls for a +//! rebind (`replay.rs`) turns as any other: a rebind's encoding again of the command buffer's +//! encoders meets the faces as their first encodings met them (`texture/faces.rs`, **Encoded +//! again**). A pass encoded again so turns nothing anew; where its first encoding turned a +//! texture, it takes that turn again ([`Texture::retake_turn`](crate::Texture)), its first +//! instance reading the face from before the turn with no copy in, as the first encoding's did. +//! A turned texture's faces' shadows are carried no //! further from the command buffer's earlier encoders (`shadow::ShadowCarry`): what they held //! is no longer where the truth is. Nor is the kept draw the command buffer's last render //! encoder carried (`render/carried.rs`): it bound the face presented before. @@ -54,11 +58,14 @@ pub(crate) struct Turns { impl Turns { /// The turns of the pass of `layout` whose encoder `core` just opened (the module docs), - /// `pass` why the pass turns no texture where it turns none for its own reasons. + /// `pass` why the pass turns no texture where it turns none for its own reasons, `again` + /// where the pass is encoded again (`replay.rs`): it takes again the turns its first encoding + /// took, and no other. pub(super) fn open( core: &mut EncoderCore, layout: &PassLayout, pass: Option, + again: bool, ) -> Turns { let mut turns = Turns { pass, @@ -78,11 +85,13 @@ impl Turns { None => color_verdict(layout, index, color), }; let verdict = checked.and_then(|()| { - let point = point.get_or_insert_with(|| core.command_buffer().turn_point()); - if point.logs_kept { - return Err(Unturned::Pass); - } - let turned = texture.turn_face(point)?; + let turned = match again { + true => texture.retake_turn().ok_or(Unturned::Pass)?, + false => { + let point = point.get_or_insert_with(|| core.command_buffer().turn_point()); + texture.turn_face(point)? + } + }; if let Some(copies) = texture.face_copies() { core.carry_no_further(&copies); } diff --git a/crates/metal2vulkan-runtime/src/shadow_log.rs b/crates/metal2vulkan-runtime/src/shadow_log.rs index 42f9c9b36..be3ea73ac 100644 --- a/crates/metal2vulkan-runtime/src/shadow_log.rs +++ b/crates/metal2vulkan-runtime/src/shadow_log.rs @@ -18,14 +18,29 @@ //! plane (`texture/surface_depth.rs`); and a YCbCr texture's converted image and its render //! shadow (`texture/ycbcr_image.rs`; its write shadow is a usage shadow). A device copy is no shadow it names, nor is a heap texture's //! (its own notice names it), a view's shadow of an image or a texture buffer's staging. -//! - **Off, it costs nothing.** The switch is read once; no line is formatted. +//! - **What a shadowed texture's first draw reads.** One line per shadowed texture (one whose +//! reads go through a shadow of its truth, a usage shadow or two faces that take turns), at the +//! first draw whose pipeline uses a slot that binds it, after the draw's bindings made the +//! shadow it reads: the slot, whether the function fetches, samples or writes it, and for each +//! sampler it samples it through, a sampler state's minification, magnification and mipmap +//! filters (Metal's names) or a constexpr sampler's (Vulkan's names, as the layout bakes it). +//! A texture's line names it once in the process ([`drew`]). +//! - **Off, it costs nothing.** The switch is read once; no line is formatted, and a draw names +//! no texture. +use super::argument_table::ArgumentTable; use super::buffer_texture::Texels; +use super::device::lock; use super::driver_facts::inform_through; use super::texture_descriptor::{TextureDescriptor, TextureLayout}; -use super::Device; +use super::{Device, Texture}; use metal2vulkan::metal::{PixelFormat, TextureUsage}; -use std::sync::OnceLock; +use metal2vulkan::pipeline::{ + BindingSource, RenderPipeline, SamplerRef, SlotClass, SlotInterface, SlotRef, Stage, +}; +use metal2vulkan::vk; +use std::collections::HashSet; +use std::sync::{Mutex, OnceLock}; /// The id name of the log's messages. const ID_NAME: &str = "metal2vulkan-shadows"; @@ -112,3 +127,130 @@ pub(super) fn made_of( ); inform_through(device.shared().instance.sink(), ID_NAME, text); } + +/// Where the log is on, name each shadowed texture that `stages`' tables bind at a slot a function +/// of `compiled`, a draw's pipeline, uses, where no line named it before (the module's **What a +/// shadowed texture's first draw reads**). +pub(crate) fn drew(device: &Device, compiled: &RenderPipeline, stages: &[(Stage, &ArgumentTable)]) { + if !enabled() { + return; + } + /// The object IDs of the textures a line named. + static NAMED: OnceLock>> = OnceLock::new(); + for &(stage, table) in stages { + for (&index, texture) in &table.textures { + let Some(kind) = shadowed(texture) else { + continue; + }; + let slot = SlotRef { + stage, + class: SlotClass::Texture, + index, + }; + let Some(SlotInterface::Texture(used)) = compiled.interface.slots.get(&slot) else { + continue; + }; + let id = texture.object_id().get(); + if !lock(NAMED.get_or_init(Mutex::default)).insert(id) { + continue; + } + let access = used.access; + let uses = [ + (access.read, "fetches"), + (access.sample, "samples"), + (access.write, "writes"), + ]; + let uses: Vec<&str> = (uses.iter()) + .filter_map(|&(used, name)| used.then_some(name)) + .collect(); + let samplers = match access.sample { + true => format!("; {}", samplers_named(compiled, table, slot)), + false => String::new(), + }; + let text = format!( + "metal2vulkan: shadow: the first draw that binds the {:?} texture of {}x{} and {} \ + levels, object {id}, through {kind}, at {stage:?} texture {index}: its function \ + {} it{samples}", + texture.pixel_format(), + texture.width(), + texture.height(), + texture.mipmap_level_count(), + uses.join(" and "), + ); + inform_through(device.shared().instance.sink(), ID_NAME, text); + } + } +} + +/// What a draw's reads of `texture` go through, where they go through a shadow: its faces +/// (`texture/faces.rs`), a usage shadow (`texture/usage_shadow.rs`) or a shadow of its truth. +fn shadowed(texture: &Texture) -> Option<&'static str> { + if texture.has_faces() { + return Some("two faces that take turns"); + } + if texture.usage_shadow_copies().is_some() { + return Some("a usage shadow"); + } + texture.shadow().map(|_| "a shadow of its truth") +} + +/// The samplers the function of `compiled` samples the texture at `slot` through, each with its +/// filters: a sampler state bound in `table` by Metal's names, a constexpr sampler by the layout's +/// Vulkan sampler. +fn samplers_named(compiled: &RenderPipeline, table: &ArgumentTable, slot: SlotRef) -> String { + let stage = match slot.stage { + Stage::Vertex => vk::ShaderStage::VERTEX, + Stage::Fragment => vk::ShaderStage::FRAGMENT, + Stage::Object => vk::ShaderStage::TASK_EXT, + Stage::Mesh => vk::ShaderStage::MESH_EXT, + _ => return "its samplers unknown".to_owned(), + }; + let reads = (compiled.stages.iter()) + .find(|module| module.stage == stage) + .and_then(|module| module.level_reads.iter().find(|r| r.slot == slot.index)); + let Some(reads) = reads else { + return "its samplers unknown".to_owned(); + }; + let mut named: Vec = Vec::new(); + for sampled in &reads.sampled { + let name = match sampled.sampler { + SamplerRef::Slot(index) => match table.samplers.get(&index) { + Some((state, _)) => { + let d = state.descriptor(); + format!( + "sampler {index}: min {:?}, mag {:?}, mip {:?}", + d.min_filter, d.mag_filter, d.mip_filter + ) + } + None => format!("sampler {index}: none bound"), + }, + SamplerRef::Constexpr(words) => { + let baked = (compiled.layout.sets.iter()) + .flat_map(|set| set.bindings.iter()) + .find_map(|binding| match binding.source { + BindingSource::CombinedTextureSampler { + texture, sampler, .. + } if texture == slot && sampler.sampler == SamplerRef::Constexpr(words) => { + binding.immutable_sampler + } + _ => None, + }); + match baked { + Some(desc) => format!( + "a constexpr sampler: min {:?}, mag {:?}, mipmap mode {:?}", + desc.min_filter, desc.mag_filter, desc.mipmap_mode + ), + None => format!("a constexpr sampler {:#x}:{:#x}", words[0], words[1]), + } + } + other => format!("{other:?}"), + }; + if !named.contains(&name) { + named.push(name); + } + } + match named.is_empty() { + true => "its samplers unknown".to_owned(), + false => format!("through {}", named.join("; ")), + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/attached_read_faces.rs b/crates/metal2vulkan-runtime/src/tests/attached_read_faces.rs index 5fa132f81..9f6e76ed3 100644 --- a/crates/metal2vulkan-runtime/src/tests/attached_read_faces.rs +++ b/crates/metal2vulkan-runtime/src/tests/attached_read_faces.rs @@ -18,19 +18,28 @@ //! first; and a turn whose command buffer goes uncommitted, after which the next read of the //! texture takes that copy, and the texture turns again. //! +//! A second test runs while the device has a buffer over host pages, so every pass logs its calls +//! for a rebind (`replay.rs`): a logged pass turns as any other, and a rebind of the buffer before +//! a turning command buffer's submission encodes again its blit that read the texture before the +//! turn and its turning pass, which read the texels each read at its first encoding +//! (`texture/faces.rs`, **Encoded again**). The same lane beside an open command buffer, where no +//! pass turns and every read copies in, reads the same bytes. +//! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `tob_rect`, //! `tob_solid` and `tob_read` of the owned fixture `validation/fixtures/public/engine/tob_renders.ll`. -use super::blit_holds::{device, Scratch, WAIT}; +use super::blit_holds::{device, over_host, Host, Scratch, WAIT}; use super::encoder_holds::{bytes_of, library}; use crate::{ - BlitOption, Buffer, ClearColor, CommandBuffer, CommandQueue, Device, LoadAction, Origin, - PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, ScissorRect, Size, - StoreAction, Texture, TextureDescriptor, WorkCounts, + BlitOption, Buffer, ClearColor, CommandBuffer, CommandQueue, Device, EventRef, LoadAction, + Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, + ScissorRect, Size, StoreAction, Texture, TextureDescriptor, WorkCounts, }; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use std::sync::atomic::AtomicUsize; +use std::sync::Arc; /// The texture: `WIDTH` texels a row of 4 bytes (`BGRA8Unorm`), `HEIGHT` rows. const WIDTH: u64 = 64; @@ -167,6 +176,18 @@ impl Tools { texture: &Texture, clear: Option, draw: Draw, + ) { + self.encode_over(command_buffer, texture, (clear, draw), None); + } + + /// As [`encode`](Self::encode), its draw's corners read from `corners_in`, a buffer and the + /// offset of the corners in it, where it is given, else from bytes set at the call. + fn encode_over( + &self, + command_buffer: &CommandBuffer, + texture: &Texture, + (clear, draw): (Option, Draw), + corners_in: Option<(&Buffer, u64)>, ) { let mut pass = RenderPassDescriptor::new(); let color = &mut pass.color_attachments[0]; @@ -196,7 +217,11 @@ impl Tools { } } if !matches!(draw, Draw::Nothing) { - encoder.set_vertex_bytes(&corners, 0).unwrap(); + match corners_in { + Some((buffer, offset)) => encoder.set_vertex_buffer(Some(buffer), offset, 0), + None => encoder.set_vertex_bytes(&corners, 0), + } + .unwrap(); encoder.set_scissor_rect(RECT).unwrap(); (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); } @@ -260,6 +285,15 @@ impl Tools { } } +/// The texture the passes render and read: `Private`, its reads sampled. +fn texture(device: &Device) -> Texture { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + device.new_texture(&descriptor).unwrap() +} + /// The steps of the module docs: every read takes the texels from before its pass, the clears /// and solid draws land where the next command reads them, and a turned pass copies nothing in. #[test] @@ -267,11 +301,7 @@ fn a_texture_s_faces_take_turns_for_its_attached_reads() { let scratch = Scratch::new("attached-read-faces"); let device = device(&scratch.0); let tools = Tools::new(&device); - let mut descriptor = - TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); - descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; - descriptor.resource_options = ResourceOptions::private(); - let texture = device.new_texture(&descriptor).unwrap(); + let texture = texture(&device); let check = |want: Vec, what: &str| { let (got, moved) = tools.bytes(&texture); assert_eq!( @@ -388,3 +418,154 @@ fn a_texture_s_faces_take_turns_for_its_attached_reads() { assert_eq!(moved, turned, "the turn after the uncommitted one"); check(image(0xb0, 0x64), "the turn after the uncommitted one"); } + +/// Where the corners lie in the pages of the second test: past the bytes its blit writes. +const CORNERS_AT: u64 = 64 << 10; + +/// What a lane of the second test moved and read. +struct Logged { + /// What its logged pass moved, the one before the command buffer the rebind encodes again. + logged: Moved, + /// What that command buffer moved, from its encoding to its completion, and how many of its + /// encoders the rebind encoded again. + again: Moved, + reencoded: u64, + /// The bytes its blit read, through its encoding again: the texture before the turning pass. + blit: Vec, + /// The texture's bytes after the command buffer. + after: Vec, +} + +/// A lane of the second test, its buffer over `first` rebound over `second` (each holding the +/// corners at [`CORNERS_AT`]), beside an open command buffer where `busy`, so that no pass turns; +/// `None`, printed, where the device imports no host memory. +fn logged_lane( + device: &Device, + tools: &Tools, + [first, second]: [&Host; 2], + busy: bool, +) -> Option { + let pages = over_host(device, first, &Arc::new(AtomicUsize::new(0)))?; + let corners = [-1.0f32, -1.0, 1.0, 1.0].map(f32::to_bits); + let at = (CORNERS_AT / 4) as usize; + first.set(at, &corners); + second.set(at, &corners); + let texture = texture(device); + let open = busy.then(|| tools.queue.command_buffer().unwrap()); + // The faces, made by the first read; then a logged pass that reads 0x50 inside the rectangle. + tools.pass(&texture, Some(0x10), Draw::Nothing); + tools.pass(&texture, None, Draw::Solid(0x40)); + tools.pass(&texture, Some(0x20), Draw::Read); + tools.pass(&texture, None, Draw::Solid(0x50)); + let logged = tools.pass(&texture, Some(0x30), Draw::Read); + tools.pass(&texture, None, Draw::Solid(0x62)); + // Behind a wait: a blit of the texture into the pages, then a pass that clears it and reads + // it, its corners from the pages. The rebind before the signal encodes both again. + let before = device.work_counts(); + let gate = device.new_shared_event().unwrap(); + let command_buffer = tools.queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&gate), 1)).unwrap(); + Tools::encode_read(&command_buffer, &texture, &pages); + let corners_in = Some((&pages, CORNERS_AT)); + tools.encode_over( + &command_buffer, + &texture, + (Some(0x90), Draw::Read), + corners_in, + ); + command_buffer.commit().unwrap(); + // SAFETY: the pages outlive the buffer (declared before the device, dropped after it), and + // only the buffer's commands use them while it lives. + unsafe { pages.rebind_bytes_no_copy(second.memory(), None, None) }.unwrap(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let counts = device.work_counts(); + let refused = counts.reencodes_refused - before.reencodes_refused; + assert_eq!(refused, 0, "a rebind refused to encode an encoder again"); + let again = Moved::of(&before, &counts); + let reencoded = counts.encoders_reencoded - before.encoders_reencoded; + let words = &second.words()[..(LENGTH / 4) as usize]; + let blit = words.iter().flat_map(|word| word.to_le_bytes()).collect(); + drop(open); + let (after, _) = tools.bytes(&texture); + Some(Logged { + logged, + again, + reencoded, + blit, + after, + }) +} + +/// The second test of the module docs: with a buffer over host pages alive, a logged pass turns +/// and copies nothing in; the rebind encodes the turning command buffer's blit and pass again, the +/// blit reading the texels from before the turn and the pass taking its turn again, reading them +/// too with no copy in. Each lane's bytes are those the same lane reads where no pass turns. +#[test] +fn a_logged_pass_turns_and_its_encoding_again_meets_the_faces_as_first_met() { + // The pages, declared before the device that uses them, so dropped after it. + let hosts: [Host; 4] = std::array::from_fn(|_| Host::new()); + let scratch = Scratch::new("attached-read-faces-logged"); + let device = device(&scratch.0); + let tools = Tools::new(&device); + let Some(turned) = logged_lane(&device, &tools, [&hosts[0], &hosts[1]], false) else { + return; + }; + let copied = logged_lane(&device, &tools, [&hosts[2], &hosts[3]], true).unwrap(); + for (lane, name) in [(&turned, "turned"), (&copied, "copied")] { + eprintln!( + "ATTACHED-READ-FACES: logged, {name}: the logged pass {:?}; encoded again ({} \ + encoders) {:?}", + lane.logged, lane.reencoded, lane.again + ); + assert_eq!( + lane.reencoded, 2, + "{name}: the blit and the pass encoded again" + ); + let differ = + |got: &[u8], want: &[u8]| (0..got.len()).filter(|&at| got[at] != want[at]).count(); + let blit = differ(&lane.blit, &image(0x30, 0x62)); + assert_eq!( + blit, 0, + "{name}: the blit encoded again: {blit} bytes differ" + ); + let after = differ(&lane.after, &image(0x90, 0x62)); + assert_eq!( + after, 0, + "{name}: the pass encoded again: {after} bytes differ" + ); + } + let turn = Moved { + swaps: 1, + reads: 1, + ..Moved::default() + }; + assert_eq!(turned.logged, turn, "the logged pass turns"); + assert_eq!( + ( + turned.again.swaps, + turned.again.copied_in, + turned.again.unswapped + ), + (1, 0, 0), + "the pass turns, and its encoding again takes the turn again with no copy in" + ); + assert_eq!( + (copied.logged.swaps, copied.logged.busy, copied.again.swaps), + (0, 1, 0), + "beside an open command buffer, no pass turns" + ); + assert!( + copied.again.copied_in > 0, + "beside an open command buffer, the pass copies in" + ); + assert_eq!( + turned.blit, copied.blit, + "the blit's bytes, turned and copied" + ); + assert_eq!( + turned.after, copied.after, + "the texture's bytes, turned and copied" + ); +} diff --git a/crates/metal2vulkan-runtime/src/texture/faces.rs b/crates/metal2vulkan-runtime/src/texture/faces.rs index e521fd912..8e8d9c368 100644 --- a/crates/metal2vulkan-runtime/src/texture/faces.rs +++ b/crates/metal2vulkan-runtime/src/texture/faces.rs @@ -17,8 +17,8 @@ //! renders one level would leave the other face's other levels stale, and one view cannot present //! levels of two images. //! - **The turn** (`render/face_swap.rs`): at the open of a render pass, once its encoder is open, -//! where the pass runs once (no replay, one group, no rate map or log, no ended encoder of its -//! command buffer keeping a replay log) and a color attachment renders the whole texture (level +//! where the pass runs once (one group, no rate map; a pass encoded again turns nothing anew, +//! **Encoded again** below) and a color attachment renders the whole texture (level //! 0, slice 0, the pass's extent the texture's), loaded `Clear` or `DontCare`, with no resolve, //! no depth or stencil attachment and no other attachment of it, the texture presents its other //! face from then on ([`Texture::turn_face`]). The pass renders into it; its draws read the face @@ -51,6 +51,17 @@ //! see what it wrote. Where the turning command buffer goes uncommitted, or commits nothing of //! its work ([`FaceSwaps::ran_nothing`]), the next batch to name the new face takes the same //! copies, once. Where its pass is submitted, every later batch is after it. +//! - **Encoded again** (`command_buffer/reencode.rs`). A pass logs its calls while the device has +//! a buffer over host pages (`replay.rs`), and a rebind of such a buffer before the turning +//! command buffer's submission encodes again its encoders that named it, the turning pass and +//! encoders before it among them. The turning pass encoded again takes its turn again +//! ([`Texture::retake_turn`]): the texture already presents the face it turned to, its draws +//! read the face from before the turn with no copy in, as the first encoding's did, since none of +//! the command buffer's work has run and that face still holds the texels from before the pass. +//! An encoder before it, encoded again, names the face it named at its first encoding, the one +//! from before the turn ([`with_faces_as_of`], read by every resolution of the face presented): +//! its first encoding's commands ran before the pass, on that face. Any other pass encoded again +//! turns nothing ([`Unturned::Pass`]). //! - **Frozen** ([`Texture::freeze_faces`]): a view of the texture, its `VkImage` handed out, a //! binding beyond its usage (whose shadow names one face as its truth for good) or a storage form //! end its turns: it presents the face it presents then from then on, the other kept as its @@ -77,6 +88,8 @@ use ash::vk; use metal2vulkan::metal::format::ycbcr_writes_stored; use metal2vulkan::metal::TextureType; use metal2vulkan::vk::{ImageType, ImageUsageFlags}; +use std::cell::RefCell; +use std::ops::Range; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, Weak}; @@ -96,8 +109,12 @@ pub(super) struct Faces { } impl Faces { - /// The face presented. + /// The face presented: to an encoder encoded again before a later pass of its command buffer + /// turned the texture, the face from before that turn ([`with_faces_as_of`]). fn face(&self) -> usize { + if let Some(face) = face_as_of(self) { + return usize::from(face); + } usize::from(self.face.load(Ordering::Acquire)) } @@ -144,8 +161,9 @@ pub(crate) enum Unturned { /// scheduler holds, a heap ticket out, a heap set this command buffer bound, a turn whose /// pass is not submitted, or a turn earlier in this command buffer. Busy, - /// The pass takes no turn of any texture: an encoding again, color groups, a - /// rasterization-rate map, or a log for a later encoding. + /// The pass takes no turn of any texture: color groups, a rasterization-rate map, or an + /// encoding again whose first encoding did not turn the texture (the module's **Encoded + /// again**). Pass, /// A swapped pass's copies after its first instance: a read after a barrier, whose copy in /// the turn does not take off. @@ -165,14 +183,82 @@ pub(crate) struct Turned { /// Where a render pass opens in its command buffer, for its turns (`CommandBuffer::turn_point`): /// the command buffer's address, which names it while it lives; the place among its ended -/// encoders' parts that the pass's encoder's first part takes; whether a command of it bound a -/// heap set; and whether an ended encoder of it keeps a log that a rebind encodes again -/// (`replay.rs`), whose commands would then name the face presented after the turn. +/// encoders' parts that the pass's encoder's first part takes; and whether a command of it bound a +/// heap set. pub(crate) struct TurnPoint { pub(crate) owner: usize, pub(crate) part: usize, pub(crate) bound_heaps: bool, - pub(crate) logs_kept: bool, +} + +/// What a thread encoding again an encoder of a command buffer takes of its turns (the module's +/// **Encoded again**): the command buffer's address, the encoder's parts, and, for each texture a +/// later pass of the command buffer turned, its faces (by address) and the face from before that +/// turn. +struct AsOf { + owner: usize, + parts: Range, + earlier: Vec<(usize, u8)>, +} + +thread_local! { + /// The turns of the command buffer whose encoder this thread encodes again now + /// ([`with_faces_as_of`]). + static AS_OF: RefCell> = const { RefCell::new(None) }; +} + +/// Run `f`, which encodes again the encoder of parts `parts` of the command buffer at `owner` on +/// `device` (`command_buffer/reencode.rs`), with the faces of its turns as that encoder's first +/// encoding met them (the module's **Encoded again**): a texture a later pass of the command buffer +/// turned presents the face from before that turn, and the pass of the turn takes it again +/// ([`Texture::retake_turn`]). With no turn of the command buffer pending, `f` runs as it is. +pub(crate) fn with_faces_as_of( + device: &Device, + (owner, parts): (usize, Range), + f: impl FnOnce() -> T, +) -> T { + let swaps = &device.shared().face_swaps; + if !swaps.any() { + return f(); + } + let earlier = swaps.earlier_faces(owner, parts.end); + /// Ends the context as `f` returns or unwinds. + struct Clear(Option); + impl Drop for Clear { + fn drop(&mut self) { + let before = self.0.take(); + AS_OF.with(|as_of| *as_of.borrow_mut() = before); + } + } + let before = AS_OF.with(|as_of| { + as_of.borrow_mut().replace(AsOf { + owner, + parts, + earlier, + }) + }); + let _clear = Clear(before); + f() +} + +/// The face `faces` presents to the encoder this thread encodes again, where a later pass of its +/// command buffer turned it ([`with_faces_as_of`]); `None` elsewhere. +fn face_as_of(faces: &Faces) -> Option { + let at = faces as *const Faces as usize; + AS_OF.with(|as_of| { + let as_of = as_of.borrow(); + let earlier = &as_of.as_ref()?.earlier; + (earlier.iter()).find_map(|&(faces, face)| (faces == at).then_some(face)) + }) +} + +/// The command buffer and parts of the encoder this thread encodes again +/// ([`with_faces_as_of`]); `None` where it encodes none so. +fn encoding_again() -> Option<(usize, Range)> { + AS_OF.with(|as_of| { + let as_of = as_of.borrow(); + as_of.as_ref().map(|a| (a.owner, a.parts.clone())) + }) } impl Texture { @@ -293,9 +379,9 @@ impl Texture { } /// The face the texture presents: 0 its own image (a texture without faces too), 1 its - /// second. + /// second; to an encoder encoded again, as its first encoding met it ([`with_faces_as_of`]). pub(crate) fn face(&self) -> u8 { - (self.0.faces.get()).map_or(0, |faces| faces.face.load(Ordering::Acquire)) + (self.0.faces.get()).map_or(0, |faces| faces.face() as u8) } /// End the texture's turns, where it has faces (the module's **Frozen**): it presents the @@ -361,6 +447,7 @@ impl Texture { owner: point.owner, part: point.part, texture: Arc::downgrade(&self.0), + from: from as u8, base, turned, stale: AtomicBool::new(false), @@ -372,6 +459,22 @@ impl Texture { }) } + /// Take again, in the encoding again of the pass that turned the texture (the module's + /// **Encoded again**), the turn that pass's first encoding took: where this thread encodes + /// again an encoder whose parts hold a pending turn of the texture by its command buffer, and + /// the texture still presents the face that turn turned to, the shadow the pass's first + /// instance reads without a copy in, the face from before the turn; else `None`. + pub(crate) fn retake_turn(&self) -> Option { + let faces = self.0.faces.get()?; + let (owner, parts) = encoding_again()?; + let swaps = &self.device().shared().face_swaps; + let from = swaps.turned_in(&self.0, owner, &parts)?; + let to = 1 - usize::from(from); + (usize::from(faces.face.load(Ordering::Acquire)) == to).then(|| Turned { + copies: Arc::clone(faces.shadows[to].copies()), + }) + } + /// The copies of the attached reads' shadow of each face, where the texture has faces: a /// command buffer's carry of either goes at a turn (`render/face_swap.rs`). pub(crate) fn face_copies(&self) -> Option<[Arc; 2]> { @@ -442,6 +545,8 @@ struct SwapRecord { owner: usize, part: usize, texture: Weak, + /// The face presented before the turn: 0 the texture's own image, 1 its second. + from: u8, /// The face that holds the truth until the pass runs, and the face presented from the turn. base: Arc, turned: Arc, @@ -588,6 +693,36 @@ impl FaceSwaps { (records.iter()).any(|record| std::ptr::eq(record.texture.as_ptr(), texture)) } + /// For each texture a pass of the command buffer at `owner` turned at a part from `part` on, + /// whose pass has not run: its faces' address and the face it presented before the turn + /// ([`with_faces_as_of`]). + fn earlier_faces(&self, owner: usize, part: usize) -> Vec<(usize, u8)> { + let records = lock(&self.records); + (records.iter()) + .filter(|record| record.owner == owner && record.part >= part) + .filter(|record| !record.stale.load(Ordering::Acquire)) + .filter_map(|record| { + let texture = record.texture.upgrade()?; + let faces = texture.faces.get()? as *const Faces as usize; + Some((faces, record.from)) + }) + .collect() + } + + /// The face `texture` presented before a pending turn of it by a pass of the command buffer at + /// `owner` among parts `parts` ([`Texture::retake_turn`]); `None` where there is none. + fn turned_in(&self, texture: &TextureShared, owner: usize, parts: &Range) -> Option { + if !self.any() { + return None; + } + let records = lock(&self.records); + (records.iter()) + .filter(|record| record.owner == owner && parts.contains(&record.part)) + .filter(|record| !record.stale.load(Ordering::Acquire)) + .find(|record| std::ptr::eq(record.texture.as_ptr(), texture)) + .map(|record| record.from) + } + /// The command buffer at `owner` will run none of its work: its went uncommitted, or its commit /// ran nothing (the module docs). Its records go stale. pub(crate) fn ran_nothing(&self, owner: usize) { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index acddc57c4..384f711f9 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -9069,8 +9069,8 @@ pub struct WorkCounts { /// buffer or one whose pass was not submitted yet. pub attached_read_unswapped_busy: u64, /// The copies in of an attached read's shadow before a pass's first instance that no turn took - /// off, for a pass that turns nothing: an encoding again, color groups, a rasterization-rate - /// map, a log of its calls or an earlier encoder's. + /// off, for a pass that turns nothing: color groups, a rasterization-rate map, or an encoding + /// again whose first encoding turned nothing (`texture/faces.rs`, **Encoded again**). pub attached_read_unswapped_pass: u64, /// The copies in of an attached read's shadow before a later instance of a pass, turned or not: /// a read after a barrier, which reads the draws before it. diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 3806888ab..23d3c7b52 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -638,6 +638,8 @@ mod linked_signatures; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod lod_bias; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod logged_face_turns; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod logic_ops; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod made_at_creation; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/logged_face_turns.rs b/crates/metal2vulkan-validation/src/runtime_lane/logged_face_turns.rs new file mode 100644 index 000000000..a15ce7120 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/logged_face_turns.rs @@ -0,0 +1,370 @@ +//! A render pass that turns a texture's two faces while it logs its calls for a rebind, on the +//! device the cfg selects, under the validation layer (the runtime's `texture/faces.rs`, +//! **Encoded again**). While the device has a no-copy buffer over host pages, every render pass +//! logs its calls, so that a rebind of such a buffer before its command buffer's first submission +//! can encode it again (`replay.rs`). Such a pass turns as any other: a `Private` texture whose +//! first attached read gave it two faces turns to the other at a pass that clears it whole, its +//! read of the texels from before the pass taking the face presented before with no copy in. +//! +//! The texture is [`WIDTH`] x [`HEIGHT`] `BGRA8Unorm`. Each pass clears it and draws, through +//! [`RECT`], `tob_read` (the texel under each pixel, written as read), or loads it and draws +//! `tob_solid` there (`fixtures/public/engine/tob_renders.ll`, with `tob_rect`); so the texels +//! inside [`RECT`] after a read are those it read, Metal's answer the texels from before the pass. +//! +//! The lane: a clear and a solid `0x40`; the first read, which makes the faces; a solid `0x50`; a logged read that clears to +//! `0x30` (it turns); a solid `0x62`; then a command buffer behind a shared-event wait holding a +//! blit of the texture into the buffer over host pages, and a read that clears to `0x90`, its +//! corners from that buffer (it turns back). A rebind of the buffer before the signal encodes both +//! encoders again: the blit reads the texels from before the turn, `0x30` around `0x62`, and the +//! pass takes its turn again, reading the `0x62` with no copy in. The same lane beside an open +//! command buffer, where no pass turns and every read copies in, reads the same bytes. The layer +//! reports nothing; under `METAL2VULKAN_LANE_VALIDATION=sync` its synchronization checks run too. + +use super::attachment_reads::function; +use super::host_memory::{no_copy, not_importable, on_device, Mapping}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor}; +use metal2vulkan_runtime::{ + BlitOption, Buffer, ClearColor, CommandBuffer, CommandQueue, Device, EventRef, HostMemory, + LoadAction, Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, ScissorRect, Size, StoreAction, Texture, TextureDescriptor, WorkCounts, +}; +use std::time::Duration; + +const WAIT: Duration = Duration::from_secs(60); + +/// The texture: `WIDTH` texels a row of 4 bytes, `HEIGHT` rows. +const WIDTH: u64 = 64; +const HEIGHT: u64 = 16; +const ROW: u64 = WIDTH * 4; +const LENGTH: u64 = ROW * HEIGHT; + +/// Where the reads and the solid draws draw: `[8, 24) x [4, 12)`. +const RECT: ScissorRect = ScissorRect { + x: 8, + y: 4, + width: 16, + height: 8, +}; + +/// The host pages' length, and where the corners lie in them, past the bytes the blit writes. +const PAGES: usize = 128 << 10; +const CORNERS_AT: u64 = 64 << 10; + +/// The texture's bytes where every texel outside [`RECT`] holds `outside` and every one inside +/// it `inside`, in each channel. +fn image(outside: u8, inside: u8) -> Vec { + let mut bytes = Vec::with_capacity(LENGTH as usize); + for y in 0..HEIGHT { + for x in 0..WIDTH { + let rows = RECT.y..RECT.y + RECT.height; + let columns = RECT.x..RECT.x + RECT.width; + let value = match rows.contains(&y) && columns.contains(&x) { + true => inside, + false => outside, + }; + bytes.extend([value; 4]); + } + } + bytes +} + +/// The corners of the draws: the whole target, which [`RECT`] scissors. +fn corners() -> Vec { + [-1.0f32, -1.0, 1.0, 1.0] + .iter() + .flat_map(|f| f.to_le_bytes()) + .collect() +} + +/// What a pass draws through [`RECT`]: a solid value in every channel, or the read. +#[derive(Clone, Copy)] +enum Draw { + Solid(u8), + Read, +} + +/// The pipelines and queue of the lane. +struct Tools { + queue: CommandQueue, + solid: RenderPipelineState, + read: RenderPipelineState, +} + +impl Tools { + fn new(device: &Device) -> Tools { + let pipeline = |name: &str| { + let mut d = + RenderPipelineDescriptor::new(function(device, "tob_rect", "tob_renders.ll")); + d.fragment = Some(function(device, name, "tob_renders.ll")); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::BGRA8Unorm)); + device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + .unwrap() + }; + Tools { + queue: device.new_command_queue().unwrap(), + solid: pipeline("tob_solid"), + read: pipeline("tob_read"), + } + } + + /// Encode into `command_buffer` a pass over `texture`, cleared to `clear` where it is given, + /// else loaded, that draws `draw`, its corners from `corners_in` (a buffer and the corners' + /// offset in it) where it is given, else from bytes. + fn encode( + &self, + command_buffer: &CommandBuffer, + texture: &Texture, + (clear, draw): (Option, Draw), + corners_in: Option<(&Buffer, u64)>, + ) { + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(texture.clone()); + color.store_action = StoreAction::Store; + match clear { + Some(value) => { + let unorm = f64::from(value) / 255.0; + color.load_action = LoadAction::Clear; + color.clear_color = ClearColor::new(unorm, unorm, unorm, unorm); + } + None => color.load_action = LoadAction::Load, + } + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + match draw { + Draw::Read => { + encoder.set_render_pipeline_state(&self.read).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + } + Draw::Solid(value) => { + encoder.set_render_pipeline_state(&self.solid).unwrap(); + let unorm = f32::from(value) / 255.0; + let rgba: Vec = [unorm; 4].iter().flat_map(|f| f.to_le_bytes()).collect(); + encoder.set_fragment_bytes(&rgba, 0).unwrap(); + } + } + match corners_in { + Some((buffer, offset)) => encoder.set_vertex_buffer(Some(buffer), offset, 0), + None => encoder.set_vertex_bytes(&corners(), 0), + } + .unwrap(); + encoder.set_scissor_rect(RECT).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap(); + encoder.end_encoding().unwrap(); + } + + /// A pass of [`encode`](Self::encode) in a command buffer of its own, run: what it moved. + fn pass(&self, texture: &Texture, clear: Option, draw: Draw) -> Moved { + let device = self.queue.device(); + let before = device.work_counts(); + let command_buffer = self.queue.command_buffer().unwrap(); + self.encode(&command_buffer, texture, (clear, draw), None); + run(&command_buffer); + Moved::of(&before, &device.work_counts()) + } + + /// Encode into `command_buffer` a copy of `texture` into `into`, at its start. + fn encode_read(command_buffer: &CommandBuffer, texture: &Texture, into: &Buffer) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + (blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(WIDTH, HEIGHT, 1), + into, + 0, + ROW, + LENGTH, + BlitOption::None, + )) + .unwrap(); + blit.end_encoding().unwrap(); + } + + /// `texture`'s bytes, through a copy in a command buffer of its own. + fn bytes(&self, texture: &Texture) -> Vec { + let device = self.queue.device(); + let back = (device.new_buffer(LENGTH, ResourceOptions::shared())).unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + Tools::encode_read(&command_buffer, texture, &back); + run(&command_buffer); + let bytes = back.contents().unwrap().as_ptr(); + // SAFETY: the buffer's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(bytes, LENGTH as usize) }.to_vec() + } +} + +/// Commit `command_buffer`, wait for it, and check it completed without error. +fn run(command_buffer: &CommandBuffer) { + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); +} + +/// The counts the lane reads, between two snapshots: the texels copied in to an image's shadow +/// (`shadow_texels_copied_in_images`), the turns (`attached_read_swaps`), the copies in for a +/// pass that turned nothing beside another command buffer (`attached_read_unswapped_busy`), and +/// the encoders a rebind encoded again (`encoders_reencoded`) or refused to +/// (`reencodes_refused`). +#[derive(Debug, Default, PartialEq, Eq)] +struct Moved { + copied_in: u64, + swaps: u64, + busy: u64, + reencoded: u64, + refused: u64, +} + +impl Moved { + fn of(before: &WorkCounts, after: &WorkCounts) -> Moved { + let delta = |count: fn(&WorkCounts) -> u64| count(after) - count(before); + Moved { + copied_in: delta(|c| c.shadow_texels_copied_in_images), + swaps: delta(|c| c.attached_read_swaps), + busy: delta(|c| c.attached_read_unswapped_busy), + reencoded: delta(|c| c.encoders_reencoded), + refused: delta(|c| c.reencodes_refused), + } + } +} + +/// What a lane moved and read: its logged pass's move, its command buffer's (from its encoding to +/// its completion), the bytes its blit read through its encoding again, and the texture's after. +struct Lane { + logged: Moved, + again: Moved, + blit: Vec, + after: Vec, +} + +/// The lane of the module docs over a buffer over `first`, rebound over `second`, beside an open +/// command buffer where `busy`; `None`, printed, where the device imports no host memory. +fn lane( + device: &Device, + tools: &Tools, + [first, second]: [&Mapping; 2], + busy: bool, +) -> Option { + for pages in [first, second] { + pages.write(CORNERS_AT as usize, &corners()); + } + // SAFETY: the mapping outlives the device (made before it, dropped after it), and only the + // buffer's commands use it while the buffer lives. + let made = unsafe { + no_copy( + device, + first.pointer(), + PAGES, + ResourceOptions::default(), + None, + ) + }; + let pages = match made { + Ok(pages) => pages, + Err(error) if not_importable(&error) => { + eprintln!("LOGGED-FACE-TURNS: the device imports no host memory: {error:?}"); + return None; + } + Err(error) => panic!("{error:?}"), + }; + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::private(); + let texture = device.new_texture(&descriptor).unwrap(); + let open = busy.then(|| tools.queue.command_buffer().unwrap()); + tools.pass(&texture, Some(0x10), Draw::Solid(0x40)); + tools.pass(&texture, Some(0x20), Draw::Read); + tools.pass(&texture, None, Draw::Solid(0x50)); + let logged = tools.pass(&texture, Some(0x30), Draw::Read); + tools.pass(&texture, None, Draw::Solid(0x62)); + let before = device.work_counts(); + let gate = device.new_shared_event().unwrap(); + let command_buffer = tools.queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&gate), 1)).unwrap(); + Tools::encode_read(&command_buffer, &texture, &pages); + let corners_in = Some((&pages, CORNERS_AT)); + tools.encode( + &command_buffer, + &texture, + (Some(0x90), Draw::Read), + corners_in, + ); + command_buffer.commit().unwrap(); + // SAFETY: as above. + let memory = unsafe { HostMemory::new(second.pointer()) }; + // SAFETY: as above. + unsafe { pages.rebind_bytes_no_copy(memory, None, None) }.unwrap(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let again = Moved::of(&before, &device.work_counts()); + let blit = second.read(0..LENGTH as usize); + drop(open); + let after = tools.bytes(&texture); + Some(Lane { + logged, + again, + blit, + after, + }) +} + +/// The module docs' lane, turned and beside an open command buffer: the same bytes, Metal's. +#[test] +fn a_logged_pass_turns_and_its_encoding_again_reads_the_texels_from_before_it() { + // Made before the device, dropped after it. + let mappings: [Mapping; 4] = std::array::from_fn(|_| Mapping::anonymous(PAGES)); + on_device(|device| { + let tools = Tools::new(device); + let Some(turned) = lane(device, &tools, [&mappings[0], &mappings[1]], false) else { + return; + }; + let copied = lane(device, &tools, [&mappings[2], &mappings[3]], true).unwrap(); + for (lane, name) in [(&turned, "turned"), (&copied, "copied")] { + eprintln!( + "LOGGED-FACE-TURNS {name}: the logged pass {:?}; the command buffer encoded \ + again {:?}", + lane.logged, lane.again + ); + assert_eq!( + (lane.again.reencoded, lane.again.refused), + (2, 0), + "{name}: the blit and the pass encoded again" + ); + let differ = + |got: &[u8], want: &[u8]| (0..got.len()).filter(|&at| got[at] != want[at]).count(); + let blit = differ(&lane.blit, &image(0x30, 0x62)); + assert_eq!( + blit, 0, + "{name}: the blit encoded again: {blit} bytes differ" + ); + let after = differ(&lane.after, &image(0x90, 0x62)); + assert_eq!( + after, 0, + "{name}: the pass encoded again: {after} bytes differ" + ); + } + assert_eq!( + (turned.logged.swaps, turned.logged.copied_in), + (1, 0), + "the logged pass turns, with no copy in" + ); + assert_eq!( + (turned.again.swaps, turned.again.copied_in), + (1, 0), + "the pass turns, and its encoding again takes the turn again with no copy in" + ); + assert_eq!( + (copied.logged.swaps, copied.logged.busy, copied.again.swaps), + (0, 1, 0), + "beside an open command buffer, no pass turns" + ); + assert!( + copied.again.copied_in > 0, + "beside an open command buffer, the pass copies in" + ); + }); +} diff --git a/crates/metal2vulkan/src/env_vars.rs b/crates/metal2vulkan/src/env_vars.rs index b5e4d7b45..2fbf2ef92 100644 --- a/crates/metal2vulkan/src/env_vars.rs +++ b/crates/metal2vulkan/src/env_vars.rs @@ -107,7 +107,9 @@ pub const REGISTRY: &[EnvVar] = &[ device's message sink or on stderr: the call, the texture's format, size, \ levels and usage, its truth (the buffer's storage mode, length and object ID, \ the texels' offset and row pitch, or its own image), and what made it a \ - shadow; set to anything but empty or 0", + shadow; and once per shadowed texture, at the first draw that binds it, \ + whether its function fetches, samples or writes it and its samplers' filters; \ + set to anything but empty or 0", }, EnvVar { name: "METAL2VULKAN_LOG_PASSES", diff --git a/docs/API.md b/docs/API.md index 44f16dbf7..3e6bbfff1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1840,7 +1840,11 @@ the bytes with or without the feedback loop usage, a shadow, or an image of its texture's image of its stored frame and its twin, a two-plane extended-range texture's image, a depth or stencil texture's tiled twin over a surface plane, and a YCbCr texture's converted image and render shadow. A heap texture's shadow, a view's shadow of an image and a texture buffer's -staging are not logged. +staging are not logged. It also logs, once per shadowed texture (a shadow of its truth, a usage +shadow or two faces that take turns), at the first draw whose pipeline uses a slot that binds it: +the slot, whether the function fetches, samples or writes the texture, and the filters of each +sampler it samples it through (a sampler state's minification, magnification and mipmap filters, +or a constexpr sampler's as the pipeline layout bakes it). 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