motion-content 0.2.0

Backend-independent images, text, vectors, particles and artwork
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Deterministic ink materials and pressure-sensitive drawing.

use motion_core::Transform;
use std::io;

mod brush;
mod lettering;
mod paint;
mod paper;

pub use lettering::StrokeFont;

pub use brush::{
    BrushCap, BrushPreset, BrushStroke, BrushStrokeBuilder, BrushTiming, InkFill, InputSample,
    NibMode, PigmentMix, PigmentPainting,
};
pub use paper::Paper;

use paper::PaperSampler;

type Point = (f64, f64);

/// A deterministic ink material for strokes and even-odd path fills.
///
/// [`BrushStrokeBuilder::ink`] uses all effects. [`InkFill`] uses dryness, bleed, roughness,
/// granulation, paper, edge pooling and [`edge_darkening`](Self::edge_darkening). Directional
/// [`fibers`](Self::fibers), [`build_up`](Self::build_up),
/// [`edge_anisotropy`](Self::edge_anisotropy) and [`height_map`](Self::height_map) need stroke
/// geometry (arc length, self-overlap or a nib) and are ignored by fills.
///
/// The default is solid ink with seed zero and no dry gaps, feathering, roughness,
/// granulation, directional fibers, paper imprint, or edge pooling. Parameters
/// use layer-local coordinates (except canvas-anchored paper) and are evaluated from
/// geometry, not previous frames. This is a bounded procedural wash, not a fluid
/// or paper-fiber simulation. Both rendering backends share the CPU coverage.
///
/// Builders store values; invalid settings are reported when a stroke is built or rendered. Use a
/// stable seed and vary bleed or pigment settings explicitly with frame-local time.
///
/// # Example
///
/// ```
/// use motion_content::prelude::*;
/// use motion_core::prelude::*;
/// use motion_core::{
///     DisplayList, RasterLimits, ResourceStore, ValidatedDisplayList, MAX_PATH_VERBS,
///     MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
/// };
/// use motion_render::{Composition, RenderPrepare, RenderOptions, BackendKind, render_still};
/// use motion_content::vector::ink::*;
/// # fn main() -> motion_core::Result {
/// let brush = Ink::new(17)
///     .dryness(0.25)
///     .fibers(1.0)
///     .bleed(4.0)
///     .edge_roughness(1.5)
///     .granulation(0.4)
///     .paper(Paper::Procedural { seed: 211, strength: 0.45, scale: 1.5 })
///     .edge_pooling(0.6, 2.0);
/// let path = Path2D::parse_svg("M0 0L60 0")?;
/// let stroke = BrushStroke::builder(path, 24.0, Color::from_hex(0x23272c))
///     .pressure(0.15, 1.2, 0.05)
///     .ink_load(1.0, 0.25)
///     .ink(brush)
///     .build()?;
/// # let _ = stroke;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct Ink {
    pub(super) seed: u32,
    pub(super) dryness: f32,
    pub(super) bleed: f32,
    pub(super) roughness: f32,
    pub(super) granulation: f32,
    fibers: f32,
    paper: Option<Paper>,
    paper_transform: Transform,
    pooling: Option<(f32, f32)>,
    pub(super) build_up: f64,
    pub(super) edge_darkening: f64,
    pub(super) anisotropy: f64,
    pub(super) height: f64,
}

impl Default for Ink {
    fn default() -> Self {
        Self {
            seed: 0,
            dryness: 0.0,
            bleed: 0.0,
            roughness: 0.0,
            granulation: 0.0,
            fibers: 0.0,
            paper: None,
            paper_transform: Transform::IDENTITY,
            pooling: None,
            build_up: 0.0,
            edge_darkening: 0.0,
            anisotropy: 1.0,
            height: 0.0,
        }
    }
}

impl Ink {
    /// Creates solid ink with a fixed seed and all effects initially disabled.
    pub fn new(seed: u32) -> Self {
        Self {
            seed,
            ..Self::default()
        }
    }

    /// Sets dry-brush strength in `0..=1`; one permits fully dry gaps.
    /// Zero retains solid coverage unless other material effects are enabled.
    pub fn dryness(mut self, strength: f32) -> Self {
        self.dryness = strength;
        self
    }

