Skip to content

Commit 6127c07

Browse files
committed
Now works a little bit more, still broken af
1 parent e78f426 commit 6127c07

File tree

8 files changed

+97
-65
lines changed

8 files changed

+97
-65
lines changed

src/bin/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ async-trait = { workspace = true }
3535
clap = { workspace = true, features = ["derive"] }
3636
flate2 = { workspace = true }
3737
ctor = { workspace = true }
38-
log = "0.4.22"
38+
rand = { workspace = true }
3939

4040

4141
[[bin]]

src/bin/src/systems/chunk_fetcher.rs

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use ferrumc_core::chunks::chunk_receiver::ChunkSendState::{Fetching, Sending};
66
use ferrumc_state::GlobalState;
77
use ferrumc_world::chunk_format::Chunk;
88
use ferrumc_world::vanilla_chunk_format::BlockData;
9-
use std::collections::{BTreeMap, HashMap};
9+
use std::collections::HashMap;
1010
use std::sync::atomic::AtomicBool;
1111
use std::sync::Arc;
1212
use tokio::task::JoinSet;
@@ -16,6 +16,22 @@ pub struct ChunkFetcher {
1616
stop: AtomicBool,
1717
}
1818

19+
fn generate_chunk(x: i32, z: i32) -> Chunk {
20+
let mut new_chunk = Chunk::new(x, z, "overworld".to_string());
21+
for y in 0..10 {
22+
new_chunk
23+
.set_section(
24+
y,
25+
BlockData {
26+
name: "minecraft:stone".to_string(),
27+
properties: None,
28+
},
29+
)
30+
.unwrap()
31+
}
32+
new_chunk
33+
}
34+
1935
impl ChunkFetcher {
2036
pub(crate) fn new() -> Self {
2137
Self {
@@ -61,24 +77,14 @@ impl System for ChunkFetcher {
6177
state.world.load_chunk(key.0, key.1, &key.2.clone()).await?
6278
} else {
6379
debug!("Chunk not found, creating new chunk");
64-
let mut new_chunk = Chunk::new(key.0, key.1, key.2.clone());
65-
for section in 0..8 {
66-
new_chunk.set_section(
67-
section,
68-
BlockData {
69-
name: "minecraft:grass_block".to_string(),
70-
properties: Some(BTreeMap::from([(
71-
"snowy".to_string(),
72-
"false".to_string(),
73-
)])),
74-
},
75-
)?;
76-
}
80+
let new_chunk = generate_chunk(key.0, key.1);
81+
7782
state.world.save_chunk(new_chunk.clone()).await?;
7883
new_chunk
7984
};
8085
*chunk = Some(fetched_chunk);
8186
}
87+
state.world.sync().await?;
8288
// Insert the fetched chunks back into the component
8389
{
8490
let Ok(mut chunk_recv) = state.universe.get_mut::<ChunkReceiver>(eid)

src/bin/src/systems/chunk_sender.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
1515
use std::sync::Arc;
1616
use std::time::Duration;
1717
use tokio::task::JoinSet;
18-
use tracing::{debug, error, info, trace};
18+
use tracing::{error, info, trace};
1919

2020
pub(super) struct ChunkSenderSystem {
2121
pub stop: AtomicBool,
@@ -74,11 +74,10 @@ impl System for ChunkSenderSystem {
7474
.get_mut::<ChunkReceiver>(eid)
7575
.expect("ChunkReceiver not found");
7676
trace!("Got chunk_recv 3 for sender");
77-
for (key, chunk) in chunk_recv.needed_chunks.iter_mut() {
77+
for (_key, chunk) in chunk_recv.needed_chunks.iter_mut() {
7878
if let Sending(confirmed_chunk) = chunk {
7979
match ChunkAndLightData::from_chunk(&confirmed_chunk.clone()) {
8080
Ok(packet) => {
81-
debug!("Queuing chunk for sending");
8281
packets.push(packet);
8382
}
8483
Err(e) => {

src/lib/core/src/chunks/chunk_receiver.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,15 @@ impl ChunkReceiver {
4646
}
4747
}
4848
}
49+
50+
pub fn queue_from_chunk(&mut self, chunk: Chunk) {
51+
let key = (chunk.x, chunk.z, chunk.dimension.clone());
52+
53+
if self.can_see.contains(&key) {
54+
self.needed_chunks
55+
.insert(key, ChunkSendState::Sending(chunk));
56+
}
57+
}
4958
}
5059

5160
impl ChunkReceiver {

src/lib/net/src/packets/incoming/place_block.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ impl IncomingPacket for PlaceBlock {
102102
},
103103
)?;
104104
state.world.save_chunk(chunk).await?;
105+
state.world.sync().await?;
105106
let q = state.universe.query::<&mut ChunkReceiver>();
106107
for (_, mut chunk_recv) in q {
107108
chunk_recv.queue_chunk_resend(x >> 4, z >> 4, "overworld".to_string());

src/lib/net/src/packets/incoming/player_action.rs

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use crate::connection::StreamWriter;
22
use crate::packets::outgoing::block_change_ack::BlockChangeAck;
3+
use crate::packets::outgoing::chunk_and_light_data::ChunkAndLightData;
34
use crate::packets::IncomingPacket;
45
use crate::NetResult;
5-
use ferrumc_core::chunks::chunk_receiver::ChunkReceiver;
66
use ferrumc_macros::{packet, NetDecode};
77
use ferrumc_net_codec::encode::NetEncodeOpts;
88
use ferrumc_net_codec::net_types::network_position::NetworkPosition;
@@ -34,36 +34,40 @@ impl IncomingPacket for PlayerAction {
3434
let block =
3535
chunk.get_block(self.location.x, self.location.y as i32, self.location.z)?;
3636
debug!("Block: {:?}", block);
37-
chunk.set_block(
38-
self.location.x,
37+
let (relative_x, relative_y, relative_z) = (
38+
self.location.x & 0xF,
3939
self.location.y as i32,
40-
self.location.z,
41-
BlockData::default(),
42-
)?;
43-
state.world.save_chunk(chunk).await?;
40+
self.location.z & 0xF,
41+
);
42+
chunk.set_block(relative_x, relative_y, relative_z, BlockData::default())?;
43+
// debug!(chunk = ?chunk, "Chunk after block placement");
44+
state.world.save_chunk(chunk.clone()).await?;
45+
state.world.sync().await?;
4446
{
45-
let packet = BlockChangeAck {
47+
let ack_packet = BlockChangeAck {
4648
sequence: self.sequence,
4749
};
4850
if let Ok(mut conn) = state.universe.get_mut::<StreamWriter>(conn_id) {
49-
conn.send_packet(packet, &NetEncodeOpts::WithLength)?;
51+
let chunk_packet = ChunkAndLightData::from_chunk(&chunk)?;
52+
conn.send_packet(chunk_packet, &NetEncodeOpts::WithLength)?;
53+
conn.send_packet(ack_packet, &NetEncodeOpts::WithLength)?;
5054
} else {
5155
debug!(
5256
"Player disconnected before we could send the BlockChangeAck packet"
5357
);
5458
}
5559
}
56-
{
57-
let q = state.universe.query::<&mut ChunkReceiver>();
58-
for (_, mut chunk_receiver) in q {
59-
debug!("Queueing chunk resend");
60-
chunk_receiver.queue_chunk_resend(
61-
self.location.x >> 4,
62-
self.location.z >> 4,
63-
"overworld".to_string(),
64-
);
65-
}
66-
}
60+
// {
61+
// let q = state.universe.query::<&mut ChunkReceiver>();
62+
// for (_, mut chunk_receiver) in q {
63+
// debug!("Queueing chunk resend");
64+
// chunk_receiver.queue_chunk_resend(
65+
// self.location.x >> 4,
66+
// self.location.z >> 4,
67+
// "overworld".to_string(),
68+
// );
69+
// }
70+
// }
6771
}
6872
1 => {
6973
debug!("You shouldn't be seeing this in creative mode.");

src/lib/net/src/packets/outgoing/chunk_and_light_data.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use ferrumc_net_codec::net_types::var_int::VarInt;
77
use ferrumc_world::chunk_format::{Chunk, Heightmaps, PaletteType};
88
use std::io::{Cursor, Write};
99
use std::ops::Not;
10-
use tracing::{debug, warn};
10+
use tracing::warn;
1111

1212
const SECTIONS: usize = 24; // Number of sections, adjust for your Y range (-64 to 319)
1313

@@ -64,7 +64,6 @@ impl ChunkAndLightData {
6464
}
6565

6666
pub fn from_chunk(chunk: &Chunk) -> Result<Self, NetError> {
67-
debug!("Serializing chunk at {}, {}", chunk.x, chunk.z);
6867
let mut raw_data = Cursor::new(Vec::new());
6968
let mut sky_light_data = Vec::new();
7069
let mut block_light_data = Vec::new();

src/lib/world/src/chunk_format.rs

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use std::cmp::max;
1212
use std::collections::hash_map::Entry;
1313
use std::collections::HashMap;
1414
use std::io::Read;
15-
use tracing::{debug, error, warn};
15+
use tracing::{error, warn};
1616
use vanilla_chunk_format::BlockData;
1717

1818
#[cfg(test)]
@@ -41,7 +41,7 @@ lazy_static! {
4141
ID2BLOCK.iter().map(|(k, v)| (v.clone(), *k)).collect();
4242
}
4343

44-
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq)]
44+
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq, Debug)]
4545
// This is a placeholder for the actual chunk format
4646
pub struct Chunk {
4747
pub x: i32,
@@ -51,7 +51,7 @@ pub struct Chunk {
5151
pub heightmaps: Heightmaps,
5252
}
5353

54-
#[derive(Encode, Decode, NBTDeserialize, NBTSerialize, Clone, DeepSizeOf)]
54+
#[derive(Encode, Decode, NBTDeserialize, NBTSerialize, Clone, DeepSizeOf, Debug)]
5555
#[nbt(net_encode)]
5656
#[derive(Eq, PartialEq)]
5757
pub struct Heightmaps {
@@ -60,22 +60,22 @@ pub struct Heightmaps {
6060
#[nbt(rename = "WORLD_SURFACE")]
6161
pub world_surface: Vec<i64>,
6262
}
63-
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq)]
63+
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq, Debug)]
6464
pub struct Section {
6565
pub y: i8,
6666
pub block_states: BlockStates,
6767
pub biome_states: BiomeStates,
6868
pub block_light: Vec<u8>,
6969
pub sky_light: Vec<u8>,
7070
}
71-
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq)]
71+
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq, Debug)]
7272
pub struct BlockStates {
7373
pub non_air_blocks: u16,
7474
pub block_data: PaletteType,
7575
pub block_counts: HashMap<BlockData, i32>,
7676
}
7777

78-
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq)]
78+
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq, Debug)]
7979
pub enum PaletteType {
8080
Single(VarInt),
8181
Indirect {
@@ -89,7 +89,7 @@ pub enum PaletteType {
8989
},
9090
}
9191

92-
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq)]
92+
#[derive(Encode, Decode, Clone, DeepSizeOf, Eq, PartialEq, Debug)]
9393
pub struct BiomeStates {
9494
pub bits_per_biome: u8,
9595
pub data: Vec<i64>,
@@ -384,7 +384,7 @@ impl Chunk {
384384
// Get old block
385385
let old_block = self.get_block(x, y, z)?;
386386
if old_block == block {
387-
debug!("Block is the same as the old block");
387+
// debug!("Block is the same as the old block");
388388
return Ok(());
389389
}
390390
// Get section
@@ -393,25 +393,39 @@ impl Chunk {
393393
.iter_mut()
394394
.find(|section| section.y == (y >> 4) as i8)
395395
.ok_or(WorldError::SectionOutOfBounds(y >> 4))?;
396+
397+
let mut converted = false;
398+
let mut new_contents = PaletteType::Indirect {
399+
bits_per_block: 4,
400+
data: vec![],
401+
palette: vec![],
402+
};
403+
404+
if let PaletteType::Single(val) = &section.block_states.block_data {
405+
new_contents = PaletteType::Indirect {
406+
bits_per_block: 4,
407+
data: vec![0; 255],
408+
palette: vec![val.clone()],
409+
};
410+
converted = true;
411+
}
412+
413+
if converted {
414+
section.block_states.block_data = new_contents;
415+
}
416+
396417
// Do different things based on the palette type
397418
match &mut section.block_states.block_data {
398-
PaletteType::Single(val) => {
399-
debug!("Converting single block to indirect palette");
400-
// If it's a single block, convert it to indirect then re-run the function
401-
section.block_states.block_data = PaletteType::Indirect {
402-
bits_per_block: 4,
403-
data: vec![0; 256],
404-
palette: vec![val.clone()],
405-
};
406-
self.set_block(x, y, z, block)?;
419+
PaletteType::Single(_val) => {
420+
panic!("Single palette type should have been converted to indirect palette type");
407421
}
408422
PaletteType::Indirect {
409423
bits_per_block,
410424
data,
411425
palette,
412426
} => {
413-
let block_counts = &mut section.block_states.block_counts;
414-
match block_counts.entry(old_block.clone()) {
427+
// debug!("Indirect mode");
428+
match section.block_states.block_counts.entry(old_block.clone()) {
415429
Entry::Occupied(mut occ_entry) => {
416430
let count = occ_entry.get_mut();
417431
if *count <= 0 {
@@ -431,9 +445,13 @@ impl Chunk {
431445
if let Some(e) = section.block_states.block_counts.get(&block) {
432446
section.block_states.block_counts.insert(block, e + 1);
433447
} else {
434-
debug!("Adding block to block counts");
448+
// debug!("Adding block to block counts");
435449
section.block_states.block_counts.insert(block, 1);
436450
}
451+
// let required_bits = max((palette.len() as f32).log2().ceil() as u8, 4);
452+
// if *bits_per_block != required_bits {
453+
// section.block_states.resize(required_bits as usize)?;
454+
// }
437455
// Get block index
438456
let block_palette_index = palette
439457
.iter()
@@ -546,11 +564,7 @@ impl Chunk {
546564
y: y as i8,
547565
block_states: BlockStates {
548566
non_air_blocks: 0,
549-
block_data: PaletteType::Indirect {
550-
bits_per_block: 4,
551-
data: vec![0; 256],
552-
palette: vec![VarInt::from(0)],
553-
},
567+
block_data: PaletteType::Single(VarInt::from(0)),
554568
block_counts: HashMap::from([(BlockData::default(), 4096)]),
555569
},
556570
biome_states: BiomeStates {

0 commit comments

Comments
 (0)