roughr 0.14.0

Generate Hand Sketched 2D Drawings
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
use euclid::default::Point2D;
use euclid::Trig;
use num_traits::{Float, FromPrimitive};
use palette::Srgba;
use rand::rngs::StdRng;
use rand::{random, Rng, SeedableRng};

/// How the fill color of a closed shape is sketched. Set it with
/// [`OptionsBuilder::fill_style`]; it only has an effect when
/// [`Options::fill`] is set.
///
/// ![fill_style](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/fill_style.png)
#[derive(Clone, PartialEq, Debug, Copy, Eq)]
pub enum FillStyle {
    /// Fills the shape with the fill color, like a regular fill.
    Solid,
    /// Parallel sketchy lines. This is the style used when
    /// [`Options::fill_style`] is `None`.
    Hachure,
    /// Hachure lines joined into a zigzag.
    ZigZag,
    /// Two sets of hachure lines crossing at right angles.
    CrossHatch,
    /// Hand drawn dots laid out along hachure lines.
    Dots,
    /// Hachure lines broken into dashes; see [`Options::dash_offset`] and
    /// [`Options::dash_gap`].
    Dashed,
    /// Hachure lines drawn as small zigzags; see [`Options::zigzag_offset`].
    ZigZagLine,
}

impl ToString for FillStyle {
    fn to_string(&self) -> String {
        match self {
            FillStyle::Solid => "Solid".into(),
            FillStyle::Hachure => "Hachure".into(),
            FillStyle::ZigZag => "ZigZag".into(),
            FillStyle::CrossHatch => "CrossHatch".into(),
            FillStyle::Dots => "Dots".into(),
            FillStyle::Dashed => "Dashed".into(),
            FillStyle::ZigZagLine => "ZigZagLine".into(),
        }
    }
}

/// How the ends of open strokes are drawn. Applied by the adapter crates when
/// a dash pattern is set.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum LineCap {
    Butt,
    Round,
    Square,
}

impl Default for LineCap {
    fn default() -> Self {
        LineCap::Butt
    }
}

/// Options for angled joins in strokes.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum LineJoin {
    Miter { limit: f64 },
    Round,
    Bevel,
}
impl LineJoin {
    pub const DEFAULT_MITER_LIMIT: f64 = 10.0;
}
impl Default for LineJoin {
    fn default() -> Self {
        LineJoin::Miter { limit: LineJoin::DEFAULT_MITER_LIMIT }
    }
}

