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
//! Runs a [`GameScript`](../map/map/enum.GameScript.html) from the
//! [script repository](../map/map/struct.Map.html#structfield.script_repository)
//! of a map, given its corresponding [`MapId`](../map/struct.MapId.html) and the
//! index of the script.

use amethyst::ecs::{World, WorldExt};

use crate::{
    lua::run_lua_script,
    map::{GameScript, MapHandler, MapId},
};

use super::{BoxedGameEvent, ExecutionConditions, GameEvent};

#[derive(Clone)]
pub struct ScriptEvent {
    script: Script,
}

#[derive(Clone)]
enum Script {
    Reference {
        map: MapId,
        script_index: usize,
    },
    Instance(GameScript),
}

impl ScriptEvent {
    pub fn new(map: MapId, script_index: usize) -> ScriptEvent {
        ScriptEvent {
            script: Script::Reference {
                map,
                script_index,
            }
        }
    }

    pub fn from_script(script: GameScript) -> ScriptEvent {
        ScriptEvent {
            script: Script::Instance(script),
        }
    }
}

impl GameEvent for ScriptEvent {
    fn boxed_clone(&self) -> BoxedGameEvent {
        Box::new(self.clone())
    }

    fn get_execution_conditions(&self) -> ExecutionConditions {
        // TODO: is this always correct?
        ExecutionConditions {
            requires_disabled_input: false,
        }
    }

    fn start(&mut self, _world: &mut World) { }

    fn tick<'a>(&mut self, world: &'a mut World, _disabled_inputs: bool) {
        let game_script = match &self.script {
            Script::Reference { map, script_index } => world
                .read_resource::<MapHandler>()
                .get_script(&map, *script_index)
                .clone(),
            Script::Instance(script) => script.clone(),
        };

        match game_script {
            GameScript::Native { script, parameters } => script(world, &parameters),
            GameScript::Lua { file, function, parameters } => {
                let result = run_lua_script(world, &file, &function, &parameters);

                if let Err(err) = result {
                    eprintln!("An error occurred during the execution of a Lua script.");
                    eprintln!("File: {}", file);
                    eprintln!("Function: {}", function);
                    eprintln!("Error message: {}", err);
                }
            },
        }
    }

    fn is_complete(&self, _world: &mut World) -> bool {
        true
    }
}