plottery_lib 0.12.0

Core geometry library of Plottery, a creative coding framework for generative vector graphics and pen plotting.
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
use crate::{Angle, Layer, Line, LineIntersection, Path, Shape, LARGE_EPSILON, V2};

use geo::BooleanOps;
use geo_types::{LineString, MultiLineString, Polygon};

use geometry_predicates::orient2d;
use itertools::Itertools;
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct SampleSettings {
    pub points_per_unit: f32,
}

impl SampleSettings {
    pub fn new(points_per_unit: f32) -> Self {
        Self { points_per_unit }
    }
    pub fn get_num_points_for_length(&self, length: f32) -> i32 {
        (length.abs() * self.points_per_unit).ceil() as i32
    }
    pub fn low_res() -> Self {
        Self {
            points_per_unit: 1.0,
        }
    }
}

impl From<f32> for SampleSettings {
    fn from(points_per_unit: f32) -> Self {
        Self::new(points_per_unit)
    }
}

impl Default for SampleSettings {
    fn default() -> Self {
        Self {
            points_per_unit: 50.0,
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct Masked {
    pub inside: Layer,
    pub outside: Layer,
}

pub trait Plottable: Clone + Into<Shape> {
    fn get_points(&self, _: SampleSettings) -> Vec<V2>;
    fn get_points_from(
        &self,
        current_drawing_head_pos: V2,
        sample_settings: SampleSettings,
    ) -> Vec<V2>;

    /// The shape sampled into a single [`Path`].
    #[must_use]
    fn to_path(&self, sample_settings: SampleSettings) -> Path {
        Path::new_from(self.get_points(sample_settings))
    }

    fn get_line_segments(&self, sample_settings: SampleSettings) -> Vec<Line> {
        self.get_points(sample_settings)
            .iter()
            .tuple_windows()
            .map(|(from, to)| Line::new(*from, *to))
            .collect()
    }

    fn length(&self) -> f32;

    fn is_closed(&self) -> bool;

    fn contains_point(&self, point: V2) -> bool; // assuming shape is closed

    fn reduce_points(&self, aggression_factor: f32) -> Self;

    /// Points of the shape with extra points inserted along segments longer than `1 / points_per_unit`.
    fn get_points_oversampled(&self, sample_settings: SampleSettings) -> Vec<V2> {
        let points = self.get_points(sample_settings);
        if points.is_empty() {
            return points;
        }
        let mut points_oversampled = vec![points[0]];
        for (from, to) in points.iter().tuple_windows() {
            let num_steps = sample_settings.get_num_points_for_length(from.dist(*to));
            if num_steps <= 1 {
                points_oversampled.push(*to);
            } else {
                let direction = to - from;
                let new_points =
                    (1..num_steps + 1).map(|i| from + direction * (i as f32 / num_steps as f32));
                points_oversampled.extend(new_points);
            }
        }
        points_oversampled
    }

    /// Oversamples the shape and maps every point through `f`.
    /// Consider [`reduce_points`](Plottable::reduce_points) on the result.
    fn distort<F: Fn(V2) -> V2>(&self, sample_settings: SampleSettings, f: F) -> Path {
        self.get_points_oversampled(sample_settings)
            .into_iter()
            .map(f)
            .collect()
    }

    /// Splits the shape into dashes of `dash_length` with gaps of `gap_length` in between.
    #[must_use]
    fn dash(&self, dash_length: f32, gap_length: f32, sample_settings: SampleSettings) -> Layer {
        self.dash_fn(sample_settings, |_, is_gap, _, _| {
            if is_gap {
                gap_length
            } else {
                dash_length
            }
        })
    }

    /// Dashes the shape, `f(point, is_gap, dist_along, fraction_along)` returns the length of the next dash or gap.
    fn dash_fn<F: Fn(V2, bool, f32, f32) -> f32>(
        &self,
        sample_settings: SampleSettings,
        f: F,
    ) -> Layer {
        let segments = self.get_line_segments(sample_settings);
        let total_length: f32 = segments.iter().map(|line| line.from.dist(line.to)).sum();
        let mut layer = Layer::new();
        if total_length <= 0.0 {
            return layer;
        }

        let mut dist_along = 0.0;
        let mut is_gap = false;
        let mut remaining = f(segments[0].from, false, 0.0, 0.0).max(LARGE_EPSILON);
        let mut current = Path::new();

        for line in segments {
            let length = line.from.dist(line.to);
            if length <= 0.0 {
                continue;
            }
            let mut pos = 0.0;
            while pos < length {
                let step = remaining.min(length - pos);
                let end = line.from + (line.to - line.from) * ((pos + step) / length);
                if !is_gap {
                    if current.is_empty() {
                        current.push(line.from + (line.to - line.from) * (pos / length));
                    }
                    current.push(end);
                }
                pos += step;
                dist_along += step;
                remaining -= step;

                if remaining <= LARGE_EPSILON {
                    if !is_gap {
                        layer.push(std::mem::take(&mut current));
                    }
                    is_gap = !is_gap;
                    remaining =
                        f(end, is_gap, dist_along, dist_along / total_length).max(LARGE_EPSILON);
                }
            }
        }
        if current.get_points_ref().len() > 1 {
            layer.push(current);
        }
        layer
    }

    /// Like [`get_points_oversampled`](Plottable::get_points_oversampled), paired with the distance along the shape.
    fn get_points_and_dist_oversampled(&self, sample_settings: SampleSettings) -> Vec<(V2, f32)> {
        let points = self.get_points(sample_settings);
        let mut dist_along_path = 0.0;
        if points.is_empty() {
            return vec![];
        }
        let mut points_oversampled = vec![(points[0], 0.0)];
        for (from, to) in points.iter().tuple_windows() {
            let num_steps = sample_settings.get_num_points_for_length(from.dist(*to));
            let segment_length = from.dist(*to);

            if num_steps <= 1 {
                points_oversampled.push((*to, dist_along_path + segment_length));
            } else {
                let direction = to - from;
                let new_points = (1..num_steps + 1).map(|i| {
                    let fraction = i as f32 / num_steps as f32;
                    let point = from + direction * fraction;
                    let dist = dist_along_path + segment_length * fraction;
                    (point, dist)
                });
                points_oversampled.extend(new_points);
            }
            dist_along_path += segment_length;
        }
        points_oversampled
    }

    fn as_geo_polygon(&self, sample_settings: SampleSettings) -> Polygon<f32> {
        Polygon::new(
            self.as_geo_line_string(sample_settings),
            vec![LineString(Vec::new())],
        )
    }

    fn as_geo_line_string(&self, sample_settings: SampleSettings) -> LineString<f32> {
        let coords = self
            .get_points(sample_settings)
            .iter()
            .map(V2::as_geo_coord)
            .collect_vec();
        LineString(coords)
    }

    fn as_geo_multi_line_string(&self, sample_settings: SampleSettings) -> MultiLineString<f32> {
        MultiLineString(vec![self.as_geo_line_string(sample_settings)])
    }

    fn mask_geo<M: Into<Shape>>(&self, mask: M, sample_settings: SampleSettings) -> Masked {
        let mask: Shape = mask.into();
        let shape_geo = self.as_geo_multi_line_string(sample_settings);
        let mask_geo = mask.as_geo_polygon(sample_settings);

        let masked_inside_geo = mask_geo.clip(&shape_geo, false);
        let masked_outside_geo = mask_geo.clip(&shape_geo, true);

        let layer_inside = Layer::from_iter(
            masked_inside_geo
                .iter()
                .map(Path::new_shape_from_geo_line_string),
        );
        let layer_outside = Layer::from_iter(
            masked_outside_geo
                .iter()
                .map(Path::new_shape_from_geo_line_string),
        );

        Masked {
            inside: layer_inside,
            outside: layer_outside,
        }
    }

    fn mask_geo_inside<M: Into<Shape>>(&self, mask: M, sample_settings: SampleSettings) -> Layer {
        let mask: Shape = mask.into();
        let shape_geo = self.as_geo_multi_line_string(sample_settings);
        let mask_geo = mask.as_geo_polygon(sample_settings);

        mask_geo
            .clip(&shape_geo, false)
            .iter()
            .map(Path::new_shape_from_geo_line_string)
            .collect()
    }

    fn mask_geo_outside<M: Into<Shape>>(&self, mask: M, sample_settings: SampleSettings) -> Layer {
        let mask: Shape = mask.into();
        let shape_geo = self.as_geo_multi_line_string(sample_settings);
        let mask_geo = mask.as_geo_polygon(sample_settings);

        mask_geo
            .clip(&shape_geo, true)
            .iter()
            .map(Path::new_shape_from_geo_line_string)
            .collect()
    }

    fn mask_brute_force<M: Into<Shape>>(&self, mask: M, sample_settings: SampleSettings) -> Masked {
        let mask: Shape = mask.into();
        let points_shape = self.get_points_oversampled(sample_settings);

        let mut inside = Layer::new();
        let mut outside = Layer::new();

        let Some(&first) = points_shape.first() else {
            return Masked::default();
        };
        let mut current_part = Path::new_from([first]);
        let mut is_inside = mask.contains_point(first);

        for point in points_shape {
            let new_inside = mask.contains_point(point);
            if is_inside != new_inside {
                if is_inside {
                    inside.push(current_part);
                } else {
                    outside.push(current_part);
                }
                current_part = Path::new_from(vec![point]);
            }
            is_inside = new_inside;
            current_part.push(point);
        }

        if is_inside {
            inside.push(current_part);
        } else {
            outside.push(current_part);
        }

        if inside.is_empty() && !outside.is_empty() {
            // shape is completely outside of mask
            return Masked {
                inside: Layer::new(),
                outside: self.to_layer(),
            };
        } else if outside.is_empty() && !inside.is_empty() {
            // shape is completely inside of mask
            return Masked {
                inside: self.to_layer(),
                outside: Layer::new(),
            };
        }

        Masked { inside, outside }
    }

    fn mask_by_intersections<M: Into<Shape>>(
        &self,
        mask: M,
        sample_settings: SampleSettings,
    ) -> Masked {
        let mask: Shape = mask.into();
        let segments_mask = mask.get_line_segments(sample_settings);

        // perturb the path to avoid points on the mask lines
        let mut perturbed_path = Path::new();
        for point in self.get_points(sample_settings) {
            let mut perturbed_point = point;
            loop {
                let (is_on_mask_line, line_angle) =
                    is_point_on_mask_line(perturbed_point, &segments_mask, 0.1);
                if is_on_mask_line {
                    perturbed_point += V2::polar(line_angle + Angle::quarter_rotation(), 0.05);
                    continue;
                }

                break;
            }
            perturbed_path.push(perturbed_point);
        }

        let segments_shape: Vec<_> = perturbed_path.get_line_segments(sample_settings);
        let mut inside = Layer::new();
        let mut outside = Layer::new();
        let Some(first_segment) = segments_shape.first() else {
            return Masked::default();
        };
        let mut current_part = Path::new_from([first_segment.from]);
        let mut currently_inside = mask.contains_point(*current_part.get_start().unwrap());

        // switch inside to outside on each intersection
        for segment in segments_shape {
            let intersections_sorted = get_intersections_sorted(&segment, &segments_mask);

            for intersection in intersections_sorted {
                current_part.push(intersection);
                if currently_inside {
                    inside.push(current_part);
                } else {
                    outside.push(current_part);
                }
                current_part = Path::new_from(vec![intersection]);
                currently_inside = !currently_inside;
            }

            current_part.push(segment.to);
        }

        if currently_inside {
            inside.push(current_part);
        } else {
            outside.push(current_part);
        }

        Masked { inside, outside }
    }

    #[must_use]
    fn to_layer(&self) -> Layer {
        Layer::new_from(vec![self.clone().into()])
    }
}

fn get_intersections_sorted(segment: &Line, segments_mask: &[Line]) -> Vec<V2> {
    segments_mask
        .iter()
        .map(|segment_mask| segment.intersection(*segment_mask))
        .filter_map(|intersection| match intersection {
            LineIntersection::Intersection(point) => Some(point),
            _ => None,
        })
        .sorted_by_cached_key(|point| point.dist_squared(segment.from).to_bits())
        .collect()
}

fn is_point_on_mask_line(point: V2, segments_mask: &[Line], epsilon: f64) -> (bool, Angle) {
    for segment_mask in segments_mask {
        let orientation = orient2d(
            [segment_mask.from.x as f64, segment_mask.from.y as f64],
            [segment_mask.to.x as f64, segment_mask.to.y as f64],
            [point.x as f64, point.y as f64],
        );
        if orientation < epsilon && orientation > -epsilon {
            return (true, segment_mask.angle());
        }
    }
    (false, Angle::zero())
}