Compare commits

...

35 Commits

Author SHA1 Message Date
07e85776bb explore worker pool ideas 2023-10-20 18:59:15 -07:00
2356286dc2 move some stuff 2023-10-20 18:08:50 -07:00
8cc86d88fc note about adapter 2023-10-20 17:54:01 -07:00
c1bc67fd3a write some guesses 2023-10-20 17:51:52 -07:00
d2c896031c graphics resize 2023-10-20 17:51:52 -07:00
d27187aa53 fix many red underline 2023-10-20 17:51:52 -07:00
2e13d9b74e idk about this 2023-10-20 16:51:09 -07:00
431611b62a move window stuff to window 2023-10-20 16:01:17 -07:00
b55a35c488 pull apart framework completely 2023-10-20 16:01:17 -07:00
cb6102b9dc move out of main fixings 2023-10-20 15:56:03 -07:00
6eaec7d6a6 Input::Mailbox 2023-10-19 22:56:28 -07:00
407b322664 note about using functions for input and output 2023-10-19 22:56:28 -07:00
d4c4d9e7d6 Input::Query 2023-10-19 22:56:28 -07:00
ff8c61ee32 comment on issue 2023-10-19 22:56:20 -07:00
00eb1ce19c drop dead code 2023-10-19 22:56:20 -07:00
168091408e shrink pollster onto the only future in the code 2023-10-19 22:56:20 -07:00
ad0130db74 drop async_executor dep 2023-10-19 22:56:20 -07:00
ee8f9ba9e4 drop env_logger & log deps 2023-10-19 22:56:20 -07:00
1af8468e5b drop wasm32 code 2023-10-19 22:56:20 -07:00
f8320c9df5 why did they do it like that 2023-10-19 22:56:20 -07:00
eb376c1e68 put window stuff in here 2023-10-19 22:56:20 -07:00
0bf253aa11 remove graphics stuff from main 2023-10-19 22:32:01 -07:00
85b70331fd thread load file 2023-10-19 22:32:01 -07:00
7fd592329e split load file 2023-10-19 22:32:01 -07:00
5260c2b40d try unpub 2023-10-19 22:32:01 -07:00
b5febfad14 introduce render_thread to manage physics and graphics 2023-10-19 22:32:01 -07:00
d1b491b6e7 wip: implement INWorker 2023-10-19 22:32:01 -07:00
8043862c99 delete compat worker 2023-10-19 22:32:01 -07:00
b760a4bc65 idle does not advance body 2023-10-19 22:32:01 -07:00
124139274f real threads + GraphicsInstruction + thread accessible mouse 2023-10-19 22:32:01 -07:00
7130eafc06 implement QNWorker 2023-10-19 22:24:20 -07:00
ab276b517b rename workers 2023-10-19 22:24:20 -07:00
3721995791 WorkerDescription brainstorming (make invalid states unrepresentable) 2023-10-19 22:24:20 -07:00
72258d3549 self.graphics->self 2023-10-18 18:30:44 -07:00
02170bd91a move graphics code 2023-10-18 18:30:40 -07:00
10 changed files with 1925 additions and 2115 deletions

195
Cargo.lock generated
View File

