Skip to main content

paiagram_core/export/
graphviz.rs

1use bevy::ecs::system::RunSystemOnce;
2use bevy::prelude::*;
3use petgraph::dot;
4
5use crate::graph::Graph;
6
7pub struct Graphviz<'a> {
8    world: &'a mut World,
9}
10
11impl<'a> super::ExportObject for Graphviz<'a> {
12    fn export_to_buffer(&mut self, buffer: &mut Vec<u8>) {
13        self.world
14            .run_system_once_with(make_dot_string, buffer)
15            .unwrap();
16    }
17    fn extension(&self) -> impl AsRef<str> {
18        ".dot"
19    }
20    fn filename(&self) -> impl AsRef<str> {
21        "diagram"
22    }
23}
24
25fn make_dot_string(InMut(buffer): InMut<Vec<u8>>, graph: Res<Graph>, names: Query<&Name>) {
26    let get_node_attr = |_, (_, entity): (_, &Entity)| {
27        format!(
28            r#"label = "{}""#,
29            names
30                .get(entity.entity())
31                .map_or("<Unknown>".to_string(), |name| name.to_string())
32        )
33    };
34    let get_edge_attr = |_, _| String::new();
35    let dot_string = dot::Dot::with_attr_getters(
36        &graph.map,
37        &[dot::Config::EdgeNoLabel, dot::Config::NodeNoLabel],
38        &get_edge_attr,
39        &get_node_attr,
40    );
41    buffer.clear();
42    buffer.extend_from_slice(&format!("{:?}", dot_string).into_bytes());
43}