Skip to main content

drawland_graph/
api.rs

1//! The library for Rust: the same functions a JavaScript or Python profile
2//! calls, as methods. Handles are typed ([`Features`], [`Area`], [`Lines`]);
3//! options are objects ([`crate::obj!`]), with the keys the library documents
4//! (`drawland.d.ts`, the reference at draw.land/docs).
5//!
6//! ```
7//! use drawland_graph::{obj, Graph};
8//!
9//! let mut g = Graph::new(Some((37.8053, -122.4436)));
10//! g.output(obj! { "width" => "6in", "height" => "4in", "scale" => "1:10000" })?;
11//! let water = g.features().tiles(&["water"])?;
12//! let sea = g.areas().polygons(&water)?;
13//! let waves = g.fills().fill(obj! { "in" => &sea, "pattern" => "waves", "spacing" => "0.8mm" })?;
14//! g.draw(obj! { "id" => "water", "from" => &waves })?;
15//! let centre = g.world().center()?;
16//! assert!((centre.0 - 37.8053).abs() < 1e-9);
17//! # Ok::<(), drawland_graph::Error>(())
18//! ```
19
20use crate::arg::{Arg, Obj};
21use crate::graph::{Graph, Result};
22
23/// A set of map features (`features.*`).
24#[derive(Clone, Debug, PartialEq)]
25pub struct Features(pub(crate) Arg);
26
27/// An area (`areas.*`, `page.frame`, a module's area).
28#[derive(Clone, Debug, PartialEq)]
29pub struct Area(pub(crate) Arg);
30
31/// Lines (`lines.*`, `fills.fill`, a module's output).
32#[derive(Clone, Debug, PartialEq)]
33pub struct Lines(pub(crate) Arg);
34
35macro_rules! handle {
36    ($t:ident) => {
37        impl From<&$t> for Arg {
38            fn from(h: &$t) -> Arg {
39                h.0.clone()
40            }
41        }
42        impl From<$t> for Arg {
43            fn from(h: $t) -> Arg {
44                h.0
45            }
46        }
47        impl $t {
48            /// The handle as the library passes it.
49            pub fn arg(&self) -> &Arg {
50                &self.0
51            }
52        }
53    };
54}
55handle!(Features);
56handle!(Area);
57handle!(Lines);
58
59impl Features {
60    fn of(a: Arg) -> Features {
61        Features(a)
62    }
63}
64impl Area {
65    fn of(a: Arg) -> Area {
66        Area(a)
67    }
68}
69impl Lines {
70    fn of(a: Arg) -> Lines {
71        Lines(a)
72    }
73}
74
75/// `modules.roads(…)`: what the roads module publishes.
76#[derive(Clone, Debug)]
77pub struct Roads {
78    pub area: Area,
79    pub outlines: Lines,
80    pub details: Lines,
81    pub trails: Lines,
82    pub centerlines: Lines,
83    pub seams: Lines,
84    pub rails: Lines,
85}
86
87/// `modules.labels(…)` or a graticule: parts made when asked for with
88/// [`Module::area`], [`Module::part`]…
89#[derive(Clone, Debug)]
90pub struct Module(pub(crate) Arg);
91
92fn list<T: Into<Arg> + Clone>(items: &[T]) -> Arg {
93    Arg::List(items.iter().cloned().map(Into::into).collect())
94}
95
96fn many<T>(items: &[&T]) -> Vec<Arg>
97where
98    for<'a> &'a T: Into<Arg>,
99{
100    items.iter().map(|h| (*h).into()).collect()
101}
102
103/// `features.*`: what to read from the map.
104pub struct FeaturesApi<'g>(&'g mut Graph);
105/// `areas.*`: shapes on the page.
106pub struct AreasApi<'g>(&'g mut Graph);
107/// `lines.*`: strokes.
108pub struct LinesApi<'g>(&'g mut Graph);
109/// `fills.*`: patterns inside areas.
110pub struct FillsApi<'g>(&'g mut Graph);
111/// `modules.*`: roads, labels, graticules.
112pub struct ModulesApi<'g>(&'g mut Graph);
113/// `compose.*`: stacking, masks, and the plotter's steps.
114pub struct ComposeApi<'g>(&'g mut Graph);
115/// `page.*`: the paper, in mm from its top left.
116pub struct PageApi<'g>(&'g mut Graph);
117/// `world.*`: the ground under the page.
118pub struct WorldApi<'g>(&'g mut Graph);
119
120impl Graph {
121    pub fn features(&mut self) -> FeaturesApi<'_> {
122        FeaturesApi(self)
123    }
124    pub fn areas(&mut self) -> AreasApi<'_> {
125        AreasApi(self)
126    }
127    pub fn lines(&mut self) -> LinesApi<'_> {
128        LinesApi(self)
129    }
130    pub fn fills(&mut self) -> FillsApi<'_> {
131        FillsApi(self)
132    }
133    pub fn modules(&mut self) -> ModulesApi<'_> {
134        ModulesApi(self)
135    }
136    pub fn compose(&mut self) -> ComposeApi<'_> {
137        ComposeApi(self)
138    }
139    pub fn page(&mut self) -> PageApi<'_> {
140        PageApi(self)
141    }
142    pub fn world(&mut self) -> WorldApi<'_> {
143        WorldApi(self)
144    }
145
146    /// Where the map is and on what paper: `{ lat, lng, width, height,
147    /// scale, bearing, projection, padding, slices, warp, tileZoom }`. A
148    /// `remap` warp is a function of page points: [`Graph::output_remap`].
149    pub fn output(&mut self, spec: Obj) -> Result<()> {
150        self.call("output", &[Arg::Map(spec)]).map(|_| ())
151    }
152
153    /// `output` with `remaps[i]` the function of the `i`-th `remap` warp in
154    /// `spec.warp` (written `{ "remap": true, "grid": 64 }`): each runs on a
155    /// grid of page points, and may read the ground under one with
156    /// `g.page().to_world(p)` (through the warps before it).
157    pub fn output_remap(&mut self, mut spec: Obj, remaps: &mut [&mut dyn FnMut(&mut Graph, [f64; 2]) -> Result<[f64; 2]>]) -> Result<()> {
158        let warps: Vec<Arg> = match spec.get("warp") {
159            None | Some(Arg::Null) => vec![],
160            Some(Arg::List(l)) => l.clone(),
161            Some(w) => vec![w.clone()],
162        };
163        let marked: Vec<Arg> = warps
164            .iter()
165            .map(|w| match w {
166                Arg::Map(o) if o.has("remap") => {
167                    let mut o = o.clone();
168                    o.set("remap", Arg::Func);
169                    Arg::Map(o)
170                }
171                other => other.clone(),
172            })
173            .collect();
174        spec.set("warp", Arg::List(marked.clone()));
175        if !self.output_begin(&spec)? {
176            return Ok(());
177        }
178        let mut done = Vec::new();
179        let mut next = 0;
180        for (n, w) in marked.iter().enumerate() {
181            match w {
182                Arg::Map(o) if o.has("remap") => {
183                    self.output_warps(&done)?;
184                    let (columns, rows, points) = self.remap_grid(o, n)?;
185                    let f = remaps.get_mut(next).ok_or_else(|| self.error(format!("output.warp[{n}]: no function given for this remap")))?;
186                    next += 1;
187                    let mut went = Vec::with_capacity(points.len());
188                    for p in &points {
189                        let [x, y] = f(self, *p)?;
190                        went.push(Arg::List(vec![Arg::Num(x), Arg::Num(y)]));
191                    }
192                    done.push(self.remap_mesh(n, columns, rows, &points, &went)?);
193                }
194                other => done.push(other.clone()),
195            }
196        }
197        self.output_warps(&done)
198    }
199
200    /// The map's title, for the SVG and the files.
201    pub fn title(&mut self, text: &str) -> Result<()> {
202        self.call("title", &[Arg::str(text)]).map(|_| ())
203    }
204
205    /// Draw lines as a group (a pen): `{ id, from, stroke }`. Its group id.
206    pub fn draw(&mut self, spec: Obj) -> Result<String> {
207        match self.call("draw", &[Arg::Map(spec)])? {
208            Arg::Str(id) => Ok(id),
209            _ => Ok(String::new()),
210        }
211    }
212
213    /// Another place drawn into a rectangle of the page: `{ id, at, size,
214    /// lat, lng, scale, … }`, its graph built by `style`. Its id.
215    pub fn view(&mut self, spec: Obj, style: impl FnOnce(&mut Graph) -> Result<()>) -> Result<String> {
216        self.view_begin(&Arg::Map(spec))?;
217        let built = style(self);
218        let id = self.view_end(built.is_ok())?;
219        built?;
220        Ok(id.as_str().unwrap_or_default().to_string())
221    }
222}
223
224impl FeaturesApi<'_> {
225    /// OpenFreeMap's vector tiles: presets (`"buildings"`) or rules (`"landcover:park,garden"`).
226    pub fn tiles(self, items: &[&str]) -> Result<Features> {
227        self.0.call("features.tiles", &[list(items)]).map(Features::of)
228    }
229    /// OpenStreetMap through Overpass: `{ leisure: "park" }`.
230    pub fn osm(self, tags: Obj) -> Result<Features> {
231        self.0.call("features.osm", &[Arg::Map(tags)]).map(Features::of)
232    }
233    /// A GeoJSON dataset: a URL, a file beside the profile, or inline GeoJSON.
234    pub fn geojson(self, source: impl Into<Arg>) -> Result<Features> {
235        self.0.call("features.geojson", &[source.into()]).map(Features::of)
236    }
237    /// Points from plain JSON: `{ items, lat, lng }` as dot-paths.
238    pub fn json(self, url: &str, paths: Obj) -> Result<Features> {
239        self.0.call("features.json", &[Arg::str(url), Arg::Map(paths)]).map(Features::of)
240    }
241    /// Contour lines from the elevation: `{ step, from, to, index, blur, minLength }`.
242    pub fn contours(self, options: Obj) -> Result<Features> {
243        self.0.call("features.contours", &[Arg::Map(options)]).map(Features::of)
244    }
245    /// Depth soundings: `{ every, on, blur, jitter }`.
246    pub fn soundings(self, options: Obj) -> Result<Features> {
247        self.0.call("features.soundings", &[Arg::Map(options)]).map(Features::of)
248    }
249    /// The features whose tags pass every test.
250    pub fn filter(self, of: &Features, tags: Obj) -> Result<Features> {
251        self.0.call("features.where", &[of.into(), Arg::Map(tags)]).map(Features::of)
252    }
253}
254
255impl AreasApi<'_> {
256    pub fn polygons(self, of: &Features) -> Result<Area> {
257        self.0.call("areas.polygons", &[of.into()]).map(Area::of)
258    }
259    pub fn union(self, areas: &[&Area]) -> Result<Area> {
260        self.0.call("areas.union", &many(areas)).map(Area::of)
261    }
262    pub fn difference(self, base: &Area, cut: &[&Area]) -> Result<Area> {
263        let mut args = vec![base.into()];
264        args.extend(many(cut));
265        self.0.call("areas.difference", &args).map(Area::of)
266    }
267    pub fn intersect(self, base: &Area, keep: &Area) -> Result<Area> {
268        self.0.call("areas.intersect", &[base.into(), keep.into()]).map(Area::of)
269    }
270    pub fn fill_holes(self, of: &Area) -> Result<Area> {
271        self.0.call("areas.fillHoles", &[of.into()]).map(Area::of)
272    }
273    pub fn grow(self, of: &Area, by: impl Into<Arg>) -> Result<Area> {
274        self.0.call("areas.grow", &[of.into(), by.into()]).map(Area::of)
275    }
276    /// Moved across the page by `[across, down]`.
277    pub fn moved(self, of: &Area, by: [impl Into<Arg> + Clone; 2]) -> Result<Area> {
278        self.0.call("areas.move", &[of.into(), Arg::from(by)]).map(Area::of)
279    }
280    pub fn around(self, of: &Features, by: impl Into<Arg>) -> Result<Area> {
281        self.0.call("areas.around", &[of.into(), by.into()]).map(Area::of)
282    }
283    pub fn buffer(self, of: &Lines, by: impl Into<Arg>, options: Obj) -> Result<Area> {
284        self.0.call("areas.buffer", &[of.into(), by.into(), Arg::Map(options)]).map(Area::of)
285    }
286    pub fn shape(self, spec: Obj) -> Result<Area> {
287        self.0.call("areas.shape", &[Arg::Map(spec)]).map(Area::of)
288    }
289    pub fn text(self, spec: Obj) -> Result<Area> {
290        self.0.call("areas.text", &[Arg::Map(spec)]).map(Area::of)
291    }
292    /// A band of the elevation: `{ elevMin, elevMax, depthMin, depthMax }`.
293    pub fn band(self, band: Obj, options: Obj) -> Result<Area> {
294        self.0.call("areas.band", &[Arg::Map(band), Arg::Map(options)]).map(Area::of)
295    }
296    pub fn extend_to_frame(self, of: &Area, within: &Area, options: Obj) -> Result<Area> {
297        self.0.call("areas.extendToFrame", &[of.into(), within.into(), Arg::Map(options)]).map(Area::of)
298    }
299    /// The open sea from the tiles, grown to the page's edge.
300    pub fn ocean(self) -> Result<Area> {
301        self.0.call("engine.ocean", &[]).map(Area::of)
302    }
303}
304
305impl LinesApi<'_> {
306    pub fn of(self, features: &Features) -> Result<Lines> {
307        self.0.call("lines.of", &[features.into()]).map(Lines::of)
308    }
309    pub fn rings(self, of: &Area, options: Obj) -> Result<Lines> {
310        self.0.call("lines.rings", &[of.into(), Arg::Map(options)]).map(Lines::of)
311    }
312    pub fn segments(self, features: &Features) -> Result<Lines> {
313        self.0.call("lines.segments", &[features.into()]).map(Lines::of)
314    }
315    pub fn shape(self, spec: Obj) -> Result<Lines> {
316        self.0.call("lines.shape", &[Arg::Map(spec)]).map(Lines::of)
317    }
318    pub fn text(self, spec: Obj) -> Result<Lines> {
319        self.0.call("lines.text", &[Arg::Map(spec)]).map(Lines::of)
320    }
321    pub fn dedupe(self, of: &Lines) -> Result<Lines> {
322        self.0.call("lines.dedupe", &[of.into()]).map(Lines::of)
323    }
324    pub fn merge(self, of: &Lines) -> Result<Lines> {
325        self.0.call("lines.merge", &[of.into()]).map(Lines::of)
326    }
327    pub fn join(self, sets: &[&Lines]) -> Result<Lines> {
328        self.0.call("lines.join", &many(sets)).map(Lines::of)
329    }
330    pub fn clip(self, of: &Lines, within: &Area, options: Obj) -> Result<Lines> {
331        self.0.call("lines.clip", &[of.into(), within.into(), Arg::Map(options)]).map(Lines::of)
332    }
333    pub fn terrain(self, options: Obj) -> Result<Lines> {
334        self.0.call("lines.terrain", &[Arg::Map(options)]).map(Lines::of)
335    }
336    pub fn contours(self, options: Obj) -> Result<Lines> {
337        self.0.call("lines.contours", &[Arg::Map(options)]).map(Lines::of)
338    }
339    /// A burin document (its JSON, as burin builds it) drawn on the terrain.
340    pub fn burin(self, atlas: serde_json::Value, options: Obj) -> Result<Lines> {
341        self.0.call("burin.terrain", &[Arg::from_json(&atlas), Arg::Map(options)]).map(Lines::of)
342    }
343}
344
345impl FillsApi<'_> {
346    /// A pattern inside an area: `{ in, pattern, spacing, angle, per, … }`.
347    pub fn fill(self, spec: Obj) -> Result<Lines> {
348        self.0.call("fills.fill", &[Arg::Map(spec)]).map(Lines::of)
349    }
350    /// What a fill with the same options covers on paper.
351    pub fn cover(self, spec: Obj) -> Result<Area> {
352        self.0.call("fills.cover", &[Arg::Map(spec)]).map(Area::of)
353    }
354}
355
356impl ModulesApi<'_> {
357    pub fn roads(self, options: Obj) -> Result<Roads> {
358        let out = self.0.call("modules.roads", &[Arg::Map(options)])?;
359        let o = out.as_map().cloned().unwrap_or_default();
360        let lines = |k: &str| Lines(o.get(k).cloned().unwrap_or(Arg::Null));
361        Ok(Roads {
362            area: Area(o.get("area").cloned().unwrap_or(Arg::Null)),
363            outlines: lines("outlines"),
364            details: lines("details"),
365            trails: lines("trails"),
366            centerlines: lines("centerlines"),
367            seams: lines("seams"),
368            rails: lines("rails"),
369        })
370    }
371    pub fn labels(self, options: Obj) -> Result<Module> {
372        self.0.call("modules.labels", &[Arg::Map(options)]).map(Module)
373    }
374    pub fn graticule(self, options: Obj) -> Result<Module> {
375        self.0.call("modules.graticule", &[Arg::Map(options)]).map(Module)
376    }
377}
378
379impl Module {
380    /// A part as lines: `lines`, a graticule's `labels`, a rule's `lines`.
381    pub fn lines(&self, g: &mut Graph, part: &str) -> Result<Lines> {
382        g.get(&self.0, part).map(Lines)
383    }
384    /// A part as an area: `area`, `dots`, a graticule's `keys` and `labelArea`.
385    pub fn area(&self, g: &mut Graph, part: &str) -> Result<Area> {
386        g.get(&self.0, part).map(Area)
387    }
388    /// A labels rule's bucket, by its id.
389    pub fn rule(&self, g: &mut Graph, id: &str) -> Result<Module> {
390        g.get(&self.0, id).map(Module)
391    }
392}
393
394impl ComposeApi<'_> {
395    /// Bottom to top.
396    pub fn order(self, ids: &[&str]) -> Result<()> {
397        self.0.call("compose.order", &[list(ids)]).map(|_| ())
398    }
399    /// `{ name, from: area, occludes: [ids] }`.
400    pub fn mask(self, spec: Obj) -> Result<()> {
401        self.0.call("compose.mask", &[Arg::Map(spec)]).map(|_| ())
402    }
403    /// `"auto"`, `"none"`, or the areas to clip to.
404    pub fn clip(self, clip: impl Into<Arg>) -> Result<()> {
405        self.0.call("compose.clip", &[clip.into()]).map(|_| ())
406    }
407    /// A plotter step: `step` is `deoverlap`, `linemerge`, `simplify`,
408    /// `filter`, `reloop`, `hand`, `orient` or `linesort`, on the groups
409    /// `layers` (none: every group), with its options (and `except`).
410    pub fn step(self, step: &str, layers: &[&str], options: Obj) -> Result<()> {
411        let mut args = Vec::new();
412        if !layers.is_empty() {
413            args.push(list(layers));
414        }
415        args.push(Arg::Map(options));
416        self.0.call(&format!("compose.{step}"), &args).map(|_| ())
417    }
418}
419
420impl PageApi<'_> {
421    pub fn width(self) -> Result<f64> {
422        self.0.get_property("page.width").map(|v| v.as_num().unwrap_or(0.0))
423    }
424    pub fn height(self) -> Result<f64> {
425        self.0.get_property("page.height").map(|v| v.as_num().unwrap_or(0.0))
426    }
427    pub fn center(self) -> Result<[f64; 2]> {
428        let w = self.0.get_property("page.width")?.as_num().unwrap_or(0.0);
429        let h = self.0.get_property("page.height")?.as_num().unwrap_or(0.0);
430        Ok([w / 2.0, h / 2.0])
431    }
432    /// The paper as an area.
433    pub fn frame(self) -> Result<Area> {
434        self.0.get_property("page.frame").map(Area)
435    }
436    /// The ground at `[x, y]` (mm): `(lat, lng)`.
437    pub fn to_world(self, p: [f64; 2]) -> Result<(f64, f64)> {
438        let v = self.0.call("page.toWorld", &[Arg::from(p)])?;
439        let o = v.as_map().cloned().unwrap_or_default();
440        Ok((o.get("lat").and_then(Arg::as_num).unwrap_or(0.0), o.get("lng").and_then(Arg::as_num).unwrap_or(0.0)))
441    }
442}
443
444impl WorldApi<'_> {
445    pub fn scale(self) -> Result<f64> {
446        self.0.get_property("world.scale").map(|v| v.as_num().unwrap_or(0.0))
447    }
448    pub fn bearing(self) -> Result<f64> {
449        self.0.get_property("world.bearing").map(|v| v.as_num().unwrap_or(0.0))
450    }
451    /// The place at the middle of the page: `(lat, lng)`.
452    pub fn center(self) -> Result<(f64, f64)> {
453        let o = self.0.get_property("world.center")?.as_map().cloned().unwrap_or_default();
454        Ok((o.get("lat").and_then(Arg::as_num).unwrap_or(0.0), o.get("lng").and_then(Arg::as_num).unwrap_or(0.0)))
455    }
456    /// `(north, south, east, west)` round the page's edge.
457    pub fn bounds(self) -> Result<(f64, f64, f64, f64)> {
458        let o = self.0.get_property("world.bounds")?.as_map().cloned().unwrap_or_default();
459        let n = |k: &str| o.get(k).and_then(Arg::as_num).unwrap_or(0.0);
460        Ok((n("north"), n("south"), n("east"), n("west")))
461    }
462    /// Where the map draws `(lat, lng)`: `[x, y]` in page mm.
463    pub fn to_page(self, lat: f64, lng: f64) -> Result<[f64; 2]> {
464        let v = self.0.call("world.toPage", &[Arg::Map(crate::obj! { "lat" => lat, "lng" => lng })])?;
465        let l = v.as_list().unwrap_or(&[]);
466        Ok([l.first().and_then(Arg::as_num).unwrap_or(0.0), l.get(1).and_then(Arg::as_num).unwrap_or(0.0)])
467    }
468}