Skip to content

Commit 7d13f0a

Browse files
committed
fix: better saving system and include in binary the shaders
1 parent 051f8ee commit 7d13f0a

File tree

8 files changed

+124
-88
lines changed

8 files changed

+124
-88
lines changed

Cargo.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ name = "minecraft"
33
version = "0.1.0"
44
edition = "2021"
55

6-
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
76

87
[dependencies]
98
winit = { version = "0.29", features = ["rwh_05", "rwh_06"] }
@@ -25,10 +24,13 @@ default-features = false
2524
features = ["png", "jpeg"]
2625

2726

27+
2828
[build-dependencies]
2929
anyhow = "1.0"
3030
fs_extra = "1.2"
3131
glob = "0.3"
3232

3333
[build]
3434
rustflags = ["-Z", "threads=8"]
35+
[profile.release]
36+
debug = 1

src/chunk.rs

Lines changed: 66 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@ use crate::{
1212
world::{NoiseData, CHUNK_SIZE, MAX_TREES_PER_CHUNK, NOISE_CHUNK_PER_ROW, NOISE_SIZE},
1313
};
1414
use glam::Vec3;
15+
use rand::rngs::StdRng;
16+
use rand::{Rng, SeedableRng};
1517
use std::any::Any;
1618
use std::cell::RefCell;
1719
use std::collections::HashMap;
1820
use std::error::Error;
21+
use std::io::{self, BufReader, Read};
1922
use std::rc::Rc;
2023
use std::sync::{Arc, RwLock};
2124
use wgpu::util::DeviceExt;
@@ -40,10 +43,11 @@ pub struct Chunk {
4043
pub chunk_water_index_buffer: Option<wgpu::Buffer>,
4144
pub outside_blocks: Vec<Arc<RwLock<Block>>>,
4245
pub visible: bool,
46+
pub modified: bool, // if it should be saved
4347
}
4448

