bevy_flash 0.1.1

A Bevy plugin for Flash Animation.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use swf::{CharacterId, FillStyle, LineStyle, Rectangle, Shape, ShapeRecord, Twips};

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum FillRule {
    EvenOdd,
    NonZero,
}

impl From<FillRule> for lyon_tessellation::path::FillRule {
    fn from(rule: FillRule) -> lyon_tessellation::path::FillRule {
        match rule {
            FillRule::EvenOdd => lyon_tessellation::path::FillRule::EvenOdd,
            FillRule::NonZero => lyon_tessellation::path::FillRule::NonZero,
        }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum GradientType {
    Linear,
    Radial,
    Focal,
}

pub fn calculate_shape_bounds(shape_records: &[swf::ShapeRecord]) -> swf::Rectangle<Twips> {
    let mut bounds = swf::Rectangle {
        x_min: Twips::new(i32::MAX),
        y_min: Twips::new(i32::MAX),
        x_max: Twips::new(i32::MIN),
        y_max: Twips::new(i32::MIN),
    };
    let mut cursor = swf::Point::ZERO;
    for record in shape_records {
        match record {
            swf::ShapeRecord::StyleChange(style_change) => {
                if let Some(move_to) = &style_change.move_to {
                    cursor = *move_to;
                    bounds.x_min = bounds.x_min.min(cursor.x);
                    bounds.x_max = bounds.x_max.max(cursor.x);
                    bounds.y_min = bounds.y_min.min(cursor.y);
                    bounds.y_max = bounds.y_max.max(cursor.y);
                }
            }
            swf::ShapeRecord::StraightEdge { delta } => {
                cursor += *delta;
                bounds.x_min = bounds.x_min.min(cursor.x);
                bounds.x_max = bounds.x_max.max(cursor.x);
                bounds.y_min = bounds.y_min.min(cursor.y);
                bounds.y_max = bounds.y_max.max(cursor.y);
            }
            swf::ShapeRecord::CurvedEdge {
                control_delta,
                anchor_delta,
            } => {
                cursor += *control_delta;
                let control = cursor;
                cursor += *anchor_delta;
                let anchor = cursor;
                bounds = bounds.union(&quadratic_curve_bounds(
                    cursor,
                    Twips::ZERO,
                    control,
                    anchor,
                ));
            }
        }
    }
    if bounds.x_max < bounds.x_min || bounds.y_max < bounds.y_min {
        bounds = Default::default();
    }
    bounds
}

/// `DrawPath` represents a solid fill or a stroke.
/// Fills are always closed paths, while strokes may be open or closed.
/// Closed paths will have the first point equal to the last point.
#[derive(Clone, Debug, PartialEq)]
pub enum DrawPath<'a> {
    Stroke {
        style: &'a LineStyle,
        is_closed: bool,
        commands: Vec<DrawCommand>,
    },
    Fill {
        style: &'a FillStyle,
        commands: Vec<DrawCommand>,
        winding_rule: FillRule,
    },
}

/// `DistilledShape` represents a ready-to-be-consumed collection of paths (both fills and strokes)
/// that has been converted down from another source (such as SWF's `swf::Shape` format).
#[derive(Clone, Debug, PartialEq)]
pub struct DistilledShape<'a> {
    pub paths: Vec<DrawPath<'a>>,
    pub shape_bounds: Rectangle<Twips>,
    pub edge_bounds: Rectangle<Twips>,
    pub id: CharacterId,
}

impl<'a> From<&'a swf::Shape> for DistilledShape<'a> {
    fn from(shape: &'a Shape) -> Self {
        Self {
            paths: ShapeConverter::from_shape(shape).into_commands(),
            shape_bounds: shape.shape_bounds.clone(),
            edge_bounds: shape.edge_bounds.clone(),
            id: shape.id,
        }
    }
}

/// `DrawCommands` trace the outline of a path.
/// Fills follow the even-odd fill rule, with opposite winding for holes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DrawCommand {
    MoveTo(swf::Point<Twips>),
    LineTo(swf::Point<Twips>),
    QuadraticCurveTo {
        control: swf::Point<Twips>,
        anchor: swf::Point<Twips>,
    },
}

#[derive(Clone, Copy, Debug)]
struct Point {
    x: Twips,
    y: Twips,
    is_bezier_control: bool,
}

impl From<Point> for swf::Point<Twips> {
    fn from(point: Point) -> Self {
        Self::new(point.x, point.y)
    }
}

/// A continuous series of edges in a path.
/// Fill segments are directed, because the winding determines the fill-rule.
/// Stroke segments are undirected.
#[derive(Clone, Debug)]
struct PathSegment {
    pub points: Vec<Point>,
}

