bones_scripting/
lua.rs

1use crate::prelude::*;
2
3use bevy_tasks::{ComputeTaskPool, TaskPool, ThreadExecutor};
4use bones_asset::dashmap::mapref::one::{MappedRef, MappedRefMut};
5use bones_lib::ecs::utils::*;
6
7use parking_lot::Mutex;
8pub use piccolo;
9use piccolo::{
10    compiler::{LineNumber, ParseError},
11    registry::{Fetchable, Stashable},
12    Closure, Context, Executor, FromValue, Lua, PrototypeError, StashedClosure, Table, UserData,
13    Value,
14};
15use send_wrapper::SendWrapper;
16use std::{any::Any, rc::Rc, sync::Arc};
17
18#[macro_use]
19mod freeze;
20use freeze::*;
21
22mod asset;
23pub use asset::*;
24
25mod ext;
26pub use ext::*;
27
28pub mod bindings;
29
30/// Install the lua scripting plugin.
31pub fn lua_game_plugin(game: &mut Game) {
32    // Register asset type.
33    LuaScript::register_schema();
34
35    // Add `SchemaLuaMetatable` type data for common types.
36    bindings::register_lua_typedata();
37
38    // Initialize the lua engine resource.
39    game.init_shared_resource::<LuaEngine>();
40}
41
42/// A [`SessionPlugin] that will run the provided lua plugins
43pub struct LuaPluginLoaderSessionPlugin(pub Arc<Vec<Handle<LuaPlugin>>>);
44
45/// Resource containing the lua plugins that have been installed in this session.
46#[derive(HasSchema, Deref, DerefMut, Default, Clone)]
47pub struct LuaPlugins(pub Arc<Vec<Handle<LuaPlugin>>>);
48
49impl SessionPlugin for LuaPluginLoaderSessionPlugin {
50    fn install(self, session: &mut Session) {
51        session.add_startup_resource(LuaPlugins(self.0));
52
53        for lua_stage in [
54            CoreStage::Startup,
55            CoreStage::First,
56            CoreStage::PreUpdate,
57            CoreStage::Update,
58            CoreStage::PostUpdate,
59            CoreStage::Last,
60        ] {
61            session.stages.add_system_to_stage(
62                lua_stage,
63                move |engine: Res<LuaEngine>,
64                      asset_server: Res<AssetServer>,
65                      lua_plugins: Res<LuaPlugins>,
66                      world: &World| {
67                    engine.exec(|lua| {
68                        Frozen::<Freeze![&'freeze World]>::in_scope(world, |world| {
69                            lua.enter(|ctx| {
70                                let env = ctx.singletons().get(ctx, bindings::env);
71                                let worldref = WorldRef(world);
72                                worldref.add_to_env(ctx, env);
73                            });
74
75                            for plugin_handle in lua_plugins.iter() {
76                                let Some(plugin) = asset_server.try_get(*plugin_handle) else {
77                                    return;
78                                };
79                                let plugin = plugin.unwrap();
80
81                                // Load the plugin if necessary
82                                if !plugin.has_loaded() {
83                                    if let Err(e) = plugin.load(engine.executor.clone(), lua) {
84                                        tracing::error!("Error loading lua plugin: {e}");
85                                    }
86                                }
87
88                                let mut systems = plugin.systems.borrow_mut();
89                                let systems = systems.as_loaded_mut();
90
91                                for (stage, closure) in &systems.core_stages {
92                                    if stage == &lua_stage {
93                                        let executor = lua.enter(|ctx| {
94                                            let closure = ctx.registry().fetch(closure);
95                                            let ex = Executor::start(ctx, closure.into(), ());
96                                            ctx.registry().stash(&ctx, ex)
97                                        });
98                                        if let Err(e) = lua.execute::<()>(&executor) {
99                                            tracing::error!("Error running lua plugin system: {e}");
100                                        }
101                                    }
102                                }
103                            }
104                        })
105                    });
106                },
107            );
108        }
109    }
110}
111
112/// A frozen reference to the ECS [`World`].
113///
114// This type can be converted into lua userdata for accessing the world from lua.
115#[derive(Deref, DerefMut, Clone)]
116pub struct WorldRef(Frozen<Freeze![&'freeze World]>);
117impl Default for WorldRef {
118    fn default() -> Self {
119        Self(Frozen::new())
120    }
121}
122impl<'gc> FromValue<'gc> for &'gc WorldRef {
123    fn from_value(_ctx: Context<'gc>, value: Value<'gc>) -> Result<Self, piccolo::TypeError> {
124        value.as_static_user_data::<WorldRef>()
125    }
126}
127
128impl WorldRef {
129    /// Convert this [`WorldRef`] into a Lua userdata.
130    pub fn into_userdata(self, ctx: Context<'_>) -> UserData<'_> {
131        let data = UserData::new_static(&ctx, self);
132        data.set_metatable(
133            &ctx,
134            Some(ctx.singletons().get(ctx, bindings::world::metatable)),
135        );
136        data
137    }
138
139    /// Add this world
140    fn add_to_env<'gc>(&self, ctx: Context<'gc>, env: Table<'gc>) {
141        ctx.globals()
142            .set(ctx, "world", self.clone().into_userdata(ctx))
143            .unwrap();
144        for (name, metatable) in [
145            ("world", bindings::world::metatable as fn(Context) -> Table),
146            ("components", bindings::components::metatable),
147            ("resources", bindings::resources::metatable),
148            ("assets", bindings::assets::metatable),
149        ] {
150            let data = UserData::new_static(&ctx, self.clone());
151            data.set_metatable(&ctx, Some(ctx.singletons().get(ctx, metatable)));
152            env.set(ctx, name, data).unwrap();
153        }
154    }
155}
156
157/// Resource used to access the lua scripting engine.
158#[derive(HasSchema, Clone)]
159#[schema(no_default)]
160pub struct LuaEngine {
161    /// The thread-local task executor that is used to spawn any tasks that need access to the
162    /// lua engine which can only be accessed on it's own thread.
163    executor: Arc<ThreadExecutor<'static>>,
164    /// The lua engine state container.
165    state: Arc<SendWrapper<EngineState>>,
166}
167
168/// Internal state for [`LuaEngine`].
169struct EngineState {
170    /// The Lua engine.
171    lua: Mutex<Lua>,
172    /// Persisted lua data we need stored in Rust, such as the environment table, world
173    /// metatable, etc.
174    data: LuaSingletons,
175    /// Cache of the content IDs of loaded scripts, and their compiled lua closures.
176    compiled_scripts: Mutex<HashMap<Cid, StashedClosure>>,
177}
178
179// TODO: Don't Use Function Pointers to Index Lua Singletons.
180// Unfortunately, function pointers with different signatures may be unified by
181// LLVM when activating, for intance, LTO, and that can cause unexpected behavior
182// when using them as indexes into a HashMap for singletons.
183/// Struct for accessing and initializing lua singletons.
184///
185/// This is stored in a lua global and accessed conveniently through our [`CtxExt`] trait
186/// so that we can easily initialize lua tables and callbacks throughout our lua bindings.
187pub struct LuaSingletons {
188    singletons: Rc<AtomicCell<HashMap<usize, Box<dyn Any>>>>,
189}
190impl Default for LuaSingletons {
191    fn default() -> Self {
192        Self {
193            singletons: Rc::new(AtomicCell::new(HashMap::default())),
194        }
195    }
196}
197impl LuaSingletons {
198    /// Fetch a lua singleton, initializing it if it has not yet been created.
199    ///
200    /// The singleton is defined by a function pointer that returns a stashable value.
201    fn get<
202        'gc,
203        S: Fetchable<'gc, Fetched = T> + 'static,
204        T: Stashable<'gc, Stashed = S> + Clone + Copy + 'gc,
205    >(
206        &self,
207        ctx: Context<'gc>,
208        singleton: fn(Context<'gc>) -> T,
209    ) -> T {
210        let map = self.singletons.borrow_mut();
211        let id = singleton as usize;
212        if let Some(entry) = map.get(&id) {
213            let stashed = entry.downcast_ref::<S>().expect(
214                "Encountered two functions with different return types and \
215                the same function pointer.",
216            );
217            ctx.registry().fetch(stashed)
218        } else {
219            drop(map); // Make sure we don't deadlock
220            let v = singleton(ctx);
221            let stashed = ctx.registry().stash(&ctx, v);
222            self.singletons.borrow_mut().insert(id, Box::new(stashed));
223            v
224        }
225    }
226}
227
228impl Default for EngineState {
229    fn default() -> Self {
230        // Initialize an empty lua engine and our lua data.
231        let mut lua = Lua::core();
232        lua.try_enter(|ctx| {
233            // Insert our lua singletons.
234            ctx.globals().set(
235                ctx,
236                "luasingletons",
237                UserData::new_static(&ctx, LuaSingletons::default()),
238            )?;
239            Ok(())
240        })
241        .unwrap();
242        Self {
243            lua: Mutex::new(lua),
244            data: default(),
245            compiled_scripts: default(),
246        }
247    }
248}
249
250impl Default for LuaEngine {
251    /// Initialize the Lua engine.
252    fn default() -> Self {
253        // Make sure the compute task pool is initialized
254        ComputeTaskPool::init(TaskPool::new);
255
256        #[cfg(not(target_arch = "wasm32"))]
257        let executor = {
258            let (send, recv) = async_channel::bounded(1);
259
260            // Spawn the executor task that will be used for the lua engine.
261            let pool = ComputeTaskPool::get();
262            pool.spawn_local(async move {
263                let executor = Arc::new(ThreadExecutor::new());
264                send.try_send(executor.clone()).unwrap();
265
266                let ticker = (*executor).ticker().unwrap();
267                loop {
268                    ticker.tick().await;
269                }
270            })
271            .detach();
272            pool.with_local_executor(|local| while local.try_tick() {});
273
274            recv.try_recv().unwrap()
275        };
276
277        #[cfg(target_arch = "wasm32")]
278        let executor = Arc::new(ThreadExecutor::new());
279
280        LuaEngine {
281            executor,
282            state: Arc::new(SendWrapper::new(default())),
283        }
284    }
285}
286
287impl LuaEngine {
288    /// Access the lua engine to run code on it.
289    pub fn exec<'a, F: FnOnce(&mut Lua) + Send + 'a>(&self, f: F) {
290        let pool = ComputeTaskPool::get();
291
292        // Create a new scope spawned on the lua engine thread.
293        pool.scope_with_executor(false, Some(&self.executor), |scope| {
294            scope.spawn_on_external(async {
295                f(&mut self.state.lua.lock());
296            });
297        });
298    }
299
300    /// Run a lua script as a system on the given world.
301    pub fn run_script_system(&self, world: &World, script: Handle<LuaScript>) {
302        self.exec(|lua| {
303            Frozen::<Freeze![&'freeze World]>::in_scope(world, |world| {
304                // Wrap world reference so that it can be converted to lua userdata.
305                let worldref = WorldRef(world);
306
307                let executor = lua.try_enter(|ctx| {
308                    // Fetch the env table
309                    let env = self.state.data.get(ctx, bindings::env);
310
311                    // Compile the script
312                    let closure = worldref.with(|world| {
313                        let asset_server = world.resource::<AssetServer>();
314                        let cid = *asset_server
315                            .store
316                            .asset_ids
317                            .get(&script.untyped())
318                            .ok_or_else(|| {
319                                tracing::warn!("Script asset not loaded.");
320                                PrototypeError::Parser(ParseError {
321                                    kind: piccolo::compiler::ParseErrorKind::EndOfStream {
322                                        expected: None,
323                                    },
324                                    line_number: LineNumber(0),
325                                })
326                            })?;
327
328                        let mut compiled_scripts = self.state.compiled_scripts.lock();
329                        let closure = compiled_scripts.get(&cid);
330
331                        Ok::<_, PrototypeError>(match closure {
332                            Some(closure) => ctx.registry().fetch(closure),
333                            None => {
334                                let asset = asset_server.store.assets.get(&cid).unwrap();
335                                let source = &asset.data.cast_ref::<LuaScript>().source;
336                                // TODO: Provide a meaningfull name to loaded scripts.
337                                let closure =
338                                    Closure::load_with_env(ctx, None, source.as_bytes(), env)?;
339                                compiled_scripts.insert(cid, ctx.registry().stash(&ctx, closure));
340
341                                closure
342                            }
343                        })
344                    })?;
345
346                    // Insert the world ref into the global scope
347                    worldref.add_to_env(ctx, env);
348
349                    let ex = Executor::start(ctx, closure.into(), ());
350                    let ex = ctx.registry().stash(&ctx, ex);
351                    Ok(ex)
352                });
353
354                if let Err(e) = executor.and_then(|ex| lua.execute::<()>(&ex)) {
355                    tracing::error!("{e}");
356                }
357            });
358        });
359    }
360}