From 94eaeaa0091dfa1711afc9b5d163cee747853948 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Fri, 13 Mar 2020 21:38:11 +0100 Subject: [PATCH 01/35] impl IntoIterator for Vec2, Vec3 --- rask-engine/src/math/vec2.rs | 12 ++++++++++++ rask-engine/src/math/vec3.rs | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/rask-engine/src/math/vec2.rs b/rask-engine/src/math/vec2.rs index 1c68caf9..f62793ae 100644 --- a/rask-engine/src/math/vec2.rs +++ b/rask-engine/src/math/vec2.rs @@ -1,4 +1,5 @@ use core::cmp::Ordering; +use core::iter::{Chain, Once, once}; use core::ops; use crate::math::EPSILON; @@ -146,6 +147,17 @@ impl From for (f32, f32) { } } +pub type IntoIter = Chain, Once>; + +impl IntoIterator for Vec2 { + type Item = f32; + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + once(self.x).chain(once(self.y)) + } +} + impl Vec2 { /// Creates a new `Vec2` from x and y coordinates. pub const fn new(x: f32, y: f32) -> Self { diff --git a/rask-engine/src/math/vec3.rs b/rask-engine/src/math/vec3.rs index 8e1fb160..76a69e35 100644 --- a/rask-engine/src/math/vec3.rs +++ b/rask-engine/src/math/vec3.rs @@ -1,4 +1,5 @@ use core::cmp::Ordering; +use core::iter::{Chain, Once, once}; use core::ops; use crate::math::EPSILON; @@ -150,6 +151,17 @@ impl From for (f32, f32, f32) { } } +pub type IntoIter = Chain, Chain, Once>>; + +impl IntoIterator for Vec3 { + type Item = f32; + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + once(self.x).chain(once(self.y).chain(once(self.z))) + } +} + impl Vec3 { /// Creates a new `Vec3` from x and y coordinates. pub const fn new(x: f32, y: f32, z: f32) -> Self { From 0dad915576c36bee4f26eec0f519d0b7eb79aea7 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Fri, 13 Mar 2020 22:00:27 +0100 Subject: [PATCH 02/35] remove PartialOrd impl for Vec2, Vec3 --- rask-engine/src/collide.rs | 3 ++- rask-engine/src/math/vec2.rs | 15 --------------- rask-engine/src/math/vec3.rs | 15 --------------- 3 files changed, 2 insertions(+), 31 deletions(-) diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index e64c313e..2678be5f 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -17,7 +17,8 @@ impl Collide for Vec2 { impl Collide for AABox { fn collides(&self, other: &Vec2) -> bool { - self.pos < *other && *other < self.pos + self.size + self.pos.into_iter().zip(other.into_iter()).all(|(a, b)| a < b) + && other.into_iter().zip((self.pos + self.size).into_iter()).all(|(a, b)| a < b) } } diff --git a/rask-engine/src/math/vec2.rs b/rask-engine/src/math/vec2.rs index f62793ae..4545618b 100644 --- a/rask-engine/src/math/vec2.rs +++ b/rask-engine/src/math/vec2.rs @@ -1,4 +1,3 @@ -use core::cmp::Ordering; use core::iter::{Chain, Once, once}; use core::ops; @@ -113,20 +112,6 @@ impl ops::DivAssign for Vec2 { } } -impl PartialOrd for Vec2 { - fn partial_cmp(&self, other: &Self) -> Option { - if self == other { - Some(Ordering::Equal) - } else if self.x <= other.x && self.y <= other.y { - Some(Ordering::Less) - } else if self.x >= other.x && self.y >= other.y { - Some(Ordering::Greater) - } else { - None - } - } -} - impl PartialEq for Vec2 { fn eq(&self, other: &Self) -> bool { f32::abs(self.x - other.x) < EPSILON && f32::abs(self.y - other.y) < EPSILON diff --git a/rask-engine/src/math/vec3.rs b/rask-engine/src/math/vec3.rs index 76a69e35..70d3d450 100644 --- a/rask-engine/src/math/vec3.rs +++ b/rask-engine/src/math/vec3.rs @@ -1,4 +1,3 @@ -use core::cmp::Ordering; use core::iter::{Chain, Once, once}; use core::ops; @@ -115,20 +114,6 @@ impl ops::DivAssign for Vec3 { } } -impl PartialOrd for Vec3 { - fn partial_cmp(&self, other: &Self) -> Option { - if self == other { - Some(Ordering::Equal) - } else if self.x <= other.x && self.y <= other.y && self.z <= other.z { - Some(Ordering::Less) - } else if self.x >= other.x && self.y >= other.y && self.z >= other.z { - Some(Ordering::Greater) - } else { - None - } - } -} - impl PartialEq for Vec3 { fn eq(&self, other: &Self) -> bool { f32::abs(self.x - other.x) < EPSILON From 78b698096e91955295f9b80d6bc45595a535cbb7 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sat, 14 Mar 2020 13:59:38 +0100 Subject: [PATCH 03/35] cargo fmt --- rask-engine/src/collide.rs | 10 ++++++++-- rask-engine/src/math/vec2.rs | 2 +- rask-engine/src/math/vec3.rs | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index 2678be5f..4771d603 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -17,8 +17,14 @@ impl Collide for Vec2 { impl Collide for AABox { fn collides(&self, other: &Vec2) -> bool { - self.pos.into_iter().zip(other.into_iter()).all(|(a, b)| a < b) - && other.into_iter().zip((self.pos + self.size).into_iter()).all(|(a, b)| a < b) + self.pos + .into_iter() + .zip(other.into_iter()) + .all(|(a, b)| a < b) + && other + .into_iter() + .zip((self.pos + self.size).into_iter()) + .all(|(a, b)| a < b) } } diff --git a/rask-engine/src/math/vec2.rs b/rask-engine/src/math/vec2.rs index 4545618b..e4548f17 100644 --- a/rask-engine/src/math/vec2.rs +++ b/rask-engine/src/math/vec2.rs @@ -1,4 +1,4 @@ -use core::iter::{Chain, Once, once}; +use core::iter::{once, Chain, Once}; use core::ops; use crate::math::EPSILON; diff --git a/rask-engine/src/math/vec3.rs b/rask-engine/src/math/vec3.rs index 70d3d450..a8f31787 100644 --- a/rask-engine/src/math/vec3.rs +++ b/rask-engine/src/math/vec3.rs @@ -1,4 +1,4 @@ -use core::iter::{Chain, Once, once}; +use core::iter::{once, Chain, Once}; use core::ops; use crate::math::EPSILON; From 7eb38f37dde933498b6511dbf563a5eba6cb6379 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sat, 14 Mar 2020 15:53:36 +0100 Subject: [PATCH 04/35] update tests --- rask-engine/src/collide.rs | 13 +++++-------- rask-engine/tests/vec2.rs | 32 -------------------------------- rask-engine/tests/vec3.rs | 32 -------------------------------- 3 files changed, 5 insertions(+), 72 deletions(-) diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index 4771d603..09b447af 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -17,14 +17,11 @@ impl Collide for Vec2 { impl Collide for AABox { fn collides(&self, other: &Vec2) -> bool { - self.pos - .into_iter() - .zip(other.into_iter()) - .all(|(a, b)| a < b) - && other - .into_iter() - .zip((self.pos + self.size).into_iter()) - .all(|(a, b)| a < b) + fn left_under(v1: Vec2, v2: Vec2) -> bool { + v1.into_iter().zip(v2).all(|(a, b)| a < b) + } + + left_under(self.pos, *other) && left_under(*other, self.pos + self.size) } } diff --git a/rask-engine/tests/vec2.rs b/rask-engine/tests/vec2.rs index c5ca2585..41de20b9 100644 --- a/rask-engine/tests/vec2.rs +++ b/rask-engine/tests/vec2.rs @@ -79,38 +79,6 @@ fn test_div_vec2() { assert_eq!(a / b, Vec2::new(-4.2, 3.75)); } -#[test] -fn test_less_vec2() { - let a = Vec2::new(1.0, 7.5); - let b = Vec2::new(-3.0, 2.5); - - assert!(b < a); -} - -#[test] -fn test_less_vec2_fail() { - let a = Vec2::new(1.0, 7.5); - let b = Vec2::new(3.0, 2.5); - - assert!(!(a < b)); -} - -#[test] -fn test_greater_vec2() { - let a = Vec2::new(1.0, 7.5); - let b = Vec2::new(-3.0, 2.5); - - assert!(a > b); -} - -#[test] -fn test_greater_vec2_fail() { - let a = Vec2::new(1.0, 7.5); - let b = Vec2::new(3.0, 2.5); - - assert!(!(a > b)); -} - #[test] fn test_norm_vec2() { let a = Vec2::new(3.0, 4.0); diff --git a/rask-engine/tests/vec3.rs b/rask-engine/tests/vec3.rs index 69389f68..d4ba3da2 100644 --- a/rask-engine/tests/vec3.rs +++ b/rask-engine/tests/vec3.rs @@ -78,38 +78,6 @@ fn test_div_vec3() { assert_eq!(a / b, Vec3::new(-4.2, 3.75, 16.0)); } -#[test] -fn test_less_vec3() { - let a = Vec3::new(1.0, 50.0, 7.5); - let b = Vec3::new(-3.0, 1.0, 2.5); - - assert!(b < a); -} - -#[test] -fn test_less_vec3_fail() { - let a = Vec3::new(1.0, 67.0, 7.5); - let b = Vec3::new(3.0, -2.0, 2.5); - - assert!(!(a < b)); -} - -#[test] -fn test_greater_vec3() { - let a = Vec3::new(1.0, 4.0, 7.5); - let b = Vec3::new(-3.0, 1.0, 2.5); - - assert!(a > b); -} - -#[test] -fn test_greater_vec3_fail() { - let a = Vec3::new(1.0, 54.0, 7.5); - let b = Vec3::new(3.0, 5.0, 2.5); - - assert!(!(a > b)); -} - #[test] fn test_norm_vec3() { let a = Vec3::new(13.0, 4.0, 16.0); From 26a564551314f82a45eff0b0a8fe556bc619c471 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sat, 14 Mar 2020 22:36:16 +0100 Subject: [PATCH 05/35] remove unused files, start world module --- rask-engine/src/lib.rs | 1 + rask-engine/src/math_simd/mat2.rs | 128 ---------------------- rask-engine/src/math_simd/mod.rs | 11 -- rask-engine/src/math_simd/vec2.rs | 176 ------------------------------ rask-engine/src/webhogg_game.rs | 13 --- rask-engine/src/webhogg_player.rs | 3 - rask-engine/src/world.rs | 52 +++++++++ 7 files changed, 53 insertions(+), 331 deletions(-) delete mode 100644 rask-engine/src/math_simd/mat2.rs delete mode 100644 rask-engine/src/math_simd/mod.rs delete mode 100644 rask-engine/src/math_simd/vec2.rs delete mode 100644 rask-engine/src/webhogg_game.rs delete mode 100644 rask-engine/src/webhogg_player.rs create mode 100644 rask-engine/src/world.rs diff --git a/rask-engine/src/lib.rs b/rask-engine/src/lib.rs index 3e911b44..1ac36d9b 100644 --- a/rask-engine/src/lib.rs +++ b/rask-engine/src/lib.rs @@ -5,3 +5,4 @@ pub mod boxes; pub mod collide; pub mod math; +pub mod world; diff --git a/rask-engine/src/math_simd/mat2.rs b/rask-engine/src/math_simd/mat2.rs deleted file mode 100644 index 710c0daf..00000000 --- a/rask-engine/src/math_simd/mat2.rs +++ /dev/null @@ -1,128 +0,0 @@ -use std::{fmt, ops}; - -use packed_simd::{f32x2, shuffle}; - -use crate::math_simd::{Vec2, EPSILON}; - -#[derive(Clone, Copy)] -pub struct Mat2(f32x2, f32x2); - -impl ops::Add for Mat2 { - type Output = Self; - - fn add(self, other: Self) -> Self::Output { - Self(self.0 + other.0, self.1 + other.1) - } -} - -impl ops::AddAssign for Mat2 { - fn add_assign(&mut self, other: Self) { - self.0 += other.0; - self.1 += other.1; - } -} - -impl ops::Sub for Mat2 { - type Output = Self; - - fn sub(self, other: Self) -> Self::Output { - Self(self.0 - other.0, self.1 - other.1) - } -} - -impl ops::SubAssign for Mat2 { - fn sub_assign(&mut self, other: Self) { - self.0 -= other.0; - self.1 -= other.1; - } -} - -impl ops::Neg for Mat2 { - type Output = Self; - - fn neg(self) -> Self::Output { - Self(-self.0, -self.1) - } -} - -impl ops::Mul for Mat2 { - type Output = Self; - - fn mul(self, scale: f32) -> Self::Output { - Self(self.0 * scale, self.1 * scale) - } -} - -impl ops::MulAssign for Mat2 { - fn mul_assign(&mut self, scale: f32) { - self.0 *= scale; - self.1 *= scale; - } -} - -impl ops::Mul for Mat2 { - type Output = Vec2; - - fn mul(self, other: Vec2) -> Self::Output { - Vec2(self.0 * other.0.extract(0) + self.1 * other.0.extract(1)) - } -} -/* -impl ops::Mul for Mat2 { - type Output = Mat2; - - fn mul(self, other: Self) -> Self::Output {} -} - -impl ops::MulAssign for Mat2 { - fn mul_assign(&mut self, other: Self) {} -} -*/ -impl ops::Div for Mat2 { - type Output = Self; - - fn div(self, scale: f32) -> Self::Output { - Self(self.0 / scale, self.1 / scale) - } -} - -impl ops::DivAssign for Mat2 { - fn div_assign(&mut self, scale: f32) { - self.0 /= scale; - self.1 /= scale; - } -} - -impl PartialEq for Mat2 { - fn eq(&self, other: &Self) -> bool { - (self.0 - other.0).abs().lt(f32x2::splat(EPSILON)).all() - && (self.1 - other.1).abs().lt(f32x2::splat(EPSILON)).all() - } -} - -impl Eq for Mat2 {} - -impl Mat2 { - pub fn new(a: f32, b: f32, c: f32, d: f32) -> Self { - Self(f32x2::new(a, c), f32x2::new(b, d)) - } - - pub fn from_vec2(v1: Vec2, v2: Vec2) -> Self { - Self(v1.0, v2.0) - } - - pub fn zero() -> Self { - Self(f32x2::splat(0.0), f32x2::splat(0.0)) - } - - pub fn identity() -> Self { - Self(f32x2::new(1.0, 0.0), f32x2::new(0.0, 1.0)) - } - - pub fn transpose(self) -> Self { - Self( - shuffle!(self.0, self.1, [0, 2]), - shuffle!(self.0, self.1, [1, 3]), - ) - } -} diff --git a/rask-engine/src/math_simd/mod.rs b/rask-engine/src/math_simd/mod.rs deleted file mode 100644 index 87807e3a..00000000 --- a/rask-engine/src/math_simd/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Note: this requires `packed_simd = "0.3.3"` as dependency in Cargo.toml to compile -//! This module is supposed to have the same types and functions as the math module, but is using -//! SIMD to achieve that. However, currently the module is not exposed. - -pub mod mat2; -pub mod vec2; - -pub use mat2::Mat2; -pub use vec2::Vec2; - -pub const EPSILON: f32 = 1e-8; diff --git a/rask-engine/src/math_simd/vec2.rs b/rask-engine/src/math_simd/vec2.rs deleted file mode 100644 index 1ac3319a..00000000 --- a/rask-engine/src/math_simd/vec2.rs +++ /dev/null @@ -1,176 +0,0 @@ -use std::cmp::Ordering; -use std::{fmt, ops}; - -use packed_simd::f32x2; - -use crate::math_simd::EPSILON; - -#[derive(Clone, Copy)] -pub struct Vec2(pub(super) f32x2); - -impl fmt::Debug for Vec2 { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "Vec2 {{ x: {:?}, y: {:?} }}", - self.0.extract(0), - self.0.extract(1) - ) - } -} - -impl ops::Add for Vec2 { - type Output = Self; - - fn add(self, other: Self) -> Self::Output { - Self(self.0 + other.0) - } -} - -impl ops::AddAssign for Vec2 { - fn add_assign(&mut self, other: Self) { - self.0 += other.0; - } -} - -impl ops::Sub for Vec2 { - type Output = Self; - - fn sub(self, other: Self) -> Self::Output { - Self(self.0 - other.0) - } -} - -impl ops::SubAssign for Vec2 { - fn sub_assign(&mut self, other: Self) { - self.0 -= other.0; - } -} - -impl ops::Neg for Vec2 { - type Output = Self; - - fn neg(self) -> Self::Output { - Self(-self.0) - } -} - -impl ops::Mul for Vec2 { - type Output = Self; - - fn mul(self, scale: f32) -> Self::Output { - Self(self.0 * scale) - } -} - -impl ops::MulAssign for Vec2 { - fn mul_assign(&mut self, scale: f32) { - self.0 *= scale; - } -} - -impl ops::Mul for Vec2 { - type Output = Self; - - fn mul(self, other: Self) -> Self::Output { - Self(self.0 * other.0) - } -} - -impl ops::MulAssign for Vec2 { - fn mul_assign(&mut self, other: Self) { - self.0 *= other.0; - } -} - -impl ops::Div for Vec2 { - type Output = Self; - - fn div(self, scale: f32) -> Self::Output { - Self(self.0 / scale) - } -} - -impl ops::DivAssign for Vec2 { - fn div_assign(&mut self, scale: f32) { - self.0 /= scale; - } -} - -impl ops::Div for Vec2 { - type Output = Self; - - fn div(self, other: Self) -> Self::Output { - Self(self.0 / other.0) - } -} - -impl ops::DivAssign for Vec2 { - fn div_assign(&mut self, other: Self) { - self.0 /= other.0; - } -} - -impl PartialOrd for Vec2 { - fn partial_cmp(&self, other: &Self) -> Option { - if self == other { - Some(Ordering::Equal) - } else if self.0.le(other.0).all() { - Some(Ordering::Less) - } else if self.0.ge(other.0).all() { - Some(Ordering::Greater) - } else { - None - } - } -} - -impl PartialEq for Vec2 { - fn eq(&self, other: &Self) -> bool { - (self.0 - other.0).abs().lt(f32x2::splat(EPSILON)).all() - } -} - -impl Eq for Vec2 {} - -impl Vec2 { - /// Creates a new Vec2 from x and y coordinates. - pub fn new(x: f32, y: f32) -> Self { - Self(f32x2::new(x, y)) - } - - /// Returns the zero vector. - pub fn zero() -> Self { - Self(f32x2::splat(0.0)) - } - - /// Returns the x coordinate. - pub fn x(self) -> f32 { - self.0.extract(0) - } - - /// Returns the y coordinate. - pub fn y(self) -> f32 { - self.0.extract(1) - } - - /// Returns the dot product. - pub fn dot(self, other: Self) -> f32 { - (self.0 * other.0).sum() - } - - /// Returns the square of the euclidean norm of the vector. - pub fn norm2(self) -> f32 { - self.dot(self) - } - - /// Returns the euclidean norm of the vector. - pub fn norm(self) -> f32 { - self.norm2().sqrt() - } - - /// Returns a normalized version of the vector, that is, a vector that points in the same direction, but has norm 1. - pub fn normalized(self) -> Self { - self / self.norm() - } -} diff --git a/rask-engine/src/webhogg_game.rs b/rask-engine/src/webhogg_game.rs deleted file mode 100644 index b3f35cc7..00000000 --- a/rask-engine/src/webhogg_game.rs +++ /dev/null @@ -1,13 +0,0 @@ -use crate::math::Vec2; - -pub struct WebhoggPlayer { - pos: Vec2, -} - -pub struct WebhoggGame { - player1: WebhoggPlayer, - player2: WebhoggPlayer, -} - -impl WebhoggGame { -} diff --git a/rask-engine/src/webhogg_player.rs b/rask-engine/src/webhogg_player.rs deleted file mode 100644 index 38b95965..00000000 --- a/rask-engine/src/webhogg_player.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub struct WebhoggPlayer { - -} diff --git a/rask-engine/src/world.rs b/rask-engine/src/world.rs new file mode 100644 index 00000000..5c4b04c0 --- /dev/null +++ b/rask-engine/src/world.rs @@ -0,0 +1,52 @@ +use crate::math::Vec2; + +const GRAVITY: Vec2 = Vec2::new(0.0, -9.81); + +pub trait Move { + fn gravity() -> bool; + fn position(&mut self) -> &mut Vec2; + fn velocity(&mut self) -> &mut Vec2; + + fn update(&mut self, dt: f32) { + if Self::gravity() { + *self.velocity() += dt * GRAVITY; + } + let vel = *self.velocity(); + *self.position() += dt * vel; + } +} + +pub struct World { + players: Vec, + entities: Vec, + ground: Ground, + background: Background, +} + +pub struct Player { + position: Vec2, + velocity: Vec2, + skeleton: Skeleton, +} + +impl Move for Player { + fn gravity() -> bool { + true + } + + fn position(&mut self) -> &mut Vec2 { + &mut self.position + } + + fn velocity(&mut self) -> &mut Vec2 { + &mut self.velocity + } +} + +pub struct Entity; + +pub struct Skeleton; + +pub struct Ground; + +pub struct Background; From 6ab1c9d886c650765a755de1e22a67f7689d0ebc Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sun, 15 Mar 2020 00:09:49 +0100 Subject: [PATCH 06/35] add EngineError --- rask-engine/src/lib.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rask-engine/src/lib.rs b/rask-engine/src/lib.rs index 1ac36d9b..b2ca4ed9 100644 --- a/rask-engine/src/lib.rs +++ b/rask-engine/src/lib.rs @@ -6,3 +6,18 @@ pub mod boxes; pub mod collide; pub mod math; pub mod world; + +use std::error::Error; +use std::fmt::{self, Display}; + +/// The error type used by the game engine. +#[derive(Debug)] +pub enum EngineError {} + +impl Display for EngineError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + todo!() + } +} + +impl Error for EngineError {} From 28206c46fc909d3f59d7a68bc48e119b995f1d72 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 15 Mar 2020 00:38:57 +0100 Subject: [PATCH 07/35] Add ressources module --- rask-engine/Cargo.toml | 4 ++++ rask-engine/src/lib.rs | 1 + rask-engine/src/ressources/libary.rs | 1 + rask-engine/src/ressources/mod.rs | 13 +++++++++++++ rask-engine/src/ressources/sound.rs | 1 + .../src => rask-engine/src/ressources}/texture.rs | 2 +- 6 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 rask-engine/src/ressources/libary.rs create mode 100644 rask-engine/src/ressources/mod.rs create mode 100644 rask-engine/src/ressources/sound.rs rename {client/shared/src => rask-engine/src/ressources}/texture.rs (97%) diff --git a/rask-engine/Cargo.toml b/rask-engine/Cargo.toml index 89a78e5c..d3895178 100644 --- a/rask-engine/Cargo.toml +++ b/rask-engine/Cargo.toml @@ -5,3 +5,7 @@ authors = ["konsumlamm ", "Dennis Kobert Date: Sun, 15 Mar 2020 05:00:35 +0100 Subject: [PATCH 08/35] Add load Store fuction to library --- rask-engine/Cargo.toml | 1 + rask-engine/src/lib.rs | 3 ++ rask-engine/src/ressources/libary.rs | 1 - rask-engine/src/ressources/library.rs | 43 +++++++++++++++++++++++++++ rask-engine/src/ressources/mod.rs | 30 ++++++++++++++++--- 5 files changed, 73 insertions(+), 5 deletions(-) delete mode 100644 rask-engine/src/ressources/libary.rs create mode 100644 rask-engine/src/ressources/library.rs diff --git a/rask-engine/Cargo.toml b/rask-engine/Cargo.toml index db906f74..be7c26df 100644 --- a/rask-engine/Cargo.toml +++ b/rask-engine/Cargo.toml @@ -6,6 +6,7 @@ edition = "2018" [dependencies] image = "0.23" +lazy_static = "1.4.0" [dependencies.spine_tiny] git = "https://github.com/reeFridge/spine-rs" diff --git a/rask-engine/src/lib.rs b/rask-engine/src/lib.rs index 8464c55a..2ade584a 100644 --- a/rask-engine/src/lib.rs +++ b/rask-engine/src/lib.rs @@ -8,3 +8,6 @@ pub mod error; pub mod math; pub mod ressources; pub mod world; + +#[doc(inline)] +pub use error::EngineError; diff --git a/rask-engine/src/ressources/libary.rs b/rask-engine/src/ressources/libary.rs deleted file mode 100644 index 9c33d727..00000000 --- a/rask-engine/src/ressources/libary.rs +++ /dev/null @@ -1 +0,0 @@ -struct Libary {} diff --git a/rask-engine/src/ressources/library.rs b/rask-engine/src/ressources/library.rs new file mode 100644 index 00000000..37ea41ea --- /dev/null +++ b/rask-engine/src/ressources/library.rs @@ -0,0 +1,43 @@ +use super::Resource; +use crate::EngineError; + +const CATALOUGE_SIZE: usize = 512; + +pub struct Library { + catalog: &'static mut [Resource], +} + +macro_rules! get_store { + ($type: ty, $enum_type: ident) => { + impl GetStore<$type> for Library { + unsafe fn get(&'static self, id: usize) -> Result<&'static $type, EngineError> { + match &self.catalog[id] { + Resource::$enum_type(value) => Ok(&value), + _ => Err("Wrong ressource type".into()), + } + } + unsafe fn store(&'static mut self, data: $type, id: usize) { + self.catalog[id] = Resource::$enum_type(data); + } + } + }; +} + +pub trait GetStore { + unsafe fn get(&'static self, id: usize) -> Result<&'static T, EngineError>; + unsafe fn store(&'static mut self, data: T, id: usize); +} + +impl Library { + pub unsafe fn new(memory_offset: usize) -> Self { + Library { + catalog: core::slice::from_raw_parts_mut( + memory_offset as *mut Resource, + CATALOUGE_SIZE, + ), + } + } +} +get_store!(super::Texture, Texture); +get_store!(spine::skeleton::Skeleton, Skeleton); +get_store!(super::Sound, Sound); diff --git a/rask-engine/src/ressources/mod.rs b/rask-engine/src/ressources/mod.rs index 965d6228..104f26c4 100644 --- a/rask-engine/src/ressources/mod.rs +++ b/rask-engine/src/ressources/mod.rs @@ -1,13 +1,35 @@ /*! The ressource management system for the ratatosk game engine + +#Example +use lazy_static::lazy_static; + +lazy_static! { + static ref LIB: Library = { unsafe { Library::new(0) } }; +} + +fn test() { + use library::GetStore; + unsafe { + let _texture: &Texture = LIB.get(0).unwrap(); + } +} */ -pub mod libary; +pub mod library; pub mod sound; pub mod texture; -enum Ressource { - Texture(texture::Texture), - Sound(sound::Sound), +#[doc(inline)] +pub use library::Library; +#[doc(inline)] +pub use sound::Sound; +#[doc(inline)] +pub use texture::Texture; + +enum Resource { + None, + Texture(Texture), + Sound(Sound), Skeleton(spine::skeleton::Skeleton), } From c81648a4b6d2f65f3aeac8726ab16b9f5dff2607 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 15 Mar 2020 05:01:51 +0100 Subject: [PATCH 09/35] Add lazy_static as dependency for rask engine --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index c95e8add..a9e2a289 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1235,6 +1235,7 @@ name = "rask-engine" version = "0.2.0" dependencies = [ "image", + "lazy_static", "spine_tiny 0.1.0 (git+https://github.com/reeFridge/spine-rs)", ] From 3dd49cc3ea80c28831ae03567739f76a76cb850b Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 15 Mar 2020 15:32:15 +0100 Subject: [PATCH 10/35] Implement collide for spine SRT --- Cargo.lock | 7 +++++++ rask-engine/Cargo.toml | 1 + rask-engine/src/boxes.rs | 12 +++++++++++ rask-engine/src/collide.rs | 12 +++++++++++ rask-engine/src/error.rs | 29 ++++++++++++++------------- rask-engine/src/math/mat3.rs | 9 +++++++++ rask-engine/src/math/vec3.rs | 5 +++++ rask-engine/src/ressources/library.rs | 24 +++++++++++++++++----- 8 files changed, 80 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a9e2a289..1981c808 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1237,6 +1237,7 @@ dependencies = [ "image", "lazy_static", "spine_tiny 0.1.0 (git+https://github.com/reeFridge/spine-rs)", + "stackvec", ] [[package]] @@ -1592,6 +1593,12 @@ dependencies = [ "serde_json", ] +[[package]] +name = "stackvec" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28337dadadf1f595e7472e02ed7e27cbc790828b10336f144b5790d21152c16" + [[package]] name = "string" version = "0.2.1" diff --git a/rask-engine/Cargo.toml b/rask-engine/Cargo.toml index be7c26df..17f16dba 100644 --- a/rask-engine/Cargo.toml +++ b/rask-engine/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" [dependencies] image = "0.23" lazy_static = "1.4.0" +stackvec = "0.2" [dependencies.spine_tiny] git = "https://github.com/reeFridge/spine-rs" diff --git a/rask-engine/src/boxes.rs b/rask-engine/src/boxes.rs index aa416a21..7f1425ba 100644 --- a/rask-engine/src/boxes.rs +++ b/rask-engine/src/boxes.rs @@ -121,4 +121,16 @@ impl PartialEq for RBox { } } +impl From<&spine::skeleton::SRT> for RBox { + fn from(srt: &spine::skeleton::SRT) -> RBox { + use crate::math::Vec3; + let mat3 = super::math::Mat3::from_nested_arr(&srt.to_matrix3()) + .expect("Fatal error, spine matrix is not 3x3"); + let pos = (mat3 * Vec3::new(-1f32, 1f32, 1f32)).to_vec2(); + let v1 = pos - (mat3 * Vec3::new(-1f32, -1f32, 1f32)).to_vec2(); + let v2 = pos - (mat3 * Vec3::new(1f32, 1f32, 1f32)).to_vec2(); + RBox { pos, v1, v2 } + } +} + impl Eq for RBox {} diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index 09b447af..0a5181f6 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -46,6 +46,18 @@ impl Collide for RBox { //&& v2_diff < self.pos + self.v1 && self.pos < v2_diff } } +impl Collide for spine::skeleton::SRT { + fn collides(&self, other: &Vec2) -> bool { + let rbox: RBox = self.into(); + rbox.collides(other) + } +} +impl Collide for spine::skeleton::SRT { + fn collides(&self, other: &AABox) -> bool { + let rbox: RBox = self.into(); + rbox.collides(other) + } +} impl Collide for RBox { fn collides(&self, other: &AABox) -> bool { diff --git a/rask-engine/src/error.rs b/rask-engine/src/error.rs index d093d699..35985930 100644 --- a/rask-engine/src/error.rs +++ b/rask-engine/src/error.rs @@ -5,6 +5,7 @@ use std::fmt::{self, Display}; #[derive(Debug)] pub enum EngineError { ResourceError(String), + MathError(String), Misc(String), } @@ -13,24 +14,24 @@ impl Display for EngineError { match self { EngineError::ResourceError(e) => write!(f, "ResourceError: {}", e), EngineError::Misc(e) => write!(f, "EngineError: {}", e), + EngineError::MathError(e) => write!(f, "MathError: {}", e), } } } impl Error for EngineError {} -impl From<&str> for EngineError { - fn from(error: &str) -> Self { - EngineError::Misc(error.to_owned()) - } -} -impl From for EngineError { - fn from(error: String) -> Self { - EngineError::Misc(error) - } -} -impl From for EngineError { - fn from(error: image::error::ImageError) -> Self { - EngineError::ResourceError(format!("{}", error)) - } +macro_rules! derive_from { + ($type: ty, $kind: ident) => { + impl From<$type> for EngineError { + fn from(error: $type) -> Self { + EngineError::$kind(format!("{}", error)) + } + } + }; } + +derive_from!(&str, Misc); +derive_from!(String, Misc); +derive_from!(image::error::ImageError, ResourceError); +derive_from!(stackvec::error::IncompleteArrayError, MathError); diff --git a/rask-engine/src/math/mat3.rs b/rask-engine/src/math/mat3.rs index 3739e5b2..4c35abd1 100644 --- a/rask-engine/src/math/mat3.rs +++ b/rask-engine/src/math/mat3.rs @@ -224,6 +224,7 @@ impl Mat3 { /// (a b c) /// (d e f) /// (g h i) + #[allow(clippy::many_single_char_names)] pub const fn new( a: f32, b: f32, @@ -255,6 +256,14 @@ impl Mat3 { ) } + pub fn from_nested_arr(arr: &[[f32; 3]; 3]) -> Result { + extern crate stackvec; + use ::stackvec::prelude::*; + Ok(Mat3 { + data: arr.into_iter().flatten().cloned().try_collect()?, + }) + } + /// Returns the zero matrix. pub const fn zero() -> Self { Self::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) diff --git a/rask-engine/src/math/vec3.rs b/rask-engine/src/math/vec3.rs index a8f31787..7bc2598c 100644 --- a/rask-engine/src/math/vec3.rs +++ b/rask-engine/src/math/vec3.rs @@ -192,4 +192,9 @@ impl Vec3 { pub fn normalized(self) -> Self { self / self.norm() } + + /// Returns vec2 disregarding the last dimension + pub fn to_vec2(&self) -> super::Vec2 { + super::Vec2::new(self.x(), self.y()) + } } diff --git a/rask-engine/src/ressources/library.rs b/rask-engine/src/ressources/library.rs index 37ea41ea..27fa7c7c 100644 --- a/rask-engine/src/ressources/library.rs +++ b/rask-engine/src/ressources/library.rs @@ -1,8 +1,11 @@ use super::Resource; use crate::EngineError; -const CATALOUGE_SIZE: usize = 512; +/// Size of the internal catalog +/// This determines the highes available id +const CATALOG_SIZE: usize = 512; +/// The library is used to store and retrive Resources pub struct Library { catalog: &'static mut [Resource], } @@ -24,17 +27,28 @@ macro_rules! get_store { } pub trait GetStore { + /// retrive a resource from the library + /// # Safety + /// the function is not concurrency safe unsafe fn get(&'static self, id: usize) -> Result<&'static T, EngineError>; + /// store a resource to the library + /// # Safety + /// the function is not concurrency safe unsafe fn store(&'static mut self, data: T, id: usize); } impl Library { + /// Create a new library at a specific position in memory + /// # Safety + /// the function is save as long as the memory from memory_offset to memory_offset + CATALOG_SIZE * sizeof(Resource) pub unsafe fn new(memory_offset: usize) -> Self { Library { - catalog: core::slice::from_raw_parts_mut( - memory_offset as *mut Resource, - CATALOUGE_SIZE, - ), + catalog: core::slice::from_raw_parts_mut(memory_offset as *mut Resource, CATALOG_SIZE), + } + } + pub unsafe fn init(&mut self) { + for i in 0..CATALOG_SIZE { + self.catalog[i] = Resource::None; } } } From 289cf5617b10885dd4321c07b8ae8b44df0637a2 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sun, 15 Mar 2020 15:34:53 +0100 Subject: [PATCH 11/35] fix typos + doctest in resources module --- rask-engine/src/lib.rs | 2 +- .../src/{ressources => resources}/library.rs | 10 ++++------ rask-engine/src/{ressources => resources}/mod.rs | 11 ++++++++--- .../src/{ressources => resources}/sound.rs | 0 .../src/{ressources => resources}/texture.rs | 15 ++++++++------- 5 files changed, 21 insertions(+), 17 deletions(-) rename rask-engine/src/{ressources => resources}/library.rs (80%) rename rask-engine/src/{ressources => resources}/mod.rs (72%) rename rask-engine/src/{ressources => resources}/sound.rs (100%) rename rask-engine/src/{ressources => resources}/texture.rs (86%) diff --git a/rask-engine/src/lib.rs b/rask-engine/src/lib.rs index 2ade584a..1c5dead9 100644 --- a/rask-engine/src/lib.rs +++ b/rask-engine/src/lib.rs @@ -6,7 +6,7 @@ pub mod boxes; pub mod collide; pub mod error; pub mod math; -pub mod ressources; +pub mod resources; pub mod world; #[doc(inline)] diff --git a/rask-engine/src/ressources/library.rs b/rask-engine/src/resources/library.rs similarity index 80% rename from rask-engine/src/ressources/library.rs rename to rask-engine/src/resources/library.rs index 37ea41ea..cfe21b05 100644 --- a/rask-engine/src/ressources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -1,7 +1,7 @@ use super::Resource; use crate::EngineError; -const CATALOUGE_SIZE: usize = 512; +const CATALOG_SIZE: usize = 512; pub struct Library { catalog: &'static mut [Resource], @@ -13,7 +13,7 @@ macro_rules! get_store { unsafe fn get(&'static self, id: usize) -> Result<&'static $type, EngineError> { match &self.catalog[id] { Resource::$enum_type(value) => Ok(&value), - _ => Err("Wrong ressource type".into()), + _ => Err("Wrong resource type".into()), } } unsafe fn store(&'static mut self, data: $type, id: usize) { @@ -31,13 +31,11 @@ pub trait GetStore { impl Library { pub unsafe fn new(memory_offset: usize) -> Self { Library { - catalog: core::slice::from_raw_parts_mut( - memory_offset as *mut Resource, - CATALOUGE_SIZE, - ), + catalog: core::slice::from_raw_parts_mut(memory_offset as *mut Resource, CATALOG_SIZE), } } } + get_store!(super::Texture, Texture); get_store!(spine::skeleton::Skeleton, Skeleton); get_store!(super::Sound, Sound); diff --git a/rask-engine/src/ressources/mod.rs b/rask-engine/src/resources/mod.rs similarity index 72% rename from rask-engine/src/ressources/mod.rs rename to rask-engine/src/resources/mod.rs index 104f26c4..1b22c08f 100644 --- a/rask-engine/src/ressources/mod.rs +++ b/rask-engine/src/resources/mod.rs @@ -1,19 +1,24 @@ /*! -The ressource management system for the ratatosk game engine +The resource management system for the ratatosk game engine. -#Example +# Example + +``` use lazy_static::lazy_static; +# use rask_engine::resources::*; lazy_static! { - static ref LIB: Library = { unsafe { Library::new(0) } }; + static ref LIB: Library = unsafe { Library::new(0) }; } fn test() { use library::GetStore; + unsafe { let _texture: &Texture = LIB.get(0).unwrap(); } } +``` */ pub mod library; diff --git a/rask-engine/src/ressources/sound.rs b/rask-engine/src/resources/sound.rs similarity index 100% rename from rask-engine/src/ressources/sound.rs rename to rask-engine/src/resources/sound.rs diff --git a/rask-engine/src/ressources/texture.rs b/rask-engine/src/resources/texture.rs similarity index 86% rename from rask-engine/src/ressources/texture.rs rename to rask-engine/src/resources/texture.rs index 5e6428ab..44e7780f 100644 --- a/rask-engine/src/ressources/texture.rs +++ b/rask-engine/src/resources/texture.rs @@ -1,7 +1,8 @@ -use crate::error::EngineError; +use std::convert::TryInto; + use image::{png::PngDecoder, ImageDecoder}; -use std::convert::TryInto; +use crate::error::EngineError; pub use image::ColorType; @@ -9,7 +10,7 @@ pub struct Texture { raw_data: Vec, w: u32, h: u32, - colortype: ColorType, + color_type: ColorType, } impl Texture { @@ -29,7 +30,7 @@ impl Texture { raw_data: bytes, w, h, - colortype, + color_type: colortype, }) } @@ -37,11 +38,11 @@ impl Texture { (self.w, self.h) } - pub fn colortype(&self) -> ColorType { - self.colortype + pub fn color_type(&self) -> ColorType { + self.color_type } - pub fn raw(&self) -> &Vec { + pub fn raw(&self) -> &[u8] { &self.raw_data } From 667c7293194a7eb30154cb086a9fefcb10404f79 Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sun, 15 Mar 2020 19:30:18 +0100 Subject: [PATCH 12/35] various fixes fix typos fix Rbox::new fix From<&SRT> impl for RBox remove smallvec dependency add conversions from and to arrays for Vec2, Vec3 update docs NOTE: the Collide impl is currently not working properly --- Cargo.lock | 7 ----- client/shared/src/lib.rs | 2 +- client/shared/src/mem.rs | 2 +- rask-engine/Cargo.toml | 1 - rask-engine/src/boxes.rs | 38 ++++++++-------------------- rask-engine/src/collide.rs | 34 ++++++++++++------------- rask-engine/src/error.rs | 3 +-- rask-engine/src/math/mat3.rs | 9 +------ rask-engine/src/math/vec2.rs | 12 +++++++++ rask-engine/src/math/vec3.rs | 16 ++++++++++-- rask-engine/src/resources/library.rs | 22 ++++++++++------ rask-engine/tests/collide_test.rs | 1 + 12 files changed, 72 insertions(+), 75 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1981c808..a9e2a289 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1237,7 +1237,6 @@ dependencies = [ "image", "lazy_static", "spine_tiny 0.1.0 (git+https://github.com/reeFridge/spine-rs)", - "stackvec", ] [[package]] @@ -1593,12 +1592,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "stackvec" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28337dadadf1f595e7472e02ed7e27cbc790828b10336f144b5790d21152c16" - [[package]] name = "string" version = "0.2.1" diff --git a/client/shared/src/lib.rs b/client/shared/src/lib.rs index 09b206c1..e52e8159 100644 --- a/client/shared/src/lib.rs +++ b/client/shared/src/lib.rs @@ -11,5 +11,5 @@ pub mod wasm_log; pub use error::*; pub use mem::*; -pub use rask_engine::ressources::texture; +pub use rask_engine::resources::texture; pub use wee_alloc; diff --git a/client/shared/src/mem.rs b/client/shared/src/mem.rs index 559e0df6..0749c156 100644 --- a/client/shared/src/mem.rs +++ b/client/shared/src/mem.rs @@ -2,7 +2,7 @@ use crate::state::State; type Buffer = crate::double_buffer::DoubleBuffer; use crate::sprite::*; -use rask_engine::ressources::texture::*; +use rask_engine::resources::texture::*; const fn KiB(n: usize) -> usize { n * 1024 diff --git a/rask-engine/Cargo.toml b/rask-engine/Cargo.toml index 17f16dba..be7c26df 100644 --- a/rask-engine/Cargo.toml +++ b/rask-engine/Cargo.toml @@ -7,7 +7,6 @@ edition = "2018" [dependencies] image = "0.23" lazy_static = "1.4.0" -stackvec = "0.2" [dependencies.spine_tiny] git = "https://github.com/reeFridge/spine-rs" diff --git a/rask-engine/src/boxes.rs b/rask-engine/src/boxes.rs index 7f1425ba..cdff0896 100644 --- a/rask-engine/src/boxes.rs +++ b/rask-engine/src/boxes.rs @@ -6,10 +6,11 @@ use core::ops; use crate::math::Vec2; /// An axis-aligned box. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct AABox { + /// The position of the box. pub pos: Vec2, - /// the size may not be smaller than zero + /// The size, may not be smaller than zero. pub size: Vec2, } @@ -47,16 +48,8 @@ impl ops::SubAssign for AABox { } } -impl PartialEq for AABox { - fn eq(&self, other: &Self) -> bool { - self.pos == other.pos && self.size == other.size - } -} - -impl Eq for AABox {} - /// A rotated box. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct RBox { /// The origin. pub pos: Vec2, @@ -68,9 +61,9 @@ pub struct RBox { impl RBox { /// Creates a new rotated box from a position, an orientation and a width. - pub fn new(pos: Vec2, orientation: Vec2, width: f32) -> Self { - let scale = width / orientation.norm(); - let orth = Vec2::new(orientation.x(), -orientation.y()) / scale; + pub fn new(pos: Vec2, orientation: Vec2, height: f32) -> Self { + let scale = height / orientation.norm(); + let orth = Vec2::new(-orientation.y(), orientation.x()) * scale; Self { pos, v1: orientation, @@ -115,22 +108,11 @@ impl ops::SubAssign for RBox { } } -impl PartialEq for RBox { - fn eq(&self, other: &Self) -> bool { - self.pos == other.pos && self.v1 == other.v1 && self.v2 == other.v2 - } -} - impl From<&spine::skeleton::SRT> for RBox { fn from(srt: &spine::skeleton::SRT) -> RBox { - use crate::math::Vec3; - let mat3 = super::math::Mat3::from_nested_arr(&srt.to_matrix3()) - .expect("Fatal error, spine matrix is not 3x3"); - let pos = (mat3 * Vec3::new(-1f32, 1f32, 1f32)).to_vec2(); - let v1 = pos - (mat3 * Vec3::new(-1f32, -1f32, 1f32)).to_vec2(); - let v2 = pos - (mat3 * Vec3::new(1f32, 1f32, 1f32)).to_vec2(); + let pos = srt.transform([-1.0, -1.0]).into(); + let v1 = Vec2::from(srt.transform([1.0, -1.0])) - pos; + let v2 = Vec2::from(srt.transform([-1.0, 1.0])) - pos; RBox { pos, v1, v2 } } } - -impl Eq for RBox {} diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index 0a5181f6..c02e5de0 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -9,6 +9,10 @@ pub trait Collide { fn collides(&self, other: &Rhs) -> bool; } +fn left_under(v1: Vec2, v2: Vec2) -> bool { + v1.x() < v2.x() && v1.y() < v2.y() +} + impl Collide for Vec2 { fn collides(&self, other: &Self) -> bool { self == other @@ -17,20 +21,14 @@ impl Collide for Vec2 { impl Collide for AABox { fn collides(&self, other: &Vec2) -> bool { - fn left_under(v1: Vec2, v2: Vec2) -> bool { - v1.into_iter().zip(v2).all(|(a, b)| a < b) - } - left_under(self.pos, *other) && left_under(*other, self.pos + self.size) } } impl Collide for AABox { fn collides(&self, other: &Self) -> bool { - self.pos.x() < other.pos.x() + other.size.x() - && other.pos.x() < self.pos.x() + self.size.x() - && self.pos.y() < other.pos.y() + other.size.y() - && other.pos.y() < self.pos.y() + self.size.y() + left_under(self.pos, other.pos + other.size) + && left_under(other.pos, self.pos + self.size) } } @@ -46,12 +44,14 @@ impl Collide for RBox { //&& v2_diff < self.pos + self.v1 && self.pos < v2_diff } } + impl Collide for spine::skeleton::SRT { fn collides(&self, other: &Vec2) -> bool { let rbox: RBox = self.into(); rbox.collides(other) } } + impl Collide for spine::skeleton::SRT { fn collides(&self, other: &AABox) -> bool { let rbox: RBox = self.into(); @@ -98,19 +98,19 @@ impl Collide for RBox { v2_dist_size.y() }; - let minx = f32::min( + let min_x = f32::min( self.pos.x(), f32::min((self.pos + self.v1).x(), (self.pos + self.v2).x()), ); - let maxx = f32::max( + let max_x = f32::max( self.pos.x(), f32::max((self.pos + self.v1).x(), (self.pos + self.v2).x()), ); - let miny = f32::min( + let min_y = f32::min( self.pos.y(), f32::min((self.pos + self.v1).y(), (self.pos + self.v2).y()), ); - let maxy = f32::max( + let max_y = f32::max( self.pos.y(), f32::max((self.pos + self.v1).y(), (self.pos + self.v2).y()), ); @@ -119,14 +119,14 @@ impl Collide for RBox { && v1_dist <= 1.0 && 0.0 <= v2_dist_size && v2_dist <= 1.0 - && other.pos.x() <= maxx - && minx <= other.pos.x() + other.size.x() - && other.pos.y() <= maxy - && miny <= other.pos.y() + other.size.y() + && other.pos.x() <= max_x + && min_x <= other.pos.x() + other.size.x() + && other.pos.y() <= max_y + && min_y <= other.pos.y() + other.size.y() } } -impl> Collide for Vec { +impl> Collide for [T] { fn collides(&self, other: &S) -> bool { self.iter().any(|x| x.collides(other)) } diff --git a/rask-engine/src/error.rs b/rask-engine/src/error.rs index 35985930..324ced03 100644 --- a/rask-engine/src/error.rs +++ b/rask-engine/src/error.rs @@ -22,7 +22,7 @@ impl Display for EngineError { impl Error for EngineError {} macro_rules! derive_from { - ($type: ty, $kind: ident) => { + ($type:ty, $kind:ident) => { impl From<$type> for EngineError { fn from(error: $type) -> Self { EngineError::$kind(format!("{}", error)) @@ -34,4 +34,3 @@ macro_rules! derive_from { derive_from!(&str, Misc); derive_from!(String, Misc); derive_from!(image::error::ImageError, ResourceError); -derive_from!(stackvec::error::IncompleteArrayError, MathError); diff --git a/rask-engine/src/math/mat3.rs b/rask-engine/src/math/mat3.rs index 4c35abd1..6dcd47cc 100644 --- a/rask-engine/src/math/mat3.rs +++ b/rask-engine/src/math/mat3.rs @@ -224,6 +224,7 @@ impl Mat3 { /// (a b c) /// (d e f) /// (g h i) + #[allow(clippy::too_many_arguments)] #[allow(clippy::many_single_char_names)] pub const fn new( a: f32, @@ -256,14 +257,6 @@ impl Mat3 { ) } - pub fn from_nested_arr(arr: &[[f32; 3]; 3]) -> Result { - extern crate stackvec; - use ::stackvec::prelude::*; - Ok(Mat3 { - data: arr.into_iter().flatten().cloned().try_collect()?, - }) - } - /// Returns the zero matrix. pub const fn zero() -> Self { Self::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) diff --git a/rask-engine/src/math/vec2.rs b/rask-engine/src/math/vec2.rs index e4548f17..0d0cfbc7 100644 --- a/rask-engine/src/math/vec2.rs +++ b/rask-engine/src/math/vec2.rs @@ -132,6 +132,18 @@ impl From for (f32, f32) { } } +impl From<[f32; 2]> for Vec2 { + fn from([x, y]: [f32; 2]) -> Self { + Self::new(x, y) + } +} + +impl From for [f32; 2] { + fn from(vec: Vec2) -> Self { + [vec.x(), vec.y()] + } +} + pub type IntoIter = Chain, Once>; impl IntoIterator for Vec2 { diff --git a/rask-engine/src/math/vec3.rs b/rask-engine/src/math/vec3.rs index 7bc2598c..200b68fd 100644 --- a/rask-engine/src/math/vec3.rs +++ b/rask-engine/src/math/vec3.rs @@ -136,6 +136,18 @@ impl From for (f32, f32, f32) { } } +impl From<[f32; 3]> for Vec3 { + fn from([x, y, z]: [f32; 3]) -> Self { + Self::new(x, y, z) + } +} + +impl From for [f32; 3] { + fn from(vec: Vec3) -> Self { + [vec.x(), vec.y(), vec.z()] + } +} + pub type IntoIter = Chain, Chain, Once>>; impl IntoIterator for Vec3 { @@ -193,8 +205,8 @@ impl Vec3 { self / self.norm() } - /// Returns vec2 disregarding the last dimension - pub fn to_vec2(&self) -> super::Vec2 { + /// Returns this `Vec3` as a `Vec2`, disregarding the z component. + pub fn into_vec2(self) -> super::Vec2 { super::Vec2::new(self.x(), self.y()) } } diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index 3ef4db9e..ff99177f 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -1,11 +1,11 @@ use super::Resource; use crate::EngineError; -/// Size of the internal catalog +/// Size of the internal catalog. /// This determines the highest available id. const CATALOG_SIZE: usize = 512; -/// The library is used to store and retrive Resources +/// The library is used to store and retrieve resources. pub struct Library { catalog: &'static mut [Resource], } @@ -27,20 +27,26 @@ macro_rules! get_store { } pub trait GetStore { - /// retrive a resource from the library + /// Retrieve a resource from the library. + /// /// # Safety - /// the function is not concurrency safe + /// + /// The function is not thread safe. unsafe fn get(&'static self, id: usize) -> Result<&'static T, EngineError>; - /// store a resource to the library + /// Store a resource to the library + /// /// # Safety - /// the function is not concurrency safe + /// + /// The function is not thread safe. unsafe fn store(&'static mut self, data: T, id: usize); } impl Library { - /// Create a new library at a specific position in memory + /// Create a new library at a specific position in memory. + /// /// # Safety - /// the function is save as long as the memory from memory_offset to memory_offset + CATALOG_SIZE * sizeof(Resource) + /// + /// The function is safe as long as the memory from memory_offset to memory_offset + CATALOG_SIZE * sizeof(Resource) pub unsafe fn new(memory_offset: usize) -> Self { Library { catalog: core::slice::from_raw_parts_mut(memory_offset as *mut Resource, CATALOG_SIZE), diff --git a/rask-engine/tests/collide_test.rs b/rask-engine/tests/collide_test.rs index f1f261e6..c00e2908 100644 --- a/rask-engine/tests/collide_test.rs +++ b/rask-engine/tests/collide_test.rs @@ -133,6 +133,7 @@ fn test_collide_rbox_aabox_edges_touch() { } #[test] +// TODO: fix test fn test_collide_rbox_aabox_crossed() { let a = Vec2::new(2.0, 0.5); let b = Vec2::new(1.0, 7.5); From 766d7c581844fa6b512e015c873cb895379a16dc Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sat, 11 Apr 2020 01:26:32 +0200 Subject: [PATCH 13/35] Rework mem fregmentation --- Cargo.lock | 21 +++++ client/Makefile.toml | 6 +- client/build.rs | 89 +++++++++++++++++ client/double-buffer/Cargo.toml | 11 --- client/double-buffer/src/lib.rs | 110 ---------------------- client/double-buffer/tests/integration.rs | 21 ----- client/graphics/build.rs | 1 + client/logic/build.rs | 1 + client/shared/Cargo.toml | 1 + client/shared/src/mem.rs | 16 +++- 10 files changed, 129 insertions(+), 148 deletions(-) create mode 100644 client/build.rs delete mode 100644 client/double-buffer/Cargo.toml delete mode 100644 client/double-buffer/src/lib.rs delete mode 100644 client/double-buffer/tests/integration.rs create mode 120000 client/graphics/build.rs create mode 120000 client/logic/build.rs diff --git a/Cargo.lock b/Cargo.lock index f4c39430..5b110e61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -221,6 +221,26 @@ dependencies = [ "winapi 0.3.8", ] +[[package]] +name = "const_env" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e9e4f72c6e3398ca6da372abd9affd8f89781fe728869bbf986206e9af9627e" +dependencies = [ + "const_env_impl", +] + +[[package]] +name = "const_env_impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a4f51209740b5e1589e702b3044cdd4562cef41b6da404904192ffffb852d62" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "cookie" version = "0.12.0" @@ -1288,6 +1308,7 @@ dependencies = [ name = "rask-wasm-shared" version = "0.1.0" dependencies = [ + "const_env", "fern", "image", "js-sys", diff --git a/client/Makefile.toml b/client/Makefile.toml index febaa2aa..b66625e2 100644 --- a/client/Makefile.toml +++ b/client/Makefile.toml @@ -27,10 +27,12 @@ script = [ [tasks.crate-build] workspace = false -command = "cargo" condition = { env_set = [ "STACK_SIZE", "CARGO_TARGET_DIR" ] } env = { "RUSTFLAGS" = "-Clink-arg=--stack-first -Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--max-memory=1073741824 -Clink-arg=--threads -Clink-arg=-zstack-size=${STACK_SIZE} -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory" } -args = [ "make", "exec-${BUILD_ENV}", "--", "build", "-p", "rask-${@}", "--target", "wasm32-unknown-unknown" ] +script = [ + "touch build.rs && cargo make exec-${BUILD_ENV} -- build -p rask-${@} --target wasm32-unknown-unknown", + "mv $CARGO_TARGET_DIR/output/* dist/", +] # TODO cargo doesn't seem to have a post-build hook but it might be nice # to determine if a rebuild happened (otherwise we don't need to rerun wasm-bindgen). diff --git a/client/build.rs b/client/build.rs new file mode 100644 index 00000000..5649da56 --- /dev/null +++ b/client/build.rs @@ -0,0 +1,89 @@ +const fn KiB(n: usize) -> usize { + n * 1024 +} +const fn MiB(n: usize) -> usize { + n * KiB(1024) +} + +const WEBWORKER_VAR: &'static str = "WEBWORKER"; + +/// Reserved memory +const MAX_MEORY: usize = 1073741824; + +/// The first page of memory is reserved +const STACK_ALIGNMENT: usize = 1024 * 63; + +/// The size of the stack. Its start is at address 0 +const GRAPHICS_STACK_SIZE: usize = MiB(4); +const GRAPHICS_HEAP_SIZE: usize = MiB(1); + +/// The size of the Allocator structures +const ALLOCATOR_SIZE: usize = MiB(1); + +/// Size of the internal resource library. +/// This determines the highest available id. +const CATALOG_SIZE: usize = 512; + +/// Size of rask_engine::resources::resource +const RESOURCE_SIZE: usize = 32; + +/// Length of the message queue used to communicate between main.js and the logic thread +/// This address must be exorted to javascript. +const MESSAGE_QUEUE_LENGTH: usize = 64; +const MESSAGE_QUEUE_ELEMENT_SIZE: usize = 32; + +/// The address memory synchronization area. +/// It contains data needed for synchronization between main thread and logic thread. +/// This address must be exorted to javascript. +const SYNCHRONIZATION_MEMORY_SIZE: usize = 32; + +/// Number of sprites to store in the double buffer +const BUFFER_SPRITE_COUNT: usize = 32; +/// Size of each sprites +const BUFFER_SPRITE_SIZE: usize = 32; + + +fn main() -> std::io::Result<()> { + let logic = None; + match std::env::var_os(WEBWORKER_VAR).map(|x|x.to_str().expect(format!("Failed to parse {}", WEBWORKER_VAR).as_str())) { + Some("logic") => logic = Some(true), + Some("graphics") => logic = Some(false), + Some(key) => println!("{} is no valid value. Possibel values are logic and graphics", key), + None => println!("{} is not defined in the environment.", WEBWORKER_VAR), + } + + if logic.is_none() { + std::process::exit(1) + } + + let graphics_stack = STACK_ALIGNMENT + GRAPHICS_STACK_SIZE; + let alloc = graphics_stack; + let graphics_heap = alloc + ALLOCATOR_SIZE; + let sync = alloc + GRAPHICS_HEAP_SIZE; + let catalog = sync + SYNCHRONIZATION_MEMORY_SIZE; + let buffer = catalog + RESOURCE_SIZE * CATALOG_SIZE; + let queue = buffer + BUFFER_SPRITE_SIZE * BUFFER_SPRITE_COUNT; + let logic_heap = queue + MESSAGE_QUEUE_ELEMENT_SIZE * MESSAGE_QUEUE_LENGTH; + let logic_stack = MAX_MEORY; + + println!("cargo:rustc-env=GRAPHICS_STACK={}", graphics_stack); + println!("cargo:rustc-env=ALLOCATOR={}", alloc); + println!("cargo:rustc-env=GRAPHICS_HEAP={}", graphics_heap); + println!("cargo:rustc-env=SYNCHRONIZATION_MEMORY={}", sync); + println!("cargo:rustc-env=CATALOG={}", catalog); + println!("cargo:rustc-env=DOUBLE_BUFFER={}", catalog); + println!("cargo:rustc-env=MESSAGE_QUEUE={}", queue); + println!("cargo:rustc-env=LOGIC_HEAP={}", logic_heap); + println!("cargo:rustc-env=LOGIC_STACK={}", logic_stack); + + + let stacksize = if logic.unwrap() {logic_stack} else {graphics_stack}; + println!("cargo:rustc-flags=-Clink-arg=--stack-first -Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--max-memory={} -Clink-arg=--threads -Clink-arg=-zstack-size={} -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory", MAX_MEORY, stacksize); + + use std::fs::File; + use std::io::prelude::*; + let out_dir = std::env::var("OUT_DIR").unwrap(); + let mut file = File::create(format!("{}/mem.json", out_dir))?; + file.write_all(format!("{{max_memory:{},queue_start:{},sync_area:{}}}", MAX_MEORY, queue, sync).as_bytes())?; + Ok(()) +} diff --git a/client/double-buffer/Cargo.toml b/client/double-buffer/Cargo.toml deleted file mode 100644 index 3ca866c4..00000000 --- a/client/double-buffer/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "double-buffer" -version = "0.1.0" -authors = ["natrixaeria"] -edition = "2018" - -[lib] -crate-type = ["rlib"] - -[profile.release] -lto = true diff --git a/client/double-buffer/src/lib.rs b/client/double-buffer/src/lib.rs deleted file mode 100644 index 474dbb2c..00000000 --- a/client/double-buffer/src/lib.rs +++ /dev/null @@ -1,110 +0,0 @@ -use std::fmt::Debug; - -pub trait Element: Clone + Sized + Default + Debug {} -type Flag = u8; - -impl Element for T {} - -#[derive(Debug)] -pub struct DoubleBuffer { - reading_at: Flag, - provided: Flag, - buffer: [T; 2], -} - -#[derive(Debug)] -pub struct ReaderBufferView<'a, T: Element> { - ptr: &'a mut DoubleBuffer, - read_pos: u8, -} - -#[derive(Debug)] -pub struct WriterBufferView<'a, T: Element> { - ptr: &'a mut DoubleBuffer, - write_pos: u8, -} - -impl DoubleBuffer { - pub fn new() -> Self { - DoubleBuffer { - reading_at: 0, - provided: 0, - buffer: [ - T::default(), - T::default() - ]} - } - - pub fn borrow_reader<'a>(&'a mut self) -> Option> { - match (self.get_reading_at(), self.get_provided()) { - (0, 0) => None, - (0, p) => { - let mut x = p; - self.set_reading_at(x); - while x != p { - x = p; - self.set_reading_at(x); - }; - Some(ReaderBufferView { ptr: self, read_pos: x - 1 }) - }, - (c, p) => panic!("invalid state ({},{}) for consumer reached", c, p), - } - } - - pub fn borrow_writer<'a>(&'a mut self) -> WriterBufferView<'a, T> { - let write_pos = match (self.get_reading_at(), self.get_provided()) { - (0, 0) => 0, - (0, y) => 2 - y, - (y, x) => if x == y { 2 - y } else { self.set_provided(y); y - 1 }, - }; - WriterBufferView { ptr: self, write_pos } - } - - #[inline(never)] - #[no_mangle] - fn set_reading_at(&mut self, reading_at: Flag) { - self.reading_at = reading_at; - } - - #[inline(never)] - #[no_mangle] - fn get_reading_at(&mut self) -> Flag { - self.reading_at - } - - #[inline(never)] - #[no_mangle] - fn set_provided(&mut self, provided: Flag) { - self.provided = provided; - } - - #[inline(never)] - #[no_mangle] - fn get_provided(&mut self) -> Flag { - self.provided - } -} - -impl<'a, T: Element> ReaderBufferView<'a, T> { - pub fn get(&self) -> &T { - &self.ptr.buffer[self.read_pos as usize] - } -} - -impl<'a, T: Element> WriterBufferView<'a, T> { - pub fn set(&mut self, data: T) { - self.ptr.buffer[self.write_pos as usize] = data; - } -} - -impl<'a, T: Element> std::ops::Drop for ReaderBufferView<'a, T> { - fn drop(&mut self) { - self.ptr.set_reading_at(0); - } -} - -impl<'a, T: Element> std::ops::Drop for WriterBufferView<'a, T> { - fn drop(&mut self) { - self.ptr.set_provided(self.write_pos + 1); - } -} diff --git a/client/double-buffer/tests/integration.rs b/client/double-buffer/tests/integration.rs deleted file mode 100644 index b736316a..00000000 --- a/client/double-buffer/tests/integration.rs +++ /dev/null @@ -1,21 +0,0 @@ -use double_buffer::DoubleBuffer; - -#[test] -fn test_initial_empty() { - let mut db: DoubleBuffer = DoubleBuffer::new(); - - assert!(db.borrow_reader().is_none()); -} - -#[test] -fn test_simple_read_write() { - let mut db = DoubleBuffer::new(); - { - let mut writer = db.borrow_writer(); - writer.set(42); - } - { - let reader = db.borrow_reader().unwrap(); - assert_eq!(*reader.get(), 42); - } -} diff --git a/client/graphics/build.rs b/client/graphics/build.rs new file mode 120000 index 00000000..10238032 --- /dev/null +++ b/client/graphics/build.rs @@ -0,0 +1 @@ +../build.rs \ No newline at end of file diff --git a/client/logic/build.rs b/client/logic/build.rs new file mode 120000 index 00000000..10238032 --- /dev/null +++ b/client/logic/build.rs @@ -0,0 +1 @@ +../build.rs \ No newline at end of file diff --git a/client/shared/Cargo.toml b/client/shared/Cargo.toml index 688698a7..71e13d53 100644 --- a/client/shared/Cargo.toml +++ b/client/shared/Cargo.toml @@ -18,6 +18,7 @@ js-sys = "=0.3.35" fern = "0.5.9" rand = "0.7" image = "0.23" +const_env = "0.1" [dependencies.rask-engine] version = "0.2.0" diff --git a/client/shared/src/mem.rs b/client/shared/src/mem.rs index 5c69ad9a..a21c8adb 100644 --- a/client/shared/src/mem.rs +++ b/client/shared/src/mem.rs @@ -48,6 +48,8 @@ pub struct SynchronizationMemory { /// time elapsed since logic thread initialisation in milliseconds pub elapsed_ms: i32, last_elapsed_ms: i32, + pub mouse_x: f32, + pub mouse_y: f32, } impl SynchronizationMemory { @@ -82,14 +84,15 @@ impl MessageQueueElement { fn get_writing(&self) -> u8 { unsafe { atomic_read_u8(&self.writing) } } - fn read(&mut self) -> Option { self.set_reading(1); if self.get_writing() == 0 { let e = self.payload.clone(); self.set_reading(0); Some(e) - } else { None } + } else { + None + } } } @@ -99,7 +102,7 @@ pub struct MessageQueue { writer_index: u32, /// the index of the next element to be read reader_index: u32, - _phantom: core::marker::PhantomData + _phantom: core::marker::PhantomData, } impl MessageQueue { @@ -112,7 +115,12 @@ impl MessageQueue { } unsafe fn get_mut(&mut self, n: usize) -> Option<&mut MessageQueueElement> { - core::slice::from_raw_parts_mut((self as *mut Self as *mut u8).offset(core::mem::size_of::() as isize) as *mut MessageQueueElement, Self::length()).get_mut(n) + core::slice::from_raw_parts_mut( + (self as *mut Self as *mut u8).offset(core::mem::size_of::() as isize) + as *mut MessageQueueElement, + Self::length(), + ) + .get_mut(n) } pub fn pop(&mut self) -> Option { From f44a9fd046f00cd92968f0e7f17ffebcf31ddf22 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sat, 11 Apr 2020 02:12:06 +0000 Subject: [PATCH 14/35] stable? --- Cargo.lock | 159 +++++++++++++++++++++---------------------- client/Makefile.toml | 8 +-- client/build.rs | 73 +++++++++++++------- 3 files changed, 129 insertions(+), 111 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5b110e61..cbf47b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,9 +17,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.26" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7825f6833612eb2414095684fcf6c635becf3ce97fe48cf6421321e93bfbd53c" +checksum = "d9a60d744a80c30fcb657dfe2c1b22bcb3e814c1a1e3674f32bf5820b570fbff" [[package]] name = "atty" @@ -46,9 +46,9 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" [[package]] name = "backtrace" -version = "0.3.44" +version = "0.3.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4036b9bf40f3cf16aba72a3d65e8a520fc4bafcdc7079aea8f848c58c5b5536" +checksum = "b1e692897359247cc6bb902933361652380af0f1b7651ae5c5013407f30e109e" dependencies = [ "backtrace-sys", "cfg-if", @@ -58,9 +58,9 @@ dependencies = [ [[package]] name = "backtrace-sys" -version = "0.1.32" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6575f128516de27e3ce99689419835fce9643a9b215a14d2b5b685be018491" +checksum = "7de8aba10a69c8e8d7622c5710229485ec32e9d55fdad160ea559c086fdcd118" dependencies = [ "cc", "libc", @@ -114,9 +114,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.2.0" +version = "3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f359dc14ff8911330a51ef78022d376f25ed00248912803b58f00cb1c27f742" +checksum = "12ae9db68ad7fac5fe51304d20f016c911539251075a214f8e663babefa35187" [[package]] name = "byte-tools" @@ -147,15 +147,6 @@ dependencies = [ "iovec", ] -[[package]] -name = "c2-chacha" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214238caa1bf3a496ec3392968969cab8549f96ff30652c9e56885329315f6bb" -dependencies = [ - "ppv-lite86", -] - [[package]] name = "cc" version = "1.0.50" @@ -170,9 +161,9 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "chrono" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31850b4a4d6bae316f7a09e691c944c28299298837edc0a03f755618c23cbc01" +checksum = "80094f509cf8b5ae86a4966a39b3ff66cd7e2a3e594accec3743ff3fabeab5b2" dependencies = [ "num-integer", "num-traits", @@ -271,9 +262,9 @@ dependencies = [ [[package]] name = "core-foundation" -version = "0.6.4" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" +checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" dependencies = [ "core-foundation-sys", "libc", @@ -281,9 +272,9 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.6.2" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" +checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac" [[package]] name = "crc32fast" @@ -343,9 +334,9 @@ dependencies = [ [[package]] name = "deflate" -version = "0.7.20" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707b6a7b384888a70c8d2e8650b3e60170dfc6a67bb4aa67b6dfca57af4bedb4" +checksum = "e7e5d2a2273fed52a7f947ee55b092c4057025d7a3e04e5ecdbd25d6c3fb1bd7" dependencies = [ "adler32", "byteorder", @@ -392,9 +383,9 @@ dependencies = [ [[package]] name = "failure" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8273f13c977665c5db7eb2b99ae520952fe5ac831ae4cd09d80c4c7042b5ed9" +checksum = "b8529c2421efa3066a5cbd8063d2244603824daccb6936b079010bb2aa89464b" dependencies = [ "backtrace", "failure_derive", @@ -402,9 +393,9 @@ dependencies = [ [[package]] name = "failure_derive" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bc225b78e0391e4b8683440bf2e63c2deeeb2ce5189eab46e2b68c6d3725d08" +checksum = "030a733c8287d6213886dd487564ff5c8f6aae10278b3588ed177f9d18f8d231" dependencies = [ "proc-macro2", "quote", @@ -430,9 +421,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bd6d6f4752952feb71363cffc9ebac9411b75b87c6ab6058c40c8900cf43c0f" +checksum = "2cfff41391129e0a856d6d822600b8d71179d46879e310417eb9c762eb178b42" dependencies = [ "cfg-if", "crc32fast", @@ -566,9 +557,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.1.8" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1010591b26bbfe835e9faeabeb11866061cc7dcebffd56ad7d0942d0e61aefd8" +checksum = "725cf19794cf90aa94e65050cb4191ff5d8fa87a498383774c47b332e3af952e" dependencies = [ "libc", ] @@ -669,9 +660,9 @@ dependencies = [ [[package]] name = "image" -version = "0.23.0" +version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef4e336ec01a678e7ab692914c641181528e8656451e6252f8f9e33728882eaf" +checksum = "bfc5483f8d5afd3653b38a196c52294dcb239c3e1a5bade1990353ea13bcf387" dependencies = [ "bytemuck", "byteorder", @@ -761,15 +752,15 @@ checksum = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" [[package]] name = "libc" -version = "0.2.67" +version = "0.2.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" +checksum = "dea0c0405123bba743ee3f91f49b1c7cfb684eef0da0a50110f758ccf24cdff0" [[package]] name = "lock_api" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79b2de95ecb4691949fea4716ca53cdbcfccb2c612e19644a8bad05edcf9f47b" +checksum = "c4da24a77a3d8a6d4862d95f72e6fdb9c09a643ecdb402d754004a557f2bec75" dependencies = [ "scopeguard", ] @@ -809,11 +800,11 @@ checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" [[package]] name = "memoffset" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75189eb85871ea5c2e2c15abbdd541185f63b408415e5051f5cac122d8c774b9" +checksum = "b4fc2c02a7e374099d4ee95a193111f72d2110197fe200272371758f6c3643d8" dependencies = [ - "rustc_version", + "autocfg 1.0.0", ] [[package]] @@ -892,9 +883,9 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b2df1a4c22fd44a62147fd8f13dd0f95c9d8ca7b2610299b2a2f9cf8964274e" +checksum = "2b0d88c06fe90d5ee94048ba40409ef1d9315d86f6f38c2efdaad4fb50c58b2d" dependencies = [ "lazy_static", "libc", @@ -952,9 +943,9 @@ dependencies = [ [[package]] name = "num-rational" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da4dc79f9e6c81bef96148c8f6b8e72ad4541caa4a24373e900a36da07de03a3" +checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" dependencies = [ "autocfg 1.0.0", "num-integer", @@ -988,9 +979,9 @@ checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" [[package]] name = "openssl" -version = "0.10.28" +version = "0.10.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "973293749822d7dd6370d6da1e523b0d1db19f06c459134c658b2a4261378b52" +checksum = "cee6d85f4cb4c4f59a6a85d5b68a233d280c82e29e822913b9c8b129fbf20bdd" dependencies = [ "bitflags", "cfg-if", @@ -1008,9 +999,9 @@ checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" [[package]] name = "openssl-sys" -version = "0.9.54" +version = "0.9.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1024c0a59774200a555087a6da3f253a9095a5f344e353b212ac4c8b8e450986" +checksum = "7717097d810a0f2e2323f9e5d11e71608355e24828410b55b9d4f18aa5f9a5d8" dependencies = [ "autocfg 1.0.0", "cc", @@ -1065,9 +1056,9 @@ checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" [[package]] name = "png" -version = "0.15.3" +version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef859a23054bbfee7811284275ae522f0434a3c8e7f4b74bd4a35ae7e1c4a283" +checksum = "910f09135b1ed14bb16be445a8c23ddf0777eca485fbfc7cee00d81fecab158a" dependencies = [ "bitflags", "crc32fast", @@ -1083,9 +1074,9 @@ checksum = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" [[package]] name = "proc-macro2" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c09721c6781493a2a492a96b5a5bf19b65917fe6728884e7c44dd0c60ca3435" +checksum = "df246d292ff63439fea9bc8c0a270bed0e390d5ebd4db4ba15aba81111b5abe3" dependencies = [ "unicode-xid", ] @@ -1105,9 +1096,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +checksum = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f" dependencies = [ "proc-macro2", ] @@ -1139,7 +1130,7 @@ checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" dependencies = [ "getrandom", "libc", - "rand_chacha 0.2.1", + "rand_chacha 0.2.2", "rand_core 0.5.1", "rand_hc 0.2.0", ] @@ -1156,11 +1147,11 @@ dependencies = [ [[package]] name = "rand_chacha" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" dependencies = [ - "c2-chacha", + "ppv-lite86", "rand_core 0.5.1", ] @@ -1361,18 +1352,18 @@ checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" [[package]] name = "regex" -version = "1.3.4" +version = "1.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "322cf97724bea3ee221b78fe25ac9c46114ebb51747ad5babd51a2fc6a8235a8" +checksum = "7f6946991529684867e47d86474e3a6d0c0ab9b82d5821e314b1ede31fa3a4b3" dependencies = [ "regex-syntax", ] [[package]] name = "regex-syntax" -version = "0.6.14" +version = "0.6.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b28dfe3fe9badec5dbf0a79a9cccad2cfc2ab5484bdb3e44cbd1ae8b3ba2be06" +checksum = "7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae" [[package]] name = "remove_dir_all" @@ -1440,15 +1431,15 @@ dependencies = [ [[package]] name = "ryu" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" +checksum = "535622e6be132bccd223f4bb2b8ac8d53cda3c7a6394944d3b2b33fb974f9d76" [[package]] name = "schannel" -version = "0.1.17" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507a9e6e8ffe0a4e0ebb9a10293e62fdf7657c06f1b8bb07a8fcf697d2abf295" +checksum = "039c25b130bd8c1321ee2d7de7fde2659fa9c2744e4bb29711cfc852ea53cd19" dependencies = [ "lazy_static", "winapi 0.3.8", @@ -1468,10 +1459,11 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "security-framework" -version = "0.3.4" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ef2429d7cefe5fd28bd1d2ed41c944547d4ff84776f5935b456da44593a16df" +checksum = "572dfa3a0785509e7a44b5b4bebcf94d41ba34e9ed9eb9df722545c3b3c4144a" dependencies = [ + "bitflags", "core-foundation", "core-foundation-sys", "libc", @@ -1480,11 +1472,12 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "0.3.3" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31493fc37615debb8c5090a7aeb4a9730bc61e77ab10b9af59f1a202284f895" +checksum = "8ddb15a5fec93b7021b8a9e96009c5d8d51c15673569f7c0f6b7204e5b7b404f" dependencies = [ "core-foundation-sys", + "libc", ] [[package]] @@ -1504,18 +1497,18 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -version = "1.0.104" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" +checksum = "36df6ac6412072f67cf767ebbde4133a5b2e88e76dc6187fa7104cd16f783399" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.104" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" +checksum = "9e549e3abf4fb8621bd1609f11dfc9f5e50320802273b12f3811a67e6716ea6c" dependencies = [ "proc-macro2", "quote", @@ -1524,9 +1517,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.48" +version = "1.0.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9371ade75d4c2d6cb154141b9752cf3781ec9c05e0e5cf35060e1e70ee7b9c25" +checksum = "da07b57ee2623368351e9a0488bb0b261322a15a6e0ae53e243cbdc0f4208da9" dependencies = [ "itoa", "ryu", @@ -1574,9 +1567,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" +checksum = "05720e22615919e4734f6a99ceae50d00226c3c5aca406e102ebc33298214e0a" [[package]] name = "sourcefile" @@ -1616,9 +1609,9 @@ checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" [[package]] name = "syn" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "123bd9499cfb380418d509322d7a6d52e5315f064fe4b3ad18a53d6b92c07859" +checksum = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03" dependencies = [ "proc-macro2", "quote", @@ -1860,7 +1853,7 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5479532badd04e128284890390c1e876ef7a993d0570b3597ae43dfa1d59afa4" dependencies = [ - "smallvec 1.2.0", + "smallvec 1.3.0", ] [[package]] diff --git a/client/Makefile.toml b/client/Makefile.toml index b66625e2..14ccccdc 100644 --- a/client/Makefile.toml +++ b/client/Makefile.toml @@ -11,7 +11,7 @@ args = [ "fmt", "--all" ] [tasks.logic] workspace = false -env = { STACK_SIZE = "134217728", CARGO_TARGET_DIR = "../target/logic", CRATE = "logic" } +env = { CARGO_TARGET_DIR = "../target/logic", CRATE = "logic" } script = [ "cargo make crate-build wasm-logic", "cargo make wasm logic", @@ -19,7 +19,7 @@ script = [ [tasks.graphics] workspace = false -env = { STACK_SIZE = "4194304", CARGO_TARGET_DIR = "../target/graphics", CRATE = "graphics" } +env = { CARGO_TARGET_DIR = "../target/graphics", CRATE = "graphics" } script = [ "cargo make crate-build wasm-graphics", "cargo make wasm graphics", @@ -27,8 +27,8 @@ script = [ [tasks.crate-build] workspace = false -condition = { env_set = [ "STACK_SIZE", "CARGO_TARGET_DIR" ] } -env = { "RUSTFLAGS" = "-Clink-arg=--stack-first -Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--max-memory=1073741824 -Clink-arg=--threads -Clink-arg=-zstack-size=${STACK_SIZE} -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory" } +condition = { env_set = [ "CARGO_TARGET_DIR" ] } +env = { "RUSTFLAGS" = "-Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--threads -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory" } script = [ "touch build.rs && cargo make exec-${BUILD_ENV} -- build -p rask-${@} --target wasm32-unknown-unknown", "mv $CARGO_TARGET_DIR/output/* dist/", diff --git a/client/build.rs b/client/build.rs index 5649da56..106205ee 100644 --- a/client/build.rs +++ b/client/build.rs @@ -1,3 +1,6 @@ +use std::fs::File; +use std::io::prelude::*; + const fn KiB(n: usize) -> usize { n * 1024 } @@ -5,10 +8,10 @@ const fn MiB(n: usize) -> usize { n * KiB(1024) } -const WEBWORKER_VAR: &'static str = "WEBWORKER"; +const WORKER_NAME_VAR: &'static str = "CARGO_PKG_NAME"; /// Reserved memory -const MAX_MEORY: usize = 1073741824; +const MAX_MEORY: usize = MiB(2048); /// The first page of memory is reserved const STACK_ALIGNMENT: usize = 1024 * 63; @@ -24,7 +27,7 @@ const ALLOCATOR_SIZE: usize = MiB(1); /// This determines the highest available id. const CATALOG_SIZE: usize = 512; -/// Size of rask_engine::resources::resource +/// Size of rask_engine::resources::resource const RESOURCE_SIZE: usize = 32; /// Length of the message queue used to communicate between main.js and the logic thread @@ -42,29 +45,31 @@ const BUFFER_SPRITE_COUNT: usize = 32; /// Size of each sprites const BUFFER_SPRITE_SIZE: usize = 32; - fn main() -> std::io::Result<()> { - let logic = None; - match std::env::var_os(WEBWORKER_VAR).map(|x|x.to_str().expect(format!("Failed to parse {}", WEBWORKER_VAR).as_str())) { - Some("logic") => logic = Some(true), - Some("graphics") => logic = Some(false), - Some(key) => println!("{} is no valid value. Possibel values are logic and graphics", key), - None => println!("{} is not defined in the environment.", WEBWORKER_VAR), - } - - if logic.is_none() { - std::process::exit(1) - } + println!("{:#?}", std::env::vars().collect::>()); + let name = std::env::var(WORKER_NAME_VAR); + let is_logic = match name { + Ok(worker) if &worker == "rask-wasm-logic" => true, + Ok(worker) if &worker == "rask-wasm-graphics" => false, + Ok(key) => panic!( + "{} is no valid value. Possibel values are logic and graphics", + key + ), + Err(std::env::VarError::NotPresent) => { + panic!("{} is not defined in the environment.", WORKER_NAME_VAR) + } + Err(err) => panic!("env var parsing failed (\"{:?}\")", err), + }; let graphics_stack = STACK_ALIGNMENT + GRAPHICS_STACK_SIZE; let alloc = graphics_stack; - let graphics_heap = alloc + ALLOCATOR_SIZE; - let sync = alloc + GRAPHICS_HEAP_SIZE; + let graphics_heap = alloc + ALLOCATOR_SIZE; + let sync = alloc + GRAPHICS_HEAP_SIZE; let catalog = sync + SYNCHRONIZATION_MEMORY_SIZE; let buffer = catalog + RESOURCE_SIZE * CATALOG_SIZE; let queue = buffer + BUFFER_SPRITE_SIZE * BUFFER_SPRITE_COUNT; let logic_heap = queue + MESSAGE_QUEUE_ELEMENT_SIZE * MESSAGE_QUEUE_LENGTH; - let logic_stack = MAX_MEORY; + let logic_stack = MAX_MEORY - MiB(1); println!("cargo:rustc-env=GRAPHICS_STACK={}", graphics_stack); println!("cargo:rustc-env=ALLOCATOR={}", alloc); @@ -76,14 +81,34 @@ fn main() -> std::io::Result<()> { println!("cargo:rustc-env=LOGIC_HEAP={}", logic_heap); println!("cargo:rustc-env=LOGIC_STACK={}", logic_stack); + let stacksize = if is_logic { + logic_stack + } else { + println!("cargo:rustc-cdylib-link-arg=--stack-first"); + println!("cargo:rustc-cdylib-link-arg=-zstack-size={}", graphics_stack); + graphics_stack + }; + //println!("cargo:rustc-cdylib-link-arg=--no-entry"); + //println!("cargo:rustc-cdylib-link-arg=--allow-undefined"); + //println!("cargo:rustc-cdylib-link-arg=--strip-all"); + //println!("cargo:rustc-cdylib-link-arg=--export-dynamic"); + //println!("cargo:rustc-cdylib-link-arg=--import-memory"); + //println!("cargo:rustc-cdylib-link-arg=--shared-memory"); + println!("cargo:rustc-cdylib-link-arg=--max-memory={}", MAX_MEORY); + //println!("cargo:rustc-cdylib-link-arg=--threads"); + //println!("cargo:rustc-cdylib-link-arg=--export=__wasm_init_memory"); + //println!("cargo:rustc-cdylib-link-arg=--no-check-features"); + //println!("cargo:rustc-cdylib-link-arg=--export=__wasm_init_tls"); + //println!("cargo:rustc-cdylib-link-arg=--export=__tls_size"); - let stacksize = if logic.unwrap() {logic_stack} else {graphics_stack}; - println!("cargo:rustc-flags=-Clink-arg=--stack-first -Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--max-memory={} -Clink-arg=--threads -Clink-arg=-zstack-size={} -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory", MAX_MEORY, stacksize); - - use std::fs::File; - use std::io::prelude::*; let out_dir = std::env::var("OUT_DIR").unwrap(); let mut file = File::create(format!("{}/mem.json", out_dir))?; - file.write_all(format!("{{max_memory:{},queue_start:{},sync_area:{}}}", MAX_MEORY, queue, sync).as_bytes())?; + file.write_all( + format!( + "{{max_memory:{},queue_start:{},sync_area:{}}}", + MAX_MEORY, queue, sync + ) + .as_bytes(), + )?; Ok(()) } From fa0c6869cd23ee1d8f3ea95b08f0b233301e098a Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sat, 11 Apr 2020 02:49:34 +0000 Subject: [PATCH 15/35] Fix errors during build process --- client/Makefile.toml | 2 +- client/build.rs | 26 ++++++-------------------- 2 files changed, 7 insertions(+), 21 deletions(-) diff --git a/client/Makefile.toml b/client/Makefile.toml index 14ccccdc..91c64e86 100644 --- a/client/Makefile.toml +++ b/client/Makefile.toml @@ -31,7 +31,7 @@ condition = { env_set = [ "CARGO_TARGET_DIR" ] } env = { "RUSTFLAGS" = "-Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--threads -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory" } script = [ "touch build.rs && cargo make exec-${BUILD_ENV} -- build -p rask-${@} --target wasm32-unknown-unknown", - "mv $CARGO_TARGET_DIR/output/* dist/", + "mv $(find $CARGO_TARGET_DIR/ -name mem.json) gen/", ] # TODO cargo doesn't seem to have a post-build hook but it might be nice diff --git a/client/build.rs b/client/build.rs index 106205ee..556504ef 100644 --- a/client/build.rs +++ b/client/build.rs @@ -1,14 +1,16 @@ use std::fs::File; use std::io::prelude::*; +#[allow(non_snake_case)] const fn KiB(n: usize) -> usize { n * 1024 } +#[allow(non_snake_case)] const fn MiB(n: usize) -> usize { n * KiB(1024) } -const WORKER_NAME_VAR: &'static str = "CARGO_PKG_NAME"; +const WORKER_NAME_VAR: &'static str = "CRATE"; /// Reserved memory const MAX_MEORY: usize = MiB(2048); @@ -49,8 +51,8 @@ fn main() -> std::io::Result<()> { println!("{:#?}", std::env::vars().collect::>()); let name = std::env::var(WORKER_NAME_VAR); let is_logic = match name { - Ok(worker) if &worker == "rask-wasm-logic" => true, - Ok(worker) if &worker == "rask-wasm-graphics" => false, + Ok(worker) if &worker == "logic" => true, + Ok(worker) if &worker == "graphics" => false, Ok(key) => panic!( "{} is no valid value. Possibel values are logic and graphics", key @@ -69,7 +71,6 @@ fn main() -> std::io::Result<()> { let buffer = catalog + RESOURCE_SIZE * CATALOG_SIZE; let queue = buffer + BUFFER_SPRITE_SIZE * BUFFER_SPRITE_COUNT; let logic_heap = queue + MESSAGE_QUEUE_ELEMENT_SIZE * MESSAGE_QUEUE_LENGTH; - let logic_stack = MAX_MEORY - MiB(1); println!("cargo:rustc-env=GRAPHICS_STACK={}", graphics_stack); println!("cargo:rustc-env=ALLOCATOR={}", alloc); @@ -79,27 +80,12 @@ fn main() -> std::io::Result<()> { println!("cargo:rustc-env=DOUBLE_BUFFER={}", catalog); println!("cargo:rustc-env=MESSAGE_QUEUE={}", queue); println!("cargo:rustc-env=LOGIC_HEAP={}", logic_heap); - println!("cargo:rustc-env=LOGIC_STACK={}", logic_stack); - let stacksize = if is_logic { - logic_stack - } else { + if !is_logic { println!("cargo:rustc-cdylib-link-arg=--stack-first"); println!("cargo:rustc-cdylib-link-arg=-zstack-size={}", graphics_stack); - graphics_stack }; - //println!("cargo:rustc-cdylib-link-arg=--no-entry"); - //println!("cargo:rustc-cdylib-link-arg=--allow-undefined"); - //println!("cargo:rustc-cdylib-link-arg=--strip-all"); - //println!("cargo:rustc-cdylib-link-arg=--export-dynamic"); - //println!("cargo:rustc-cdylib-link-arg=--import-memory"); - //println!("cargo:rustc-cdylib-link-arg=--shared-memory"); println!("cargo:rustc-cdylib-link-arg=--max-memory={}", MAX_MEORY); - //println!("cargo:rustc-cdylib-link-arg=--threads"); - //println!("cargo:rustc-cdylib-link-arg=--export=__wasm_init_memory"); - //println!("cargo:rustc-cdylib-link-arg=--no-check-features"); - //println!("cargo:rustc-cdylib-link-arg=--export=__wasm_init_tls"); - //println!("cargo:rustc-cdylib-link-arg=--export=__tls_size"); let out_dir = std::env::var("OUT_DIR").unwrap(); let mut file = File::create(format!("{}/mem.json", out_dir))?; From 1758b05bb357534aec5ae01be8ae5b4a5ec6b8da Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sat, 11 Apr 2020 05:11:08 +0200 Subject: [PATCH 16/35] Use meory ofsets, passed by the envorement variables --- client/build.rs | 2 +- client/graphics/src/context.rs | 5 +- client/graphics/src/render.rs | 12 ++-- client/logic/src/game_context.rs | 6 +- client/shared/src/alloc.rs | 8 +-- client/shared/src/mem.rs | 94 ++++++++------------------------ 6 files changed, 42 insertions(+), 85 deletions(-) diff --git a/client/build.rs b/client/build.rs index 556504ef..d7c56da1 100644 --- a/client/build.rs +++ b/client/build.rs @@ -13,7 +13,7 @@ const fn MiB(n: usize) -> usize { const WORKER_NAME_VAR: &'static str = "CRATE"; /// Reserved memory -const MAX_MEORY: usize = MiB(2048); +const MAX_MEORY: usize = MiB(512); /// The first page of memory is reserved const STACK_ALIGNMENT: usize = 1024 * 63; diff --git a/client/graphics/src/context.rs b/client/graphics/src/context.rs index 9db72893..00ed69ce 100644 --- a/client/graphics/src/context.rs +++ b/client/graphics/src/context.rs @@ -13,8 +13,9 @@ impl Context { } pub fn render(&mut self) -> Result<(), ClientError> { - self.render - .render(rask_wasm_shared::mem::shared_heap().animations()) + //self.render + // .render(rask_wasm_shared::mem::shared_heap().animations()) + Ok(()) } } diff --git a/client/graphics/src/render.rs b/client/graphics/src/render.rs index 7ebdced3..d74924ff 100644 --- a/client/graphics/src/render.rs +++ b/client/graphics/src/render.rs @@ -26,10 +26,10 @@ impl Render { self.graphics .ok() .map_err(|e| ClientError::WebGlError(format!("WebGl2 error: {}", e)))?; - if rask_wasm_shared::mem::shared_heap().get_texture_notify() { - rask_wasm_shared::mem::shared_heap().unset_texture_notify(); - self.update_textures()?; - } + //if rask_wasm_shared::mem::shared_heap().get_texture_notify() { + // rask_wasm_shared::mem::shared_heap().unset_texture_notify(); + // self.update_textures()?; + //} self.graphics.start_frame(&[0.8, 0.05, 0.55])?; if self.draw_sprites(animations)? { self.frame_nr += 1; @@ -38,7 +38,7 @@ impl Render { } pub fn update_textures(&mut self) -> Result<(), ClientError> { - if let Some(textures) = rask_wasm_shared::mem::shared_heap().textures_mut() { + /*if let Some(textures) = rask_wasm_shared::mem::shared_heap().textures_mut() { let n = textures.len() as u32; self.graphics.resize_texture_pool(n)?; if n > self.texture_count { @@ -51,7 +51,7 @@ impl Render { } } self.texture_count = n; - } + }*/ Ok(()) } diff --git a/client/logic/src/game_context.rs b/client/logic/src/game_context.rs index 0410b292..32b6dd86 100644 --- a/client/logic/src/game_context.rs +++ b/client/logic/src/game_context.rs @@ -41,7 +41,7 @@ impl GameContext { self.state .append_sprite(&Sprite::new(math::Vec2::new(-0.6, 0.6), 1, 0, 1)); - let shared_heap = rask_wasm_shared::mem::shared_heap(); + /*let shared_heap = rask_wasm_shared::mem::shared_heap(); *shared_heap.animations_mut() = vec![ Animation::new(vec![ Frame::new(vec![rask_engine::math::Mat3::scaling(0.4, 0.4)]), @@ -67,8 +67,10 @@ impl GameContext { rask_wasm_shared::texture::Texture::from_png_stream(IMAGE2_DATA)?, ]); shared_heap.set_texture_notify(); + */ } + /* let animations = rask_wasm_shared::mem::shared_heap().animations(); for sprite in self.state.sprites_mut().iter_mut() { if (self.tick_nr % 10) == 9 { @@ -76,7 +78,7 @@ impl GameContext { .next_frame(animations) .ok_or(ClientError::ResourceError(format!("invalid animation id")))?; } - } + }*/ self.push_state()?; self.tick_nr += 1; Ok(()) diff --git a/client/shared/src/alloc.rs b/client/shared/src/alloc.rs index cc4a09be..cb83f2c6 100644 --- a/client/shared/src/alloc.rs +++ b/client/shared/src/alloc.rs @@ -11,19 +11,19 @@ pub mod settings { impl AllocSettings for Logic { fn allocator_addr() -> usize { - ALLOCATOR_AREA_START + ALLOCATOR } fn allocation_start_address() -> isize { - LOGIC_ALLOCATION_AREA_START as isize + LOGIC_HEAP as isize } } impl AllocSettings for Graphics { fn allocator_addr() -> usize { - ALLOCATOR_AREA_START + std::mem::size_of::() + ALLOCATOR + std::mem::size_of::() } fn allocation_start_address() -> isize { - GRAPHICS_ALLOCATION_AREA_START as isize + GRAPHICS_HEAP as isize } } } diff --git a/client/shared/src/mem.rs b/client/shared/src/mem.rs index a21c8adb..2b1eb344 100644 --- a/client/shared/src/mem.rs +++ b/client/shared/src/mem.rs @@ -1,46 +1,41 @@ -use crate::state::State; type Buffer = crate::double_buffer::DoubleBuffer; +use crate::state::State; use crate::{sprite::*, texture::*}; +use const_env::from_env; -const fn KiB(n: usize) -> usize { - n * 1024 -} -const fn MiB(n: usize) -> usize { - n * KiB(1024) -} +#[from_env] +/// The position of the stack. +pub const GRAPHIC_STACK: usize = 0; -const STACK_ALIGNMENT: usize = 1024 * 63; -const MESSAGE_QUEUE_LENGTH: usize = 32; +#[from_env] +/// The address of the Allocator structures +pub const ALLOCATOR: usize = 0; -/// The size of the stack. Its start is at address 0 -pub const GRAPHIC_STACK_SIZE: usize = MiB(4) + STACK_ALIGNMENT; - -/// The address of the Allocator structures (size: 1MiB) -pub const ALLOCATOR_AREA_START: usize = GRAPHIC_STACK_SIZE; +/// The graphics heap address +pub const GRAPHICS_HEAP: usize = 0; +#[from_env] /// The address memory synchronization area. (size: 1MiB) /// It contains data needed for synchronization between main thread and logic thread. /// This address must currently be 0x50fc00. /// On change you have to modify the corresponding js file. -pub const SYNCHRONIZATION_MEMORY_START: usize = ALLOCATOR_AREA_START + MiB(1); +pub const SYNCHRONIZATION_MEMORY: usize = 0; -/// The address of the double buffer (size: target dependent) -pub const SHARED_BUFFER_AREA_START: usize = - SYNCHRONIZATION_MEMORY_START + core::mem::size_of::(); +/// Adress of the internal resource library. +pub const CATALOG: usize = 0; -/// The logic heap address (size: 32MiB) -pub const LOGIC_ALLOCATION_AREA_START: usize = - SHARED_BUFFER_AREA_START + core::mem::size_of::(); +/// The address of the double buffer (size: target dependent) +pub const DOUBLE_BUFFER: usize = 0; -/// The graphics heap address (size: 32MiB) -pub const GRAPHICS_ALLOCATION_AREA_START: usize = LOGIC_ALLOCATION_AREA_START + MiB(32); +/// Adress of the event queue +pub const MESSAGE_QUEUE: usize = 0; -/// The start of unbounded shared memory (size: unbounded) -pub const SHARED_ALLOCATION_AREA_START: usize = GRAPHICS_ALLOCATION_AREA_START + MiB(32); +/// The logic heap address (size: 32MiB) +pub const LOGIC_HEAP: usize = 0; pub fn get_double_buffer() -> &'static mut Buffer { - unsafe { &mut *(SHARED_BUFFER_AREA_START as *mut Buffer) } + unsafe { &mut *(DOUBLE_BUFFER as *mut Buffer) } } #[repr(align(4))] @@ -54,11 +49,11 @@ pub struct SynchronizationMemory { impl SynchronizationMemory { pub unsafe fn get() -> &'static Self { - &*(SYNCHRONIZATION_MEMORY_START as *const Self) + &*(SYNCHRONIZATION_MEMORY as *const Self) } pub unsafe fn get_mut() -> &'static mut Self { - &mut *(SYNCHRONIZATION_MEMORY_START as *mut Self) + &mut *(SYNCHRONIZATION_MEMORY as *mut Self) } pub fn wait_for_main_thread_notify(&mut self) { @@ -107,7 +102,7 @@ pub struct MessageQueue { impl MessageQueue { pub fn length() -> usize { - MESSAGE_QUEUE_LENGTH + MESSAGE_QUEUE } fn mem_size() -> usize { @@ -134,47 +129,6 @@ impl MessageQueue { } } -pub struct SharedHeap { - last_addr: u32, - animations: Vec, - texture_notify: bool, - textures: Option>, -} - -impl SharedHeap { - pub fn animations_mut(&mut self) -> &mut Vec { - &mut self.animations - } - - pub fn animations(&self) -> &Vec { - &self.animations - } - - pub fn unset_texture_notify(&mut self) { - self.texture_notify = false - } - - pub fn set_texture_notify(&mut self) { - self.texture_notify = true - } - - pub fn get_texture_notify(&mut self) -> bool { - self.texture_notify - } - - pub fn textures_mut(&mut self) -> &mut Option> { - &mut self.textures - } - - pub fn textures(&self) -> &Option> { - &self.textures - } -} - -pub fn shared_heap() -> &'static mut SharedHeap { - unsafe { &mut *(SHARED_ALLOCATION_AREA_START as *mut SharedHeap) } -} - extern "C" { #[link_name = "llvm.wasm.atomic.wait.i32"] /// see https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators From 7e16f99da6cb00220599a8f4d0718c2b384e6dde Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 00:14:01 +0200 Subject: [PATCH 17/35] Rename Library to ResourceTable --- rask-engine/src/resources/library.rs | 29 ++++++++++++---------------- rask-engine/src/resources/mod.rs | 4 ++-- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index ff99177f..15804fd4 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -1,26 +1,20 @@ use super::Resource; use crate::EngineError; -/// Size of the internal catalog. -/// This determines the highest available id. -const CATALOG_SIZE: usize = 512; - /// The library is used to store and retrieve resources. -pub struct Library { - catalog: &'static mut [Resource], -} +pub struct ResourceTable(&'static mut [Resource]); macro_rules! get_store { ($type: ty, $enum_type: ident) => { - impl GetStore<$type> for Library { + impl GetStore<$type> for ResourceTable { unsafe fn get(&'static self, id: usize) -> Result<&'static $type, EngineError> { - match &self.catalog[id] { + match &self.0[id] { Resource::$enum_type(value) => Ok(&value), _ => Err("Wrong resource type".into()), } } unsafe fn store(&'static mut self, data: $type, id: usize) { - self.catalog[id] = Resource::$enum_type(data); + self.0[id] = Resource::$enum_type(data); } } }; @@ -41,21 +35,22 @@ pub trait GetStore { unsafe fn store(&'static mut self, data: T, id: usize); } -impl Library { +impl ResourceTable { /// Create a new library at a specific position in memory. /// /// # Safety /// /// The function is safe as long as the memory from memory_offset to memory_offset + CATALOG_SIZE * sizeof(Resource) - pub unsafe fn new(memory_offset: usize) -> Self { - Library { - catalog: core::slice::from_raw_parts_mut(memory_offset as *mut Resource, CATALOG_SIZE), - } + pub unsafe fn new(memory_offset: usize, catalog_size: usize) -> Self { + ResourceTable(core::slice::from_raw_parts_mut( + memory_offset as *mut Resource, + catalog_size, + )) } pub unsafe fn init(&mut self) { - for i in 0..CATALOG_SIZE { - self.catalog[i] = Resource::None; + for i in 0..self.0.len() { + self.0[i] = Resource::None; } } } diff --git a/rask-engine/src/resources/mod.rs b/rask-engine/src/resources/mod.rs index 1b22c08f..9ec11fd2 100644 --- a/rask-engine/src/resources/mod.rs +++ b/rask-engine/src/resources/mod.rs @@ -21,12 +21,12 @@ fn test() { ``` */ -pub mod library; +mod library; pub mod sound; pub mod texture; #[doc(inline)] -pub use library::Library; +pub use library::*; #[doc(inline)] pub use sound::Sound; #[doc(inline)] From 6b4bcca77f88dda3ea76800f50fdd8d102b0fcd8 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 00:14:56 +0200 Subject: [PATCH 18/35] Cargo format --- client/build.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/client/build.rs b/client/build.rs index d7c56da1..2402409e 100644 --- a/client/build.rs +++ b/client/build.rs @@ -83,7 +83,10 @@ fn main() -> std::io::Result<()> { if !is_logic { println!("cargo:rustc-cdylib-link-arg=--stack-first"); - println!("cargo:rustc-cdylib-link-arg=-zstack-size={}", graphics_stack); + println!( + "cargo:rustc-cdylib-link-arg=-zstack-size={}", + graphics_stack + ); }; println!("cargo:rustc-cdylib-link-arg=--max-memory={}", MAX_MEORY); From 00eb3731a5d91821d87e47ae908199f125613728 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 00:54:26 +0200 Subject: [PATCH 19/35] Rename ENV variables to match RESOURCE_TABLE --- Cargo.lock | 24 +++++++++++++++++++++++- client/build.rs | 25 ++++++++++++++----------- client/graphics/src/graphics.rs | 4 ++-- client/shared/src/mem.rs | 4 +--- rask-engine/src/collide.rs | 3 +-- 5 files changed, 41 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cbf47b5c..fc3aa178 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -109,7 +109,7 @@ dependencies = [ "rask-engine", "serde", "serde_json", - "spine_tiny", + "spine_tiny 0.1.0 (git+http://github.com/tomaka/spine-rs)", ] [[package]] @@ -1253,6 +1253,11 @@ dependencies = [ [[package]] name = "rask-engine" version = "0.2.0" +dependencies = [ + "image", + "lazy_static", + "spine_tiny 0.1.0 (git+https://github.com/reeFridge/spine-rs)", +] [[package]] name = "rask-server" @@ -1414,6 +1419,12 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" +[[package]] +name = "rustc-hex" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceb8ce7a5e520de349e1fa172baeba4a9e8d5ef06c47471863530bc4972ee1e" + [[package]] name = "rustc-serialize" version = "0.3.24" @@ -1592,6 +1603,17 @@ dependencies = [ "rustc-serialize", ] +[[package]] +name = "spine_tiny" +version = "0.1.0" +source = "git+https://github.com/reeFridge/spine-rs#280ae6cbbe24cdfb8374adac583b755395321ac4" +dependencies = [ + "rustc-hex", + "serde", + "serde_derive", + "serde_json", +] + [[package]] name = "string" version = "0.2.1" diff --git a/client/build.rs b/client/build.rs index 2402409e..79f5c3d8 100644 --- a/client/build.rs +++ b/client/build.rs @@ -9,6 +9,9 @@ const fn KiB(n: usize) -> usize { const fn MiB(n: usize) -> usize { n * KiB(1024) } +const fn align(n: usize) -> usize { + (n + 3) & !3 +} const WORKER_NAME_VAR: &'static str = "CRATE"; @@ -27,7 +30,7 @@ const ALLOCATOR_SIZE: usize = MiB(1); /// Size of the internal resource library. /// This determines the highest available id. -const CATALOG_SIZE: usize = 512; +const RESOURCE_TABLE_SIZE: usize = 512; /// Size of rask_engine::resources::resource const RESOURCE_SIZE: usize = 32; @@ -63,21 +66,21 @@ fn main() -> std::io::Result<()> { Err(err) => panic!("env var parsing failed (\"{:?}\")", err), }; - let graphics_stack = STACK_ALIGNMENT + GRAPHICS_STACK_SIZE; - let alloc = graphics_stack; - let graphics_heap = alloc + ALLOCATOR_SIZE; - let sync = alloc + GRAPHICS_HEAP_SIZE; - let catalog = sync + SYNCHRONIZATION_MEMORY_SIZE; - let buffer = catalog + RESOURCE_SIZE * CATALOG_SIZE; - let queue = buffer + BUFFER_SPRITE_SIZE * BUFFER_SPRITE_COUNT; - let logic_heap = queue + MESSAGE_QUEUE_ELEMENT_SIZE * MESSAGE_QUEUE_LENGTH; + let graphics_stack = align(STACK_ALIGNMENT + GRAPHICS_STACK_SIZE); + let alloc = align(graphics_stack); + let graphics_heap = align(alloc + ALLOCATOR_SIZE); + let sync = align(alloc + GRAPHICS_HEAP_SIZE); + let table = align(sync + SYNCHRONIZATION_MEMORY_SIZE); + let buffer = align(table + RESOURCE_SIZE * RESOURCE_TABLE_SIZE); + let queue = align(buffer + BUFFER_SPRITE_SIZE * BUFFER_SPRITE_COUNT); + let logic_heap = align(queue + MESSAGE_QUEUE_ELEMENT_SIZE * MESSAGE_QUEUE_LENGTH); println!("cargo:rustc-env=GRAPHICS_STACK={}", graphics_stack); println!("cargo:rustc-env=ALLOCATOR={}", alloc); println!("cargo:rustc-env=GRAPHICS_HEAP={}", graphics_heap); println!("cargo:rustc-env=SYNCHRONIZATION_MEMORY={}", sync); - println!("cargo:rustc-env=CATALOG={}", catalog); - println!("cargo:rustc-env=DOUBLE_BUFFER={}", catalog); + println!("cargo:rustc-env=RESOURCE_TABLE={}", table); + println!("cargo:rustc-env=DOUBLE_BUFFER={}", buffer); println!("cargo:rustc-env=MESSAGE_QUEUE={}", queue); println!("cargo:rustc-env=LOGIC_HEAP={}", logic_heap); diff --git a/client/graphics/src/graphics.rs b/client/graphics/src/graphics.rs index d4fcf370..1e24fd1e 100644 --- a/client/graphics/src/graphics.rs +++ b/client/graphics/src/graphics.rs @@ -218,13 +218,13 @@ impl GraphicsApi for WebGl { let handle = WebGlApiTexture::new(&self.gl)?; self.gl.active_texture(Gl2::TEXTURE0); handle.bind(&self.gl); - if let ColorType::Rgb8 = texture.colortype() { + if let ColorType::Rgb8 = texture.color_type() { // TODO: copy RGB buffer to RGBA return Err(ClientError::ResourceError(format!( "RGB not yet implemented" ))); } - let (internalformat, format) = Self::colorformat(texture.colortype())?; + let (internalformat, format) = Self::colorformat(texture.color_type())?; let (w, h) = texture.dimension(); self.gl .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_u8_array( diff --git a/client/shared/src/mem.rs b/client/shared/src/mem.rs index ef06db09..219fcedd 100644 --- a/client/shared/src/mem.rs +++ b/client/shared/src/mem.rs @@ -1,9 +1,7 @@ type Buffer = crate::double_buffer::DoubleBuffer; use crate::state::State; -use crate::{sprite::*, texture::*}; use const_env::from_env; -use rask_engine::resources::texture::*; #[from_env] /// The position of the stack. @@ -24,7 +22,7 @@ pub const GRAPHICS_HEAP: usize = 0; pub const SYNCHRONIZATION_MEMORY: usize = 0; /// Adress of the internal resource library. -pub const CATALOG: usize = 0; +pub const RESOURCE_TABLE: usize = 0; /// The address of the double buffer (size: target dependent) pub const DOUBLE_BUFFER: usize = 0; diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index c02e5de0..405f7796 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -27,8 +27,7 @@ impl Collide for AABox { impl Collide for AABox { fn collides(&self, other: &Self) -> bool { - left_under(self.pos, other.pos + other.size) - && left_under(other.pos, self.pos + self.size) + left_under(self.pos, other.pos + other.size) && left_under(other.pos, self.pos + self.size) } } From 257dbdf400f9ef945cdf05dd8ffc9d0e6f8c1943 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 00:55:36 +0200 Subject: [PATCH 20/35] Move formatting to the end of the pipeline --- .drone.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.drone.yml b/.drone.yml index 04d40ada..7b046469 100644 --- a/.drone.yml +++ b/.drone.yml @@ -2,11 +2,6 @@ kind: pipeline name: default steps: -- name: format - image: truedoctor/rust-wasm:nightly-2020-02-28 - pull: if-not-exists - commands: - - nix-shell --run 'cargo make check-format' --arg inCI true # check formatting for all projects - name: build image: truedoctor/rust-wasm:nightly-2020-02-28 pull: if-not-exists @@ -39,6 +34,11 @@ steps: path: /tmp/demo commands: - cp -r client /tmp/demo +- name: format + image: truedoctor/rust-wasm:nightly-2020-02-28 + pull: if-not-exists + commands: + - nix-shell --run 'cargo make check-format' --arg inCI true # check formatting for all projects volumes: - name: demo From 1205cbf56d11d5b6d3125c687570425b3c7913e4 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 01:08:34 +0200 Subject: [PATCH 21/35] Remove unused dependencies --- client/shared/src/alloc.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/client/shared/src/alloc.rs b/client/shared/src/alloc.rs index cb83f2c6..42e0a33c 100644 --- a/client/shared/src/alloc.rs +++ b/client/shared/src/alloc.rs @@ -1,6 +1,8 @@ +use settings::AllocSettings; +use std::alloc::{GlobalAlloc, Layout}; + pub mod settings { use crate::mem::*; - use std::alloc::{GlobalAlloc, Layout}; pub trait AllocSettings { fn allocator_addr() -> usize; @@ -28,9 +30,6 @@ pub mod settings { } } -use settings::AllocSettings; -use std::alloc::{GlobalAlloc, Layout}; - pub trait MutableAlloc { unsafe fn alloc(&mut self, layout: Layout) -> *mut u8; unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout); From b6dfccf77b93ba95d358e69ddebb0d07398a02fb Mon Sep 17 00:00:00 2001 From: konsumlamm Date: Sun, 12 Apr 2020 02:01:18 +0200 Subject: [PATCH 22/35] Fix collision detection rename variables in tests add ratatosk.iml to .gitignore --- .gitignore | 3 + rask-engine/src/boxes.rs | 13 ++- rask-engine/src/collide.rs | 130 +++++++++++++----------------- rask-engine/tests/collide_test.rs | 39 +++++---- 4 files changed, 92 insertions(+), 93 deletions(-) diff --git a/.gitignore b/.gitignore index 34af0419..224f07a9 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,6 @@ gen/ # Direnv state-directory .direnv/ + +# IntelliJ +ratatosk.iml diff --git a/rask-engine/src/boxes.rs b/rask-engine/src/boxes.rs index cdff0896..c15327dd 100644 --- a/rask-engine/src/boxes.rs +++ b/rask-engine/src/boxes.rs @@ -10,7 +10,7 @@ use crate::math::Vec2; pub struct AABox { /// The position of the box. pub pos: Vec2, - /// The size, may not be smaller than zero. + /// The size, both components must be greater than zero. pub size: Vec2, } @@ -61,6 +61,7 @@ pub struct RBox { impl RBox { /// Creates a new rotated box from a position, an orientation and a width. + // v2 has the same direction as v1 rotated to the left by 90° pub fn new(pos: Vec2, orientation: Vec2, height: f32) -> Self { let scale = height / orientation.norm(); let orth = Vec2::new(-orientation.y(), orientation.x()) * scale; @@ -108,6 +109,16 @@ impl ops::SubAssign for RBox { } } +impl From for RBox { + fn from(aabox: AABox) -> Self { + Self { + pos: aabox.pos, + v1: Vec2::new(aabox.size.x(), 0.0), + v2: Vec2::new(0.0, aabox.size.y()), + } + } +} + impl From<&spine::skeleton::SRT> for RBox { fn from(srt: &spine::skeleton::SRT) -> RBox { let pos = srt.transform([-1.0, -1.0]).into(); diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index c02e5de0..1dcd40c9 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -4,6 +4,8 @@ use crate::boxes::{AABox, RBox}; use crate::math::Vec2; +// For information on the SAT, see: http://www.dyn4j.org/2010/01/sat/. + /// A trait for objects that can collide with other objects. pub trait Collide { fn collides(&self, other: &Rhs) -> bool; @@ -13,6 +15,44 @@ fn left_under(v1: Vec2, v2: Vec2) -> bool { v1.x() < v2.x() && v1.y() < v2.y() } +#[derive(Debug)] +struct Projection { + min: f32, + max: f32, +} + +impl Collide for Projection { + fn collides(&self, other: &Self) -> bool { + self.max >= other.min && self.min <= other.max + } +} + +fn project(rbox: &RBox, axis: &Vec2) -> Projection { + // the vertices of rbox without rbox.pos + let vertices = [ + rbox.pos + rbox.v1, + rbox.pos + rbox.v2, + rbox.pos + rbox.v1 + rbox.v2, + ]; + // project each vertex onto axis + vertices.iter().fold( + { + let p = axis.dot(rbox.pos); + Projection { min: p, max: p } + }, + |Projection { min, max }, vertex| { + let p = axis.dot(*vertex); + if p < min { + Projection { min: p, max } + } else if p > max { + Projection { min, max: p } + } else { + Projection { min, max } + } + }, + ) +} + impl Collide for Vec2 { fn collides(&self, other: &Self) -> bool { self == other @@ -27,21 +67,17 @@ impl Collide for AABox { impl Collide for AABox { fn collides(&self, other: &Self) -> bool { - left_under(self.pos, other.pos + other.size) - && left_under(other.pos, self.pos + self.size) + left_under(self.pos, other.pos + other.size) && left_under(other.pos, self.pos + self.size) } } impl Collide for RBox { fn collides(&self, other: &Vec2) -> bool { - let v1_diff = *other + self.v1 * (-self.v1.dot(*other - self.pos) / self.v1.norm2()); - let v2_diff = *other + self.v2 * (-self.v2.dot(*other - self.pos) / self.v2.norm2()); - - let v1_dist = ((v1_diff - self.pos) / self.v2).x(); - let v2_dist = ((v2_diff - self.pos) / self.v1).x(); - 0.0 <= v1_dist && v1_dist <= 1.0 && 0.0 <= v2_dist && v2_dist <= 1.0 - //v1_diff < self.pos + self.v2 && self.pos < v1_diff - //&& v2_diff < self.pos + self.v1 && self.pos < v2_diff + let v1_proj = project(self, &self.v1); + let p1 = other.dot(self.v1); + let v2_proj = project(self, &self.v2); + let p2 = other.dot(self.v2); + v1_proj.min <= p1 && v1_proj.max >= p1 && v2_proj.min <= p2 && v2_proj.max >= p2 } } @@ -61,68 +97,18 @@ impl Collide for spine::skeleton::SRT { impl Collide for RBox { fn collides(&self, other: &AABox) -> bool { - let other_size = other.pos + other.size; - - // project points onto a orthogonal line - let v1_diff = other.pos + self.v1 * (-self.v1.dot(other.pos - self.pos) / self.v1.norm2()); - let v2_diff = other.pos + self.v2 * (-self.v2.dot(other.pos) / self.v2.norm2()); - let v1_diff_size = - other_size + self.v1 * (-self.v1.dot(other_size - self.pos) / self.v1.norm2()); - let v2_diff_size = - other_size + self.v2 * (-self.v2.dot(other_size - self.pos) / self.v2.norm2()); - - // calculate the norm - let v1_dist = (v1_diff - self.pos) / self.v2; - let v2_dist = (v2_diff - self.pos) / self.v1; - let v1_dist_size = (v1_diff_size - self.pos) / self.v2; - let v2_dist_size = (v2_diff_size - self.pos) / self.v1; - - let v1_dist = if v1_dist.x().is_finite() { - v1_dist.x() - } else { - v1_dist.y() - }; - let v2_dist = if v2_dist.x().is_finite() { - v2_dist.x() - } else { - v2_dist.y() - }; - let v1_dist_size = if v1_dist_size.x().is_finite() { - v1_dist_size.x() - } else { - v1_dist_size.y() - }; - let v2_dist_size = if v2_dist_size.x().is_finite() { - v2_dist_size.x() - } else { - v2_dist_size.y() - }; - - let min_x = f32::min( - self.pos.x(), - f32::min((self.pos + self.v1).x(), (self.pos + self.v2).x()), - ); - let max_x = f32::max( - self.pos.x(), - f32::max((self.pos + self.v1).x(), (self.pos + self.v2).x()), - ); - let min_y = f32::min( - self.pos.y(), - f32::min((self.pos + self.v1).y(), (self.pos + self.v2).y()), - ); - let max_y = f32::max( - self.pos.y(), - f32::max((self.pos + self.v1).y(), (self.pos + self.v2).y()), - ); - - 0.0 <= v1_dist_size - && v1_dist <= 1.0 - && 0.0 <= v2_dist_size - && v2_dist <= 1.0 - && other.pos.x() <= max_x - && min_x <= other.pos.x() + other.size.x() - && other.pos.y() <= max_y - && min_y <= other.pos.y() + other.size.y() + let rbox: RBox = (*other).into(); + self.collides(&rbox) + } +} + +impl Collide for RBox { + fn collides(&self, other: &Self) -> bool { + // using the SAT + // TODO: optimization: remove duplicate axes + let axes = [self.v1, self.v2, other.v1, other.v2]; + axes.iter() + .all(|axis| project(self, axis).collides(&project(other, axis))) } } diff --git a/rask-engine/tests/collide_test.rs b/rask-engine/tests/collide_test.rs index c00e2908..13d5bfde 100644 --- a/rask-engine/tests/collide_test.rs +++ b/rask-engine/tests/collide_test.rs @@ -76,7 +76,7 @@ fn test_collide_rbox_dot() { let a = Vec2::new(1.0, 1.0); let b = Vec2::new(1.0, 1.0); let c = Vec2::new(1.0, -1.0); - let aa_box = RBox { + let rbox = RBox { pos: a, v1: b, v2: c, @@ -84,7 +84,7 @@ fn test_collide_rbox_dot() { let c = Vec2::new(1.6, 0.6); - assert!(aa_box.collides(&c)); + assert!(rbox.collides(&c)); } #[test] @@ -92,7 +92,7 @@ fn test_not_collide_rbox_dot() { let a = Vec2::new(1.0, 1.0); let b = Vec2::new(1.0, 1.0); let c = Vec2::new(1.0, -1.0); - let aa_box = RBox { + let rbox = RBox { pos: a, v1: b, v2: c, @@ -100,7 +100,7 @@ fn test_not_collide_rbox_dot() { let c = Vec2::new(1.4, 0.4); - assert!(!(aa_box.collides(&c))); + assert!(!(rbox.collides(&c))); } #[test] @@ -108,53 +108,52 @@ fn test_collide_rbox_aabox_intersecting() { let a = Vec2::new(1.0, 2.5); let b = Vec2::new(0.0, 2.5); let c = Vec2::new(3.0, 0.5); - let aa_box = RBox { + let box1 = RBox { pos: a, v1: b, v2: c, }; let a = Vec2::new(2.0, 3.5); let b = Vec2::new(3.0, 7.5); - let bb_box = AABox { pos: a, size: b }; + let box2 = AABox { pos: a, size: b }; - assert!(aa_box.collides(&bb_box)); + assert!(box1.collides(&box2)); } #[test] fn test_collide_rbox_aabox_edges_touch() { let a = Vec2::new(4.0, 5.5); let b = Vec2::new(1.0, 7.5); - let aa_box = RBox::new(a, b, 3.9); + let box1 = RBox::new(a, b, 3.9); let a = Vec2::new(0.0, 0.5); let b = Vec2::new(4.0, 5.0); - let bb_box = AABox { pos: a, size: b }; + let box2 = AABox { pos: a, size: b }; - assert!(aa_box.collides(&bb_box)); + assert!(box1.collides(&box2)); } #[test] -// TODO: fix test fn test_collide_rbox_aabox_crossed() { let a = Vec2::new(2.0, 0.5); let b = Vec2::new(1.0, 7.5); - let aa_box = RBox::new(a, b, 3.9); + let box1 = RBox::new(a, b, 3.9); let a = Vec2::new(0.0, 4.5); let b = Vec2::new(15.0, 1.5); - let bb_box = AABox { pos: a, size: b }; + let box2 = AABox { pos: a, size: b }; - assert!(aa_box.collides(&bb_box)); + assert!(box1.collides(&box2)); } #[test] fn test_not_collide_rbox_aabox_next_to() { let a = Vec2::new(2.0, 0.5); let b = Vec2::new(1.0, 7.5); - let aa_box = RBox::new(a, b, 3.9); + let box1 = RBox::new(a, b, 3.9); let a = Vec2::new(5.0, 40.5); let b = Vec2::new(15.0, 1.5); - let bb_box = AABox { pos: a, size: b }; + let box2 = AABox { pos: a, size: b }; - assert!(!aa_box.collides(&bb_box)); + assert!(!box1.collides(&box2)); } #[test] @@ -162,14 +161,14 @@ fn test_not_collide_rbox_aabox() { let a = Vec2::new(1.0, 1.0); let b = Vec2::new(0.0, 1.0); let c = Vec2::new(1.0, 0.0); - let aa_box = RBox { + let box1 = RBox { pos: a, v1: b, v2: c, }; let a = Vec2::new(3.0, 3.5); let b = Vec2::new(3.0, 7.5); - let bb_box = AABox { pos: a, size: b }; + let box2 = AABox { pos: a, size: b }; - assert!(!(aa_box.collides(&bb_box))); + assert!(!(box1.collides(&box2))); } From 9d3c548d191cf11c7a737575b82a53ddbe40b6e1 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 02:26:23 +0200 Subject: [PATCH 23/35] Fix color_type --- client/graphics/src/graphics.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/graphics/src/graphics.rs b/client/graphics/src/graphics.rs index 7168e90a..8bf3d4e1 100644 --- a/client/graphics/src/graphics.rs +++ b/client/graphics/src/graphics.rs @@ -212,13 +212,13 @@ impl GraphicsApi for WebGl { let handle = WebGlApiTexture::new(&self.gl)?; self.gl.active_texture(Gl2::TEXTURE0); handle.bind(&self.gl); - if let ColorType::Rgb8 = texture.colortype() { + if let ColorType::Rgb8 = texture.color_type() { // TODO: copy RGB buffer to RGBA return Err(ClientError::ResourceError(format!( "RGB not yet implemented" ))); } - let (internalformat, format) = Self::colorformat(texture.colortype())?; + let (internalformat, format) = Self::colorformat(texture.color_type())?; let (w, h) = texture.dimension(); self.gl .tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_u8_array( From 43d744e9d2aa8edf1676cd979fae24f05058b3b8 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 02:36:45 +0200 Subject: [PATCH 24/35] Fix doctest in resources/mod.rs --- rask-engine/src/resources/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/rask-engine/src/resources/mod.rs b/rask-engine/src/resources/mod.rs index 9ec11fd2..e8db47df 100644 --- a/rask-engine/src/resources/mod.rs +++ b/rask-engine/src/resources/mod.rs @@ -8,12 +8,10 @@ use lazy_static::lazy_static; # use rask_engine::resources::*; lazy_static! { - static ref LIB: Library = unsafe { Library::new(0) }; + static ref LIB: ResourceTable = unsafe { ResourceTable::new(0, 0) }; } fn test() { - use library::GetStore; - unsafe { let _texture: &Texture = LIB.get(0).unwrap(); } From 6b24c1f59884a9ff19cf87e5a553b01f7c615f8e Mon Sep 17 00:00:00 2001 From: NatrixAeria Date: Sun, 12 Apr 2020 03:45:39 +0200 Subject: [PATCH 25/35] Replace rbox aabox collision --- rask-engine/src/collide.rs | 40 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index 1dcd40c9..cdb8586e 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -3,6 +3,7 @@ use crate::boxes::{AABox, RBox}; use crate::math::Vec2; +use core::ops::Range; // For information on the SAT, see: http://www.dyn4j.org/2010/01/sat/. @@ -53,6 +54,35 @@ fn project(rbox: &RBox, axis: &Vec2) -> Projection { ) } +/// Calculate the bound in a line segment that collides an AABox projected onto an axis. +/// `bound` is a tuple of the start and ending point of the AABB. +/// `pos` is a component of the position vector of the line segment. +/// `direction` is a component of the direction vector of the line segment. +fn calculate_aabox_rbox_component_bounds(bound: Range, pos: f32, direction: f32) + -> (f32, f32) { + if direction == 0.0 { return (0.0, 1.0) } + // get bounds of s by transforming "g(s) = pos + s * direction" + // and applying the inequation g(s) >= bound.start and g(s) <= bound.end + let (s1, s2) = ((bound.start - pos) / direction, (bound.end - pos) / direction); + // if direction is negative, you have to switch the values + if direction > 0.0 { (s1, s2) } + else { (s2, s1) } +} + +/// Test for collision between an AABox and an edge of a rbox +fn collide_aabox_rbox_segment(xbound: Range, ybound: Range, pos: Vec2, direction: Vec2) + -> bool { + let sbound1 = calculate_aabox_rbox_component_bounds(xbound, pos.x(), direction.x()); + if sbound1.0 > sbound1.1 { return false; } + let sbound2 = calculate_aabox_rbox_component_bounds(ybound, pos.y(), direction.y()); + if sbound2.0 > sbound2.1 { return false; } + let (sbound1, sbound2) = (sbound1.0..sbound1.1, sbound2.0..sbound2.1); + + sbound1.end >= sbound2.start && sbound1.start <= sbound2.end + && sbound1.end >= 0.0 && sbound2.end >= 0.0 + && sbound1.start <= 1.0 && sbound2.start <= 1.0 +} + impl Collide for Vec2 { fn collides(&self, other: &Self) -> bool { self == other @@ -97,8 +127,14 @@ impl Collide for spine::skeleton::SRT { impl Collide for RBox { fn collides(&self, other: &AABox) -> bool { - let rbox: RBox = (*other).into(); - self.collides(&rbox) + let xbound = other.pos.x()..other.pos.x()+other.size.x(); + let ybound = other.pos.y()..other.pos.y()+other.size.y(); + let edges = [(self.pos, self.v1), (self.pos, self.v2), + (self.pos + self.v1, self.v2), (self.pos + self.v2, self.v1)]; + collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos, self.v1) + || collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos, self.v2) + || collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos + self.v1, self.v2) + || collide_aabox_rbox_segment(xbound, ybound, self.pos + self.v2, self.v1) } } From 570c6f6f602e557fd4cbaaaa600d48cb16d90184 Mon Sep 17 00:00:00 2001 From: NatrixAeria Date: Sun, 12 Apr 2020 03:48:06 +0200 Subject: [PATCH 26/35] Run cargo make format :'( --- rask-engine/src/collide.rs | 71 +++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 20 deletions(-) diff --git a/rask-engine/src/collide.rs b/rask-engine/src/collide.rs index cdb8586e..a220691e 100644 --- a/rask-engine/src/collide.rs +++ b/rask-engine/src/collide.rs @@ -58,29 +58,51 @@ fn project(rbox: &RBox, axis: &Vec2) -> Projection { /// `bound` is a tuple of the start and ending point of the AABB. /// `pos` is a component of the position vector of the line segment. /// `direction` is a component of the direction vector of the line segment. -fn calculate_aabox_rbox_component_bounds(bound: Range, pos: f32, direction: f32) - -> (f32, f32) { - if direction == 0.0 { return (0.0, 1.0) } +fn calculate_aabox_rbox_component_bounds( + bound: Range, + pos: f32, + direction: f32, +) -> (f32, f32) { + if direction == 0.0 { + return (0.0, 1.0); + } // get bounds of s by transforming "g(s) = pos + s * direction" // and applying the inequation g(s) >= bound.start and g(s) <= bound.end - let (s1, s2) = ((bound.start - pos) / direction, (bound.end - pos) / direction); + let (s1, s2) = ( + (bound.start - pos) / direction, + (bound.end - pos) / direction, + ); // if direction is negative, you have to switch the values - if direction > 0.0 { (s1, s2) } - else { (s2, s1) } + if direction > 0.0 { + (s1, s2) + } else { + (s2, s1) + } } /// Test for collision between an AABox and an edge of a rbox -fn collide_aabox_rbox_segment(xbound: Range, ybound: Range, pos: Vec2, direction: Vec2) - -> bool { +fn collide_aabox_rbox_segment( + xbound: Range, + ybound: Range, + pos: Vec2, + direction: Vec2, +) -> bool { let sbound1 = calculate_aabox_rbox_component_bounds(xbound, pos.x(), direction.x()); - if sbound1.0 > sbound1.1 { return false; } + if sbound1.0 > sbound1.1 { + return false; + } let sbound2 = calculate_aabox_rbox_component_bounds(ybound, pos.y(), direction.y()); - if sbound2.0 > sbound2.1 { return false; } + if sbound2.0 > sbound2.1 { + return false; + } let (sbound1, sbound2) = (sbound1.0..sbound1.1, sbound2.0..sbound2.1); - sbound1.end >= sbound2.start && sbound1.start <= sbound2.end - && sbound1.end >= 0.0 && sbound2.end >= 0.0 - && sbound1.start <= 1.0 && sbound2.start <= 1.0 + sbound1.end >= sbound2.start + && sbound1.start <= sbound2.end + && sbound1.end >= 0.0 + && sbound2.end >= 0.0 + && sbound1.start <= 1.0 + && sbound2.start <= 1.0 } impl Collide for Vec2 { @@ -127,14 +149,23 @@ impl Collide for spine::skeleton::SRT { impl Collide for RBox { fn collides(&self, other: &AABox) -> bool { - let xbound = other.pos.x()..other.pos.x()+other.size.x(); - let ybound = other.pos.y()..other.pos.y()+other.size.y(); - let edges = [(self.pos, self.v1), (self.pos, self.v2), - (self.pos + self.v1, self.v2), (self.pos + self.v2, self.v1)]; + let xbound = other.pos.x()..other.pos.x() + other.size.x(); + let ybound = other.pos.y()..other.pos.y() + other.size.y(); + let edges = [ + (self.pos, self.v1), + (self.pos, self.v2), + (self.pos + self.v1, self.v2), + (self.pos + self.v2, self.v1), + ]; collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos, self.v1) - || collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos, self.v2) - || collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos + self.v1, self.v2) - || collide_aabox_rbox_segment(xbound, ybound, self.pos + self.v2, self.v1) + || collide_aabox_rbox_segment(xbound.clone(), ybound.clone(), self.pos, self.v2) + || collide_aabox_rbox_segment( + xbound.clone(), + ybound.clone(), + self.pos + self.v1, + self.v2, + ) + || collide_aabox_rbox_segment(xbound, ybound, self.pos + self.v2, self.v1) } } From 21e25397a82771f9b4d8f8a6cdef8b62926cc2f7 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 05:18:01 +0200 Subject: [PATCH 27/35] Start introducing ResourceTable * Calculate Length of memory areas at compile time --- Cargo.lock | 1 + client/build.rs | 25 +++++------- client/graphics/Cargo.toml | 1 + client/graphics/src/context.rs | 17 ++++++-- client/graphics/src/graphics.rs | 13 +++--- client/graphics/src/render.rs | 49 +++------------------- client/logic/src/game_context.rs | 61 ++++++---------------------- client/shared/src/mem.rs | 30 +++++++++++++- client/shared/src/sprite.rs | 56 ++----------------------- rask-engine/src/resources/library.rs | 46 ++++++++++++--------- rask-engine/src/resources/mod.rs | 6 +-- 11 files changed, 113 insertions(+), 192 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fc3aa178..b8d6d43a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1278,6 +1278,7 @@ version = "0.1.0" dependencies = [ "fern", "js-sys", + "lazy_static", "log", "rand 0.7.3", "rask-engine", diff --git a/client/build.rs b/client/build.rs index 79f5c3d8..a51bf904 100644 --- a/client/build.rs +++ b/client/build.rs @@ -30,15 +30,11 @@ const ALLOCATOR_SIZE: usize = MiB(1); /// Size of the internal resource library. /// This determines the highest available id. -const RESOURCE_TABLE_SIZE: usize = 512; +const RESOURCE_TABLE_SIZE: usize = KiB(1); -/// Size of rask_engine::resources::resource -const RESOURCE_SIZE: usize = 32; - -/// Length of the message queue used to communicate between main.js and the logic thread -/// This address must be exorted to javascript. -const MESSAGE_QUEUE_LENGTH: usize = 64; -const MESSAGE_QUEUE_ELEMENT_SIZE: usize = 32; +/// Size of the message queue used to communicate between main.js and the logic thread +/// Its address must be exorted to javascript. +const MESSAGE_QUEUE_SIZE: usize = 64; /// The address memory synchronization area. /// It contains data needed for synchronization between main thread and logic thread. @@ -46,9 +42,7 @@ const MESSAGE_QUEUE_ELEMENT_SIZE: usize = 32; const SYNCHRONIZATION_MEMORY_SIZE: usize = 32; /// Number of sprites to store in the double buffer -const BUFFER_SPRITE_COUNT: usize = 32; -/// Size of each sprites -const BUFFER_SPRITE_SIZE: usize = 32; +const BUFFER_SIZE: usize = KiB(1); fn main() -> std::io::Result<()> { println!("{:#?}", std::env::vars().collect::>()); @@ -71,17 +65,20 @@ fn main() -> std::io::Result<()> { let graphics_heap = align(alloc + ALLOCATOR_SIZE); let sync = align(alloc + GRAPHICS_HEAP_SIZE); let table = align(sync + SYNCHRONIZATION_MEMORY_SIZE); - let buffer = align(table + RESOURCE_SIZE * RESOURCE_TABLE_SIZE); - let queue = align(buffer + BUFFER_SPRITE_SIZE * BUFFER_SPRITE_COUNT); - let logic_heap = align(queue + MESSAGE_QUEUE_ELEMENT_SIZE * MESSAGE_QUEUE_LENGTH); + let buffer = align(table + RESOURCE_TABLE_SIZE); + let queue = align(buffer + BUFFER_SIZE); + let logic_heap = align(queue + MESSAGE_QUEUE_SIZE); println!("cargo:rustc-env=GRAPHICS_STACK={}", graphics_stack); println!("cargo:rustc-env=ALLOCATOR={}", alloc); println!("cargo:rustc-env=GRAPHICS_HEAP={}", graphics_heap); println!("cargo:rustc-env=SYNCHRONIZATION_MEMORY={}", sync); println!("cargo:rustc-env=RESOURCE_TABLE={}", table); + println!("cargo:rustc-env=RESOURCE_TABLE_SIZE={}", buffer - table); println!("cargo:rustc-env=DOUBLE_BUFFER={}", buffer); + println!("cargo:rustc-env=DOUBLE_BUFFER_SIZE={}", queue - buffer); println!("cargo:rustc-env=MESSAGE_QUEUE={}", queue); + println!("cargo:rustc-env=MESSAGE_QUEUE_SIZE={}", logic_heap - queue); println!("cargo:rustc-env=LOGIC_HEAP={}", logic_heap); if !is_logic { diff --git a/client/graphics/Cargo.toml b/client/graphics/Cargo.toml index ff8708bb..7c195683 100644 --- a/client/graphics/Cargo.toml +++ b/client/graphics/Cargo.toml @@ -17,6 +17,7 @@ log = "0.4" js-sys = "=0.3.35" fern = "0.5.9" rand = "0.7" +lazy_static = "1.4" [dependencies.rask-wasm-shared] version = "0.1.0" diff --git a/client/graphics/src/context.rs b/client/graphics/src/context.rs index 00ed69ce..b7f2cdd1 100644 --- a/client/graphics/src/context.rs +++ b/client/graphics/src/context.rs @@ -1,7 +1,19 @@ use crate::graphics::WebGl; use crate::render::Render; +use lazy_static::lazy_static; +use rask_engine::resources::*; +use rask_engine::resources::{GetStore, ResourceTable}; use rask_wasm_shared::error::ClientError; -use rask_wasm_shared::sprite::{Animation, Frame}; +use rask_wasm_shared::mem::{RESOURCE_TABLE as rt, RESOURCE_TABLE_ELEMENT_COUNT as rtc}; +use rask_wasm_shared::sprite::Frame; + +lazy_static! { + static ref RESOURCE_TABLE: ResourceTable = unsafe { + let mut table = ResourceTable::new(rt, rtc); + table.init(); + table + }; +} pub struct Context { render: Render, @@ -13,8 +25,7 @@ impl Context { } pub fn render(&mut self) -> Result<(), ClientError> { - //self.render - // .render(rask_wasm_shared::mem::shared_heap().animations()) + self.render.render(); Ok(()) } } diff --git a/client/graphics/src/graphics.rs b/client/graphics/src/graphics.rs index 1e24fd1e..e41c6b17 100644 --- a/client/graphics/src/graphics.rs +++ b/client/graphics/src/graphics.rs @@ -69,7 +69,7 @@ pub trait GraphicsApi: Sized { fn start_frame(&mut self, color: &[f32; 3]) -> Result<(), ClientError>; fn end_frame(&self) -> Result<(), ClientError>; - fn draw_rect(&self, pos: &math::Vec2, mat: &Mat3, tex: u32) -> Result<(), ClientError>; + fn draw_rect(&self, mat: &Mat3, tex: u32) -> Result<(), ClientError>; fn upload_texture(&mut self, texture: &mut Texture, n: u32) -> Result<(), ClientError>; fn resize_texture_pool(&mut self, n: u32) -> Result<(), ClientError>; fn ok(&self) -> Result<(), Self::GraphicsError>; @@ -272,13 +272,13 @@ impl GraphicsApi for WebGl { self.fb.render_pass_1(&self.gl); self.gl .viewport(0, 0, self.width as i32, self.height as i32); - self.draw_rect_notexture(&math::Vec2::new(0.0, 0.0), &-Mat3::identity())?; + self.draw_rect_notexture(&-Mat3::identity())?; Ok(()) } - fn draw_rect(&self, pos: &math::Vec2, mat: &Mat3, tex: TextureId) -> Result<(), ClientError> { + fn draw_rect(&self, mat: &Mat3, tex: TextureId) -> Result<(), ClientError> { self.bind_texture(tex); - self.draw_rect_notexture(pos, mat) + self.draw_rect_notexture(mat) } } @@ -348,11 +348,10 @@ impl WebGl { } } - fn draw_rect_notexture(&self, pos: &math::Vec2, mat: &Mat3) -> Result<(), ClientError> { + fn draw_rect_notexture(&self, mat: &Mat3) -> Result<(), ClientError> { self.prog.upload_fransformation(&self.gl, mat); self.prog.upload_texture_id(&self.gl, 0); - self.gl - .vertex_attrib2fv_with_f32_array(1, &[pos.x(), pos.y()]); + // TODO Fix self.gl.vertex_attrib2fv_with_f32_array(1, &[pos.x(), pos.y()]); self.gl.draw_arrays(Gl2::TRIANGLES, 0, 6); Ok(()) } diff --git a/client/graphics/src/render.rs b/client/graphics/src/render.rs index d74924ff..234370f3 100644 --- a/client/graphics/src/render.rs +++ b/client/graphics/src/render.rs @@ -2,7 +2,7 @@ use crate::graphics::GraphicsApi; use rask_engine::math::Mat3; use rask_wasm_shared::error::ClientError; use rask_wasm_shared::get_double_buffer; -use rask_wasm_shared::sprite::{Animation, Frame, Sprite}; +use rask_wasm_shared::sprite::{Frame, Sprite}; use rask_wasm_shared::state::State; use rask_wasm_shared::texture::Texture; @@ -22,65 +22,26 @@ impl Render { }) } - pub fn render(&mut self, animations: &[Animation]) -> Result<(), ClientError> { + pub fn render(&mut self) -> Result<(), ClientError> { self.graphics .ok() .map_err(|e| ClientError::WebGlError(format!("WebGl2 error: {}", e)))?; - //if rask_wasm_shared::mem::shared_heap().get_texture_notify() { - // rask_wasm_shared::mem::shared_heap().unset_texture_notify(); - // self.update_textures()?; - //} self.graphics.start_frame(&[0.8, 0.05, 0.55])?; - if self.draw_sprites(animations)? { + if self.draw_sprites()? { self.frame_nr += 1; } self.graphics.end_frame() } - pub fn update_textures(&mut self) -> Result<(), ClientError> { - /*if let Some(textures) = rask_wasm_shared::mem::shared_heap().textures_mut() { - let n = textures.len() as u32; - self.graphics.resize_texture_pool(n)?; - if n > self.texture_count { - for (i, texture) in textures - .iter_mut() - .skip(self.texture_count as usize) - .enumerate() - { - self.graphics.upload_texture(texture, i as u32)? - } - } - self.texture_count = n; - }*/ - Ok(()) - } - - pub fn draw_sprites(&mut self, animations: &[Animation]) -> Result { + pub fn draw_sprites(&mut self) -> Result { if let Some(state) = get_double_buffer().borrow_reader() { for sprite in state.get().sprites().iter() { //log::debug!("draw sprite: {:?}", sprite); - self.draw_sprite(sprite, animations)?; + self.graphics.draw_rect(&sprite.transform, sprite.tex_id)?; } Ok(true) } else { Ok(false) } } - - pub fn draw_sprite( - &mut self, - sprite: &Sprite, - animations: &[Animation], - ) -> Result<(), ClientError> { - let frame = sprite - .get_frame(animations) - .ok_or(ClientError::ResourceError( - "could not get animation frame".to_owned(), - ))?; - for transformation in frame.transformations().iter() { - self.graphics - .draw_rect(&sprite.pos, transformation, sprite.tex_id)?; - } - Ok(()) - } } diff --git a/client/logic/src/game_context.rs b/client/logic/src/game_context.rs index 32b6dd86..8b011964 100644 --- a/client/logic/src/game_context.rs +++ b/client/logic/src/game_context.rs @@ -1,6 +1,8 @@ use rask_engine::math; +use rask_engine::resources::{GetStore, ResourceTable, Texture}; use rask_wasm_shared::error::ClientError; use rask_wasm_shared::get_double_buffer; +use rask_wasm_shared::mem::{RESOURCE_TABLE, RESOURCE_TABLE_ELEMENT_COUNT}; use rask_wasm_shared::sprite::*; use rask_wasm_shared::state::State; @@ -10,6 +12,7 @@ const IMAGE2_DATA: &[u8] = include_bytes!("../../res/thief.png"); pub struct GameContext { state: State, tick_nr: u64, + resource_table: ResourceTable, } impl GameContext { @@ -17,6 +20,9 @@ impl GameContext { Ok(Self { state: State::default(), tick_nr: 0, + resource_table: unsafe { + ResourceTable::new(RESOURCE_TABLE, RESOURCE_TABLE_ELEMENT_COUNT) + }, }) } @@ -28,57 +34,16 @@ impl GameContext { pub fn tick(&mut self) -> Result<(), ClientError> { if self.state.sprites().is_empty() { - self.state - .append_sprite(&Sprite::new(math::Vec2::new(0.0, 0.0), 3, 0, 0)); - self.state - .append_sprite(&Sprite::new(math::Vec2::new(0.0, 0.0), 2, 0, 0)); - self.state - .append_sprite(&Sprite::new(math::Vec2::new(0.3, 0.3), 0, 0, 1)); - self.state - .append_sprite(&Sprite::new(math::Vec2::new(0.0, 0.0), 1, 0, 1)); - self.state - .append_sprite(&Sprite::new(math::Vec2::new(0.0, -0.6), 0, 0, 1)); - self.state - .append_sprite(&Sprite::new(math::Vec2::new(-0.6, 0.6), 1, 0, 1)); + self.state.append_sprite(&Sprite::default()); - /*let shared_heap = rask_wasm_shared::mem::shared_heap(); - *shared_heap.animations_mut() = vec![ - Animation::new(vec![ - Frame::new(vec![rask_engine::math::Mat3::scaling(0.4, 0.4)]), - Frame::new(vec![ - rask_engine::math::Mat3::scaling(0.4, 0.4) - * rask_engine::math::Mat3::translation(0.5, 0.0) - * rask_engine::math::Mat3::rotation(6.0), - ]), - ]), - Animation::new(vec![ - Frame::new(vec![rask_engine::math::Mat3::scaling(0.4, 0.4)]), - Frame::new(vec![rask_engine::math::Mat3::scaling(0.6, 0.2)]), - ]), - Animation::new(vec![Frame::new(vec![rask_engine::math::Mat3::scaling( - 9.0 / 16.0, - 1.0, - )])]), - Animation::new(vec![Frame::new(vec![rask_engine::math::Mat3::identity()])]), - ]; - - *shared_heap.textures_mut() = Some(vec![ - rask_wasm_shared::texture::Texture::from_png_stream(IMAGE1_DATA)?, - rask_wasm_shared::texture::Texture::from_png_stream(IMAGE2_DATA)?, - ]); - shared_heap.set_texture_notify(); - */ + unsafe { + self.resource_table + .store(Texture::from_png_stream(IMAGE1_DATA)?, 0)?; + self.resource_table + .store(Texture::from_png_stream(IMAGE2_DATA)?, 1)?; + } } - /* - let animations = rask_wasm_shared::mem::shared_heap().animations(); - for sprite in self.state.sprites_mut().iter_mut() { - if (self.tick_nr % 10) == 9 { - sprite - .next_frame(animations) - .ok_or(ClientError::ResourceError(format!("invalid animation id")))?; - } - }*/ self.push_state()?; self.tick_nr += 1; Ok(()) diff --git a/client/shared/src/mem.rs b/client/shared/src/mem.rs index 219fcedd..a9878912 100644 --- a/client/shared/src/mem.rs +++ b/client/shared/src/mem.rs @@ -1,7 +1,11 @@ type Buffer = crate::double_buffer::DoubleBuffer; +use crate::double_buffer::DoubleBuffer; +use crate::sprite::Sprite; use crate::state::State; use const_env::from_env; +use rask_engine::resources::{Resource, ResourceTable}; +use std::mem::size_of; #[from_env] /// The position of the stack. @@ -11,6 +15,7 @@ pub const GRAPHIC_STACK: usize = 0; /// The address of the Allocator structures pub const ALLOCATOR: usize = 0; +#[from_env] /// The graphics heap address pub const GRAPHICS_HEAP: usize = 0; @@ -21,15 +26,35 @@ pub const GRAPHICS_HEAP: usize = 0; /// On change you have to modify the corresponding js file. pub const SYNCHRONIZATION_MEMORY: usize = 0; -/// Adress of the internal resource library. +#[from_env] +/// Address of the internal resource library. pub const RESOURCE_TABLE: usize = 0; +#[from_env] +pub const RESOURCE_TABLE_SIZE: usize = 0; +pub const RESOURCE_TABLE_ELEMENT_COUNT: usize = (RESOURCE_TABLE_SIZE as i64 + - size_of::() as i64) as usize + / size_of::(); +#[from_env] /// The address of the double buffer (size: target dependent) pub const DOUBLE_BUFFER: usize = 0; +#[from_env] +pub const DOUBLE_BUFFER_SIZE: usize = 0; +pub const DOUBLE_BUFFER_ELEMENT_COUNT: usize = + (DOUBLE_BUFFER_SIZE as i64 - size_of::>() as i64) as usize + / size_of::(); -/// Adress of the event queue +#[from_env] +/// Address of the event queue pub const MESSAGE_QUEUE: usize = 0; +#[from_env] +pub const MESSAGE_QUEUE_SIZE: usize = 0; +pub const MESSAGE_QUEUE_ELEMENT_COUNT: usize = (MESSAGE_QUEUE_SIZE as i64 + - size_of::>>() as i64) + as usize + / size_of::>(); +#[from_env] /// The logic heap address (size: 32MiB) pub const LOGIC_HEAP: usize = 0; @@ -64,6 +89,7 @@ impl SynchronizationMemory { } #[repr(align(4))] +#[derive(Clone)] struct MessageQueueElement { reading: u8, writing: u8, diff --git a/client/shared/src/sprite.rs b/client/shared/src/sprite.rs index b7111c4e..b446e46b 100644 --- a/client/shared/src/sprite.rs +++ b/client/shared/src/sprite.rs @@ -6,70 +6,22 @@ pub type TextureId = u32; #[derive(Clone, Copy, Debug)] pub struct Sprite { - pub pos: math::Vec2, - pub animation_id: AnimationId, - pub frame_id: FrameId, + pub transform: math::Mat3, pub tex_id: TextureId, } impl Default for Sprite { fn default() -> Self { Self { - pos: math::Vec2::new(0.0, 0.0), - animation_id: 0, - frame_id: 0, + transform: math::Mat3::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0), tex_id: 0, } } } impl Sprite { - pub fn get_animation<'a>(&self, animations: &'a [Animation]) -> Option<&'a Animation> { - animations.get(self.animation_id as usize) - } - - pub fn get_frame<'a>(&self, animations: &'a [Animation]) -> Option<&'a Frame> { - self.get_animation(animations)? - .frames - .get(self.frame_id as usize) - } - - pub fn new( - pos: math::Vec2, - animation_id: AnimationId, - frame_id: FrameId, - tex_id: TextureId, - ) -> Self { - Self { - pos, - animation_id, - frame_id, - tex_id, - } - } - - pub fn next_frame(&mut self, animations: &[Animation]) -> Option { - self.frame_id = self.get_animation(animations)?.next(self.frame_id); - Some(self.frame_id) - } -} - -#[derive(Debug)] -pub struct Animation { - frames: Vec, -} - -impl Animation { - pub fn new(frames: Vec) -> Self { - Self { frames } - } - - pub fn next(&self, frame_id: FrameId) -> FrameId { - match self.frames.len() as u32 { - 0 => 0, - len if len - 1 <= frame_id => (frame_id + 1) % len, - _ => frame_id + 1, - } + pub fn new(transform: math::Mat3, tex_id: TextureId) -> Self { + Self { transform, tex_id } } } diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index ff99177f..5d8c2104 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -1,26 +1,22 @@ use super::Resource; use crate::EngineError; -/// Size of the internal catalog. -/// This determines the highest available id. -const CATALOG_SIZE: usize = 512; - /// The library is used to store and retrieve resources. -pub struct Library { - catalog: &'static mut [Resource], -} +pub struct ResourceTable(&'static mut [Resource]); macro_rules! get_store { ($type: ty, $enum_type: ident) => { - impl GetStore<$type> for Library { + impl GetStore<$type> for ResourceTable { unsafe fn get(&'static self, id: usize) -> Result<&'static $type, EngineError> { - match &self.catalog[id] { + self.index_check(id)?; + match &self.0[id] { Resource::$enum_type(value) => Ok(&value), _ => Err("Wrong resource type".into()), } } - unsafe fn store(&'static mut self, data: $type, id: usize) { - self.catalog[id] = Resource::$enum_type(data); + unsafe fn store(&mut self, data: $type, id: usize) -> Result<(), EngineError> { + self.index_check(id)?; + Ok(self.0[id] = Resource::$enum_type(data)) } } }; @@ -38,25 +34,37 @@ pub trait GetStore { /// # Safety /// /// The function is not thread safe. - unsafe fn store(&'static mut self, data: T, id: usize); + unsafe fn store(&mut self, data: T, id: usize) -> Result<(), EngineError>; } -impl Library { +impl ResourceTable { /// Create a new library at a specific position in memory. /// /// # Safety /// /// The function is safe as long as the memory from memory_offset to memory_offset + CATALOG_SIZE * sizeof(Resource) - pub unsafe fn new(memory_offset: usize) -> Self { - Library { - catalog: core::slice::from_raw_parts_mut(memory_offset as *mut Resource, CATALOG_SIZE), - } + pub unsafe fn new(memory_offset: usize, catalog_size: usize) -> Self { + ResourceTable(core::slice::from_raw_parts_mut( + memory_offset as *mut Resource, + catalog_size, + )) } pub unsafe fn init(&mut self) { - for i in 0..CATALOG_SIZE { - self.catalog[i] = Resource::None; + for i in 0..self.0.len() { + self.0[i] = Resource::None; + } + } + + fn index_check(&self, id: usize) -> Result<(), EngineError> { + if id > self.0.len() { + return Err(EngineError::ResourceError(format!( + "The requested texture index: {} is out ouf range, the max id is {}", + id, + self.0.len() - 1 + ))); } + Ok(()) } } diff --git a/rask-engine/src/resources/mod.rs b/rask-engine/src/resources/mod.rs index 1b22c08f..d5207b41 100644 --- a/rask-engine/src/resources/mod.rs +++ b/rask-engine/src/resources/mod.rs @@ -21,18 +21,18 @@ fn test() { ``` */ -pub mod library; +mod library; pub mod sound; pub mod texture; #[doc(inline)] -pub use library::Library; +pub use library::*; #[doc(inline)] pub use sound::Sound; #[doc(inline)] pub use texture::Texture; -enum Resource { +pub enum Resource { None, Texture(Texture), Sound(Sound), From 577f8bef3ba81b0d315c72cbb9da9555311ccf64 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 06:24:23 +0200 Subject: [PATCH 28/35] Add upload_texture function to render --- client/graphics/src/context.rs | 5 ++--- client/graphics/src/graphics.rs | 13 ++++++++++--- client/graphics/src/render.rs | 19 +++++++++++++++++-- client/shared/src/double_buffer.rs | 4 ++++ client/shared/src/lib.rs | 2 +- 5 files changed, 34 insertions(+), 9 deletions(-) diff --git a/client/graphics/src/context.rs b/client/graphics/src/context.rs index b7f2cdd1..27075f68 100644 --- a/client/graphics/src/context.rs +++ b/client/graphics/src/context.rs @@ -8,7 +8,7 @@ use rask_wasm_shared::mem::{RESOURCE_TABLE as rt, RESOURCE_TABLE_ELEMENT_COUNT a use rask_wasm_shared::sprite::Frame; lazy_static! { - static ref RESOURCE_TABLE: ResourceTable = unsafe { + pub static ref RESOURCE_TABLE: ResourceTable = unsafe { let mut table = ResourceTable::new(rt, rtc); table.init(); table @@ -25,8 +25,7 @@ impl Context { } pub fn render(&mut self) -> Result<(), ClientError> { - self.render.render(); - Ok(()) + self.render.render() } } diff --git a/client/graphics/src/graphics.rs b/client/graphics/src/graphics.rs index e41c6b17..922d63c8 100644 --- a/client/graphics/src/graphics.rs +++ b/client/graphics/src/graphics.rs @@ -1,10 +1,10 @@ use crate::shader::Program; use rask_engine::math; use rask_engine::math::Mat3; +use rask_engine::resources::texture::{ColorType, Texture}; use rask_wasm_shared::error::ClientError; use rask_wasm_shared::sprite::TextureId; use rask_wasm_shared::state::State; -use rask_wasm_shared::texture::{ColorType, Texture}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::WebGl2RenderingContext as Gl2; @@ -70,8 +70,9 @@ pub trait GraphicsApi: Sized { fn start_frame(&mut self, color: &[f32; 3]) -> Result<(), ClientError>; fn end_frame(&self) -> Result<(), ClientError>; fn draw_rect(&self, mat: &Mat3, tex: u32) -> Result<(), ClientError>; - fn upload_texture(&mut self, texture: &mut Texture, n: u32) -> Result<(), ClientError>; + fn upload_texture(&mut self, texture: &Texture, n: u32) -> Result<(), ClientError>; fn resize_texture_pool(&mut self, n: u32) -> Result<(), ClientError>; + fn grow_texture_pool(&mut self, n: u32) -> Result<(), ClientError>; fn ok(&self) -> Result<(), Self::GraphicsError>; } @@ -208,7 +209,7 @@ impl GraphicsApi for WebGl { }) } - fn upload_texture(&mut self, texture: &mut Texture, n: u32) -> Result<(), ClientError> { + fn upload_texture(&mut self, texture: &Texture, n: u32) -> Result<(), ClientError> { log::debug!( "uploading texture (id {}, {}x{})", n, @@ -256,6 +257,12 @@ impl GraphicsApi for WebGl { Ok(()) } + fn grow_texture_pool(&mut self, n: u32) -> Result<(), ClientError> { + Ok(self + .texture_handles + .resize(self.texture_handles.len() + n as usize, None)) + } + fn ok(&self) -> Result<(), Self::GraphicsError> { Self::_ok(&self.gl) } diff --git a/client/graphics/src/render.rs b/client/graphics/src/render.rs index 234370f3..42f97d7f 100644 --- a/client/graphics/src/render.rs +++ b/client/graphics/src/render.rs @@ -1,10 +1,12 @@ +use crate::context::RESOURCE_TABLE; use crate::graphics::GraphicsApi; use rask_engine::math::Mat3; +use rask_engine::resources::GetStore; +use rask_engine::resources::Texture; use rask_wasm_shared::error::ClientError; use rask_wasm_shared::get_double_buffer; use rask_wasm_shared::sprite::{Frame, Sprite}; use rask_wasm_shared::state::State; -use rask_wasm_shared::texture::Texture; pub struct Render { graphics: T, @@ -33,10 +35,23 @@ impl Render { self.graphics.end_frame() } + pub fn upload_texture(&mut self, id: u32) -> Result<(), ClientError> { + let texture = unsafe { RESOURCE_TABLE.get(id as usize)? }; + //self.graphics.grow_texture_pool(1); + self.graphics.upload_texture(texture, id)?; + self.texture_count += 1; + Ok(()) + } + pub fn draw_sprites(&mut self) -> Result { if let Some(state) = get_double_buffer().borrow_reader() { - for sprite in state.get().sprites().iter() { + let sprites = state.get().sprites(); + self.graphics.resize_texture_pool(sprites.len() as u32)?; + self.texture_count = 0; + for sprite in sprites { //log::debug!("draw sprite: {:?}", sprite); + self.upload_texture(sprite.tex_id)?; + self.graphics.draw_rect(&sprite.transform, sprite.tex_id)?; } Ok(true) diff --git a/client/shared/src/double_buffer.rs b/client/shared/src/double_buffer.rs index 786578b8..f3425b15 100644 --- a/client/shared/src/double_buffer.rs +++ b/client/shared/src/double_buffer.rs @@ -72,21 +72,25 @@ impl DoubleBuffer { } } + #[allow(unused_attributes)] #[inline(always)] pub extern "C" fn set_reading_at(&mut self, reading_at: Flag) { unsafe { mem::atomic_write_u8(&mut self.reading_at, reading_at) } } + #[allow(unused_attributes)] #[inline(always)] pub extern "C" fn get_reading_at(&self) -> Flag { unsafe { mem::atomic_read_u8(&self.reading_at) } } + #[allow(unused_attributes)] #[inline(always)] pub extern "C" fn set_provided(&mut self, provided: Flag) { unsafe { mem::atomic_write_u8(&mut self.provided, provided) } } + #[allow(unused_attributes)] #[inline(always)] pub extern "C" fn get_provided(&self) -> Flag { unsafe { mem::atomic_read_u8(&self.provided) } diff --git a/client/shared/src/lib.rs b/client/shared/src/lib.rs index dfa62710..ea163cd5 100644 --- a/client/shared/src/lib.rs +++ b/client/shared/src/lib.rs @@ -12,5 +12,5 @@ pub mod wasm_log; pub use error::*; pub use mem::*; -pub use rask_engine::resources::texture; +//pub use rask_engine::resources::texture; pub use wee_alloc; From ec19728ace3a354d323d50f66a4a6fc03df5042f Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 06:30:48 +0200 Subject: [PATCH 29/35] Crate gen/ directory if it does not exist --- client/Makefile.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/client/Makefile.toml b/client/Makefile.toml index 91c64e86..4443973a 100644 --- a/client/Makefile.toml +++ b/client/Makefile.toml @@ -31,6 +31,7 @@ condition = { env_set = [ "CARGO_TARGET_DIR" ] } env = { "RUSTFLAGS" = "-Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--threads -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory" } script = [ "touch build.rs && cargo make exec-${BUILD_ENV} -- build -p rask-${@} --target wasm32-unknown-unknown", + "mkdir -p gen", "mv $(find $CARGO_TARGET_DIR/ -name mem.json) gen/", ] From a445563769d9a5709dc50574b3577f9686a23fdd Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 15:00:22 +0200 Subject: [PATCH 30/35] Fix broke Cargo.lock --- Cargo.lock | 29 +++-------------------------- 1 file changed, 3 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 83e82c1c..8f6554b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15,12 +15,6 @@ dependencies = [ "winapi 0.3.8", ] -[[package]] -name = "anyhow" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9a60d744a80c30fcb657dfe2c1b22bcb3e814c1a1e3674f32bf5820b570fbff" - [[package]] name = "atty" version = "0.2.14" @@ -46,9 +40,9 @@ checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" [[package]] name = "backtrace" -version = "0.3.45" +version = "0.3.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad235dabf00f36301792cfe82499880ba54c6486be094d1047b02bacb67c14e8" +checksum = "b1e692897359247cc6bb902933361652380af0f1b7651ae5c5013407f30e109e" dependencies = [ "backtrace-sys", "cfg-if", @@ -651,15 +645,9 @@ dependencies = [ [[package]] name = "image" -<<<<<<< HEAD version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfc5483f8d5afd3653b38a196c52294dcb239c3e1a5bade1990353ea13bcf387" -======= -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9062b90712d25bc6bb165d110aa59c6b47c849246e341e7b86a98daff9d49f60" ->>>>>>> master dependencies = [ "bytemuck", "byteorder", @@ -1037,15 +1025,9 @@ checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" [[package]] name = "png" -<<<<<<< HEAD version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "910f09135b1ed14bb16be445a8c23ddf0777eca485fbfc7cee00d81fecab158a" -======= -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46060468187c21c00ffa2a920690b29997d7fd543f5a4d400461e4a7d4fccde8" ->>>>>>> master dependencies = [ "bitflags", "crc32fast", @@ -1465,6 +1447,7 @@ dependencies = [ "bitflags", "core-foundation", "core-foundation-sys", + "libc", "security-framework-sys", ] @@ -1495,15 +1478,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" [[package]] name = "serde" -<<<<<<< HEAD version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36df6ac6412072f67cf767ebbde4133a5b2e88e76dc6187fa7104cd16f783399" -======= -version = "1.0.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e707fbbf255b8fc8c3b99abb91e7257a622caeb20a9818cbadbeeede4e0932ff" ->>>>>>> master dependencies = [ "serde_derive", ] From cc451e35b2c5f69e111274456293d64457943db0 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 17:04:55 +0200 Subject: [PATCH 31/35] Fix some minor issues --- client/Makefile.toml | 3 ++- client/build.rs | 27 ++++++++++++++------------- rask-engine/src/resources/library.rs | 4 ++-- rask-engine/src/resources/mod.rs | 4 ++-- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/client/Makefile.toml b/client/Makefile.toml index 1d9c3b45..5da74f85 100644 --- a/client/Makefile.toml +++ b/client/Makefile.toml @@ -30,7 +30,8 @@ workspace = false condition = { env_set = [ "CARGO_TARGET_DIR" ] } env = { "RUSTFLAGS" = "-Clink-arg=--no-entry -Clink-arg=--allow-undefined -Clink-arg=--strip-all -Clink-arg=--export-dynamic -Clink-arg=--import-memory -Clink-arg=--shared-memory -Clink-arg=--threads -Clink-arg=--export=__wasm_init_memory -Clink-arg=--no-check-features -Clink-arg=--export=__wasm_init_tls -Clink-arg=--export=__tls_size -Ctarget-feature=+atomics,+bulk-memory" } script = [ - "touch build.rs && cargo make exec-${BUILD_ENV} -- build -p rask-${@} --target wasm32-unknown-unknown", + "touch build.rs #triggers the build.rs to be rebuild every time", + "cargo make exec-${BUILD_ENV} -- build -p rask-${@} --target wasm32-unknown-unknown", "mkdir -p gen", "mv $(find $CARGO_TARGET_DIR/ -name mem.json) gen/", ] diff --git a/client/build.rs b/client/build.rs index a51bf904..34e198b1 100644 --- a/client/build.rs +++ b/client/build.rs @@ -9,7 +9,8 @@ const fn KiB(n: usize) -> usize { const fn MiB(n: usize) -> usize { n * KiB(1024) } -const fn align(n: usize) -> usize { +/// align the given address to the next 32bit +const fn align32_up(n: usize) -> usize { (n + 3) & !3 } @@ -33,12 +34,12 @@ const ALLOCATOR_SIZE: usize = MiB(1); const RESOURCE_TABLE_SIZE: usize = KiB(1); /// Size of the message queue used to communicate between main.js and the logic thread -/// Its address must be exorted to javascript. +/// Its address must be exported to javascript. const MESSAGE_QUEUE_SIZE: usize = 64; /// The address memory synchronization area. /// It contains data needed for synchronization between main thread and logic thread. -/// This address must be exorted to javascript. +/// This address must be exported to javascript. const SYNCHRONIZATION_MEMORY_SIZE: usize = 32; /// Number of sprites to store in the double buffer @@ -51,8 +52,8 @@ fn main() -> std::io::Result<()> { Ok(worker) if &worker == "logic" => true, Ok(worker) if &worker == "graphics" => false, Ok(key) => panic!( - "{} is no valid value. Possibel values are logic and graphics", - key + "{} is no valid value for {}. Possible values are logic and graphics", + key, WORKER_NAME_VAR, ), Err(std::env::VarError::NotPresent) => { panic!("{} is not defined in the environment.", WORKER_NAME_VAR) @@ -60,14 +61,14 @@ fn main() -> std::io::Result<()> { Err(err) => panic!("env var parsing failed (\"{:?}\")", err), }; - let graphics_stack = align(STACK_ALIGNMENT + GRAPHICS_STACK_SIZE); - let alloc = align(graphics_stack); - let graphics_heap = align(alloc + ALLOCATOR_SIZE); - let sync = align(alloc + GRAPHICS_HEAP_SIZE); - let table = align(sync + SYNCHRONIZATION_MEMORY_SIZE); - let buffer = align(table + RESOURCE_TABLE_SIZE); - let queue = align(buffer + BUFFER_SIZE); - let logic_heap = align(queue + MESSAGE_QUEUE_SIZE); + let graphics_stack = align32_up(STACK_ALIGNMENT + GRAPHICS_STACK_SIZE); + let alloc = align32_up(graphics_stack); + let graphics_heap = align32_up(alloc + ALLOCATOR_SIZE); + let sync = align32_up(alloc + GRAPHICS_HEAP_SIZE); + let table = align32_up(sync + SYNCHRONIZATION_MEMORY_SIZE); + let buffer = align32_up(table + RESOURCE_TABLE_SIZE); + let queue = align32_up(buffer + BUFFER_SIZE); + let logic_heap = align32_up(queue + MESSAGE_QUEUE_SIZE); println!("cargo:rustc-env=GRAPHICS_STACK={}", graphics_stack); println!("cargo:rustc-env=ALLOCATOR={}", alloc); diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index 5d8c2104..ff7ebe39 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -57,9 +57,9 @@ impl ResourceTable { } fn index_check(&self, id: usize) -> Result<(), EngineError> { - if id > self.0.len() { + if id >= self.0.len() { return Err(EngineError::ResourceError(format!( - "The requested texture index: {} is out ouf range, the max id is {}", + "The requested resource index: {} is out ouf range, the max id is {}", id, self.0.len() - 1 ))); diff --git a/rask-engine/src/resources/mod.rs b/rask-engine/src/resources/mod.rs index 5a35ce85..72ec8a1a 100644 --- a/rask-engine/src/resources/mod.rs +++ b/rask-engine/src/resources/mod.rs @@ -8,12 +8,12 @@ use lazy_static::lazy_static; # use rask_engine::resources::*; lazy_static! { - static ref LIB: ResourceTable = unsafe { ResourceTable::new(0, 0) }; + static ref TABLE: ResourceTable = unsafe { ResourceTable::new(0, 0) }; } fn test() { unsafe { - let _texture: &Texture = LIB.get(0).unwrap(); + let _texture: &Texture = TABLE.get(0).unwrap(); } } ``` From a49727d4b269af9e03b22f399828386448185dc1 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 17:13:01 +0200 Subject: [PATCH 32/35] Add lifetimes to GetStore trait --- client/build.rs | 34 +++++++++++++--------------- client/graphics/src/context.rs | 5 ++-- rask-engine/src/resources/library.rs | 8 +++---- 3 files changed, 22 insertions(+), 25 deletions(-) diff --git a/client/build.rs b/client/build.rs index 34e198b1..905bcf9b 100644 --- a/client/build.rs +++ b/client/build.rs @@ -2,48 +2,48 @@ use std::fs::File; use std::io::prelude::*; #[allow(non_snake_case)] -const fn KiB(n: usize) -> usize { +const fn KiB(n: u32) -> u32 { n * 1024 } #[allow(non_snake_case)] -const fn MiB(n: usize) -> usize { +const fn MiB(n: u32) -> u32 { n * KiB(1024) } /// align the given address to the next 32bit -const fn align32_up(n: usize) -> usize { +const fn align32_up(n: u32) -> u32 { (n + 3) & !3 } const WORKER_NAME_VAR: &'static str = "CRATE"; /// Reserved memory -const MAX_MEORY: usize = MiB(512); +const MAX_MEORY: u32 = MiB(512); /// The first page of memory is reserved -const STACK_ALIGNMENT: usize = 1024 * 63; +const STACK_ALIGNMENT: u32 = 1024 * 63; /// The size of the stack. Its start is at address 0 -const GRAPHICS_STACK_SIZE: usize = MiB(4); -const GRAPHICS_HEAP_SIZE: usize = MiB(1); +const GRAPHICS_STACK_SIZE: u32 = MiB(4); +const GRAPHICS_HEAP_SIZE: u32 = MiB(1); /// The size of the Allocator structures -const ALLOCATOR_SIZE: usize = MiB(1); +const ALLOCATOR_SIZE: u32 = MiB(1); /// Size of the internal resource library. /// This determines the highest available id. -const RESOURCE_TABLE_SIZE: usize = KiB(1); +const RESOURCE_TABLE_SIZE: u32 = KiB(1); /// Size of the message queue used to communicate between main.js and the logic thread /// Its address must be exported to javascript. -const MESSAGE_QUEUE_SIZE: usize = 64; +const MESSAGE_QUEUE_SIZE: u32 = 64; /// The address memory synchronization area. /// It contains data needed for synchronization between main thread and logic thread. /// This address must be exported to javascript. -const SYNCHRONIZATION_MEMORY_SIZE: usize = 32; +const SYNCHRONIZATION_MEMORY_SIZE: u32 = 32; /// Number of sprites to store in the double buffer -const BUFFER_SIZE: usize = KiB(1); +const BUFFER_SIZE: u32 = KiB(1); fn main() -> std::io::Result<()> { println!("{:#?}", std::env::vars().collect::>()); @@ -93,12 +93,10 @@ fn main() -> std::io::Result<()> { let out_dir = std::env::var("OUT_DIR").unwrap(); let mut file = File::create(format!("{}/mem.json", out_dir))?; - file.write_all( - format!( - "{{max_memory:{},queue_start:{},sync_area:{}}}", - MAX_MEORY, queue, sync - ) - .as_bytes(), + write!( + &mut file, + "{{max_memory:{},queue_start:{},sync_area:{}}}", + MAX_MEORY, queue, sync )?; Ok(()) } diff --git a/client/graphics/src/context.rs b/client/graphics/src/context.rs index 27075f68..0938bbf5 100644 --- a/client/graphics/src/context.rs +++ b/client/graphics/src/context.rs @@ -1,15 +1,14 @@ use crate::graphics::WebGl; use crate::render::Render; use lazy_static::lazy_static; -use rask_engine::resources::*; use rask_engine::resources::{GetStore, ResourceTable}; use rask_wasm_shared::error::ClientError; -use rask_wasm_shared::mem::{RESOURCE_TABLE as rt, RESOURCE_TABLE_ELEMENT_COUNT as rtc}; +use rask_wasm_shared::mem; use rask_wasm_shared::sprite::Frame; lazy_static! { pub static ref RESOURCE_TABLE: ResourceTable = unsafe { - let mut table = ResourceTable::new(rt, rtc); + let mut table = ResourceTable::new(mem::RESOURCE_TABLE, mem::RESOURCE_TABLE_ELEMENT_COUNT); table.init(); table }; diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index ff7ebe39..ee5ae060 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -6,8 +6,8 @@ pub struct ResourceTable(&'static mut [Resource]); macro_rules! get_store { ($type: ty, $enum_type: ident) => { - impl GetStore<$type> for ResourceTable { - unsafe fn get(&'static self, id: usize) -> Result<&'static $type, EngineError> { + impl<'a> GetStore<'a, $type> for ResourceTable { + unsafe fn get(&'a self, id: usize) -> Result<&'a $type, EngineError> { self.index_check(id)?; match &self.0[id] { Resource::$enum_type(value) => Ok(&value), @@ -22,13 +22,13 @@ macro_rules! get_store { }; } -pub trait GetStore { +pub trait GetStore<'a, T> { /// Retrieve a resource from the library. /// /// # Safety /// /// The function is not thread safe. - unsafe fn get(&'static self, id: usize) -> Result<&'static T, EngineError>; + unsafe fn get(&'a self, id: usize) -> Result<&'a T, EngineError>; /// Store a resource to the library /// /// # Safety From e03029dc2ff8cb4ba0fa6dc4e2c95964f382f8c4 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 18:06:51 +0200 Subject: [PATCH 33/35] Diversify ResourceErrors --- rask-engine/src/error.rs | 8 +++++--- rask-engine/src/resources/library.rs | 4 ++-- rask-engine/src/resources/texture.rs | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/rask-engine/src/error.rs b/rask-engine/src/error.rs index 324ced03..e5740925 100644 --- a/rask-engine/src/error.rs +++ b/rask-engine/src/error.rs @@ -4,7 +4,8 @@ use std::fmt::{self, Display}; /// The error type used by the game engine. #[derive(Debug)] pub enum EngineError { - ResourceError(String), + ResourceType(String), + ResourceIndex(String), MathError(String), Misc(String), } @@ -12,7 +13,8 @@ pub enum EngineError { impl Display for EngineError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - EngineError::ResourceError(e) => write!(f, "ResourceError: {}", e), + EngineError::ResourceType(e) => write!(f, "ResourceError: {}", e), + EngineError::ResourceIndex(e) => write!(f, "ResourceError: {}", e), EngineError::Misc(e) => write!(f, "EngineError: {}", e), EngineError::MathError(e) => write!(f, "MathError: {}", e), } @@ -33,4 +35,4 @@ macro_rules! derive_from { derive_from!(&str, Misc); derive_from!(String, Misc); -derive_from!(image::error::ImageError, ResourceError); +derive_from!(image::error::ImageError, ResourceType); diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index ee5ae060..b8788c1b 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -11,7 +11,7 @@ macro_rules! get_store { self.index_check(id)?; match &self.0[id] { Resource::$enum_type(value) => Ok(&value), - _ => Err("Wrong resource type".into()), + _ => Err(EngineError::ResourceType("Wrong resource type".into())), } } unsafe fn store(&mut self, data: $type, id: usize) -> Result<(), EngineError> { @@ -58,7 +58,7 @@ impl ResourceTable { fn index_check(&self, id: usize) -> Result<(), EngineError> { if id >= self.0.len() { - return Err(EngineError::ResourceError(format!( + return Err(EngineError::ResourceIndex(format!( "The requested resource index: {} is out ouf range, the max id is {}", id, self.0.len() - 1 diff --git a/rask-engine/src/resources/texture.rs b/rask-engine/src/resources/texture.rs index 44e7780f..35d68586 100644 --- a/rask-engine/src/resources/texture.rs +++ b/rask-engine/src/resources/texture.rs @@ -18,7 +18,7 @@ impl Texture { let decoder = PngDecoder::new(r)?; let (w, h) = decoder.dimensions(); - let e = |_| EngineError::ResourceError("invalid image resolution".to_owned()); + let e = |_| EngineError::ResourceType("invalid image resolution".to_owned()); let (w, h) = (w.try_into().map_err(e)?, h.try_into().map_err(e)?); let colortype = decoder.color_type(); From d712d46dba47b1f8964a9b0b2bb06c00bb74f0ab Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 18:13:40 +0200 Subject: [PATCH 34/35] Remove lifetime specification from library --- rask-engine/src/resources/library.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index b8788c1b..5b1c9054 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -6,8 +6,8 @@ pub struct ResourceTable(&'static mut [Resource]); macro_rules! get_store { ($type: ty, $enum_type: ident) => { - impl<'a> GetStore<'a, $type> for ResourceTable { - unsafe fn get(&'a self, id: usize) -> Result<&'a $type, EngineError> { + impl GetStore<$type> for ResourceTable { + unsafe fn get(&self, id: usize) -> Result<&$type, EngineError> { self.index_check(id)?; match &self.0[id] { Resource::$enum_type(value) => Ok(&value), @@ -22,13 +22,13 @@ macro_rules! get_store { }; } -pub trait GetStore<'a, T> { +pub trait GetStore { /// Retrieve a resource from the library. /// /// # Safety /// /// The function is not thread safe. - unsafe fn get(&'a self, id: usize) -> Result<&'a T, EngineError>; + unsafe fn get(&self, id: usize) -> Result<&T, EngineError>; /// Store a resource to the library /// /// # Safety From 5c7ed15d1150a7d1b627147ff15c5a6d11dafc34 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 12 Apr 2020 21:17:44 +0200 Subject: [PATCH 35/35] Fix minor issues --- client/graphics/src/context.rs | 5 +++-- client/logic/src/game_context.rs | 2 +- client/shared/src/double_buffer.rs | 8 -------- client/shared/src/mem.rs | 6 ++---- rask-engine/src/resources/library.rs | 4 ++-- rask-engine/src/resources/mod.rs | 2 +- 6 files changed, 9 insertions(+), 18 deletions(-) diff --git a/client/graphics/src/context.rs b/client/graphics/src/context.rs index 0938bbf5..a45513d8 100644 --- a/client/graphics/src/context.rs +++ b/client/graphics/src/context.rs @@ -8,8 +8,9 @@ use rask_wasm_shared::sprite::Frame; lazy_static! { pub static ref RESOURCE_TABLE: ResourceTable = unsafe { - let mut table = ResourceTable::new(mem::RESOURCE_TABLE, mem::RESOURCE_TABLE_ELEMENT_COUNT); - table.init(); + let mut table = + ResourceTable::from_memory(mem::RESOURCE_TABLE, mem::RESOURCE_TABLE_ELEMENT_COUNT); + table.clear(); table }; } diff --git a/client/logic/src/game_context.rs b/client/logic/src/game_context.rs index 8b011964..154b3f26 100644 --- a/client/logic/src/game_context.rs +++ b/client/logic/src/game_context.rs @@ -21,7 +21,7 @@ impl GameContext { state: State::default(), tick_nr: 0, resource_table: unsafe { - ResourceTable::new(RESOURCE_TABLE, RESOURCE_TABLE_ELEMENT_COUNT) + ResourceTable::from_memory(RESOURCE_TABLE, RESOURCE_TABLE_ELEMENT_COUNT) }, }) } diff --git a/client/shared/src/double_buffer.rs b/client/shared/src/double_buffer.rs index f3425b15..bf767c19 100644 --- a/client/shared/src/double_buffer.rs +++ b/client/shared/src/double_buffer.rs @@ -72,26 +72,18 @@ impl DoubleBuffer { } } - #[allow(unused_attributes)] - #[inline(always)] pub extern "C" fn set_reading_at(&mut self, reading_at: Flag) { unsafe { mem::atomic_write_u8(&mut self.reading_at, reading_at) } } - #[allow(unused_attributes)] - #[inline(always)] pub extern "C" fn get_reading_at(&self) -> Flag { unsafe { mem::atomic_read_u8(&self.reading_at) } } - #[allow(unused_attributes)] - #[inline(always)] pub extern "C" fn set_provided(&mut self, provided: Flag) { unsafe { mem::atomic_write_u8(&mut self.provided, provided) } } - #[allow(unused_attributes)] - #[inline(always)] pub extern "C" fn get_provided(&self) -> Flag { unsafe { mem::atomic_read_u8(&self.provided) } } diff --git a/client/shared/src/mem.rs b/client/shared/src/mem.rs index a9878912..2f7891ae 100644 --- a/client/shared/src/mem.rs +++ b/client/shared/src/mem.rs @@ -50,8 +50,7 @@ pub const MESSAGE_QUEUE: usize = 0; #[from_env] pub const MESSAGE_QUEUE_SIZE: usize = 0; pub const MESSAGE_QUEUE_ELEMENT_COUNT: usize = (MESSAGE_QUEUE_SIZE as i64 - - size_of::>>() as i64) - as usize + - size_of::>() as i64) as usize / size_of::>(); #[from_env] @@ -89,7 +88,6 @@ impl SynchronizationMemory { } #[repr(align(4))] -#[derive(Clone)] struct MessageQueueElement { reading: u8, writing: u8, @@ -127,7 +125,7 @@ pub struct MessageQueue { impl MessageQueue { pub fn length() -> usize { - MESSAGE_QUEUE + MESSAGE_QUEUE_ELEMENT_COUNT } fn mem_size() -> usize { diff --git a/rask-engine/src/resources/library.rs b/rask-engine/src/resources/library.rs index 5b1c9054..1a64615b 100644 --- a/rask-engine/src/resources/library.rs +++ b/rask-engine/src/resources/library.rs @@ -43,14 +43,14 @@ impl ResourceTable { /// # Safety /// /// The function is safe as long as the memory from memory_offset to memory_offset + CATALOG_SIZE * sizeof(Resource) - pub unsafe fn new(memory_offset: usize, catalog_size: usize) -> Self { + pub unsafe fn from_memory(memory_offset: usize, catalog_size: usize) -> Self { ResourceTable(core::slice::from_raw_parts_mut( memory_offset as *mut Resource, catalog_size, )) } - pub unsafe fn init(&mut self) { + pub fn clear(&mut self) { for i in 0..self.0.len() { self.0[i] = Resource::None; } diff --git a/rask-engine/src/resources/mod.rs b/rask-engine/src/resources/mod.rs index 72ec8a1a..a6454f7f 100644 --- a/rask-engine/src/resources/mod.rs +++ b/rask-engine/src/resources/mod.rs @@ -8,7 +8,7 @@ use lazy_static::lazy_static; # use rask_engine::resources::*; lazy_static! { - static ref TABLE: ResourceTable = unsafe { ResourceTable::new(0, 0) }; + static ref TABLE: ResourceTable = unsafe { ResourceTable::from_memory(0, 0) }; } fn test() {