// lib.rs
pub mod material;
pub mod render;
pub mod simulation;
use winit::{
dpi::PhysicalSize,
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
mod render;
mod simulation;
mod material;
use render::Renderer;
use simulation::Simulation;
use material::Material;
use egui::Context;
use std::time::Instant;
fn main() {
let window_size = PhysicalSize::new(500, 500);
code
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("Falling Sand Simulator")
.with_inner_size(window_size)
.with_resizable(false)
.build(&event_loop)
.unwrap();
// Initialize the renderer and simulation
let mut renderer = pollster::block_on(Renderer::new(&window));
let mut simulation = Simulation::new();
let mut egui_ctx = Context::default();
let start_time = Instant::now();
// Selected material
let mut selected_material = Material::Sand;
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Poll;
// Pass the winit events to egui
match &event {
Event::WindowEvent { event, .. } => {
renderer.platform.handle_event(event);
}
_ => {}
}
match event {
Event::RedrawRequested(_) => {
// Update egui
let raw_input = renderer.platform.take_egui_input(&window);
egui_ctx.begin_frame(raw_input);
// Build UI
egui::Window::new("Materials").show(&egui_ctx, |ui| {
ui.label("Select a material:");
ui.radio_value(&mut selected_material, Material::Sand, "Sand");
ui.radio_value(&mut selected_material, Material::Water, "Water");
ui.radio_value(&mut selected_material, Material::Earth, "Earth");
ui.radio_value(&mut selected_material, Material::Lava, "Lava");
});
let (_output, shapes) = egui_ctx.end_frame();
let paint_jobs = egui_ctx.tessellate(shapes);
// Update simulation
simulation.update();
// Render
match renderer.render(&simulation, &paint_jobs, &egui_ctx) {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => renderer.resize(renderer.size),
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
Err(e) => eprintln!("{:?}", e),
}
}
Event::MainEventsCleared => {
window.request_redraw();
}
Event::WindowEvent { ref event, .. } => {
if !renderer.input(event, &mut simulation, &window, selected_material) {
match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
_ => {}
}
}
}
_ => {}
}
});
Assistant
}
// material.rs
use bytemuck::{Pod, Zeroable};
#[repr(u32)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Material {
Empty = 0,
Sand = 1,
Water = 2,
Earth = 3,
Lava = 4,
// Add more materials if needed
}
// SAFETY: Material is a field-less enum with a defined integer representation.
unsafe impl Zeroable for Material {}
unsafe impl Pod for Material {}
impl Material {
pub fn color(&self) -> [f32; 3] {
match self {
Material::Empty => [0.0, 0.0, 0.0], // Black
Material::Sand => [0.8, 0.7, 0.5], // Sandy color
Material::Water => [0.0, 0.5, 1.0], // Blue
Material::Earth => [0.4, 0.3, 0.2], // Brown
Material::Lava => [1.0, 0.3, 0.0], // Orange-red
}
}
}
use winit::window::Window;
use crate::simulation::{Simulation, SIM_HEIGHT, SIM_WIDTH};
use crate::material::Material;
use egui_wgpu::renderer::{Renderer as EguiRenderer, ScreenDescriptor};
impl Simulation {
pub fn new() -> Self {
// Initialize the grid with empty materials
let cells = vec![Material::Empty; (SIM_WIDTH * SIM_HEIGHT) as usize];
code
Self { cells }
}
pub fn update(&mut self) {
// Update simulation state if needed
// Currently, the logic is handled on the GPU
}
// Methods to interact with the simulation (e.g., add material at position)
pub fn add_material(&mut self, x: u32, y: u32, material: Material) {
if x < SIM_WIDTH && y < SIM_HEIGHT {
let index = (y * SIM_WIDTH + x) as usize;
self.cells[index] = material;
}
}
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) global_id: vec3) {
let x = global_id.x;
let y = global_id.y;
let index = y * SIM_WIDTH + x;
code
// Check bounds
if x >= SIM_WIDTH || y >= SIM_HEIGHT {
return;
}
let cell_material = cells[index];
if cell_material == 1u { // Sand
// Implement sand logic
var moved = false;
// Try moving down
if y + 1u < SIM_HEIGHT {
let below_index = (y + 1u) * SIM_WIDTH + x;
if cells[below_index] == 0u || cells[below_index] == 2u { // empty or water
cells[index] = cells[below_index];
cells[below_index] = 1u;
moved = true;
}
}
// Try moving down-left
if !moved && x > 0u && y + 1u < SIM_HEIGHT {
let below_left_index = (y + 1u) * SIM_WIDTH + (x - 1u);
if cells[below_left_index] == 0u || cells[below_left_index] == 2u {
cells[index] = cells[below_left_index];
cells[below_left_index] = 1u;
moved = true;
}
}
// Try moving down-right
if !moved && x + 1u < SIM_WIDTH && y + 1u < SIM_HEIGHT {
let below_right_index = (y + 1u) * SIM_WIDTH + (x + 1u);
if cells[below_right_index] == 0u || cells[below_right_index] == 2u {
cells[index] = cells[below_right_index];
cells[below_right_index] = 1u;
moved = true;
}
}
} else if cell_material == 2u { // Water
// Implement water logic
var moved = false;
// Try moving down
if y + 1u < SIM_HEIGHT {
let below_index = (y + 1u) * SIM_WIDTH + x;
if cells[below_index] == 0u {
cells[index] = cells[below_index];
cells[below_index] = 2u;
moved = true;
}
}
// Try moving left
if !moved && x > 0u {
let left_index = y * SIM_WIDTH + (x - 1u);
if cells[left_index] == 0u {
cells[index] = cells[left_index];
cells[left_index] = 2u;
moved = true;
}
}
// Try moving right
if !moved && x + 1u < SIM_WIDTH {
let right_index = y * SIM_WIDTH + (x + 1u);
if cells[right_index] == 0u {
cells[index] = cells[right_index];
cells[right_index] = 2u;
moved = true;
}
}
}
// Add logic for other materials if needed
let x = u32(frag_coord.x / sim_cell_width);
let y = u32(frag_coord.y / sim_cell_height);
// Check bounds
if x >= SIM_WIDTH || y >= SIM_HEIGHT {
discard;
}
let index = y * SIM_WIDTH + x;
let material = cells[index];
var color: vec3<f32>;
if material == 0u {
discard; // Don't draw anything
} else if material == 1u {
color = vec3(0.8, 0.7, 0.5); // Sand
} else if material == 2u {
color = vec3(0.0, 0.5, 1.0); // Water
} else if material == 3u {
color = vec3(0.4, 0.3, 0.2); // Earth
} else if material == 4u {
color = vec3(1.0, 0.3, 0.0); // Lava
} else {
color = vec3(1.0, 1.0, 1.0); // Default
}
return vec4(color, 1.0);
let pos = positions[vertex_index];
return vec4(pos, 0.0, 1.0);
}
error[E0432]: unresolved import egui_winit
--> src\render.rs:9:5
|
9 | use egui_winit::State;
| ^^^^^^^^^^ use of undeclared crate or module egui_winit
error[E0308]: arguments to this function are incorrect
--> src\render.rs:228:29
|
228 | let egui_renderer = EguiRenderer::new(&device, config.format, None, 1);
| ^^^^^^^^^^^^^^^^^ ------- ------------- expected egui_wgpu::wgpu::TextureFormat, found wgpu::TextureFormat
| |
| expected egui_wgpu::wgpu::Device, found wgpu::Device
|
= note: wgpu::Device and egui_wgpu::wgpu::Device have similar names, but are actually distinct types
note: wgpu::Device is defined in crate wgpu
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-0.16.3\src\lib.rs:117:1
|
117 | pub struct Device {
| ^^^^^^^^^^^^^^^^^
note: egui_wgpu::wgpu::Device is defined in crate wgpu
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-0.17.2\src\lib.rs:160:1
|
160 | pub struct Device {
| ^^^^^^^^^^^^^^^^^
= note: perhaps two different versions of crate wgpu are being used?
= note: wgpu::TextureFormat and egui_wgpu::wgpu::TextureFormat have similar names, but are actually distinct types
note: wgpu::TextureFormat is defined in crate wgpu_types
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-types-0.16.1\src\lib.rs:1907:1
|
1907 | pub enum TextureFormat {
| ^^^^^^^^^^^^^^^^^^^^^^
note: egui_wgpu::wgpu::TextureFormat is defined in crate wgpu_types
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-types-0.17.0\src\lib.rs:1940:1
|
1940 | pub enum TextureFormat {
| ^^^^^^^^^^^^^^^^^^^^^^
= note: perhaps two different versions of crate wgpu_types are being used?
note: associated function defined here
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\egui-wgpu-0.23.0\src\renderer.rs:180:12
|
180 | pub fn new(
| ^^^
error[E0560]: struct ScreenDescriptor has no field named physical_width
--> src\render.rs:358:13
|
358 | physical_width: self.size.width,
| ^^^^^^^^^^^^^^ ScreenDescriptor does not have this field
|
= note: available fields are: size_in_pixels, pixels_per_point
error[E0560]: struct ScreenDescriptor has no field named physical_height
--> src\render.rs:359:13
|
359 | physical_height: self.size.height,
| ^^^^^^^^^^^^^^^ ScreenDescriptor does not have this field
|
= note: available fields are: size_in_pixels, pixels_per_point
error[E0560]: struct ScreenDescriptor has no field named scale_factor
--> src\render.rs:360:13
|
360 | scale_factor: 1.0,
| ^^^^^^^^^^^^ ScreenDescriptor does not have this field
|
= note: available fields are: size_in_pixels, pixels_per_point
error[E0061]: this method takes 5 arguments but 4 arguments were supplied
--> src\render.rs:363:28
|
363 | self.egui_renderer.update_buffers(
| ^^^^^^^^^^^^^^
364 | &self.device,
| ------------ expected egui_wgpu::wgpu::Device, found wgpu::Device
365 | &self.queue,
| ----------- expected egui_wgpu::wgpu::Queue, found wgpu::Queue
366 | paint_jobs,
| ---------- argument #3 of type &mut egui_wgpu::wgpu::CommandEncoder is missing
|
= note: wgpu::Device and egui_wgpu::wgpu::Device have similar names, but are actually distinct types
note: wgpu::Device is defined in crate wgpu
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-0.16.3\src\lib.rs:117:1
|
117 | pub struct Device {
| ^^^^^^^^^^^^^^^^^
note: egui_wgpu::wgpu::Device is defined in crate wgpu
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-0.17.2\src\lib.rs:160:1
|
160 | pub struct Device {
| ^^^^^^^^^^^^^^^^^
= note: perhaps two different versions of crate wgpu are being used?
= note: wgpu::Queue and egui_wgpu::wgpu::Queue have similar names, but are actually distinct types
note: wgpu::Queue is defined in crate wgpu
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-0.16.3\src\lib.rs:715:1
|
715 | pub struct Queue {
| ^^^^^^^^^^^^^^^^
note: egui_wgpu::wgpu::Queue is defined in crate wgpu
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\wgpu-0.17.2\src\lib.rs:884:1
|
884 | pub struct Queue {
| ^^^^^^^^^^^^^^^^
= note: perhaps two different versions of crate wgpu are being used?
note: method defined here
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\egui-wgpu-0.23.0\src\renderer.rs:752:12
|
752 | pub fn update_buffers(
| ^^^^^^^^^^^^^^
help: provide the argument
|
363 | self.egui_renderer.update_buffers(/* &egui_wgpu::wgpu::Device /, / &egui_wgpu::wgpu::Queue /, / &mut egui_wgpu::wgpu::CommandEncoder */, paint_jobs, &screen_descriptor);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error[E0061]: this method takes 3 arguments but 5 arguments were supplied
--> src\render.rs:372:32
|
372 | self.egui_renderer.render(
| ^^^^^^
373 | &mut encoder,
| ------------ expected &mut RenderPass<'_>, found &mut CommandEncoder
374 | &view,
| ----- unexpected argument #2 of type &wgpu::TextureView
...
377 | None,
| ---- unexpected argument #5 of type Option<_>
|
= note: expected mutable reference &mut egui_wgpu::wgpu::RenderPass<'_>
found mutable reference &mut wgpu::CommandEncoder
note: method defined here
--> C:\Users\Enzo.cargo\registry\src\index.crates.io-6f17d22bba15001f\egui-wgpu-0.23.0\src\renderer.rs:360:12
|
360 | pub fn render<'rp>(
| ^^^^^^
help: remove the extra arguments
|
373 ~ /* &mut egui_wgpu::wgpu::RenderPass<'_> */,
374 | paint_jobs,
375 ~ &screen_descriptor,
|
error[E0599]: no method named unwrap found for unit type () in the current scope
--> src\render.rs:378:15
|
372 | / self.egui_renderer.render(
373 | | &mut encoder,
374 | | &view,
375 | | paint_jobs,
376 | | &screen_descriptor,
377 | | None,
378 | | ).unwrap();
| | -^^^^^^ method not found in ()
| |______________|
|
Some errors have detailed explanations: E0061, E0308, E0432, E0560, E0599.
For more information about an error, try rustc --explain E0061.
error: could not compile falling_sand_simulator (lib) due to 8 previous errors
The errors you're encountering are primarily due to version mismatches between the wgpu, wgpu_types, and egui_wgpu crates. Specifically, your project is using different versions of wgpu and wgpu_types than what egui_wgpu expects, leading to type mismatches and unresolved imports.
Let's break down the key issues and provide step-by-step solutions to resolve them.
Understanding the Errors
Unresolved Import egui_winit
code
error[E0432]: unresolved import `egui_winit`
--> src\render.rs:9:5
|
9 | use egui_winit::State;
| ^^^^^^^^^^ use of undeclared crate or module `egui_winit`
This suggests that the egui_winit crate isn't included in your Cargo.toml dependencies.
Multiple Versions of wgpu and wgpu_types
code
error[E0308]: arguments to this function are incorrect
...
= note: `wgpu::Device` and `egui_wgpu::wgpu::Device` have similar names, but are actually distinct types
...
= note: perhaps two different versions of crate `wgpu` are being used?
This indicates that your code is using one version of wgpu, while egui_wgpu is using another, leading to type mismatches because Rust considers types from different versions of the same crate as different.
Struct ScreenDescriptor Fields Not Matching
code
error[E0560]: struct `ScreenDescriptor` has no field named `physical_width`
--> src\render.rs:358:13
|
358 | physical_width: self.size.width,
| ^^^^^^^^^^^^^^ `ScreenDescriptor` does not have this field
|
= note: available fields are: `size_in_pixels`, `pixels_per_point`
This suggests that the ScreenDescriptor struct has a different API in the version you're using compared to what's expected in your code.
Method Argument Mismatches
code
error[E0061]: this method takes 5 arguments but 4 arguments were supplied
This indicates that the method signatures have changed between versions.
Step-by-Step Solutions
1. Align wgpu and wgpu_types Versions
The root cause is that different crates are using different versions of wgpu. You need to ensure that all dependencies use the same version.
if self.platform.on_event(egui_ctx, event).consumed {
return true;
}
4. Full Code Adjustments
Here's how your render method should look after adjustments:
rust
Adjust your main function as well to pass window to the render method:
rust
match renderer.render(&simulation, &paint_jobs, &egui_ctx, &window) {
// ...
}
5. Re-compile and Test
With these changes:
Run cargo clean to remove old build artifacts.
Build your project with cargo build.
Run your project with cargo run.
Summary
The errors were due to:
Version mismatches between wgpu crates.
API changes in newer versions of egui_wgpu, egui_winit, and wgpu.
Key steps:
Update all wgpu-related crates to the same version (0.17).
Adjust your code to match the new APIs of these crates.
By ensuring all your dependencies are compatible and updating your code accordingly, you should resolve the compilation errors and get your falling sand simulator running with the integrated GUI.
Not yet included in a published release.
WH
E
I
G
H
T
:
u32=
Note: Remove the .unwrap() as the render method doesn’t return a Result anymore.
pub fn render(
&mut self,
simulation: &Simulation,
paint_jobs: &[egui::ClippedPrimitive],
egui_ctx: &Context,
window: &Window, // Add window parameter to access scale factor
) -> Result<(), wgpu::SurfaceError> {
// Update the cell buffer with the simulation data
self.queue.write_buffer(
&self.cell_buffer,
0,
bytemuck::cast_slice(&simulation.cells),
);
// Get current frame
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
// Create command encoder
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Main Encoder"),
});
// Run compute shader to update simulation
{
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.compute_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);
}
// Render pass for the simulation
{
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 {
// Clear the screen before drawing
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: true,
},
})],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.render_bind_group, &[]);
render_pass.draw(0..6, 0..1); // Drawing a quad
}
// Prepare egui
let screen_descriptor = ScreenDescriptor {
size_in_pixels: [self.size.width, self.size.height],
pixels_per_point: window.scale_factor() as f32,
};
self.egui_renderer.update_buffers(
&self.device,
&self.queue,
&mut encoder,
paint_jobs,
&screen_descriptor,
);
// Render egui
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("egui Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load, // Use existing content
store: true,
},
})],
depth_stencil_attachment: None,
});
self.egui_renderer.render(
&mut render_pass,
paint_jobs,
&screen_descriptor,
);
}
// Submit command buffer
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}