/// Settings that control how shapes are sketched.
///
/// Build it with [`OptionsBuilder`]; every field has a default, so set only
/// what you want to change:
///
/// ```
/// use palette::Srgba;
/// use roughr::core::{FillStyle, OptionsBuilder};
///
/// let options = OptionsBuilder::default()
///     .roughness(1.5)
///     .stroke(Srgba::new(0.45, 0.34, 0.32, 1.0))
///     .fill(Srgba::new(1.0, 0.96, 0.79, 1.0))
///     .fill_style(FillStyle::CrossHatch)
///     .build()
///     .unwrap();
/// ```
///
/// The images below each field show the same shape with only that field
/// changed, from left to right. They are generated by the `options_gallery`
/// example of `rough_tiny_skia`. To try options interactively, run the
/// `drawing_app` example of `rough_iced`.
#[derive(Clone, Builder)]
#[builder(setter(strip_option))]
pub struct Options {
    /// Upper bound, in pixels, for how far line end points and bowing are
    /// randomly moved. It is scaled by [`roughness`](Options::roughness).
    ///
    /// Default: `2.0`.
    ///
    /// ![max_randomness_offset](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/max_randomness_offset.png)
    #[builder(default = "Some(2.0)")]
    pub max_randomness_offset: Option<f32>,
    /// How far lines wander from the true shape. `0` draws a clean shape;
    /// values above `2` look very sketchy. For SVG paths, higher roughness
    /// also samples curves more coarsely.
    ///
    /// Default: `1.0`.
    ///
    /// ![roughness](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/roughness.png)
    #[builder(default = "Some(1.0)")]
    pub roughness: Option<f32>,
    /// How much straight lines bend in the middle, like a hand drawn line.
    /// `0` keeps lines straight.
    ///
    /// Default: `2.0`.
    ///
    /// ![bowing](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/bowing.png)
    #[builder(default = "Some(2.0)")]
    pub bowing: Option<f32>,
    /// Outline color. Set it to a transparent color to hide the outline.
    ///
    /// Default: opaque black.
    #[builder(default = "Some(Srgba::new(0.0, 0.0, 0.0, 1.0))")]
    pub stroke: Option<Srgba>,
    /// Outline width in pixels. Also the base for the automatic
    /// [`fill_weight`](Options::fill_weight) and
    /// [`hachure_gap`](Options::hachure_gap).
    ///
    /// Default: `1.0`.
    ///
    /// ![stroke_width](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/stroke_width.png)
    #[builder(default = "Some(1.0)")]
    pub stroke_width: Option<f32>,
    /// How closely ellipses, circles and arcs follow their true radius, from
    /// `0` to `1`. Lower values make round shapes more lopsided.
    ///
    /// Default: `0.95`.
    ///
    /// ![curve_fitting](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/curve_fitting.png)
    #[builder(default = "Some(0.95)")]
    pub curve_fitting: Option<f32>,
    /// How tightly [`curve`](crate::generator::Generator::curve) passes
    /// through its points. `0` gives smooth curves, `1` straight segments.
    ///
    /// Default: `0.0`.
    ///
    /// ![curve_tightness](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/curve_tightness.png)
    #[builder(default = "Some(0.0)")]
    pub curve_tightness: Option<f32>,
    /// How many points are used to approximate ellipses, circles and arcs.
    /// Low values give polygon-like shapes; large shapes get extra points
    /// automatically.
    ///
    /// Default: `9.0`.
    ///
    /// ![curve_step_count](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/curve_step_count.png)
    #[builder(default = "Some(9.0)")]
    pub curve_step_count: Option<f32>,
    /// Fill color of closed shapes. Shapes are only filled when this is set.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub fill: Option<Srgba>,
    /// How the fill color is sketched; see [`FillStyle`].
    ///
    /// Default: `None`, which fills with [`FillStyle::Hachure`].
    #[builder(default = "None")]
    pub fill_style: Option<FillStyle>,
    /// Width of the lines of sketched fills, in pixels. A negative value
    /// uses half of [`stroke_width`](Options::stroke_width). For
    /// [`FillStyle::Dots`] it is the dot size.
    ///
    /// Default: `-1.0`.
    ///
    /// ![fill_weight](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/fill_weight.png)
    #[builder(default = "Some(-1.0)")]
    pub fill_weight: Option<f32>,
    /// Angle of the fill lines, in degrees.
    ///
    /// Default: `-41.0`.
    ///
    /// ![hachure_angle](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/hachure_angle.png)
    #[builder(default = "Some(-41.0)")]
    pub hachure_angle: Option<f32>,
    /// Space between fill lines, in pixels. A negative value uses four times
    /// [`stroke_width`](Options::stroke_width).
    ///
    /// Default: `-1.0`.
    ///
    /// ![hachure_gap](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/hachure_gap.png)
    #[builder(default = "Some(-1.0)")]
    pub hachure_gap: Option<f32>,
    /// Below `1`, SVG paths passed to
    /// [`path`](crate::generator::Generator::path) are sampled with fewer
    /// points, so curves become simpler and more angular. `1` keeps all detail.
    ///
    /// Default: `1.0`.
    ///
    /// ![simplification](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/simplification.png)
    #[builder(default = "Some(1.0)")]
    pub simplification: Option<f32>,
    /// Length of each dash for [`FillStyle::Dashed`], in pixels. A negative
    /// value uses [`hachure_gap`](Options::hachure_gap).
    ///
    /// Default: `-1.0`.
    ///
    /// ![dash_offset](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/dash_offset.png)
    #[builder(default = "Some(-1.0)")]
    pub dash_offset: Option<f32>,
    /// Gap between dashes for [`FillStyle::Dashed`], in pixels. A negative
    /// value uses [`hachure_gap`](Options::hachure_gap).
    ///
    /// Default: `-1.0`.
    ///
    /// ![dash_gap](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/dash_gap.png)
    #[builder(default = "Some(-1.0)")]
    pub dash_gap: Option<f32>,
    /// Size of each zigzag for [`FillStyle::ZigZagLine`], in pixels. A
    /// negative value uses [`hachure_gap`](Options::hachure_gap).
    ///
    /// Default: `-1.0`.
    ///
    /// ![zigzag_offset](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/zigzag_offset.png)
    #[builder(default = "Some(-1.0)")]
    pub zigzag_offset: Option<f32>,
    /// Seed for the random number generator. The same seed and options always
    /// produce the same drawing; set `None` for a different drawing on every
    /// run.
    ///
    /// Default: `345`.
    ///
    /// ![seed](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/seed.png)
    #[builder(default = "Some(345_u64)")]
    pub seed: Option<u64>,
    /// Dash pattern for outlines, as alternating dash and gap lengths in
    /// pixels. Applied by the adapter crates, except `rough_plotters_svg`.
    ///
    /// Default: `None`.
    ///
    /// ![stroke_line_dash](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/stroke_line_dash.png)
    #[builder(default = "None")]
    pub stroke_line_dash: Option<Vec<f64>>,
    /// Offset into [`stroke_line_dash`](Options::stroke_line_dash), in pixels.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub stroke_line_dash_offset: Option<f64>,
    /// Line cap used together with the dash patterns.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub line_cap: Option<LineCap>,
    /// Line join used together with the dash patterns.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub line_join: Option<LineJoin>,
    /// Dash pattern for the lines of sketched fills, like
    /// [`stroke_line_dash`](Options::stroke_line_dash).
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub fill_line_dash: Option<Vec<f64>>,
    /// Offset into [`fill_line_dash`](Options::fill_line_dash), in pixels.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub fill_line_dash_offset: Option<f64>,
    /// Draws each outline once instead of twice. The double stroke is what
    /// makes lines look hand drawn; disable it for a cleaner look.
    ///
    /// Default: `false`.
    ///
    /// ![disable_multi_stroke](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/disable_multi_stroke.png)
    #[builder(default = "Some(false)")]
    pub disable_multi_stroke: Option<bool>,
    /// Draws each fill line once instead of twice.
    ///
    /// Default: `false`.
    ///
    /// ![disable_multi_stroke_fill](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/disable_multi_stroke_fill.png)
    #[builder(default = "Some(false)")]
    pub disable_multi_stroke_fill: Option<bool>,
    /// Keeps the corners of polygons, rectangles and paths at their exact
    /// position; only the lines between them are roughened.
    ///
    /// Default: `false`.
    ///
    /// ![preserve_vertices](https://raw.githubusercontent.com/orhanbalci/rough-rs/roughr@0.14.0/roughr/assets/options/preserve_vertices.png)
    #[builder(default = "Some(false)")]
    pub preserve_vertices: Option<bool>,
    /// Carried over from Rough.js. Currently has no effect.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub fixed_decimal_place_digits: Option<f32>,
    /// Random number generator state, created from [`seed`](Options::seed) on
    /// first use. You do not need to set this.
    ///
    /// Default: `None`.
    #[builder(default = "None")]
    pub randomizer: Option<StdRng>,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            max_randomness_offset: Some(2.0),
            roughness: Some(1.0),
            bowing: Some(2.0),
            stroke: Some(Srgba::new(0.0, 0.0, 0.0, 1.0)),
            stroke_width: Some(1.0),
            curve_tightness: Some(0.0),
            curve_fitting: Some(0.95),
            curve_step_count: Some(9.0),
            fill: None,
            fill_style: None,
            fill_weight: Some(-1.0),
            hachure_angle: Some(-41.0),
            hachure_gap: Some(-1.0),
            dash_offset: Some(-1.0),
            dash_gap: Some(-1.0),
            zigzag_offset: Some(-1.0),
            seed: Some(345_u64),
            disable_multi_stroke: Some(false),
            disable_multi_stroke_fill: Some(false),
            preserve_vertices: Some(false),
            simplification: Some(1.0),
            stroke_line_dash: None,
            stroke_line_dash_offset: None,
            line_cap: None,
            line_join: None,
            fill_line_dash: None,
            fill_line_dash_offset: None,
            fixed_decimal_place_digits: None,
            randomizer: None,
        }
    }
}

