Skip to main content

rust_motion_affinity/
paint.rs

1//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint,
2//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index).
3
4use crate::model::{Affine, Reader};
5use crate::stream::{ObjId, Value};
6
7/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless
8/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Color {
11    Rgb {
12        r: f64,
13        g: f64,
14        b: f64,
15        a: f64,
16    },
17    Cmyk {
18        c: f64,
19        m: f64,
20        y: f64,
21        k: f64,
22        a: f64,
23    },
24    Gray {
25        v: f64,
26        a: f64,
27    },
28    /// CIE L*a*b* (D50).
29    Lab {
30        l: f64,
31        a: f64,
32        b: f64,
33        alpha: f64,
34    },
35}
36
37impl Color {
38    pub fn alpha(&self) -> f64 {
39        match self {
40            Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a,
41            Color::Lab { alpha, .. } => *alpha,
42        }
43    }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum GradientKind {
48    Linear,
49    /// Elliptical and radial: distance from the centre in unit space.
50    Radial,
51    /// Angle around the centre.
52    Conical,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct Stop {
57    pub offset: f64,
58    pub color: Color,
59    /// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend).
60    pub bias: f64,
61}
62
63impl Stop {
64    /// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve
65    /// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`.
66    pub fn half_point(&self) -> f64 {
67        let k = 1.0 + 8.0 * (self.bias - 0.5).abs();
68        let h = 0.5f64.powf(1.0 / k);
69        if self.bias >= 0.5 {
70            h
71        } else {
72            1.0 - h
73        }
74    }
75}
76
77#[derive(Debug, Clone, PartialEq)]
78pub struct Gradient {
79    pub kind: GradientKind,
80    pub stops: Vec<Stop>,
81    /// Unit space to document pixels: linear runs from unit (0,0) to (1,0); radial is the unit
82    /// circle; conical starts along unit +x and turns towards unit +y.
83    pub transform: Affine,
84}
85
86#[derive(Debug, Clone, PartialEq, Default)]
87pub enum Paint {
88    #[default]
89    None,
90    Solid(Color),
91    Gradient(Gradient),
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Cap {
96    Butt,
97    Round,
98    Square,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Join {
103    Miter,
104    Round,
105    Bevel,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum Align {
110    Center,
111    Inside,
112    Outside,
113}
114
115#[derive(Debug, Clone, PartialEq)]
116pub struct Stroke {
117    pub paint: Paint,
118    /// Width in document pixels.
119    pub width: f64,
120    pub cap: Cap,
121    pub join: Join,
122    pub miter_limit: f64,
123    pub align: Align,
124    /// Dash and gap lengths in document pixels, and the phase.
125    pub dash: Option<(Vec<f64>, f64)>,
126    /// Painted below the fill instead of above it.
127    pub behind: bool,
128}
129
130/// Gradient stops per gradient.
131const MAX_STOPS: usize = 1024;
132
133fn floats(v: &Value) -> Option<Vec<f64>> {
134    match v {
135        Value::Floats(f) => Some(f.clone()),
136        Value::Bytes(b) if b.len() % 4 == 0 => Some(
137            b.as_chunks::<4>()
138                .0
139                .iter()
140                .map(|c| f64::from(f32::from_le_bytes(*c)))
141                .collect(),
142        ),
143        _ => None,
144    }
145}
146
147/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`).
148pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option<Color> {
149    let s = r.s;
150    let class = s.class(id)?;
151    let col = || -> Option<Vec<f64>> {
152        let v = floats(s.field(id, b"_col")?)?;
153        v.iter().all(|f| f.is_finite()).then_some(v)
154    };
155    Some(match &class.0.to_be_bytes() {
156        b"RGBA" => {
157            let v = col()?;
158            Color::Rgb {
159                r: *v.first()?,
160                g: *v.get(1)?,
161                b: *v.get(2)?,
162                a: v.get(3)?.clamp(0.0, 1.0),
163            }
164        }
165        b"HSLA" => {
166            let v = col()?;
167            let (r2, g, b) = hsl(*v.first()?, *v.get(1)?, *v.get(2)?);
168            Color::Rgb {
169                r: r2,
170                g,
171                b,
172                a: v.get(3)?.clamp(0.0, 1.0),
173            }
174        }
175        b"CMYK" => {
176            let v = col()?;
177            Color::Cmyk {
178                c: *v.first()?,
179                m: *v.get(1)?,
180                y: *v.get(2)?,
181                k: *v.get(3)?,
182                a: v.get(4)?.clamp(0.0, 1.0),
183            }
184        }
185        b"GRAY" => {
186            let v = col()?;
187            Color::Gray {
188                v: *v.first()?,
189                a: v.get(1)?.clamp(0.0, 1.0),
190            }
191        }
192        b"LABA" => {
193            let b = s.bytes(id, b"_col")?;
194            let u = |i: usize| -> Option<f64> {
195                Some(f64::from(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) / 65535.0)
196            };
197            Color::Lab {
198                l: 100.0 * u(0)?,
199                a: 255.0 * u(1)? - 128.0,
200                b: 255.0 * u(2)? - 128.0,
201                alpha: u(3)?,
202            }
203        }
204        b"Pant" => {
205            r.warn("spot colours (imported as their RGB equivalent)");
206            return s
207                .obj(id, b"srgb")
208                .and_then(|c| color(r, c))
209                .or_else(|| s.obj(id, b"base").and_then(|c| color(r, c)));
210        }
211        b"RegC" => Color::Cmyk {
212            c: 1.0,
213            m: 1.0,
214            y: 1.0,
215            k: 1.0,
216            a: 1.0,
217        },
218        _ => {
219            r.warn("colours in an unknown model");
220            return None;
221        }
222    })
223}
224
225fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
226    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
227    let hp = (h.rem_euclid(1.0)) * 6.0;
228    let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
229    let (r, g, b) = match hp as u32 {
230        0 => (c, x, 0.0),
231        1 => (x, c, 0.0),
232        2 => (0.0, c, x),
233        3 => (0.0, x, c),
234        4 => (x, 0.0, c),
235        _ => (c, 0.0, x),
236    };
237    let m = l - c / 2.0;
238    (r + m, g + m, b + m)
239}
240
241/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's
242/// space to document pixels.
243pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Paint> {
244    let s = r.s;
245    let (fill, unit) = if s.is(id, b"FDsc") {
246        let unit = s
247            .floats::<6>(id, b"FDeX")
248            .map(Affine::from_xfrm)
249            .unwrap_or(Affine::IDENTITY);
250        (s.obj(id, b"FDeF")?, unit)
251    } else {
252        (id, Affine::IDENTITY)
253    };
254    match &s.class(fill)?.0.to_be_bytes() {
255        b"FilN" => Some(Paint::None),
256        b"FilS" => Some(Paint::Solid(color(r, s.obj(fill, b"Colr")?)?)),
257        b"FilG" => {
258            let kind = match s.enumeration(fill, b"Type").map(|(i, _)| i) {
259                Some(0) | None => GradientKind::Linear,
260                Some(1 | 2) => GradientKind::Radial,
261                Some(3) => GradientKind::Conical,
262                Some(_) => {
263                    r.warn("gradients of an unknown kind (imported as linear)");
264                    GradientKind::Linear
265                }
266            };
267            let grad = s.obj(fill, b"Grad")?;
268            let cols = s.objs(grad, b"Cols");
269            let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
270                Some(Value::Array(a)) => a.iter().filter_map(floats).collect(),
271                _ => Vec::new(),
272            };
273            let mut stops = Vec::new();
274            for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
275                let color = color(r, *c)?;
276                let offset = p
277                    .first()
278                    .copied()
279                    .filter(|v| v.is_finite())
280                    .unwrap_or(0.0)
281                    .clamp(0.0, 1.0);
282                let bias = p
283                    .get(1)
284                    .copied()
285                    .filter(|v| v.is_finite())
286                    .unwrap_or(0.5)
287                    .clamp(0.0, 1.0);
288                stops.push(Stop {
289                    offset,
290                    color,
291                    bias,
292                });
293            }
294            if stops.is_empty() {
295                return Some(Paint::None);
296            }
297            Some(Paint::Gradient(Gradient {
298                kind,
299                stops,
300                transform: unit.then(local),
301            }))
302        }
303        b"FilB" => {
304            r.warn("bitmap and pattern fills (left empty)");
305            Some(Paint::None)
306        }
307        _ => {
308            r.warn("fills of an unknown kind (left empty)");
309            Some(Paint::None)
310        }
311    }
312}
313
314fn current(r: &Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> Option<ObjId> {
315    let items = r.s.objs(id, list);
316    let i =
317        r.s.int(id, index)
318            .and_then(|i| usize::try_from(i).ok())
319            .unwrap_or(0);
320    items.get(i).or_else(|| items.first()).copied()
321}
322
323/// The fills of `list` (artboard backgrounds use `BFFl`).
324pub(crate) fn fills(
325    r: &mut Reader,
326    id: ObjId,
327    local: Affine,
328    list: &[u8; 4],
329) -> Vec<crate::paint::Paint> {
330    let d = current(r, id, list, b"BFCr").or_else(|| r.s.obj(id, b"BFil"));
331    d.and_then(|d| descriptor(r, d, local))
332        .filter(|p| *p != Paint::None)
333        .into_iter()
334        .collect()
335}
336
337/// A node's fill and stroke. `local` maps the node's space to document pixels.
338pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec<Paint>, Vec<Stroke>) {
339    let s = r.s;
340    let fills = fills(r, id, local, b"BFFl");
341    if r.s.objs(id, b"BFFl").len() > 1 || r.s.objs(id, b"LIFl").len() > 1 {
342        r.warn("several fills or strokes on one object (only the active one is imported)");
343    }
344    if s.f64(id, b"FOpc").is_some_and(|o| o < 0.999) {
345        r.warn("fill opacity (imported at full fill opacity)");
346    }
347    if s.obj(id, b"Trns").is_some() {
348        r.warn("transparency gradients (imported without them)");
349    }
350    let (pen, style) = if s.field(id, b"LIFl").is_some() {
351        (
352            current(r, id, b"LIFl", b"LICr"),
353            current(r, id, b"LILn", b"LICr"),
354        )
355    } else {
356        (s.obj(id, b"PFil"), s.obj(id, b"LSty"))
357    };
358    let behind = matches!(s.field(id, b"DrwO"), Some(Value::Array(a)) if a.first() == Some(&Value::Enum { id: 1, version: 0 }));
359    let stroke = match (pen, style) {
360        (Some(pen), Some(style)) => stroke(r, pen, style, local, behind),
361        _ => None,
362    };
363    (fills, stroke.into_iter().collect())
364}
365
366fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option<Stroke> {
367    let s = r.s;
368    let paint = descriptor(r, pen, local)?;
369    if paint == Paint::None {
370        return None;
371    }
372    let lsty = if s.is(ldsc, b"LDsc") {
373        s.obj(ldsc, b"LDeL")?
374    } else {
375        ldsc
376    };
377    let weight = s.f64(lsty, b"Wght").filter(|w| *w > 0.0 && *w < 1e7)?;
378    // "Scale with object": the weight follows the object's transform; otherwise it is absolute.
379    let scales = s.bool(ldsc, b"LDSc").unwrap_or(true);
380    let width = if scales {
381        weight * local.scale()
382    } else {
383        weight
384    };
385    let data = s.bytes(lsty, b"Data").unwrap_or_default();
386    let miter_limit = data
387        .get(0..8)
388        .and_then(|b| b.try_into().ok())
389        .map(f64::from_le_bytes)
390        .filter(|m| m.is_finite() && *m >= 1.0)
391        .unwrap_or(4.0);
392    // Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample;
393    // (2, 2) ends plain lines square and brush lines round; joins import round, which never
394    // looks wrong.
395    let (cap, join) = match (
396        data.get(8).copied(),
397        data.get(9).copied(),
398        data.get(10).copied(),
399    ) {
400        (Some(0), Some(0), _) => (Cap::Butt, Join::Miter),
401        (Some(0), Some(_), _) => (Cap::Butt, Join::Round),
402        (Some(2), Some(2), Some(3)) => (Cap::Round, Join::Round),
403        (Some(2), Some(2), _) => (Cap::Square, Join::Round),
404        _ => (Cap::Round, Join::Round),
405    };
406    let align = match s.int(ldsc, b"LDSa") {
407        Some(1) => Align::Inside,
408        Some(2) => Align::Outside,
409        _ => Align::Center,
410    };
411    let dash = match s.field(lsty, b"Patn") {
412        Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => {
413            let mut v: Vec<f64> = a
414                .iter()
415                .filter_map(|x| {
416                    if let Value::Float(f) = x {
417                        Some(*f)
418                    } else {
419                        None
420                    }
421                })
422                .collect();
423            while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) {
424                v.truncate(v.len() - 2);
425            }
426            let valid = !v.is_empty()
427                && v.iter().all(|x| x.is_finite() && *x >= 0.0)
428                && v.iter().any(|x| *x > 0.0);
429            valid.then(|| {
430                (
431                    v.iter().map(|x| x * width).collect(),
432                    s.f64(lsty, b"Phse").unwrap_or(0.0) * width,
433                )
434            })
435        }
436        _ => None,
437    };
438    if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() {
439        r.warn("brush and pressure strokes (imported as plain strokes)");
440    }
441    Some(Stroke {
442        paint,
443        width,
444        cap,
445        join,
446        miter_limit,
447        align,
448        dash,
449        behind,
450    })
451}