    /// Sets the maximum soft wash extent beyond a fill or stroke edge, in local pixels.
    /// Must be finite and nonnegative. Zero disables feathering. The halo has
    /// finite support, is affected by the layer transform, and respects clips.
    /// Animate this value to suggest absorption without retaining frame history.
    pub fn bleed(mut self, radius: f32) -> Self {
        self.bleed = radius;
        self
    }

    /// Sets the maximum inward/outward edge displacement in local pixels.
    /// Must be finite and nonnegative. Seeded low-frequency noise shapes the edge;
    /// zero preserves the geometric silhouette. It is not a blur radius.
    pub fn edge_roughness(mut self, amplitude: f32) -> Self {
        self.roughness = amplitude;
        self
    }

    /// Sets pigment variation in `0..=1`, from uniform to strongly mottled.
    /// This attenuates coverage, not RGB channels or the composition background.
    /// Coarse local noise produces density variation without per-frame randomness.
    pub fn granulation(mut self, strength: f32) -> Self {
        self.granulation = strength;
        self
    }

    /// Blends axis-oriented dry gaps towards path-following fibers in `0..=1`.
    /// One uses full-path arc length and signed distance across the sampled
    /// flattened segment. Requires dryness or depleted [`BrushStrokeBuilder::ink_load`]
    /// to expose gaps. Trim preserves the full-path phase. Changing geometry can
    /// change arc length; corners, closed seams, and crossings are not simulated
    /// bristle transport. Zero retains the original local-axis texture. Stroke-only.
    pub fn fibers(mut self, strength: f32) -> Self {
        self.fibers = strength;
        self
    }

    /// Sets the paper sheet that attenuates pigment coverage, not the background.
    ///
    /// [`Paper::Procedural`] fibers are seeded noise (strength in `0..=1`, scale finite and
    /// positive in paper-space pixels); [`Paper::Texture`] repeats a resolved height map and
    /// attenuates by its luma. Either is sampled in paper space: local coordinates mapped by
    /// [`paper_transform`](Self::paper_transform), which is the identity (untransformed design
    /// space) by default. A layer that moves or scales keeps its paper fixed on the canvas only
    /// when the transform equals the node transform. Reuse one `Paper` on fills and strokes for
    /// one sheet. Setting a paper replaces the previous one. This attenuates alpha only; it is
    /// not a paper height or fluid simulation.
    pub fn paper(mut self, paper: Paper) -> Self {
        self.paper = Some(paper);
        self
    }

    /// Supplies the authored local-to-paper coordinates; the identity uses untransformed design
    /// space. Must be finite.
    pub fn paper_transform(mut self, transform: Transform) -> Self {
        self.paper_transform = transform;
        self
    }

    /// Adds an inner edge deposit by diluting the body relative to the rim.
    /// Strength must be in `0..=1`; width must be finite and positive local pixels.
    /// Applied to the fill boundary or stroke union, not individual segment caps. Does not
    /// expand bounds, change RGB, fill completely dry gaps, or simulate drying.
    pub fn edge_pooling(mut self, strength: f32, width: f32) -> Self {
        self.pooling = Some((strength, width));
        self
    }

    /// Darkens RGB near the geometric rim, in `0..=1`. Unlike pooling it changes color, not
    /// alpha.
    pub fn edge_darkening(mut self, strength: f64) -> Self {
        self.edge_darkening = strength;
        self
    }

    /// Adds density at stroke self-intersections using independent segment coverage, in
    /// `0..=1`. Stroke-only.
    pub fn build_up(mut self, strength: f64) -> Self {
        self.build_up = strength;
        self
    }

    /// Scales directional material coordinates; a positive ratio in `0.1..=10`. Stroke-only.
    pub fn edge_anisotropy(mut self, ratio: f64) -> Self {
        self.anisotropy = ratio;
        self
    }

    /// Makes a stroke a grayscale rounded-ridge height drawable for
    /// `Optics::Relight { height_from: Luma }`; strength in `0..=16`. Stroke-only.
    pub fn height_map(mut self, strength: f64) -> Self {
        self.height = strength;
        self
    }

