|
|
@@ -0,0 +1,296 @@
|
|
|
+use crate::render::{
|
|
|
+ atlas::*,
|
|
|
+ camera::*,
|
|
|
+ depth::*,
|
|
|
+ object::*,
|
|
|
+ pipeline,
|
|
|
+ vertex::*
|
|
|
+};
|
|
|
+
|
|
|
+use std::{
|
|
|
+ fs,
|
|
|
+ iter
|
|
|
+};
|
|
|
+
|
|
|
+use bytemuck::cast_slice;
|
|
|
+use chair::{Mesh, MeshReader};
|
|
|
+use wgpu::{
|
|
|
+ util::{BufferInitDescriptor, DeviceExt},
|
|
|
+ *
|
|
|
+};
|
|
|
+use winit::{
|
|
|
+ dpi::*,
|
|
|
+ window::{CursorGrabMode, Window}
|
|
|
+};
|
|
|
+
|
|
|
+pub type WindowSize = PhysicalSize<u32>;
|
|
|
+pub type MousePos = PhysicalPosition<f64>;
|
|
|
+
|
|
|
+pub struct Renderer {
|
|
|
+ surface: Surface,
|
|
|
+ device: Device,
|
|
|
+ queue: Queue,
|
|
|
+ config: SurfaceConfiguration,
|
|
|
+ size: WindowSize,
|
|
|
+
|
|
|
+ camera_bind_group: BindGroup,
|
|
|
+ mesh_pipeline: RenderPipeline,
|
|
|
+
|
|
|
+ // resources
|
|
|
+ texture_bind_group: BindGroup,
|
|
|
+ mesh: Mesh,
|
|
|
+
|
|
|
+ // frame state
|
|
|
+ depth: DepthBuffer,
|
|
|
+ camera: Camera,
|
|
|
+ uniforms: Buffer,
|
|
|
+ objects: Vec<Object>,
|
|
|
+ mesh_instances: Buffer
|
|
|
+}
|
|
|
+
|
|
|
+impl Renderer {
|
|
|
+ pub async fn new(window: &Window, path: &str) -> Self {
|
|
|
+ let size = window.inner_size();
|
|
|
+
|
|
|
+ let instance = Instance::new(Backends::all());
|
|
|
+ let surface = unsafe { instance.create_surface(window) };
|
|
|
+ let adapter = instance.request_adapter(
|
|
|
+ // want to find the fastest gpu first, must support rendering to our surface
|
|
|
+ &RequestAdapterOptions {
|
|
|
+ power_preference: PowerPreference::default(),
|
|
|
+ compatible_surface: Some(&surface),
|
|
|
+ // no software rendering please
|
|
|
+ force_fallback_adapter: false,
|
|
|
+ }
|
|
|
+ ).await.expect("Failed to find a suitable gpu");
|
|
|
+
|
|
|
+ let (device, queue) = adapter.request_device(
|
|
|
+ // don't care about what the gpu supports
|
|
|
+ &DeviceDescriptor {
|
|
|
+ features: Features::empty(),
|
|
|
+ limits: get_device_limits(),
|
|
|
+ label: None
|
|
|
+ },
|
|
|
+ None // Trace path
|
|
|
+ ).await.expect("Failed to find a suitable physical device");
|
|
|
+
|
|
|
+ let config = SurfaceConfiguration {
|
|
|
+ // using the surface to write to the window
|
|
|
+ usage: TextureUsages::RENDER_ATTACHMENT,
|
|
|
+ format: *surface.get_supported_formats(&adapter)
|
|
|
+ .first()
|
|
|
+ .expect("Surface has no preferred format"),
|
|
|
+ width: size.width,
|
|
|
+ height: size.height,
|
|
|
+ present_mode: PresentMode::AutoVsync,
|
|
|
+ alpha_mode: CompositeAlphaMode::Auto
|
|
|
+ };
|
|
|
+ surface.configure(&device, &config);
|
|
|
+
|
|
|
+ let depth = DepthBuffer::new(&device, &config);
|
|
|
+
|
|
|
+ // load mesh
|
|
|
+ let atlas = WholeAtlas;
|
|
|
+ let mesh_data = fs::read(path)
|
|
|
+ .expect("Failed to read mesh");
|
|
|
+ let mesh = MeshReader::new::<TexturedVertex>(&atlas, Some(""))
|
|
|
+ .create::<TexturedVertex>(&device, &mesh_data)
|
|
|
+ .expect("Failed to load mesh");
|
|
|
+
|
|
|
+ let mut objects = Vec::with_capacity(100);
|
|
|
+ for i in 0..100 {
|
|
|
+ let x = i % 10 - 5;
|
|
|
+ let y = i / 10 - 5;
|
|
|
+ let fade = (i as f32) / 100.0;
|
|
|
+
|
|
|
+ objects.push(Object {
|
|
|
+ pos: (x as f32, 0.0, y as f32).into(),
|
|
|
+ scale: fade,
|
|
|
+ col: [fade; 4]
|
|
|
+ });
|
|
|
+ }
|
|
|
+ let instance_data = objects.iter()
|
|
|
+ .map(Object::build)
|
|
|
+ .collect::<Vec<_>>();
|
|
|
+
|
|
|
+ // create buffers
|
|
|
+ let camera = Camera::new((config.width as f32, config.height as f32));
|
|
|
+ let uniforms = device.create_buffer_init(&BufferInitDescriptor {
|
|
|
+ label: Some("Uniform Buffer"),
|
|
|
+ contents: cast_slice(&camera.build_matrix()),
|
|
|
+ // need to modify it at every frame
|
|
|
+ usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST
|
|
|
+ });
|
|
|
+ let mesh_instances = device.create_buffer_init(&BufferInitDescriptor {
|
|
|
+ label: Some("Instance Buffer"),
|
|
|
+ contents: cast_slice(&instance_data),
|
|
|
+ usage: BufferUsages::VERTEX
|
|
|
+ });
|
|
|
+
|
|
|
+ // set up bind groups
|
|
|
+ let (texture_bind_group, texture_layout) = load_texture(&device, &queue, include_bytes!("../../texture.png"));
|
|
|
+ let (camera_bind_group, camera_layout) = bind_camera(&device, &uniforms);
|
|
|
+
|
|
|
+ // create mesh pipeline
|
|
|
+ let mesh_pipeline = pipeline::mesh(&device, &config, &[
|
|
|
+ &texture_layout,
|
|
|
+ &camera_layout
|
|
|
+ ]);
|
|
|
+
|
|
|
+ // TODO: move elsewhere
|
|
|
+ window.set_cursor_grab(CursorGrabMode::Confined)
|
|
|
+ .expect("Failed to grab cursor");
|
|
|
+// window.set_cursor_visible(false);
|
|
|
+
|
|
|
+ Self {
|
|
|
+ surface,
|
|
|
+ device,
|
|
|
+ queue,
|
|
|
+ config,
|
|
|
+ size,
|
|
|
+
|
|
|
+ camera_bind_group,
|
|
|
+ mesh_pipeline,
|
|
|
+
|
|
|
+ texture_bind_group,
|
|
|
+ mesh,
|
|
|
+
|
|
|
+ depth,
|
|
|
+ camera,
|
|
|
+ uniforms,
|
|
|
+ objects,
|
|
|
+ mesh_instances
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn resize(&mut self, size: WindowSize) {
|
|
|
+ self.size = size;
|
|
|
+ self.config.width = size.width;
|
|
|
+ self.config.height = size.height;
|
|
|
+ self.surface.configure(&self.device, &self.config);
|
|
|
+
|
|
|
+ // recreate anything that depends on surface configuration
|
|
|
+ self.depth = DepthBuffer::new(&self.device, &self.config);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn recreate(&mut self) {
|
|
|
+ self.resize(self.size)
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn cursor_moved(&mut self, x: f64, y: f64) {
|
|
|
+ let center = self.center();
|
|
|
+ // map cursor from 0, size to -1.0, 1.0
|
|
|
+ let dx = (x - center.x) / (self.size.width as f64) * 6.28;
|
|
|
+ let dy = (y - center.y) / (self.size.height as f64) * 3.14;
|
|
|
+ let r = 4.0;
|
|
|
+ // TODO: correct x, z
|
|
|
+ self.camera.set_eye(r * dx.sin() as f32, r * dy.sin() as f32, r * dx.cos() as f32);
|
|
|
+
|
|
|
+ // update camera in uniforms
|
|
|
+ let matrix = self.camera.build_matrix();
|
|
|
+ let bytes = cast_slice(&matrix);
|
|
|
+ self.queue.write_buffer(&self.uniforms, 0, bytes);
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn render(&mut self) -> Result<(), SurfaceError> {
|
|
|
+ let output = self.surface.get_current_texture()?;
|
|
|
+ let view = output.texture.create_view(&TextureViewDescriptor::default());
|
|
|
+ let mut encoder = self.device.create_command_encoder(&CommandEncoderDescriptor {
|
|
|
+ label: Some("Render Encoder")
|
|
|
+ });
|
|
|
+
|
|
|
+ self.create_render_pass(&mut encoder, &view);
|
|
|
+
|
|
|
+ // submit commands for rendering
|
|
|
+ self.queue.submit(iter::once(encoder.finish()));
|
|
|
+ output.present();
|
|
|
+
|
|
|
+ Ok(())
|
|
|
+ }
|
|
|
+
|
|
|
+ pub fn center(&self) -> MousePos {
|
|
|
+ MousePos::new(self.size.width as f64 / 2.0, self.size.height as f64 / 2.0)
|
|
|
+ }
|
|
|
+
|
|
|
+ fn create_render_pass(&self, encoder: &mut CommandEncoder, view: &TextureView) {
|
|
|
+ let mut pass = encoder.begin_render_pass(&RenderPassDescriptor {
|
|
|
+ label: Some("Render Pass"),
|
|
|
+ color_attachments: &[Some(RenderPassColorAttachment {
|
|
|
+ view: &view,
|
|
|
+ // no multisampling
|
|
|
+ resolve_target: None,
|
|
|
+ ops: Operations {
|
|
|
+ // clear with this colour
|
|
|
+ load: LoadOp::Clear(Color {
|
|
|
+ r: 0.1,
|
|
|
+ g: 0.2,
|
|
|
+ b: 0.3,
|
|
|
+ a: 1.0
|
|
|
+ }),
|
|
|
+ // keep what is rendered
|
|
|
+ store: true
|
|
|
+ }
|
|
|
+ })],
|
|
|
+ // boy thats a mouthful
|
|
|
+ depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
|
|
|
+ view: &self.depth.view,
|
|
|
+ depth_ops: Some(Operations {
|
|
|
+ load: wgpu::LoadOp::Clear(1.0),
|
|
|
+ store: true
|
|
|
+ }),
|
|
|
+ stencil_ops: None
|
|
|
+ })
|
|
|
+ });
|
|
|
+
|
|
|
+ pass.set_pipeline(&self.mesh_pipeline);
|
|
|
+ pass.set_bind_group(0, &self.texture_bind_group, &[]);
|
|
|
+ pass.set_bind_group(1, &self.camera_bind_group, &[]);
|
|
|
+
|
|
|
+ let instances = self.objects.len() as u32;
|
|
|
+ pass.set_vertex_buffer(1, self.mesh_instances.slice(..));
|
|
|
+ self.mesh.draw_instanced(&mut pass, 0..instances);
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+fn get_device_limits() -> Limits {
|
|
|
+ let mut limits = Limits::default();
|
|
|
+ // compute isn't needed
|
|
|
+ limits.max_compute_workgroup_storage_size = 0;
|
|
|
+ limits.max_compute_invocations_per_workgroup = 0;
|
|
|
+ limits.max_compute_workgroup_size_x = 0;
|
|
|
+ limits.max_compute_workgroup_size_y = 0;
|
|
|
+ limits.max_compute_workgroup_size_z = 0;
|
|
|
+ limits.max_compute_workgroups_per_dimension = 0;
|
|
|
+ limits
|
|
|
+}
|
|
|
+
|
|
|
+fn bind_camera(device: &Device, buffer: &Buffer) -> (BindGroup, BindGroupLayout) {
|
|
|
+ let layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
|
|
|
+ label: Some("Camera bind group layout"),
|
|
|
+ entries: &[
|
|
|
+ BindGroupLayoutEntry {
|
|
|
+ binding: 0,
|
|
|
+ visibility: ShaderStages::VERTEX,
|
|
|
+ ty: BindingType::Buffer {
|
|
|
+ ty: BufferBindingType::Uniform,
|
|
|
+ // single camera, no need to resize it
|
|
|
+ has_dynamic_offset: false,
|
|
|
+ min_binding_size: None
|
|
|
+ },
|
|
|
+ count: None
|
|
|
+ }
|
|
|
+ ]
|
|
|
+ });
|
|
|
+ let bind_group = device.create_bind_group(&BindGroupDescriptor {
|
|
|
+ label: Some("Camera bind group"),
|
|
|
+ layout: &layout,
|
|
|
+ entries: &[
|
|
|
+ BindGroupEntry {
|
|
|
+ binding: 0,
|
|
|
+ resource: buffer.as_entire_binding()
|
|
|
+ }
|
|
|
+ ]
|
|
|
+ });
|
|
|
+
|
|
|
+ (bind_group, layout)
|
|
|
+}
|