2022-10-02 18:59:20 +03:00
|
|
|
use cgmath::prelude::*;
|
|
|
|
use std::time::Duration;
|
|
|
|
|
2022-10-01 23:58:09 +03:00
|
|
|
use wgpu::{include_wgsl, util::DeviceExt};
|
|
|
|
use winit::{event::*, window::Window};
|
|
|
|
|
2022-10-02 18:59:20 +03:00
|
|
|
use super::camera::{Camera, CameraController, CameraUniform};
|
|
|
|
use super::instance::{Instance, InstanceRaw};
|
2022-10-02 22:03:50 +03:00
|
|
|
use super::model::{DrawModel, Model, ModelVertex, Vertex};
|
|
|
|
use super::resources;
|
2022-10-02 18:59:20 +03:00
|
|
|
use super::texture::Texture;
|
2022-10-02 22:03:50 +03:00
|
|
|
|
2022-10-02 18:59:20 +03:00
|
|
|
const NUM_INSTANCES_PER_ROW: u32 = 10;
|
2022-10-01 23:58:09 +03:00
|
|
|
|
|
|
|
pub struct State {
|
|
|
|
pub size: winit::dpi::PhysicalSize<u32>,
|
|
|
|
|
|
|
|
surface: wgpu::Surface,
|
|
|
|
device: wgpu::Device,
|
|
|
|
queue: wgpu::Queue,
|
|
|
|
config: wgpu::SurfaceConfiguration,
|
|
|
|
render_pipeline: wgpu::RenderPipeline,
|
2022-10-02 18:59:20 +03:00
|
|
|
camera: Camera,
|
|
|
|
camera_uniform: CameraUniform,
|
|
|
|
camera_buffer: wgpu::Buffer,
|
|
|
|
camera_bind_group: wgpu::BindGroup,
|
|
|
|
camera_controller: CameraController,
|
|
|
|
instances: Vec<Instance>,
|
|
|
|
instance_buffer: wgpu::Buffer,
|
2022-10-02 22:03:50 +03:00
|
|
|
depth_texture: Texture,
|
|
|
|
obj_model: Model,
|
2022-10-01 23:58:09 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
impl State {
|
|
|
|
// Creating some of the wgpu types requires async code
|
|
|
|
pub async fn new(window: &Window) -> Self {
|
|
|
|
let size = window.inner_size();
|
|
|
|
let instance = wgpu::Instance::new(wgpu::Backends::all());
|
|
|
|
let surface = unsafe { instance.create_surface(window) };
|
|
|
|
|
|
|
|
let adapter = instance
|
|
|
|
.request_adapter(&wgpu::RequestAdapterOptions {
|
|
|
|
power_preference: wgpu::PowerPreference::HighPerformance,
|
|
|
|
compatible_surface: Some(&surface),
|
|
|
|
force_fallback_adapter: false,
|
|
|
|
})
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let (device, queue) = adapter
|
|
|
|
.request_device(
|
|
|
|
&wgpu::DeviceDescriptor {
|
|
|
|
features: wgpu::Features::empty(),
|
|
|
|
limits: wgpu::Limits::default(),
|
|
|
|
label: None,
|
|
|
|
},
|
|
|
|
None, // Trace path
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let config = wgpu::SurfaceConfiguration {
|
|
|
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
|
|
|
format: surface.get_supported_formats(&adapter)[0],
|
|
|
|
width: size.width,
|
|
|
|
height: size.height,
|
|
|
|
present_mode: wgpu::PresentMode::Fifo,
|
|
|
|
};
|
|
|
|
|
|
|
|
surface.configure(&device, &config);
|
|
|
|
|
2022-10-02 18:59:20 +03:00
|
|
|
// Camera
|
|
|
|
let camera = Camera::new(
|
|
|
|
(0.0, 0.0, 0.0).into(),
|
|
|
|
0.0,
|
|
|
|
0.0,
|
|
|
|
60.0,
|
|
|
|
config.width as f32 / config.height as f32,
|
2022-10-01 23:58:09 +03:00
|
|
|
);
|
2022-10-02 18:59:20 +03:00
|
|
|
|
|
|
|
let mut camera_uniform = CameraUniform::new();
|
|
|
|
camera_uniform.update_view_proj(&camera);
|
|
|
|
|
|
|
|
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
|
|
|
label: Some("Camera Buffer"),
|
|
|
|
contents: bytemuck::cast_slice(&[camera_uniform]),
|
|
|
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
|
|
|
});
|
|
|
|
let camera_bind_group_layout =
|
|
|
|
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
|
|
entries: &[wgpu::BindGroupLayoutEntry {
|
|
|
|
binding: 0,
|
|
|
|
visibility: wgpu::ShaderStages::VERTEX,
|
|
|
|
ty: wgpu::BindingType::Buffer {
|
|
|
|
ty: wgpu::BufferBindingType::Uniform,
|
|
|
|
has_dynamic_offset: false,
|
|
|
|
min_binding_size: None,
|
|
|
|
},
|
|
|
|
count: None,
|
|
|
|
}],
|
|
|
|
label: Some("camera_bind_group_layout"),
|
|
|
|
});
|
|
|
|
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
|
|
layout: &camera_bind_group_layout,
|
|
|
|
entries: &[wgpu::BindGroupEntry {
|
|
|
|
binding: 0,
|
|
|
|
resource: camera_buffer.as_entire_binding(),
|
|
|
|
}],
|
|
|
|
label: Some("camera_bind_group"),
|
2022-10-01 23:58:09 +03:00
|
|
|
});
|
2022-10-02 18:59:20 +03:00
|
|
|
|
|
|
|
let camera_controller = CameraController::new(1.0, 2.0);
|
|
|
|
|
|
|
|
surface.configure(&device, &config);
|
|
|
|
|
2022-10-01 23:58:09 +03:00
|
|
|
let texture_bind_group_layout =
|
|
|
|
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
|
|
entries: &[
|
|
|
|
wgpu::BindGroupLayoutEntry {
|
|
|
|
binding: 0,
|
|
|
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
|
|
|
ty: wgpu::BindingType::Texture {
|
|
|
|
multisampled: false,
|
|
|
|
view_dimension: wgpu::TextureViewDimension::D2,
|
|
|
|
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
|
|
|
},
|
|
|
|
count: None,
|
|
|
|
},
|
|
|
|
wgpu::BindGroupLayoutEntry {
|
|
|
|
binding: 1,
|
|
|
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
|
|
|
// This should match the filterable field of the
|
|
|
|
// corresponding Texture entry above.
|
|
|
|
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
|
|
|
count: None,
|
|
|
|
},
|
|
|
|
],
|
|
|
|
label: Some("texture_bind_group_layout"),
|
|
|
|
});
|
|
|
|
|
2022-10-02 22:03:50 +03:00
|
|
|
let obj_model =
|
|
|
|
resources::load_model("cube.obj", &device, &queue, &texture_bind_group_layout)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
const SPACE_BETWEEN: f32 = 3.0;
|
2022-10-02 18:59:20 +03:00
|
|
|
let instances = (0..NUM_INSTANCES_PER_ROW)
|
|
|
|
.flat_map(|z| {
|
|
|
|
(0..NUM_INSTANCES_PER_ROW).map(move |x| {
|
2022-10-02 22:03:50 +03:00
|
|
|
let x = SPACE_BETWEEN * (x as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0);
|
|
|
|
let z = SPACE_BETWEEN * (z as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0);
|
|
|
|
|
|
|
|
let position = cgmath::Vector3 { x, y: 0.0, z };
|
2022-10-02 18:59:20 +03:00
|
|
|
|
|
|
|
let rotation = if position.is_zero() {
|
|
|
|
cgmath::Quaternion::from_axis_angle(
|
|
|
|
cgmath::Vector3::unit_z(),
|
|
|
|
cgmath::Deg(0.0),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
cgmath::Quaternion::from_axis_angle(position.normalize(), cgmath::Deg(45.0))
|
|
|
|
};
|
|
|
|
|
|
|
|
Instance { position, rotation }
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
2022-10-02 22:03:50 +03:00
|
|
|
|
2022-10-02 18:59:20 +03:00
|
|
|
let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>();
|
|
|
|
let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
|
|
|
label: Some("Instance Buffer"),
|
|
|
|
contents: bytemuck::cast_slice(&instance_data),
|
|
|
|
usage: wgpu::BufferUsages::VERTEX,
|
|
|
|
});
|
|
|
|
|
2022-10-02 22:03:50 +03:00
|
|
|
let depth_texture = Texture::create_depth_texture(&device, &config, "depth_texture");
|
|
|
|
|
2022-10-01 23:58:09 +03:00
|
|
|
// let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
|
|
|
// label: Some("Shader"),
|
|
|
|
// source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/test.wgsl").into()),
|
|
|
|
// });
|
|
|
|
let shader = device.create_shader_module(include_wgsl!("../shaders/test.wgsl"));
|
|
|
|
|
|
|
|
let render_pipeline_layout =
|
|
|
|
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
|
|
|
label: Some("Render Pipeline Layout"),
|
2022-10-02 18:59:20 +03:00
|
|
|
bind_group_layouts: &[&texture_bind_group_layout, &camera_bind_group_layout],
|
2022-10-01 23:58:09 +03:00
|
|
|
push_constant_ranges: &[],
|
|
|
|
});
|
|
|
|
|
|
|
|
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
|
|
|
label: Some("Render Pipeline"),
|
|
|
|
layout: Some(&render_pipeline_layout),
|
|
|
|
vertex: wgpu::VertexState {
|
|
|
|
module: &shader,
|
|
|
|
entry_point: "vs_main",
|
2022-10-02 22:03:50 +03:00
|
|
|
buffers: &[ModelVertex::desc(), InstanceRaw::desc()],
|
2022-10-01 23:58:09 +03:00
|
|
|
},
|
|
|
|
fragment: Some(wgpu::FragmentState {
|
|
|
|
module: &shader,
|
|
|
|
entry_point: "fs_main",
|
|
|
|
targets: &[Some(wgpu::ColorTargetState {
|
|
|
|
format: config.format,
|
|
|
|
blend: Some(wgpu::BlendState::REPLACE),
|
|
|
|
write_mask: wgpu::ColorWrites::ALL,
|
|
|
|
})],
|
|
|
|
}),
|
|
|
|
primitive: wgpu::PrimitiveState {
|
|
|
|
topology: wgpu::PrimitiveTopology::TriangleList,
|
|
|
|
strip_index_format: None,
|
|
|
|
front_face: wgpu::FrontFace::Ccw,
|
|
|
|
cull_mode: Some(wgpu::Face::Back),
|
|
|
|
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
|
|
|
|
polygon_mode: wgpu::PolygonMode::Fill,
|
|
|
|
// Requires Features::DEPTH_CLIP_CONTROL
|
|
|
|
unclipped_depth: false,
|
|
|
|
// Requires Features::CONSERVATIVE_RASTERIZATION
|
|
|
|
conservative: false,
|
|
|
|
},
|
2022-10-02 22:03:50 +03:00
|
|
|
depth_stencil: Some(wgpu::DepthStencilState {
|
|
|
|
format: Texture::DEPTH_FORMAT,
|
|
|
|
depth_write_enabled: true,
|
|
|
|
depth_compare: wgpu::CompareFunction::Less,
|
|
|
|
stencil: wgpu::StencilState::default(),
|
|
|
|
bias: wgpu::DepthBiasState::default(),
|
|
|
|
}),
|
2022-10-01 23:58:09 +03:00
|
|
|
multisample: wgpu::MultisampleState {
|
|
|
|
count: 1,
|
|
|
|
mask: !0,
|
|
|
|
alpha_to_coverage_enabled: false,
|
|
|
|
},
|
|
|
|
multiview: None,
|
|
|
|
});
|
|
|
|
|
|
|
|
return Self {
|
|
|
|
size,
|
|
|
|
surface,
|
|
|
|
device,
|
|
|
|
queue,
|
|
|
|
config,
|
|
|
|
render_pipeline,
|
2022-10-02 18:59:20 +03:00
|
|
|
camera,
|
|
|
|
camera_uniform,
|
|
|
|
camera_buffer,
|
|
|
|
camera_bind_group,
|
|
|
|
camera_controller,
|
|
|
|
instances,
|
|
|
|
instance_buffer,
|
2022-10-02 22:03:50 +03:00
|
|
|
depth_texture,
|
|
|
|
obj_model,
|
2022-10-01 23:58:09 +03:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
|
|
|
|
if new_size.width > 0 && new_size.height > 0 {
|
|
|
|
self.size = new_size;
|
|
|
|
self.config.width = new_size.width;
|
|
|
|
self.config.height = new_size.height;
|
|
|
|
self.surface.configure(&self.device, &self.config);
|
2022-10-02 18:59:20 +03:00
|
|
|
self.camera
|
|
|
|
.projection
|
|
|
|
.resize(new_size.width, new_size.height);
|
2022-10-02 22:03:50 +03:00
|
|
|
self.depth_texture =
|
|
|
|
Texture::create_depth_texture(&self.device, &self.config, "depth_texture");
|
2022-10-01 23:58:09 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-02 18:59:20 +03:00
|
|
|
pub fn input(
|
|
|
|
&mut self,
|
|
|
|
window_event: Option<&WindowEvent>,
|
|
|
|
device_event: Option<&DeviceEvent>,
|
|
|
|
) -> bool {
|
|
|
|
return self
|
|
|
|
.camera_controller
|
|
|
|
.process_events(window_event, device_event);
|
2022-10-01 23:58:09 +03:00
|
|
|
}
|
|
|
|
|
2022-10-02 18:59:20 +03:00
|
|
|
pub fn update(&mut self, dt: Duration) {
|
|
|
|
self.camera.update(dt, &self.camera_controller);
|
|
|
|
self.camera_controller.reset(false);
|
|
|
|
self.camera_uniform.update_view_proj(&self.camera);
|
|
|
|
self.queue.write_buffer(
|
|
|
|
&self.camera_buffer,
|
|
|
|
0,
|
|
|
|
bytemuck::cast_slice(&[self.camera_uniform]),
|
|
|
|
);
|
|
|
|
}
|
2022-10-01 23:58:09 +03:00
|
|
|
|
|
|
|
pub fn render(&mut self) -> 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: &[
|
|
|
|
// This is what @location(0) in the fragment shader targets
|
|
|
|
Some(wgpu::RenderPassColorAttachment {
|
|
|
|
view: &view,
|
|
|
|
resolve_target: None,
|
|
|
|
ops: wgpu::Operations {
|
|
|
|
load: wgpu::LoadOp::Clear(wgpu::Color {
|
2022-10-02 22:03:50 +03:00
|
|
|
r: 0.0,
|
|
|
|
g: 0.5,
|
|
|
|
b: 0.0,
|
2022-10-01 23:58:09 +03:00
|
|
|
a: 1.0,
|
|
|
|
}),
|
|
|
|
store: true,
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
],
|
2022-10-02 22:03:50 +03:00
|
|
|
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
|
|
|
view: &self.depth_texture.view,
|
|
|
|
depth_ops: Some(wgpu::Operations {
|
|
|
|
load: wgpu::LoadOp::Clear(1.0),
|
|
|
|
store: true,
|
|
|
|
}),
|
|
|
|
stencil_ops: None,
|
|
|
|
}),
|
2022-10-01 23:58:09 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
render_pass.set_pipeline(&self.render_pipeline);
|
2022-10-02 18:59:20 +03:00
|
|
|
|
|
|
|
render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
|
|
|
|
|
2022-10-02 22:03:50 +03:00
|
|
|
render_pass.draw_model_instanced(
|
|
|
|
&self.obj_model,
|
|
|
|
0..self.instances.len() as u32,
|
|
|
|
&self.camera_bind_group,
|
|
|
|
);
|
2022-10-01 23:58:09 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// submit will accept anything that implements IntoIter
|
|
|
|
self.queue.submit(std::iter::once(encoder.finish()));
|
|
|
|
output.present();
|
|
|
|
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
}
|