Skip to content

Commit

Permalink
feat: add meta to flecs components
Browse files Browse the repository at this point in the history
- also manually register components
  • Loading branch information
andrewgazelka committed Nov 1, 2024
1 parent ac986ff commit 9b30f14
Show file tree
Hide file tree
Showing 12 changed files with 137 additions and 26 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ default-features = false
version = '1.0.30'

[workspace.dependencies.flecs_ecs]
features = ["flecs_manual_registration"]
git = 'https://github.com/Indra-db/Flecs-Rust'

[workspace.dependencies.hyperion]
Expand Down
2 changes: 2 additions & 0 deletions crates/hyperion-permission/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ pub fn parse_perms_command(input: &str) -> IResult<&str, Command<'_>> {

impl Module for PermissionModule {
fn module(world: &World) {
world.component::<Group>();
world.component::<storage::PermissionStorage>();
cmd_with(world, "perms", |scope| {
scope.literal_with("set", |scope| {
scope.argument_with(
Expand Down
1 change: 1 addition & 0 deletions crates/hyperion/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ fastrand.workspace = true
flecs_ecs.workspace = true
heapless.workspace = true
heed.workspace = true
hex.workspace = true
hyperion-crafting.workspace = true
hyperion-event-macros.workspace = true
hyperion-inventory.workspace = true
Expand Down
4 changes: 2 additions & 2 deletions crates/hyperion/src/egress/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ impl Module for EgressModule {
stream.push(io.inner());

let position = hyperion_proto::ChunkPosition {
x: i16::try_from(pos.0.x).unwrap(),
z: i16::try_from(pos.0.y).unwrap(),
x: i16::try_from(pos.position.x).unwrap(),
z: i16::try_from(pos.position.y).unwrap(),
};

positions.push(position);
Expand Down
9 changes: 6 additions & 3 deletions crates/hyperion/src/egress/sync_chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::{
};

#[derive(Component, Deref, DerefMut, Default)]
#[meta]
pub struct ChunkSendQueue {
changes: Vec<IVec2>,
}
Expand All @@ -30,7 +31,9 @@ pub struct SyncChunksModule;

impl Module for SyncChunksModule {
fn module(world: &World) {
world.component::<ChunkSendQueue>();
meta_register_vector_type!(world, IVec2 { x: 0, y: 0 });

world.component::<ChunkSendQueue>().meta();

let radius = world.get::<&Config>(|config| config.view_distance);
let liberal_radius = radius + 2;
Expand All @@ -54,7 +57,7 @@ impl Module for SyncChunksModule {
move |entity, (compose, last_sent, pose, &stream_id, chunk_changes)| {
let world = entity.world();

let last_sent_chunk = last_sent.0;
let last_sent_chunk = last_sent.position;

let current_chunk = pose.to_chunk();

Expand All @@ -76,7 +79,7 @@ impl Module for SyncChunksModule {
return;
}

last_sent.0 = current_chunk;
last_sent.position = current_chunk;

let last_sent_range_x = (last_sent_chunk.x - radius)..(last_sent_chunk.x + radius);
let last_sent_range_z = (last_sent_chunk.y - radius)..(last_sent_chunk.y + radius);
Expand Down
8 changes: 7 additions & 1 deletion crates/hyperion/src/ingress/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,11 @@ fn process_login(

ign_map.insert(username.clone(), entity.id(), world);

// first 4 bytes of the uuid
let uuid_short = hex::encode(&uuid.as_bytes()[0..4]);

let name = format!("{username}-{uuid_short}");

entity
.set(InGameName::from(username))
.add::<AiTargetable>()
Expand All @@ -173,7 +178,8 @@ fn process_login(
.set(Health::default())
.set(ChunkSendQueue::default())
.set(ChunkPosition::null())
.set(EntityReaction::default());
.set(EntityReaction::default())
.set_name(&name);

compose.io_buf().set_receive_broadcasts(stream_id, world);

Expand Down
49 changes: 39 additions & 10 deletions crates/hyperion/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use derive_more::{Deref, DerefMut};
use egress::EgressModule;
use flecs_ecs::prelude::*;
pub use glam;
use glam::IVec2;
use ingress::IngressModule;
#[cfg(unix)]
use libc::{getrlimit, setrlimit, RLIMIT_NOFILE};
Expand Down Expand Up @@ -77,7 +78,9 @@ pub use valence_ident;

pub use crate::simulation::command::CommandScope;
use crate::{
simulation::{EntitySize, IgnMap, Player},
ingress::PendingRemove,
net::{proxy::ReceiveState, NetworkStreamRef, PacketDecoder},
simulation::{EgressComm, EntitySize, IgnMap, PacketState, Player},
util::mojang::ApiProvider,
};

Expand Down Expand Up @@ -192,7 +195,7 @@ impl Hyperion {
let world = World::new();

let world = Box::new(world);
let world = Box::leak(world);
let world: &World = Box::leak(world);

let mut app = world.app();

Expand All @@ -208,27 +211,45 @@ impl Hyperion {
.next()
.context("could not get first address")?;

component!(world, IVec2 { x: i32, y: i32 });
world.component::<PendingRemove>();

world.component::<Yaw>();
component!(world, Yaw).opaque_func(meta_ser_stringify_type_display::<Yaw>);

world.component::<Pitch>();
component!(world, Pitch).opaque_func(meta_ser_stringify_type_display::<Pitch>);

world.component::<PacketDecoder>();

world.component::<PacketState>();

world.component::<NetworkStreamRef>();
world.component::<ReceiveState>();
world.component::<Compose>();
world.component::<CraftingRegistry>();

world.component::<LocalDb>();
world.component::<SkinHandler>();
world.component::<MojangClient>();
world.component::<Events>();

world.component::<Comms>();
world.component::<EgressComm>();
world.component::<Blocks>();
world.component::<AsyncRuntime>();
world.component::<StreamLookup>();
world.component::<EntitySize>();
world.component::<IgnMap>();

world.set(IgnMap::default());

world
.component::<Player>()
.add_trait::<(flecs::With, EntitySize)>()
.add_trait::<(flecs::With, Yaw)>()
.add_trait::<(flecs::With, Pitch)>();
world.component::<config::Config>();

info!("starting hyperion");
let config = config::Config::load("run/config.toml")?;
world.set(config);

let runtime = AsyncRuntime::default();

world.component::<GlobalEventHandlers>();
world.set(GlobalEventHandlers::default());

info!("initializing database");
Expand Down Expand Up @@ -277,6 +298,14 @@ impl Hyperion {
world.import::<EgressModule>();
world.import::<IngressModule>();

world
.component::<Player>()
.add_trait::<(flecs::With, EntitySize)>()
.add_trait::<(flecs::With, Yaw)>()
.add_trait::<(flecs::With, Pitch)>();

world.set(IgnMap::default());

handlers(world);

app.run();
Expand Down
74 changes: 64 additions & 10 deletions crates/hyperion/src/simulation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use skin::PlayerSkin;
use uuid;

use crate::{storage::ThreadLocalVec, Global};
use crate::{simulation::command::Command, storage::ThreadLocalVec, Global};

pub mod animation;
pub mod blocks;
Expand Down Expand Up @@ -116,7 +116,9 @@ impl<K: Eq + Hash, V> DeferredMap<K, V> {
}

/// The in-game name of a player.
/// todo: fix the meta
#[derive(Component, Deref, From, Display, Debug)]
#[meta]
pub struct InGameName(Arc<str>);

#[derive(Component, Deref, DerefMut, From, Debug, Default)]
Expand Down Expand Up @@ -156,6 +158,7 @@ pub enum PacketState {
/// This method restores the entity to full health and allows it to be affected
/// by subsequent health changes.
#[derive(Component, Debug, PartialEq)]
#[meta]
pub struct Health {
value: f32,

Expand Down Expand Up @@ -272,6 +275,7 @@ impl Default for Health {

#[derive(Component, Debug, Eq, PartialEq, Default)]
#[expect(missing_docs)]
#[meta]
pub struct ImmuneStatus {
/// The tick until the player is immune to player attacks.
pub until: i64,
Expand Down Expand Up @@ -339,6 +343,7 @@ pub struct AiTargetable;
DerefMut,
From
)]
#[meta]
pub struct Position {
/// The (x, y, z) position of the entity.
/// Note we are using [`Vec3`] instead of [`glam::DVec3`] because *cache locality* is important.
Expand All @@ -351,6 +356,20 @@ pub struct Yaw {
yaw: f16,
}

impl Display for Yaw {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let yaw = self.yaw as f32;
write!(f, "{yaw}")
}
}

impl Display for Pitch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let pitch = self.pitch as f32;
write!(f, "{pitch}")
}
}

#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Default)]
pub struct Pitch {
pitch: f16,
Expand All @@ -359,12 +378,21 @@ pub struct Pitch {
const PLAYER_WIDTH: f16 = 0.6;
const PLAYER_HEIGHT: f16 = 1.8;

#[derive(Component, Copy, Clone)]
#[derive(Component, Copy, Clone, Debug)]
#[meta]
pub struct EntitySize {
pub half_width: f16,
pub height: f16,
}

impl Display for EntitySize {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let half_width = self.half_width as f32;
let height = self.height as f32;
write!(f, "{half_width}x{height}")
}
}

impl Default for EntitySize {
fn default() -> Self {
Self {
Expand All @@ -383,8 +411,10 @@ impl Position {
}

#[derive(Component, Debug, Copy, Clone)]
#[expect(missing_docs)]
pub struct ChunkPosition(pub IVec2);
#[meta]
pub struct ChunkPosition {
pub position: IVec2,
}

const SANE_MAX_RADIUS: i32 = 128;

Expand All @@ -393,7 +423,9 @@ impl ChunkPosition {
#[expect(missing_docs)]
pub const fn null() -> Self {
// todo: huh
Self(IVec2::new(SANE_MAX_RADIUS, SANE_MAX_RADIUS))
Self {
position: IVec2::new(SANE_MAX_RADIUS, SANE_MAX_RADIUS),
}
}
}

Expand Down Expand Up @@ -441,6 +473,7 @@ impl Position {
/// - Therefore, we have an [`EntityReaction`] component which is used to store the reaction of an entity to collisions.
/// - Later we can apply the reaction to the entity's [`Position`] to move the entity.
#[derive(Component, Default, Debug)]
#[meta]
pub struct EntityReaction {
/// The velocity of the entity.
pub velocity: Vec3,
Expand All @@ -451,15 +484,36 @@ pub struct SimModule;

impl Module for SimModule {
fn module(world: &World) {
world.component::<Position>();
world.component::<PlayerSkin>();
world.component::<Command>();

component!(world, EntitySize).opaque_func(meta_ser_stringify_type_display::<EntitySize>);
component!(world, IVec3 {
x: i32,
y: i32,
z: i32
});
component!(world, Vec3 {
x: f32,
y: f32,
z: f32
});

component!(world, IgnMap);

world.component::<Position>().meta();

world.component::<Player>();

world.component::<InGameName>();
component!(world, InGameName).opaque_func(meta_ser_stringify_type_display::<InGameName>);

world.component::<AiTargetable>();
world.component::<ImmuneStatus>();
world.component::<ImmuneStatus>().meta();
world.component::<Uuid>();
world.component::<Health>();
world.component::<ChunkPosition>();
world.component::<EntityReaction>();
world.component::<Health>().meta();
world.component::<ChunkPosition>().meta();
world.component::<EntityReaction>().meta();
world.component::<Play>();
world.component::<ConfirmBlockSequences>();
world.component::<metadata::Metadata>();
Expand Down
9 changes: 9 additions & 0 deletions events/proof-of-concept/src/module/attack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,20 @@ use tracing::trace_span;
pub struct AttackModule;

#[derive(Component, Default, Copy, Clone, Debug)]
#[meta]
pub struct ImmuneUntil {
tick: i64,
}

#[derive(Component, Default, Copy, Clone, Debug)]
#[meta]
pub struct Armor {
pub armor: f32,
}

// Used as a component only for commands, does not include armor or weapons
#[derive(Component, Default, Copy, Clone, Debug)]
#[meta]
pub struct CombatStats {
pub armor: f32,
pub armor_toughness: f32,
Expand All @@ -61,13 +64,19 @@ pub struct CombatStats {
}

#[derive(Component, Default, Copy, Clone, Debug)]
#[meta]
pub struct KillCount {
pub kill_count: u32,
}

impl Module for AttackModule {
#[allow(clippy::excessive_nesting)]
fn module(world: &World) {
world.component::<ImmuneUntil>().meta();
world.component::<Armor>().meta();
world.component::<CombatStats>().meta();
world.component::<KillCount>().meta();

world
.component::<Player>()
.add_trait::<(flecs::With, ImmuneUntil)>()
Expand Down
Loading

0 comments on commit 9b30f14

Please sign in to comment.