    pub(crate) fn padding(&self) -> io::Result<f32> {
        let padding = self.bleed + self.roughness;
        if ![
            self.dryness,
            self.bleed,
            self.roughness,
            self.granulation,
            self.fibers,
            padding,
        ]
        .iter()
        .all(|value| value.is_finite())
            || !(0.0..=1.0).contains(&self.dryness)
            || !(0.0..=1.0).contains(&self.granulation)
            || !(0.0..=1.0).contains(&self.fibers)
            || self.paper.as_ref().is_some_and(|paper| !paper.is_valid())
            || !self.paper_transform.is_finite()
            || self.pooling.is_some_and(|(strength, width)| {
                !strength.is_finite()
                    || !(0.0..=1.0).contains(&strength)
                    || !width.is_finite()
                    || width <= 0.0
            })
            || self.bleed < 0.0
            || self.roughness < 0.0
            || !self.build_up.is_finite()
            || !(0.0..=1.0).contains(&self.build_up)
            || !self.edge_darkening.is_finite()
            || !(0.0..=1.0).contains(&self.edge_darkening)
            || !self.anisotropy.is_finite()
            || !(0.1..=10.0).contains(&self.anisotropy)
            || !self.height.is_finite()
            || !(0.0..=16.0).contains(&self.height)
        {
            return Err(invalid(
                "Ink strengths must be in 0..=1, bleed/roughness nonnegative, paper/pooling scales positive and finite, anisotropy in 0.1..=10 and height in 0..=16",
            ));
        }
        Ok(padding)
    }

    /// Maps a local point into paper space.
    fn paper_space(&self, point: motion_core::Point) -> motion_core::Point {
        self.paper_transform.apply(point)
    }

    /// Prepares the texture paper, if any, once per baked material.
    fn paper_sampler(&self) -> Option<PaperSampler> {
        match &self.paper {
            Some(Paper::Texture {
                texture,
                grain_scale,
                absorbency,
            }) => Some(PaperSampler::new(
                texture.clone(),
                *grain_scale,
                *absorbency,
            )),
            _ => None,
        }
    }

    #[cfg(test)]
    pub(super) fn has_fill_edges(&self) -> bool {
        self.bleed > 0.0
            || self.roughness > 0.0
            || self.pooling.is_some_and(|(strength, _)| strength > 0.0)
    }

    pub(super) fn sample(&self, point: Point, canvas: Point) -> InkSample {
        let dry = (self.dryness > 0.0).then(|| DrySample::new(point, self.seed));
        let mut density = dry.map_or(1.0, |dry| dry.coverage(f64::from(self.dryness)));
        let mut pigment = 1.0;
        if self.granulation > 0.0 {
            let cloud = noise((point.0 * 0.08, point.1 * 0.08), self.seed.wrapping_add(43));
            let grain = noise((point.0 * 0.65, point.1 * 0.65), self.seed.wrapping_add(71));
            let factor =
                1.0 - f64::from(self.granulation) * (0.2 + 0.8 * (cloud * 0.7 + grain * 0.3));
            density *= factor;
            pigment *= factor;
        }
        if let Some(Paper::Procedural {
            seed,
            strength,
            scale,
        }) = self.paper
        {
            let paper = (canvas.0 / f64::from(scale), canvas.1 / f64::from(scale));
            let horizontal = noise((paper.0 * 0.08, paper.1 * 2.8), seed);
            let vertical = noise((paper.0 * 2.5, paper.1 * 0.12), seed.wrapping_add(101));
            let grain = noise((paper.0 * 0.7, paper.1 * 0.7), seed.wrapping_add(137));
            let factor = 1.0
                - f64::from(strength)
                    * (0.15 + 0.85 * (horizontal * 0.5 + vertical * 0.3 + grain * 0.2));
            density *= factor;
            pigment *= factor;
        }
        InkSample {
            edge: if self.roughness > 0.0 {
                f64::from(self.roughness)
                    * (noise((point.0 * 0.22, point.1 * 0.22), self.seed.wrapping_add(29)) * 2.0
                        - 1.0)
            } else {
                0.0
            },
            bleed: if self.bleed > 0.0 {
                f64::from(self.bleed)
                    * (0.65
                        + 0.35
                            * noise((point.0 * 0.35, point.1 * 0.35), self.seed.wrapping_add(61)))
            } else {
                0.0
            },
            density,
            pigment,
            point,
            shade: Some(Shade {
                seed: self.seed,
                dryness: self.dryness,
                fibers: self.fibers,
                pooling: self.pooling,
            }),
            dry,
        }
    }
}

