bevy_mod_scripting_lua/
lib.rs

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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! Lua integration for the bevy_mod_scripting system.
use bevy::{
    app::Plugin,
    asset::AssetPath,
    ecs::{entity::Entity, world::World},
};
use bevy_mod_scripting_core::{
    asset::{AssetPathToLanguageMapper, Language},
    bindings::{
        function::namespace::Namespace, script_value::ScriptValue, ThreadWorldContainer,
        WorldContainer,
    },
    context::{ContextBuilder, ContextInitializer, ContextPreHandlingInitializer},
    error::ScriptError,
    event::CallbackLabel,
    reflection_extensions::PartialReflectExt,
    runtime::RuntimeSettings,
    script::ScriptId,
    IntoScriptPluginParams, ScriptingPlugin,
};
use bindings::{
    reference::{LuaReflectReference, LuaStaticReflectReference},
    script_value::LuaScriptValue,
};
pub use mlua;
use mlua::{Function, IntoLua, Lua, MultiValue};

/// Bindings for lua.
pub mod bindings;

impl IntoScriptPluginParams for LuaScriptingPlugin {
    type C = Lua;
    type R = ();
    const LANGUAGE: Language = Language::Lua;

    fn build_runtime() -> Self::R {}
}

// necessary for automatic config goodies
impl AsMut<ScriptingPlugin<Self>> for LuaScriptingPlugin {
    fn as_mut(&mut self) -> &mut ScriptingPlugin<LuaScriptingPlugin> {
        &mut self.scripting_plugin
    }
}

/// The lua scripting plugin. Used to add lua scripting to a bevy app within the context of the BMS framework.
pub struct LuaScriptingPlugin {
    /// The internal scripting plugin
    pub scripting_plugin: ScriptingPlugin<Self>,
}

impl Default for LuaScriptingPlugin {
    fn default() -> Self {
        LuaScriptingPlugin {
            scripting_plugin: ScriptingPlugin {
                context_assigner: Default::default(),
                runtime_settings: RuntimeSettings::default(),
                callback_handler: lua_handler,
                context_builder: ContextBuilder::<LuaScriptingPlugin> {
                    load: lua_context_load,
                    reload: lua_context_reload,
                },
                language_mapper: AssetPathToLanguageMapper {
                    map: lua_language_mapper,
                },
                context_initializers: vec![
                    |_script_id, context| {
                        // set the world global
                        context
                            .globals()
                            .set(
                                "world",
                                LuaStaticReflectReference(std::any::TypeId::of::<World>()),
                            )
                            .map_err(ScriptError::from_mlua_error)?;
                        Ok(())
                    },
                    |_script_id, context: &mut Lua| {
                        // set static globals
                        let world = ThreadWorldContainer.try_get_world()?;
                        let type_registry = world.type_registry();
                        let type_registry = type_registry.read();

                        for registration in type_registry.iter() {
                            // only do this for non generic types
                            // we don't want to see `Vec<Entity>:function()` in lua
                            if !registration.type_info().generics().is_empty() {
                                continue;
                            }

                            if let Some(global_name) =
                                registration.type_info().type_path_table().ident()
                            {
                                let ref_ = LuaStaticReflectReference(registration.type_id());
                                context
                                    .globals()
                                    .set(global_name, ref_)
                                    .map_err(ScriptError::from_mlua_error)?;
                            }
                        }

                        // go through functions in the global namespace and add them to the lua context
                        let script_function_registry = world.script_function_registry();
                        let script_function_registry = script_function_registry.read();

                        for (key, function) in script_function_registry
                            .iter_all()
                            .filter(|(k, _)| k.namespace == Namespace::Global)
                        {
                            context
                                .globals()
                                .set(
                                    key.name.to_string(),
                                    LuaScriptValue::from(ScriptValue::Function(function.clone())),
                                )
                                .map_err(ScriptError::from_mlua_error)?;
                        }

                        Ok(())
                    },
                ],
                context_pre_handling_initializers: vec![|script_id, entity, context| {
                    let world = ThreadWorldContainer.try_get_world()?;
                    context
                        .globals()
                        .set(
                            "entity",
                            LuaReflectReference(<Entity>::allocate(Box::new(entity), world)),
                        )
                        .map_err(ScriptError::from_mlua_error)?;
                    context
                        .globals()
                        .set("script_id", script_id)
                        .map_err(ScriptError::from_mlua_error)?;
                    Ok(())
                }],
                supported_extensions: &["lua"],
            },
        }
    }
}
#[profiling::function]
fn lua_language_mapper(path: &AssetPath) -> Language {
    match path.path().extension().and_then(|ext| ext.to_str()) {
        Some("lua") => Language::Lua,
        _ => Language::Unknown,
    }
}

