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
use bevy::prelude::*;
use roxmltree;
use std::{error::Error, fs};
use svgtypes::{PathParser, PathSegment};

mod style;
pub use style::{StyleStrategy, SvgStyle};

/// Struct that parses the svg paths with their style
#[derive(Debug)]
struct StyleSegment {
    style: SvgStyle,
    traces: Vec<PathSegment>,
}

impl From<(&str, &str)> for StyleSegment {
    fn from(tup: (&str, &str)) -> Self {
        let style: SvgStyle = SvgStyle::from(tup.0);
        let traces = PathParser::from(tup.1).map(|n| n.unwrap()).collect();
        StyleSegment { style, traces }
    }
}

/// Return a zero-cost read-only view of the svg XML document as a graph
fn take_lines_with_style<'a>(doc: &'a roxmltree::Document) -> Vec<(&'a str, &'a str)> {
    doc.descendants()
        .filter(|n| match n.attribute("d") {
            Some(_) => true,
            _ => false,
        })
        .map(|n| (n.attribute("style").unwrap(), n.attribute("d").unwrap()))
        .collect()
}

/// Parse each "d" node's attribute into a StyleSegment
fn tokenize_svg(path: &str) -> Result<Vec<StyleSegment>, Box<dyn Error>> {
    let xmlfile = fs::read_to_string(path)?;
    let doc = roxmltree::Document::parse(&xmlfile)?;
    Ok(take_lines_with_style(&doc)
        .iter()
        .map(|p| StyleSegment::from(*p))
        .collect())
}

/// Take the Commands and add Components given the paths in a SVG file
/// TODO: strategy design: expose a trait with a method that returns materials given style,
/// and a method that adds Components given the style.
pub fn load_svg_map<T: StyleStrategy>(
    mut commands: Commands,
    mut materials: ResMut<Assets<ColorMaterial>>,
    svg_map: &str,
    strategy: T,
) {
    let wall_thickness = 10.0;
    let (x_max, y_max) = tokenize_svg(svg_map)
        .unwrap()
        .iter()
        .flat_map(|n| n.traces.iter())
        .fold((0f64, 0f64), |acc, n| match n {
            PathSegment::MoveTo { abs: _, x, y } => (x.abs().max(acc.0), y.abs().max(acc.1)),
            PathSegment::HorizontalLineTo { abs: _, x } => (x.abs().max(acc.0), acc.1),
            PathSegment::VerticalLineTo { abs: _, y } => (acc.0, y.abs().max(acc.1)),
            _ => {
                println!("Found a not yet handled PathSegment");
                acc
            }
        });
    let (x_max, y_max) = ((x_max / 2.) as f32, (y_max / 2.) as f32);

    for StyleSegment { style, traces } in tokenize_svg(svg_map).unwrap().iter() {
        let mut origin = Vec3::new(0f32, 0f32, 0f32);
        let wall_material = materials.add(strategy.color_decider(style).into());
        for tok in traces.iter() {
            match tok {
                PathSegment::MoveTo { abs: _, x, y } => {
                    origin = Vec3::new((*x as f32).abs(), (*y as f32).abs(), 0f32);
                    println!("{:?}", origin);
                    continue;
                }
                PathSegment::HorizontalLineTo { abs: _, x } => {
                    let x = (*x as f32).abs();
                    strategy.component_decider(
                        style,
                        commands.spawn(SpriteComponents {
                            material: wall_material,
                            transform: Transform::from_translation(Vec3::new(
                                (origin.x() + x) / 2.0 - x_max,
                                origin.y() - y_max,
                                0.0,
                            )),
                            sprite: Sprite::new(Vec2::new((origin.x() - x).abs(), wall_thickness)),
                            ..Default::default()
                        }),
                    );
                    // .with(Collider::Solid);
                    origin = Vec3::new(x, origin.y(), 0f32);
                }
                PathSegment::VerticalLineTo { abs: _, y } => {
                    let y = (*y as f32).abs();
                    strategy.component_decider(
                        style,
                        commands.spawn(SpriteComponents {
                            material: wall_material,
                            transform: Transform::from_translation(Vec3::new(
                                origin.x() - x_max,
                                (origin.y() + y) / 2.0 - y_max,
                                0.0,
                            )),
                            sprite: Sprite::new(Vec2::new(wall_thickness, (origin.y() - y).abs())),
                            ..Default::default()
                        }),
                    );
                    // .with(Collider::Solid);
                    origin = Vec3::new(origin.x(), y, 0f32);
                }
                _ => {}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn tokenize_properly() {
        let (_, _) = tokenize_svg("assets/ex.svg")
            .unwrap()
            .iter()
            .flat_map(|n| n.traces.iter())
            .fold((0f64, 0f64), |acc, n| match n {
                PathSegment::MoveTo { abs: _, x, y } => (x.abs().max(acc.0), y.abs().max(acc.1)),
                PathSegment::HorizontalLineTo { abs: _, x } => (x.abs().max(acc.0), acc.1),
                PathSegment::VerticalLineTo { abs: _, y } => (acc.0, y.abs().max(acc.1)),
                _ => {
                    println!("Found a not yet handled PathSegment");
                    acc
                }
            });
    }
}