473 lines
16 KiB
Rust
Raw Normal View History

2025-05-04 01:13:13 +02:00
use std::cmp::max;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::Duration;
2025-05-04 12:03:18 +02:00
use cgmath::num_traits::ToPrimitive;
use cgmath::Rotation3;
2025-05-04 01:04:46 +02:00
use pollster::FutureExt;
use wgpu::util::DeviceExt;
2025-05-04 01:04:46 +02:00
use wgpu::{Adapter, Device, Instance, PresentMode, Queue, Surface, SurfaceCapabilities};
use winit::application::ApplicationHandler;
use winit::dpi::PhysicalSize;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::window::{Window, WindowId};
use solar_engine::{Body, Simulator};
2025-05-04 01:04:46 +02:00
pub async fn run() {
let event_loop = EventLoop::new().unwrap();
let mut window_state = StateApplication::new();
let _ = event_loop.run_app(&mut window_state);
}
2025-05-04 12:03:18 +02:00
struct RenderInstance {
position: cgmath::Vector3<f32>,
rotation: cgmath::Quaternion<f32>,
2025-05-04 12:51:41 +02:00
color: [f32; 3],
2025-05-04 12:55:12 +02:00
scale: f32
2025-05-04 12:03:18 +02:00
}
impl RenderInstance {
fn to_raw(&self) -> InstanceRaw {
2025-05-04 12:51:41 +02:00
let model = cgmath::Matrix4::from_translation(self.position)
2025-05-04 12:55:12 +02:00
* cgmath::Matrix4::from(self.rotation)
* cgmath::Matrix4::from_scale(self.scale);
2025-05-04 12:51:41 +02:00
InstanceRaw {
model: model.into(),
2025-05-04 12:55:12 +02:00
color: self.color,
2025-05-04 12:51:41 +02:00
}
2025-05-04 12:03:18 +02:00
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct InstanceRaw {
model: [[f32; 4]; 4],
2025-05-04 12:51:41 +02:00
color: [f32; 3],
2025-05-04 12:03:18 +02:00
}
impl InstanceRaw {
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
2025-05-04 12:51:41 +02:00
array_stride: std::mem::size_of::<InstanceRaw>() as wgpu::BufferAddress,
2025-05-04 12:03:18 +02:00
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute { offset: 0, shader_location: 5, format: wgpu::VertexFormat::Float32x4 },
2025-05-04 12:51:41 +02:00
wgpu::VertexAttribute { offset: 16, shader_location: 6, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 32, shader_location: 7, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 48, shader_location: 8, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 64, shader_location: 9, format: wgpu::VertexFormat::Float32x3 },
2025-05-04 12:03:18 +02:00
],
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
position: [f32; 3],
color: [f32; 3],
}
impl Vertex {
const ATTRIBS: [wgpu::VertexAttribute; 2] =
wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3];
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: size_of::<Self>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &Self::ATTRIBS,
}
}
}
const VERTICES: &[Vertex] = &[
2025-05-04 11:34:25 +02:00
Vertex { position: [-0.0868241, 0.49240386, 0.0], color: [0.5, 0.0, 0.5] },
Vertex { position: [-0.49513406, 0.06958647, 0.0], color: [0.5, 0.0, 0.5] },
Vertex { position: [-0.21918549, -0.44939706, 0.0], color: [0.5, 0.0, 0.5] },
Vertex { position: [0.35966998, -0.3473291, 0.0], color: [0.5, 0.0, 0.5] },
Vertex { position: [0.44147372, 0.2347359, 0.0], color: [0.5, 0.0, 0.5] },
];
const INDICES: &[u16] = &[
0, 1, 4,
1, 2, 4,
2, 3, 4,
];
2025-05-04 01:04:46 +02:00
struct StateApplication<'a> {
state: Option<State<'a>>,
}
impl<'a> StateApplication<'a> {
pub fn new() -> Self {
Self {
state: None,
}
}
}
impl<'a> ApplicationHandler for StateApplication<'a>{
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = event_loop.create_window(Window::default_attributes().with_title("Hello!")).unwrap();
self.state = Some(State::new(window));
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
let window = self.state.as_ref().unwrap().window();
if window.id() == window_id {
match event {
WindowEvent::CloseRequested => {
event_loop.exit();
}
WindowEvent::Resized(physical_size) => {
self.state.as_mut().unwrap().resize(physical_size);
}
WindowEvent::RedrawRequested => {
2025-05-04 01:22:33 +02:00
self.state.as_mut().unwrap().update();
2025-05-04 01:04:46 +02:00
self.state.as_mut().unwrap().render().unwrap();
}
2025-05-04 01:20:26 +02:00
WindowEvent::KeyboardInput { .. } => {
if let Some(state) = self.state.as_mut() {
if state.input(&event) {
return;
}
}
}
2025-05-04 01:04:46 +02:00
_ => {}
}
}
}
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
let window = self.state.as_ref().unwrap().window();
window.request_redraw();
}
2025-05-03 23:41:57 +02:00
}
2025-05-04 01:04:46 +02:00
struct State<'a> {
surface: Surface<'a>,
device: Device,
queue: Queue,
config: wgpu::SurfaceConfiguration,
size: PhysicalSize<u32>,
window: Arc<Window>,
2025-05-04 01:37:26 +02:00
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
2025-05-04 11:34:25 +02:00
index_buffer: wgpu::Buffer,
2025-05-04 12:03:18 +02:00
instances: Vec<RenderInstance>,
instance_buffer: wgpu::Buffer,
num_vertices: u32,
2025-05-04 11:34:25 +02:00
num_indices: u32,
simulator: Arc<RwLock<Simulator>>,
2025-05-04 01:04:46 +02:00
}
impl<'a> State<'a> {
pub fn new (window: Window) -> Self {
let window_arc = Arc::new(window);
let size = window_arc.inner_size();
let instance = Self::create_gpu_instance();
let surface = instance.create_surface(window_arc.clone()).unwrap();
let adapter = Self::create_adapter(instance, &surface);
let (device, queue) = Self::create_device(&adapter);
let surface_caps = surface.get_capabilities(&adapter);
let config = Self::create_surface_config(size, surface_caps);
surface.configure(&device, &config);
2025-05-04 01:37:26 +02:00
let render_pipeline = Self::create_render_pipeline(&device, &config);
let vertex_buffer = Self::create_vertex_buffer(&device);
2025-05-04 11:34:25 +02:00
let index_buffer = Self::create_index_buffer(&device);
let num_vertices = VERTICES.len() as u32;
2025-05-04 11:34:25 +02:00
let num_indices = INDICES.len() as u32;
2025-05-04 01:37:26 +02:00
let mut sim = Simulator::new(60.0 * 60.0 * 24.0);
sim.add_body(Body {
name: "Sun".to_string(),
position: [0.0, 0.0],
velocity: [0.0, 0.0],
mass: 1.989e30,
});
sim.add_body(Body {
name: "Earth".to_string(),
position: [1.496e11, 0.0],
velocity: [0.0, 29780.0],
mass: 5.972e24,
});
2025-05-04 12:51:41 +02:00
let simulator = Arc::new(RwLock::new(sim));
let sim_clone = simulator.clone();
thread::spawn(move || {
loop {
{
let mut sim = sim_clone.write().unwrap();
sim.step();
}
thread::sleep(Duration::from_millis(16));
}
});
let instances = {
let sim = simulator.read().unwrap();
2025-05-04 12:51:41 +02:00
sim.bodies.iter().enumerate().map(|(i, b)| RenderInstance {
position: cgmath::Vector3::new(
(b.position[0] / 1.496e11) as f32,
(b.position[1] / 1.496e11) as f32,
0.0,
),
2025-05-04 12:03:18 +02:00
rotation: cgmath::Quaternion::from_angle_z(cgmath::Deg(0.0)),
2025-05-04 12:51:41 +02:00
color: match i {
0 => [1.0, 1.0, 0.0],
1 => [0.0, 0.0, 1.0],
_ => [0.5, 0.5, 0.5],
},
2025-05-04 12:55:12 +02:00
scale: 0.1,
}).collect::<Vec<_>>()
};
2025-05-04 12:03:18 +02:00
let instance_data: Vec<InstanceRaw> = instances.iter().map(RenderInstance::to_raw).collect();
let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Instance Buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
2025-05-04 12:03:18 +02:00
});
2025-05-04 01:04:46 +02:00
Self {
surface,
device,
queue,
config,
size,
window: window_arc,
2025-05-04 01:37:26 +02:00
render_pipeline,
vertex_buffer,
2025-05-04 11:34:25 +02:00
index_buffer,
2025-05-04 12:03:18 +02:00
instances,
instance_buffer,
num_vertices,
2025-05-04 11:34:25 +02:00
num_indices,
simulator,
2025-05-04 01:04:46 +02:00
}
}
2025-05-04 01:20:26 +02:00
pub fn input(&mut self, event: &WindowEvent) -> bool {
false
}
fn update(&mut self) {
let updated_instances: Vec<RenderInstance> = {
let sim = self.simulator.read().unwrap();
2025-05-04 12:51:41 +02:00
sim.bodies.iter().enumerate().map(|(i, b)| RenderInstance {
position: cgmath::Vector3::new((b.position[0] / 1.496e11) as f32, (b.position[1] / 1.496e11) as f32, 0.0),
rotation: cgmath::Quaternion::from_angle_z(cgmath::Deg(0.0)),
2025-05-04 12:51:41 +02:00
color: match i {
0 => [1.0, 1.0, 0.0],
1 => [0.0, 0.0, 1.0],
_ => [0.5, 0.5, 0.5],
},
2025-05-04 12:55:12 +02:00
scale: 0.5,
}).collect()
};
let instance_data: Vec<InstanceRaw> = updated_instances.iter().map(RenderInstance::to_raw).collect();
self.queue.write_buffer(&self.instance_buffer, 0, bytemuck::cast_slice(&instance_data));
self.instances = updated_instances;
2025-05-04 01:20:26 +02:00
}
2025-05-04 01:37:26 +02:00
2025-05-04 11:34:25 +02:00
fn create_index_buffer(device: &Device) -> wgpu::Buffer {
device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"),
contents: bytemuck::cast_slice(INDICES),
usage: wgpu::BufferUsages::INDEX,
}
)
}
fn create_vertex_buffer(device: &Device) -> wgpu::Buffer {
device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(VERTICES),
usage: wgpu::BufferUsages::VERTEX,
}
)
}
2025-05-04 01:37:26 +02:00
fn create_render_pipeline(device: &Device, config: &wgpu::SurfaceConfiguration) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
2025-05-04 12:03:18 +02:00
buffers: &[Vertex::desc(), InstanceRaw::desc()],
compilation_options: Default::default(),
2025-05-04 01:37:26 +02:00
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList, // 1.
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,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
cache: None,
})
}
2025-05-04 01:20:26 +02:00
2025-05-04 01:04:46 +02:00
fn create_surface_config(size: PhysicalSize<u32>, capabilities: SurfaceCapabilities) -> wgpu::SurfaceConfiguration {
let surface_format = capabilities.formats.iter()
.find(|f| f.is_srgb())
.copied()
.unwrap_or(capabilities.formats[0]);
wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: PresentMode::AutoNoVsync,
alpha_mode: capabilities.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
}
}
fn create_device(adapter: &Adapter) -> (Device, Queue) {
adapter.request_device(
&wgpu::DeviceDescriptor {
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
memory_hints: Default::default(),
label: None,
trace: Default::default(),
}).block_on().unwrap()
}
fn create_adapter(instance: Instance, surface: &Surface) -> Adapter {
instance.request_adapter(
&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}
).block_on().unwrap()
}
fn create_gpu_instance() -> Instance {
Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
})
}
pub fn resize(&mut self, new_size: PhysicalSize<u32>) {
self.size = new_size;
2025-05-04 01:13:13 +02:00
self.config.width = max(new_size.width, 1);
self.config.height = max(new_size.height, 1);
2025-05-04 01:04:46 +02:00
self.surface.configure(&self.device, &self.config);
println!("Resized to {:?} from state!", new_size);
}
pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?;
2025-05-04 01:04:46 +02:00
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 {
2025-05-04 01:04:46 +02:00
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 1.0,
g: 0.2,
b: 0.3,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
}
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
2025-05-04 11:34:25 +02:00
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
if !self.instances.is_empty() {
render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
render_pass.draw_indexed(0..self.num_indices, 0, 0..self.instances.len() as u32);
}
2025-05-04 01:04:46 +02:00
}
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}
pub fn window(&self) -> &Window {
&self.window
}
}
fn main() {
pollster::block_on(run());
}