First attempt at a GPU runner
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) ```
This commit is contained in:
@@ -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
|
||||
@@ -0,0 +1,28 @@
|
||||
use cargo_gpu_install::install::Install;
|
||||
use cargo_gpu_install::spirv_builder::{Capability, ShaderPanicStrategy, SpirvMetadata};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn main() -> anyhow::Result<()> {
|
||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let crate_path = [manifest_dir, "..", "image-binary"]
|
||||
.iter()
|
||||
.copied()
|
||||
.collect::<PathBuf>();
|
||||
|
||||
let install = Install::from_shader_crate(crate_path.clone())
|
||||
.within_build_script()
|
||||
.run()?;
|
||||
let mut builder = install.to_spirv_builder(crate_path, "spirv-unknown-vulkan1.3");
|
||||
builder.build_script.defaults = true;
|
||||
builder.shader_panic_strategy = ShaderPanicStrategy::SilentExit;
|
||||
builder.spirv_metadata = SpirvMetadata::Full;
|
||||
builder.capabilities = vec![Capability::Int8, Capability::Int16, Capability::Int64];
|
||||
|
||||
let compile_result = builder.build()?;
|
||||
let spv_path = compile_result.module.unwrap_single();
|
||||
println!(
|
||||
"cargo::rustc-env=SHADER_SPV_PATH_IMAGE_BINARY={}",
|
||||
spv_path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
Reference in New Issue
Block a user