Init renderer
This commit is contained in:
commit
52af9dfd86
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
8
.idea/.gitignore
generated
vendored
Normal file
8
.idea/.gitignore
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/orbital_simulation.iml" filepath="$PROJECT_DIR$/.idea/orbital_simulation.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
11
.idea/orbital_simulation.iml
generated
Normal file
11
.idea/orbital_simulation.iml
generated
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="EMPTY_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager">
|
||||||
|
<content url="file://$MODULE_DIR$">
|
||||||
|
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||||
|
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
2170
Cargo.lock
generated
Normal file
2170
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
12
Cargo.toml
Normal file
12
Cargo.toml
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
[package]
|
||||||
|
name = "orbital_simulation"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
pollster = "0.3"
|
||||||
|
winit = { version = "0.29", features = ["rwh_05"] }
|
||||||
|
env_logger = "0.10"
|
||||||
|
log = "0.4"
|
||||||
|
wgpu = "22.0"
|
||||||
|
bytemuck = { version = "1.16", features = [ "derive" ] }
|
||||||
432
src/lib.rs
Normal file
432
src/lib.rs
Normal file
@ -0,0 +1,432 @@
|
|||||||
|
use winit::{
|
||||||
|
event::*,
|
||||||
|
event_loop::EventLoop,
|
||||||
|
keyboard::{KeyCode, PhysicalKey},
|
||||||
|
window::WindowBuilder,
|
||||||
|
};
|
||||||
|
|
||||||
|
use winit::window::Window;
|
||||||
|
|
||||||
|
use wgpu::util::DeviceExt;
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||||
|
struct Vertex {
|
||||||
|
position: [f32; 3],
|
||||||
|
color: [f32; 3],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vertex {
|
||||||
|
fn desc() -> wgpu::VertexBufferLayout<'static> {
|
||||||
|
wgpu::VertexBufferLayout {
|
||||||
|
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
||||||
|
step_mode: wgpu::VertexStepMode::Vertex,
|
||||||
|
attributes: &[
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
offset: 0,
|
||||||
|
shader_location: 0,
|
||||||
|
format: wgpu::VertexFormat::Float32x3,
|
||||||
|
},
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
|
||||||
|
shader_location: 1,
|
||||||
|
format: wgpu::VertexFormat::Float32x3,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const VERTICES: &[Vertex] = &[
|
||||||
|
Vertex { position: [-0.0868241, 0.49240386, 0.0], color: [0.5, 0.0, 0.5] }, // A
|
||||||
|
Vertex { position: [-0.49513406, 0.06958647, 0.0], color: [0.5, 0.0, 0.5] }, // B
|
||||||
|
Vertex { position: [-0.21918549, -0.44939706, 0.0], color: [0.5, 0.0, 0.5] }, // C
|
||||||
|
Vertex { position: [0.35966998, -0.3473291, 0.0], color: [0.5, 0.0, 0.5] }, // D
|
||||||
|
Vertex { position: [0.44147372, 0.2347359, 0.0], color: [0.5, 0.0, 0.5] }, // E
|
||||||
|
];
|
||||||
|
|
||||||
|
const INDICES: &[u16] = &[
|
||||||
|
0, 1, 4,
|
||||||
|
1, 2, 4,
|
||||||
|
2, 3, 4,
|
||||||
|
];
|
||||||
|
|
||||||
|
struct State<'a> {
|
||||||
|
surface: wgpu::Surface<'a>,
|
||||||
|
device: wgpu::Device,
|
||||||
|
queue: wgpu::Queue,
|
||||||
|
config: wgpu::SurfaceConfiguration,
|
||||||
|
size: winit::dpi::PhysicalSize<u32>,
|
||||||
|
// The window must be declared after the surface so
|
||||||
|
// it gets dropped after it as the surface contains
|
||||||
|
// unsafe references to the window's resources.
|
||||||
|
window: &'a Window,
|
||||||
|
render_pipeline: wgpu::RenderPipeline,
|
||||||
|
vertex_buffer: wgpu::Buffer,
|
||||||
|
index_buffer: wgpu::Buffer,
|
||||||
|
num_indices: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> State<'a> {
|
||||||
|
// Creating some of the wgpu types requires async code
|
||||||
|
async fn new(window: &'a Window) -> State<'a> {
|
||||||
|
let size = window.inner_size();
|
||||||
|
let num_vertices = VERTICES.len() as u32;
|
||||||
|
|
||||||
|
// The instance is a handle to our GPU
|
||||||
|
// Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
|
||||||
|
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||||
|
// TODO: Change this when enabling switchable graphics for the user
|
||||||
|
// If this is not for the web, we can use Vulkan + Metal + DX12
|
||||||
|
#[cfg(not(target_arch="wasm32"))]
|
||||||
|
backends: wgpu::Backends::PRIMARY,
|
||||||
|
// TODO: Probably remove this, because WebAssembly won't be used for the foreseeable future
|
||||||
|
#[cfg(target_arch="wasm32")]
|
||||||
|
backends: wgpu::Backends::GL,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
let surface = instance.create_surface(window).unwrap();
|
||||||
|
|
||||||
|
// This checks all the adapters on a machine and returns an iterator
|
||||||
|
/*let adapter = instance
|
||||||
|
.enumerate_adapters(wgpu::Backends::all())
|
||||||
|
.filter(|adapter| {
|
||||||
|
// Check if this adapter supports our surface
|
||||||
|
adapter.is_surface_supported(&surface)
|
||||||
|
})
|
||||||
|
.next()
|
||||||
|
.unwrap()*/
|
||||||
|
|
||||||
|
// TODO: Include Telemetry to see how many users WGPU chooses a suboptimal adapter for
|
||||||
|
let adapter = instance.request_adapter(
|
||||||
|
&wgpu::RequestAdapterOptions {
|
||||||
|
power_preference: wgpu::PowerPreference::default(),
|
||||||
|
compatible_surface: Some(&surface),
|
||||||
|
force_fallback_adapter: false,
|
||||||
|
},
|
||||||
|
).await.unwrap();
|
||||||
|
|
||||||
|
log::info!("Adapter: {:?}", adapter.get_info());
|
||||||
|
|
||||||
|
// List of all features the current device supports
|
||||||
|
// let features = adapter.features();
|
||||||
|
|
||||||
|
let (device, queue) = adapter.request_device(
|
||||||
|
&wgpu::DeviceDescriptor {
|
||||||
|
required_features: wgpu::Features::empty(),
|
||||||
|
// WebGL doesn't support all of wgpu's features, so if
|
||||||
|
// we're building for the web, we'll have to disable some.
|
||||||
|
// TODO: Probably remove check for wasm32, because WebAssembly won't be used for the foreseeable future
|
||||||
|
required_limits: if cfg!(target_arch = "wasm32") {
|
||||||
|
wgpu::Limits::downlevel_webgl2_defaults()
|
||||||
|
} else {
|
||||||
|
wgpu::Limits::default()
|
||||||
|
},
|
||||||
|
label: None,
|
||||||
|
// Default is performance, which requires more memory, but is faster
|
||||||
|
memory_hints: Default::default(),
|
||||||
|
},
|
||||||
|
None, // Trace path
|
||||||
|
).await.unwrap();
|
||||||
|
|
||||||
|
let surface_caps = surface.get_capabilities(&adapter);
|
||||||
|
// Shader code assumes an sRGB surface texture. Using a different
|
||||||
|
// one will result in all the colors coming out darker. If you want to support non
|
||||||
|
// sRGB surfaces, you'll need to account for that when drawing to the frame.
|
||||||
|
let surface_format = surface_caps.formats.iter()
|
||||||
|
.find(|f| f.is_srgb())
|
||||||
|
.copied()
|
||||||
|
.unwrap_or(surface_caps.formats[0]);
|
||||||
|
|
||||||
|
log::info!("Surface format: {:?}", surface_format);
|
||||||
|
log::info!("Surface present modes: {:?}", surface_caps.present_modes);
|
||||||
|
log::info!("Surface alpha modes: {:?}", surface_caps.alpha_modes);
|
||||||
|
|
||||||
|
let config = wgpu::SurfaceConfiguration {
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||||
|
format: surface_format,
|
||||||
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
// PresentMod::Fifo => VSync (Always supported)
|
||||||
|
present_mode: surface_caps.present_modes[0],
|
||||||
|
alpha_mode: surface_caps.alpha_modes[0],
|
||||||
|
view_formats: vec![],
|
||||||
|
desired_maximum_frame_latency: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
let render_pipeline_layout =
|
||||||
|
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||||
|
label: Some("Render Pipeline Layout"),
|
||||||
|
bind_group_layouts: &[],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||||
|
label: Some("Shader"),
|
||||||
|
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
|
||||||
|
});
|
||||||
|
|
||||||
|
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",
|
||||||
|
buffers: &[Vertex::desc()],
|
||||||
|
compilation_options: Default::default(),
|
||||||
|
},
|
||||||
|
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,
|
||||||
|
})],
|
||||||
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||||
|
}),
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
depth_stencil: None,
|
||||||
|
multisample: wgpu::MultisampleState {
|
||||||
|
count: 1,
|
||||||
|
mask: !0,
|
||||||
|
alpha_to_coverage_enabled: false,
|
||||||
|
},
|
||||||
|
multiview: None,
|
||||||
|
cache: 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,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
let num_indices = INDICES.len() as u32;
|
||||||
|
|
||||||
|
Self {
|
||||||
|
window,
|
||||||
|
surface,
|
||||||
|
device,
|
||||||
|
queue,
|
||||||
|
config,
|
||||||
|
size,
|
||||||
|
render_pipeline,
|
||||||
|
vertex_buffer,
|
||||||
|
index_buffer,
|
||||||
|
num_indices,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window(&self) -> &Window {
|
||||||
|
&self.window
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input(&mut self, event: &WindowEvent) -> bool {
|
||||||
|
// Change color on mouse move
|
||||||
|
match event {
|
||||||
|
WindowEvent::CursorMoved { position, .. } => {
|
||||||
|
/*let size = self.size;
|
||||||
|
let color = wgpu::Color {
|
||||||
|
r: position.x as f64 / size.width as f64,
|
||||||
|
g: position.y as f64 / size.height as f64,
|
||||||
|
b: 0.3,
|
||||||
|
a: 1.0,
|
||||||
|
};
|
||||||
|
|
||||||
|
let output = self.surface.get_current_texture().unwrap();
|
||||||
|
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
|
|
||||||
|
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||||
|
label: Some("Render Encoder"),
|
||||||
|
});
|
||||||
|
|
||||||
|
{
|
||||||
|
let _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(color),
|
||||||
|
store: wgpu::StoreOp::Store,
|
||||||
|
},
|
||||||
|
})],
|
||||||
|
depth_stencil_attachment: None,
|
||||||
|
occlusion_query_set: None,
|
||||||
|
timestamp_writes: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
self.queue.submit(std::iter::once(encoder.finish()));
|
||||||
|
output.present();
|
||||||
|
return true;*/
|
||||||
|
false
|
||||||
|
}
|
||||||
|
WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
physical_key: PhysicalKey::Code(KeyCode::Space),
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {
|
||||||
|
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: &[
|
||||||
|
// 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 {
|
||||||
|
r: 0.1,
|
||||||
|
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(..));
|
||||||
|
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
|
||||||
|
render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// submit will accept anything that implements IntoIter
|
||||||
|
self.queue.submit(std::iter::once(encoder.finish()));
|
||||||
|
output.present();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run() {
|
||||||
|
env_logger::init();
|
||||||
|
let event_loop = EventLoop::new().unwrap();
|
||||||
|
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||||
|
|
||||||
|
let mut state = State::new(&window).await;
|
||||||
|
// Variable used to prevent rendering before the surface is configured
|
||||||
|
let mut surface_configured = false;
|
||||||
|
|
||||||
|
event_loop.run(move |event, control_flow| {
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
ref event,
|
||||||
|
window_id,
|
||||||
|
} if window_id == state.window().id() => if !state.input(event) {
|
||||||
|
match event {
|
||||||
|
WindowEvent::CloseRequested
|
||||||
|
| WindowEvent::KeyboardInput {
|
||||||
|
event:
|
||||||
|
KeyEvent {
|
||||||
|
state: ElementState::Pressed,
|
||||||
|
physical_key: PhysicalKey::Code(KeyCode::Escape),
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} => control_flow.exit(),
|
||||||
|
|
||||||
|
WindowEvent::Resized(physical_size) => {
|
||||||
|
surface_configured = true;
|
||||||
|
state.resize(*physical_size);
|
||||||
|
}
|
||||||
|
|
||||||
|
WindowEvent::RedrawRequested => {
|
||||||
|
// This tells winit that we want another frame after this one
|
||||||
|
state.window().request_redraw();
|
||||||
|
|
||||||
|
if !surface_configured {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
state.update();
|
||||||
|
match state.render() {
|
||||||
|
Ok(_) => {}
|
||||||
|
// Reconfigure the surface if it's lost or outdated
|
||||||
|
Err(
|
||||||
|
wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated,
|
||||||
|
) => state.resize(state.size),
|
||||||
|
// The system is out of memory, we should probably quit
|
||||||
|
Err(wgpu::SurfaceError::OutOfMemory) => {
|
||||||
|
log::error!("OutOfMemory");
|
||||||
|
control_flow.exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// This happens when the a frame takes too long to present
|
||||||
|
Err(wgpu::SurfaceError::Timeout) => {
|
||||||
|
log::warn!("Surface timeout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}).expect("Event loop crashed unexpectedly");
|
||||||
|
}
|
||||||
93
src/main.rs
Normal file
93
src/main.rs
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
/*
|
||||||
|
This program is for simulating orbits of planets around a star.
|
||||||
|
A body can be a star, planet or moon. (Doesn't matter for now)
|
||||||
|
*/
|
||||||
|
|
||||||
|
use orbital_simulation::run;
|
||||||
|
|
||||||
|
// Gravitational constant
|
||||||
|
static G: f64 = 6.67430e-11;
|
||||||
|
|
||||||
|
struct Body {
|
||||||
|
name: String,
|
||||||
|
mass: f64,
|
||||||
|
radius: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calculate_gravitational_force(body1: &Body, body2: &Body, distance: f64) -> f64 {
|
||||||
|
(G * body1.mass * body2.mass) / distance.powi(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calculate_required_velocity(body1: &Body, body2: &Body, distance: f64, force: f64) -> f64 {
|
||||||
|
(force * distance / body2.mass).sqrt()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// simulate a two body system to simplify the problem
|
||||||
|
let sun = Body {
|
||||||
|
name: "Sun".to_string(),
|
||||||
|
mass: 1.989e30,
|
||||||
|
radius: 6.9634e8,
|
||||||
|
};
|
||||||
|
|
||||||
|
let earth = Body {
|
||||||
|
name: "Earth".to_string(),
|
||||||
|
mass: 5.972e24,
|
||||||
|
radius: 6.371e6,
|
||||||
|
};
|
||||||
|
|
||||||
|
/*// Calculate the velocity pulling the earth towards the sun
|
||||||
|
let distance = 1.496e11;
|
||||||
|
let force = calculate_gravitational_force(&sun, &earth, distance);
|
||||||
|
|
||||||
|
let velocity = calculate_required_velocity(&sun, &earth, distance, force);
|
||||||
|
|
||||||
|
println!("The velocity of the earth is: {} m/s", velocity);*/
|
||||||
|
|
||||||
|
// Now we simulate a whole orbit around the sun
|
||||||
|
let distance = 1.496e11;
|
||||||
|
let force = calculate_gravitational_force(&sun, &earth, distance);
|
||||||
|
let velocity = calculate_required_velocity(&sun, &earth, distance, force);
|
||||||
|
|
||||||
|
let mut time = 0.0;
|
||||||
|
let mut position = 0.0;
|
||||||
|
let mut velocity = velocity;
|
||||||
|
let mut acceleration = 0.0;
|
||||||
|
let mut force = force;
|
||||||
|
let mut distance = distance;
|
||||||
|
let mut mass = earth.mass;
|
||||||
|
let mut radius = earth.radius;
|
||||||
|
|
||||||
|
let dt = 1.0;
|
||||||
|
let steps = 1000;
|
||||||
|
|
||||||
|
for _ in 0..steps {
|
||||||
|
// Calculate the acceleration
|
||||||
|
acceleration = force / mass;
|
||||||
|
|
||||||
|
// Calculate the new position
|
||||||
|
position += velocity * dt + 0.5 * acceleration * dt.powi(2);
|
||||||
|
|
||||||
|
// Calculate the new velocity
|
||||||
|
velocity += acceleration * dt;
|
||||||
|
|
||||||
|
// Calculate the new distance
|
||||||
|
distance = position;
|
||||||
|
|
||||||
|
// Calculate the new force
|
||||||
|
force = calculate_gravitational_force(&sun, &earth, distance);
|
||||||
|
|
||||||
|
// Calculate the new mass
|
||||||
|
mass = earth.mass;
|
||||||
|
|
||||||
|
// Calculate the new radius
|
||||||
|
radius = earth.radius;
|
||||||
|
|
||||||
|
// Calculate the new time
|
||||||
|
time += dt;
|
||||||
|
|
||||||
|
println!("Time: {} s, Position: {} m, Velocity: {} m/s, Acceleration: {} m/s^2, Force: {} N, Distance: {} m, Mass: {} kg, Radius: {} m", time, position, velocity, acceleration, force, distance, mass, radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
pollster::block_on(run());
|
||||||
|
}
|
||||||
28
src/shader.wgsl
Normal file
28
src/shader.wgsl
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
// Vertex shader
|
||||||
|
|
||||||
|
struct VertexInput {
|
||||||
|
@location(0) position: vec3<f32>,
|
||||||
|
@location(1) color: vec3<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct VertexOutput {
|
||||||
|
@builtin(position) clip_position: vec4<f32>,
|
||||||
|
@location(0) color: vec3<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_main(
|
||||||
|
model: VertexInput,
|
||||||
|
) -> VertexOutput {
|
||||||
|
var out: VertexOutput;
|
||||||
|
out.color = model.color;
|
||||||
|
out.clip_position = vec4<f32>(model.position, 1.0);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fragment shader
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||||
|
return vec4<f32>(in.color, 1.0);
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user