bones_scripting/lua/bindings/
assets.rs

1use super::*;
2
3pub fn metatable(ctx: Context) -> Table {
4    let metatable = Table::new(&ctx);
5    metatable
6        .set(ctx, "__newindex", ctx.singletons().get(ctx, no_newindex))
7        .unwrap();
8    metatable
9        .set(
10            ctx,
11            "__tostring",
12            Callback::from_fn(&ctx, |ctx, _fuel, mut stack| {
13                stack.push_front(piccolo::String::from_static(&ctx, "Assets { root, get }").into());
14                Ok(CallbackReturn::Return)
15            }),
16        )
17        .unwrap();
18
19    let get_callback = ctx.registry().stash(
20        &ctx,
21        Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
22            let (world, ecsref): (&WorldRef, &EcsRef) = stack.consume(ctx)?;
23
24            let b = ecsref.borrow();
25            let handle = b.schema_ref()?.try_cast::<UntypedHandle>()?;
26
27            let assetref = world
28                .with(|world| EcsRef {
29                    data: EcsRefData::Asset(AssetRef {
30                        server: (*world.resources.get::<AssetServer>().unwrap()).clone(),
31                        handle: *handle,
32                    }),
33                    path: default(),
34                })
35                .into_value(ctx);
36            stack.push_front(assetref);
37
38            Ok(CallbackReturn::Return)
39        }),
40    );
41
42    metatable
43        .set(
44            ctx,
45            "__index",
46            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
47                let (world, key): (&WorldRef, lua::Value) = stack.consume(ctx)?;
48
49                if let Value::String(key) = key {
50                    #[allow(clippy::single_match)]
51                    match key.as_bytes() {
52                        b"root" => {
53                            world.with(|world| {
54                                let asset_server = world.resources.get::<AssetServer>().unwrap();
55                                let root = asset_server.core().root;
56                                let assetref = EcsRef {
57                                    data: EcsRefData::Asset(AssetRef {
58                                        server: (*asset_server).clone(),
59                                        handle: root,
60                                    }),
61                                    path: default(),
62                                }
63                                .into_value(ctx);
64                                stack.push_front(assetref);
65                            });
66                        }
67                        b"get" => {
68                            stack.push_front(ctx.registry().fetch(&get_callback).into());
69                        }
70                        _ => (),
71                    }
72                }
73
74                Ok(CallbackReturn::Return)
75            }),
76        )
77        .unwrap();
78
79    metatable
80}