forked from StrafesNET/strafe-project
Compare commits
62 Commits
Author | SHA1 | Date | |
---|---|---|---|
53d2b5b3f5 | |||
c565120ea7 | |||
4f5c9afed3 | |||
53605746d4 | |||
cead05b08b | |||
949897a558 | |||
a4ed50fc38 | |||
846f681648 | |||
ff54a03487 | |||
8c2dda5205 | |||
addde65caa | |||
2c4e6f642b | |||
f11742ef3b | |||
e6862b5bad | |||
e18e8a9a7d | |||
f600092f13 | |||
1f1ef5d3ad | |||
54bf0358d6 | |||
6caa273623 | |||
101f0f8d12 | |||
fc751a9fe8 | |||
5391b635fb | |||
230469496e | |||
ea3134de51 | |||
05156d1741 | |||
d72e3fcabd | |||
99d4e51ee8 | |||
7effceff03 | |||
355956e532 | |||
8aad878d49 | |||
5fb9f8b1bc | |||
a9977c0bd2 | |||
fd34fbe367 | |||
75695946a0 | |||
2dba9554ea | |||
b5880d484a | |||
0b230b7597 | |||
988f204358 | |||
abd002e3bf | |||
1776dc4c39 | |||
946687639a | |||
69c7896011 | |||
1a1509f315 | |||
87f674238d | |||
cce9800045 | |||
8792b8e782 | |||
c9cb22be68 | |||
d4172f5040 | |||
df43dc6f6e | |||
c3290e2ce6 | |||
e347d4fd51 | |||
ad46418e79 | |||
82da9bf40f | |||
bda898a1f1 | |||
ce5f6fceb9 | |||
7179f20e67 | |||
e25a2d7a7a | |||
7c247b6949 | |||
49fde16c4f | |||
403910d2d8 | |||
7a23ef2734 | |||
1e25f71618 |
28
Cargo.lock
generated
28
Cargo.lock
generated
@ -302,26 +302,6 @@ dependencies = [
|
|||||||
"crossbeam-utils",
|
"crossbeam-utils",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "console_error_panic_hook"
|
|
||||||
version = "0.1.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "console_log"
|
|
||||||
version = "1.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "be8aed40e4edbf4d3b4431ab260b63fdc40f5780a4766824329ea0f1eefe3c0f"
|
|
||||||
dependencies = [
|
|
||||||
"log",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "core-foundation"
|
name = "core-foundation"
|
||||||
version = "0.9.3"
|
version = "0.9.3"
|
||||||
@ -1425,22 +1405,16 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "strafe-client"
|
name = "strafe-client"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-executor",
|
"async-executor",
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"console_error_panic_hook",
|
|
||||||
"console_log",
|
|
||||||
"ddsfile",
|
"ddsfile",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"glam",
|
"glam",
|
||||||
"js-sys",
|
|
||||||
"log",
|
"log",
|
||||||
"obj",
|
"obj",
|
||||||
"pollster",
|
"pollster",
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-futures",
|
|
||||||
"web-sys",
|
|
||||||
"wgpu",
|
"wgpu",
|
||||||
"winit",
|
"winit",
|
||||||
]
|
]
|
||||||
|
15
Cargo.toml
15
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "strafe-client"
|
name = "strafe-client"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
@ -17,12 +17,7 @@ pollster = "0.3.0"
|
|||||||
wgpu = "0.17.0"
|
wgpu = "0.17.0"
|
||||||
winit = "0.28.6"
|
winit = "0.28.6"
|
||||||
|
|
||||||
# https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies
|
[profile.release]
|
||||||
|
lto = true
|
||||||
[target.wasm32-unknown-unknown.dependencies]
|
strip = true
|
||||||
console_error_panic_hook = "0.1.7"
|
codegen-units = 1
|
||||||
console_log = "1.0.0"
|
|
||||||
js-sys = "0.3.64"
|
|
||||||
wasm-bindgen = "0.2.87"
|
|
||||||
wasm-bindgen-futures = "0.4.37"
|
|
||||||
web-sys = { version = "0.3.64", features = ["Location", "Window"] }
|
|
||||||
|
@ -1,8 +0,0 @@
|
|||||||
<html>
|
|
||||||
<body>
|
|
||||||
<script type="module">
|
|
||||||
import init from "./strafe-client.js";
|
|
||||||
init();
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
2580
models/suzanne.obj
Normal file
2580
models/suzanne.obj
Normal file
File diff suppressed because it is too large
Load Diff
2866
models/teapot.obj
Normal file
2866
models/teapot.obj
Normal file
File diff suppressed because it is too large
Load Diff
321
src/body.rs
Normal file
321
src/body.rs
Normal file
@ -0,0 +1,321 @@
|
|||||||
|
use crate::instruction::TimedInstruction;
|
||||||
|
|
||||||
|
pub enum PhysicsInstruction {
|
||||||
|
CollisionStart(RelativeCollision),
|
||||||
|
CollisionEnd(RelativeCollision),
|
||||||
|
StrafeTick,
|
||||||
|
Jump,
|
||||||
|
SetWalkTargetVelocity(glam::Vec3),
|
||||||
|
ReachWalkTargetVelocity,
|
||||||
|
// Water,
|
||||||
|
// Spawn(
|
||||||
|
// Option<SpawnId>,
|
||||||
|
// bool,//true = Trigger; false = teleport
|
||||||
|
// bool,//true = Force
|
||||||
|
// )
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Body {
|
||||||
|
pub position: glam::Vec3,//I64 where 2^32 = 1 u
|
||||||
|
pub velocity: glam::Vec3,//I64 where 2^32 = 1 u/s
|
||||||
|
pub time: TIME,//nanoseconds x xxxxD!
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum MoveRestriction {
|
||||||
|
Air,
|
||||||
|
Water,
|
||||||
|
Ground,
|
||||||
|
Ladder,//multiple ladders how
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PhysicsState {
|
||||||
|
pub body: Body,
|
||||||
|
pub contacts: Vec<RelativeCollision>,
|
||||||
|
pub models_cringe_clone: Vec<Model>,
|
||||||
|
pub time: TIME,
|
||||||
|
pub strafe_tick_num: TIME,
|
||||||
|
pub strafe_tick_den: TIME,
|
||||||
|
pub tick: u32,
|
||||||
|
pub mv: f32,
|
||||||
|
pub walkspeed: f32,
|
||||||
|
pub friction: f32,
|
||||||
|
pub gravity: glam::Vec3,
|
||||||
|
pub grounded: bool,
|
||||||
|
pub jump_trying: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone,Copy)]
|
||||||
|
pub enum AabbFace{
|
||||||
|
Right,//+X
|
||||||
|
Top,
|
||||||
|
Back,
|
||||||
|
Left,
|
||||||
|
Bottom,
|
||||||
|
Front,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Aabb {
|
||||||
|
min: glam::Vec3,
|
||||||
|
max: glam::Vec3,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Aabb {
|
||||||
|
// const FACE_DATA: [[f32; 3]; 6] = [
|
||||||
|
// [0.0f32, 0., 1.],
|
||||||
|
// [0.0f32, 0., -1.],
|
||||||
|
// [1.0f32, 0., 0.],
|
||||||
|
// [-1.0f32, 0., 0.],
|
||||||
|
// [0.0f32, 1., 0.],
|
||||||
|
// [0.0f32, -1., 0.],
|
||||||
|
// ];
|
||||||
|
const VERTEX_DATA_RIGHT: [glam::Vec3; 4] = [
|
||||||
|
glam::vec3(1., -1., -1.),
|
||||||
|
glam::vec3(1., 1., -1.),
|
||||||
|
glam::vec3(1., 1., 1.),
|
||||||
|
glam::vec3(1., -1., 1.),
|
||||||
|
];
|
||||||
|
const VERTEX_DATA_TOP: [glam::Vec3; 4] = [
|
||||||
|
glam::vec3(1., 1., -1.),
|
||||||
|
glam::vec3(-1., 1., -1.),
|
||||||
|
glam::vec3(-1., 1., 1.),
|
||||||
|
glam::vec3(1., 1., 1.),
|
||||||
|
];
|
||||||
|
const VERTEX_DATA_BACK: [glam::Vec3; 4] = [
|
||||||
|
glam::vec3(-1., -1., 1.),
|
||||||
|
glam::vec3(1., -1., 1.),
|
||||||
|
glam::vec3(1., 1., 1.),
|
||||||
|
glam::vec3(-1., 1., 1.),
|
||||||
|
];
|
||||||
|
const VERTEX_DATA_LEFT: [glam::Vec3; 4] = [
|
||||||
|
glam::vec3(-1., -1., 1.),
|
||||||
|
glam::vec3(-1., 1., 1.),
|
||||||
|
glam::vec3(-1., 1., -1.),
|
||||||
|
glam::vec3(-1., -1., -1.),
|
||||||
|
];
|
||||||
|
const VERTEX_DATA_BOTTOM: [glam::Vec3; 4] = [
|
||||||
|
glam::vec3(1., -1., 1.),
|
||||||
|
glam::vec3(-1., -1., 1.),
|
||||||
|
glam::vec3(-1., -1., -1.),
|
||||||
|
glam::vec3(1., -1., -1.),
|
||||||
|
];
|
||||||
|
const VERTEX_DATA_FRONT: [glam::Vec3; 4] = [
|
||||||
|
glam::vec3(-1., 1., -1.),
|
||||||
|
glam::vec3(1., 1., -1.),
|
||||||
|
glam::vec3(1., -1., -1.),
|
||||||
|
glam::vec3(-1., -1., -1.),
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {min: glam::Vec3::INFINITY,max: glam::Vec3::NEG_INFINITY}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn grow(&mut self, point:glam::Vec3){
|
||||||
|
self.min=self.min.min(point);
|
||||||
|
self.max=self.max.max(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn normal(face:AabbFace) -> glam::Vec3 {
|
||||||
|
match face {
|
||||||
|
AabbFace::Right => glam::vec3(1.,0.,0.),
|
||||||
|
AabbFace::Top => glam::vec3(0.,1.,0.),
|
||||||
|
AabbFace::Back => glam::vec3(0.,0.,1.),
|
||||||
|
AabbFace::Left => glam::vec3(-1.,0.,0.),
|
||||||
|
AabbFace::Bottom => glam::vec3(0.,-1.,0.),
|
||||||
|
AabbFace::Front => glam::vec3(0.,0.,-1.),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn face_vertices(face:AabbFace) -> [glam::Vec3;4] {
|
||||||
|
match face {
|
||||||
|
AabbFace::Right => Self::VERTEX_DATA_RIGHT,
|
||||||
|
AabbFace::Top => Self::VERTEX_DATA_TOP,
|
||||||
|
AabbFace::Back => Self::VERTEX_DATA_BACK,
|
||||||
|
AabbFace::Left => Self::VERTEX_DATA_LEFT,
|
||||||
|
AabbFace::Bottom => Self::VERTEX_DATA_BOTTOM,
|
||||||
|
AabbFace::Front => Self::VERTEX_DATA_FRONT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Face = AabbFace;
|
||||||
|
type TreyMesh = Aabb;
|
||||||
|
|
||||||
|
pub struct Model {
|
||||||
|
//A model is a thing that has a hitbox. can be represented by a list of TreyMesh-es
|
||||||
|
//in this iteration, all it needs is extents.
|
||||||
|
transform: glam::Mat4,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Model {
|
||||||
|
pub fn new(transform:glam::Mat4) -> Self {
|
||||||
|
Self{transform}
|
||||||
|
}
|
||||||
|
pub fn face_vertices(&self,face:Face) -> [glam::Vec3;4] {
|
||||||
|
Aabb::face_vertices(face)
|
||||||
|
}
|
||||||
|
pub fn face_mesh(&self,face:Face) -> TreyMesh {
|
||||||
|
let mut aabb=Aabb::new();
|
||||||
|
for &vertex in self.face_vertices(face).iter() {
|
||||||
|
aabb.grow(vertex);
|
||||||
|
}
|
||||||
|
return aabb;
|
||||||
|
}
|
||||||
|
pub fn face_normal(&self,face:Face) -> glam::Vec3 {
|
||||||
|
let mut n=glam::Vec3Swizzles::xyzz(Aabb::normal(face));
|
||||||
|
n.w=0.0;//what a man will do to avoid writing out the components
|
||||||
|
glam::Vec4Swizzles::xyz(self.transform*n)//this is wrong for scale
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RelativeCollision {
|
||||||
|
face: Face,//just an id
|
||||||
|
model: u32,//using id to avoid lifetimes
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RelativeCollision {
|
||||||
|
pub fn mesh(&self,models:&Vec<Model>) -> TreyMesh {
|
||||||
|
return models.get(self.model as usize).unwrap().face_mesh(self.face)
|
||||||
|
}
|
||||||
|
pub fn normal(&self,models:&Vec<Model>) -> glam::Vec3 {
|
||||||
|
return models.get(self.model as usize).unwrap().face_normal(self.face)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type TIME = i64;
|
||||||
|
|
||||||
|
const CONTROL_JUMP:u32 = 0b01000000;//temp DATA NORMALIZATION!@#$
|
||||||
|
impl PhysicsState {
|
||||||
|
//delete this, we are tickless gamers
|
||||||
|
pub fn run(&mut self, time: TIME){
|
||||||
|
//prepare is ommitted - everything is done via instructions.
|
||||||
|
while let Some(instruction) = self.next_instruction() {//collect
|
||||||
|
if time<instruction.time {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
//advance
|
||||||
|
self.advance_time(instruction.time);
|
||||||
|
//process
|
||||||
|
self.process_instruction(instruction);
|
||||||
|
//write hash lol
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//delete this
|
||||||
|
pub fn extrapolate_position(&self, time: TIME) -> glam::Vec3 {
|
||||||
|
let dt=(time-self.body.time) as f64/1_000_000_000f64;
|
||||||
|
self.body.position+self.body.velocity*(dt as f32)+self.gravity*((0.5*dt*dt) as f32)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
return Some(TimedInstruction{
|
||||||
|
time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
|
||||||
|
//only poll the physics if there is a before and after mouse event
|
||||||
|
instruction:PhysicsInstruction::StrafeTick
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
//state mutated on collision:
|
||||||
|
//Accelerator
|
||||||
|
//stair step-up
|
||||||
|
|
||||||
|
//state mutated on instruction
|
||||||
|
//change fly acceleration (fly_sustain)
|
||||||
|
//change fly velocity
|
||||||
|
|
||||||
|
//generic event emmiters
|
||||||
|
//PlatformStandTime
|
||||||
|
//walk/swim/air/ladder sounds
|
||||||
|
//VState?
|
||||||
|
|
||||||
|
//falling under the map
|
||||||
|
// fn next_respawn_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
// if self.body.position<self.world.min_y {
|
||||||
|
// return Some(TimedInstruction{
|
||||||
|
// time:self.time,
|
||||||
|
// instruction:PhysicsInstruction::Trigger(None)
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// fn next_water_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
// return Some(TimedInstruction{
|
||||||
|
// time:(self.time*self.strafe_tick_num/self.strafe_tick_den+1)*self.strafe_tick_den/self.strafe_tick_num,
|
||||||
|
// //only poll the physics if there is a before and after mouse event
|
||||||
|
// instruction:PhysicsInstruction::Water
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
|
||||||
|
fn next_walk_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
//check if you are accelerating towards a walk target velocity and create an instruction
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
fn predict_collision_end(&self,model:&Model) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
//must treat cancollide false objects differently: you may not exit through the same face you entered.
|
||||||
|
None
|
||||||
|
}
|
||||||
|
fn predict_collision_start(&self,model:&Model) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl crate::instruction::InstructionEmitter<PhysicsInstruction> for PhysicsState {
|
||||||
|
//this little next instruction function can cache its return value and invalidate the cached value by watching the State.
|
||||||
|
fn next_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||||
|
//JUST POLLING!!! NO MUTATION
|
||||||
|
let mut collector = crate::instruction::InstructionCollector::new();
|
||||||
|
//autohop (already pressing spacebar; the signal to begin trying to jump is different)
|
||||||
|
if self.grounded&&self.jump_trying {
|
||||||
|
//scroll will be implemented with InputInstruction::Jump(true) but it blocks setting self.jump_trying=true
|
||||||
|
collector.collect(Some(TimedInstruction{
|
||||||
|
time:self.time,
|
||||||
|
instruction:PhysicsInstruction::Jump
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
//check for collision stop instructions with curent contacts
|
||||||
|
for collision_data in self.contacts.iter() {
|
||||||
|
collector.collect(self.predict_collision_end(self.models_cringe_clone.get(collision_data.model as usize).unwrap()));
|
||||||
|
}
|
||||||
|
//check for collision start instructions (against every part in the game with no optimization!!)
|
||||||
|
for model in &self.models_cringe_clone {
|
||||||
|
collector.collect(self.predict_collision_start(model));
|
||||||
|
}
|
||||||
|
if self.grounded {
|
||||||
|
//walk maintenance
|
||||||
|
collector.collect(self.next_walk_instruction());
|
||||||
|
}else{
|
||||||
|
//check to see when the next strafe tick is
|
||||||
|
collector.collect(self.next_strafe_instruction());
|
||||||
|
}
|
||||||
|
collector.instruction()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsState {
|
||||||
|
fn process_instruction(&mut self, ins:TimedInstruction<PhysicsInstruction>) {
|
||||||
|
//mutate position and velocity and time
|
||||||
|
self.body.advance_time(ins.time);//should this be in a separate function: self.advance_time?
|
||||||
|
match ins.instruction {
|
||||||
|
PhysicsInstruction::CollisionStart(_) => todo!(),
|
||||||
|
PhysicsInstruction::CollisionEnd(_) => todo!(),
|
||||||
|
PhysicsInstruction::StrafeTick => {
|
||||||
|
let control_dir=self.get_control_dir();//this respects your mouse interpolation settings
|
||||||
|
let d=self.body.velocity.dot(control_dir);
|
||||||
|
if d<self.mv {
|
||||||
|
self.body.velocity+=(self.mv-d)*control_dir;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PhysicsInstruction::Jump => {
|
||||||
|
self.grounded=false;//do I need this?
|
||||||
|
self.body.velocity+=glam::Vec3::new(0.0,0.715588/2.0*100.0,0.0);
|
||||||
|
}
|
||||||
|
PhysicsInstruction::ReachWalkTargetVelocity => {
|
||||||
|
//precisely set velocity
|
||||||
|
self.body.velocity=self.walk_target_velocity;
|
||||||
|
}
|
||||||
|
PhysicsInstruction::SetWalkTargetVelocity(v) => {
|
||||||
|
self.walk_target_velocity=v;
|
||||||
|
//calculate acceleration yada yada
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
820
src/framework.rs
820
src/framework.rs
@ -6,438 +6,438 @@ use std::time::Instant;
|
|||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
|
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
|
||||||
use winit::{
|
use winit::{
|
||||||
event::{self, WindowEvent},
|
event::{self, WindowEvent},
|
||||||
event_loop::{ControlFlow, EventLoop},
|
event_loop::{ControlFlow, EventLoop},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
|
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
|
||||||
use std::{mem::size_of, slice::from_raw_parts};
|
use std::{mem::size_of, slice::from_raw_parts};
|
||||||
|
|
||||||
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
|
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub enum ShaderStage {
|
pub enum ShaderStage {
|
||||||
Vertex,
|
Vertex,
|
||||||
Fragment,
|
Fragment,
|
||||||
Compute,
|
Compute,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait Example: 'static + Sized {
|
pub trait Example: 'static + Sized {
|
||||||
fn optional_features() -> wgpu::Features {
|
fn optional_features() -> wgpu::Features {
|
||||||
wgpu::Features::empty()
|
wgpu::Features::empty()
|
||||||
}
|
}
|
||||||
fn required_features() -> wgpu::Features {
|
fn required_features() -> wgpu::Features {
|
||||||
wgpu::Features::empty()
|
wgpu::Features::empty()
|
||||||
}
|
}
|
||||||
fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities {
|
fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities {
|
||||||
wgpu::DownlevelCapabilities {
|
wgpu::DownlevelCapabilities {
|
||||||
flags: wgpu::DownlevelFlags::empty(),
|
flags: wgpu::DownlevelFlags::empty(),
|
||||||
shader_model: wgpu::ShaderModel::Sm5,
|
shader_model: wgpu::ShaderModel::Sm5,
|
||||||
..wgpu::DownlevelCapabilities::default()
|
..wgpu::DownlevelCapabilities::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn required_limits() -> wgpu::Limits {
|
fn required_limits() -> wgpu::Limits {
|
||||||
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
|
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
|
||||||
}
|
}
|
||||||
fn init(
|
fn init(
|
||||||
config: &wgpu::SurfaceConfiguration,
|
config: &wgpu::SurfaceConfiguration,
|
||||||
adapter: &wgpu::Adapter,
|
adapter: &wgpu::Adapter,
|
||||||
device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
) -> Self;
|
) -> Self;
|
||||||
fn resize(
|
fn resize(
|
||||||
&mut self,
|
&mut self,
|
||||||
config: &wgpu::SurfaceConfiguration,
|
config: &wgpu::SurfaceConfiguration,
|
||||||
device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
);
|
);
|
||||||
fn update(&mut self, event: WindowEvent);
|
fn update(&mut self, event: WindowEvent);
|
||||||
fn move_mouse(&mut self, delta: (f64,f64));
|
fn move_mouse(&mut self, delta: (f64,f64));
|
||||||
fn render(
|
fn render(
|
||||||
&mut self,
|
&mut self,
|
||||||
view: &wgpu::TextureView,
|
view: &wgpu::TextureView,
|
||||||
device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
spawner: &Spawner,
|
spawner: &Spawner,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Setup {
|
struct Setup {
|
||||||
window: winit::window::Window,
|
window: winit::window::Window,
|
||||||
event_loop: EventLoop<()>,
|
event_loop: EventLoop<()>,
|
||||||
instance: wgpu::Instance,
|
instance: wgpu::Instance,
|
||||||
size: winit::dpi::PhysicalSize<u32>,
|
size: winit::dpi::PhysicalSize<u32>,
|
||||||
surface: wgpu::Surface,
|
surface: wgpu::Surface,
|
||||||
adapter: wgpu::Adapter,
|
adapter: wgpu::Adapter,
|
||||||
device: wgpu::Device,
|
device: wgpu::Device,
|
||||||
queue: wgpu::Queue,
|
queue: wgpu::Queue,
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
|
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
struct OffscreenCanvasSetup {
|
struct OffscreenCanvasSetup {
|
||||||
offscreen_canvas: OffscreenCanvas,
|
offscreen_canvas: OffscreenCanvas,
|
||||||
bitmap_renderer: ImageBitmapRenderingContext,
|
bitmap_renderer: ImageBitmapRenderingContext,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn setup<E: Example>(title: &str) -> Setup {
|
async fn setup<E: Example>(title: &str) -> Setup {
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
{
|
{
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
};
|
};
|
||||||
|
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new();
|
||||||
let mut builder = winit::window::WindowBuilder::new();
|
let mut builder = winit::window::WindowBuilder::new();
|
||||||
builder = builder.with_title(title);
|
builder = builder.with_title(title);
|
||||||
#[cfg(windows_OFF)] // TODO
|
#[cfg(windows_OFF)] // TODO
|
||||||
{
|
{
|
||||||
use winit::platform::windows::WindowBuilderExtWindows;
|
use winit::platform::windows::WindowBuilderExtWindows;
|
||||||
builder = builder.with_no_redirection_bitmap(true);
|
builder = builder.with_no_redirection_bitmap(true);
|
||||||
}
|
}
|
||||||
let window = builder.build(&event_loop).unwrap();
|
let window = builder.build(&event_loop).unwrap();
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
{
|
{
|
||||||
use winit::platform::web::WindowExtWebSys;
|
use winit::platform::web::WindowExtWebSys;
|
||||||
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
||||||
let level: log::Level = parse_url_query_string(&query_string, "RUST_LOG")
|
let level: log::Level = parse_url_query_string(&query_string, "RUST_LOG")
|
||||||
.and_then(|x| x.parse().ok())
|
.and_then(|x| x.parse().ok())
|
||||||
.unwrap_or(log::Level::Error);
|
.unwrap_or(log::Level::Error);
|
||||||
console_log::init_with_level(level).expect("could not initialize logger");
|
console_log::init_with_level(level).expect("could not initialize logger");
|
||||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||||
// On wasm, append the canvas to the document body
|
// On wasm, append the canvas to the document body
|
||||||
web_sys::window()
|
web_sys::window()
|
||||||
.and_then(|win| win.document())
|
.and_then(|win| win.document())
|
||||||
.and_then(|doc| doc.body())
|
.and_then(|doc| doc.body())
|
||||||
.and_then(|body| {
|
.and_then(|body| {
|
||||||
body.append_child(&web_sys::Element::from(window.canvas()))
|
body.append_child(&web_sys::Element::from(window.canvas()))
|
||||||
.ok()
|
.ok()
|
||||||
})
|
})
|
||||||
.expect("couldn't append canvas to document body");
|
.expect("couldn't append canvas to document body");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
let mut offscreen_canvas_setup: Option<OffscreenCanvasSetup> = None;
|
let mut offscreen_canvas_setup: Option<OffscreenCanvasSetup> = None;
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
{
|
{
|
||||||
use wasm_bindgen::JsCast;
|
use wasm_bindgen::JsCast;
|
||||||
use winit::platform::web::WindowExtWebSys;
|
use winit::platform::web::WindowExtWebSys;
|
||||||
|
|
||||||
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
||||||
if let Some(offscreen_canvas_param) =
|
if let Some(offscreen_canvas_param) =
|
||||||
parse_url_query_string(&query_string, "offscreen_canvas")
|
parse_url_query_string(&query_string, "offscreen_canvas")
|
||||||
{
|
{
|
||||||
if FromStr::from_str(offscreen_canvas_param) == Ok(true) {
|
if FromStr::from_str(offscreen_canvas_param) == Ok(true) {
|
||||||
log::info!("Creating OffscreenCanvasSetup");
|
log::info!("Creating OffscreenCanvasSetup");
|
||||||
|
|
||||||
let offscreen_canvas =
|
let offscreen_canvas =
|
||||||
OffscreenCanvas::new(1024, 768).expect("couldn't create OffscreenCanvas");
|
OffscreenCanvas::new(1024, 768).expect("couldn't create OffscreenCanvas");
|
||||||
|
|
||||||
let bitmap_renderer = window
|
let bitmap_renderer = window
|
||||||
.canvas()
|
.canvas()
|
||||||
.get_context("bitmaprenderer")
|
.get_context("bitmaprenderer")
|
||||||
.expect("couldn't create ImageBitmapRenderingContext (Result)")
|
.expect("couldn't create ImageBitmapRenderingContext (Result)")
|
||||||
.expect("couldn't create ImageBitmapRenderingContext (Option)")
|
.expect("couldn't create ImageBitmapRenderingContext (Option)")
|
||||||
.dyn_into::<ImageBitmapRenderingContext>()
|
.dyn_into::<ImageBitmapRenderingContext>()
|
||||||
.expect("couldn't convert into ImageBitmapRenderingContext");
|
.expect("couldn't convert into ImageBitmapRenderingContext");
|
||||||
|
|
||||||
offscreen_canvas_setup = Some(OffscreenCanvasSetup {
|
offscreen_canvas_setup = Some(OffscreenCanvasSetup {
|
||||||
offscreen_canvas,
|
offscreen_canvas,
|
||||||
bitmap_renderer,
|
bitmap_renderer,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
log::info!("Initializing the surface...");
|
log::info!("Initializing the surface...");
|
||||||
|
|
||||||
let backends = wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
let backends = wgpu::util::backend_bits_from_env().unwrap_or_else(wgpu::Backends::all);
|
||||||
let dx12_shader_compiler = wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
let dx12_shader_compiler = wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default();
|
||||||
|
|
||||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||||
backends,
|
backends,
|
||||||
dx12_shader_compiler,
|
dx12_shader_compiler,
|
||||||
});
|
});
|
||||||
let (size, surface) = unsafe {
|
let (size, surface) = unsafe {
|
||||||
let size = window.inner_size();
|
let size = window.inner_size();
|
||||||
|
|
||||||
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
|
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
|
||||||
let surface = instance.create_surface(&window).unwrap();
|
let surface = instance.create_surface(&window).unwrap();
|
||||||
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
|
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
|
||||||
let surface = {
|
let surface = {
|
||||||
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
||||||
log::info!("Creating surface from OffscreenCanvas");
|
log::info!("Creating surface from OffscreenCanvas");
|
||||||
instance.create_surface_from_offscreen_canvas(
|
instance.create_surface_from_offscreen_canvas(
|
||||||
offscreen_canvas_setup.offscreen_canvas.clone(),
|
offscreen_canvas_setup.offscreen_canvas.clone(),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
instance.create_surface(&window)
|
instance.create_surface(&window)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
(size, surface)
|
(size, surface)
|
||||||
};
|
};
|
||||||
let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface))
|
let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface))
|
||||||
.await
|
.await
|
||||||
.expect("No suitable GPU adapters found on the system!");
|
.expect("No suitable GPU adapters found on the system!");
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
{
|
{
|
||||||
let adapter_info = adapter.get_info();
|
let adapter_info = adapter.get_info();
|
||||||
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
||||||
}
|
}
|
||||||
|
|
||||||
let optional_features = E::optional_features();
|
let optional_features = E::optional_features();
|
||||||
let required_features = E::required_features();
|
let required_features = E::required_features();
|
||||||
let adapter_features = adapter.features();
|
let adapter_features = adapter.features();
|
||||||
assert!(
|
assert!(
|
||||||
adapter_features.contains(required_features),
|
adapter_features.contains(required_features),
|
||||||
"Adapter does not support required features for this example: {:?}",
|
"Adapter does not support required features for this example: {:?}",
|
||||||
required_features - adapter_features
|
required_features - adapter_features
|
||||||
);
|
);
|
||||||
|
|
||||||
let required_downlevel_capabilities = E::required_downlevel_capabilities();
|
let required_downlevel_capabilities = E::required_downlevel_capabilities();
|
||||||
let downlevel_capabilities = adapter.get_downlevel_capabilities();
|
let downlevel_capabilities = adapter.get_downlevel_capabilities();
|
||||||
assert!(
|
assert!(
|
||||||
downlevel_capabilities.shader_model >= required_downlevel_capabilities.shader_model,
|
downlevel_capabilities.shader_model >= required_downlevel_capabilities.shader_model,
|
||||||
"Adapter does not support the minimum shader model required to run this example: {:?}",
|
"Adapter does not support the minimum shader model required to run this example: {:?}",
|
||||||
required_downlevel_capabilities.shader_model
|
required_downlevel_capabilities.shader_model
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
downlevel_capabilities
|
downlevel_capabilities
|
||||||
.flags
|
.flags
|
||||||
.contains(required_downlevel_capabilities.flags),
|
.contains(required_downlevel_capabilities.flags),
|
||||||
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
||||||
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
||||||
);
|
);
|
||||||
|
|
||||||
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
|
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
|
||||||
let needed_limits = E::required_limits().using_resolution(adapter.limits());
|
let needed_limits = E::required_limits().using_resolution(adapter.limits());
|
||||||
|
|
||||||
let trace_dir = std::env::var("WGPU_TRACE");
|
let trace_dir = std::env::var("WGPU_TRACE");
|
||||||
let (device, queue) = adapter
|
let (device, queue) = adapter
|
||||||
.request_device(
|
.request_device(
|
||||||
&wgpu::DeviceDescriptor {
|
&wgpu::DeviceDescriptor {
|
||||||
label: None,
|
label: None,
|
||||||
features: (optional_features & adapter_features) | required_features,
|
features: (optional_features & adapter_features) | required_features,
|
||||||
limits: needed_limits,
|
limits: needed_limits,
|
||||||
},
|
},
|
||||||
trace_dir.ok().as_ref().map(std::path::Path::new),
|
trace_dir.ok().as_ref().map(std::path::Path::new),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("Unable to find a suitable GPU adapter!");
|
.expect("Unable to find a suitable GPU adapter!");
|
||||||
|
|
||||||
Setup {
|
Setup {
|
||||||
window,
|
window,
|
||||||
event_loop,
|
event_loop,
|
||||||
instance,
|
instance,
|
||||||
size,
|
size,
|
||||||
surface,
|
surface,
|
||||||
adapter,
|
adapter,
|
||||||
device,
|
device,
|
||||||
queue,
|
queue,
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
offscreen_canvas_setup,
|
offscreen_canvas_setup,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start<E: Example>(
|
fn start<E: Example>(
|
||||||
#[cfg(not(target_arch = "wasm32"))] Setup {
|
#[cfg(not(target_arch = "wasm32"))] Setup {
|
||||||
window,
|
window,
|
||||||
event_loop,
|
event_loop,
|
||||||
instance,
|
instance,
|
||||||
size,
|
size,
|
||||||
surface,
|
surface,
|
||||||
adapter,
|
adapter,
|
||||||
device,
|
device,
|
||||||
queue,
|
queue,
|
||||||
}: Setup,
|
}: Setup,
|
||||||
#[cfg(target_arch = "wasm32")] Setup {
|
#[cfg(target_arch = "wasm32")] Setup {
|
||||||
window,
|
window,
|
||||||
event_loop,
|
event_loop,
|
||||||
instance,
|
instance,
|
||||||
size,
|
size,
|
||||||
surface,
|
surface,
|
||||||
adapter,
|
adapter,
|
||||||
device,
|
device,
|
||||||
queue,
|
queue,
|
||||||
offscreen_canvas_setup,
|
offscreen_canvas_setup,
|
||||||
}: Setup,
|
}: Setup,
|
||||||
) {
|
) {
|
||||||
let spawner = Spawner::new();
|
let spawner = Spawner::new();
|
||||||
let mut config = surface
|
let mut config = surface
|
||||||
.get_default_config(&adapter, size.width, size.height)
|
.get_default_config(&adapter, size.width, size.height)
|
||||||
.expect("Surface isn't supported by the adapter.");
|
.expect("Surface isn't supported by the adapter.");
|
||||||
let surface_view_format = config.format.add_srgb_suffix();
|
let surface_view_format = config.format.add_srgb_suffix();
|
||||||
config.view_formats.push(surface_view_format);
|
config.view_formats.push(surface_view_format);
|
||||||
surface.configure(&device, &config);
|
surface.configure(&device, &config);
|
||||||
|
|
||||||
log::info!("Initializing the example...");
|
log::info!("Initializing the example...");
|
||||||
let mut example = E::init(&config, &adapter, &device, &queue);
|
let mut example = E::init(&config, &adapter, &device, &queue);
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
let mut last_frame_inst = Instant::now();
|
let mut last_frame_inst = Instant::now();
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
let (mut frame_count, mut accum_time) = (0, 0.0);
|
let (mut frame_count, mut accum_time) = (0, 0.0);
|
||||||
|
|
||||||
log::info!("Entering render loop...");
|
log::info!("Entering render loop...");
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, _, control_flow| {
|
||||||
let _ = (&instance, &adapter); // force ownership by the closure
|
let _ = (&instance, &adapter); // force ownership by the closure
|
||||||
*control_flow = if cfg!(feature = "metal-auto-capture") {
|
*control_flow = if cfg!(feature = "metal-auto-capture") {
|
||||||
ControlFlow::Exit
|
ControlFlow::Exit
|
||||||
} else {
|
} else {
|
||||||
ControlFlow::Poll
|
ControlFlow::Poll
|
||||||
};
|
};
|
||||||
match event {
|
match event {
|
||||||
event::Event::RedrawEventsCleared => {
|
event::Event::RedrawEventsCleared => {
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
spawner.run_until_stalled();
|
spawner.run_until_stalled();
|
||||||
|
|
||||||
window.request_redraw();
|
window.request_redraw();
|
||||||
}
|
}
|
||||||
event::Event::WindowEvent {
|
event::Event::WindowEvent {
|
||||||
event:
|
event:
|
||||||
WindowEvent::Resized(size)
|
WindowEvent::Resized(size)
|
||||||
| WindowEvent::ScaleFactorChanged {
|
| WindowEvent::ScaleFactorChanged {
|
||||||
new_inner_size: &mut size,
|
new_inner_size: &mut size,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
// Once winit is fixed, the detection conditions here can be removed.
|
// Once winit is fixed, the detection conditions here can be removed.
|
||||||
// https://github.com/rust-windowing/winit/issues/2876
|
// https://github.com/rust-windowing/winit/issues/2876
|
||||||
let max_dimension = adapter.limits().max_texture_dimension_2d;
|
let max_dimension = adapter.limits().max_texture_dimension_2d;
|
||||||
if size.width > max_dimension || size.height > max_dimension {
|
if size.width > max_dimension || size.height > max_dimension {
|
||||||
log::warn!(
|
log::warn!(
|
||||||
"The resizing size {:?} exceeds the limit of {}.",
|
"The resizing size {:?} exceeds the limit of {}.",
|
||||||
size,
|
size,
|
||||||
max_dimension
|
max_dimension
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
log::info!("Resizing to {:?}", size);
|
log::info!("Resizing to {:?}", size);
|
||||||
config.width = size.width.max(1);
|
config.width = size.width.max(1);
|
||||||
config.height = size.height.max(1);
|
config.height = size.height.max(1);
|
||||||
example.resize(&config, &device, &queue);
|
example.resize(&config, &device, &queue);
|
||||||
surface.configure(&device, &config);
|
surface.configure(&device, &config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
event::Event::WindowEvent { event, .. } => match event {
|
event::Event::WindowEvent { event, .. } => match event {
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
input:
|
||||||
event::KeyboardInput {
|
event::KeyboardInput {
|
||||||
virtual_keycode: Some(event::VirtualKeyCode::Escape),
|
virtual_keycode: Some(event::VirtualKeyCode::Escape),
|
||||||
state: event::ElementState::Pressed,
|
state: event::ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
| WindowEvent::CloseRequested => {
|
| WindowEvent::CloseRequested => {
|
||||||
*control_flow = ControlFlow::Exit;
|
*control_flow = ControlFlow::Exit;
|
||||||
}
|
}
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
input:
|
input:
|
||||||
event::KeyboardInput {
|
event::KeyboardInput {
|
||||||
virtual_keycode: Some(event::VirtualKeyCode::R),
|
virtual_keycode: Some(event::VirtualKeyCode::R),
|
||||||
state: event::ElementState::Pressed,
|
state: event::ElementState::Pressed,
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
println!("{:#?}", instance.generate_report());
|
println!("{:#?}", instance.generate_report());
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
example.update(event);
|
example.update(event);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
event::Event::DeviceEvent {
|
event::Event::DeviceEvent {
|
||||||
event:
|
event:
|
||||||
winit::event::DeviceEvent::MouseMotion {
|
winit::event::DeviceEvent::MouseMotion {
|
||||||
delta,
|
delta,
|
||||||
},
|
},
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
example.move_mouse(delta);
|
example.move_mouse(delta);
|
||||||
},
|
},
|
||||||
event::Event::RedrawRequested(_) => {
|
event::Event::RedrawRequested(_) => {
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
{
|
{
|
||||||
accum_time += last_frame_inst.elapsed().as_secs_f32();
|
accum_time += last_frame_inst.elapsed().as_secs_f32();
|
||||||
last_frame_inst = Instant::now();
|
last_frame_inst = Instant::now();
|
||||||
frame_count += 1;
|
frame_count += 1;
|
||||||
if frame_count == 100 {
|
if frame_count == 100 {
|
||||||
println!(
|
println!(
|
||||||
"Avg frame time {}ms",
|
"Avg frame time {}ms",
|
||||||
accum_time * 1000.0 / frame_count as f32
|
accum_time * 1000.0 / frame_count as f32
|
||||||
);
|
);
|
||||||
accum_time = 0.0;
|
accum_time = 0.0;
|
||||||
frame_count = 0;
|
frame_count = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let frame = match surface.get_current_texture() {
|
let frame = match surface.get_current_texture() {
|
||||||
Ok(frame) => frame,
|
Ok(frame) => frame,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
surface.configure(&device, &config);
|
surface.configure(&device, &config);
|
||||||
surface
|
surface
|
||||||
.get_current_texture()
|
.get_current_texture()
|
||||||
.expect("Failed to acquire next surface texture!")
|
.expect("Failed to acquire next surface texture!")
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
|
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
|
||||||
format: Some(surface_view_format),
|
format: Some(surface_view_format),
|
||||||
..wgpu::TextureViewDescriptor::default()
|
..wgpu::TextureViewDescriptor::default()
|
||||||
});
|
});
|
||||||
|
|
||||||
example.render(&view, &device, &queue, &spawner);
|
example.render(&view, &device, &queue, &spawner);
|
||||||
|
|
||||||
frame.present();
|
frame.present();
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
{
|
{
|
||||||
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
||||||
let image_bitmap = offscreen_canvas_setup
|
let image_bitmap = offscreen_canvas_setup
|
||||||
.offscreen_canvas
|
.offscreen_canvas
|
||||||
.transfer_to_image_bitmap()
|
.transfer_to_image_bitmap()
|
||||||
.expect("couldn't transfer offscreen canvas to image bitmap.");
|
.expect("couldn't transfer offscreen canvas to image bitmap.");
|
||||||
offscreen_canvas_setup
|
offscreen_canvas_setup
|
||||||
.bitmap_renderer
|
.bitmap_renderer
|
||||||
.transfer_from_image_bitmap(&image_bitmap);
|
.transfer_from_image_bitmap(&image_bitmap);
|
||||||
|
|
||||||
log::info!("Transferring OffscreenCanvas to ImageBitmapRenderer");
|
log::info!("Transferring OffscreenCanvas to ImageBitmapRenderer");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
pub struct Spawner<'a> {
|
pub struct Spawner<'a> {
|
||||||
executor: async_executor::LocalExecutor<'a>,
|
executor: async_executor::LocalExecutor<'a>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
impl<'a> Spawner<'a> {
|
impl<'a> Spawner<'a> {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
executor: async_executor::LocalExecutor::new(),
|
executor: async_executor::LocalExecutor::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'a) {
|
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'a) {
|
||||||
self.executor.spawn(future).detach();
|
self.executor.spawn(future).detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_until_stalled(&self) {
|
fn run_until_stalled(&self) {
|
||||||
while self.executor.try_tick() {}
|
while self.executor.try_tick() {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
@ -445,69 +445,69 @@ pub struct Spawner {}
|
|||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
impl Spawner {
|
impl Spawner {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
Self {}
|
Self {}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'static) {
|
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'static) {
|
||||||
wasm_bindgen_futures::spawn_local(future);
|
wasm_bindgen_futures::spawn_local(future);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
pub fn run<E: Example>(title: &str) {
|
pub fn run<E: Example>(title: &str) {
|
||||||
let setup = pollster::block_on(setup::<E>(title));
|
let setup = pollster::block_on(setup::<E>(title));
|
||||||
start::<E>(setup);
|
start::<E>(setup);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
pub fn run<E: Example>(title: &str) {
|
pub fn run<E: Example>(title: &str) {
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
let title = title.to_owned();
|
let title = title.to_owned();
|
||||||
wasm_bindgen_futures::spawn_local(async move {
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
let setup = setup::<E>(&title).await;
|
let setup = setup::<E>(&title).await;
|
||||||
let start_closure = Closure::once_into_js(move || start::<E>(setup));
|
let start_closure = Closure::once_into_js(move || start::<E>(setup));
|
||||||
|
|
||||||
// make sure to handle JS exceptions thrown inside start.
|
// make sure to handle JS exceptions thrown inside start.
|
||||||
// Otherwise wasm_bindgen_futures Queue would break and never handle any tasks again.
|
// Otherwise wasm_bindgen_futures Queue would break and never handle any tasks again.
|
||||||
// This is required, because winit uses JS exception for control flow to escape from `run`.
|
// This is required, because winit uses JS exception for control flow to escape from `run`.
|
||||||
if let Err(error) = call_catch(&start_closure) {
|
if let Err(error) = call_catch(&start_closure) {
|
||||||
let is_control_flow_exception = error.dyn_ref::<js_sys::Error>().map_or(false, |e| {
|
let is_control_flow_exception = error.dyn_ref::<js_sys::Error>().map_or(false, |e| {
|
||||||
e.message().includes("Using exceptions for control flow", 0)
|
e.message().includes("Using exceptions for control flow", 0)
|
||||||
});
|
});
|
||||||
|
|
||||||
if !is_control_flow_exception {
|
if !is_control_flow_exception {
|
||||||
web_sys::console::error_1(&error);
|
web_sys::console::error_1(&error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
extern "C" {
|
extern "C" {
|
||||||
#[wasm_bindgen(catch, js_namespace = Function, js_name = "prototype.call.call")]
|
#[wasm_bindgen(catch, js_namespace = Function, js_name = "prototype.call.call")]
|
||||||
fn call_catch(this: &JsValue) -> Result<(), JsValue>;
|
fn call_catch(this: &JsValue) -> Result<(), JsValue>;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
/// Parse the query string as returned by `web_sys::window()?.location().search()?` and get a
|
/// Parse the query string as returned by `web_sys::window()?.location().search()?` and get a
|
||||||
/// specific key out of it.
|
/// specific key out of it.
|
||||||
pub fn parse_url_query_string<'a>(query: &'a str, search_key: &str) -> Option<&'a str> {
|
pub fn parse_url_query_string<'a>(query: &'a str, search_key: &str) -> Option<&'a str> {
|
||||||
let query_string = query.strip_prefix('?')?;
|
let query_string = query.strip_prefix('?')?;
|
||||||
|
|
||||||
for pair in query_string.split('&') {
|
for pair in query_string.split('&') {
|
||||||
let mut pair = pair.split('=');
|
let mut pair = pair.split('=');
|
||||||
let key = pair.next()?;
|
let key = pair.next()?;
|
||||||
let value = pair.next()?;
|
let value = pair.next()?;
|
||||||
|
|
||||||
if key == search_key {
|
if key == search_key {
|
||||||
return Some(value);
|
return Some(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
// This allows treating the framework as a standalone example,
|
// This allows treating the framework as a standalone example,
|
||||||
|
37
src/instruction.rs
Normal file
37
src/instruction.rs
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
pub struct TimedInstruction<I> {
|
||||||
|
pub time: crate::body::TIME,
|
||||||
|
pub instruction: I,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait InstructionEmitter<I> {
|
||||||
|
fn next_instruction(&self) -> Option<TimedInstruction<I>>;
|
||||||
|
}
|
||||||
|
pub trait InstructionConsumer<I> {
|
||||||
|
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
|
||||||
|
}
|
||||||
|
|
||||||
|
//PROPER PRIVATE FIELDS!!!
|
||||||
|
pub struct InstructionCollector<I> {
|
||||||
|
instruction: Option<TimedInstruction<I>>,
|
||||||
|
}
|
||||||
|
impl<I> InstructionCollector<I> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self{instruction:None}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn collect(&mut self,instruction:Option<TimedInstruction<I>>){
|
||||||
|
match &instruction {
|
||||||
|
Some(unwrap_instruction) => match &self.instruction {
|
||||||
|
Some(unwrap_best_instruction) => if unwrap_instruction.time<unwrap_best_instruction.time {
|
||||||
|
self.instruction=instruction;
|
||||||
|
},
|
||||||
|
None => self.instruction=instruction,
|
||||||
|
},
|
||||||
|
None => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn instruction(self) -> Option<TimedInstruction<I>> {
|
||||||
|
//STEAL INSTRUCTION AND DESTROY INSTRUCTIONCOLLECTOR
|
||||||
|
return self.instruction
|
||||||
|
}
|
||||||
|
}
|
@ -1 +1,4 @@
|
|||||||
pub mod framework;
|
pub mod framework;
|
||||||
|
pub mod body;
|
||||||
|
pub mod instruction;
|
||||||
|
pub mod timelines;
|
||||||
|
1179
src/main.rs
1179
src/main.rs
File diff suppressed because it is too large
Load Diff
139
src/shader.wgsl
139
src/shader.wgsl
@ -1,17 +1,17 @@
|
|||||||
struct SkyOutput {
|
struct SkyOutput {
|
||||||
@builtin(position) position: vec4<f32>,
|
@builtin(position) position: vec4<f32>,
|
||||||
@location(0) sampledir: vec3<f32>,
|
@location(0) sampledir: vec3<f32>,
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Data {
|
struct Data {
|
||||||
// from camera to screen
|
// from camera to screen
|
||||||
proj: mat4x4<f32>,
|
proj: mat4x4<f32>,
|
||||||
// from screen to camera
|
// from screen to camera
|
||||||
proj_inv: mat4x4<f32>,
|
proj_inv: mat4x4<f32>,
|
||||||
// from world to camera
|
// from world to camera
|
||||||
view: mat4x4<f32>,
|
view: mat4x4<f32>,
|
||||||
// camera position
|
// camera position
|
||||||
cam_pos: vec4<f32>,
|
cam_pos: vec4<f32>,
|
||||||
};
|
};
|
||||||
@group(0)
|
@group(0)
|
||||||
@binding(0)
|
@binding(0)
|
||||||
@ -19,64 +19,72 @@ var<uniform> r_data: Data;
|
|||||||
|
|
||||||
@vertex
|
@vertex
|
||||||
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||||
// hacky way to draw a large triangle
|
// hacky way to draw a large triangle
|
||||||
let tmp1 = i32(vertex_index) / 2;
|
let tmp1 = i32(vertex_index) / 2;
|
||||||
let tmp2 = i32(vertex_index) & 1;
|
let tmp2 = i32(vertex_index) & 1;
|
||||||
let pos = vec4<f32>(
|
let pos = vec4<f32>(
|
||||||
f32(tmp1) * 4.0 - 1.0,
|
f32(tmp1) * 4.0 - 1.0,
|
||||||
f32(tmp2) * 4.0 - 1.0,
|
f32(tmp2) * 4.0 - 1.0,
|
||||||
1.0,
|
1.0,
|
||||||
1.0
|
1.0
|
||||||
);
|
);
|
||||||
|
|
||||||
// transposition = inversion for this orthonormal matrix
|
// transposition = inversion for this orthonormal matrix
|
||||||
let inv_model_view = transpose(mat3x3<f32>(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz));
|
let inv_model_view = transpose(mat3x3<f32>(r_data.view[0].xyz, r_data.view[1].xyz, r_data.view[2].xyz));
|
||||||
let unprojected = r_data.proj_inv * pos;
|
let unprojected = r_data.proj_inv * pos;
|
||||||
|
|
||||||
var result: SkyOutput;
|
var result: SkyOutput;
|
||||||
result.sampledir = inv_model_view * unprojected.xyz;
|
result.sampledir = inv_model_view * unprojected.xyz;
|
||||||
result.position = pos;
|
result.position = pos;
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GroundOutput {
|
struct GroundOutput {
|
||||||
@builtin(position) position: vec4<f32>,
|
@builtin(position) position: vec4<f32>,
|
||||||
@location(4) pos: vec3<f32>,
|
@location(4) pos: vec3<f32>,
|
||||||
};
|
};
|
||||||
|
|
||||||
@vertex
|
@vertex
|
||||||
fn vs_ground(@builtin(vertex_index) vertex_index: u32) -> GroundOutput {
|
fn vs_ground(@builtin(vertex_index) vertex_index: u32) -> GroundOutput {
|
||||||
// hacky way to draw two triangles that make a square
|
// hacky way to draw two triangles that make a square
|
||||||
let tmp1 = (i32(vertex_index)-i32(vertex_index)/3*2) / 2;
|
let tmp1 = i32(vertex_index)/2-i32(vertex_index)/3;
|
||||||
let tmp2 = (i32(vertex_index)-i32(vertex_index)/3*2) & 1;
|
let tmp2 = i32(vertex_index)&1;
|
||||||
let pos = vec3<f32>(
|
let pos = vec3<f32>(
|
||||||
f32(tmp1) * 2.0 - 1.0,
|
f32(tmp1) * 2.0 - 1.0,
|
||||||
0.0,
|
0.0,
|
||||||
f32(tmp2) * 2.0 - 1.0
|
f32(tmp2) * 2.0 - 1.0
|
||||||
) * 100.0;
|
) * 160.0;
|
||||||
|
|
||||||
var result: GroundOutput;
|
var result: GroundOutput;
|
||||||
result.pos = pos;
|
result.pos = pos;
|
||||||
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
|
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
struct EntityOutput {
|
struct EntityOutput {
|
||||||
@builtin(position) position: vec4<f32>,
|
@builtin(position) position: vec4<f32>,
|
||||||
@location(1) normal: vec3<f32>,
|
@location(1) texture: vec2<f32>,
|
||||||
@location(3) view: vec3<f32>,
|
@location(2) normal: vec3<f32>,
|
||||||
|
@location(3) view: vec3<f32>,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@group(1)
|
||||||
|
@binding(0)
|
||||||
|
var<uniform> r_EntityTransform: mat4x4<f32>;
|
||||||
|
|
||||||
@vertex
|
@vertex
|
||||||
fn vs_entity(
|
fn vs_entity(
|
||||||
@location(0) pos: vec3<f32>,
|
@location(0) pos: vec3<f32>,
|
||||||
@location(1) normal: vec3<f32>,
|
@location(1) texture: vec2<f32>,
|
||||||
|
@location(2) normal: vec3<f32>,
|
||||||
) -> EntityOutput {
|
) -> EntityOutput {
|
||||||
var result: EntityOutput;
|
var position: vec4<f32> = r_EntityTransform * vec4<f32>(pos, 1.0);
|
||||||
result.normal = normal;
|
var result: EntityOutput;
|
||||||
result.view = pos - r_data.cam_pos.xyz;
|
result.normal = (r_EntityTransform * vec4<f32>(normal, 0.0)).xyz;
|
||||||
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
|
result.texture=texture;
|
||||||
return result;
|
result.view = position.xyz - r_data.cam_pos.xyz;
|
||||||
|
result.position = r_data.proj * r_data.view * position;
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@group(0)
|
@group(0)
|
||||||
@ -88,21 +96,36 @@ var r_sampler: sampler;
|
|||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
|
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
|
||||||
return textureSample(r_texture, r_sampler, vertex.sampledir);
|
return textureSample(r_texture, r_sampler, vertex.sampledir);
|
||||||
}
|
}
|
||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> {
|
fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> {
|
||||||
let incident = normalize(vertex.view);
|
let incident = normalize(vertex.view);
|
||||||
let normal = normalize(vertex.normal);
|
let normal = normalize(vertex.normal);
|
||||||
let reflected = incident - 2.0 * dot(normal, incident) * normal;
|
let d = dot(normal, incident);
|
||||||
|
let reflected = incident - 2.0 * d * normal;
|
||||||
|
|
||||||
let reflected_color = textureSample(r_texture, r_sampler, reflected).rgb;
|
let dir = vec3<f32>(-1.0)+2.0*vec3<f32>(vertex.texture.x,0.0,vertex.texture.y);
|
||||||
return vec4<f32>(vec3<f32>(0.1) + 0.5 * reflected_color, 1.0);
|
let texture_color = textureSample(r_texture, r_sampler, dir).rgb;
|
||||||
|
let reflected_color = textureSample(r_texture, r_sampler, reflected).rgb;
|
||||||
|
return vec4<f32>(mix(vec3<f32>(0.1) + 0.5 * reflected_color,texture_color,1.0-pow(1.0-abs(d),2.0)), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modulo_euclidean (a: f32, b: f32) -> f32 {
|
||||||
|
var m = a % b;
|
||||||
|
if (m < 0.0) {
|
||||||
|
if (b < 0.0) {
|
||||||
|
m -= b;
|
||||||
|
} else {
|
||||||
|
m += b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m;
|
||||||
}
|
}
|
||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_ground(vertex: GroundOutput) -> @location(0) vec4<f32> {
|
fn fs_ground(vertex: GroundOutput) -> @location(0) vec4<f32> {
|
||||||
let dir = vec3<f32>(-1.0)+vec3<f32>(vertex.pos.x/16.%1.0,0.0,vertex.pos.z/16.%1.0)*2.0;
|
let dir = vec3<f32>(-1.0)+vec3<f32>(modulo_euclidean(vertex.pos.x/16.,1.0),0.0,modulo_euclidean(vertex.pos.z/16.,1.0))*2.0;
|
||||||
return vec4<f32>(textureSample(r_texture, r_sampler, dir).rgb, 1.0);
|
return vec4<f32>(textureSample(r_texture, r_sampler, dir).rgb, 1.0);
|
||||||
}
|
}
|
||||||
|
8
src/sweep.rs
Normal file
8
src/sweep.rs
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
//something that implements body + hitbox + transform can predict collision
|
||||||
|
impl crate::sweep::PredictCollision for Model {
|
||||||
|
fn predict_collision(&self,other:&Model) -> Option<crate::event::EventStruct> {
|
||||||
|
//math!
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
47
src/timelines.rs
Normal file
47
src/timelines.rs
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
type ORDER = u32;
|
||||||
|
|
||||||
|
pub struct Tracker {
|
||||||
|
order: ORDER,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TimelineInstruction<I>{
|
||||||
|
pub order: ORDER,//absolute ordering of instructions which can be used for sorting even when there are multiple simultaneous timestamps
|
||||||
|
pub instruction: crate::instruction::TimedInstruction<I>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Timeline<I>{
|
||||||
|
instructions: std::collections::VecDeque<TimelineInstruction<I>>,
|
||||||
|
trackers: Vec<Tracker>,//wrong
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<I> Timeline<I>{
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self{
|
||||||
|
instructions:std::collections::VecDeque::<TimelineInstruction<I>>::new(),
|
||||||
|
trackers:Vec::<Tracker>::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
return self.instructions.len()
|
||||||
|
}
|
||||||
|
pub fn first(&self) -> Option<&TimelineInstruction<I>> {
|
||||||
|
return self.instructions.get(0)
|
||||||
|
}
|
||||||
|
pub fn last(&self) -> Option<&TimelineInstruction<I>> {
|
||||||
|
return self.instructions.get(self.instructions.len()-1)
|
||||||
|
}
|
||||||
|
pub fn append(&mut self,instruction:TimelineInstruction<I>){
|
||||||
|
let i=self.instructions.len();
|
||||||
|
self.instructions.push_back(instruction);
|
||||||
|
for tracker in self.trackers.iter() {
|
||||||
|
tracker.set_active(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn get_index_after_time(&mut self,time:crate::body::TIME) -> usize{
|
||||||
|
self.instructions.partition_point(|ins|ins.instruction.time<time)
|
||||||
|
}
|
||||||
|
pub fn get_index_after_order(&mut self,order:ORDER) -> usize{
|
||||||
|
self.instructions.partition_point(|ins|ins.order<order)
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user