Skip to content

Commit

Permalink
refactor: accumulate
Browse files Browse the repository at this point in the history
  • Loading branch information
Liyze09 committed Oct 4, 2024
1 parent 835f998 commit 7f6d0ff
Show file tree
Hide file tree
Showing 27 changed files with 228 additions and 185 deletions.
5 changes: 4 additions & 1 deletion Cargo.lock

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

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ lto = "fat"
spotlight = { path = "crates/spotlight", version = "0.0.1" }
tokio = { version = "1.40.0", features = ["full"] }
bytes = "1.7.2"
dashmap = "6.1.0"
dashmap = { version = "6.1.0", features = ["inline"] }
serde = "1.0.210"
serde_json = "1.0.128"
serde_derive = "1.0.210"
Expand All @@ -26,7 +26,6 @@ fastrand = "2.1.1"
nohash-hasher = "0.2.0"
mimalloc = "0.1.43"
rayon = "1.10.0"
once_cell = "1.20.1"
parking_lot = "0.12.3"
sha2 = "0.10.8"
toml = "0.8.19"
Expand Down
11 changes: 4 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
# Spot

<div align="center">

![CI](https://github.com/SpotMC/Spot/actions/workflows/build.yml/badge.svg)
[![License: LGPL](https://img.shields.io/badge/License-LGPL--2.1-red.svg)](https://opensource.org/license/lgpl-2-1)
![Current version)](https://img.shields.io/badge/Working_On-1.21.1-yellow)

</div>
![CI](https://github.com/SpotMC/Spot/actions/workflows/build.yml/badge.svg)

## About

Expand All @@ -18,11 +14,12 @@ Built on top of the **Rayon and Tokio** without any code from Mojang.
## Our Goals
- **High Performance**: Times faster than official implement.
- **Vanilla-Like**: Support as many as possible vanilla feathers, support vanilla client and load vanilla world.
- **Vanilla-Like**: Support as many as possible vanilla feathers, support vanilla clients and load vanilla worlds.
- **Extensibility**: Load plugins which are written in Rust and provide full toolchain for development.

## Things We WON'T do
- Support plugins for other server implement.

- Support plugins for another server implement.

## Contributing

Expand Down
17 changes: 9 additions & 8 deletions crates/kernel/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ use crate::world::dimension::Dimension;
use dashmap::DashMap;
use downcast_rs::{impl_downcast, DowncastSync};
use hashbrown::HashMap;
use once_cell::sync::Lazy;
use serde::de::DeserializeOwned;
use std::sync::Arc;
use std::sync::LazyLock;

pub trait Block: Send + Sync + DowncastSync {
fn when_block_update(
Expand Down Expand Up @@ -53,11 +53,12 @@ pub trait BlockState: Send + Sync + DowncastSync {
}
impl_downcast!(sync BlockState);

pub(crate) static BLOCKS_BY_ID: Lazy<DashMap<u32, Box<dyn Block>>> = Lazy::new(DashMap::new);
pub(crate) static BLOCKS_BY_NAME: Lazy<DashMap<String, u32>> = Lazy::new(DashMap::new);
pub(crate) static BLOCK_STATES_BY_ID: Lazy<DashMap<u32, Arc<(dyn BlockState)>>> =
Lazy::new(DashMap::new);
pub(crate) static BLOCK_ITEM_BY_ID: Lazy<DashMap<u32, u32>> = Lazy::new(DashMap::new);
pub(crate) static BLOCKS_BY_ID: LazyLock<DashMap<u32, Box<dyn Block>>> =
LazyLock::new(DashMap::new);
pub(crate) static BLOCKS_BY_NAME: LazyLock<DashMap<String, u32>> = LazyLock::new(DashMap::new);
pub(crate) static BLOCK_STATES_BY_ID: LazyLock<DashMap<u32, Arc<(dyn BlockState)>>> =
LazyLock::new(DashMap::new);
pub(crate) static BLOCK_ITEM_BY_ID: LazyLock<DashMap<u32, u32>> = LazyLock::new(DashMap::new);

pub fn register_block(id: &str, block: Box<dyn Block + 'static>) {
block.get_block_states().into_iter().for_each(|(k, v)| {
Expand All @@ -79,8 +80,8 @@ impl BlockBuilder {
id: &str,
block_settings: BlockSettings,
) -> BlockBuilder {
let protocol_id = get_protocol_id("minecraft:block", &id).unwrap();
let (block_states, default_state) = get_block_states::<T>(&id);
let protocol_id = get_protocol_id("minecraft:block", id).unwrap();
let (block_states, default_state) = get_block_states::<T>(id);
BlockBuilder {
protocol_id,
default_state,
Expand Down
21 changes: 11 additions & 10 deletions crates/kernel/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use once_cell::sync::Lazy;
use sha2::{Digest, Sha256};
use std::sync::LazyLock;
use toml::{toml, Value};

static TOML: Lazy<Value> = Lazy::new(|| {
static TOML: LazyLock<Value> = LazyLock::new(|| {
if let Ok(file) = std::fs::read_to_string("./config.toml") {
toml::from_str(&file).unwrap()
} else {
Expand All @@ -17,19 +17,20 @@ static TOML: Lazy<Value> = Lazy::new(|| {
toml
}
});
pub static PORT: Lazy<i32> = Lazy::new(|| TOML.get("port").unwrap().as_integer().unwrap() as i32);
pub static MAX_PLAYERS: Lazy<i32> =
Lazy::new(|| TOML.get("max-players").unwrap().as_integer().unwrap() as i32);
pub static VIEW_DISTANCE: Lazy<i32> =
Lazy::new(|| TOML.get("view-distance").unwrap().as_integer().unwrap() as i32);
pub static SIMULATION_DISTANCE: Lazy<i32> = Lazy::new(|| {
pub static PORT: LazyLock<i32> =
LazyLock::new(|| TOML.get("port").unwrap().as_integer().unwrap() as i32);
pub static MAX_PLAYERS: LazyLock<i32> =
LazyLock::new(|| TOML.get("max-players").unwrap().as_integer().unwrap() as i32);
pub static VIEW_DISTANCE: LazyLock<i32> =
LazyLock::new(|| TOML.get("view-distance").unwrap().as_integer().unwrap() as i32);
pub static SIMULATION_DISTANCE: LazyLock<i32> = LazyLock::new(|| {
TOML.get("simulation-distance")
.unwrap()
.as_integer()
.unwrap() as i32
});
pub static SEED: Lazy<i64> = Lazy::new(|| TOML.get("seed").unwrap().as_integer().unwrap());
pub static HASHED_SEED: Lazy<i64> = Lazy::new(|| {
pub static SEED: LazyLock<i64> = LazyLock::new(|| TOML.get("seed").unwrap().as_integer().unwrap());
pub static HASHED_SEED: LazyLock<i64> = LazyLock::new(|| {
let mut sha = Sha256::new();
sha.update(SEED.to_be_bytes());
let hash_result = sha.finalize();
Expand Down
28 changes: 12 additions & 16 deletions crates/kernel/src/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,21 @@ pub trait Entity: Send + Sync + DowncastSync {
}

fn get_dimension(&mut self) -> Arc<Dimension> {
unsafe {
WORLD
.read()
.dimensions
.get(self.get_data().dimension)
.unwrap()
.clone()
}
WORLD
.read()
.dimensions
.get(self.get_data().dimension)
.unwrap()
.clone()
}

fn set_dimension(&mut self, dimension: &str) {
unsafe {
self.get_data_mut().dimension = WORLD
.read()
.dimensions
.iter()
.position(|d| d.dimension_name == dimension)
.unwrap();
}
self.get_data_mut().dimension = WORLD
.read()
.dimensions
.iter()
.position(|d| d.dimension_name == dimension)
.unwrap();
}

fn get_eid(&self) -> i32 {
Expand Down
63 changes: 58 additions & 5 deletions crates/kernel/src/item.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
pub mod dirt_item;
pub mod grass_block_item;
pub mod stone_item;

use crate::block::BLOCK_ITEM_BY_ID;
use crate::registry::protocol_id::get_protocol_id;
use dashmap::DashMap;
use downcast_rs::{impl_downcast, DowncastSync};
use once_cell::sync::Lazy;
use std::sync::LazyLock;

pub(crate) static ITEMS_BY_ID: Lazy<DashMap<u32, Box<dyn Item>>> = Lazy::new(DashMap::new);
pub(crate) static ITEMS_BY_NAME: Lazy<DashMap<String, u32>> = Lazy::new(DashMap::new);
pub(crate) static ITEMS_BY_ID: LazyLock<DashMap<u32, Box<dyn Item>>> = LazyLock::new(DashMap::new);
pub(crate) static ITEMS_BY_NAME: LazyLock<DashMap<String, u32>> = LazyLock::new(DashMap::new);
pub fn register_item(id: &str, item: Box<dyn Item + 'static>) {
let protocol_id = item.get_item_id();
ITEMS_BY_NAME.insert(id.to_string(), protocol_id);
ITEMS_BY_ID.insert(protocol_id, item);
}
pub fn register_block_item(id: &str, item: Box<dyn Item + 'static>, block: u32) {
pub fn register_block_item(id: &str, block: u32, item: Box<dyn Item + 'static>) {
let protocol_id = item.get_item_id();
BLOCK_ITEM_BY_ID.insert(block, protocol_id);
ITEMS_BY_NAME.insert(id.to_string(), protocol_id);
Expand All @@ -26,7 +30,7 @@ pub trait Item: Send + Sync + DowncastSync {
impl_downcast!(sync Item);

pub trait BlockItem: Item {
fn get_block() -> u32;
fn get_block(&self) -> u32;
}

pub struct ItemBuilder {
Expand Down Expand Up @@ -76,3 +80,52 @@ impl Default for ItemSettings {
Self::new()
}
}

#[macro_export]
macro_rules! item_def {
($name:tt, $id:expr, $settings:expr) => {
pub struct $name {
builder: ItemBuilder,
}
impl Item for $name {
fn get_builder(&self) -> &ItemBuilder {
&self.builder
}
}
impl $name {
pub fn new() -> $name {
$name {
builder: ItemBuilder::new($id, $settings),
}
}
}
};
}

#[macro_export]
macro_rules! block_item_def {
($name:tt, $id:expr, $settings:expr) => {
pub struct $name {
builder: ItemBuilder,
block_id: u32,
}
impl Item for $name {
fn get_builder(&self) -> &ItemBuilder {
&self.builder
}
}
impl $name {
pub fn new(block_id: u32) -> $name {
$name {
builder: ItemBuilder::new($id, $settings),
block_id,
}
}
}
impl BlockItem for $name {
fn get_block(&self) -> u32 {
self.block_id
}
}
};
}
5 changes: 5 additions & 0 deletions crates/kernel/src/item/dirt_item.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use crate::block::dirt::DIRT;
use crate::block_item_def;
use crate::item::*;

block_item_def!(DirtItem, DIRT, ItemSettings::new());
5 changes: 5 additions & 0 deletions crates/kernel/src/item/grass_block_item.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use crate::block::grass_block::GRASS_BLOCK;
use crate::block_item_def;
use crate::item::*;

block_item_def!(GrassBlockItem, GRASS_BLOCK, ItemSettings::new());
5 changes: 5 additions & 0 deletions crates/kernel/src/item/stone_item.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use crate::block::stone::STONE;
use crate::block_item_def;
use crate::item::*;

block_item_def!(StoneItem, STONE, ItemSettings::new());
18 changes: 9 additions & 9 deletions crates/kernel/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ pub mod block;
pub mod config;
pub mod entity;
pub mod item;
pub mod nbt;
pub(crate) mod network;
pub mod registry;
mod test;
Expand All @@ -18,14 +17,15 @@ use crate::registry::{
};
use mimalloc::MiMalloc;
use network::connection::read_socket;
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use static_files::Resource;
use std::collections::HashMap;
use std::io::Error;
use std::net::SocketAddr;
use std::sync::LazyLock;
use tokio::io::{stdin, AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::block_in_place;
use tokio::time::MissedTickBehavior::Skip;
use tracing::{debug, info, instrument, trace};
use tracing_subscriber::fmt;
Expand All @@ -35,11 +35,11 @@ use tracing_subscriber::fmt::format;
static ALLOCATOR: MiMalloc = MiMalloc;

pub const PROTOCOL_VERSION: i32 = 767;
pub const MINECRAFT_VERSION: &str = "1.21";
pub const MINECRAFT_VERSION: &str = "1.21"; // 1.21 - 1.21.1 ( Protocol 767 )
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
//noinspection RsUnresolvedPath
pub static GENERATED: Lazy<HashMap<&'static str, Resource>> = Lazy::new(generate);
pub static mut WORLD: Lazy<RwLock<world::World>> = Lazy::new(|| RwLock::from(world::World::new()));
pub static GENERATED: LazyLock<HashMap<&'static str, Resource>> = LazyLock::new(generate);
pub static WORLD: LazyLock<RwLock<world::World>> =
LazyLock::new(|| RwLock::from(world::World::new()));
#[tokio::main]
#[instrument]
async fn main() {
Expand Down Expand Up @@ -77,17 +77,17 @@ async fn main() {
"Loaded {:?} painting variants.",
PAINTING_VARIANTS_INDEX.len()
);
register_vanilla();
tokio::spawn(async move {
let mut interval = tokio::time::interval(std::time::Duration::from_millis(50));
interval.set_missed_tick_behavior(Skip);
loop {
unsafe {
block_in_place(|| {
WORLD.write().tick();
}
});
interval.tick().await;
}
});
register_vanilla();
tokio::spawn(async move {
info!("Network thread started.");
info!("Time elapsed {:?} ns", time.elapsed().as_nanos());
Expand Down
2 changes: 0 additions & 2 deletions crates/kernel/src/network/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ pub(crate) async fn read_socket(socket: &mut TcpStream) -> Result<(), Error> {
let mut connection = Connection::new(socket);
loop {
let packet = connection.read_packet().await?;
yield_now().await;
match connection.state {
Handshake => {
let mut data: Pin<&mut Box<&[u8]>> = pin!(Box::new(&*packet.data));
Expand Down Expand Up @@ -74,7 +73,6 @@ pub(crate) async fn read_socket(socket: &mut TcpStream) -> Result<(), Error> {
if let Some(recv) = &mut connection.recv {
while let Ok(update) = &recv.try_recv() {
// TODO
yield_now().await;
}
}
}
Expand Down
Loading

0 comments on commit 7f6d0ff

Please sign in to comment.