mirror of
https://github.com/griffi-gh/kubi.git
synced 2024-11-21 22:38:41 -06:00
Compare commits
12 commits
c162893fd0
...
2045b26544
Author | SHA1 | Date | |
---|---|---|---|
griffi-gh | 2045b26544 | ||
griffi-gh | 5c40e68d66 | ||
griffi-gh | 14e9cb32f7 | ||
griffi-gh | f3a844bf55 | ||
griffi-gh | f97b922943 | ||
griffi-gh | 6a96d6c3d3 | ||
griffi-gh | 778c2b279e | ||
griffi-gh | 89ccd595ac | ||
griffi-gh | b34f1a94b1 | ||
griffi-gh | 1466f62b5a | ||
griffi-gh | 93e34b2c88 | ||
griffi-gh | 0ae87b6ddd |
63
Cargo.lock
generated
63
Cargo.lock
generated
|
@ -886,6 +886,30 @@ version = "0.4.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hui"
|
||||
version = "0.0.2"
|
||||
source = "git+https://github.com/griffi-gh/hui?rev=1e1dccde0c#1e1dccde0c1f8ba8f4143a5a57d91cf923203508"
|
||||
dependencies = [
|
||||
"fontdue",
|
||||
"glam",
|
||||
"hashbrown 0.14.3",
|
||||
"log",
|
||||
"nohash-hasher",
|
||||
"rect_packer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hui-glium"
|
||||
version = "0.0.2"
|
||||
source = "git+https://github.com/griffi-gh/hui?rev=1e1dccde0c#1e1dccde0c1f8ba8f4143a5a57d91cf923203508"
|
||||
dependencies = [
|
||||
"glam",
|
||||
"glium",
|
||||
"hui",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "humantime"
|
||||
version = "2.1.0"
|
||||
|
@ -1073,11 +1097,11 @@ dependencies = [
|
|||
"glutin",
|
||||
"glutin-winit",
|
||||
"hashbrown 0.14.3",
|
||||
"hui",
|
||||
"hui-glium",
|
||||
"image",
|
||||
"kubi-logging",
|
||||
"kubi-shared",
|
||||
"kubi-ui",
|
||||
"kubi-ui-glium",
|
||||
"log",
|
||||
"lz4_flex",
|
||||
"ndk",
|
||||
|
@ -1152,41 +1176,6 @@ dependencies = [
|
|||
"strum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubi-ui"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"fontdue",
|
||||
"glam",
|
||||
"hashbrown 0.14.3",
|
||||
"log",
|
||||
"nohash-hasher",
|
||||
"rect_packer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubi-ui-examples"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"glam",
|
||||
"glium",
|
||||
"kubi-logging",
|
||||
"kubi-ui",
|
||||
"kubi-ui-glium",
|
||||
"log",
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubi-ui-glium"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"glam",
|
||||
"glium",
|
||||
"kubi-ui",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.4.0"
|
||||
|
|
|
@ -4,10 +4,7 @@ members = [
|
|||
"kubi-server",
|
||||
"kubi-shared",
|
||||
"kubi-logging",
|
||||
"kubi-pool",
|
||||
"kubi-ui",
|
||||
"kubi-ui-glium",
|
||||
"kubi-ui-examples"
|
||||
"kubi-pool"
|
||||
]
|
||||
default-members = ["kubi"]
|
||||
resolver = "2"
|
||||
|
@ -38,3 +35,6 @@ opt-level = 3
|
|||
#enabling debug assertions here causes the game to abort
|
||||
[profile.dev.package.android-activity]
|
||||
debug-assertions = false
|
||||
|
||||
[patch.crates-io]
|
||||
glium = { git = "https://github.com/glium/glium", rev = "a352c667" }
|
||||
|
|
|
@ -118,7 +118,7 @@ name = "Kubi Server" # server name
|
|||
|
||||
<h2>"In-house" libraries</h2>
|
||||
|
||||
- [`kubi-ui`](kubi-ui): semi-imm.mode backend-agnostic ui system\
|
||||
- [`hui`](https://github.com/griffi-gh/hui): semi-imm.mode backend-agnostic ui system\
|
||||
mostly ready to use, it has already replaced the Kubi legacy ui
|
||||
- [`kubi-ui-glium`](kubi-ui-glium) Glium-based backend for `kubi-ui`
|
||||
- [`kubi-pool`](kubi-pool): very early work-in-progress work-stealing threadpool system\
|
||||
|
|
|
@ -1,334 +1,342 @@
|
|||
use bracket_noise::prelude::*;
|
||||
use rand::prelude::*;
|
||||
use glam::{IVec3, ivec3, Vec3Swizzles, IVec2};
|
||||
use rand_xoshiro::Xoshiro256StarStar;
|
||||
use crate::{
|
||||
chunk::{BlockData, CHUNK_SIZE},
|
||||
block::Block,
|
||||
queue::QueuedBlock,
|
||||
};
|
||||
|
||||
fn mountain_ramp(mut x: f32) -> f32 {
|
||||
x *= 2.0;
|
||||
if x < 0.4 {
|
||||
0.5 * x
|
||||
} else if x < 0.55 {
|
||||
4. * (x - 0.4) + 0.2
|
||||
} else {
|
||||
0.4444 * (x - 0.55) + 0.8
|
||||
}
|
||||
}
|
||||
|
||||
fn local_height(height: i32, chunk_position: IVec3) -> usize {
|
||||
let offset = chunk_position * CHUNK_SIZE as i32;
|
||||
(height - offset.y).clamp(0, CHUNK_SIZE as i32) as usize
|
||||
}
|
||||
|
||||
fn local_y_position(height: i32, chunk_position: IVec3) -> Option<usize> {
|
||||
let offset = chunk_position * CHUNK_SIZE as i32;
|
||||
let position = height - offset.y;
|
||||
(0..CHUNK_SIZE as i32).contains(&position).then_some(position as usize)
|
||||
}
|
||||
|
||||
|
||||
pub fn generate_world(chunk_position: IVec3, seed: u64) -> (BlockData, Vec<QueuedBlock>) {
|
||||
let offset = chunk_position * CHUNK_SIZE as i32;
|
||||
let mut blocks = Box::new([[[Block::Air; CHUNK_SIZE]; CHUNK_SIZE]; CHUNK_SIZE]);
|
||||
let mut queue = Vec::with_capacity(0);
|
||||
|
||||
let mut smart_place = |blocks: &mut BlockData, position: IVec3, block: Block| {
|
||||
if position.to_array().iter().any(|&x| !(0..CHUNK_SIZE).contains(&(x as usize))) {
|
||||
let event_pos = offset + position;
|
||||
queue.retain(|block: &QueuedBlock| {
|
||||
block.position != event_pos
|
||||
});
|
||||
queue.push(QueuedBlock {
|
||||
position: event_pos,
|
||||
block_type: block,
|
||||
soft: true
|
||||
});
|
||||
} else {
|
||||
blocks[position.x as usize][position.y as usize][position.z as usize] = block;
|
||||
}
|
||||
};
|
||||
|
||||
let mut height_noise = FastNoise::seeded(seed);
|
||||
height_noise.set_fractal_type(FractalType::FBM);
|
||||
height_noise.set_fractal_octaves(4);
|
||||
height_noise.set_frequency(0.003);
|
||||
|
||||
let mut elevation_noise = FastNoise::seeded(seed.rotate_left(1));
|
||||
elevation_noise.set_fractal_type(FractalType::FBM);
|
||||
elevation_noise.set_fractal_octaves(1);
|
||||
elevation_noise.set_frequency(0.001);
|
||||
|
||||
let mut cave_noise_a = FastNoise::seeded(seed.rotate_left(2));
|
||||
cave_noise_a.set_fractal_type(FractalType::FBM);
|
||||
cave_noise_a.set_fractal_octaves(2);
|
||||
cave_noise_a.set_frequency(0.01);
|
||||
|
||||
let mut cave_noise_b = FastNoise::seeded(seed.rotate_left(3));
|
||||
cave_noise_b.set_fractal_type(FractalType::FBM);
|
||||
cave_noise_b.set_fractal_octaves(3);
|
||||
cave_noise_b.set_frequency(0.015);
|
||||
|
||||
let mut cave_noise_holes = FastNoise::seeded(seed.rotate_left(4));
|
||||
cave_noise_holes.set_fractal_type(FractalType::FBM);
|
||||
cave_noise_holes.set_fractal_octaves(2);
|
||||
cave_noise_holes.set_frequency(0.005);
|
||||
|
||||
let mut ravine_nose_line = FastNoise::seeded(seed.rotate_left(5));
|
||||
ravine_nose_line.set_fractal_type(FractalType::Billow);
|
||||
ravine_nose_line.set_fractal_octaves(2);
|
||||
ravine_nose_line.set_frequency(0.005);
|
||||
|
||||
let mut ravine_noise_location = FastNoise::seeded(seed.rotate_left(6));
|
||||
ravine_noise_location.set_fractal_type(FractalType::FBM);
|
||||
ravine_noise_location.set_fractal_octaves(1);
|
||||
ravine_noise_location.set_frequency(0.005);
|
||||
|
||||
let mut river_noise = FastNoise::seeded(seed.rotate_left(7));
|
||||
river_noise.set_fractal_type(FractalType::Billow);
|
||||
river_noise.set_fractal_octaves(2);
|
||||
river_noise.set_frequency(0.5 * 0.005);
|
||||
|
||||
let mut rng = Xoshiro256StarStar::seed_from_u64(
|
||||
seed
|
||||
^ (chunk_position.x as u32 as u64)
|
||||
^ ((chunk_position.z as u32 as u64) << 32)
|
||||
);
|
||||
let rng_map_a: [[f32; CHUNK_SIZE]; CHUNK_SIZE] = rng.gen();
|
||||
let rng_map_b: [[f32; CHUNK_SIZE]; CHUNK_SIZE] = rng.gen();
|
||||
|
||||
//Generate height map
|
||||
let mut within_heightmap = false;
|
||||
let mut deco_heightmap = [[None; CHUNK_SIZE]; CHUNK_SIZE];
|
||||
|
||||
for x in 0..CHUNK_SIZE {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
let (noise_x, noise_y) = ((offset.x + x as i32) as f32, (offset.z + z as i32) as f32);
|
||||
//sample noises (that are needed right now)
|
||||
let raw_heightmap_value = height_noise.get_noise(noise_x, noise_y);
|
||||
let raw_elevation_value = elevation_noise.get_noise(noise_x, noise_y);
|
||||
let raw_ravine_location_value = ravine_noise_location.get_noise(noise_x, noise_y);
|
||||
//compute height
|
||||
let mut is_surface = true;
|
||||
let mut river_fill_height = None;
|
||||
let height = {
|
||||
let local_elevation = raw_elevation_value.powi(4).sqrt();
|
||||
let mut height = (mountain_ramp(raw_heightmap_value) * local_elevation * 100.) as i32;
|
||||
//Flatten valleys
|
||||
if height < 0 {
|
||||
height /= 2;
|
||||
}
|
||||
//Generate rivers
|
||||
{
|
||||
let river_width = (height as f32 / -5.).clamp(0.5, 1.);
|
||||
let river_value = river_noise.get_noise(noise_x, noise_y);
|
||||
if ((-0.00625 * river_width)..(0.00625 * river_width)).contains(&(river_value.powi(2))) {
|
||||
is_surface = false;
|
||||
river_fill_height = Some(height - 1);
|
||||
//river_fill_height = Some(-3);
|
||||
height -= (river_width * 15. * ((0.00625 * river_width) - river_value.powi(2)) * (1. / (0.00625 * river_width))).round() as i32;
|
||||
}
|
||||
}
|
||||
//Generate ravines
|
||||
if height < 0 && raw_ravine_location_value > 0.4 {
|
||||
let raw_ravine_value = ravine_nose_line.get_noise(noise_x, noise_y);
|
||||
if (-0.0125..0.0125).contains(&(raw_ravine_value.powi(2))) {
|
||||
is_surface = false;
|
||||
height -= (100. * (0.0125 - raw_ravine_value.powi(2)) * (1. / 0.0125)).round() as i32;
|
||||
}
|
||||
}
|
||||
height
|
||||
};
|
||||
//add to heightmap
|
||||
if is_surface {
|
||||
deco_heightmap[x][z] = Some(height);
|
||||
//place dirt
|
||||
for y in 0..local_height(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Dirt;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//place stone
|
||||
for y in 0..local_height(height - 5 - (raw_heightmap_value * 5.) as i32, chunk_position) {
|
||||
blocks[x][y][z] = Block::Stone;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//place grass
|
||||
if let Some(y) = local_y_position(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Grass;
|
||||
within_heightmap = true;
|
||||
}
|
||||
} else if let Some(river_fill_height) = river_fill_height {
|
||||
//Place water
|
||||
for y in 0..local_height(river_fill_height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Water;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//Place stone
|
||||
for y in 0..local_height(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Stone;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//Place dirt
|
||||
if let Some(y) = local_y_position(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Dirt;
|
||||
within_heightmap = true;
|
||||
}
|
||||
} else {
|
||||
//Place stone
|
||||
for y in 0..local_height(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Stone;
|
||||
within_heightmap = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Carve out caves
|
||||
if within_heightmap {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
for y in 0..CHUNK_SIZE {
|
||||
for x in 0..CHUNK_SIZE {
|
||||
if blocks[x][y][z] != Block::Stone { continue }
|
||||
|
||||
let cave_size = ((offset.y + y as i32) as f32 / -100.).clamp(0., 1.);
|
||||
let inv_cave_size = 1. - cave_size;
|
||||
if cave_size < 0.1 { continue }
|
||||
|
||||
let position = ivec3(x as i32, y as i32, z as i32) + offset;
|
||||
|
||||
let is_cave = || {
|
||||
let raw_cavemap_value_a = cave_noise_a.get_noise3d(position.x as f32, position.y as f32, position.z as f32);
|
||||
let raw_cavemap_value_b = cave_noise_b.get_noise3d(position.x as f32, position.y as f32, position.z as f32);
|
||||
((cave_size * -0.15)..=(cave_size * 0.15)).contains(&raw_cavemap_value_a) &&
|
||||
((cave_size * -0.15)..=(cave_size * 0.15)).contains(&raw_cavemap_value_b)
|
||||
};
|
||||
let is_hole_cave = || {
|
||||
let raw_cavemap_value_holes = cave_noise_holes.get_noise3d(position.x as f32, position.y as f32, position.z as f32);
|
||||
((0.9 + (0.1 * inv_cave_size))..=1.0).contains(&raw_cavemap_value_holes.abs())
|
||||
};
|
||||
|
||||
if is_cave() || is_hole_cave() {
|
||||
blocks[x][y][z] = Block::Air;
|
||||
if deco_heightmap[x][z] == Some(y as i32 + offset.y) {
|
||||
deco_heightmap[x][z] = None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Add decorations
|
||||
for x in 0..CHUNK_SIZE {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
//get height
|
||||
let Some(height) = deco_heightmap[x][z] else { continue };
|
||||
//check for air
|
||||
// if blocks[x][local_y][z] == Block::Air {
|
||||
// continue
|
||||
// }
|
||||
//place tall grass
|
||||
if rng_map_a[x][z] < 0.03 {
|
||||
if let Some(y) = local_y_position(height + 1, chunk_position) {
|
||||
blocks[x][y][z] = Block::TallGrass;
|
||||
}
|
||||
}
|
||||
//place trees!
|
||||
if rng_map_a[x][z] < 0.001 {
|
||||
//Replace grass with dirt under the tree
|
||||
if let Some(y) = local_y_position(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Dirt;
|
||||
}
|
||||
|
||||
//Place wood (no smart_place needed here!)
|
||||
let tree_height = 4 + (rng_map_b[x][z] * 3.).round() as i32;
|
||||
for tree_y in 0..tree_height {
|
||||
if let Some(y) = local_y_position(height + 1 + tree_y, chunk_position) {
|
||||
blocks[x][y][z] = Block::Wood;
|
||||
}
|
||||
}
|
||||
|
||||
let tree_height = 4 + (rng_map_b[x][z] * 3.).round() as i32;
|
||||
|
||||
//Place leaf blocks
|
||||
if let Some(y) = local_y_position(height + 1, chunk_position) {
|
||||
let tree_pos = ivec3(x as i32, y as i32, z as i32);
|
||||
// Place wood (smart_place)
|
||||
// for tree_y in 0..tree_height {
|
||||
// smart_place(&mut blocks, tree_pos + tree_y * IVec3::Y, Block::Wood);
|
||||
// }
|
||||
// Part that wraps around the tree
|
||||
{
|
||||
let tree_leaf_height = tree_height - 3;
|
||||
let leaf_width = 2;
|
||||
for tree_y in tree_leaf_height..tree_height {
|
||||
for tree_x in (-leaf_width)..=leaf_width {
|
||||
for tree_z in (-leaf_width)..=leaf_width {
|
||||
let tree_offset = ivec3(tree_x, tree_y, tree_z);
|
||||
if tree_offset.xz() == IVec2::ZERO { continue }
|
||||
smart_place(&mut blocks, tree_pos + tree_offset, Block::Leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//part above the tree
|
||||
{
|
||||
let leaf_above_height = 2;
|
||||
let leaf_width = 1;
|
||||
for tree_y in tree_height..(tree_height + leaf_above_height) {
|
||||
for tree_x in (-leaf_width)..=leaf_width {
|
||||
for tree_z in (-leaf_width)..=leaf_width {
|
||||
let tree_offset = ivec3(tree_x, tree_y, tree_z);
|
||||
smart_place(&mut blocks, tree_pos + tree_offset, Block::Leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(blocks, queue)
|
||||
|
||||
// let mut cave_noise = FastNoise::seeded(seed);
|
||||
// cave_noise.set_fractal_type(FractalType::FBM);
|
||||
// cave_noise.set_frequency(0.1);
|
||||
|
||||
// let mut dirt_noise = FastNoise::seeded(seed.rotate_left(1));
|
||||
// dirt_noise.set_fractal_type(FractalType::FBM);
|
||||
// dirt_noise.set_frequency(0.1);
|
||||
|
||||
//
|
||||
|
||||
// if chunk_position.y >= 0 {
|
||||
// if chunk_position.y == 0 {
|
||||
// for x in 0..CHUNK_SIZE {
|
||||
// for z in 0..CHUNK_SIZE {
|
||||
// blocks[x][0][z] = Block::Dirt;
|
||||
// blocks[x][1][z] = Block::Grass;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// for x in 0..CHUNK_SIZE {
|
||||
// for y in 0..CHUNK_SIZE {
|
||||
// for z in 0..CHUNK_SIZE {
|
||||
// let position = ivec3(x as i32, y as i32, z as i32) + offset;
|
||||
// let v_cave_noise = cave_noise.get_noise3d(position.x as f32, position.y as f32, position.z as f32) * (-position.y as f32 - 10.0).clamp(0., 1.);
|
||||
// let v_dirt_noise = dirt_noise.get_noise3d(position.x as f32, position.y as f32, position.z as f32) * (-position.y as f32).clamp(0., 1.);
|
||||
// if v_cave_noise > 0.5 {
|
||||
// blocks[x][y][z] = Block::Stone;
|
||||
// } else if v_dirt_noise > 0.5 {
|
||||
// blocks[x][y][z] = Block::Dirt;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// blocks
|
||||
|
||||
}
|
||||
use bracket_noise::prelude::*;
|
||||
use rand::prelude::*;
|
||||
use glam::{IVec3, ivec3, Vec3Swizzles, IVec2};
|
||||
use rand_xoshiro::Xoshiro256StarStar;
|
||||
use crate::{
|
||||
chunk::{BlockData, CHUNK_SIZE},
|
||||
block::Block,
|
||||
queue::QueuedBlock,
|
||||
};
|
||||
|
||||
fn mountain_ramp(mut x: f32) -> f32 {
|
||||
x *= 2.0;
|
||||
if x < 0.4 {
|
||||
0.5 * x
|
||||
} else if x < 0.55 {
|
||||
4. * (x - 0.4) + 0.2
|
||||
} else {
|
||||
0.4444 * (x - 0.55) + 0.8
|
||||
}
|
||||
}
|
||||
|
||||
fn local_height(height: i32, chunk_position: IVec3) -> usize {
|
||||
let offset = chunk_position * CHUNK_SIZE as i32;
|
||||
(height - offset.y).clamp(0, CHUNK_SIZE as i32) as usize
|
||||
}
|
||||
|
||||
fn local_y_position(height: i32, chunk_position: IVec3) -> Option<usize> {
|
||||
let offset = chunk_position * CHUNK_SIZE as i32;
|
||||
let position = height - offset.y;
|
||||
(0..CHUNK_SIZE as i32).contains(&position).then_some(position as usize)
|
||||
}
|
||||
|
||||
|
||||
pub fn generate_world(chunk_position: IVec3, seed: u64) -> (BlockData, Vec<QueuedBlock>) {
|
||||
let offset = chunk_position * CHUNK_SIZE as i32;
|
||||
let mut blocks = Box::new([[[Block::Air; CHUNK_SIZE]; CHUNK_SIZE]; CHUNK_SIZE]);
|
||||
let mut queue = Vec::with_capacity(0);
|
||||
|
||||
let mut smart_place = |blocks: &mut BlockData, position: IVec3, block: Block| {
|
||||
if position.to_array().iter().any(|&x| !(0..CHUNK_SIZE).contains(&(x as usize))) {
|
||||
let event_pos = offset + position;
|
||||
queue.retain(|block: &QueuedBlock| {
|
||||
block.position != event_pos
|
||||
});
|
||||
queue.push(QueuedBlock {
|
||||
position: event_pos,
|
||||
block_type: block,
|
||||
soft: true
|
||||
});
|
||||
} else {
|
||||
blocks[position.x as usize][position.y as usize][position.z as usize] = block;
|
||||
}
|
||||
};
|
||||
|
||||
//STICK
|
||||
if chunk_position.x == 0 && chunk_position.y == 5 {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
blocks[0][0][z] = Block::Stone;
|
||||
}
|
||||
}
|
||||
//
|
||||
|
||||
let mut height_noise = FastNoise::seeded(seed);
|
||||
height_noise.set_fractal_type(FractalType::FBM);
|
||||
height_noise.set_fractal_octaves(4);
|
||||
height_noise.set_frequency(0.003);
|
||||
|
||||
let mut elevation_noise = FastNoise::seeded(seed.rotate_left(1));
|
||||
elevation_noise.set_fractal_type(FractalType::FBM);
|
||||
elevation_noise.set_fractal_octaves(1);
|
||||
elevation_noise.set_frequency(0.001);
|
||||
|
||||
let mut cave_noise_a = FastNoise::seeded(seed.rotate_left(2));
|
||||
cave_noise_a.set_fractal_type(FractalType::FBM);
|
||||
cave_noise_a.set_fractal_octaves(2);
|
||||
cave_noise_a.set_frequency(0.01);
|
||||
|
||||
let mut cave_noise_b = FastNoise::seeded(seed.rotate_left(3));
|
||||
cave_noise_b.set_fractal_type(FractalType::FBM);
|
||||
cave_noise_b.set_fractal_octaves(3);
|
||||
cave_noise_b.set_frequency(0.015);
|
||||
|
||||
let mut cave_noise_holes = FastNoise::seeded(seed.rotate_left(4));
|
||||
cave_noise_holes.set_fractal_type(FractalType::FBM);
|
||||
cave_noise_holes.set_fractal_octaves(2);
|
||||
cave_noise_holes.set_frequency(0.005);
|
||||
|
||||
let mut ravine_nose_line = FastNoise::seeded(seed.rotate_left(5));
|
||||
ravine_nose_line.set_fractal_type(FractalType::Billow);
|
||||
ravine_nose_line.set_fractal_octaves(2);
|
||||
ravine_nose_line.set_frequency(0.005);
|
||||
|
||||
let mut ravine_noise_location = FastNoise::seeded(seed.rotate_left(6));
|
||||
ravine_noise_location.set_fractal_type(FractalType::FBM);
|
||||
ravine_noise_location.set_fractal_octaves(1);
|
||||
ravine_noise_location.set_frequency(0.005);
|
||||
|
||||
let mut river_noise = FastNoise::seeded(seed.rotate_left(7));
|
||||
river_noise.set_fractal_type(FractalType::Billow);
|
||||
river_noise.set_fractal_octaves(2);
|
||||
river_noise.set_frequency(0.5 * 0.005);
|
||||
|
||||
let mut rng = Xoshiro256StarStar::seed_from_u64(
|
||||
seed
|
||||
^ (chunk_position.x as u32 as u64)
|
||||
^ ((chunk_position.z as u32 as u64) << 32)
|
||||
);
|
||||
let rng_map_a: [[f32; CHUNK_SIZE]; CHUNK_SIZE] = rng.gen();
|
||||
let rng_map_b: [[f32; CHUNK_SIZE]; CHUNK_SIZE] = rng.gen();
|
||||
|
||||
//Generate height map
|
||||
let mut within_heightmap = false;
|
||||
let mut deco_heightmap = [[None; CHUNK_SIZE]; CHUNK_SIZE];
|
||||
|
||||
for x in 0..CHUNK_SIZE {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
let (noise_x, noise_y) = ((offset.x + x as i32) as f32, (offset.z + z as i32) as f32);
|
||||
//sample noises (that are needed right now)
|
||||
let raw_heightmap_value = height_noise.get_noise(noise_x, noise_y);
|
||||
let raw_elevation_value = elevation_noise.get_noise(noise_x, noise_y);
|
||||
let raw_ravine_location_value = ravine_noise_location.get_noise(noise_x, noise_y);
|
||||
//compute height
|
||||
let mut is_surface = true;
|
||||
let mut river_fill_height = None;
|
||||
let height = {
|
||||
let local_elevation = raw_elevation_value.powi(4).sqrt();
|
||||
let mut height = (mountain_ramp(raw_heightmap_value) * local_elevation * 100.) as i32;
|
||||
//Flatten valleys
|
||||
if height < 0 {
|
||||
height /= 2;
|
||||
}
|
||||
//Generate rivers
|
||||
{
|
||||
let river_width = (height as f32 / -5.).clamp(0.5, 1.);
|
||||
let river_value = river_noise.get_noise(noise_x, noise_y);
|
||||
if ((-0.00625 * river_width)..(0.00625 * river_width)).contains(&(river_value.powi(2))) {
|
||||
is_surface = false;
|
||||
river_fill_height = Some(height - 1);
|
||||
//river_fill_height = Some(-3);
|
||||
height -= (river_width * 15. * ((0.00625 * river_width) - river_value.powi(2)) * (1. / (0.00625 * river_width))).round() as i32;
|
||||
}
|
||||
}
|
||||
//Generate ravines
|
||||
if height < 0 && raw_ravine_location_value > 0.4 {
|
||||
let raw_ravine_value = ravine_nose_line.get_noise(noise_x, noise_y);
|
||||
if (-0.0125..0.0125).contains(&(raw_ravine_value.powi(2))) {
|
||||
is_surface = false;
|
||||
height -= (100. * (0.0125 - raw_ravine_value.powi(2)) * (1. / 0.0125)).round() as i32;
|
||||
}
|
||||
}
|
||||
height
|
||||
};
|
||||
//add to heightmap
|
||||
if is_surface {
|
||||
deco_heightmap[x][z] = Some(height);
|
||||
//place dirt
|
||||
for y in 0..local_height(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Dirt;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//place stone
|
||||
for y in 0..local_height(height - 5 - (raw_heightmap_value * 5.) as i32, chunk_position) {
|
||||
blocks[x][y][z] = Block::Stone;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//place grass
|
||||
if let Some(y) = local_y_position(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Grass;
|
||||
within_heightmap = true;
|
||||
}
|
||||
} else if let Some(river_fill_height) = river_fill_height {
|
||||
//Place water
|
||||
for y in 0..local_height(river_fill_height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Water;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//Place stone
|
||||
for y in 0..local_height(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Stone;
|
||||
within_heightmap = true;
|
||||
}
|
||||
//Place dirt
|
||||
if let Some(y) = local_y_position(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Dirt;
|
||||
within_heightmap = true;
|
||||
}
|
||||
} else {
|
||||
//Place stone
|
||||
for y in 0..local_height(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Stone;
|
||||
within_heightmap = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Carve out caves
|
||||
if within_heightmap {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
for y in 0..CHUNK_SIZE {
|
||||
for x in 0..CHUNK_SIZE {
|
||||
if blocks[x][y][z] != Block::Stone { continue }
|
||||
|
||||
let cave_size = ((offset.y + y as i32) as f32 / -100.).clamp(0., 1.);
|
||||
let inv_cave_size = 1. - cave_size;
|
||||
if cave_size < 0.1 { continue }
|
||||
|
||||
let position = ivec3(x as i32, y as i32, z as i32) + offset;
|
||||
|
||||
let is_cave = || {
|
||||
let raw_cavemap_value_a = cave_noise_a.get_noise3d(position.x as f32, position.y as f32, position.z as f32);
|
||||
let raw_cavemap_value_b = cave_noise_b.get_noise3d(position.x as f32, position.y as f32, position.z as f32);
|
||||
((cave_size * -0.15)..=(cave_size * 0.15)).contains(&raw_cavemap_value_a) &&
|
||||
((cave_size * -0.15)..=(cave_size * 0.15)).contains(&raw_cavemap_value_b)
|
||||
};
|
||||
let is_hole_cave = || {
|
||||
let raw_cavemap_value_holes = cave_noise_holes.get_noise3d(position.x as f32, position.y as f32, position.z as f32);
|
||||
((0.9 + (0.1 * inv_cave_size))..=1.0).contains(&raw_cavemap_value_holes.abs())
|
||||
};
|
||||
|
||||
if is_cave() || is_hole_cave() {
|
||||
blocks[x][y][z] = Block::Air;
|
||||
if deco_heightmap[x][z] == Some(y as i32 + offset.y) {
|
||||
deco_heightmap[x][z] = None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Add decorations
|
||||
for x in 0..CHUNK_SIZE {
|
||||
for z in 0..CHUNK_SIZE {
|
||||
//get height
|
||||
let Some(height) = deco_heightmap[x][z] else { continue };
|
||||
//check for air
|
||||
// if blocks[x][local_y][z] == Block::Air {
|
||||
// continue
|
||||
// }
|
||||
//place tall grass
|
||||
if rng_map_a[x][z] < 0.03 {
|
||||
if let Some(y) = local_y_position(height + 1, chunk_position) {
|
||||
blocks[x][y][z] = Block::TallGrass;
|
||||
}
|
||||
}
|
||||
//place trees!
|
||||
if rng_map_a[x][z] < 0.001 {
|
||||
//Replace grass with dirt under the tree
|
||||
if let Some(y) = local_y_position(height, chunk_position) {
|
||||
blocks[x][y][z] = Block::Dirt;
|
||||
}
|
||||
|
||||
//Place wood (no smart_place needed here!)
|
||||
let tree_height = 4 + (rng_map_b[x][z] * 3.).round() as i32;
|
||||
for tree_y in 0..tree_height {
|
||||
if let Some(y) = local_y_position(height + 1 + tree_y, chunk_position) {
|
||||
blocks[x][y][z] = Block::Wood;
|
||||
}
|
||||
}
|
||||
|
||||
let tree_height = 4 + (rng_map_b[x][z] * 3.).round() as i32;
|
||||
|
||||
//Place leaf blocks
|
||||
if let Some(y) = local_y_position(height + 1, chunk_position) {
|
||||
let tree_pos = ivec3(x as i32, y as i32, z as i32);
|
||||
// Place wood (smart_place)
|
||||
// for tree_y in 0..tree_height {
|
||||
// smart_place(&mut blocks, tree_pos + tree_y * IVec3::Y, Block::Wood);
|
||||
// }
|
||||
// Part that wraps around the tree
|
||||
{
|
||||
let tree_leaf_height = tree_height - 3;
|
||||
let leaf_width = 2;
|
||||
for tree_y in tree_leaf_height..tree_height {
|
||||
for tree_x in (-leaf_width)..=leaf_width {
|
||||
for tree_z in (-leaf_width)..=leaf_width {
|
||||
let tree_offset = ivec3(tree_x, tree_y, tree_z);
|
||||
if tree_offset.xz() == IVec2::ZERO { continue }
|
||||
smart_place(&mut blocks, tree_pos + tree_offset, Block::Leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//part above the tree
|
||||
{
|
||||
let leaf_above_height = 2;
|
||||
let leaf_width = 1;
|
||||
for tree_y in tree_height..(tree_height + leaf_above_height) {
|
||||
for tree_x in (-leaf_width)..=leaf_width {
|
||||
for tree_z in (-leaf_width)..=leaf_width {
|
||||
let tree_offset = ivec3(tree_x, tree_y, tree_z);
|
||||
smart_place(&mut blocks, tree_pos + tree_offset, Block::Leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(blocks, queue)
|
||||
|
||||
// let mut cave_noise = FastNoise::seeded(seed);
|
||||
// cave_noise.set_fractal_type(FractalType::FBM);
|
||||
// cave_noise.set_frequency(0.1);
|
||||
|
||||
// let mut dirt_noise = FastNoise::seeded(seed.rotate_left(1));
|
||||
// dirt_noise.set_fractal_type(FractalType::FBM);
|
||||
// dirt_noise.set_frequency(0.1);
|
||||
|
||||
//
|
||||
|
||||
// if chunk_position.y >= 0 {
|
||||
// if chunk_position.y == 0 {
|
||||
// for x in 0..CHUNK_SIZE {
|
||||
// for z in 0..CHUNK_SIZE {
|
||||
// blocks[x][0][z] = Block::Dirt;
|
||||
// blocks[x][1][z] = Block::Grass;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// for x in 0..CHUNK_SIZE {
|
||||
// for y in 0..CHUNK_SIZE {
|
||||
// for z in 0..CHUNK_SIZE {
|
||||
// let position = ivec3(x as i32, y as i32, z as i32) + offset;
|
||||
// let v_cave_noise = cave_noise.get_noise3d(position.x as f32, position.y as f32, position.z as f32) * (-position.y as f32 - 10.0).clamp(0., 1.);
|
||||
// let v_dirt_noise = dirt_noise.get_noise3d(position.x as f32, position.y as f32, position.z as f32) * (-position.y as f32).clamp(0., 1.);
|
||||
// if v_cave_noise > 0.5 {
|
||||
// blocks[x][y][z] = Block::Stone;
|
||||
// } else if v_dirt_noise > 0.5 {
|
||||
// blocks[x][y][z] = Block::Dirt;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// blocks
|
||||
|
||||
}
|
||||
|
|
|
@ -1,16 +0,0 @@
|
|||
#created as a workaround for rust-analyzer dependency cycle (which should be allowed)
|
||||
|
||||
[package]
|
||||
name = "kubi-ui-examples"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dev-dependencies]
|
||||
kubi-ui = { path = "../kubi-ui" }
|
||||
kubi-ui-glium = { path = "../kubi-ui-glium" }
|
||||
kubi-logging = { path = "../kubi-logging" }
|
||||
glium = { git = "https://github.com/glium/glium", rev = "a352c667" }
|
||||
winit = "0.29"
|
||||
glam = "0.25"
|
||||
log = "0.4"
|
|
@ -1,111 +0,0 @@
|
|||
use std::time::Instant;
|
||||
use glam::{UVec2, vec4};
|
||||
use glium::{backend::glutin::SimpleWindowBuilder, Surface};
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{EventLoopBuilder, ControlFlow}
|
||||
};
|
||||
use kubi_ui::{
|
||||
KubiUi,
|
||||
element::{
|
||||
progress_bar::ProgressBar,
|
||||
container::{Container, Sides, Alignment},
|
||||
text::Text
|
||||
},
|
||||
UiSize,
|
||||
elements,
|
||||
};
|
||||
use kubi_ui_glium::GliumUiRenderer;
|
||||
|
||||
fn main() {
|
||||
kubi_logging::init();
|
||||
|
||||
let event_loop = EventLoopBuilder::new().build().unwrap();
|
||||
let (window, display) = SimpleWindowBuilder::new().build(&event_loop);
|
||||
window.set_title("Mom Downloader 2000");
|
||||
|
||||
let mut kui = KubiUi::new();
|
||||
let mut backend = GliumUiRenderer::new(&display);
|
||||
|
||||
let font_handle = kui.add_font_from_bytes(include_bytes!("../../assets/fonts/roboto/Roboto-Regular.ttf"));
|
||||
|
||||
let instant = Instant::now();
|
||||
|
||||
event_loop.run(|event, window_target| {
|
||||
window_target.set_control_flow(ControlFlow::Poll);
|
||||
match event {
|
||||
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
||||
window_target.exit();
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
let mut frame = display.draw();
|
||||
frame.clear_color_srgb(0., 0., 0., 1.);
|
||||
|
||||
let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2();
|
||||
|
||||
kui.begin();
|
||||
|
||||
let mom_ratio = (instant.elapsed().as_secs_f32() / 60.).powf(0.5);
|
||||
|
||||
kui.add(Container {
|
||||
align: (Alignment::Center, Alignment::Center),
|
||||
size: (UiSize::Percentage(1.), UiSize::Percentage(1.)),
|
||||
background: Some(vec4(0.1, 0.1, 0.1, 1.)),
|
||||
elements: vec![Box::new(Container {
|
||||
gap: 5.,
|
||||
padding: Sides::all(10.),
|
||||
align: (Alignment::Begin, Alignment::Begin),
|
||||
size: (UiSize::Pixels(450.), UiSize::Auto),
|
||||
background: Some(vec4(0.2, 0.2, 0.5, 1.)),
|
||||
elements: elements(|el| {
|
||||
if instant.elapsed().as_secs_f32() < 5. {
|
||||
el.add(Text {
|
||||
text: "Downloading your mom...".into(),
|
||||
font: font_handle,
|
||||
text_size: 32,
|
||||
..Default::default()
|
||||
});
|
||||
el.add(ProgressBar {
|
||||
value: mom_ratio,
|
||||
..Default::default()
|
||||
});
|
||||
el.add(Text {
|
||||
text: format!("{:.2}% ({:.1} GB)", mom_ratio * 100., mom_ratio * 10000.).into(),
|
||||
font: font_handle,
|
||||
text_size: 24,
|
||||
..Default::default()
|
||||
});
|
||||
} else if instant.elapsed().as_secs() < 10 {
|
||||
el.add(Text {
|
||||
text: "Error 413 Request Entity Too Large".into(),
|
||||
font: font_handle,
|
||||
color: vec4(1., 0.125, 0.125, 1.),
|
||||
text_size: 26,
|
||||
..Default::default()
|
||||
});
|
||||
el.add(Text {
|
||||
text: format!("Exiting in {}...", 10 - instant.elapsed().as_secs()).into(),
|
||||
font: font_handle,
|
||||
text_size: 24,
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
window_target.exit();
|
||||
}
|
||||
}),
|
||||
..Default::default()
|
||||
})],
|
||||
..Default::default()
|
||||
}, resolution);
|
||||
|
||||
kui.end();
|
||||
|
||||
backend.update(&kui);
|
||||
backend.draw(&mut frame, resolution);
|
||||
|
||||
frame.finish().unwrap();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
|
@ -1,90 +0,0 @@
|
|||
use std::time::Instant;
|
||||
use glam::{Vec2, IVec2, UVec2};
|
||||
use glium::{backend::glutin::SimpleWindowBuilder, Surface};
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{EventLoopBuilder, ControlFlow}
|
||||
};
|
||||
use kubi_ui::{
|
||||
KubiUi,
|
||||
element::{
|
||||
UiElement,
|
||||
progress_bar::ProgressBar,
|
||||
container::{Container, Sides}
|
||||
},
|
||||
UiSize
|
||||
};
|
||||
use kubi_ui_glium::GliumUiRenderer;
|
||||
|
||||
fn main() {
|
||||
kubi_logging::init();
|
||||
|
||||
let event_loop = EventLoopBuilder::new().build().unwrap();
|
||||
let (window, display) = SimpleWindowBuilder::new().build(&event_loop);
|
||||
|
||||
let mut kui = KubiUi::new();
|
||||
let mut backend = GliumUiRenderer::new(&display);
|
||||
|
||||
let instant = Instant::now();
|
||||
let mut pcnt = 0;
|
||||
event_loop.run(|event, window_target| {
|
||||
window_target.set_control_flow(ControlFlow::Poll);
|
||||
match event {
|
||||
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
||||
window_target.exit();
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
let mut frame = display.draw();
|
||||
frame.clear_color_srgb(0.5, 0.5, 0.5, 0.);
|
||||
|
||||
let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2();
|
||||
|
||||
kui.begin();
|
||||
|
||||
kui.add(Container {
|
||||
gap: 5.,
|
||||
padding: Sides::all(5.),
|
||||
elements: vec![
|
||||
Box::new(ProgressBar {
|
||||
value: 0.5,
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(ProgressBar {
|
||||
value: instant.elapsed().as_secs_f32().sin().powi(2),
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(Container {
|
||||
gap: 1.,
|
||||
elements: {
|
||||
let mut elements: Vec<Box<dyn UiElement>> = vec![];
|
||||
let cnt = instant.elapsed().as_secs() * 10000;
|
||||
if pcnt != cnt {
|
||||
log::info!("{cnt}");
|
||||
pcnt = cnt;
|
||||
}
|
||||
for i in 0..cnt {
|
||||
elements.push(Box::new(ProgressBar {
|
||||
value: (instant.elapsed().as_secs_f32() + (i as f32 / 10.)).sin().powi(2),
|
||||
size: (UiSize::Auto, UiSize::Pixels(5.)),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
elements
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
],
|
||||
..Default::default()
|
||||
}, resolution);
|
||||
|
||||
kui.end();
|
||||
|
||||
backend.update(&kui);
|
||||
backend.draw(&mut frame, resolution);
|
||||
|
||||
frame.finish().unwrap();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
|
@ -1,146 +0,0 @@
|
|||
use std::time::Instant;
|
||||
use glam::{UVec2, vec4};
|
||||
use glium::{backend::glutin::SimpleWindowBuilder, Surface};
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{EventLoopBuilder, ControlFlow}
|
||||
};
|
||||
use kubi_ui::{
|
||||
KubiUi,
|
||||
element::{
|
||||
UiElement,
|
||||
progress_bar::ProgressBar,
|
||||
container::{Container, Sides, Alignment},
|
||||
rect::Rect
|
||||
},
|
||||
interaction::IntoInteractable,
|
||||
UiSize,
|
||||
UiDirection, IfModified,
|
||||
};
|
||||
use kubi_ui_glium::GliumUiRenderer;
|
||||
|
||||
fn main() {
|
||||
kubi_logging::init();
|
||||
|
||||
let event_loop = EventLoopBuilder::new().build().unwrap();
|
||||
let (window, display) = SimpleWindowBuilder::new().build(&event_loop);
|
||||
|
||||
let mut kui = KubiUi::new();
|
||||
let mut backend = GliumUiRenderer::new(&display);
|
||||
|
||||
let instant = Instant::now();
|
||||
event_loop.run(|event, window_target| {
|
||||
window_target.set_control_flow(ControlFlow::Poll);
|
||||
match event {
|
||||
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
||||
window_target.exit();
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
let mut frame = display.draw();
|
||||
frame.clear_color_srgb(0.5, 0.5, 0.5, 0.);
|
||||
|
||||
let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2();
|
||||
|
||||
kui.begin();
|
||||
|
||||
let z = instant.elapsed().as_secs_f32().sin().powi(2);
|
||||
|
||||
kui.add(Container {
|
||||
gap: 5.,
|
||||
padding: Sides::all(5.),
|
||||
align: (Alignment::Begin, Alignment::Center),
|
||||
size: (UiSize::Percentage(1.), UiSize::Percentage(1.)),
|
||||
elements: vec![
|
||||
Box::new(ProgressBar {
|
||||
value: 0.5,
|
||||
..Default::default()
|
||||
}),
|
||||
],
|
||||
..Default::default()
|
||||
}, resolution);
|
||||
|
||||
kui.add(Container {
|
||||
gap: 5.,
|
||||
padding: Sides::all(5.),
|
||||
align: (Alignment::End, Alignment::Center),
|
||||
size: (UiSize::Percentage(1.), UiSize::Percentage(1.)),
|
||||
elements: vec![
|
||||
Box::new(ProgressBar {
|
||||
value: z,
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(Container {
|
||||
size: (UiSize::Percentage(1.), UiSize::Auto),
|
||||
align: (Alignment::Center, Alignment::End),
|
||||
padding: Sides::all(5.),
|
||||
gap: 10.,
|
||||
elements: vec![
|
||||
Box::new(Rect {
|
||||
size: (UiSize::Percentage(0.5), UiSize::Pixels(30.)),
|
||||
color: Some(vec4(0.75, 0., 0., 1.))
|
||||
}),
|
||||
Box::new(Rect {
|
||||
size: (UiSize::Percentage(z / 2. + 0.5), UiSize::Pixels(30.)),
|
||||
color: Some(vec4(0., 0.75, 0., 1.))
|
||||
}),
|
||||
],
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(Rect {
|
||||
size: (UiSize::Percentage(z / 2. + 0.5), UiSize::Pixels(30.)),
|
||||
color: Some(vec4(0., 0.75, 0., 1.))
|
||||
}),
|
||||
Box::new(Container {
|
||||
gap: 5.,
|
||||
padding: Sides::all(5.),
|
||||
background: Some(vec4(0., 0., 0., 0.5)),
|
||||
direction: UiDirection::Horizontal,
|
||||
elements: {
|
||||
let mut x: Vec<Box<dyn UiElement>> = vec![];
|
||||
for i in 0..10 {
|
||||
x.push(Box::new(Rect {
|
||||
size: (UiSize::Pixels(50.), UiSize::Pixels(50.)),
|
||||
color: if i == 1 {
|
||||
Some(vec4(0.75, 0.75, 0.75, 0.75))
|
||||
} else {
|
||||
Some(vec4(0.5, 0.5, 0.5, 0.75))
|
||||
}
|
||||
}));
|
||||
}
|
||||
x
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
Box::new(Container {
|
||||
background: Some(vec4(1., 0., 0., 1.)),
|
||||
padding: Sides {
|
||||
top: 10.,
|
||||
bottom: 20.,
|
||||
left: 30.,
|
||||
right: 40.,
|
||||
},
|
||||
elements: vec![
|
||||
Box::new(Rect {
|
||||
size: (UiSize::Pixels(50.), UiSize::Pixels(50.)),
|
||||
color: Some(vec4(1., 1., 1., 0.75))
|
||||
}.into_interactable().on_click(|| {
|
||||
println!("clicked");
|
||||
}))
|
||||
],
|
||||
..Default::default()
|
||||
})
|
||||
],
|
||||
..Default::default()
|
||||
}, resolution);
|
||||
|
||||
kui.end();
|
||||
|
||||
backend.update(&kui);
|
||||
backend.draw(&mut frame, resolution);
|
||||
|
||||
frame.finish().unwrap();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
|
@ -1,116 +0,0 @@
|
|||
use std::{time::Instant, vec};
|
||||
use glam::{UVec2, vec4};
|
||||
use glium::{backend::glutin::SimpleWindowBuilder, Surface};
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::{EventLoopBuilder, ControlFlow}
|
||||
};
|
||||
use kubi_ui::{
|
||||
KubiUi,
|
||||
element::{
|
||||
progress_bar::ProgressBar,
|
||||
container::{Container, Sides, Alignment},
|
||||
text::Text, rect::Rect, spacer::Spacer
|
||||
},
|
||||
UiSize,
|
||||
elements,
|
||||
};
|
||||
use kubi_ui_glium::GliumUiRenderer;
|
||||
|
||||
fn main() {
|
||||
kubi_logging::init();
|
||||
|
||||
let event_loop = EventLoopBuilder::new().build().unwrap();
|
||||
let (window, display) = SimpleWindowBuilder::new().build(&event_loop);
|
||||
window.set_title("Text rendering test");
|
||||
|
||||
let mut kui = KubiUi::new();
|
||||
let mut backend = GliumUiRenderer::new(&display);
|
||||
|
||||
let font_handle = kui.add_font_from_bytes(include_bytes!("../../assets/fonts/roboto/Roboto-Regular.ttf"));
|
||||
let instant = Instant::now();
|
||||
|
||||
event_loop.run(|event, window_target| {
|
||||
window_target.set_control_flow(ControlFlow::Poll);
|
||||
match event {
|
||||
Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => {
|
||||
window_target.exit();
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
let mut frame = display.draw();
|
||||
frame.clear_color_srgb(0., 0., 0., 1.);
|
||||
|
||||
let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2();
|
||||
|
||||
kui.begin();
|
||||
|
||||
kui.add(Container {
|
||||
size: (UiSize::Percentage(1.), UiSize::Percentage(1.)),
|
||||
background: Some(vec4(0.1, 0.1, 0.1, 1.)),
|
||||
elements: elements(|elem| {
|
||||
elem.add(Text {
|
||||
text: "THIS LINE SHOULD BE SHARP!".into(),
|
||||
..Default::default()
|
||||
});
|
||||
elem.add(Text {
|
||||
text: "THIS LINE SHOULD BE SHARP!".into(),
|
||||
text_size: 32,
|
||||
..Default::default()
|
||||
});
|
||||
elem.add(Text {
|
||||
text: "All lines except 3 and 6 below will be blurry:".into(),
|
||||
..Default::default()
|
||||
});
|
||||
for size in [9, 12, 16, 18, 24, 32] {
|
||||
elem.add(Text {
|
||||
text: "Testing default font, Proggy Tiny".into(),
|
||||
text_size: size,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
elem.add(Rect {
|
||||
size: (UiSize::Percentage(1.), UiSize::Pixels(10.)),
|
||||
color: Some(vec4(0., 0., 1., 1.)),
|
||||
});
|
||||
elem.add(Rect {
|
||||
size: (UiSize::Percentage(1.), UiSize::Pixels(10.)),
|
||||
color: Some(vec4(1., 1., 0., 1.)),
|
||||
});
|
||||
elem.add(Text {
|
||||
text: "Hello, world!\nżółty liść. życie nie ma sensu i wszyscy zginemy;\nтест кирилиці їїїїїїїїїїї\njapanese text: テスト".into(),
|
||||
font: font_handle,
|
||||
text_size: 32,
|
||||
..Default::default()
|
||||
});
|
||||
if instant.elapsed().as_secs() & 1 != 0 {
|
||||
elem.add(Rect {
|
||||
size: (UiSize::Percentage(1.), UiSize::Pixels(10.)),
|
||||
color: Some(vec4(1., 0., 0., 1.)),
|
||||
});
|
||||
elem.add(Rect {
|
||||
size: (UiSize::Percentage(1.), UiSize::Pixels(10.)),
|
||||
color: Some(vec4(0., 0., 0., 1.)),
|
||||
});
|
||||
elem.add(Spacer(100.));
|
||||
elem.add(Text {
|
||||
text: "FLAG SHOULD NOT OVERLAP WITH TEXT".into(),
|
||||
text_size: 64,
|
||||
color: vec4(1., 0., 1., 1.),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}),
|
||||
..Default::default()
|
||||
}, resolution);
|
||||
|
||||
kui.end();
|
||||
|
||||
backend.update(&kui);
|
||||
backend.draw(&mut frame, resolution);
|
||||
|
||||
frame.finish().unwrap();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
[package]
|
||||
name = "kubi-ui-glium"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
kubi-ui = { path = "../kubi-ui", default-features = false }
|
||||
#kubi-ui = { path = "../kubi-ui" }
|
||||
glium = { git = "https://github.com/glium/glium", rev = "a352c667" }
|
||||
glam = "0.25"
|
||||
log = "0.4"
|
|
@ -1,12 +0,0 @@
|
|||
#version 300 es
|
||||
|
||||
precision highp float;
|
||||
precision highp sampler2D;
|
||||
|
||||
out vec4 out_color;
|
||||
in vec4 vtx_color;
|
||||
in vec2 vtx_uv;
|
||||
|
||||
void main() {
|
||||
out_color = vtx_color;
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
#version 300 es
|
||||
|
||||
precision highp float;
|
||||
precision highp sampler2D;
|
||||
|
||||
out vec4 out_color;
|
||||
in vec4 vtx_color;
|
||||
in vec2 vtx_uv;
|
||||
uniform sampler2D tex;
|
||||
|
||||
void main() {
|
||||
out_color = texture(tex, vtx_uv) * vtx_color;
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
#version 300 es
|
||||
|
||||
precision highp float;
|
||||
|
||||
uniform vec2 resolution;
|
||||
in vec2 uv;
|
||||
in vec4 color;
|
||||
in vec2 position;
|
||||
out vec4 vtx_color;
|
||||
out vec2 vtx_uv;
|
||||
|
||||
void main() {
|
||||
vtx_color = color;
|
||||
vtx_uv = uv;
|
||||
vec2 pos2d = (vec2(2., -2.) * (position / resolution)) + vec2(-1, 1);
|
||||
gl_Position = vec4(pos2d, 0., 1.);
|
||||
}
|
|
@ -1,229 +0,0 @@
|
|||
use std::rc::Rc;
|
||||
use glam::Vec2;
|
||||
use glium::{
|
||||
Surface, DrawParameters, Blend,
|
||||
Program, VertexBuffer, IndexBuffer,
|
||||
backend::{Facade, Context},
|
||||
texture::{SrgbTexture2d, RawImage2d},
|
||||
index::PrimitiveType,
|
||||
implement_vertex,
|
||||
uniform, uniforms::{Sampler, SamplerBehavior, SamplerWrapFunction},
|
||||
};
|
||||
use kubi_ui::{
|
||||
KubiUi,
|
||||
draw::{UiDrawPlan, UiVertex, BindTexture},
|
||||
text::FontTextureInfo, IfModified,
|
||||
};
|
||||
|
||||
const VERTEX_SHADER: &str = include_str!("../shaders/vertex.vert");
|
||||
const FRAGMENT_SHADER: &str = include_str!("../shaders/fragment.frag");
|
||||
const FRAGMENT_SHADER_TEX: &str = include_str!("../shaders/fragment_tex.frag");
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[repr(C)]
|
||||
struct Vertex {
|
||||
position: [f32; 2],
|
||||
color: [f32; 4],
|
||||
uv: [f32; 2],
|
||||
}
|
||||
|
||||
impl From<UiVertex> for Vertex {
|
||||
fn from(v: UiVertex) -> Self {
|
||||
Self {
|
||||
position: v.position.to_array(),
|
||||
color: v.color.to_array(),
|
||||
uv: v.uv.to_array(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
implement_vertex!(Vertex, position, color, uv);
|
||||
|
||||
struct BufferPair {
|
||||
pub vertex_buffer: glium::VertexBuffer<Vertex>,
|
||||
pub index_buffer: glium::IndexBuffer<u32>,
|
||||
pub vertex_count: usize,
|
||||
pub index_count: usize,
|
||||
}
|
||||
|
||||
impl BufferPair {
|
||||
pub fn new<F: Facade>(facade: &F) -> Self {
|
||||
log::debug!("init ui buffers...");
|
||||
Self {
|
||||
vertex_buffer: VertexBuffer::empty_dynamic(facade, 1024).unwrap(),
|
||||
index_buffer: IndexBuffer::empty_dynamic(facade, PrimitiveType::TrianglesList, 1024).unwrap(),
|
||||
vertex_count: 0,
|
||||
index_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure_buffer_size(&mut self, need_vtx: usize, need_idx: usize) {
|
||||
let current_vtx_size = self.vertex_buffer.get_size() / std::mem::size_of::<Vertex>();
|
||||
let current_idx_size = self.index_buffer.get_size() / std::mem::size_of::<u32>();
|
||||
//log::debug!("current vtx size: {}, current idx size: {}", current_vtx_size, current_idx_size);
|
||||
if current_vtx_size >= need_vtx && current_idx_size >= need_idx {
|
||||
return
|
||||
}
|
||||
let new_vtx_size = (need_vtx + 1).next_power_of_two();
|
||||
let new_idx_size = (need_idx + 1).next_power_of_two();
|
||||
log::debug!("resizing buffers: vtx {} -> {}, idx {} -> {}", current_vtx_size, new_vtx_size, current_idx_size, new_idx_size);
|
||||
if current_vtx_size != new_vtx_size {
|
||||
self.vertex_buffer = VertexBuffer::empty_dynamic(
|
||||
self.vertex_buffer.get_context(),
|
||||
new_vtx_size
|
||||
).unwrap();
|
||||
}
|
||||
if current_idx_size != new_idx_size {
|
||||
self.index_buffer = IndexBuffer::empty_dynamic(
|
||||
self.index_buffer.get_context(),
|
||||
PrimitiveType::TrianglesList,
|
||||
new_idx_size
|
||||
).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_data(&mut self, vtx: &[Vertex], idx: &[u32]) {
|
||||
//log::trace!("uploading {} vertices and {} indices", vtx.len(), idx.len());
|
||||
|
||||
self.vertex_count = vtx.len();
|
||||
self.index_count = idx.len();
|
||||
|
||||
self.vertex_buffer.invalidate();
|
||||
self.index_buffer.invalidate();
|
||||
|
||||
if self.vertex_count == 0 || self.index_count == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
self.ensure_buffer_size(self.vertex_count, self.index_count);
|
||||
|
||||
self.vertex_buffer.slice_mut(0..self.vertex_count).unwrap().write(vtx);
|
||||
self.index_buffer.slice_mut(0..self.index_count).unwrap().write(idx);
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.vertex_count == 0 || self.index_count == 0
|
||||
}
|
||||
}
|
||||
|
||||
struct GlDrawCall {
|
||||
active: bool,
|
||||
buffer: BufferPair,
|
||||
bind_texture: Option<Rc<SrgbTexture2d>>,
|
||||
}
|
||||
|
||||
pub struct GliumUiRenderer {
|
||||
context: Rc<Context>,
|
||||
program: glium::Program,
|
||||
program_tex: glium::Program,
|
||||
font_texture: Option<Rc<SrgbTexture2d>>,
|
||||
plan: Vec<GlDrawCall>,
|
||||
}
|
||||
|
||||
impl GliumUiRenderer {
|
||||
pub fn new<F: Facade>(facade: &F) -> Self {
|
||||
log::info!("init glium backend for kui");
|
||||
Self {
|
||||
program: Program::from_source(facade, VERTEX_SHADER, FRAGMENT_SHADER, None).unwrap(),
|
||||
program_tex: Program::from_source(facade, VERTEX_SHADER, FRAGMENT_SHADER_TEX, None).unwrap(),
|
||||
context: Rc::clone(facade.get_context()),
|
||||
font_texture: None,
|
||||
plan: vec![]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_draw_plan(&mut self, plan: &UiDrawPlan) {
|
||||
if plan.calls.len() > self.plan.len() {
|
||||
self.plan.resize_with(plan.calls.len(), || {
|
||||
GlDrawCall {
|
||||
buffer: BufferPair::new(&self.context),
|
||||
bind_texture: None,
|
||||
active: false,
|
||||
}
|
||||
});
|
||||
} else {
|
||||
for step in &mut self.plan[plan.calls.len()..] {
|
||||
step.active = false;
|
||||
}
|
||||
}
|
||||
for (idx, call) in plan.calls.iter().enumerate() {
|
||||
let data_vtx = &call.vertices.iter().copied().map(Vertex::from).collect::<Vec<_>>()[..];
|
||||
let data_idx = &call.indices[..];
|
||||
self.plan[idx].active = true;
|
||||
self.plan[idx].buffer.write_data(data_vtx, data_idx);
|
||||
self.plan[idx].bind_texture = match call.bind_texture {
|
||||
Some(BindTexture::FontTexture) => {
|
||||
const NO_FNT_TEX: &str = "Font texture exists in draw plan but not yet inited. Make sure to call update_font_texture() *before* update_draw_plan()";
|
||||
Some(Rc::clone(self.font_texture.as_ref().expect(NO_FNT_TEX)))
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_font_texture(&mut self, font_texture: &FontTextureInfo) {
|
||||
log::debug!("updating font texture");
|
||||
self.font_texture = Some(Rc::new(SrgbTexture2d::new(
|
||||
&self.context,
|
||||
RawImage2d::from_raw_rgba(
|
||||
font_texture.data.to_owned(),
|
||||
(font_texture.size.x, font_texture.size.y)
|
||||
)
|
||||
).unwrap()));
|
||||
}
|
||||
|
||||
pub fn update(&mut self, kui: &KubiUi) {
|
||||
if let Some(texture) = kui.font_texture().if_modified() {
|
||||
self.update_font_texture(texture);
|
||||
}
|
||||
if let Some(plan) = kui.draw_plan().if_modified() {
|
||||
self.update_draw_plan(plan);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw(&self, frame: &mut glium::Frame, resolution: Vec2) {
|
||||
let params = DrawParameters {
|
||||
blend: Blend::alpha_blending(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for step in &self.plan {
|
||||
if !step.active {
|
||||
continue
|
||||
}
|
||||
|
||||
if step.buffer.is_empty() {
|
||||
continue
|
||||
}
|
||||
|
||||
let vtx_buffer = step.buffer.vertex_buffer.slice(0..step.buffer.vertex_count).unwrap();
|
||||
let idx_buffer = step.buffer.index_buffer.slice(0..step.buffer.index_count).unwrap();
|
||||
|
||||
if let Some(bind_texture) = step.bind_texture.as_ref() {
|
||||
frame.draw(
|
||||
vtx_buffer,
|
||||
idx_buffer,
|
||||
&self.program_tex,
|
||||
&uniform! {
|
||||
resolution: resolution.to_array(),
|
||||
tex: Sampler(bind_texture.as_ref(), SamplerBehavior {
|
||||
wrap_function: (SamplerWrapFunction::Clamp, SamplerWrapFunction::Clamp, SamplerWrapFunction::Clamp),
|
||||
..Default::default()
|
||||
}),
|
||||
},
|
||||
¶ms,
|
||||
).unwrap();
|
||||
} else {
|
||||
frame.draw(
|
||||
vtx_buffer,
|
||||
idx_buffer,
|
||||
&self.program,
|
||||
&uniform! {
|
||||
resolution: resolution.to_array(),
|
||||
},
|
||||
¶ms,
|
||||
).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
[package]
|
||||
name = "kubi-ui"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
hashbrown = "0.14"
|
||||
nohash-hasher = "0.2"
|
||||
glam = "0.25"
|
||||
fontdue = "0.8"
|
||||
rect_packer = "0.2"
|
||||
log = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["builtin_elements", "builtin_font"]
|
||||
builtin_font = []
|
||||
builtin_elements = []
|
||||
#parallel = ["dep:rayon", "fontdue/parallel"]
|
|
@ -1,7 +0,0 @@
|
|||
Copyright (c) 2004, 2005 Tristan Grimmer
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
Binary file not shown.
|
@ -1,220 +0,0 @@
|
|||
use crate::{IfModified, text::{TextRenderer, FontHandle}};
|
||||
|
||||
use std::borrow::Cow;
|
||||
use fontdue::layout::{Layout, CoordinateSystem, TextStyle};
|
||||
use glam::{Vec2, Vec4, vec2};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiDrawCommand {
|
||||
///Filled, colored rectangle
|
||||
Rectangle {
|
||||
///Position in pixels
|
||||
position: Vec2,
|
||||
///Size in pixels
|
||||
size: Vec2,
|
||||
///Color (RGBA)
|
||||
color: Vec4,
|
||||
},
|
||||
Text {
|
||||
///Position in pixels
|
||||
position: Vec2,
|
||||
///Font size
|
||||
size: u8,
|
||||
///Color (RGBA)
|
||||
color: Vec4,
|
||||
///Text to draw
|
||||
text: Cow<'static, str>,
|
||||
///Font handle to use
|
||||
font: FontHandle,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UiDrawCommands {
|
||||
pub commands: Vec<UiDrawCommand>,
|
||||
}
|
||||
|
||||
impl UiDrawCommands {
|
||||
pub fn add(&mut self, command: UiDrawCommand) {
|
||||
self.commands.push(command);
|
||||
}
|
||||
}
|
||||
|
||||
// impl UiDrawCommands {
|
||||
// pub fn compare(&self, other: &Self) -> bool {
|
||||
// // if self.commands.len() != other.commands.len() { return false }
|
||||
// // self.commands.iter().zip(other.commands.iter()).all(|(a, b)| a == b)
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BindTexture {
|
||||
FontTexture,
|
||||
//UserDefined(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct UiVertex {
|
||||
pub position: Vec2,
|
||||
pub color: Vec4,
|
||||
pub uv: Vec2,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UiDrawCall {
|
||||
pub vertices: Vec<UiVertex>,
|
||||
pub indices: Vec<u32>,
|
||||
pub bind_texture: Option<BindTexture>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UiDrawPlan {
|
||||
pub calls: Vec<UiDrawCall>
|
||||
}
|
||||
|
||||
struct CallSwapper {
|
||||
calls: Vec<UiDrawCall>,
|
||||
call: UiDrawCall,
|
||||
}
|
||||
|
||||
impl CallSwapper {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
calls: vec![],
|
||||
call: UiDrawCall::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current(&self) -> &UiDrawCall {
|
||||
&self.call
|
||||
}
|
||||
|
||||
pub fn current_mut(&mut self) -> &mut UiDrawCall {
|
||||
&mut self.call
|
||||
}
|
||||
|
||||
pub fn swap(&mut self) {
|
||||
self.calls.push(std::mem::replace(&mut self.call, UiDrawCall::default()));
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Vec<UiDrawCall> {
|
||||
self.calls.push(self.call);
|
||||
self.calls
|
||||
}
|
||||
}
|
||||
|
||||
impl UiDrawPlan {
|
||||
pub fn build(draw_commands: &UiDrawCommands, tr: &mut TextRenderer) -> Self {
|
||||
let mut swapper = CallSwapper::new();
|
||||
let mut prev_command = None;
|
||||
for command in &draw_commands.commands {
|
||||
|
||||
let do_swap = if let Some(prev_command) = prev_command {
|
||||
std::mem::discriminant(prev_command) != std::mem::discriminant(command)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if do_swap {
|
||||
swapper.swap();
|
||||
}
|
||||
|
||||
if do_swap || prev_command.is_none() {
|
||||
match command {
|
||||
UiDrawCommand::Rectangle { .. } => (),
|
||||
UiDrawCommand::Text { .. } => {
|
||||
swapper.current_mut().bind_texture = Some(BindTexture::FontTexture);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match command {
|
||||
UiDrawCommand::Rectangle { position, size, color } => {
|
||||
let vidx = swapper.current().vertices.len() as u32;
|
||||
swapper.current_mut().indices.extend([vidx, vidx + 1, vidx + 2, vidx, vidx + 2, vidx + 3]);
|
||||
swapper.current_mut().vertices.extend([
|
||||
UiVertex {
|
||||
position: *position,
|
||||
color: *color,
|
||||
uv: vec2(0.0, 0.0),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + vec2(size.x, 0.0),
|
||||
color: *color,
|
||||
uv: vec2(1.0, 0.0),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + *size,
|
||||
color: *color,
|
||||
uv: vec2(1.0, 1.0),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + vec2(0.0, size.y),
|
||||
color: *color,
|
||||
uv: vec2(0.0, 1.0),
|
||||
},
|
||||
]);
|
||||
},
|
||||
UiDrawCommand::Text { position, size, color, text, font } => {
|
||||
//XXX: should we be doing this every time?
|
||||
let mut layout = Layout::new(CoordinateSystem::PositiveYDown);
|
||||
layout.append(
|
||||
&[tr.internal_font(*font)],
|
||||
&TextStyle::new(text, *size as f32, 0)
|
||||
);
|
||||
let glyphs = layout.glyphs();
|
||||
|
||||
//let mut rpos_x = 0.;
|
||||
for layout_glyph in glyphs {
|
||||
if !layout_glyph.char_data.rasterize() {
|
||||
continue
|
||||
}
|
||||
let vidx = swapper.current().vertices.len() as u32;
|
||||
let glyph = tr.glyph(*font, layout_glyph.parent, layout_glyph.key.px as u8);
|
||||
//rpos_x += glyph.metrics.advance_width;//glyph.metrics.advance_width;
|
||||
swapper.current_mut().indices.extend([vidx, vidx + 1, vidx + 2, vidx, vidx + 2, vidx + 3]);
|
||||
let p0x = glyph.position.x as f32 / 1024.;
|
||||
let p1x = (glyph.position.x + glyph.size.x as i32) as f32 / 1024.;
|
||||
let p0y = glyph.position.y as f32 / 1024.;
|
||||
let p1y = (glyph.position.y + glyph.size.y as i32) as f32 / 1024.;
|
||||
swapper.current_mut().vertices.extend([
|
||||
UiVertex {
|
||||
position: *position + vec2(layout_glyph.x, layout_glyph.y),
|
||||
color: *color,
|
||||
uv: vec2(p0x, p0y),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + vec2(layout_glyph.x + glyph.metrics.width as f32, layout_glyph.y),
|
||||
color: *color,
|
||||
uv: vec2(p1x, p0y),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + vec2(layout_glyph.x + glyph.metrics.width as f32, layout_glyph.y + glyph.metrics.height as f32),
|
||||
color: *color,
|
||||
uv: vec2(p1x, p1y),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + vec2(layout_glyph.x, layout_glyph.y + glyph.metrics.height as f32),
|
||||
color: *color,
|
||||
uv: vec2(p0x, p1y),
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
prev_command = Some(command);
|
||||
}
|
||||
Self {
|
||||
calls: swapper.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IfModified<UiDrawPlan> for (bool, &UiDrawPlan) {
|
||||
fn if_modified(&self) -> Option<&UiDrawPlan> {
|
||||
match self.0 {
|
||||
true => Some(self.1),
|
||||
false => None,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,29 +0,0 @@
|
|||
use std::any::Any;
|
||||
use crate::{
|
||||
LayoutInfo,
|
||||
draw::UiDrawCommands,
|
||||
measure::Response,
|
||||
state::StateRepo
|
||||
};
|
||||
|
||||
#[cfg(feature = "builtin_elements")]
|
||||
mod builtin {
|
||||
pub mod rect;
|
||||
pub mod container;
|
||||
pub mod spacer;
|
||||
pub mod progress_bar;
|
||||
pub mod text;
|
||||
}
|
||||
|
||||
#[cfg(feature = "builtin_elements")]
|
||||
pub use builtin::*;
|
||||
|
||||
pub trait UiElement {
|
||||
fn name(&self) -> &'static str { "UiElement" }
|
||||
fn state_id(&self) -> Option<u64> { None }
|
||||
fn is_stateful(&self) -> bool { self.state_id().is_some() }
|
||||
fn is_stateless(&self) -> bool { self.state_id().is_none() }
|
||||
fn init_state(&self) -> Option<Box<dyn Any>> { None }
|
||||
fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response;
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands);
|
||||
}
|
|
@ -1,237 +0,0 @@
|
|||
use glam::{Vec2, vec2, Vec4};
|
||||
use crate::{
|
||||
UiDirection,
|
||||
UiSize,
|
||||
LayoutInfo,
|
||||
draw::{UiDrawCommand, UiDrawCommands},
|
||||
measure::{Response, Hints},
|
||||
state::StateRepo,
|
||||
element::UiElement
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Alignment {
|
||||
Begin,
|
||||
Center,
|
||||
End,
|
||||
}
|
||||
|
||||
pub struct Border {
|
||||
pub color: Vec4,
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub struct Sides<T> {
|
||||
pub top: T,
|
||||
pub bottom: T,
|
||||
pub left: T,
|
||||
pub right: T,
|
||||
}
|
||||
|
||||
impl<T: Clone> Sides<T> {
|
||||
#[inline]
|
||||
pub fn all(value: T) -> Self {
|
||||
Self {
|
||||
top: value.clone(),
|
||||
bottom: value.clone(),
|
||||
left: value.clone(),
|
||||
right: value,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn horizontal_vertical(horizontal: T, vertical: T) -> Self {
|
||||
Self {
|
||||
top: vertical.clone(),
|
||||
bottom: vertical,
|
||||
left: horizontal.clone(),
|
||||
right: horizontal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Container {
|
||||
// pub min_size: (UiSize, UiSize),
|
||||
// pub max_size: (UiSize, UiSize),
|
||||
pub size: (UiSize, UiSize),
|
||||
pub direction: UiDirection,
|
||||
//pub reverse: bool,
|
||||
pub gap: f32,
|
||||
pub padding: Sides<f32>,
|
||||
///Primary/secondary axis
|
||||
pub align: (Alignment, Alignment),
|
||||
pub background: Option<Vec4>,
|
||||
pub borders: Sides<Option<Border>>,
|
||||
pub clip: bool,
|
||||
pub elements: Vec<Box<dyn UiElement>>,
|
||||
}
|
||||
|
||||
impl Default for Container {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
// min_size: (UiSize::Auto, UiSize::Auto),
|
||||
// max_size: (UiSize::Auto, UiSize::Auto),
|
||||
size: (UiSize::Auto, UiSize::Auto),
|
||||
direction: UiDirection::Vertical,
|
||||
//reverse: false,
|
||||
gap: 0.,
|
||||
padding: Sides::all(0.),
|
||||
align: (Alignment::Begin, Alignment::Begin),
|
||||
background: Default::default(),
|
||||
borders: Default::default(),
|
||||
clip: Default::default(),
|
||||
elements: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Container {
|
||||
pub fn measure_max_inner_size(&self, layout: &LayoutInfo) -> Vec2 {
|
||||
let outer_size_x = match self.size.0 {
|
||||
UiSize::Auto => layout.max_size.x,
|
||||
UiSize::Percentage(p) => layout.max_size.x * p,
|
||||
UiSize::Pixels(p) => p,
|
||||
};
|
||||
let outer_size_y = match self.size.1 {
|
||||
UiSize::Auto => layout.max_size.y,
|
||||
UiSize::Percentage(p) => layout.max_size.y * p,
|
||||
UiSize::Pixels(p) => p,
|
||||
};
|
||||
vec2(
|
||||
outer_size_x - (self.padding.left + self.padding.right),
|
||||
outer_size_y - (self.padding.top + self.padding.bottom),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl UiElement for Container {
|
||||
fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response {
|
||||
let mut size = Vec2::ZERO;
|
||||
//if matches!(self.size.0, UiSize::Auto) || matches!(self.size.1, UiSize::Auto) {
|
||||
let mut leftover_gap = Vec2::ZERO;
|
||||
for element in &self.elements {
|
||||
let measure = element.measure(state, &LayoutInfo {
|
||||
position: layout.position + size,
|
||||
max_size: self.measure_max_inner_size(layout), // - size TODO
|
||||
direction: self.direction,
|
||||
});
|
||||
match self.direction {
|
||||
UiDirection::Horizontal => {
|
||||
size.x += measure.size.x + self.gap;
|
||||
size.y = size.y.max(measure.size.y);
|
||||
leftover_gap.x = self.gap;
|
||||
},
|
||||
UiDirection::Vertical => {
|
||||
size.x = size.x.max(measure.size.x);
|
||||
size.y += measure.size.y + self.gap;
|
||||
leftover_gap.y = self.gap;
|
||||
}
|
||||
}
|
||||
}
|
||||
size -= leftover_gap;
|
||||
|
||||
let inner_content_size = Some(size);
|
||||
|
||||
size += vec2(
|
||||
self.padding.left + self.padding.right,
|
||||
self.padding.top + self.padding.bottom,
|
||||
);
|
||||
|
||||
match self.size.0 {
|
||||
UiSize::Auto => (),
|
||||
UiSize::Percentage(percentage) => size.x = layout.max_size.x * percentage,
|
||||
UiSize::Pixels(pixels) => size.x = pixels,
|
||||
}
|
||||
match self.size.1 {
|
||||
UiSize::Auto => (),
|
||||
UiSize::Percentage(percentage) => size.y = layout.max_size.y * percentage,
|
||||
UiSize::Pixels(pixels) => size.y = pixels,
|
||||
}
|
||||
|
||||
Response {
|
||||
size,
|
||||
hints: Hints {
|
||||
inner_content_size,
|
||||
..Default::default()
|
||||
},
|
||||
user_data: None
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
let mut position = layout.position;
|
||||
|
||||
//background
|
||||
if let Some(color) = self.background {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position,
|
||||
size: measure.size,
|
||||
color
|
||||
});
|
||||
}
|
||||
|
||||
//padding
|
||||
position += vec2(self.padding.left, self.padding.top);
|
||||
|
||||
//alignment
|
||||
match (self.align.0, self.direction) {
|
||||
(Alignment::Begin, _) => (),
|
||||
(Alignment::Center, UiDirection::Horizontal) => {
|
||||
position.x += (measure.size.x - measure.hints.inner_content_size.unwrap().x) / 2.;
|
||||
},
|
||||
(Alignment::Center, UiDirection::Vertical) => {
|
||||
position.y += (measure.size.y - measure.hints.inner_content_size.unwrap().y) / 2.;
|
||||
},
|
||||
(Alignment::End, UiDirection::Horizontal) => {
|
||||
position.x += measure.size.x - measure.hints.inner_content_size.unwrap().x - self.padding.right - self.padding.left;
|
||||
},
|
||||
(Alignment::End, UiDirection::Vertical) => {
|
||||
position.y += measure.size.y - measure.hints.inner_content_size.unwrap().y - self.padding.bottom - self.padding.top;
|
||||
}
|
||||
}
|
||||
|
||||
for element in &self.elements {
|
||||
//(passing max size from layout rather than actual bounds for the sake of consistency with measure() above)
|
||||
|
||||
let mut el_layout = LayoutInfo {
|
||||
position,
|
||||
max_size: self.measure_max_inner_size(layout),
|
||||
direction: self.direction,
|
||||
};
|
||||
|
||||
//measure
|
||||
let el_measure = element.measure(state, &el_layout);
|
||||
|
||||
//align (on sec. axis)
|
||||
match (self.align.1, self.direction) {
|
||||
(Alignment::Begin, _) => (),
|
||||
(Alignment::Center, UiDirection::Horizontal) => {
|
||||
el_layout.position.y += (measure.size.y - self.padding.bottom - self.padding.top - el_measure.size.y) / 2.;
|
||||
},
|
||||
(Alignment::Center, UiDirection::Vertical) => {
|
||||
el_layout.position.x += (measure.size.x - self.padding.left - self.padding.right - el_measure.size.x) / 2.;
|
||||
},
|
||||
(Alignment::End, UiDirection::Horizontal) => {
|
||||
el_layout.position.y += measure.size.y - el_measure.size.y - self.padding.bottom;
|
||||
},
|
||||
(Alignment::End, UiDirection::Vertical) => {
|
||||
el_layout.position.x += measure.size.x - el_measure.size.x - self.padding.right;
|
||||
}
|
||||
}
|
||||
|
||||
//process
|
||||
element.process(&el_measure, state, &el_layout, draw);
|
||||
|
||||
//layout
|
||||
match self.direction {
|
||||
UiDirection::Horizontal => {
|
||||
position.x += el_measure.size.x + self.gap;
|
||||
},
|
||||
UiDirection::Vertical => {
|
||||
position.y += el_measure.size.y + self.gap;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,70 +0,0 @@
|
|||
use glam::{vec2, Vec4, vec4};
|
||||
use crate::{
|
||||
UiSize, LayoutInfo,
|
||||
draw::{UiDrawCommand, UiDrawCommands},
|
||||
measure::Response,
|
||||
state::StateRepo,
|
||||
element::UiElement
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ProgressBar {
|
||||
pub size: (UiSize, UiSize),
|
||||
pub value: f32,
|
||||
pub color_foreground: Vec4,
|
||||
pub color_background: Vec4,
|
||||
}
|
||||
|
||||
impl Default for ProgressBar {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
size: (UiSize::Auto, UiSize::Auto),
|
||||
value: 0.,
|
||||
color_foreground: vec4(0.0, 0.0, 1.0, 1.0),
|
||||
color_background: vec4(0.0, 0.0, 0.0, 1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const BAR_HEIGHT: f32 = 20.0;
|
||||
|
||||
impl UiElement for ProgressBar {
|
||||
fn name(&self) -> &'static str { "Progress bar" }
|
||||
|
||||
fn measure(&self, _: &StateRepo, layout: &LayoutInfo) -> Response {
|
||||
Response {
|
||||
size: vec2(
|
||||
match self.size.0 {
|
||||
UiSize::Auto => layout.max_size.x.max(300.),
|
||||
UiSize::Percentage(p) => layout.max_size.x * p,
|
||||
UiSize::Pixels(p) => p,
|
||||
},
|
||||
match self.size.1 {
|
||||
UiSize::Auto => BAR_HEIGHT,
|
||||
UiSize::Percentage(p) => layout.max_size.y * p,
|
||||
UiSize::Pixels(p) => p,
|
||||
}
|
||||
),
|
||||
hints: Default::default(),
|
||||
user_data: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
let value = self.value.clamp(0., 1.);
|
||||
if value < 1. {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position: layout.position,
|
||||
size: measure.size,
|
||||
color: self.color_background
|
||||
});
|
||||
}
|
||||
if value > 0. {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position: layout.position,
|
||||
size: measure.size * vec2(value, 1.0),
|
||||
color: self.color_foreground
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,54 +0,0 @@
|
|||
use glam::{vec2, Vec4};
|
||||
use crate::{
|
||||
LayoutInfo,
|
||||
UiSize,
|
||||
element::UiElement,
|
||||
state::StateRepo,
|
||||
measure::Response,
|
||||
draw::{UiDrawCommand, UiDrawCommands}
|
||||
};
|
||||
|
||||
pub struct Rect {
|
||||
pub size: (UiSize, UiSize),
|
||||
pub color: Option<Vec4>,
|
||||
}
|
||||
|
||||
impl Default for Rect {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
size: (UiSize::Pixels(10.), UiSize::Pixels(10.)),
|
||||
color: Some(Vec4::new(0., 0., 0., 0.5)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UiElement for Rect {
|
||||
fn measure(&self, _state: &StateRepo, layout: &LayoutInfo) -> Response {
|
||||
Response {
|
||||
size: vec2(
|
||||
match self.size.0 {
|
||||
UiSize::Auto => layout.max_size.x,
|
||||
UiSize::Percentage(percentage) => layout.max_size.x * percentage,
|
||||
UiSize::Pixels(pixels) => pixels,
|
||||
},
|
||||
match self.size.1 {
|
||||
UiSize::Auto => layout.max_size.y,
|
||||
UiSize::Percentage(percentage) => layout.max_size.y * percentage,
|
||||
UiSize::Pixels(pixels) => pixels,
|
||||
},
|
||||
),
|
||||
hints: Default::default(),
|
||||
user_data: None
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&self, measure: &Response, _state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
if let Some(color) = self.color {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position: layout.position,
|
||||
size: measure.size,
|
||||
color,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
use glam::vec2;
|
||||
use crate::{
|
||||
LayoutInfo,
|
||||
UiDirection,
|
||||
element::UiElement,
|
||||
state::StateRepo,
|
||||
measure::Response,
|
||||
draw::{UiDrawCommand, UiDrawCommands}
|
||||
};
|
||||
|
||||
pub struct Spacer(pub f32);
|
||||
|
||||
impl Default for Spacer {
|
||||
fn default() -> Self {
|
||||
Self(5.)
|
||||
}
|
||||
}
|
||||
|
||||
impl UiElement for Spacer {
|
||||
fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response {
|
||||
Response {
|
||||
size: match layout.direction {
|
||||
UiDirection::Horizontal => vec2(self.0, 0.),
|
||||
UiDirection::Vertical => vec2(0., self.0),
|
||||
},
|
||||
hints: Default::default(),
|
||||
user_data: None
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&self, _measure: &Response, _state: &mut StateRepo, _layout: &LayoutInfo, _draw: &mut UiDrawCommands) {}
|
||||
}
|
|
@ -1,61 +0,0 @@
|
|||
use std::borrow::Cow;
|
||||
use glam::{vec2, Vec4};
|
||||
use crate::{
|
||||
LayoutInfo,
|
||||
UiSize,
|
||||
element::UiElement,
|
||||
state::StateRepo,
|
||||
measure::Response,
|
||||
draw::{UiDrawCommand, UiDrawCommands}, text::FontHandle
|
||||
};
|
||||
|
||||
pub struct Text {
|
||||
pub text: Cow<'static, str>,
|
||||
pub size: (UiSize, UiSize),
|
||||
pub color: Vec4,
|
||||
pub font: FontHandle,
|
||||
pub text_size: u8,
|
||||
}
|
||||
|
||||
impl Default for Text {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: "".into(),
|
||||
size: (UiSize::Auto, UiSize::Auto),
|
||||
color: Vec4::new(1., 1., 1., 1.),
|
||||
font: FontHandle(0),
|
||||
text_size: 16,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UiElement for Text {
|
||||
fn measure(&self, _state: &StateRepo, layout: &LayoutInfo) -> Response {
|
||||
Response {
|
||||
size: vec2(
|
||||
match self.size.0 {
|
||||
UiSize::Auto => layout.max_size.x,
|
||||
UiSize::Percentage(percentage) => layout.max_size.x * percentage,
|
||||
UiSize::Pixels(pixels) => pixels,
|
||||
},
|
||||
match self.size.1 {
|
||||
UiSize::Auto => self.text_size as f32,
|
||||
UiSize::Percentage(percentage) => layout.max_size.y * percentage,
|
||||
UiSize::Pixels(pixels) => pixels,
|
||||
},
|
||||
),
|
||||
hints: Default::default(),
|
||||
user_data: None
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&self, _measure: &Response, _state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
draw.add(UiDrawCommand::Text {
|
||||
text: self.text.clone(),
|
||||
position: layout.position,
|
||||
size: self.text_size,
|
||||
color: self.color,
|
||||
font: self.font
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
use glam::Vec2;
|
||||
|
||||
pub enum UiEvent {
|
||||
MouseMove(Vec2),
|
||||
MouseDown(Vec2),
|
||||
MouseUp(Vec2),
|
||||
KeyDown(u32),
|
||||
KeyUp(u32),
|
||||
TextInput(char),
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
use crate::{element::UiElement, draw::UiDrawCommands};
|
||||
|
||||
pub struct Interactable<T: UiElement> {
|
||||
pub element: T,
|
||||
pub hovered: Option<Box<dyn FnOnce()>>,
|
||||
pub clicked: Option<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
impl<T: UiElement> Interactable<T> {
|
||||
pub fn new(element: T) -> Self {
|
||||
Self {
|
||||
element,
|
||||
hovered: None,
|
||||
clicked: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_click(self, clicked: impl FnOnce() + 'static) -> Self {
|
||||
Self {
|
||||
clicked: Some(Box::new(clicked)),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_hover(self, clicked: impl FnOnce() + 'static) -> Self {
|
||||
Self {
|
||||
clicked: Some(Box::new(clicked)),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: UiElement> UiElement for Interactable<T> {
|
||||
fn measure(&self, state: &crate::state::StateRepo, layout: &crate::LayoutInfo) -> crate::measure::Response {
|
||||
self.element.measure(state, layout)
|
||||
}
|
||||
|
||||
fn process(&self, measure: &crate::measure::Response, state: &mut crate::state::StateRepo, layout: &crate::LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
self.element.process(measure, state, layout, draw)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IntoInteractable<T: UiElement>: UiElement {
|
||||
fn into_interactable(self) -> Interactable<T>;
|
||||
}
|
||||
|
||||
impl<T: UiElement> IntoInteractable<T> for T {
|
||||
fn into_interactable(self) -> Interactable<Self> {
|
||||
Interactable::new(self)
|
||||
}
|
||||
}
|
|
@ -1,129 +0,0 @@
|
|||
use glam::Vec2;
|
||||
|
||||
pub mod element;
|
||||
pub mod event;
|
||||
pub mod draw;
|
||||
pub mod measure;
|
||||
pub mod state;
|
||||
pub mod text;
|
||||
pub mod interaction;
|
||||
|
||||
use element::UiElement;
|
||||
use state::StateRepo;
|
||||
use draw::{UiDrawCommands, UiDrawPlan};
|
||||
use text::{TextRenderer, FontTextureInfo, FontHandle};
|
||||
|
||||
// pub struct ElementContext<'a> {
|
||||
// pub state: &'a mut StateRepo,
|
||||
// pub draw: &'a mut UiDrawCommands,
|
||||
// pub text: &'a mut TextRenderer,
|
||||
// }
|
||||
pub trait IfModified<T> {
|
||||
fn if_modified(&self) -> Option<&T>;
|
||||
}
|
||||
|
||||
pub struct KubiUi {
|
||||
//mouse_position: Vec2,
|
||||
stateful_state: StateRepo,
|
||||
//event_queue: VecDeque<UiEvent>,
|
||||
prev_draw_commands: UiDrawCommands,
|
||||
draw_commands: UiDrawCommands,
|
||||
draw_plan: UiDrawPlan,
|
||||
draw_plan_modified: bool,
|
||||
text_renderer: TextRenderer,
|
||||
}
|
||||
|
||||
impl KubiUi {
|
||||
pub fn new() -> Self {
|
||||
KubiUi {
|
||||
//mouse_position: Vec2::ZERO,
|
||||
stateful_state: StateRepo::default(),
|
||||
//event_queue: VecDeque::new(),
|
||||
// root_elements: Vec::new(),
|
||||
prev_draw_commands: UiDrawCommands::default(),
|
||||
draw_commands: UiDrawCommands::default(),
|
||||
draw_plan: UiDrawPlan::default(),
|
||||
draw_plan_modified: false,
|
||||
// ftm: FontTextureManager::default(),
|
||||
text_renderer: TextRenderer::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_font_from_bytes(&mut self, font: &[u8]) -> FontHandle {
|
||||
self.text_renderer.add_font_from_bytes(font)
|
||||
}
|
||||
|
||||
pub fn add<T: UiElement>(&mut self, element: T, max_size: Vec2) {
|
||||
let layout = LayoutInfo {
|
||||
position: Vec2::ZERO,
|
||||
max_size,
|
||||
direction: UiDirection::Vertical,
|
||||
};
|
||||
let measure = element.measure(&self.stateful_state, &layout);
|
||||
element.process(&measure, &mut self.stateful_state, &layout, &mut self.draw_commands);
|
||||
}
|
||||
|
||||
pub fn begin(&mut self) {
|
||||
std::mem::swap(&mut self.prev_draw_commands, &mut self.draw_commands);
|
||||
self.draw_plan_modified = false;
|
||||
self.draw_commands.commands.clear();
|
||||
self.text_renderer.reset_frame();
|
||||
}
|
||||
|
||||
pub fn end(&mut self) {
|
||||
if self.draw_commands.commands == self.prev_draw_commands.commands {
|
||||
return
|
||||
}
|
||||
self.draw_plan = UiDrawPlan::build(&self.draw_commands, &mut self.text_renderer);
|
||||
self.draw_plan_modified = true;
|
||||
}
|
||||
|
||||
pub fn draw_plan(&self) -> (bool, &UiDrawPlan) {
|
||||
(self.draw_plan_modified, &self.draw_plan)
|
||||
}
|
||||
|
||||
pub fn font_texture(&self) -> FontTextureInfo {
|
||||
self.text_renderer.font_texture()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for KubiUi {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub enum UiSize {
|
||||
#[default]
|
||||
Auto,
|
||||
Percentage(f32),
|
||||
Pixels(f32),
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum UiDirection {
|
||||
#[default]
|
||||
Vertical,
|
||||
Horizontal,
|
||||
}
|
||||
|
||||
pub struct LayoutInfo {
|
||||
///Not availabe during measuring step
|
||||
pub position: Vec2,
|
||||
pub max_size: Vec2,
|
||||
pub direction: UiDirection,
|
||||
}
|
||||
|
||||
pub struct ElementList(Vec<Box<dyn UiElement>>);
|
||||
|
||||
impl ElementList {
|
||||
pub fn add(&mut self, element: impl UiElement + 'static) {
|
||||
self.0.push(Box::new(element));
|
||||
}
|
||||
}
|
||||
pub fn elements(f: impl FnOnce(&mut ElementList)) -> Vec<Box<dyn UiElement>> {
|
||||
let mut elements = ElementList(Vec::new());
|
||||
f(&mut elements);
|
||||
elements.0
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
use glam::Vec2;
|
||||
|
||||
#[derive(Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct Hints {
|
||||
pub inner_content_size: Option<Vec2>,
|
||||
pub inner_content_size_cache: Option<Vec<Vec2>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Response {
|
||||
pub size: Vec2,
|
||||
pub hints: Hints,
|
||||
pub user_data: Option<Box<dyn std::any::Any>>,
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
use hashbrown::{HashMap, HashSet};
|
||||
use nohash_hasher::BuildNoHashHasher;
|
||||
use std::any::Any;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct StateRepo {
|
||||
state: HashMap<u64, Box<dyn Any>, BuildNoHashHasher<u64>>,
|
||||
active_ids: HashSet<u64, BuildNoHashHasher<u64>>
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
mod font;
|
||||
mod ftm;
|
||||
|
||||
use font::FontManager;
|
||||
pub use font::FontHandle;
|
||||
use fontdue::{Font, FontSettings};
|
||||
use ftm::FontTextureManager;
|
||||
pub use ftm::{FontTextureInfo, GlyphCacheEntry};
|
||||
|
||||
pub struct TextRenderer {
|
||||
fm: FontManager,
|
||||
ftm: FontTextureManager,
|
||||
}
|
||||
|
||||
impl TextRenderer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
fm: FontManager::new(),
|
||||
ftm: FontTextureManager::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_font_from_bytes(&mut self, font: &[u8]) -> FontHandle {
|
||||
self.fm.add_font(Font::from_bytes(font, FontSettings::default()).unwrap())
|
||||
}
|
||||
|
||||
pub fn reset_frame(&mut self) {
|
||||
self.ftm.reset_modified();
|
||||
}
|
||||
|
||||
pub fn font_texture(&self) -> FontTextureInfo {
|
||||
self.ftm.info()
|
||||
}
|
||||
|
||||
pub fn glyph(&mut self, font_handle: FontHandle, character: char, size: u8) -> Arc<GlyphCacheEntry> {
|
||||
self.ftm.glyph(&self.fm, font_handle, character, size)
|
||||
}
|
||||
|
||||
pub(crate) fn internal_font(&self, handle: FontHandle) -> &Font {
|
||||
self.fm.get(handle).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TextRenderer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
use fontdue::Font;
|
||||
|
||||
#[cfg(feature = "builtin_font")]
|
||||
const BIN_FONT: &[u8] = include_bytes!("../../assets/font/ProggyTiny.ttf");
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct FontHandle(pub(crate) usize);
|
||||
|
||||
#[cfg(feature = "builtin_font")]
|
||||
pub const BUILTIN_FONT: FontHandle = FontHandle(0);
|
||||
|
||||
pub struct FontManager {
|
||||
fonts: Vec<Font>,
|
||||
}
|
||||
|
||||
impl FontManager {
|
||||
pub fn new() -> Self {
|
||||
let mut this = Self {
|
||||
fonts: Vec::new(),
|
||||
};
|
||||
#[cfg(feature = "builtin_font")]
|
||||
{
|
||||
let font = Font::from_bytes(BIN_FONT, fontdue::FontSettings::default()).unwrap();
|
||||
this.add_font(font);
|
||||
};
|
||||
this
|
||||
}
|
||||
|
||||
/// Add a (fontdue) font to the renderer.
|
||||
pub fn add_font(&mut self, font: Font) -> FontHandle {
|
||||
self.fonts.push(font);
|
||||
FontHandle(self.fonts.len() - 1)
|
||||
}
|
||||
|
||||
pub fn get(&self, handle: FontHandle) -> Option<&Font> {
|
||||
self.fonts.get(handle.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FontManager {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
|
@ -1,139 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
use fontdue::Metrics;
|
||||
use glam::{IVec2, UVec2, uvec2, ivec2};
|
||||
use hashbrown::HashMap;
|
||||
use rect_packer::DensePacker;
|
||||
|
||||
use crate::IfModified;
|
||||
|
||||
use super::font::{FontHandle, FontManager};
|
||||
|
||||
#[derive(PartialEq, Eq, Hash)]
|
||||
struct GlyphCacheKey {
|
||||
font_index: usize,
|
||||
character: char,
|
||||
size: u8,
|
||||
}
|
||||
|
||||
pub struct GlyphCacheEntry {
|
||||
pub data: Vec<u8>,
|
||||
pub metrics: Metrics,
|
||||
pub position: IVec2,
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FontTextureInfo<'a> {
|
||||
pub modified: bool,
|
||||
pub data: &'a [u8],
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
impl<'a> IfModified<FontTextureInfo<'a>> for FontTextureInfo<'a> {
|
||||
fn if_modified(&self) -> Option<&Self> {
|
||||
match self.modified {
|
||||
true => Some(self),
|
||||
false => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// impl<'a> FontTextureInfo<'a> {
|
||||
// fn if_modified(&self) -> Option<Self> {
|
||||
// match self.modified {
|
||||
// true => Some(*self),
|
||||
// false => None,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
pub struct FontTextureManager {
|
||||
glyph_cache: HashMap<GlyphCacheKey, Arc<GlyphCacheEntry>>,
|
||||
packer: DensePacker,
|
||||
font_texture: Vec<u8>,
|
||||
font_texture_size: UVec2,
|
||||
modified: bool,
|
||||
}
|
||||
|
||||
impl FontTextureManager {
|
||||
pub fn new(size: UVec2) -> Self {
|
||||
FontTextureManager {
|
||||
glyph_cache: HashMap::new(),
|
||||
packer: DensePacker::new(size.x as i32, size.y as i32),
|
||||
font_texture: vec![0; (size.x * size.y * 4) as usize],
|
||||
font_texture_size: size,
|
||||
modified: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset_modified(&mut self) {
|
||||
self.modified = false;
|
||||
}
|
||||
|
||||
pub fn info(&self) -> FontTextureInfo {
|
||||
FontTextureInfo {
|
||||
modified: self.modified,
|
||||
data: &self.font_texture,
|
||||
size: self.font_texture_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Either looks up the glyph in the cache or renders it and adds it to the cache.
|
||||
pub fn glyph(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> Arc<GlyphCacheEntry> {
|
||||
let key = GlyphCacheKey {
|
||||
font_index: font_handle.0,
|
||||
character,
|
||||
size,
|
||||
};
|
||||
if let Some(entry) = self.glyph_cache.get(&key) {
|
||||
return Arc::clone(entry);
|
||||
}
|
||||
let font = font_manager.get(font_handle).unwrap();
|
||||
let (metrics, bitmap) = font.rasterize(character, size as f32);
|
||||
log::debug!("rasterized glyph: {}, {:?}, {:?}", character, metrics, bitmap);
|
||||
let texture_position = self.packer.pack(metrics.width as i32, metrics.height as i32, false).unwrap();
|
||||
let texture_size = uvec2(metrics.width as u32, metrics.height as u32);
|
||||
let entry = Arc::new(GlyphCacheEntry {
|
||||
data: bitmap,
|
||||
metrics,
|
||||
position: ivec2(texture_position.x, texture_position.y),
|
||||
size: texture_size,
|
||||
});
|
||||
self.glyph_cache.insert_unique_unchecked(key, Arc::clone(&entry));
|
||||
self.glyph_place(&entry);
|
||||
self.modified = true;
|
||||
entry
|
||||
}
|
||||
|
||||
/// Place glyph onto the font texture.
|
||||
fn glyph_place(&mut self, entry: &GlyphCacheEntry) {
|
||||
let tex_size = self.font_texture_size;
|
||||
let GlyphCacheEntry { size, position, data, .. } = entry;
|
||||
//println!("{size:?} {position:?}");
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let src = (size.x * y + x) as usize;
|
||||
let dst = (tex_size.x * (y + position.y as u32) + (x + position.x as u32)) as usize * 4;
|
||||
self.font_texture[dst..=(dst + 3)].copy_from_slice(&[255, 255, 255, data[src]]);
|
||||
//print!("{} ", if data[src] > 0 {'#'} else {'.'});
|
||||
//print!("{src} {dst} / ");
|
||||
}
|
||||
//println!();
|
||||
}
|
||||
}
|
||||
|
||||
// pub fn glyph(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> Arc<GlyphCacheEntry> {
|
||||
// let (is_new, glyph) = self.glyph_allocate(font_manager, font_handle, character, size);
|
||||
// if is_new {
|
||||
// self.glyph_place(&glyph);
|
||||
// self.modified = true;
|
||||
// }
|
||||
// glyph
|
||||
// }
|
||||
}
|
||||
|
||||
impl Default for FontTextureManager {
|
||||
fn default() -> Self {
|
||||
Self::new(uvec2(1024, 1024))
|
||||
}
|
||||
}
|
|
@ -11,8 +11,8 @@ crate-type = ["lib", "cdylib"]
|
|||
[dependencies]
|
||||
kubi-shared = { path = "../kubi-shared" }
|
||||
kubi-logging = { path = "../kubi-logging" }
|
||||
kubi-ui = { path = "../kubi-ui" }
|
||||
kubi-ui-glium = { path = "../kubi-ui-glium" }
|
||||
hui = { version = "^0.0", git = "https://github.com/griffi-gh/hui", rev = "1e1dccde0c" }
|
||||
hui-glium = { version = "^0.0", git = "https://github.com/griffi-gh/hui", rev = "1e1dccde0c" }
|
||||
log = "0.4"
|
||||
glium = { git = "https://github.com/glium/glium", rev = "a352c667" }
|
||||
glutin = "0.31"
|
||||
|
|
|
@ -1,49 +1,185 @@
|
|||
//TODO client-side physics
|
||||
//TODO move this to shared
|
||||
use glam::{Mat4, Vec3};
|
||||
use kubi_shared::transform::Transform;
|
||||
use glam::{vec3, IVec3, Mat4, Vec3, Vec3Swizzles};
|
||||
use shipyard::{track, AllStoragesView, Component, IntoIter, Unique, UniqueView, View, ViewMut};
|
||||
use crate::delta_time::DeltaTime;
|
||||
use kubi_shared::{block::{Block, CollisionType}, transform::Transform};
|
||||
use crate::{delta_time::DeltaTime, world::ChunkStorage};
|
||||
|
||||
#[derive(Unique)]
|
||||
pub struct GlobalClPhysicsConfig {
|
||||
pub gravity: Vec3,
|
||||
///XXX: currenly unused:
|
||||
pub iterations: usize,
|
||||
}
|
||||
|
||||
impl Default for GlobalClPhysicsConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
gravity: Vec3::new(0., -9.8, 0.),
|
||||
iterations: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: actors should be represented by a vertical line, not a point.
|
||||
//XXX: maybe a capsule? (or configurable hull?)
|
||||
//TODO: per block friction
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct ClPhysicsActor {
|
||||
pub disable: bool,
|
||||
pub offset: Vec3,
|
||||
pub forces: Vec3,
|
||||
pub frame_velocity: Vec3,
|
||||
pub velocity: Vec3,
|
||||
pub terminal_velocity: f32,
|
||||
//TODO: this should be configurable per block
|
||||
pub friction_agains_ground: f32,
|
||||
pub decel: Vec3,
|
||||
pub gravity_scale: f32,
|
||||
pub max_velocity: (Option<f32>, Option<f32>, Option<f32>),
|
||||
pub hack_xz_circular: bool,
|
||||
flag_ground: bool,
|
||||
flag_collision: bool,
|
||||
}
|
||||
|
||||
impl ClPhysicsActor {
|
||||
pub fn apply_force(&mut self, force: Vec3) {
|
||||
self.forces += force;
|
||||
}
|
||||
|
||||
pub fn add_frame_velocity(&mut self, force: Vec3) {
|
||||
self.frame_velocity += force;
|
||||
}
|
||||
|
||||
pub fn on_ground(&self) -> bool {
|
||||
self.flag_ground
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ClPhysicsActor {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
//HACK: for player
|
||||
disable: false,
|
||||
offset: vec3(0., 1.5, 0.),
|
||||
forces: Vec3::ZERO,
|
||||
frame_velocity: Vec3::ZERO,
|
||||
velocity: Vec3::ZERO,
|
||||
terminal_velocity: 40.,
|
||||
friction_agains_ground: 0.5,
|
||||
//constant deceleration, in ratio per second. e.g. value of 1 should stop the actor in 1 second.
|
||||
decel: vec3(1., 0., 1.),
|
||||
gravity_scale: 1.,
|
||||
max_velocity: (Some(20.), None, Some(20.)),
|
||||
hack_xz_circular: true,
|
||||
flag_ground: false,
|
||||
flag_collision: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait BlockCollisionExt {
|
||||
fn collision_type(&self) -> CollisionType;
|
||||
fn is_solid(&self) -> bool {
|
||||
self.collision_type() == CollisionType::Solid
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockCollisionExt for Option<Block> {
|
||||
fn collision_type(&self) -> CollisionType {
|
||||
self.unwrap_or(Block::Air).descriptor().collision
|
||||
}
|
||||
}
|
||||
|
||||
impl BlockCollisionExt for Block {
|
||||
fn collision_type(&self) -> CollisionType {
|
||||
self.descriptor().collision
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_client_physics(
|
||||
storages: AllStoragesView,
|
||||
) {
|
||||
storages.add_unique(GlobalClPhysicsConfig {
|
||||
gravity: Vec3::new(0., -9.8, 0.),
|
||||
});
|
||||
storages.add_unique(GlobalClPhysicsConfig::default());
|
||||
}
|
||||
|
||||
pub fn update_client_physics_late(
|
||||
controllers: View<ClPhysicsActor>,
|
||||
mut actors: ViewMut<ClPhysicsActor>,
|
||||
mut transforms: ViewMut<Transform, track::All>,
|
||||
conf: UniqueView<GlobalClPhysicsConfig>,
|
||||
world: UniqueView<ChunkStorage>,
|
||||
dt: UniqueView<DeltaTime>,
|
||||
phy_conf: UniqueView<GlobalClPhysicsConfig>,
|
||||
) {
|
||||
for (mut actor, mut transform) in (&mut actors, &mut transforms).iter() {
|
||||
if actor.disable {
|
||||
actor.forces = Vec3::ZERO;
|
||||
continue;
|
||||
}
|
||||
|
||||
//apply forces
|
||||
let actor_forces = actor.forces;
|
||||
actor.velocity += (actor_forces + conf.gravity) * dt.0.as_secs_f32();
|
||||
actor.forces = Vec3::ZERO;
|
||||
|
||||
//get position
|
||||
let (scale, rotation, mut actor_position) = transform.0.to_scale_rotation_translation();
|
||||
actor_position -= actor.offset;
|
||||
|
||||
//get grid-aligned pos and blocks
|
||||
let actor_block_pos = actor_position.floor().as_ivec3();
|
||||
let actor_block = world.get_block(actor_block_pos);
|
||||
let actor_block_pos_slightly_below = (actor_position + Vec3::NEG_Y * 0.01).floor().as_ivec3();
|
||||
let actor_block_below = world.get_block(actor_block_pos_slightly_below);
|
||||
|
||||
//update flags
|
||||
actor.flag_collision = actor_block.is_solid();
|
||||
actor.flag_ground = actor.flag_collision || actor_block_below.is_solid();
|
||||
|
||||
//push actor back out of the block
|
||||
if actor.flag_collision {
|
||||
//first, compute restitution, based on position inside the block
|
||||
// let block_center = actor_block_pos.as_f32() + Vec3::ONE * 0.5;
|
||||
// let to_block_center = actor_position - block_center;
|
||||
|
||||
//then, based on normal:
|
||||
//push the actor back
|
||||
//actor_position += normal * 0.5;
|
||||
//cancel out velocity in the direction of the normal
|
||||
// let dot = actor.velocity.dot(normal);
|
||||
// if dot > 0. {
|
||||
// //actor.velocity -= normal * dot;
|
||||
// actor.velocity = Vec3::ZERO;
|
||||
// }
|
||||
|
||||
//HACK: for now, just stop the vertical velocity if on ground altogether,
|
||||
//as we don't have proper collision velocity resolution yet (we need to compute dot product or sth)
|
||||
if actor.flag_ground {
|
||||
actor.velocity.y = actor.velocity.y.max(0.);
|
||||
}
|
||||
}
|
||||
|
||||
//clamp velocity
|
||||
let max_velocity = actor.max_velocity;
|
||||
if actor.hack_xz_circular && actor.max_velocity.0.is_some() && (actor.max_velocity.0 == actor.max_velocity.2) {
|
||||
actor.velocity.y = actor.velocity.y.clamp(-max_velocity.1.unwrap_or(f32::MAX), max_velocity.1.unwrap_or(f32::MAX));
|
||||
let clamped = actor.velocity.xz().clamp_length_max(actor.max_velocity.0.unwrap_or(f32::MAX));
|
||||
actor.velocity.x = clamped.x;
|
||||
actor.velocity.z = clamped.y;
|
||||
} else {
|
||||
actor.velocity = vec3(
|
||||
actor.velocity.x.clamp(-max_velocity.0.unwrap_or(f32::MAX), max_velocity.0.unwrap_or(f32::MAX)),
|
||||
actor.velocity.y.clamp(-max_velocity.1.unwrap_or(f32::MAX), max_velocity.1.unwrap_or(f32::MAX)),
|
||||
actor.velocity.z.clamp(-max_velocity.2.unwrap_or(f32::MAX), max_velocity.2.unwrap_or(f32::MAX)),
|
||||
);
|
||||
}
|
||||
|
||||
//Apply velocity
|
||||
actor_position += (actor.velocity + actor.frame_velocity) * dt.0.as_secs_f32();
|
||||
actor.frame_velocity = Vec3::ZERO;
|
||||
actor_position += actor.offset;
|
||||
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation.normalize(), actor_position);
|
||||
|
||||
//Apply "friction"
|
||||
let actor_velocity = actor.velocity;
|
||||
let actor_decel = actor.decel;
|
||||
actor.velocity -= actor_velocity * actor_decel * dt.0.as_secs_f32();
|
||||
}
|
||||
// for (_, mut transform) in (&controllers, &mut transforms).iter() {
|
||||
// let (scale, rotation, mut translation) = transform.0.to_scale_rotation_translation();
|
||||
// translation.y -= dt.0.as_secs_f32() * 100.;
|
||||
|
|
|
@ -1,35 +1,39 @@
|
|||
use shipyard::{Component, View, ViewMut, EntitiesViewMut, IntoIter, track};
|
||||
use glam::{IVec3, Quat, Vec3};
|
||||
use kubi_shared::block::Block;
|
||||
use crate::{
|
||||
player::MainPlayer,
|
||||
transform::Transform
|
||||
};
|
||||
use super::EventComponent;
|
||||
|
||||
#[derive(Component, Clone, Copy, Debug)]
|
||||
pub enum PlayerActionEvent {
|
||||
PositionChanged {
|
||||
position: Vec3,
|
||||
direction: Quat
|
||||
},
|
||||
UpdatedBlock {
|
||||
position: IVec3,
|
||||
block: Block,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn generate_move_events(
|
||||
transforms: View<Transform, track::All>,
|
||||
player: View<MainPlayer>,
|
||||
mut entities: EntitiesViewMut,
|
||||
mut events: ViewMut<EventComponent>,
|
||||
mut actions: ViewMut<PlayerActionEvent>,
|
||||
) {
|
||||
let Some((_, transform)) = (&player, transforms.inserted_or_modified()).iter().next() else { return };
|
||||
let (_, direction, position) = transform.0.to_scale_rotation_translation();
|
||||
entities.add_entity(
|
||||
(&mut events, &mut actions),
|
||||
(EventComponent, PlayerActionEvent::PositionChanged { position, direction })
|
||||
);
|
||||
}
|
||||
use shipyard::{Component, View, ViewMut, EntitiesViewMut, IntoIter, track};
|
||||
use glam::{IVec3, Quat, Vec3};
|
||||
use kubi_shared::block::Block;
|
||||
use crate::{
|
||||
client_physics::ClPhysicsActor, player::MainPlayer, transform::Transform
|
||||
};
|
||||
use super::EventComponent;
|
||||
|
||||
#[derive(Component, Clone, Copy, Debug)]
|
||||
pub enum PlayerActionEvent {
|
||||
PositionChanged {
|
||||
position: Vec3,
|
||||
//XXX: should this even be here?
|
||||
velocity: Vec3,
|
||||
direction: Quat
|
||||
},
|
||||
UpdatedBlock {
|
||||
position: IVec3,
|
||||
block: Block,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn generate_move_events(
|
||||
transforms: View<Transform, track::All>,
|
||||
player: View<MainPlayer>,
|
||||
actors: View<ClPhysicsActor>,
|
||||
mut entities: EntitiesViewMut,
|
||||
mut events: ViewMut<EventComponent>,
|
||||
mut actions: ViewMut<PlayerActionEvent>,
|
||||
) {
|
||||
let Some((_, transform, actor)) = (&player, transforms.inserted_or_modified(), &actors).iter().next() else { return };
|
||||
let (_, direction, position) = transform.0.to_scale_rotation_translation();
|
||||
//HACK: if the actor is disabled, the velocity is irrelevant, so we just set it to zero.
|
||||
let velocity = if actor.disable { Vec3::ZERO } else { actor.velocity };
|
||||
entities.add_entity(
|
||||
(&mut events, &mut actions),
|
||||
(EventComponent, PlayerActionEvent::PositionChanged { position, velocity, direction })
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,53 +0,0 @@
|
|||
use glam::{Vec3, Mat4, Quat, EulerRot, Vec2};
|
||||
use shipyard::{Component, View, ViewMut, IntoIter, UniqueView, Workload, IntoWorkload, track};
|
||||
use std::f32::consts::PI;
|
||||
use crate::{transform::Transform, input::Inputs, settings::GameSettings, delta_time::DeltaTime};
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct FlyController;
|
||||
|
||||
pub fn update_controllers() -> Workload {
|
||||
(
|
||||
update_look,
|
||||
update_movement
|
||||
).into_sequential_workload()
|
||||
}
|
||||
|
||||
const MAX_PITCH: f32 = PI/2. - 0.05;
|
||||
|
||||
fn update_look(
|
||||
controllers: View<FlyController>,
|
||||
mut transforms: ViewMut<Transform, track::All>,
|
||||
inputs: UniqueView<Inputs>,
|
||||
settings: UniqueView<GameSettings>,
|
||||
dt: UniqueView<DeltaTime>,
|
||||
) {
|
||||
let look = inputs.look * settings.mouse_sensitivity * dt.0.as_secs_f32();
|
||||
if look == Vec2::ZERO { return }
|
||||
for (_, mut transform) in (&controllers, &mut transforms).iter() {
|
||||
let (scale, mut rotation, translation) = transform.0.to_scale_rotation_translation();
|
||||
let (mut yaw, mut pitch, _roll) = rotation.to_euler(EulerRot::YXZ);
|
||||
yaw -= look.x;
|
||||
pitch -= look.y;
|
||||
pitch = pitch.clamp(-MAX_PITCH, MAX_PITCH);
|
||||
rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, 0.).normalize();
|
||||
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation, translation);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_movement(
|
||||
controllers: View<FlyController>,
|
||||
mut transforms: ViewMut<Transform, track::All>,
|
||||
inputs: UniqueView<Inputs>,
|
||||
dt: UniqueView<DeltaTime>,
|
||||
) {
|
||||
if inputs.movement == Vec2::ZERO { return }
|
||||
let movement = inputs.movement * 30. * dt.0.as_secs_f32();
|
||||
for (_, mut transform) in (&controllers, &mut transforms).iter() {
|
||||
let (scale, rotation, mut translation) = transform.0.to_scale_rotation_translation();
|
||||
let rotation_norm = rotation.normalize();
|
||||
translation += (rotation_norm * Vec3::NEG_Z).normalize() * movement.y;
|
||||
translation += (rotation_norm * Vec3::X).normalize() * movement.x;
|
||||
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation_norm, translation);
|
||||
}
|
||||
}
|
|
@ -1,43 +1,43 @@
|
|||
use kubi_ui::KubiUi;
|
||||
use kubi_ui_glium::GliumUiRenderer;
|
||||
use shipyard::{AllStoragesView, Unique, UniqueView, NonSendSync, UniqueViewMut};
|
||||
use crate::rendering::{Renderer, RenderTarget, WindowSize};
|
||||
|
||||
#[derive(Unique)]
|
||||
pub struct UiState {
|
||||
pub kui: KubiUi,
|
||||
pub renderer: GliumUiRenderer,
|
||||
}
|
||||
|
||||
pub fn kubi_ui_init(
|
||||
storages: AllStoragesView
|
||||
) {
|
||||
let renderer = storages.borrow::<NonSendSync<UniqueView<Renderer>>>().unwrap();
|
||||
storages.add_unique_non_send_sync(UiState {
|
||||
kui: KubiUi::new(),
|
||||
renderer: GliumUiRenderer::new(&renderer.display)
|
||||
});
|
||||
}
|
||||
|
||||
pub fn kubi_ui_begin(
|
||||
mut ui: NonSendSync<UniqueViewMut<UiState>>
|
||||
) {
|
||||
ui.kui.begin();
|
||||
}
|
||||
|
||||
pub fn kubi_ui_end(
|
||||
mut ui: NonSendSync<UniqueViewMut<UiState>>
|
||||
) {
|
||||
let ui: &mut UiState = &mut ui;
|
||||
let UiState { kui, renderer } = ui;
|
||||
kui.end();
|
||||
renderer.update(kui);
|
||||
}
|
||||
|
||||
pub fn kubi_ui_draw(
|
||||
ui: NonSendSync<UniqueView<UiState>>,
|
||||
mut target: NonSendSync<UniqueViewMut<RenderTarget>>,
|
||||
size: UniqueView<WindowSize>
|
||||
) {
|
||||
ui.renderer.draw(&mut target.0, size.0.as_vec2());
|
||||
}
|
||||
use hui::UiInstance;
|
||||
use hui_glium::GliumUiRenderer;
|
||||
use shipyard::{AllStoragesView, Unique, UniqueView, NonSendSync, UniqueViewMut};
|
||||
use crate::rendering::{Renderer, RenderTarget, WindowSize};
|
||||
|
||||
#[derive(Unique)]
|
||||
pub struct UiState {
|
||||
pub hui: UiInstance,
|
||||
pub renderer: GliumUiRenderer,
|
||||
}
|
||||
|
||||
pub fn kubi_ui_init(
|
||||
storages: AllStoragesView
|
||||
) {
|
||||
let renderer = storages.borrow::<NonSendSync<UniqueView<Renderer>>>().unwrap();
|
||||
storages.add_unique_non_send_sync(UiState {
|
||||
hui: UiInstance::new(),
|
||||
renderer: GliumUiRenderer::new(&renderer.display)
|
||||
});
|
||||
}
|
||||
|
||||
pub fn kubi_ui_begin(
|
||||
mut ui: NonSendSync<UniqueViewMut<UiState>>
|
||||
) {
|
||||
ui.hui.begin();
|
||||
}
|
||||
|
||||
pub fn kubi_ui_end(
|
||||
mut ui: NonSendSync<UniqueViewMut<UiState>>
|
||||
) {
|
||||
let ui: &mut UiState = &mut ui;
|
||||
let UiState { hui, renderer } = ui;
|
||||
hui.end();
|
||||
renderer.update(hui);
|
||||
}
|
||||
|
||||
pub fn kubi_ui_draw(
|
||||
ui: NonSendSync<UniqueView<UiState>>,
|
||||
mut target: NonSendSync<UniqueViewMut<RenderTarget>>,
|
||||
size: UniqueView<WindowSize>
|
||||
) {
|
||||
ui.renderer.draw(&mut target.0, size.0.as_vec2());
|
||||
}
|
|
@ -1,297 +1,301 @@
|
|||
use gilrs::{Gilrs, GamepadId, Button, Event, Axis};
|
||||
use glam::{Vec2, DVec2, vec2, dvec2};
|
||||
use winit::{
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
event::{DeviceEvent, DeviceId, ElementState, TouchPhase}
|
||||
};
|
||||
use hashbrown::HashMap;
|
||||
use tinyset::{SetU32, SetU64};
|
||||
use nohash_hasher::BuildNoHashHasher;
|
||||
use shipyard::{AllStoragesView, Unique, View, IntoIter, UniqueViewMut, Workload, IntoWorkload, UniqueView, NonSendSync};
|
||||
use crate::{
|
||||
events::{InputDeviceEvent, TouchEvent},
|
||||
rendering::WindowSize
|
||||
};
|
||||
|
||||
#[derive(Unique, Clone, Copy, Default, Debug)]
|
||||
pub struct Inputs {
|
||||
pub movement: Vec2,
|
||||
pub look: Vec2,
|
||||
pub action_a: bool,
|
||||
pub action_b: bool,
|
||||
}
|
||||
|
||||
#[derive(Unique, Clone, Copy, Default, Debug)]
|
||||
pub struct PrevInputs(pub Inputs);
|
||||
|
||||
#[derive(Unique, Clone, Default, Debug)]
|
||||
pub struct RawKbmInputState {
|
||||
pub keyboard_state: SetU32,
|
||||
pub button_state: [bool; 32],
|
||||
pub mouse_delta: DVec2
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub enum FingerCheck {
|
||||
#[default]
|
||||
Start,
|
||||
Current,
|
||||
StartOrCurrent,
|
||||
StartAndCurrent,
|
||||
NotMoved,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Finger {
|
||||
pub id: u64,
|
||||
pub device_id: DeviceId,
|
||||
pub prev_position: DVec2,
|
||||
pub start_position: DVec2,
|
||||
pub current_position: DVec2,
|
||||
pub has_moved: bool,
|
||||
}
|
||||
impl Finger {
|
||||
pub fn within_area(&self, area_pos: DVec2, area_size: DVec2, check: FingerCheck) -> bool {
|
||||
let within_area = |pos: DVec2| -> bool {
|
||||
((pos - area_pos).min_element() >= 0.) &&
|
||||
((pos - (area_pos + area_size)).max_element() <= 0.)
|
||||
};
|
||||
let start = within_area(self.start_position);
|
||||
let current = within_area(self.current_position);
|
||||
match check {
|
||||
FingerCheck::Start => start,
|
||||
FingerCheck::Current => current,
|
||||
FingerCheck::StartOrCurrent => start || current,
|
||||
FingerCheck::StartAndCurrent => start && current,
|
||||
FingerCheck::NotMoved => current && !self.has_moved,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Unique, Clone, Default, Debug)]
|
||||
pub struct RawTouchState {
|
||||
//TODO: handle multiple touch devices somehow
|
||||
pub fingers: HashMap<u64, Finger, BuildNoHashHasher<u64>>
|
||||
}
|
||||
|
||||
impl RawTouchState {
|
||||
pub fn query_area(&self, area_pos: DVec2, area_size: DVec2, check: FingerCheck) -> impl Iterator<Item = Finger> + '_ {
|
||||
self.fingers.iter().filter_map(move |(_, &finger)| {
|
||||
finger.within_area(area_pos, area_size, check).then_some(finger)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Unique)]
|
||||
pub struct GilrsWrapper(Option<Gilrs>);
|
||||
|
||||
#[derive(Unique, Default, Clone, Copy)]
|
||||
pub struct ActiveGamepad(Option<GamepadId>);
|
||||
|
||||
//maybe we should manage gamepad state ourselves just like keyboard?
|
||||
//at least for the sake of consitency
|
||||
|
||||
fn process_events(
|
||||
device_events: View<InputDeviceEvent>,
|
||||
mut input_state: UniqueViewMut<RawKbmInputState>,
|
||||
) {
|
||||
input_state.mouse_delta = DVec2::ZERO;
|
||||
for event in device_events.iter() {
|
||||
match &event.event {
|
||||
DeviceEvent::MouseMotion { delta } => {
|
||||
input_state.mouse_delta = DVec2::from(*delta);
|
||||
},
|
||||
DeviceEvent::Key(input) => {
|
||||
if let PhysicalKey::Code(code) = input.physical_key {
|
||||
match input.state {
|
||||
ElementState::Pressed => input_state.keyboard_state.insert(code as u32),
|
||||
ElementState::Released => input_state.keyboard_state.remove(code as u32),
|
||||
};
|
||||
}
|
||||
},
|
||||
DeviceEvent::Button { button, state } => {
|
||||
if *button < 32 {
|
||||
input_state.button_state[*button as usize] = matches!(*state, ElementState::Pressed);
|
||||
}
|
||||
},
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_touch_events(
|
||||
touch_events: View<TouchEvent>,
|
||||
mut touch_state: UniqueViewMut<RawTouchState>,
|
||||
) {
|
||||
for (_, finger) in &mut touch_state.fingers {
|
||||
finger.prev_position = finger.current_position;
|
||||
}
|
||||
for event in touch_events.iter() {
|
||||
let position = dvec2(event.0.location.x, event.0.location.y);
|
||||
match event.0.phase {
|
||||
TouchPhase::Started => {
|
||||
//println!("touch started: finger {}", event.0.id);
|
||||
touch_state.fingers.insert(event.0.id, Finger {
|
||||
id: event.0.id,
|
||||
device_id: event.0.device_id,
|
||||
start_position: position,
|
||||
current_position: position,
|
||||
prev_position: position,
|
||||
has_moved: false
|
||||
});
|
||||
},
|
||||
TouchPhase::Moved => {
|
||||
if let Some(finger) = touch_state.fingers.get_mut(&event.0.id) {
|
||||
finger.has_moved = true;
|
||||
finger.current_position = position;
|
||||
}
|
||||
},
|
||||
TouchPhase::Ended | TouchPhase::Cancelled => {
|
||||
//println!("touch ended: finger {}", event.0.id);
|
||||
touch_state.fingers.remove(&event.0.id);
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_gilrs_events(
|
||||
mut gilrs: NonSendSync<UniqueViewMut<GilrsWrapper>>,
|
||||
mut active_gamepad: UniqueViewMut<ActiveGamepad>
|
||||
) {
|
||||
if let Some(gilrs) = &mut gilrs.0 {
|
||||
while let Some(Event { id, event: _, time: _ }) = gilrs.next_event() {
|
||||
active_gamepad.0 = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn input_start(
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
mut prev_inputs: UniqueViewMut<PrevInputs>,
|
||||
) {
|
||||
prev_inputs.0 = *inputs;
|
||||
*inputs = Inputs::default();
|
||||
}
|
||||
|
||||
fn update_input_state (
|
||||
raw_inputs: UniqueView<RawKbmInputState>,
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
inputs.movement += Vec2::new(
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyD as u32) as u32 as f32 -
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyA as u32) as u32 as f32,
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyW as u32) as u32 as f32 -
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyS as u32) as u32 as f32
|
||||
);
|
||||
inputs.look += raw_inputs.mouse_delta.as_vec2();
|
||||
inputs.action_a |= raw_inputs.button_state[0];
|
||||
inputs.action_b |= raw_inputs.button_state[1];
|
||||
}
|
||||
|
||||
fn update_input_state_gamepad (
|
||||
gilrs: NonSendSync<UniqueView<GilrsWrapper>>,
|
||||
active_gamepad: UniqueView<ActiveGamepad>,
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
if let Some(gilrs) = &gilrs.0 {
|
||||
if let Some(gamepad) = active_gamepad.0.map(|id| gilrs.gamepad(id)) {
|
||||
let left_stick = vec2(gamepad.value(Axis::LeftStickX), gamepad.value(Axis::LeftStickY));
|
||||
let right_stick = vec2(gamepad.value(Axis::RightStickX), -gamepad.value(Axis::RightStickY));
|
||||
inputs.movement += left_stick;
|
||||
inputs.look += right_stick;
|
||||
inputs.action_a |= gamepad.is_pressed(Button::South);
|
||||
inputs.action_b |= gamepad.is_pressed(Button::East);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_input_state_touch (
|
||||
touch_state: UniqueView<RawTouchState>,
|
||||
win_size: UniqueView<WindowSize>,
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
let w = win_size.0.as_dvec2();
|
||||
|
||||
//Movement
|
||||
if let Some(finger) = touch_state.query_area(
|
||||
dvec2(0., 0.),
|
||||
dvec2(w.x / 2., w.y),
|
||||
FingerCheck::Start
|
||||
).next() {
|
||||
inputs.movement += (((finger.current_position - finger.start_position) / (w.x / 4.)) * dvec2(1., -1.)).as_vec2();
|
||||
}
|
||||
|
||||
//Action buttons
|
||||
let action_button_fingers = {
|
||||
let mut action_button_fingers = SetU64::new();
|
||||
|
||||
//Creates iterator of fingers that started within action button area
|
||||
let action_finger_iter = || touch_state.query_area(
|
||||
dvec2(w.x * 0.75, w.y * 0.666),
|
||||
dvec2(w.x * 0.25, w.y * 0.333),
|
||||
FingerCheck::Start
|
||||
);
|
||||
|
||||
//Action button A
|
||||
inputs.action_a |= action_finger_iter().filter(|finger| finger.within_area(
|
||||
dvec2(w.x * (0.75 + 0.125), w.y * 0.666),
|
||||
dvec2(w.x * 0.125, w.y * 0.333),
|
||||
FingerCheck::StartOrCurrent
|
||||
)).map(|x| action_button_fingers.insert(x.id)).next().is_some();
|
||||
|
||||
//Action button B
|
||||
inputs.action_b |= action_finger_iter().filter(|finger| finger.within_area(
|
||||
dvec2(w.x * 0.75, w.y * 0.666),
|
||||
dvec2(w.x * 0.125, w.y * 0.333),
|
||||
FingerCheck::StartOrCurrent
|
||||
)).map(|x| action_button_fingers.insert(x.id)).next().is_some();
|
||||
|
||||
action_button_fingers
|
||||
};
|
||||
|
||||
//Camera controls
|
||||
if let Some(finger) = touch_state.query_area(
|
||||
dvec2(w.x / 2., 0.),
|
||||
dvec2(w.x / 2., w.y),
|
||||
FingerCheck::Start
|
||||
).find(|x| !action_button_fingers.contains(x.id)) {
|
||||
inputs.look += (((finger.current_position - finger.prev_position) / (w.x / 4.)) * 300.).as_vec2();
|
||||
}
|
||||
}
|
||||
|
||||
fn input_end(
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
if inputs.movement.length() >= 1. {
|
||||
inputs.movement = inputs.movement.normalize();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_input (
|
||||
storages: AllStoragesView
|
||||
) {
|
||||
storages.add_unique_non_send_sync(GilrsWrapper(
|
||||
Gilrs::new().map_err(|x| {
|
||||
log::error!("Failed to initialize Gilrs");
|
||||
x
|
||||
}).ok()
|
||||
));
|
||||
storages.add_unique(ActiveGamepad::default());
|
||||
storages.add_unique(Inputs::default());
|
||||
storages.add_unique(PrevInputs::default());
|
||||
storages.add_unique(RawKbmInputState::default());
|
||||
storages.add_unique(RawTouchState::default());
|
||||
}
|
||||
|
||||
pub fn process_inputs() -> Workload {
|
||||
(
|
||||
process_events,
|
||||
process_touch_events,
|
||||
process_gilrs_events,
|
||||
input_start,
|
||||
update_input_state,
|
||||
update_input_state_touch,
|
||||
update_input_state_gamepad,
|
||||
input_end,
|
||||
).into_sequential_workload()
|
||||
}
|
||||
use gilrs::{Gilrs, GamepadId, Button, Event, Axis};
|
||||
use glam::{Vec2, DVec2, vec2, dvec2};
|
||||
use winit::{
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
event::{DeviceEvent, DeviceId, ElementState, TouchPhase}
|
||||
};
|
||||
use hashbrown::HashMap;
|
||||
use tinyset::{SetU32, SetU64};
|
||||
use nohash_hasher::BuildNoHashHasher;
|
||||
use shipyard::{AllStoragesView, Unique, View, IntoIter, UniqueViewMut, Workload, IntoWorkload, UniqueView, NonSendSync};
|
||||
use crate::{
|
||||
events::{InputDeviceEvent, TouchEvent},
|
||||
rendering::WindowSize
|
||||
};
|
||||
|
||||
#[derive(Unique, Clone, Copy, Default, Debug)]
|
||||
pub struct Inputs {
|
||||
pub movement: Vec2,
|
||||
pub look: Vec2,
|
||||
pub action_a: bool,
|
||||
pub action_b: bool,
|
||||
pub jump: bool,
|
||||
}
|
||||
|
||||
#[derive(Unique, Clone, Copy, Default, Debug)]
|
||||
pub struct PrevInputs(pub Inputs);
|
||||
|
||||
#[derive(Unique, Clone, Default, Debug)]
|
||||
pub struct RawKbmInputState {
|
||||
pub keyboard_state: SetU32,
|
||||
pub button_state: [bool; 32],
|
||||
pub mouse_delta: DVec2
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub enum FingerCheck {
|
||||
#[default]
|
||||
Start,
|
||||
Current,
|
||||
StartOrCurrent,
|
||||
StartAndCurrent,
|
||||
NotMoved,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Finger {
|
||||
pub id: u64,
|
||||
pub device_id: DeviceId,
|
||||
pub prev_position: DVec2,
|
||||
pub start_position: DVec2,
|
||||
pub current_position: DVec2,
|
||||
pub has_moved: bool,
|
||||
}
|
||||
impl Finger {
|
||||
pub fn within_area(&self, area_pos: DVec2, area_size: DVec2, check: FingerCheck) -> bool {
|
||||
let within_area = |pos: DVec2| -> bool {
|
||||
((pos - area_pos).min_element() >= 0.) &&
|
||||
((pos - (area_pos + area_size)).max_element() <= 0.)
|
||||
};
|
||||
let start = within_area(self.start_position);
|
||||
let current = within_area(self.current_position);
|
||||
match check {
|
||||
FingerCheck::Start => start,
|
||||
FingerCheck::Current => current,
|
||||
FingerCheck::StartOrCurrent => start || current,
|
||||
FingerCheck::StartAndCurrent => start && current,
|
||||
FingerCheck::NotMoved => current && !self.has_moved,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Unique, Clone, Default, Debug)]
|
||||
pub struct RawTouchState {
|
||||
//TODO: handle multiple touch devices somehow
|
||||
pub fingers: HashMap<u64, Finger, BuildNoHashHasher<u64>>
|
||||
}
|
||||
|
||||
impl RawTouchState {
|
||||
pub fn query_area(&self, area_pos: DVec2, area_size: DVec2, check: FingerCheck) -> impl Iterator<Item = Finger> + '_ {
|
||||
self.fingers.iter().filter_map(move |(_, &finger)| {
|
||||
finger.within_area(area_pos, area_size, check).then_some(finger)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Unique)]
|
||||
pub struct GilrsWrapper(Option<Gilrs>);
|
||||
|
||||
#[derive(Unique, Default, Clone, Copy)]
|
||||
pub struct ActiveGamepad(Option<GamepadId>);
|
||||
|
||||
//maybe we should manage gamepad state ourselves just like keyboard?
|
||||
//at least for the sake of consitency
|
||||
|
||||
fn process_events(
|
||||
device_events: View<InputDeviceEvent>,
|
||||
mut input_state: UniqueViewMut<RawKbmInputState>,
|
||||
) {
|
||||
input_state.mouse_delta = DVec2::ZERO;
|
||||
for event in device_events.iter() {
|
||||
match &event.event {
|
||||
DeviceEvent::MouseMotion { delta } => {
|
||||
input_state.mouse_delta = DVec2::from(*delta);
|
||||
},
|
||||
DeviceEvent::Key(input) => {
|
||||
if let PhysicalKey::Code(code) = input.physical_key {
|
||||
match input.state {
|
||||
ElementState::Pressed => input_state.keyboard_state.insert(code as u32),
|
||||
ElementState::Released => input_state.keyboard_state.remove(code as u32),
|
||||
};
|
||||
}
|
||||
},
|
||||
DeviceEvent::Button { button, state } => {
|
||||
if *button < 32 {
|
||||
input_state.button_state[*button as usize] = matches!(*state, ElementState::Pressed);
|
||||
}
|
||||
},
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_touch_events(
|
||||
touch_events: View<TouchEvent>,
|
||||
mut touch_state: UniqueViewMut<RawTouchState>,
|
||||
) {
|
||||
for (_, finger) in &mut touch_state.fingers {
|
||||
finger.prev_position = finger.current_position;
|
||||
}
|
||||
for event in touch_events.iter() {
|
||||
let position = dvec2(event.0.location.x, event.0.location.y);
|
||||
match event.0.phase {
|
||||
TouchPhase::Started => {
|
||||
//println!("touch started: finger {}", event.0.id);
|
||||
touch_state.fingers.insert(event.0.id, Finger {
|
||||
id: event.0.id,
|
||||
device_id: event.0.device_id,
|
||||
start_position: position,
|
||||
current_position: position,
|
||||
prev_position: position,
|
||||
has_moved: false
|
||||
});
|
||||
},
|
||||
TouchPhase::Moved => {
|
||||
if let Some(finger) = touch_state.fingers.get_mut(&event.0.id) {
|
||||
finger.has_moved = true;
|
||||
finger.current_position = position;
|
||||
}
|
||||
},
|
||||
TouchPhase::Ended | TouchPhase::Cancelled => {
|
||||
//println!("touch ended: finger {}", event.0.id);
|
||||
touch_state.fingers.remove(&event.0.id);
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_gilrs_events(
|
||||
mut gilrs: NonSendSync<UniqueViewMut<GilrsWrapper>>,
|
||||
mut active_gamepad: UniqueViewMut<ActiveGamepad>
|
||||
) {
|
||||
if let Some(gilrs) = &mut gilrs.0 {
|
||||
while let Some(Event { id, event: _, time: _ }) = gilrs.next_event() {
|
||||
active_gamepad.0 = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn input_start(
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
mut prev_inputs: UniqueViewMut<PrevInputs>,
|
||||
) {
|
||||
prev_inputs.0 = *inputs;
|
||||
*inputs = Inputs::default();
|
||||
}
|
||||
|
||||
fn update_input_state (
|
||||
raw_inputs: UniqueView<RawKbmInputState>,
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
inputs.movement += Vec2::new(
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyD as u32) as u32 as f32 -
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyA as u32) as u32 as f32,
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyW as u32) as u32 as f32 -
|
||||
raw_inputs.keyboard_state.contains(KeyCode::KeyS as u32) as u32 as f32
|
||||
);
|
||||
inputs.look += raw_inputs.mouse_delta.as_vec2();
|
||||
inputs.action_a |= raw_inputs.button_state[0];
|
||||
inputs.action_b |= raw_inputs.button_state[1];
|
||||
inputs.jump |= raw_inputs.keyboard_state.contains(KeyCode::Space as u32);
|
||||
}
|
||||
|
||||
fn update_input_state_gamepad (
|
||||
gilrs: NonSendSync<UniqueView<GilrsWrapper>>,
|
||||
active_gamepad: UniqueView<ActiveGamepad>,
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
if let Some(gilrs) = &gilrs.0 {
|
||||
if let Some(gamepad) = active_gamepad.0.map(|id| gilrs.gamepad(id)) {
|
||||
let left_stick = vec2(gamepad.value(Axis::LeftStickX), gamepad.value(Axis::LeftStickY));
|
||||
let right_stick = vec2(gamepad.value(Axis::RightStickX), -gamepad.value(Axis::RightStickY));
|
||||
inputs.movement += left_stick;
|
||||
//HACK: for now, we multiply look by 2 to make it feel more responsive
|
||||
inputs.look += right_stick * 2.;
|
||||
inputs.action_a |= gamepad.is_pressed(Button::West);
|
||||
inputs.action_b |= gamepad.is_pressed(Button::East);
|
||||
inputs.jump |= gamepad.is_pressed(Button::South);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn update_input_state_touch (
|
||||
touch_state: UniqueView<RawTouchState>,
|
||||
win_size: UniqueView<WindowSize>,
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
let w = win_size.0.as_dvec2();
|
||||
|
||||
//Movement
|
||||
if let Some(finger) = touch_state.query_area(
|
||||
dvec2(0., 0.),
|
||||
dvec2(w.x / 2., w.y),
|
||||
FingerCheck::Start
|
||||
).next() {
|
||||
inputs.movement += (((finger.current_position - finger.start_position) / (w.x / 4.)) * dvec2(1., -1.)).as_vec2();
|
||||
}
|
||||
|
||||
//Action buttons
|
||||
let action_button_fingers = {
|
||||
let mut action_button_fingers = SetU64::new();
|
||||
|
||||
//Creates iterator of fingers that started within action button area
|
||||
let action_finger_iter = || touch_state.query_area(
|
||||
dvec2(w.x * 0.75, w.y * 0.666),
|
||||
dvec2(w.x * 0.25, w.y * 0.333),
|
||||
FingerCheck::Start
|
||||
);
|
||||
|
||||
//Action button A
|
||||
inputs.action_a |= action_finger_iter().filter(|finger| finger.within_area(
|
||||
dvec2(w.x * (0.75 + 0.125), w.y * 0.666),
|
||||
dvec2(w.x * 0.125, w.y * 0.333),
|
||||
FingerCheck::StartOrCurrent
|
||||
)).map(|x| action_button_fingers.insert(x.id)).next().is_some();
|
||||
|
||||
//Action button B
|
||||
inputs.action_b |= action_finger_iter().filter(|finger| finger.within_area(
|
||||
dvec2(w.x * 0.75, w.y * 0.666),
|
||||
dvec2(w.x * 0.125, w.y * 0.333),
|
||||
FingerCheck::StartOrCurrent
|
||||
)).map(|x| action_button_fingers.insert(x.id)).next().is_some();
|
||||
|
||||
action_button_fingers
|
||||
};
|
||||
|
||||
//Camera controls
|
||||
if let Some(finger) = touch_state.query_area(
|
||||
dvec2(w.x / 2., 0.),
|
||||
dvec2(w.x / 2., w.y),
|
||||
FingerCheck::Start
|
||||
).find(|x| !action_button_fingers.contains(x.id)) {
|
||||
inputs.look += (((finger.current_position - finger.prev_position) / (w.x / 4.)) * 300.).as_vec2();
|
||||
}
|
||||
}
|
||||
|
||||
fn input_end(
|
||||
mut inputs: UniqueViewMut<Inputs>,
|
||||
) {
|
||||
if inputs.movement.length() >= 1. {
|
||||
inputs.movement = inputs.movement.normalize();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_input (
|
||||
storages: AllStoragesView
|
||||
) {
|
||||
storages.add_unique_non_send_sync(GilrsWrapper(
|
||||
Gilrs::new().map_err(|x| {
|
||||
log::error!("Failed to initialize Gilrs");
|
||||
x
|
||||
}).ok()
|
||||
));
|
||||
storages.add_unique(ActiveGamepad::default());
|
||||
storages.add_unique(Inputs::default());
|
||||
storages.add_unique(PrevInputs::default());
|
||||
storages.add_unique(RawKbmInputState::default());
|
||||
storages.add_unique(RawTouchState::default());
|
||||
}
|
||||
|
||||
pub fn process_inputs() -> Workload {
|
||||
(
|
||||
process_events,
|
||||
process_touch_events,
|
||||
process_gilrs_events,
|
||||
input_start,
|
||||
update_input_state,
|
||||
update_input_state_touch,
|
||||
update_input_state_gamepad,
|
||||
input_end,
|
||||
).into_sequential_workload()
|
||||
}
|
||||
|
|
|
@ -23,13 +23,13 @@ pub(crate) mod settings;
|
|||
pub(crate) mod camera;
|
||||
pub(crate) mod events;
|
||||
pub(crate) mod input;
|
||||
pub(crate) mod fly_controller;
|
||||
pub(crate) mod player_controller;
|
||||
pub(crate) mod block_placement;
|
||||
pub(crate) mod delta_time;
|
||||
pub(crate) mod cursor_lock;
|
||||
pub(crate) mod control_flow;
|
||||
pub(crate) mod state;
|
||||
pub(crate) mod kubi_ui_integration;
|
||||
pub(crate) mod hui_integration;
|
||||
pub(crate) mod networking;
|
||||
pub(crate) mod init;
|
||||
pub(crate) mod color;
|
||||
|
@ -57,7 +57,7 @@ use events::{
|
|||
player_actions::generate_move_events,
|
||||
};
|
||||
use input::{init_input, process_inputs};
|
||||
use fly_controller::update_controllers;
|
||||
use player_controller::{debug_switch_ctl_type, update_player_controllers};
|
||||
use rendering::{
|
||||
Renderer,
|
||||
RenderTarget,
|
||||
|
@ -77,7 +77,7 @@ use control_flow::{exit_on_esc, insert_control_flow_unique, RequestExit};
|
|||
use state::{is_ingame, is_ingame_or_loading, is_loading, init_state, update_state, is_connecting};
|
||||
use networking::{update_networking, update_networking_late, is_multiplayer, disconnect_on_exit, is_singleplayer};
|
||||
use init::initialize_from_args;
|
||||
use kubi_ui_integration::{kubi_ui_init, kubi_ui_begin, kubi_ui_end, kubi_ui_draw};
|
||||
use hui_integration::{kubi_ui_init, kubi_ui_begin, kubi_ui_end, kubi_ui_draw};
|
||||
use loading_screen::update_loading_screen;
|
||||
use connecting_screen::switch_to_loading_if_connected;
|
||||
use fixed_timestamp::init_fixed_timestamp_storage;
|
||||
|
@ -133,7 +133,8 @@ fn update() -> Workload {
|
|||
update_loaded_world_around_player,
|
||||
).into_sequential_workload().run_if(is_ingame_or_loading),
|
||||
(
|
||||
update_controllers,
|
||||
debug_switch_ctl_type,
|
||||
update_player_controllers,
|
||||
update_client_physics_late,
|
||||
generate_move_events,
|
||||
update_raycasts,
|
||||
|
|
|
@ -1,60 +1,60 @@
|
|||
use kubi_ui::element::progress_bar::ProgressBar;
|
||||
use shipyard::{UniqueView, UniqueViewMut, Workload, NonSendSync, IntoWorkload};
|
||||
use winit::keyboard::KeyCode;
|
||||
use crate::{
|
||||
world::ChunkStorage,
|
||||
state::{GameState, NextState},
|
||||
rendering::WindowSize,
|
||||
input::RawKbmInputState,
|
||||
kubi_ui_integration::UiState,
|
||||
};
|
||||
|
||||
fn render_progressbar(
|
||||
mut ui: NonSendSync<UniqueViewMut<UiState>>,
|
||||
world: UniqueView<ChunkStorage>,
|
||||
size: UniqueView<WindowSize>
|
||||
) {
|
||||
let value = {
|
||||
let loaded = world.chunks.iter().fold(0, |acc, (&_, chunk)| {
|
||||
acc + chunk.desired_state.matches_current(chunk.current_state) as usize
|
||||
});
|
||||
let total = world.chunks.len();
|
||||
loaded as f32 / total as f32
|
||||
};
|
||||
ui.kui.add(
|
||||
ProgressBar { value, ..Default::default() },
|
||||
size.0.as_vec2()
|
||||
);
|
||||
}
|
||||
|
||||
fn switch_to_ingame_if_loaded(
|
||||
world: UniqueView<ChunkStorage>,
|
||||
mut state: UniqueViewMut<NextState>
|
||||
) {
|
||||
if world.chunks.is_empty() {
|
||||
return
|
||||
}
|
||||
if world.chunks.iter().all(|(_, chunk)| {
|
||||
chunk.desired_state.matches_current(chunk.current_state)
|
||||
}) {
|
||||
log::info!("Finished loading chunks");
|
||||
state.0 = Some(GameState::InGame);
|
||||
}
|
||||
}
|
||||
|
||||
fn override_loading(
|
||||
kbm_state: UniqueView<RawKbmInputState>,
|
||||
mut state: UniqueViewMut<NextState>
|
||||
) {
|
||||
if kbm_state.keyboard_state.contains(KeyCode::KeyF as u32) {
|
||||
state.0 = Some(GameState::InGame);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_loading_screen() -> Workload {
|
||||
(
|
||||
render_progressbar,
|
||||
override_loading,
|
||||
switch_to_ingame_if_loaded,
|
||||
).into_sequential_workload()
|
||||
}
|
||||
use hui::element::progress_bar::ProgressBar;
|
||||
use shipyard::{UniqueView, UniqueViewMut, Workload, NonSendSync, IntoWorkload};
|
||||
use winit::keyboard::KeyCode;
|
||||
use crate::{
|
||||
world::ChunkStorage,
|
||||
state::{GameState, NextState},
|
||||
rendering::WindowSize,
|
||||
input::RawKbmInputState,
|
||||
hui_integration::UiState,
|
||||
};
|
||||
|
||||
fn render_progressbar(
|
||||
mut ui: NonSendSync<UniqueViewMut<UiState>>,
|
||||
world: UniqueView<ChunkStorage>,
|
||||
size: UniqueView<WindowSize>
|
||||
) {
|
||||
let value = {
|
||||
let loaded = world.chunks.iter().fold(0, |acc, (&_, chunk)| {
|
||||
acc + chunk.desired_state.matches_current(chunk.current_state) as usize
|
||||
});
|
||||
let total = world.chunks.len();
|
||||
loaded as f32 / total as f32
|
||||
};
|
||||
ui.hui.add(
|
||||
ProgressBar { value, ..Default::default() },
|
||||
size.0.as_vec2()
|
||||
);
|
||||
}
|
||||
|
||||
fn switch_to_ingame_if_loaded(
|
||||
world: UniqueView<ChunkStorage>,
|
||||
mut state: UniqueViewMut<NextState>
|
||||
) {
|
||||
if world.chunks.is_empty() {
|
||||
return
|
||||
}
|
||||
if world.chunks.iter().all(|(_, chunk)| {
|
||||
chunk.desired_state.matches_current(chunk.current_state)
|
||||
}) {
|
||||
log::info!("Finished loading chunks");
|
||||
state.0 = Some(GameState::InGame);
|
||||
}
|
||||
}
|
||||
|
||||
fn override_loading(
|
||||
kbm_state: UniqueView<RawKbmInputState>,
|
||||
mut state: UniqueViewMut<NextState>
|
||||
) {
|
||||
if kbm_state.keyboard_state.contains(KeyCode::KeyF as u32) {
|
||||
state.0 = Some(GameState::InGame);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_loading_screen() -> Workload {
|
||||
(
|
||||
render_progressbar,
|
||||
override_loading,
|
||||
switch_to_ingame_if_loaded,
|
||||
).into_sequential_workload()
|
||||
}
|
||||
|
|
|
@ -1,101 +1,101 @@
|
|||
use glam::{Vec3, Mat4};
|
||||
use shipyard::{UniqueViewMut, View, IntoIter, AllStoragesView, AllStoragesViewMut, UniqueView, ViewMut, Get};
|
||||
use uflow::{SendMode, client::Event as ClientEvent};
|
||||
use kubi_shared::{
|
||||
transform::Transform,
|
||||
networking::{
|
||||
messages::{ClientToServerMessage, ServerToClientMessage, ServerToClientMessageType},
|
||||
channels::Channel,
|
||||
client::ClientIdMap,
|
||||
},
|
||||
};
|
||||
use crate::{
|
||||
events::player_actions::PlayerActionEvent,
|
||||
player::spawn_remote_player_multiplayer,
|
||||
};
|
||||
use super::{UdpClient, NetworkEvent};
|
||||
|
||||
pub fn init_client_map(
|
||||
storages: AllStoragesView,
|
||||
) {
|
||||
storages.add_unique(ClientIdMap::new());
|
||||
}
|
||||
|
||||
pub fn send_player_movement_events(
|
||||
actions: View<PlayerActionEvent>,
|
||||
mut client: UniqueViewMut<UdpClient>,
|
||||
) {
|
||||
for event in actions.iter() {
|
||||
let PlayerActionEvent::PositionChanged { position, direction } = event else {
|
||||
continue
|
||||
};
|
||||
client.0.send(
|
||||
postcard::to_allocvec(&ClientToServerMessage::PositionChanged {
|
||||
position: *position,
|
||||
velocity: Vec3::ZERO,
|
||||
direction: *direction
|
||||
}).unwrap().into_boxed_slice(),
|
||||
Channel::Move as usize,
|
||||
SendMode::TimeSensitive
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receive_player_movement_events(
|
||||
mut transforms: ViewMut<Transform>,
|
||||
network_events: View<NetworkEvent>,
|
||||
id_map: UniqueView<ClientIdMap>
|
||||
) {
|
||||
for event in network_events.iter() {
|
||||
let ClientEvent::Receive(data) = &event.0 else {
|
||||
continue
|
||||
};
|
||||
|
||||
if !event.is_message_of_type::<{ServerToClientMessageType::PlayerPositionChanged as u8}>() {
|
||||
continue
|
||||
}
|
||||
|
||||
let Ok(parsed_message) = postcard::from_bytes(data) else {
|
||||
log::error!("Malformed message");
|
||||
continue
|
||||
};
|
||||
|
||||
let ServerToClientMessage::PlayerPositionChanged {
|
||||
client_id, position, direction
|
||||
} = parsed_message else { unreachable!() };
|
||||
|
||||
let Some(&ent_id) = id_map.0.get(&client_id) else {
|
||||
log::error!("Not in client-id map");
|
||||
continue
|
||||
};
|
||||
|
||||
let mut transform = (&mut transforms).get(ent_id)
|
||||
.expect("invalid player entity id");
|
||||
|
||||
transform.0 = Mat4::from_rotation_translation(direction, position);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receive_player_connect_events(
|
||||
mut storages: AllStoragesViewMut,
|
||||
) {
|
||||
let messages: Vec<ServerToClientMessage> = storages.borrow::<View<NetworkEvent>>().unwrap().iter().filter_map(|event| {
|
||||
let ClientEvent::Receive(data) = &event.0 else {
|
||||
return None
|
||||
};
|
||||
if !event.is_message_of_type::<{ServerToClientMessageType::PlayerConnected as u8}>() {
|
||||
return None
|
||||
};
|
||||
let Ok(parsed_message) = postcard::from_bytes(data) else {
|
||||
log::error!("Malformed message");
|
||||
return None
|
||||
};
|
||||
Some(parsed_message)
|
||||
}).collect();
|
||||
|
||||
for message in messages {
|
||||
let ServerToClientMessage::PlayerConnected { init } = message else { unreachable!() };
|
||||
log::info!("player connected: {} (id {})", init.username, init.client_id);
|
||||
spawn_remote_player_multiplayer(&mut storages, init);
|
||||
}
|
||||
}
|
||||
use glam::{Vec3, Mat4};
|
||||
use shipyard::{UniqueViewMut, View, IntoIter, AllStoragesView, AllStoragesViewMut, UniqueView, ViewMut, Get};
|
||||
use uflow::{SendMode, client::Event as ClientEvent};
|
||||
use kubi_shared::{
|
||||
transform::Transform,
|
||||
networking::{
|
||||
messages::{ClientToServerMessage, ServerToClientMessage, ServerToClientMessageType},
|
||||
channels::Channel,
|
||||
client::ClientIdMap,
|
||||
},
|
||||
};
|
||||
use crate::{
|
||||
events::player_actions::PlayerActionEvent,
|
||||
player::spawn_remote_player_multiplayer,
|
||||
};
|
||||
use super::{UdpClient, NetworkEvent};
|
||||
|
||||
pub fn init_client_map(
|
||||
storages: AllStoragesView,
|
||||
) {
|
||||
storages.add_unique(ClientIdMap::new());
|
||||
}
|
||||
|
||||
pub fn send_player_movement_events(
|
||||
actions: View<PlayerActionEvent>,
|
||||
mut client: UniqueViewMut<UdpClient>,
|
||||
) {
|
||||
for event in actions.iter() {
|
||||
let PlayerActionEvent::PositionChanged { position, velocity, direction } = event else {
|
||||
continue
|
||||
};
|
||||
client.0.send(
|
||||
postcard::to_allocvec(&ClientToServerMessage::PositionChanged {
|
||||
position: *position,
|
||||
velocity: *velocity,
|
||||
direction: *direction
|
||||
}).unwrap().into_boxed_slice(),
|
||||
Channel::Move as usize,
|
||||
SendMode::TimeSensitive
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receive_player_movement_events(
|
||||
mut transforms: ViewMut<Transform>,
|
||||
network_events: View<NetworkEvent>,
|
||||
id_map: UniqueView<ClientIdMap>
|
||||
) {
|
||||
for event in network_events.iter() {
|
||||
let ClientEvent::Receive(data) = &event.0 else {
|
||||
continue
|
||||
};
|
||||
|
||||
if !event.is_message_of_type::<{ServerToClientMessageType::PlayerPositionChanged as u8}>() {
|
||||
continue
|
||||
}
|
||||
|
||||
let Ok(parsed_message) = postcard::from_bytes(data) else {
|
||||
log::error!("Malformed message");
|
||||
continue
|
||||
};
|
||||
|
||||
let ServerToClientMessage::PlayerPositionChanged {
|
||||
client_id, position, direction
|
||||
} = parsed_message else { unreachable!() };
|
||||
|
||||
let Some(&ent_id) = id_map.0.get(&client_id) else {
|
||||
log::error!("Not in client-id map");
|
||||
continue
|
||||
};
|
||||
|
||||
let mut transform = (&mut transforms).get(ent_id)
|
||||
.expect("invalid player entity id");
|
||||
|
||||
transform.0 = Mat4::from_rotation_translation(direction, position);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn receive_player_connect_events(
|
||||
mut storages: AllStoragesViewMut,
|
||||
) {
|
||||
let messages: Vec<ServerToClientMessage> = storages.borrow::<View<NetworkEvent>>().unwrap().iter().filter_map(|event| {
|
||||
let ClientEvent::Receive(data) = &event.0 else {
|
||||
return None
|
||||
};
|
||||
if !event.is_message_of_type::<{ServerToClientMessageType::PlayerConnected as u8}>() {
|
||||
return None
|
||||
};
|
||||
let Ok(parsed_message) = postcard::from_bytes(data) else {
|
||||
log::error!("Malformed message");
|
||||
return None
|
||||
};
|
||||
Some(parsed_message)
|
||||
}).collect();
|
||||
|
||||
for message in messages {
|
||||
let ServerToClientMessage::PlayerConnected { init } = message else { unreachable!() };
|
||||
log::info!("player connected: {} (id {})", init.username, init.client_id);
|
||||
spawn_remote_player_multiplayer(&mut storages, init);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@ use kubi_shared::{
|
|||
use crate::{
|
||||
camera::Camera,
|
||||
client_physics::ClPhysicsActor,
|
||||
fly_controller::FlyController,
|
||||
player_controller::PlayerController,
|
||||
transform::Transform,
|
||||
world::raycast::LookingAtBlock
|
||||
};
|
||||
|
@ -31,7 +31,7 @@ pub fn spawn_player (
|
|||
Health::new(PLAYER_HEALTH),
|
||||
Transform::default(),
|
||||
Camera::default(),
|
||||
FlyController,
|
||||
PlayerController::DEFAULT_FPS_CTL,
|
||||
LookingAtBlock::default(),
|
||||
PlayerHolding(Some(Block::Cobblestone)),
|
||||
Username("LocalPlayer".into()),
|
||||
|
@ -53,7 +53,7 @@ pub fn spawn_local_player_multiplayer (
|
|||
init.health,
|
||||
Transform(Mat4::from_rotation_translation(init.direction, init.position)),
|
||||
Camera::default(),
|
||||
FlyController,
|
||||
PlayerController::DEFAULT_FPS_CTL,
|
||||
LookingAtBlock::default(),
|
||||
PlayerHolding::default(),
|
||||
),(
|
||||
|
|
130
kubi/src/player_controller.rs
Normal file
130
kubi/src/player_controller.rs
Normal file
|
@ -0,0 +1,130 @@
|
|||
use glam::{vec3, EulerRot, Mat4, Quat, Vec2, Vec2Swizzles, Vec3, Vec3Swizzles};
|
||||
use shipyard::{track, Component, Get, IntoIter, IntoWithId, IntoWorkload, Unique, UniqueView, View, ViewMut, Workload};
|
||||
use winit::keyboard::KeyCode;
|
||||
use std::f32::consts::PI;
|
||||
use crate::{client_physics::ClPhysicsActor, delta_time::DeltaTime, input::{Inputs, PrevInputs, RawKbmInputState}, settings::GameSettings, transform::Transform};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PlayerControllerType {
|
||||
FlyCam,
|
||||
FpsCtl,
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct PlayerController {
|
||||
pub control_type: PlayerControllerType,
|
||||
pub speed: f32,
|
||||
}
|
||||
|
||||
impl PlayerController {
|
||||
pub const DEFAULT_FLY_CAM: Self = Self {
|
||||
control_type: PlayerControllerType::FlyCam,
|
||||
speed: 50.,
|
||||
};
|
||||
|
||||
pub const DEFAULT_FPS_CTL: Self = Self {
|
||||
control_type: PlayerControllerType::FpsCtl,
|
||||
speed: 10.,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn update_player_controllers() -> Workload {
|
||||
(
|
||||
update_look,
|
||||
update_movement
|
||||
).into_sequential_workload()
|
||||
}
|
||||
|
||||
const MAX_PITCH: f32 = PI/2. - 0.05;
|
||||
|
||||
fn update_look(
|
||||
controllers: View<PlayerController>,
|
||||
mut transforms: ViewMut<Transform, track::All>,
|
||||
inputs: UniqueView<Inputs>,
|
||||
settings: UniqueView<GameSettings>,
|
||||
dt: UniqueView<DeltaTime>,
|
||||
) {
|
||||
let look = inputs.look * settings.mouse_sensitivity * dt.0.as_secs_f32();
|
||||
if look == Vec2::ZERO { return }
|
||||
for (_, mut transform) in (&controllers, &mut transforms).iter() {
|
||||
let (scale, mut rotation, translation) = transform.0.to_scale_rotation_translation();
|
||||
let (mut yaw, mut pitch, _roll) = rotation.to_euler(EulerRot::YXZ);
|
||||
yaw -= look.x;
|
||||
pitch -= look.y;
|
||||
pitch = pitch.clamp(-MAX_PITCH, MAX_PITCH);
|
||||
rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, 0.).normalize();
|
||||
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation, translation);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_movement(
|
||||
controllers: View<PlayerController>,
|
||||
mut transforms: ViewMut<Transform, track::All>,
|
||||
mut actors: ViewMut<ClPhysicsActor>,
|
||||
inputs: UniqueView<Inputs>,
|
||||
prev_inputs: UniqueView<PrevInputs>,
|
||||
dt: UniqueView<DeltaTime>,
|
||||
) {
|
||||
let jump = inputs.jump && !prev_inputs.0.jump;
|
||||
if (inputs.movement == Vec2::ZERO) && !jump { return }
|
||||
let movement = inputs.movement.extend(jump as u32 as f32).xzy();
|
||||
for (id, (ctl, mut transform)) in (&controllers, &mut transforms).iter().with_id() {
|
||||
let (scale, rotation, mut translation) = transform.0.to_scale_rotation_translation();
|
||||
let rotation_norm = rotation.normalize();
|
||||
match ctl.control_type {
|
||||
PlayerControllerType::FlyCam => {
|
||||
translation += (rotation_norm * Vec3::NEG_Z).normalize() * movement.z * ctl.speed * dt.0.as_secs_f32();
|
||||
translation += (rotation_norm * Vec3::X).normalize() * movement.x * ctl.speed * dt.0.as_secs_f32();
|
||||
translation += Vec3::Y * movement.y * ctl.speed * dt.0.as_secs_f32();
|
||||
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation_norm, translation);
|
||||
},
|
||||
PlayerControllerType::FpsCtl => {
|
||||
let mut actor = (&mut actors).get(id).unwrap();
|
||||
let actor_on_ground = actor.on_ground();
|
||||
|
||||
let euler = rotation_norm.to_euler(EulerRot::YZX);
|
||||
let right = Vec2::from_angle(-euler.0).extend(0.).xzy();
|
||||
let forward = Vec2::from_angle(-(euler.0 + PI/2.)).extend(0.).xzy();
|
||||
|
||||
//TODO: remove hardcoded jump force
|
||||
// actor.apply_constant_force(ctl.speed * (
|
||||
// (forward * movement.z) +
|
||||
// (right * movement.x)
|
||||
// ));
|
||||
actor.apply_force(
|
||||
ctl.speed * (
|
||||
(forward * movement.z) +
|
||||
(right * movement.x)
|
||||
) +
|
||||
Vec3::Y * movement.y * 1250. * (actor_on_ground as u8 as f32)
|
||||
);
|
||||
|
||||
// actor.decel =
|
||||
// (right * (1. - inputs.movement.x.abs()) * 10.) +
|
||||
// (forward * (1. - inputs.movement.y.abs()) * 10.);
|
||||
|
||||
// translation += forward * movement.z * ctl.speed * dt.0.as_secs_f32();
|
||||
// translation += right * movement.x * ctl.speed * dt.0.as_secs_f32();
|
||||
// translation += Vec3::Y * movement.y * ctl.speed * dt.0.as_secs_f32();
|
||||
|
||||
// transform.0 = Mat4::from_scale_rotation_translation(scale, rotation_norm, translation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn debug_switch_ctl_type(
|
||||
mut controllers: ViewMut<PlayerController>,
|
||||
mut actors: ViewMut<ClPhysicsActor>,
|
||||
kbm_state: UniqueView<RawKbmInputState>,
|
||||
) {
|
||||
for (mut controller, mut actor) in (&mut controllers, &mut actors).iter() {
|
||||
if kbm_state.keyboard_state.contains(KeyCode::F4 as u32) {
|
||||
*controller = PlayerController::DEFAULT_FPS_CTL;
|
||||
actor.disable = false;
|
||||
} else if kbm_state.keyboard_state.contains(KeyCode::F5 as u32) {
|
||||
*controller = PlayerController::DEFAULT_FLY_CAM;
|
||||
actor.disable = true;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue