Skip to main content

egui_pop_viewport/
tiles.rs

1//! The tile cache: what to ask the source for, what arrived, what is
2//! drawn, and what to forget when over budget.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! Each frame, for each side shown:
8//!
9//! 1. take what the source delivered (a tile answering a request no
10//!    longer wanted is dropped, a changed region marks its tiles stale)
11//!    and upload it, within the upload budget when one is set: the
12//!    tiles of the visible area first (proxy, then the view's scale,
13//!    then other scales), then the others nearest the view's centre;
14//!    the rest waits for the next frame, kept when the view moves;
15//! 2. want the proxy (the whole image at a power of two at or below the
16//!    fit scale) and, once the view has settled, the exact tiles of what
17//!    is visible at the view's scale (`min(zoom, 1)`, so below 100 % one
18//!    texel lands on one physical pixel);
19//! 3. ask for what is wanted and neither cached nor asked for, cancel what
20//!    was asked for and is no longer wanted;
21//! 4. draw the proxy, then the exact tiles over it; stale tiles stay on
22//!    screen until their replacements arrive;
23//! 5. evict the least recently drawn tiles past the budget, never one
24//!    drawn this frame.
25//!
26//! Tiles are textures of at most the device's largest texture side, so
27//! an image or a window larger than the GPU's limit is drawn whole.
28
29use std::collections::HashMap;
30use std::sync::Arc;
31use std::sync::atomic::{AtomicU64, Ordering};
32
33use egui::{Color32, ColorImage, Context, TextureHandle, TextureOptions};
34
35use crate::display::{self, DisplayTarget, DisplayTransform};
36use crate::source::{
37    Arrival, Body, CancelToken, Feed, Message, Pixels, Prep, Quality, Readout, RequestId, Scale,
38    Side, Stats, TileKey, TileRequest, TileSink, TileSource,
39};
40use crate::view::{Mapping, fit_zoom};
41
42/// The default side of a tile, in pixels.
43pub const TILE_SIZE: u32 = 256;
44
45/// The default texture budget, in bytes.
46pub const DEFAULT_BUDGET: usize = 256 << 20;
47
48/// The default time the view stays still before exact tiles are asked
49/// for, in seconds.
50pub const DEFAULT_SETTLE: f64 = 0.1;
51
52/// The coarsest proxy scale.
53pub const MIN_PROXY_SCALE: f64 = 1.0 / 64.0;
54
55static NEXT_TEXTURE: AtomicU64 = AtomicU64::new(1);
56
57/// A tile's texture.
58pub(crate) enum Texture {
59    /// An egui texture, sRGB 8 bits (display-ready pixels, or scene
60    /// pixels transformed on the CPU).
61    Egui(TextureHandle),
62    /// A texture of the GPU path, by id (scene pixels, transformed in
63    /// the shader).
64    Gpu(u64),
65}
66
67impl std::fmt::Debug for Texture {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            Texture::Egui(h) => write!(f, "Egui({:?})", h.id()),
71            Texture::Gpu(id) => write!(f, "Gpu({id})"),
72        }
73    }
74}
75
76#[derive(Debug)]
77struct Entry {
78    texture: Texture,
79    size: [u32; 2],
80    bytes: usize,
81    last_used: u64,
82    /// The frame it was uploaded in.
83    born: u64,
84    stale: bool,
85    /// Scene pixels transformed on the CPU: redone when the display
86    /// target or transform changes.
87    baked: bool,
88    /// A refused device tile's fallback pixels: asked for again when the
89    /// render device changes (read only with the `wgpu` feature).
90    #[cfg_attr(
91        not(feature = "wgpu"),
92        allow(
93            dead_code,
94            reason = "only the GPU path, behind the wgpu feature, reads it"
95        )
96    )]
97    fallback: bool,
98}
99
100#[derive(Debug)]
101struct Asked {
102    id: RequestId,
103    cancel: CancelToken,
104    quality: Quality,
105}
106
107/// A tile to draw: its texture and where it lands, in physical pixels
108/// (`[x0, y0, x1, y1]`, window coordinates).
109#[derive(Debug)]
110pub(crate) struct Draw<'a> {
111    pub texture: &'a Texture,
112    pub size: [u32; 2],
113    pub dst_px: [f64; 4],
114}
115
116/// A GPU path tile's pixels: scene floats (converted at the paint) or
117/// texels prepared by the delivering thread. Only the GPU path reads
118/// them: without the `wgpu` feature they are queued and never read.
119#[derive(Debug)]
120#[cfg_attr(
121    not(feature = "wgpu"),
122    allow(
123        dead_code,
124        reason = "only the GPU path, behind the wgpu feature, reads it"
125    )
126)]
127pub(crate) enum GpuData {
128    Scene(Vec<f32>),
129    Texels(Vec<u8>),
130    /// On the render device: bound, not copied.
131    #[cfg(feature = "wgpu")]
132    Device(Box<crate::device::DeviceTile>),
133}
134
135/// A tile for the GPU path: its texture id, size and pixels.
136pub(crate) type Upload = (u64, [u32; 2], GpuData);
137
138/// The GPU path's uploads and releases, waiting for the next paint.
139#[derive(Debug, Default)]
140pub(crate) struct GpuQueue {
141    pub uploads: Vec<Upload>,
142    pub frees: Vec<u64>,
143    /// What the paints copied and bound so far.
144    pub copied: Transfers,
145    /// The tile cache is dropped: `frees` holds every texture it had on
146    /// the GPU path, for the render state that bound them to release at
147    /// its next paint, whichever viewport paints.
148    pub closed: bool,
149}
150
151impl GpuQueue {
152    /// What a paint takes in: the uploads, less those released since they
153    /// were queued (a tile replaced within a frame: dropped here, with
154    /// what a device tile keeps alive), and the textures to release.
155    #[cfg_attr(
156        not(feature = "wgpu"),
157        allow(
158            dead_code,
159            reason = "only the GPU path, behind the wgpu feature, reads it"
160        )
161    )]
162    pub(crate) fn drain(&mut self) -> (Vec<Upload>, Vec<u64>) {
163        let frees = std::mem::take(&mut self.frees);
164        let mut uploads = std::mem::take(&mut self.uploads);
165        if !frees.is_empty() {
166            let freed: std::collections::HashSet<u64> = frees.iter().copied().collect();
167            uploads.retain(|u| !freed.contains(&u.0));
168        }
169        (uploads, frees)
170    }
171}
172
173/// Tile pixels copied from the CPU to the GPU, counted where the copy
174/// happens: an egui texture loaded (the CPU path), a GPU path texture
175/// written at the paint. Device tiles are bound in place and count as
176/// `bound`, with no byte. The draws' uniforms (a few hundred bytes a
177/// frame) are not tile pixels and are not counted.
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
179pub struct Transfers {
180    /// Bytes copied.
181    pub bytes: u64,
182    /// Tiles copied.
183    pub tiles: u64,
184    /// Device tiles bound, nothing copied.
185    pub bound: u64,
186}
187
188impl Transfers {
189    fn plus(self, o: Transfers) -> Transfers {
190        Transfers {
191            bytes: self.bytes + o.bytes,
192            tiles: self.tiles + o.tiles,
193            bound: self.bound + o.bound,
194        }
195    }
196
197    fn minus(self, o: Transfers) -> Transfers {
198        Transfers {
199            bytes: self.bytes.saturating_sub(o.bytes),
200            tiles: self.tiles.saturating_sub(o.tiles),
201            bound: self.bound.saturating_sub(o.bound),
202        }
203    }
204
205    /// Nothing copied.
206    pub fn is_zero_copy(&self) -> bool {
207        self.bytes == 0 && self.tiles == 0
208    }
209}
210
211/// How much a frame uploads at most: tiles and bytes (whichever is
212/// reached first; at least one tile a frame). What is left waits for the
213/// next frame, never dropped. [`UploadBudget::DEFAULT`] (8 MiB a frame)
214/// unless the viewport is told otherwise.
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub struct UploadBudget {
217    pub tiles: usize,
218    pub bytes: usize,
219}
220
221impl UploadBudget {
222    /// The default: 8 MiB a frame, sixteen 256-pixel tiles of the GPU
223    /// path's half floats or thirty-two of 8-bit RGBA. It bounds the
224    /// copy to the GPU at the render when a fast source (a cache, a GPU
225    /// pipeline) delivers a whole view at once; a source on worker
226    /// threads rarely reaches it.
227    pub const DEFAULT: UploadBudget = UploadBudget {
228        tiles: usize::MAX,
229        bytes: 8 << 20,
230    };
231
232    /// No limit: every tile arrived is uploaded in the frame that takes
233    /// it in (the behaviour before the budget existed).
234    pub const UNLIMITED: UploadBudget = UploadBudget {
235        tiles: usize::MAX,
236        bytes: usize::MAX,
237    };
238
239    /// At most `n` tiles a frame.
240    pub fn tiles(n: usize) -> UploadBudget {
241        UploadBudget {
242            tiles: n.max(1),
243            bytes: usize::MAX,
244        }
245    }
246
247    /// At most `n` bytes a frame (and at least one tile).
248    pub fn bytes(n: usize) -> UploadBudget {
249        UploadBudget {
250            tiles: usize::MAX,
251            bytes: n,
252        }
253    }
254
255    /// Whether it limits anything.
256    pub fn is_limited(&self) -> bool {
257        *self != UploadBudget::UNLIMITED
258    }
259}
260
261impl Default for UploadBudget {
262    fn default() -> Self {
263        UploadBudget::DEFAULT
264    }
265}
266
267/// A tile taken in and not uploaded yet.
268#[derive(Debug)]
269struct Pending {
270    size: [u32; 2],
271    body: Body,
272    /// Arrival order, to keep it among equals.
273    seq: u64,
274    /// A refused device tile's fallback pixels.
275    fallback: bool,
276}
277
278/// What the uploads of the last frame did.
279#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
280pub struct UploadReport {
281    /// Tiles uploaded.
282    pub tiles: usize,
283    /// Bytes they copy.
284    pub bytes: usize,
285    /// Tiles left for the next frames.
286    pub waiting: usize,
287    /// Exact tiles of the view uploaded in that frame and drawn.
288    pub fresh_exact_drawn: usize,
289}
290
291/// What the device allows, from the GPU path's install (or egui's
292/// limits on the CPU path).
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
294pub struct Device {
295    /// The largest texture side.
296    pub max_texture_side: u32,
297    /// Scene tiles go to the GPU path (installed).
298    pub gpu: bool,
299}
300
301/// The device of the windows of `ctx`: the GPU path's when installed,
302/// else egui's texture limit and the CPU path.
303pub(crate) fn device(ctx: &Context) -> Device {
304    #[cfg(feature = "wgpu")]
305    if let Some(d) = crate::gpu::installed(ctx) {
306        return d;
307    }
308    Device {
309        max_texture_side: ctx.input(|i| i.max_texture_side) as u32,
310        gpu: false,
311    }
312}
313
314/// The tile cache of one viewport state.
315#[derive(Debug)]
316pub(crate) struct Tiles {
317    pub feed: Feed,
318    entries: HashMap<(Side, TileKey), Entry>,
319    asked: HashMap<(Side, TileKey), Asked>,
320    next_id: u64,
321    frame: u64,
322    used: usize,
323    pub budget: usize,
324    /// The tile side in use: the one wanted, within the device's limit.
325    pub tile_size: u32,
326    /// The tile side wanted.
327    pub wanted_size: u32,
328    pub settle: f64,
329    pub stats: Arc<Stats>,
330    sizes: HashMap<Side, [u32; 2]>,
331    view_key: Option<[u64; 3]>,
332    view_since: f64,
333    /// Wanted exact tiles not on screen yet (or stale), last frame.
334    missing: usize,
335    pub readout: Option<Readout>,
336    /// The last error a source reported.
337    pub last_error: Option<String>,
338    pub gpu: Arc<std::sync::Mutex<GpuQueue>>,
339    /// Tiles taken in, waiting for their upload.
340    pending: HashMap<(Side, TileKey), Pending>,
341    next_seq: u64,
342    pub upload_budget: UploadBudget,
343    /// Tiles converted by the delivering thread.
344    pub prepare_on_worker: bool,
345    /// What the delivering threads convert with, and its stamp.
346    prep_key: Option<PrepKey>,
347    prep_stamp: u64,
348    pub report: UploadReport,
349    /// What the interface thread copied (egui textures).
350    cpu_copied: Transfers,
351    /// Everything copied, as of the start of this frame.
352    last_total: Transfers,
353    /// What the last whole frame copied: from the start of the frame
354    /// before to the start of this one, its paint included.
355    pub frame_transfers: Transfers,
356    /// The render device seen at the last frame's start.
357    #[cfg(feature = "wgpu")]
358    render_seen: Option<egui_wgpu::wgpu::Device>,
359}
360
361impl Drop for Tiles {
362    /// What the GPU path holds for this cache is released by the next
363    /// paint on the render state that bound it (with what device tiles
364    /// keep alive): the queue, closed, keeps the textures to release,
365    /// and that render state keeps the queue. Tiles waiting for their
366    /// paint are dropped now.
367    fn drop(&mut self) {
368        let ids: Vec<u64> = self
369            .entries
370            .values()
371            .filter_map(|e| match e.texture {
372                Texture::Gpu(id) => Some(id),
373                Texture::Egui(_) => None,
374            })
375            .collect();
376        let mut q = self
377            .gpu
378            .lock()
379            .unwrap_or_else(std::sync::PoisonError::into_inner);
380        q.uploads.clear();
381        q.frees.extend(ids);
382        q.closed = true;
383    }
384}
385
386/// A waiting tile's upload order: its class, its distance to the view's
387/// centre, its arrival.
388type Rank = (u8, f64, u64);
389
390/// What a preparation depends on.
391#[derive(Clone, Copy, Debug, PartialEq)]
392struct PrepKey {
393    transform: usize,
394    revision: u64,
395    target: DisplayTarget,
396    gpu: Option<bool>,
397}
398
399impl Default for Tiles {
400    fn default() -> Self {
401        Tiles {
402            feed: Feed::default(),
403            entries: HashMap::new(),
404            asked: HashMap::new(),
405            next_id: 1,
406            frame: 0,
407            used: 0,
408            budget: DEFAULT_BUDGET,
409            tile_size: TILE_SIZE,
410            wanted_size: TILE_SIZE,
411            settle: DEFAULT_SETTLE,
412            stats: Arc::default(),
413            sizes: HashMap::new(),
414            view_key: None,
415            view_since: 0.0,
416            missing: 0,
417            readout: None,
418            last_error: None,
419            gpu: Arc::default(),
420            pending: HashMap::new(),
421            next_seq: 0,
422            upload_budget: UploadBudget::DEFAULT,
423            prepare_on_worker: true,
424            prep_key: None,
425            prep_stamp: 0,
426            report: UploadReport::default(),
427            cpu_copied: Transfers::default(),
428            last_total: Transfers::default(),
429            frame_transfers: Transfers::default(),
430            #[cfg(feature = "wgpu")]
431            render_seen: None,
432        }
433    }
434}
435
436/// The proxy scale for an image in a view: the power of two at or below
437/// the fit scale, at most 1.
438pub fn proxy_scale(m: &Mapping) -> f64 {
439    let size = egui::vec2(
440        (m.rect_px[2] - m.rect_px[0]) as f32,
441        (m.rect_px[3] - m.rect_px[1]) as f32,
442    );
443    let fit = fit_zoom(m.image, size).min(1.0);
444    2f64.powf(fit.log2().floor()).clamp(MIN_PROXY_SCALE, 1.0)
445}
446
447/// The exact scale of a view: one texel per physical pixel below 100 %,
448/// the image's own pixels above.
449pub fn exact_scale(m: &Mapping) -> f64 {
450    m.zoom.min(1.0)
451}
452
453/// The scaled image's size at `scale`.
454pub fn scaled_size(image: [f64; 2], scale: f64) -> [i64; 2] {
455    [
456        ((image[0] * scale).ceil() as i64).max(1),
457        ((image[1] * scale).ceil() as i64).max(1),
458    ]
459}
460
461fn rects_meet(a: [f64; 4], b: [f64; 4]) -> bool {
462    a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3]
463}
464
465impl Tiles {
466    pub fn sink(&self, side: Side) -> TileSink {
467        self.feed.sink(side)
468    }
469
470    /// No request outstanding, nothing waiting for its upload, and every
471    /// wanted exact tile on screen.
472    pub fn complete(&self) -> bool {
473        self.asked.is_empty() && self.pending.is_empty() && self.missing == 0
474    }
475
476    /// Requests still waiting for an answer.
477    pub fn outstanding(&self) -> usize {
478        self.asked.len()
479    }
480
481    /// Everything copied so far (the GPU path's paints up to the last
482    /// one).
483    pub fn transfers(&self) -> Transfers {
484        let gpu = self
485            .gpu
486            .lock()
487            .unwrap_or_else(std::sync::PoisonError::into_inner)
488            .copied;
489        self.cpu_copied.plus(gpu)
490    }
491
492    /// Bytes of textures held.
493    pub fn used(&self) -> usize {
494        self.used
495    }
496
497    /// Tiles held.
498    pub fn len(&self) -> usize {
499        self.entries.len()
500    }
501
502    /// The image rectangle a tile covers, in image pixels.
503    fn tile_rect(&self, key: &TileKey) -> [f64; 4] {
504        let s = key.scale.get();
505        let t = f64::from(self.tile_size);
506        [
507            key.x as f64 * t / s,
508            key.y as f64 * t / s,
509            (key.x + 1) as f64 * t / s,
510            (key.y + 1) as f64 * t / s,
511        ]
512    }
513
514    /// Tells the delivering threads what to convert with (or that the
515    /// interface thread converts), when it changed.
516    fn update_prep(
517        &mut self,
518        ctx: &Context,
519        device: Device,
520        target: &DisplayTarget,
521        transform: &Arc<dyn DisplayTransform>,
522    ) {
523        if !self.prepare_on_worker {
524            if self.prep_key.take().is_some() {
525                self.feed.set_prep(None);
526            }
527            return;
528        }
529        #[cfg(feature = "wgpu")]
530        let gpu = device.gpu.then(|| crate::gpu::half_float(ctx));
531        #[cfg(not(feature = "wgpu"))]
532        let gpu = {
533            let _ = (ctx, device);
534            None
535        };
536        let key = PrepKey {
537            transform: Arc::as_ptr(transform).cast::<()>() as usize,
538            revision: transform.revision(),
539            target: *target,
540            gpu,
541        };
542        if self.prep_key == Some(key) {
543            return;
544        }
545        self.prep_key = Some(key);
546        self.prep_stamp += 1;
547        self.feed.set_prep(Some(Prep {
548            stamp: self.prep_stamp,
549            transform: transform.clone(),
550            target: *target,
551            gpu,
552        }));
553    }
554
555    /// Starts a frame: takes in what the sources sent and uploads it,
556    /// within the upload budget, the view's tiles first (`view`: the
557    /// mapping of this frame).
558    pub fn receive(
559        &mut self,
560        ctx: &Context,
561        device: Device,
562        target: &DisplayTarget,
563        transform: &Arc<dyn DisplayTransform>,
564        view: &Mapping,
565    ) {
566        // Every tile that arrived since the last frame, uploaded now (or
567        // within the budget).
568        profiling::scope!("pop.tiles.receive");
569        self.frame += 1;
570        self.missing = 0;
571        self.report = UploadReport::default();
572        let total = self.transfers();
573        self.frame_transfers = total.minus(self.last_total);
574        self.last_total = total;
575        self.feed.set_context(ctx);
576        #[cfg(feature = "wgpu")]
577        self.note_render(ctx);
578        let effective = self.wanted_size.min(device.max_texture_side).max(16);
579        if effective != self.tile_size {
580            self.tile_size = effective;
581            self.clear_all();
582        }
583        self.update_prep(ctx, device, target, transform);
584        while let Ok(m) = self.feed.rx.try_recv() {
585            if matches!(m, Message::Changed(..) | Message::Readout(_)) {
586                self.feed.backlog.taken();
587            }
588            match m {
589                Message::Tile(side, tile) => self.take(side, tile),
590                Message::Failed(side, id, error) => {
591                    self.last_error = Some(error);
592                    let k = self
593                        .asked
594                        .iter()
595                        .find(|(k, a)| k.0 == side && a.id == id)
596                        .map(|(k, _)| *k);
597                    if let Some(k) = k {
598                        self.asked.remove(&k);
599                        Stats::add(&self.stats.failed, 1);
600                    }
601                }
602                Message::Changed(side, region) => {
603                    Stats::add(&self.stats.changed, 1);
604                    self.invalidate(side, region);
605                }
606                #[cfg(feature = "wgpu")]
607                Message::Refused(error) => {
608                    Stats::add(&self.stats.refused, 1);
609                    self.last_error = Some(error);
610                }
611                Message::Readout(r) => self.readout = Some(r),
612            }
613        }
614        // Changes folded while the viewport was not drawn: the whole
615        // image changed.
616        let (whole, coalesced) = self.feed.backlog.take_folded();
617        Stats::add(&self.stats.coalesced, coalesced);
618        for side in whole {
619            Stats::add(&self.stats.changed, 1);
620            self.invalidate(side, None);
621        }
622        self.upload(ctx, device, target, transform.as_ref(), view);
623    }
624
625    /// A new render device (the GPU path installed, or installed again):
626    /// the fallback pixels of device tiles refused before are asked for
627    /// again, as device tiles, and shown until they arrive.
628    #[cfg(feature = "wgpu")]
629    fn note_render(&mut self, ctx: &Context) {
630        let now = crate::gpu::render_device(ctx).map(|r| r.device);
631        if now == self.render_seen {
632            return;
633        }
634        self.render_seen = now;
635        let before = self.pending.len();
636        self.pending.retain(|_, p| !p.fallback);
637        Stats::add(&self.stats.dropped, (before - self.pending.len()) as u64);
638        for e in self.entries.values_mut() {
639            if e.fallback {
640                e.stale = true;
641            }
642        }
643    }
644
645    /// A tile delivered: kept for its upload when still wanted.
646    fn take(&mut self, side: Side, tile: Arrival) {
647        let k = (side, tile.key);
648        if self.asked.get(&k).is_none_or(|a| a.id != tile.request) {
649            Stats::add(&self.stats.dropped, 1);
650            return;
651        }
652        self.asked.remove(&k);
653        self.next_seq += 1;
654        self.pending.insert(
655            k,
656            Pending {
657                size: tile.size,
658                body: tile.body,
659                seq: self.next_seq,
660                fallback: tile.fallback,
661            },
662        );
663    }
664
665    /// The upload order of a waiting tile: the visible area first (the
666    /// proxy, then the view's scale, then other scales), then the rest;
667    /// nearest the view's centre first within each.
668    fn priority(&self, key: &TileKey, view: &Mapping) -> (u8, f64) {
669        let r = self.tile_rect(key);
670        let centre = [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0];
671        let Some(visible) = view.visible() else {
672            return (3, 0.0);
673        };
674        let c = [
675            (visible[0] + visible[2]) / 2.0,
676            (visible[1] + visible[3]) / 2.0,
677        ];
678        let d = (centre[0] - c[0]).powi(2) + (centre[1] - c[1]).powi(2);
679        let scale = key.scale.get();
680        let class = if !rects_meet(r, visible) {
681            3
682        } else if scale == proxy_scale(view) {
683            0
684        } else if scale == exact_scale(view) {
685            1
686        } else {
687            2
688        };
689        (class, d)
690    }
691
692    /// Uploads what waits, within the budget; asks for another frame
693    /// when some is left.
694    fn upload(
695        &mut self,
696        ctx: &Context,
697        device: Device,
698        target: &DisplayTarget,
699        transform: &dyn DisplayTransform,
700        view: &Mapping,
701    ) {
702        if self.pending.is_empty() {
703            return;
704        }
705        let budget = self.upload_budget;
706        let mut order: Vec<(Rank, (Side, TileKey))> = self
707            .pending
708            .iter()
709            .map(|(k, p)| {
710                let (class, d) = if budget.is_limited() {
711                    self.priority(&k.1, view)
712                } else {
713                    (0, 0.0)
714                };
715                ((class, d, p.seq), *k)
716            })
717            .collect();
718        order.sort_by(|a, b| {
719            a.0.0
720                .cmp(&b.0.0)
721                .then(a.0.1.total_cmp(&b.0.1))
722                .then(a.0.2.cmp(&b.0.2))
723        });
724        let (mut tiles, mut bytes) = (0usize, 0usize);
725        for (_, k) in order {
726            let Some(p) = self.pending.get(&k) else {
727                continue;
728            };
729            let cost = p.body.upload_bytes(p.size, device.gpu);
730            if tiles > 0 && (tiles >= budget.tiles || bytes.saturating_add(cost) > budget.bytes) {
731                break;
732            }
733            let Some(p) = self.pending.remove(&k) else {
734                continue;
735            };
736            tiles += 1;
737            bytes += cost;
738            self.arrived(ctx, device, target, transform, k, p);
739        }
740        self.report.tiles = tiles;
741        self.report.bytes = bytes;
742        self.report.waiting = self.pending.len();
743        if !self.pending.is_empty() {
744            ctx.request_repaint();
745        }
746    }
747
748    fn arrived(
749        &mut self,
750        ctx: &Context,
751        device: Device,
752        target: &DisplayTarget,
753        transform: &dyn DisplayTransform,
754        k: (Side, TileKey),
755        tile: Pending,
756    ) {
757        let n = tile.size[0] as usize * tile.size[1] as usize;
758        let ok = match &tile.body {
759            Body::Raw(Pixels::Display(v)) => v.len() == n * 4,
760            Body::Raw(Pixels::Scene(v)) => v.len() == n * 4,
761            Body::Image { image, .. } => image.pixels.len() == n,
762            Body::Texels { .. } => true,
763            // Checked below, against the render device of this frame.
764            #[cfg(feature = "wgpu")]
765            Body::Device(_) => true,
766        };
767        if !ok || n == 0 {
768            Stats::add(&self.stats.failed, 1);
769            return;
770        }
771        let id = NEXT_TEXTURE.fetch_add(1, Ordering::Relaxed);
772        let current = self.prep_stamp;
773        let load = |image: ColorImage| {
774            ctx.load_texture(
775                format!("egui-pop-viewport-tile-{id}"),
776                image,
777                TextureOptions::NEAREST,
778            )
779        };
780        let (texture, bytes, baked, stale) = match tile.body {
781            Body::Raw(Pixels::Scene(data)) if device.gpu => {
782                self.gpu
783                    .lock()
784                    .unwrap_or_else(std::sync::PoisonError::into_inner)
785                    .uploads
786                    .push((id, tile.size, GpuData::Scene(data)));
787                (Texture::Gpu(id), n * 8, false, false)
788            }
789            Body::Texels { data, stamp } => {
790                if stamp != current || !device.gpu {
791                    // Prepared for a device since replaced: asked for
792                    // again.
793                    Stats::add(&self.stats.dropped, 1);
794                    return;
795                }
796                self.gpu
797                    .lock()
798                    .unwrap_or_else(std::sync::PoisonError::into_inner)
799                    .uploads
800                    .push((id, tile.size, GpuData::Texels(data)));
801                (Texture::Gpu(id), n * 8, false, false)
802            }
803            #[cfg(feature = "wgpu")]
804            Body::Device(dt) => {
805                // The device may have changed since the source checked:
806                // refused, the tile is dropped (what it keeps with it,
807                // its fallback not called: never on the interface
808                // thread) and asked for again, the source checking it
809                // against the device of now.
810                let render = crate::gpu::render_device(ctx);
811                if let Err(e) = dt.check(render.as_ref(), tile.size) {
812                    Stats::add(&self.stats.refused, 1);
813                    self.last_error = Some(format!("device tile refused: {e}"));
814                    // Asked for since it was neither held fresh nor asked
815                    // for: the next request pass asks again (an older
816                    // tile there, stale, stays on screen until then).
817                    drop(dt);
818                    ctx.request_repaint();
819                    return;
820                }
821                Stats::add(&self.stats.device, 1);
822                let bytes = dt.footprint(tile.size);
823                self.gpu
824                    .lock()
825                    .unwrap_or_else(std::sync::PoisonError::into_inner)
826                    .uploads
827                    .push((id, tile.size, GpuData::Device(dt)));
828                (Texture::Gpu(id), bytes, false, false)
829            }
830            Body::Image {
831                image,
832                baked,
833                stamp,
834            } => {
835                profiling::scope!("pop.tiles.upload");
836                // Transformed with a transform since replaced: shown
837                // until its replacement arrives.
838                let stale = baked && stamp != current;
839                self.cpu_copied.bytes += (n * 4) as u64;
840                self.cpu_copied.tiles += 1;
841                (Texture::Egui(load(image)), n * 4, baked, stale)
842            }
843            Body::Raw(pixels) => {
844                profiling::scope!("pop.tiles.upload");
845                let baked = matches!(pixels, Pixels::Scene(_));
846                let image = match pixels {
847                    Pixels::Display(bytes) => ColorImage::from_rgba_unmultiplied(
848                        [tile.size[0] as usize, tile.size[1] as usize],
849                        &bytes,
850                    ),
851                    Pixels::Scene(data) => {
852                        let mut out = vec![Color32::BLACK; n];
853                        display::apply_cpu(transform, target, &data, &mut out);
854                        ColorImage::new([tile.size[0] as usize, tile.size[1] as usize], out)
855                    }
856                };
857                self.cpu_copied.bytes += (n * 4) as u64;
858                self.cpu_copied.tiles += 1;
859                (Texture::Egui(load(image)), n * 4, baked, false)
860            }
861        };
862        Stats::add(&self.stats.delivered, 1);
863        if let Some(old) = self.entries.remove(&k) {
864            self.release(old);
865        }
866        self.used += bytes;
867        self.entries.insert(
868            k,
869            Entry {
870                texture,
871                size: tile.size,
872                bytes,
873                last_used: self.frame,
874                born: self.frame,
875                stale,
876                baked,
877                fallback: tile.fallback,
878            },
879        );
880    }
881
882    /// Marks the tiles transformed on the CPU stale (a new display
883    /// target or transform): they are asked for again, and stay on
884    /// screen until then.
885    pub fn rebake(&mut self) {
886        for e in self.entries.values_mut() {
887            if e.baked {
888                e.stale = true;
889            }
890        }
891    }
892
893    fn release(&mut self, e: Entry) {
894        self.used = self.used.saturating_sub(e.bytes);
895        if let Texture::Gpu(id) = e.texture {
896            self.gpu
897                .lock()
898                .unwrap_or_else(std::sync::PoisonError::into_inner)
899                .frees
900                .push(id);
901        }
902    }
903
904    fn invalidate(&mut self, side: Side, region: Option<[f64; 4]>) {
905        let hit = |r: [f64; 4]| region.is_none_or(|reg| rects_meet(r, reg));
906        // Waiting tiles there show the image as it was: dropped, asked
907        // for again.
908        let waiting: Vec<_> = self
909            .pending
910            .keys()
911            .filter(|k| k.0 == side)
912            .copied()
913            .collect();
914        for k in waiting {
915            if hit(self.tile_rect(&k.1)) {
916                self.pending.remove(&k);
917                Stats::add(&self.stats.dropped, 1);
918            }
919        }
920        let keys: Vec<_> = self
921            .entries
922            .keys()
923            .filter(|k| k.0 == side)
924            .copied()
925            .collect();
926        for k in keys {
927            if hit(self.tile_rect(&k.1))
928                && let Some(e) = self.entries.get_mut(&k)
929            {
930                e.stale = true;
931            }
932        }
933        let asked: Vec<_> = self.asked.keys().filter(|k| k.0 == side).copied().collect();
934        for k in asked {
935            if hit(self.tile_rect(&k.1))
936                && let Some(a) = self.asked.remove(&k)
937            {
938                a.cancel.cancel();
939                Stats::add(&self.stats.cancelled, 1);
940            }
941        }
942    }
943
944    fn clear_side(&mut self, side: Side) {
945        self.pending.retain(|k, _| k.0 != side);
946        let keys: Vec<_> = self
947            .entries
948            .keys()
949            .filter(|k| k.0 == side)
950            .copied()
951            .collect();
952        for k in keys {
953            if let Some(e) = self.entries.remove(&k) {
954                self.release(e);
955            }
956        }
957        let asked: Vec<_> = self.asked.keys().filter(|k| k.0 == side).copied().collect();
958        for k in asked {
959            if let Some(a) = self.asked.remove(&k) {
960                a.cancel.cancel();
961                Stats::add(&self.stats.cancelled, 1);
962            }
963        }
964    }
965
966    fn clear_all(&mut self) {
967        self.clear_side(Side::After);
968        self.clear_side(Side::Before);
969    }
970
971    /// Notes the view; exact tiles wait until it has been still for
972    /// `settle` seconds.
973    pub fn note_view(&mut self, m: &Mapping, now: f64) -> bool {
974        let key = [
975            m.zoom.to_bits(),
976            m.origin[0].to_bits(),
977            m.origin[1].to_bits(),
978        ];
979        if self.view_key != Some(key) {
980            self.view_key = Some(key);
981            self.view_since = now;
982        }
983        now - self.view_since >= self.settle
984    }
985
986    /// When the view will have settled, if it has not.
987    pub fn settles_in(&self, now: f64) -> Option<f64> {
988        let left = self.settle - (now - self.view_since);
989        (left > 0.0).then_some(left)
990    }
991
992    /// The tiles of one level covering `region` (image pixels).
993    fn keys(&self, image: [f64; 2], scale: f64, region: [f64; 4]) -> Vec<TileKey> {
994        let t = f64::from(self.tile_size);
995        let size = scaled_size(image, scale);
996        let tiles = [
997            (size[0] as f64 / t).ceil() as i64,
998            (size[1] as f64 / t).ceil() as i64,
999        ];
1000        let x0 = ((region[0] * scale / t).floor() as i64).clamp(0, tiles[0]);
1001        let y0 = ((region[1] * scale / t).floor() as i64).clamp(0, tiles[1]);
1002        let x1 = ((region[2] * scale / t).ceil() as i64).clamp(0, tiles[0]);
1003        let y1 = ((region[3] * scale / t).ceil() as i64).clamp(0, tiles[1]);
1004        let mut keys = Vec::new();
1005        for y in y0..y1 {
1006            for x in x0..x1 {
1007                keys.push(TileKey {
1008                    scale: Scale::new(scale),
1009                    x,
1010                    y,
1011                });
1012            }
1013        }
1014        // Nearest the centre first.
1015        let c = [(x0 + x1) as f64 / 2.0, (y0 + y1) as f64 / 2.0];
1016        keys.sort_by(|a, b| {
1017            let d =
1018                |k: &TileKey| (k.x as f64 + 0.5 - c[0]).powi(2) + (k.y as f64 + 0.5 - c[1]).powi(2);
1019            d(a).total_cmp(&d(b))
1020        });
1021        keys
1022    }
1023
1024    /// Asks a source for what one side needs, and returns what to draw,
1025    /// proxy first.
1026    pub fn frame(
1027        &mut self,
1028        side: Side,
1029        source: &dyn TileSource,
1030        m: &Mapping,
1031        settled: bool,
1032    ) -> Vec<Draw<'_>> {
1033        profiling::scope!("pop.tiles.frame");
1034        let Some(size) = source.size() else {
1035            self.clear_side(side);
1036            return Vec::new();
1037        };
1038        if self.sizes.get(&side) != Some(&size) {
1039            self.clear_side(side);
1040            self.sizes.insert(side, size);
1041        }
1042        let image = [f64::from(size[0]), f64::from(size[1])];
1043        // Nothing of the image in view: no exact tile wanted (the
1044        // proxy is still asked for, to be ready).
1045        let visible = m.visible().unwrap_or([0.0, 0.0, 0.0, 0.0]);
1046        let p = proxy_scale(m);
1047        let s = exact_scale(m);
1048        let whole = [0.0, 0.0, image[0], image[1]];
1049        let mut wanted: Vec<(TileKey, Quality)> = Vec::new();
1050        let exact_keys = if settled || s == p {
1051            self.keys(image, s, visible)
1052        } else {
1053            Vec::new()
1054        };
1055        if s != p {
1056            wanted.extend(
1057                self.keys(image, p, whole)
1058                    .into_iter()
1059                    .map(|k| (k, Quality::Proxy)),
1060            );
1061        }
1062        wanted.extend(exact_keys.iter().map(|k| (*k, Quality::Exact)));
1063
1064        // Cancel exact requests no longer wanted (proxies stay useful).
1065        let keep: std::collections::HashSet<TileKey> = wanted.iter().map(|w| w.0).collect();
1066        let gone: Vec<_> = self
1067            .asked
1068            .iter()
1069            .filter(|(k, a)| k.0 == side && a.quality == Quality::Exact && !keep.contains(&k.1))
1070            .map(|(k, _)| *k)
1071            .collect();
1072        for k in gone {
1073            if let Some(a) = self.asked.remove(&k) {
1074                a.cancel.cancel();
1075                Stats::add(&self.stats.cancelled, 1);
1076            }
1077        }
1078
1079        // Ask for what is neither held (fresh) nor asked for.
1080        let t = i64::from(self.tile_size);
1081        let scaled = |scale: f64| scaled_size(image, scale);
1082        let mut batch = Vec::new();
1083        for (key, quality) in &wanted {
1084            let k = (side, *key);
1085            let fresh = self.entries.get(&k).is_some_and(|e| !e.stale);
1086            if fresh || self.asked.contains_key(&k) || self.pending.contains_key(&k) {
1087                continue;
1088            }
1089            let full = scaled(key.scale.get());
1090            let origin = [key.x * t, key.y * t];
1091            let w = (full[0] - origin[0]).min(t).max(0) as u32;
1092            let h = (full[1] - origin[1]).min(t).max(0) as u32;
1093            if w == 0 || h == 0 {
1094                continue;
1095            }
1096            let id = RequestId(self.next_id);
1097            self.next_id += 1;
1098            let cancel = CancelToken::default();
1099            self.asked.insert(
1100                k,
1101                Asked {
1102                    id,
1103                    cancel: cancel.clone(),
1104                    quality: *quality,
1105                },
1106            );
1107            batch.push(TileRequest {
1108                id,
1109                key: *key,
1110                quality: *quality,
1111                origin,
1112                size: [w, h],
1113                cancel,
1114            });
1115        }
1116        if !batch.is_empty() {
1117            Stats::add(&self.stats.requested, batch.len() as u64);
1118            source.request(batch);
1119        }
1120        self.missing += exact_keys
1121            .iter()
1122            .filter(|k| self.entries.get(&(side, **k)).is_none_or(|e| e.stale))
1123            .count()
1124            + usize::from(!settled && s != p);
1125
1126        // Draw: the proxy under, the exact tiles over.
1127        let frame = self.frame;
1128        let mut draws_keys: Vec<(Side, TileKey)> = Vec::new();
1129        if s != p {
1130            for key in self.keys(image, p, visible) {
1131                if self.entries.contains_key(&(side, key)) {
1132                    draws_keys.push((side, key));
1133                }
1134            }
1135        }
1136        for key in self.keys(image, s, visible) {
1137            if self.entries.contains_key(&(side, key)) {
1138                draws_keys.push((side, key));
1139            }
1140        }
1141        let exact = Scale::new(s);
1142        for k in &draws_keys {
1143            if let Some(e) = self.entries.get_mut(k) {
1144                e.last_used = frame;
1145                if e.born == frame && k.1.scale == exact {
1146                    self.report.fresh_exact_drawn += 1;
1147                }
1148            }
1149        }
1150        let tile = f64::from(self.tile_size);
1151        draws_keys
1152            .into_iter()
1153            .filter_map(|k| {
1154                let e = self.entries.get(&k)?;
1155                let scale = k.1.scale.get();
1156                let x0 = k.1.x as f64 * tile / scale;
1157                let y0 = k.1.y as f64 * tile / scale;
1158                let a = m.image_to_px([x0, y0]);
1159                let b = m.image_to_px([
1160                    x0 + f64::from(e.size[0]) / scale,
1161                    y0 + f64::from(e.size[1]) / scale,
1162                ]);
1163                Some(Draw {
1164                    texture: &e.texture,
1165                    size: e.size,
1166                    dst_px: [a[0], a[1], b[0], b[1]],
1167                })
1168            })
1169            .collect()
1170    }
1171
1172    /// Evicts the least recently drawn tiles past the budget; never one
1173    /// drawn this frame.
1174    pub fn evict(&mut self) {
1175        if self.used <= self.budget {
1176            return;
1177        }
1178        let mut old: Vec<_> = self
1179            .entries
1180            .iter()
1181            .filter(|(_, e)| e.last_used < self.frame)
1182            .map(|(k, e)| (e.last_used, *k))
1183            .collect();
1184        old.sort();
1185        for (_, k) in old {
1186            if self.used <= self.budget {
1187                break;
1188            }
1189            if let Some(e) = self.entries.remove(&k) {
1190                self.release(e);
1191                Stats::add(&self.stats.evicted, 1);
1192            }
1193        }
1194    }
1195}
1196
1197#[cfg(all(test, feature = "wgpu"))]
1198mod device_tests {
1199    //! Device tiles through the cache, on wgpu's stub device (no GPU):
1200    //! what a tile keeps alive, where its fallback runs, and the render
1201    //! device read when it is needed.
1202
1203    use std::sync::atomic::AtomicUsize;
1204    use std::sync::{Arc, Mutex};
1205    use std::thread::ThreadId;
1206
1207    use egui::{Rect, pos2, vec2};
1208    use egui_wgpu::wgpu;
1209
1210    use super::*;
1211    use crate::device::DeviceTile;
1212    use crate::display::LinearSrgb;
1213    use crate::view::View;
1214
1215    fn stub_device() -> wgpu::Device {
1216        wgpu::Device::noop(&wgpu::DeviceDescriptor::default()).0
1217    }
1218
1219    /// Two stub devices of one instance (stub devices of two instances
1220    /// may compare equal).
1221    fn two_stub_devices() -> (wgpu::Device, wgpu::Device) {
1222        fn ready<T>(f: impl std::future::Future<Output = T>) -> T {
1223            let mut f = std::pin::pin!(f);
1224            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
1225            match f.as_mut().poll(&mut cx) {
1226                std::task::Poll::Ready(v) => v,
1227                std::task::Poll::Pending => panic!("the stub backend answers at once"),
1228            }
1229        }
1230        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
1231            backends: wgpu::Backends::NOOP,
1232            backend_options: wgpu::BackendOptions {
1233                noop: wgpu::NoopBackendOptions::enabled(),
1234                ..Default::default()
1235            },
1236            ..wgpu::InstanceDescriptor::new_without_display_handle()
1237        });
1238        let adapter = ready(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
1239            .expect("the stub adapter");
1240        let device = || {
1241            ready(adapter.request_device(&wgpu::DeviceDescriptor::default()))
1242                .expect("a stub device")
1243                .0
1244        };
1245        let (a, b) = (device(), device());
1246        assert!(a != b);
1247        (a, b)
1248    }
1249
1250    /// Counts the values alive: one more made, one less dropped.
1251    struct Token(Arc<AtomicUsize>);
1252
1253    impl Token {
1254        fn new(live: &Arc<AtomicUsize>) -> Token {
1255            live.fetch_add(1, Ordering::SeqCst);
1256            Token(live.clone())
1257        }
1258    }
1259
1260    impl Drop for Token {
1261        fn drop(&mut self) {
1262            self.0.fetch_sub(1, Ordering::SeqCst);
1263        }
1264    }
1265
1266    /// A 64-pixel image (one tile), delivered from a worker thread as a
1267    /// texture on `device`, keeping a token, with a fallback that notes
1268    /// the thread it runs on.
1269    struct Source {
1270        sink: TileSink,
1271        device: wgpu::Device,
1272        live: Arc<AtomicUsize>,
1273        requests: Arc<AtomicUsize>,
1274        fallbacks: Arc<Mutex<Vec<ThreadId>>>,
1275    }
1276
1277    impl Source {
1278        fn new(sink: TileSink, device: wgpu::Device) -> Source {
1279            Source {
1280                sink,
1281                device,
1282                live: Arc::default(),
1283                requests: Arc::default(),
1284                fallbacks: Arc::default(),
1285            }
1286        }
1287
1288        fn live(&self) -> usize {
1289            self.live.load(Ordering::SeqCst)
1290        }
1291
1292        fn fallback_threads(&self) -> Vec<ThreadId> {
1293            self.fallbacks.lock().unwrap().clone()
1294        }
1295    }
1296
1297    impl TileSource for Source {
1298        fn size(&self) -> Option<[u32; 2]> {
1299            Some([64, 64])
1300        }
1301
1302        fn request(&self, requests: Vec<TileRequest>) {
1303            self.requests.fetch_add(requests.len(), Ordering::SeqCst);
1304            std::thread::scope(|s| {
1305                s.spawn(|| {
1306                    for r in requests {
1307                        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
1308                            label: None,
1309                            size: wgpu::Extent3d {
1310                                width: r.size[0],
1311                                height: r.size[1],
1312                                depth_or_array_layers: 1,
1313                            },
1314                            mip_level_count: 1,
1315                            sample_count: 1,
1316                            dimension: wgpu::TextureDimension::D2,
1317                            format: wgpu::TextureFormat::Rgba16Float,
1318                            usage: wgpu::TextureUsages::TEXTURE_BINDING,
1319                            view_formats: &[],
1320                        });
1321                        let fallbacks = self.fallbacks.clone();
1322                        let n = (r.size[0] * r.size[1] * 4) as usize;
1323                        let tile = DeviceTile::texture(&self.device, texture)
1324                            .keep(Token::new(&self.live))
1325                            .fallback(move || {
1326                                fallbacks.lock().unwrap().push(std::thread::current().id());
1327                                Some(Pixels::Scene(vec![0.5; n]))
1328                            });
1329                        self.sink.deliver_device(&r, tile);
1330                    }
1331                });
1332            });
1333        }
1334    }
1335
1336    struct Bench {
1337        ctx: Context,
1338        tiles: Tiles,
1339        mapping: Mapping,
1340        transform: Arc<dyn DisplayTransform>,
1341    }
1342
1343    impl Bench {
1344        fn new() -> Bench {
1345            let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(100.0, 100.0));
1346            Bench {
1347                ctx: Context::default(),
1348                tiles: Tiles::default(),
1349                mapping: Mapping::new(&View::actual([32.0, 32.0]), [64.0, 64.0], rect, 1.0),
1350                transform: Arc::new(LinearSrgb),
1351            }
1352        }
1353
1354        /// One frame: take in what arrived, then ask for what is wanted.
1355        fn step(&mut self, source: &Source) {
1356            let gpu = crate::gpu::render_device(&self.ctx).is_some();
1357            let device = Device {
1358                max_texture_side: 8192,
1359                gpu,
1360            };
1361            self.tiles.receive(
1362                &self.ctx,
1363                device,
1364                &DisplayTarget::default(),
1365                &self.transform,
1366                &self.mapping,
1367            );
1368            let _ = self
1369                .tiles
1370                .frame(Side::After, source, &self.mapping, true)
1371                .len();
1372        }
1373
1374        /// What the next paint does with the queue: binds the uploads
1375        /// (held, returned) and releases the rest.
1376        fn paint(&self) -> Vec<Upload> {
1377            self.tiles.gpu.lock().unwrap().drain().0
1378        }
1379
1380        fn stat(&self, name: &str) -> u64 {
1381            self.tiles
1382                .stats
1383                .snapshot()
1384                .iter()
1385                .find(|(k, _)| *k == name)
1386                .map_or(0, |(_, v)| *v)
1387        }
1388    }
1389
1390    #[test]
1391    fn what_a_device_tile_keeps_lives_as_long_as_the_tile() {
1392        let mut b = Bench::new();
1393        let device = stub_device();
1394        crate::gpu::set_render_device(&b.ctx, &device);
1395        let source = Source::new(b.tiles.feed.sink(Side::After), device);
1396        b.step(&source);
1397        assert_eq!(source.live(), 1, "delivered, waiting to be taken in");
1398        b.step(&source);
1399        assert_eq!(b.stat("device"), 1);
1400        let bound = b.paint();
1401        assert_eq!(bound.len(), 1);
1402        assert_eq!(source.live(), 1, "held with the binding");
1403        // The image changed: the tile is asked for again, the new one
1404        // replaces it in the frame that takes it in.
1405        source.sink.changed(None);
1406        b.step(&source);
1407        assert_eq!(source.live(), 2, "the shown tile and its replacement");
1408        b.step(&source);
1409        assert_eq!(b.stat("device"), 2);
1410        let (uploads, frees) = b.tiles.gpu.lock().unwrap().drain();
1411        assert_eq!(frees, vec![bound[0].0], "the replaced tile is released");
1412        // The paint drops the released binding with what it keeps.
1413        drop(bound);
1414        assert_eq!(source.live(), 1);
1415        // Replaced twice before a paint: the upload released before it
1416        // was bound is dropped by the paint, with what it keeps.
1417        source.sink.changed(None);
1418        b.step(&source);
1419        b.step(&source);
1420        source.sink.changed(None);
1421        b.step(&source);
1422        b.step(&source);
1423        assert_eq!(source.live(), 3, "one bound, two queued");
1424        let next = b.paint();
1425        assert_eq!(next.len(), 1);
1426        assert_eq!(source.live(), 2);
1427        drop(uploads);
1428        assert_eq!(source.live(), 1);
1429        // The viewport's state dropped: the tiles waiting for a paint are
1430        // dropped at once, the bound ones released by the next paint.
1431        source.sink.changed(None);
1432        b.step(&source);
1433        b.step(&source);
1434        assert_eq!(source.live(), 2, "the bound tile and one queued");
1435        drop(b);
1436        assert_eq!(source.live(), 1, "the queued one dropped");
1437        drop(next);
1438        assert_eq!(source.live(), 0);
1439    }
1440
1441    #[test]
1442    fn a_tile_refused_at_take_in_is_asked_again_and_falls_back_off_the_interface_thread() {
1443        let mut b = Bench::new();
1444        let (first, second) = two_stub_devices();
1445        crate::gpu::set_render_device(&b.ctx, &first);
1446        let source = Source::new(b.tiles.feed.sink(Side::After), first);
1447        // Delivered and checked against the first device.
1448        b.step(&source);
1449        assert_eq!(source.requests.load(Ordering::SeqCst), 1);
1450        assert_eq!(b.stat("refused"), 0);
1451        // The render device changes before the interface takes it in.
1452        crate::gpu::set_render_device(&b.ctx, &second);
1453        b.step(&source);
1454        assert_eq!(b.stat("refused"), 1, "at take-in");
1455        assert_eq!(
1456            source.requests.load(Ordering::SeqCst),
1457            2,
1458            "asked for again in the same frame"
1459        );
1460        let main = std::thread::current().id();
1461        let threads = source.fallback_threads();
1462        assert_eq!(threads.len(), 1, "the fallback ran once");
1463        assert!(threads.iter().all(|t| *t != main), "never on this thread");
1464        assert_eq!(source.live(), 0, "both refused tiles dropped");
1465        b.step(&source);
1466        assert_eq!(b.stat("refused"), 2, "then on the worker");
1467        assert_eq!(b.tiles.entries.len(), 1, "the fallback pixels shown");
1468        assert!(
1469            b.tiles
1470                .last_error
1471                .as_deref()
1472                .is_some_and(|e| e.contains("another wgpu device"))
1473        );
1474    }
1475
1476    #[test]
1477    fn the_gpu_path_installed_after_the_first_frame_replaces_the_fallback() {
1478        let mut b = Bench::new();
1479        let device = stub_device();
1480        let source = Source::new(b.tiles.feed.sink(Side::After), device.clone());
1481        // No GPU path: refused on the worker, the fallback shown.
1482        b.step(&source);
1483        assert!(source.sink.render_device().is_none());
1484        b.step(&source);
1485        assert_eq!(b.tiles.entries.len(), 1);
1486        assert_eq!(b.stat("device"), 0);
1487        assert_eq!(source.fallback_threads().len(), 1);
1488        // Installed between frames: the sink reads it at once.
1489        crate::gpu::set_render_device(&b.ctx, &device);
1490        assert!(
1491            source
1492                .sink
1493                .render_device()
1494                .is_some_and(|r| r.device == device)
1495        );
1496        // The next frame asks for the fallback's tile again, as a device
1497        // tile, shown in the frame after.
1498        b.step(&source);
1499        assert_eq!(source.requests.load(Ordering::SeqCst), 2);
1500        b.step(&source);
1501        assert_eq!(b.stat("device"), 1);
1502        assert_eq!(source.fallback_threads().len(), 1);
1503        assert!(b.tiles.entries.values().all(|e| !e.fallback && !e.stale));
1504    }
1505}