1 Commits

Author SHA1 Message Date
bspeice 53d5ad1422 First attempt at a GPU runner
CI / cargo fmt (push) Failing after 1m5s
CI / cargo test (push) Failing after 2m15s
CI / cargo test (GPU) (push) Successful in 16m58s
Currently failing with an error I don't understand:

```
wgpu error: Validation Error

Caused by:
  In Device::create_shader_module, label = '...\image_binary.spv'

Shader '...\image_binary.spv' parsing error: InvalidTypeWidth(1)
```
2026-07-29 11:12:52 -04:00
15 changed files with 1482 additions and 276 deletions
Generated
+1057 -55
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -1,7 +1,8 @@
[workspace]
members = [
"enkou-shaders",
"enkou-shaders-tests",
"examples/image-runner",
"examples/image-binary",
]
resolver = "3"
@@ -13,6 +14,7 @@ license = "MIT"
repository = ""
[workspace.lints.rust]
missing_docs = { level = "warn" }
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
[workspace.dependencies]
@@ -21,6 +23,7 @@ spirv-std = { git = "https://github.com/Rust-GPU/rust-gpu.git", rev = "67f1ff2"
anyhow = "1.0.102"
bytemuck = { version = "1.25.0", features = ["derive"] }
futures = "0.3.32"
glam = { version = "0.33.1", default-features = false, features = ["bytemuck", "scalar-math"] }
image = { version = "0.25.10", default-features = false, features = ["default-formats"]}
libm = "0.2.16"
@@ -28,3 +31,6 @@ rand = { version = "0.10.1", default-features = false }
rand_xoshiro = "0.8.1"
rspirv = "0.13.0"
tempfile = "3.27.0"
thiserror = "2.0.19"
wgpu = { version = "30.0.0", features = ["spirv"] }
xflags = "0.3.2"
-67
View File
@@ -1,67 +0,0 @@
#[cfg(test)]
mod test {
use rspirv::binary::parse_bytes;
use rspirv::dr::{Module, Operand};
use rspirv::spirv::ExecutionModel;
use std::sync::OnceLock;
static SHADER_MODULE: OnceLock<Module> = OnceLock::new();
fn shader() -> &'static Module {
SHADER_MODULE.get_or_init(|| {
let shader_bytes = include_bytes!(env!("SHADER_SPV_PATH"));
let mut loader = rspirv::dr::Loader::new();
parse_bytes(shader_bytes, &mut loader).expect("Unable to parse shader");
loader.module()
})
}
fn has_entry_point(execution_model: ExecutionModel, name: &str) -> bool {
for entry_point in shader().entry_points.iter() {
let operands: Vec<Operand> = entry_point
.operands
.iter()
.filter(|op| matches!(op, Operand::ExecutionModel(_) | Operand::LiteralString(_)))
.cloned()
.collect();
assert_eq!(operands.len(), 2);
match &operands[0] {
Operand::ExecutionModel(actual) => {
if execution_model != *actual {
continue;
}
}
op => panic!("Unexpected operand; {}", op),
}
match &operands[1] {
Operand::LiteralString(actual) => {
if name != actual {
continue;
}
}
op => panic!("Unexpected operand; {}", op),
}
return true;
}
false
}
#[test]
pub fn has_entry_main_chaos_game() {
assert!(has_entry_point(
ExecutionModel::GLCompute,
"main_chaos_game"
))
}
#[test]
pub fn has_entry_main_camera() {
assert!(has_entry_point(ExecutionModel::GLCompute, "main_camera"))
}
}
-5
View File
@@ -16,8 +16,3 @@ libm.workspace = true
rand.workspace = true
rand_xoshiro.workspace = true
spirv-std.workspace = true
[dev-dependencies]
anyhow.workspace = true
image.workspace = true
tempfile.workspace = true
-95
View File
@@ -1,95 +0,0 @@
use anyhow::{Context, Result};
use enkou_shaders::Coefficients2;
use enkou_shaders::camera::Camera;
use enkou_shaders::camera::entry::main_camera;
use enkou_shaders::chaos_game::entry::main_chaos_game;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use glam::{Affine2, IVec2, UVec2, Vec2, uvec2};
use image::{GrayImage, Luma};
use std::mem;
use std::process::Command;
use tempfile::NamedTempFile;
const ITERATIONS_DISCARD: u32 = 20;
const ITERATIONS: u32 = 50_000;
const IMAGE_DIMENSION: UVec2 = uvec2(600, 600);
pub fn main() -> Result<()> {
let transforms = [
{
// F_0: (x / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
{
// F_1: ((x + 1) / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
{
// F_2: (x / 2, (y + 1) / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
];
let weights = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
let variations = [Variation::IDENTITY];
let mut output_points_ifs = Vec::new();
output_points_ifs.resize(ITERATIONS as usize, Vec2::ZERO);
main_chaos_game(
ITERATIONS_DISCARD,
&[4u8; 32],
&transforms,
&weights,
&variations,
&mut output_points_ifs,
);
// The gasket is defined on the range [0, 1] for both X and Y
let camera = Camera::new(
IMAGE_DIMENSION,
Vec2::ONE * 0.5,
0.0,
Vec2::ZERO,
IMAGE_DIMENSION.as_vec2(),
);
let mut output_points_pixel = Vec::new();
output_points_pixel.resize(ITERATIONS as usize, IVec2::ZERO);
main_camera(&camera, &output_points_ifs, &mut output_points_pixel);
let mut image = GrayImage::new(IMAGE_DIMENSION.x, IMAGE_DIMENSION.y);
let dimensions = image.dimensions();
output_points_pixel
.iter()
.skip_while(|p| {
p.x < 0 || (p.x as u32) > dimensions.0 || p.y < 0 || (p.y as u32) > dimensions.1
})
.map(|p| (p.x as u32, p.y as u32))
.for_each(|(x, y)| image.put_pixel(x, y, Luma([255u8])));
let temp = NamedTempFile::with_suffix(".png").context("Unable to create file for image")?;
image.save(temp.path()).context("Unable to save image")?;
let open_program: &str = cfg_select! {
unix => "xdg-open",
_ => panic!("No available program to open images")
};
Command::new(open_program)
.arg(temp.path())
.spawn()?
.wait()?;
// In case the image viewer forks and gives control back prior to reading the file,
// drop it and don't run the destructor
mem::forget(temp);
Ok(())
}
-36
View File
@@ -106,39 +106,3 @@ impl<'a, R: Rng> Iterator for ChaosGame<'a, R> {
Some(next_point)
}
}
/// Shader entry point for running the chaos game to produce new IFS coordinates
pub mod entry {
use crate::chaos_game::ChaosGame;
use crate::rng::xoshiro256starstar_from_seed;
use crate::transform::Transform;
use crate::variation::Variation;
use glam::Vec2;
use spirv_std::spirv;
/// Given a set of fractal flame parameters, generate new IFS coordinates
/// and store them in the output array.
#[spirv(compute(entry_point_name = "main_chaos_game", threads(1)))]
pub fn main_chaos_game(
#[spirv(spec_constant(id = 1, default = 20))] iteration_discard: u32,
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] rng_seed: &[u8],
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] transforms: &[Transform],
#[spirv(storage_buffer, descriptor_set = 0, binding = 2)] weights: &[f32],
#[spirv(storage_buffer, descriptor_set = 0, binding = 3)] variations: &[Variation],
#[spirv(storage_buffer, descriptor_set = 1, binding = 0)] output: &mut [Vec2],
) {
let mut rng_seed_actual = [0u8; 32];
(0..32).for_each(|i| rng_seed_actual[i] = rng_seed[i]);
let mut rng = xoshiro256starstar_from_seed(rng_seed_actual);
let mut chaos_game = ChaosGame::new(&mut rng, transforms, weights, variations);
for _ in 0..iteration_discard {
chaos_game.next().unwrap();
}
for i in 0..output.len() {
output[i] = chaos_game.next().unwrap();
}
}
}
+5 -4
View File
@@ -1,11 +1,12 @@
//! # Enkou
#![no_std]
#![deny(missing_docs)]
#![allow(clippy::needless_range_loop)] // SPIR-V backend has issues with iteration over items
#![cfg_attr(target_arch = "spirv", no_std)]
// SPIR-V backend is unable to compile iteration over items
#![allow(clippy::needless_range_loop)]
pub mod camera;
pub mod chaos_game;
mod rng;
pub mod rng;
pub mod transform;
pub mod variation;
+4 -1
View File
@@ -1,3 +1,6 @@
//! # RNG
//!
//! Random number generation utilities for shaders
use rand::SeedableRng;
use rand_xoshiro::Xoshiro256StarStar;
@@ -14,7 +17,7 @@ use rand_xoshiro::Xoshiro256StarStar;
/// This function assumes a properly-initialized state array;
/// output may silently degenerate if the initial state is all zeros,
/// so this module is private to the crate.
pub(crate) fn xoshiro256starstar_from_seed(
pub fn xoshiro256starstar_from_seed(
rng_state: <Xoshiro256StarStar as SeedableRng>::Seed,
) -> Xoshiro256StarStar {
let mut rng_state_actual = [0u64; 4];
+1 -1
View File
@@ -68,7 +68,7 @@ impl Variation {
};
/// Create a new variation by providing the variation kind, weight, and parameters.
pub fn new(kind: VariationKind, weight: f32, params: VariationParams) -> Variation {
pub const fn new(kind: VariationKind, weight: f32, params: VariationParams) -> Variation {
Variation {
kind,
weight,
@@ -1,18 +1,16 @@
[package]
name = "enkou-shaders-tests"
publish = false
name = "image-binary"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
enkou-shaders = { path = "../../enkou-shaders" }
glam.workspace = true
spirv-std.workspace = true
wgpu = { workspace = true, optional = true }
[lints]
workspace = true
[dependencies]
rspirv.workspace = true
[build-dependencies]
anyhow.workspace = true
cargo-gpu-install.workspace = true
+82
View File
@@ -0,0 +1,82 @@
//! # Binary image
#![cfg_attr(target_arch = "spirv", no_std)]
use enkou_shaders::camera::Camera;
use enkou_shaders::chaos_game::ChaosGame;
use enkou_shaders::rng::xoshiro256starstar_from_seed;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use glam::{UVec2, UVec4};
use spirv_std::spirv;
#[cfg(feature = "wgpu")]
pub use wgpu::*;
const IMAGE_QUALITY: f32 = 1.0;
const ITERATIONS_FUSE: u32 = 20;
/// Sierpinski Gasket
#[spirv(compute(entry_point_name = "main_image_binary", threads(1)))]
pub fn main_image_binary(
#[spirv(storage_buffer, descriptor_set = 0, binding = 0)] image_dimensions: &UVec2,
#[spirv(storage_buffer, descriptor_set = 0, binding = 1)] transforms: &[Transform],
#[spirv(storage_buffer, descriptor_set = 0, binding = 2)] weights: &[f32],
#[spirv(storage_buffer, descriptor_set = 0, binding = 3)] variations: &[Variation],
#[spirv(storage_buffer, descriptor_set = 0, binding = 4)] camera: &Camera,
#[spirv(storage_buffer, descriptor_set = 0, binding = 5)] image_buffer: &mut [UVec4],
) {
// Initialize RNG and run the chaos game
let mut rng = xoshiro256starstar_from_seed([4; 32]);
let mut chaos_game = ChaosGame::new(&mut rng, transforms, weights, variations);
// Discard the first few iterations
for _ in 0..ITERATIONS_FUSE {
chaos_game.next().unwrap();
}
// Plot the remaining points generated by the chaos game
let iterations = (image_dimensions.as_vec2().element_product() * IMAGE_QUALITY) as u32;
for _ in 0..iterations {
let ifs_point = chaos_game.next().unwrap();
let pixel_point = camera.transform_point_to_image(ifs_point);
if let Some(pixel_point) = pixel_point {
let pixel_index = pixel_point.y * image_dimensions.x + pixel_point.x;
image_buffer[pixel_index as usize] = UVec4::splat(255);
}
}
}
#[cfg(feature = "wgpu")]
pub mod wgpu {
const fn bgle(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
}
pub const BGLE_IMAGE_DIMENSIONS: wgpu::BindGroupLayoutEntry = bgle(0, true);
pub const BGLE_TRANSFORMS: wgpu::BindGroupLayoutEntry = bgle(1, true);
pub const BGLE_WEIGHTS: wgpu::BindGroupLayoutEntry = bgle(2, true);
pub const BGLE_VARIATIONS: wgpu::BindGroupLayoutEntry = bgle(3, true);
pub const BGLE_CAMERA: wgpu::BindGroupLayoutEntry = bgle(4, true);
pub const BGLE_IMAGE_BUFFER: wgpu::BindGroupLayoutEntry = bgle(5, false);
pub const BIND_GROUP_IMAGE_BINARY: wgpu::BindGroupLayoutDescriptor = wgpu::BindGroupLayoutDescriptor {
label: Some("main_image_binary"),
entries: &[
BGLE_IMAGE_DIMENSIONS,
BGLE_TRANSFORMS,
BGLE_WEIGHTS,
BGLE_VARIATIONS,
BGLE_CAMERA,
BGLE_IMAGE_BUFFER,
],
};
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "image-runner"
version.workspace = true
authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
enkou-shaders = { path = "../../enkou-shaders" }
image-binary = { path = "../image-binary", features = ["wgpu"] }
anyhow.workspace = true
bytemuck.workspace = true
futures.workspace = true
glam = { workspace = true, features = ["u8"] }
image.workspace = true
tempfile.workspace = true
wgpu.workspace = true
xflags.workspace = true
[build-dependencies]
anyhow.workspace = true
cargo-gpu-install.workspace = true
[lints]
workspace = true
@@ -4,7 +4,7 @@ use std::path::PathBuf;
pub fn main() -> anyhow::Result<()> {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let crate_path = [manifest_dir, "..", "enkou-shaders"]
let crate_path = [manifest_dir, "..", "image-binary"]
.iter()
.copied()
.collect::<PathBuf>();
@@ -20,6 +20,9 @@ pub fn main() -> anyhow::Result<()> {
let compile_result = builder.build()?;
let spv_path = compile_result.module.unwrap_single();
println!("cargo::rustc-env=SHADER_SPV_PATH={}", spv_path.display());
println!(
"cargo::rustc-env=SHADER_SPV_PATH_IMAGE_BINARY={}",
spv_path.display()
);
Ok(())
}
+210
View File
@@ -0,0 +1,210 @@
use enkou_shaders::Coefficients2;
use enkou_shaders::transform::Transform;
use enkou_shaders::variation::Variation;
use futures::channel::oneshot;
use futures::executor::block_on;
use glam::{uvec2, Affine2, UVec2, UVec4, Vec2};
use image::{Rgba, RgbaImage};
use image_binary::{main_image_binary, BIND_GROUP_IMAGE_BINARY, BGLE_IMAGE_DIMENSIONS, BGLE_TRANSFORMS, BGLE_WEIGHTS, BGLE_CAMERA, BGLE_IMAGE_BUFFER, BGLE_VARIATIONS};
use std::path::Path;
use wgpu::util::DeviceExt;
use enkou_shaders::camera::Camera;
fn transforms() -> [Transform; 3] {
[
{
// F_0: (x / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
{
// F_1: ((x + 1) / 2, y / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.5, 0.0, 0.5, 0.0);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
{
// F_2: (x / 2, (y + 1) / 2)
let coefficients = Affine2::from_coefficients(0.5, 0.0, 0.0, 0.0, 0.5, 0.5);
Transform::new(coefficients, Affine2::IDENTITY, uvec2(0, 1))
},
]
}
fn weights() -> [f32; 3] {
[1.0 / 3.0; 3]
}
fn variations() -> [Variation; 1] {
[Variation::IDENTITY]
}
fn camera(image_dimensions: UVec2) -> Camera {
Camera::new(
image_dimensions,
Vec2::ONE * 0.5,
0.0,
Vec2::ZERO,
Vec2::splat(image_dimensions.min_element() as f32),
)
}
pub(crate) fn main_cpu(image_dimensions: UVec2, output_path: &Path) -> Result<(), anyhow::Error> {
let mut image_buffer = Vec::<UVec4>::new();
image_buffer.resize(image_dimensions.element_product() as usize, UVec4::ZERO);
main_image_binary(
&image_dimensions,
&transforms(),
&weights(),
&variations(),
&camera(image_dimensions),
&mut image_buffer,
);
let mut image = RgbaImage::new(image_dimensions.x, image_dimensions.y);
for (i, color) in image_buffer.into_iter().enumerate() {
let image_x = i as u32 % image_dimensions.x;
let image_y = i as u32 / image_dimensions.x;
image.put_pixel(image_x, image_y, color.as_u8vec4().to_array().into());
}
image.save(output_path)?;
Ok(())
}
const SHADER_MODULE: wgpu::ShaderModuleDescriptor = wgpu::include_spirv!(env!("SHADER_SPV_PATH_IMAGE_BINARY"));
fn bge<'a>(entry: &'a wgpu::BindGroupLayoutEntry, buffer: &'a wgpu::Buffer) -> wgpu::BindGroupEntry<'a> {
wgpu::BindGroupEntry {
binding: entry.binding,
resource: buffer.as_entire_binding(),
}
}
pub(crate) fn main_gpu(device: &wgpu::Device, queue: &wgpu::Queue, image_dimensions: UVec2, output_path: &Path) -> Result<(), anyhow::Error> {
let bind_group_layout = device.create_bind_group_layout(&BIND_GROUP_IMAGE_BINARY);
let image_dimensions_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("image_dimensions"),
contents: bytemuck::bytes_of(&image_dimensions),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let transforms_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("transforms"),
contents: bytemuck::cast_slice(&transforms()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let weights_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("weights"),
contents: bytemuck::cast_slice(&weights()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let variations_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("variations"),
contents: bytemuck::cast_slice(&variations()),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("camera"),
contents: bytemuck::bytes_of(&camera(image_dimensions)),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::STORAGE,
});
let image_buffer_elements = image_dimensions.element_product() as u64;
let image_buffer_size = image_buffer_elements * size_of::<UVec4>() as u64;
let image_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("image_buffer"),
size: image_buffer_size,
usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
});
let image_staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("image_buffer_staging"),
size: image_buffer_size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("main_image_binary"),
layout: &bind_group_layout,
entries: &[
bge(&BGLE_IMAGE_DIMENSIONS, &image_dimensions_buffer),
bge(&BGLE_TRANSFORMS, &transforms_buffer),
bge(&BGLE_WEIGHTS, &weights_buffer),
bge(&BGLE_VARIATIONS, &variations_buffer),
bge(&BGLE_CAMERA, &camera_buffer),
bge(&BGLE_IMAGE_BUFFER, &image_buffer),
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("main_image_binary"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let module = device.create_shader_module(SHADER_MODULE);
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("main_image_binary"),
layout: Some(&layout),
module: &module,
entry_point: Some("main_image_binary"),
compilation_options: Default::default(),
cache: None,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("main_image_binary"),
});
{
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("main_image_binary"),
timestamp_writes: None,
});
compute_pass.set_pipeline(&compute_pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
}
encoder.copy_buffer_to_buffer(&image_buffer, 0, &image_staging, 0, Some(image_buffer_size));
let (sender, receiver) = oneshot::channel();
let image_staging_capturable = image_staging.clone();
encoder.map_buffer_on_submit(&image_buffer, wgpu::MapMode::Read, .., move |result| {
result.expect("unable to map buffer");
let staging_buffer_view = image_staging_capturable.get_mapped_range(..).expect("Unable to map staging buffer");
let mut image = RgbaImage::new(image_dimensions.x, image_dimensions.y);
let image_buffer_elements = bytemuck::cast_slice::<u8, UVec4>(staging_buffer_view.as_ref());
for (i, element) in image_buffer_elements.iter().enumerate() {
let image_x = i as u32 % image_dimensions.x;
let image_y = i as u32 / image_dimensions.x;
let pixel_colors = element.as_u8vec4();
image.put_pixel(image_x, image_y, Rgba(*pixel_colors.as_ref()))
}
sender.send(image).expect("Unable to send image");
});
queue.submit(Some(encoder.finish()));
device.poll(wgpu::PollType::wait_indefinitely())?;
let image = block_on(receiver)?;
image_staging.unmap();
image.save(output_path)?;
Ok(())
}
+77
View File
@@ -0,0 +1,77 @@
use glam::{uvec2};
use std::mem;
use std::process::Command;
use std::path::PathBuf;
use futures::executor::block_on;
use tempfile::NamedTempFile;
mod image_binary;
fn main() -> Result<(), anyhow::Error> {
let instance_future = wgpu::util::new_instance_with_webgpu_detection(wgpu::InstanceDescriptor {
backends: Default::default(),
flags: Default::default(),
memory_budget_thresholds: Default::default(),
backend_options: Default::default(),
display: None,
});
let instance = block_on(instance_future);
let adapter_future = instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: Default::default(),
force_fallback_adapter: false,
compatible_surface: None,
apply_limit_buckets: false,
});
let adapter = block_on(adapter_future)?;
let device_future = adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("image-runner"),
required_features: Default::default(),
required_limits: Default::default(),
experimental_features: Default::default(),
memory_hints: Default::default(),
trace: Default::default(),
});
let (device, queue) = block_on(device_future)?;
let flags = xflags::parse_or_exit! {
/// Image dimensions to output, as `width,height`
optional -d, --dimensions dimensions: String
/// Output pathname to use
optional -o, --output output: PathBuf
/// Image type to generate
required image: String
};
let dimensions = if let Some(dimensions) = flags.dimensions {
let (width_str, height_str) = dimensions.split_once(",").ok_or(anyhow::anyhow!("Invalid format for image dimensions"))?;
uvec2(width_str.parse()?, height_str.parse()?)
} else {
uvec2(1600, 900)
};
let output = if let Some(output) = flags.output { output } else {
let path = NamedTempFile::with_suffix(".png")?;
let pathbuf: PathBuf = path.path().into();
mem::forget(path);
pathbuf
};
match flags.image.as_ref() {
"binary_cpu" => image_binary::main_cpu(dimensions, output.as_ref()),
"binary_gpu" => image_binary::main_gpu(&device, &queue, dimensions, output.as_ref()),
_ => Err(anyhow::anyhow!("Unrecognized image type"))
}?;
let mut command = cfg_select! {
unix => Command::new("xdg-open").arg(temp.path()).spawn(),
windows => Command::new("PowerShell").arg("-Command").arg(format!("start {}", output.display())).spawn(),
_ => Err(anyhow::anyhow!("No available program to open images"))?
}?;
command.wait()?;
Ok(())
}