#[derive(Clone, Copy)]
pub(super) struct InkSample {
    edge: f64,
    bleed: f64,
    density: f64,
    pigment: f64,
    point: Point,
    shade: Option<Shade>,
    dry: Option<DrySample>,
}

/// The per-material constants that [`InkSample`] needs after sampling.
#[derive(Clone, Copy)]
struct Shade {
    seed: u32,
    dryness: f32,
    fibers: f32,
    pooling: Option<(f32, f32)>,
}

impl Default for InkSample {
    fn default() -> Self {
        Self {
            edge: 0.0,
            bleed: 0.0,
            density: 1.0,
            pigment: 1.0,
            point: (0.0, 0.0),
            shade: None,
            dry: None,
        }
    }
}

impl InkSample {
    #[cfg(test)]
    pub(super) fn fill_coverage(self, coverage: f64) -> f64 {
        coverage * self.density
    }

    pub(super) fn fill_edge_coverage(self, distance: f64, metric: f64) -> f64 {
        self.coverage(distance, metric) * (self.density * self.pool_density(distance))
    }

    fn pool_density(self, distance: f64) -> f64 {
        self.shade
            .and_then(|shade| shade.pooling)
            .map_or(1.0, |(strength, width)| {
                let rim = (1.0 - (distance - self.edge).abs() / f64::from(width)).clamp(0.0, 1.0);
                1.0 - f64::from(strength) * 0.45 * (1.0 - rim * rim)
            })
    }

    pub(super) fn coverage(self, distance: f64, metric: f64) -> f64 {
        let distance = distance - self.edge;
        let core = (0.5 - distance / metric).clamp(0.0, 1.0);
        // A finite-support wash leaves no tails beyond the validated local padding.
        let halo = if self.bleed > 0.0 {
            let remaining = (1.0 - distance.max(0.0) / self.bleed).clamp(0.0, 1.0);
            remaining * remaining * 0.35
        } else {
            0.0
        };
        core + (1.0 - core) * halo
    }

    pub(super) fn shade(self, coverage: f64, distance: f64, fiber: Point, load: f64) -> f64 {
        if load <= 0.0 {
            return 0.0;
        }
        let mut density = self.density;
        if let Some(shade) = self.shade {
            if shade.fibers > 0.0 || load < 1.0 {
                let dryness = 1.0 - (1.0 - f64::from(shade.dryness)) * load;
                let isotropic = self
                    .dry
                    .unwrap_or_else(|| DrySample::new(self.point, shade.seed))
                    .coverage(dryness);
                let dry = if shade.fibers > 0.0 {
                    let directional = dry_coverage(fiber, shade.seed, dryness);
                    isotropic + (directional - isotropic) * f64::from(shade.fibers)
                } else {
                    isotropic
                };
                density = dry * self.pigment;
            }
            density *= self.pool_density(distance);
        }
        coverage * density * load
    }
}

fn invalid(message: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message)
}

fn dry_coverage(point: Point, seed: u32, dryness: f64) -> f64 {
    DrySample::new(point, seed).coverage(dryness)
}

#[derive(Clone, Copy)]
struct DrySample {
    grain: f64,
    fiber: f64,
}

impl DrySample {
    fn new(point: Point, seed: u32) -> Self {
        Self {
            grain: noise((point.0 * 1.3, point.1 * 1.3), seed),
            fiber: noise((point.0 * 0.15, point.1 * 3.0), seed.wrapping_add(17)),
        }
    }

    fn coverage(self, dryness: f64) -> f64 {
        let density =
            ((self.fiber - dryness * 0.7) * 8.0).clamp(0.0, 1.0) * (0.5 + 0.5 * self.grain);
        1.0 - dryness + dryness * density
    }
}

