Skip to main content

egui_pop_viewport/
demo.rs

1//! A procedural tile source, for galleries, examples and benchmarks: an
2//! image of any size computed on worker threads, scene-referred (linear
3//! floats), with a parameter that changes the whole image.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! It shows how a source behaves: requests return at once, workers skip
9//! cancelled requests, tiles come back through the sink, and a change
10//! is announced with [`TileSink::changed`]. [`Procedural::wait_idle`]
11//! blocks until every request taken has been answered or dropped: tests
12//! wait on it instead of sleeping.
13
14use std::collections::VecDeque;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
17use std::thread::JoinHandle;
18
19use crate::source::{Pixels, Tile, TileRequest, TileSink, TileSource};
20
21#[derive(Debug, Default)]
22struct Queue {
23    jobs: VecDeque<TileRequest>,
24    busy: usize,
25    shift: f32,
26    served: u64,
27    skipped: u64,
28}
29
30#[derive(Debug)]
31struct Shared {
32    queue: Mutex<Queue>,
33    work: Condvar,
34    idle: Condvar,
35    stop: AtomicBool,
36    sink: TileSink,
37    size: [u32; 2],
38}
39
40impl Shared {
41    fn lock(&self) -> MutexGuard<'_, Queue> {
42        self.queue.lock().unwrap_or_else(PoisonError::into_inner)
43    }
44}
45
46/// The procedural source. Dropping it stops its workers.
47#[derive(Debug)]
48pub struct Procedural {
49    shared: Arc<Shared>,
50    workers: Vec<JoinHandle<()>>,
51}
52
53/// The image's colour at image point `(x, y)` (continuous) for a size
54/// and a shift: smooth hues, rings, and a faint one-pixel checker so
55/// 100 % and above show single pixels. Linear RGB.
56pub fn sample(x: f64, y: f64, size: [u32; 2], shift: f32) -> [f32; 3] {
57    let (w, h) = (f64::from(size[0]), f64::from(size[1]));
58    let (u, v) = (x / w, y / h);
59    let tau = std::f64::consts::TAU;
60    let s = f64::from(shift);
61    let mut rgb = [
62        0.5 + 0.5 * (tau * (u + s)).cos(),
63        0.5 + 0.5 * (tau * (v + s + 1.0 / 3.0)).cos(),
64        0.5 + 0.5 * (tau * (u + v + s + 2.0 / 3.0)).cos(),
65    ];
66    let d = ((x - w / 2.0).powi(2) + (y - h / 2.0).powi(2)).sqrt();
67    let ring = 0.75 + 0.25 * (d * 0.06).cos();
68    let checker = if (x.floor() as i64 + y.floor() as i64) & 1 == 0 {
69        1.0
70    } else {
71        0.92
72    };
73    for c in &mut rgb {
74        *c = (*c * ring * checker).powi(2) * 0.9;
75    }
76    rgb.map(|c| c as f32)
77}
78
79fn render(r: &TileRequest, size: [u32; 2], shift: f32) -> Vec<f32> {
80    let [tw, th] = r.size;
81    let s = r.scale();
82    // Below 100 %, average a few samples over each scaled pixel.
83    let n = if s < 1.0 { 2 } else { 1 };
84    let step = 1.0 / s / f64::from(n);
85    let mut out = Vec::with_capacity(tw as usize * th as usize * 4);
86    for j in 0..th {
87        for i in 0..tw {
88            let x0 = (r.origin[0] as f64 + f64::from(i)) / s;
89            let y0 = (r.origin[1] as f64 + f64::from(j)) / s;
90            let mut acc = [0.0f32; 3];
91            for a in 0..n {
92                for b in 0..n {
93                    let c = sample(
94                        x0 + (f64::from(a) + 0.5) * step,
95                        y0 + (f64::from(b) + 0.5) * step,
96                        size,
97                        shift,
98                    );
99                    for k in 0..3 {
100                        acc[k] += c[k];
101                    }
102                }
103            }
104            let m = (n * n) as f32;
105            out.extend([acc[0] / m, acc[1] / m, acc[2] / m, 1.0]);
106        }
107    }
108    out
109}
110
111fn work(shared: &Shared) {
112    loop {
113        let (job, shift) = {
114            let mut q = shared.lock();
115            loop {
116                if shared.stop.load(Ordering::Relaxed) {
117                    return;
118                }
119                if let Some(j) = q.jobs.pop_front() {
120                    q.busy += 1;
121                    break (j, q.shift);
122                }
123                q = shared.work.wait(q).unwrap_or_else(PoisonError::into_inner);
124            }
125        };
126        let served = if job.is_cancelled() {
127            false
128        } else {
129            let data = render(&job, shared.size, shift);
130            if job.is_cancelled() {
131                false
132            } else {
133                shared.sink.deliver(Tile::answer(&job, Pixels::Scene(data)));
134                true
135            }
136        };
137        let mut q = shared.lock();
138        q.busy -= 1;
139        if served {
140            q.served += 1;
141        } else {
142            q.skipped += 1;
143        }
144        if q.jobs.is_empty() && q.busy == 0 {
145            shared.idle.notify_all();
146        }
147    }
148}
149
150impl Procedural {
151    /// An image of `size` pixels, computed by `workers` threads (none:
152    /// computed when asked, on the caller's thread, for platforms
153    /// without threads).
154    pub fn new(sink: TileSink, size: [u32; 2], workers: usize) -> Procedural {
155        let shared = Arc::new(Shared {
156            queue: Mutex::default(),
157            work: Condvar::new(),
158            idle: Condvar::new(),
159            stop: AtomicBool::new(false),
160            sink,
161            size,
162        });
163        let workers = (0..workers)
164            .map(|i| {
165                let s = shared.clone();
166                std::thread::Builder::new()
167                    .name(format!("egui-pop-viewport-demo-{i}"))
168                    .spawn(move || work(&s))
169                    .expect("a worker thread")
170            })
171            .collect();
172        Procedural { shared, workers }
173    }
174
175    /// Moves the hues: the whole image changes, tiles on screen stay
176    /// until their replacements arrive.
177    pub fn set_shift(&self, shift: f32) {
178        self.shared.lock().shift = shift;
179        self.shared.sink.changed(None);
180    }
181
182    /// The current shift.
183    pub fn shift(&self) -> f32 {
184        self.shared.lock().shift
185    }
186
187    /// Blocks until every request taken was answered or skipped (never
188    /// call it on the interface thread of a running application).
189    pub fn wait_idle(&self) {
190        let mut q = self.shared.lock();
191        while !(q.jobs.is_empty() && q.busy == 0) {
192            q = self
193                .shared
194                .idle
195                .wait(q)
196                .unwrap_or_else(PoisonError::into_inner);
197        }
198    }
199
200    /// Tiles answered and requests skipped because they were cancelled.
201    pub fn counts(&self) -> (u64, u64) {
202        let q = self.shared.lock();
203        (q.served, q.skipped)
204    }
205}
206
207impl Drop for Procedural {
208    fn drop(&mut self) {
209        self.shared.stop.store(true, Ordering::Relaxed);
210        self.shared.work.notify_all();
211        for w in self.workers.drain(..) {
212            let _ = w.join();
213        }
214    }
215}
216
217impl TileSource for Procedural {
218    fn size(&self) -> Option<[u32; 2]> {
219        Some(self.shared.size)
220    }
221
222    fn request(&self, requests: Vec<TileRequest>) {
223        if self.workers.is_empty() {
224            // No threads (the web): computed here, a frame's work.
225            let shift = self.shift();
226            for r in requests {
227                let data = render(&r, self.shared.size, shift);
228                self.shared
229                    .sink
230                    .deliver(Tile::answer(&r, Pixels::Scene(data)));
231                self.shared.lock().served += 1;
232            }
233            return;
234        }
235        self.shared.lock().jobs.extend(requests);
236        self.shared.work.notify_all();
237    }
238
239    fn readout(&self, pixel: [i64; 2]) {
240        let shift = self.shift();
241        let c = sample(
242            pixel[0] as f64 + 0.5,
243            pixel[1] as f64 + 0.5,
244            self.shared.size,
245            shift,
246        );
247        self.shared.sink.readout(
248            pixel,
249            vec![("R".into(), c[0]), ("G".into(), c[1]), ("B".into(), c[2])],
250        );
251    }
252}