Compare commits

..

No commits in common. "master" and "feat/simulation" have entirely different histories.

12 changed files with 208 additions and 515 deletions

1
Cargo.lock generated
View File

@ -2084,7 +2084,6 @@ dependencies = [
"bevy-inspector-egui",
"bevy_prototype_debug_lines",
"bevy_rapier2d",
"fastrand",
"lazy_static",
"noise",
]

View File

@ -10,7 +10,6 @@ bevy = { version = "0.9.0", features = ["dynamic"] }
bevy-inspector-egui = "0.14.0"
bevy_prototype_debug_lines = "0.9.0"
bevy_rapier2d = "0.19.0"
fastrand = "1.8.0"
lazy_static = "1.4.0"
noise = "0.8.2"

View File

@ -7,7 +7,10 @@ use crate::{
};
use self::{
camera::GameCameraPlugin, debug::DebugPlugin, kinematic::KinematicPlugin, player::PlayerPlugin,
camera::{GameCameraPlugin, WORLD_WIDTH},
debug::DebugPlugin,
kinematic::KinematicPlugin,
player::PlayerPlugin,
};
pub mod camera;
@ -32,15 +35,15 @@ pub fn init() {
fn setup_window(mut windows: ResMut<Windows>) {
if let Some(window) = windows.get_primary_mut() {
window.set_resolution(1280.0, 720.0);
window.set_resolution(900.0, 450.0);
window.set_title("Kuilu".to_string());
}
}
fn setup_terrain(mut commands: Commands, mut terrain: ResMut<Terrain2D>) {
let terrain_gen = TerrainGen2D::new(432678);
for y in 0..(Terrain2D::WORLD_HEIGHT / Chunk2D::SIZE_Y as i32) {
for x in 0..(Terrain2D::WORLD_WIDTH / Chunk2D::SIZE_X as i32) {
for y in 0..(WORLD_WIDTH / Chunk2D::SIZE_Y as i32) {
for x in 0..(WORLD_WIDTH / Chunk2D::SIZE_X as i32) {
let position = Vector2I { x, y };
terrain.add_chunk(position, terrain_gen.gen_chunk(&position));
}
@ -57,6 +60,6 @@ fn setup_terrain(mut commands: Commands, mut terrain: ResMut<Terrain2D>) {
.spawn(Name::new("Right wall"))
.insert(Collider::halfspace(Vec2::NEG_X).unwrap())
.insert(TransformBundle::from_transform(
Transform::from_translation(Vec3::new(Terrain2D::WORLD_WIDTH as f32, 0.0, 0.0)),
Transform::from_translation(Vec3::new(WORLD_WIDTH as f32, 0.0, 0.0)),
));
}

View File

@ -4,10 +4,9 @@ use bevy::{
};
use bevy_inspector_egui::{Inspectable, RegisterInspectable};
use crate::{
terrain2d::Terrain2D,
util::{move_towards_vec3, vec3_lerp},
};
use crate::util::{move_towards_vec3, vec3_lerp};
pub const WORLD_WIDTH: i32 = 512;
pub struct GameCameraPlugin;
@ -49,7 +48,7 @@ fn camera_setup(mut commands: Commands) {
Name::new("Camera"),
Camera2dBundle {
projection: OrthographicProjection {
scaling_mode: ScalingMode::FixedHorizontal(Terrain2D::WORLD_WIDTH as f32),
scaling_mode: ScalingMode::FixedHorizontal(WORLD_WIDTH as f32),
window_origin: WindowOrigin::Center,
scale: 1.0 / 2.0,
..default()
@ -80,7 +79,7 @@ fn camera_system(
for (mut camera_transform, projection) in camera_query.iter_mut() {
let left_limit = 0.0;
let right_limit = Terrain2D::WORLD_WIDTH as f32;
let right_limit = WORLD_WIDTH as f32;
let offset = Vec3::new(0.0, 0.0, 999.9);
match follow.movement {
FollowMovement::Instant => {

View File

@ -1,7 +1,9 @@
use bevy::prelude::*;
// use bevy_inspector_egui::*;
use bevy_prototype_debug_lines::DebugLinesPlugin;
// use bevy_rapier2d::prelude::*;
pub mod terrain;
mod terrain;
use terrain::TerrainDebugPlugin;
@ -10,8 +12,8 @@ pub struct DebugPlugin;
impl Plugin for DebugPlugin {
fn build(&self, app: &mut App) {
app.add_plugin(DebugLinesPlugin::default())
// .add_plugin(bevy_rapier2d::prelude::RapierDebugRenderPlugin::default())
// .add_plugin(bevy_inspector_egui::WorldInspectorPlugin::new())
// .add_plugin(RapierDebugRenderPlugin::default())
// .add_plugin(WorldInspectorPlugin::new())
.add_plugin(TerrainDebugPlugin);
}
}

View File

@ -1,5 +1,3 @@
use std::collections::HashMap;
use crate::{game::camera::GameCamera, terrain2d::*, util::Vector2I};
use bevy::{input::mouse::MouseWheel, prelude::*, render::camera::RenderTarget};
use bevy_prototype_debug_lines::DebugLines;
@ -9,8 +7,7 @@ pub struct TerrainDebugPlugin;
impl Plugin for TerrainDebugPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(TerrainBrush2D::default())
// .add_system_to_stage(TerrainStages::EventHandler, dirty_rect_visualizer)
// .add_system_to_stage(CoreStage::Last, chunk_debugger)
.add_system_to_stage(TerrainStages::EventHandler, dirty_rect_visualizer)
.add_system(debug_painter);
}
}
@ -23,10 +20,7 @@ struct TerrainBrush2D {
impl Default for TerrainBrush2D {
fn default() -> Self {
TerrainBrush2D {
radius: 40,
tile: 8,
}
TerrainBrush2D { radius: 5, tile: 4 }
}
}
@ -134,7 +128,7 @@ fn debug_painter(
);
if mouse_input.pressed(MouseButton::Left) || mouse_input.pressed(MouseButton::Right)
{
terrain.set_texel(&pos, Texel2D { id, ..default() }, None)
terrain.set_texel(&pos, id, None)
}
}
}
@ -152,69 +146,22 @@ fn dirty_rect_visualizer(terrain: Res<Terrain2D>, mut debug_draw: ResMut<DebugLi
continue;
};
let offset = Vec3::from(chunk_index_to_global(chunk_index));
let min = offset + Vec3::from(rect.min);
let max = offset + Vec3::from(rect.max + Vector2I::ONE);
draw_box(&mut debug_draw, min, max, Color::RED, 0.0);
}
}
let color = Color::RED;
fn chunk_debugger(terrain: Res<Terrain2D>, mut debug_draw: ResMut<DebugLines>) {
for (chunk_index, chunk) in terrain.chunk_iter() {
println!("chunk contents: {chunk_index:?}");
let offset = Vec3::from(chunk_index_to_global(chunk_index));
let min = offset + Vec3::ZERO;
let max = offset + Vec3::from(Chunk2D::SIZE);
draw_box(
&mut debug_draw,
min,
max,
Color::rgba(0.5, 0.0, 0.5, 0.5),
0.0,
);
let mut tile_counter: HashMap<TexelID, (u32, u32)> = HashMap::new();
for y in 0..Chunk2D::SIZE_Y as i32 {
for x in 0..Chunk2D::SIZE_X as i32 {
let local = Vector2I::new(x, y);
let global = local_to_global(&local, chunk_index);
if let (Some(texel), _) = terrain.get_texel_behaviour(&global) {
if !tile_counter.contains_key(&texel.id) {
tile_counter.insert(texel.id, (0, 0));
}
let (old_count, old_density) = tile_counter[&texel.id].clone();
tile_counter.insert(
texel.id,
(old_count + 1, old_density + texel.density as u32),
);
}
}
}
let mut counts: Vec<(u8, String, u32, u32)> = vec![];
for (id, (count, total_density)) in tile_counter.iter() {
let name =
TexelBehaviour2D::from_id(id).map_or("unknown".to_string(), |b| b.name.to_string());
counts.push((*id, name, *count, *total_density));
}
counts.sort_unstable_by_key(|c| c.0);
for (id, name, count, total_density) in counts {
println!(
"\tmaterial: {name:<24}id: {id:<8}count: {count:<8}total_density: {total_density:<8}"
let points = vec![
Vec3::new(rect.min.x as f32, rect.min.y as f32, 0.0),
Vec3::new((rect.max.x + 1) as f32, rect.min.y as f32, 0.0),
Vec3::new((rect.max.x + 1) as f32, (rect.max.y + 1) as f32, 0.0),
Vec3::new(rect.min.x as f32, (rect.max.y + 1) as f32, 0.0),
];
for i in 0..points.len() {
let offset = Vec3::from(chunk_index_to_global(chunk_index));
debug_draw.line_colored(
offset + points[i],
offset + points[(i + 1) % points.len()],
0.0,
color,
);
}
}
}
pub fn draw_box(debug_draw: &mut DebugLines, min: Vec3, max: Vec3, color: Color, duration: f32) {
let points = vec![
Vec3::new(min.x, min.y, min.z),
Vec3::new(max.x, min.y, min.z),
Vec3::new(max.x, max.y, min.z),
Vec3::new(min.x, max.y, min.z),
];
for i in 0..points.len() {
debug_draw.line_colored(points[i], points[(i + 1) % points.len()], duration, color);
}
}

View File

@ -81,6 +81,9 @@ pub fn player_spawn(mut commands: Commands) {
},
..default()
})
.insert(TransformBundle::from_transform(Transform::from_xyz(
256.0, 128.0, 0.0,
)))
.insert(Collider::cuboid(3.0, 6.0))
.insert(PlayerBundle {
kinematic,
@ -91,6 +94,6 @@ pub fn player_spawn(mut commands: Commands) {
.insert(Sleeping::disabled())
.insert(CameraFollow {
priority: 1,
movement: FollowMovement::Instant,
movement: FollowMovement::Smooth(18.0),
});
}

View File

@ -17,7 +17,10 @@ pub use terrain_gen2d::*;
pub use texel2d::*;
pub use texel_behaviour2d::*;
use crate::util::{frame_counter::FrameCounter, math::*, Vector2I};
use crate::{
game::camera::WORLD_WIDTH,
util::{frame_counter::FrameCounter, math::*, Vector2I},
};
pub struct Terrain2DPlugin;
@ -43,10 +46,10 @@ impl Plugin for Terrain2DPlugin {
app.register_type::<TerrainChunk2D>()
.insert_resource(Terrain2D::new(
Some(Terrain2D::WORLD_HEIGHT),
Some(WORLD_WIDTH * 2),
Some(0),
Some(0),
Some(Terrain2D::WORLD_WIDTH),
Some(WORLD_WIDTH),
))
.add_event::<TerrainEvent2D>()
.add_system_to_stage(TerrainStages::Simulation, terrain_simulation)
@ -71,11 +74,7 @@ pub enum TerrainStages {
ChunkSync,
}
fn terrain_simulation(
mut terrain: ResMut<Terrain2D>,
frame_counter: Res<FrameCounter>,
mut debug_draw: ResMut<bevy_prototype_debug_lines::DebugLines>,
) {
fn terrain_simulation(mut terrain: ResMut<Terrain2D>, frame_counter: Res<FrameCounter>) {
let simulation_frame = (frame_counter.frame % u8::MAX as u64) as u8 + 1;
let indices = terrain
@ -105,10 +104,9 @@ fn terrain_simulation(
} else {
continue;
};
// Texel simulation
let mut y_range: Vec<_> = (rect.min.y..rect.max.y + 1).collect();
let mut x_range: Vec<_> = (rect.min.x..rect.max.x + 1).collect();
if frame_counter.frame % 2 == 0 {
y_range.reverse();
}
@ -122,8 +120,8 @@ fn terrain_simulation(
let global = local_to_global(&local, &chunk_index);
if terrain
.get_latest_simulation(&global)
.map_or(true, |frame| frame == simulation_frame)
.get_texel(&global)
.map_or(true, |t| t.last_simulation == simulation_frame)
{
continue;
};
@ -131,172 +129,6 @@ fn terrain_simulation(
simulate_texel(global, &mut terrain, &frame_counter);
}
}
// Gas dispersion
let alternate_dispersion = frame_counter.frame % 2 == 0;
let alternate = if alternate_dispersion { 1 } else { 0 };
let y_range =
((rect.min.y - alternate)..rect.max.y + 1 + alternate).collect::<Vec<_>>();
let x_range =
((rect.min.x - alternate)..rect.max.x + 1 + alternate).collect::<Vec<_>>();
const DISPERSION_WIDTH: usize = 2;
const DISPERSION_HEIGHT: usize = 2;
for y_arr in y_range.chunks(DISPERSION_HEIGHT) {
for x_arr in x_range.chunks(DISPERSION_WIDTH) {
let mut global_positions = vec![];
for y in y_arr.iter() {
for x in x_arr.iter() {
let local = Vector2I::new(*x, *y);
let global = local_to_global(&local, &chunk_index);
global_positions.push(global);
}
}
// Distribute gas
disperse_gas(
global_positions,
&mut terrain,
&frame_counter,
&mut debug_draw,
)
}
}
}
}
}
// TODO: Don't update if the result of dispersion is similar to before
fn disperse_gas(
global_positions: Vec<Vector2I>,
terrain: &mut Terrain2D,
frame_counter: &FrameCounter,
debug_draw: &mut bevy_prototype_debug_lines::DebugLines,
) {
use u32 as Capacity;
use u8 as Min;
use u8 as Max;
let mut total_densities: HashMap<TexelID, (Capacity, Min, Max)> = HashMap::new();
let mut valid_globals = vec![];
for global in global_positions.iter() {
let (texel, behaviour) = terrain.get_texel_behaviour(global);
if behaviour.clone().map_or(true, |b| b.form == TexelForm::Gas) {
valid_globals.push(*global);
}
match (texel, behaviour) {
(Some(texel), Some(behaviour)) => {
if behaviour.form == TexelForm::Gas {
if let Some((old_density, old_min, old_max)) = total_densities.get(&texel.id) {
total_densities.insert(
texel.id,
(
texel.density as u32 + *old_density,
texel.density.min(*old_min),
texel.density.max(*old_max),
),
);
} else {
total_densities.insert(
texel.id,
(texel.density as u32, texel.density, texel.density),
);
}
}
}
(_, _) => (),
}
}
let mut total_densities: Vec<(TexelID, Capacity, Min, Max)> = total_densities
.iter()
.map(|(t, (d, min, max))| (*t, *d, *min, *max))
.collect();
if total_densities.len() == 0 {
return;
}
total_densities.sort_unstable_by_key(|(_, density, _, _)| *density);
total_densities.reverse();
const TILE_CAPACITY: u32 = u8::MAX as u32;
let free_slots = valid_globals.len() as u32
- total_densities
.iter()
.map(|(_, v, _, _)| (*v / (TILE_CAPACITY + 1)) + 1)
.sum::<u32>();
// Stop if the gas is already close to a stable state
const STABLE_TRESHOLD: u8 = 3;
if total_densities.iter().all(|(_, _, min, max)| {
if u8::abs_diff(*min, *max) > STABLE_TRESHOLD {
return false;
}
free_slots > 0 && *max <= STABLE_TRESHOLD
}) {
// // DEBUG: draw box for stabilized area
// let mut min = valid_globals.first().unwrap().clone();
// let mut max = valid_globals.first().unwrap().clone();
// for global in valid_globals.iter() {
// min = Vector2I::min(&min, global);
// max = Vector2I::max(&max, global);
// }
// max = max + Vector2I::ONE;
// crate::game::debug::terrain::draw_box(
// debug_draw,
// Vec3::from(min),
// Vec3::from(max),
// Color::CYAN,
// 0.0,
// );
return;
}
// Allocate slots
let mut slots: Vec<(TexelID, u32)> = vec![];
for (id, density, _, _) in total_densities.iter() {
let min_slots = (density / (TILE_CAPACITY + 1)) + 1;
slots.push((*id, min_slots));
}
for i in 0..free_slots as usize {
let len = slots.len();
slots[i % len].1 += 1;
}
// Disperse into given slots
let mut texels: Vec<Texel2D> = vec![];
for (id, total_density, _, _) in total_densities.iter() {
let slots = slots.iter().find(|s| s.0 == *id).unwrap().1;
let mut density_left = *total_density;
for i in 0..slots {
let density = if i < (slots - 1) {
(total_density / slots).min(density_left)
} else {
density_left
}
.min(u8::MAX as u32);
if density > 0 {
texels.push(Texel2D {
id: *id,
density: density as u8,
});
density_left -= density;
}
}
}
// Apply changes
if texels.len() > valid_globals.len() {
panic!("disperse_gas() - valid_globals is shorter than texels");
}
fastrand::shuffle(&mut valid_globals);
for i in 0..valid_globals.len() {
let global = valid_globals[i];
if i < texels.len() {
let texel = texels[i];
terrain.set_texel(&global, texel, None);
} else {
terrain.set_texel(&global, Texel2D::default(), None)
}
}
}
@ -314,37 +146,29 @@ fn simulate_texel(global: Vector2I, terrain: &mut Terrain2D, frame_counter: &Fra
let grav_offset = Vector2I::from(gravity);
let grav_pos = global + grav_offset;
if behaviour.form != TexelForm::Gas || gravity.abs() > fastrand::u8(0..u8::MAX) {
// Try falling
{
let (_, other_behaviour) = terrain.get_texel_behaviour(&grav_pos);
if TexelBehaviour2D::can_displace(&behaviour, &other_behaviour) {
terrain.swap_texels(&global, &grav_pos, Some(simulation_frame));
return;
}
if terrain.can_transfer_density(&global, &grav_pos) {
terrain.transfer_density(&global, &grav_pos, gravity, Some(simulation_frame))
}
// Try falling
{
let (_, other_behaviour) = terrain.get_texel_behaviour(&grav_pos);
if TexelBehaviour2D::can_displace(&behaviour, &other_behaviour) {
terrain.swap_texels(&global, &grav_pos, Some(simulation_frame));
return;
}
}
// Try "sliding"
let mut dirs = vec![Vector2I::RIGHT, Vector2I::LEFT];
if ((frame_counter.frame / 73) % 2) as i32 == global.y % 2 {
dirs.reverse();
}
for dir in dirs.iter() {
let slide_pos = match behaviour.form {
TexelForm::Solid => grav_pos + *dir,
TexelForm::Liquid | TexelForm::Gas => global + *dir,
};
let (_, other_behaviour) = terrain.get_texel_behaviour(&slide_pos);
if TexelBehaviour2D::can_displace(&behaviour, &other_behaviour) {
terrain.swap_texels(&global, &slide_pos, Some(simulation_frame));
return;
}
if terrain.can_transfer_density(&global, &grav_pos) {
terrain.transfer_density(&global, &grav_pos, gravity, Some(simulation_frame))
}
// Try "sliding"
let mut dirs = vec![Vector2I::RIGHT, Vector2I::LEFT];
if ((frame_counter.frame / 73) % 2) as i32 == global.y % 2 {
dirs.reverse();
}
for dir in dirs.iter() {
let slide_pos = match behaviour.form {
TexelForm::Solid => grav_pos + *dir,
TexelForm::Liquid | TexelForm::Gas => global + *dir,
};
let (_, other_behaviour) = terrain.get_texel_behaviour(&slide_pos);
if TexelBehaviour2D::can_displace(&behaviour, &other_behaviour) {
terrain.swap_texels(&global, &slide_pos, Some(simulation_frame));
return;
}
}
}
@ -381,16 +205,13 @@ pub struct Terrain2D {
}
impl Terrain2D {
pub const WORLD_WIDTH: i32 = 512;
pub const WORLD_HEIGHT: i32 = Self::WORLD_WIDTH * 2;
pub fn new(
top_boundary: Option<i32>,
bottom_boundary: Option<i32>,
left_boundary: Option<i32>,
right_boundary: Option<i32>,
) -> Self {
Self {
) -> Terrain2D {
Terrain2D {
chunk_map: HashMap::new(),
events: Vec::new(),
top_boundary,
@ -457,7 +278,7 @@ impl Terrain2D {
pub fn is_within_boundaries(&self, global: &Vector2I) -> bool {
if let Some(top) = self.top_boundary {
if global.y >= top {
if global.y > top {
return false;
}
}
@ -472,7 +293,7 @@ impl Terrain2D {
}
}
if let Some(right) = self.right_boundary {
if global.x >= right {
if global.x > right {
return false;
}
}
@ -484,12 +305,6 @@ impl Terrain2D {
.map_or(None, |chunk| chunk.get_texel(&global_to_local(global)))
}
pub fn get_latest_simulation(&self, global: &Vector2I) -> Option<u8> {
self.global_to_chunk(global).map_or(None, |chunk| {
chunk.get_latest_simulation(&global_to_local(global))
})
}
pub fn get_texel_behaviour(
&self,
global: &Vector2I,
@ -505,22 +320,16 @@ impl Terrain2D {
)
}
pub fn set_texel(
&mut self,
global: &Vector2I,
new_texel: Texel2D,
simulation_frame: Option<u8>,
) {
pub fn set_texel(&mut self, global: &Vector2I, id: TexelID, simulation_frame: Option<u8>) {
if !self.is_within_boundaries(global) {
return;
}
let index = global_to_chunk_index(global);
let changed = match self.index_to_chunk_mut(&index) {
Some(chunk) => chunk.set_texel(&global_to_local(global), new_texel, simulation_frame),
Some(chunk) => chunk.set_texel(&global_to_local(global), id, simulation_frame),
None => {
let mut chunk = Chunk2D::new();
let changed =
chunk.set_texel(&global_to_local(global), new_texel, simulation_frame);
let changed = chunk.set_texel(&global_to_local(global), id, simulation_frame);
self.add_chunk(index, chunk);
changed
}
@ -539,71 +348,11 @@ impl Terrain2D {
to_global: &Vector2I,
simulation_frame: Option<u8>,
) {
let from = self.get_texel(from_global).unwrap_or_default();
let to = self.get_texel(to_global).unwrap_or_default();
let from = self.get_texel(from_global).map_or(0, |t| t.id);
let to = self.get_texel(to_global).map_or(0, |t| t.id);
self.set_texel(to_global, from, simulation_frame);
// REM: The displaced texel is also marked as simulated
self.set_texel(from_global, to, simulation_frame);
}
fn can_transfer_density(&self, from_global: &Vector2I, to_global: &Vector2I) -> bool {
let from = self.get_texel(from_global).unwrap_or_default();
let to = self.get_texel(to_global).unwrap_or_default();
if from.id != to.id {
return false;
}
let behaviour = if let Some(behaviour) = from.behaviour() {
behaviour
} else {
return false;
};
behaviour.form == TexelForm::Gas
}
fn transfer_density(
&mut self,
from_global: &Vector2I,
to_global: &Vector2I,
gravity: TexelGravity,
simulation_frame: Option<u8>,
) {
let from = self.get_texel(from_global).unwrap_or_default();
let to = self.get_texel(to_global).unwrap_or_default();
let max_transfer = gravity.abs();
// DEBUG: Test this out, another property?
const MAX_TARGET_DENSITY: u8 = 25;
let transfer = (u8::MAX - to.density)
.min(max_transfer)
.min(from.density)
.min(MAX_TARGET_DENSITY.max(to.density) - to.density);
if transfer == 0 {
return;
}
if from.density - transfer == 0 {
self.set_texel(&from_global, Texel2D::default(), simulation_frame);
} else {
self.set_texel(
&from_global,
Texel2D {
density: from.density - transfer,
..from
},
simulation_frame,
);
}
self.set_texel(
&to_global,
Texel2D {
density: to.density + transfer,
..to
},
simulation_frame,
);
}
}
pub fn local_to_texel_index(position: &Vector2I) -> Option<usize> {

View File

@ -1,13 +1,18 @@
use std::collections::VecDeque;
use super::*;
use super::{
local_to_texel_index, texel_index_to_local, Terrain2D, TerrainEvent2D, Texel2D,
TexelBehaviour2D, TexelID, NEIGHBOUR_INDEX_MAP,
};
use crate::util::{CollisionLayers, Segment2I, Vector2I};
use bevy::render::{render_resource::Extent3d, texture::ImageSampler};
use bevy::{
prelude::*,
render::{render_resource::Extent3d, texture::ImageSampler},
};
use bevy_rapier2d::prelude::*;
use lazy_static::lazy_static;
type Island = VecDeque<Segment2I>;
pub type Chunk2DIndex = Vector2I;
pub type NeighbourMask = u8;
lazy_static! {
/// Marching Square case dictionary.
@ -44,14 +49,6 @@ lazy_static! {
/* down */ Segment2I { from: Vector2I::RIGHT, to: Vector2I::ZERO },
/* left */ Segment2I { from: Vector2I::ZERO, to: Vector2I::UP },
];
static ref NEIGHBOUR_INDEX_MAP: HashMap<Vector2I, u8> = {
let mut map = HashMap::new();
for i in 0..Chunk2D::NEIGHBOUR_OFFSET_VECTORS.len() {
map.insert(Chunk2D::NEIGHBOUR_OFFSET_VECTORS[i], i as u8);
}
map
};
}
#[derive(Reflect, Component, Default)]
@ -82,6 +79,8 @@ pub struct ChunkColliderBundle {
pub transform: TransformBundle,
}
pub type Chunk2DIndex = Vector2I;
#[derive(Clone, Copy)]
pub struct ChunkRect {
pub min: Vector2I,
@ -98,11 +97,7 @@ impl ChunkRect {
}
pub struct Chunk2D {
pub texels: [Texel2D; Self::SIZE_X * Self::SIZE_Y],
/// bitmask of empty/non-empty neighbours, see NEIGHBOUR_OFFSET_VECTORS for the order
pub neighbour_mask: [NeighbourMask; Self::SIZE_X * Self::SIZE_Y],
/// Used in simulation step so that texels won't be updated twice. Value of 0 is always updated.
pub simulation_frames: [u8; Self::SIZE_X * Self::SIZE_Y],
pub texels: [Texel2D; (Self::SIZE_X * Self::SIZE_Y) as usize],
// TODO: handle multiple dirty rects?
pub dirty_rect: Option<ChunkRect>,
}
@ -114,22 +109,65 @@ impl Chunk2D {
x: Self::SIZE_X as i32,
y: Self::SIZE_Y as i32,
};
pub const NEIGHBOUR_OFFSET_VECTORS: [Vector2I; 4] = [
Vector2I { x: 0, y: 1 },
Vector2I { x: 1, y: 0 },
Vector2I { x: 0, y: -1 },
Vector2I { x: -1, y: 0 },
];
pub fn new() -> Chunk2D {
Chunk2D {
texels: [Texel2D::default(); Self::SIZE_X * Self::SIZE_Y],
neighbour_mask: [0; Self::SIZE_X * Self::SIZE_Y],
simulation_frames: [0; Self::SIZE_X * Self::SIZE_Y],
texels: Self::new_texel_array(),
dirty_rect: None,
}
}
pub fn new_full() -> Chunk2D {
let mut chunk = Chunk2D {
texels: Self::new_texel_array(),
dirty_rect: None,
};
for y in 0..Self::SIZE_Y {
for x in 0..Self::SIZE_X {
chunk.set_texel(&Vector2I::new(x as i32, y as i32), 1, None);
}
}
chunk
}
pub fn new_half() -> Chunk2D {
let mut chunk = Chunk2D {
texels: Self::new_texel_array(),
dirty_rect: None,
};
for y in 0..Self::SIZE_Y {
for x in 0..Self::SIZE_X {
if x <= Self::SIZE_Y - y {
chunk.set_texel(&Vector2I::new(x as i32, y as i32), 1, None);
}
}
}
chunk
}
pub fn new_circle() -> Chunk2D {
let mut chunk = Chunk2D {
texels: Self::new_texel_array(),
dirty_rect: None,
};
let origin = Self::SIZE / 2;
let radius = Self::SIZE_X as i32 / 2;
for y in 0..Self::SIZE_Y {
for x in 0..Self::SIZE_X {
let dx = (x as i32 - origin.x).abs();
let dy = (y as i32 - origin.y).abs();
if dx * dx + dy * dy <= (radius - 1) * (radius - 1) {
chunk.set_texel(&Vector2I::new(x as i32, y as i32), 1, None);
}
}
}
chunk
}
pub fn new_texel_array() -> [Texel2D; Self::SIZE_X * Self::SIZE_Y] {
[Texel2D::default(); Self::SIZE_X * Self::SIZE_Y]
}
pub fn xy_vec() -> Vec<Vector2I> {
let mut result = Vec::with_capacity(Self::SIZE_X * Self::SIZE_Y);
for y in 0..Self::SIZE_Y {
@ -170,10 +208,6 @@ impl Chunk2D {
local_to_texel_index(position).map(|i| self.texels[i])
}
pub fn get_latest_simulation(&self, position: &Vector2I) -> Option<u8> {
local_to_texel_index(position).map(|i| self.simulation_frames[i])
}
pub fn get_texel_mut(&mut self, position: &Vector2I) -> Option<&mut Texel2D> {
local_to_texel_index(position).map(|i| &mut self.texels[i])
}
@ -181,44 +215,46 @@ impl Chunk2D {
pub fn set_texel(
&mut self,
position: &Vector2I,
new_texel: Texel2D,
id: TexelID,
simulation_frame: Option<u8>,
) -> bool {
let i = local_to_texel_index(position).expect("Texel index out of range");
if self.texels[i] == new_texel {
return false;
if self.texels[i].id != id {
self.mark_dirty(position);
}
self.mark_dirty(position);
let update_neighbours = self.texels[i].has_collision() != new_texel.has_collision();
self.texels[i] = new_texel;
// Update simulation frame
let update_neighbours = TexelBehaviour2D::has_collision(&self.texels[i].id)
!= TexelBehaviour2D::has_collision(&id);
let changed = self.texels[i].id != id;
self.texels[i].id = id;
if let Some(simulation_frame) = simulation_frame {
self.simulation_frames[i] = simulation_frame;
self.texels[i].last_simulation = simulation_frame;
}
// Update neighbour mask
if update_neighbours {
for offset in Self::NEIGHBOUR_OFFSET_VECTORS {
for offset in Texel2D::NEIGHBOUR_OFFSET_VECTORS {
// Flip neighbour's bit
match local_to_texel_index(&(*position + offset)) {
Some(index) => {
self.neighbour_mask[index] ^= 1 << NEIGHBOUR_INDEX_MAP[&-offset];
match self.get_texel_mut(&(*position + offset)) {
Some(mut neighbour) => {
neighbour.neighbour_mask ^= 1 << NEIGHBOUR_INDEX_MAP[&-offset];
}
None => (),
}
}
}
true
changed
}
pub fn create_texture_data(&self) -> Vec<u8> {
let mut image_data = Vec::with_capacity(Chunk2D::SIZE_X * Chunk2D::SIZE_Y * 4);
for y in (0..Chunk2D::SIZE_Y).rev() {
for x in 0..Chunk2D::SIZE_X {
let texel = &self.get_texel(&Vector2I::new(x as i32, y as i32)).unwrap();
let behaviour = texel.behaviour();
let mut color =
let id = &self
.get_texel(&Vector2I::new(x as i32, y as i32))
.unwrap()
.id;
let behaviour = TexelBehaviour2D::from_id(id);
let color =
behaviour.map_or(Color::rgba_u8(0, 0, 0, 0), |behaviour| behaviour.color);
color.set_a(color.a() * ((texel.density as f32) / 256.0));
let color_data = color.as_rgba_u32();
let mut color_data: Vec<u8> = vec![
((color_data >> 0) & 0xff) as u8,
@ -232,7 +268,6 @@ impl Chunk2D {
image_data
}
// TODO: Don't create collision for falling texels, it's pretty annoying that a stream of small grains blocks movement
pub fn create_collision_data(&self) -> Vec<Vec<Vec2>> {
let mut islands: Vec<Island> = Vec::new();
for i in 0..self.texels.len() {
@ -252,7 +287,7 @@ impl Chunk2D {
let mut sides: Vec<Segment2I>;
let has_collision = TexelBehaviour2D::has_collision(&self.texels[i].id);
if !has_collision {
sides = MST_CASE_MAP[self.neighbour_mask[i] as usize]
sides = MST_CASE_MAP[self.texels[i].neighbour_mask as usize]
.iter()
.clone()
.map(|side| Segment2I {
@ -438,7 +473,9 @@ pub fn chunk_spawner(
}
}
/// Update the chunk sprite as needed
/**
Update the chunk sprite as needed
*/
pub fn chunk_sprite_sync(
mut terrain_events: EventReader<TerrainEvent2D>,
mut images: ResMut<Assets<Image>>,
@ -495,7 +532,9 @@ pub fn chunk_sprite_sync(
}
}
/// Create and update colliders for chunk as needed
/**
Create and update colliders for chunk as needed
*/
pub fn chunk_collision_sync(
mut terrain_events: EventReader<TerrainEvent2D>,
mut commands: Commands,

View File

@ -1,7 +1,6 @@
use noise::{NoiseFn, PerlinSurflet};
use super::*;
use crate::util::{inverse_lerp, lerp};
use super::{chunk_index_to_global, Chunk2D, Chunk2DIndex};
pub struct TerrainGen2D {
pub seed: u32,
@ -40,7 +39,7 @@ impl TerrainGen2D {
id = 13;
}
chunk.set_texel(&local, Texel2D { id, ..default() }, None);
chunk.set_texel(&local, id, None);
}
chunk
}

View File

@ -1,32 +1,35 @@
use lazy_static::lazy_static;
use std::collections::HashMap;
pub use u8 as TexelID;
pub use u8 as NeighbourMask;
use super::TexelBehaviour2D;
use crate::util::Vector2I;
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Default)]
pub struct Texel2D {
/// Identifier for a set of properties
pub id: TexelID,
/// Used by gas materials
pub density: u8,
/// bitmask of empty/non-empty neighbours, see NEIGHBOUR_OFFSET_VECTORS for the order
pub neighbour_mask: NeighbourMask,
pub last_simulation: u8,
}
impl Default for Texel2D {
fn default() -> Self {
Self {
id: TexelID::default(),
density: u8::MAX,
lazy_static! {
pub static ref NEIGHBOUR_INDEX_MAP: HashMap<Vector2I, u8> = {
let mut map = HashMap::new();
for i in 0..Texel2D::NEIGHBOUR_OFFSET_VECTORS.len() {
map.insert(Texel2D::NEIGHBOUR_OFFSET_VECTORS[i], i as u8);
}
}
map
};
}
impl Texel2D {
pub const EMPTY: TexelID = 0;
pub fn has_collision(&self) -> bool {
TexelBehaviour2D::has_collision(&self.id)
}
pub fn behaviour(&self) -> Option<TexelBehaviour2D> {
TexelBehaviour2D::from_id(&self.id)
}
pub const NEIGHBOUR_OFFSET_VECTORS: [Vector2I; 4] = [
Vector2I { x: 0, y: 1 },
Vector2I { x: 1, y: 0 },
Vector2I { x: 0, y: -1 },
Vector2I { x: -1, y: 0 },
];
}

View File

@ -14,7 +14,7 @@ lazy_static! {
TexelBehaviour2D {
name: Cow::Borrowed("loose sand"),
color: Color::rgb(0.61, 0.49, 0.38),
gravity: Some(TexelGravity::Down(200)),
gravity: Some(TexelGravity::Down(100)),
has_collision: true,
..default()
},
@ -25,7 +25,7 @@ lazy_static! {
TexelBehaviour2D {
name: Cow::Borrowed("loose stone"),
color: Color::rgb(0.21, 0.19, 0.17),
gravity: Some(TexelGravity::Down(200)),
gravity: Some(TexelGravity::Down(100)),
has_collision: true,
..default()
},
@ -36,7 +36,7 @@ lazy_static! {
TexelBehaviour2D {
name: Cow::Borrowed("loose sturdy stone"),
color: Color::rgb(0.11, 0.11, 0.11),
gravity: Some(TexelGravity::Down(200)),
gravity: Some(TexelGravity::Down(100)),
has_collision: true,
..default()
},
@ -48,7 +48,7 @@ lazy_static! {
name: Cow::Borrowed("water"),
color: Color::rgba(0.0, 0.0, 1.0, 0.5),
form: TexelForm::Liquid,
gravity: Some(TexelGravity::Down(50)),
gravity: Some(TexelGravity::Down(10)),
..default()
},
);
@ -57,9 +57,9 @@ lazy_static! {
5,
TexelBehaviour2D {
name: Cow::Borrowed("oil"),
color: Color::rgba(0.5, 0.5, 0.25, 0.5),
form: TexelForm::Liquid,
gravity: Some(TexelGravity::Down(20)),
color: Color::rgba(0.0, 1.0, 0.0, 0.5),
form: TexelForm::Gas,
gravity: Some(TexelGravity::Up(50)),
..default()
},
);
@ -67,31 +67,10 @@ lazy_static! {
result.insert(
6,
TexelBehaviour2D {
name: Cow::Borrowed("light gas"),
color: Color::rgba(0.0, 1.0, 0.0, 0.5),
form: TexelForm::Gas,
gravity: Some(TexelGravity::Up(160)),
..default()
},
);
result.insert(
7,
TexelBehaviour2D {
name: Cow::Borrowed("heavy gas"),
color: Color::rgba(1.0, 0.5, 0.5, 0.5),
form: TexelForm::Gas,
gravity: Some(TexelGravity::Down(60)),
..default()
},
);
result.insert(
8,
TexelBehaviour2D {
name: Cow::Borrowed("oxygen"),
color: Color::rgba(0.5, 0.5, 0.5, 0.5),
form: TexelForm::Gas,
name: Cow::Borrowed("gas"),
color: Color::rgba(0.5, 0.5, 0.25, 0.5),
form: TexelForm::Liquid,
gravity: Some(TexelGravity::Down(5)),
..default()
},
);
@ -128,16 +107,9 @@ lazy_static! {
result
};
static ref FORM_DISPLACEMENT_PRIORITY: HashMap<TexelForm, u8> = {
let mut result = HashMap::new();
result.insert(TexelForm::Gas, 0);
result.insert(TexelForm::Liquid, 1);
result.insert(TexelForm::Solid, 2);
result
};
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Default, PartialEq)]
pub enum TexelForm {
#[default]
// Solid materials, when affected by gravity, create pyramid-like piles
@ -148,16 +120,7 @@ pub enum TexelForm {
Gas,
}
impl TexelForm {
fn priority(&self) -> u8 {
FORM_DISPLACEMENT_PRIORITY
.get(self)
.cloned()
.unwrap_or_default()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, PartialEq)]
pub enum TexelGravity {
Down(u8),
Up(u8),
@ -172,16 +135,7 @@ impl From<TexelGravity> for Vector2I {
}
}
impl TexelGravity {
pub fn abs(&self) -> u8 {
match self {
TexelGravity::Down(grav) => *grav,
TexelGravity::Up(grav) => *grav,
}
}
}
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct TexelBehaviour2D {
pub name: Cow<'static, str>,
pub color: Color,
@ -231,10 +185,7 @@ impl TexelBehaviour2D {
let to = if let Some(to) = to { to } else { return true };
match (from.form, to.form) {
(from_form, to_form) => {
if from_form.priority() != to_form.priority() {
return from_form.priority() > to_form.priority();
}
(_, to_form) => {
if let (Some(from_grav), Some(to_grav)) = (from.gravity, to.gravity) {
match (from_grav, to_grav) {
(TexelGravity::Down(from_grav), TexelGravity::Down(to_grav)) => {