impl PathSegment {
    fn new(start: swf::Point<Twips>) -> Self {
        Self {
            points: vec![Point {
                x: start.x,
                y: start.y,
                is_bezier_control: false,
            }],
        }
    }

    fn reset(&mut self, start: swf::Point<Twips>) {
        self.points.clear();
        self.points.push(Point {
            x: start.x,
            y: start.y,
            is_bezier_control: false,
        });
    }

    /// Flips the direction of the path segment.
    /// Flash fill paths are dual-sided, with fill style 1 indicating the positive side
    /// and fill style 0 indicating the negative. We have to flip fill style 0 paths
    /// in order to link them to fill style 1 paths.
    fn flip(&mut self) {
        self.points.reverse();
    }

    /// Adds an edge to the end of the path segment.
    fn add_point(&mut self, point: Point) {
        self.points.push(point);
    }

    fn is_empty(&self) -> bool {
        self.points.len() <= 1
    }

    fn start(&self) -> Option<swf::Point<Twips>> {
        Some((*self.points.first()?).into())
    }

    fn end(&self) -> Option<swf::Point<Twips>> {
        Some((*self.points.last()?).into())
    }

    fn is_closed(&self) -> bool {
        self.start() == self.end()
    }

    fn to_draw_commands(&self) -> impl '_ + Iterator<Item = DrawCommand> {
        assert!(!self.is_empty());
        let mut i = self.points.iter();
        let first = i.next().expect("Points should not be empty");
        std::iter::once(DrawCommand::MoveTo((*first).into())).chain(std::iter::from_fn(move || {
            match i.next() {
                Some(
                    point @ Point {
                        is_bezier_control: false,
                        ..
                    },
                ) => Some(DrawCommand::LineTo((*point).into())),
                Some(
                    point @ Point {
                        is_bezier_control: true,
                        ..
                    },
                ) => {
                    let end = i.next().expect("Bezier without endpoint");
                    Some(DrawCommand::QuadraticCurveTo {
                        control: (*point).into(),
                        anchor: (*end).into(),
                    })
                }
                None => None,
            }
        }))
    }
}

/// The internal path structure used by ShapeConverter.
///
/// Each path is uniquely identified by its fill/stroke style. But Flash gives
/// the path edges as an "edge soup" -- they can arrive in an arbitrary order.
/// We have to link the edges together for each path. This structure contains
/// a list of path segment, and each time a path segment is added, it will try
/// to merge it with an existing segment.
#[derive(Clone, Debug)]
struct PendingPath {
    /// The list of path segments for this fill/stroke.
    /// For fills, this should turn into a list of closed paths when the shape is complete.
    /// Strokes may or may not be closed.
    segments: Vec<PathSegment>,
}

impl PendingPath {
    fn new() -> Self {
        Self { segments: vec![] }
    }

    /// Adds a path segment to the path, attempting to link it to existing segments.
    fn add_segment(&mut self, mut new_segment: PathSegment) {
        if !new_segment.is_empty() {
            // Try to link this segment onto existing segments with a matching endpoint.
            // Both the start and the end points of the new segment can be linked.
            let mut start_open = true;
            let mut end_open = true;
            let mut i = 0;
            while (start_open || end_open) && i < self.segments.len() {
                let other = &mut self.segments[i];
                if start_open && other.end() == new_segment.start() {
                    other.points.extend_from_slice(&new_segment.points[1..]);
                    new_segment = self.segments.swap_remove(i);
                    start_open = false;
                } else if end_open && new_segment.end() == other.start() {
                    std::mem::swap(&mut other.points, &mut new_segment.points);
                    other.points.extend_from_slice(&new_segment.points[1..]);
                    new_segment = self.segments.swap_remove(i);
                    end_open = false;
                } else {
                    i += 1;
                }
            }
            // The segment can't link to any further segments. Add it to list.
            self.segments.push(new_segment);
        }
    }

    fn push_path(&mut self, segment: PathSegment) {
        self.segments.push(segment);
    }

    fn to_draw_commands(&self) -> impl '_ + Iterator<Item = DrawCommand> {
        self.segments.iter().flat_map(PathSegment::to_draw_commands)
    }
}

#[derive(Clone, Debug)]
pub struct ActivePath {
    style_id: u32,
    segment: PathSegment,
}

impl ActivePath {
    fn new() -> Self {
        Self {
            style_id: 0,
            segment: PathSegment::new(swf::Point::ZERO),
        }
    }

    fn add_point(&mut self, point: Point) {
        self.segment.add_point(point)
    }

