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
}
#[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,
},
}
#[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,
}
}
}
#[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)
}
}
#[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,
});
}
fn flip(&mut self) {
self.points.reverse();
}
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,
}
}))
}
}
#[derive(Clone, Debug)]
struct PendingPath {
segments: Vec<PathSegment>,
}
impl PendingPath {
fn new() -> Self {
Self { segments: vec![] }
}
fn add_segment(&mut self, mut new_segment: PathSegment) {
if !new_segment.is_empty() {
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;
}
}
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> {
iter: std::slice::Iter<'a, swf::ShapeRecord>,
cursor: swf::Point<Twips>,
fill_styles: &'a [swf::FillStyle],
line_styles: &'a [swf::LineStyle],
fill_style0: ActivePath,
fill_style1: ActivePath,
line_style: ActivePath,
winding_rule: FillRule,
fills: Vec<PendingPath>,
strokes: Vec<PendingPath>,
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>> {
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;
self.flush_paths();
}
if let Some(styles) = &style_change.new_styles {
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);
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);
}
}
}
self.flush_layer();
self.commands
}
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);
}
}
fn flush_paths(&mut self) {
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);
}
fn flush_layer(&mut self) {
self.flush_paths();
for (i, path) in self.fills.iter_mut().enumerate() {
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();
}
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> {
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,
))
}