write a basic 3d game on rust
- User
write a basic 3d game on rust
- Assistant
write a basic 3d game on rust
Creating a basic 3D game in Rust can be a rewarding experience, as Rust offers powerful performance and safety guarantees. To develop a simple 3D game, you can use libraries like winit for window management and event handling, wgpu for rendering, and cgmath for mathematical operations. Let's create a basic 3D setup that creates a window and renders a rotating cube. This example assumes you have Rust and Cargo installed.
Project Setup: First, create a new Rust project.
cargo new simple_3d_game
cd simple_3d_game
Dependencies: Add necessary dependencies to your Cargo.toml file.
[dependencies]
winit = "0.28.5"
wgpu = "0.13.1"
cgmath = "0.18.0"
pollster = "0.3.1"
Code: Replace the contents of src/main.rs with the following:
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
use wgpu::util::DeviceExt;
use cgmath::{Deg, Matrix4, Point3, Vector3, perspective, InnerSpace, Rotation3, Zero};
use std::time::{Duration, Instant};
#[rustfmt::skip]
const VERTICES: &[f32] = &[
// positions // colors
-0.5, -0.5, 0.5, 1.0, 0.0, 0.0, // Front face
0.5, -0.5, 0.5, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, 1.0, 1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0, 1.0, // Back face
0.5, -0.5, -0.5, 1.0, 0.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0, 1.0,
-0.5, 0.5, -0.5, 0.2, 0.2, 0.2,
];
const INDICES: &[u16] = &[
0, 1, 2, 2, 3, 0, // front
4, 5, 6, 6, 7, 4, // back
0, 4, 7, 7, 3, 0, // left
1, 5, 6, 6, 2, 1, // right
3, 2, 6, 6, 7, 3, // top
0, 1, 5, 5, 4, 0, // bottom
];
#[derive(Debug)]
struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
sc_desc: wgpu::SurfaceConfiguration,
size: winit::dpi::PhysicalSize<u32>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
num_indices: u32,
start_time: Instant,
}
impl State {
async fn new(window: &winit::window::Window) -> Self {
let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::Backends::PRIMARY);
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).await.unwrap();
let sc_desc = 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, &sc_desc);
let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});
let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[wgpu::VertexBufferLayout {
array_stride: 6 * 4,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 3 * 4,
shader_location: 1,
},
],
}],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[wgpu::ColorTargetState {
format: sc_desc.format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::REPLACE,
alpha: wgpu::BlendComponent::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),
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(VERTICES),
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"),
contents: bytemuck::cast_slice(INDICES),
usage: wgpu::BufferUsages::INDEX,
});
Self {
surface,
device,
queue,
sc_desc,
size,
render_pipeline,
vertex_buffer,
index_buffer,
num_indices: INDICES.len() as u32,
start_time: Instant::now(),
}
}
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
self.size = new_size;
self.sc_desc.width = new_size.width;
self.sc_desc.height = new_size.height;
self.surface.configure(&self.device, &self.sc_desc);
}
}
fn input(&mut self, _event: &WindowEvent) -> bool {
false
}
fn update(&mut self) {}
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: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
}),
store: true,
},
})],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
}
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}
}
fn main() {
pollster::block_on(run());
}
async fn run() {
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.build(&event_loop)
.unwrap();
let mut state = State::new(&window).await;
event_loop.run(move |event, _, control_flow| {
match event {
Event::WindowEvent {
ref event,
window_id,
} if window_id == window.id() => if !state.input(event) {
match event {
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(physical_size) => {
state.resize(*physical_size);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
state.resize(**new_inner_size);
}
_ => {}
}
},
Event::RedrawRequested(_) => {
state.update();
match state.render() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost) => state.resize(state.size),
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
Err(e) => eprintln!("{:?}", e),
}
}
Event::MainEventsCleared => {
window.request_redraw();
}
_ => {}
}
});
}
Shader: Create a shader file src/shader.wgsl with the following content:
struct VertexInput {
[[builtin(vertex_index)]] vertex_index: u32,
[[location(0)]] pos: vec3<f32>,
[[location(1)]] color: vec3<f32>,
};
[[block]] struct Uniforms {
mvp: mat4x4<f32>;
};
[[binding(0), group(0)]] var<uniform> uniforms: Uniforms;
struct VertexOutput {
[[builtin(position)]] position: vec4<f32>,
[[location(0)]] frag_color: vec3<f32>,
};
[[stage(vertex)]]
fn vs_main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = uniforms.mvp * vec4<f32>(input.pos, 1.0);
output.frag_color = input.color;
return output;
}
[[stage(fragment)]]
fn fs_main(input: VertexOutput) -> [[location(0)]] vec4<f32> {
return vec4<f32>(input.frag_color, 1.0);
}
Build and Run: Finally, build and run the project.
cargo run
This example code sets up a window with a colored rotating cube. It initializes the window and event loop, configures the graphics pipeline, and draws a cube with indexed rendering. You can extend this by adding more features such as camera controls, lighting, and animation.
Not yet included in a published release.