impl Plugin for LuaScriptingPlugin {
    fn build(&self, app: &mut bevy::prelude::App) {
        self.scripting_plugin.build(app);
    }

    fn finish(&self, app: &mut bevy::app::App) {
        self.scripting_plugin.finish(app);
    }
}
#[profiling::function]
/// Load a lua context from a script
pub fn lua_context_load(
    script_id: &ScriptId,
    content: &[u8],
    initializers: &[ContextInitializer<LuaScriptingPlugin>],
    pre_handling_initializers: &[ContextPreHandlingInitializer<LuaScriptingPlugin>],
    _: &mut (),
) -> Result<Lua, ScriptError> {
    #[cfg(feature = "unsafe_lua_modules")]
    let mut context = unsafe { Lua::unsafe_new() };
    #[cfg(not(feature = "unsafe_lua_modules"))]
    let mut context = Lua::new();

    initializers
        .iter()
        .try_for_each(|init| init(script_id, &mut context))?;

    pre_handling_initializers
        .iter()
        .try_for_each(|init| init(script_id, Entity::from_raw(0), &mut context))?;

    context
        .load(content)
        .exec()
        .map_err(ScriptError::from_mlua_error)?;

    Ok(context)
}
#[profiling::function]
/// Reload a lua context from a script
pub fn lua_context_reload(
    script: &ScriptId,
    content: &[u8],
    old_ctxt: &mut Lua,
    initializers: &[ContextInitializer<LuaScriptingPlugin>],
    pre_handling_initializers: &[ContextPreHandlingInitializer<LuaScriptingPlugin>],
    _: &mut (),
) -> Result<(), ScriptError> {
    *old_ctxt = lua_context_load(
        script,
        content,
        initializers,
        pre_handling_initializers,
        &mut (),
    )?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
#[profiling::function]
/// The lua handler for events
pub fn lua_handler(
    args: Vec<ScriptValue>,
    entity: bevy::ecs::entity::Entity,
    script_id: &ScriptId,
    callback_label: &CallbackLabel,
    context: &mut Lua,
    pre_handling_initializers: &[ContextPreHandlingInitializer<LuaScriptingPlugin>],
    _: &mut (),
) -> Result<ScriptValue, bevy_mod_scripting_core::error::ScriptError> {
    pre_handling_initializers
        .iter()
        .try_for_each(|init| init(script_id, entity, context))?;

    let handler: Function = match context.globals().raw_get(callback_label.as_ref()) {
        Ok(handler) => handler,
        // not subscribed to this event type
        Err(_) => {
            bevy::log::trace!(
                "Script {} is not subscribed to callback {}",
                script_id,
                callback_label.as_ref()
            );
            return Ok(ScriptValue::Unit);
        }
    };

    let input = MultiValue::from_vec(
        args.into_iter()
            .map(|arg| LuaScriptValue::from(arg).into_lua(context))
            .collect::<Result<_, _>>()?,
    );

    let out = handler.call::<LuaScriptValue>(input)?;
    Ok(out.into())
}