// Instance
let instance = wgpu::Instance::default();
// Surface
let surface = unsafe { instance.create_surface(window) }.unwrap();
// Adapter
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
..Default::default()
})
.await
.unwrap();
// Device and Queue
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::default(), // No need to enable additional features
limits: wgpu::Limits::default(),
label: None,
},
None,
)
.await
.unwrap();
// Surface configuration
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface.get_capabilities(&adapter).formats[0],
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: surface.get_capabilities(&adapter).alpha_modes[0],
view_formats: vec![],
};
surface.configure(&device, &config);
// Create a buffer for the simulation data
let cell_buffer_size =
(std::mem::size_of::<u32>() * SIM_WIDTH as usize * SIM_HEIGHT as usize) as u64;
let cell_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Cell Buffer"),
size: cell_buffer_size,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
// Bind group layout and bind group
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Cell Bind Group Layout"),
entries: &[
// Binding for compute shader (read-write)
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Binding for vertex and fragment shaders (read-only)
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Cell Bind Group"),
layout: &bind_group_layout,
entries: &[
// Binding for compute shader
wgpu::BindGroupEntry {
binding: 0,
resource: cell_buffer.as_entire_binding(),
},
// Binding for vertex and fragment shaders
wgpu::BindGroupEntry {
binding: 1,
resource: cell_buffer.as_entire_binding(),
},
],
});
// Load shaders
let vertex_shader_source = include_str!("shaders/vertex.wgsl");
// Replace placeholders with actual values (if any)
let vertex_shader_source = vertex_shader_source
.replace("$SIM_WIDTH", &SIM_WIDTH.to_string())
.replace("$SIM_HEIGHT", &SIM_HEIGHT.to_string())
.replace("$WINDOW_WIDTH", &size.width.to_string())
.replace("$WINDOW_HEIGHT", &size.height.to_string());
let vertex_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex Shader"),
source: wgpu::ShaderSource::Wgsl(vertex_shader_source.into()),
});
let fragment_shader_source = include_str!("shaders/fragment.wgsl");
// Replace placeholders with actual values
let fragment_shader_source = fragment_shader_source
.replace("$SIM_WIDTH", &SIM_WIDTH.to_string())
.replace("$SIM_HEIGHT", &SIM_HEIGHT.to_string())
.replace("$WINDOW_WIDTH", &size.width.to_string())
.replace("$WINDOW_HEIGHT", &size.height.to_string());
let fragment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Fragment Shader"),
source: wgpu::ShaderSource::Wgsl(fragment_shader_source.into()),
});
let compute_shader_source = include_str!("shaders/compute.wgsl");
// Replace placeholders with actual values
let compute_shader_source = compute_shader_source
.replace("$SIM_WIDTH", &SIM_WIDTH.to_string())
.replace("$SIM_HEIGHT", &SIM_HEIGHT.to_string());
let compute_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Compute Shader"),
source: wgpu::ShaderSource::Wgsl(compute_shader_source.into()),
});
// Render pipeline layout
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[],
});
// Render pipeline
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &vertex_shader,
entry_point: "main",
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &fragment_shader,
entry_point: "main",
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
});
// Compute pipeline layout
let compute_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Compute Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[],
});
// Compute pipeline
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Compute Pipeline"),
layout: Some(&compute_pipeline_layout),
module: &compute_shader,
entry_point: "main",
});
Self {
device,
queue,
surface,
config,
size,
render_pipeline,
compute_pipeline,
cell_buffer,
bind_group,
cursor_position: None, // Initialize cursor_position
}
}
pub fn input(
&mut self,
event: &winit::event::WindowEvent,
simulation: &mut Simulation,
_window: &Window,
) -> bool {
match event {
winit::event::WindowEvent::CursorMoved { position, .. } => {
// Store the current cursor position
self.cursor_position = Some(*position);
false
}
winit::event::WindowEvent::MouseInput {
state,
button,
..
} => {
if *button == winit::event::MouseButton::Left
&& *state == winit::event::ElementState::Pressed
{
if let Some(pos) = self.cursor_position {
let x = (pos.x / self.size.width as f64 * SIM_WIDTH as f64) as u32;
let y = (pos.y / self.size.height as f64 * SIM_HEIGHT as f64) as u32;
simulation.add_material(x, y, Material::Sand);
}
true
} else {
false
}
}
_ => false,
}
}
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);
}
}
pub fn render(&mut self, simulation: &Simulation) -> Result<(), wgpu::SurfaceError> {
// Update the cell buffer with the simulation data
self.queue.write_buffer(
&self.cell_buffer,
0,
bytemuck::cast_slice(&simulation.cells),
);
// Run compute shader to update simulation
{
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Compute Encoder"),
});
{
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Compute Pass"),
});
compute_pass.set_pipeline(&self.compute_pipeline);
compute_pass.set_bind_group(0, &self.bind_group, &[]);
// Adjust workgroup counts
let workgroup_size = 8u32;
let dispatch_x = (SIM_WIDTH + workgroup_size - 1) / workgroup_size;
let dispatch_y = (SIM_HEIGHT + workgroup_size - 1) / workgroup_size;
compute_pass.dispatch_workgroups(dispatch_x, dispatch_y, 1);
}
self.queue.submit(Some(encoder.finish()));
}
// Get current frame
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
// Command encoder
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
// Render pass
{
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::Load,
store: true,
},
})],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.draw(0..6, 0..1); // Drawing a quad
}
// Submit command buffer
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}
To fix the errors and warnings in the given code, particularly the shader parsing error that causes the program to panic, we need to ensure that the constants in the WGSL shader code have the correct type annotations. Here's how you can fix the issues:
1. Fixing the Shader Constants
The main error arises because in WGSL (WebGPU Shading Language), integer literals without a type suffix are inferred as i32 by default. When you assign these to a u32 constant without specifying the literal as unsigned (by appending a u), you get a type mismatch.
Solution: Modify the Rust code where you replace the placeholders in the shader source to append the appropriate type suffixes.
In your Renderer::new function in render.rs, update the placeholder replacements for the shader source codes as follows:
// For the fragment shader
let fragment_shader_source = fragment_shader_source
.replace("$SIM_WIDTH", &format!("{}u", SIM_WIDTH))
.replace("$SIM_HEIGHT", &format!("{}u", SIM_HEIGHT))
.replace("$WINDOW_WIDTH", &format!("{}.", size.width))
.replace("$WINDOW_HEIGHT", &format!("{}.", size.height));
// For the compute shader
let compute_shader_source = compute_shader_source
.replace("$SIM_WIDTH", &format!("{}u", SIM_WIDTH))
.replace("$SIM_HEIGHT", &format!("{}u", SIM_HEIGHT));
Explanation:
- Unsigned Integers (
u32): By appending u to the constants (e.g., 500u), you ensure they are interpreted as u32 in WGSL.
- Floating-Point Numbers (
f32): By ensuring there's a decimal point in the constants (e.g., 500.), you make sure they are interpreted as f32.
2. Addressing the Warnings
While the warnings don't prevent your code from running, addressing them will make your code cleaner and free from unnecessary code.
-
Unused Import Warning:
In main.rs, you're importing Material but not using it directly. Since Material is used in render.rs, you don't need to import it in main.rs.
// Remove this line in main.rs
// use material::Material;
-
Unused Methods and Variants:
-
Unused update method in Simulation: If you don't plan to use this method yet, you can comment it out or remove it. Alternatively, if you intend to use it in future development, you can suppress the warning by adding #[allow(dead_code)] above it.
#[allow(dead_code)]
pub fn update(&mut self) {
// Implementation...
}
-
Unused Variants in Material: Similarly, if you plan to use Water, Earth, and Lava in the future, you can suppress the warning:
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[allow(dead_code)]
pub enum Material {
Empty = 0,
Sand = 1,
Water = 2,
Earth = 3,
Lava = 4,
}
-
Unused color Method in Material: If you don't use the color method, you can remove it or suppress the warning:
#[allow(dead_code)]
impl Material {
pub fn color(&self) -> [f32; 3] {
// Implementation...
}
}
3. Full Corrected Code Sections
Here's the corrected sections of your code:
In render.rs:
// Load shaders
let fragment_shader_source = include_str!("shaders/fragment.wgsl");
// Replace placeholders with actual values
let fragment_shader_source = fragment_shader_source
.replace("$SIM_WIDTH", &format!("{}u", SIM_WIDTH))
.replace("$SIM_HEIGHT", &format!("{}u", SIM_HEIGHT))
.replace("$WINDOW_WIDTH", &format!("{}.", size.width))
.replace("$WINDOW_HEIGHT", &format!("{}.", size.height));
let compute_shader_source = include_str!("shaders/compute.wgsl");
// Replace placeholders with actual values
let compute_shader_source = compute_shader_source
.replace("$SIM_WIDTH", &format!("{}u", SIM_WIDTH))
.replace("$SIM_HEIGHT", &format!("{}u", SIM_HEIGHT));
In main.rs:
// Remove the unused import
// use material::Material;
4. Explanation of Changes
- Type Suffixes in Shader Constants: By appending
u to integer constants and adding a decimal point to floating-point constants, you ensure type correctness in WGSL, preventing type mismatch errors.
- Suppressing Warnings: By using
#[allow(dead_code)], you inform the compiler that certain code is intentionally unused at the moment, which suppresses the corresponding warnings.
5. Rebuilding and Running
After making these changes, rebuild your project:
cargo build
Then run it:
cargo run
Your program should now compile without errors, and the shader should work correctly, rendering the simulation as expected.
Note on Future Development:
As you continue developing your simulation and start using the unused variants and methods, you can remove the #[allow(dead_code)] annotations. This way, the compiler will help you catch any genuinely unused code in the future.