use anyhow::Result; use bytemuck; use cgmath::{Deg, EuclideanSpace, Matrix2, Matrix4, Point2, Vector3}; use galactica_constants; use std::{iter, rc::Rc}; use wgpu; use winit::{self, dpi::LogicalSize, window::Window}; use crate::{ content, globaldata::{GlobalData, GlobalDataContent}, pipeline::PipelineBuilder, sprite::ObjectSubSprite, starfield::Starfield, texturearray::TextureArray, vertexbuffer::{ consts::{SPRITE_INDICES, SPRITE_VERTICES}, types::{ObjectInstance, ParticleInstance, StarfieldInstance, TexturedVertex, UiInstance}, BufferObject, VertexBuffer, }, FrameState, ObjectSprite, UiSprite, OPENGL_TO_WGPU_MATRIX, }; /// A high-level GPU wrapper. Consumes game state, /// produces pretty pictures. pub struct GPUState { /// The window to we draw on pub window: Window, /// The size of the window we draw on pub window_size: winit::dpi::PhysicalSize, device: wgpu::Device, config: wgpu::SurfaceConfiguration, surface: wgpu::Surface, queue: wgpu::Queue, window_aspect: f32, object_pipeline: wgpu::RenderPipeline, starfield_pipeline: wgpu::RenderPipeline, particle_pipeline: wgpu::RenderPipeline, ui_pipeline: wgpu::RenderPipeline, starfield: Starfield, texture_array: TextureArray, global_data: GlobalData, vertex_buffers: VertexBuffers, } struct VertexBuffers { object: Rc, starfield: Rc, ui: Rc, /// The index of the next particle slot we'll write to. /// This must cycle to 0 whenever it exceeds the size /// of the particle instance array. particle_array_head: u64, particle: Rc, } impl GPUState { /// Make a new GPUState that draws on `window` pub async fn new(window: Window, ct: &content::Content) -> Result { let window_size = window.inner_size(); let window_aspect = window_size.width as f32 / window_size.height as f32; let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends: wgpu::Backends::all(), ..Default::default() }); let surface = unsafe { instance.create_surface(&window) }.unwrap(); // Basic setup let device; let queue; let config; { let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: Some(&surface), force_fallback_adapter: false, }) .await .unwrap(); (device, queue) = adapter .request_device( &wgpu::DeviceDescriptor { features: wgpu::Features::TEXTURE_BINDING_ARRAY | wgpu::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, // We may need limits if we compile for wasm limits: wgpu::Limits::default(), label: Some("gpu device"), }, None, ) .await .unwrap(); // Assume sRGB let surface_caps = surface.get_capabilities(&adapter); let surface_format = surface_caps .formats .iter() .copied() .filter(|f| f.is_srgb()) .filter(|f| f.has_stencil_aspect()) .next() .unwrap_or(surface_caps.formats[0]); config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: surface_format, width: window_size.width, height: window_size.height, present_mode: surface_caps.present_modes[0], alpha_mode: surface_caps.alpha_modes[0], view_formats: vec![], }; surface.configure(&device, &config); } let vertex_buffers = VertexBuffers { object: Rc::new(VertexBuffer::new::( "object", &device, Some(SPRITE_VERTICES), Some(SPRITE_INDICES), galactica_constants::OBJECT_SPRITE_INSTANCE_LIMIT, )), starfield: Rc::new(VertexBuffer::new::( "starfield", &device, Some(SPRITE_VERTICES), Some(SPRITE_INDICES), galactica_constants::STARFIELD_SPRITE_INSTANCE_LIMIT, )), ui: Rc::new(VertexBuffer::new::( "ui", &device, Some(SPRITE_VERTICES), Some(SPRITE_INDICES), galactica_constants::UI_SPRITE_INSTANCE_LIMIT, )), particle_array_head: 0, particle: Rc::new(VertexBuffer::new::( "particle", &device, Some(SPRITE_VERTICES), Some(SPRITE_INDICES), galactica_constants::PARTICLE_SPRITE_INSTANCE_LIMIT, )), }; // Load uniforms let global_data = GlobalData::new(&device); let texture_array = TextureArray::new(&device, &queue, ct)?; // Make sure these match the indices in each shader let bind_group_layouts = &[ &texture_array.bind_group_layout, &global_data.bind_group_layout, ]; // Create render pipelines let object_pipeline = PipelineBuilder::new("object", &device) .set_shader(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/shaders/", "object.wgsl" ))) .set_format(config.format) .set_triangle(true) .set_vertex_buffer(&vertex_buffers.object) .set_bind_group_layouts(bind_group_layouts) .build(); let starfield_pipeline = PipelineBuilder::new("starfield", &device) .set_shader(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/shaders/", "starfield.wgsl" ))) .set_format(config.format) .set_triangle(true) .set_vertex_buffer(&vertex_buffers.starfield) .set_bind_group_layouts(bind_group_layouts) .build(); let ui_pipeline = PipelineBuilder::new("ui", &device) .set_shader(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/shaders/", "ui.wgsl" ))) .set_format(config.format) .set_triangle(true) .set_vertex_buffer(&vertex_buffers.ui) .set_bind_group_layouts(bind_group_layouts) .build(); let particle_pipeline = PipelineBuilder::new("particle", &device) .set_shader(include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/shaders/", "particle.wgsl" ))) .set_format(config.format) .set_triangle(true) .set_vertex_buffer(&vertex_buffers.particle) .set_bind_group_layouts(bind_group_layouts) .build(); let mut starfield = Starfield::new(); starfield.regenerate(); return Ok(Self { device, config, surface, queue, window, window_size, window_aspect, object_pipeline, starfield_pipeline, ui_pipeline, particle_pipeline, starfield, texture_array, global_data, vertex_buffers, }); } /// Get the window this GPUState is attached to pub fn window(&self) -> &Window { &self.window } /// Update window size. /// This should be called whenever our window is resized. pub fn resize(&mut self) { let new_size = self.window.inner_size(); if new_size.width > 0 && new_size.height > 0 { self.window_size = new_size; self.window_aspect = new_size.width as f32 / new_size.height as f32; self.config.width = new_size.width; self.config.height = new_size.height; self.surface.configure(&self.device, &self.config); } self.update_starfield_buffer() } /// Create a ObjectInstance for an object and add it to `instances`. /// Also handles child sprites. fn push_object_sprite( &self, camera_zoom: f32, camera_pos: Point2, instances: &mut Vec, clip_ne: Point2, clip_sw: Point2, s: &ObjectSprite, ) { // Position adjusted for parallax // TODO: adjust parallax for zoom? let pos: Point2 = { (Point2 { x: s.pos.x, y: s.pos.y, } - camera_pos.to_vec()) / s.pos.z }; let texture = self.texture_array.get_texture(s.texture); // Game dimensions of this sprite post-scale. // Don't divide by 2, we use this later. let height = s.size / s.pos.z; // Width or height, whichever is larger. // Accounts for sprite rotation. let m = height * texture.aspect.max(1.0); // Don't draw (or compute matrices for) // sprites that are off the screen if pos.x < clip_ne.x - m || pos.y > clip_ne.y + m || pos.x > clip_sw.x + m || pos.y < clip_sw.y - m { return; } // TODO: clean up let scale = height / camera_zoom; // Note that our mesh starts centered at (0, 0). // This is essential---we do not want scale and rotation // changing our sprite's position! // Apply sprite aspect ratio, preserving height. // This must be done *before* rotation. // // We apply the provided scale here as well as a minor optimization let sprite_aspect_and_scale = Matrix4::from_nonuniform_scale(texture.aspect * scale, scale, 1.0); // Apply rotation let rotate = Matrix4::from_angle_z(s.angle); // Apply screen aspect ratio, again preserving height. // This must be done AFTER rotation... think about it! let screen_aspect = Matrix4::from_nonuniform_scale(1.0 / self.window_aspect, 1.0, 1.0); // After finishing all ops, translate. // This must be done last, all other operations // require us to be at (0, 0). // // Note that we divide camera zoom by two. // THIS IS IMPORTANT! // The height of the viewport is `zoom` in game units, // but it's 2 in screen units! (since coordinates range from -1 to 1) let translate = Matrix4::from_translation(Vector3 { x: pos.x / (camera_zoom / 2.0) / self.window_aspect, y: pos.y / (camera_zoom / 2.0), z: 0.0, }); // Order matters! // The rightmost matrix is applied first. let t = OPENGL_TO_WGPU_MATRIX * translate * screen_aspect * rotate * sprite_aspect_and_scale; instances.push(ObjectInstance { transform: t.into(), texture_index: texture.index, }); // Add children if let Some(children) = &s.children { for c in children { self.push_object_subsprite(camera_zoom, instances, c, pos, s.angle); } } } /// Add an object sprite's subsprite to `instances`. /// Only called by `self.push_object_sprite`. fn push_object_subsprite( &self, camera_zoom: f32, instances: &mut Vec, s: &ObjectSubSprite, parent_pos: Point2, parent_angle: Deg, ) { let texture = self.texture_array.get_texture(s.texture); let scale = s.size / (s.pos.z * camera_zoom); let sprite_aspect_and_scale = Matrix4::from_nonuniform_scale(texture.aspect * scale, scale, 1.0); let rotate = Matrix4::from_angle_z(s.angle); let screen_aspect = Matrix4::from_nonuniform_scale(1.0 / self.window_aspect, 1.0, 1.0); let ptranslate = Matrix4::from_translation(Vector3 { x: parent_pos.x / (camera_zoom / 2.0) / self.window_aspect, y: parent_pos.y / (camera_zoom / 2.0), z: 0.0, }); let protate = Matrix4::from_angle_z(parent_angle); let translate = Matrix4::from_translation(Vector3 { x: s.pos.x / (camera_zoom / 2.0) / self.window_aspect, y: s.pos.y / (camera_zoom / 2.0), z: 0.0, }); // Order matters! // The rightmost matrix is applied first. let t = OPENGL_TO_WGPU_MATRIX * ptranslate * screen_aspect * protate * translate * rotate * sprite_aspect_and_scale; instances.push(ObjectInstance { transform: t.into(), texture_index: texture.index, }); } /// Create a ObjectInstance for a ui sprite and add it to `instances` fn push_ui_sprite(&self, instances: &mut Vec, s: &UiSprite) { let logical_size: LogicalSize = self.window_size.to_logical(self.window.scale_factor()); let texture = self.texture_array.get_texture(s.texture); let width = s.dimensions.x; let height = s.dimensions.y; // Compute square scale, since we must apply screen aspect ratio // AFTER rotation. let scale = Matrix4::from_nonuniform_scale( width / logical_size.height, height / logical_size.height, 1.0, ); let rotate = Matrix4::from_angle_z(s.angle); let translate = Matrix4::from_translation(match s.pos { super::AnchoredUiPosition::NwC(p) => Vector3 { // Note the signs. Positive y points north! x: -1.0 + p.x / (logical_size.width / 2.0), y: 1.0 + p.y / (logical_size.height / 2.0), z: 0.0, }, super::AnchoredUiPosition::NwNw(p) => Vector3 { x: -1.0 + (width / 2.0 + p.x) / (logical_size.width / 2.0), y: 1.0 - (height / 2.0 - p.y) / (logical_size.height / 2.0), z: 0.0, }, super::AnchoredUiPosition::NwNe(p) => Vector3 { x: -1.0 - (width / 2.0 - p.x) / (logical_size.width / 2.0), y: 1.0 - (height / 2.0 - p.y) / (logical_size.height / 2.0), z: 0.0, }, super::AnchoredUiPosition::NwSw(p) => Vector3 { x: -1.0 + (width / 2.0 + p.x) / (logical_size.width / 2.0), y: 1.0 + (height / 2.0 + p.y) / (logical_size.height / 2.0), z: 0.0, }, super::AnchoredUiPosition::NwSe(p) => Vector3 { x: -1.0 - (width / 2.0 - p.x) / (logical_size.width / 2.0), y: 1.0 + (height / 2.0 + p.y) / (logical_size.height / 2.0), z: 0.0, }, }); let screen_aspect = Matrix4::from_nonuniform_scale(1.0 / self.window_aspect, 1.0, 1.0); instances.push(UiInstance { transform: (OPENGL_TO_WGPU_MATRIX * translate * screen_aspect * rotate * scale).into(), texture_index: texture.index, color: s.color.unwrap_or([1.0, 1.0, 1.0, 1.0]), }); } /// Make an instance for all the game's sprites /// (Objects and UI) /// This will Will panic if any X_SPRITE_INSTANCE_LIMIT is exceeded. fn update_sprite_instances(&self, framestate: FrameState) -> (usize, usize) { let mut object_instances: Vec = Vec::new(); // Game coordinates (relative to camera) of ne and sw corners of screen. // Used to skip off-screen sprites. let clip_ne = Point2::from((-self.window_aspect, 1.0)) * framestate.camera_zoom; let clip_sw = Point2::from((self.window_aspect, -1.0)) * framestate.camera_zoom; for s in framestate.object_sprites { self.push_object_sprite( framestate.camera_zoom, framestate.camera_pos, &mut object_instances, clip_ne, clip_sw, &s, ); } // Enforce sprite limit if object_instances.len() as u64 > galactica_constants::OBJECT_SPRITE_INSTANCE_LIMIT { // TODO: no panic, handle this better. panic!("Sprite limit exceeded!") } self.queue.write_buffer( &self.vertex_buffers.object.instances, 0, bytemuck::cast_slice(&object_instances), ); let mut ui_instances: Vec = Vec::new(); for s in framestate.ui_sprites { self.push_ui_sprite(&mut ui_instances, &s); } if ui_instances.len() as u64 > galactica_constants::UI_SPRITE_INSTANCE_LIMIT { panic!("Ui sprite limit exceeded!") } self.queue.write_buffer( &self.vertex_buffers.ui.instances, 0, bytemuck::cast_slice(&ui_instances), ); return (object_instances.len(), ui_instances.len()); } /// Make a StarfieldInstance for each star that needs to be drawn. /// Will panic if STARFIELD_INSTANCE_LIMIT is exceeded. /// /// Starfield data rarely changes, so this is called only when it's needed. pub fn update_starfield_buffer(&mut self) { self.queue.write_buffer( &self.vertex_buffers.starfield.instances, 0, bytemuck::cast_slice(&self.starfield.make_instances(self.window_aspect)), ); } /// Main render function. Draws sprites on a window. pub fn render(&mut self, framestate: FrameState) -> Result<(), wgpu::SurfaceError> { let output = self.surface.get_current_texture()?; let view = output .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("render encoder"), }); let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("render pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, occlusion_query_set: None, timestamp_writes: None, }); // Update global values self.queue.write_buffer( &self.global_data.buffer, 0, bytemuck::cast_slice(&[GlobalDataContent { camera_position: framestate.camera_pos.into(), camera_zoom: [framestate.camera_zoom, 0.0], camera_zoom_limits: [galactica_constants::ZOOM_MIN, galactica_constants::ZOOM_MAX], window_size: [ self.window_size.width as f32, self.window_size.height as f32, ], window_aspect: [self.window_aspect, 0.0], starfield_texture: [self.texture_array.get_starfield_texture().index, 0], starfield_tile_size: [galactica_constants::STARFIELD_SIZE as f32, 0.0], starfield_size_limits: [ galactica_constants::STARFIELD_SIZE_MIN, galactica_constants::STARFIELD_SIZE_MAX, ], current_time: [framestate.current_time, 0.0], }]), ); // Write all new particles to GPU buffer for i in framestate.new_particles.iter() { let texture = self.texture_array.get_texture(i.texture); self.queue.write_buffer( &self.vertex_buffers.particle.instances, ParticleInstance::SIZE * self.vertex_buffers.particle_array_head, bytemuck::cast_slice(&[ParticleInstance { position: [i.pos.x, i.pos.y], velocity: i.velocity.into(), rotation: Matrix2::from_angle(i.angle).into(), size: i.size, texture_index_len_rep: [texture.index, texture.len, texture.repeat], texture_aspect_fps: [texture.aspect, texture.fps], created: framestate.current_time, expires: framestate.current_time + i.lifetime, }]), ); self.vertex_buffers.particle_array_head += 1; if self.vertex_buffers.particle_array_head == galactica_constants::PARTICLE_SPRITE_INSTANCE_LIMIT { self.vertex_buffers.particle_array_head = 0; } } framestate.new_particles.clear(); // Create sprite instances let (n_object, n_ui) = self.update_sprite_instances(framestate); // These should match the indices in each shader, // and should each have a corresponding bind group layout. render_pass.set_bind_group(0, &self.texture_array.bind_group, &[]); render_pass.set_bind_group(1, &self.global_data.bind_group, &[]); // Starfield pipeline self.vertex_buffers.starfield.set_in_pass(&mut render_pass); render_pass.set_pipeline(&self.starfield_pipeline); render_pass.draw_indexed( 0..SPRITE_INDICES.len() as u32, 0, 0..self.starfield.instance_count, ); // Sprite pipeline self.vertex_buffers.object.set_in_pass(&mut render_pass); render_pass.set_pipeline(&self.object_pipeline); render_pass.draw_indexed(0..SPRITE_INDICES.len() as u32, 0, 0..n_object as _); // Particle pipeline self.vertex_buffers.particle.set_in_pass(&mut render_pass); render_pass.set_pipeline(&self.particle_pipeline); render_pass.draw_indexed( 0..SPRITE_INDICES.len() as u32, 0, 0..galactica_constants::PARTICLE_SPRITE_INSTANCE_LIMIT as _, ); // Ui pipeline self.vertex_buffers.ui.set_in_pass(&mut render_pass); render_pass.set_pipeline(&self.ui_pipeline); render_pass.draw_indexed(0..SPRITE_INDICES.len() as u32, 0, 0..n_ui as _); // begin_render_pass borrows encoder mutably, so we can't call finish() // without dropping this variable. drop(render_pass); self.queue.submit(iter::once(encoder.finish())); output.present(); Ok(()) } }