From f4003f3ddbc0e2494f991d8a67180629faefca6c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 02:07:01 -0800 Subject: [PATCH] :racehorse: Batch vertex draws in processes that hold a copied buffer PR 205 sent a run of vertex draws one command at a time in every encoder of a process once any copy of host pages was live (copied::any(), process state), so a guest whose app held one no-copy buffer over a copy lost the batch everywhere. The batch now notes each buffer's copy as it binds, a use that can write it, as a bind alone notes it, and takes every run it can: the recorder (a tool path, off by default) and an encoder ended, with no pipeline state or with its names gone still send them one at a time. For the guest: nothing changes but speed; each run's binds and draws are rt's calls in the order the commands alone make them. The batch is its own method, batch_draws, which answers None where it takes none, so draw_batches_sync_a_copied_vertex_buffer_on_vulkan now asserts that its run was taken as a batch. draw_primitives' doc said it checked for a pipeline state, which its caller does; it now says so. The batch tests and their case enum have doc comments, and the module's docs say what a run of draws is. --- .../src/rt_platform/render.rs | 195 +++++++++++------- 1 file changed, 123 insertions(+), 72 deletions(-) diff --git a/crates/reims-vgpu-vulkan/src/rt_platform/render.rs b/crates/reims-vgpu-vulkan/src/rt_platform/render.rs index 8680971cf..f5afdf5dc 100644 --- a/crates/reims-vgpu-vulkan/src/rt_platform/render.rs +++ b/crates/reims-vgpu-vulkan/src/rt_platform/render.rs @@ -6,6 +6,11 @@ //! `set*Textures:withRange:`, `set*SamplerStates:withRange:` and its form with LOD clamps) is one //! call per entry, in its order; the shorter draw forms are the longest one with one instance and //! bases of 0. +//! - **A run of vertex draws** (`RenderEncoder::encode_draws`: a vertex buffer's bind, then a +//! draw of primitives, for each) is rt's calls in their order under one hold of the encoder, as +//! the commands one at a time would make them, each buffer's copy noted as it binds, as a bind +//! alone notes it (`super::copied`); where the recorder records, or the encoder ended or has no +//! pipeline state set, the commands go one at a time. //! - **A pipeline state the encoder sets is kept by its command buffer** until the command buffer //! completes ([`Kept`]), as the compute encoder's are (`super::compute`). //! - **Indirect draws** of primitives, indexed primitives and patches are rt's: the GPU reads the @@ -721,7 +726,10 @@ fn set(pipeline: Option) -> Result<(), Stop> { } } -/// The short draw form, after checking that a pipeline is bound. +/// `drawPrimitives:vertexStart:vertexCount:` into rt's open `encoder`: rt's longest draw form +/// with one instance and a base instance of 0. A start or count past rt's 32 bits and a primitive +/// type Metal has none of stop it; whether a pipeline state is set is the caller's to check +/// ([`set`]). fn draw_primitives( encoder: &mut rt::RenderCommandEncoder, primitive_type: u64, @@ -1130,6 +1138,86 @@ fn note_names(names: &mut EncoderNames, cmd: &RenderCmd<'_, RtPlatform>) { } } +impl RtObj { + /// `draws` under one hold of the encoder, each draw's bind and draw rt's call in order, as + /// the commands one at a time would make them ([`RenderEncoder::encode_draws`]): each bound + /// buffer named for the command buffers in flight (`super::fault`), and the copy each lies + /// over noted as it binds, a use that can write it, as a `setVertexBuffer:offset:atIndex:` + /// notes it ([`note_copies`]). A refused bind or draw is reported once, as alone, and the + /// draws after it go one at a time. `None`, taking none of them, where the recorder records + /// (its tool path, off by default, records each call as sent alone), or the encoder ended, + /// has no pipeline state set or its names joined the list: the caller then sends them one at + /// a time ([`encode_each`]). + fn batch_draws( + &self, + on: OnFault, + draws: &[VertexDraw<'_, RtPlatform>], + ) -> Option> { + if draws.is_empty() { + return Some(Ok(())); + } + if crate::recorder::on() { + return None; + } + let held = self.open.lock(); + let mut open = held.borrow_mut(); + let Open { + rt, + pipeline, + seen, + naming, + } = &mut *open; + let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else { + return None; + }; + let used = self.kept.copies(); + let mut last = None; + let mut buffer = None; + for (i, draw) in draws.iter().enumerate() { + if let Some(bound) = draw.buffer { + names.bound_buffers.add_named(bound.named()); + } + let key = draw.buffer.map(std::ptr::from_ref); + if key != last { + last = key; + buffer = draw.buffer.map(|b| b.rt()); + draw.buffer.iter().for_each(|b| used.buffer(b)); + } + let bound = small(draw.index).and_then(|index| { + encoder + .set_vertex_buffer(buffer, draw.offset, index) + .map_err(Stop::from) + }); + // A refusal is reported once. After a refused bind, the draw still sees the + // encoder's existing binding, and only commands that have yet to run go to encode. + if let Err(stop) = bound { + drop(open); + drop(held); + report(draw.vertex_buffer().selector(), Some(stop)); + if let Err(raise) = self.encode(on, draw.primitives()) { + return Some(Err(raise)); + } + return Some(encode_each(self, on, &draws[i + 1..])); + } + if let Err(stop) = draw_primitives( + encoder, + draw.primitive_type, + draw.vertex_start, + draw.vertex_count, + ) { + let sel = draw.primitives().selector(); + let functions = + self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None); + drop(open); + drop(held); + naming_functions(functions, || report(sel, Some(stop))); + return Some(encode_each(self, on, &draws[i + 1..])); + } + } + Some(Ok(())) + } +} + impl RenderEncoder for RtObj { /// rt's command (the module's docs); `endEncoding` ends rt's encoder. fn encode(&self, on: OnFault, cmd: RenderCmd<'_, RtPlatform>) -> RaiseResult<()> { @@ -1177,67 +1265,13 @@ impl RenderEncoder for RtObj { recorded_answer } + /// `batch_draws`'s, under one hold of the encoder, where it takes them; else one at a time + /// ([`encode_each`]). fn encode_draws(&self, on: OnFault, draws: &[VertexDraw<'_, RtPlatform>]) -> RaiseResult<()> { - if draws.is_empty() { - return Ok(()); + match self.batch_draws(on, draws) { + Some(answer) => answer, + None => encode_each(self, on, draws), } - if crate::recorder::on() || super::copied::any() { - return encode_each(self, on, draws); - } - let held = self.open.lock(); - let mut open = held.borrow_mut(); - let Open { - rt, - pipeline, - seen, - naming, - } = &mut *open; - let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else { - drop(open); - drop(held); - return encode_each(self, on, draws); - }; - let mut last = None; - let mut buffer = None; - for (i, draw) in draws.iter().enumerate() { - if let Some(bound) = draw.buffer { - names.bound_buffers.add_named(bound.named()); - } - let key = draw.buffer.map(std::ptr::from_ref); - if key != last { - last = key; - buffer = draw.buffer.map(|b| b.rt()); - } - let bound = small(draw.index).and_then(|index| { - encoder - .set_vertex_buffer(buffer, draw.offset, index) - .map_err(Stop::from) - }); - // A refusal is reported once. After a refused bind, the draw still sees the - // encoder's existing binding, and only commands that have yet to run go to encode. - if let Err(stop) = bound { - drop(open); - drop(held); - report(draw.vertex_buffer().selector(), Some(stop)); - self.encode(on, draw.primitives())?; - return encode_each(self, on, &draws[i + 1..]); - } - if let Err(stop) = draw_primitives( - encoder, - draw.primitive_type, - draw.vertex_start, - draw.vertex_count, - ) { - let sel = draw.primitives().selector(); - let functions = - self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None); - drop(open); - drop(held); - naming_functions(functions, || report(sel, Some(stop))); - return encode_each(self, on, &draws[i + 1..]); - } - } - Ok(()) } /// Holds the encoder for `run` ([`RtRenderEncoder`]'s `open`): the commands `run` sends take @@ -1609,29 +1643,44 @@ mod tests { check_draw_batch(DrawBatchCase::Existing) } + /// A bind of no buffer between two binds of one: the draw after it is refused, counted once + /// as rt's own refusal, and the next bind and draw go on, as the commands one at a time do. #[test] fn draw_batches_clear_and_rebind_a_vertex_buffer_on_vulkan() -> Result<(), &'static str> { check_draw_batch(DrawBatchCase::Unbind) } + /// A draw rt refuses as its gap (a line of width 2) is reported once, and the draws after it + /// go on: as the commands one at a time do. #[test] fn draw_batches_report_a_gap_and_continue_on_vulkan() -> Result<(), &'static str> { check_draw_batch(DrawBatchCase::Gap) } + /// Each draw's bound buffer is named for the command buffers in flight, once a bind, as the + /// commands one at a time name them. #[test] fn draw_batches_record_bound_buffer_names_on_vulkan() -> Result<(), &'static str> { check_draw_batch(DrawBatchCase::Names) } + /// What [`check_draw_batch`] checks of a batch against the same draws one at a time. #[derive(PartialEq, Eq)] enum DrawBatchCase { + /// Draws over the buffers bound before, refused binds and draws among them, with and + /// without a pipeline state, in an encoder open and ended. Existing, + /// A bind of no buffer between two of one. Unbind, + /// A draw rt refuses as its gap between two it draws. Gap, + /// The names of the buffers the draws bind. Names, } + /// On the GPU the test holds: `case`'s draws into a 4x4 target, encoded as a batch and one + /// at a time, leave the same pixels, visibility result, refusal counts and bound buffers' + /// names, which are the ones `case` expects. fn check_draw_batch(case: DrawBatchCase) -> Result<(), &'static str> { use crate::core::platform::command::WorkNames; use crate::rt_platform::fault::{Ids, Operands, name_buffer}; @@ -1880,6 +1929,9 @@ mod tests { Ok(()) } + /// On the GPU the test holds: a batch whose vertex buffer lies over a copy of host pages + /// (`super::super::copied`) is taken as a batch, not one at a time, and its draw reads the + /// bytes the CPU wrote into the pages before the commit, which the commit copied in. #[test] fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> { use crate::core::host::HostPtr; @@ -1954,19 +2006,18 @@ mod tests { ), Ok(()) ); + let draws = [VertexDraw { + buffer: Some(&buffer), + offset: 0, + index: 0, + primitive_type: TRIANGLE, + vertex_start: 0, + vertex_count: 3, + }]; assert_eq!( - encoder.encode_draws( - on, - &[VertexDraw { - buffer: Some(&buffer), - offset: 0, - index: 0, - primitive_type: TRIANGLE, - vertex_start: 0, - vertex_count: 3, - }] - ), - Ok(()) + encoder.batch_draws(on, &draws), + Some(Ok(())), + "taken as a batch" ); assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(())); assert_eq!(commands.commit(on), Ok(()));