    fn flush_fill(&mut self, start: swf::Point<Twips>, pending: &mut [PendingPath], flip: bool) {
        if self.style_id > 0 && !self.segment.is_empty() {
            if flip {
                self.segment.flip();
            }
            pending[self.style_id as usize - 1].add_segment(self.segment.clone());
        }
        self.segment.reset(start);
    }

    fn flush_stroke(&mut self, start: swf::Point<Twips>, pending: &mut [PendingPath]) {
        if self.style_id > 0 && !self.segment.is_empty() {
            pending[self.style_id as usize - 1].push_path(self.segment.clone());
        }
        self.segment.reset(start);
    }
}

pub struct ShapeConverter<'a> {
    // SWF shape commands.
    iter: std::slice::Iter<'a, swf::ShapeRecord>,

    // Pen position.
    cursor: swf::Point<Twips>,

    // Fill styles and line styles.
    // These change from StyleChangeRecords, and a flush occurs when these change.
    fill_styles: &'a [swf::FillStyle],
    line_styles: &'a [swf::LineStyle],

    fill_style0: ActivePath,
    fill_style1: ActivePath,
    line_style: ActivePath,
    winding_rule: FillRule,

    // Paths. These get flushed for each new layer.
    fills: Vec<PendingPath>,
    strokes: Vec<PendingPath>,

    // Output.
    commands: Vec<DrawPath<'a>>,
}

impl<'a> ShapeConverter<'a> {
    const DEFAULT_CAPACITY: usize = 512;

    fn from_shape(shape: &'a swf::Shape) -> Self {
        ShapeConverter {
            iter: shape.shape.iter(),

            cursor: swf::Point::ZERO,

            fill_styles: &shape.styles.fill_styles,
            line_styles: &shape.styles.line_styles,

            fill_style0: ActivePath::new(),
            fill_style1: ActivePath::new(),
            line_style: ActivePath::new(),

            fills: vec![PendingPath::new(); shape.styles.fill_styles.len()],
            strokes: vec![PendingPath::new(); shape.styles.line_styles.len()],

            commands: Vec::with_capacity(Self::DEFAULT_CAPACITY),

            winding_rule: if shape.flags.contains(swf::ShapeFlag::NON_ZERO_WINDING_RULE) {
                FillRule::NonZero
            } else {
                FillRule::EvenOdd
            },
        }
    }

    fn into_commands(mut self) -> Vec<DrawPath<'a>> {
        // As u32 is okay because SWF has a max of 65536 fills (TODO: should be u16?)
        let mut num_fill_styles = self.fill_styles.len() as u32;
        let mut num_line_styles = self.line_styles.len() as u32;
        while let Some(record) = self.iter.next() {
            match record {
                ShapeRecord::StyleChange(style_change) => {
                    if let Some(move_to) = &style_change.move_to {
                        self.cursor = *move_to;
                        // We've lifted the pen, so we're starting a new path.
                        // Flush the previous path.
                        self.flush_paths();
                    }

                    if let Some(styles) = &style_change.new_styles {
                        // A new style list is also used to indicate a new drawing layer.
                        self.flush_layer();
                        self.fill_styles = &styles.fill_styles;
                        self.line_styles = &styles.line_styles;
                        self.fills
                            .resize_with(self.fill_styles.len(), PendingPath::new);
                        self.strokes
                            .resize_with(self.line_styles.len(), PendingPath::new);
                        num_fill_styles = self.fill_styles.len() as u32;
                        num_line_styles = self.line_styles.len() as u32;
                    }

                    if let Some(new_style_id) = style_change.fill_style_1 {
                        self.fill_style1
                            .flush_fill(self.cursor, &mut self.fills, false);
                        // Validate in case we index an invalid fill style.
                        // <= because fill ID 0 (no fill) is implicit, so the array is actually 1-based
                        self.fill_style1.style_id = if new_style_id <= num_fill_styles {
                            new_style_id
                        } else {
                            0
                        };
                    }

                    if let Some(new_style_id) = style_change.fill_style_0 {
                        self.fill_style0
                            .flush_fill(self.cursor, &mut self.fills, true);
                        self.fill_style0.style_id = if new_style_id <= num_fill_styles {
                            new_style_id
                        } else {
                            0
                        }
                    }

                    if let Some(new_style_id) = style_change.line_style {
                        self.line_style.flush_stroke(self.cursor, &mut self.strokes);
                        self.line_style.style_id = if new_style_id <= num_line_styles {
                            new_style_id
                        } else {
                            0
                        }
                    }
                }
                ShapeRecord::StraightEdge { delta } => {
                    self.cursor += *delta;
                    self.visit_point(false);
                }
                ShapeRecord::CurvedEdge {
                    control_delta,
                    anchor_delta,
                } => {
                    self.cursor += *control_delta;
                    self.visit_point(true);

                    self.cursor += *anchor_delta;
                    self.visit_point(false);
                }
            }
        }

