Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: packet handling functions #771

Merged
merged 26 commits into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a3b9e38
feat: packet handler registry
andrewgazelka Dec 19, 2024
9e1bd3a
stuck
andrewgazelka Dec 19, 2024
88bd398
Use unsafe transmutes to fix HandlerRegistry
james-j-obrien Dec 19, 2024
a119418
Free leaked boxes
james-j-obrien Dec 19, 2024
f7f8b01
Clean-up drop handling
james-j-obrien Dec 19, 2024
38f59bb
Fix typo
james-j-obrien Dec 19, 2024
3ea1fc2
Fix string literal
james-j-obrien Dec 19, 2024
59a7258
Fix more typos
james-j-obrien Dec 19, 2024
5d8f3e4
Move process packet logic into deserializer
james-j-obrien Dec 19, 2024
8bf6f81
Remove compiler error reports
james-j-obrien Dec 19, 2024
227c115
change a lil
andrewgazelka Dec 20, 2024
f362e11
add lifetime utils
TestingPlant Dec 29, 2024
6e4a20d
get registry working
TestingPlant Dec 29, 2024
1fab615
convert code to use RegistryHandler
TestingPlant Dec 31, 2024
fe00a24
reimplement RuntimeLifetime
TestingPlant Jan 1, 2025
b3cd7f5
set up LifetimeTracker
TestingPlant Jan 8, 2025
56ef103
re-add events
TestingPlant Jan 8, 2025
bf96ecc
remove GlobalEventHandlers
TestingPlant Jan 9, 2025
78fd0a3
remove ReducedLifetime
TestingPlant Jan 9, 2025
8a46ace
prohibit lifetimes stored in events
TestingPlant Jan 9, 2025
26b925c
Merge remote-tracking branch 'origin/main' into unsafe-packet-handling
TestingPlant Jan 11, 2025
211f4a0
fix: make packet_switch unsafe
TestingPlant Jan 11, 2025
e21b11a
fix: seal LifetimeHandle::references
TestingPlant Jan 11, 2025
6abeceb
fix: use Relaxed ordering for reference count
TestingPlant Jan 11, 2025
f4dd1cf
docs: clean up comments
TestingPlant Jan 12, 2025
5eb73f2
docs: fix link to PacketSwitchQuery::compose
TestingPlant Jan 12, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ members = [
'crates/hyperion-item',
'crates/hyperion-minecraft-proto',
'crates/hyperion-nerd-font',
'crates/hyperion-packet-macros',
'crates/hyperion-palette',
'crates/hyperion-permission',
'crates/hyperion-proto',
Expand Down Expand Up @@ -182,6 +183,9 @@ path = 'crates/hyperion-item'
[workspace.dependencies.hyperion-nerd-font]
path = 'crates/hyperion-nerd-font'

[workspace.dependencies.hyperion-packet-macros]
path = 'crates/hyperion-packet-macros'

[workspace.dependencies.hyperion-palette]
path = 'crates/hyperion-palette'

Expand Down
4 changes: 2 additions & 2 deletions crates/hyperion-clap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use flecs_ecs::{
use hyperion::{
net::{Compose, ConnectionId, DataBundle, agnostic},
simulation::{IgnMap, command::get_root_command_entity, handlers::PacketSwitchQuery},
storage::{CommandCompletionRequest, EventFn},
storage::CommandCompletionRequest,
};
pub use hyperion_clap_macros::CommandPermission;
pub use hyperion_command;
Expand Down Expand Up @@ -111,7 +111,7 @@ pub trait MinecraftCommand: Parser + CommandPermission {
};
};

let on_tab_complete: EventFn<CommandCompletionRequest<'static>> = Box::new(
let on_tab_complete = Box::new(
|packet_switch_query: &mut PacketSwitchQuery<'_>,
completion: &CommandCompletionRequest<'_>| {
let full_query = completion.query;
Expand Down
1 change: 1 addition & 0 deletions crates/hyperion-command/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ publish = false
[dependencies]
flecs_ecs = { workspace = true }
hyperion = { workspace = true }
hyperion-utils = { workspace = true }
indexmap = { workspace = true }
tracing = { workspace = true }

Expand Down
6 changes: 4 additions & 2 deletions crates/hyperion-command/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ use flecs_ecs::{
macros::Component,
prelude::Module,
};
use hyperion::storage::{CommandCompletionRequest, EventFn};
use hyperion::{simulation::handlers::PacketSwitchQuery, storage::CommandCompletionRequest};
use indexmap::IndexMap;

pub type OnTabComplete =
Box<dyn Fn(&mut PacketSwitchQuery<'_>, &CommandCompletionRequest<'_>) + 'static + Send + Sync>;
pub struct CommandHandler {
pub on_execute: fn(input: &str, system: EntityView<'_>, caller: Entity),
pub on_tab_complete: EventFn<CommandCompletionRequest<'static>>,
pub on_tab_complete: OnTabComplete,
pub has_permissions: fn(world: &World, caller: Entity) -> bool,
}

Expand Down
62 changes: 35 additions & 27 deletions crates/hyperion-command/src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use flecs_ecs::{
};
use hyperion::{
net::agnostic,
simulation::event,
storage::{EventQueue, GlobalEventHandlers},
simulation::{event, handlers::PacketSwitchQuery, packet::HandlerRegistry},
storage::{CommandCompletionRequest, EventQueue},
};
use hyperion_utils::LifetimeHandle;

use crate::component::CommandRegistry;

Expand All @@ -21,14 +22,15 @@ impl Module for CommandSystemModule {
system!(
"execute_command",
world,
&mut EventQueue<event::Command<'_>>($),
&mut EventQueue<event::Command>($),
&CommandRegistry($)
)
.each_iter(|it, _, (event_queue, registry)| {
let system = it.system();

let world = it.world();
for event::Command { raw, by } in event_queue.drain() {
let raw = raw.get();
let Some(first_word) = raw.split_whitespace().next() else {
tracing::warn!("command is empty");
continue;
Expand Down Expand Up @@ -65,30 +67,36 @@ impl Module for CommandSystemModule {
}
});

world.get::<&mut GlobalEventHandlers>(|handlers| {
handlers.completion.register(|query, completion| {
let input = completion.query;

// should be in form "/{command}"
let command = input
.strip_prefix("/")
.unwrap_or(input)
.split_whitespace()
.next()
.unwrap_or("");

if command.is_empty() {
return;
}

query.world.get::<&CommandRegistry>(|registry| {
let Some(cmd) = registry.commands.get(command) else {
return;
};
let on_tab = &cmd.on_tab_complete;
on_tab(query, completion);
});
});
world.get::<&mut HandlerRegistry>(|registry| {
registry.add_handler(Box::new(
|completion: &CommandCompletionRequest<'_>,
_: &dyn LifetimeHandle<'_>,
query: &mut PacketSwitchQuery<'_>| {
let input = completion.query;

// should be in form "/{command}"
let command = input
.strip_prefix("/")
.unwrap_or(input)
.split_whitespace()
.next()
.unwrap_or("");

if command.is_empty() {
return Ok(());
}

query.world.get::<&CommandRegistry>(|registry| {
let Some(cmd) = registry.commands.get(command) else {
return;
};
let on_tab = &cmd.on_tab_complete;
on_tab(query, completion);
});

Ok(())
},
));
});
}
}
68 changes: 14 additions & 54 deletions crates/hyperion-event-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
Lifetime, Token, Type,
Token, Type,
parse::{Parse, ParseStream, Result},
parse_macro_input,
punctuated::Punctuated,
Expand Down Expand Up @@ -40,19 +40,16 @@ impl Parse for EventsInput {
}
}

/// Struct representing a single event type, possibly with a lifetime
/// Struct representing a single event type
struct EventType {
path: syn::Ident,
ty: Type,
lifetime: Option<Lifetime>,
ident: syn::Ident,
}

impl EventType {
/// Extracts necessary components from a `syn::Type`
fn from_type(ty: Type) -> Result<Self> {
let mut lifetime = None;

let Type::Path(type_path) = &ty else {
return Err(syn::Error::new(ty.span(), "expected a path"));
};
Expand All @@ -69,12 +66,14 @@ impl EventType {
let ident = last_segment.ident.clone();
let generics = last_segment.arguments.clone();

// Extract lifetime if present
if let syn::PathArguments::AngleBracketed(args) = &generics {
for generic_arg in &args.args {
if let syn::GenericArgument::Lifetime(l) = generic_arg {
lifetime = Some(l.clone());
break;
return Err(syn::Error::new(
l.span(),
"lifetimes are not allowed in events, consider using \
hyperion_utils::RuntimeLifetime to store references",
));
}
}
}
Expand All @@ -88,12 +87,7 @@ impl EventType {

let path = first_segment.ident.clone();

Ok(Self {
path,
ty,
lifetime,
ident,
})
Ok(Self { path, ty, ident })
}

/// Generates the field definition for the Events struct
Expand Down Expand Up @@ -125,50 +119,16 @@ impl EventType {
let field_name = self.ident.to_string().to_case(Case::Snake);
let field_ident = format_ident!("{field_name}");

if self.lifetime.is_some() {
quote! {
impl Event for #path::#ident<'static> {
fn input(elem: Self, events: &Events, world: &World) {
unsafe {
(*events.#field_ident.0).push(elem, world);
}
}
}

impl sealed::Sealed for #path::#ident<'static> {}

impl ReducedLifetime for #path::#ident<'static> {
type Reduced<'a> = #path::#ident<'a>
where
Self: 'a;

fn reduce<'a>(self) -> Self::Reduced<'a> {
self
quote! {
impl Event for #path::#ident {
fn input(elem: Self, events: &Events, world: &World) {
unsafe {
(*events.#field_ident.0).push(elem, world);
}
}
}
} else {
quote! {
impl Event for #path::#ident {
fn input(elem: Self, events: &Events, world: &World) {
unsafe {
(*events.#field_ident.0).push(elem, world);
}
}
}

impl sealed::Sealed for #path::#ident {}

impl ReducedLifetime for #path::#ident {
type Reduced<'a> = Self
where
Self: 'a;

fn reduce<'a>(self) -> Self::Reduced<'a> {
self
}
}
}
impl sealed::Sealed for #path::#ident {}
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions crates/hyperion-gui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ version.workspace = true
edition.workspace = true

[dependencies]
anyhow = { workspace = true }
flecs_ecs = { workspace = true }
hyperion = { workspace = true }
hyperion-utils = { workspace = true }
serde = { version = "1.0", features = ["derive"] }
valence_protocol = { workspace = true }

Expand Down
Loading
Loading