Skip to main content

gfx/
lib.rs

1// gfx -- surfaces and the draw context (clip, origin, colour), fills, blits  [src/gfx/surface.s]
2//
3//   Surface::new(w, h, fmt)            zeroed pixels, stride 64-byte aligned (sides 0..65536)
4//   Dc::new(w, h) / dc.begin(&sf) / dc.end()      the draw context of a target; begin saves
5//                                      clip, origin and opacity and resets them for another
6//                                      target, end restores them (gfx_begin / gfx_end)
7//   dc.begin_rows(&sf, row0, h)        sf holds rows row0 .. row0 + sf.h of a target h rows
8//                                      high (a row band drawn on a thread of its own): the
9//                                      coordinates stay the target's, only the pixel rows move
10//   dc: set_color(argb), set_opacity(op), clip_push(x, y, w, h) / clip_pop(), origin(x, y),
11//       translate(dx, dy), fill / clear / hline / vline / frame / blit / blit_scaled (sf, ...)
12//   set_parallel(f) / parallel()       the loop large copies run on (the UI runtime passes the
13//                                      worker pool's): a blit that copies XRGB rows from
14//                                      COPY_PAR_MIN bytes on is cut into row bands on it, from
15//                                      COPY_STREAM_MIN bytes on past the caches (a 4K canvas)
16//   path (Path, 24.8 and float API), raster (Raster), stroke (Path::stroke), shapes (Shapes),
17//   blend (row kernels), straight (straight-alpha rows), blendmode (paint.net blend modes),
18//   tmask (tiled masks), flood (flood fill), gradient, pathdata (SVG path data), dash
19//
20// Colours are straight 0xAARRGGBB; Dc keeps the premultiplied form for the kernels.  The
21// surface is passed to every drawing call: Dc holds no pointer to it.
22
23#![no_std]
24#![forbid(unsafe_code)]
25
26// in a module's build (--cfg jflib_module, docs/CRATES.md) the module runtime goes by the same name
27#[cfg(jflib_module)]
28extern crate modrt as rt;
29
30extern crate alloc;
31
32pub mod blend;
33pub mod blendmode;
34pub mod dash;
35pub mod flood;
36pub mod gradient;
37pub mod path;
38mod panel;
39pub mod pathdata;
40pub mod raster;
41pub mod shapes;
42pub mod straight;
43pub mod stroke;
44pub mod tmask;
45pub mod xform;
46
47use alloc::vec;
48use alloc::vec::Vec;
49
50pub use rt::fx::div255;
51
52pub const FMT_XRGB: u8 = 0; // 0x??RRGGBB, alpha byte ignored (window framebuffer)
53pub const FMT_PARGB: u8 = 1; // premultiplied 0xAARRGGBB (images, layers)
54pub const FMT_A8: u8 = 2; // 8-bit coverage / mask
55pub const FMT_ARGB: u8 = 3; // straight 0xAARRGGBB = bytes B, G, R, A
56pub const SFF_OWNED: u8 = 1;
57pub const SFF_OPAQUE: u8 = 2; // hint: every alpha is 255
58pub const FX_ONE: i32 = 256; // 24.8 fixed point: 1 pixel
59pub const RULE_NONZERO: u32 = 0;
60pub const RULE_EVENODD: u32 = 1;
61pub const JOIN_MITER: u32 = 0; // stroke style = join | cap << 4
62pub const JOIN_ROUND: u32 = 1;
63pub const JOIN_BEVEL: u32 = 2;
64pub const CAP_BUTT: u32 = 0;
65pub const CAP_ROUND: u32 = 1;
66pub const CAP_SQUARE: u32 = 2;
67pub const ERR_FAIL: i32 = -1;
68pub const ERR_NOMEM: i32 = -8;
69pub const ERR_LIMIT: i32 = -15;
70const SURF_MAX: i32 = 65536; // largest surface side (px)
71/// a blit's plain copy (XRGB source) from this many bytes on runs in row bands on the loop of
72/// set_parallel (gfxtest --bench-blit: a 1 MB copy takes about a fifth on 12 workers)
73pub const COPY_PAR_MIN: usize = 1 << 20;
74/// ... and from this many on with streaming stores (gfx::blend::copy_stream): source and target
75/// together no longer fit the caches, the target is not read first.  A 4K frame (32 MB): 1.9 ms on
76/// 12 workers and the calling thread, 2.7 ms with plain stores, 5 ms on one thread (Ryzen 5 3600,
77/// DDR4-3200, a loaded machine; the memory's limit for such a copy is about 1.7 ms there)
78pub const COPY_STREAM_MIN: usize = 12 << 20;
79// bytes of a band of such a copy (the pool hands the bands out as threads get free)
80const COPY_BAND: usize = 256 * 1024;
81
82/// runs f(i) for every i in 0..n, possibly on several threads (img_core::ParallelFor)
83pub type ParallelFor = fn(usize, &(dyn Fn(usize) + Sync));
84
85static PAR: rt::sync::SpinLock<Option<ParallelFor>> = rt::sync::SpinLock::new(None);
86
87/// the loop large copies run on (Dc::blit, COPY_PAR_MIN); the UI runtime passes a wrapper of
88/// plat::parallel_for -- gfx does not depend on plat.  Without it they run on the calling thread
89/// (the same bytes)
90pub fn set_parallel(f: ParallelFor) {
91    *PAR.lock() = Some(f);
92}
93
94/// the loop set by set_parallel
95pub fn parallel() -> Option<ParallelFor> {
96    *PAR.lock()
97}
98
99/// rows rows of n bytes: from src (stride ss) at row sy, byte sx into dst (stride ds) at row dy,
100/// byte dx.  From COPY_PAR_MIN bytes on in bands on the loop of set_parallel, from
101/// COPY_STREAM_MIN on past the caches (fenced before it returns)
102#[allow(clippy::too_many_arguments)]
103fn copy_rows(dst: &mut [u8], ds: usize, dy: usize, dx: usize, src: &[u8], ss: usize, sy: usize, sx: usize, n: usize, rows: usize) {
104    let bytes = rows.saturating_mul(n);
105    let stream = bytes >= COPY_STREAM_MIN;
106    let copy = |d: &mut [u8], s: &[u8]| {
107        if stream {
108            blend::copy_stream(d, s);
109        } else {
110            d.copy_from_slice(s);
111        }
112    };
113    let par = if bytes >= COPY_PAR_MIN && rows >= 2 { parallel() } else { None };
114    let Some(pf) = par else {
115        for r in 0..rows {
116            let (d, s) = ((dy + r) * ds + dx, (sy + r) * ss + sx);
117            copy(&mut dst[d..d + n], &src[s..s + n]);
118        }
119        if stream {
120            blend::stream_fence();
121        }
122        return;
123    };
124    // bands of bh rows: chunks of the target's rows from row dy on (each band locks its own)
125    let bh = rows.div_ceil((bytes / COPY_BAND).clamp(2, rows));
126    let chunks: Vec<rt::sync::SpinLock<&mut [u8]>> = dst[dy * ds..].chunks_mut(bh * ds).take(rows.div_ceil(bh)).map(rt::sync::SpinLock::new).collect();
127    pf(chunks.len(), &|i| {
128        let Some(cell) = chunks.get(i) else { return };
129        let mut c = cell.lock();
130        for r in i * bh..((i + 1) * bh).min(rows) {
131            let (d, s) = ((r - i * bh) * ds + dx, (sy + r) * ss + sx);
132            copy(&mut c[d..d + n], &src[s..s + n]);
133        }
134        if stream {
135            blend::stream_fence(); // (this thread's stores, before the loop reports it done)
136        }
137    });
138}
139
140/// pixels of one image: rows of `stride` bytes (4 per pixel, A8: 1)
141#[derive(Default)]
142pub struct Surface {
143    pub px: Vec<u8>,
144    pub w: i32,
145    pub h: i32,
146    pub stride: i32,
147    pub fmt: u8,
148    pub flags: u8,
149    pub opac: u8,  // layer opacity 0..255
150    pub blend: u8, // layer blend mode
151}
152
153/// n zeroed bytes | None when the memory is not there (instead of an abort). A probe
154/// reservation first, then vec![0; n]: that is alloc_zeroed, whose fresh pages need no
155/// clearing pass.
156pub fn try_zeroed(n: usize) -> Option<Vec<u8>> {
157    let mut probe: Vec<u8> = Vec::new();
158    probe.try_reserve_exact(n).ok()?;
159    drop(probe);
160    Some(vec![0u8; n])
161}
162
163impl Surface {
164    /// zeroed pixels, stride 64-byte aligned; sides outside 0..65536 give an empty surface
165    /// (surf_alloc fails). Byte lengths beyond the target's addressable allocation size
166    /// also give an empty surface, before allocating pixels.
167    pub fn new(w: i32, h: i32, fmt: u8) -> Surface {
168        let Some((stride, bytes)) = Surface::layout(w, h, fmt) else {
169            return Surface { px: Vec::new(), w: 0, h: 0, stride: 0, fmt, flags: 0, opac: 255, blend: 0 };
170        };
171        Surface { px: vec![0u8; bytes], w, h, stride, fmt, flags: SFF_OWNED, opac: 255, blend: 0 }
172    }
173
174    /// like `new`, but None (instead of an empty surface or an abort) when the size is
175    /// invalid or the memory is not there (try_zeroed). For sizes that come from a file or
176    /// from the user.
177    pub fn try_new(w: i32, h: i32, fmt: u8) -> Option<Surface> {
178        let (stride, bytes) = Surface::layout(w, h, fmt)?;
179        Some(Surface { px: try_zeroed(bytes)?, w, h, stride, fmt, flags: SFF_OWNED, opac: 255, blend: 0 })
180    }
181
182    // (stride, pixel bytes) or None for sides outside 0..=SURF_MAX or a size beyond isize::MAX
183    fn layout(w: i32, h: i32, fmt: u8) -> Option<(i32, usize)> {
184        if !(0..=SURF_MAX).contains(&w) || !(0..=SURF_MAX).contains(&h) {
185            return None;
186        }
187        let row = if fmt == FMT_A8 { w } else { w * 4 };
188        let stride = (row + 63) & !63;
189        let bytes = (stride as usize).checked_mul(h as usize).filter(|&n| n <= isize::MAX as usize)?;
190        Some((stride, bytes.max(64)))
191    }
192
193    /// a tightly packed A8 surface (glyph masks: stride = w)
194    pub fn new_a8_packed(w: i32, h: i32) -> Surface {
195        Surface { px: vec![0u8; (w * h) as usize], w, h, stride: w, fmt: FMT_A8, flags: SFF_OWNED, opac: 255, blend: 0 }
196    }
197
198    /// new size, same format; the contents are NOT kept  [surf_resize]
199    pub fn resize(&mut self, w: i32, h: i32) {
200        *self = Surface::new(w, h, self.fmt);
201    }
202
203    /// bytes per pixel
204    pub fn bpp(&self) -> usize {
205        if self.fmt == FMT_A8 { 1 } else { 4 }
206    }
207}
208
209// what begin saves of the previous target
210#[derive(Clone, Copy)]
211struct Saved {
212    w: i32,
213    h: i32,
214    clip: [i32; 4],
215    csp: usize,
216    ox: i32,
217    oy: i32,
218    opac: u32,
219    row0: i32,
220}
221
222/// the draw context of a target: clip (x0, y0, x1, y1 exclusive, in target pixels), origin,
223/// colour (straight and premultiplied), opacity
224pub struct Dc {
225    pub clip: [i32; 4],
226    clip_stack: Vec<[i32; 4]>,
227    targets: Vec<Saved>,
228    pub ox: i32,
229    pub oy: i32,
230    pub w: i32,
231    pub h: i32,
232    pub color: u32,
233    pub opac: u32,
234    pub pcol: [u32; 4], // premultiplied B, G, R, A
235    pub pcol32: u32,
236    pub ia: u32, // 255 - premultiplied alpha
237    /// the target row in the surface's first row (begin_rows: a band of a taller target);
238    /// 0 otherwise.  The fills and blits here, the rasterizer (paths, shapes, panels) and the
239    /// text engine's glyph blits honour it; other row writers (tmask, gradient, flood) expect 0.
240    pub row0: i32,
241}
242
243impl Dc {
244    /// a context for a w x h target: clip = the whole target, colour opaque black  [gfx_init]
245    pub fn new(w: i32, h: i32) -> Dc {
246        let mut dc = Dc {
247            clip: [0, 0, w, h],
248            clip_stack: Vec::new(),
249            targets: Vec::new(),
250            ox: 0,
251            oy: 0,
252            w,
253            h,
254            color: 0,
255            opac: 255,
256            pcol: [0; 4],
257            pcol32: 0,
258            ia: 255,
259            row0: 0,
260        };
261        dc.set_color(0xFF00_0000);
262        dc
263    }
264
265    /// draw into another target: clip, origin and opacity of the current one are saved; the
266    /// clip becomes the whole new target, the origin 0  [gfx_begin]
267    pub fn begin(&mut self, sf: &Surface) {
268        self.begin_rows(sf, 0, sf.h);
269    }
270
271    /// begin for a band: sf holds rows row0 .. row0 + sf.h of a target h rows high.  Drawing
272    /// keeps the target's coordinates (clip, origin, paths, glyph positions), so a band gets
273    /// the bytes the whole target would get there; the clip starts as the band's rows.
274    pub fn begin_rows(&mut self, sf: &Surface, row0: i32, h: i32) {
275        self.targets.push(Saved {
276            w: self.w,
277            h: self.h,
278            clip: self.clip,
279            csp: self.clip_stack.len(),
280            ox: self.ox,
281            oy: self.oy,
282            opac: self.opac,
283            row0: self.row0,
284        });
285        self.w = sf.w;
286        self.h = h;
287        self.ox = 0;
288        self.oy = 0;
289        self.row0 = row0;
290        let y1 = row0.saturating_add(sf.h).min(h);
291        self.clip = [0, row0.clamp(0, y1.max(0)), sf.w, y1.max(0)];
292    }
293
294    /// back to the previous target with its clip, origin and opacity  [gfx_end]
295    pub fn end(&mut self) {
296        let Some(s) = self.targets.pop() else { return };
297        self.w = s.w;
298        self.h = s.h;
299        self.clip = s.clip;
300        self.clip_stack.truncate(s.csp);
301        self.ox = s.ox;
302        self.oy = s.oy;
303        self.row0 = s.row0;
304        self.clamp_clip();
305        self.set_opacity(s.opac);
306    }
307
308    /// store the colour and its premultiplied forms  [gfx_set_color]
309    pub fn set_color(&mut self, argb: u32) {
310        self.color = argb;
311        let a = div255((argb >> 24) * self.opac);
312        self.ia = 255 - a;
313        self.pcol[3] = a;
314        let mut packed = a << 24;
315        for ch in 0..3 {
316            let c = (argb >> (ch * 8)) & 255;
317            let p = div255(c * a);
318            self.pcol[ch] = p;
319            packed |= p << (ch * 8);
320        }
321        self.pcol32 = packed;
322    }
323
324    pub fn get_color(&self) -> u32 {
325        self.color
326    }
327
328    /// global opacity 0..255 (multiplies every alpha)
329    pub fn set_opacity(&mut self, op: u32) {
330        self.opac = op & 255;
331        let c = self.color;
332        self.set_color(c);
333    }
334
335    pub fn origin(&mut self, x: i32, y: i32) {
336        self.ox = x;
337        self.oy = y;
338    }
339
340    pub fn translate(&mut self, dx: i32, dy: i32) {
341        self.ox = self.ox.wrapping_add(dx);
342        self.oy = self.oy.wrapping_add(dy);
343    }
344
345    /// save the clip and intersect it with the rectangle (origin-relative)
346    pub fn clip_push(&mut self, x: i32, y: i32, w: i32, h: i32) {
347        self.clip_stack.push(self.clip);
348        let x = x.wrapping_add(self.ox);
349        let y = y.wrapping_add(self.oy);
350        let x0 = x.max(self.clip[0]);
351        let y0 = y.max(self.clip[1]);
352        let x1 = x.wrapping_add(w).min(self.clip[2]).max(x0); // an empty clip stays empty
353        let y1 = y.wrapping_add(h).min(self.clip[3]).max(y0);
354        self.clip = [x0, y0, x1, y1];
355    }
356
357    pub fn clip_pop(&mut self) {
358        if let Some(c) = self.clip_stack.pop() {
359            self.clip = c;
360            self.clamp_clip();
361        }
362    }
363
364    /// 0 <= x0 <= x1 <= W, 0 <= y0 <= y1 <= H (a restored clip may belong to a larger target)
365    fn clamp_clip(&mut self) {
366        let x0 = self.clip[0].max(0).min(self.w);
367        let x1 = self.clip[2].min(self.w).max(x0);
368        let y0 = self.clip[1].max(0).min(self.h);
369        let y1 = self.clip[3].min(self.h).max(y0);
370        self.clip = [x0, y0, x1, y1];
371    }
372
373    /// origin-relative rectangle -> clipped target rectangle (x0, y0, x1, y1), or None
374    pub fn clip_rect(&self, x: i32, y: i32, w: i32, h: i32) -> Option<[i32; 4]> {
375        let x = x.wrapping_add(self.ox);
376        let y = y.wrapping_add(self.oy);
377        let x0 = x.max(self.clip[0]);
378        let y0 = y.max(self.clip[1]);
379        let x1 = x.wrapping_add(w).min(self.clip[2]);
380        let y1 = y.wrapping_add(h).min(self.clip[3]);
381        if x1 <= x0 || y1 <= y0 { None } else { Some([x0, y0, x1, y1]) }
382    }
383
384    /// blend the colour over a rectangle (A8 targets: store the alpha)  [gfx_fill]
385    pub fn fill(&self, sf: &mut Surface, x: i32, y: i32, w: i32, h: i32) {
386        let Some([x0, y0, x1, y1]) = self.clip_rect(x, y, w, h) else { return };
387        let stride = sf.stride as usize;
388        if sf.fmt == FMT_A8 {
389            let a = (self.pcol32 >> 24) as u8;
390            for yy in y0..y1 {
391                let o = (yy - self.row0) as usize * stride;
392                sf.px[o + x0 as usize..o + x1 as usize].fill(a);
393            }
394            return;
395        }
396        if self.ia != 0 && self.pcol32 == 0 {
397            return; // fully transparent
398        }
399        for yy in y0..y1 {
400            let o = (yy - self.row0) as usize * stride + x0 as usize * 4;
401            let row = &mut sf.px[o..o + (x1 - x0) as usize * 4];
402            if self.ia == 0 {
403                blend::fill_solid(row, self.pcol32);
404            } else {
405                blend::fill_over(row, &self.pcol, self.ia);
406            }
407        }
408    }
409
410    /// replace every pixel inside the clip by argb (premultiplied, no blending)  [gfx_clear]
411    pub fn clear(&self, sf: &mut Surface, argb: u32) {
412        let [x0, y0, x1, y1] = self.clip;
413        if x1 <= x0 || y1 <= y0 {
414            return;
415        }
416        let a = argb >> 24;
417        let mut c = argb;
418        if a != 255 {
419            c = argb & 0xFF00_0000;
420            for ch in 0..3 {
421                c |= div255(((argb >> (ch * 8)) & 255) * a) << (ch * 8);
422            }
423        }
424        let stride = sf.stride as usize;
425        for yy in y0..y1 {
426            let o = (yy - self.row0) as usize * stride;
427            if sf.fmt == FMT_A8 {
428                sf.px[o + x0 as usize..o + x1 as usize].fill((c >> 24) as u8);
429            } else {
430                blend::fill_solid(&mut sf.px[o + x0 as usize * 4..o + x1 as usize * 4], c);
431            }
432        }
433    }
434
435    pub fn hline(&self, sf: &mut Surface, x: i32, y: i32, w: i32) {
436        self.fill(sf, x, y, w, 1);
437    }
438
439    pub fn vline(&self, sf: &mut Surface, x: i32, y: i32, h: i32) {
440        self.fill(sf, x, y, 1, h);
441    }
442
443    /// 1-pixel outline inside the rectangle  [gfx_frame]
444    pub fn frame(&self, sf: &mut Surface, x: i32, y: i32, w: i32, h: i32) {
445        if w <= 0 || h <= 0 {
446            return;
447        }
448        self.hline(sf, x, y, w);
449        if h == 1 {
450            return;
451        }
452        self.hline(sf, x, y + h - 1, w);
453        if h == 2 {
454            return;
455        }
456        self.vline(sf, x, y + 1, h - 2);
457        if w == 1 {
458            return;
459        }
460        self.vline(sf, x + w - 1, y + 1, h - 2);
461    }
462
463    /// draw a surface at x, y: premultiplied over (x opacity), XRGB sources are copied (a large
464    /// copy in row bands on the loop of set_parallel, COPY_PAR_MIN)  [gfx_blit]
465    pub fn blit(&self, sf: &mut Surface, src: &Surface, x: i32, y: i32) {
466        if sf.fmt == FMT_A8 || src.fmt == FMT_A8 {
467            return;
468        }
469        let Some([x0, y0, x1, y1]) = self.clip_rect(x, y, src.w, src.h) else { return };
470        let sx = (x0 - x.wrapping_add(self.ox)) as usize;
471        let sy = (y0 - y.wrapping_add(self.oy)) as usize;
472        let n = (x1 - x0) as usize;
473        let (ds, ss) = (sf.stride as usize, src.stride as usize);
474        if src.fmt == FMT_XRGB {
475            copy_rows(&mut sf.px, ds, (y0 - self.row0) as usize, x0 as usize * 4, &src.px, ss, sy, sx * 4, n * 4, (y1 - y0) as usize);
476            return;
477        }
478        for r in 0..(y1 - y0) as usize {
479            let d = ((y0 - self.row0) as usize + r) * ds + x0 as usize * 4;
480            let s = (sy + r) * ss + sx * 4;
481            blend::blit_over(&mut sf.px[d..d + n * 4], &src.px[s..s + n * 4], self.opac);
482        }
483    }
484
485    /// nearest-neighbour blit scaled to w x h (over)  [gfx_blit_scaled]
486    pub fn blit_scaled(&self, sf: &mut Surface, src: &Surface, x: i32, y: i32, w: i32, h: i32) {
487        if w == src.w && h == src.h {
488            self.blit(sf, src, x, y);
489            return;
490        }
491        if w <= 0 || h <= 0 || src.w <= 0 || src.h <= 0 || sf.fmt == FMT_A8 || src.fmt == FMT_A8 {
492            return;
493        }
494        let xa = x.wrapping_add(self.ox);
495        let ya = y.wrapping_add(self.oy);
496        let Some([x0, y0, x1, y1]) = self.clip_rect(x, y, w, h) else { return };
497        let vw = (x1 - x0) as usize;
498        let xstep = ((src.w as u64) << 16) / w as u64;
499        let ystep = ((src.h as u64) << 16) / h as u64;
500        let mut row = vec![0u8; vw * 4];
501        for r in 0..(y1 - y0) {
502            let sy = (((y0 + r - ya) as u32 as u64 * ystep + (ystep >> 1)) >> 16) as usize;
503            let srow = sy * src.stride as usize;
504            let mut fx = (x0 - xa) as u32 as u64 * xstep + (xstep >> 1);
505            for i in 0..vw {
506                let s = srow + (fx >> 16) as usize * 4;
507                row[i * 4..i * 4 + 4].copy_from_slice(&src.px[s..s + 4]);
508                fx += xstep;
509            }
510            let d = (y0 + r - self.row0) as usize * sf.stride as usize + x0 as usize * 4;
511            let dst = &mut sf.px[d..d + vw * 4];
512            if src.fmt == FMT_XRGB {
513                dst.copy_from_slice(&row);
514            } else {
515                blend::blit_over(dst, &row, self.opac);
516            }
517        }
518    }
519}