        // Flush any open paths.
        self.flush_layer();
        self.commands
    }

    /// Adds a point to the current path for the active fills/strokes.
    fn visit_point(&mut self, is_bezier_control: bool) {
        let point = Point {
            x: self.cursor.x,
            y: self.cursor.y,
            is_bezier_control,
        };
        if self.fill_style1.style_id > 0 {
            self.fill_style1.add_point(point);
        }
        if self.fill_style0.style_id > 0 {
            self.fill_style0.add_point(point);
        }
        if self.line_style.style_id > 0 {
            self.line_style.add_point(point);
        }
    }

    /// When the pen jumps to a new position, we reset the active path.
    fn flush_paths(&mut self) {
        // Move the current paths to the active list.
        self.fill_style1
            .flush_fill(self.cursor, &mut self.fills, false);
        self.fill_style0
            .flush_fill(self.cursor, &mut self.fills, true);
        self.line_style.flush_stroke(self.cursor, &mut self.strokes);
    }

    /// When a new layer starts, all paths are flushed and turned into drawing commands.
    fn flush_layer(&mut self) {
        self.flush_paths();

        // Draw fills, and then strokes.
        // Paths are drawn in order of style id, not based on the order of the draw commands.
        for (i, path) in self.fills.iter_mut().enumerate() {
            // These invariants are checked above (any invalid/empty fill ID should not have been added).
            debug_assert!(i < self.fill_styles.len());
            if path.segments.is_empty() {
                continue;
            }
            let style = unsafe { self.fill_styles.get_unchecked(i) };
            self.commands.push(DrawPath::Fill {
                style,
                commands: path.to_draw_commands().collect(),
                winding_rule: self.winding_rule,
            });
            path.segments.clear();
        }

        // Strokes are drawn last because they always appear on top of fills in the same layer.
        // Because path segments can either be open or closed, we convert each stroke segment into
        // a separate draw command.
        for (i, path) in self.strokes.iter_mut().enumerate() {
            debug_assert!(i < self.line_styles.len());
            let style = unsafe { self.line_styles.get_unchecked(i) };
            for segment in &path.segments {
                if segment.is_empty() {
                    continue;
                }
                self.commands.push(DrawPath::Stroke {
                    style,
                    is_closed: segment.is_closed(),
                    commands: segment.to_draw_commands().collect(),
                });
            }
            path.segments.clear();
        }
    }
}

pub fn quadratic_curve_bounds(
    start: swf::Point<Twips>,
    stroke_width: Twips,
    control: swf::Point<Twips>,
    anchor: swf::Point<Twips>,
) -> Rectangle<Twips> {
    // extremes
    let from_x = start.x.to_pixels();
    let from_y = start.y.to_pixels();
    let anchor_x = anchor.x.to_pixels();
    let anchor_y = anchor.y.to_pixels();
    let control_x = control.x.to_pixels();
    let control_y = control.y.to_pixels();

    let mut min_x = from_x.min(anchor_x);
    let mut min_y = from_y.min(anchor_y);
    let mut max_x = from_x.max(anchor_x);
    let mut max_y = from_y.max(anchor_y);

    if control_x < min_x || control_x > max_x {
        let t_x = ((from_x - control_x) / (from_x - (control_x * 2.0) + anchor_x)).clamp(0.0, 1.0);
        let s_x = 1.0 - t_x;
        let q_x = s_x * s_x * from_x + (s_x * 2.0) * t_x * control_x + t_x * t_x * anchor_x;

        min_x = min_x.min(q_x);
        max_x = max_x.max(q_x);
    }

    if control_y < min_y || control_y > max_y {
        let t_y = ((from_y - control_y) / (from_y - (control_y * 2.0) + anchor_y)).clamp(0.0, 1.0);
        let s_y = 1.0 - t_y;
        let q_y = s_y * s_y * from_y + (s_y * 2.0) * t_y * control_y + t_y * t_y * anchor_y;

        min_y = min_y.min(q_y);
        max_y = max_y.max(q_y);
    }

    let radius = stroke_width / 2;
    Rectangle::default()
        .encompass(swf::Point::new(
            Twips::from_pixels(min_x) - radius,
            Twips::from_pixels(min_y) - radius,
        ))
        .encompass(swf::Point::new(
            Twips::from_pixels(max_x) + radius,
            Twips::from_pixels(max_y) + radius,
        ))
}