@ -107,35 +107,6 @@ dependencies = [
"libloading 0.7.4",
]
[[package]]
name = "async-executor"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fa3dc5f2a8564f07759c008b9109dc0d39de92a88d5588b8a5036d286383afb"
dependencies = [
"async-lock",
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"slab",
]
[[package]]
name = "async-lock"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b"
dependencies = [
"event-listener",
]
[[package]]
name = "async-task"
version = "4.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc7ab41815b3c653ccd2978ec3255c81349336702dfdf62ee6f7069b12a3aae"
[[package]]
name = "autocfg"
version = "1.1.0"
@ -322,15 +293,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf43edc576402991846b093a7ca18a3477e0ef9c588cde84964b5d3e43016642"
[[package]]
name = "concurrent-queue"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "configparser"
version = "3.0.2"
@ -392,15 +354,6 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
@ -474,61 +427,12 @@ dependencies = [
"num-traits 0.1.43",
]
[[package]]
name = "env_logger"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0"
dependencies = [
"humantime",
"is-terminal",
"log",
"regex",
"termcolor",
]
[[package]]
name = "equivalent"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "errno"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd"
dependencies = [
"errno-dragonfly",
"libc",
"windows-sys 0.48.0",
]
[[package]]
name = "errno-dragonfly"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "event-listener"
version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "fastrand"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
dependencies = [
"instant",
]
[[package]]
name = "fdeflate"
version = "0.3.0"
@ -590,33 +494,6 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "futures-core"
version = "0.3.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c"
[[package]]
name = "futures-io"
version = "0.3.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964"
[[package]]
name = "futures-lite"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"memchr",
"parking",
"pin-project-lite",
"waker-fn",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@ -744,24 +621,12 @@ dependencies = [
"winapi",
]
[[package]]
name = "hermit-abi"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b"
[[package]]
name = "hexf-parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "indexmap"
version = "1.9.3"
@ -794,17 +659,6 @@ dependencies = [
"web-sys",
]
[[package]]
name = "is-terminal"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b"
dependencies = [
"hermit-abi",
"rustix",
"windows-sys 0.48.0",
]
[[package]]
name = "jni-sys"
version = "0.3.0"
@ -895,12 +749,6 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503"
[[package]]
name = "lock_api"
version = "0.4.10"
@ -1241,12 +1089,6 @@ dependencies = [
"ttf-parser",
]
[[package]]
name = "parking"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e"
[[package]]
name = "parking_lot"
version = "0.12.1"
@ -1282,12 +1124,6 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94"
[[package]]
name = "pin-project-lite"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
[[package]]
name = "pkg-config"
version = "0.3.27"
@ -1563,19 +1399,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]]
name = "rustix"
version = "0.38.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed6248e1caa625eb708e266e06159f135e8c26f2bb7ceb72dc4b2766d0340964"
dependencies = [
"bitflags 2.4.0",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.48.0",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
@ -1627,15 +1450,6 @@ version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"
[[package]]
name = "slab"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
[[package]]
name = "slotmap"
version = "1.0.6"
@ -1690,14 +1504,11 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
name = "strafe-client"
version = "0.8.0"
dependencies = [
"async-executor",
"bytemuck",
"configparser",
"ddsfile",
"env_logger",
"glam",
"lazy-regex",
"log",
"obj",
"parking_lot",
"pollster",
@ -1856,12 +1667,6 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "waker-fn"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"

View File

@ -6,14 +6,11 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-executor = "1.5.1"
bytemuck = { version = "1.13.1", features = ["derive"] }
configparser = "3.0.2"
ddsfile = "0.5.1"
env_logger = "0.10.0"
glam = "0.24.1"
lazy-regex = "3.0.2"
log = "0.4.20"
obj = "0.10.2"
parking_lot = "0.12.1"
pollster = "0.3.0"

View File

@ -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() {}

1000
src/graphics.rs Normal file

File diff suppressed because it is too large Load Diff

315
src/graphics_context.rs Normal file
View File

@ -0,0 +1,315 @@
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()
}
}
pub fn required_limits() -> wgpu::Limits {
wgpu::Limits::downlevel_webgl2_defaults() // These downlevel limits will allow the code to run on all possible hardware
}
struct GraphicsContextPartial1{
backends:wgpu::Backends,
instance:wgpu::Instance,
}
fn create_instance()->GraphicsContextPartial1{
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();
GraphicsContextPartial1{
backends,
instance:wgpu::Instance::new(wgpu::InstanceDescriptor{
backends,
dx12_shader_compiler,
}),
}
}
impl GraphicsContextPartial1{
fn create_surface(self,window:&winit::window::Window)->Result<GraphicsContextPartial2,wgpu::CreateSurfaceError>{
Ok(GraphicsContextPartial2{
backends:self.backends,
instance:self.instance,
surface:unsafe{self.instance.create_surface(window)}?
})
}
}
struct GraphicsContextPartial2{
backends:wgpu::Backends,
instance:wgpu::Instance,
surface:wgpu::Surface,
}
impl GraphicsContextPartial2{
fn pick_adapter(self)->GraphicsContextPartial3{
let adapter;
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
);
GraphicsContextPartial3{
instance:self.instance,
surface:self.surface,
adapter,
}
}
}
struct GraphicsContextPartial3{
instance:wgpu::Instance,
surface:wgpu::Surface,
adapter:wgpu::Adapter,
}
impl GraphicsContextPartial3{
fn request_device(self)->GraphicsContextPartial4{
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!");
GraphicsContextPartial4{
instance:self.instance,
surface:self.surface,
adapter:self.adapter,
device,
queue,
}
}
}
struct GraphicsContextPartial4{
instance:wgpu::Instance,
surface:wgpu::Surface,
adapter:wgpu::Adapter,
device:wgpu::Device,
queue:wgpu::Queue,
}
impl GraphicsContextPartial4{
fn configure_surface(self,size:&winit::dpi::PhysicalSize<u32>)->GraphicsContext{
let mut config=self.surface
.get_default_config(&self.adapter, size.width, size.height)
.expect("Surface isn't supported by the adapter.");
let surface_view_format=config.format.add_srgb_suffix();
config.view_formats.push(surface_view_format);
self.surface.configure(&self.device, &config);
GraphicsContext{
instance:self.instance,
surface:self.surface,
adapter:self.adapter,
device:self.device,
queue:self.queue,
config,
}
}
}
pub struct GraphicsContext{
pub instance:wgpu::Instance,
pub surface:wgpu::Surface,
pub adapter:wgpu::Adapter,
pub device:wgpu::Device,
pub queue:wgpu::Queue,
pub config:wgpu::SurfaceConfiguration,
}
pub fn setup(title:&str)->GraphicsContextSetup{
let event_loop=winit::event_loop::EventLoop::new();
let window=crate::window::WindowState::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();
GraphicsContextSetup{
window,
event_loop,
partial_graphics_context:partial_4,
}
}
struct GraphicsContextSetup{
window:winit::window::Window,
event_loop:winit::event_loop::EventLoop<()>,
partial_graphics_context:GraphicsContextPartial4,
}
impl GraphicsContextSetup{
fn into_split(self)->(winit::window::Window,winit::event_loop::EventLoop<()>,GraphicsContext){
let size=self.window.inner_size();
//Steal values and drop self
(
self.window,
self.event_loop,
self.partial_graphics_context.configure_surface(&size),
)
}
pub fn start(self,mut global_state:crate::GlobalState){
let (window,event_loop,graphics_context)=self.into_split();
println!("Entering render loop...");
event_loop.run(move |event,_,control_flow|{
*control_flow=if cfg!(feature="metal-auto-capture"){
winit::event_loop::ControlFlow::Exit
}else{
winit::event_loop::ControlFlow::Poll
};
match event{
winit::event::Event::RedrawEventsCleared=>{
window.request_redraw();
}
winit::event::Event::WindowEvent {
event:
winit::event::WindowEvent::Resized(size)
| winit::event::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
// this has been fixed if I update winit (remove the if statement and only use the else case)
//drop adapter when you delete this
let max_dimension=graphics_context.adapter.limits().max_texture_dimension_2d;
if max_dimension<size.width||max_dimension<size.height{
println!(
"The resizing size {:?} exceeds the limit of {}.",
size,
max_dimension
);
}else{
println!("Resizing to {:?}",size);
graphics_context.config.width=size.width.max(1);
graphics_context.config.height=size.height.max(1);
window.resize(&graphics_context);
graphics_context.surface.configure(&graphics_context.device,&graphics_context.config);
}
}
winit::event::Event::WindowEvent{event,..}=>match event{
winit::event::WindowEvent::KeyboardInput{
input:
winit::event::KeyboardInput{
virtual_keycode:Some(winit::event::VirtualKeyCode::Escape),
state: winit::event::ElementState::Pressed,
..
},
..
}
|winit::event::WindowEvent::CloseRequested=>{
*control_flow=winit::event_loop::ControlFlow::Exit;
}
winit::event::WindowEvent::KeyboardInput{
input:
winit::event::KeyboardInput{
virtual_keycode:Some(winit::event::VirtualKeyCode::Scroll),
state: winit::event::ElementState::Pressed,
..
},
..
}=>{
println!("{:#?}",graphics_context.instance.generate_report());
}
_=>{
global_state.update(event);
}
},
winit::event::Event::DeviceEvent{
event,
..
} => {
global_state.device_event(event);
},
winit::event::Event::RedrawRequested(_)=>{
let frame=match graphics_context.surface.get_current_texture(){
Ok(frame)=>frame,
Err(_)=>{
graphics_context.surface.configure(&graphics_context.device,&graphics_context.config);
graphics_context.surface
.get_current_texture()
.expect("Failed to acquire next surface texture!")
}
};
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
format:Some(graphics_context.config.view_formats[0]),
..wgpu::TextureViewDescriptor::default()
});
graphics.render(&view,&graphics_context.device,&graphics_context.queue);
frame.present();
}
_=>{}
}
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -32,23 +32,7 @@ pub enum PhysicsInputInstruction {
Reset,
Idle,
}
#[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,
Idle,
//Idle: there were no input events, but the simulation is safe to advance to this timestep
//for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation.
}
#[derive(Clone,Hash)]
pub struct Body {
position: Planar64Vec3,//I64 where 2^32 = 1 u
@ -523,15 +507,15 @@ enum MoveState{
}
pub struct PhysicsState{
pub time:Time,
time:Time,
body:Body,
world:WorldState,//currently there is only one state the world can be in
pub game:GameMechanicsState,
game:GameMechanicsState,
style:StyleModifiers,
touching:TouchingState,
//camera must exist in state because wormholes modify the camera, also camera punch
camera:PhysicsCamera,
next_mouse:MouseState,//Where is the mouse headed next
pub next_mouse:MouseState,//Where is the mouse headed next
controls:u32,
move_state:MoveState,
//all models
@ -541,7 +525,7 @@ pub struct PhysicsState{
modes:Modes,
//the spawn point is where you spawn when you load into the map.
//This is not the same as Reset which teleports you to Spawn0
pub spawn_point:Planar64Vec3,
spawn_point:Planar64Vec3,
}
#[derive(Clone)]
pub struct PhysicsOutputState{
@ -736,93 +720,6 @@ impl PhysicsState {
self.touching.clear();
}
pub fn into_worker(mut self)->crate::worker::CompatWorker<TimedInstruction<InputInstruction>,PhysicsOutputState,Box<dyn FnMut(TimedInstruction<InputInstruction>)->PhysicsOutputState>>{
let mut mouse_blocking=true;
let mut last_mouse_time=self.next_mouse.time;
let mut timeline=std::collections::VecDeque::new();
crate::worker::CompatWorker::new(self.output(),Box::new(move |ins:TimedInstruction<InputInstruction>|{
if if let Some(phys_input)=match ins.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:self.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),
InputInstruction::Idle=>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-self.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:self.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(){
self.run(instruction.time);
self.process_instruction(TimedInstruction{
time:instruction.time,
instruction:PhysicsInstruction::Input(instruction.instruction),
});
}
}
self.output()
}))
}
pub fn output(&self)->PhysicsOutputState{
PhysicsOutputState{
body:self.body.clone(),
@ -830,6 +727,15 @@ impl PhysicsState {
}
}
pub fn spawn(&mut self,spawn_point:Planar64Vec3){
self.game.stage_id=0;
self.spawn_point=spawn_point;
self.process_instruction(crate::instruction::TimedInstruction{
time:self.time,
instruction: PhysicsInstruction::Input(PhysicsInputInstruction::Reset),
});
}
pub fn generate_models(&mut self,indexed_models:&crate::model::IndexedModelInstances){
let mut starts=Vec::new();
let mut spawns=Vec::new();
@ -1357,7 +1263,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
}
//selectively update body
match &ins.instruction {
//PhysicsInstruction::Input(InputInstruction::MoveMouse(_)) => (),//dodge time for mouse movement
PhysicsInstruction::Input(PhysicsInputInstruction::Idle)=>self.time=ins.time,//idle simply updates time
PhysicsInstruction::Input(_)
|PhysicsInstruction::ReachWalkTargetVelocity
|PhysicsInstruction::CollisionStart(_)

129
src/render_thread.rs Normal file
View File

@ -0,0 +1,129 @@
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,
Render,
//Idle: there were no input events, but the simulation is safe to advance to this timestep
//for interpolation / networking / playback reasons, most playback heads will always want
//to be 1 instruction ahead to generate the next state for interpolation.
}
pub struct RenderState{
physics:crate::physics::PhysicsState,
graphics:crate::graphics::GraphicsState,
}
impl RenderState{
pub fn new(user_settings:&crate::settings::UserSettings,indexed_model_instances:crate::model::IndexedModelInstances){
let mut physics=crate::physics::PhysicsState::default();
physics.spawn(indexed_model_instances.spawn_point);
physics.load_user_settings(user_settings);
physics.generate_models(&indexed_model_instances);
let mut graphics=Self::new_graphics_state();
graphics.load_user_settings(user_settings);
graphics.generate_models(indexed_model_instances);
//manual reset
}
pub fn into_worker(mut self)->crate::worker::CNWorker<TimedInstruction<InputInstruction>>{
let mut mouse_blocking=true;
let mut last_mouse_time=self.physics.next_mouse.time;
let mut timeline=std::collections::VecDeque::new();
crate::worker::CNWorker::new(move |ins:TimedInstruction<InputInstruction>|{
let mut render=false;
if if let Some(phys_input)=match ins.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:self.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),
InputInstruction::Render=>{render=true;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-self.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:self.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(){
self.physics.run(instruction.time);
self.physics.process_instruction(TimedInstruction{
time:instruction.time,
instruction:crate::physics::PhysicsInstruction::Input(instruction.instruction),
});
}
}
if render{
self.graphics.render();
}
})
}
}

152
src/window.rs Normal file
View File

@ -0,0 +1,152 @@
pub struct WindowState{
//ok
}
impl WindowState{
fn resize(&mut self);
fn render(&self);
fn update(&mut self, window: &winit::window::Window, event: winit::event::WindowEvent) {
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
match event {
winit::event::WindowEvent::DroppedFile(path)=>{
std::thread::spawn(move ||{
let indexed_model_instances=load_file(path);
self.render_thread.send(Instruction::Die(indexed_model_instances));
});
},
winit::event::WindowEvent::Focused(state)=>{
//pause unpause
//recalculate pressed keys on focus
},
winit::event::WindowEvent::KeyboardInput {
input:winit::event::KeyboardInput{state, virtual_keycode,..},
..
}=>{
let s=match state {
winit::event::ElementState::Pressed => true,
winit::event::ElementState::Released => false,
};
match virtual_keycode{
Some(winit::event::VirtualKeyCode::Tab)=>{
if s{
self.manual_mouse_lock=false;
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
match 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 window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
Ok(())=>(),
Err(_)=>{
match window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
Ok(())=>(),
Err(e)=>{
self.manual_mouse_lock=true;
println!("Could not confine cursor: {:?}",e)
},
}
}
}
}
window.set_cursor_visible(s);
},
Some(winit::event::VirtualKeyCode::F11)=>{
if s{
if window.fullscreen().is_some(){
window.set_fullscreen(None);
}else{
window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
}
}
},
Some(winit::event::VirtualKeyCode::Escape)=>{
if s{
self.manual_mouse_lock=false;
match window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
window.set_cursor_visible(true);
}
},
Some(keycode)=>{
if let Some(input_instruction)=match keycode {
winit::event::VirtualKeyCode::W => Some(InputInstruction::MoveForward(s)),
winit::event::VirtualKeyCode::A => Some(InputInstruction::MoveLeft(s)),
winit::event::VirtualKeyCode::S => Some(InputInstruction::MoveBack(s)),
winit::event::VirtualKeyCode::D => Some(InputInstruction::MoveRight(s)),
winit::event::VirtualKeyCode::E => Some(InputInstruction::MoveUp(s)),
winit::event::VirtualKeyCode::Q => Some(InputInstruction::MoveDown(s)),
winit::event::VirtualKeyCode::Space => Some(InputInstruction::Jump(s)),
winit::event::VirtualKeyCode::Z => Some(InputInstruction::Zoom(s)),
winit::event::VirtualKeyCode::R => if s{Some(InputInstruction::Reset)}else{None},
_ => None,
}{
self.physics_thread.send(TimedInstruction{
time,
instruction:input_instruction,
}).unwrap();
}
},
_=>(),
}
},
_=>(),
}
}
fn device_event(&mut self, window: &winit::window::Window, event: winit::event::DeviceEvent) {
//there's no way this is the best way get a timestamp.
let time=integer::Time::from_nanos(self.start_time.elapsed().as_nanos() as i64);
match event {
winit::event::DeviceEvent::MouseMotion {
delta,//these (f64,f64) are integers on my machine
} => {
if self.manual_mouse_lock{
match window.set_cursor_position(winit::dpi::PhysicalPosition::new(self.graphics.camera.screen_size.x as f32/2.0, self.graphics.camera.screen_size.y as f32/2.0)){
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: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: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 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)
}
}

View File

@ -1,17 +1,69 @@
use std::thread;
use std::sync::{mpsc,Arc};
use parking_lot::Mutex;
use parking_lot::{Mutex,Condvar};
//WorkerPool
struct Pool(u32);
enum PoolOrdering{
Single,//single thread cannot get out of order
Ordered(u32),//order matters and should be buffered/dropped according to ControlFlow
Unordered(u32),//order does not matter
}
//WorkerInput
enum Input{
//no input, workers have everything needed at creation
None,
//Immediate input to any available worker, dropped if they are overflowing (all workers are busy)
Immediate,
//Queued input is ordered, but serial jobs that mutate state (such as running physics) can only be done with a single worker
Queued,//"Fifo"
//Query a function to get next input when a thread becomes available
//worker stops querying when Query function returns None and dies after all threads complete
//lifetimes sound crazy on this one
Query,
//Queue of length one, the input is replaced if it is submitted twice before the current work finishes
Mailbox,
}
//WorkerOutput
enum Output{
None(Pool),
Realtime(PoolOrdering),//outputs are dropped if they are out of order and order is demanded
Buffered(PoolOrdering),//outputs are held back internally if they are out of order and order is demanded
}
//It would be possible to implement all variants
//with a query input function and callback output function but I'm not sure if that's worth it.
//Immediate = Condvar
//Queued = receiver.recv()
//a callback function would need to use an async runtime!
//realtime output is an arc mutex of the output value that is assigned every time a worker completes a job
//buffered output produces a receiver object that can be passed to the creation of another worker
//when ordering is requested, output is ordered by the order each thread is run
//which is the same as the order that the input data is processed except for Input::None which has no input data
//WorkerDescription
struct Description{
input:Input,
output:Output,
}
//The goal here is to have a worker thread that parks itself when it runs out of work.
//The worker thread publishes the result of its work back to the worker object for every item in the work queue.
//Previous values do not matter as soon as a new value is produced, which is why it's called "Realtime"
//The physics (target use case) knows when it has not changed the body, so not updating the value is also an option.
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>,
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 {
let (sender, receiver) = mpsc::channel::<Task>();
let ret=Self {
@ -45,28 +97,146 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
}
}
pub struct CompatWorker<Task,Value:Clone,F>{
data:std::marker::PhantomData<Task>,
f:F,
value:Value,
/*
QN = WorkerDescription{
input:Queued,
output:None(Single),
}
*/
//None Output Worker does all its work internally from the perspective of the work submitter
pub struct QNWorker<Task:Send> {
sender: mpsc::Sender<Task>,
}
impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
pub fn new(value:Value,f:F) -> Self {
Self {
f,
value,
data:std::marker::PhantomData,
impl<Task:Send+'static> QNWorker<Task>{
pub fn new<F:FnMut(Task)+Send+'static>(mut f:F)->Self{
let (sender,receiver)=mpsc::channel::<Task>();
let ret=Self {
sender,
};
thread::spawn(move ||{
loop {
match receiver.recv() {
Ok(task)=>f(task),
Err(_)=>{
println!("Worker stopping.",);
break;
}
}
}
});
ret
}
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
self.sender.send(task)
}
}
pub fn send(&mut self,task:Task)->Result<(),()>{
self.value=(self.f)(task);
Ok(())
/*
IN = WorkerDescription{
input:Immediate,
output:None(Single),
}
*/
//Inputs are dropped if the worker is busy
pub struct INWorker<Task:Clone>{
input:Arc<(Mutex<Task>,Condvar)>,
}
pub fn grab_clone(&self)->Value{
self.value.clone()
impl<Task:Clone+Send+'static> INWorker<Task>{
pub fn new<F:FnMut(Task)+Send+'static>(task:Task,mut f:F)->Self{
let ret=Self {
input:Arc::new((Mutex::new(task),Condvar::new())),
};
let input=ret.input.clone();
thread::spawn(move ||{
loop {
input.1.wait(&mut input.0.lock());
f(input.0.lock().clone());
}
});
ret
}
pub fn send(&self,task:Task){
*self.input.0.lock()=task;
self.input.1.notify_one();
}
}
//worker pools work by cloning a mpsc and passing it into the thread, the thread sends its results through that
//worker pools have a master thread that manages the pool so that the work submission thread does not need to implement async
pub struct QQWorkerPool<Task:Send,Value:Send>{
sender:mpsc::Sender<Task>,
queue:Arc<Mutex<std::collections::VecDeque<Value>>>,
}
impl<Task:Send+'static,Value:Send+'static> QQWorkerPool<Task,Value>{
pub fn new<F:Fn(Task)->Value+Send+'static>(pool_size:usize,f:F)->Self{
let (task_sender,task_receiver)=mpsc::channel::<Task>();
let (value_sender,value_receiver)=mpsc::channel::<Value>();
let ret=Self{
sender:task_sender,
queue:Arc::new(Mutex::new(std::collections::VecDeque::new())),
};
let mut queue_collect=ret.queue.clone();
let mut worker_senders=Vec::with_capacity(pool_size);
let mut active_workers_collect=Arc::new(Mutex::new(0usize));
let mut active_workers_dispatch=active_workers_collect.clone();
let mut condvar_collect=Arc::new(Condvar::new());
let mut condvar_dispatch=condvar_collect.clone();
//task dispatch thread
thread::spawn(move ||{
loop{
//block if no workers are available, value collection thread will notify
let n=*active_workers_dispatch.lock();
if n==pool_size{
//wait for notifiy
condvar_dispatch.wait(&mut active_workers_dispatch.lock());
}
match task_receiver.recv(){
Ok(task)=>{
*active_workers_dispatch.lock()+=1;
//workers are never full here
//else if workers busy: spawn a new worker
//else: send task to an available worker
}
Err(_)=>{
println!("Dispatch stopping.",);
break;
}
}
}
});
//value collection thread (bad idea, put this logic in each thread)
thread::spawn(move ||{
loop{
match value_receiver.recv(){
Ok(value)=>{
//maybe I can be smart with this as a signal that a worker finished a task
let n=*active_workers_collect.lock();
*active_workers_collect.lock()-=1;
if n==pool_size{
condvar_collect.notify_one();
}
(*queue_collect.lock()).push_front(value);
}
Err(_)=>{
println!("Collection stopping.",);
break;
}
}
}
});
ret
}
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
self.sender.send(task)
}
pub fn get(&self)->Option<Value>{
(*self.queue.lock()).pop_back()
}
}
@ -74,7 +244,7 @@ impl<Task,Value:Clone,F:FnMut(Task)->Value> CompatWorker<Task,Value,F> {
fn test_worker() {
println!("hiiiii");
// 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)
);