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
use iced_native::{Point, Rectangle, Size, Vector};

use crate::{
    canvas::{Fill, Geometry, Path, Stroke, Text},
    triangle, Primitive,
};

/// The frame of a [`Canvas`].
///
/// [`Canvas`]: struct.Canvas.html
#[derive(Debug)]
pub struct Frame {
    size: Size,
    buffers: lyon::tessellation::VertexBuffers<triangle::Vertex2D, u32>,
    primitives: Vec<Primitive>,
    transforms: Transforms,
}

#[derive(Debug)]
struct Transforms {
    previous: Vec<Transform>,
    current: Transform,
}

#[derive(Debug, Clone, Copy)]
struct Transform {
    raw: lyon::math::Transform,
    is_identity: bool,
}

impl Frame {
    /// Creates a new empty [`Frame`] with the given dimensions.
    ///
    /// The default coordinate system of a [`Frame`] has its origin at the
    /// top-left corner of its bounds.
    ///
    /// [`Frame`]: struct.Frame.html
    pub fn new(size: Size) -> Frame {
        Frame {
            size,
            buffers: lyon::tessellation::VertexBuffers::new(),
            primitives: Vec::new(),
            transforms: Transforms {
                previous: Vec::new(),
                current: Transform {
                    raw: lyon::math::Transform::identity(),
                    is_identity: true,
                },
            },
        }
    }