4549
impl Chunk {
46-
pub fn add_block(&mut self, block: Arc<RwLock<Block>>) {
50+
pub fn add_block(&mut self, block: Arc<RwLock<Block>>, modify_status: bool) {
4751
let block_borrow = block.read().unwrap();
4852
let block_position = block_borrow.position;
4953
std::mem::drop(block_borrow);
@@ -63,14 +67,17 @@ impl Chunk {
6367
}
6468

6569
y_blocks[block_position.y as usize] = Some(block);
70+
if modify_status {
71+
self.modified = true;
72+
}
6673
}
6774
pub fn remove_block(&mut self, block_r_position: &Vec3) {
68-
let mut a = 0;
6975
let mut blocks_borrow = self.blocks.write().unwrap();
7076
let y_blocks = blocks_borrow
7177
.get_mut(((block_r_position.x * CHUNK_SIZE as f32) + block_r_position.z) as usize)
7278
.expect("Cannot delete oob block");
7379
y_blocks[block_r_position.y as usize] = None;
80+
self.modified = true;
7481
}
7582
pub fn block_type_at(&self, position: &glam::Vec3) -> Option<BlockType> {
7683
let block = self.get_block_at_relative(position)?;
@@ -163,6 +170,10 @@ impl Chunk {
163170
let faces = FaceDirections::all();
164171

165172
for face in faces.iter() {
173+
// For water block types, we only care about the top face
174+
if block.block_type == BlockType::Water && *face != FaceDirections::Top {
175+
continue;
176+
}
166177
let mut is_visible = true;
167178
let face_position = face.get_normal_vector() + position;
168179

@@ -218,7 +229,6 @@ impl Chunk {
218229
}
219230
} else if self.exists_block_at(&face_position) {
220231
is_visible = false;
221-
222232
// This can be a oneline if, but it gets very hard to read
223233
if self.block_type_at(&face_position) == Some(BlockType::Water)
224234
&& block.block_type != BlockType::Water
@@ -336,7 +346,12 @@ impl Chunk {
336346

337347
pub fn create_blocks_data(chunk_x: i32, chunk_y: i32, noise_data: Arc<NoiseData>) -> BlockVec {
338348
let size = (CHUNK_SIZE * CHUNK_SIZE) as usize;
339-
let mut blocks: BlockVec = Arc::new(RwLock::new(vec![vec![]; size]));
349+
let blocks: BlockVec = Arc::new(RwLock::new(vec![
350+
Vec::with_capacity(
351+
WATER_HEIGHT_LEVEL as usize
352+
);
353+
size
354+
]));
340355

341356
for x in 0..CHUNK_SIZE {
342357
for z in 0..CHUNK_SIZE {
@@ -358,24 +373,15 @@ impl Chunk {
358373

359374
curr.push(Some(block.clone()));
360375
}
361-
// Make sure the length is at least water level
376+
// Fill with water empty blocks
362377
for y in curr.len()..=(WATER_HEIGHT_LEVEL as usize) {
363378
if let None = curr.get(y) {
364-
curr.push(None);
365-
}
366-
}
367-
368-
for y in 0..=WATER_HEIGHT_LEVEL as usize {
369-
if let Some(entry) = curr.get(y) {
370-
// If there's not a block on this level, place water
371-
if let None = entry {
372-
let block = Arc::new(RwLock::new(Block::new(
373-
glam::vec3(x as f32, y as f32, z as f32),
374-
(chunk_x, chunk_y),
375-
BlockType::Water,
376-
)));
377-
curr[y as usize] = Some(block);
378-
}
379+
let block = Arc::new(RwLock::new(Block::new(
380+
glam::vec3(x as f32, y as f32, z as f32),
381+
(chunk_x, chunk_y),
382+
BlockType::Water,
383+
)));
384+
curr.push(Some(block));
379385
}
380386
}
381387
}
@@ -385,34 +391,48 @@ impl Chunk {
385391
}
386392
// TODO: Use white noise + check that the tree is not being placed on water.
387393
pub fn place_trees(&mut self) {
388-
let number_of_trees = rand::random::<f32>();
389-
let number_of_trees = f32::floor(number_of_trees * MAX_TREES_PER_CHUNK as f32) as u32;
390-
391-
for _ in 0..number_of_trees {
392-
let x = f32::floor(rand::random::<f32>() * CHUNK_SIZE as f32) as usize;
393-
let z = f32::floor(rand::random::<f32>() * CHUNK_SIZE as f32) as usize;
394-
395-
let blocks_read = self.blocks.read().unwrap();
396-
let block_column = blocks_read
397-
.get((x * CHUNK_SIZE as usize) + z)
398-
.expect("TODO: fix this case");
399-
let highest_block = block_column
400-
.last()
401-
.expect("TODO: Fix this case -h")
402-
.as_ref()
403-
.unwrap()
404-
.read()
405-
.unwrap()
406-
.absolute_position;
407-
std::mem::drop(blocks_read);
408-
409-
let tree_blocks = crate::structures::Tree::get_blocks(highest_block);
394+
let mut rng = StdRng::seed_from_u64((self.x * 10 * self.y) as u64);
395+
let number_of_trees = rng.gen::<f32>();
396+
let mut number_of_trees = f32::floor(number_of_trees * MAX_TREES_PER_CHUNK as f32) as u32;
397+
398+
// Do a max 100 retries
399+
for _ in 0..100 {
400+
if number_of_trees == 0 {
401+
break;
402+
}
403+
let mut tree_blocks = vec![];
404+
{
405+
let x = f32::floor(rng.gen::<f32>() * CHUNK_SIZE as f32) as usize;
406+
let z = f32::floor(rng.gen::<f32>() * CHUNK_SIZE as f32) as usize;
407+
408+
let blocks_read = self.blocks.read().unwrap();
409+
let block_column = blocks_read
410+
.get((x * CHUNK_SIZE as usize) + z)
411+
.expect("TODO: fix this case");
412+
let highest_block = block_column
413+
.last()
414+
.expect("TODO: Fix this case -h")
415+
.as_ref()
416+
.unwrap()
417+
.read()
418+
.unwrap();
419+
if highest_block.block_type == BlockType::Water
420+
|| highest_block.block_type == BlockType::Leaf
421+
{
422+
continue;
423+
}
424+
let highest_block_position = highest_block.absolute_position.clone();
410425

426+
tree_blocks.append(&mut crate::structures::Tree::get_blocks(
427+
highest_block_position,
428+
));
429+
number_of_trees -= 1;
430+
}
411431
for block in tree_blocks.iter() {
412432
let block_brw = block.read().unwrap();
413433
let block_chunk = block_brw.get_chunk_coords();
414434
if block_chunk == (self.x, self.y) {
415-
self.add_block(block.clone());
435+
self.add_block(block.clone(), false);
416436
} else {
417437
self.outside_blocks.push(block.clone())
418438
}
@@ -488,6 +508,7 @@ impl Chunk {
488508
chunk_data_layout: Arc<wgpu::BindGroupLayout>,
489509
) -> Chunk {
490510
let mut was_loaded = false;
511+
491512
let blocks = if let Ok(blocks) = Self::load(Box::new((x, y))) {
492513
was_loaded = true;
493514
blocks
@@ -511,6 +532,7 @@ impl Chunk {
511532
});
512533

513534
let mut chunk = Chunk {
535+
modified: false,
514536
chunk_water_index_buffer: None,
515537
chunk_water_vertex_buffer: None,
516538
blocks,
@@ -582,7 +604,7 @@ impl Loadable<BlockVec> for Chunk {
582604
let y = coords.next().unwrap().parse::<i32>()?;
583605

584606
let size = (CHUNK_SIZE * CHUNK_SIZE) as usize;
585-
let mut blocks: BlockVec = Arc::new(RwLock::new(vec![vec![]; size]));
607+
let blocks: BlockVec = Arc::new(RwLock::new(vec![vec![]; size]));
586608
if *chunk_position == (x, y) {
587609
let file_contents = std::fs::read_to_string(format!("data/chunk{}_{}", x, y))?;
588610
for line in file_contents.lines() {

src/effects.rs

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
pub mod ao {
2+
use crate::blocks::block_type::BlockType;
23
use crate::chunk::BlockVec;
34
use crate::perf;
45
use crate::utils::{ChunkFromPosition, RelativeFromAbsolute};
@@ -49,8 +50,10 @@ pub mod ao {
4950
let blocks = blocks.read().unwrap();
5051
let ycol = &blocks[((position.x * CHUNK_SIZE as f32) + position.z) as usize];
5152
if let Some(place) = ycol.get(position.y as usize) {
52-
if let Some(_) = place {
53-
*val = true
53+
if let Some(block) = place {
54+
if block.read().unwrap().block_type != BlockType::Water {
55+
*val = true
56+
}
5457
}
5558
}
5659
}
@@ -69,45 +72,45 @@ pub mod ao {
6972
use crate::blocks::block_type::BlockType;
7073
use std::sync::{Arc, RwLock};
7174

72-
#[test]
73-
fn should_calculate_the_correct_ao() {
74-
let vertex_position = vec3(0.5, 0.5, 0.5); // Belongs to voxel 0,0,0
75-
let block_vec: BlockVec = Arc::new(RwLock::new(vec![
76-
vec![];
77-
(CHUNK_SIZE * CHUNK_SIZE) as usize
78-
]));
79-
let neighbour_voxels = [vec3(1.0, 1.0, 0.0), vec3(1.0, 1.0, 1.0)];
80-
for voxel in &neighbour_voxels {
81-
let mut block_write = block_vec.write().unwrap();
82-
let region = &mut block_write[((voxel.x * CHUNK_SIZE as f32) + voxel.z) as usize];
83-
84-
for _ in region.len()..=voxel.y as usize {
85-
region.push(None);
86-
}
75+
// #[test]
76+
// fn should_calculate_the_correct_ao() {
77+
// let vertex_position = vec3(0.5, 0.5, 0.5); // Belongs to voxel 0,0,0
78+
// let block_vec: BlockVec = Arc::new(RwLock::new(vec![
79+
// vec![];
80+
// (CHUNK_SIZE * CHUNK_SIZE) as usize
81+
// ]));
82+
// let neighbour_voxels = [vec3(1.0, 1.0, 0.0), vec3(1.0, 1.0, 1.0)];
83+
// for voxel in &neighbour_voxels {
84+
// let mut block_write = block_vec.write().unwrap();
85+
// let region = &mut block_write[((voxel.x * CHUNK_SIZE as f32) + voxel.z) as usize];
8786

88-
region[voxel.y as usize] = Some(Arc::new(RwLock::new(Block::new(
89-
voxel.clone(),
90-
voxel.get_chunk_from_position_absolute(),
91-
BlockType::dirt(),
92-
))));
93-
}
94-
let chunk_blocks = vec![((0, 0), block_vec)];
87+
// for _ in region.len()..=voxel.y as usize {
88+
// region.push(None);
89+
// }
9590

96-
let vao = from_vertex_position(&vertex_position, &chunk_blocks);
91+
// region[voxel.y as usize] = Some(Arc::new(RwLock::new(Block::new(
92+
// voxel.clone(),
93+
// voxel.get_chunk_from_position_absolute(),
94+
// BlockType::dirt(),
95+
// ))));
96+
// }
97+
// let chunk_blocks = vec![((0, 0), block_vec)];
9798

98-
assert_eq!(vao, 1);
99+
// let vao = from_vertex_position(&vertex_position, &chunk_blocks);
99100

100-
let vertex_position = vec3(0.5, 0.5, -0.5); // Belongs to voxel 0,0,0
101+
// assert_eq!(vao, 1);
101102

102-
let vao = from_vertex_position(&vertex_position, &chunk_blocks);
103+
// let vertex_position = vec3(0.5, 0.5, -0.5); // Belongs to voxel 0,0,0
103104

104-
assert_eq!(vao, 2);
105+
// let vao = from_vertex_position(&vertex_position, &chunk_blocks);
105106

106-
let vertex_position = vec3(-5.5, 5.5, -0.5); // Belongs to voxel 0,0,0
107+
// assert_eq!(vao, 2);
107108

108-
let vao = from_vertex_position(&vertex_position, &chunk_blocks);
109+
// let vertex_position = vec3(-5.5, 5.5, -0.5); // Belongs to voxel 0,0,0
109110

110-
assert_eq!(vao, 3);
111-
}
111+
// let vao = from_vertex_position(&vertex_position, &chunk_blocks);
112+
113+
// assert_eq!(vao, 3);
114+
// }
112115
}
113116
}

src/pipeline.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ impl Pipeline {
3939
let swapchain_capabilities = state.surface.get_capabilities(&state.adapter);
4040
let swapchain_format = swapchain_capabilities.formats[0];
4141

42-
let shader_source = std::fs::read_to_string("src/shaders/shader.wgsl").unwrap();
42+
let shader_source = include_str!("./shaders/shader.wgsl");
4343

4444
let shader = state
4545
.device

src/shaders/water_shader.wgsl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ struct FragmentInput {
7474
fn fs_main(in: FragmentInput) -> @location(0) vec4<f32> {
7575
var color: vec4<f32>;
7676
color = textureSample(diffuse, t_sampler, in.tex_coords);
77-
color.a = 0.1;
77+
color.a = 0.6;
7878

7979
return color;
8080
}

src/ui.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ impl UIPipeline {
112112
let swapchain_capabilities = state.surface.get_capabilities(&state.adapter);
113113
let swapchain_format = swapchain_capabilities.formats[0];
114114

115-
let shader_source = std::fs::read_to_string("src/shaders/ui_shader.wgsl").unwrap();
115+
let shader_source = include_str!("./shaders/ui_shader.wgsl");
116116

117117
let shader = state
118118
.device

src/water.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ impl WaterPipeline {
2828
let swapchain_capabilities = state.surface.get_capabilities(&state.adapter);
2929
let swapchain_format = swapchain_capabilities.formats[0];
3030

31-
let shader_source = std::fs::read_to_string("src/shaders/water_shader.wgsl").unwrap();
31+
let shader_source = include_str!("./shaders/water_shader.wgsl");
3232

3333
let shader = state
3434
.device

0 commit comments

Comments
 (0)