/// Lattice value noise in 0..=1, stateless so effects stay attached to the path.
fn noise(point: Point, seed: u32) -> f64 {
    motion_core::noise::value2([point.0, point.1], seed) * 0.5 + 0.5
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fill_edges_have_bounded_wash_and_relative_rim_density() {
        let point = (13.5, 24.5);
        let ink = Ink::new(17).bleed(4.0).edge_pooling(1.0, 2.0);
        assert!(ink.has_fill_edges());
        assert!(
            !Ink::new(17)
                .fibers(1.0)
                .edge_pooling(0.0, 2.0)
                .has_fill_edges()
        );
        let sample = ink.sample(point, point);
        assert!(sample.fill_edge_coverage(1.0, 1.0) > 0.0);
        assert_eq!(sample.fill_edge_coverage(5.0, 1.0), 0.0);
        assert!(sample.fill_edge_coverage(-0.5, 1.0) > sample.fill_edge_coverage(-5.0, 1.0));
        let fibers = ink.fibers(1.0).sample(point, point);
        assert_eq!(
            sample.fill_edge_coverage(-0.5, 1.0),
            fibers.fill_edge_coverage(-0.5, 1.0)
        );
    }

    #[test]
    fn fill_density_preserves_coverage_and_is_stateless() {
        let point = (13.5, 24.5);
        let neutral = Ink::new(17).sample(point, point);
        let ink = Ink::new(17)
            .dryness(0.4)
            .granulation(0.6)
            .paper(Paper::Procedural {
                seed: 211,
                strength: 0.7,
                scale: 1.5,
            });
        for coverage in [0.0, 0.25, 0.5, 0.75, 1.0] {
            assert_eq!(neutral.fill_coverage(coverage), coverage);
            let first = ink.sample(point, point).fill_coverage(coverage);
            let _ = ink.sample((40.5, 8.5), (8.5, 40.5));
            assert_eq!(first, ink.sample(point, point).fill_coverage(coverage));
            assert!(first >= 0.0 && first <= coverage);
        }
        assert!(ink.sample(point, point).fill_coverage(1.0) < 1.0);
        let paper = Ink::new(17).paper(Paper::Procedural {
            seed: 211,
            strength: 0.7,
            scale: 1.5,
        });
        assert_eq!(
            paper.sample(point, point).fill_coverage(1.0),
            paper.sample((90.0, 12.0), point).fill_coverage(1.0)
        );
    }

    #[test]
    fn neutral_fibers_preserve_reference_dry_coverage() {
        for point in [(2.5, 3.5), (15.5, 9.5), (37.5, 24.5)] {
            let material = Ink::new(17).dryness(0.7).sample(point, point);
            for distance in [-4.0, -0.2, 0.3, 2.0] {
                let expected = (0.5_f64 - distance).clamp(0.0, 1.0)
                    * dry_coverage(point, 17, f64::from(0.7_f32));
                assert_eq!(
                    material.shade(material.coverage(distance, 1.0), distance, (0.0, 0.0), 1.0),
                    expected
                );
            }
        }
    }

    #[test]
    fn paper_is_canvas_anchored_and_pooling_keeps_a_darker_rim() {
        let paper = Ink::new(17).paper(Paper::Procedural {
            seed: 211,
            strength: 0.7,
            scale: 1.5,
        });
        let canvas = (13.5, 24.5);
        assert_eq!(
            paper.sample((0.0, 0.0), canvas).density,
            paper.sample((90.0, 12.0), canvas).density
        );
        assert_eq!(
            paper.sample((0.0, 0.0), canvas).density,
            Ink::new(99)
                .paper(Paper::Procedural {
                    seed: 211,
                    strength: 0.7,
                    scale: 1.5
                })
                .sample((0.0, 0.0), canvas)
                .density
        );
        assert!((1..20).any(|offset| {
            paper
                .sample((0.0, 0.0), (canvas.0 + f64::from(offset), canvas.1))
                .density
                != paper.sample((0.0, 0.0), canvas).density
        }));
        let pooled = Ink::new(17).edge_pooling(1.0, 2.0).sample(canvas, canvas);
        assert!(
            pooled.shade(1.0, -0.5, (0.0, 0.0), 1.0) > pooled.shade(1.0, -5.0, (0.0, 0.0), 1.0)
        );
        assert_eq!(pooled.shade(1.0, -0.5, (0.0, 0.0), 0.0), 0.0);
    }
}