1use ::wgpu;
11use core::sync::atomic::{AtomicU64, AtomicU8, Ordering};
12use std::collections::VecDeque;
13use std::vec;
14use std::vec::Vec;
15
16use crate::arena::SmallVec;
17use crate::engine::VeloxEngine;
18use crate::motion::DrawOp;
19use crate::paint::ExternalTextureId;
20use crate::solver::Region;
21
22use super::interop::{
23 allocate_shared_texture, create_shared_fence, ExportedHandle, ExportedTextureAlloc,
24 ExternalSyncHandle, PlatformSharedFence,
25};
26use super::pipeline::WgpuRenderer;
27use super::window::PreparedWgpuContext;
28
29pub struct SharedSlot {
31 alloc: ExportedTextureAlloc,
32 ready_fence_val: AtomicU64,
33}
34
35impl SharedSlot {
36 #[inline]
38 pub fn texture(&self) -> &wgpu::Texture {
39 &self.alloc.texture
40 }
41
42 #[inline]
44 pub fn view(&self) -> &wgpu::TextureView {
45 &self.alloc.view
46 }
47
48 #[inline]
50 pub const fn handle(&self) -> ExportedHandle {
51 self.alloc.handle
52 }
53
54 #[inline]
56 pub fn ready_fence_value(&self) -> u64 {
57 self.ready_fence_val.load(Ordering::Acquire)
58 }
59}
60
61#[derive(Clone, Debug)]
63pub struct SharedFrameLease {
64 pub generation_id: u32,
66 pub slot_index: u8,
68 pub width: u32,
70 pub height: u32,
72 pub format: wgpu::TextureFormat,
74 pub handle: ExportedHandle,
76 pub sync_handle: ExternalSyncHandle,
78 pub fence_value: u64,
80 pub dirty_rects: SmallVec<Region, 8>,
82 pub is_fresh: bool,
84}
85
86struct RetiredPool {
88 generation_id: u32,
89 last_fence_val: u64,
90 in_use_by_host: bool,
91 _slots: [SharedSlot; 3],
92}
93
94#[inline(always)]
96const fn pack_mailbox(ready: u8, read: u8, write: u8, fresh: bool) -> u8 {
97 (ready & 0x3) | ((read & 0x3) << 2) | ((write & 0x3) << 4) | (if fresh { 1 << 6 } else { 0 })
98}
99
100#[inline(always)]
101const fn unpack_mailbox(state: u8) -> (u8, u8, u8, bool) {
102 (
103 state & 0x3,
104 (state >> 2) & 0x3,
105 (state >> 4) & 0x3,
106 (state & (1 << 6)) != 0,
107 )
108}
109
110pub struct WgpuSharedExportRenderer {
112 ctx: PreparedWgpuContext,
113 sdf_renderer: WgpuRenderer,
114 format: wgpu::TextureFormat,
115 width: u32,
116 height: u32,
117 clear_color: wgpu::Color,
118 canvas_tex: wgpu::Texture,
120 canvas_view: wgpu::TextureView,
121 slots: [SharedSlot; 3],
122 mailbox_state: AtomicU8,
124 shared_fence: PlatformSharedFence,
125 next_fence_val: AtomicU64,
126 generation_id: u32,
127 dirty_history: [SmallVec<Region, 8>; 2],
129 last_merged_dirty: SmallVec<Region, 8>,
130 force_full_sync: bool,
131 retired_pools: VecDeque<RetiredPool>,
132}
133
134impl WgpuSharedExportRenderer {
135 pub fn new(
140 width: u32,
141 height: u32,
142 adapter_luid: Option<[u8; 8]>,
143 device_uuid: Option<[u8; 16]>,
144 ) -> Option<Self> {
145 let ctx = PreparedWgpuContext::from_host_adapter_id(adapter_luid, device_uuid)?;
146 Some(Self::from_context(
147 ctx,
148 width,
149 height,
150 wgpu::TextureFormat::Bgra8Unorm,
151 ))
152 }
153
154 pub fn from_context(
156 mut ctx: PreparedWgpuContext,
157 width: u32,
158 height: u32,
159 format: wgpu::TextureFormat,
160 ) -> Self {
161 let w = width.max(1);
162 let h = height.max(1);
163 let sdf_renderer = ctx.take_or_create_renderer(format);
164 let luid = ctx.adapter_luid().unwrap_or([0u8; 8]);
165 let (canvas_tex, canvas_view) = Self::create_canvas(ctx.device(), w, h, format);
166 let slots = Self::create_slot_triple(ctx.device(), w, h, format, luid);
167 let shared_fence = create_shared_fence(ctx.device());
168
169 Self {
170 ctx,
171 sdf_renderer,
172 format,
173 width: w,
174 height: h,
175 clear_color: wgpu::Color::TRANSPARENT,
176 canvas_tex,
177 canvas_view,
178 slots,
179 mailbox_state: AtomicU8::new(pack_mailbox(0, 1, 2, false)),
180 shared_fence,
181 next_fence_val: AtomicU64::new(1),
182 generation_id: 1,
183 dirty_history: [SmallVec::new(), SmallVec::new()],
184 last_merged_dirty: SmallVec::new(),
185 force_full_sync: true,
186 retired_pools: VecDeque::new(),
187 }
188 }
189
190 fn create_canvas(
191 device: &wgpu::Device,
192 width: u32,
193 height: u32,
194 format: wgpu::TextureFormat,
195 ) -> (wgpu::Texture, wgpu::TextureView) {
196 let tex = device.create_texture(&wgpu::TextureDescriptor {
197 label: Some("velox_shared_exporter_canvas"),
198 size: wgpu::Extent3d {
199 width: width.max(1),
200 height: height.max(1),
201 depth_or_array_layers: 1,
202 },
203 mip_level_count: 1,
204 sample_count: 1,
205 dimension: wgpu::TextureDimension::D2,
206 format,
207 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
208 | wgpu::TextureUsages::COPY_SRC
209 | wgpu::TextureUsages::TEXTURE_BINDING,
210 view_formats: &[],
211 });
212 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
213 (tex, view)
214 }
215
216 fn create_slot_triple(
217 device: &wgpu::Device,
218 width: u32,
219 height: u32,
220 format: wgpu::TextureFormat,
221 luid: [u8; 8],
222 ) -> [SharedSlot; 3] {
223 [
224 SharedSlot {
225 alloc: allocate_shared_texture(device, width, height, format, luid),
226 ready_fence_val: AtomicU64::new(0),
227 },
228 SharedSlot {
229 alloc: allocate_shared_texture(device, width, height, format, luid),
230 ready_fence_val: AtomicU64::new(0),
231 },
232 SharedSlot {
233 alloc: allocate_shared_texture(device, width, height, format, luid),
234 ready_fence_val: AtomicU64::new(0),
235 },
236 ]
237 }
238
239 #[inline]
241 pub fn set_clear_color(&mut self, color: wgpu::Color) {
242 self.clear_color = color;
243 }
244
245 #[inline]
247 pub const fn generation_id(&self) -> u32 {
248 self.generation_id
249 }
250
251 #[inline]
253 pub const fn size(&self) -> (u32, u32) {
254 (self.width, self.height)
255 }
256
257 #[inline]
259 pub const fn format(&self) -> wgpu::TextureFormat {
260 self.format
261 }
262
263 #[inline]
265 pub fn device(&self) -> &wgpu::Device {
266 self.ctx.device()
267 }
268
269 #[inline]
271 pub fn queue(&self) -> &wgpu::Queue {
272 self.ctx.queue()
273 }
274
275 #[inline]
277 pub fn adapter_info(&self) -> (&str, &'static str) {
278 (self.ctx.adapter_name(), self.ctx.backend_name())
279 }
280
281 #[inline]
283 pub const fn adapter_luid(&self) -> Option<[u8; 8]> {
284 self.ctx.adapter_luid()
285 }
286
287 #[inline]
289 pub const fn device_uuid(&self) -> Option<[u8; 16]> {
290 self.ctx.device_uuid()
291 }
292
293 #[inline]
295 pub fn sync_handle(&self) -> ExternalSyncHandle {
296 self.shared_fence.export_handle()
297 }
298
299 #[inline]
301 pub fn renderer_mut(&mut self) -> &mut WgpuRenderer {
302 &mut self.sdf_renderer
303 }
304
305 #[inline]
307 pub fn register_external_texture(
308 &mut self,
309 view: wgpu::TextureView,
310 sampler: Option<wgpu::Sampler>,
311 ) -> ExternalTextureId {
312 self.sdf_renderer.register_external_texture(view, sampler)
313 }
314
315 #[inline]
317 pub fn update_external_texture(
318 &mut self,
319 id: ExternalTextureId,
320 view: wgpu::TextureView,
321 ) -> bool {
322 self.sdf_renderer.update_external_texture(id, view)
323 }
324
325 #[inline]
327 pub fn unregister_external_texture(&mut self, id: ExternalTextureId) -> bool {
328 self.sdf_renderer.unregister_external_texture(id)
329 }
330
331 #[inline]
333 pub fn retired_pool_count(&self) -> usize {
334 self.retired_pools.len()
335 }
336
337 pub fn resize(&mut self, width: u32, height: u32) {
339 let w = width.max(1);
340 let h = height.max(1);
341 if self.width == w && self.height == h {
342 return;
343 }
344 let luid = self.ctx.adapter_luid().unwrap_or([0u8; 8]);
345 let new_slots = Self::create_slot_triple(self.ctx.device(), w, h, self.format, luid);
346 let old_slots = core::mem::replace(&mut self.slots, new_slots);
347 let last_fence = self.next_fence_val.load(Ordering::Acquire).saturating_sub(1);
348 self.retired_pools.push_back(RetiredPool {
349 generation_id: self.generation_id,
350 last_fence_val: last_fence,
351 in_use_by_host: true,
352 _slots: old_slots,
353 });
354
355 let (ct, cv) = Self::create_canvas(self.ctx.device(), w, h, self.format);
356 self.canvas_tex = ct;
357 self.canvas_view = cv;
358 self.width = w;
359 self.height = h;
360 self.generation_id = self.generation_id.wrapping_add(1).max(1);
361 self.mailbox_state
362 .store(pack_mailbox(0, 1, 2, false), Ordering::Release);
363 self.dirty_history[0].clear();
364 self.dirty_history[1].clear();
365 self.last_merged_dirty.clear();
366 self.force_full_sync = true;
367 self.gc_retired_pools();
368 }
369
370 pub fn gc_retired_pools(&mut self) {
372 let completed = self.shared_fence.completed_value();
373 while let Some(front) = self.retired_pools.front() {
374 if !front.in_use_by_host && completed >= front.last_fence_val {
375 self.retired_pools.pop_front();
376 } else {
377 break;
378 }
379 }
380 }
381
382 fn merge_3_frame_dirty(&mut self, current_dirty: &[Region], sf: f32) -> SmallVec<Region, 8> {
384 let full = Region::new(0, 0, self.width as i16, self.height as i16);
385 let mut cur_phys: SmallVec<Region, 8> = SmallVec::new();
386 for &r in current_dirty {
387 if r.is_empty() {
388 continue;
389 }
390 let x0 = ((r.x as f32) * sf).floor().max(0.0) as i16;
391 let y0 = ((r.y as f32) * sf).floor().max(0.0) as i16;
392 let x1 = ((r.right() as f32) * sf).ceil().min(self.width as f32) as i16;
393 let y1 = ((r.bottom() as f32) * sf).ceil().min(self.height as f32) as i16;
394 if x1 > x0 && y1 > y0 {
395 let _ = cur_phys.push(Region::new(x0, y0, x1 - x0, y1 - y0));
396 }
397 }
398
399 let mut merged: SmallVec<Region, 8> = SmallVec::new();
400 if self.force_full_sync || cur_phys.is_empty() {
401 let _ = merged.push(full);
402 self.force_full_sync = false;
403 } else {
404 let mut push_or_union = |r: Region| {
405 if !merged.push(r) {
406 let mut u = merged[0];
408 let x0 = u.x.min(r.x);
409 let y0 = u.y.min(r.y);
410 let x1 = u.right().max(r.right());
411 let y1 = u.bottom().max(r.bottom());
412 u = Region::new(x0, y0, x1 - x0, y1 - y0);
413 merged[0] = u;
414 }
415 };
416 for &r in cur_phys.as_slice() {
417 push_or_union(r);
418 }
419 for &r in self.dirty_history[0].as_slice() {
420 push_or_union(r);
421 }
422 for &r in self.dirty_history[1].as_slice() {
423 push_or_union(r);
424 }
425 }
426
427 self.dirty_history[1] = self.dirty_history[0].clone();
428 self.dirty_history[0] = cur_phys;
429 self.last_merged_dirty = merged.clone();
430 merged
431 }
432
433 pub fn render_draw_ops(
435 &mut self,
436 ops: &[DrawOp<'_>],
437 viewport: Region,
438 scale_factor: f32,
439 dirty_regions: &[Region],
440 ) -> u64 {
441 let sf = scale_factor.clamp(0.5, 4.0);
442 let pw = ((viewport.w.max(1) as f32) * sf).round().max(1.0) as u32;
443 let ph = ((viewport.h.max(1) as f32) * sf).round().max(1.0) as u32;
444 if pw != self.width || ph != self.height {
445 self.resize(pw, ph);
446 }
447
448 let merged_dirty = self.merge_3_frame_dirty(dirty_regions, sf);
449
450 self.sdf_renderer.render_to_view(
452 self.ctx.device(),
453 self.ctx.queue(),
454 ops,
455 viewport,
456 sf,
457 &self.canvas_view,
458 self.width,
459 self.height,
460 self.clear_color,
461 );
462
463 let (_, _, write_idx, _) = unpack_mailbox(self.mailbox_state.load(Ordering::Acquire));
465 let dst_tex = &self.slots[write_idx as usize].alloc.texture;
466 let mut copy_enc =
467 self.ctx
468 .device()
469 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
470 label: Some("velox_shared_exporter_copy"),
471 });
472 for &r in merged_dirty.as_slice() {
473 let x = (r.x.max(0) as u32).min(self.width);
474 let y = (r.y.max(0) as u32).min(self.height);
475 let cw = (r.w.max(0) as u32).min(self.width.saturating_sub(x));
476 let ch = (r.h.max(0) as u32).min(self.height.saturating_sub(y));
477 if cw == 0 || ch == 0 {
478 continue;
479 }
480 copy_enc.copy_texture_to_texture(
481 wgpu::TexelCopyTextureInfo {
482 texture: &self.canvas_tex,
483 mip_level: 0,
484 origin: wgpu::Origin3d { x, y, z: 0 },
485 aspect: wgpu::TextureAspect::All,
486 },
487 wgpu::TexelCopyTextureInfo {
488 texture: dst_tex,
489 mip_level: 0,
490 origin: wgpu::Origin3d { x, y, z: 0 },
491 aspect: wgpu::TextureAspect::All,
492 },
493 wgpu::Extent3d {
494 width: cw,
495 height: ch,
496 depth_or_array_layers: 1,
497 },
498 );
499 }
500 self.ctx.queue().submit([copy_enc.finish()]);
501
502 let fence_val = self.next_fence_val.fetch_add(1, Ordering::AcqRel);
504 self.shared_fence
505 .signal_on_queue(self.ctx.device(), fence_val);
506 self.slots[write_idx as usize]
507 .ready_fence_val
508 .store(fence_val, Ordering::Release);
509
510 loop {
512 let cur = self.mailbox_state.load(Ordering::Acquire);
513 let (ready, read, write, _fresh) = unpack_mailbox(cur);
514 let next = pack_mailbox(write, read, ready, true);
515 if self
516 .mailbox_state
517 .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
518 .is_ok()
519 {
520 break;
521 }
522 }
523
524 self.gc_retired_pools();
525 fence_val
526 }
527
528 pub fn step_and_render(&mut self, engine: &mut VeloxEngine, dt_ms: u16) -> Option<u64> {
530 let mut dirty: SmallVec<Region, 8> = SmallVec::new();
531 for &r in engine.step_frame_dt(dt_ms) {
532 let _ = dirty.push(r);
533 }
534 if dirty.is_empty() && !self.force_full_sync {
535 return None;
536 }
537 let vp = engine.viewport_region();
538 let sf = engine.scale_factor();
539 let ops = engine.cached_draw_ops();
540 Some(self.render_draw_ops(ops, vp, sf, dirty.as_slice()))
541 }
542
543 pub fn acquire_shared_frame(&self) -> SharedFrameLease {
545 let (slot_idx, is_fresh) = loop {
546 let cur = self.mailbox_state.load(Ordering::Acquire);
547 let (ready, read, write, fresh) = unpack_mailbox(cur);
548 if !fresh {
549 break (read, false);
550 }
551 let next = pack_mailbox(read, ready, write, false);
552 if self
553 .mailbox_state
554 .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
555 .is_ok()
556 {
557 break (ready, true);
558 }
559 };
560
561 let slot = &self.slots[slot_idx as usize];
562 SharedFrameLease {
563 generation_id: self.generation_id,
564 slot_index: slot_idx,
565 width: self.width,
566 height: self.height,
567 format: self.format,
568 handle: slot.handle(),
569 sync_handle: self.shared_fence.export_handle(),
570 fence_value: slot.ready_fence_value(),
571 dirty_rects: self.last_merged_dirty.clone(),
572 is_fresh,
573 }
574 }
575
576 pub fn release_shared_frame(&mut self, generation_id: u32, _slot_index: u8) {
578 if generation_id != self.generation_id {
579 for pool in &mut self.retired_pools {
580 if pool.generation_id == generation_id {
581 pool.in_use_by_host = false;
582 }
583 }
584 self.gc_retired_pools();
585 }
586 }
587
588 pub fn wait_fence_cpu(&self, fence_value: u64, timeout_ms: u32) -> bool {
590 self.shared_fence
591 .wait_cpu(self.ctx.device(), fence_value, timeout_ms)
592 }
593
594 pub fn readback_slot_bytes(&self, slot_index: u8) -> Option<Vec<u8>> {
596 let slot = self.slots.get(slot_index as usize)?;
597 let fence_val = slot.ready_fence_value();
598 if fence_val > 0 {
599 let _ = self.wait_fence_cpu(fence_val, 3000);
600 }
601 let unpadded = self.width * 4;
602 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
603 let padded = unpadded.div_ceil(align) * align;
604 let rb = self.ctx.device().create_buffer(&wgpu::BufferDescriptor {
605 label: Some("velox_shared_slot_readback"),
606 size: (padded as u64) * (self.height as u64),
607 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
608 mapped_at_creation: false,
609 });
610 let mut enc =
611 self.ctx
612 .device()
613 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
614 label: Some("velox_shared_slot_readback_enc"),
615 });
616 enc.copy_texture_to_buffer(
617 wgpu::TexelCopyTextureInfo {
618 texture: slot.texture(),
619 mip_level: 0,
620 origin: wgpu::Origin3d::ZERO,
621 aspect: wgpu::TextureAspect::All,
622 },
623 wgpu::TexelCopyBufferInfo {
624 buffer: &rb,
625 layout: wgpu::TexelCopyBufferLayout {
626 offset: 0,
627 bytes_per_row: Some(padded),
628 rows_per_image: Some(self.height),
629 },
630 },
631 wgpu::Extent3d {
632 width: self.width,
633 height: self.height,
634 depth_or_array_layers: 1,
635 },
636 );
637 self.ctx.queue().submit([enc.finish()]);
638
639 let slice = rb.slice(..);
640 let (tx, rx) = std::sync::mpsc::channel();
641 slice.map_async(wgpu::MapMode::Read, move |res| {
642 let _ = tx.send(res);
643 });
644 let _ = self.ctx.device().poll(wgpu::PollType::wait_indefinitely());
645 rx.recv().ok()?.ok()?;
646
647 let mapped = slice.get_mapped_range().ok()?;
648 let mut out = vec![0u8; (self.width as usize) * (self.height as usize) * 4];
649 let row_bytes = (self.width as usize) * 4;
650 let stride = padded as usize;
651 for y in 0..(self.height as usize) {
652 let src = &mapped[y * stride..y * stride + row_bytes];
653 out[y * row_bytes..(y + 1) * row_bytes].copy_from_slice(src);
654 }
655 drop(mapped);
656 rb.unmap();
657 Some(out)
658 }
659}