Skip to main content

deq_shapes/
generate.rs

1//! Seeded pattern generator: bands, grids, rosettes and borders of Deq motifs (ADR 0015).
2
3use std::sync::LazyLock;
4
5use regex::Regex;
6use serde_json::{Map, Value, json};
7
8use crate::error::{DeqError, Result};
9use crate::geometry::cos_sin;
10use crate::leet::{Check, integer, seed_check, split_options, to_seed, to_usize};
11use crate::options::{number, picklist};
12use crate::pattern::compile;
13use crate::random::Random;
14use crate::registry::{get_shape, list_shapes};
15use crate::scene::{Cell, Scene, resolve_scene_options, scene_svg};
16
17static ID: LazyLock<Regex> = LazyLock::new(|| compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$"));
18
19fn motifs_check(v: &Value) -> Option<String> {
20    let ok = v.as_array().is_some_and(|ids| {
21        (1..=64).contains(&ids.len())
22            && ids.iter().all(|id| {
23                id.as_str()
24                    .is_some_and(|s| s.chars().count() <= 64 && ID.is_match(s))
25            })
26    });
27    (!ok).then(|| "must be a list of 1 to 64 shape ids".to_owned())
28}
29
30fn count_check(v: &Value) -> Option<String> {
31    integer(v, 3.0, 63.0)
32        .or_else(|| (v.as_f64().unwrap_or(0.0) % 2.0 != 1.0).then(|| "must be odd".to_owned()))
33}
34
35const CHECKS: [(&str, Check); 8] = [
36    ("kind", |v| {
37        picklist(v, &["band", "grid", "rosette", "border"])
38    }),
39    ("seed", seed_check),
40    ("motifs", motifs_check),
41    ("count", count_check),
42    ("cols", |v| integer(v, 1.0, 32.0)),
43    ("rows", |v| integer(v, 1.0, 32.0)),
44    ("petals", |v| integer(v, 3.0, 24.0)),
45    ("spacing", |v| number(v, 0.0, 24.0, false)),
46];
47
48/// The result of [`pattern`].
49#[derive(Debug, Clone, PartialEq)]
50pub struct PatternResult {
51    /// The SVG document, one `<g data-layer="cN">` per motif.
52    pub svg: String,
53    /// The motifs chosen, in the order the pattern uses them.
54    pub motifs: Vec<String>,
55    /// The placed motifs.
56    pub scene: Scene,
57}
58
59/// `count` distinct motifs from `pool` (repeating only when the pool is smaller).
60fn choose(pool: &[String], count: usize, random: &mut Random) -> Vec<String> {
61    let mut left: Vec<String> = pool.to_vec();
62    let mut out = Vec::with_capacity(count);
63    for _ in 0..count {
64        if left.is_empty() {
65            left.extend_from_slice(pool);
66        }
67        let i = random.below(left.len());
68        if i < left.len() {
69            out.push(left.remove(i));
70        }
71    }
72    out
73}
74
75fn nth(items: &[String], i: usize) -> String {
76    items
77        .get(i % items.len().max(1))
78        .cloned()
79        .unwrap_or_default()
80}
81
82fn cell(x: f64, y: f64, shape: &str, rotate: f64, scale: f64) -> Cell {
83    let mut part = Map::new();
84    part.insert("shape".into(), json!(shape));
85    if rotate != 0.0 || scale != 1.0 {
86        let mut transform = Map::new();
87        if scale != 1.0 {
88            transform.insert("scale".into(), json!(scale));
89        }
90        if rotate != 0.0 {
91            transform.insert("rotate".into(), json!(rotate));
92        }
93        part.insert("transform".into(), Value::Object(transform));
94    }
95    Cell {
96        x,
97        y,
98        glyph: Value::Array(vec![Value::Object(part)]),
99    }
100}
101
102/// Generate a pattern of Deq motifs.
103///
104/// `band` repeats motifs in a row (alternating or mirrored), `grid` lays a checkerboard,
105/// `rosette` rings petals round a centre and `border` frames a rectangle. Options are
106/// `kind`, `seed`, `motifs`, `count`, `cols`, `rows`, `petals`, `spacing`, `colors` and the
107/// render options except the per-shape ones.
108///
109/// # Errors
110/// `InvalidOptions`, `UnknownShape` or `LimitExceeded`.
111#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
112pub fn pattern(options: &Value) -> Result<PatternResult> {
113    let (own, scene) = split_options(options, &CHECKS, "pattern options")?;
114    resolve_scene_options(&scene)?;
115    let pool: Vec<String> = match own.get("motifs").and_then(Value::as_array) {
116        Some(ids) => ids
117            .iter()
118            .filter_map(|v| v.as_str().map(str::to_owned))
119            .collect(),
120        None => list_shapes(None)
121            .iter()
122            .filter_map(|s| s["id"].as_str().map(str::to_owned))
123            .collect(),
124    };
125    for id in &pool {
126        get_shape(id)?;
127    }
128    let int = |key: &str, default: usize| {
129        own.get(key)
130            .and_then(Value::as_f64)
131            .map_or(default, to_usize)
132    };
133    let mut random = Random::new(to_seed(own.get("seed")));
134    let step = 24.0 + own.get("spacing").and_then(Value::as_f64).unwrap_or(2.0);
135    let kind = own.get("kind").and_then(Value::as_str).unwrap_or("band");
136    let mut cells = Vec::new();
137    let used: Vec<String>;
138    let (width, height);
139    match kind {
140        "band" => {
141            let n = int("count", 9);
142            let mirror = random.below(2) == 1;
143            used = choose(&pool, if mirror { 3 } else { 2 }, &mut random);
144            for i in 0..n {
145                let j = if mirror { i.min(n - 1 - i) } else { i };
146                cells.push(cell(i as f64 * step, 0.0, &nth(&used, j), 0.0, 1.0));
147            }
148            width = n as f64 * step - (step - 24.0);
149            height = 24.0;
150        }
151        "grid" => {
152            let (c, r) = (int("cols", 5), int("rows", 5));
153            used = choose(&pool, 2, &mut random);
154            for y in 0..r {
155                for x in 0..c {
156                    let shape = nth(&used, x + y);
157                    cells.push(cell(x as f64 * step, y as f64 * step, &shape, 0.0, 1.0));
158                }
159            }
160            width = c as f64 * step - (step - 24.0);
161            height = r as f64 * step - (step - 24.0);
162        }
163        "rosette" => {
164            let n = int("petals", 8);
165            used = choose(&pool, 2, &mut random);
166            cells.push(cell(step, step, &nth(&used, 0), 0.0, 1.0));
167            let petal = nth(&used, 1);
168            for i in 0..n {
169                let angle = (360.0 * i as f64) / n as f64;
170                let (c, s) = cos_sin(angle);
171                cells.push(cell(step + step * s, step - step * c, &petal, angle, 0.75));
172            }
173            width = 2.0 * step + 24.0;
174            height = width;
175        }
176        _ => {
177            let (c, r) = (int("cols", 7), int("rows", 3));
178            if c < 3 || r < 3 {
179                let issue = "cols, rows: a border needs at least 3 x 3 cells".to_owned();
180                return Err(DeqError::options("invalid pattern options", vec![issue]));
181            }
182            used = choose(&pool, 2, &mut random);
183            let (corner, edge) = (nth(&used, 0), nth(&used, 1));
184            let right = (c - 1) as f64 * step;
185            let bottom = (r - 1) as f64 * step;
186            for x in 0..c {
187                let end = x == 0 || x == c - 1;
188                let turn = if end && x > 0 { 90.0 } else { 0.0 };
189                let shape = if end { &corner } else { &edge };
190                cells.push(cell(x as f64 * step, 0.0, shape, turn, 1.0));
191            }
192            for y in 1..r - 1 {
193                cells.push(cell(right, y as f64 * step, &edge, 90.0, 1.0));
194            }
195            for x in (0..c).rev() {
196                let end = x == 0 || x == c - 1;
197                let turn = match (end, x > 0) {
198                    (true, true) | (false, _) => 180.0,
199                    (true, false) => 270.0,
200                };
201                let shape = if end { &corner } else { &edge };
202                cells.push(cell(x as f64 * step, bottom, shape, turn, 1.0));
203            }
204            for y in (1..r - 1).rev() {
205                cells.push(cell(0.0, y as f64 * step, &edge, 270.0, 1.0));
206            }
207            width = right + 24.0;
208            height = bottom + 24.0;
209        }
210    }
211    let placed = Scene {
212        width,
213        height,
214        cells,
215    };
216    let svg = scene_svg(&placed, &scene, &format!("Deq {kind} pattern"), "")?;
217    Ok(PatternResult {
218        svg,
219        motifs: used,
220        scene: placed,
221    })
222}