finished tui
1557
Cargo.lock
generated
19
Cargo.toml
|
@ -6,9 +6,26 @@ edition = "2021"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
image = "0.24"
|
||||
gif = "0.12"
|
||||
tiny-skia = "0.11"
|
||||
futures = "0.3"
|
||||
wgpu = {version="0.18", features=["webgl"]}
|
||||
bytemuck = {version="1.14", features=["derive"]}
|
||||
futures-intrusive = "0.5"
|
||||
pollster = "0.3"
|
||||
clap = { version = "4.4.16", features = ["derive"] }
|
||||
indicatif = "0.17"
|
||||
|
||||
[dev-dependencies]
|
||||
flexi_logger = "0.27"
|
||||
|
||||
[profile.dev]
|
||||
opt-level=1
|
||||
# codegen-units = 1
|
||||
# lto = "fat"
|
||||
|
||||
[profile.release]
|
||||
opt-level=3
|
||||
codegen-units = 1
|
||||
lto = "fat"
|
||||
|
|
BIN
garden.gif
Normal file
After Width: | Height: | Size: 4.7 MiB |
Before Width: | Height: | Size: 8 MiB After Width: | Height: | Size: 8 MiB |
BIN
resources/cube.png
Normal file
After Width: | Height: | Size: 468 KiB |
BIN
resources/garden.jpg
Normal file
After Width: | Height: | Size: 116 KiB |
BIN
resources/riley.png
Normal file
After Width: | Height: | Size: 2 MiB |
BIN
resources/thermo.png
Normal file
After Width: | Height: | Size: 489 KiB |
449
src/draw.rs
Normal file
|
@ -0,0 +1,449 @@
|
|||
use wgpu::{
|
||||
util::{BufferInitDescriptor, DeviceExt},
|
||||
*,
|
||||
};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Vertex {
|
||||
position: [f32; 2],
|
||||
uv: [f32; 2],
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
pub fn desc() -> wgpu::VertexBufferLayout<'static> {
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &[
|
||||
wgpu::VertexAttribute {
|
||||
offset: 0,
|
||||
shader_location: 0,
|
||||
format: wgpu::VertexFormat::Float32x2,
|
||||
},
|
||||
wgpu::VertexAttribute {
|
||||
offset: std::mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
|
||||
shader_location: 1,
|
||||
format: wgpu::VertexFormat::Float32x2,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Circle {
|
||||
pub position: [f32; 2],
|
||||
pub radius: f32,
|
||||
pub color: [u8; 4],
|
||||
}
|
||||
|
||||
impl Circle {
|
||||
fn desc() -> wgpu::VertexBufferLayout<'static> {
|
||||
use std::mem;
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: mem::size_of::<Self>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &[
|
||||
wgpu::VertexAttribute {
|
||||
offset: 0,
|
||||
shader_location: 2,
|
||||
format: wgpu::VertexFormat::Float32x2,
|
||||
},
|
||||
wgpu::VertexAttribute {
|
||||
offset: mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
|
||||
shader_location: 3,
|
||||
format: wgpu::VertexFormat::Float32,
|
||||
},
|
||||
wgpu::VertexAttribute {
|
||||
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
|
||||
shader_location: 4,
|
||||
format: wgpu::VertexFormat::Uint32,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct GpuUniforms {
|
||||
width: f32,
|
||||
height: f32,
|
||||
}
|
||||
|
||||
const SQUARE: &[Vertex] = &[
|
||||
Vertex {
|
||||
position: [-1.0, 1.0],
|
||||
uv: [0.0, 0.0],
|
||||
},
|
||||
Vertex {
|
||||
position: [1.0, 1.0],
|
||||
uv: [1.0, 0.0],
|
||||
},
|
||||
Vertex {
|
||||
position: [1.0, -1.0],
|
||||
uv: [1.0, 1.0],
|
||||
},
|
||||
Vertex {
|
||||
position: [1.0, -1.0],
|
||||
uv: [1.0, 1.0],
|
||||
},
|
||||
Vertex {
|
||||
position: [-1.0, -1.0],
|
||||
uv: [0.0, 1.0],
|
||||
},
|
||||
Vertex {
|
||||
position: [-1.0, 1.0],
|
||||
uv: [0.0, 0.0],
|
||||
},
|
||||
];
|
||||
|
||||
pub struct QuickDraw {
|
||||
device: Device,
|
||||
queue: Queue,
|
||||
width: u32,
|
||||
height: u32,
|
||||
uniform_buffer: Buffer,
|
||||
uniform_bind_group: BindGroup,
|
||||
texture_desc: TextureDescriptor<'static>,
|
||||
texture: Texture,
|
||||
texture_view: TextureView,
|
||||
instance_count: u64,
|
||||
instance_buffer: Buffer,
|
||||
output_buffer: Buffer,
|
||||
vertex_buffer: Buffer,
|
||||
pipeline: RenderPipeline,
|
||||
}
|
||||
|
||||
impl QuickDraw {
|
||||
pub async fn new(width: u32, height: u32, max_circles: u64) -> Self {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::all(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let adapter = match instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
compatible_surface: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
Some(a) => a,
|
||||
None => {
|
||||
eprintln!("Could not find WGPU adapter");
|
||||
std::process::exit(1);
|
||||
},
|
||||
};
|
||||
let (device, queue) =
|
||||
match adapter.request_device(&Default::default(), None).await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
eprintln!("Could not find WGPU device:");
|
||||
eprintln!("{}", e);
|
||||
std::process::exit(1);
|
||||
},
|
||||
};
|
||||
|
||||
let uniforms = GpuUniforms {
|
||||
width: width as f32,
|
||||
height: height as f32,
|
||||
};
|
||||
let uniform_buffer = device.create_buffer_init(&BufferInitDescriptor {
|
||||
label: Some("Uniform Buffer"),
|
||||
contents: bytemuck::cast_slice(&[uniforms]),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
let uniform_layout =
|
||||
device.create_bind_group_layout(&BindGroupLayoutDescriptor {
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
label: Some("Uniform Bind Group Layout"),
|
||||
});
|
||||
|
||||
let uniform_bind_group =
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Uniform Bind Group"),
|
||||
layout: &uniform_layout,
|
||||
entries: &[BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: uniform_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
let texture_desc = wgpu::TextureDescriptor {
|
||||
size: wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
view_formats: &[wgpu::TextureFormat::Rgba8Unorm],
|
||||
usage: wgpu::TextureUsages::COPY_SRC
|
||||
| wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
label: None,
|
||||
};
|
||||
let texture = device.create_texture(&texture_desc);
|
||||
let texture_view = texture.create_view(&Default::default());
|
||||
|
||||
let instance_buffer = device.create_buffer(&BufferDescriptor {
|
||||
label: Some("Instance Buffer"),
|
||||
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size: max_circles * std::mem::size_of::<Circle>() as u64,
|
||||
});
|
||||
|
||||
let u32_size = std::mem::size_of::<u32>() as u32;
|
||||
let output_buffer_size = (u32_size * width * height) as wgpu::BufferAddress;
|
||||
let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
size: output_buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST
|
||||
// this tells wpgu that we want to read this buffer from the cpu
|
||||
| wgpu::BufferUsages::MAP_READ,
|
||||
label: None,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
let vertex_buffer = device.create_buffer_init(&BufferInitDescriptor {
|
||||
label: Some("Vertex Buffer"),
|
||||
usage: BufferUsages::VERTEX,
|
||||
contents: bytemuck::cast_slice(SQUARE),
|
||||
});
|
||||
// Shaders
|
||||
let shader = std::borrow::Cow::Borrowed(include_str!("shader.wgsl"));
|
||||
let vert = device.create_shader_module(ShaderModuleDescriptor {
|
||||
label: Some("Vertex Shader"),
|
||||
source: ShaderSource::Wgsl(shader.clone()),
|
||||
});
|
||||
let frag = device.create_shader_module(ShaderModuleDescriptor {
|
||||
label: Some("Vertex Shader"),
|
||||
source: ShaderSource::Wgsl(shader),
|
||||
});
|
||||
// Pipeline
|
||||
let render_pipeline_layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[&uniform_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
let pipeline =
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
multiview: None,
|
||||
label: Some("Render Pipeline"),
|
||||
layout: Some(&render_pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &vert,
|
||||
entry_point: "vs_main",
|
||||
buffers: &[Vertex::desc(), Circle::desc()],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &frag,
|
||||
entry_point: "fs_main",
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: texture_desc.format,
|
||||
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: None,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
// Setting this to anything other than Fill requires
|
||||
// Features::NON_FILL_POLYGON_MODE
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
});
|
||||
|
||||
Self {
|
||||
device,
|
||||
queue,
|
||||
width,
|
||||
height,
|
||||
uniform_buffer,
|
||||
uniform_bind_group,
|
||||
texture_desc,
|
||||
texture,
|
||||
texture_view,
|
||||
instance_count: 0,
|
||||
instance_buffer,
|
||||
output_buffer,
|
||||
vertex_buffer,
|
||||
pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn resize(&mut self, width: u32, height: u32, max_circles: usize) {
|
||||
let texture_desc = wgpu::TextureDescriptor {
|
||||
size: wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
view_formats: &[wgpu::TextureFormat::Rgba8Unorm],
|
||||
usage: wgpu::TextureUsages::COPY_SRC
|
||||
| wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
label: None,
|
||||
};
|
||||
let texture = self.device.create_texture(&texture_desc);
|
||||
let texture_view = texture.create_view(&Default::default());
|
||||
|
||||
let u32_size = std::mem::size_of::<u32>() as u32;
|
||||
let output_buffer_size = (u32_size * width * height) as wgpu::BufferAddress;
|
||||
let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
size: output_buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST
|
||||
// this tells wpgu that we want to read this buffer from the cpu
|
||||
| wgpu::BufferUsages::MAP_READ,
|
||||
label: None,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
self.allocate(max_circles).await;
|
||||
self.width = width;
|
||||
self.height = height;
|
||||
self.texture_desc = texture_desc;
|
||||
self.texture = texture;
|
||||
self.texture_view = texture_view;
|
||||
self.output_buffer = output_buffer;
|
||||
}
|
||||
|
||||
async fn draw_call(&mut self) {
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||
let render_pass_desc = wgpu::RenderPassDescriptor {
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
label: Some("Render Pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &self.texture_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: 0.0,
|
||||
g: 0.0,
|
||||
b: 0.0,
|
||||
a: 1.0,
|
||||
}),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
};
|
||||
let mut render_pass = encoder.begin_render_pass(&render_pass_desc);
|
||||
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
|
||||
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
||||
render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
|
||||
render_pass.draw(0..6, 0..self.instance_count as u32);
|
||||
drop(render_pass);
|
||||
|
||||
let u32_size = std::mem::size_of::<u32>() as u32;
|
||||
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::ImageCopyTexture {
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
texture: &self.texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
},
|
||||
wgpu::ImageCopyBuffer {
|
||||
buffer: &self.output_buffer,
|
||||
layout: wgpu::ImageDataLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(u32_size * self.width),
|
||||
rows_per_image: Some(self.height),
|
||||
},
|
||||
},
|
||||
self.texture_desc.size,
|
||||
);
|
||||
self.output_buffer.unmap();
|
||||
self.queue.submit(Some(encoder.finish()));
|
||||
}
|
||||
|
||||
async fn read_output_buffer(&self) -> BufferView {
|
||||
let buffer_slice = self.output_buffer.slice(..);
|
||||
|
||||
// NOTE: We have to create the mapping THEN device.poll()
|
||||
// before await the future. Otherwise the application
|
||||
// will freeze.
|
||||
let (tx, rx) = futures_intrusive::channel::shared::oneshot_channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
tx.send(result).unwrap();
|
||||
});
|
||||
// buffer_slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
self.device.poll(wgpu::Maintain::Wait);
|
||||
rx.receive().await.unwrap().unwrap();
|
||||
buffer_slice.get_mapped_range()
|
||||
}
|
||||
|
||||
// Allocates space for *size* circles, also clears the
|
||||
// circles buffer
|
||||
pub async fn allocate(&mut self, size: usize) {
|
||||
let size = (size * std::mem::size_of::<Circle>()) as u64;
|
||||
if size >= self.instance_buffer.size() {
|
||||
self.instance_buffer = self.device.create_buffer(&BufferDescriptor {
|
||||
label: Some("Instance Buffer"),
|
||||
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
size,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_circles(&mut self, circles: &[Circle]) {
|
||||
self.allocate(circles.len()).await;
|
||||
self.queue.write_buffer(
|
||||
&self.instance_buffer,
|
||||
0,
|
||||
&bytemuck::cast_slice(&circles),
|
||||
);
|
||||
// self.queue.submit([]);
|
||||
self.instance_count = circles.len() as u64;
|
||||
}
|
||||
|
||||
async fn bytes(&self) -> Vec<u8> {
|
||||
let mut buffer = vec![0; self.output_buffer.size() as usize];
|
||||
{
|
||||
let data = self.read_output_buffer().await;
|
||||
|
||||
for (i, d) in data.iter().enumerate() {
|
||||
buffer[i] = *d;
|
||||
}
|
||||
}
|
||||
buffer
|
||||
}
|
||||
|
||||
pub async fn draw_circles(&mut self, circles: &[Circle]) -> Vec<u8> {
|
||||
self.write_circles(circles).await;
|
||||
self.draw_call().await;
|
||||
self.bytes().await
|
||||
}
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
use tiny_skia::*;
|
||||
|
||||
use crate::sim::Circle;
|
||||
pub fn clear(pixmap: &mut Pixmap) {
|
||||
let mut black = Paint::default();
|
||||
black.set_color_rgba8(0, 0, 0, 255);
|
||||
pixmap.fill_rect(
|
||||
Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
|
||||
.unwrap(),
|
||||
&black,
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn draw_circle(pixmap: &mut Pixmap, circle: &Circle) {
|
||||
let x = circle.position.x;
|
||||
let y = circle.position.y;
|
||||
let radius = circle.radius;
|
||||
let r = circle.color.0;
|
||||
let g = circle.color.1;
|
||||
let b = circle.color.2;
|
||||
let mut paint = Paint::default();
|
||||
paint.set_color_rgba8(r, g, b, 255);
|
||||
let mut brush = PathBuilder::new();
|
||||
brush.push_circle(x, y, radius);
|
||||
brush.move_to(x, y);
|
||||
brush.close();
|
||||
|
||||
pixmap.fill_path(
|
||||
&brush.finish().unwrap(),
|
||||
&paint,
|
||||
FillRule::Winding,
|
||||
tiny_skia::Transform::identity(),
|
||||
None,
|
||||
)
|
||||
}
|
58
src/lib.rs
|
@ -1,58 +0,0 @@
|
|||
use std::io::Write;
|
||||
|
||||
use image::{ImageBuffer, Rgb};
|
||||
|
||||
mod drawing;
|
||||
mod helper;
|
||||
mod sim;
|
||||
|
||||
fn write_frame<W: Write>(
|
||||
sim: &sim::Simulation,
|
||||
encoder: &mut gif::Encoder<&mut W>,
|
||||
) {
|
||||
let mut pixbuf = tiny_skia::Pixmap::new(500, 500).unwrap();
|
||||
drawing::clear(&mut pixbuf);
|
||||
for index in 0..sim.circles.len() {
|
||||
let circle = &sim.circles[index];
|
||||
drawing::draw_circle(&mut pixbuf, circle);
|
||||
}
|
||||
let mut frame = gif::Frame::from_rgba(500, 500, pixbuf.data_mut());
|
||||
frame.delay = 1;
|
||||
encoder.write_frame(&frame).unwrap();
|
||||
}
|
||||
|
||||
async fn write_frame_async<W: Write>(
|
||||
sim: &sim::Simulation,
|
||||
encoder: &mut gif::Encoder<&mut W>,
|
||||
) {
|
||||
write_frame(sim, encoder);
|
||||
}
|
||||
|
||||
pub fn generate(image: ImageBuffer<Rgb<u8>, Vec<u8>>) -> Vec<u8> {
|
||||
let (mut sim, it) = sim::Simulation::simulate_image(500.0, 500.0, 8.0, image);
|
||||
|
||||
let mut buffer = Vec::<u8>::new();
|
||||
let mut encoder = gif::Encoder::new(&mut buffer, 500, 500, &[]).unwrap();
|
||||
// encoder.set_repeat(gif::Repeat::Infinite).unwrap();
|
||||
while sim.clock < it {
|
||||
write_frame(&sim, &mut encoder);
|
||||
(0..5).for_each(|_| sim.step());
|
||||
}
|
||||
drop(encoder);
|
||||
buffer
|
||||
}
|
||||
|
||||
pub async fn generate_async(image: ImageBuffer<Rgb<u8>, Vec<u8>>) -> Vec<u8> {
|
||||
let (mut sim, it) =
|
||||
sim::Simulation::simulate_image_async(500.0, 500.0, 8.0, image).await;
|
||||
|
||||
let mut buffer = Vec::<u8>::new();
|
||||
let mut encoder = gif::Encoder::new(&mut buffer, 500, 500, &[]).unwrap();
|
||||
// encoder.set_repeat(gif::Repeat::Infinite).unwrap();
|
||||
while sim.clock < it {
|
||||
write_frame_async(&sim, &mut encoder).await;
|
||||
(0..5).for_each(|_| sim.step());
|
||||
}
|
||||
drop(encoder);
|
||||
buffer
|
||||
}
|
176
src/main.rs
Normal file
|
@ -0,0 +1,176 @@
|
|||
#![feature(future_join)]
|
||||
use std::{cell::RefCell, future::join, io::Write, path::Path, sync::Arc};
|
||||
|
||||
use draw::QuickDraw;
|
||||
use gif::Frame;
|
||||
use image::{ImageBuffer, Rgb};
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use log::debug;
|
||||
|
||||
pub mod draw;
|
||||
pub mod helper;
|
||||
pub mod sim;
|
||||
pub mod tests;
|
||||
|
||||
pub fn make_progress(msg: &'static str, max: u64) -> ProgressBar {
|
||||
let progress = ProgressBar::new(max);
|
||||
progress.set_style(ProgressStyle::with_template("{msg} :: {bar}").unwrap());
|
||||
progress.set_message(msg);
|
||||
progress
|
||||
}
|
||||
|
||||
const WIDTH: f32 = 512.0;
|
||||
const HEIGHT: f32 = 512.0;
|
||||
|
||||
pub async fn preprocess(
|
||||
image: ImageBuffer<Rgb<u8>, Vec<u8>>,
|
||||
radius: f32,
|
||||
) -> (sim::Simulation, usize, usize) {
|
||||
let (sim, it, max_circles) =
|
||||
sim::Simulation::simulate_image(WIDTH, HEIGHT, radius, image).await;
|
||||
(sim, it, max_circles)
|
||||
}
|
||||
|
||||
pub async fn simulate(
|
||||
draw: &mut QuickDraw,
|
||||
mut sim: Simulation,
|
||||
it: usize,
|
||||
step: usize,
|
||||
max_circles: usize,
|
||||
) -> Vec<Frame<'static>> {
|
||||
draw.resize(WIDTH as u32, HEIGHT as u32, max_circles).await;
|
||||
let mut frames = vec![];
|
||||
let progress =
|
||||
make_progress("Simulating ", ((it - sim.clock) / sim.substeps) as u64);
|
||||
while sim.clock < it {
|
||||
let circles = &sim
|
||||
.circles
|
||||
.iter()
|
||||
.map(|c| draw::Circle {
|
||||
position: [c.position.x, c.position.y],
|
||||
radius: c.radius,
|
||||
color: [c.color.0, c.color.1, c.color.2, 255],
|
||||
})
|
||||
.collect::<Vec<draw::Circle>>();
|
||||
let bytes_future = draw.draw_circles(circles);
|
||||
let steps = sim.steps(step);
|
||||
let mut bytes = join!(bytes_future, steps).await.0;
|
||||
let frame = gif::Frame::from_rgba(WIDTH as u16, HEIGHT as u16, &mut bytes);
|
||||
frames.push(frame);
|
||||
progress.inc(step as u64);
|
||||
}
|
||||
progress.finish();
|
||||
frames
|
||||
}
|
||||
|
||||
pub async fn encode(frames: Vec<Frame<'static>>, repeat: bool) -> Vec<u8> {
|
||||
let mut buffer = Vec::<u8>::new();
|
||||
let mut encoder =
|
||||
gif::Encoder::new(&mut buffer, WIDTH as u16, HEIGHT as u16, &[]).unwrap();
|
||||
let progress = make_progress("Encoding ", frames.len() as u64);
|
||||
for mut frame in frames {
|
||||
frame.delay = 1;
|
||||
encoder.write_frame(&frame).unwrap();
|
||||
progress.inc(1);
|
||||
}
|
||||
progress.finish();
|
||||
if repeat {
|
||||
encoder.set_repeat(gif::Repeat::Infinite).unwrap();
|
||||
}
|
||||
drop(encoder);
|
||||
buffer
|
||||
}
|
||||
|
||||
use clap::Parser;
|
||||
use sim::Simulation;
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
struct Args {
|
||||
/// Input file to process. All common image types are
|
||||
/// supported, see the `image` crate docs for specific
|
||||
/// compatibility
|
||||
#[arg(short = 'i', value_hint = clap::ValueHint::DirPath)]
|
||||
input: std::path::PathBuf,
|
||||
|
||||
/// Output file path ('./output.gif' by default)
|
||||
#[arg(short = 'o', value_hint = clap::ValueHint::DirPath)]
|
||||
output: Option<std::path::PathBuf>,
|
||||
|
||||
/// How many physics-steps between frames. Affects the
|
||||
/// speed and length of the animation
|
||||
#[arg(short = 's')]
|
||||
step: Option<u32>,
|
||||
|
||||
/// Radius of the circle, smaller means more detailed but
|
||||
/// slower to compute (8.0 by default, must be between
|
||||
/// 1.0 and 50.0 inclusive)
|
||||
#[arg(short = 'r')]
|
||||
radius: Option<f32>,
|
||||
|
||||
/// Loop the GIF
|
||||
#[arg(short = 'l', long = "loop")]
|
||||
looping: bool,
|
||||
}
|
||||
|
||||
fn open_image<P: AsRef<Path>>(path: P) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
|
||||
let image = match image::io::Reader::open(path) {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
eprintln!("Error opening file for processing: ");
|
||||
eprintln!("{}", e);
|
||||
std::process::exit(1);
|
||||
},
|
||||
};
|
||||
|
||||
let decoded = match image.decode() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("Error processing file: ");
|
||||
eprintln!("{}", e);
|
||||
std::process::exit(1);
|
||||
},
|
||||
};
|
||||
decoded.to_rgb8()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
let output = args.output.unwrap_or("output.gif".into());
|
||||
let step = args.step.unwrap_or(20) as usize;
|
||||
if step == 0 {
|
||||
eprintln!("Physics step cannot be 0");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let radius = args.radius.unwrap_or(8.0);
|
||||
if radius < 1.0 || radius > 50.0 {
|
||||
eprintln!("Invalid radius {}", radius);
|
||||
eprintln!("Must be between 1.0 and 50.0 inclusive");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let image = open_image(args.input);
|
||||
let (sim, it, max) = pollster::block_on(preprocess(image, radius));
|
||||
let mut draw = pollster::block_on(QuickDraw::new(512, 512, 1000));
|
||||
let frames = pollster::block_on(simulate(&mut draw, sim, it, step, max));
|
||||
let gif = pollster::block_on(encode(frames, args.looping));
|
||||
let mut file = match std::fs::File::create(output.clone()) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("Error opening file for writing:");
|
||||
eprintln!("{}", e);
|
||||
std::process::exit(1);
|
||||
},
|
||||
};
|
||||
|
||||
match file.write(&gif) {
|
||||
Ok(_) => {
|
||||
println!("Successfully created file at '{}'", output.display());
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("Error writing output file: ");
|
||||
eprintln!("{}", e);
|
||||
std::process::exit(1);
|
||||
},
|
||||
};
|
||||
}
|
58
src/shader.wgsl
Normal file
|
@ -0,0 +1,58 @@
|
|||
struct Uniforms {
|
||||
width: f32, height: f32,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
|
||||
|
||||
struct VertexInput {
|
||||
@location(0) position: vec2<f32>,
|
||||
@location(1) uv: vec2<f32>,
|
||||
@location(2) offset: vec2<f32>,
|
||||
@location(3) radius: f32,
|
||||
@location(4) color: u32,
|
||||
}
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@location(1) color: vec4<f32>,
|
||||
}
|
||||
|
||||
fn get_color(input: u32) -> vec4<f32> {
|
||||
let r = f32(input & 255u) / 255.0;
|
||||
let g = f32((input & (255u << 8u)) >> 8u) / 255.0;
|
||||
let b = f32((input & (255u << 16u)) >> 16u) / 255.0;
|
||||
let a = f32((input & (255u << 24u)) >> 24u) / 255.0;
|
||||
return vec4<f32>(r, g, b, a);
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(
|
||||
model: VertexInput
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
var x = (model.position.x * model.radius) - uniforms.width / 2.0;
|
||||
x += model.offset.x;
|
||||
var y = (model.position.y * model.radius) - uniforms.height / 2.0;
|
||||
y += model.offset.y;
|
||||
var norm_x = x / (uniforms.width / 2.0);
|
||||
var norm_y = -y / (uniforms.height / 2.0);
|
||||
out.clip_position = vec4<f32>(norm_x, norm_y, 0.0, 1.0);
|
||||
out.uv = model.uv;
|
||||
out.color = get_color(model.color);
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
var x = in.uv.x - 0.5;
|
||||
var y = in.uv.y - 0.5;
|
||||
var d = sqrt(x * x + y * y) * 2.0;
|
||||
if d > 1.1 {
|
||||
discard;
|
||||
} else if d > 1.0 {
|
||||
return vec4<f32>(in.color.xyz, 1.1 - d);
|
||||
} else {
|
||||
return in.color;
|
||||
}
|
||||
}
|
109
src/sim.rs
|
@ -1,6 +1,6 @@
|
|||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use crate::helper::*;
|
||||
use crate::{helper::*, make_progress};
|
||||
use image::{ImageBuffer, Rgb};
|
||||
|
||||
pub struct Circle {
|
||||
|
@ -16,7 +16,7 @@ pub struct Simulation {
|
|||
pub colors: Vec<Color>,
|
||||
pub max_circles: usize,
|
||||
pub clock: usize,
|
||||
substeps: usize,
|
||||
pub substeps: usize,
|
||||
rand_seed: usize,
|
||||
timescale: f32,
|
||||
circle_radius: f32,
|
||||
|
@ -27,6 +27,8 @@ pub struct Simulation {
|
|||
}
|
||||
|
||||
impl Simulation {
|
||||
pub const POST_PROCESS: usize = 120;
|
||||
|
||||
pub fn new(
|
||||
width: f32,
|
||||
height: f32,
|
||||
|
@ -35,12 +37,12 @@ impl Simulation {
|
|||
) -> Self {
|
||||
let area = width * height;
|
||||
let circle_area = circle_radius.powi(2) * std::f32::consts::PI;
|
||||
let approx_max = ((area / circle_area).round() * 1.0) as usize;
|
||||
let approx_max = ((area / circle_area).round() * 0.9) as usize;
|
||||
Self {
|
||||
circles: Vec::with_capacity(approx_max),
|
||||
max_circles: approx_max,
|
||||
timescale: 1.0 / 60.0,
|
||||
substeps: 4,
|
||||
substeps: 8,
|
||||
colors: vec![Color(255, 255, 255); approx_max],
|
||||
clock: rand_seed,
|
||||
rand_seed,
|
||||
|
@ -48,12 +50,15 @@ impl Simulation {
|
|||
radius_variance: circle_radius * 0.1,
|
||||
area_size: (width, height),
|
||||
gravity: height,
|
||||
response_mod: 0.4,
|
||||
response_mod: 0.9,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn assign_colors_from_image(&mut self, img: ImageBuffer<Rgb<u8>, Vec<u8>>) {
|
||||
async fn assign_colors_from_image(
|
||||
&mut self,
|
||||
img: ImageBuffer<Rgb<u8>, Vec<u8>>,
|
||||
) {
|
||||
let (width, height) = (img.width() as f32 - 1.0, img.height() as f32 - 1.0);
|
||||
for (pos, index) in self.circles.iter().map(|c| (c.position, c.index)) {
|
||||
let img_x =
|
||||
|
@ -68,53 +73,37 @@ impl Simulation {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
pub fn simulate_image(
|
||||
pub async fn simulate_image(
|
||||
width: f32,
|
||||
height: f32,
|
||||
circle_radius: f32,
|
||||
img: ImageBuffer<Rgb<u8>, Vec<u8>>,
|
||||
) -> (Self, usize) {
|
||||
) -> (Self, usize, usize) {
|
||||
let image_hash = ({
|
||||
let mut s = std::hash::DefaultHasher::new();
|
||||
img.hash(&mut s);
|
||||
s.finish()
|
||||
} % 1204) as usize;
|
||||
let mut sim = Simulation::new(width, height, circle_radius, image_hash);
|
||||
let progress = make_progress(
|
||||
"Preprocessing",
|
||||
(sim.max_circles + Self::POST_PROCESS) as u64,
|
||||
);
|
||||
while sim.circles() < sim.max_circles {
|
||||
sim.step();
|
||||
sim.step().await;
|
||||
progress.inc(2);
|
||||
}
|
||||
(0..120).for_each(|_| sim.step());
|
||||
for _ in 0..Self::POST_PROCESS {
|
||||
sim.step().await;
|
||||
progress.inc(1);
|
||||
}
|
||||
progress.finish();
|
||||
let total_iterations = sim.clock;
|
||||
sim.assign_colors_from_image(img);
|
||||
let max_circles = sim.circles.len();
|
||||
sim.assign_colors_from_image(img).await;
|
||||
sim.circles.clear();
|
||||
sim.clock = sim.rand_seed;
|
||||
(sim, total_iterations)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn simulate_image_async(
|
||||
width: f32,
|
||||
height: f32,
|
||||
circle_radius: f32,
|
||||
img: ImageBuffer<Rgb<u8>, Vec<u8>>,
|
||||
) -> (Self, usize) {
|
||||
let image_hash = ({
|
||||
let mut s = std::hash::DefaultHasher::new();
|
||||
img.hash(&mut s);
|
||||
s.finish()
|
||||
} % 1204) as usize;
|
||||
let mut sim = Simulation::new(width, height, circle_radius, image_hash);
|
||||
while sim.circles() < sim.max_circles {
|
||||
sim.step_async().await;
|
||||
}
|
||||
for _ in 0..120 {
|
||||
sim.step_async().await
|
||||
}
|
||||
let total_iterations = sim.clock;
|
||||
sim.assign_colors_from_image(img);
|
||||
sim.circles.clear();
|
||||
sim.clock = sim.rand_seed;
|
||||
(sim, total_iterations)
|
||||
(sim, total_iterations, max_circles)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
@ -155,7 +144,7 @@ impl Simulation {
|
|||
|
||||
// Insertion sort
|
||||
#[inline]
|
||||
fn sort(&mut self) {
|
||||
async fn sort(&mut self) {
|
||||
if self.circles.len() == 1 {
|
||||
return;
|
||||
}
|
||||
|
@ -170,7 +159,7 @@ impl Simulation {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn integrate(&mut self) {
|
||||
async fn integrate(&mut self) {
|
||||
let delta = self.timescale * (1.0 / self.substeps as f32);
|
||||
let gravity = Vector2::new(0.0, self.gravity) * delta.powi(2);
|
||||
self.circles.iter_mut().for_each(|circle| {
|
||||
|
@ -181,7 +170,7 @@ impl Simulation {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn collide(&mut self) {
|
||||
async fn collide(&mut self) {
|
||||
for i in 0..self.circles.len() {
|
||||
// Apply gravity
|
||||
for j in i..self.circles.len() {
|
||||
|
@ -229,7 +218,7 @@ impl Simulation {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
pub fn step(&mut self) {
|
||||
pub async fn step(&mut self) {
|
||||
if self.circles.len() < self.max_circles {
|
||||
self.launch();
|
||||
}
|
||||
|
@ -237,42 +226,22 @@ impl Simulation {
|
|||
self.launch2();
|
||||
}
|
||||
|
||||
(0..self.substeps).for_each(|_| {
|
||||
for _ in 0..self.substeps {
|
||||
self.constrain_rect();
|
||||
self.sort();
|
||||
self.collide();
|
||||
self.integrate();
|
||||
self.sort().await;
|
||||
self.collide().await;
|
||||
self.integrate().await;
|
||||
self.clock += 1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub async fn step_async(&mut self) {
|
||||
if self.circles.len() < self.max_circles {
|
||||
self.launch();
|
||||
pub async fn steps(&mut self, steps: usize) {
|
||||
for _ in 0..steps {
|
||||
self.step().await;
|
||||
}
|
||||
if self.circles.len() < self.max_circles {
|
||||
self.launch2();
|
||||
}
|
||||
|
||||
(0..self.substeps).for_each(|_| {
|
||||
self.constrain_rect();
|
||||
self.sort();
|
||||
self.collide();
|
||||
self.integrate();
|
||||
self.clock += 1;
|
||||
});
|
||||
}
|
||||
|
||||
// #[inline]
|
||||
// pub fn draw(&self, d: &mut RaylibDrawHandle) {
|
||||
// self
|
||||
// .circles
|
||||
// .iter()
|
||||
// .map(|c| (c.position, c.radius, c.color))
|
||||
// .for_each(|(pos, radius, color)| d.draw_circle_v(pos,
|
||||
// radius, color)); }
|
||||
|
||||
pub fn circles(&self) -> usize {
|
||||
self.circles.len()
|
||||
}
|
||||
|
|
19
src/tests.rs
Normal file
|
@ -0,0 +1,19 @@
|
|||
#[cfg(test)]
|
||||
#[test]
|
||||
fn bench_async() {
|
||||
use std::io::Write;
|
||||
flexi_logger::Logger::try_with_str("debug").unwrap();
|
||||
|
||||
let image = image::io::Reader::open(
|
||||
"resources/mona
|
||||
lisa.png",
|
||||
)
|
||||
.unwrap()
|
||||
.decode()
|
||||
.unwrap()
|
||||
.to_rgb8();
|
||||
// let gif = pollster::block_on(crate::generate_async(image, None));
|
||||
// let mut file =
|
||||
// std::fs::File::create("test.gif").unwrap();
|
||||
// file.write(&gif).unwrap();
|
||||
}
|