Compare commits

...

10 Commits

Author SHA1 Message Date
d633820d19
refactor: try removing gc_stop
This used to cause deadlocks, but it's been a while with many things
rewritten. Let's try enabling it again to see if any issues surface.
Performance should increase as this was called on every event (packet?).
2025-02-26 17:38:04 -05:00
9b0f8ec406
feat(client): add menu field 2025-02-26 17:37:50 -05:00
543f0af741
refactor(lua/system): return command output as strings 2025-02-25 18:19:11 -05:00
e081813ba4
fix: flip direction table values 2025-02-25 18:12:33 -05:00
2b9bf1987b
refactor: minor improvements 2025-02-25 18:07:01 -05:00
5691afaf2d
fix(lib/inventory): use client.container 2025-02-24 22:20:07 -05:00
d7f863b680
feat: add set_health event 2025-02-24 18:27:50 -05:00
247612fad0
refactor: use a RwLock for event listeners 2025-02-24 16:56:10 -05:00
36054ced03
refactor: random cleanups and efficiency improvements 2025-02-24 01:31:51 -05:00
2ea7ec9e7e
fix(events): manipulate listeners in a task to avoid deadlocks 2025-02-23 17:18:55 -05:00
15 changed files with 202 additions and 133 deletions

12
Cargo.lock generated
View File

