Compare commits

...

10 commits

Author SHA1 Message Date
56fd44062c Bump version
Some checks failed
Deploy book / deploy (push) Has been cancelled
Rust / build (push) Has been cancelled
2025-05-07 14:37:51 +02:00
Jarosław Konik
297bffd060
Make value struct fields public, add examples (#44) 2025-05-07 14:23:26 +02:00
Peter David Faria
2c82a2fa0e
Added initial support for bevy 0.16.0 (#39)
* Added initial support for bevy 0.16.0

* Removed unnecessary bevy feature

* update version references

---------

Co-authored-by: Jaroslaw Konik <konikjar@gmail.com>
2025-05-01 11:18:52 +02:00
Jarosław Konik
ec84d9e740
move demo up (#37) 2025-04-18 08:54:33 +00:00
GolDNenex
f9e872e111
Update bevy 0.15 (#36)
* Update bevy 0.15

* Removed unused import "AsyncReadExt"

* Update README.md

* Update lib.rs

* Update README.md

* Fix cargo test by not running examples that never end in lib.rs

* get rid of warnings

* update version references

* dont run examples

* deny warnings

* remove obsolete runners

---------

Co-authored-by: Jarosław Konik <konikjar@gmail.com>
2025-04-15 21:27:08 +02:00
gak
a718aa7ce6
smallest typo fix ever: life -> live (#25) 2024-07-28 07:09:33 +02:00
Dennis
be8a80519d
Added add_scripting_api function to AppBuilder (#23)
* Added `add_scripting_api` function to builder
2024-07-17 10:36:00 +02:00
Jarosław Konik
f85dbcffe2
update readme (#22) 2024-07-05 17:26:25 +02:00
Jarosław Konik
182f26e273
update book bevy support matrix (#21) 2024-07-05 17:21:00 +02:00
Jarosław Konik
7488de076b
support bevy 0.14 (#20)
* support bevy 0.14
2024-07-05 17:16:06 +02:00
33 changed files with 513 additions and 167 deletions

View file

@ -11,9 +11,9 @@ env:
jobs:
build:
runs-on: ubuntu-latest
env:
RUSTFLAGS: -D warnings
steps:
- uses: actions/checkout@v3
- name: Clippy
@ -22,7 +22,3 @@ jobs:
run: cargo build --all-features --verbose
- name: Run tests
run: cargo test --all-features --verbose
- name: Install cargo-examples
run: cargo install cargo-examples
- name: Run all examples
run: cargo examples --features=lua,rhai

View file

@ -1,7 +1,7 @@
[package]
name = "bevy_scriptum"
authors = ["Jaroslaw Konik <konikjar@gmail.com>"]
version = "0.5.0"
version = "0.8.1"
edition = "2021"
license = "MIT OR Apache-2.0"
readme = "README.md"
@ -15,95 +15,141 @@ lua = ["mlua/luajit"]
rhai = ["dep:rhai"]
[dependencies]
bevy = { default-features = false, version = "0.13.0", features = [
"bevy_asset",
] }
bevy = { default-features = false, version = "0.16", features = ["bevy_asset", "bevy_log"] }
serde = "1.0.162"
rhai = { version = "1.14.0", features = ["sync", "internals", "unchecked"], optional = true }
rhai = { version = "1.14.0", features = [
"sync",
"internals",
"unchecked",
], optional = true }
thiserror = "1.0.40"
anyhow = "1.0.82"
tracing = "0.1.40"
mlua = { version = "0.9.8", features = ["luajit", "vendored", "send"], optional = true }
mlua = { version = "0.9.8", features = [
"luajit",
"vendored",
"send",
], optional = true }
[[example]]
name = "call_function_from_rust_rhai"
path = "examples/rhai/call_function_from_rust.rs"
required-features = ["rhai"]
[[example]]
name = "current_entity_rhai"
path = "examples/rhai/current_entity.rs"
required-features = ["rhai"]
[[example]]
name = "custom_type_rhai"
path = "examples/rhai/custom_type.rs"
required-features = ["rhai"]
[[example]]
name = "ecs_rhai"
path = "examples/rhai/ecs.rs"
required-features = ["rhai"]
[[example]]
name = "entity_variable_rhai"
path = "examples/rhai/entity_variable.rs"
required-features = ["rhai"]
[[example]]
name = "function_params_rhai"
path = "examples/rhai/function_params.rs"
required-features = ["rhai"]
[[example]]
name = "hello_world_rhai"
path = "examples/rhai/hello_world.rs"
required-features = ["rhai"]
[[example]]
name = "multiple_plugins_rhai"
path = "examples/rhai/multiple_plugins.rs"
required-features = ["rhai"]
[[example]]
name = "non_closure_system_rhai"
path = "examples/rhai/non_closure_system.rs"
required-features = ["rhai"]
[[example]]
name = "promises_rhai"
path = "examples/rhai/promises.rs"
required-features = ["rhai"]
[[example]]
name = "side_effects_rhai"
path = "examples/rhai/side_effects.rs"
required-features = ["rhai"]
[[example]]
name = "function_return_value_rhai"
path = "examples/rhai/function_return_value.rs"
required-features = ["rhai"]
[[example]]
name = "call_function_from_rust_lua"
path = "examples/lua/call_function_from_rust.rs"
required-features = ["lua"]
[[example]]
name = "current_entity_lua"
path = "examples/lua/current_entity.rs"
required-features = ["lua"]
[[example]]
name = "custom_type_lua"
path = "examples/lua/custom_type.rs"
required-features = ["lua"]
[[example]]
name = "ecs_lua"
path = "examples/lua/ecs.rs"
required-features = ["lua"]
[[example]]
name = "entity_variable_lua"
path = "examples/lua/entity_variable.rs"
required-features = ["lua"]
[[example]]
name = "function_params_lua"
path = "examples/lua/function_params.rs"
required-features = ["lua"]
[[example]]
name = "hello_world_lua"
path = "examples/lua/hello_world.rs"
required-features = ["lua"]
[[example]]
name = "multiple_plugins_lua"
path = "examples/lua/multiple_plugins.rs"
required-features = ["lua"]
[[example]]
name = "non_closure_system_lua"
path = "examples/lua/non_closure_system.rs"
required-features = ["lua"]
[[example]]
name = "promises_lua"
path = "examples/lua/promises.rs"
required-features = ["lua"]
[[example]]
name = "side_effects_lua"
path = "examples/lua/side_effects.rs"
required-features = ["lua"]
[[example]]
name = "function_return_value_lua"
path = "examples/lua/function_return_value.rs"
required-features = ["lua"]
[dev-dependencies]
tracing-subscriber = "0.3.18"

View file

@ -1,5 +1,7 @@
# bevy_scriptum 📜
![demo](demo.gif)
bevy_scriptum is a a plugin for [Bevy](https://bevyengine.org/) that allows you to write some of your game logic in a scripting language.
Currently [Rhai](https://rhai.rs/) and [Lua](https://lua.org/) are supported, but more languages may be added in the future.
@ -84,6 +86,33 @@ which you can then call in your script like this:
```lua
fun_with_string_param("Hello world!")
```
It is also possible to split the definition of your callback functions up over multiple plugins. This enables you to split up your code by subject and keep the main initialization light and clean.
This can be accomplished by using `add_scripting_api`. Be careful though, `add_scripting` has to be called before adding plugins.
```rust
use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
struct MyPlugin;
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.add_scripting_api::<LuaRuntime>(|runtime| {
runtime.add_function(String::from("hello_from_my_plugin"), || {
info!("Hello from MyPlugin");
});
});
}
}
App::new()
.add_plugins(DefaultPlugins)
.add_scripting::<LuaRuntime>(|_| {
// nice and clean
})
.add_plugins(MyPlugin)
.run();
```
### Usage
@ -91,7 +120,7 @@ Add the following to your `Cargo.toml`:
```toml
[dependencies]
bevy_scriptum = { version = "0.5", features = ["lua"] }
bevy_scriptum = { version = "0.7", features = ["lua"] }
```
or execute `cargo add bevy_scriptum --features lua` from your project directory.
@ -147,10 +176,6 @@ App::new()
You should then see `my_print: 'Hello world!'` printed in your console.
### Demo
![demo](demo.gif)
### Provided examples
You can also try running provided examples by cloning this repository and running `cargo run --example <example_name>_<language_name>`. For example:
@ -163,7 +188,10 @@ The examples live in `examples` directory and their corresponding scripts live i
### Bevy compatibility
| bevy version | bevy_scriptum version |
|--------------|----------------------|
|--------------|-----------------------|
| 0.16 | 0.8 |
| 0.15 | 0.7 |
| 0.14 | 0.6 |
| 0.13 | 0.4-0.5 |
| 0.12 | 0.3 |
| 0.11 | 0.2 |

View file

@ -7,7 +7,7 @@ currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| 0.5 | :white_check_mark: |
| 0.8 | :white_check_mark: |
## Reporting a Vulnerability

View file

@ -0,0 +1,3 @@
function get_value()
return 42
end

View file

@ -0,0 +1 @@
hello_from_plugin_a()

View file

@ -0,0 +1 @@
hello_from_plugin_b_with_parameters("hello", 42)

View file

@ -0,0 +1,3 @@
fn get_value() {
42
}

View file

@ -0,0 +1 @@
hello_from_plugin_a();

View file

@ -0,0 +1 @@
hello_from_plugin_b_with_parameters("hello", 42);

View file

@ -1,7 +1,10 @@
# Bevy support matrix
| bevy version | bevy_scriptum version |
|--------------|----------------------|
| ------------ | --------------------- |
| 0.16 | 0.8 |
| 0.15 | 0.7 |
| 0.14 | 0.6 |
| 0.13 | 0.4-0.5 |
| 0.12 | 0.3 |
| 0.11 | 0.2 |

View file

@ -88,13 +88,43 @@ which you can then call in your script like this:
fun_with_string_param("Hello world!")
```
It is also possible to split the definition of your callback functions up over multiple plugins. This enables you to split up your code by subject and keep the main initialization light and clean.
This can be accomplished by using `add_scripting_api`. Be careful though, `add_scripting` has to be called before adding plugins.
```rust
use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
struct MyPlugin;
impl Plugin for MyPlugin {
fn build(&self, app: &mut App) {
app.add_scripting_api::<LuaRuntime>(|runtime| {
runtime.add_function(String::from("hello_from_my_plugin"), || {
info!("Hello from MyPlugin");
});
});
}
}
// Main
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_scripting::<LuaRuntime>(|_| {
// nice and clean
})
.add_plugins(MyPlugin)
.run();
}
```
### Usage
Add the following to your `Cargo.toml`:
```toml
[dependencies]
bevy_scriptum = { version = "0.5", features = ["lua"] }
bevy_scriptum = { version = "0.8", features = ["lua"] }
```
or execute `cargo add bevy_scriptum --features lua` from your project directory.

View file

@ -4,8 +4,8 @@ Add the following to your `Cargo.toml`:
```toml
[dependencies]
bevy = "0.13"
bevy_scriptum = { version = "0.5", features = ["lua"] }
bevy = "0.16"
bevy_scriptum = { version = "0.8", features = ["lua"] }
```
If you need a different version of bevy you need to use a matching bevy_scriptum

View file

@ -4,8 +4,8 @@ Add the following to your `Cargo.toml`:
```toml
[dependencies]
bevy = "0.13"
bevy_scriptum = { version = "0.5", features = ["rhai"] }
bevy = "0.16"
bevy_scriptum = { version = "0.8", features = ["rhai"] }
```
If you need a different version of bevy you need to use a matching bevy_scriptum

View file

@ -2,11 +2,11 @@
## Bevy included support
To enable life reload it should be enough to enable `file-watcher` feature
To enable live reload it should be enough to enable `file-watcher` feature
within bevy dependency in `Cargo.toml`
```
bevy = { version = "0.13", features = ["file_watcher"] }
bevy = { version = "0.16", features = ["file_watcher"] }
```
## Init-teardown pattern for game development

View file

@ -1,32 +1,15 @@
use bevy::{app::AppExit, ecs::event::ManualEventReader, prelude::*};
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
fn main() {
App::new()
// This is just needed for headless console app, not needed for a regular bevy game
// that uses a winit window
.set_runner(move |mut app: App| {
let mut app_exit_event_reader = ManualEventReader::<AppExit>::default();
loop {
if let Some(app_exit_events) = app.world.get_resource_mut::<Events<AppExit>>() {
if app_exit_event_reader
.read(&app_exit_events)
.last()
.is_some()
{
break;
}
}
app.update();
}
})
.add_plugins(DefaultPlugins)
.add_systems(Startup, startup)
.add_systems(Update, call_lua_on_update_from_rust)
.add_scripting::<LuaRuntime>(|runtime| {
runtime.add_function(String::from("quit"), |mut exit: EventWriter<AppExit>| {
exit.send(AppExit);
exit.write(AppExit::Success);
});
})
.run();

View file

@ -0,0 +1,42 @@
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, startup)
.add_systems(Update, call_lua_on_update_from_rust)
.add_scripting::<LuaRuntime>(|runtime| {
runtime.add_function(String::from("quit"), |mut exit: EventWriter<AppExit>| {
exit.write(AppExit::Success);
});
})
.run();
}
fn startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<LuaScript>::new(
assets_server.load("examples/lua/function_return_value.lua"),
));
}
fn call_lua_on_update_from_rust(
mut scripted_entities: Query<(Entity, &mut LuaScriptData)>,
scripting_runtime: ResMut<LuaRuntime>,
mut exit: EventWriter<AppExit>,
) {
for (entity, mut script_data) in &mut scripted_entities {
let val = scripting_runtime
.call_fn("get_value", &mut script_data, entity, ())
.unwrap()
.0;
scripting_runtime.with_engine(|engine| {
println!(
"script returned: {}",
engine.registry_value::<mlua::Integer>(&val).unwrap()
);
});
exit.write(AppExit::Success);
}
}

View file

@ -0,0 +1,67 @@
use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
// Plugin A
struct PluginA;
impl Plugin for PluginA {
fn build(&self, app: &mut App) {
app.add_scripting_api::<LuaRuntime>(|runtime| {
runtime.add_function(String::from("hello_from_plugin_a"), || {
info!("Hello from Plugin A");
});
})
.add_systems(Startup, plugin_a_startup);
}
}
fn plugin_a_startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<LuaScript>::new(
assets_server.load("examples/lua/multiple_plugins_plugin_a.lua"),
));
}
// Plugin B
struct PluginB;
impl Plugin for PluginB {
fn build(&self, app: &mut App) {
app.add_scripting_api::<LuaRuntime>(|runtime| {
runtime.add_function(
String::from("hello_from_plugin_b_with_parameters"),
hello_from_b,
);
})
.add_systems(Startup, plugin_b_startup);
}
}
fn plugin_b_startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<LuaScript>::new(
assets_server.load("examples/lua/multiple_plugins_plugin_b.lua"),
));
}
fn hello_from_b(In((text, x)): In<(String, i32)>) {
info!("{} from Plugin B: {}", text, x);
}
// Main
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_scripting::<LuaRuntime>(|runtime| {
runtime.add_function(String::from("hello_bevy"), || {
info!("hello bevy, called from script");
});
})
.add_systems(Startup, main_startup)
.add_plugins(PluginA)
.add_plugins(PluginB)
.run();
}
fn main_startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<LuaScript>::new(
assets_server.load("examples/lua/hello_world.lua"),
));
}

View file

@ -11,7 +11,7 @@ fn main() {
.add_scripting::<LuaRuntime>(|builder| {
builder.add_function(
String::from("get_player_name"),
|player_names: Query<&Name, With<Player>>| player_names.single().to_string(),
|player_names: Query<&Name, With<Player>>| player_names.single().expect("Missing player_names").to_string(),
);
})
.add_systems(Startup, startup)

View file

@ -1,4 +1,4 @@
use bevy::{app::AppExit, ecs::event::ManualEventReader, prelude::*};
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
@ -7,18 +7,11 @@ fn main() {
// This is just needed for headless console app, not needed for a regular bevy game
// that uses a winit window
.set_runner(move |mut app: App| {
let mut app_exit_event_reader = ManualEventReader::<AppExit>::default();
loop {
if let Some(app_exit_events) = app.world.get_resource_mut::<Events<AppExit>>() {
if app_exit_event_reader
.read(&app_exit_events)
.last()
.is_some()
{
break;
}
}
app.update();
if let Some(exit) = app.should_exit() {
return exit;
}
}
})
.add_plugins(DefaultPlugins)
@ -45,6 +38,6 @@ fn print_entity_names_and_quit(query: Query<&Name>, mut exit: EventWriter<AppExi
for e in &query {
println!("{}", e);
}
exit.send(AppExit);
exit.write(AppExit::Success);
}
}

View file

@ -1,32 +1,15 @@
use bevy::{app::AppExit, ecs::event::ManualEventReader, prelude::*};
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::rhai::prelude::*;
fn main() {
App::new()
// This is just needed for headless console app, not needed for a regular bevy game
// that uses a winit window
.set_runner(move |mut app: App| {
let mut app_exit_event_reader = ManualEventReader::<AppExit>::default();
loop {
if let Some(app_exit_events) = app.world.get_resource_mut::<Events<AppExit>>() {
if app_exit_event_reader
.read(&app_exit_events)
.last()
.is_some()
{
break;
}
}
app.update();
}
})
.add_plugins(DefaultPlugins)
.add_systems(Startup, startup)
.add_systems(Update, call_rhai_on_update_from_rust)
.add_scripting::<RhaiRuntime>(|runtime| {
runtime.add_function(String::from("quit"), |mut exit: EventWriter<AppExit>| {
exit.send(AppExit);
exit.write(AppExit::Success);
});
})
.run();

View file

@ -0,0 +1,37 @@
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::rhai::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, startup)
.add_systems(Update, call_rhai_on_update_from_rust)
.add_scripting::<RhaiRuntime>(|runtime| {
runtime.add_function(String::from("quit"), |mut exit: EventWriter<AppExit>| {
exit.write(AppExit::Success);
});
})
.run();
}
fn startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<RhaiScript>::new(
assets_server.load("examples/rhai/function_return_value.rhai"),
));
}
fn call_rhai_on_update_from_rust(
mut scripted_entities: Query<(Entity, &mut RhaiScriptData)>,
scripting_runtime: ResMut<RhaiRuntime>,
mut exit: EventWriter<AppExit>,
) {
for (entity, mut script_data) in &mut scripted_entities {
let val = scripting_runtime
.call_fn("get_value", &mut script_data, entity, ())
.unwrap()
.0;
println!("script returned: {}", val);
exit.write(AppExit::Success);
}
}

View file

@ -0,0 +1,68 @@
use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::rhai::prelude::*;
use rhai::ImmutableString;
// Plugin A
struct PluginA;
impl Plugin for PluginA {
fn build(&self, app: &mut App) {
app.add_scripting_api::<RhaiRuntime>(|runtime| {
runtime.add_function(String::from("hello_from_plugin_a"), || {
info!("Hello from Plugin A");
});
})
.add_systems(Startup, plugin_a_startup);
}
}
fn plugin_a_startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<RhaiScript>::new(
assets_server.load("examples/rhai/multiple_plugins_plugin_a.rhai"),
));
}
// Plugin B
struct PluginB;
impl Plugin for PluginB {
fn build(&self, app: &mut App) {
app.add_scripting_api::<RhaiRuntime>(|runtime| {
runtime.add_function(
String::from("hello_from_plugin_b_with_parameters"),
hello_from_b,
);
})
.add_systems(Startup, plugin_b_startup);
}
}
fn plugin_b_startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<RhaiScript>::new(
assets_server.load("examples/rhai/multiple_plugins_plugin_b.rhai"),
));
}
fn hello_from_b(In((text, x)): In<(ImmutableString, i64)>) {
info!("{} from Plugin B: {}", text, x);
}
// Main
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_scripting::<RhaiRuntime>(|runtime| {
runtime.add_function(String::from("hello_bevy"), || {
info!("hello bevy, called from script");
});
})
.add_systems(Startup, main_startup)
.add_plugins(PluginA)
.add_plugins(PluginB)
.run();
}
fn main_startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<RhaiScript>::new(
assets_server.load("examples/rhai/hello_world.rhai"),
));
}

View file

@ -11,7 +11,7 @@ fn main() {
.add_scripting::<RhaiRuntime>(|builder| {
builder.add_function(
String::from("get_player_name"),
|player_names: Query<&Name, With<Player>>| player_names.single().to_string(),
|player_names: Query<&Name, With<Player>>| player_names.single().expect("Missing player_names").to_string(),
);
})
.add_systems(Startup, startup)

View file

@ -1,4 +1,4 @@
use bevy::{app::AppExit, ecs::event::ManualEventReader, prelude::*};
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::rhai::prelude::*;
@ -6,19 +6,10 @@ fn main() {
App::new()
// This is just needed for headless console app, not needed for a regular bevy game
// that uses a winit window
.set_runner(move |mut app: App| {
let mut app_exit_event_reader = ManualEventReader::<AppExit>::default();
loop {
if let Some(app_exit_events) = app.world.get_resource_mut::<Events<AppExit>>() {
if app_exit_event_reader
.read(&app_exit_events)
.last()
.is_some()
{
break;
}
}
.set_runner(move |mut app: App| loop {
app.update();
if let Some(exit) = app.should_exit() {
return exit;
}
})
.add_plugins(DefaultPlugins)
@ -45,6 +36,6 @@ fn print_entity_names_and_quit(query: Query<&Name>, mut exit: EventWriter<AppExi
for e in &query {
println!("{}", e);
}
exit.send(AppExit);
exit.write(AppExit::Success);
}
}

View file

@ -1,8 +1,8 @@
use std::marker::PhantomData;
use bevy::{
asset::{io::Reader, Asset, AssetLoader, AsyncReadExt as _, LoadContext},
utils::BoxedFuture,
asset::{io::Reader, Asset, AssetLoader, LoadContext},
tasks::ConditionalSendFuture,
};
/// A loader for script assets.
@ -29,12 +29,12 @@ impl<A: Asset + From<String> + GetExtensions> AssetLoader for ScriptLoader<A> {
type Settings = ();
type Error = anyhow::Error;
fn load<'a>(
&'a self,
reader: &'a mut Reader,
_settings: &'a Self::Settings,
_load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, anyhow::Result<A, anyhow::Error>> {
fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
_load_context: &mut LoadContext,
) -> impl ConditionalSendFuture<Output = Result<Self::Asset, Self::Error>> {
Box::pin(async move {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;

View file

@ -6,7 +6,7 @@ use crate::{promise::Promise, Runtime};
/// A system that can be used to call a script function.
pub struct CallbackSystem<R: Runtime> {
pub(crate) system: Box<dyn System<In = Vec<R::Value>, Out = R::Value>>,
pub(crate) system: Box<dyn System<In = In<Vec<R::Value>>, Out = R::Value>>,
pub(crate) arg_types: Vec<TypeId>,
}
@ -56,7 +56,10 @@ pub(crate) trait FromRuntimeValueWithEngine<'a, R: Runtime> {
}
/// Trait that alllows to convert a script callback function into a Bevy [`System`].
pub trait IntoCallbackSystem<R: Runtime, In, Out, Marker>: IntoSystem<In, Out, Marker> {
pub trait IntoCallbackSystem<R: Runtime, In, Out, Marker>: IntoSystem<In, Out, Marker>
where
In: SystemInput,
{
/// Convert this function into a [CallbackSystem].
#[must_use]
fn into_callback_system(self, world: &mut World) -> CallbackSystem<R>;
@ -87,10 +90,10 @@ where
macro_rules! impl_tuple {
($($idx:tt $t:tt),+) => {
impl<RN: Runtime, $($t,)+ Out, FN, Marker> IntoCallbackSystem<RN, ($($t,)+), Out, Marker>
impl<RN: Runtime, $($t,)+ Out, FN, Marker> IntoCallbackSystem<RN, In<($($t,)+)>, Out, Marker>
for FN
where
FN: IntoSystem<($($t,)+), Out, Marker>,
FN: IntoSystem<In<($($t,)+)>, Out, Marker>,
Out: for<'a> IntoRuntimeValueWithEngine<'a, Out, RN>,
$($t: 'static + for<'a> FromRuntimeValueWithEngine<'a, RN>,)+
{

View file

@ -1,3 +1,5 @@
//! ![demo](demo.gif)
//!
//! bevy_scriptum is a a plugin for [Bevy](https://bevyengine.org/) that allows you to write some of your game logic in a scripting language.
//! Currently [Rhai](https://rhai.rs/) and [Lua](https://lua.org/) are supported, but more languages may be added in the future.
//!
@ -16,7 +18,7 @@
//! Scripts are separate files that can be hot-reloaded at runtime. This allows you to quickly iterate on your game logic without having to recompile your game.
//!
//! All you need to do is register callbacks on your Bevy app like this:
//! ```rust
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! use bevy_scriptum::runtimes::lua::prelude::*;
@ -37,7 +39,7 @@
//!
//! Every callback function that you expose to the scripting language is also a Bevy system, so you can easily query and mutate ECS components and resources just like you would in a regular Bevy system:
//!
//! ```rust
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! use bevy_scriptum::runtimes::lua::prelude::*;
@ -61,7 +63,7 @@
//! ```
//!
//! You can also pass arguments to your callback functions, just like you would in a regular Bevy system - using `In` structs with tuples:
//! ```rust
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! use bevy_scriptum::runtimes::lua::prelude::*;
@ -82,6 +84,33 @@
//! ```lua
//! fun_with_string_param("Hello world!")
//! ```
//! It is also possible to split the definition of your callback functions up over multiple plugins. This enables you to split up your code by subject and keep the main initialization light and clean.
//! This can be accomplished by using `add_scripting_api`. Be careful though, `add_scripting` has to be called before adding plugins.
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! use bevy_scriptum::runtimes::lua::prelude::*;
//!
//! struct MyPlugin;
//! impl Plugin for MyPlugin {
//! fn build(&self, app: &mut App) {
//! app.add_scripting_api::<LuaRuntime>(|runtime| {
//! runtime.add_function(String::from("hello_from_my_plugin"), || {
//! info!("Hello from MyPlugin");
//! });
//! });
//! }
//! }
//!
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_scripting::<LuaRuntime>(|_| {
//! // nice and clean
//! })
//! .add_plugins(MyPlugin)
//! .run();
//! ```
//!
//!
//! ## Usage
//!
@ -89,14 +118,14 @@
//!
//! ```toml
//! [dependencies]
//! bevy_scriptum = { version = "0.5", features = ["lua"] }
//! bevy_scriptum = { version = "0.8", features = ["lua"] }
//! ```
//!
//! or execute `cargo add bevy_scriptum --features lua` from your project directory.
//!
//! You can now start exposing functions to the scripting language. For example, you can expose a function that prints a message to the console:
//!
//! ```rust
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! use bevy_scriptum::runtimes::lua::prelude::*;
@ -122,7 +151,7 @@
//!
//! And spawn an entity with attached `Script` component with a handle to a script source file:
//!
//! ```rust
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_scriptum::prelude::*;
//! use bevy_scriptum::runtimes::lua::prelude::*;
@ -145,10 +174,6 @@
//!
//! You should then see `my_print: 'Hello world!'` printed in your console.
//!
//! ## Demo
//!
//! ![demo](demo.gif)
//!
//! ## Provided examples
//!
//! You can also try running provided examples by cloning this repository and running `cargo run --example <example_name>_<language_name>`. For example:
@ -161,7 +186,10 @@
//! ## Bevy compatibility
//!
//! | bevy version | bevy_scriptum version |
//! |--------------|----------------------|
//! |--------------|-----------------------|
//! | 0.16 | 0.8 |
//! | 0.15 | 0.7 |
//! | 0.14 | 0.6 |
//! | 0.13 | 0.4-0.5 |
//! | 0.12 | 0.3 |
//! | 0.11 | 0.2 |
@ -231,7 +259,7 @@ use std::{
sync::{Arc, Mutex},
};
use bevy::{app::MainScheduleOrder, ecs::schedule::ScheduleLabel, prelude::*};
use bevy::{app::MainScheduleOrder, ecs::{component::Mutable, schedule::ScheduleLabel}, prelude::*};
use callback::{Callback, IntoCallbackSystem};
use systems::{init_callbacks, log_errors, process_calls};
use thiserror::Error;
@ -241,6 +269,7 @@ use self::{
systems::{process_new_scripts, reload_scripts},
};
#[cfg(any(feature = "rhai", feature = "lua"))]
const ENTITY_VAR_NAME: &str = "entity";
/// An error that can occur when internal [ScriptingPlugin] systems are being executed
@ -262,7 +291,7 @@ pub enum ScriptingError {
pub trait Runtime: Resource + Default {
type Schedule: ScheduleLabel + Debug + Clone + Eq + Hash + Default;
type ScriptAsset: Asset + From<String> + GetExtensions;
type ScriptData: Component;
type ScriptData: Component<Mutability = Mutable>;
type CallContext: Send + Clone;
type Value: Send + Clone;
type RawEngine;
@ -330,6 +359,12 @@ pub trait BuildScriptingRuntime {
/// Returns a "runtime" type than can be used to setup scripting runtime(
/// add scripting functions etc.).
fn add_scripting<R: Runtime>(&mut self, f: impl Fn(ScriptingRuntimeBuilder<R>)) -> &mut Self;
/// Returns a "runtime" type that can be used to add additional scripting functions from plugins etc.
fn add_scripting_api<R: Runtime>(
&mut self,
f: impl Fn(ScriptingRuntimeBuilder<R>),
) -> &mut Self;
}
pub struct ScriptingRuntimeBuilder<'a, R: Runtime> {
@ -353,7 +388,10 @@ impl<'a, R: Runtime> ScriptingRuntimeBuilder<'a, R> {
self,
name: String,
fun: impl IntoCallbackSystem<R, In, Out, Marker>,
) -> Self {
) -> Self
where
In: SystemInput,
{
let system = fun.into_callback_system(self.world);
let mut callbacks_resource = self.world.resource_mut::<Callbacks<R>>();
@ -372,7 +410,7 @@ impl BuildScriptingRuntime for App {
/// Adds a scripting runtime. Registers required bevy systems that take
/// care of processing and running the scripts.
fn add_scripting<R: Runtime>(&mut self, f: impl Fn(ScriptingRuntimeBuilder<R>)) -> &mut Self {
self.world
self.world_mut()
.resource_mut::<MainScheduleOrder>()
.insert_after(Update, R::Schedule::default());
@ -395,7 +433,22 @@ impl BuildScriptingRuntime for App {
),
);
let runtime = ScriptingRuntimeBuilder::<R>::new(&mut self.world);
let runtime = ScriptingRuntimeBuilder::<R>::new(self.world_mut());
f(runtime);
self
}
/// Adds a way to add additional accesspoints to the scripting runtime. For example from plugins to add
/// for example additional lua functions to the runtime.
///
/// Be careful with calling this though, make sure that the `add_scripting` call is already called before calling this function.
fn add_scripting_api<R: Runtime>(
&mut self,
f: impl Fn(ScriptingRuntimeBuilder<R>),
) -> &mut Self {
let runtime = ScriptingRuntimeBuilder::<R>::new(self.world_mut());
f(runtime);

View file

@ -58,6 +58,7 @@ impl<C: Clone + Send + 'static, V: Send + Clone> Promise<C, V> {
}
/// Register a callback that will be called when the [Promise] is resolved.
#[cfg(any(feature = "rhai", feature = "lua"))]
pub(crate) fn then(&mut self, callback: V) -> Self {
let mut inner = self
.inner

View file

@ -1,6 +1,6 @@
use bevy::{
asset::Asset,
ecs::{component::Component, entity::Entity, schedule::ScheduleLabel, system::Resource},
ecs::{component::Component, entity::Entity, resource::Resource, schedule::ScheduleLabel},
math::Vec3,
reflect::TypePath,
};
@ -21,7 +21,7 @@ use crate::{
type LuaEngine = Arc<Mutex<Lua>>;
#[derive(Clone)]
pub struct LuaValue(Arc<RegistryKey>);
pub struct LuaValue(pub Arc<RegistryKey>);
impl LuaValue {
fn new<'a, T: IntoLua<'a>>(engine: &'a Lua, value: T) -> Self {

View file

@ -2,7 +2,7 @@ use std::fmt::Debug;
use bevy::{
asset::Asset,
ecs::{component::Component, entity::Entity, schedule::ScheduleLabel, system::Resource},
ecs::{component::Component, entity::Entity, resource::Resource, schedule::ScheduleLabel},
math::Vec3,
reflect::TypePath,
};
@ -48,7 +48,7 @@ pub struct RhaiScriptData {
}
#[derive(Debug, Clone)]
pub struct RhaiValue(rhai::Dynamic);
pub struct RhaiValue(pub rhai::Dynamic);
impl Runtime for RhaiRuntime {
type Schedule = RhaiSchedule;

View file

@ -1,4 +1,4 @@
use bevy::{prelude::*, utils::tracing};
use bevy::{prelude::*, log::tracing};
use std::{
fmt::Display,
sync::{Arc, Mutex},

View file

@ -1,12 +1,17 @@
#[cfg(any(feature = "rhai", feature = "lua"))]
use std::sync::OnceLock;
#[cfg(any(feature = "rhai", feature = "lua"))]
use bevy::ecs::system::RunSystemOnce as _;
#[cfg(any(feature = "rhai", feature = "lua"))]
use bevy::prelude::*;
#[cfg(any(feature = "rhai", feature = "lua"))]
use bevy_scriptum::{prelude::*, FuncArgs, Runtime};
use mlua::Table;
#[cfg(any(feature = "rhai", feature = "lua"))]
static TRACING_SUBSCRIBER: OnceLock<()> = OnceLock::new();
#[cfg(any(feature = "rhai", feature = "lua"))]
fn build_test_app() -> App {
let mut app = App::new();
@ -20,34 +25,37 @@ fn build_test_app() -> App {
app
}
#[cfg(any(feature = "rhai", feature = "lua"))]
fn run_script<R: Runtime, Out, Marker>(
app: &mut App,
path: String,
system: impl IntoSystem<(), Out, Marker>,
) -> Entity {
let asset_server = app.world.get_resource_mut::<AssetServer>().unwrap();
let asset_server = app.world_mut().get_resource_mut::<AssetServer>().unwrap();
let asset = asset_server.load::<R::ScriptAsset>(path);
let entity_id = app.world.spawn(Script::new(asset)).id();
let entity_id = app.world_mut().spawn(Script::new(asset)).id();
app.update(); // let `ScriptData` resources be added to entities
app.world.run_system_once(system);
app.world_mut().run_system_once(system).unwrap();
app.update(); // let callbacks be executed
entity_id
}
#[cfg(any(feature = "rhai", feature = "lua"))]
fn call_script_on_update_from_rust<R: Runtime>(
mut scripted_entities: Query<(Entity, &mut R::ScriptData)>,
scripting_runtime: ResMut<R>,
) where
(): for<'a> FuncArgs<'a, R::Value, R>,
{
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
scripting_runtime
.call_fn("test_func", &mut script_data, entity, ())
.unwrap();
}
#[cfg(any(feature = "rhai", feature = "lua"))]
trait AssertStateKeyValue {
type ScriptData;
fn assert_state_key_value_i64(world: &World, entity_id: Entity, key: &str, value: i64);
@ -55,6 +63,7 @@ trait AssertStateKeyValue {
fn assert_state_key_value_string(world: &World, entity_id: Entity, key: &str, value: &str);
}
#[cfg(any(feature = "rhai", feature = "lua"))]
macro_rules! scripting_tests {
($runtime:ty, $script:literal, $extension:literal) => {
use super::*;
@ -74,7 +83,7 @@ macro_rules! scripting_tests {
.to_string(),
|mut scripted_entities: Query<(Entity, &mut <$runtime as Runtime>::ScriptData)>,
scripting_runtime: ResMut<$runtime>| {
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
scripting_runtime
.call_fn("test_func", &mut script_data, entity, vec![1])
.unwrap();
@ -91,7 +100,7 @@ macro_rules! scripting_tests {
my_int: i64,
}
app.world.init_resource::<IntResource>();
app.world_mut().init_resource::<IntResource>();
app.add_scripting::<$runtime>(|runtime| {
runtime.add_function(
@ -112,7 +121,7 @@ macro_rules! scripting_tests {
call_script_on_update_from_rust::<$runtime>,
);
assert_eq!(app.world.get_resource::<IntResource>().unwrap().my_int, 5);
assert_eq!(app.world().get_resource::<IntResource>().unwrap().my_int, 5);
}
#[test]
@ -125,7 +134,7 @@ macro_rules! scripting_tests {
b: String,
}
app.world.init_resource::<TestResource>();
app.world_mut().init_resource::<TestResource>();
app.add_scripting::<$runtime>(|runtime| {
runtime.add_function(
@ -147,9 +156,9 @@ macro_rules! scripting_tests {
call_script_on_update_from_rust::<$runtime>,
);
assert_eq!(app.world.get_resource::<TestResource>().unwrap().a, 5);
assert_eq!(app.world().get_resource::<TestResource>().unwrap().a, 5);
assert_eq!(
app.world.get_resource::<TestResource>().unwrap().b,
app.world().get_resource::<TestResource>().unwrap().b,
String::from("test")
);
}
@ -169,14 +178,14 @@ macro_rules! scripting_tests {
.to_string(),
|mut scripted_entities: Query<(Entity, &mut <$runtime as Runtime>::ScriptData)>,
scripting_runtime: ResMut<$runtime>| {
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
scripting_runtime
.call_fn("test_func", &mut script_data, entity, vec![1])
.unwrap();
},
);
<$runtime>::assert_state_key_value_i32(&app.world, entity_id, "a_value", 1i32);
<$runtime>::assert_state_key_value_i32(&app.world(), entity_id, "a_value", 1i32);
}
#[test]
@ -194,7 +203,7 @@ macro_rules! scripting_tests {
.to_string(),
|mut scripted_entities: Query<(Entity, &mut <$runtime as Runtime>::ScriptData)>,
scripting_runtime: ResMut<$runtime>| {
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
scripting_runtime
.call_fn(
"test_func",
@ -206,9 +215,9 @@ macro_rules! scripting_tests {
},
);
<$runtime>::assert_state_key_value_i32(&app.world, entity_id, "a_value", 1i32);
<$runtime>::assert_state_key_value_i32(&app.world(), entity_id, "a_value", 1i32);
<$runtime>::assert_state_key_value_string(
&app.world,
&app.world(),
entity_id,
"b_value",
&String::from("abc"),
@ -230,15 +239,15 @@ macro_rules! scripting_tests {
.to_string(),
|mut scripted_entities: Query<(Entity, &mut <$runtime as Runtime>::ScriptData)>,
scripting_runtime: ResMut<$runtime>| {
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
scripting_runtime
.call_fn("test_func", &mut script_data, entity, vec![1, 2])
.unwrap();
},
);
<$runtime>::assert_state_key_value_i32(&app.world, entity_id, "a_value", 1i32);
<$runtime>::assert_state_key_value_i32(&app.world, entity_id, "b_value", 2i32);
<$runtime>::assert_state_key_value_i32(&app.world(), entity_id, "a_value", 1i32);
<$runtime>::assert_state_key_value_i32(&app.world(), entity_id, "b_value", 2i32);
}
#[test]
@ -256,7 +265,7 @@ macro_rules! scripting_tests {
.to_string(),
|mut scripted_entities: Query<(Entity, &mut <$runtime as Runtime>::ScriptData)>,
scripting_runtime: ResMut<$runtime>| {
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
let result =
scripting_runtime.call_fn("test_func", &mut script_data, entity, ());
assert!(result.is_err());
@ -279,7 +288,7 @@ macro_rules! scripting_tests {
.to_string(),
|mut scripted_entities: Query<(Entity, &mut <$runtime as Runtime>::ScriptData)>,
scripting_runtime: ResMut<$runtime>| {
let (entity, mut script_data) = scripted_entities.single_mut();
let (entity, mut script_data) = scripted_entities.single_mut().unwrap();
let result =
scripting_runtime.call_fn("does_not_exist", &mut script_data, entity, ());
assert!(result.is_err());
@ -303,7 +312,7 @@ macro_rules! scripting_tests {
call_script_on_update_from_rust::<$runtime>,
);
<$runtime>::assert_state_key_value_i64(&app.world, entity_id, "times_called", 1i64);
<$runtime>::assert_state_key_value_i64(&app.world(), entity_id, "times_called", 1i64);
}
#[test]
@ -320,7 +329,7 @@ macro_rules! scripting_tests {
call_script_on_update_from_rust::<$runtime>,
);
<$runtime>::assert_state_key_value_i32(&app.world, entity_id, "x", 123i32);
<$runtime>::assert_state_key_value_i32(&app.world(), entity_id, "x", 123i32);
}
#[test]
@ -357,9 +366,11 @@ macro_rules! scripting_tests {
call_script_on_update_from_rust::<$runtime>,
);
app.world.run_system_once(|tagged: Query<&MyTag>| {
tagged.single();
});
app.world_mut()
.run_system_once(|tagged: Query<&MyTag>| {
tagged.single().unwrap();
})
.unwrap();
}
#[test]
@ -371,7 +382,7 @@ macro_rules! scripting_tests {
times_called: u8,
}
app.world.init_resource::<TimesCalled>();
app.world_mut().init_resource::<TimesCalled>();
app.add_scripting::<$runtime>(|runtime| {
runtime.add_function(String::from("rust_func"), |mut res: ResMut<TimesCalled>| {
@ -390,7 +401,7 @@ macro_rules! scripting_tests {
);
assert_eq!(
app.world
app.world()
.get_resource::<TimesCalled>()
.unwrap()
.times_called,
@ -434,6 +445,7 @@ mod rhai_tests {
mod lua_tests {
use bevy::prelude::*;
use bevy_scriptum::runtimes::lua::prelude::*;
use mlua::Table;
impl AssertStateKeyValue for LuaRuntime {
type ScriptData = LuaScriptData;