Compare commits
35 Commits
winit-0.29
...
worker-poo
Author | SHA1 | Date | |
---|---|---|---|
07e85776bb | |||
2356286dc2 | |||
8cc86d88fc | |||
c1bc67fd3a | |||
d2c896031c | |||
d27187aa53 | |||
2e13d9b74e | |||
431611b62a | |||
b55a35c488 | |||
cb6102b9dc | |||
6eaec7d6a6 | |||
407b322664 | |||
d4c4d9e7d6 | |||
ff8c61ee32 | |||
00eb1ce19c | |||
168091408e | |||
ad0130db74 | |||
ee8f9ba9e4 | |||
1af8468e5b | |||
f8320c9df5 | |||
eb376c1e68 | |||
0bf253aa11 | |||
85b70331fd | |||
7fd592329e | |||
5260c2b40d | |||
b5febfad14 | |||
d1b491b6e7 | |||
8043862c99 | |||
b760a4bc65 | |||
124139274f | |||
7130eafc06 | |||
ab276b517b | |||
3721995791 | |||
72258d3549 | |||
02170bd91a |
830
Cargo.lock
generated
830
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
|
||||
|
||||
[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"
|
||||
@ -22,7 +19,7 @@ rbx_dom_weak = "2.5.0"
|
||||
rbx_reflection_database = "0.2.7"
|
||||
rbx_xml = "0.13.1"
|
||||
wgpu = "0.17.0"
|
||||
winit = { version = "0.29.2", features = ["rwh_05"] }
|
||||
winit = "0.28.6"
|
||||
|
||||
#[profile.release]
|
||||
#lto = true
|
||||
|
505
src/framework.rs
505
src/framework.rs
@ -1,505 +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::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().unwrap();
|
||||
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, elwt| {
|
||||
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::AboutToWait => {
|
||||
#[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,
|
||||
// ..
|
||||
// },
|
||||
WindowEvent::Resized(size),//ignoring scale factor changed for now because mutex bruh
|
||||
..
|
||||
} => {
|
||||
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::DeviceEvent {
|
||||
event,
|
||||
..
|
||||
} => {
|
||||
example.device_event(&window,event);
|
||||
},
|
||||
event::Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
event::KeyEvent {
|
||||
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
|
||||
state: event::ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
| WindowEvent::CloseRequested => {
|
||||
elwt.exit();
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
event::KeyEvent {
|
||||
logical_key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::ScrollLock),
|
||||
state: event::ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
println!("{:#?}", instance.generate_report());
|
||||
}
|
||||
WindowEvent::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");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
example.update(&window,&device,&queue,event);
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
||||
|
||||
#[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
1000
src/graphics.rs
Normal file
File diff suppressed because it is too large
Load Diff
315
src/graphics_context.rs
Normal file
315
src/graphics_context.rs
Normal 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();
|
||||
}
|
||||
_=>{}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
1396
src/main.rs
1396
src/main.rs
File diff suppressed because it is too large
Load Diff
232
src/physics.rs
232
src/physics.rs
@ -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
|
||||
@ -291,7 +275,7 @@ enum JumpImpulse{
|
||||
struct StyleModifiers{
|
||||
controls_mask:u32,//controls which are unable to be activated
|
||||
controls_held:u32,//controls which must be active to be able to strafe
|
||||
strafe_tick_rate:Option<Ratio64>,
|
||||
strafe_tick_rate:Ratio64,
|
||||
jump_impulse:JumpImpulse,
|
||||
jump_calculation:JumpCalculation,
|
||||
static_friction:Planar64,
|
||||
@ -305,7 +289,6 @@ struct StyleModifiers{
|
||||
mass:Planar64,
|
||||
mv:Planar64,
|
||||
air_accel_limit:Option<Planar64>,
|
||||
rocket_force:Option<Planar64>,
|
||||
gravity:Planar64Vec3,
|
||||
hitbox_halfsize:Planar64Vec3,
|
||||
}
|
||||
@ -332,7 +315,7 @@ impl StyleModifiers{
|
||||
Self{
|
||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||
controls_held:0,
|
||||
strafe_tick_rate:Some(Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap()),
|
||||
strafe_tick_rate:Ratio64::new(128,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||
jump_impulse:JumpImpulse::FromEnergy(Planar64::int(512)),
|
||||
jump_calculation:JumpCalculation::Energy,
|
||||
gravity:Planar64Vec3::int(0,-80,0),
|
||||
@ -341,7 +324,6 @@ impl StyleModifiers{
|
||||
mass:Planar64::int(1),
|
||||
mv:Planar64::int(2),
|
||||
air_accel_limit:None,
|
||||
rocket_force:None,
|
||||
walk_speed:Planar64::int(16),
|
||||
walk_accel:Planar64::int(80),
|
||||
ladder_speed:Planar64::int(16),
|
||||
@ -356,7 +338,7 @@ impl StyleModifiers{
|
||||
Self{
|
||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||
controls_held:0,
|
||||
strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
|
||||
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
||||
jump_calculation:JumpCalculation::Capped,
|
||||
gravity:Planar64Vec3::int(0,-100,0),
|
||||
@ -365,7 +347,6 @@ impl StyleModifiers{
|
||||
mass:Planar64::int(1),
|
||||
mv:Planar64::int(27)/10,
|
||||
air_accel_limit:None,
|
||||
rocket_force:None,
|
||||
walk_speed:Planar64::int(18),
|
||||
walk_accel:Planar64::int(90),
|
||||
ladder_speed:Planar64::int(18),
|
||||
@ -379,7 +360,7 @@ impl StyleModifiers{
|
||||
Self{
|
||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||
controls_held:0,
|
||||
strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
|
||||
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
||||
jump_calculation:JumpCalculation::Capped,
|
||||
gravity:Planar64Vec3::int(0,-50,0),
|
||||
@ -388,7 +369,6 @@ impl StyleModifiers{
|
||||
mass:Planar64::int(1),
|
||||
mv:Planar64::int(27)/10,
|
||||
air_accel_limit:None,
|
||||
rocket_force:None,
|
||||
walk_speed:Planar64::int(18),
|
||||
walk_accel:Planar64::int(90),
|
||||
ladder_speed:Planar64::int(18),
|
||||
@ -404,7 +384,7 @@ impl StyleModifiers{
|
||||
Self{
|
||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||
controls_held:0,
|
||||
strafe_tick_rate:Some(Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap()),
|
||||
strafe_tick_rate:Ratio64::new(100,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
|
||||
jump_calculation:JumpCalculation::Linear,
|
||||
gravity:Planar64Vec3::raw(0,-800<<28,0),
|
||||
@ -413,7 +393,6 @@ impl StyleModifiers{
|
||||
mass:Planar64::int(1),
|
||||
mv:Planar64::raw(30<<28),
|
||||
air_accel_limit:Some(Planar64::raw(150<<28)*66),
|
||||
rocket_force:None,
|
||||
walk_speed:Planar64::int(18),//?
|
||||
walk_accel:Planar64::int(90),//?
|
||||
ladder_speed:Planar64::int(18),//?
|
||||
@ -428,7 +407,7 @@ impl StyleModifiers{
|
||||
Self{
|
||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||
controls_held:0,
|
||||
strafe_tick_rate:Some(Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap()),
|
||||
strafe_tick_rate:Ratio64::new(66,Time::ONE_SECOND.nanos() as u64).unwrap(),
|
||||
jump_impulse:JumpImpulse::FromHeight(Planar64::raw(52<<28)),
|
||||
jump_calculation:JumpCalculation::Linear,
|
||||
gravity:Planar64Vec3::raw(0,-800<<28,0),
|
||||
@ -437,7 +416,6 @@ impl StyleModifiers{
|
||||
mass:Planar64::int(1),
|
||||
mv:Planar64::raw(30<<28),
|
||||
air_accel_limit:Some(Planar64::raw(150<<28)*66),
|
||||
rocket_force:None,
|
||||
walk_speed:Planar64::int(18),//?
|
||||
walk_accel:Planar64::int(90),//?
|
||||
ladder_speed:Planar64::int(18),//?
|
||||
@ -447,29 +425,6 @@ impl StyleModifiers{
|
||||
hitbox_halfsize:Planar64Vec3::raw(33<<28,73<<28,33<<28)/2,
|
||||
}
|
||||
}
|
||||
fn roblox_rocket()->Self{
|
||||
Self{
|
||||
controls_mask:!0,//&!(Self::CONTROL_MOVEUP|Self::CONTROL_MOVEDOWN),
|
||||
controls_held:0,
|
||||
strafe_tick_rate:None,
|
||||
jump_impulse:JumpImpulse::FromTime(Time::from_micros(715_588)),
|
||||
jump_calculation:JumpCalculation::Capped,
|
||||
gravity:Planar64Vec3::int(0,-100,0),
|
||||
static_friction:Planar64::int(2),
|
||||
kinetic_friction:Planar64::int(3),//unrealistic: kinetic friction is typically lower than static
|
||||
mass:Planar64::int(1),
|
||||
mv:Planar64::int(27)/10,
|
||||
air_accel_limit:None,
|
||||
rocket_force:Some(Planar64::int(200)),
|
||||
walk_speed:Planar64::int(18),
|
||||
walk_accel:Planar64::int(90),
|
||||
ladder_speed:Planar64::int(18),
|
||||
ladder_accel:Planar64::int(180),
|
||||
ladder_dot:(Planar64::int(1)/2).sqrt(),
|
||||
swim_speed:Planar64::int(12),
|
||||
hitbox_halfsize:Planar64Vec3::int(2,5,2)/2,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_control(&self,control:u32,controls:u32)->bool{
|
||||
controls&self.controls_mask&control==control
|
||||
@ -537,9 +492,10 @@ impl StyleModifiers{
|
||||
// return cross(cross(Normal,ControlDir),Normal)/sqrt(1-d*d)
|
||||
control_dir*self.walk_speed
|
||||
}
|
||||
fn get_propulsion_control_dir(&self,camera:&PhysicsCamera,controls:u32,next_mouse:&MouseState,time:Time)->Planar64Vec3{
|
||||
fn get_propulsion_target_velocity(&self,camera:&PhysicsCamera,controls:u32,next_mouse:&MouseState,time:Time)->Planar64Vec3{
|
||||
let camera_mat=camera.simulate_move_rotation(camera.mouse.lerp(&next_mouse,time));
|
||||
camera_mat*self.get_control_dir(controls)
|
||||
let control_dir=camera_mat*self.get_control_dir(controls);
|
||||
control_dir*self.walk_speed
|
||||
}
|
||||
}
|
||||
|
||||
@ -551,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
|
||||
@ -569,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{
|
||||
@ -764,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(),
|
||||
@ -858,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();
|
||||
@ -961,13 +839,11 @@ impl PhysicsState {
|
||||
}
|
||||
|
||||
fn next_strafe_instruction(&self) -> Option<TimedInstruction<PhysicsInstruction>> {
|
||||
self.style.strafe_tick_rate.as_ref().map(|strafe_tick_rate|{
|
||||
TimedInstruction{
|
||||
time:Time::from_nanos(strafe_tick_rate.rhs_div_int(strafe_tick_rate.mul_int(self.time.nanos())+1)),
|
||||
//only poll the physics if there is a before and after mouse event
|
||||
instruction:PhysicsInstruction::StrafeTick
|
||||
}
|
||||
})
|
||||
return Some(TimedInstruction{
|
||||
time:Time::from_nanos(self.style.strafe_tick_rate.rhs_div_int(self.style.strafe_tick_rate.mul_int(self.time.nanos())+1)),
|
||||
//only poll the physics if there is a before and after mouse event
|
||||
instruction:PhysicsInstruction::StrafeTick
|
||||
});
|
||||
}
|
||||
|
||||
//state mutated on collision:
|
||||
@ -1001,20 +877,16 @@ impl PhysicsState {
|
||||
// });
|
||||
// }
|
||||
|
||||
fn refresh_walk_target(&mut self)->Option<Planar64Vec3>{
|
||||
fn refresh_walk_target(&mut self){
|
||||
match &mut self.move_state{
|
||||
MoveState::Air|MoveState::Water=>None,
|
||||
MoveState::Air|MoveState::Water=>(),
|
||||
MoveState::Walk(WalkState{normal,state})=>{
|
||||
let n=normal;
|
||||
let a;
|
||||
(*state,a)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_walk_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
||||
Some(a)
|
||||
(*state,self.body.acceleration)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_walk_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
||||
},
|
||||
MoveState::Ladder(WalkState{normal,state})=>{
|
||||
let n=normal;
|
||||
let a;
|
||||
(*state,a)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_ladder_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
||||
Some(a)
|
||||
(*state,self.body.acceleration)=WalkEnum::with_target_velocity(&self.touching,&self.body,&self.style,&self.models,self.style.get_ladder_target_velocity(&self.camera,self.controls,&self.next_mouse,self.time),&n);
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -1185,7 +1057,7 @@ impl PhysicsState {
|
||||
},
|
||||
}
|
||||
//generate instruction
|
||||
if let Some(_face) = exit_face{
|
||||
if let Some(face) = exit_face{
|
||||
return Some(TimedInstruction {
|
||||
time: best_time,
|
||||
instruction: PhysicsInstruction::CollisionEnd(collision_data.clone())
|
||||
@ -1391,12 +1263,12 @@ 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(_)
|
||||
|PhysicsInstruction::CollisionEnd(_)
|
||||
|PhysicsInstruction::StrafeTick => self.advance_time(ins.time),
|
||||
|PhysicsInstruction::StrafeTick=>self.advance_time(ins.time),
|
||||
}
|
||||
match ins.instruction {
|
||||
PhysicsInstruction::CollisionStart(c) => {
|
||||
@ -1442,7 +1314,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
match booster{
|
||||
&crate::model::GameMechanicBooster::Affine(transform)=>v=transform.transform_point3(v),
|
||||
&crate::model::GameMechanicBooster::Velocity(velocity)=>v+=velocity,
|
||||
&crate::model::GameMechanicBooster::Energy{direction: _,energy: _}=>todo!(),
|
||||
&crate::model::GameMechanicBooster::Energy{direction,energy}=>todo!(),
|
||||
}
|
||||
self.touching.constrain_velocity(&self.models,&mut v);
|
||||
},
|
||||
@ -1453,10 +1325,10 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
match trajectory{
|
||||
crate::model::GameMechanicSetTrajectory::AirTime(_) => todo!(),
|
||||
crate::model::GameMechanicSetTrajectory::Height(_) => todo!(),
|
||||
crate::model::GameMechanicSetTrajectory::TargetPointTime { target_point: _, time: _ } => todo!(),
|
||||
crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint { target_point: _, speed: _, trajectory_choice: _ } => todo!(),
|
||||
crate::model::GameMechanicSetTrajectory::TargetPointTime { target_point, time } => todo!(),
|
||||
crate::model::GameMechanicSetTrajectory::TrajectoryTargetPoint { target_point, speed, trajectory_choice } => todo!(),
|
||||
&crate::model::GameMechanicSetTrajectory::Velocity(velocity)=>v=velocity,
|
||||
crate::model::GameMechanicSetTrajectory::DotVelocity { direction: _, dot: _ } => todo!(),
|
||||
crate::model::GameMechanicSetTrajectory::DotVelocity { direction, dot } => todo!(),
|
||||
}
|
||||
self.touching.constrain_velocity(&self.models,&mut v);
|
||||
},
|
||||
@ -1466,11 +1338,9 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
if self.style.get_control(StyleModifiers::CONTROL_JUMP,self.controls){
|
||||
self.jump();
|
||||
}
|
||||
if let Some(a)=self.refresh_walk_target(){
|
||||
self.body.acceleration=a;
|
||||
}
|
||||
self.refresh_walk_target();
|
||||
},
|
||||
PhysicsCollisionAttributes::Intersect{intersecting: _,general}=>{
|
||||
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
|
||||
//I think that setting the velocity to 0 was preventing surface contacts from entering an infinite loop
|
||||
self.touching.insert_intersect(c.model,c);
|
||||
run_teleport_behaviour(&general.teleport_behaviour,&mut self.game,&self.models,&self.modes,&self.style,&mut self.touching,&mut self.body,model);
|
||||
@ -1480,12 +1350,9 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
PhysicsInstruction::CollisionEnd(c) => {
|
||||
let model=c.model(&self.models).unwrap();
|
||||
match &model.attributes{
|
||||
PhysicsCollisionAttributes::Contact{contacting: _,general: _}=>{
|
||||
PhysicsCollisionAttributes::Contact{contacting,general}=>{
|
||||
self.touching.remove_contact(c.model);//remove contact before calling contact_constrain_acceleration
|
||||
let mut a=self.style.gravity;
|
||||
if let Some(rocket_force)=self.style.rocket_force{
|
||||
a+=self.style.get_propulsion_control_dir(&self.camera,self.controls,&self.next_mouse,self.time)*rocket_force;
|
||||
}
|
||||
self.touching.constrain_acceleration(&self.models,&mut a);
|
||||
self.body.acceleration=a;
|
||||
//check ground
|
||||
@ -1495,12 +1362,10 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
//TODO: make this more advanced checking contacts
|
||||
self.move_state=MoveState::Air;
|
||||
},
|
||||
_=>if let Some(a)=self.refresh_walk_target(){
|
||||
self.body.acceleration=a;
|
||||
},
|
||||
_=>self.refresh_walk_target(),
|
||||
}
|
||||
},
|
||||
PhysicsCollisionAttributes::Intersect{intersecting: _,general: _}=>{
|
||||
PhysicsCollisionAttributes::Intersect{intersecting,general}=>{
|
||||
self.touching.remove_intersect(c.model);
|
||||
},
|
||||
}
|
||||
@ -1574,14 +1439,7 @@ impl crate::instruction::InstructionConsumer<PhysicsInstruction> for PhysicsStat
|
||||
PhysicsInputInstruction::Idle => {refresh_walk_target=false;},//literally idle!
|
||||
}
|
||||
if refresh_walk_target{
|
||||
if let Some(a)=self.refresh_walk_target(){
|
||||
self.body.acceleration=a;
|
||||
}else if let Some(rocket_force)=self.style.rocket_force{
|
||||
let mut a=self.style.gravity;
|
||||
a+=self.style.get_propulsion_control_dir(&self.camera,self.controls,&self.next_mouse,self.time)*rocket_force;
|
||||
self.touching.constrain_acceleration(&self.models,&mut a);
|
||||
self.body.acceleration=a;
|
||||
}
|
||||
self.refresh_walk_target();
|
||||
}
|
||||
},
|
||||
}
|
||||
|
129
src/render_thread.rs
Normal file
129
src/render_thread.rs
Normal 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
152
src/window.rs
Normal 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)
|
||||
}
|
||||
}
|
210
src/worker.rs
210
src/worker.rs
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
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)>,
|
||||
}
|
||||
|
||||
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(&mut self,task:Task)->Result<(),()>{
|
||||
self.value=(self.f)(task);
|
||||
Ok(())
|
||||
pub fn send(&self,task:Task)->Result<(),mpsc::SendError<Task>>{
|
||||
self.sender.send(task)
|
||||
}
|
||||
|
||||
pub fn grab_clone(&self)->Value{
|
||||
self.value.clone()
|
||||
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)
|
||||
);
|
||||
|
||||
|
Reference in New Issue
Block a user