impl Options {
    pub fn random(&mut self) -> f64 {
        match &mut self.randomizer {
            Some(r) => r.gen(),
            None => match self.seed {
                Some(s) => {
                    let rnd = self.randomizer.insert(StdRng::seed_from_u64(s));
                    rnd.gen()
                }
                None => {
                    let rnd = self.randomizer.insert(StdRng::seed_from_u64(random()));
                    rnd.gen()
                }
            },
        }
    }

    pub fn set_hachure_angle(&mut self, angle: Option<f32>) -> &mut Self {
        self.hachure_angle = angle;
        self
    }

    pub fn set_hachure_gap(&mut self, gap: Option<f32>) -> &mut Self {
        self.hachure_gap = gap;
        self
    }
}

#[derive(Clone, PartialEq, Debug, Eq)]
pub enum OpType {
    Move,
    BCurveTo,
    LineTo,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OpSetType {
    Path,
    FillPath,
    FillSketch,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Op<F: Float + Trig> {
    pub op: OpType,
    pub data: Vec<F>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpSet<F: Float + Trig> {
    pub op_set_type: OpSetType,
    pub ops: Vec<Op<F>>,
    pub size: Option<Point2D<F>>,
    pub path: Option<String>,
}

pub struct Drawable<F: Float + Trig> {
    pub shape: String,
    pub options: Options,
    pub sets: Vec<OpSet<F>>,
}

pub struct PathInfo {
    pub d: String,
    pub stroke: Option<Srgba>,
    pub stroke_width: Option<f32>,
    pub fill: Option<Srgba>,
}

pub fn _c<U: Float + FromPrimitive>(inp: f32) -> U {
    U::from(inp).expect("can not parse from f32")
}

pub fn _cc<U: Float + FromPrimitive>(inp: f64) -> U {
    U::from(inp).expect("can not parse from f64")
}