-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
console_integration.rs
180 lines (154 loc) · 5.96 KB
/
console_integration.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
use bevy::{ecs::event::Events, prelude::*};
use bevy_console::{AddConsoleCommand, ConsoleCommand, ConsolePlugin, PrintConsoleLine};
use bevy_mod_scripting::prelude::*;
use clap::Parser;
use std::sync::Mutex;
#[derive(Default)]
pub struct LuaAPIProvider;
/// the custom Lua api, world is provided via a global pointer,
/// and callbacks are defined only once at script creation
impl APIProvider for LuaAPIProvider {
type APITarget = Mutex<Lua>;
type DocTarget = LuaDocFragment;
type ScriptContext = Mutex<Lua>;
fn attach_api(&mut self, ctx: &mut Self::APITarget) -> Result<(), ScriptError> {
// callbacks can receive any `ToLuaMulti` arguments, here '()' and
// return any `FromLuaMulti` arguments, here a `usize`
// check the Rlua documentation for more details
let ctx = ctx.get_mut().unwrap();
ctx.globals()
.set(
"print_to_console",
ctx.create_function(|ctx, msg: String| {
// retrieve the world pointer
let world = ctx.get_world()?;
let mut world = world.write();
let mut events: Mut<Events<PrintConsoleLine>> =
world.get_resource_mut().unwrap();
events.send(PrintConsoleLine { line: msg });
// return something
Ok(())
})
.map_err(ScriptError::new_other)?,
)
.map_err(ScriptError::new_other)?;
Ok(())
}
fn setup_script(
&mut self,
_: &ScriptData,
_: &mut Self::ScriptContext,
) -> Result<(), ScriptError> {
Ok(())
}
}
/// sends updates to script host which are then handled by the scripts
/// in their designated system sets
pub fn trigger_on_update_lua(mut w: PriorityEventWriter<LuaEvent<()>>) {
let event = LuaEvent {
hook_name: "on_update".to_string(),
args: (),
recipients: Recipients::All,
};
w.send(event, 0);
}
pub fn forward_script_err_to_console(
mut r: EventReader<ScriptErrorEvent>,
mut w: EventWriter<PrintConsoleLine>,
) {
for e in r.read() {
w.send(PrintConsoleLine {
line: format!("ERROR:{}", e.error),
});
}
}
// we use bevy-debug-console to demonstrate how this can fit in in the runtime of a game
// note that using just the entity id instead of the full Entity has issues,
// but since we aren't despawning/spawning entities this works in our case
#[derive(Parser, ConsoleCommand)]
#[command(name = "run_script")]
///Runs a Lua script from the `assets/scripts` directory
pub struct RunScriptCmd {
/// the relative path to the script, e.g.: `/hello.lua` for a script located in `assets/scripts/hello.lua`
pub path: String,
/// the entity id to attach this script to
pub entity: Option<u32>,
}
pub fn run_script_cmd(
mut log: ConsoleCommand<RunScriptCmd>,
server: Res<AssetServer>,
mut commands: Commands,
mut existing_scripts: Query<&mut ScriptCollection<LuaFile>>,
) {
if let Some(Ok(RunScriptCmd { path, entity })) = log.take() {
let handle = server.load::<LuaFile>(&format!("scripts/{}", &path));
match entity {
Some(e) => {
if let Ok(mut scripts) = existing_scripts.get_mut(Entity::from_raw(e)) {
info!("Creating script: scripts/{} {:?}", &path, e);
scripts.scripts.push(Script::<LuaFile>::new(path, handle));
} else {
log.reply_failed("Something went wrong".to_string());
};
}
None => {
info!("Creating script: scripts/{}", &path);
commands.spawn(()).insert(ScriptCollection::<LuaFile> {
scripts: vec![Script::<LuaFile>::new(path, handle)],
});
}
};
}
}
pub fn delete_script_cmd(
mut log: ConsoleCommand<DeleteScriptCmd>,
mut scripts: Query<(Entity, &mut ScriptCollection<LuaFile>)>,
) {
if let Some(Ok(DeleteScriptCmd { name, entity_id })) = log.take() {
for (e, mut s) in scripts.iter_mut() {
if e.index() == entity_id {
let old_len = s.scripts.len();
s.scripts.retain(|s| s.name() != name);
if old_len > s.scripts.len() {
log.reply_ok(format!("Deleted script {}, on entity: {}", name, entity_id));
} else {
log.reply_failed(format!(
"Entity {} did own a script named: {}",
entity_id, name
))
};
return;
}
}
log.reply_failed("Could not find given entity ID with a script")
}
}
#[derive(Parser, ConsoleCommand)]
#[command(name = "delete_script")]
///Runs a Lua script from the `assets/scripts` directory
pub struct DeleteScriptCmd {
/// the name of the script
pub name: String,
/// the entity the script is attached to
pub entity_id: u32,
}
fn main() -> std::io::Result<()> {
let mut app = App::new();
app.add_plugins(DefaultPlugins)
.add_plugins(ScriptingPlugin)
.add_plugins(ConsolePlugin)
// register bevy_console commands
.add_console_command::<RunScriptCmd, _>(run_script_cmd)
.add_console_command::<DeleteScriptCmd, _>(delete_script_cmd)
// choose and register the script hosts you want to use
.add_script_host::<LuaScriptHost<()>>(PostUpdate)
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaAPIProvider))
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaCoreBevyAPIProvider))
.add_script_handler::<LuaScriptHost<()>, 0, 0>(PostUpdate)
// add your systems
.add_systems(Update, trigger_on_update_lua)
.add_systems(Update, forward_script_err_to_console);
info!("press '~' to open the console. Type in `run_script \"console_integration.lua\"` to run example script!");
app.run();
Ok(())
}