Compare commits
193 Commits
redo-input
...
zeroes-opt
Author | SHA1 | Date | |
---|---|---|---|
91f8652ece | |||
0ec0d24302 | |||
f7ee18076a | |||
ee7df7787a | |||
db5f4e1da3 | |||
01a8efe4d4 | |||
08d4e7d997 | |||
e1f4f6e535 | |||
3a4c4ef9fe | |||
41dd155c50 | |||
5fd6ca219b | |||
1c22f4a3c3 | |||
1e6c489750 | |||
9f62f5f2fd | |||
7be7d2c0df | |||
cb6b0acd44 | |||
cbcf047c3f | |||
6e5de4aa46 | |||
cc776e7cb4 | |||
5a66ac46b9 | |||
38f6e1df3f | |||
849dcf98f7 | |||
d04d1be27e | |||
35bfd1d366 | |||
586bf8ce89 | |||
127b205401 | |||
4f596ca5d7 | |||
87f781a656 | |||
cd9cf164e9 | |||
497ca93071 | |||
747f628f04 | |||
7e1cf7041a | |||
50543ffcea | |||
54498f20f9 | |||
2240b80656 | |||
d18f2168e4 | |||
381b7b3c2f | |||
0d6741a81c | |||
2e8cdf968c | |||
dd0ac7cc7e | |||
e2af6fc4ed | |||
bdc0dd1b3b | |||
95fb316a23 | |||
9dec53d764 | |||
3552491a9a | |||
dd13a066d0 | |||
f3dd43b171 | |||
82d71df94e | |||
684dbda73a | |||
e398da3aa6 | |||
944393dabe | |||
4adce7acd3 | |||
5b935c32fe | |||
436706bc4d | |||
bde24d35a2 | |||
fc91d644e6 | |||
2b47827383 | |||
a942e10554 | |||
5d1e38c36c | |||
e78cabf0f5 | |||
4e90da2228 | |||
9fa4ea6716 | |||
aedef03e7c | |||
6a9af0441f | |||
8cf66f3446 | |||
1cb0d6e586 | |||
12a4bf7948 | |||
f2e4286a08 | |||
bd6cd5eacc | |||
f2dfb438d0 | |||
7c8bc8d647 | |||
4943bc6a7f | |||
55eebba1c5 | |||
b8f13539db | |||
fb2e2afeb9 | |||
f30f246e5f | |||
0ac49308a0 | |||
30cbbbca1b | |||
66fa8fd637 | |||
f2c71caae3 | |||
c8ec1f05d1 | |||
b102319b33 | |||
50e9152ee2 | |||
7a8de938af | |||
696f383aee | |||
bfd6f4493f | |||
ed96572a24 | |||
5914db3599 | |||
f72acaf2d4 | |||
734ce661f2 | |||
bb8c53aee2 | |||
de0eb0790a | |||
9e9550885f | |||
58be446297 | |||
d16404167b | |||
79262ce3b4 | |||
c47020c149 | |||
5854171619 | |||
616b09a857 | |||
6ff2620bbc | |||
d3e4918d3e | |||
6c2eb5ff29 | |||
02a509868a | |||
af750151f7 | |||
bf4560193d | |||
514c45fc21 | |||
95d16271de | |||
355d391ea5 | |||
d8c6444af3 | |||
fddd4576bd | |||
c7538869b4 | |||
923889d956 | |||
215ac47fcb | |||
d86aed5ae1 | |||
92bbbce1c3 | |||
5cd40afa56 | |||
602816a618 | |||
d7010956b3 | |||
b3f7802046 | |||
977c8e565c | |||
4ee29911a3 | |||
9ce9eb50be | |||
ccc94839e5 | |||
c85a84a52e | |||
2df76f020b | |||
7e3bfeb59e | |||
402def667f | |||
d4835187a8 | |||
f36b681614 | |||
a618f305e1 | |||
575d343276 | |||
ac4ba19ed3 | |||
ed712933e5 | |||
665a83d174 | |||
ba21ce262a | |||
5b770fc8a9 | |||
23a1a8690b | |||
60be7f14e5 | |||
37e9299f7d | |||
099865c682 | |||
c65354c23f | |||
1b29db0daf | |||
aa3e717f36 | |||
a06a28c595 | |||
0d6e989812 | |||
da3d0ca254 | |||
e685ef7388 | |||
b5c689f8ff | |||
0913063a00 | |||
f492a09377 | |||
b404908a55 | |||
f0d9c219b6 | |||
8fc87a59ce | |||
f0b3e87abb | |||
836749df47 | |||
31156aadfb | |||
ff7b12e90e | |||
e70dc9ad0f | |||
c5deef8753 | |||
7c2666fdf5 | |||
6da4c81826 | |||
c868a91a06 | |||
b513e4037d | |||
a803ada0e4 | |||
eafcbae677 | |||
2e786b090f | |||
70e8f7a0ad | |||
48091fc15d | |||
23857d38d9 | |||
1c9bc347f6 | |||
c9afa2d059 | |||
1a66dfbaf7 | |||
847209aac4 | |||
42ba757ec0 | |||
1cee3b52ac | |||
e27ce3b507 | |||
bc8f2bd566 | |||
eed932212d | |||
73edb9ff95 | |||
ae0c9e73ee | |||
953d424a57 | |||
ca919b92fd | |||
1de3501e89 | |||
0135b17917 | |||
1878528a4f | |||
25e80a7c17 | |||
21835d13f6 | |||
91f6a5261f | |||
fb4a5efa14 | |||
acb658f3e9 | |||
7e427b3879 | |||
d16485ae6d | |||
cdf695ee6e |
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
||||
/target
|
||||
/textures
|
1111
Cargo.lock
generated
1111
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
22
Cargo.toml
22
Cargo.toml
@ -1,23 +1,27 @@
|
||||
[package]
|
||||
name = "strafe-client"
|
||||
version = "0.3.0"
|
||||
version = "0.8.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
async-executor = "1.5.1"
|
||||
bytemuck = { version = "1.13.1", features = ["derive"] }
|
||||
configparser = "3.0.2"
|
||||
ddsfile = "0.5.1"
|
||||
env_logger = "0.10.0"
|
||||
glam = "0.24.1"
|
||||
log = "0.4.20"
|
||||
lazy-regex = "3.0.2"
|
||||
obj = "0.10.2"
|
||||
parking_lot = "0.12.1"
|
||||
pollster = "0.3.0"
|
||||
rbx_binary = "0.7.1"
|
||||
rbx_dom_weak = "2.5.0"
|
||||
rbx_reflection_database = "0.2.7"
|
||||
rbx_xml = "0.13.1"
|
||||
wgpu = "0.17.0"
|
||||
winit = "0.28.6"
|
||||
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
#[profile.release]
|
||||
#lto = true
|
||||
#strip = true
|
||||
#codegen-units = 1
|
||||
|
BIN
images/squid.dds
Normal file
BIN
images/squid.dds
Normal file
Binary file not shown.
89
src/aabb.rs
Normal file
89
src/aabb.rs
Normal file
@ -0,0 +1,89 @@
|
||||
use crate::integer::Planar64Vec3;
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub enum AabbFace{
|
||||
Right,//+X
|
||||
Top,
|
||||
Back,
|
||||
Left,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Aabb{
|
||||
pub min:Planar64Vec3,
|
||||
pub max:Planar64Vec3,
|
||||
}
|
||||
|
||||
impl Default for Aabb {
|
||||
fn default()->Self {
|
||||
Self{min:Planar64Vec3::MAX,max:Planar64Vec3::MIN}
|
||||
}
|
||||
}
|
||||
|
||||
impl Aabb{
|
||||
const VERTEX_DATA:[Planar64Vec3;8]=[
|
||||
Planar64Vec3::int( 1,-1,-1),
|
||||
Planar64Vec3::int( 1, 1,-1),
|
||||
Planar64Vec3::int( 1, 1, 1),
|
||||
Planar64Vec3::int( 1,-1, 1),
|
||||
Planar64Vec3::int(-1,-1, 1),
|
||||
Planar64Vec3::int(-1, 1, 1),
|
||||
Planar64Vec3::int(-1, 1,-1),
|
||||
Planar64Vec3::int(-1,-1,-1),
|
||||
];
|
||||
|
||||
pub fn grow(&mut self,point:Planar64Vec3){
|
||||
self.min=self.min.min(point);
|
||||
self.max=self.max.max(point);
|
||||
}
|
||||
pub fn join(&mut self,aabb:&Aabb){
|
||||
self.min=self.min.min(aabb.min);
|
||||
self.max=self.max.max(aabb.max);
|
||||
}
|
||||
pub fn inflate(&mut self,hs:Planar64Vec3){
|
||||
self.min-=hs;
|
||||
self.max+=hs;
|
||||
}
|
||||
pub fn intersects(&self,aabb:&Aabb)->bool{
|
||||
(self.min.cmplt(aabb.max)&aabb.min.cmplt(self.max)).all()
|
||||
}
|
||||
pub fn normal(face:AabbFace)->Planar64Vec3{
|
||||
match face {
|
||||
AabbFace::Right=>Planar64Vec3::int(1,0,0),
|
||||
AabbFace::Top=>Planar64Vec3::int(0,1,0),
|
||||
AabbFace::Back=>Planar64Vec3::int(0,0,1),
|
||||
AabbFace::Left=>Planar64Vec3::int(-1,0,0),
|
||||
AabbFace::Bottom=>Planar64Vec3::int(0,-1,0),
|
||||
AabbFace::Front=>Planar64Vec3::int(0,0,-1),
|
||||
}
|
||||
}
|
||||
pub fn unit_vertices()->[Planar64Vec3;8] {
|
||||
return Self::VERTEX_DATA;
|
||||
}
|
||||
// pub fn face(&self,face:AabbFace)->Aabb {
|
||||
// let mut aabb=self.clone();
|
||||
// //in this implementation face = worldspace aabb face
|
||||
// match face {
|
||||
// AabbFace::Right => aabb.min.x=aabb.max.x,
|
||||
// AabbFace::Top => aabb.min.y=aabb.max.y,
|
||||
// AabbFace::Back => aabb.min.z=aabb.max.z,
|
||||
// AabbFace::Left => aabb.max.x=aabb.min.x,
|
||||
// AabbFace::Bottom => aabb.max.y=aabb.min.y,
|
||||
// AabbFace::Front => aabb.max.z=aabb.min.z,
|
||||
// }
|
||||
// return aabb;
|
||||
// }
|
||||
pub fn center(&self)->Planar64Vec3{
|
||||
return self.min.midpoint(self.max)
|
||||
}
|
||||
//probably use floats for area & volume because we don't care about precision
|
||||
// pub fn area_weight(&self)->f32{
|
||||
// let d=self.max-self.min;
|
||||
// d.x*d.y+d.y*d.z+d.z*d.x
|
||||
// }
|
||||
// pub fn volume(&self)->f32{
|
||||
// let d=self.max-self.min;
|
||||
// d.x*d.y*d.z
|
||||
// }
|
||||
}
|
1020
src/body.rs
1020
src/body.rs
File diff suppressed because it is too large
Load Diff
107
src/bvh.rs
Normal file
107
src/bvh.rs
Normal file
@ -0,0 +1,107 @@
|
||||
use crate::aabb::Aabb;
|
||||
|
||||
//da algaritum
|
||||
//lista boxens
|
||||
//sort by {minx,maxx,miny,maxy,minz,maxz} (6 lists)
|
||||
//find the sets that minimizes the sum of surface areas
|
||||
//splitting is done when the minimum split sum of surface areas is larger than the node's own surface area
|
||||
|
||||
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
|
||||
//sort the centerpoints on each axis (3 lists)
|
||||
//bv is put into octant based on whether it is upper or lower in each list
|
||||
#[derive(Default)]
|
||||
pub struct BvhNode{
|
||||
children:Vec<Self>,
|
||||
models:Vec<usize>,
|
||||
aabb:Aabb,
|
||||
}
|
||||
|
||||
impl BvhNode{
|
||||
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
|
||||
for &model in &self.models{
|
||||
f(model);
|
||||
}
|
||||
for child in &self.children{
|
||||
if aabb.intersects(&child.aabb){
|
||||
child.the_tester(aabb,f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_bvh(boxen:Vec<Aabb>)->BvhNode{
|
||||
generate_bvh_node(boxen.into_iter().enumerate().collect())
|
||||
}
|
||||
|
||||
fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
||||
let n=boxen.len();
|
||||
if n<20{
|
||||
let mut aabb=Aabb::default();
|
||||
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0}).collect();
|
||||
BvhNode{
|
||||
children:Vec::new(),
|
||||
models,
|
||||
aabb,
|
||||
}
|
||||
}else{
|
||||
let mut octant=std::collections::HashMap::with_capacity(n);//this ids which octant the boxen is put in
|
||||
let mut sort_x=Vec::with_capacity(n);
|
||||
let mut sort_y=Vec::with_capacity(n);
|
||||
let mut sort_z=Vec::with_capacity(n);
|
||||
for (i,aabb) in boxen.iter(){
|
||||
let center=aabb.center();
|
||||
octant.insert(*i,0);
|
||||
sort_x.push((*i,center.x()));
|
||||
sort_y.push((*i,center.y()));
|
||||
sort_z.push((*i,center.z()));
|
||||
}
|
||||
sort_x.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
|
||||
sort_y.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
|
||||
sort_z.sort_by(|tup0,tup1|tup0.1.partial_cmp(&tup1.1).unwrap());
|
||||
let h=n/2;
|
||||
let median_x=sort_x[h].1;
|
||||
let median_y=sort_y[h].1;
|
||||
let median_z=sort_z[h].1;
|
||||
for (i,c) in sort_x{
|
||||
if median_x<c{
|
||||
octant.insert(i,octant[&i]+1<<0);
|
||||
}
|
||||
}
|
||||
for (i,c) in sort_y{
|
||||
if median_y<c{
|
||||
octant.insert(i,octant[&i]+1<<1);
|
||||
}
|
||||
}
|
||||
for (i,c) in sort_z{
|
||||
if median_z<c{
|
||||
octant.insert(i,octant[&i]+1<<2);
|
||||
}
|
||||
}
|
||||
//generate lists for unique octant values
|
||||
let mut list_list=Vec::with_capacity(8);
|
||||
let mut octant_list=Vec::with_capacity(8);
|
||||
for (i,aabb) in boxen.into_iter(){
|
||||
let octant_id=octant[&i];
|
||||
let list_id=if let Some(list_id)=octant_list.iter().position(|&id|id==octant_id){
|
||||
list_id
|
||||
}else{
|
||||
let list_id=list_list.len();
|
||||
octant_list.push(octant_id);
|
||||
list_list.push(Vec::new());
|
||||
list_id
|
||||
};
|
||||
list_list[list_id].push((i,aabb));
|
||||
}
|
||||
let mut aabb=Aabb::default();
|
||||
let children=list_list.into_iter().map(|b|{
|
||||
let node=generate_bvh_node(b);
|
||||
aabb.join(&node.aabb);
|
||||
node
|
||||
}).collect();
|
||||
BvhNode{
|
||||
children,
|
||||
models:Vec::new(),
|
||||
aabb,
|
||||
}
|
||||
}
|
||||
}
|
21
src/compat_worker.rs
Normal file
21
src/compat_worker.rs
Normal file
@ -0,0 +1,21 @@
|
||||
pub type QNWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||
pub type INWorker<'a,Task>=CompatNWorker<'a,Task>;
|
||||
|
||||
pub struct CompatNWorker<'a,Task>{
|
||||
data:std::marker::PhantomData<Task>,
|
||||
f:Box<dyn FnMut(Task)+'a>,
|
||||
}
|
||||
|
||||
impl<'a,Task> CompatNWorker<'a,Task>{
|
||||
pub fn new(f:impl FnMut(Task)+'a)->CompatNWorker<'a,Task>{
|
||||
Self{
|
||||
data:std::marker::PhantomData,
|
||||
f:Box::new(f),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send(&mut self,task:Task)->Result<(),()>{
|
||||
(self.f)(task);
|
||||
Ok(())
|
||||
}
|
||||
}
|
492
src/framework.rs
492
src/framework.rs
@ -1,492 +0,0 @@
|
||||
use std::future::Future;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use std::str::FromStr;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use web_sys::{ImageBitmapRenderingContext, OffscreenCanvas};
|
||||
use winit::{
|
||||
event::{self, WindowEvent, DeviceEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
};
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
|
||||
use std::{mem::size_of, slice::from_raw_parts};
|
||||
|
||||
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub enum ShaderStage {
|
||||
Vertex,
|
||||
Fragment,
|
||||
Compute,
|
||||
}
|
||||
|
||||
pub trait Example: 'static + Sized {
|
||||
fn optional_features() -> wgpu::Features {
|
||||
wgpu::Features::empty()
|
||||
}
|
||||
fn required_features() -> wgpu::Features {
|
||||
wgpu::Features::empty()
|
||||
}
|
||||
fn required_downlevel_capabilities() -> wgpu::DownlevelCapabilities {
|
||||
wgpu::DownlevelCapabilities {
|
||||
flags: wgpu::DownlevelFlags::empty(),
|
||||
shader_model: wgpu::ShaderModel::Sm5,
|
||||
..wgpu::DownlevelCapabilities::default()
|
||||
}
|
||||
}
|
||||
fn required_limits() -> wgpu::Limits {
|
||||
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
|
||||
}
|
||||
fn init(
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
adapter: &wgpu::Adapter,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
) -> Self;
|
||||
fn resize(
|
||||
&mut self,
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
);
|
||||
fn update(&mut self, event: WindowEvent);
|
||||
fn device_event(&mut self, event: DeviceEvent);
|
||||
fn render(
|
||||
&mut self,
|
||||
view: &wgpu::TextureView,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
spawner: &Spawner,
|
||||
);
|
||||
}
|
||||
|
||||
struct Setup {
|
||||
window: winit::window::Window,
|
||||
event_loop: EventLoop<()>,
|
||||
instance: wgpu::Instance,
|
||||
size: winit::dpi::PhysicalSize<u32>,
|
||||
surface: wgpu::Surface,
|
||||
adapter: wgpu::Adapter,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
offscreen_canvas_setup: Option<OffscreenCanvasSetup>,
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
struct OffscreenCanvasSetup {
|
||||
offscreen_canvas: OffscreenCanvas,
|
||||
bitmap_renderer: ImageBitmapRenderingContext,
|
||||
}
|
||||
|
||||
async fn setup<E: Example>(title: &str) -> Setup {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
env_logger::init();
|
||||
};
|
||||
|
||||
let event_loop = EventLoop::new();
|
||||
let mut builder = winit::window::WindowBuilder::new();
|
||||
builder = builder.with_title(title);
|
||||
#[cfg(windows_OFF)] // TODO
|
||||
{
|
||||
use winit::platform::windows::WindowBuilderExtWindows;
|
||||
builder = builder.with_no_redirection_bitmap(true);
|
||||
}
|
||||
let window = builder.build(&event_loop).unwrap();
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
use winit::platform::web::WindowExtWebSys;
|
||||
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
||||
let level: log::Level = parse_url_query_string(&query_string, "RUST_LOG")
|
||||
.and_then(|x| x.parse().ok())
|
||||
.unwrap_or(log::Level::Error);
|
||||
console_log::init_with_level(level).expect("could not initialize logger");
|
||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||
// On wasm, append the canvas to the document body
|
||||
web_sys::window()
|
||||
.and_then(|win| win.document())
|
||||
.and_then(|doc| doc.body())
|
||||
.and_then(|body| {
|
||||
body.append_child(&web_sys::Element::from(window.canvas()))
|
||||
.ok()
|
||||
})
|
||||
.expect("couldn't append canvas to document body");
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let mut offscreen_canvas_setup: Option<OffscreenCanvasSetup> = None;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
use wasm_bindgen::JsCast;
|
||||
use winit::platform::web::WindowExtWebSys;
|
||||
|
||||
let query_string = web_sys::window().unwrap().location().search().unwrap();
|
||||
if let Some(offscreen_canvas_param) =
|
||||
parse_url_query_string(&query_string, "offscreen_canvas")
|
||||
{
|
||||
if FromStr::from_str(offscreen_canvas_param) == Ok(true) {
|
||||
log::info!("Creating OffscreenCanvasSetup");
|
||||
|
||||
let offscreen_canvas =
|
||||
OffscreenCanvas::new(1024, 768).expect("couldn't create OffscreenCanvas");
|
||||
|
||||
let bitmap_renderer = window
|
||||
.canvas()
|
||||
.get_context("bitmaprenderer")
|
||||
.expect("couldn't create ImageBitmapRenderingContext (Result)")
|
||||
.expect("couldn't create ImageBitmapRenderingContext (Option)")
|
||||
.dyn_into::<ImageBitmapRenderingContext>()
|
||||
.expect("couldn't convert into ImageBitmapRenderingContext");
|
||||
|
||||
offscreen_canvas_setup = Some(OffscreenCanvasSetup {
|
||||
offscreen_canvas,
|
||||
bitmap_renderer,
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
log::info!("Initializing the surface...");
|
||||
|
||||
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 instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends,
|
||||
dx12_shader_compiler,
|
||||
});
|
||||
let (size, surface) = unsafe {
|
||||
let size = window.inner_size();
|
||||
|
||||
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
|
||||
let surface = instance.create_surface(&window).unwrap();
|
||||
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
|
||||
let surface = {
|
||||
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
||||
log::info!("Creating surface from OffscreenCanvas");
|
||||
instance.create_surface_from_offscreen_canvas(
|
||||
offscreen_canvas_setup.offscreen_canvas.clone(),
|
||||
)
|
||||
} else {
|
||||
instance.create_surface(&window)
|
||||
}
|
||||
}
|
||||
.unwrap();
|
||||
|
||||
(size, surface)
|
||||
};
|
||||
let adapter = wgpu::util::initialize_adapter_from_env_or_default(&instance, Some(&surface))
|
||||
.await
|
||||
.expect("No suitable GPU adapters found on the system!");
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let adapter_info = adapter.get_info();
|
||||
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
||||
}
|
||||
|
||||
let optional_features = E::optional_features();
|
||||
let required_features = E::required_features();
|
||||
let adapter_features = adapter.features();
|
||||
assert!(
|
||||
adapter_features.contains(required_features),
|
||||
"Adapter does not support required features for this example: {:?}",
|
||||
required_features - adapter_features
|
||||
);
|
||||
|
||||
let required_downlevel_capabilities = E::required_downlevel_capabilities();
|
||||
let downlevel_capabilities = adapter.get_downlevel_capabilities();
|
||||
assert!(
|
||||
downlevel_capabilities.shader_model >= required_downlevel_capabilities.shader_model,
|
||||
"Adapter does not support the minimum shader model required to run this example: {:?}",
|
||||
required_downlevel_capabilities.shader_model
|
||||
);
|
||||
assert!(
|
||||
downlevel_capabilities
|
||||
.flags
|
||||
.contains(required_downlevel_capabilities.flags),
|
||||
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
||||
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.
|
||||
let needed_limits = E::required_limits().using_resolution(adapter.limits());
|
||||
|
||||
let trace_dir = std::env::var("WGPU_TRACE");
|
||||
let (device, queue) = adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: None,
|
||||
features: (optional_features & adapter_features) | required_features,
|
||||
limits: needed_limits,
|
||||
},
|
||||
trace_dir.ok().as_ref().map(std::path::Path::new),
|
||||
)
|
||||
.await
|
||||
.expect("Unable to find a suitable GPU adapter!");
|
||||
|
||||
Setup {
|
||||
window,
|
||||
event_loop,
|
||||
instance,
|
||||
size,
|
||||
surface,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
offscreen_canvas_setup,
|
||||
}
|
||||
}
|
||||
|
||||
fn start<E: Example>(
|
||||
#[cfg(not(target_arch = "wasm32"))] Setup {
|
||||
window,
|
||||
event_loop,
|
||||
instance,
|
||||
size,
|
||||
surface,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
}: Setup,
|
||||
#[cfg(target_arch = "wasm32")] Setup {
|
||||
window,
|
||||
event_loop,
|
||||
instance,
|
||||
size,
|
||||
surface,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
offscreen_canvas_setup,
|
||||
}: Setup,
|
||||
) {
|
||||
let spawner = Spawner::new();
|
||||
let mut config = surface
|
||||
.get_default_config(&adapter, size.width, size.height)
|
||||
.expect("Surface isn't supported by the adapter.");
|
||||
let surface_view_format = config.format.add_srgb_suffix();
|
||||
config.view_formats.push(surface_view_format);
|
||||
surface.configure(&device, &config);
|
||||
|
||||
log::info!("Initializing the example...");
|
||||
let mut example = E::init(&config, &adapter, &device, &queue);
|
||||
|
||||
log::info!("Entering render loop...");
|
||||
event_loop.run(move |event, _, control_flow| {
|
||||
let _ = (&instance, &adapter); // force ownership by the closure
|
||||
*control_flow = if cfg!(feature = "metal-auto-capture") {
|
||||
ControlFlow::Exit
|
||||
} else {
|
||||
ControlFlow::Poll
|
||||
};
|
||||
match event {
|
||||
event::Event::RedrawEventsCleared => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
spawner.run_until_stalled();
|
||||
|
||||
window.request_redraw();
|
||||
}
|
||||
event::Event::WindowEvent {
|
||||
event:
|
||||
WindowEvent::Resized(size)
|
||||
| WindowEvent::ScaleFactorChanged {
|
||||
new_inner_size: &mut size,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
// Once winit is fixed, the detection conditions here can be removed.
|
||||
// https://github.com/rust-windowing/winit/issues/2876
|
||||
let max_dimension = adapter.limits().max_texture_dimension_2d;
|
||||
if size.width > max_dimension || size.height > max_dimension {
|
||||
log::warn!(
|
||||
"The resizing size {:?} exceeds the limit of {}.",
|
||||
size,
|
||||
max_dimension
|
||||
);
|
||||
} else {
|
||||
log::info!("Resizing to {:?}", size);
|
||||
config.width = size.width.max(1);
|
||||
config.height = size.height.max(1);
|
||||
example.resize(&config, &device, &queue);
|
||||
surface.configure(&device, &config);
|
||||
}
|
||||
}
|
||||
event::Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
input:
|
||||
event::KeyboardInput {
|
||||
virtual_keycode: Some(event::VirtualKeyCode::Escape),
|
||||
state: event::ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
| WindowEvent::CloseRequested => {
|
||||
*control_flow = ControlFlow::Exit;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
WindowEvent::KeyboardInput {
|
||||
input:
|
||||
event::KeyboardInput {
|
||||
virtual_keycode: Some(event::VirtualKeyCode::R),
|
||||
state: event::ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
println!("{:#?}", instance.generate_report());
|
||||
}
|
||||
_ => {
|
||||
example.update(event);
|
||||
}
|
||||
},
|
||||
event::Event::DeviceEvent {
|
||||
event,
|
||||
..
|
||||
} => {
|
||||
example.device_event(event);
|
||||
},
|
||||
event::Event::RedrawRequested(_) => {
|
||||
|
||||
let frame = match surface.get_current_texture() {
|
||||
Ok(frame) => frame,
|
||||
Err(_) => {
|
||||
surface.configure(&device, &config);
|
||||
surface
|
||||
.get_current_texture()
|
||||
.expect("Failed to acquire next surface texture!")
|
||||
}
|
||||
};
|
||||
let view = frame.texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
format: Some(surface_view_format),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
});
|
||||
|
||||
example.render(&view, &device, &queue, &spawner);
|
||||
|
||||
frame.present();
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
|
||||
let image_bitmap = offscreen_canvas_setup
|
||||
.offscreen_canvas
|
||||
.transfer_to_image_bitmap()
|
||||
.expect("couldn't transfer offscreen canvas to image bitmap.");
|
||||
offscreen_canvas_setup
|
||||
.bitmap_renderer
|
||||
.transfer_from_image_bitmap(&image_bitmap);
|
||||
|
||||
log::info!("Transferring OffscreenCanvas to ImageBitmapRenderer");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub struct Spawner<'a> {
|
||||
executor: async_executor::LocalExecutor<'a>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl<'a> Spawner<'a> {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
executor: async_executor::LocalExecutor::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'a) {
|
||||
self.executor.spawn(future).detach();
|
||||
}
|
||||
|
||||
fn run_until_stalled(&self) {
|
||||
while self.executor.try_tick() {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub struct Spawner {}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
impl Spawner {
|
||||
fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn spawn_local(&self, future: impl Future<Output = ()> + 'static) {
|
||||
wasm_bindgen_futures::spawn_local(future);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn run<E: Example>(title: &str) {
|
||||
let setup = pollster::block_on(setup::<E>(title));
|
||||
start::<E>(setup);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn run<E: Example>(title: &str) {
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
let title = title.to_owned();
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let setup = setup::<E>(&title).await;
|
||||
let start_closure = Closure::once_into_js(move || start::<E>(setup));
|
||||
|
||||
// make sure to handle JS exceptions thrown inside start.
|
||||
// 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`.
|
||||
if let Err(error) = call_catch(&start_closure) {
|
||||
let is_control_flow_exception = error.dyn_ref::<js_sys::Error>().map_or(false, |e| {
|
||||
e.message().includes("Using exceptions for control flow", 0)
|
||||
});
|
||||
|
||||
if !is_control_flow_exception {
|
||||
web_sys::console::error_1(&error);
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(catch, js_namespace = Function, js_name = "prototype.call.call")]
|
||||
fn call_catch(this: &JsValue) -> Result<(), JsValue>;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
/// Parse the query string as returned by `web_sys::window()?.location().search()?` and get a
|
||||
/// specific key out of it.
|
||||
pub fn parse_url_query_string<'a>(query: &'a str, search_key: &str) -> Option<&'a str> {
|
||||
let query_string = query.strip_prefix('?')?;
|
||||
|
||||
for pair in query_string.split('&') {
|
||||
let mut pair = pair.split('=');
|
||||
let key = pair.next()?;
|
||||
let value = pair.next()?;
|
||||
|
||||
if key == search_key {
|
||||
return Some(value);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
// This allows treating the framework as a standalone example,
|
||||
// thus avoiding listing the example names in `Cargo.toml`.
|
||||
#[allow(dead_code)]
|
||||
fn main() {}
|
994
src/graphics.rs
Normal file
994
src/graphics.rs
Normal file
@ -0,0 +1,994 @@
|
||||
use std::borrow::Cow;
|
||||
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
|
||||
use crate::model_graphics::{GraphicsVertex,ModelGraphicsColor4,ModelGraphicsInstance,ModelGraphicsSingleTexture,IndexedModelGraphicsSingleTexture,IndexedGroupFixedTexture};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ModelUpdate{
|
||||
transform:Option<glam::Mat4>,
|
||||
color:Option<glam::Vec4>,
|
||||
}
|
||||
|
||||
struct Entity {
|
||||
index_count: u32,
|
||||
index_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
struct ModelGraphics {
|
||||
instances: Vec<ModelGraphicsInstance>,
|
||||
vertex_buf: wgpu::Buffer,
|
||||
entities: Vec<Entity>,
|
||||
bind_group: wgpu::BindGroup,
|
||||
model_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
pub struct GraphicsSamplers{
|
||||
repeat: wgpu::Sampler,
|
||||
}
|
||||
|
||||
pub struct GraphicsBindGroupLayouts{
|
||||
model: wgpu::BindGroupLayout,
|
||||
}
|
||||
|
||||
pub struct GraphicsBindGroups {
|
||||
camera: wgpu::BindGroup,
|
||||
skybox_texture: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
pub struct GraphicsPipelines{
|
||||
skybox: wgpu::RenderPipeline,
|
||||
model: wgpu::RenderPipeline,
|
||||
}
|
||||
|
||||
pub struct GraphicsCamera{
|
||||
screen_size: glam::UVec2,
|
||||
fov: glam::Vec2,//slope
|
||||
//camera angles and such are extrapolated and passed in every time
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn perspective_rh(fov_x_slope: f32, fov_y_slope: f32, z_near: f32, z_far: f32) -> glam::Mat4 {
|
||||
//glam_assert!(z_near > 0.0 && z_far > 0.0);
|
||||
let r = z_far / (z_near - z_far);
|
||||
glam::Mat4::from_cols(
|
||||
glam::Vec4::new(1.0/fov_x_slope, 0.0, 0.0, 0.0),
|
||||
glam::Vec4::new(0.0, 1.0/fov_y_slope, 0.0, 0.0),
|
||||
glam::Vec4::new(0.0, 0.0, r, -1.0),
|
||||
glam::Vec4::new(0.0, 0.0, r * z_near, 0.0),
|
||||
)
|
||||
}
|
||||
impl GraphicsCamera{
|
||||
pub fn new(screen_size:glam::UVec2,fov:glam::Vec2)->Self{
|
||||
Self{
|
||||
screen_size,
|
||||
fov,
|
||||
}
|
||||
}
|
||||
pub fn proj(&self)->glam::Mat4{
|
||||
perspective_rh(self.fov.x, self.fov.y, 0.5, 2000.0)
|
||||
}
|
||||
pub fn world(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
|
||||
//f32 good enough for view matrix
|
||||
glam::Mat4::from_translation(pos) * glam::Mat4::from_euler(glam::EulerRot::YXZ, angles.x, angles.y, 0f32)
|
||||
}
|
||||
|
||||
pub fn to_uniform_data(&self,(pos,angles): (glam::Vec3,glam::Vec2)) -> [f32; 16 * 4] {
|
||||
let proj=self.proj();
|
||||
let proj_inv = proj.inverse();
|
||||
let view_inv=self.world(pos,angles);
|
||||
let view=view_inv.inverse();
|
||||
|
||||
let mut raw = [0f32; 16 * 4];
|
||||
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
||||
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
||||
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view)[..]);
|
||||
raw[48..64].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||
raw
|
||||
}
|
||||
}
|
||||
impl std::default::Default for GraphicsCamera{
|
||||
fn default()->Self{
|
||||
Self{
|
||||
screen_size:glam::UVec2::ONE,
|
||||
fov:glam::Vec2::ONE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphicsState{
|
||||
pipelines: GraphicsPipelines,
|
||||
bind_groups: GraphicsBindGroups,
|
||||
bind_group_layouts: GraphicsBindGroupLayouts,
|
||||
samplers: GraphicsSamplers,
|
||||
camera:GraphicsCamera,
|
||||
camera_buf: wgpu::Buffer,
|
||||
temp_squid_texture_view: wgpu::TextureView,
|
||||
models: Vec<ModelGraphics>,
|
||||
depth_view: wgpu::TextureView,
|
||||
staging_belt: wgpu::util::StagingBelt,
|
||||
}
|
||||
|
||||
impl GraphicsState{
|
||||
const DEPTH_FORMAT: wgpu::TextureFormat=wgpu::TextureFormat::Depth24Plus;
|
||||
fn create_depth_texture(
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
device: &wgpu::Device,
|
||||
) -> wgpu::TextureView {
|
||||
let depth_texture=device.create_texture(&wgpu::TextureDescriptor {
|
||||
size: wgpu::Extent3d {
|
||||
width: config.width,
|
||||
height: config.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: Self::DEPTH_FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
label: None,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
||||
}
|
||||
pub fn clear(&mut self){
|
||||
self.models.clear();
|
||||
}
|
||||
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
||||
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
||||
}
|
||||
pub fn generate_models(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,indexed_models:crate::model::IndexedModelInstances){
|
||||
//generate texture view per texture
|
||||
|
||||
//idk how to do this gooder lol
|
||||
let mut double_map=std::collections::HashMap::<u32,u32>::new();
|
||||
let mut texture_loading_threads=Vec::new();
|
||||
let num_textures=indexed_models.textures.len();
|
||||
for (i,texture_id) in indexed_models.textures.into_iter().enumerate(){
|
||||
if let Ok(mut file) = std::fs::File::open(std::path::Path::new(&format!("textures/{}.dds",texture_id))){
|
||||
double_map.insert(i as u32, texture_loading_threads.len() as u32);
|
||||
texture_loading_threads.push((texture_id,std::thread::spawn(move ||{
|
||||
ddsfile::Dds::read(&mut file).unwrap()
|
||||
})));
|
||||
}
|
||||
}
|
||||
|
||||
let texture_views:Vec<wgpu::TextureView>=texture_loading_threads.into_iter().map(|(texture_id,thread)|{
|
||||
let image=thread.join().unwrap();
|
||||
|
||||
let (mut width,mut height)=(image.get_width(),image.get_height());
|
||||
|
||||
let format=match image.header10.unwrap().dxgi_format{
|
||||
ddsfile::DxgiFormat::R8G8B8A8_UNorm_sRGB => wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
ddsfile::DxgiFormat::BC7_UNorm_sRGB => {
|
||||
//floor(w,4), should be ceil(w,4)
|
||||
width=width/4*4;
|
||||
height=height/4*4;
|
||||
wgpu::TextureFormat::Bc7RgbaUnormSrgb
|
||||
},
|
||||
other=>panic!("unsupported format {:?}",other),
|
||||
};
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
|
||||
let layer_size = wgpu::Extent3d {
|
||||
depth_or_array_layers: 1,
|
||||
..size
|
||||
};
|
||||
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||
|
||||
let texture = device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
size,
|
||||
mip_level_count: max_mips,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
label: Some(format!("Texture{}",texture_id).as_str()),
|
||||
view_formats: &[],
|
||||
},
|
||||
&image.data,
|
||||
);
|
||||
texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
label: Some(format!("Texture{} View",texture_id).as_str()),
|
||||
dimension: Some(wgpu::TextureViewDimension::D2),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
})
|
||||
}).collect();
|
||||
|
||||
//split groups with different textures into separate models
|
||||
//the models received here are supposed to be tightly packed, i.e. no code needs to check if two models are using the same groups.
|
||||
let indexed_models_len=indexed_models.models.len();
|
||||
let mut unique_texture_models=Vec::with_capacity(indexed_models_len);
|
||||
for model in indexed_models.models.into_iter(){
|
||||
//convert ModelInstance into ModelGraphicsInstance
|
||||
let instances:Vec<ModelGraphicsInstance>=model.instances.into_iter().filter_map(|instance|{
|
||||
if instance.color.w==0.0{
|
||||
None
|
||||
}else{
|
||||
Some(ModelGraphicsInstance{
|
||||
transform: instance.transform.into(),
|
||||
normal_transform: Into::<glam::Mat3>::into(instance.transform.matrix3).inverse().transpose(),
|
||||
color:ModelGraphicsColor4::from(instance.color),
|
||||
})
|
||||
}
|
||||
}).collect();
|
||||
//skip pushing a model if all instances are invisible
|
||||
if instances.len()==0{
|
||||
continue;
|
||||
}
|
||||
//check each group, if it's using a new texture then make a new clone of the model
|
||||
let id=unique_texture_models.len();
|
||||
let mut unique_textures=Vec::new();
|
||||
for group in model.groups.into_iter(){
|
||||
//ignore zero copy optimization for now
|
||||
let texture_index=if let Some(texture_index)=unique_textures.iter().position(|&texture|texture==group.texture){
|
||||
texture_index
|
||||
}else{
|
||||
//create new texture_index
|
||||
let texture_index=unique_textures.len();
|
||||
unique_textures.push(group.texture);
|
||||
unique_texture_models.push(IndexedModelGraphicsSingleTexture{
|
||||
unique_pos:model.unique_pos.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||
unique_tex:model.unique_tex.iter().map(|v|*v.as_ref()).collect(),
|
||||
unique_normal:model.unique_normal.iter().map(|&v|*Into::<glam::Vec3>::into(v).as_ref()).collect(),
|
||||
unique_color:model.unique_color.iter().map(|v|*v.as_ref()).collect(),
|
||||
unique_vertices:model.unique_vertices.clone(),
|
||||
texture:group.texture,
|
||||
groups:Vec::new(),
|
||||
instances:instances.clone(),
|
||||
});
|
||||
texture_index
|
||||
};
|
||||
unique_texture_models[id+texture_index].groups.push(IndexedGroupFixedTexture{
|
||||
polys:group.polys,
|
||||
});
|
||||
}
|
||||
}
|
||||
//check every model to see if it's using the same (texture,color) but has few instances, if it is combine it into one model
|
||||
//1. collect unique instances of texture and color, note model id
|
||||
//2. for each model id, check if removing it from the pool decreases both the model count and instance count by more than one
|
||||
//3. transpose all models that stay in the set
|
||||
|
||||
//best plan: benchmark set_bind_group, set_vertex_buffer, set_index_buffer and draw_indexed
|
||||
//check if the estimated render performance is better by transposing multiple model instances into one model instance
|
||||
|
||||
//for now: just deduplicate single models...
|
||||
let mut deduplicated_models=Vec::with_capacity(indexed_models_len);//use indexed_models_len because the list will likely get smaller instead of bigger
|
||||
let mut unique_texture_color=std::collections::HashMap::new();//texture->color->vec![(model_id,instance_id)]
|
||||
for (model_id,model) in unique_texture_models.iter().enumerate(){
|
||||
//for now: filter out models with more than one instance
|
||||
if 1<model.instances.len(){
|
||||
continue;
|
||||
}
|
||||
//populate hashmap
|
||||
let unique_color=if let Some(unique_color)=unique_texture_color.get_mut(&model.texture){
|
||||
unique_color
|
||||
}else{
|
||||
//make new hashmap
|
||||
let unique_color=std::collections::HashMap::new();
|
||||
unique_texture_color.insert(model.texture,unique_color);
|
||||
unique_texture_color.get_mut(&model.texture).unwrap()
|
||||
};
|
||||
//separate instances by color
|
||||
for (instance_id,instance) in model.instances.iter().enumerate(){
|
||||
let model_instance_list=if let Some(model_instance_list)=unique_color.get_mut(&instance.color){
|
||||
model_instance_list
|
||||
}else{
|
||||
//make new hashmap
|
||||
let model_instance_list=Vec::new();
|
||||
unique_color.insert(instance.color.clone(),model_instance_list);
|
||||
unique_color.get_mut(&instance.color).unwrap()
|
||||
};
|
||||
//add model instance to list
|
||||
model_instance_list.push((model_id,instance_id));
|
||||
}
|
||||
}
|
||||
//populate a hashset of models selected for transposition
|
||||
//construct transposed models
|
||||
let mut selected_model_instances=std::collections::HashSet::new();
|
||||
for (texture,unique_color) in unique_texture_color.into_iter(){
|
||||
for (color,model_instance_list) in unique_color.into_iter(){
|
||||
//world transforming one model does not meet the definition of deduplicaiton
|
||||
if 1<model_instance_list.len(){
|
||||
//create model
|
||||
let mut unique_pos=Vec::new();
|
||||
let mut pos_id_from=std::collections::HashMap::new();
|
||||
let mut unique_tex=Vec::new();
|
||||
let mut tex_id_from=std::collections::HashMap::new();
|
||||
let mut unique_normal=Vec::new();
|
||||
let mut normal_id_from=std::collections::HashMap::new();
|
||||
let mut unique_color=Vec::new();
|
||||
let mut color_id_from=std::collections::HashMap::new();
|
||||
let mut unique_vertices=Vec::new();
|
||||
let mut vertex_id_from=std::collections::HashMap::new();
|
||||
|
||||
let mut polys=Vec::new();
|
||||
//transform instance vertices
|
||||
for (model_id,instance_id) in model_instance_list.into_iter(){
|
||||
//populate hashset to prevent these models from being copied
|
||||
selected_model_instances.insert(model_id);
|
||||
//there is only one instance per model
|
||||
let model=&unique_texture_models[model_id];
|
||||
let instance=&model.instances[instance_id];
|
||||
//just hash word slices LOL
|
||||
let map_pos_id:Vec<u32>=model.unique_pos.iter().map(|untransformed_pos|{
|
||||
let pos=instance.transform.transform_point3(glam::Vec3::from_array(untransformed_pos.clone())).to_array();
|
||||
let h=pos.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||
(if let Some(&pos_id)=pos_id_from.get(&h){
|
||||
pos_id
|
||||
}else{
|
||||
let pos_id=unique_pos.len();
|
||||
unique_pos.push(pos.clone());
|
||||
pos_id_from.insert(h,pos_id);
|
||||
pos_id
|
||||
}) as u32
|
||||
}).collect();
|
||||
let map_tex_id:Vec<u32>=model.unique_tex.iter().map(|tex|{
|
||||
let h=tex.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||
(if let Some(&tex_id)=tex_id_from.get(&h){
|
||||
tex_id
|
||||
}else{
|
||||
let tex_id=unique_tex.len();
|
||||
unique_tex.push(tex.clone());
|
||||
tex_id_from.insert(h,tex_id);
|
||||
tex_id
|
||||
}) as u32
|
||||
}).collect();
|
||||
let map_normal_id:Vec<u32>=model.unique_normal.iter().map(|untransformed_normal|{
|
||||
let normal=(instance.normal_transform*glam::Vec3::from_array(untransformed_normal.clone())).to_array();
|
||||
let h=normal.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||
(if let Some(&normal_id)=normal_id_from.get(&h){
|
||||
normal_id
|
||||
}else{
|
||||
let normal_id=unique_normal.len();
|
||||
unique_normal.push(normal.clone());
|
||||
normal_id_from.insert(h,normal_id);
|
||||
normal_id
|
||||
}) as u32
|
||||
}).collect();
|
||||
let map_color_id:Vec<u32>=model.unique_color.iter().map(|color|{
|
||||
let h=color.map(|v|bytemuck::cast::<f32,u32>(v));
|
||||
(if let Some(&color_id)=color_id_from.get(&h){
|
||||
color_id
|
||||
}else{
|
||||
let color_id=unique_color.len();
|
||||
unique_color.push(color.clone());
|
||||
color_id_from.insert(h,color_id);
|
||||
color_id
|
||||
}) as u32
|
||||
}).collect();
|
||||
//map the indexed vertices onto new indices
|
||||
//creating the vertex map is slightly different because the vertices are directly hashable
|
||||
let map_vertex_id:Vec<u32>=model.unique_vertices.iter().map(|unmapped_vertex|{
|
||||
let vertex=crate::model::IndexedVertex{
|
||||
pos:map_pos_id[unmapped_vertex.pos as usize] as u32,
|
||||
tex:map_tex_id[unmapped_vertex.tex as usize] as u32,
|
||||
normal:map_normal_id[unmapped_vertex.normal as usize] as u32,
|
||||
color:map_color_id[unmapped_vertex.color as usize] as u32,
|
||||
};
|
||||
(if let Some(&vertex_id)=vertex_id_from.get(&vertex){
|
||||
vertex_id
|
||||
}else{
|
||||
let vertex_id=unique_vertices.len();
|
||||
unique_vertices.push(vertex.clone());
|
||||
vertex_id_from.insert(vertex,vertex_id);
|
||||
vertex_id
|
||||
}) as u32
|
||||
}).collect();
|
||||
for group in &model.groups{
|
||||
for poly in &group.polys{
|
||||
polys.push(crate::model::IndexedPolygon{vertices:poly.vertices.iter().map(|&vertex_id|map_vertex_id[vertex_id as usize]).collect()});
|
||||
}
|
||||
}
|
||||
}
|
||||
//push model into dedup
|
||||
deduplicated_models.push(IndexedModelGraphicsSingleTexture{
|
||||
unique_pos,
|
||||
unique_tex,
|
||||
unique_normal,
|
||||
unique_color,
|
||||
unique_vertices,
|
||||
texture,
|
||||
groups:vec![IndexedGroupFixedTexture{
|
||||
polys
|
||||
}],
|
||||
instances:vec![ModelGraphicsInstance{
|
||||
transform:glam::Mat4::IDENTITY,
|
||||
normal_transform:glam::Mat3::IDENTITY,
|
||||
color
|
||||
}],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
//fill untouched models
|
||||
for (model_id,model) in unique_texture_models.into_iter().enumerate(){
|
||||
if !selected_model_instances.contains(&model_id){
|
||||
deduplicated_models.push(model);
|
||||
}
|
||||
}
|
||||
|
||||
//de-index models
|
||||
let deduplicated_models_len=deduplicated_models.len();
|
||||
let models:Vec<ModelGraphicsSingleTexture>=deduplicated_models.into_iter().map(|model|{
|
||||
let mut vertices = Vec::new();
|
||||
let mut index_from_vertex = std::collections::HashMap::new();//::<IndexedVertex,usize>
|
||||
let mut entities = Vec::new();
|
||||
//this mut be combined in a more complex way if the models use different render patterns per group
|
||||
let mut indices = Vec::new();
|
||||
for group in model.groups {
|
||||
for poly in group.polys {
|
||||
for end_index in 2..poly.vertices.len() {
|
||||
for &index in &[0, end_index - 1, end_index] {
|
||||
let vertex_index = poly.vertices[index];
|
||||
if let Some(&i)=index_from_vertex.get(&vertex_index){
|
||||
indices.push(i);
|
||||
}else{
|
||||
let i=vertices.len() as u16;
|
||||
let vertex=&model.unique_vertices[vertex_index as usize];
|
||||
vertices.push(GraphicsVertex{
|
||||
pos: model.unique_pos[vertex.pos as usize],
|
||||
tex: model.unique_tex[vertex.tex as usize],
|
||||
normal: model.unique_normal[vertex.normal as usize],
|
||||
color:model.unique_color[vertex.color as usize],
|
||||
});
|
||||
index_from_vertex.insert(vertex_index,i);
|
||||
indices.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
entities.push(indices);
|
||||
ModelGraphicsSingleTexture{
|
||||
instances:model.instances,
|
||||
vertices,
|
||||
entities,
|
||||
texture:model.texture,
|
||||
}
|
||||
}).collect();
|
||||
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
||||
let mut model_count=0;
|
||||
let mut instance_count=0;
|
||||
let uniform_buffer_binding_size=crate::setup::required_limits().max_uniform_buffer_binding_size as usize;
|
||||
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
||||
self.models.reserve(models.len());
|
||||
for model in models.into_iter() {
|
||||
instance_count+=model.instances.len();
|
||||
for instances_chunk in model.instances.rchunks(chunk_size){
|
||||
model_count+=1;
|
||||
let model_uniforms = get_instances_buffer_data(instances_chunk);
|
||||
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some(format!("Model{} Buf",model_count).as_str()),
|
||||
contents: bytemuck::cast_slice(&model_uniforms),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
let texture_view=match model.texture{
|
||||
Some(texture_id)=>{
|
||||
match double_map.get(&texture_id){
|
||||
Some(&mapped_texture_id)=>&texture_views[mapped_texture_id as usize],
|
||||
None=>&self.temp_squid_texture_view,
|
||||
}
|
||||
},
|
||||
None=>&self.temp_squid_texture_view,
|
||||
};
|
||||
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &self.bind_group_layouts.model,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: model_buf.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&self.samplers.repeat),
|
||||
},
|
||||
],
|
||||
label: Some(format!("Model{} Bind Group",model_count).as_str()),
|
||||
});
|
||||
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Vertex"),
|
||||
contents: bytemuck::cast_slice(&model.vertices),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
//all of these are being moved here
|
||||
self.models.push(ModelGraphics{
|
||||
instances:instances_chunk.to_vec(),
|
||||
vertex_buf,
|
||||
entities: model.entities.iter().map(|indices|{
|
||||
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Index"),
|
||||
contents: bytemuck::cast_slice(&indices),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
});
|
||||
Entity {
|
||||
index_buf,
|
||||
index_count: indices.len() as u32,
|
||||
}
|
||||
}).collect(),
|
||||
bind_group: model_bind_group,
|
||||
model_buf,
|
||||
});
|
||||
}
|
||||
}
|
||||
println!("Texture References={}",num_textures);
|
||||
println!("Textures Loaded={}",texture_views.len());
|
||||
println!("Indexed Models={}",indexed_models_len);
|
||||
println!("Deduplicated Models={}",deduplicated_models_len);
|
||||
println!("Graphics Objects: {}",self.models.len());
|
||||
println!("Graphics Instances: {}",instance_count);
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
device:&wgpu::Device,
|
||||
queue:&wgpu::Queue,
|
||||
config:&wgpu::SurfaceConfiguration,
|
||||
)->Self{
|
||||
let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let skybox_texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Skybox Texture Bind Group Layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::Cube,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Model Bind Group Layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let clamp_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Clamp Sampler"),
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
let repeat_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Repeat Sampler"),
|
||||
address_mode_u: wgpu::AddressMode::Repeat,
|
||||
address_mode_v: wgpu::AddressMode::Repeat,
|
||||
address_mode_w: wgpu::AddressMode::Repeat,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// Create the render pipeline
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||
});
|
||||
|
||||
//load textures
|
||||
let device_features = device.features();
|
||||
|
||||
let skybox_texture_view={
|
||||
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
||||
println!("Using ASTC");
|
||||
wgpu::TextureFormat::Astc {
|
||||
block: AstcBlock::B4x4,
|
||||
channel: AstcChannel::UnormSrgb,
|
||||
}
|
||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
||||
println!("Using ETC2");
|
||||
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
|
||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
||||
println!("Using BC");
|
||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
||||
} else {
|
||||
println!("Using plain");
|
||||
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||
};
|
||||
|
||||
let bytes = match skybox_format {
|
||||
wgpu::TextureFormat::Astc {
|
||||
block: AstcBlock::B4x4,
|
||||
channel: AstcChannel::UnormSrgb,
|
||||
} => &include_bytes!("../images/astc.dds")[..],
|
||||
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
|
||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
|
||||
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let skybox_image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width: skybox_image.get_width(),
|
||||
height: skybox_image.get_height(),
|
||||
depth_or_array_layers: 6,
|
||||
};
|
||||
|
||||
let layer_size = wgpu::Extent3d {
|
||||
depth_or_array_layers: 1,
|
||||
..size
|
||||
};
|
||||
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||
|
||||
let skybox_texture = device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
size,
|
||||
mip_level_count: max_mips,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: skybox_format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
label: Some("Skybox Texture"),
|
||||
view_formats: &[],
|
||||
},
|
||||
&skybox_image.data,
|
||||
);
|
||||
|
||||
skybox_texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
label: Some("Skybox Texture View"),
|
||||
dimension: Some(wgpu::TextureViewDimension::Cube),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
})
|
||||
};
|
||||
|
||||
//squid
|
||||
let squid_texture_view={
|
||||
let bytes = include_bytes!("../images/squid.dds");
|
||||
|
||||
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(bytes)).unwrap();
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width: image.get_width(),
|
||||
height: image.get_height(),
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
|
||||
let layer_size = wgpu::Extent3d {
|
||||
depth_or_array_layers: 1,
|
||||
..size
|
||||
};
|
||||
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||
|
||||
let texture = device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
size,
|
||||
mip_level_count: max_mips,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Bc7RgbaUnorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
label: Some("Squid Texture"),
|
||||
view_formats: &[],
|
||||
},
|
||||
&image.data,
|
||||
);
|
||||
|
||||
texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
label: Some("Squid Texture View"),
|
||||
dimension: Some(wgpu::TextureViewDimension::D2),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
})
|
||||
};
|
||||
|
||||
let model_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: None,
|
||||
bind_group_layouts: &[
|
||||
&camera_bind_group_layout,
|
||||
&skybox_texture_bind_group_layout,
|
||||
&model_bind_group_layout,
|
||||
],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
let sky_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: None,
|
||||
bind_group_layouts: &[
|
||||
&camera_bind_group_layout,
|
||||
&skybox_texture_bind_group_layout,
|
||||
],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
// Create the render pipelines
|
||||
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Sky Pipeline"),
|
||||
layout: Some(&sky_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_sky",
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_sky",
|
||||
targets: &[Some(config.view_formats[0].into())],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
front_face: wgpu::FrontFace::Cw,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: Self::DEPTH_FORMAT,
|
||||
depth_write_enabled: false,
|
||||
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
});
|
||||
let model_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Model Pipeline"),
|
||||
layout: Some(&model_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_entity_texture",
|
||||
buffers: &[wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<GraphicsVertex>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32x3, 3 => Float32x4],
|
||||
}],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_entity_texture",
|
||||
targets: &[Some(config.view_formats[0].into())],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
front_face: wgpu::FrontFace::Cw,
|
||||
cull_mode:Some(wgpu::Face::Front),
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: Self::DEPTH_FORMAT,
|
||||
depth_write_enabled: true,
|
||||
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
});
|
||||
|
||||
let camera=GraphicsCamera::default();
|
||||
let camera_uniforms = camera.to_uniform_data(crate::physics::PhysicsOutputState::default().extrapolate(glam::IVec2::ZERO,crate::integer::Time::ZERO));
|
||||
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Camera"),
|
||||
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &camera_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: camera_buf.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
label: Some("Camera"),
|
||||
});
|
||||
|
||||
let skybox_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &skybox_texture_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&skybox_texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&clamp_sampler),
|
||||
},
|
||||
],
|
||||
label: Some("Sky Texture"),
|
||||
});
|
||||
|
||||
let depth_view = Self::create_depth_texture(config, device);
|
||||
|
||||
Self{
|
||||
pipelines:GraphicsPipelines{
|
||||
skybox:sky_pipeline,
|
||||
model:model_pipeline
|
||||
},
|
||||
bind_groups:GraphicsBindGroups{
|
||||
camera:camera_bind_group,
|
||||
skybox_texture:skybox_texture_bind_group,
|
||||
},
|
||||
camera,
|
||||
camera_buf,
|
||||
models: Vec::new(),
|
||||
depth_view,
|
||||
staging_belt: wgpu::util::StagingBelt::new(0x100),
|
||||
bind_group_layouts: GraphicsBindGroupLayouts { model: model_bind_group_layout },
|
||||
samplers: GraphicsSamplers { repeat: repeat_sampler },
|
||||
temp_squid_texture_view: squid_texture_view,
|
||||
}
|
||||
}
|
||||
pub fn resize(
|
||||
&mut self,
|
||||
device:&wgpu::Device,
|
||||
config:&wgpu::SurfaceConfiguration,
|
||||
user_settings:&crate::settings::UserSettings,
|
||||
) {
|
||||
self.depth_view=Self::create_depth_texture(config,device);
|
||||
self.camera.screen_size=glam::uvec2(config.width,config.height);
|
||||
self.load_user_settings(user_settings);
|
||||
}
|
||||
pub fn render(
|
||||
&mut self,
|
||||
view:&wgpu::TextureView,
|
||||
device:&wgpu::Device,
|
||||
queue:&wgpu::Queue,
|
||||
physics_output:crate::physics::PhysicsOutputState,
|
||||
predicted_time:crate::integer::Time,
|
||||
mouse_pos:glam::IVec2,
|
||||
) {
|
||||
//TODO: use scheduled frame times to create beautiful smoothing simulation physics extrapolation assuming no input
|
||||
|
||||
let mut encoder =
|
||||
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||
|
||||
// update rotation
|
||||
let camera_uniforms = self.camera.to_uniform_data(physics_output.extrapolate(mouse_pos,predicted_time));
|
||||
self.staging_belt
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
&self.camera_buf,
|
||||
0,
|
||||
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||
device,
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||
//This code only needs to run when the uniforms change
|
||||
/*
|
||||
for model in self.models.iter() {
|
||||
let model_uniforms = get_instances_buffer_data(&model.instances);
|
||||
self.staging_belt
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
&model.model_buf,//description of where data will be written when command is executed
|
||||
0,//offset in staging belt?
|
||||
wgpu::BufferSize::new((model_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||
device,
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
|
||||
}
|
||||
*/
|
||||
self.staging_belt.finish();
|
||||
|
||||
{
|
||||
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: None,
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
}),
|
||||
store: true,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: false,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
});
|
||||
|
||||
rpass.set_bind_group(0, &self.bind_groups.camera, &[]);
|
||||
rpass.set_bind_group(1, &self.bind_groups.skybox_texture, &[]);
|
||||
|
||||
rpass.set_pipeline(&self.pipelines.model);
|
||||
for model in self.models.iter() {
|
||||
rpass.set_bind_group(2, &model.bind_group, &[]);
|
||||
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
||||
|
||||
for entity in model.entities.iter() {
|
||||
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
||||
rpass.draw_indexed(0..entity.index_count, 0, 0..model.instances.len() as u32);
|
||||
}
|
||||
}
|
||||
|
||||
rpass.set_pipeline(&self.pipelines.skybox);
|
||||
rpass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
self.staging_belt.recall();
|
||||
}
|
||||
}
|
||||
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
||||
fn get_instances_buffer_data(instances:&[ModelGraphicsInstance]) -> Vec<f32> {
|
||||
let mut raw = Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||
for (i,mi) in instances.iter().enumerate(){
|
||||
let mut v = raw.split_off(MODEL_BUFFER_SIZE*i);
|
||||
//model transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||
//normal transform
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
//color
|
||||
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get()));
|
||||
raw.append(&mut v);
|
||||
}
|
||||
raw
|
||||
}
|
62
src/graphics_worker.rs
Normal file
62
src/graphics_worker.rs
Normal file
@ -0,0 +1,62 @@
|
||||
pub enum Instruction{
|
||||
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2),
|
||||
//UpdateModel(crate::graphics::ModelUpdate),
|
||||
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||
GenerateModels(crate::model::IndexedModelInstances),
|
||||
ClearModels,
|
||||
}
|
||||
|
||||
//Ideally the graphics thread worker description is:
|
||||
/*
|
||||
WorkerDescription{
|
||||
input:Immediate,
|
||||
output:Realtime(PoolOrdering::Ordered(3)),
|
||||
}
|
||||
*/
|
||||
//up to three frames in flight, dropping new frame requests when all three are busy, and dropping output frames when one renders out of order
|
||||
|
||||
pub fn new<'a>(
|
||||
mut graphics:crate::graphics::GraphicsState,
|
||||
mut config:wgpu::SurfaceConfiguration,
|
||||
surface:wgpu::Surface,
|
||||
device:wgpu::Device,
|
||||
queue:wgpu::Queue,
|
||||
)->crate::compat_worker::INWorker<'a,Instruction>{
|
||||
crate::compat_worker::INWorker::new(move |ins:Instruction|{
|
||||
match ins{
|
||||
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||
graphics.generate_models(&device,&queue,indexed_model_instances);
|
||||
},
|
||||
Instruction::ClearModels=>{
|
||||
graphics.clear();
|
||||
},
|
||||
Instruction::Resize(size,user_settings)=>{
|
||||
println!("Resizing to {:?}",size);
|
||||
config.width=size.width.max(1);
|
||||
config.height=size.height.max(1);
|
||||
surface.configure(&device,&config);
|
||||
graphics.resize(&device,&config,&user_settings);
|
||||
}
|
||||
Instruction::Render(physics_output,predicted_time,mouse_pos)=>{
|
||||
//this has to go deeper somehow
|
||||
let frame=match surface.get_current_texture(){
|
||||
Ok(frame)=>frame,
|
||||
Err(_)=>{
|
||||
surface.configure(&device,&config);
|
||||
surface
|
||||
.get_current_texture()
|
||||
.expect("Failed to acquire next surface texture!")
|
||||
}
|
||||
};
|
||||
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
||||
format:Some(config.view_formats[0]),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
});
|
||||
|
||||
graphics.render(&view,&device,&queue,physics_output,predicted_time,mouse_pos);
|
||||
|
||||
frame.present();
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
@ -1,23 +1,25 @@
|
||||
use crate::integer::Time;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TimedInstruction<I> {
|
||||
pub time: crate::body::TIME,
|
||||
pub instruction: I,
|
||||
pub struct TimedInstruction<I>{
|
||||
pub time:Time,
|
||||
pub instruction:I,
|
||||
}
|
||||
|
||||
pub trait InstructionEmitter<I> {
|
||||
fn next_instruction(&self, time_limit:crate::body::TIME) -> Option<TimedInstruction<I>>;
|
||||
pub trait InstructionEmitter<I>{
|
||||
fn next_instruction(&self,time_limit:Time)->Option<TimedInstruction<I>>;
|
||||
}
|
||||
pub trait InstructionConsumer<I> {
|
||||
pub trait InstructionConsumer<I>{
|
||||
fn process_instruction(&mut self, instruction:TimedInstruction<I>);
|
||||
}
|
||||
|
||||
//PROPER PRIVATE FIELDS!!!
|
||||
pub struct InstructionCollector<I> {
|
||||
time: crate::body::TIME,
|
||||
instruction: Option<I>,
|
||||
pub struct InstructionCollector<I>{
|
||||
time:Time,
|
||||
instruction:Option<I>,
|
||||
}
|
||||
impl<I> InstructionCollector<I> {
|
||||
pub fn new(time:crate::body::TIME) -> Self {
|
||||
impl<I> InstructionCollector<I>{
|
||||
pub fn new(time:Time)->Self{
|
||||
Self{
|
||||
time,
|
||||
instruction:None
|
||||
@ -25,24 +27,24 @@ impl<I> InstructionCollector<I> {
|
||||
}
|
||||
|
||||
pub fn collect(&mut self,instruction:Option<TimedInstruction<I>>){
|
||||
match instruction {
|
||||
Some(unwrap_instruction) => {
|
||||
match instruction{
|
||||
Some(unwrap_instruction)=>{
|
||||
if unwrap_instruction.time<self.time {
|
||||
self.time=unwrap_instruction.time;
|
||||
self.instruction=Some(unwrap_instruction.instruction);
|
||||
}
|
||||
},
|
||||
None => (),
|
||||
None=>(),
|
||||
}
|
||||
}
|
||||
pub fn instruction(self) -> Option<TimedInstruction<I>> {
|
||||
pub fn instruction(self)->Option<TimedInstruction<I>>{
|
||||
//STEAL INSTRUCTION AND DESTROY INSTRUCTIONCOLLECTOR
|
||||
match self.instruction {
|
||||
match self.instruction{
|
||||
Some(instruction)=>Some(TimedInstruction{
|
||||
time:self.time,
|
||||
instruction
|
||||
}),
|
||||
None => None,
|
||||
None=>None,
|
||||
}
|
||||
}
|
||||
}
|
958
src/integer.rs
Normal file
958
src/integer.rs
Normal file
@ -0,0 +1,958 @@
|
||||
//integer units
|
||||
#[derive(Clone,Copy,Hash,PartialEq,PartialOrd,Debug)]
|
||||
pub struct Time(i64);
|
||||
impl Time{
|
||||
pub const ZERO:Self=Self(0);
|
||||
pub const ONE_SECOND:Self=Self(1_000_000_000);
|
||||
pub const ONE_MILLISECOND:Self=Self(1_000_000);
|
||||
pub const ONE_MICROSECOND:Self=Self(1_000);
|
||||
pub const ONE_NANOSECOND:Self=Self(1);
|
||||
#[inline]
|
||||
pub fn from_secs(num:i64)->Self{
|
||||
Self(Self::ONE_SECOND.0*num)
|
||||
}
|
||||
#[inline]
|
||||
pub fn from_millis(num:i64)->Self{
|
||||
Self(Self::ONE_MILLISECOND.0*num)
|
||||
}
|
||||
#[inline]
|
||||
pub fn from_micros(num:i64)->Self{
|
||||
Self(Self::ONE_MICROSECOND.0*num)
|
||||
}
|
||||
#[inline]
|
||||
pub fn from_nanos(num:i64)->Self{
|
||||
Self(Self::ONE_NANOSECOND.0*num)
|
||||
}
|
||||
//should I have checked subtraction? force all time variables to be positive?
|
||||
#[inline]
|
||||
pub fn nanos(&self)->i64{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl From<Planar64> for Time{
|
||||
#[inline]
|
||||
fn from(value:Planar64)->Self{
|
||||
Time((((value.0 as i128)*1_000_000_000)>>32) as i64)
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for Time{
|
||||
#[inline]
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
||||
}
|
||||
}
|
||||
impl std::default::Default for Time{
|
||||
fn default()->Self{
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Neg for Time{
|
||||
type Output=Time;
|
||||
#[inline]
|
||||
fn neg(self)->Self::Output {
|
||||
Time(-self.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Add<Time> for Time{
|
||||
type Output=Time;
|
||||
#[inline]
|
||||
fn add(self,rhs:Self)->Self::Output {
|
||||
Time(self.0+rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Sub<Time> for Time{
|
||||
type Output=Time;
|
||||
#[inline]
|
||||
fn sub(self,rhs:Self)->Self::Output {
|
||||
Time(self.0-rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Time> for Time{
|
||||
type Output=Time;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Time)->Self::Output{
|
||||
Self((((self.0 as i128)*(rhs.0 as i128))/1_000_000_000) as i64)
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<i64> for Time{
|
||||
type Output=Time;
|
||||
#[inline]
|
||||
fn div(self,rhs:i64)->Self::Output {
|
||||
Time(self.0/rhs)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
const fn gcd(mut a:u64,mut b:u64)->u64{
|
||||
while b!=0{
|
||||
(a,b)=(b,a.rem_euclid(b));
|
||||
};
|
||||
a
|
||||
}
|
||||
#[derive(Clone,Hash)]
|
||||
pub struct Ratio64{
|
||||
num:i64,
|
||||
den:u64,
|
||||
}
|
||||
impl Ratio64{
|
||||
pub const ZERO:Self=Ratio64{num:0,den:1};
|
||||
pub const ONE:Self=Ratio64{num:1,den:1};
|
||||
#[inline]
|
||||
pub const fn new(num:i64,den:u64)->Option<Ratio64>{
|
||||
if den==0{
|
||||
None
|
||||
}else{
|
||||
let d=gcd(num.unsigned_abs(),den);
|
||||
Some(Self{num:num/d as i64,den:den/d})
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn mul_int(&self,rhs:i64)->i64{
|
||||
rhs*self.num/self.den as i64
|
||||
}
|
||||
#[inline]
|
||||
pub fn rhs_div_int(&self,rhs:i64)->i64{
|
||||
rhs*self.den as i64/self.num
|
||||
}
|
||||
#[inline]
|
||||
pub fn mul_ref(&self,rhs:&Ratio64)->Ratio64{
|
||||
let (num,den)=(self.num*rhs.num,self.den*rhs.den);
|
||||
let d=gcd(num.unsigned_abs(),den);
|
||||
Self{
|
||||
num:num/d as i64,
|
||||
den:den/d,
|
||||
}
|
||||
}
|
||||
}
|
||||
//from num_traits crate
|
||||
#[inline]
|
||||
fn integer_decode_f32(f: f32) -> (u64, i16, i8) {
|
||||
let bits: u32 = f.to_bits();
|
||||
let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 };
|
||||
let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
|
||||
let mantissa = if exponent == 0 {
|
||||
(bits & 0x7fffff) << 1
|
||||
} else {
|
||||
(bits & 0x7fffff) | 0x800000
|
||||
};
|
||||
// Exponent bias + mantissa shift
|
||||
exponent -= 127 + 23;
|
||||
(mantissa as u64, exponent, sign)
|
||||
}
|
||||
#[inline]
|
||||
fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
|
||||
let bits: u64 = f.to_bits();
|
||||
let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
|
||||
let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
|
||||
let mantissa = if exponent == 0 {
|
||||
(bits & 0xfffffffffffff) << 1
|
||||
} else {
|
||||
(bits & 0xfffffffffffff) | 0x10000000000000
|
||||
};
|
||||
// Exponent bias + mantissa shift
|
||||
exponent -= 1023 + 52;
|
||||
(mantissa, exponent, sign)
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum Ratio64TryFromFloatError{
|
||||
Nan,
|
||||
Infinite,
|
||||
Subnormal,
|
||||
HighlyNegativeExponent(i16),
|
||||
HighlyPositiveExponent(i16),
|
||||
}
|
||||
const MAX_DENOMINATOR:u128=u64::MAX as u128;
|
||||
#[inline]
|
||||
fn ratio64_from_mes((m,e,s):(u64,i16,i8))->Result<Ratio64,Ratio64TryFromFloatError>{
|
||||
if e< -127{
|
||||
//this can also just be zero
|
||||
Err(Ratio64TryFromFloatError::HighlyNegativeExponent(e))
|
||||
}else if e< -63{
|
||||
//approximate input ratio within denominator limit
|
||||
let mut target_num=m as u128;
|
||||
let mut target_den=1u128<<-e;
|
||||
|
||||
let mut num=1;
|
||||
let mut den=0;
|
||||
let mut prev_num=0;
|
||||
let mut prev_den=1;
|
||||
|
||||
while target_den!=0{
|
||||
let whole=target_num/target_den;
|
||||
(target_num,target_den)=(target_den,target_num-whole*target_den);
|
||||
let new_num=whole*num+prev_num;
|
||||
let new_den=whole*den+prev_den;
|
||||
if MAX_DENOMINATOR<new_den{
|
||||
break;
|
||||
}else{
|
||||
(prev_num,prev_den)=(num,den);
|
||||
(num,den)=(new_num,new_den);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Ratio64::new(num as i64,den as u64).unwrap())
|
||||
}else if e<0{
|
||||
Ok(Ratio64::new((m as i64)*(s as i64),1<<-e).unwrap())
|
||||
}else if (64-m.leading_zeros() as i16)+e<64{
|
||||
Ok(Ratio64::new((m as i64)*(s as i64)*(1<<e),1).unwrap())
|
||||
}else{
|
||||
Err(Ratio64TryFromFloatError::HighlyPositiveExponent(e))
|
||||
}
|
||||
}
|
||||
impl TryFrom<f32> for Ratio64{
|
||||
type Error=Ratio64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:f32)->Result<Self,Self::Error>{
|
||||
match value.classify(){
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>ratio64_from_mes(integer_decode_f32(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl TryFrom<f64> for Ratio64{
|
||||
type Error=Ratio64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:f64)->Result<Self,Self::Error>{
|
||||
match value.classify(){
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>ratio64_from_mes(integer_decode_f64(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Ratio64> for Ratio64{
|
||||
type Output=Ratio64;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Ratio64)->Self::Output{
|
||||
let (num,den)=(self.num*rhs.num,self.den*rhs.den);
|
||||
let d=gcd(num.unsigned_abs(),den);
|
||||
Self{
|
||||
num:num/d as i64,
|
||||
den:den/d,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<i64> for Ratio64{
|
||||
type Output=Ratio64;
|
||||
#[inline]
|
||||
fn mul(self,rhs:i64)->Self::Output {
|
||||
Self{
|
||||
num:self.num*rhs,
|
||||
den:self.den,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<u64> for Ratio64{
|
||||
type Output=Ratio64;
|
||||
#[inline]
|
||||
fn div(self,rhs:u64)->Self::Output {
|
||||
Self{
|
||||
num:self.num,
|
||||
den:self.den*rhs,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Hash)]
|
||||
pub struct Ratio64Vec2{
|
||||
pub x:Ratio64,
|
||||
pub y:Ratio64,
|
||||
}
|
||||
impl Ratio64Vec2{
|
||||
pub const ONE:Self=Self{x:Ratio64::ONE,y:Ratio64::ONE};
|
||||
#[inline]
|
||||
pub fn new(x:Ratio64,y:Ratio64)->Self{
|
||||
Self{x,y}
|
||||
}
|
||||
#[inline]
|
||||
pub fn mul_int(&self,rhs:glam::I64Vec2)->glam::I64Vec2{
|
||||
glam::i64vec2(
|
||||
self.x.mul_int(rhs.x),
|
||||
self.y.mul_int(rhs.y),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<i64> for Ratio64Vec2{
|
||||
type Output=Ratio64Vec2;
|
||||
#[inline]
|
||||
fn mul(self,rhs:i64)->Self::Output {
|
||||
Self{
|
||||
x:self.x*rhs,
|
||||
y:self.y*rhs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///[-pi,pi) = [-2^31,2^31-1]
|
||||
#[derive(Clone,Copy,Hash)]
|
||||
pub struct Angle32(i32);
|
||||
impl Angle32{
|
||||
pub const FRAC_PI_2:Self=Self(1<<30);
|
||||
pub const PI:Self=Self(-1<<31);
|
||||
#[inline]
|
||||
pub fn wrap_from_i64(theta:i64)->Self{
|
||||
//take lower bits
|
||||
//note: this was checked on compiler explorer and compiles to 1 instruction!
|
||||
Self(i32::from_ne_bytes(((theta&((1<<32)-1)) as u32).to_ne_bytes()))
|
||||
}
|
||||
#[inline]
|
||||
pub fn clamp_from_i64(theta:i64)->Self{
|
||||
//the assembly is a bit confusing for this, I thought it was checking the same thing twice
|
||||
//but it's just checking and then overwriting the value for both upper and lower bounds.
|
||||
Self(theta.clamp(i32::MIN as i64,i32::MAX as i64) as i32)
|
||||
}
|
||||
#[inline]
|
||||
pub fn get(&self)->i32{
|
||||
self.0
|
||||
}
|
||||
/// Clamps the value towards the midpoint of the range.
|
||||
/// Note that theta_min can be larger than theta_max and it will wrap clamp the other way around
|
||||
#[inline]
|
||||
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
|
||||
//((max-min as u32)/2 as i32)+min
|
||||
let midpoint=((
|
||||
u32::from_ne_bytes(theta_max.0.to_ne_bytes())
|
||||
.wrapping_sub(u32::from_ne_bytes(theta_min.0.to_ne_bytes()))
|
||||
/2
|
||||
) as i32)//(u32::MAX/2) as i32 ALWAYS works
|
||||
.wrapping_add(theta_min.0);
|
||||
//(theta-mid).clamp(max-mid,min-mid)+mid
|
||||
Self(
|
||||
self.0.wrapping_sub(midpoint)
|
||||
.max(theta_min.0.wrapping_sub(midpoint))
|
||||
.min(theta_max.0.wrapping_sub(midpoint))
|
||||
.wrapping_add(midpoint)
|
||||
)
|
||||
}
|
||||
/*
|
||||
#[inline]
|
||||
pub fn cos(&self)->Unit32{
|
||||
//TODO: fix this rounding towards 0
|
||||
Unit32(unsafe{((self.0 as f64*ANGLE32_TO_FLOAT64_RADIANS).cos()*UNIT32_ONE_FLOAT64).to_int_unchecked()})
|
||||
}
|
||||
#[inline]
|
||||
pub fn sin(&self)->Unit32{
|
||||
//TODO: fix this rounding towards 0
|
||||
Unit32(unsafe{((self.0 as f64*ANGLE32_TO_FLOAT64_RADIANS).sin()*UNIT32_ONE_FLOAT64).to_int_unchecked()})
|
||||
}
|
||||
*/
|
||||
}
|
||||
const ANGLE32_TO_FLOAT64_RADIANS:f64=std::f64::consts::PI/((1i64<<31) as f64);
|
||||
impl Into<f32> for Angle32{
|
||||
#[inline]
|
||||
fn into(self)->f32{
|
||||
(self.0 as f64*ANGLE32_TO_FLOAT64_RADIANS) as f32
|
||||
}
|
||||
}
|
||||
impl std::ops::Neg for Angle32{
|
||||
type Output=Angle32;
|
||||
#[inline]
|
||||
fn neg(self)->Self::Output{
|
||||
Angle32(self.0.wrapping_neg())
|
||||
}
|
||||
}
|
||||
impl std::ops::Add<Angle32> for Angle32{
|
||||
type Output=Angle32;
|
||||
#[inline]
|
||||
fn add(self,rhs:Self)->Self::Output {
|
||||
Angle32(self.0.wrapping_add(rhs.0))
|
||||
}
|
||||
}
|
||||
impl std::ops::Sub<Angle32> for Angle32{
|
||||
type Output=Angle32;
|
||||
#[inline]
|
||||
fn sub(self,rhs:Self)->Self::Output {
|
||||
Angle32(self.0.wrapping_sub(rhs.0))
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<i32> for Angle32{
|
||||
type Output=Angle32;
|
||||
#[inline]
|
||||
fn mul(self,rhs:i32)->Self::Output {
|
||||
Angle32(self.0.wrapping_mul(rhs))
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Angle32> for Angle32{
|
||||
type Output=Angle32;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Self)->Self::Output {
|
||||
Angle32(self.0.wrapping_mul(rhs.0))
|
||||
}
|
||||
}
|
||||
|
||||
/* Unit type unused for now, may revive it for map files
|
||||
///[-1.0,1.0] = [-2^30,2^30]
|
||||
pub struct Unit32(i32);
|
||||
impl Unit32{
|
||||
#[inline]
|
||||
pub fn as_planar64(&self) -> Planar64{
|
||||
Planar64(4*(self.0 as i64))
|
||||
}
|
||||
}
|
||||
const UNIT32_ONE_FLOAT64=((1<<30) as f64);
|
||||
///[-1.0,1.0] = [-2^30,2^30]
|
||||
pub struct Unit32Vec3(glam::IVec3);
|
||||
impl TryFrom<[f32;3]> for Unit32Vec3{
|
||||
type Error=Unit32TryFromFloatError;
|
||||
fn try_from(value:[f32;3])->Result<Self,Self::Error>{
|
||||
Ok(Self(glam::ivec3(
|
||||
Unit32::try_from(Planar64::try_from(value[0])?)?.0,
|
||||
Unit32::try_from(Planar64::try_from(value[1])?)?.0,
|
||||
Unit32::try_from(Planar64::try_from(value[2])?)?.0,
|
||||
)))
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
///[-1.0,1.0] = [-2^32,2^32]
|
||||
#[derive(Clone,Copy,Hash,Eq,Ord,PartialEq,PartialOrd)]
|
||||
pub struct Planar64(i64);
|
||||
impl Planar64{
|
||||
pub const ZERO:Self=Self(0);
|
||||
pub const ONE:Self=Self(1<<32);
|
||||
#[inline]
|
||||
pub const fn int(num:i32)->Self{
|
||||
Self(Self::ONE.0*num as i64)
|
||||
}
|
||||
#[inline]
|
||||
pub const fn raw(num:i64)->Self{
|
||||
Self(num)
|
||||
}
|
||||
#[inline]
|
||||
pub const fn get(&self)->i64{
|
||||
self.0
|
||||
}
|
||||
pub fn sqrt(&self)->Self{
|
||||
Planar64(unsafe{(((self.0 as i128)<<32) as f64).sqrt().to_int_unchecked()})
|
||||
}
|
||||
}
|
||||
const PLANAR64_ONE_FLOAT32:f32=(1u64<<32) as f32;
|
||||
const PLANAR64_CONVERT_TO_FLOAT32:f32=1.0/PLANAR64_ONE_FLOAT32;
|
||||
const PLANAR64_ONE_FLOAT64:f64=(1u64<<32) as f64;
|
||||
impl Into<f32> for Planar64{
|
||||
#[inline]
|
||||
fn into(self)->f32{
|
||||
self.0 as f32*PLANAR64_CONVERT_TO_FLOAT32
|
||||
}
|
||||
}
|
||||
impl From<Ratio64> for Planar64{
|
||||
#[inline]
|
||||
fn from(ratio:Ratio64)->Self{
|
||||
Self((((ratio.num as i128)<<32)/ratio.den as i128) as i64)
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum Planar64TryFromFloatError{
|
||||
Nan,
|
||||
Infinite,
|
||||
Subnormal,
|
||||
HighlyNegativeExponent(i16),
|
||||
HighlyPositiveExponent(i16),
|
||||
}
|
||||
#[inline]
|
||||
fn planar64_from_mes((m,e,s):(u64,i16,i8))->Result<Planar64,Planar64TryFromFloatError>{
|
||||
let e32=e+32;
|
||||
if e32<0&&(m>>-e32)==0{//shifting m will underflow to 0
|
||||
Ok(Planar64::ZERO)
|
||||
// println!("m{} e{} s{}",m,e,s);
|
||||
// println!("f={}",(m as f64)*(2.0f64.powf(e as f64))*(s as f64));
|
||||
// Err(Planar64TryFromFloatError::HighlyNegativeExponent(e))
|
||||
}else if (64-m.leading_zeros() as i16)+e32<64{//shifting m will not overflow
|
||||
if e32<0{
|
||||
Ok(Planar64((m as i64)*(s as i64)>>-e32))
|
||||
}else{
|
||||
Ok(Planar64((m as i64)*(s as i64)<<e32))
|
||||
}
|
||||
}else{//if shifting m will overflow (prev check failed)
|
||||
Err(Planar64TryFromFloatError::HighlyPositiveExponent(e))
|
||||
}
|
||||
}
|
||||
impl TryFrom<f32> for Planar64{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:f32)->Result<Self,Self::Error>{
|
||||
match value.classify(){
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>planar64_from_mes(integer_decode_f32(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl TryFrom<f64> for Planar64{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:f64)->Result<Self,Self::Error>{
|
||||
match value.classify(){
|
||||
std::num::FpCategory::Nan=>Err(Self::Error::Nan),
|
||||
std::num::FpCategory::Infinite=>Err(Self::Error::Infinite),
|
||||
std::num::FpCategory::Zero=>Ok(Self::ZERO),
|
||||
std::num::FpCategory::Subnormal=>Err(Self::Error::Subnormal),
|
||||
std::num::FpCategory::Normal=>planar64_from_mes(integer_decode_f64(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for Planar64{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{:.3}",
|
||||
Into::<f32>::into(*self),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl std::ops::Neg for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn neg(self)->Self::Output{
|
||||
Planar64(-self.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Add<Planar64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Planar64(self.0+rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Sub<Planar64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
Planar64(self.0-rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<i64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn mul(self, rhs: i64) -> Self::Output {
|
||||
Planar64(self.0*rhs)
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Planar64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Self) -> Self::Output {
|
||||
Planar64(((self.0 as i128*rhs.0 as i128)>>32) as i64)
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Time> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Time)->Self::Output{
|
||||
Planar64(((self.0 as i128*rhs.0 as i128)/1_000_000_000) as i64)
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<i64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn div(self, rhs: i64) -> Self::Output {
|
||||
Planar64(self.0/rhs)
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<Planar64> for Planar64{
|
||||
type Output=Planar64;
|
||||
#[inline]
|
||||
fn div(self, rhs: Planar64) -> Self::Output {
|
||||
Planar64((((self.0 as i128)<<32)/rhs.0 as i128) as i64)
|
||||
}
|
||||
}
|
||||
// impl PartialOrd<i64> for Planar64{
|
||||
// fn partial_cmp(&self, other: &i64) -> Option<std::cmp::Ordering> {
|
||||
// self.0.partial_cmp(other)
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
///[-1.0,1.0] = [-2^32,2^32]
|
||||
#[derive(Clone,Copy,Default,Hash,Eq,PartialEq)]
|
||||
pub struct Planar64Vec3(glam::I64Vec3);
|
||||
impl Planar64Vec3{
|
||||
pub const ZERO:Self=Planar64Vec3(glam::I64Vec3::ZERO);
|
||||
pub const ONE:Self=Self::int(1,1,1);
|
||||
pub const X:Self=Self::int(1,0,0);
|
||||
pub const Y:Self=Self::int(0,1,0);
|
||||
pub const Z:Self=Self::int(0,0,1);
|
||||
pub const NEG_X:Self=Self::int(-1,0,0);
|
||||
pub const NEG_Y:Self=Self::int(0,-1,0);
|
||||
pub const NEG_Z:Self=Self::int(0,0,-1);
|
||||
pub const MIN:Self=Planar64Vec3(glam::I64Vec3::MIN);
|
||||
pub const MAX:Self=Planar64Vec3(glam::I64Vec3::MAX);
|
||||
#[inline]
|
||||
pub const fn int(x:i32,y:i32,z:i32)->Self{
|
||||
Self(glam::i64vec3((x as i64)<<32,(y as i64)<<32,(z as i64)<<32))
|
||||
}
|
||||
#[inline]
|
||||
pub const fn raw(x:i64,y:i64,z:i64)->Self{
|
||||
Self(glam::i64vec3(x,y,z))
|
||||
}
|
||||
#[inline]
|
||||
pub fn x(&self)->Planar64{
|
||||
Planar64(self.0.x)
|
||||
}
|
||||
#[inline]
|
||||
pub fn y(&self)->Planar64{
|
||||
Planar64(self.0.y)
|
||||
}
|
||||
#[inline]
|
||||
pub fn z(&self)->Planar64{
|
||||
Planar64(self.0.z)
|
||||
}
|
||||
#[inline]
|
||||
pub fn min(&self,rhs:Self)->Self{
|
||||
Self(glam::i64vec3(
|
||||
self.0.x.min(rhs.0.x),
|
||||
self.0.y.min(rhs.0.y),
|
||||
self.0.z.min(rhs.0.z),
|
||||
))
|
||||
}
|
||||
#[inline]
|
||||
pub fn max(&self,rhs:Self)->Self{
|
||||
Self(glam::i64vec3(
|
||||
self.0.x.max(rhs.0.x),
|
||||
self.0.y.max(rhs.0.y),
|
||||
self.0.z.max(rhs.0.z),
|
||||
))
|
||||
}
|
||||
#[inline]
|
||||
pub fn midpoint(&self,rhs:Self)->Self{
|
||||
Self((self.0+rhs.0)/2)
|
||||
}
|
||||
#[inline]
|
||||
pub fn cmplt(&self,rhs:Self)->glam::BVec3{
|
||||
self.0.cmplt(rhs.0)
|
||||
}
|
||||
#[inline]
|
||||
pub fn dot(&self,rhs:Self)->Planar64{
|
||||
Planar64(((
|
||||
(self.0.x as i128)*(rhs.0.x as i128)+
|
||||
(self.0.y as i128)*(rhs.0.y as i128)+
|
||||
(self.0.z as i128)*(rhs.0.z as i128)
|
||||
)>>32) as i64)
|
||||
}
|
||||
#[inline]
|
||||
pub fn length(&self)->Planar64{
|
||||
let radicand=(self.0.x as i128)*(self.0.x as i128)+(self.0.y as i128)*(self.0.y as i128)+(self.0.z as i128)*(self.0.z as i128);
|
||||
Planar64(unsafe{(radicand as f64).sqrt().to_int_unchecked()})
|
||||
}
|
||||
#[inline]
|
||||
pub fn with_length(&self,length:Planar64)->Self{
|
||||
let radicand=(self.0.x as i128)*(self.0.x as i128)+(self.0.y as i128)*(self.0.y as i128)+(self.0.z as i128)*(self.0.z as i128);
|
||||
let self_length:i128=unsafe{(radicand as f64).sqrt().to_int_unchecked()};
|
||||
//self.0*length/self_length
|
||||
Planar64Vec3(
|
||||
glam::i64vec3(
|
||||
((self.0.x as i128)*(length.0 as i128)/self_length) as i64,
|
||||
((self.0.y as i128)*(length.0 as i128)/self_length) as i64,
|
||||
((self.0.z as i128)*(length.0 as i128)/self_length) as i64,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Into<glam::Vec3> for Planar64Vec3{
|
||||
#[inline]
|
||||
fn into(self)->glam::Vec3{
|
||||
glam::vec3(
|
||||
self.0.x as f32,
|
||||
self.0.y as f32,
|
||||
self.0.z as f32,
|
||||
)*PLANAR64_CONVERT_TO_FLOAT32
|
||||
}
|
||||
}
|
||||
impl TryFrom<[f32;3]> for Planar64Vec3{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:[f32;3])->Result<Self,Self::Error>{
|
||||
Ok(Self(glam::i64vec3(
|
||||
Planar64::try_from(value[0])?.0,
|
||||
Planar64::try_from(value[1])?.0,
|
||||
Planar64::try_from(value[2])?.0,
|
||||
)))
|
||||
}
|
||||
}
|
||||
impl TryFrom<glam::Vec3A> for Planar64Vec3{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:glam::Vec3A)->Result<Self,Self::Error>{
|
||||
Ok(Self(glam::i64vec3(
|
||||
Planar64::try_from(value.x)?.0,
|
||||
Planar64::try_from(value.y)?.0,
|
||||
Planar64::try_from(value.z)?.0,
|
||||
)))
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for Planar64Vec3{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{:.3},{:.3},{:.3}",
|
||||
Into::<f32>::into(self.x()),Into::<f32>::into(self.y()),Into::<f32>::into(self.z()),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl std::ops::Neg for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn neg(self)->Self::Output{
|
||||
Planar64Vec3(-self.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::Add<Planar64Vec3> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn add(self,rhs:Planar64Vec3) -> Self::Output {
|
||||
Planar64Vec3(self.0+rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::AddAssign<Planar64Vec3> for Planar64Vec3{
|
||||
#[inline]
|
||||
fn add_assign(&mut self,rhs:Planar64Vec3){
|
||||
*self=*self+rhs
|
||||
}
|
||||
}
|
||||
impl std::ops::Sub<Planar64Vec3> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn sub(self,rhs:Planar64Vec3) -> Self::Output {
|
||||
Planar64Vec3(self.0-rhs.0)
|
||||
}
|
||||
}
|
||||
impl std::ops::SubAssign<Planar64Vec3> for Planar64Vec3{
|
||||
#[inline]
|
||||
fn sub_assign(&mut self,rhs:Planar64Vec3){
|
||||
*self=*self-rhs
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Planar64Vec3> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Planar64Vec3) -> Self::Output {
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
(((self.0.x as i128)*(rhs.0.x as i128))>>32) as i64,
|
||||
(((self.0.y as i128)*(rhs.0.y as i128))>>32) as i64,
|
||||
(((self.0.z as i128)*(rhs.0.z as i128))>>32) as i64
|
||||
))
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Planar64> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self, rhs: Planar64) -> Self::Output {
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
(((self.0.x as i128)*(rhs.0 as i128))>>32) as i64,
|
||||
(((self.0.y as i128)*(rhs.0 as i128))>>32) as i64,
|
||||
(((self.0.z as i128)*(rhs.0 as i128))>>32) as i64
|
||||
))
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<i64> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self,rhs:i64)->Self::Output {
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
self.0.x*rhs,
|
||||
self.0.y*rhs,
|
||||
self.0.z*rhs
|
||||
))
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Time> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Time)->Self::Output{
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
(((self.0.x as i128)*(rhs.0 as i128))/1_000_000_000) as i64,
|
||||
(((self.0.y as i128)*(rhs.0 as i128))/1_000_000_000) as i64,
|
||||
(((self.0.z as i128)*(rhs.0 as i128))/1_000_000_000) as i64
|
||||
))
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<i64> for Planar64Vec3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn div(self,rhs:i64)->Self::Output{
|
||||
Planar64Vec3(glam::i64vec3(
|
||||
self.0.x/rhs,
|
||||
self.0.y/rhs,
|
||||
self.0.z/rhs,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
///[-1.0,1.0] = [-2^32,2^32]
|
||||
#[derive(Clone,Copy)]
|
||||
pub struct Planar64Mat3{
|
||||
x_axis:Planar64Vec3,
|
||||
y_axis:Planar64Vec3,
|
||||
z_axis:Planar64Vec3,
|
||||
}
|
||||
impl Default for Planar64Mat3{
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self{
|
||||
x_axis:Planar64Vec3::X,
|
||||
y_axis:Planar64Vec3::Y,
|
||||
z_axis:Planar64Vec3::Z,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::ops::Mul<Planar64Vec3> for Planar64Mat3{
|
||||
type Output=Planar64Vec3;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Planar64Vec3) -> Self::Output {
|
||||
self.x_axis*rhs.x()
|
||||
+self.y_axis*rhs.y()
|
||||
+self.z_axis*rhs.z()
|
||||
}
|
||||
}
|
||||
|
||||
impl Planar64Mat3{
|
||||
#[inline]
|
||||
pub fn from_cols(x_axis:Planar64Vec3,y_axis:Planar64Vec3,z_axis:Planar64Vec3)->Self{
|
||||
Self{
|
||||
x_axis,
|
||||
y_axis,
|
||||
z_axis,
|
||||
}
|
||||
}
|
||||
pub const fn int_from_cols_array(array:[i32;9])->Self{
|
||||
Self{
|
||||
x_axis:Planar64Vec3::int(array[0],array[1],array[2]),
|
||||
y_axis:Planar64Vec3::int(array[3],array[4],array[5]),
|
||||
z_axis:Planar64Vec3::int(array[6],array[7],array[8]),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn from_rotation_yx(yaw:Angle32,pitch:Angle32)->Self{
|
||||
let xtheta=yaw.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
||||
let (xs,xc)=xtheta.sin_cos();
|
||||
let (xc,xs)=(xc*PLANAR64_ONE_FLOAT64,xs*PLANAR64_ONE_FLOAT64);
|
||||
let ytheta=pitch.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
||||
let (ys,yc)=ytheta.sin_cos();
|
||||
let (yc,ys)=(yc*PLANAR64_ONE_FLOAT64,ys*PLANAR64_ONE_FLOAT64);
|
||||
//TODO: fix this rounding towards 0
|
||||
let (xc,xs):(i64,i64)=(unsafe{xc.to_int_unchecked()},unsafe{xs.to_int_unchecked()});
|
||||
let (yc,ys):(i64,i64)=(unsafe{yc.to_int_unchecked()},unsafe{ys.to_int_unchecked()});
|
||||
Self::from_cols(
|
||||
Planar64Vec3(glam::i64vec3(xc,0,-xs)),
|
||||
Planar64Vec3(glam::i64vec3(((xs as i128*ys as i128)>>32) as i64,yc,((xc as i128*ys as i128)>>32) as i64)),
|
||||
Planar64Vec3(glam::i64vec3(((xs as i128*yc as i128)>>32) as i64,-ys,((xc as i128*yc as i128)>>32) as i64)),
|
||||
)
|
||||
}
|
||||
#[inline]
|
||||
pub fn from_rotation_y(angle:Angle32)->Self{
|
||||
let theta=angle.0 as f64*ANGLE32_TO_FLOAT64_RADIANS;
|
||||
let (s,c)=theta.sin_cos();
|
||||
let (c,s)=(c*PLANAR64_ONE_FLOAT64,s*PLANAR64_ONE_FLOAT64);
|
||||
//TODO: fix this rounding towards 0
|
||||
let (c,s):(i64,i64)=(unsafe{c.to_int_unchecked()},unsafe{s.to_int_unchecked()});
|
||||
Self::from_cols(
|
||||
Planar64Vec3(glam::i64vec3(c,0,-s)),
|
||||
Planar64Vec3::Y,
|
||||
Planar64Vec3(glam::i64vec3(s,0,c)),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Into<glam::Mat3> for Planar64Mat3{
|
||||
#[inline]
|
||||
fn into(self)->glam::Mat3{
|
||||
glam::Mat3::from_cols(
|
||||
self.x_axis.into(),
|
||||
self.y_axis.into(),
|
||||
self.z_axis.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl TryFrom<glam::Mat3A> for Planar64Mat3{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
#[inline]
|
||||
fn try_from(value:glam::Mat3A)->Result<Self,Self::Error>{
|
||||
Ok(Self{
|
||||
x_axis:Planar64Vec3::try_from(value.x_axis)?,
|
||||
y_axis:Planar64Vec3::try_from(value.y_axis)?,
|
||||
z_axis:Planar64Vec3::try_from(value.z_axis)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for Planar64Mat3{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"\n{:.3},{:.3},{:.3}\n{:.3},{:.3},{:.3}\n{:.3},{:.3},{:.3}",
|
||||
Into::<f32>::into(self.x_axis.x()),Into::<f32>::into(self.x_axis.y()),Into::<f32>::into(self.x_axis.z()),
|
||||
Into::<f32>::into(self.y_axis.x()),Into::<f32>::into(self.y_axis.y()),Into::<f32>::into(self.y_axis.z()),
|
||||
Into::<f32>::into(self.z_axis.x()),Into::<f32>::into(self.z_axis.y()),Into::<f32>::into(self.z_axis.z()),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl std::ops::Div<i64> for Planar64Mat3{
|
||||
type Output=Planar64Mat3;
|
||||
#[inline]
|
||||
fn div(self,rhs:i64)->Self::Output{
|
||||
Planar64Mat3{
|
||||
x_axis:self.x_axis/rhs,
|
||||
y_axis:self.y_axis/rhs,
|
||||
z_axis:self.z_axis/rhs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///[-1.0,1.0] = [-2^32,2^32]
|
||||
#[derive(Clone,Copy,Default)]
|
||||
pub struct Planar64Affine3{
|
||||
pub matrix3:Planar64Mat3,//includes scale above 1
|
||||
pub translation:Planar64Vec3,
|
||||
}
|
||||
|
||||
impl Planar64Affine3{
|
||||
#[inline]
|
||||
pub fn new(matrix3:Planar64Mat3,translation:Planar64Vec3)->Self{
|
||||
Self{matrix3,translation}
|
||||
}
|
||||
#[inline]
|
||||
pub fn transform_point3(&self,point:Planar64Vec3) -> Planar64Vec3{
|
||||
Planar64Vec3(
|
||||
self.translation.0
|
||||
+(self.matrix3.x_axis*point.x()).0
|
||||
+(self.matrix3.y_axis*point.y()).0
|
||||
+(self.matrix3.z_axis*point.z()).0
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Into<glam::Mat4> for Planar64Affine3{
|
||||
#[inline]
|
||||
fn into(self)->glam::Mat4{
|
||||
glam::Mat4::from_cols_array(&[
|
||||
self.matrix3.x_axis.0.x as f32,self.matrix3.x_axis.0.y as f32,self.matrix3.x_axis.0.z as f32,0.0,
|
||||
self.matrix3.y_axis.0.x as f32,self.matrix3.y_axis.0.y as f32,self.matrix3.y_axis.0.z as f32,0.0,
|
||||
self.matrix3.z_axis.0.x as f32,self.matrix3.z_axis.0.y as f32,self.matrix3.z_axis.0.z as f32,0.0,
|
||||
self.translation.0.x as f32,self.translation.0.y as f32,self.translation.0.z as f32,PLANAR64_ONE_FLOAT32
|
||||
])*PLANAR64_CONVERT_TO_FLOAT32
|
||||
}
|
||||
}
|
||||
impl TryFrom<glam::Affine3A> for Planar64Affine3{
|
||||
type Error=Planar64TryFromFloatError;
|
||||
fn try_from(value: glam::Affine3A)->Result<Self, Self::Error> {
|
||||
Ok(Self{
|
||||
matrix3:Planar64Mat3::try_from(value.matrix3)?,
|
||||
translation:Planar64Vec3::try_from(value.translation)?
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for Planar64Affine3{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"translation: {:.3},{:.3},{:.3}\nmatrix3:\n{:.3},{:.3},{:.3}\n{:.3},{:.3},{:.3}\n{:.3},{:.3},{:.3}",
|
||||
Into::<f32>::into(self.translation.x()),Into::<f32>::into(self.translation.y()),Into::<f32>::into(self.translation.z()),
|
||||
Into::<f32>::into(self.matrix3.x_axis.x()),Into::<f32>::into(self.matrix3.x_axis.y()),Into::<f32>::into(self.matrix3.x_axis.z()),
|
||||
Into::<f32>::into(self.matrix3.y_axis.x()),Into::<f32>::into(self.matrix3.y_axis.y()),Into::<f32>::into(self.matrix3.y_axis.z()),
|
||||
Into::<f32>::into(self.matrix3.z_axis.x()),Into::<f32>::into(self.matrix3.z_axis.y()),Into::<f32>::into(self.matrix3.z_axis.z()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sqrt(){
|
||||
let r=Planar64::int(400);
|
||||
println!("r{}",r.get());
|
||||
let s=r.sqrt();
|
||||
println!("s{}",s.get());
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
pub mod framework;
|
||||
pub mod body;
|
||||
pub mod zeroes;
|
||||
pub mod instruction;
|
496
src/load_roblox.rs
Normal file
496
src/load_roblox.rs
Normal file
@ -0,0 +1,496 @@
|
||||
use crate::primitives;
|
||||
use crate::integer::{Planar64,Planar64Vec3,Planar64Mat3,Planar64Affine3};
|
||||
|
||||
fn class_is_a(class: &str, superclass: &str) -> bool {
|
||||
if class==superclass {
|
||||
return true
|
||||
}
|
||||
let class_descriptor=rbx_reflection_database::get().classes.get(class);
|
||||
if let Some(descriptor) = &class_descriptor {
|
||||
if let Some(class_super) = &descriptor.superclass {
|
||||
return class_is_a(&class_super, superclass)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
fn recursive_collect_superclass(objects: &mut std::vec::Vec<rbx_dom_weak::types::Ref>,dom: &rbx_dom_weak::WeakDom, instance: &rbx_dom_weak::Instance, superclass: &str){
|
||||
for &referent in instance.children() {
|
||||
if let Some(c) = dom.get_by_ref(referent) {
|
||||
if class_is_a(c.class.as_str(), superclass) {
|
||||
objects.push(c.referent());//copy ref
|
||||
}
|
||||
recursive_collect_superclass(objects,dom,c,superclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn planar64_affine3_from_roblox(cf:&rbx_dom_weak::types::CFrame,size:&rbx_dom_weak::types::Vector3)->Planar64Affine3{
|
||||
Planar64Affine3::new(
|
||||
Planar64Mat3::from_cols(
|
||||
Planar64Vec3::try_from([cf.orientation.x.x,cf.orientation.y.x,cf.orientation.z.x]).unwrap()
|
||||
*Planar64::try_from(size.x/2.0).unwrap(),
|
||||
Planar64Vec3::try_from([cf.orientation.x.y,cf.orientation.y.y,cf.orientation.z.y]).unwrap()
|
||||
*Planar64::try_from(size.y/2.0).unwrap(),
|
||||
Planar64Vec3::try_from([cf.orientation.x.z,cf.orientation.y.z,cf.orientation.z.z]).unwrap()
|
||||
*Planar64::try_from(size.z/2.0).unwrap(),
|
||||
),
|
||||
Planar64Vec3::try_from([cf.position.x,cf.position.y,cf.position.z]).unwrap()
|
||||
)
|
||||
}
|
||||
fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_intersecting:bool)->crate::model::CollisionAttributes{
|
||||
let mut general=crate::model::GameMechanicAttributes::default();
|
||||
let mut intersecting=crate::model::IntersectingAttributes::default();
|
||||
let mut contacting=crate::model::ContactingAttributes::default();
|
||||
let mut force_can_collide=can_collide;
|
||||
match name{
|
||||
"Water"=>{
|
||||
force_can_collide=false;
|
||||
//TODO: read stupid CustomPhysicalProperties
|
||||
intersecting.water=Some(crate::model::IntersectingWater{density:Planar64::ONE,viscosity:Planar64::ONE/10,current:velocity});
|
||||
},
|
||||
"Accelerator"=>{
|
||||
//although the new game supports collidable accelerators, this is a roblox compatability map loader
|
||||
force_can_collide=false;
|
||||
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
||||
},
|
||||
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(velocity)),
|
||||
"MapFinish"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Finish})},
|
||||
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
|
||||
"Platform"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
||||
mode_id:0,
|
||||
stage_id:0,
|
||||
force:false,
|
||||
behaviour:crate::model::StageElementBehaviour::Platform,
|
||||
})),
|
||||
other=>{
|
||||
if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Spawn|SpawnAt|Trigger|Teleport|Platform)(\d+)$")
|
||||
.captures(other){
|
||||
general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
||||
mode_id:0,
|
||||
stage_id:captures[3].parse::<u32>().unwrap(),
|
||||
force:match captures.get(1){
|
||||
Some(m)=>m.as_str()=="Force",
|
||||
None=>false,
|
||||
},
|
||||
behaviour:match &captures[2]{
|
||||
"Spawn"|"SpawnAt"=>crate::model::StageElementBehaviour::SpawnAt,
|
||||
//cancollide false so you don't hit the side
|
||||
//NOT a decoration
|
||||
"Trigger"=>{force_can_collide=false;crate::model::StageElementBehaviour::Trigger},
|
||||
"Teleport"=>{force_can_collide=false;crate::model::StageElementBehaviour::Teleport},
|
||||
"Platform"=>crate::model::StageElementBehaviour::Platform,
|
||||
_=>panic!("regex1[2] messed up bad"),
|
||||
}
|
||||
}));
|
||||
}else if let Some(captures)=lazy_regex::regex!(r"^(Force)?(Jump)(\d+)$")
|
||||
.captures(other){
|
||||
general.teleport_behaviour=Some(crate::model::TeleportBehaviour::StageElement(crate::model::GameMechanicStageElement{
|
||||
mode_id:0,
|
||||
stage_id:0,
|
||||
force:match captures.get(1){
|
||||
Some(m)=>m.as_str()=="Force",
|
||||
None=>false,
|
||||
},
|
||||
behaviour:match &captures[2]{
|
||||
"Jump"=>crate::model::StageElementBehaviour::JumpLimit(captures[3].parse::<u32>().unwrap()),
|
||||
_=>panic!("regex4[1] messed up bad"),
|
||||
}
|
||||
}));
|
||||
}else if let Some(captures)=lazy_regex::regex!(r"^Bonus(Finish|Anticheat)(\d+)$")
|
||||
.captures(other){
|
||||
force_can_collide=false;
|
||||
match &captures[1]{
|
||||
"Finish"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Finish}),
|
||||
"Anticheat"=>general.zone=Some(crate::model::GameMechanicZone{mode_id:captures[2].parse::<u32>().unwrap(),behaviour:crate::model::ZoneBehaviour::Anitcheat}),
|
||||
_=>panic!("regex2[1] messed up bad"),
|
||||
}
|
||||
}else if let Some(captures)=lazy_regex::regex!(r"^(WormholeIn)(\d+)$")
|
||||
.captures(other){
|
||||
force_can_collide=false;
|
||||
match &captures[1]{
|
||||
"WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})),
|
||||
_=>panic!("regex3[1] messed up bad"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//need some way to skip this
|
||||
if velocity!=Planar64Vec3::ZERO{
|
||||
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
|
||||
}
|
||||
match force_can_collide{
|
||||
true=>{
|
||||
match name{
|
||||
"Bounce"=>contacting.contact_behaviour=Some(crate::model::ContactingBehaviour::Elastic(u32::MAX)),
|
||||
"Surf"=>contacting.contact_behaviour=Some(crate::model::ContactingBehaviour::Surf),
|
||||
"Ladder"=>contacting.contact_behaviour=Some(crate::model::ContactingBehaviour::Ladder(crate::model::ContactingLadder{sticky:true})),
|
||||
_=>(),
|
||||
}
|
||||
crate::model::CollisionAttributes::Contact{contacting,general}
|
||||
},
|
||||
false=>if force_intersecting
|
||||
||general.any()
|
||||
||intersecting.any()
|
||||
{
|
||||
crate::model::CollisionAttributes::Intersect{intersecting,general}
|
||||
}else{
|
||||
crate::model::CollisionAttributes::Decoration
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
struct RobloxAssetId(u64);
|
||||
struct RobloxAssetIdParseErr;
|
||||
impl std::str::FromStr for RobloxAssetId {
|
||||
type Err=RobloxAssetIdParseErr;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err>{
|
||||
let regman=lazy_regex::regex!(r"(\d+)$");
|
||||
if let Some(captures) = regman.captures(s) {
|
||||
if captures.len()==2{//captures[0] is all captures concatenated, and then each individual capture
|
||||
if let Ok(id) = captures[0].parse::<u64>() {
|
||||
return Ok(Self(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(RobloxAssetIdParseErr)
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy,PartialEq)]
|
||||
struct RobloxTextureTransform{
|
||||
offset_u:f32,
|
||||
offset_v:f32,
|
||||
scale_u:f32,
|
||||
scale_v:f32,
|
||||
}
|
||||
impl std::cmp::Eq for RobloxTextureTransform{}//????
|
||||
impl std::default::Default for RobloxTextureTransform{
|
||||
fn default() -> Self {
|
||||
Self{offset_u:0.0,offset_v:0.0,scale_u:1.0,scale_v:1.0}
|
||||
}
|
||||
}
|
||||
impl std::hash::Hash for RobloxTextureTransform {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.offset_u.to_ne_bytes().hash(state);
|
||||
self.offset_v.to_ne_bytes().hash(state);
|
||||
self.scale_u.to_ne_bytes().hash(state);
|
||||
self.scale_v.to_ne_bytes().hash(state);
|
||||
}
|
||||
}
|
||||
#[derive(Clone,PartialEq)]
|
||||
struct RobloxFaceTextureDescription{
|
||||
texture:u32,
|
||||
color:glam::Vec4,
|
||||
transform:RobloxTextureTransform,
|
||||
}
|
||||
impl std::cmp::Eq for RobloxFaceTextureDescription{}//????
|
||||
impl std::hash::Hash for RobloxFaceTextureDescription {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.texture.hash(state);
|
||||
self.transform.hash(state);
|
||||
for &el in self.color.as_ref().iter() {
|
||||
el.to_ne_bytes().hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl RobloxFaceTextureDescription{
|
||||
fn to_face_description(&self)->primitives::FaceDescription{
|
||||
primitives::FaceDescription{
|
||||
texture:Some(self.texture),
|
||||
transform:glam::Affine2::from_translation(
|
||||
glam::vec2(self.transform.offset_u,self.transform.offset_v)
|
||||
)
|
||||
*glam::Affine2::from_scale(
|
||||
glam::vec2(self.transform.scale_u,self.transform.scale_v)
|
||||
),
|
||||
color:self.color,
|
||||
}
|
||||
}
|
||||
}
|
||||
type RobloxPartDescription=[Option<RobloxFaceTextureDescription>;6];
|
||||
type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||
#[derive(Clone,Eq,Hash,PartialEq)]
|
||||
enum RobloxBasePartDescription{
|
||||
Sphere,
|
||||
Part(RobloxPartDescription),
|
||||
Cylinder,
|
||||
Wedge(RobloxWedgeDescription),
|
||||
CornerWedge(RobloxCornerWedgeDescription),
|
||||
}
|
||||
pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::IndexedModelInstances{
|
||||
//IndexedModelInstances includes textures
|
||||
let mut spawn_point=Planar64Vec3::ZERO;
|
||||
|
||||
let mut indexed_models=Vec::new();
|
||||
let mut model_id_from_description=std::collections::HashMap::<RobloxBasePartDescription,usize>::new();
|
||||
|
||||
let mut texture_id_from_asset_id=std::collections::HashMap::<u64,u32>::new();
|
||||
let mut asset_id_from_texture_id=Vec::new();
|
||||
|
||||
let mut object_refs=Vec::new();
|
||||
let mut temp_objects=Vec::new();
|
||||
recursive_collect_superclass(&mut object_refs, &dom, dom.root(),"BasePart");
|
||||
for object_ref in object_refs {
|
||||
if let Some(object)=dom.get_by_ref(object_ref){
|
||||
if let (
|
||||
Some(rbx_dom_weak::types::Variant::CFrame(cf)),
|
||||
Some(rbx_dom_weak::types::Variant::Vector3(size)),
|
||||
Some(rbx_dom_weak::types::Variant::Vector3(velocity)),
|
||||
Some(rbx_dom_weak::types::Variant::Float32(transparency)),
|
||||
Some(rbx_dom_weak::types::Variant::Color3uint8(color3)),
|
||||
Some(rbx_dom_weak::types::Variant::Bool(can_collide)),
|
||||
) = (
|
||||
object.properties.get("CFrame"),
|
||||
object.properties.get("Size"),
|
||||
object.properties.get("Velocity"),
|
||||
object.properties.get("Transparency"),
|
||||
object.properties.get("Color"),
|
||||
object.properties.get("CanCollide"),
|
||||
)
|
||||
{
|
||||
let model_transform=planar64_affine3_from_roblox(cf,size);
|
||||
|
||||
//push TempIndexedAttributes
|
||||
let mut force_intersecting=false;
|
||||
let mut temp_indexing_attributes=Vec::new();
|
||||
if let Some(attr)=match &object.name[..]{
|
||||
"MapStart"=>{
|
||||
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
||||
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
|
||||
},
|
||||
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint(crate::model::TempAttrUnorderedCheckpoint{mode_id:0})),
|
||||
other=>{
|
||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint|WormholeOut)(\d+)$");
|
||||
if let Some(captures) = regman.captures(other) {
|
||||
match &captures[1]{
|
||||
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
|
||||
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn(crate::model::TempAttrSpawn{mode_id:0,stage_id:captures[2].parse::<u32>().unwrap()})),
|
||||
"OrderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::OrderedCheckpoint(crate::model::TempAttrOrderedCheckpoint{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()})),
|
||||
"WormholeOut"=>Some(crate::model::TempIndexedAttributes::Wormhole(crate::model::TempAttrWormhole{wormhole_id:captures[2].parse::<u32>().unwrap()})),
|
||||
_=>None,
|
||||
}
|
||||
}else{
|
||||
None
|
||||
}
|
||||
}
|
||||
}{
|
||||
force_intersecting=true;
|
||||
temp_indexing_attributes.push(attr);
|
||||
}
|
||||
|
||||
//TODO: also detect "CylinderMesh" etc here
|
||||
let shape=match &object.class[..]{
|
||||
"Part"=>{
|
||||
if let Some(rbx_dom_weak::types::Variant::Enum(shape))=object.properties.get("Shape"){
|
||||
match shape.to_u32(){
|
||||
0=>primitives::Primitives::Sphere,
|
||||
1=>primitives::Primitives::Cube,
|
||||
2=>primitives::Primitives::Cylinder,
|
||||
3=>primitives::Primitives::Wedge,
|
||||
4=>primitives::Primitives::CornerWedge,
|
||||
_=>panic!("Funky roblox PartType={};",shape.to_u32()),
|
||||
}
|
||||
}else{
|
||||
panic!("Part has no Shape!");
|
||||
}
|
||||
},
|
||||
"WedgePart"=>primitives::Primitives::Wedge,
|
||||
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
|
||||
_=>{
|
||||
println!("Unsupported BasePart ClassName={}; defaulting to cube",object.class);
|
||||
primitives::Primitives::Cube
|
||||
}
|
||||
};
|
||||
|
||||
//use the biggest one and cut it down later...
|
||||
let mut part_texture_description:RobloxPartDescription=[None,None,None,None,None,None];
|
||||
temp_objects.clear();
|
||||
recursive_collect_superclass(&mut temp_objects, &dom, object,"Decal");
|
||||
for &decal_ref in &temp_objects{
|
||||
if let Some(decal)=dom.get_by_ref(decal_ref){
|
||||
if let (
|
||||
Some(rbx_dom_weak::types::Variant::Content(content)),
|
||||
Some(rbx_dom_weak::types::Variant::Enum(normalid)),
|
||||
Some(rbx_dom_weak::types::Variant::Color3(decal_color3)),
|
||||
Some(rbx_dom_weak::types::Variant::Float32(decal_transparency)),
|
||||
) = (
|
||||
decal.properties.get("Texture"),
|
||||
decal.properties.get("Face"),
|
||||
decal.properties.get("Color3"),
|
||||
decal.properties.get("Transparency"),
|
||||
) {
|
||||
if let Ok(asset_id)=content.clone().into_string().parse::<RobloxAssetId>(){
|
||||
let texture_id=if let Some(&texture_id)=texture_id_from_asset_id.get(&asset_id.0){
|
||||
texture_id
|
||||
}else{
|
||||
let texture_id=asset_id_from_texture_id.len() as u32;
|
||||
texture_id_from_asset_id.insert(asset_id.0,texture_id);
|
||||
asset_id_from_texture_id.push(asset_id.0);
|
||||
texture_id
|
||||
};
|
||||
let normal_id=normalid.to_u32();
|
||||
if normal_id<6{
|
||||
let (roblox_texture_color,roblox_texture_transform)=if decal.class=="Texture"{
|
||||
//generate tranform
|
||||
if let (
|
||||
Some(rbx_dom_weak::types::Variant::Float32(ox)),
|
||||
Some(rbx_dom_weak::types::Variant::Float32(oy)),
|
||||
Some(rbx_dom_weak::types::Variant::Float32(sx)),
|
||||
Some(rbx_dom_weak::types::Variant::Float32(sy)),
|
||||
) = (
|
||||
decal.properties.get("OffsetStudsU"),
|
||||
decal.properties.get("OffsetStudsV"),
|
||||
decal.properties.get("StudsPerTileU"),
|
||||
decal.properties.get("StudsPerTileV"),
|
||||
)
|
||||
{
|
||||
let (size_u,size_v)=match normal_id{
|
||||
0=>(size.z,size.y),//right
|
||||
1=>(size.x,size.z),//top
|
||||
2=>(size.x,size.y),//back
|
||||
3=>(size.z,size.y),//left
|
||||
4=>(size.x,size.z),//bottom
|
||||
5=>(size.x,size.y),//front
|
||||
_=>panic!("unreachable"),
|
||||
};
|
||||
(
|
||||
glam::vec4(decal_color3.r,decal_color3.g,decal_color3.b,1.0-*decal_transparency),
|
||||
RobloxTextureTransform{
|
||||
offset_u:*ox/(*sx),offset_v:*oy/(*sy),
|
||||
scale_u:size_u/(*sx),scale_v:size_v/(*sy),
|
||||
}
|
||||
)
|
||||
}else{
|
||||
(glam::Vec4::ONE,RobloxTextureTransform::default())
|
||||
}
|
||||
}else{
|
||||
(glam::Vec4::ONE,RobloxTextureTransform::default())
|
||||
};
|
||||
part_texture_description[normal_id as usize]=Some(RobloxFaceTextureDescription{
|
||||
texture:texture_id,
|
||||
color:roblox_texture_color,
|
||||
transform:roblox_texture_transform,
|
||||
});
|
||||
}else{
|
||||
println!("NormalId={} unsupported for shape={:?}",normal_id,shape);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//obscure rust syntax "slice pattern"
|
||||
let [
|
||||
f0,//Cube::Right
|
||||
f1,//Cube::Top
|
||||
f2,//Cube::Back
|
||||
f3,//Cube::Left
|
||||
f4,//Cube::Bottom
|
||||
f5,//Cube::Front
|
||||
]=part_texture_description;
|
||||
let basepart_texture_description=match shape{
|
||||
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
|
||||
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
|
||||
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
|
||||
//use front face texture first and use top face texture as a fallback
|
||||
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
||||
f0,//Cube::Right->Wedge::Right
|
||||
if f5.is_some(){f5}else{f1},//Cube::Front|Cube::Top->Wedge::TopFront
|
||||
f2,//Cube::Back->Wedge::Back
|
||||
f3,//Cube::Left->Wedge::Left
|
||||
f4,//Cube::Bottom->Wedge::Bottom
|
||||
]),
|
||||
//TODO: fix Left+Back texture coordinates to match roblox when not overwridden by Top
|
||||
primitives::Primitives::CornerWedge=>RobloxBasePartDescription::CornerWedge([
|
||||
f0,//Cube::Right->CornerWedge::Right
|
||||
if f2.is_some(){f2}else{f1.clone()},//Cube::Back|Cube::Top->CornerWedge::TopBack
|
||||
if f3.is_some(){f3}else{f1},//Cube::Left|Cube::Top->CornerWedge::TopLeft
|
||||
f4,//Cube::Bottom->CornerWedge::Bottom
|
||||
f5,//Cube::Front->CornerWedge::Front
|
||||
]),
|
||||
};
|
||||
//make new model if unit cube has not been created before
|
||||
let model_id=if let Some(&model_id)=model_id_from_description.get(&basepart_texture_description){
|
||||
//push to existing texture model
|
||||
model_id
|
||||
}else{
|
||||
let model_id=indexed_models.len();
|
||||
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
|
||||
indexed_models.push(match basepart_texture_description{
|
||||
RobloxBasePartDescription::Sphere=>primitives::unit_sphere(),
|
||||
RobloxBasePartDescription::Part(part_texture_description)=>{
|
||||
let mut cube_face_description=primitives::CubeFaceDescription::new();
|
||||
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
|
||||
cube_face_description.insert(
|
||||
match face_id{
|
||||
0=>primitives::CubeFace::Right,
|
||||
1=>primitives::CubeFace::Top,
|
||||
2=>primitives::CubeFace::Back,
|
||||
3=>primitives::CubeFace::Left,
|
||||
4=>primitives::CubeFace::Bottom,
|
||||
5=>primitives::CubeFace::Front,
|
||||
_=>panic!("unreachable"),
|
||||
},
|
||||
match roblox_face_description{
|
||||
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
|
||||
None=>primitives::FaceDescription::default(),
|
||||
});
|
||||
}
|
||||
primitives::generate_partial_unit_cube(cube_face_description)
|
||||
},
|
||||
RobloxBasePartDescription::Cylinder=>primitives::unit_cylinder(),
|
||||
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
|
||||
let mut wedge_face_description=primitives::WedgeFaceDescription::new();
|
||||
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
|
||||
wedge_face_description.insert(
|
||||
match face_id{
|
||||
0=>primitives::WedgeFace::Right,
|
||||
1=>primitives::WedgeFace::TopFront,
|
||||
2=>primitives::WedgeFace::Back,
|
||||
3=>primitives::WedgeFace::Left,
|
||||
4=>primitives::WedgeFace::Bottom,
|
||||
_=>panic!("unreachable"),
|
||||
},
|
||||
match roblox_face_description{
|
||||
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
|
||||
None=>primitives::FaceDescription::default(),
|
||||
});
|
||||
}
|
||||
primitives::generate_partial_unit_wedge(wedge_face_description)
|
||||
},
|
||||
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
|
||||
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::new();
|
||||
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
||||
cornerwedge_face_description.insert(
|
||||
match face_id{
|
||||
0=>primitives::CornerWedgeFace::Right,
|
||||
1=>primitives::CornerWedgeFace::TopBack,
|
||||
2=>primitives::CornerWedgeFace::TopLeft,
|
||||
3=>primitives::CornerWedgeFace::Bottom,
|
||||
4=>primitives::CornerWedgeFace::Front,
|
||||
_=>panic!("unreachable"),
|
||||
},
|
||||
match roblox_face_description{
|
||||
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
|
||||
None=>primitives::FaceDescription::default(),
|
||||
});
|
||||
}
|
||||
primitives::generate_partial_unit_cornerwedge(cornerwedge_face_description)
|
||||
},
|
||||
});
|
||||
model_id
|
||||
};
|
||||
indexed_models[model_id].instances.push(crate::model::ModelInstance {
|
||||
transform:model_transform,
|
||||
color:glam::vec4(color3.r as f32/255f32, color3.g as f32/255f32, color3.b as f32/255f32, 1.0-*transparency),
|
||||
attributes:get_attributes(&object.name,*can_collide,Planar64Vec3::try_from([velocity.x,velocity.y,velocity.z]).unwrap(),force_intersecting),
|
||||
temp_indexing:temp_indexing_attributes,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::model::IndexedModelInstances{
|
||||
textures:asset_id_from_texture_id.iter().map(|t|t.to_string()).collect(),
|
||||
models:indexed_models,
|
||||
spawn_point,
|
||||
modes:Vec::new(),
|
||||
}
|
||||
}
|
786
src/main.rs
786
src/main.rs
@ -1,684 +1,124 @@
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use strafe_client::{instruction::{TimedInstruction, InstructionConsumer},body::{InputInstruction, PhysicsInstruction}};
|
||||
use std::{borrow::Cow, time::Instant};
|
||||
use wgpu::{util::DeviceExt, AstcBlock, AstcChannel};
|
||||
mod bvh;
|
||||
mod aabb;
|
||||
mod model;
|
||||
mod setup;
|
||||
mod window;
|
||||
mod worker;
|
||||
mod zeroes;
|
||||
mod integer;
|
||||
mod physics;
|
||||
mod graphics;
|
||||
mod settings;
|
||||
mod primitives;
|
||||
mod instruction;
|
||||
mod load_roblox;
|
||||
mod compat_worker;
|
||||
mod model_graphics;
|
||||
mod physics_worker;
|
||||
mod graphics_worker;
|
||||
|
||||
const IMAGE_SIZE: u32 = 128;
|
||||
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
struct Vertex {
|
||||
pos: [f32; 3],
|
||||
texture: [f32; 2],
|
||||
normal: [f32; 3],
|
||||
}
|
||||
|
||||
struct Entity {
|
||||
index_count: u32,
|
||||
index_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
//temp?
|
||||
struct ModelData {
|
||||
transform: glam::Mat4,
|
||||
vertex_buf: wgpu::Buffer,
|
||||
entities: Vec<Entity>,
|
||||
}
|
||||
|
||||
struct ModelGraphics {
|
||||
transform: glam::Mat4,
|
||||
vertex_buf: wgpu::Buffer,
|
||||
entities: Vec<Entity>,
|
||||
bind_group: wgpu::BindGroup,
|
||||
model_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
pub struct Skybox {
|
||||
block_mouse:strafe_client::body::TIME,
|
||||
period:strafe_client::body::TIME,
|
||||
start_time: std::time::Instant,
|
||||
screen_size: (u32, u32),
|
||||
physics: strafe_client::body::PhysicsState,
|
||||
sky_pipeline: wgpu::RenderPipeline,
|
||||
entity_pipeline: wgpu::RenderPipeline,
|
||||
ground_pipeline: wgpu::RenderPipeline,
|
||||
main_bind_group: wgpu::BindGroup,
|
||||
camera_buf: wgpu::Buffer,
|
||||
models: Vec<ModelGraphics>,
|
||||
depth_view: wgpu::TextureView,
|
||||
staging_belt: wgpu::util::StagingBelt,
|
||||
}
|
||||
|
||||
impl Skybox {
|
||||
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24Plus;
|
||||
|
||||
fn create_depth_texture(
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
device: &wgpu::Device,
|
||||
) -> wgpu::TextureView {
|
||||
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
size: wgpu::Extent3d {
|
||||
width: config.width,
|
||||
height: config.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: Self::DEPTH_FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
label: None,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_transform_uniform_data(transform:&glam::Mat4) -> [f32; 4*4] {
|
||||
let mut raw = [0f32; 4*4];
|
||||
raw[0..16].copy_from_slice(&AsRef::<[f32; 4*4]>::as_ref(transform)[..]);
|
||||
raw
|
||||
}
|
||||
|
||||
fn add_obj(device:&wgpu::Device,modeldatas:& mut Vec<ModelData>,source:&[u8]){
|
||||
let data = obj::ObjData::load_buf(&source[..]).unwrap();
|
||||
let mut vertices = Vec::new();
|
||||
let mut vertex_index = std::collections::HashMap::<obj::IndexTuple,u16>::new();
|
||||
for object in data.objects {
|
||||
let mut entities = Vec::<Entity>::new();
|
||||
for group in object.groups {
|
||||
let mut indices = Vec::new();
|
||||
for poly in group.polys {
|
||||
for end_index in 2..poly.0.len() {
|
||||
for &index in &[0, end_index - 1, end_index] {
|
||||
let vert = poly.0[index];
|
||||
if let Some(&i)=vertex_index.get(&vert){
|
||||
indices.push(i);
|
||||
}else{
|
||||
let i=vertices.len() as u16;
|
||||
vertices.push(Vertex {
|
||||
pos: data.position[vert.0],
|
||||
texture: data.texture[vert.1.unwrap()],
|
||||
normal: data.normal[vert.2.unwrap()],
|
||||
});
|
||||
vertex_index.insert(vert,i);
|
||||
indices.push(i);
|
||||
}
|
||||
fn load_file(path: std::path::PathBuf)->Option<model::IndexedModelInstances>{
|
||||
println!("Loading file: {:?}", &path);
|
||||
//oh boy! let's load the map!
|
||||
if let Ok(file)=std::fs::File::open(path){
|
||||
let mut input = std::io::BufReader::new(file);
|
||||
let mut first_8=[0u8;8];
|
||||
//.rbxm roblox binary = "<roblox!"
|
||||
//.rbxmx roblox xml = "<roblox "
|
||||
//.bsp = "VBSP"
|
||||
//.vmf =
|
||||
//.snf = "SNMF"
|
||||
//.snf = "SNBF"
|
||||
if let (Ok(()),Ok(()))=(std::io::Read::read_exact(&mut input, &mut first_8),std::io::Seek::rewind(&mut input)){
|
||||
match &first_8[0..4]{
|
||||
b"<rob"=>{
|
||||
match match &first_8[4..8]{
|
||||
b"lox!"=>rbx_binary::from_reader(input).map_err(|e|format!("{:?}",e)),
|
||||
b"lox "=>rbx_xml::from_reader(input,rbx_xml::DecodeOptions::default()).map_err(|e|format!("{:?}",e)),
|
||||
other=>Err(format!("Unknown Roblox file type {:?}",other)),
|
||||
}{
|
||||
Ok(dom)=>Some(load_roblox::generate_indexed_models(dom)),
|
||||
Err(e)=>{
|
||||
println!("Error loading roblox file:{:?}",e);
|
||||
None
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
//b"VBSP"=>Some(load_bsp::generate_indexed_models(input)),
|
||||
//b"SNFM"=>Some(sniffer::generate_indexed_models(input)),
|
||||
//b"SNFB"=>Some(sniffer::load_bot(input)),
|
||||
other=>{
|
||||
println!("loser file {:?}",other);
|
||||
None
|
||||
},
|
||||
}
|
||||
let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Index"),
|
||||
contents: bytemuck::cast_slice(&indices),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
});
|
||||
entities.push(Entity {
|
||||
index_buf,
|
||||
index_count: indices.len() as u32,
|
||||
});
|
||||
}else{
|
||||
println!("Failed to read first 8 bytes and seek back to beginning of file.");
|
||||
None
|
||||
}
|
||||
let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Vertex"),
|
||||
contents: bytemuck::cast_slice(&vertices),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
modeldatas.push(ModelData {
|
||||
transform: glam::Mat4::default(),
|
||||
vertex_buf,
|
||||
entities,
|
||||
})
|
||||
}else{
|
||||
println!("Could not open file");
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn to_uniform_data(camera: &strafe_client::body::Camera, pos: glam::Vec3) -> [f32; 16 * 3 + 4] {
|
||||
let proj=camera.proj();
|
||||
let proj_inv = proj.inverse();
|
||||
let view=camera.view(pos);
|
||||
let view_inv = view.inverse();
|
||||
|
||||
let mut raw = [0f32; 16 * 3 + 4];
|
||||
raw[..16].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj)[..]);
|
||||
raw[16..32].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&proj_inv)[..]);
|
||||
raw[32..48].copy_from_slice(&AsRef::<[f32; 16]>::as_ref(&view_inv)[..]);
|
||||
raw[48..52].copy_from_slice(AsRef::<[f32; 4]>::as_ref(&view.col(3)));
|
||||
raw
|
||||
}
|
||||
|
||||
impl strafe_client::framework::Example for Skybox {
|
||||
fn optional_features() -> wgpu::Features {
|
||||
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||
| wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||
| wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||
}
|
||||
|
||||
fn init(
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
_adapter: &wgpu::Adapter,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
) -> Self {
|
||||
let mut modeldatas = Vec::<ModelData>::new();
|
||||
add_obj(device,& mut modeldatas,include_bytes!("../models/teslacyberv3.0.obj"));
|
||||
add_obj(device,& mut modeldatas,include_bytes!("../models/suzanne.obj"));
|
||||
add_obj(device,& mut modeldatas,include_bytes!("../models/teapot.obj"));
|
||||
println!("models.len = {:?}", modeldatas.len());
|
||||
modeldatas[1].transform=glam::Mat4::from_translation(glam::vec3(10.,5.,10.));
|
||||
modeldatas[2].transform=glam::Mat4::from_translation(glam::vec3(-10.,5.,10.));
|
||||
|
||||
let main_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::Cube,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let model_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Create the render pipeline
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||
});
|
||||
|
||||
let physics = strafe_client::body::PhysicsState {
|
||||
body: strafe_client::body::Body::with_pva(glam::vec3(0.0,50.0,0.0),glam::vec3(0.0,0.0,0.0),glam::vec3(0.0,-100.0,0.0)),
|
||||
time: 0,
|
||||
tick: 0,
|
||||
strafe_tick_num: 100,//100t
|
||||
strafe_tick_den: 1_000_000_000,
|
||||
gravity: glam::vec3(0.0,-100.0,0.0),
|
||||
friction: 1.2,
|
||||
walk_accel: 90.0,
|
||||
mv: 2.7,
|
||||
grounded: false,
|
||||
walkspeed: 18.0,
|
||||
contacts: std::collections::HashSet::new(),
|
||||
models_cringe_clone: modeldatas.iter().map(|m|strafe_client::body::Model::new(m.transform)).collect(),
|
||||
walk: strafe_client::body::WalkState::new(),
|
||||
hitbox_halfsize: glam::vec3(1.0,2.5,1.0),
|
||||
camera: strafe_client::body::Camera::from_offset(glam::vec3(0.0,4.5-2.5,0.0),(config.width as f32)/(config.height as f32)),
|
||||
mouse_interpolation: strafe_client::body::MouseInterpolationState::new(),
|
||||
controls: 0,
|
||||
};
|
||||
|
||||
let camera_uniforms = to_uniform_data(&physics.camera,physics.body.extrapolated_position(0));
|
||||
let camera_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Camera"),
|
||||
contents: bytemuck::cast_slice(&camera_uniforms),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
|
||||
//drain the modeldata vec so entities can be /moved/ to models.entities
|
||||
let mut models = Vec::<ModelGraphics>::with_capacity(modeldatas.len());
|
||||
for (i,modeldata) in modeldatas.drain(..).enumerate() {
|
||||
let model_uniforms = get_transform_uniform_data(&modeldata.transform);
|
||||
let model_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some(format!("ModelGraphics{}",i).as_str()),
|
||||
contents: bytemuck::cast_slice(&model_uniforms),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
let model_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &model_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: model_buf.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
label: Some(format!("ModelGraphics{}",i).as_str()),
|
||||
});
|
||||
//all of these are being moved here
|
||||
models.push(ModelGraphics{
|
||||
transform: modeldata.transform,
|
||||
vertex_buf:modeldata.vertex_buf,
|
||||
entities: modeldata.entities,
|
||||
bind_group: model_bind_group,
|
||||
model_buf,
|
||||
})
|
||||
}
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: None,
|
||||
bind_group_layouts: &[&main_bind_group_layout, &model_bind_group_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
// Create the render pipelines
|
||||
let sky_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Sky"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_sky",
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_sky",
|
||||
targets: &[Some(config.view_formats[0].into())],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
front_face: wgpu::FrontFace::Cw,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: Self::DEPTH_FORMAT,
|
||||
depth_write_enabled: false,
|
||||
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
});
|
||||
let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Entity"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_entity",
|
||||
buffers: &[wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32x3],
|
||||
}],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_entity",
|
||||
targets: &[Some(config.view_formats[0].into())],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
front_face: wgpu::FrontFace::Cw,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: Self::DEPTH_FORMAT,
|
||||
depth_write_enabled: true,
|
||||
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
});
|
||||
let ground_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Ground"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_ground",
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_ground",
|
||||
targets: &[Some(config.view_formats[0].into())],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
front_face: wgpu::FrontFace::Cw,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: Self::DEPTH_FORMAT,
|
||||
depth_write_enabled: true,
|
||||
depth_compare: wgpu::CompareFunction::LessEqual,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
});
|
||||
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: None,
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let device_features = device.features();
|
||||
|
||||
let skybox_format = if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC) {
|
||||
log::info!("Using ASTC");
|
||||
wgpu::TextureFormat::Astc {
|
||||
block: AstcBlock::B4x4,
|
||||
channel: AstcChannel::UnormSrgb,
|
||||
}
|
||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2) {
|
||||
log::info!("Using ETC2");
|
||||
wgpu::TextureFormat::Etc2Rgb8UnormSrgb
|
||||
} else if device_features.contains(wgpu::Features::TEXTURE_COMPRESSION_BC) {
|
||||
log::info!("Using BC");
|
||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb
|
||||
} else {
|
||||
log::info!("Using plain");
|
||||
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||
};
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width: IMAGE_SIZE,
|
||||
height: IMAGE_SIZE,
|
||||
depth_or_array_layers: 6,
|
||||
};
|
||||
|
||||
let layer_size = wgpu::Extent3d {
|
||||
depth_or_array_layers: 1,
|
||||
..size
|
||||
};
|
||||
let max_mips = layer_size.max_mips(wgpu::TextureDimension::D2);
|
||||
|
||||
log::debug!(
|
||||
"Copying {:?} skybox images of size {}, {}, 6 with {} mips to gpu",
|
||||
skybox_format,
|
||||
IMAGE_SIZE,
|
||||
IMAGE_SIZE,
|
||||
max_mips,
|
||||
);
|
||||
|
||||
let bytes = match skybox_format {
|
||||
wgpu::TextureFormat::Astc {
|
||||
block: AstcBlock::B4x4,
|
||||
channel: AstcChannel::UnormSrgb,
|
||||
} => &include_bytes!("../images/astc.dds")[..],
|
||||
wgpu::TextureFormat::Etc2Rgb8UnormSrgb => &include_bytes!("../images/etc2.dds")[..],
|
||||
wgpu::TextureFormat::Bc1RgbaUnormSrgb => &include_bytes!("../images/bc1.dds")[..],
|
||||
wgpu::TextureFormat::Bgra8UnormSrgb => &include_bytes!("../images/bgra.dds")[..],
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let image = ddsfile::Dds::read(&mut std::io::Cursor::new(&bytes)).unwrap();
|
||||
|
||||
let texture = device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
size,
|
||||
mip_level_count: max_mips,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: skybox_format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
label: None,
|
||||
view_formats: &[],
|
||||
},
|
||||
&image.data,
|
||||
);
|
||||
|
||||
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
label: None,
|
||||
dimension: Some(wgpu::TextureViewDimension::Cube),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
});
|
||||
let main_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &main_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: camera_buf.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
],
|
||||
label: Some("Camera"),
|
||||
});
|
||||
|
||||
let depth_view = Self::create_depth_texture(config, device);
|
||||
|
||||
Skybox {
|
||||
block_mouse:0,
|
||||
period:5_000_000,
|
||||
start_time: Instant::now(),
|
||||
screen_size: (config.width,config.height),
|
||||
physics,
|
||||
sky_pipeline,
|
||||
entity_pipeline,
|
||||
ground_pipeline,
|
||||
main_bind_group,
|
||||
camera_buf,
|
||||
models,
|
||||
depth_view,
|
||||
staging_belt: wgpu::util::StagingBelt::new(0x100),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::single_match)]
|
||||
fn update(&mut self, event: winit::event::WindowEvent) {
|
||||
//nothing atm
|
||||
}
|
||||
|
||||
fn device_event(&mut self, event: winit::event::DeviceEvent) {
|
||||
//there's no way this is the best way get a timestamp.
|
||||
let time=self.start_time.elapsed().as_nanos() as i64;
|
||||
match event {
|
||||
winit::event::DeviceEvent::Key(winit::event::KeyboardInput {
|
||||
state,
|
||||
scancode: keycode,
|
||||
..
|
||||
}) => {
|
||||
let s=match state {
|
||||
winit::event::ElementState::Pressed => true,
|
||||
winit::event::ElementState::Released => false,
|
||||
};
|
||||
if let Some(input_instruction)=match keycode {
|
||||
17 => Some(InputInstruction::MoveForward(s)),//W
|
||||
30 => Some(InputInstruction::MoveLeft(s)),//A
|
||||
31 => Some(InputInstruction::MoveBack(s)),//S
|
||||
32 => Some(InputInstruction::MoveRight(s)),//D
|
||||
18 => Some(InputInstruction::MoveUp(s)),//E
|
||||
16 => Some(InputInstruction::MoveDown(s)),//Q
|
||||
57 => Some(InputInstruction::Jump(s)),//Space
|
||||
44 => Some(InputInstruction::Zoom(s)),//Z
|
||||
19 => if s{Some(InputInstruction::Reset)}else{None},//R
|
||||
_ => None,
|
||||
}
|
||||
{
|
||||
self.physics.run(time);//call it a day
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(input_instruction),
|
||||
})
|
||||
}
|
||||
},
|
||||
winit::event::DeviceEvent::MouseMotion {
|
||||
delta,//these (f64,f64) are integers on my machine
|
||||
} => {
|
||||
let run_the_physics=
|
||||
if time<self.block_mouse{
|
||||
false
|
||||
}else{
|
||||
if time-self.block_mouse<2*self.period{
|
||||
self.block_mouse+=self.period
|
||||
}else{
|
||||
self.block_mouse=time+self.period
|
||||
}
|
||||
true
|
||||
};
|
||||
if run_the_physics{
|
||||
//This lags like crazy if you require a substep for every mouse event (every 3ms)
|
||||
//I'm going to forgo mouse interpolation for now
|
||||
//because it's actually a hard problem to prevent the physics from running on every mouse update
|
||||
self.physics.run(time);//call it a day
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(InputInstruction::MoveMouse(glam::ivec2(delta.0 as i32,delta.1 as i32))),
|
||||
})
|
||||
}
|
||||
},
|
||||
winit::event::DeviceEvent::MouseWheel {
|
||||
delta,
|
||||
} => {
|
||||
println!("mousewheel{:?}",delta);
|
||||
if true{//self.physics.use_scroll
|
||||
self.physics.run(time);//call it a day
|
||||
self.physics.process_instruction(TimedInstruction{
|
||||
time,
|
||||
instruction:PhysicsInstruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||
})
|
||||
}
|
||||
}
|
||||
_=>(),
|
||||
}
|
||||
}
|
||||
|
||||
fn resize(
|
||||
&mut self,
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
device: &wgpu::Device,
|
||||
_queue: &wgpu::Queue,
|
||||
) {
|
||||
self.depth_view = Self::create_depth_texture(config, device);
|
||||
self.screen_size = (config.width, config.height);
|
||||
self.physics.camera.set_fov_aspect(1.0,(config.width as f32)/(config.height as f32));
|
||||
}
|
||||
|
||||
fn render(
|
||||
&mut self,
|
||||
view: &wgpu::TextureView,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
_spawner: &strafe_client::framework::Spawner,
|
||||
) {
|
||||
let time=self.start_time.elapsed().as_nanos() as i64;
|
||||
|
||||
self.physics.run(time);
|
||||
|
||||
let mut encoder =
|
||||
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||
|
||||
// update rotation
|
||||
let camera_uniforms = to_uniform_data(&self.physics.camera,self.physics.body.extrapolated_position(time));
|
||||
self.staging_belt
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
&self.camera_buf,
|
||||
0,
|
||||
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||
device,
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||
//This code only needs to run when the uniforms change
|
||||
for model in self.models.iter() {
|
||||
let model_uniforms = get_transform_uniform_data(&model.transform);
|
||||
self.staging_belt
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
&model.model_buf,//description of where data will be written when command is executed
|
||||
0,//offset in staging belt?
|
||||
wgpu::BufferSize::new((model_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||
device,
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&model_uniforms));
|
||||
}
|
||||
self.staging_belt.finish();
|
||||
|
||||
{
|
||||
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: None,
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
}),
|
||||
store: true,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: false,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
});
|
||||
|
||||
rpass.set_bind_group(0, &self.main_bind_group, &[]);
|
||||
|
||||
rpass.set_pipeline(&self.entity_pipeline);
|
||||
for model in self.models.iter() {
|
||||
rpass.set_bind_group(1, &model.bind_group, &[]);
|
||||
rpass.set_vertex_buffer(0, model.vertex_buf.slice(..));
|
||||
|
||||
for entity in model.entities.iter() {
|
||||
rpass.set_index_buffer(entity.index_buf.slice(..), wgpu::IndexFormat::Uint16);
|
||||
rpass.draw_indexed(0..entity.index_count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
rpass.set_pipeline(&self.ground_pipeline);
|
||||
//rpass.set_index_buffer(&[0u16,1,2,1,2,3][..] as wgpu::BufferSlice, wgpu::IndexFormat::Uint16);
|
||||
//rpass.draw_indexed(0..4, 0, 0..1);
|
||||
rpass.draw(0..6, 0..1);
|
||||
|
||||
rpass.set_pipeline(&self.sky_pipeline);
|
||||
rpass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
self.staging_belt.recall();
|
||||
pub fn default_models()->model::IndexedModelInstances{
|
||||
let mut indexed_models = Vec::new();
|
||||
indexed_models.append(&mut model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teslacyberv3.0.obj")[..]).unwrap(),glam::Vec4::ONE));
|
||||
indexed_models.push(primitives::unit_sphere());
|
||||
indexed_models.push(primitives::unit_cylinder());
|
||||
indexed_models.push(primitives::unit_cube());
|
||||
println!("models.len = {:?}", indexed_models.len());
|
||||
indexed_models[0].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(10.,0.,-10.))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
//quad monkeys
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(10.,5.,10.))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(20.,5.,10.))).unwrap(),
|
||||
color:glam::vec4(1.0,0.0,0.0,1.0),
|
||||
..Default::default()
|
||||
});
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(10.,5.,20.))).unwrap(),
|
||||
color:glam::vec4(0.0,1.0,0.0,1.0),
|
||||
..Default::default()
|
||||
});
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(20.,5.,20.))).unwrap(),
|
||||
color:glam::vec4(0.0,0.0,1.0,1.0),
|
||||
..Default::default()
|
||||
});
|
||||
//decorative monkey
|
||||
indexed_models[1].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(15.,10.,15.))).unwrap(),
|
||||
color:glam::vec4(0.5,0.5,0.5,0.5),
|
||||
attributes:model::CollisionAttributes::Decoration,
|
||||
..Default::default()
|
||||
});
|
||||
//teapot
|
||||
indexed_models[2].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_scale_rotation_translation(glam::vec3(0.5, 1.0, 0.2),glam::quat(-0.22248298016985793,-0.839457167990537,-0.05603504040830783,-0.49261857546227916),glam::vec3(-10.,7.,10.))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
//ground
|
||||
indexed_models[3].instances.push(model::ModelInstance{
|
||||
transform:integer::Planar64Affine3::try_from(glam::Affine3A::from_translation(glam::vec3(0.,0.,0.))*glam::Affine3A::from_scale(glam::vec3(160.0, 1.0, 160.0))).unwrap(),
|
||||
..Default::default()
|
||||
});
|
||||
model::IndexedModelInstances{
|
||||
textures:Vec::new(),
|
||||
models:indexed_models,
|
||||
spawn_point:integer::Planar64Vec3::Y*50,
|
||||
modes:Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
strafe_client::framework::run::<Skybox>(
|
||||
format!("Strafe Client v{}",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
).as_str()
|
||||
);
|
||||
fn main(){
|
||||
let context=setup::setup(format!("Strafe Client v{}",env!("CARGO_PKG_VERSION")).as_str());
|
||||
context.start();//creates and runs a window context
|
||||
}
|
||||
|
294
src/model.rs
Normal file
294
src/model.rs
Normal file
@ -0,0 +1,294 @@
|
||||
use crate::integer::{Time,Planar64,Planar64Vec3,Planar64Affine3};
|
||||
pub type TextureCoordinate=glam::Vec2;
|
||||
pub type Color4=glam::Vec4;
|
||||
#[derive(Clone,Hash,PartialEq,Eq)]
|
||||
pub struct IndexedVertex{
|
||||
pub pos:u32,
|
||||
pub tex:u32,
|
||||
pub normal:u32,
|
||||
pub color:u32,
|
||||
}
|
||||
pub struct IndexedPolygon{
|
||||
pub vertices:Vec<u32>,
|
||||
}
|
||||
pub struct IndexedGroup{
|
||||
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
||||
pub polys:Vec<IndexedPolygon>,
|
||||
}
|
||||
pub struct IndexedModel{
|
||||
pub unique_pos:Vec<Planar64Vec3>,
|
||||
pub unique_normal:Vec<Planar64Vec3>,
|
||||
pub unique_tex:Vec<TextureCoordinate>,
|
||||
pub unique_color:Vec<Color4>,
|
||||
pub unique_vertices:Vec<IndexedVertex>,
|
||||
pub groups: Vec<IndexedGroup>,
|
||||
pub instances:Vec<ModelInstance>,
|
||||
}
|
||||
pub struct ModelInstance{
|
||||
//pub id:u64,//this does not actually help with map fixes resimulating bots, they must always be resimulated
|
||||
pub transform:Planar64Affine3,
|
||||
pub color:Color4,//transparency is in here
|
||||
pub attributes:CollisionAttributes,
|
||||
pub temp_indexing:Vec<TempIndexedAttributes>,
|
||||
}
|
||||
impl std::default::Default for ModelInstance{
|
||||
fn default() -> Self {
|
||||
Self{
|
||||
color:Color4::ONE,
|
||||
transform:Default::default(),
|
||||
attributes:Default::default(),
|
||||
temp_indexing:Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct IndexedModelInstances{
|
||||
pub textures:Vec<String>,//RenderPattern
|
||||
pub models:Vec<IndexedModel>,
|
||||
//may make this into an object later.
|
||||
pub modes:Vec<ModeDescription>,
|
||||
pub spawn_point:Planar64Vec3,
|
||||
}
|
||||
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
||||
pub struct ModeDescription{
|
||||
pub start:usize,//start=model_id
|
||||
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
|
||||
pub ordered_checkpoints:Vec<usize>,//ordered_checkpoints[checkpoint_id]=model_id
|
||||
pub unordered_checkpoints:Vec<usize>,//unordered_checkpoints[checkpoint_id]=model_id
|
||||
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
||||
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
||||
}
|
||||
impl ModeDescription{
|
||||
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
|
||||
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
|
||||
}
|
||||
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&usize>{
|
||||
self.ordered_checkpoints.get(*self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id)?)
|
||||
}
|
||||
}
|
||||
//I don't want this code to exist!
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrStart{
|
||||
pub mode_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrSpawn{
|
||||
pub mode_id:u32,
|
||||
pub stage_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrOrderedCheckpoint{
|
||||
pub mode_id:u32,
|
||||
pub checkpoint_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrUnorderedCheckpoint{
|
||||
pub mode_id:u32,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct TempAttrWormhole{
|
||||
pub wormhole_id:u32,
|
||||
}
|
||||
pub enum TempIndexedAttributes{
|
||||
Start(TempAttrStart),
|
||||
Spawn(TempAttrSpawn),
|
||||
OrderedCheckpoint(TempAttrOrderedCheckpoint),
|
||||
UnorderedCheckpoint(TempAttrUnorderedCheckpoint),
|
||||
Wormhole(TempAttrWormhole),
|
||||
}
|
||||
|
||||
//you have this effect while in contact
|
||||
#[derive(Clone)]
|
||||
pub struct ContactingLadder{
|
||||
pub sticky:bool
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum ContactingBehaviour{
|
||||
Surf,
|
||||
Ladder(ContactingLadder),
|
||||
Elastic(u32),//[1/2^32,1] 0=None (elasticity+1)/2^32
|
||||
}
|
||||
//you have this effect while intersecting
|
||||
#[derive(Clone)]
|
||||
pub struct IntersectingWater{
|
||||
pub viscosity:Planar64,
|
||||
pub density:Planar64,
|
||||
pub current:Planar64Vec3,
|
||||
}
|
||||
//All models can be given these attributes
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicAccelerator{
|
||||
pub acceleration:Planar64Vec3
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum GameMechanicBooster{
|
||||
Affine(Planar64Affine3),//capable of SetVelocity,DotVelocity,normal booster,bouncy part,redirect velocity, and much more
|
||||
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
|
||||
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum TrajectoryChoice{
|
||||
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
||||
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum GameMechanicSetTrajectory{
|
||||
AirTime(Time),//air time (relative to gravity direction) is invariant across mass and gravity changes
|
||||
Height(Planar64),//boost height (relative to gravity direction) is invariant across mass and gravity changes
|
||||
TargetPointTime{//launch on a trajectory that will land at a target point in a set amount of time
|
||||
target_point:Planar64Vec3,
|
||||
time:Time,//short time = fast and direct, long time = launch high in the air, negative time = wrong way
|
||||
},
|
||||
TrajectoryTargetPoint{//launch at a fixed speed and land at a target point
|
||||
target_point:Planar64Vec3,
|
||||
speed:Planar64,//if speed is too low this will fail to reach the target. The closest-passing trajectory will be chosen instead
|
||||
trajectory_choice:TrajectoryChoice,
|
||||
},
|
||||
Velocity(Planar64Vec3),//SetVelocity
|
||||
DotVelocity{direction:Planar64Vec3,dot:Planar64},//set your velocity in a specific direction without touching other directions
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum ZoneBehaviour{
|
||||
//Start is indexed
|
||||
//Checkpoints are indexed
|
||||
Finish,
|
||||
Anitcheat,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicZone{
|
||||
pub mode_id:u32,
|
||||
pub behaviour:ZoneBehaviour,
|
||||
}
|
||||
// enum TrapCondition{
|
||||
// FasterThan(Planar64),
|
||||
// SlowerThan(Planar64),
|
||||
// InRange(Planar64,Planar64),
|
||||
// OutsideRange(Planar64,Planar64),
|
||||
// }
|
||||
#[derive(Clone)]
|
||||
pub enum StageElementBehaviour{
|
||||
//Spawn,//The behaviour of stepping on a spawn setting the spawnid
|
||||
SpawnAt,
|
||||
Trigger,
|
||||
Teleport,
|
||||
Platform,
|
||||
JumpLimit(u32),
|
||||
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicStageElement{
|
||||
pub mode_id:u32,
|
||||
pub stage_id:u32,//which spawn to send to
|
||||
pub force:bool,//allow setting to lower spawn id i.e. 7->3
|
||||
pub behaviour:StageElementBehaviour
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct GameMechanicWormhole{
|
||||
//destination does not need to be another wormhole
|
||||
//this defines a one way portal to a destination model transform
|
||||
//two of these can create a two way wormhole
|
||||
pub destination_model_id:u32,
|
||||
//(position,angles)*=origin.transform.inverse()*destination.transform
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum TeleportBehaviour{
|
||||
StageElement(GameMechanicStageElement),
|
||||
Wormhole(GameMechanicWormhole),
|
||||
}
|
||||
//attributes listed in order of handling
|
||||
#[derive(Default,Clone)]
|
||||
pub struct GameMechanicAttributes{
|
||||
pub zone:Option<GameMechanicZone>,
|
||||
pub booster:Option<GameMechanicBooster>,
|
||||
pub trajectory:Option<GameMechanicSetTrajectory>,
|
||||
pub teleport_behaviour:Option<TeleportBehaviour>,
|
||||
pub accelerator:Option<GameMechanicAccelerator>,
|
||||
}
|
||||
impl GameMechanicAttributes{
|
||||
pub fn any(&self)->bool{
|
||||
self.booster.is_some()
|
||||
||self.trajectory.is_some()
|
||||
||self.zone.is_some()
|
||||
||self.teleport_behaviour.is_some()
|
||||
||self.accelerator.is_some()
|
||||
}
|
||||
}
|
||||
#[derive(Default,Clone)]
|
||||
pub struct ContactingAttributes{
|
||||
//friction?
|
||||
pub contact_behaviour:Option<ContactingBehaviour>,
|
||||
}
|
||||
impl ContactingAttributes{
|
||||
pub fn any(&self)->bool{
|
||||
self.contact_behaviour.is_some()
|
||||
}
|
||||
}
|
||||
#[derive(Default,Clone)]
|
||||
pub struct IntersectingAttributes{
|
||||
pub water:Option<IntersectingWater>,
|
||||
}
|
||||
impl IntersectingAttributes{
|
||||
pub fn any(&self)->bool{
|
||||
self.water.is_some()
|
||||
}
|
||||
}
|
||||
//Spawn(u32) NO! spawns are indexed in the map header instead of marked with attibutes
|
||||
pub enum CollisionAttributes{
|
||||
Decoration,//visual only
|
||||
Contact{//track whether you are contacting the object
|
||||
contacting:ContactingAttributes,
|
||||
general:GameMechanicAttributes,
|
||||
},
|
||||
Intersect{//track whether you are intersecting the object
|
||||
intersecting:IntersectingAttributes,
|
||||
general:GameMechanicAttributes,
|
||||
},
|
||||
}
|
||||
impl std::default::Default for CollisionAttributes{
|
||||
fn default() -> Self {
|
||||
Self::Contact{
|
||||
contacting:ContactingAttributes::default(),
|
||||
general:GameMechanicAttributes::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_indexed_model_list_from_obj(data:obj::ObjData,color:Color4)->Vec<IndexedModel>{
|
||||
let mut unique_vertex_index = std::collections::HashMap::<obj::IndexTuple,u32>::new();
|
||||
return data.objects.iter().map(|object|{
|
||||
unique_vertex_index.clear();
|
||||
let mut unique_vertices = Vec::new();
|
||||
let groups = object.groups.iter().map(|group|{
|
||||
IndexedGroup{
|
||||
texture:None,
|
||||
polys:group.polys.iter().map(|poly|{
|
||||
IndexedPolygon{
|
||||
vertices:poly.0.iter().map(|&tup|{
|
||||
if let Some(&i)=unique_vertex_index.get(&tup){
|
||||
i
|
||||
}else{
|
||||
let i=unique_vertices.len() as u32;
|
||||
unique_vertices.push(IndexedVertex{
|
||||
pos: tup.0 as u32,
|
||||
tex: tup.1.unwrap() as u32,
|
||||
normal: tup.2.unwrap() as u32,
|
||||
color: 0,
|
||||
});
|
||||
unique_vertex_index.insert(tup,i);
|
||||
i
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
}).collect();
|
||||
IndexedModel{
|
||||
unique_pos: data.position.iter().map(|&v|Planar64Vec3::try_from(v).unwrap()).collect(),
|
||||
unique_tex: data.texture.iter().map(|&v|TextureCoordinate::from_array(v)).collect(),
|
||||
unique_normal: data.normal.iter().map(|&v|Planar64Vec3::try_from(v).unwrap()).collect(),
|
||||
unique_color: vec![color],
|
||||
unique_vertices,
|
||||
groups,
|
||||
instances:Vec::new(),
|
||||
}
|
||||
}).collect()
|
||||
}
|
55
src/model_graphics.rs
Normal file
55
src/model_graphics.rs
Normal file
@ -0,0 +1,55 @@
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use crate::model::{IndexedVertex,IndexedPolygon};
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
#[repr(C)]
|
||||
pub struct GraphicsVertex {
|
||||
pub pos: [f32; 3],
|
||||
pub tex: [f32; 2],
|
||||
pub normal: [f32; 3],
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
pub struct IndexedGroupFixedTexture{
|
||||
pub polys:Vec<IndexedPolygon>,
|
||||
}
|
||||
pub struct IndexedModelGraphicsSingleTexture{
|
||||
pub unique_pos:Vec<[f32; 3]>,
|
||||
pub unique_tex:Vec<[f32; 2]>,
|
||||
pub unique_normal:Vec<[f32; 3]>,
|
||||
pub unique_color:Vec<[f32; 4]>,
|
||||
pub unique_vertices:Vec<IndexedVertex>,
|
||||
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
||||
pub groups: Vec<IndexedGroupFixedTexture>,
|
||||
pub instances:Vec<ModelGraphicsInstance>,
|
||||
}
|
||||
pub struct ModelGraphicsSingleTexture{
|
||||
pub instances: Vec<ModelGraphicsInstance>,
|
||||
pub vertices: Vec<GraphicsVertex>,
|
||||
pub entities: Vec<Vec<u16>>,
|
||||
pub texture: Option<u32>,
|
||||
}
|
||||
#[derive(Clone,PartialEq)]
|
||||
pub struct ModelGraphicsColor4(glam::Vec4);
|
||||
impl ModelGraphicsColor4{
|
||||
pub const fn get(&self)->glam::Vec4{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl From<glam::Vec4> for ModelGraphicsColor4{
|
||||
fn from(value:glam::Vec4)->Self{
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl std::hash::Hash for ModelGraphicsColor4{
|
||||
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
||||
for &f in self.0.as_ref(){
|
||||
bytemuck::cast::<f32,u32>(f).hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Eq for ModelGraphicsColor4{}
|
||||
#[derive(Clone)]
|
||||
pub struct ModelGraphicsInstance{
|
||||
pub transform:glam::Mat4,
|
||||
pub normal_transform:glam::Mat3,
|
||||
pub color:ModelGraphicsColor4,
|
||||
}
|
1
src/model_physics.rs
Normal file
1
src/model_physics.rs
Normal file
@ -0,0 +1 @@
|
||||
//
|
1524
src/physics.rs
Normal file
1524
src/physics.rs
Normal file
File diff suppressed because it is too large
Load Diff
133
src/physics_worker.rs
Normal file
133
src/physics_worker.rs
Normal file
@ -0,0 +1,133 @@
|
||||
use crate::integer::Time;
|
||||
use crate::physics::{MouseState,PhysicsInputInstruction};
|
||||
use crate::instruction::{TimedInstruction,InstructionConsumer};
|
||||
#[derive(Debug)]
|
||||
pub enum InputInstruction {
|
||||
MoveMouse(glam::IVec2),
|
||||
MoveRight(bool),
|
||||
MoveUp(bool),
|
||||
MoveBack(bool),
|
||||
MoveLeft(bool),
|
||||
MoveDown(bool),
|
||||
MoveForward(bool),
|
||||
Jump(bool),
|
||||
Zoom(bool),
|
||||
Reset,
|
||||
}
|
||||
pub enum Instruction{
|
||||
Input(InputInstruction),
|
||||
Render,
|
||||
Resize(winit::dpi::PhysicalSize<u32>,crate::settings::UserSettings),
|
||||
GenerateModels(crate::model::IndexedModelInstances),
|
||||
ClearModels,
|
||||
//Graphics(crate::graphics_worker::Instruction),
|
||||
}
|
||||
|
||||
pub fn new(mut physics:crate::physics::PhysicsState,mut graphics_worker:crate::compat_worker::INWorker<crate::graphics_worker::Instruction>)->crate::compat_worker::QNWorker<TimedInstruction<Instruction>>{
|
||||
let mut mouse_blocking=true;
|
||||
let mut last_mouse_time=physics.next_mouse.time;
|
||||
let mut timeline=std::collections::VecDeque::new();
|
||||
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<Instruction>|{
|
||||
if if let Some(phys_input)=match &ins.instruction{
|
||||
Instruction::Input(input_instruction)=>match input_instruction{
|
||||
&InputInstruction::MoveMouse(m)=>{
|
||||
if mouse_blocking{
|
||||
//tell the game state which is living in the past about its future
|
||||
timeline.push_front(TimedInstruction{
|
||||
time:last_mouse_time,
|
||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:m}),
|
||||
});
|
||||
}else{
|
||||
//mouse has just started moving again after being still for longer than 10ms.
|
||||
//replace the entire mouse interpolation state to avoid an intermediate state with identical m0.t m1.t timestamps which will divide by zero
|
||||
timeline.push_front(TimedInstruction{
|
||||
time:last_mouse_time,
|
||||
instruction:PhysicsInputInstruction::ReplaceMouse(
|
||||
MouseState{time:last_mouse_time,pos:physics.next_mouse.pos},
|
||||
MouseState{time:ins.time,pos:m}
|
||||
),
|
||||
});
|
||||
//delay physics execution until we have an interpolation target
|
||||
mouse_blocking=true;
|
||||
}
|
||||
last_mouse_time=ins.time;
|
||||
None
|
||||
},
|
||||
&InputInstruction::MoveForward(s)=>Some(PhysicsInputInstruction::SetMoveForward(s)),
|
||||
&InputInstruction::MoveLeft(s)=>Some(PhysicsInputInstruction::SetMoveLeft(s)),
|
||||
&InputInstruction::MoveBack(s)=>Some(PhysicsInputInstruction::SetMoveBack(s)),
|
||||
&InputInstruction::MoveRight(s)=>Some(PhysicsInputInstruction::SetMoveRight(s)),
|
||||
&InputInstruction::MoveUp(s)=>Some(PhysicsInputInstruction::SetMoveUp(s)),
|
||||
&InputInstruction::MoveDown(s)=>Some(PhysicsInputInstruction::SetMoveDown(s)),
|
||||
&InputInstruction::Jump(s)=>Some(PhysicsInputInstruction::SetJump(s)),
|
||||
&InputInstruction::Zoom(s)=>Some(PhysicsInputInstruction::SetZoom(s)),
|
||||
InputInstruction::Reset=>Some(PhysicsInputInstruction::Reset),
|
||||
},
|
||||
Instruction::GenerateModels(_)=>Some(PhysicsInputInstruction::Idle),
|
||||
Instruction::ClearModels=>Some(PhysicsInputInstruction::Idle),
|
||||
Instruction::Resize(_,_)=>Some(PhysicsInputInstruction::Idle),
|
||||
Instruction::Render=>Some(PhysicsInputInstruction::Idle),
|
||||
}{
|
||||
//non-mouse event
|
||||
timeline.push_back(TimedInstruction{
|
||||
time:ins.time,
|
||||
instruction:phys_input,
|
||||
});
|
||||
|
||||
if mouse_blocking{
|
||||
//assume the mouse has stopped moving after 10ms.
|
||||
//shitty mice are 125Hz which is 8ms so this should cover that.
|
||||
//setting this to 100us still doesn't print even though it's 10x lower than the polling rate,
|
||||
//so mouse events are probably not handled separately from drawing and fire right before it :(
|
||||
if Time::from_millis(10)<ins.time-physics.next_mouse.time{
|
||||
//push an event to extrapolate no movement from
|
||||
timeline.push_front(TimedInstruction{
|
||||
time:last_mouse_time,
|
||||
instruction:PhysicsInputInstruction::SetNextMouse(MouseState{time:ins.time,pos:physics.next_mouse.pos}),
|
||||
});
|
||||
last_mouse_time=ins.time;
|
||||
//stop blocking. the mouse is not moving so the physics does not need to live in the past and wait for interpolation targets.
|
||||
mouse_blocking=false;
|
||||
true
|
||||
}else{
|
||||
false
|
||||
}
|
||||
}else{
|
||||
//keep this up to date so that it can be used as a known-timestamp
|
||||
//that the mouse was not moving when the mouse starts moving again
|
||||
last_mouse_time=ins.time;
|
||||
true
|
||||
}
|
||||
}else{
|
||||
//mouse event
|
||||
true
|
||||
}{
|
||||
//empty queue
|
||||
while let Some(instruction)=timeline.pop_front(){
|
||||
physics.run(instruction.time);
|
||||
physics.process_instruction(TimedInstruction{
|
||||
time:instruction.time,
|
||||
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
|
||||
});
|
||||
}
|
||||
}
|
||||
match ins.instruction{
|
||||
Instruction::Render=>{
|
||||
graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos)).unwrap();
|
||||
},
|
||||
Instruction::Resize(size,user_settings)=>{
|
||||
graphics_worker.send(crate::graphics_worker::Instruction::Resize(size,user_settings)).unwrap();
|
||||
},
|
||||
Instruction::GenerateModels(indexed_model_instances)=>{
|
||||
physics.generate_models(&indexed_model_instances);
|
||||
physics.spawn(indexed_model_instances.spawn_point);
|
||||
graphics_worker.send(crate::graphics_worker::Instruction::GenerateModels(indexed_model_instances)).unwrap();
|
||||
},
|
||||
Instruction::ClearModels=>{
|
||||
physics.clear();
|
||||
graphics_worker.send(crate::graphics_worker::Instruction::ClearModels).unwrap();
|
||||
},
|
||||
_=>(),
|
||||
}
|
||||
})
|
||||
}
|
510
src/primitives.rs
Normal file
510
src/primitives.rs
Normal file
@ -0,0 +1,510 @@
|
||||
use crate::model::{Color4,TextureCoordinate,IndexedModel,IndexedPolygon,IndexedGroup,IndexedVertex};
|
||||
use crate::integer::Planar64Vec3;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Primitives{
|
||||
Sphere,
|
||||
Cube,
|
||||
Cylinder,
|
||||
Wedge,
|
||||
CornerWedge,
|
||||
}
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
pub enum CubeFace{
|
||||
Right,
|
||||
Top,
|
||||
Back,
|
||||
Left,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
const CUBE_DEFAULT_TEXTURE_COORDS:[TextureCoordinate;4]=[
|
||||
TextureCoordinate::new(0.0,0.0),
|
||||
TextureCoordinate::new(1.0,0.0),
|
||||
TextureCoordinate::new(1.0,1.0),
|
||||
TextureCoordinate::new(0.0,1.0),
|
||||
];
|
||||
const CUBE_DEFAULT_VERTICES:[Planar64Vec3;8]=[
|
||||
Planar64Vec3::int(-1,-1, 1),//0 left bottom back
|
||||
Planar64Vec3::int( 1,-1, 1),//1 right bottom back
|
||||
Planar64Vec3::int( 1, 1, 1),//2 right top back
|
||||
Planar64Vec3::int(-1, 1, 1),//3 left top back
|
||||
Planar64Vec3::int(-1, 1,-1),//4 left top front
|
||||
Planar64Vec3::int( 1, 1,-1),//5 right top front
|
||||
Planar64Vec3::int( 1,-1,-1),//6 right bottom front
|
||||
Planar64Vec3::int(-1,-1,-1),//7 left bottom front
|
||||
];
|
||||
const CUBE_DEFAULT_NORMALS:[Planar64Vec3;6]=[
|
||||
Planar64Vec3::int( 1, 0, 0),//CubeFace::Right
|
||||
Planar64Vec3::int( 0, 1, 0),//CubeFace::Top
|
||||
Planar64Vec3::int( 0, 0, 1),//CubeFace::Back
|
||||
Planar64Vec3::int(-1, 0, 0),//CubeFace::Left
|
||||
Planar64Vec3::int( 0,-1, 0),//CubeFace::Bottom
|
||||
Planar64Vec3::int( 0, 0,-1),//CubeFace::Front
|
||||
];
|
||||
const CUBE_DEFAULT_POLYS:[[[u32;3];4];6]=[
|
||||
// right (1, 0, 0)
|
||||
[
|
||||
[6,2,0],//[vertex,tex,norm]
|
||||
[5,1,0],
|
||||
[2,0,0],
|
||||
[1,3,0],
|
||||
],
|
||||
// top (0, 1, 0)
|
||||
[
|
||||
[5,3,1],
|
||||
[4,2,1],
|
||||
[3,1,1],
|
||||
[2,0,1],
|
||||
],
|
||||
// back (0, 0, 1)
|
||||
[
|
||||
[0,3,2],
|
||||
[1,2,2],
|
||||
[2,1,2],
|
||||
[3,0,2],
|
||||
],
|
||||
// left (-1, 0, 0)
|
||||
[
|
||||
[0,2,3],
|
||||
[3,1,3],
|
||||
[4,0,3],
|
||||
[7,3,3],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
[
|
||||
[1,1,4],
|
||||
[0,0,4],
|
||||
[7,3,4],
|
||||
[6,2,4],
|
||||
],
|
||||
// front (0, 0,-1)
|
||||
[
|
||||
[4,1,5],
|
||||
[5,0,5],
|
||||
[6,3,5],
|
||||
[7,2,5],
|
||||
],
|
||||
];
|
||||
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
pub enum WedgeFace{
|
||||
Right,
|
||||
TopFront,
|
||||
Back,
|
||||
Left,
|
||||
Bottom,
|
||||
}
|
||||
const WEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
Planar64Vec3::int( 1, 0, 0),//Wedge::Right
|
||||
Planar64Vec3::int( 0, 1,-1),//Wedge::TopFront
|
||||
Planar64Vec3::int( 0, 0, 1),//Wedge::Back
|
||||
Planar64Vec3::int(-1, 0, 0),//Wedge::Left
|
||||
Planar64Vec3::int( 0,-1, 0),//Wedge::Bottom
|
||||
];
|
||||
/*
|
||||
local cornerWedgeVerticies = {
|
||||
Vector3.new(-1/2,-1/2,-1/2),7
|
||||
Vector3.new(-1/2,-1/2, 1/2),0
|
||||
Vector3.new( 1/2,-1/2,-1/2),6
|
||||
Vector3.new( 1/2,-1/2, 1/2),1
|
||||
Vector3.new( 1/2, 1/2,-1/2),5
|
||||
}
|
||||
*/
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
pub enum CornerWedgeFace{
|
||||
Right,
|
||||
TopBack,
|
||||
TopLeft,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
Planar64Vec3::int( 1, 0, 0),//CornerWedge::Right
|
||||
Planar64Vec3::int( 0, 1, 1),//CornerWedge::BackTop
|
||||
Planar64Vec3::int(-1, 1, 0),//CornerWedge::LeftTop
|
||||
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
||||
Planar64Vec3::int( 0, 0,-1),//CornerWedge::Front
|
||||
];
|
||||
//HashMap fits this use case perfectly but feels like using a sledgehammer to drive a nail
|
||||
pub fn unit_sphere()->crate::model::IndexedModel{
|
||||
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/suzanne.obj")[..]).unwrap(),Color4::ONE).remove(0);
|
||||
for pos in indexed_model.unique_pos.iter_mut(){
|
||||
*pos=*pos/2;
|
||||
}
|
||||
indexed_model
|
||||
}
|
||||
pub type CubeFaceDescription=std::collections::HashMap::<CubeFace,FaceDescription>;
|
||||
pub fn unit_cube()->crate::model::IndexedModel{
|
||||
let mut t=CubeFaceDescription::new();
|
||||
t.insert(CubeFace::Right,FaceDescription::default());
|
||||
t.insert(CubeFace::Top,FaceDescription::default());
|
||||
t.insert(CubeFace::Back,FaceDescription::default());
|
||||
t.insert(CubeFace::Left,FaceDescription::default());
|
||||
t.insert(CubeFace::Bottom,FaceDescription::default());
|
||||
t.insert(CubeFace::Front,FaceDescription::default());
|
||||
generate_partial_unit_cube(t)
|
||||
}
|
||||
const TEAPOT_TRANSFORM:crate::integer::Planar64Mat3=crate::integer::Planar64Mat3::int_from_cols_array([0,1,0, -1,0,0, 0,0,1]);
|
||||
pub fn unit_cylinder()->crate::model::IndexedModel{
|
||||
let mut indexed_model=crate::model::generate_indexed_model_list_from_obj(obj::ObjData::load_buf(&include_bytes!("../models/teapot.obj")[..]).unwrap(),Color4::ONE).remove(0);
|
||||
for pos in indexed_model.unique_pos.iter_mut(){
|
||||
*pos=TEAPOT_TRANSFORM*(*pos)/10;
|
||||
}
|
||||
indexed_model
|
||||
}
|
||||
pub type WedgeFaceDescription=std::collections::HashMap::<WedgeFace,FaceDescription>;
|
||||
pub fn unit_wedge()->crate::model::IndexedModel{
|
||||
let mut t=WedgeFaceDescription::new();
|
||||
t.insert(WedgeFace::Right,FaceDescription::default());
|
||||
t.insert(WedgeFace::TopFront,FaceDescription::default());
|
||||
t.insert(WedgeFace::Back,FaceDescription::default());
|
||||
t.insert(WedgeFace::Left,FaceDescription::default());
|
||||
t.insert(WedgeFace::Bottom,FaceDescription::default());
|
||||
generate_partial_unit_wedge(t)
|
||||
}
|
||||
pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,FaceDescription>;
|
||||
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
||||
let mut t=CornerWedgeFaceDescription::new();
|
||||
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::Bottom,FaceDescription::default());
|
||||
t.insert(CornerWedgeFace::Front,FaceDescription::default());
|
||||
generate_partial_unit_cornerwedge(t)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FaceDescription{
|
||||
pub texture:Option<u32>,
|
||||
pub transform:glam::Affine2,
|
||||
pub color:Color4,
|
||||
}
|
||||
impl std::default::Default for FaceDescription{
|
||||
fn default()->Self {
|
||||
Self{
|
||||
texture:None,
|
||||
transform:glam::Affine2::IDENTITY,
|
||||
color:Color4::new(1.0,1.0,1.0,0.0),//zero alpha to hide the default texture
|
||||
}
|
||||
}
|
||||
}
|
||||
impl FaceDescription{
|
||||
pub fn new(texture:u32,transform:glam::Affine2,color:Color4)->Self{
|
||||
Self{texture:Some(texture),transform,color}
|
||||
}
|
||||
pub fn from_texture(texture:u32)->Self{
|
||||
Self{
|
||||
texture:Some(texture),
|
||||
transform:glam::Affine2::IDENTITY,
|
||||
color:Color4::ONE,
|
||||
}
|
||||
}
|
||||
}
|
||||
//TODO: it's probably better to use a shared vertex buffer between all primitives and use indexed rendering instead of generating a unique vertex buffer for each primitive.
|
||||
//implementation: put all roblox primitives into one model.groups <- this won't work but I forget why
|
||||
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate::model::IndexedModel{
|
||||
let mut generated_pos=Vec::new();
|
||||
let mut generated_tex=Vec::new();
|
||||
let mut generated_normal=Vec::new();
|
||||
let mut generated_color=Vec::new();
|
||||
let mut generated_vertices=Vec::new();
|
||||
let mut groups=Vec::new();
|
||||
let mut transforms=Vec::new();
|
||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||
for (face,face_description) in face_descriptions.into_iter(){
|
||||
//assume that scanning short lists is faster than hashing.
|
||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||
transform_index
|
||||
}else{
|
||||
//create new transform_index
|
||||
let transform_index=transforms.len();
|
||||
transforms.push(face_description.transform);
|
||||
for tex in CUBE_DEFAULT_TEXTURE_COORDS{
|
||||
generated_tex.push(face_description.transform.transform_point2(tex));
|
||||
}
|
||||
transform_index
|
||||
} as u32;
|
||||
let color_index=if let Some(color_index)=generated_color.iter().position(|&color|color==face_description.color){
|
||||
color_index
|
||||
}else{
|
||||
//create new color_index
|
||||
let color_index=generated_color.len();
|
||||
generated_color.push(face_description.color);
|
||||
color_index
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
CubeFace::Right => 0,
|
||||
CubeFace::Top => 1,
|
||||
CubeFace::Back => 2,
|
||||
CubeFace::Left => 3,
|
||||
CubeFace::Bottom => 4,
|
||||
CubeFace::Front => 5,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
|
||||
//push vertices as they are needed
|
||||
groups.push(IndexedGroup{
|
||||
texture:face_description.texture,
|
||||
polys:vec![IndexedPolygon{
|
||||
vertices:CUBE_DEFAULT_POLYS[face_id].map(|tup|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
|
||||
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
|
||||
pos_index
|
||||
}else{
|
||||
//create new pos_index
|
||||
let pos_index=generated_pos.len();
|
||||
generated_pos.push(pos);
|
||||
pos_index
|
||||
} as u32;
|
||||
//always push vertex
|
||||
let vertex=IndexedVertex{
|
||||
pos:pos_index,
|
||||
tex:tup[1]+4*transform_index,
|
||||
normal:normal_index,
|
||||
color:color_index,
|
||||
};
|
||||
let vert_index=generated_vertices.len();
|
||||
generated_vertices.push(vertex);
|
||||
vert_index as u32
|
||||
}).to_vec(),
|
||||
}],
|
||||
});
|
||||
}
|
||||
IndexedModel{
|
||||
unique_pos:generated_pos,
|
||||
unique_tex:generated_tex,
|
||||
unique_normal:generated_normal,
|
||||
unique_color:generated_color,
|
||||
unique_vertices:generated_vertices,
|
||||
groups,
|
||||
instances:Vec::new(),
|
||||
}
|
||||
}
|
||||
//don't think too hard about the copy paste because this is all going into the map tool eventually...
|
||||
pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crate::model::IndexedModel{
|
||||
let wedge_default_polys=vec![
|
||||
// right (1, 0, 0)
|
||||
vec![
|
||||
[6,2,0],//[vertex,tex,norm]
|
||||
[2,0,0],
|
||||
[1,3,0],
|
||||
],
|
||||
// FrontTop (0, 1, -1)
|
||||
vec![
|
||||
[3,1,1],
|
||||
[2,0,1],
|
||||
[6,3,1],
|
||||
[7,2,1],
|
||||
],
|
||||
// back (0, 0, 1)
|
||||
vec![
|
||||
[0,3,2],
|
||||
[1,2,2],
|
||||
[2,1,2],
|
||||
[3,0,2],
|
||||
],
|
||||
// left (-1, 0, 0)
|
||||
vec![
|
||||
[0,2,3],
|
||||
[3,1,3],
|
||||
[7,3,3],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
vec![
|
||||
[1,1,4],
|
||||
[0,0,4],
|
||||
[7,3,4],
|
||||
[6,2,4],
|
||||
],
|
||||
];
|
||||
let mut generated_pos=Vec::new();
|
||||
let mut generated_tex=Vec::new();
|
||||
let mut generated_normal=Vec::new();
|
||||
let mut generated_color=Vec::new();
|
||||
let mut generated_vertices=Vec::new();
|
||||
let mut groups=Vec::new();
|
||||
let mut transforms=Vec::new();
|
||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||
for (face,face_description) in face_descriptions.into_iter(){
|
||||
//assume that scanning short lists is faster than hashing.
|
||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||
transform_index
|
||||
}else{
|
||||
//create new transform_index
|
||||
let transform_index=transforms.len();
|
||||
transforms.push(face_description.transform);
|
||||
for tex in CUBE_DEFAULT_TEXTURE_COORDS{
|
||||
generated_tex.push(face_description.transform.transform_point2(tex));
|
||||
}
|
||||
transform_index
|
||||
} as u32;
|
||||
let color_index=if let Some(color_index)=generated_color.iter().position(|&color|color==face_description.color){
|
||||
color_index
|
||||
}else{
|
||||
//create new color_index
|
||||
let color_index=generated_color.len();
|
||||
generated_color.push(face_description.color);
|
||||
color_index
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
WedgeFace::Right => 0,
|
||||
WedgeFace::TopFront => 1,
|
||||
WedgeFace::Back => 2,
|
||||
WedgeFace::Left => 3,
|
||||
WedgeFace::Bottom => 4,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
|
||||
//push vertices as they are needed
|
||||
groups.push(IndexedGroup{
|
||||
texture:face_description.texture,
|
||||
polys:vec![IndexedPolygon{
|
||||
vertices:wedge_default_polys[face_id].iter().map(|tup|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
|
||||
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
|
||||
pos_index
|
||||
}else{
|
||||
//create new pos_index
|
||||
let pos_index=generated_pos.len();
|
||||
generated_pos.push(pos);
|
||||
pos_index
|
||||
} as u32;
|
||||
//always push vertex
|
||||
let vertex=IndexedVertex{
|
||||
pos:pos_index,
|
||||
tex:tup[1]+4*transform_index,
|
||||
normal:normal_index,
|
||||
color:color_index,
|
||||
};
|
||||
let vert_index=generated_vertices.len();
|
||||
generated_vertices.push(vertex);
|
||||
vert_index as u32
|
||||
}).collect(),
|
||||
}],
|
||||
});
|
||||
}
|
||||
IndexedModel{
|
||||
unique_pos:generated_pos,
|
||||
unique_tex:generated_tex,
|
||||
unique_normal:generated_normal,
|
||||
unique_color:generated_color,
|
||||
unique_vertices:generated_vertices,
|
||||
groups,
|
||||
instances:Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescription)->crate::model::IndexedModel{
|
||||
let cornerwedge_default_polys=vec![
|
||||
// right (1, 0, 0)
|
||||
vec![
|
||||
[6,2,0],//[vertex,tex,norm]
|
||||
[5,1,0],
|
||||
[1,3,0],
|
||||
],
|
||||
// BackTop (0, 1, 1)
|
||||
vec![
|
||||
[5,3,1],
|
||||
[0,1,1],
|
||||
[1,0,1],
|
||||
],
|
||||
// LeftTop (-1, 1, 0)
|
||||
vec![
|
||||
[5,3,2],
|
||||
[7,2,2],
|
||||
[0,1,2],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
vec![
|
||||
[1,1,3],
|
||||
[0,0,3],
|
||||
[7,3,3],
|
||||
[6,2,3],
|
||||
],
|
||||
// front (0, 0,-1)
|
||||
vec![
|
||||
[5,0,4],
|
||||
[6,3,4],
|
||||
[7,2,4],
|
||||
],
|
||||
];
|
||||
let mut generated_pos=Vec::new();
|
||||
let mut generated_tex=Vec::new();
|
||||
let mut generated_normal=Vec::new();
|
||||
let mut generated_color=Vec::new();
|
||||
let mut generated_vertices=Vec::new();
|
||||
let mut groups=Vec::new();
|
||||
let mut transforms=Vec::new();
|
||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||
for (face,face_description) in face_descriptions.into_iter(){
|
||||
//assume that scanning short lists is faster than hashing.
|
||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||
transform_index
|
||||
}else{
|
||||
//create new transform_index
|
||||
let transform_index=transforms.len();
|
||||
transforms.push(face_description.transform);
|
||||
for tex in CUBE_DEFAULT_TEXTURE_COORDS{
|
||||
generated_tex.push(face_description.transform.transform_point2(tex));
|
||||
}
|
||||
transform_index
|
||||
} as u32;
|
||||
let color_index=if let Some(color_index)=generated_color.iter().position(|&color|color==face_description.color){
|
||||
color_index
|
||||
}else{
|
||||
//create new color_index
|
||||
let color_index=generated_color.len();
|
||||
generated_color.push(face_description.color);
|
||||
color_index
|
||||
} as u32;
|
||||
let face_id=match face{
|
||||
CornerWedgeFace::Right => 0,
|
||||
CornerWedgeFace::TopBack => 1,
|
||||
CornerWedgeFace::TopLeft => 2,
|
||||
CornerWedgeFace::Bottom => 3,
|
||||
CornerWedgeFace::Front => 4,
|
||||
};
|
||||
//always push normal
|
||||
let normal_index=generated_normal.len() as u32;
|
||||
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
|
||||
//push vertices as they are needed
|
||||
groups.push(IndexedGroup{
|
||||
texture:face_description.texture,
|
||||
polys:vec![IndexedPolygon{
|
||||
vertices:cornerwedge_default_polys[face_id].iter().map(|tup|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
|
||||
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
|
||||
pos_index
|
||||
}else{
|
||||
//create new pos_index
|
||||
let pos_index=generated_pos.len();
|
||||
generated_pos.push(pos);
|
||||
pos_index
|
||||
} as u32;
|
||||
//always push vertex
|
||||
let vertex=IndexedVertex{
|
||||
pos:pos_index,
|
||||
tex:tup[1]+4*transform_index,
|
||||
normal:normal_index,
|
||||
color:color_index,
|
||||
};
|
||||
let vert_index=generated_vertices.len();
|
||||
generated_vertices.push(vertex);
|
||||
vert_index as u32
|
||||
}).collect(),
|
||||
}],
|
||||
});
|
||||
}
|
||||
IndexedModel{
|
||||
unique_pos:generated_pos,
|
||||
unique_tex:generated_tex,
|
||||
unique_normal:generated_normal,
|
||||
unique_color:generated_color,
|
||||
unique_vertices:generated_vertices,
|
||||
groups,
|
||||
instances:Vec::new(),
|
||||
}
|
||||
}
|
139
src/settings.rs
Normal file
139
src/settings.rs
Normal file
@ -0,0 +1,139 @@
|
||||
use crate::integer::{Ratio64,Ratio64Vec2};
|
||||
#[derive(Clone)]
|
||||
struct Ratio{
|
||||
ratio:f64,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
enum DerivedFov{
|
||||
FromScreenAspect,
|
||||
FromAspect(Ratio),
|
||||
}
|
||||
#[derive(Clone)]
|
||||
enum Fov{
|
||||
Exactly{x:f64,y:f64},
|
||||
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
||||
SpecifyYDeriveX{x:DerivedFov,y:f64},
|
||||
}
|
||||
impl Default for Fov{
|
||||
fn default()->Self{
|
||||
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
enum DerivedSensitivity{
|
||||
FromRatio(Ratio64),
|
||||
}
|
||||
#[derive(Clone)]
|
||||
enum Sensitivity{
|
||||
Exactly{x:Ratio64,y:Ratio64},
|
||||
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
||||
SpecifyYDeriveX{x:DerivedSensitivity,y:Ratio64},
|
||||
}
|
||||
impl Default for Sensitivity{
|
||||
fn default()->Self{
|
||||
Sensitivity::SpecifyXDeriveY{x:Ratio64::ONE*524288,y:DerivedSensitivity::FromRatio(Ratio64::ONE)}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default,Clone)]
|
||||
pub struct UserSettings{
|
||||
fov:Fov,
|
||||
sensitivity:Sensitivity,
|
||||
}
|
||||
impl UserSettings{
|
||||
pub fn calculate_fov(&self,zoom:f64,screen_size:&glam::UVec2)->glam::DVec2{
|
||||
zoom*match &self.fov{
|
||||
&Fov::Exactly{x,y}=>glam::dvec2(x,y),
|
||||
Fov::SpecifyXDeriveY{x,y}=>match y{
|
||||
DerivedFov::FromScreenAspect=>glam::dvec2(*x,x*(screen_size.y as f64/screen_size.x as f64)),
|
||||
DerivedFov::FromAspect(ratio)=>glam::dvec2(*x,x*ratio.ratio),
|
||||
},
|
||||
Fov::SpecifyYDeriveX{x,y}=>match x{
|
||||
DerivedFov::FromScreenAspect=>glam::dvec2(y*(screen_size.x as f64/screen_size.y as f64),*y),
|
||||
DerivedFov::FromAspect(ratio)=>glam::dvec2(y*ratio.ratio,*y),
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn calculate_sensitivity(&self)->Ratio64Vec2{
|
||||
match &self.sensitivity{
|
||||
Sensitivity::Exactly{x,y}=>Ratio64Vec2::new(x.clone(),y.clone()),
|
||||
Sensitivity::SpecifyXDeriveY{x,y}=>match y{
|
||||
DerivedSensitivity::FromRatio(ratio)=>Ratio64Vec2::new(x.clone(),x.mul_ref(ratio)),
|
||||
}
|
||||
Sensitivity::SpecifyYDeriveX{x,y}=>match x{
|
||||
DerivedSensitivity::FromRatio(ratio)=>Ratio64Vec2::new(y.mul_ref(ratio),y.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
//sensitivity is raw input dots (i.e. dpi = dots per inch) to radians conversion factor
|
||||
sensitivity_x=0.001
|
||||
sensitivity_y_from_x_ratio=1
|
||||
Sensitivity::DeriveY{x:0.0.001,y:DerivedSensitivity{ratio:1.0}}
|
||||
*/
|
||||
|
||||
pub fn read_user_settings()->UserSettings{
|
||||
let mut cfg=configparser::ini::Ini::new();
|
||||
if let Ok(_)=cfg.load("settings.conf"){
|
||||
let (cfg_fov_x,cfg_fov_y)=(cfg.getfloat("camera","fov_x"),cfg.getfloat("camera","fov_y"));
|
||||
let fov=match(cfg_fov_x,cfg_fov_y){
|
||||
(Ok(Some(fov_x)),Ok(Some(fov_y)))=>Fov::Exactly {
|
||||
x:fov_x,
|
||||
y:fov_y
|
||||
},
|
||||
(Ok(Some(fov_x)),Ok(None))=>Fov::SpecifyXDeriveY{
|
||||
x:fov_x,
|
||||
y:if let Ok(Some(fov_y_from_x_ratio))=cfg.getfloat("camera","fov_y_from_x_ratio"){
|
||||
DerivedFov::FromAspect(Ratio{ratio:fov_y_from_x_ratio})
|
||||
}else{
|
||||
DerivedFov::FromScreenAspect
|
||||
}
|
||||
},
|
||||
(Ok(None),Ok(Some(fov_y)))=>Fov::SpecifyYDeriveX{
|
||||
x:if let Ok(Some(fov_x_from_y_ratio))=cfg.getfloat("camera","fov_x_from_y_ratio"){
|
||||
DerivedFov::FromAspect(Ratio{ratio:fov_x_from_y_ratio})
|
||||
}else{
|
||||
DerivedFov::FromScreenAspect
|
||||
},
|
||||
y:fov_y,
|
||||
},
|
||||
_=>{
|
||||
Fov::default()
|
||||
},
|
||||
};
|
||||
let (cfg_sensitivity_x,cfg_sensitivity_y)=(cfg.getfloat("camera","sensitivity_x"),cfg.getfloat("camera","sensitivity_y"));
|
||||
let sensitivity=match(cfg_sensitivity_x,cfg_sensitivity_y){
|
||||
(Ok(Some(sensitivity_x)),Ok(Some(sensitivity_y)))=>Sensitivity::Exactly {
|
||||
x:Ratio64::try_from(sensitivity_x).unwrap(),
|
||||
y:Ratio64::try_from(sensitivity_y).unwrap(),
|
||||
},
|
||||
(Ok(Some(sensitivity_x)),Ok(None))=>Sensitivity::SpecifyXDeriveY{
|
||||
x:Ratio64::try_from(sensitivity_x).unwrap(),
|
||||
y:if let Ok(Some(sensitivity_y_from_x_ratio))=cfg.getfloat("camera","sensitivity_y_from_x_ratio"){
|
||||
DerivedSensitivity::FromRatio(Ratio64::try_from(sensitivity_y_from_x_ratio).unwrap())
|
||||
}else{
|
||||
DerivedSensitivity::FromRatio(Ratio64::ONE)
|
||||
},
|
||||
},
|
||||
(Ok(None),Ok(Some(sensitivity_y)))=>Sensitivity::SpecifyYDeriveX{
|
||||
x:if let Ok(Some(sensitivity_x_from_y_ratio))=cfg.getfloat("camera","sensitivity_x_from_y_ratio"){
|
||||
DerivedSensitivity::FromRatio(Ratio64::try_from(sensitivity_x_from_y_ratio).unwrap())
|
||||
}else{
|
||||
DerivedSensitivity::FromRatio(Ratio64::ONE)
|
||||
},
|
||||
y:Ratio64::try_from(sensitivity_y).unwrap(),
|
||||
},
|
||||
_=>{
|
||||
Sensitivity::default()
|
||||
},
|
||||
};
|
||||
UserSettings{
|
||||
fov,
|
||||
sensitivity,
|
||||
}
|
||||
}else{
|
||||
UserSettings::default()
|
||||
}
|
||||
}
|
301
src/setup.rs
Normal file
301
src/setup.rs
Normal file
@ -0,0 +1,301 @@
|
||||
use crate::instruction::TimedInstruction;
|
||||
use crate::window::WindowInstruction;
|
||||
|
||||
fn optional_features()->wgpu::Features{
|
||||
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||
|wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||
}
|
||||
fn required_features()->wgpu::Features{
|
||||
wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||
}
|
||||
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
|
||||
wgpu::DownlevelCapabilities{
|
||||
flags:wgpu::DownlevelFlags::empty(),
|
||||
shader_model:wgpu::ShaderModel::Sm5,
|
||||
..wgpu::DownlevelCapabilities::default()
|
||||
}
|
||||
}
|
||||
pub fn required_limits()->wgpu::Limits{
|
||||
wgpu::Limits::default()
|
||||
}
|
||||
|
||||
struct SetupContextPartial1{
|
||||
backends:wgpu::Backends,
|
||||
instance:wgpu::Instance,
|
||||
}
|
||||
fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
|
||||
let mut builder = winit::window::WindowBuilder::new();
|
||||
builder = builder.with_title(title);
|
||||
#[cfg(windows_OFF)] // TODO
|
||||
{
|
||||
use winit::platform::windows::WindowBuilderExtWindows;
|
||||
builder = builder.with_no_redirection_bitmap(true);
|
||||
}
|
||||
builder.build(event_loop)
|
||||
}
|
||||
fn create_instance()->SetupContextPartial1{
|
||||
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();
|
||||
SetupContextPartial1{
|
||||
backends,
|
||||
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
|
||||
backends,
|
||||
dx12_shader_compiler,
|
||||
}),
|
||||
}
|
||||
}
|
||||
impl SetupContextPartial1{
|
||||
fn create_surface(self,window:&winit::window::Window)->Result<SetupContextPartial2,wgpu::CreateSurfaceError>{
|
||||
Ok(SetupContextPartial2{
|
||||
backends:self.backends,
|
||||
surface:unsafe{self.instance.create_surface(window)}?,
|
||||
instance:self.instance,
|
||||
})
|
||||
}
|
||||
}
|
||||
struct SetupContextPartial2{
|
||||
backends:wgpu::Backends,
|
||||
instance:wgpu::Instance,
|
||||
surface:wgpu::Surface,
|
||||
}
|
||||
impl SetupContextPartial2{
|
||||
fn pick_adapter(self)->SetupContextPartial3{
|
||||
let adapter;
|
||||
|
||||
//TODO: prefer adapter that implements optional features
|
||||
//let optional_features=optional_features();
|
||||
let required_features=required_features();
|
||||
|
||||
//no helper function smh gotta write it myself
|
||||
let adapters=self.instance.enumerate_adapters(self.backends);
|
||||
|
||||
let mut chosen_adapter=None;
|
||||
let mut chosen_adapter_score=0;
|
||||
for adapter in adapters {
|
||||
if !adapter.is_surface_supported(&self.surface) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let score=match adapter.get_info().device_type{
|
||||
wgpu::DeviceType::IntegratedGpu=>3,
|
||||
wgpu::DeviceType::DiscreteGpu=>4,
|
||||
wgpu::DeviceType::VirtualGpu=>2,
|
||||
wgpu::DeviceType::Other|wgpu::DeviceType::Cpu=>1,
|
||||
};
|
||||
|
||||
let adapter_features=adapter.features();
|
||||
if chosen_adapter_score<score&&adapter_features.contains(required_features) {
|
||||
chosen_adapter_score=score;
|
||||
chosen_adapter=Some(adapter);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(maybe_chosen_adapter)=chosen_adapter{
|
||||
adapter=maybe_chosen_adapter;
|
||||
}else{
|
||||
panic!("No suitable GPU adapters found on the system!");
|
||||
}
|
||||
|
||||
|
||||
let adapter_info=adapter.get_info();
|
||||
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
||||
|
||||
let required_downlevel_capabilities=required_downlevel_capabilities();
|
||||
let downlevel_capabilities=adapter.get_downlevel_capabilities();
|
||||
assert!(
|
||||
downlevel_capabilities.shader_model >= required_downlevel_capabilities.shader_model,
|
||||
"Adapter does not support the minimum shader model required to run this example: {:?}",
|
||||
required_downlevel_capabilities.shader_model
|
||||
);
|
||||
assert!(
|
||||
downlevel_capabilities
|
||||
.flags
|
||||
.contains(required_downlevel_capabilities.flags),
|
||||
"Adapter does not support the downlevel capabilities required to run this example: {:?}",
|
||||
required_downlevel_capabilities.flags - downlevel_capabilities.flags
|
||||
);
|
||||
SetupContextPartial3{
|
||||
instance:self.instance,
|
||||
surface:self.surface,
|
||||
adapter,
|
||||
}
|
||||
}
|
||||
}
|
||||
struct SetupContextPartial3{
|
||||
instance:wgpu::Instance,
|
||||
surface:wgpu::Surface,
|
||||
adapter:wgpu::Adapter,
|
||||
}
|
||||
impl SetupContextPartial3{
|
||||
fn request_device(self)->SetupContextPartial4{
|
||||
let optional_features=optional_features();
|
||||
let required_features=required_features();
|
||||
|
||||
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
|
||||
let needed_limits=required_limits().using_resolution(self.adapter.limits());
|
||||
|
||||
let trace_dir=std::env::var("WGPU_TRACE");
|
||||
let (device, queue)=pollster::block_on(self.adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: None,
|
||||
features: (optional_features & self.adapter.features()) | required_features,
|
||||
limits: needed_limits,
|
||||
},
|
||||
trace_dir.ok().as_ref().map(std::path::Path::new),
|
||||
))
|
||||
.expect("Unable to find a suitable GPU adapter!");
|
||||
|
||||
SetupContextPartial4{
|
||||
instance:self.instance,
|
||||
surface:self.surface,
|
||||
adapter:self.adapter,
|
||||
device,
|
||||
queue,
|
||||
}
|
||||
}
|
||||
}
|
||||
struct SetupContextPartial4{
|
||||
instance:wgpu::Instance,
|
||||
surface:wgpu::Surface,
|
||||
adapter:wgpu::Adapter,
|
||||
device:wgpu::Device,
|
||||
queue:wgpu::Queue,
|
||||
}
|
||||
impl SetupContextPartial4{
|
||||
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->SetupContext{
|
||||
let mut config=self.surface
|
||||
.get_default_config(&self.adapter, size.width, size.height)
|
||||
.expect("Surface isn't supported by the adapter.");
|
||||
let surface_view_format=config.format.add_srgb_suffix();
|
||||
config.view_formats.push(surface_view_format);
|
||||
self.surface.configure(&self.device, &config);
|
||||
|
||||
SetupContext{
|
||||
instance:self.instance,
|
||||
surface:self.surface,
|
||||
device:self.device,
|
||||
queue:self.queue,
|
||||
config,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct SetupContext{
|
||||
pub instance:wgpu::Instance,
|
||||
pub surface:wgpu::Surface,
|
||||
pub device:wgpu::Device,
|
||||
pub queue:wgpu::Queue,
|
||||
pub config:wgpu::SurfaceConfiguration,
|
||||
}
|
||||
|
||||
pub fn setup(title:&str)->SetupContextSetup{
|
||||
let event_loop=winit::event_loop::EventLoop::new().unwrap();
|
||||
|
||||
let window=create_window(title,&event_loop).unwrap();
|
||||
|
||||
println!("Initializing the surface...");
|
||||
|
||||
let partial_1=create_instance();
|
||||
|
||||
let partial_2=partial_1.create_surface(&window).unwrap();
|
||||
|
||||
let partial_3=partial_2.pick_adapter();
|
||||
|
||||
let partial_4=partial_3.request_device();
|
||||
|
||||
SetupContextSetup{
|
||||
window,
|
||||
event_loop,
|
||||
partial_context:partial_4,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SetupContextSetup{
|
||||
window:winit::window::Window,
|
||||
event_loop:winit::event_loop::EventLoop<()>,
|
||||
partial_context:SetupContextPartial4,
|
||||
}
|
||||
|
||||
impl SetupContextSetup{
|
||||
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,SetupContext){
|
||||
let size=self.window.inner_size();
|
||||
//Steal values and drop self
|
||||
(
|
||||
self.window,
|
||||
self.event_loop,
|
||||
self.partial_context.configure_surface(&size),
|
||||
)
|
||||
}
|
||||
pub fn start(self){
|
||||
let (window,event_loop,setup_context)=self.into_split();
|
||||
|
||||
//dedicated thread to ping request redraw back and resize the window doesn't seem logical
|
||||
|
||||
let window=crate::window::WindowContextSetup::new(&setup_context,window);
|
||||
//the thread that spawns the physics thread
|
||||
let window_thread=window.into_worker(setup_context);
|
||||
|
||||
println!("Entering event loop...");
|
||||
let root_time=std::time::Instant::now();
|
||||
run_event_loop(event_loop,window_thread,root_time).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn run_event_loop(
|
||||
event_loop:winit::event_loop::EventLoop<()>,
|
||||
mut window_thread:crate::compat_worker::QNWorker<TimedInstruction<WindowInstruction>>,
|
||||
root_time:std::time::Instant
|
||||
)->Result<(),winit::error::EventLoopError>{
|
||||
event_loop.run(move |event,elwt|{
|
||||
let time=crate::integer::Time::from_nanos(root_time.elapsed().as_nanos() as i64);
|
||||
// *control_flow=if cfg!(feature="metal-auto-capture"){
|
||||
// winit::event_loop::ControlFlow::Exit
|
||||
// }else{
|
||||
// winit::event_loop::ControlFlow::Poll
|
||||
// };
|
||||
match event{
|
||||
winit::event::Event::AboutToWait=>{
|
||||
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::RequestRedraw}).unwrap();
|
||||
}
|
||||
winit::event::Event::WindowEvent {
|
||||
event:
|
||||
// WindowEvent::Resized(size)
|
||||
// | WindowEvent::ScaleFactorChanged {
|
||||
// new_inner_size: &mut size,
|
||||
// ..
|
||||
// },
|
||||
winit::event::WindowEvent::Resized(size),//ignoring scale factor changed for now because mutex bruh
|
||||
window_id:_,
|
||||
} => {
|
||||
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Resize(size)}).unwrap();
|
||||
}
|
||||
winit::event::Event::WindowEvent{event,..}=>match event{
|
||||
winit::event::WindowEvent::KeyboardInput{
|
||||
event:
|
||||
winit::event::KeyEvent {
|
||||
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
|
||||
state: winit::event::ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
|winit::event::WindowEvent::CloseRequested=>{
|
||||
elwt.exit();
|
||||
}
|
||||
winit::event::WindowEvent::RedrawRequested=>{
|
||||
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::Render}).unwrap();
|
||||
}
|
||||
_=>{
|
||||
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::WindowEvent(event)}).unwrap();
|
||||
}
|
||||
},
|
||||
winit::event::Event::DeviceEvent{
|
||||
event,
|
||||
..
|
||||
} => {
|
||||
window_thread.send(TimedInstruction{time,instruction:WindowInstruction::DeviceEvent(event)}).unwrap();
|
||||
},
|
||||
_=>{}
|
||||
}
|
||||
})
|
||||
}
|
131
src/shader.wgsl
131
src/shader.wgsl
@ -1,21 +1,23 @@
|
||||
struct SkyOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) sampledir: vec3<f32>,
|
||||
};
|
||||
|
||||
struct Data {
|
||||
struct Camera {
|
||||
// from camera to screen
|
||||
proj: mat4x4<f32>,
|
||||
// from screen to camera
|
||||
proj_inv: mat4x4<f32>,
|
||||
// from world to camera
|
||||
view: mat4x4<f32>,
|
||||
// camera position
|
||||
cam_pos: vec4<f32>,
|
||||
// from camera to world
|
||||
view_inv: mat4x4<f32>,
|
||||
};
|
||||
|
||||
//group 0 is the camera
|
||||
@group(0)
|
||||
@binding(0)
|
||||
var<uniform> r_data: Data;
|
||||
var<uniform> camera: Camera;
|
||||
|
||||
struct SkyOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) sampledir: vec3<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||
@ -29,9 +31,8 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||
1.0
|
||||
);
|
||||
|
||||
// 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 unprojected = r_data.proj_inv * pos;
|
||||
let inv_model_view = mat3x3<f32>(camera.view_inv[0].xyz, camera.view_inv[1].xyz, camera.view_inv[2].xyz);
|
||||
let unprojected = camera.proj_inv * pos;
|
||||
|
||||
var result: SkyOutput;
|
||||
result.sampledir = inv_model_view * unprojected.xyz;
|
||||
@ -39,93 +40,73 @@ fn vs_sky(@builtin(vertex_index) vertex_index: u32) -> SkyOutput {
|
||||
return result;
|
||||
}
|
||||
|
||||
struct GroundOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(4) pos: vec3<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_ground(@builtin(vertex_index) vertex_index: u32) -> GroundOutput {
|
||||
// hacky way to draw two triangles that make a square
|
||||
let tmp1 = i32(vertex_index)/2-i32(vertex_index)/3;
|
||||
let tmp2 = i32(vertex_index)&1;
|
||||
let pos = vec3<f32>(
|
||||
f32(tmp1) * 2.0 - 1.0,
|
||||
0.0,
|
||||
f32(tmp2) * 2.0 - 1.0
|
||||
) * 160.0;
|
||||
|
||||
var result: GroundOutput;
|
||||
result.pos = pos;
|
||||
result.position = r_data.proj * r_data.view * vec4<f32>(pos, 1.0);
|
||||
return result;
|
||||
struct ModelInstance{
|
||||
transform:mat4x4<f32>,
|
||||
normal_transform:mat3x3<f32>,
|
||||
color:vec4<f32>,
|
||||
}
|
||||
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
|
||||
//the texture transform then maps the texture coordinates to the location of the specific texture
|
||||
//group 1 is the model
|
||||
const MAX_MODEL_INSTANCES=4096;
|
||||
@group(2)
|
||||
@binding(0)
|
||||
var<uniform> model_instances: array<ModelInstance, MAX_MODEL_INSTANCES>;
|
||||
@group(2)
|
||||
@binding(1)
|
||||
var model_texture: texture_2d<f32>;
|
||||
@group(2)
|
||||
@binding(2)
|
||||
var model_sampler: sampler;
|
||||
|
||||
struct EntityOutput {
|
||||
struct EntityOutputTexture {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(1) texture: vec2<f32>,
|
||||
@location(2) normal: vec3<f32>,
|
||||
@location(3) view: vec3<f32>,
|
||||
@location(4) color: vec4<f32>,
|
||||
@location(5) @interpolate(flat) model_color: vec4<f32>,
|
||||
};
|
||||
|
||||
@group(1)
|
||||
@binding(0)
|
||||
var<uniform> r_EntityTransform: mat4x4<f32>;
|
||||
|
||||
@vertex
|
||||
fn vs_entity(
|
||||
fn vs_entity_texture(
|
||||
@builtin(instance_index) instance: u32,
|
||||
@location(0) pos: vec3<f32>,
|
||||
@location(1) texture: vec2<f32>,
|
||||
@location(2) normal: vec3<f32>,
|
||||
) -> EntityOutput {
|
||||
var position: vec4<f32> = r_EntityTransform * vec4<f32>(pos, 1.0);
|
||||
var result: EntityOutput;
|
||||
result.normal = (r_EntityTransform * vec4<f32>(normal, 0.0)).xyz;
|
||||
result.texture=texture;
|
||||
result.view = position.xyz - r_data.cam_pos.xyz;
|
||||
result.position = r_data.proj * r_data.view * position;
|
||||
@location(3) color: vec4<f32>,
|
||||
) -> EntityOutputTexture {
|
||||
var position: vec4<f32> = model_instances[instance].transform * vec4<f32>(pos, 1.0);
|
||||
var result: EntityOutputTexture;
|
||||
result.normal = model_instances[instance].normal_transform * normal;
|
||||
result.texture = texture;
|
||||
result.color = color;
|
||||
result.model_color = model_instances[instance].color;
|
||||
result.view = position.xyz - camera.view_inv[3].xyz;//col(3)
|
||||
result.position = camera.proj * camera.view * position;
|
||||
return result;
|
||||
}
|
||||
|
||||
@group(0)
|
||||
//group 2 is the skybox texture
|
||||
@group(1)
|
||||
@binding(0)
|
||||
var cube_texture: texture_cube<f32>;
|
||||
@group(1)
|
||||
@binding(1)
|
||||
var r_texture: texture_cube<f32>;
|
||||
@group(0)
|
||||
@binding(2)
|
||||
var r_sampler: sampler;
|
||||
var cube_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_sky(vertex: SkyOutput) -> @location(0) vec4<f32> {
|
||||
return textureSample(r_texture, r_sampler, vertex.sampledir);
|
||||
return textureSample(cube_texture, cube_sampler, vertex.sampledir);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_entity(vertex: EntityOutput) -> @location(0) vec4<f32> {
|
||||
fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
|
||||
let incident = normalize(vertex.view);
|
||||
let normal = normalize(vertex.normal);
|
||||
let d = dot(normal, incident);
|
||||
let reflected = incident - 2.0 * d * normal;
|
||||
|
||||
let dir = vec3<f32>(-1.0)+2.0*vec3<f32>(vertex.texture.x,0.0,vertex.texture.y);
|
||||
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
|
||||
fn fs_ground(vertex: GroundOutput) -> @location(0) vec4<f32> {
|
||||
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);
|
||||
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color;
|
||||
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
|
||||
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),0.5+0.5*abs(d));
|
||||
}
|
||||
|
243
src/window.rs
Normal file
243
src/window.rs
Normal file
@ -0,0 +1,243 @@
|
||||
use crate::instruction::TimedInstruction;
|
||||
use crate::physics_worker::InputInstruction;
|
||||
|
||||
pub enum WindowInstruction{
|
||||
Resize(winit::dpi::PhysicalSize<u32>),
|
||||
WindowEvent(winit::event::WindowEvent),
|
||||
DeviceEvent(winit::event::DeviceEvent),
|
||||
RequestRedraw,
|
||||
Render,
|
||||
}
|
||||
|
||||
//holds thread handles to dispatch to
|
||||
struct WindowContext<'a>{
|
||||
manual_mouse_lock:bool,
|
||||
mouse:crate::physics::MouseState,//std::sync::Arc<std::sync::Mutex<>>
|
||||
screen_size:glam::UVec2,
|
||||
user_settings:crate::settings::UserSettings,
|
||||
window:winit::window::Window,
|
||||
physics_thread:crate::compat_worker::QNWorker<'a, TimedInstruction<crate::physics_worker::Instruction>>,
|
||||
}
|
||||
|
||||
impl WindowContext<'_>{
|
||||
fn get_middle_of_screen(&self)->winit::dpi::PhysicalPosition<f32>{
|
||||
winit::dpi::PhysicalPosition::new(self.screen_size.x as f32/2.0,self.screen_size.y as f32/2.0)
|
||||
}
|
||||
fn window_event(&mut self,time:crate::integer::Time,event: winit::event::WindowEvent) {
|
||||
match event {
|
||||
winit::event::WindowEvent::DroppedFile(path)=>{
|
||||
//blocking because it's simpler...
|
||||
if let Some(indexed_model_instances)=crate::load_file(path){
|
||||
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::ClearModels}).unwrap();
|
||||
self.physics_thread.send(TimedInstruction{time,instruction:crate::physics_worker::Instruction::GenerateModels(indexed_model_instances)}).unwrap();
|
||||
}
|
||||
},
|
||||
winit::event::WindowEvent::Focused(_state)=>{
|
||||
//pause unpause
|
||||
//recalculate pressed keys on focus
|
||||
},
|
||||
winit::event::WindowEvent::KeyboardInput{
|
||||
event:winit::event::KeyEvent{state,logical_key,repeat:false,..},
|
||||
..
|
||||
}=>{
|
||||
let s=match state{
|
||||
winit::event::ElementState::Pressed=>true,
|
||||
winit::event::ElementState::Released=>false,
|
||||
};
|
||||
match logical_key{
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab)=>{
|
||||
if s{
|
||||
self.manual_mouse_lock=false;
|
||||
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||
Ok(())=>(),
|
||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||
}
|
||||
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||
Ok(())=>(),
|
||||
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||
}
|
||||
}else{
|
||||
//if cursor is outside window don't lock but apparently there's no get pos function
|
||||
//let pos=window.get_cursor_pos();
|
||||
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
|
||||
Ok(())=>(),
|
||||
Err(_)=>{
|
||||
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
|
||||
Ok(())=>(),
|
||||
Err(e)=>{
|
||||
self.manual_mouse_lock=true;
|
||||
println!("Could not confine cursor: {:?}",e)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.window.set_cursor_visible(s);
|
||||
},
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::F11)=>{
|
||||
if s{
|
||||
if self.window.fullscreen().is_some(){
|
||||
self.window.set_fullscreen(None);
|
||||
}else{
|
||||
self.window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
|
||||
}
|
||||
}
|
||||
},
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape)=>{
|
||||
if s{
|
||||
self.manual_mouse_lock=false;
|
||||
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
|
||||
Ok(())=>(),
|
||||
Err(e)=>println!("Could not release cursor: {:?}",e),
|
||||
}
|
||||
self.window.set_cursor_visible(true);
|
||||
}
|
||||
},
|
||||
keycode=>{
|
||||
if let Some(input_instruction)=match keycode{
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space)=>Some(InputInstruction::Jump(s)),
|
||||
winit::keyboard::Key::Character(key)=>match key.as_str(){
|
||||
"w"=>Some(InputInstruction::MoveForward(s)),
|
||||
"a"=>Some(InputInstruction::MoveLeft(s)),
|
||||
"s"=>Some(InputInstruction::MoveBack(s)),
|
||||
"d"=>Some(InputInstruction::MoveRight(s)),
|
||||
"e"=>Some(InputInstruction::MoveUp(s)),
|
||||
"q"=>Some(InputInstruction::MoveDown(s)),
|
||||
"z"=>Some(InputInstruction::Zoom(s)),
|
||||
"r"=>if s{Some(InputInstruction::Reset)}else{None},
|
||||
_=>None,
|
||||
},
|
||||
_=>None,
|
||||
}{
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:crate::physics_worker::Instruction::Input(input_instruction),
|
||||
}).unwrap();
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
_=>(),
|
||||
}
|
||||
}
|
||||
|
||||
fn device_event(&mut self,time:crate::integer::Time,event: winit::event::DeviceEvent) {
|
||||
match event {
|
||||
winit::event::DeviceEvent::MouseMotion {
|
||||
delta,//these (f64,f64) are integers on my machine
|
||||
} => {
|
||||
if self.manual_mouse_lock{
|
||||
match self.window.set_cursor_position(self.get_middle_of_screen()){
|
||||
Ok(())=>(),
|
||||
Err(e)=>println!("Could not set cursor position: {:?}",e),
|
||||
}
|
||||
}
|
||||
//do not step the physics because the mouse polling rate is higher than the physics can run.
|
||||
//essentially the previous input will be overwritten until a true step runs
|
||||
//which is fine because they run all the time.
|
||||
let delta=glam::ivec2(delta.0 as i32,delta.1 as i32);
|
||||
self.mouse.pos+=delta;
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:crate::physics_worker::Instruction::Input(InputInstruction::MoveMouse(self.mouse.pos)),
|
||||
}).unwrap();
|
||||
},
|
||||
winit::event::DeviceEvent::MouseWheel {
|
||||
delta,
|
||||
} => {
|
||||
println!("mousewheel {:?}",delta);
|
||||
if false{//self.physics.style.use_scroll{
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction:crate::physics_worker::Instruction::Input(InputInstruction::Jump(true)),//activates the immediate jump path, but the style modifier prevents controls&CONTROL_JUMP bit from being set to auto jump
|
||||
}).unwrap();
|
||||
}
|
||||
}
|
||||
_=>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WindowContextSetup{
|
||||
user_settings:crate::settings::UserSettings,
|
||||
window:winit::window::Window,
|
||||
physics:crate::physics::PhysicsState,
|
||||
graphics:crate::graphics::GraphicsState,
|
||||
}
|
||||
|
||||
impl WindowContextSetup{
|
||||
pub fn new(context:&crate::setup::SetupContext,window:winit::window::Window)->Self{
|
||||
//wee
|
||||
let user_settings=crate::settings::read_user_settings();
|
||||
|
||||
let args:Vec<String>=std::env::args().collect();
|
||||
let indexed_model_instances=if args.len()==2{
|
||||
crate::load_file(std::path::PathBuf::from(&args[1]))
|
||||
}else{
|
||||
None
|
||||
}.unwrap_or(crate::default_models());
|
||||
|
||||
let mut physics=crate::physics::PhysicsState::default();
|
||||
physics.load_user_settings(&user_settings);
|
||||
physics.generate_models(&indexed_model_instances);
|
||||
physics.spawn(indexed_model_instances.spawn_point);
|
||||
|
||||
let mut graphics=crate::graphics::GraphicsState::new(&context.device,&context.queue,&context.config);
|
||||
graphics.load_user_settings(&user_settings);
|
||||
graphics.generate_models(&context.device,&context.queue,indexed_model_instances);
|
||||
|
||||
Self{
|
||||
user_settings,
|
||||
window,
|
||||
graphics,
|
||||
physics,
|
||||
}
|
||||
}
|
||||
|
||||
fn into_context<'a>(self,setup_context:crate::setup::SetupContext)->WindowContext<'a>{
|
||||
let screen_size=glam::uvec2(setup_context.config.width,setup_context.config.height);
|
||||
let graphics_thread=crate::graphics_worker::new(self.graphics,setup_context.config,setup_context.surface,setup_context.device,setup_context.queue);
|
||||
WindowContext{
|
||||
manual_mouse_lock:false,
|
||||
mouse:crate::physics::MouseState::default(),
|
||||
//make sure to update this!!!!!
|
||||
screen_size,
|
||||
user_settings:self.user_settings,
|
||||
window:self.window,
|
||||
physics_thread:crate::physics_worker::new(self.physics,graphics_thread),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_worker<'a>(self,setup_context:crate::setup::SetupContext)->crate::compat_worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{
|
||||
let mut window_context=self.into_context(setup_context);
|
||||
crate::compat_worker::QNWorker::new(move |ins:TimedInstruction<WindowInstruction>|{
|
||||
match ins.instruction{
|
||||
WindowInstruction::RequestRedraw=>{
|
||||
window_context.window.request_redraw();
|
||||
}
|
||||
WindowInstruction::WindowEvent(window_event)=>{
|
||||
window_context.window_event(ins.time,window_event);
|
||||
},
|
||||
WindowInstruction::DeviceEvent(device_event)=>{
|
||||
window_context.device_event(ins.time,device_event);
|
||||
},
|
||||
WindowInstruction::Resize(size)=>{
|
||||
window_context.physics_thread.send(
|
||||
TimedInstruction{
|
||||
time:ins.time,
|
||||
instruction:crate::physics_worker::Instruction::Resize(size,window_context.user_settings.clone())
|
||||
}
|
||||
).unwrap();
|
||||
}
|
||||
WindowInstruction::Render=>{
|
||||
window_context.physics_thread.send(
|
||||
TimedInstruction{
|
||||
time:ins.time,
|
||||
instruction:crate::physics_worker::Instruction::Render
|
||||
}
|
||||
).unwrap();
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
210
src/worker.rs
Normal file
210
src/worker.rs
Normal file
@ -0,0 +1,210 @@
|
||||
use std::thread;
|
||||
use std::sync::{mpsc,Arc};
|
||||
use parking_lot::Mutex;
|
||||
|
||||
//WorkerPool
|
||||
struct Pool(u32);
|
||||
enum PoolOrdering{
|
||||
Single,//single thread cannot get out of order
|
||||
Ordered(u32),//order matters and should be buffered/dropped according to ControlFlow
|
||||
Unordered(u32),//order does not matter
|
||||
}
|
||||
//WorkerInput
|
||||
enum Input{
|
||||
//no input, workers have everything needed at creation
|
||||
None,
|
||||
//Immediate input to any available worker, dropped if they are overflowing (all workers are busy)
|
||||
Immediate,
|
||||
//Queued input is ordered, but serial jobs that mutate state (such as running physics) can only be done with a single worker
|
||||
Queued,//"Fifo"
|
||||
//Query a function to get next input when a thread becomes available
|
||||
//worker stops querying when Query function returns None and dies after all threads complete
|
||||
//lifetimes sound crazy on this one
|
||||
Query,
|
||||
//Queue of length one, the input is replaced if it is submitted twice before the current work finishes
|
||||
Mailbox,
|
||||
}
|
||||
//WorkerOutput
|
||||
enum Output{
|
||||
None(Pool),
|
||||
Realtime(PoolOrdering),//outputs are dropped if they are out of order and order is demanded
|
||||
Buffered(PoolOrdering),//outputs are held back internally if they are out of order and order is demanded
|
||||
}
|
||||
|
||||
//It would be possible to implement all variants
|
||||
//with a query input function and callback output function but I'm not sure if that's worth it.
|
||||
//Immediate = Condvar
|
||||
//Queued = receiver.recv()
|
||||
//a callback function would need to use an async runtime!
|
||||
|
||||
//realtime output is an arc mutex of the output value that is assigned every time a worker completes a job
|
||||
//buffered output produces a receiver object that can be passed to the creation of another worker
|
||||
//when ordering is requested, output is ordered by the order each thread is run
|
||||
//which is the same as the order that the input data is processed except for Input::None which has no input data
|
||||
//WorkerDescription
|
||||
struct Description{
|
||||
input:Input,
|
||||
output:Output,
|
||||
}
|
||||
|
||||
//The goal here is to have a worker thread that parks itself when it runs out of work.
|
||||
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
|
||||
//Previous values do not matter as soon as a new value is produced, which is why it's called "Realtime"
|
||||
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
||||
|
||||
/*
|
||||
QR = WorkerDescription{
|
||||
input:Queued,
|
||||
output:Realtime(Single),
|
||||
}
|
||||
*/
|
||||
pub struct QRWorker<Task:Send,Value:Clone>{
|
||||
sender: mpsc::Sender<Task>,
|
||||
value:Arc<Mutex<Value>>,
|
||||
}
|
||||
|
||||
impl<Task:Send+'static,Value:Clone+Send+'static> QRWorker<Task,Value>{
|
||||
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
|
||||
let (sender, receiver) = mpsc::channel::<Task>();
|
||||
let ret=Self {
|
||||
sender,
|
||||
value:Arc::new(Mutex::new(value)),
|
||||
};
|
||||
let value=ret.value.clone();
|
||||
thread::spawn(move || {
|
||||
loop {
|
||||
match receiver.recv() {
|
||||
Ok(task) => {
|
||||
let v=f(task);//make sure function is evaluated before lock is acquired
|
||||
*value.lock()=v;
|
||||
}
|
||||
Err(_) => {
|
||||
println!("Worker stopping.",);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
||||
self.sender.send(task)
|
||||
}
|
||||
|
||||
pub fn grab_clone(&self)->Value{
|
||||
self.value.lock().clone()
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
QN = WorkerDescription{
|
||||
input:Queued,
|
||||
output:None(Single),
|
||||
}
|
||||
*/
|
||||
//None Output Worker does all its work internally from the perspective of the work submitter
|
||||
pub struct QNWorker<'a,Task:Send>{
|
||||
sender: mpsc::Sender<Task>,
|
||||
handle:thread::ScopedJoinHandle<'a,()>,
|
||||
}
|
||||
|
||||
impl<'a,Task:Send+'a> QNWorker<'a,Task>{
|
||||
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->QNWorker<'a,Task>{
|
||||
let (sender,receiver)=mpsc::channel::<Task>();
|
||||
let handle=scope.spawn(move ||{
|
||||
loop {
|
||||
match receiver.recv() {
|
||||
Ok(task)=>f(task),
|
||||
Err(_)=>{
|
||||
println!("Worker stopping.",);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Self{
|
||||
sender,
|
||||
handle,
|
||||
}
|
||||
}
|
||||
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
||||
self.sender.send(task)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
IN = WorkerDescription{
|
||||
input:Immediate,
|
||||
output:None(Single),
|
||||
}
|
||||
*/
|
||||
//Inputs are dropped if the worker is busy
|
||||
pub struct INWorker<'a,Task:Send>{
|
||||
sender: mpsc::SyncSender<Task>,
|
||||
handle:thread::ScopedJoinHandle<'a,()>,
|
||||
}
|
||||
|
||||
impl<'a,Task:Send+'a> INWorker<'a,Task>{
|
||||
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->INWorker<'a,Task>{
|
||||
let (sender,receiver)=mpsc::sync_channel::<Task>(1);
|
||||
let handle=scope.spawn(move ||{
|
||||
loop {
|
||||
match receiver.recv() {
|
||||
Ok(task)=>f(task),
|
||||
Err(_)=>{
|
||||
println!("Worker stopping.",);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Self{
|
||||
sender,
|
||||
handle,
|
||||
}
|
||||
}
|
||||
//blocking!
|
||||
pub fn blocking_send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
||||
self.sender.send(task)
|
||||
}
|
||||
pub fn send(&self,task:Task)->Result<(), mpsc::TrySendError<Task>>{
|
||||
self.sender.try_send(task)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]//How to run this test with printing: cargo test --release -- --nocapture
|
||||
fn test_worker() {
|
||||
println!("hiiiii");
|
||||
// Create the worker thread
|
||||
let worker=QRWorker::new(crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO),
|
||||
|_|crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE)
|
||||
);
|
||||
|
||||
// Send tasks to the worker
|
||||
for _ in 0..5 {
|
||||
let task = crate::instruction::TimedInstruction{
|
||||
time:crate::integer::Time::ZERO,
|
||||
instruction:crate::physics::PhysicsInstruction::StrafeTick,
|
||||
};
|
||||
worker.send(task).unwrap();
|
||||
}
|
||||
|
||||
// Optional: Signal the worker to stop (in a real-world scenario)
|
||||
// sender.send("STOP".to_string()).unwrap();
|
||||
|
||||
// Sleep to allow the worker thread to finish processing
|
||||
thread::sleep(std::time::Duration::from_secs(2));
|
||||
|
||||
// Send a new task
|
||||
let task = crate::instruction::TimedInstruction{
|
||||
time:crate::integer::Time::ZERO,
|
||||
instruction:crate::physics::PhysicsInstruction::StrafeTick,
|
||||
};
|
||||
worker.send(task).unwrap();
|
||||
|
||||
println!("value={}",worker.grab_clone());
|
||||
|
||||
// wait long enough to see print from final task
|
||||
thread::sleep(std::time::Duration::from_secs(1));
|
||||
}
|
@ -1,27 +1,33 @@
|
||||
//find roots of polynomials
|
||||
pub fn zeroes2(a0:f32,a1:f32,a2:f32) -> Vec<f32>{
|
||||
if a2==0f32{
|
||||
return zeroes1(a0, a1);
|
||||
use crate::integer::Planar64;
|
||||
|
||||
#[inline]
|
||||
pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64)->([Planar64;2],usize){
|
||||
if a2==Planar64::ZERO{
|
||||
let ([ret],ret_len)=zeroes1(a0,a1);
|
||||
return ([ret,Planar64::ZERO],ret_len);
|
||||
}
|
||||
let mut radicand=a1*a1-4f32*a2*a0;
|
||||
if 0f32<radicand {
|
||||
radicand=radicand.sqrt();
|
||||
if 0f32<a2 {
|
||||
return vec![(-a1-radicand)/(2f32*a2),(-a1+radicand)/(2f32*a2)];
|
||||
} else {
|
||||
return vec![(-a1+radicand)/(2f32*a2),(-a1-radicand)/(2f32*a2)];
|
||||
let radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
|
||||
if 0<radicand{
|
||||
//start with f64 sqrt
|
||||
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
|
||||
//TODO: one or two newtons
|
||||
if Planar64::ZERO<a2{
|
||||
([(-a1-planar_radicand)/(a2*2),(-a1+planar_radicand)/(a2*2)],2)
|
||||
}else{
|
||||
([(-a1+planar_radicand)/(a2*2),(-a1-planar_radicand)/(a2*2)],2)
|
||||
}
|
||||
} else if radicand==0f32 {
|
||||
return vec![-a1/(2f32*a2)];
|
||||
} else {
|
||||
return vec![];
|
||||
}else if radicand==0{
|
||||
([a1/(a2*-2),Planar64::ZERO],1)
|
||||
}else{
|
||||
([Planar64::ZERO,Planar64::ZERO],0)
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn zeroes1(a0:f32,a1:f32) -> Vec<f32> {
|
||||
if a1==0f32{
|
||||
return vec![];
|
||||
} else {
|
||||
return vec![-a0/a1];
|
||||
pub fn zeroes1(a0:Planar64,a1:Planar64)->([Planar64;1],usize){
|
||||
if a1==Planar64::ZERO{
|
||||
return ([Planar64::ZERO],0);
|
||||
}else{
|
||||
return ([-a0/a1],1);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user