1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use std::{
collections::HashMap,
error::Error,
time::{Duration, Instant},
};
use glam::UVec2;
use wgpu::{
Adapter, Backends, Device, DeviceDescriptor, Features, InstanceDescriptor, Limits, Queue,
RequestAdapterOptions, Surface, SurfaceConfiguration, TextureFormat, TextureUsages,
};
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
window::WindowId,
};
use crate::{GpuCtx, RenderOptions, RenderPass, Texture, Window};
/// Represents basic information for a given windows rendering frame.
pub struct FrameContext<'a> {
//event loop
// pub user_ctx: &'a T,
pub delta_time: f64,
pub elapsed_time: f64,
pub winit_event: &'a Event<'a, ()>,
eloop: &'a EventLoopWindowTarget<()>,
}
/// Root struct which initializes WGPU, starts window management and handles application loop.
pub struct Tridify {
windows: HashMap<WindowId, Window>,
wb: Option<EventLoop<()>>,
wgpu: wgpu::Instance,
}
impl Tridify {
pub fn new() -> Self {
// cfg_if::cfg_if! {
// if #[cfg(target_arch = "wasm32")] {
// std::panic::set_hook(Box::new(console_error_panic_hook::hook));
// console_log::init_with_level(log::Level::Warn).expect("Couldn't initialize logger");
// } else {
// env_logger::init();
// }
// }
Self {
wgpu: wgpu::Instance::new(InstanceDescriptor::default()),
wb: Some(EventLoop::new()),
windows: HashMap::new(),
}
}
pub fn has_windows(&self) -> bool { !self.windows.is_empty() }
pub fn destroy_window(&mut self, wnd_id: &WindowId) { self.windows.remove(wnd_id); }
pub fn create_window(&mut self) -> Result<&mut Window, Box<dyn Error>> {
let wnd = winit::window::Window::new(self.wb.as_ref().unwrap())?;
let wnd_id = wnd.id();
let surface = unsafe {
self.wgpu
.create_surface(&wnd)
.expect("Error creating window surface")
};
let adapter = pollster::block_on(self.wgpu.request_adapter(&RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
force_fallback_adapter: false,
compatible_surface: Some(&surface),
}))
.ok_or("Error requesting adapter.")?;
let (device, queue) = pollster::block_on(adapter.request_device(
&DeviceDescriptor {
label: None,
features: Features::empty(),
limits: Limits::downlevel_webgl2_defaults(),
},
None,
))?;
let surface_config = SurfaceConfiguration {
view_formats: vec![surface.get_capabilities(&adapter).formats[0]],
usage: TextureUsages::RENDER_ATTACHMENT,
format: surface.get_capabilities(&adapter).formats[0],
width: wnd.inner_size().width,
height: wnd.inner_size().height,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
};
surface.configure(&device, &surface_config);
// #[cfg(target_arch = "wasm32")]
// {
// use winit::dpi::PhysicalSize;
// wnd.set_inner_size(PhysicalSize::new(450, 400));
// use winit::platform::web::WindowExtWebSys;
// web_sys::window()
// .and_then(|win| win.document())
// .and_then(|doc| {
// let dst = doc.get_element_by_id("wasm-example")?;
// let canvas = web_sys::Element::from(wnd.canvas());
// dst.append_child(&canvas).ok()?;
// Some(())
// })
// .expect("Couldn't append canvas to document body.");
// }
let window = Window {
user_loop: None,
ctx: GpuCtx {
created_time: Instant::now(),
last_draw_time: Instant::now(),
winit_wnd: wnd,
adapter,
device,
queue,
surface_config,
surface,
#[cfg(feature = "egui")]
egui: None,
},
};
self.windows.insert(wnd_id, window);
let window = self.windows.get_mut(&wnd_id).unwrap();
Ok(window)
}
/// Begin application logic loop. Should be called last when initializing since this function
/// can't never return.
pub fn start<T: 'static>(mut self, user_ctx: T) -> ! {
let event_loop = self.wb.take().unwrap();
event_loop.run(move |event, eloop, flow| match event {
Event::WindowEvent {
event: ref wnd_event,
window_id,
} => {
//Update egui if initilaized
#[cfg(feature = "egui")]
if let Ok(wnd) = self.get_window_mut(&window_id) {
if let Some(egui) = wnd.ctx.egui.as_mut() {
egui.event(&event);
}
}
match wnd_event {
WindowEvent::CloseRequested => {
self.destroy_window(&window_id);
if !self.has_windows() {
*flow = ControlFlow::Exit;
}
}
WindowEvent::Resized(size) => {
let wnd = self.get_window_mut(&window_id).unwrap();
wnd.ctx
.set_wnd_gpu_size(UVec2::new(size.width, size.height))
}
_ => {}
}
}
Event::MainEventsCleared => {
for (id, wnd) in self.windows.iter_mut() {
//TODO: User configurable
if wnd.ctx().last_draw_time.elapsed() >= Duration::from_millis(16.6 as u64) {
wnd.view_mut().redraw();
wnd.view_mut().last_draw_time = Instant::now();
}
}
}
Event::RedrawRequested(id) => {
let wnd = self.get_window_mut(&id).unwrap();
let frame_ctx = FrameContext {
delta_time: wnd.ctx().last_draw_time.elapsed().as_secs_f64(),
elapsed_time: wnd.ctx().time_running().as_secs_f64(),
winit_event: &event,
// user_ctx: &user_ctx,
eloop,
};
wnd.render_step(&frame_ctx);
wnd.view_mut().last_draw_time = Instant::now();
}
_ => {}
});
}
pub fn get_window(&self, id: &WindowId) -> Result<&Window, &str> {
self.windows.get(id).ok_or("No window found.")
}
pub fn get_window_mut(&mut self, id: &WindowId) -> Result<&mut Window, &str> {
self.windows.get_mut(id).ok_or("No window found.")
}
}