forked from StrafesNET/strafe-project
Compare commits
49 Commits
the-wrong-
...
worker-sco
Author | SHA1 | Date | |
---|---|---|---|
580bbf2cc5 | |||
08f6d928cf | |||
de7b7ba7be | |||
008c66e052 | |||
ba250277bd | |||
085d4e7912 | |||
dd6b5bed24 | |||
9d4cadda30 | |||
242b4ab470 | |||
eaef3d3fd5 | |||
9d726c5419 | |||
9592f82c4e | |||
873c6ab935 | |||
7ba94c1b30 | |||
8fc6a7fb8f | |||
a3340143db | |||
9fc7884270 | |||
953b17bc69 | |||
8fcb4e5c6c | |||
073a076fe8 | |||
9848d66001 | |||
6474ddcbd1 | |||
c4cd73e914 | |||
bbb1857377 | |||
883be0bc01 | |||
5885036f8f | |||
076dab23cf | |||
c1001d6f37 | |||
08d4e7d997 | |||
e1f4f6e535 | |||
3a4c4ef9fe | |||
41dd155c50 | |||
5fd6ca219b | |||
1c22f4a3c3 | |||
1e6c489750 | |||
9f62f5f2fd | |||
7be7d2c0df | |||
cb6b0acd44 | |||
cbcf047c3f | |||
6e5de4aa46 | |||
cc776e7cb4 | |||
5a66ac46b9 | |||
38f6e1df3f | |||
849dcf98f7 | |||
d04d1be27e | |||
35bfd1d366 | |||
586bf8ce89 | |||
127b205401 | |||
4f596ca5d7 |
1245
Cargo.lock
generated
1245
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -6,14 +6,11 @@ edition = "2021"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-executor = "1.5.1"
|
|
||||||
bytemuck = { version = "1.13.1", features = ["derive"] }
|
bytemuck = { version = "1.13.1", features = ["derive"] }
|
||||||
configparser = "3.0.2"
|
configparser = "3.0.2"
|
||||||
ddsfile = "0.5.1"
|
ddsfile = "0.5.1"
|
||||||
env_logger = "0.10.0"
|
|
||||||
glam = "0.24.1"
|
glam = "0.24.1"
|
||||||
lazy-regex = "3.0.2"
|
lazy-regex = "3.0.2"
|
||||||
log = "0.4.20"
|
|
||||||
obj = "0.10.2"
|
obj = "0.10.2"
|
||||||
parking_lot = "0.12.1"
|
parking_lot = "0.12.1"
|
||||||
pollster = "0.3.0"
|
pollster = "0.3.0"
|
||||||
@ -21,8 +18,8 @@ rbx_binary = "0.7.1"
|
|||||||
rbx_dom_weak = "2.5.0"
|
rbx_dom_weak = "2.5.0"
|
||||||
rbx_reflection_database = "0.2.7"
|
rbx_reflection_database = "0.2.7"
|
||||||
rbx_xml = "0.13.1"
|
rbx_xml = "0.13.1"
|
||||||
wgpu = "0.17.0"
|
wgpu = "0.18.0"
|
||||||
winit = "0.28.6"
|
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||||
|
|
||||||
#[profile.release]
|
#[profile.release]
|
||||||
#lto = true
|
#lto = true
|
||||||
|
46
src/bvh.rs
46
src/bvh.rs
@ -9,22 +9,34 @@ use crate::aabb::Aabb;
|
|||||||
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
|
//start with bisection into octrees because a bad bvh is still 1000x better than no bvh
|
||||||
//sort the centerpoints on each axis (3 lists)
|
//sort the centerpoints on each axis (3 lists)
|
||||||
//bv is put into octant based on whether it is upper or lower in each list
|
//bv is put into octant based on whether it is upper or lower in each list
|
||||||
|
enum BvhNodeContent{
|
||||||
|
Branch(Vec<BvhNode>),
|
||||||
|
Leaf(usize),
|
||||||
|
}
|
||||||
|
impl Default for BvhNodeContent{
|
||||||
|
fn default()->Self{
|
||||||
|
Self::Branch(Vec::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct BvhNode{
|
pub struct BvhNode{
|
||||||
children:Vec<Self>,
|
content:BvhNodeContent,
|
||||||
models:Vec<u32>,
|
|
||||||
aabb:Aabb,
|
aabb:Aabb,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BvhNode{
|
impl BvhNode{
|
||||||
pub fn the_tester<F:FnMut(u32)>(&self,aabb:&Aabb,f:&mut F){
|
pub fn the_tester<F:FnMut(usize)>(&self,aabb:&Aabb,f:&mut F){
|
||||||
for &model in &self.models{
|
match &self.content{
|
||||||
f(model);
|
&BvhNodeContent::Leaf(model)=>f(model),
|
||||||
}
|
BvhNodeContent::Branch(children)=>for child in children{
|
||||||
for child in &self.children{
|
//this test could be moved outside the match statement
|
||||||
if aabb.intersects(&child.aabb){
|
//but that would test the root node aabb
|
||||||
child.the_tester(aabb,f);
|
//you're probably not going to spend a lot of time outside the map,
|
||||||
}
|
//so the test is extra work for nothing
|
||||||
|
if aabb.intersects(&child.aabb){
|
||||||
|
child.the_tester(aabb,f);
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -37,10 +49,15 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
|||||||
let n=boxen.len();
|
let n=boxen.len();
|
||||||
if n<20{
|
if n<20{
|
||||||
let mut aabb=Aabb::default();
|
let mut aabb=Aabb::default();
|
||||||
let models=boxen.into_iter().map(|b|{aabb.join(&b.1);b.0 as u32}).collect();
|
let nodes=boxen.into_iter().map(|b|{
|
||||||
|
aabb.join(&b.1);
|
||||||
|
BvhNode{
|
||||||
|
content:BvhNodeContent::Leaf(b.0),
|
||||||
|
aabb:b.1,
|
||||||
|
}
|
||||||
|
}).collect();
|
||||||
BvhNode{
|
BvhNode{
|
||||||
children:Vec::new(),
|
content:BvhNodeContent::Branch(nodes),
|
||||||
models,
|
|
||||||
aabb,
|
aabb,
|
||||||
}
|
}
|
||||||
}else{
|
}else{
|
||||||
@ -99,8 +116,7 @@ fn generate_bvh_node(boxen:Vec<(usize,Aabb)>)->BvhNode{
|
|||||||
node
|
node
|
||||||
}).collect();
|
}).collect();
|
||||||
BvhNode{
|
BvhNode{
|
||||||
children,
|
content:BvhNodeContent::Branch(children),
|
||||||
models:Vec::new(),
|
|
||||||
aabb,
|
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)+Send+'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a,Task> CompatNWorker<'a,Task>{
|
||||||
|
pub fn new(f:impl FnMut(Task)+Send+'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(())
|
||||||
|
}
|
||||||
|
}
|
516
src/framework.rs
516
src/framework.rs
@ -1,516 +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, window: &winit::window::Window, device: &wgpu::Device, queue: &wgpu::Queue, event: WindowEvent);
|
|
||||||
fn device_event(&mut self, window: &winit::window::Window, event: DeviceEvent);
|
|
||||||
fn load_file(&mut self, path:std::path::PathBuf, device: &wgpu::Device, queue: &wgpu::Queue);
|
|
||||||
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;
|
|
||||||
|
|
||||||
let optional_features = E::optional_features();
|
|
||||||
let required_features = E::required_features();
|
|
||||||
|
|
||||||
//no helper function smh gotta write it myself
|
|
||||||
let adapters = instance.enumerate_adapters(backends);
|
|
||||||
|
|
||||||
let mut chosen_adapter = None;
|
|
||||||
let mut chosen_adapter_score=0;
|
|
||||||
for adapter in adapters {
|
|
||||||
if !adapter.is_surface_supported(&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!");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
{
|
|
||||||
let adapter_info = adapter.get_info();
|
|
||||||
println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
|
|
||||||
}
|
|
||||||
|
|
||||||
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::Scroll),
|
|
||||||
state: event::ElementState::Pressed,
|
|
||||||
..
|
|
||||||
},
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
println!("{:#?}", instance.generate_report());
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
example.update(&window,&device,&queue,event);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
event::Event::DeviceEvent {
|
|
||||||
event,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
example.device_event(&window,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() {}
|
|
1005
src/graphics.rs
Normal file
1005
src/graphics.rs
Normal file
File diff suppressed because it is too large
Load Diff
71
src/graphics_worker.rs
Normal file
71
src/graphics_worker.rs
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
pub enum Instruction{
|
||||||
|
Render(crate::physics::PhysicsOutputState,crate::integer::Time,glam::IVec2),
|
||||||
|
//UpdateModel(crate::graphics::GraphicsModelUpdate),
|
||||||
|
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>(
|
||||||
|
scope:&'a std::thread::Scope<'a,'_>,
|
||||||
|
mut graphics:crate::graphics::GraphicsState,
|
||||||
|
mut config:wgpu::SurfaceConfiguration,
|
||||||
|
surface:wgpu::Surface,
|
||||||
|
device:wgpu::Device,
|
||||||
|
queue:wgpu::Queue,
|
||||||
|
)->crate::worker::INWorker<'a,Instruction>{
|
||||||
|
let mut resize=None;
|
||||||
|
crate::worker::INWorker::new(scope,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)=>{
|
||||||
|
resize=Some((size,user_settings));
|
||||||
|
}
|
||||||
|
Instruction::Render(physics_output,predicted_time,mouse_pos)=>{
|
||||||
|
if let Some((size,user_settings))=&resize{
|
||||||
|
println!("Resizing to {:?}",size);
|
||||||
|
let t0=std::time::Instant::now();
|
||||||
|
config.width=size.width.max(1);
|
||||||
|
config.height=size.height.max(1);
|
||||||
|
surface.configure(&device,&config);
|
||||||
|
graphics.resize(&device,&config,user_settings);
|
||||||
|
println!("Resize took {:?}",t0.elapsed());
|
||||||
|
}
|
||||||
|
//clear every time w/e
|
||||||
|
resize=None;
|
||||||
|
//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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -41,6 +41,11 @@ impl std::fmt::Display for Time{
|
|||||||
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
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{
|
impl std::ops::Neg for Time{
|
||||||
type Output=Time;
|
type Output=Time;
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -310,8 +315,8 @@ impl Angle32{
|
|||||||
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
|
pub fn clamp(&self,theta_min:Self,theta_max:Self)->Self{
|
||||||
//((max-min as u32)/2 as i32)+min
|
//((max-min as u32)/2 as i32)+min
|
||||||
let midpoint=((
|
let midpoint=((
|
||||||
u32::from_ne_bytes(theta_max.0.to_ne_bytes())
|
(theta_max.0 as u32)
|
||||||
.wrapping_sub(u32::from_ne_bytes(theta_min.0.to_ne_bytes()))
|
.wrapping_sub(theta_min.0 as u32)
|
||||||
/2
|
/2
|
||||||
) as i32)//(u32::MAX/2) as i32 ALWAYS works
|
) as i32)//(u32::MAX/2) as i32 ALWAYS works
|
||||||
.wrapping_add(theta_min.0);
|
.wrapping_add(theta_min.0);
|
||||||
@ -404,12 +409,11 @@ impl TryFrom<[f32;3]> for Unit32Vec3{
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
///[-1.0,1.0] = [-2^32,2^32]
|
///[-1.0,1.0] = [-2^32,2^32]
|
||||||
#[derive(Clone,Copy,Debug,Hash,Eq,Ord,PartialEq,PartialOrd)]
|
#[derive(Clone,Copy,Hash,Eq,Ord,PartialEq,PartialOrd)]
|
||||||
pub struct Planar64(i64);
|
pub struct Planar64(i64);
|
||||||
impl Planar64{
|
impl Planar64{
|
||||||
pub const ZERO:Self=Self(0);
|
pub const ZERO:Self=Self(0);
|
||||||
pub const ONE:Self=Self(1<<32);
|
pub const ONE:Self=Self(1<<32);
|
||||||
pub const FRAC_1_SQRT2:Self=Self(3_037_000_500);
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub const fn int(num:i32)->Self{
|
pub const fn int(num:i32)->Self{
|
||||||
Self(Self::ONE.0*num as i64)
|
Self(Self::ONE.0*num as i64)
|
||||||
@ -564,7 +568,7 @@ impl std::ops::Div<Planar64> for Planar64{
|
|||||||
|
|
||||||
|
|
||||||
///[-1.0,1.0] = [-2^32,2^32]
|
///[-1.0,1.0] = [-2^32,2^32]
|
||||||
#[derive(Clone,Copy,Debug,Default,Hash,Eq,PartialEq)]
|
#[derive(Clone,Copy,Default,Hash,Eq,PartialEq)]
|
||||||
pub struct Planar64Vec3(glam::I64Vec3);
|
pub struct Planar64Vec3(glam::I64Vec3);
|
||||||
impl Planar64Vec3{
|
impl Planar64Vec3{
|
||||||
pub const ZERO:Self=Planar64Vec3(glam::I64Vec3::ZERO);
|
pub const ZERO:Self=Planar64Vec3(glam::I64Vec3::ZERO);
|
||||||
@ -630,14 +634,6 @@ impl Planar64Vec3{
|
|||||||
)>>32) as i64)
|
)>>32) as i64)
|
||||||
}
|
}
|
||||||
#[inline]
|
#[inline]
|
||||||
/* pub fn cross(&self,rhs:Self)->Planar64Vec3{
|
|
||||||
Planar64Vec3(((
|
|
||||||
(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{
|
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);
|
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()})
|
Planar64(unsafe{(radicand as f64).sqrt().to_int_unchecked()})
|
||||||
|
@ -23,14 +23,6 @@ fn recursive_collect_superclass(objects: &mut std::vec::Vec<rbx_dom_weak::types:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn get_texture_refs(dom:&rbx_dom_weak::WeakDom) -> Vec<rbx_dom_weak::types::Ref>{
|
|
||||||
let mut objects = std::vec::Vec::new();
|
|
||||||
recursive_collect_superclass(&mut objects, dom, dom.root(),"Decal");
|
|
||||||
//get ids
|
|
||||||
//clear vec
|
|
||||||
//next class
|
|
||||||
objects
|
|
||||||
}
|
|
||||||
fn planar64_affine3_from_roblox(cf:&rbx_dom_weak::types::CFrame,size:&rbx_dom_weak::types::Vector3)->Planar64Affine3{
|
fn planar64_affine3_from_roblox(cf:&rbx_dom_weak::types::CFrame,size:&rbx_dom_weak::types::Vector3)->Planar64Affine3{
|
||||||
Planar64Affine3::new(
|
Planar64Affine3::new(
|
||||||
Planar64Mat3::from_cols(
|
Planar64Mat3::from_cols(
|
||||||
@ -49,7 +41,6 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
let mut intersecting=crate::model::IntersectingAttributes::default();
|
let mut intersecting=crate::model::IntersectingAttributes::default();
|
||||||
let mut contacting=crate::model::ContactingAttributes::default();
|
let mut contacting=crate::model::ContactingAttributes::default();
|
||||||
let mut force_can_collide=can_collide;
|
let mut force_can_collide=can_collide;
|
||||||
const GRAVITY:Planar64Vec3=Planar64Vec3::int(0,-100,0);
|
|
||||||
match name{
|
match name{
|
||||||
"Water"=>{
|
"Water"=>{
|
||||||
force_can_collide=false;
|
force_can_collide=false;
|
||||||
@ -61,6 +52,7 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
force_can_collide=false;
|
force_can_collide=false;
|
||||||
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
general.accelerator=Some(crate::model::GameMechanicAccelerator{acceleration:velocity});
|
||||||
},
|
},
|
||||||
|
"UnorderedCheckpoint"=>general.checkpoint=Some(crate::model::GameMechanicCheckpoint::Unordered{mode_id:0}),
|
||||||
"SetVelocity"=>general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Velocity(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})},
|
"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})},
|
"MapAnticheat"=>{force_can_collide=false;general.zone=Some(crate::model::GameMechanicZone{mode_id:0,behaviour:crate::model::ZoneBehaviour::Anitcheat})},
|
||||||
@ -119,25 +111,18 @@ fn get_attributes(name:&str,can_collide:bool,velocity:Planar64Vec3,force_interse
|
|||||||
"WormholeIn"=>general.teleport_behaviour=Some(crate::model::TeleportBehaviour::Wormhole(crate::model::GameMechanicWormhole{destination_model_id:captures[2].parse::<u32>().unwrap()})),
|
"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"),
|
_=>panic!("regex3[1] messed up bad"),
|
||||||
}
|
}
|
||||||
|
}else if let Some(captures)=lazy_regex::regex!(r"^(OrderedCheckpoint)(\d+)$")
|
||||||
|
.captures(other){
|
||||||
|
match &captures[1]{
|
||||||
|
"OrderedCheckpoint"=>general.checkpoint=Some(crate::model::GameMechanicCheckpoint::Ordered{mode_id:0,checkpoint_id:captures[2].parse::<u32>().unwrap()}),
|
||||||
|
_=>panic!("regex3[1] messed up bad"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//need some way to skip this
|
//need some way to skip this
|
||||||
if velocity!=Planar64Vec3::ZERO{
|
if velocity!=Planar64Vec3::ZERO{
|
||||||
//assume all vertical boosters are targetting a height
|
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
|
||||||
let vg=velocity.dot(GRAVITY);
|
|
||||||
if Planar64::ZERO<=vg{
|
|
||||||
//weird down booster
|
|
||||||
general.booster=Some(crate::model::GameMechanicBooster::Velocity(velocity));
|
|
||||||
}else{
|
|
||||||
println!("set attr");
|
|
||||||
let gg=GRAVITY.dot(GRAVITY);
|
|
||||||
let height=-vg*gg.sqrt().sqrt()*Planar64::FRAC_1_SQRT2/gg;//vi/sqrt(-2*a)=d
|
|
||||||
let v=velocity-GRAVITY*(vg/gg);
|
|
||||||
//if we are adding zero SO BE IT, the check to see if the vectors are parallel is too sensitive
|
|
||||||
general.booster=Some(crate::model::GameMechanicBooster::Velocity(v));
|
|
||||||
general.trajectory=Some(crate::model::GameMechanicSetTrajectory::Height(height));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
match force_can_collide{
|
match force_can_collide{
|
||||||
true=>{
|
true=>{
|
||||||
@ -232,9 +217,9 @@ type RobloxWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
|||||||
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
type RobloxCornerWedgeDescription=[Option<RobloxFaceTextureDescription>;5];
|
||||||
#[derive(Clone,Eq,Hash,PartialEq)]
|
#[derive(Clone,Eq,Hash,PartialEq)]
|
||||||
enum RobloxBasePartDescription{
|
enum RobloxBasePartDescription{
|
||||||
Sphere,
|
Sphere(RobloxPartDescription),
|
||||||
Part(RobloxPartDescription),
|
Part(RobloxPartDescription),
|
||||||
Cylinder,
|
Cylinder(RobloxPartDescription),
|
||||||
Wedge(RobloxWedgeDescription),
|
Wedge(RobloxWedgeDescription),
|
||||||
CornerWedge(RobloxCornerWedgeDescription),
|
CornerWedge(RobloxCornerWedgeDescription),
|
||||||
}
|
}
|
||||||
@ -277,16 +262,15 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
if let Some(attr)=match &object.name[..]{
|
if let Some(attr)=match &object.name[..]{
|
||||||
"MapStart"=>{
|
"MapStart"=>{
|
||||||
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
spawn_point=model_transform.transform_point3(Planar64Vec3::ZERO)+Planar64Vec3::Y*5/2;
|
||||||
Some(crate::model::TempIndexedAttributes::Start{mode_id:0})
|
Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:0}))
|
||||||
},
|
},
|
||||||
"UnorderedCheckpoint"=>Some(crate::model::TempIndexedAttributes::UnorderedCheckpoint{mode_id:0}),
|
|
||||||
other=>{
|
other=>{
|
||||||
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|OrderedCheckpoint)(\d+)$");
|
let regman=lazy_regex::regex!(r"^(BonusStart|Spawn|ForceSpawn|WormholeOut)(\d+)$");
|
||||||
if let Some(captures) = regman.captures(other) {
|
if let Some(captures) = regman.captures(other) {
|
||||||
match &captures[1]{
|
match &captures[1]{
|
||||||
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start{mode_id:captures[2].parse::<u32>().unwrap()}),
|
"BonusStart"=>Some(crate::model::TempIndexedAttributes::Start(crate::model::TempAttrStart{mode_id:captures[2].parse::<u32>().unwrap()})),
|
||||||
"Spawn"|"ForceSpawn"=>Some(crate::model::TempIndexedAttributes::Spawn{mode_id:0,stage_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{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,
|
_=>None,
|
||||||
}
|
}
|
||||||
}else{
|
}else{
|
||||||
@ -314,6 +298,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
panic!("Part has no Shape!");
|
panic!("Part has no Shape!");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"TrussPart"=>primitives::Primitives::Cube,
|
||||||
"WedgePart"=>primitives::Primitives::Wedge,
|
"WedgePart"=>primitives::Primitives::Wedge,
|
||||||
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
|
"CornerWedgePart"=>primitives::Primitives::CornerWedge,
|
||||||
_=>{
|
_=>{
|
||||||
@ -408,9 +393,9 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
f5,//Cube::Front
|
f5,//Cube::Front
|
||||||
]=part_texture_description;
|
]=part_texture_description;
|
||||||
let basepart_texture_description=match shape{
|
let basepart_texture_description=match shape{
|
||||||
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere,
|
primitives::Primitives::Sphere=>RobloxBasePartDescription::Sphere([f0,f1,f2,f3,f4,f5]),
|
||||||
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
|
primitives::Primitives::Cube=>RobloxBasePartDescription::Part([f0,f1,f2,f3,f4,f5]),
|
||||||
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder,
|
primitives::Primitives::Cylinder=>RobloxBasePartDescription::Cylinder([f0,f1,f2,f3,f4,f5]),
|
||||||
//use front face texture first and use top face texture as a fallback
|
//use front face texture first and use top face texture as a fallback
|
||||||
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
primitives::Primitives::Wedge=>RobloxBasePartDescription::Wedge([
|
||||||
f0,//Cube::Right->Wedge::Right
|
f0,//Cube::Right->Wedge::Right
|
||||||
@ -436,9 +421,10 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
let model_id=indexed_models.len();
|
let model_id=indexed_models.len();
|
||||||
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
|
model_id_from_description.insert(basepart_texture_description.clone(),model_id);//borrow checker going crazy
|
||||||
indexed_models.push(match basepart_texture_description{
|
indexed_models.push(match basepart_texture_description{
|
||||||
RobloxBasePartDescription::Sphere=>primitives::unit_sphere(),
|
RobloxBasePartDescription::Sphere(part_texture_description)
|
||||||
RobloxBasePartDescription::Part(part_texture_description)=>{
|
|RobloxBasePartDescription::Cylinder(part_texture_description)
|
||||||
let mut cube_face_description=primitives::CubeFaceDescription::new();
|
|RobloxBasePartDescription::Part(part_texture_description)=>{
|
||||||
|
let mut cube_face_description=primitives::CubeFaceDescription::default();
|
||||||
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
|
for (face_id,roblox_face_description) in part_texture_description.iter().enumerate(){
|
||||||
cube_face_description.insert(
|
cube_face_description.insert(
|
||||||
match face_id{
|
match face_id{
|
||||||
@ -457,9 +443,8 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
}
|
}
|
||||||
primitives::generate_partial_unit_cube(cube_face_description)
|
primitives::generate_partial_unit_cube(cube_face_description)
|
||||||
},
|
},
|
||||||
RobloxBasePartDescription::Cylinder=>primitives::unit_cylinder(),
|
|
||||||
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
|
RobloxBasePartDescription::Wedge(wedge_texture_description)=>{
|
||||||
let mut wedge_face_description=primitives::WedgeFaceDescription::new();
|
let mut wedge_face_description=primitives::WedgeFaceDescription::default();
|
||||||
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
|
for (face_id,roblox_face_description) in wedge_texture_description.iter().enumerate(){
|
||||||
wedge_face_description.insert(
|
wedge_face_description.insert(
|
||||||
match face_id{
|
match face_id{
|
||||||
@ -478,7 +463,7 @@ pub fn generate_indexed_models(dom:rbx_dom_weak::WeakDom) -> crate::model::Index
|
|||||||
primitives::generate_partial_unit_wedge(wedge_face_description)
|
primitives::generate_partial_unit_wedge(wedge_face_description)
|
||||||
},
|
},
|
||||||
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
|
RobloxBasePartDescription::CornerWedge(cornerwedge_texture_description)=>{
|
||||||
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::new();
|
let mut cornerwedge_face_description=primitives::CornerWedgeFaceDescription::default();
|
||||||
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
for (face_id,roblox_face_description) in cornerwedge_texture_description.iter().enumerate(){
|
||||||
cornerwedge_face_description.insert(
|
cornerwedge_face_description.insert(
|
||||||
match face_id{
|
match face_id{
|
||||||
|
1421
src/main.rs
1421
src/main.rs
File diff suppressed because it is too large
Load Diff
81
src/model.rs
81
src/model.rs
@ -50,44 +50,36 @@ pub struct IndexedModelInstances{
|
|||||||
}
|
}
|
||||||
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
//stage description referencing flattened ids is spooky, but the map loading is meant to be deterministic.
|
||||||
pub struct ModeDescription{
|
pub struct ModeDescription{
|
||||||
pub start:u32,//start=model_id
|
//TODO: put "default" style modifiers in mode
|
||||||
pub spawns:Vec<u32>,//spawns[spawn_id]=model_id
|
//pub style:StyleModifiers,
|
||||||
pub ordered_checkpoints:Vec<u32>,//ordered_checkpoints[checkpoint_id]=model_id
|
pub start:usize,//start=model_id
|
||||||
pub unordered_checkpoints:Vec<u32>,//unordered_checkpoints[checkpoint_id]=model_id
|
pub spawns:Vec<usize>,//spawns[spawn_id]=model_id
|
||||||
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
pub spawn_from_stage_id:std::collections::HashMap::<u32,usize>,
|
||||||
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
pub ordered_checkpoint_from_checkpoint_id:std::collections::HashMap::<u32,usize>,
|
||||||
}
|
}
|
||||||
impl ModeDescription{
|
impl ModeDescription{
|
||||||
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&u32>{
|
pub fn get_spawn_model_id(&self,stage_id:u32)->Option<&usize>{
|
||||||
if let Some(&spawn)=self.spawn_from_stage_id.get(&stage_id){
|
self.spawns.get(*self.spawn_from_stage_id.get(&stage_id)?)
|
||||||
self.spawns.get(spawn)
|
|
||||||
}else{
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn get_ordered_checkpoint_model_id(&self,checkpoint_id:u32)->Option<&u32>{
|
|
||||||
if let Some(&checkpoint)=self.ordered_checkpoint_from_checkpoint_id.get(&checkpoint_id){
|
|
||||||
self.ordered_checkpoints.get(checkpoint)
|
|
||||||
}else{
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//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 TempAttrWormhole{
|
||||||
|
pub wormhole_id:u32,
|
||||||
|
}
|
||||||
pub enum TempIndexedAttributes{
|
pub enum TempIndexedAttributes{
|
||||||
Start{
|
Start(TempAttrStart),
|
||||||
mode_id:u32,
|
Spawn(TempAttrSpawn),
|
||||||
},
|
Wormhole(TempAttrWormhole),
|
||||||
Spawn{
|
|
||||||
mode_id:u32,
|
|
||||||
stage_id:u32,
|
|
||||||
},
|
|
||||||
OrderedCheckpoint{
|
|
||||||
mode_id:u32,
|
|
||||||
checkpoint_id:u32,
|
|
||||||
},
|
|
||||||
UnorderedCheckpoint{
|
|
||||||
mode_id:u32,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//you have this effect while in contact
|
//you have this effect while in contact
|
||||||
@ -119,12 +111,22 @@ pub enum GameMechanicBooster{
|
|||||||
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
|
Velocity(Planar64Vec3),//straight up boost velocity adds to your current velocity
|
||||||
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
Energy{direction:Planar64Vec3,energy:Planar64},//increase energy in direction
|
||||||
}
|
}
|
||||||
#[derive(Clone,Debug)]
|
#[derive(Clone)]
|
||||||
|
pub enum GameMechanicCheckpoint{
|
||||||
|
Ordered{
|
||||||
|
mode_id:u32,
|
||||||
|
checkpoint_id:u32,
|
||||||
|
},
|
||||||
|
Unordered{
|
||||||
|
mode_id:u32,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
pub enum TrajectoryChoice{
|
pub enum TrajectoryChoice{
|
||||||
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
HighArcLongDuration,//underhand lob at target: less horizontal speed and more air time
|
||||||
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
LowArcShortDuration,//overhand throw at target: more horizontal speed and less air time
|
||||||
}
|
}
|
||||||
#[derive(Clone,Debug)]
|
#[derive(Clone)]
|
||||||
pub enum GameMechanicSetTrajectory{
|
pub enum GameMechanicSetTrajectory{
|
||||||
AirTime(Time),//air time (relative to gravity direction) is invariant across mass and gravity changes
|
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
|
Height(Planar64),//boost height (relative to gravity direction) is invariant across mass and gravity changes
|
||||||
@ -165,6 +167,13 @@ pub enum StageElementBehaviour{
|
|||||||
Trigger,
|
Trigger,
|
||||||
Teleport,
|
Teleport,
|
||||||
Platform,
|
Platform,
|
||||||
|
//Acts like a trigger if you haven't hit all the checkpoints.
|
||||||
|
Checkpoint{
|
||||||
|
//if this is 2 you must have hit OrderedCheckpoint(0) OrderedCheckpoint(1) OrderedCheckpoint(2) to pass
|
||||||
|
ordered_checkpoint_id:Option<u32>,
|
||||||
|
//if this is 2 you must have hit at least 2 UnorderedCheckpoints to pass
|
||||||
|
unordered_checkpoint_count:u32,
|
||||||
|
},
|
||||||
JumpLimit(u32),
|
JumpLimit(u32),
|
||||||
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
//Speedtrap(TrapCondition),//Acts as a trigger with a speed condition
|
||||||
}
|
}
|
||||||
@ -193,15 +202,17 @@ pub enum TeleportBehaviour{
|
|||||||
pub struct GameMechanicAttributes{
|
pub struct GameMechanicAttributes{
|
||||||
pub zone:Option<GameMechanicZone>,
|
pub zone:Option<GameMechanicZone>,
|
||||||
pub booster:Option<GameMechanicBooster>,
|
pub booster:Option<GameMechanicBooster>,
|
||||||
|
pub checkpoint:Option<GameMechanicCheckpoint>,
|
||||||
pub trajectory:Option<GameMechanicSetTrajectory>,
|
pub trajectory:Option<GameMechanicSetTrajectory>,
|
||||||
pub teleport_behaviour:Option<TeleportBehaviour>,
|
pub teleport_behaviour:Option<TeleportBehaviour>,
|
||||||
pub accelerator:Option<GameMechanicAccelerator>,
|
pub accelerator:Option<GameMechanicAccelerator>,
|
||||||
}
|
}
|
||||||
impl GameMechanicAttributes{
|
impl GameMechanicAttributes{
|
||||||
pub fn any(&self)->bool{
|
pub fn any(&self)->bool{
|
||||||
self.booster.is_some()
|
self.zone.is_some()
|
||||||
|
||self.booster.is_some()
|
||||||
|
||self.checkpoint.is_some()
|
||||||
||self.trajectory.is_some()
|
||self.trajectory.is_some()
|
||||||
||self.zone.is_some()
|
|
||||||
||self.teleport_behaviour.is_some()
|
||self.teleport_behaviour.is_some()
|
||||||
||self.accelerator.is_some()
|
||self.accelerator.is_some()
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ pub struct GraphicsVertex {
|
|||||||
pub struct IndexedGroupFixedTexture{
|
pub struct IndexedGroupFixedTexture{
|
||||||
pub polys:Vec<IndexedPolygon>,
|
pub polys:Vec<IndexedPolygon>,
|
||||||
}
|
}
|
||||||
pub struct IndexedModelGraphicsSingleTexture{
|
pub struct IndexedGraphicsModelSingleTexture{
|
||||||
pub unique_pos:Vec<[f32; 3]>,
|
pub unique_pos:Vec<[f32; 3]>,
|
||||||
pub unique_tex:Vec<[f32; 2]>,
|
pub unique_tex:Vec<[f32; 2]>,
|
||||||
pub unique_normal:Vec<[f32; 3]>,
|
pub unique_normal:Vec<[f32; 3]>,
|
||||||
@ -19,37 +19,41 @@ pub struct IndexedModelGraphicsSingleTexture{
|
|||||||
pub unique_vertices:Vec<IndexedVertex>,
|
pub unique_vertices:Vec<IndexedVertex>,
|
||||||
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
pub texture:Option<u32>,//RenderPattern? material/texture/shader/flat color
|
||||||
pub groups: Vec<IndexedGroupFixedTexture>,
|
pub groups: Vec<IndexedGroupFixedTexture>,
|
||||||
pub instances:Vec<ModelGraphicsInstance>,
|
pub instances:Vec<GraphicsModelInstance>,
|
||||||
}
|
}
|
||||||
pub struct ModelGraphicsSingleTexture{
|
pub enum Entities{
|
||||||
pub instances: Vec<ModelGraphicsInstance>,
|
U32(Vec<Vec<u32>>),
|
||||||
pub vertices: Vec<GraphicsVertex>,
|
U16(Vec<Vec<u16>>),
|
||||||
pub entities: Vec<Vec<u16>>,
|
}
|
||||||
pub texture: Option<u32>,
|
pub struct GraphicsModelSingleTexture{
|
||||||
|
pub instances:Vec<GraphicsModelInstance>,
|
||||||
|
pub vertices:Vec<GraphicsVertex>,
|
||||||
|
pub entities:Entities,
|
||||||
|
pub texture:Option<u32>,
|
||||||
}
|
}
|
||||||
#[derive(Clone,PartialEq)]
|
#[derive(Clone,PartialEq)]
|
||||||
pub struct ModelGraphicsColor4(glam::Vec4);
|
pub struct GraphicsModelColor4(glam::Vec4);
|
||||||
impl ModelGraphicsColor4{
|
impl GraphicsModelColor4{
|
||||||
pub const fn get(&self)->glam::Vec4{
|
pub const fn get(&self)->glam::Vec4{
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl From<glam::Vec4> for ModelGraphicsColor4{
|
impl From<glam::Vec4> for GraphicsModelColor4{
|
||||||
fn from(value:glam::Vec4)->Self{
|
fn from(value:glam::Vec4)->Self{
|
||||||
Self(value)
|
Self(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl std::hash::Hash for ModelGraphicsColor4{
|
impl std::hash::Hash for GraphicsModelColor4{
|
||||||
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
fn hash<H: std::hash::Hasher>(&self,state:&mut H) {
|
||||||
for &f in self.0.as_ref(){
|
for &f in self.0.as_ref(){
|
||||||
bytemuck::cast::<f32,u32>(f).hash(state);
|
bytemuck::cast::<f32,u32>(f).hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Eq for ModelGraphicsColor4{}
|
impl Eq for GraphicsModelColor4{}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ModelGraphicsInstance{
|
pub struct GraphicsModelInstance{
|
||||||
pub transform:glam::Mat4,
|
pub transform:glam::Mat4,
|
||||||
pub normal_transform:glam::Mat3,
|
pub normal_transform:glam::Mat3,
|
||||||
pub color:ModelGraphicsColor4,
|
pub color:GraphicsModelColor4,
|
||||||
}
|
}
|
||||||
|
728
src/physics.rs
728
src/physics.rs
File diff suppressed because it is too large
Load Diff
134
src/physics_worker.rs
Normal file
134
src/physics_worker.rs
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
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<'a>(scope:&'a std::thread::Scope<'a,'_>,mut physics:crate::physics::PhysicsState,graphics_worker:crate::worker::INWorker<'a,crate::graphics_worker::Instruction>)->crate::worker::QNWorker<'a,TimedInstruction<Instruction>>{
|
||||||
|
let mut mouse_blocking=true;
|
||||||
|
let mut last_mouse_time=physics.next_mouse.time;
|
||||||
|
let mut timeline=std::collections::VecDeque::new();
|
||||||
|
crate::worker::QNWorker::new(scope,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=>{
|
||||||
|
let _=graphics_worker.send(crate::graphics_worker::Instruction::Render(physics.output(),ins.time,physics.next_mouse.pos));
|
||||||
|
},
|
||||||
|
Instruction::Resize(size,user_settings)=>{
|
||||||
|
//block!
|
||||||
|
graphics_worker.blocking_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();
|
||||||
|
},
|
||||||
|
_=>(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
@ -126,17 +126,21 @@ const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
|||||||
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
Planar64Vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
||||||
Planar64Vec3::int( 0, 0,-1),//CornerWedge::Front
|
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{
|
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);
|
unit_cube()
|
||||||
for pos in indexed_model.unique_pos.iter_mut(){
|
}
|
||||||
*pos=*pos/2;
|
#[derive(Default)]
|
||||||
}
|
pub struct CubeFaceDescription([Option<FaceDescription>;6]);
|
||||||
indexed_model
|
impl CubeFaceDescription{
|
||||||
|
pub fn insert(&mut self,index:CubeFace,value:FaceDescription){
|
||||||
|
self.0[index as usize]=Some(value);
|
||||||
|
}
|
||||||
|
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,6>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||||
|
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub type CubeFaceDescription=std::collections::HashMap::<CubeFace,FaceDescription>;
|
|
||||||
pub fn unit_cube()->crate::model::IndexedModel{
|
pub fn unit_cube()->crate::model::IndexedModel{
|
||||||
let mut t=CubeFaceDescription::new();
|
let mut t=CubeFaceDescription::default();
|
||||||
t.insert(CubeFace::Right,FaceDescription::default());
|
t.insert(CubeFace::Right,FaceDescription::default());
|
||||||
t.insert(CubeFace::Top,FaceDescription::default());
|
t.insert(CubeFace::Top,FaceDescription::default());
|
||||||
t.insert(CubeFace::Back,FaceDescription::default());
|
t.insert(CubeFace::Back,FaceDescription::default());
|
||||||
@ -145,17 +149,21 @@ pub fn unit_cube()->crate::model::IndexedModel{
|
|||||||
t.insert(CubeFace::Front,FaceDescription::default());
|
t.insert(CubeFace::Front,FaceDescription::default());
|
||||||
generate_partial_unit_cube(t)
|
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{
|
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);
|
unit_cube()
|
||||||
for pos in indexed_model.unique_pos.iter_mut(){
|
}
|
||||||
*pos=TEAPOT_TRANSFORM*(*pos)/10;
|
#[derive(Default)]
|
||||||
}
|
pub struct WedgeFaceDescription([Option<FaceDescription>;5]);
|
||||||
indexed_model
|
impl WedgeFaceDescription{
|
||||||
|
pub fn insert(&mut self,index:WedgeFace,value:FaceDescription){
|
||||||
|
self.0[index as usize]=Some(value);
|
||||||
|
}
|
||||||
|
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||||
|
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
pub type WedgeFaceDescription=std::collections::HashMap::<WedgeFace,FaceDescription>;
|
|
||||||
pub fn unit_wedge()->crate::model::IndexedModel{
|
pub fn unit_wedge()->crate::model::IndexedModel{
|
||||||
let mut t=WedgeFaceDescription::new();
|
let mut t=WedgeFaceDescription::default();
|
||||||
t.insert(WedgeFace::Right,FaceDescription::default());
|
t.insert(WedgeFace::Right,FaceDescription::default());
|
||||||
t.insert(WedgeFace::TopFront,FaceDescription::default());
|
t.insert(WedgeFace::TopFront,FaceDescription::default());
|
||||||
t.insert(WedgeFace::Back,FaceDescription::default());
|
t.insert(WedgeFace::Back,FaceDescription::default());
|
||||||
@ -163,9 +171,18 @@ pub fn unit_wedge()->crate::model::IndexedModel{
|
|||||||
t.insert(WedgeFace::Bottom,FaceDescription::default());
|
t.insert(WedgeFace::Bottom,FaceDescription::default());
|
||||||
generate_partial_unit_wedge(t)
|
generate_partial_unit_wedge(t)
|
||||||
}
|
}
|
||||||
pub type CornerWedgeFaceDescription=std::collections::HashMap::<CornerWedgeFace,FaceDescription>;
|
#[derive(Default)]
|
||||||
|
pub struct CornerWedgeFaceDescription([Option<FaceDescription>;5]);
|
||||||
|
impl CornerWedgeFaceDescription{
|
||||||
|
pub fn insert(&mut self,index:CornerWedgeFace,value:FaceDescription){
|
||||||
|
self.0[index as usize]=Some(value);
|
||||||
|
}
|
||||||
|
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||||
|
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
pub fn unit_cornerwedge()->crate::model::IndexedModel{
|
||||||
let mut t=CornerWedgeFaceDescription::new();
|
let mut t=CornerWedgeFaceDescription::default();
|
||||||
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
t.insert(CornerWedgeFace::Right,FaceDescription::default());
|
||||||
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
t.insert(CornerWedgeFace::TopBack,FaceDescription::default());
|
||||||
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
t.insert(CornerWedgeFace::TopLeft,FaceDescription::default());
|
||||||
@ -189,18 +206,6 @@ impl std::default::Default for FaceDescription{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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.
|
//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
|
//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{
|
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate::model::IndexedModel{
|
||||||
@ -212,7 +217,7 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
|
|||||||
let mut groups=Vec::new();
|
let mut groups=Vec::new();
|
||||||
let mut transforms=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.
|
//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(){
|
for (face_id,face_description) in face_descriptions.pairs(){
|
||||||
//assume that scanning short lists is faster than hashing.
|
//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){
|
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||||
transform_index
|
transform_index
|
||||||
@ -233,14 +238,6 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->crate:
|
|||||||
generated_color.push(face_description.color);
|
generated_color.push(face_description.color);
|
||||||
color_index
|
color_index
|
||||||
} as u32;
|
} 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
|
//always push normal
|
||||||
let normal_index=generated_normal.len() as u32;
|
let normal_index=generated_normal.len() as u32;
|
||||||
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
|
generated_normal.push(CUBE_DEFAULT_NORMALS[face_id]);
|
||||||
@ -327,7 +324,7 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
|
|||||||
let mut groups=Vec::new();
|
let mut groups=Vec::new();
|
||||||
let mut transforms=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.
|
//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(){
|
for (face_id,face_description) in face_descriptions.pairs(){
|
||||||
//assume that scanning short lists is faster than hashing.
|
//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){
|
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||||
transform_index
|
transform_index
|
||||||
@ -348,13 +345,6 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->crat
|
|||||||
generated_color.push(face_description.color);
|
generated_color.push(face_description.color);
|
||||||
color_index
|
color_index
|
||||||
} as u32;
|
} 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
|
//always push normal
|
||||||
let normal_index=generated_normal.len() as u32;
|
let normal_index=generated_normal.len() as u32;
|
||||||
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
|
generated_normal.push(WEDGE_DEFAULT_NORMALS[face_id]);
|
||||||
@ -439,7 +429,7 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
|||||||
let mut groups=Vec::new();
|
let mut groups=Vec::new();
|
||||||
let mut transforms=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.
|
//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(){
|
for (face_id,face_description) in face_descriptions.pairs(){
|
||||||
//assume that scanning short lists is faster than hashing.
|
//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){
|
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||||
transform_index
|
transform_index
|
||||||
@ -460,13 +450,6 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
|||||||
generated_color.push(face_description.color);
|
generated_color.push(face_description.color);
|
||||||
color_index
|
color_index
|
||||||
} as u32;
|
} 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
|
//always push normal
|
||||||
let normal_index=generated_normal.len() as u32;
|
let normal_index=generated_normal.len() as u32;
|
||||||
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
|
generated_normal.push(CORNERWEDGE_DEFAULT_NORMALS[face_id]);
|
||||||
|
@ -1,11 +1,14 @@
|
|||||||
use crate::integer::{Ratio64,Ratio64Vec2};
|
use crate::integer::{Ratio64,Ratio64Vec2};
|
||||||
|
#[derive(Clone)]
|
||||||
struct Ratio{
|
struct Ratio{
|
||||||
ratio:f64,
|
ratio:f64,
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedFov{
|
enum DerivedFov{
|
||||||
FromScreenAspect,
|
FromScreenAspect,
|
||||||
FromAspect(Ratio),
|
FromAspect(Ratio),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Fov{
|
enum Fov{
|
||||||
Exactly{x:f64,y:f64},
|
Exactly{x:f64,y:f64},
|
||||||
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
SpecifyXDeriveY{x:f64,y:DerivedFov},
|
||||||
@ -16,9 +19,11 @@ impl Default for Fov{
|
|||||||
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
Fov::SpecifyYDeriveX{x:DerivedFov::FromScreenAspect,y:1.0}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum DerivedSensitivity{
|
enum DerivedSensitivity{
|
||||||
FromRatio(Ratio64),
|
FromRatio(Ratio64),
|
||||||
}
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
enum Sensitivity{
|
enum Sensitivity{
|
||||||
Exactly{x:Ratio64,y:Ratio64},
|
Exactly{x:Ratio64,y:Ratio64},
|
||||||
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
SpecifyXDeriveY{x:Ratio64,y:DerivedSensitivity},
|
||||||
@ -30,7 +35,7 @@ impl Default for Sensitivity{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default,Clone)]
|
||||||
pub struct UserSettings{
|
pub struct UserSettings{
|
||||||
fov:Fov,
|
fov:Fov,
|
||||||
sensitivity:Sensitivity,
|
sensitivity:Sensitivity,
|
||||||
|
315
src/setup.rs
Normal file
315
src/setup.rs
Normal file
@ -0,0 +1,315 @@
|
|||||||
|
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,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
config.present_mode=wgpu::PresentMode::AutoNoVsync;
|
||||||
|
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
|
||||||
|
//but here I am doing it
|
||||||
|
let root_time=std::time::Instant::now();
|
||||||
|
std::thread::scope(|s|{
|
||||||
|
let window=crate::window::WindowContextSetup::new(&setup_context,window);
|
||||||
|
//the thread that spawns the physics thread
|
||||||
|
let window_thread=window.into_worker(s,setup_context);
|
||||||
|
|
||||||
|
//schedule frames at 165fps
|
||||||
|
let event_loop_proxy=event_loop.create_proxy();
|
||||||
|
|
||||||
|
s.spawn(move ||{
|
||||||
|
loop{
|
||||||
|
std::thread::sleep(std::time::Duration::from_nanos(1_000_000_000/165));
|
||||||
|
event_loop_proxy.send_event(()).ok();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
println!("Entering event loop...");
|
||||||
|
run_event_loop(event_loop,window_thread,root_time).unwrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_event_loop(
|
||||||
|
event_loop:winit::event_loop::EventLoop<()>,
|
||||||
|
window_thread:crate::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::UserEvent(())=>{
|
||||||
|
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();
|
||||||
|
},
|
||||||
|
_=>{}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
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::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,scope:&'a std::thread::Scope<'a,'_>,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(scope,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(scope,self.physics,graphics_thread),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_worker<'a>(self,scope:&'a std::thread::Scope<'a,'_>,setup_context:crate::setup::SetupContext)->crate::worker::QNWorker<'a,TimedInstruction<WindowInstruction>>{
|
||||||
|
let mut window_context=self.into_context(scope,setup_context);
|
||||||
|
crate::worker::QNWorker::new(scope,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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
141
src/worker.rs
141
src/worker.rs
@ -2,16 +2,68 @@ use std::thread;
|
|||||||
use std::sync::{mpsc,Arc};
|
use std::sync::{mpsc,Arc};
|
||||||
use parking_lot::Mutex;
|
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 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.
|
//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.
|
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
|
||||||
|
|
||||||
pub struct Worker<Task:Send,Value:Clone> {
|
/*
|
||||||
|
QR = WorkerDescription{
|
||||||
|
input:Queued,
|
||||||
|
output:Realtime(Single),
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
pub struct QRWorker<Task:Send,Value:Clone>{
|
||||||
sender: mpsc::Sender<Task>,
|
sender: mpsc::Sender<Task>,
|
||||||
value:Arc<Mutex<Value>>,
|
value:Arc<Mutex<Value>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,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 {
|
pub fn new<F:FnMut(Task)->Value+Send+'static>(value:Value,mut f:F) -> Self {
|
||||||
let (sender, receiver) = mpsc::channel::<Task>();
|
let (sender, receiver) = mpsc::channel::<Task>();
|
||||||
let ret=Self {
|
let ret=Self {
|
||||||
@ -45,28 +97,79 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CompatWorker<Task,Value:Clone,F>{
|
/*
|
||||||
data:std::marker::PhantomData<Task>,
|
QN = WorkerDescription{
|
||||||
f:F,
|
input:Queued,
|
||||||
value:Value,
|
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<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
|
impl<'a,Task:Send+'a> QNWorker<'a,Task>{
|
||||||
pub fn new(value:Value,f:F) -> Self {
|
pub fn new<F:FnMut(Task)+Send+'a>(scope:&'a thread::Scope<'a,'_>,mut f:F)->QNWorker<'a,Task>{
|
||||||
Self {
|
let (sender,receiver)=mpsc::channel::<Task>();
|
||||||
f,
|
let handle=scope.spawn(move ||{
|
||||||
value,
|
loop {
|
||||||
data:std::marker::PhantomData,
|
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>>{
|
||||||
pub fn send(&mut self,task:Task)->Result<(),()>{
|
self.sender.send(task)
|
||||||
self.value=(self.f)(task);
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn grab_clone(&self)->Value{
|
/*
|
||||||
self.value.clone()
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,7 +177,7 @@ impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
|
|||||||
fn test_worker() {
|
fn test_worker() {
|
||||||
println!("hiiiii");
|
println!("hiiiii");
|
||||||
// Create the worker thread
|
// Create the worker thread
|
||||||
let worker = Worker::new(crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO,crate::integer::Planar64Vec3::ZERO),
|
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)
|
|_|crate::physics::Body::with_pva(crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE,crate::integer::Planar64Vec3::ONE)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ pub fn zeroes2(a0:Planar64,a1:Planar64,a2:Planar64) -> Vec<Planar64>{
|
|||||||
if a2==Planar64::ZERO{
|
if a2==Planar64::ZERO{
|
||||||
return zeroes1(a0, a1);
|
return zeroes1(a0, a1);
|
||||||
}
|
}
|
||||||
let mut radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
|
let radicand=a1.get() as i128*a1.get() as i128-a2.get() as i128*a0.get() as i128*4;
|
||||||
if 0<radicand {
|
if 0<radicand {
|
||||||
//start with f64 sqrt
|
//start with f64 sqrt
|
||||||
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
|
let planar_radicand=Planar64::raw(unsafe{(radicand as f64).sqrt().to_int_unchecked()});
|
||||||
|
1
tools/arcane
Executable file
1
tools/arcane
Executable file
@ -0,0 +1 @@
|
|||||||
|
mangohud ../target/release/strafe-client bhop_maps/5692113331.rbxm
|
1
tools/bhop_maps
Symbolic link
1
tools/bhop_maps
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
/run/media/quat/Files/Documents/map-files/verify-scripts/maps/bhop_all/
|
1
tools/cross-compile.sh
Executable file
1
tools/cross-compile.sh
Executable file
@ -0,0 +1 @@
|
|||||||
|
cargo build --release --target x86_64-pc-windows-gnu
|
4
tools/make-demo.sh
Executable file
4
tools/make-demo.sh
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
mkdir -p ../target/demo
|
||||||
|
mv ../target/x86_64-pc-windows-gnu/release/strafe-client.exe ../target/demo/strafe-client.exe
|
||||||
|
rm ../target/demo.7z
|
||||||
|
7z a -t7z -mx=9 -mfb=273 -ms -md=31 -myx=9 -mtm=- -mmt -mmtf -md=1536m -mmf=bt3 -mmc=10000 -mpb=0 -mlc=0 ../target/demo.7z ../target/demo
|
1
tools/run
Executable file
1
tools/run
Executable file
@ -0,0 +1 @@
|
|||||||
|
mangohud ../target/release/strafe-client "$1"
|
4
tools/settings.conf
Normal file
4
tools/settings.conf
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
[camera]
|
||||||
|
sensitivity_x=98384
|
||||||
|
fov_y=1.0
|
||||||
|
#fov_x_from_y_ratio=1.33333333333333333333333333333333
|
1
tools/textures
Symbolic link
1
tools/textures
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
/run/media/quat/Files/Documents/map-files/verify-scripts/textures/dds/
|
1
tools/toc
Executable file
1
tools/toc
Executable file
@ -0,0 +1 @@
|
|||||||
|
mangohud ../target/release/strafe-client bhop_maps/5692152916.rbxm
|
Reference in New Issue
Block a user