1use std::collections::HashMap;
30use std::hash::{Hash, Hasher};
31
32use etalon::util::DeviceExt;
33
34#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
36pub enum ComputeBufferKind {
37 Uniform,
39 StorageRead,
41 StorageReadWrite,
43}
44
45impl ComputeBufferKind {
46 fn is_read_write(self) -> bool {
47 matches!(self, ComputeBufferKind::StorageReadWrite)
48 }
49
50 fn wgpu_binding_type(self) -> etalon::BindingType {
51 match self {
52 ComputeBufferKind::Uniform => etalon::BindingType::Buffer {
53 ty: etalon::BufferBindingType::Uniform,
54 has_dynamic_offset: false,
55 min_binding_size: None,
56 },
57 ComputeBufferKind::StorageRead => etalon::BindingType::Buffer {
58 ty: etalon::BufferBindingType::Storage { read_only: true },
59 has_dynamic_offset: false,
60 min_binding_size: None,
61 },
62 ComputeBufferKind::StorageReadWrite => etalon::BindingType::Buffer {
63 ty: etalon::BufferBindingType::Storage { read_only: false },
64 has_dynamic_offset: false,
65 min_binding_size: None,
66 },
67 }
68 }
69}
70
71#[derive(Clone, Copy)]
73pub struct ComputeBinding<'a> {
74 pub binding: u32,
76 pub kind: ComputeBufferKind,
78 pub data: &'a [u8],
81}
82
83struct CachedPipeline {
85 pipeline: etalon::ComputePipeline,
86 layout: etalon::BindGroupLayout,
87}
88
89pub(crate) struct PendingCompute {
91 readback: etalon_render::compute_readback::ComputeReadback,
92 dispatch_id: u64,
93}
94
95struct PooledBuffer {
97 buffer: etalon::Buffer,
98 capacity: u64,
99 usage: etalon::BufferUsages,
100 _reservation: crate::gpu_context::VramReservation<'static>,
101}
102
103struct PooledBindGroup {
105 bind_group: etalon::BindGroup,
106 sizes_hash: u64,
108}
109
110struct ComputePool {
119 buffers: HashMap<(u64, u32), PooledBuffer>,
122 bind_group: Option<PooledBindGroup>,
124 staging: Option<PooledBuffer>,
126 last_key: u64,
128}
129
130impl ComputePool {
131 fn new() -> Self {
132 Self {
133 buffers: HashMap::new(),
134 bind_group: None,
135 staging: None,
136 last_key: 0,
137 }
138 }
139
140 fn reset_for_key(&mut self, key: u64) {
143 if self.last_key != 0 && self.last_key != key {
144 self.buffers.clear();
145 self.bind_group = None;
146 }
148 self.last_key = key;
149 }
150}
151
152pub(crate) struct ComputeState {
155 cache: HashMap<u64, CachedPipeline>,
156 shader_cache: Vec<Option<etalon::ShaderModule>>,
160 pending: Option<PendingCompute>,
161 next_dispatch_id: u64,
162 pool: ComputePool,
164}
165
166impl ComputeState {
167 pub(crate) fn new() -> Self {
169 Self {
170 cache: HashMap::new(),
171 shader_cache: Vec::new(),
172 pending: None,
173 next_dispatch_id: 1,
174 pool: ComputePool::new(),
175 }
176 }
177}
178
179fn align4(n: usize) -> Option<usize> {
182 n.checked_add(3).map(|aligned| aligned & !3)
183}
184
185fn cache_key(wgsl: &str, entry: &str, bindings: &[ComputeBinding<'_>]) -> u64 {
187 let mut h = std::collections::hash_map::DefaultHasher::new();
188 wgsl.hash(&mut h);
189 0u8.hash(&mut h); entry.hash(&mut h);
191 0u8.hash(&mut h);
192 for b in bindings {
193 b.binding.hash(&mut h);
194 b.kind.hash(&mut h);
195 }
196 h.finish()
197}
198
199impl super::PortalGpu {
200 pub fn compute_dispatch(
210 &mut self,
211 wgsl: &str,
212 entry_point: &str,
213 workgroups: [u32; 3],
214 bindings: &[ComputeBinding<'_>],
215 readback_binding: Option<u32>,
216 readback_bytes: usize,
217 ) -> Result<u64, String> {
218 if self.compute.pending.is_some() {
219 return Err("compute_dispatch: previous readback is still pending".into());
220 }
221 if bindings.is_empty() {
222 return Err("compute_dispatch: at least one binding is required".into());
223 }
224 if workgroups[0] == 0 || workgroups[1] == 0 || workgroups[2] == 0 {
225 return Err("compute_dispatch: workgroups must be >= 1 in every dimension".into());
226 }
227 if let Some(binding) = readback_binding {
228 if readback_bytes > 0 && !bindings.iter().any(|b| b.binding == binding) {
229 return Err(format!(
230 "compute_dispatch: readback_binding {binding} not in bindings"
231 ));
232 }
233 }
234 let want_readback = readback_binding.is_some() && readback_bytes > 0;
235 let requested_copy_size = if want_readback {
236 Some(
237 align4(readback_bytes)
238 .ok_or_else(|| "compute_dispatch: readback size overflow".to_string())?,
239 )
240 } else {
241 None
242 };
243
244 let key = cache_key(wgsl, entry_point, bindings);
245 if !self.compute.cache.contains_key(&key) {
246 let module = self
247 .device
248 .create_shader_module(etalon::ShaderModuleDescriptor {
249 label: Some("portal-compute-shader"),
250 source: etalon::ShaderSource::Wgsl(wgsl.into()),
251 });
252 let mut entries: Vec<etalon::BindGroupLayoutEntry> = bindings
253 .iter()
254 .map(|b| etalon::BindGroupLayoutEntry {
255 binding: b.binding,
256 visibility: etalon::ShaderStages::COMPUTE,
257 ty: b.kind.wgpu_binding_type(),
258 count: None,
259 })
260 .collect();
261 entries.sort_by_key(|e| e.binding);
262 let layout = self
263 .device
264 .create_bind_group_layout(&etalon::BindGroupLayoutDescriptor {
265 label: Some("portal-compute-bind-layout"),
266 entries: &entries,
267 });
268 let pipeline_layout =
269 self.device
270 .create_pipeline_layout(&etalon::PipelineLayoutDescriptor {
271 label: Some("portal-compute-pipeline-layout"),
272 bind_group_layouts: &[Some(&layout)],
273 immediate_size: 0,
274 });
275 let pipeline =
276 self.device
277 .create_compute_pipeline(&etalon::ComputePipelineDescriptor {
278 label: Some("portal-compute-pipeline"),
279 layout: Some(&pipeline_layout),
280 module: &module,
281 entry_point: Some(entry_point),
282 compilation_options: etalon::PipelineCompilationOptions::default(),
283 cache: None,
284 });
285 self.compute
286 .cache
287 .insert(key, CachedPipeline { pipeline, layout });
288 }
289 let (pipeline, layout) = {
292 let entry = self.compute.cache.get(&key).expect("just inserted");
293 (entry.pipeline.clone(), entry.layout.clone())
294 };
295
296 self.compute.pool.reset_for_key(key);
298
299 let mut binding_buffers: Vec<(u32, etalon::Buffer)> = Vec::with_capacity(bindings.len());
304 let mut sizes_hash: u64 = 0;
305 for b in bindings {
306 let mut size = b.data.len();
307 if Some(b.binding) == readback_binding && readback_bytes > size {
308 size = readback_bytes;
309 }
310 if size == 0 {
311 return Err(format!(
312 "compute_dispatch: binding {} has zero size (supply data or readback_bytes)",
313 b.binding
314 ));
315 }
316 let mut usage = etalon::BufferUsages::STORAGE | etalon::BufferUsages::COPY_DST;
317 if b.kind.is_read_write() {
318 usage |= etalon::BufferUsages::COPY_SRC;
319 }
320 if matches!(b.kind, ComputeBufferKind::Uniform) {
321 usage = etalon::BufferUsages::UNIFORM | etalon::BufferUsages::COPY_DST;
322 }
323 sizes_hash = sizes_hash.wrapping_mul(31).wrapping_add(size as u64);
325
326 let pool_key = (key, b.binding);
328 let need_new = self
329 .compute
330 .pool
331 .buffers
332 .get(&pool_key)
333 .map_or(true, |pb| pb.capacity < size as u64 || pb.usage != usage);
334 if need_new {
335 let reservation = crate::gpu_context::global_vram_ledger()
336 .try_reserve_graphics(
337 crate::gpu_context::VramResourceClass::FrameTarget,
338 size as u64,
339 )
340 .map_err(|e| format!("compute_dispatch: binding {} refused: {e}", b.binding))?;
341 let buf = if b.data.is_empty() {
342 self.device.create_buffer(&etalon::BufferDescriptor {
343 label: Some("portal-compute-buf"),
344 size: size as u64,
345 usage,
346 mapped_at_creation: false,
347 })
348 } else {
349 self.device
350 .create_buffer_init(&etalon::util::BufferInitDescriptor {
351 label: Some("portal-compute-buf"),
352 contents: b.data,
353 usage,
354 })
355 };
356 self.compute.pool.buffers.insert(
357 pool_key,
358 PooledBuffer {
359 buffer: buf.clone(),
360 capacity: size as u64,
361 usage,
362 _reservation: reservation,
363 },
364 );
365 binding_buffers.push((b.binding, buf));
366 } else {
367 let pb = self.compute.pool.buffers.get(&pool_key).unwrap();
368 let buf = pb.buffer.clone();
369 if !b.data.is_empty() {
371 self.queue.write_buffer(&buf, 0, b.data);
372 }
373 binding_buffers.push((b.binding, buf));
374 }
375 }
376
377 let need_new_bg = self
379 .compute
380 .pool
381 .bind_group
382 .as_ref()
383 .map_or(true, |pbg| pbg.sizes_hash != sizes_hash);
384 let bind_group = if need_new_bg {
385 let mut bg_entries: Vec<etalon::BindGroupEntry> = binding_buffers
386 .iter()
387 .map(|(binding, buf)| etalon::BindGroupEntry {
388 binding: *binding,
389 resource: buf.as_entire_binding(),
390 })
391 .collect();
392 bg_entries.sort_by_key(|e| e.binding);
393 let bg = self.device.create_bind_group(&etalon::BindGroupDescriptor {
394 label: Some("portal-compute-bind"),
395 layout: &layout,
396 entries: &bg_entries,
397 });
398 self.compute.pool.bind_group = Some(PooledBindGroup {
399 bind_group: bg.clone(),
400 sizes_hash,
401 });
402 bg
403 } else {
404 self.compute
405 .pool
406 .bind_group
407 .as_ref()
408 .unwrap()
409 .bind_group
410 .clone()
411 };
412
413 let (staging, copy_size) = if want_readback {
415 let copy_size = requested_copy_size.expect("readback size validated above");
416 let need_new_staging = self
417 .compute
418 .pool
419 .staging
420 .as_ref()
421 .map_or(true, |ps| ps.capacity < copy_size as u64);
422 if need_new_staging {
423 let reservation = crate::gpu_context::global_vram_ledger()
424 .try_reserve_graphics(
425 crate::gpu_context::VramResourceClass::UploadStaging,
426 copy_size as u64,
427 )
428 .map_err(|e| format!("compute_dispatch: readback staging refused: {e}"))?;
429 let staging = self.device.create_buffer(&etalon::BufferDescriptor {
430 label: Some("portal-compute-staging"),
431 size: copy_size as u64,
432 usage: etalon::BufferUsages::MAP_READ | etalon::BufferUsages::COPY_DST,
433 mapped_at_creation: false,
434 });
435 self.compute.pool.staging = Some(PooledBuffer {
436 buffer: staging.clone(),
437 capacity: copy_size as u64,
438 usage: etalon::BufferUsages::MAP_READ | etalon::BufferUsages::COPY_DST,
439 _reservation: reservation,
440 });
441 (Some(staging), copy_size)
442 } else {
443 (
444 Some(self.compute.pool.staging.as_ref().unwrap().buffer.clone()),
445 copy_size,
446 )
447 }
448 } else {
449 (None, 0)
450 };
451
452 let mut encoder = self
453 .device
454 .create_command_encoder(&etalon::CommandEncoderDescriptor {
455 label: Some("portal-compute-encoder"),
456 });
457 {
458 let mut pass = encoder.begin_compute_pass(&etalon::ComputePassDescriptor {
459 label: Some("portal-compute-pass"),
460 timestamp_writes: None,
461 });
462 pass.set_pipeline(&pipeline);
463 pass.set_bind_group(0, &bind_group, &[]);
464 pass.dispatch_workgroups(workgroups[0], workgroups[1], workgroups[2]);
465 }
466 if let (Some(staging), Some(rb)) = (staging.as_ref(), readback_binding) {
467 let src = binding_buffers
468 .iter()
469 .find(|(b, _)| *b == rb)
470 .map(|(_, buf)| buf)
471 .expect("readback binding validated before resource allocation");
472 encoder.copy_buffer_to_buffer(src, 0, staging, 0, copy_size as u64);
473 }
474 let submission = self.queue.submit(std::iter::once(encoder.finish()));
475 #[cfg(not(target_arch = "wasm32"))]
476 if submission.is_none() {
477 return Err(
478 "compute dispatch: native queue rejected the command submission".to_string(),
479 );
480 }
481 #[cfg(target_arch = "wasm32")]
482 let _ = submission;
483
484 let dispatch_id = self.compute.next_dispatch_id;
485 self.compute.next_dispatch_id = self.compute.next_dispatch_id.wrapping_add(1);
486 self.compute.pending = match staging {
487 Some(staging) => Some(PendingCompute {
488 readback: etalon_render::compute_readback::ComputeReadback::begin(
489 &staging,
490 readback_bytes,
491 etalon_wasm::readback::ready_worker(false),
492 )?,
493 dispatch_id,
494 }),
495 None => None,
496 };
497 Ok(dispatch_id)
498 }
499
500 pub fn compute_readback(&mut self) -> Option<Result<Vec<u8>, String>> {
504 let pending = self.compute.pending.as_mut()?;
505 let dispatch_id = pending.dispatch_id;
506 match pending.readback.poll(&self.device) {
507 Ok(None) => return None,
508 Ok(Some(true)) => {}
509 Ok(Some(false)) => {
510 self.compute.pending = None;
511 return Some(Err(format!(
512 "compute_readback: dispatch {dispatch_id}: map failed or stale"
513 )));
514 }
515 Err(error) => {
516 self.compute.pending = None;
517 return Some(Err(format!(
518 "compute_readback: dispatch {dispatch_id}: {error}"
519 )));
520 }
521 }
522 let mut out = vec![0; pending.readback.bytes()];
523 let result = pending.readback.copy_into(&mut out).map(|_| out);
524 self.compute.pending = None;
525 Some(result)
526 }
527 pub fn compute_pipeline_cache_size(&self) -> usize {
529 self.compute.cache.len()
530 }
531
532 pub fn compile_shader_module(&mut self, wgsl: &str, entry: &str) -> Result<u64, String> {
541 let _ = entry; let module = self
543 .device
544 .create_shader_module(etalon::ShaderModuleDescriptor {
545 label: Some("portal-compiled-shader"),
546 source: etalon::ShaderSource::Wgsl(wgsl.into()),
547 });
548 let id = {
550 let cache = &mut self.compute.shader_cache;
551 let mut value = Some(module);
552 let mut found = None;
553 for (i, slot) in cache.iter_mut().enumerate() {
554 if slot.is_none() {
555 found = Some(i);
556 *slot = value.take();
557 break;
558 }
559 }
560 match found {
561 Some(i) => i as u64,
562 None => {
563 let i = cache.len();
564 cache.push(value);
565 i as u64
566 }
567 }
568 };
569 Ok(id)
570 }
571
572 pub fn shader_cache_size(&self) -> usize {
574 self.compute
575 .shader_cache
576 .iter()
577 .filter(|s| s.is_some())
578 .count()
579 }
580}
581
582#[cfg(test)]
583#[cfg(not(target_arch = "wasm32"))]
584mod tests {
585 use super::*;
586
587 #[test]
588 fn compute_readback_alignment_checks_overflow() {
589 assert_eq!(align4(1), Some(4));
590 assert_eq!(align4(4), Some(4));
591 assert_eq!(align4(usize::MAX), None);
592 }
593
594 const VECTOR_ADD_WGSL: &str = r#"
595@group(0) @binding(0) var<storage, read> a: array<f32>;
596@group(0) @binding(1) var<storage, read> b: array<f32>;
597@group(0) @binding(2) var<storage, read_write> out: array<f32>;
598
599@compute @workgroup_size(1)
600fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
601 let i = gid.x;
602 out[i] = a[i] + b[i];
603}
604"#;
605
606 fn portal() -> Option<super::super::PortalGpu> {
607 if crate::gpu_context::try_shared_gpu().is_none() {
608 eprintln!("[compute_test] no GPU adapter — skipping");
609 return None;
610 }
611 super::super::PortalGpu::new_offscreen(32, 32, 256).ok()
612 }
613
614 #[test]
615 fn c_compute_vector_add_synchronous() {
616 let Some(mut p) = portal() else { return };
617 let a: [f32; 4] = [1.0, 2.0, 3.0, 4.0];
618 let b: [f32; 4] = [10.0, 20.0, 30.0, 40.0];
619 let a_bytes = bytemuck::cast_slice::<f32, u8>(&a).to_vec();
620 let b_bytes = bytemuck::cast_slice::<f32, u8>(&b).to_vec();
621 let bindings = vec![
622 ComputeBinding {
623 binding: 0,
624 kind: ComputeBufferKind::StorageRead,
625 data: &a_bytes,
626 },
627 ComputeBinding {
628 binding: 1,
629 kind: ComputeBufferKind::StorageRead,
630 data: &b_bytes,
631 },
632 ComputeBinding {
633 binding: 2,
634 kind: ComputeBufferKind::StorageReadWrite,
635 data: &[],
636 },
637 ];
638 let id = p
639 .compute_dispatch(VECTOR_ADD_WGSL, "main", [4, 1, 1], &bindings, Some(2), 16)
640 .expect("dispatch");
641 assert!(id > 0);
642 let out = p
643 .compute_readback()
644 .expect("readback pending")
645 .expect("readback ok");
646 let floats: Vec<f32> = bytemuck::cast_slice::<u8, f32>(&out).to_vec();
647 assert_eq!(floats, vec![11.0, 22.0, 33.0, 44.0]);
648 }
649
650 #[test]
651 fn c_compute_pipeline_cache_hit() {
652 let Some(mut p) = portal() else { return };
653 let a: [f32; 2] = [1.0, 2.0];
654 let b: [f32; 2] = [3.0, 4.0];
655 let ab = bytemuck::cast_slice::<f32, u8>(&a).to_vec();
656 let bb = bytemuck::cast_slice::<f32, u8>(&b).to_vec();
657 let bindings = vec![
658 ComputeBinding {
659 binding: 0,
660 kind: ComputeBufferKind::StorageRead,
661 data: &ab,
662 },
663 ComputeBinding {
664 binding: 1,
665 kind: ComputeBufferKind::StorageRead,
666 data: &bb,
667 },
668 ComputeBinding {
669 binding: 2,
670 kind: ComputeBufferKind::StorageReadWrite,
671 data: &[],
672 },
673 ];
674 p.compute_dispatch(VECTOR_ADD_WGSL, "main", [2, 1, 1], &bindings, Some(2), 8)
675 .expect("dispatch 1");
676 p.compute_readback().unwrap().unwrap();
677 assert_eq!(p.compute_pipeline_cache_size(), 1);
678 p.compute_dispatch(VECTOR_ADD_WGSL, "main", [2, 1, 1], &bindings, Some(2), 8)
680 .expect("dispatch 2");
681 assert_eq!(p.compute_pipeline_cache_size(), 1);
682 }
683
684 #[test]
685 fn c_compute_rejects_zero_workgroups() {
686 let Some(mut p) = portal() else { return };
687 let a = [1.0f32; 1];
688 let ab = bytemuck::cast_slice::<f32, u8>(&a).to_vec();
689 let bindings = vec![ComputeBinding {
690 binding: 0,
691 kind: ComputeBufferKind::StorageRead,
692 data: &ab,
693 }];
694 let err = p
695 .compute_dispatch(VECTOR_ADD_WGSL, "main", [0, 1, 1], &bindings, None, 0)
696 .unwrap_err();
697 assert!(err.contains("workgroups"), "got: {err}");
698 }
699
700 #[test]
716 fn vc3_render_frame_zero_alloc_after_warmup() {
717 use crate::specialized_libs::computational_geometry::allocation_counter;
718 let Some(mut p) = portal() else { return };
719 let telemetry = super::super::SystemTelemetry::default();
720
721 for i in 0..5 {
725 p.render(i as f32 * 0.1, &telemetry).expect("warmup frame");
726 }
727
728 let guard0 = allocation_counter::AllocGuard::begin("vc3_wgpu_baseline", true);
731 {
732 let enc = p
733 .device()
734 .create_command_encoder(&etalon::CommandEncoderDescriptor {
735 label: Some("vc3-baseline"),
736 });
737 p.queue().submit(std::iter::once(enc.finish()));
738 }
739 let _ = p.device().poll(etalon::PollType::wait_indefinitely());
740 let baseline = match guard0.check() {
741 Ok(()) => 0u64,
742 Err(msg) => msg
743 .split_whitespace()
744 .find(|s| s.chars().all(|c| c.is_ascii_digit()))
745 .and_then(|s| s.parse::<u64>().ok())
746 .unwrap_or(999),
747 };
748 eprintln!("vc3_wgpu_baseline (encoder+submit+poll): {baseline} heap allocs");
749
750 let guard1 = allocation_counter::AllocGuard::begin("vc3_belt_only", true);
757 {
758 let mut enc = p
759 .device()
760 .create_command_encoder(&etalon::CommandEncoderDescriptor {
761 label: Some("vc3-belt"),
762 });
763 let uniforms = super::super::AmbientUniforms {
764 time: 1.0,
765 view_width: 100.0,
766 view_height: 100.0,
767 _padding: 0.0,
768 };
769 let bytes = bytemuck::bytes_of(&uniforms);
770 p.uniform_belt_write_and_unmap(bytes);
771 p.uniform_belt_record_copy(&mut enc, &p.uniform_buf_test(), 0);
772 p.uniform_belt_advance();
773 p.queue().submit(std::iter::once(enc.finish()));
774 }
775 let belt_only = match guard1.check() {
776 Ok(()) => 0u64,
777 Err(msg) => msg
778 .split_whitespace()
779 .find(|s| s.chars().all(|c| c.is_ascii_digit()))
780 .and_then(|s| s.parse::<u64>().ok())
781 .unwrap_or(999),
782 };
783 eprintln!("vc3_belt_only (encoder+belt+submit): {belt_only} heap allocs");
784 let belt_overhead = belt_only.saturating_sub(baseline);
785 eprintln!("vc3 belt_overhead (wgpu map_async+poll internals): {belt_overhead} heap allocs");
786
787 let guard = allocation_counter::AllocGuard::begin("vc3_render_frame_steady_state", true);
789 p.render(1.0, &telemetry).expect("steady-state frame");
790 let result = guard.check();
791 let count = match &result {
792 Ok(()) => 0u64,
793 Err(msg) => msg
794 .split_whitespace()
795 .find(|s| s.chars().all(|c| c.is_ascii_digit()))
796 .and_then(|s| s.parse::<u64>().ok())
797 .unwrap_or(999),
798 };
799 eprintln!(
800 "vc3_render_frame_steady_state: {count} heap allocs (baseline: {baseline}, belt_only: {belt_only})"
801 );
802 let pass_overhead = count.saturating_sub(belt_only);
803 eprintln!(
804 "vc3 render_pass_overhead: {pass_overhead} heap allocs (wgpu command recording internals)"
805 );
806
807 assert!(
822 count <= 335,
823 "uniform belt should not increase allocations beyond the measured wgpu command-recording envelope of 335, got {count}"
824 );
825 }
826
827 #[test]
828 fn vc3_compute_dispatch_pooled_after_warmup() {
829 use crate::specialized_libs::computational_geometry::allocation_counter;
830 let Some(mut p) = portal() else { return };
831 let a: [f32; 4] = [1.0, 2.0, 3.0, 4.0];
832 let b: [f32; 4] = [10.0, 20.0, 30.0, 40.0];
833 let ab = bytemuck::cast_slice::<f32, u8>(&a).to_vec();
834 let bb = bytemuck::cast_slice::<f32, u8>(&b).to_vec();
835 let bindings = vec![
836 ComputeBinding {
837 binding: 0,
838 kind: ComputeBufferKind::StorageRead,
839 data: &ab,
840 },
841 ComputeBinding {
842 binding: 1,
843 kind: ComputeBufferKind::StorageRead,
844 data: &bb,
845 },
846 ComputeBinding {
847 binding: 2,
848 kind: ComputeBufferKind::StorageReadWrite,
849 data: &[],
850 },
851 ];
852
853 p.compute_dispatch(VECTOR_ADD_WGSL, "main", [4, 1, 1], &bindings, Some(2), 16)
857 .expect("warmup dispatch");
858 p.compute_readback().unwrap().unwrap();
859
860 p.compute_dispatch(VECTOR_ADD_WGSL, "main", [4, 1, 1], &bindings, Some(2), 16)
862 .expect("warmup dispatch 2");
863 p.compute_readback().unwrap().unwrap();
864
865 let guard = allocation_counter::AllocGuard::begin("vc3_compute_dispatch_pooled", true);
869 p.compute_dispatch(VECTOR_ADD_WGSL, "main", [4, 1, 1], &bindings, Some(2), 16)
870 .expect("pooled dispatch");
871 let result = guard.check();
872 let count = match &result {
873 Ok(()) => 0u64,
874 Err(msg) => msg
875 .split_whitespace()
876 .find(|s| s.chars().all(|c| c.is_ascii_digit()))
877 .and_then(|s| s.parse::<u64>().ok())
878 .unwrap_or(999),
879 };
880 eprintln!(
881 "vc3_compute_dispatch_pooled: {count} heap allocs (wgpu internals: encoder + compute pass + submit)"
882 );
883 assert!(
888 count < 115,
889 "resource pool should reduce from original ~115, got {count}"
890 );
891 }
892}