compiler_global/
compiler_global.rs

1//! Example showing how to construct, serialize, compile, instantiate and run graphs with compiler global constants
2
3use animgraph::compiler::prelude::*;
4use std::sync::Arc;
5
6const TEST_EVENT: &str = "TestEvent";
7
8fn main() -> anyhow::Result<()> {
9    // Custom compiler global name
10    const ALMOST_PI: &str = "ALMOST_PI";
11
12    fn construct_data() -> AnimGraph {
13        fn global_number(name: &str) -> Expression {
14            Expression::CompilerGlobal(name.to_owned())
15        }
16
17        let condition = bind_parameter::<f32>("a").ge(global_number(ALMOST_PI));
18        let endpoint = endpoint(state_event(TEST_EVENT, condition, EventEmit::Always));
19
20        let machines = [state_machine("Root", [state("StateA").with(endpoint, [])])];
21
22        AnimGraph {
23            state_machines: machines.into(),
24            ..Default::default()
25        }
26    }
27
28    fn compile_data(graph: &AnimGraph) -> Result<GraphDefinitionBuilder, CompileError> {
29        let mut registry = NodeCompilationRegistry::default();
30        add_default_nodes(&mut registry);
31
32        // Add a custom compiler global
33        let mut definition = GraphDefinitionCompilation::default();
34        definition.add_global_constant(ALMOST_PI, 3.0)?;
35
36        let mut context = GraphCompilationContext::build_context(&graph, &registry)?;
37        run_graph_definition_compilation(&mut definition, &mut context)?;
38        Ok(definition.builder)
39    }
40
41    // 1. Serialize
42    fn serialize_definition() -> serde_json::Value {
43        let animgraph = construct_data();
44        let definition_builder = compile_data(&animgraph).unwrap();
45        serde_json::to_value(definition_builder).unwrap()
46    }
47
48    // 2. Deserialize
49    fn deserialize_definition(
50        serialized: serde_json::Value,
51    ) -> anyhow::Result<Arc<GraphDefinition>> {
52        let deserialized: GraphDefinitionBuilder = serde_json::from_value(serialized)?;
53        // Validates the graph and deserializes the immutable nodes
54        let mut provider = GraphNodeRegistry::default();
55        add_default_constructors(&mut provider);
56        Ok(deserialized.build(&provider)?)
57    }
58
59    // This is an example. Serialization is not necessary
60    let serialized = serialize_definition();
61    let definition = deserialize_definition(serialized)?;
62
63    perform_runtime_test(definition);
64    
65    Ok(())
66}
67
68fn perform_runtime_test(definition: Arc<GraphDefinition>) {
69    // 3. Create the graph
70    let mut graph = definition
71        .clone()
72        .build_with_empty_skeleton(Arc::new(EmptyResourceProvider));
73
74    // 4. Query the graph
75    let event = definition.get_event_by_name(TEST_EVENT).unwrap();
76    assert!(event.get(&graph) == FlowState::Exited);
77
78    // 5. Run the graph
79    let mut context = DefaultRunContext::new(1.0);
80    context.run(&mut graph);
81    assert!(context.events.emitted.is_empty());
82
83    assert!(event.get(&graph) == FlowState::Entered);
84
85    // 6. Modify parameters
86    let a = definition.get_number_parameter::<f32>("a").unwrap();
87    a.set(&mut graph, 4.0);
88
89    context.run(&mut graph);
90    assert_eq!(&context.events.emitted, &[Id::from_str(TEST_EVENT)]);
91}