    /// Returns the width of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn width(&self) -> f32 {
        self.size.width
    }

    /// Returns the width of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn height(&self) -> f32 {
        self.size.height
    }

    /// Returns the dimensions of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn size(&self) -> Size {
        self.size
    }

    /// Returns the coordinate of the center of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn center(&self) -> Point {
        Point::new(self.size.width / 2.0, self.size.height / 2.0)
    }

    /// Draws the given [`Path`] on the [`Frame`] by filling it with the
    /// provided style.
    ///
    /// [`Path`]: path/struct.Path.html
    /// [`Frame`]: struct.Frame.html
    pub fn fill(&mut self, path: &Path, fill: impl Into<Fill>) {
        use lyon::tessellation::{
            BuffersBuilder, FillOptions, FillTessellator,
        };

        let Fill { color, rule } = fill.into();

        let mut buffers = BuffersBuilder::new(
            &mut self.buffers,
            FillVertex(color.into_linear()),
        );

        let mut tessellator = FillTessellator::new();
        let options = FillOptions::default().with_fill_rule(rule.into());

        let result = if self.transforms.current.is_identity {
            tessellator.tessellate_path(path.raw(), &options, &mut buffers)
        } else {
            let path = path.transformed(&self.transforms.current.raw);

            tessellator.tessellate_path(path.raw(), &options, &mut buffers)
        };

        let _ = result.expect("Tessellate path");
    }

    /// Draws an axis-aligned rectangle given its top-left corner coordinate and
    /// its `Size` on the [`Frame`] by filling it with the provided style.
    ///
    /// [`Frame`]: struct.Frame.html
    pub fn fill_rectangle(
        &mut self,
        top_left: Point,
        size: Size,
        fill: impl Into<Fill>,
    ) {
        use lyon::tessellation::{BuffersBuilder, FillOptions};

        let Fill { color, rule } = fill.into();

        let mut buffers = BuffersBuilder::new(
            &mut self.buffers,
            FillVertex(color.into_linear()),
        );

        let top_left =
            self.transforms.current.raw.transform_point(
                lyon::math::Point::new(top_left.x, top_left.y),
            );

        let size =
            self.transforms.current.raw.transform_vector(
                lyon::math::Vector::new(size.width, size.height),
            );

        let _ = lyon::tessellation::basic_shapes::fill_rectangle(
            &lyon::math::Rect::new(top_left, size.into()),
            &FillOptions::default().with_fill_rule(rule.into()),
            &mut buffers,
        )
        .expect("Fill rectangle");
    }

    /// Draws the stroke of the given [`Path`] on the [`Frame`] with the
    /// provided style.
    ///
    /// [`Path`]: path/struct.Path.html
    /// [`Frame`]: struct.Frame.html
    pub fn stroke(&mut self, path: &Path, stroke: impl Into<Stroke>) {
        use lyon::tessellation::{
            BuffersBuilder, StrokeOptions, StrokeTessellator,
        };

        let stroke = stroke.into();

        let mut buffers = BuffersBuilder::new(
            &mut self.buffers,
            StrokeVertex(stroke.color.into_linear()),
        );

        let mut tessellator = StrokeTessellator::new();

        let mut options = StrokeOptions::default();
        options.line_width = stroke.width;
        options.start_cap = stroke.line_cap.into();
        options.end_cap = stroke.line_cap.into();
        options.line_join = stroke.line_join.into();

        let result = if self.transforms.current.is_identity {
            tessellator.tessellate_path(path.raw(), &options, &mut buffers)
        } else {
            let path = path.transformed(&self.transforms.current.raw);

            tessellator.tessellate_path(path.raw(), &options, &mut buffers)
        };

        let _ = result.expect("Stroke path");
    }

    /// Draws the characters of the given [`Text`] on the [`Frame`], filling
    /// them with the given color.
    ///
    /// __Warning:__ Text currently does not work well with rotations and scale
    /// transforms! The position will be correctly transformed, but the
    /// resulting glyphs will not be rotated or scaled properly.
    ///
    /// Additionally, all text will be rendered on top of all the layers of
    /// a [`Canvas`]. Therefore, it is currently only meant to be used for
    /// overlays, which is the most common use case.
    ///
    /// Support for vectorial text is planned, and should address all these
    /// limitations.
    ///
    /// [`Text`]: struct.Text.html
    /// [`Frame`]: struct.Frame.html
    /// [`Canvas`]: struct.Canvas.html
    pub fn fill_text(&mut self, text: impl Into<Text>) {
        use std::f32;

        let text = text.into();

        let position = if self.transforms.current.is_identity {
            text.position
        } else {
            let transformed = self.transforms.current.raw.transform_point(
                lyon::math::Point::new(text.position.x, text.position.y),
            );

            Point::new(transformed.x, transformed.y)
        };

        // TODO: Use vectorial text instead of primitive
        self.primitives.push(Primitive::Text {
            content: text.content,
            bounds: Rectangle {
                x: position.x,
                y: position.y,
                width: f32::INFINITY,
                height: f32::INFINITY,
            },
            color: text.color,
            size: text.size,
            font: text.font,
            horizontal_alignment: text.horizontal_alignment,
            vertical_alignment: text.vertical_alignment,
        });
    }

    /// Stores the current transform of the [`Frame`] and executes the given
    /// drawing operations, restoring the transform afterwards.
    ///
    /// This method is useful to compose transforms and perform drawing
    /// operations in different coordinate systems.
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn with_save(&mut self, f: impl FnOnce(&mut Frame)) {
        self.transforms.previous.push(self.transforms.current);

        f(self);

        self.transforms.current = self.transforms.previous.pop().unwrap();
    }

    /// Applies a translation to the current transform of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn translate(&mut self, translation: Vector) {
        self.transforms.current.raw = self
            .transforms
            .current
            .raw
            .pre_translate(lyon::math::Vector::new(
                translation.x,
                translation.y,
            ));
        self.transforms.current.is_identity = false;
    }

    /// Applies a rotation to the current transform of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn rotate(&mut self, angle: f32) {
        self.transforms.current.raw = self
            .transforms
            .current
            .raw
            .pre_rotate(lyon::math::Angle::radians(-angle));
        self.transforms.current.is_identity = false;
    }

    /// Applies a scaling to the current transform of the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    #[inline]
    pub fn scale(&mut self, scale: f32) {
        self.transforms.current.raw =
            self.transforms.current.raw.pre_scale(scale, scale);
        self.transforms.current.is_identity = false;
    }

    /// Produces the [`Geometry`] representing everything drawn on the [`Frame`].
    ///
    /// [`Frame`]: struct.Frame.html
    /// [`Geometry`]: struct.Geometry.html
    pub fn into_geometry(mut self) -> Geometry {
        if !self.buffers.indices.is_empty() {
            self.primitives.push(Primitive::Mesh2D {
                buffers: triangle::Mesh2D {
                    vertices: self.buffers.vertices,
                    indices: self.buffers.indices,
                },
                size: self.size,
            });
        }

        Geometry::from_primitive(Primitive::Group {
            primitives: self.primitives,
        })
    }
}

struct FillVertex([f32; 4]);

impl lyon::tessellation::BasicVertexConstructor<triangle::Vertex2D>
    for FillVertex
{
    fn new_vertex(
        &mut self,
        position: lyon::math::Point,
    ) -> triangle::Vertex2D {
        triangle::Vertex2D {
            position: [position.x, position.y],
            color: self.0,
        }
    }
}

impl lyon::tessellation::FillVertexConstructor<triangle::Vertex2D>
    for FillVertex
{
    fn new_vertex(
        &mut self,
        position: lyon::math::Point,
        _attributes: lyon::tessellation::FillAttributes<'_>,
    ) -> triangle::Vertex2D {
        triangle::Vertex2D {
            position: [position.x, position.y],
            color: self.0,
        }
    }
}

struct StrokeVertex([f32; 4]);

impl lyon::tessellation::StrokeVertexConstructor<triangle::Vertex2D>
    for StrokeVertex
{
    fn new_vertex(
        &mut self,
        position: lyon::math::Point,
        _attributes: lyon::tessellation::StrokeAttributes<'_, '_>,
    ) -> triangle::Vertex2D {
        triangle::Vertex2D {
            position: [position.x, position.y],
            color: self.0,
        }
    }
}