@ -1184,6 +1184,7 @@ dependencies = [
"bevy_log",
"clap",
"futures",
"futures-locks",
"http-body-util",
"hyper",
"hyper-util",
@ -1317,6 +1318,17 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "futures-locks"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45ec6fe3675af967e67c5536c0b9d44e34e6c52f86bedc4ea49c5317b8e94d06"
dependencies = [
"futures-channel",
"futures-task",
"tokio",
]
[[package]]
name = "futures-macro"
version = "0.3.31"

View File

@ -21,6 +21,7 @@ bevy_app = "0"
bevy_log = "0"
clap = { version = "4", features = ["derive"] }
futures = "0"
futures-locks = "0"
http-body-util = "0"
hyper = { version = "1", features = ["server"] }
hyper-util = "0"

View File

@ -14,17 +14,17 @@ function log_player_positions()
end
end
function on_init()
add_listener("init", function()
info("client initialized, setting information...")
client:set_client_information({ view_distance = 16 })
end)
add_listener("login", function()
add_listener("login", function()
info("player successfully logged in!")
end)
end)
add_listener("death", function()
add_listener("death", function()
warn(string.format("player died at %.1f %.1f %.1f!", client.position.x, client.position.y, client.position.z))
end, "warn_player_died")
end, "warn_player_died")
add_listener("tick", log_player_positions)
end
add_listener("tick", log_player_positions)

View File

@ -17,7 +17,7 @@ function steal(item_name)
end
container = nil
while client.open_container do
while client.container do
sleep(50)
end
end

View File

@ -4,20 +4,17 @@ use crate::{
State,
commands::CommandSource,
http::serve,
lua::{self, events::register_functions, player::Player},
lua::{self, player::Player},
};
use azalea::{prelude::*, protocol::packets::game::ClientboundGamePacket};
use hyper::{server::conn::http1, service::service_fn};
use hyper_util::rt::TokioIo;
use log::{debug, error, info, trace};
use mlua::{Function, IntoLuaMulti};
use mlua::IntoLuaMulti;
use tokio::net::TcpListener;
#[allow(clippy::too_many_lines)]
pub async fn handle_event(client: Client, event: Event, state: State) -> anyhow::Result<()> {
state.lua.gc_stop();
let globals = state.lua.globals();
match event {
Event::AddPlayer(player_info) => {
call_listeners(&state, "add_player", Player::from(player_info)).await;
@ -26,7 +23,7 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> anyhow:
let formatted_message = message.message();
info!("{}", formatted_message.to_ansi());
let owners = globals.get::<Vec<String>>("Owners")?;
let owners = state.lua.globals().get::<Vec<String>>("Owners")?;
if message.is_whisper()
&& let (Some(sender), content) = message.split_sender_and_content()
&& owners.contains(&sender)
@ -69,31 +66,38 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> anyhow:
Event::UpdatePlayer(player_info) => {
call_listeners(&state, "update_player", Player::from(player_info)).await;
}
Event::Packet(packet) => {
if let ClientboundGamePacket::SetPassengers(packet) = packet.as_ref() {
Event::Packet(packet) => match packet.as_ref() {
ClientboundGamePacket::SetPassengers(packet) => {
let table = state.lua.create_table()?;
table.set("vehicle", packet.vehicle)?;
table.set("passengers", &*packet.passengers)?;
call_listeners(&state, "set_passengers", table).await;
}
ClientboundGamePacket::SetHealth(packet) => {
let table = state.lua.create_table()?;
table.set("food", packet.food)?;
table.set("health", packet.health)?;
table.set("saturation", packet.saturation)?;
call_listeners(&state, "set_health", table).await;
}
_ => (),
},
Event::Init => {
debug!("client initialized");
debug!("received initialize event");
let globals = state.lua.globals();
globals.set(
"client",
lua::client::Client {
inner: Some(client),
},
)?;
register_functions(&state.lua, &globals, state.clone()).await?;
if let Ok(on_init) = globals.get::<Function>("on_init")
&& let Err(error) = on_init.call::<()>(())
{
error!("failed to call lua on_init function: {error:?}");
}
call_listeners(&state, "init", ()).await;
let Some(address) = state.http_address else {
return Ok(());
};
if let Some(address) = state.http_address {
let listener = TcpListener::bind(address).await.map_err(|error| {
error!("failed to listen on {address}: {error:?}");
error
@ -120,7 +124,6 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> anyhow:
});
}
}
}
_ => (),
}
@ -128,10 +131,10 @@ pub async fn handle_event(client: Client, event: Event, state: State) -> anyhow:
}
async fn call_listeners<T: Clone + IntoLuaMulti>(state: &State, event_type: &str, data: T) {
if let Some(listeners) = state.event_listeners.lock().await.get(event_type) {
for (_, listener) in listeners {
if let Err(error) = listener.call_async::<()>(data.clone()).await {
error!("failed to call lua event listener for {event_type}: {error:?}");
if let Some(listeners) = state.event_listeners.read().await.get(event_type) {
for (id, callback) in listeners {
if let Err(error) = callback.call_async::<()>(data.clone()).await {
error!("failed to call lua event listener {id} for {event_type}: {error:?}");
}
}
}

View File

@ -1,10 +1,12 @@
use super::{Client, Container, ContainerRef, ItemStack, Vec3};
use azalea::{
BlockPos, inventory::Inventory, prelude::ContainerClientExt,
BlockPos,
inventory::{Inventory, Menu, Player, SlotList},
prelude::ContainerClientExt,
protocol::packets::game::ServerboundSetCarriedItem,
};
use log::error;
use mlua::{Lua, Result, UserDataRef};
use mlua::{Lua, Result, Table, UserDataRef};
pub fn container(_lua: &Lua, client: &Client) -> Result<Option<ContainerRef>> {
Ok(client
@ -13,15 +15,46 @@ pub fn container(_lua: &Lua, client: &Client) -> Result<Option<ContainerRef>> {
}
pub fn held_item(_lua: &Lua, client: &Client) -> Result<ItemStack> {
Ok(ItemStack {
inner: client.component::<Inventory>().held_item(),
})
Ok(ItemStack::from(client.component::<Inventory>().held_item()))
}
pub fn held_slot(_lua: &Lua, client: &Client) -> Result<u8> {
Ok(client.component::<Inventory>().selected_hotbar_slot)
}
pub fn menu(lua: &Lua, client: &Client) -> Result<Table> {
fn from_slot_list<const N: usize>(s: SlotList<N>) -> Vec<ItemStack> {
s.iter()
.map(|i| ItemStack::from(i.to_owned()))
.collect::<Vec<_>>()
}
let table = lua.create_table()?;
match client.menu() {
Menu::Player(Player {
craft_result,
craft,
armor,
inventory,
offhand,
}) => {
table.set("type", 0)?;
table.set("craft_result", ItemStack::from(craft_result))?;
table.set("craft", from_slot_list(craft))?;
table.set("armor", from_slot_list(armor))?;
table.set("inventory", from_slot_list(inventory))?;
table.set("offhand", ItemStack::from(offhand))?;
}
Menu::Generic9x6 { contents, player } => {
table.set("type", 6)?;
table.set("contents", from_slot_list(contents))?;
table.set("player", from_slot_list(player))?;
}
_ => (),
}
Ok(table)
}
pub async fn open_container_at(
_lua: Lua,
client: UserDataRef<Client>,

View File

@ -49,6 +49,7 @@ impl UserData for Client {
f.add_field_method_get("held_slot", container::held_slot);
f.add_field_method_get("hunger", state::hunger);
f.add_field_method_get("looking_at", movement::looking_at);
f.add_field_method_get("menu", container::menu);
f.add_field_method_get("pathfinder", movement::pathfinder);
f.add_field_method_get("position", movement::position);
f.add_field_method_get("score", state::score);

View File

@ -15,7 +15,7 @@ use mlua::{FromLua, Lua, Result, Table, UserDataRef, Value};
pub fn direction(_lua: &Lua, client: &Client) -> Result<Direction> {
let d = client.direction();
Ok(Direction { x: d.0, y: d.1 })
Ok(Direction { y: d.0, x: d.1 })
}
pub fn eye_position(_lua: &Lua, client: &Client) -> Result<Vec3> {

View File

@ -5,6 +5,12 @@ pub struct ItemStack {
pub inner: azalea::inventory::ItemStack,
}
impl From<azalea::inventory::ItemStack> for ItemStack {
fn from(inner: azalea::inventory::ItemStack) -> Self {
Self { inner }
}
}
impl UserData for ItemStack {
fn add_fields<F: UserDataFields<Self>>(f: &mut F) {
f.add_field_method_get("is_empty", |_, this| Ok(this.inner.is_empty()));
@ -38,9 +44,7 @@ impl UserData for ItemStack {
fn add_methods<M: UserDataMethods<Self>>(m: &mut M) {
m.add_method_mut("split", |_, this, count: u32| {
Ok(ItemStack {
inner: this.inner.split(count),
})
Ok(ItemStack::from(this.inner.split(count)))
});
m.add_method_mut("update_empty", |_, this, (): ()| {
this.inner.update_empty();

View File

@ -25,7 +25,7 @@ impl UserData for Container {
f.add_field_method_get("contents", |_, this| {
Ok(this.inner.contents().map(|v| {
v.iter()
.map(|i| ItemStack { inner: i.clone() })
.map(|i| ItemStack::from(i.to_owned()))
.collect::<Vec<_>>()
}))
});
@ -58,7 +58,7 @@ impl UserData for ContainerRef {
f.add_field_method_get("contents", |_, this| {
Ok(this.inner.contents().map(|v| {
v.iter()
.map(|i| ItemStack { inner: i.clone() })
.map(|i| ItemStack::from(i.to_owned()))
.collect::<Vec<_>>()
}))
});

View File

@ -3,15 +3,15 @@ use mlua::{FromLua, IntoLua, Lua, Result, Value};
#[derive(Clone)]
pub struct Direction {
pub x: f32,
pub y: f32,
pub x: f32,
}
impl From<&LookDirection> for Direction {
fn from(d: &LookDirection) -> Self {
Self {
x: d.x_rot,
y: d.y_rot,
x: d.x_rot,
}
}
}
@ -19,8 +19,8 @@ impl From<&LookDirection> for Direction {
impl IntoLua for Direction {
fn into_lua(self, lua: &Lua) -> Result<Value> {
let table = lua.create_table()?;
table.set("x", self.x)?;
table.set("y", self.y)?;
table.set("x", self.x)?;
Ok(Value::Table(table))
}
}
@ -28,12 +28,12 @@ impl IntoLua for Direction {
impl FromLua for Direction {
fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
if let Value::Table(table) = value {
Ok(if let (Ok(x), Ok(y)) = (table.get(1), table.get(2)) {
Self { x, y }
Ok(if let (Ok(y), Ok(x)) = (table.get(1), table.get(2)) {
Self { y, x }
} else {
Self {
x: table.get("x")?,
y: table.get("y")?,
x: table.get("x")?,
}
})
} else {

View File

@ -1,47 +1,53 @@
use crate::State;
use crate::ListenerMap;
use futures::executor::block_on;
use mlua::{Function, Lua, Result, Table};
use std::time::{SystemTime, UNIX_EPOCH};
pub async fn register_functions(lua: &Lua, globals: &Table, state: State) -> Result<()> {
let l = state.event_listeners.clone();
pub fn register_functions(lua: &Lua, globals: &Table, event_listeners: ListenerMap) -> Result<()> {
let m = event_listeners.clone();
globals.set(
"add_listener",
lua.create_function(
move |_, (event_type, callback, id): (String, Function, Option<String>)| {
let mut l = block_on(l.lock());
l.entry(event_type).or_default().push((
id.unwrap_or(callback.info().name.unwrap_or(format!(
move |_, (event_type, callback, optional_id): (String, Function, Option<String>)| {
let m = m.clone();
let id = optional_id.unwrap_or_else(|| {
callback.info().name.unwrap_or(format!(
"anonymous @ {}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis()
))),
callback,
));
))
});
tokio::spawn(async move {
m.write()
.await
.entry(event_type)
.or_default()
.push((id, callback));
});
Ok(())
},
)?,
)?;
let l = state.event_listeners.clone();
let m = event_listeners.clone();
globals.set(
"remove_listener",
lua.create_function(move |_, (event_type, target_id): (String, String)| {
let mut l = block_on(l.lock());
let empty = if let Some(listeners) = l.get_mut(&event_type) {
let m = m.clone();
tokio::spawn(async move {
let mut m = m.write().await;
let empty = if let Some(listeners) = m.get_mut(&event_type) {
listeners.retain(|(id, _)| target_id != *id);
listeners.is_empty()
} else {
false
};
if empty {
l.remove(&event_type);
m.remove(&event_type);
}
});
Ok(())
})?,
)?;
@ -49,10 +55,10 @@ pub async fn register_functions(lua: &Lua, globals: &Table, state: State) -> Res
globals.set(
"get_listeners",
lua.create_function(move |lua, (): ()| {
let l = block_on(state.event_listeners.lock());
let m = block_on(event_listeners.read());
let listeners = lua.create_table()?;
for (event_type, callbacks) in l.iter() {
for (event_type, callbacks) in m.iter() {
let type_listeners = lua.create_table()?;
for (id, callback) in callbacks {
let listener = lua.create_table()?;

View File

@ -8,7 +8,9 @@ pub mod player;
pub mod system;
pub mod vec3;
use crate::ListenerMap;
use mlua::{Lua, Table};
use std::{io, time::Duration};
#[derive(Debug)]
#[allow(dead_code)]
@ -18,19 +20,24 @@ pub enum Error {
ExecChunk(mlua::Error),
LoadChunk(mlua::Error),
MissingPath(mlua::Error),
ReadFile(std::io::Error),
ReadFile(io::Error),
}
pub fn register_functions(lua: &Lua, globals: &Table) -> mlua::Result<()> {
pub fn register_functions(
lua: &Lua,
globals: &Table,
event_listeners: ListenerMap,
) -> mlua::Result<()> {
globals.set(
"sleep",
lua.create_async_function(async |_, duration: u64| {
tokio::time::sleep(std::time::Duration::from_millis(duration)).await;
tokio::time::sleep(Duration::from_millis(duration)).await;
Ok(())
})?,
)?;
block::register_functions(lua, globals)?;
events::register_functions(lua, globals, event_listeners)?;
logging::register_functions(lua, globals)?;
system::register_functions(lua, globals)
}

View File

@ -48,12 +48,12 @@ pub fn register_functions(lua: &Lua, globals: &Table) -> Result<()> {
.args(args.unwrap_or_default().iter())
.output()
{
Ok(o) => {
let output = lua.create_table()?;
output.set("status", o.status.code())?;
output.set("stdout", o.stdout)?;
output.set("stderr", o.stderr)?;
Some(output)
Ok(output) => {
let table = lua.create_table()?;
table.set("status", output.status.code())?;
table.set("stdout", lua.create_string(output.stdout)?)?;
table.set("stderr", lua.create_string(output.stderr)?)?;
Some(table)
}
Err(error) => {
error!("failed to run system command: {error:?}");

View File

@ -16,8 +16,8 @@ use bevy_log::{
};
use clap::Parser;
use commands::{CommandSource, register};
use events::handle_event;
use futures::lock::Mutex;
use futures_locks::RwLock;
use mlua::{Function, Lua};
use std::{
collections::HashMap,
@ -30,12 +30,12 @@ use std::{
const DEFAULT_SCRIPT_PATH: &str = "errornowatcher.lua";
type ListenerMap = HashMap<String, Vec<(String, Function)>>;
type ListenerMap = Arc<RwLock<HashMap<String, Vec<(String, Function)>>>>;
#[derive(Default, Clone, Component)]
pub struct State {
lua: Lua,
event_listeners: Arc<Mutex<ListenerMap>>,
event_listeners: ListenerMap,
commands: Arc<CommandDispatcher<Mutex<CommandSource>>>,
http_address: Option<SocketAddr>,
}
@ -43,13 +43,14 @@ pub struct State {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = arguments::Arguments::parse();
let script_path = args.script.unwrap_or(PathBuf::from(DEFAULT_SCRIPT_PATH));
let event_listeners = Arc::new(RwLock::new(HashMap::new()));
let lua = Lua::new();
let globals = lua.globals();
globals.set("script_path", &*script_path)?;
lua::register_functions(&lua, &globals)?;
lua::register_functions(&lua, &globals, event_listeners.clone())?;
lua.load(
read_to_string(script_path)
.expect(&(DEFAULT_SCRIPT_PATH.to_owned() + " should be in current directory")),
@ -65,8 +66,7 @@ async fn main() -> anyhow::Result<()> {
let mut commands = CommandDispatcher::new();
register(&mut commands);
let Err(error) = ClientBuilder::new_without_plugins()
.add_plugins(DefaultPlugins.set(LogPlugin {
let log_plugin = LogPlugin {
custom_layer: |_| {
env::var("LOG_FILE").ok().map(|log_file| {
layer()
@ -75,18 +75,20 @@ async fn main() -> anyhow::Result<()> {
.append(true)
.create(true)
.open(log_file)
.expect("should have been able to open log file"),
.expect("log file should be accessible"),
)
.boxed()
})
},
..Default::default()
}))
};
let Err(error) = ClientBuilder::new_without_plugins()
.add_plugins(DefaultPlugins.set(log_plugin))
.add_plugins(DefaultBotPlugins)
.set_handler(handle_event)
.set_handler(events::handle_event)
.set_state(State {
lua,
event_listeners: Arc::new(Mutex::new(HashMap::new())),
event_listeners,
commands: Arc::new(commands),
http_address: args.http_address,
})