mirror of
https://github.com/storytold/wgpu.git
synced 2026-12-01 02:24:35 +01:00
* Add the base of the example. May need refining and definitely fact-checking. * Start change to changelog. * Complete changelog change for repeated-compute. * Apply suggestion to fix typos. Co-authored-by: Alphyr <47725341+a1phyr@users.noreply.github.com> * Add storage-texture example which currently works native but needs to be changed to work for wasm. [no ci] * repeated-compute now works on the web. [no ci] * `storage-texture` now works on the web as well as native. * Format because I forgot to do that (ugh). * Add `storage-texture` to changelog. * Add `render-to-texture` example. * Not all the files got git added. Fixed it. * Add `render-to-texture` to changelog. * Make better readme's and add examples to said readme's. * Oops. Put the example updates in the wrong place. * Add `uniform-values` example. * Apply clippy suggestions. * Improved readme's and documentation. * Fmt. Turning into the Joker rn. * Make instructions for examples on the web more clear. \(Fmt and clippy happy\) * hello-workgroups It doesn't work. * Add basic comments and readme to hello-workgroups. * Add hello-synchronization example. Currently doesn't have any tests but those should be added later. * Forgot to check wasm compatibility for hello-synchronization. Fixed it. * Add test for hello-synchronization. * Make my examples downlevel defaults. * Make uniform-values downlevel defaults. (Forgot to do that last commit.) * Fix clippy doc complaints. * Didn't fully fix the docs last commit. Got it here I think. * Fix redundant bullet point in examples/hello-workgroups/README.md. * Trim down the introduction section of examples/hello-workgroups/README.md. * Add technical links section to examples/hello-workgroups/README.md. * Use idiomatic Rust comments, break up big text wall into paragraphs, and fix some spelling errors. * Move output image functions into examples/common and give output_image_wasm some upgrades. * Modify changelog for moving output_image_native and output_image_wasm into wgpu-example. * Fix output_image_wasm. (Formerly did not handle pre-existing output image targets.) * Make a multiline comment be made of single lines to be more ideomatic. * "Fix" more multiline comments. I think this is actually the last of them. * Make the window a consistant, square size that's convenient for viewing. * Make the window on uniform-values not endlessly poll, taking up 100% of the main thread in background at idle. Also, change layout a little and make native use nanos by default for logging. * Make execute in hello-synchronization return a struct of vecs instead of using out parameters. * Didn't realize the naming of wgpu_example::framework so I moved my common example utility functions into wgpu_example::utils. * Add add_web_nothing_to_see_msg function to replace all the instances of adding "open the console" messages across the examples. * Add small documentation to add_web_nothing_to_see_msg and change it to use h1 instead of p. * Add documentation to output_image_native and output_image_wasm in examples/common. * Do better logging for output image functions in wgpu-example::utils. * Remove redundant append_child'ing of the output image element in wgpu-example::utils::output_image_wasm. * Fix error regarding log message for having written the image in wgpu-example::utils::output_image_native. * Fmt. * In examples/README.md, re-arrange the examples in the graph to be in alphabetical order. * Fix changlog item regarding wgpu-example::utils and the output image functions. * Move all the added examples into one changelog item that lists all of them. * Updated table in examples/README.md with new examples. Added new features to the table to accurately represent the examples.\n\nFor the new features, not all old examples may be fully represented. * Fix inaccurate comment in hello-workgroups/src/shader.wgsl. * Update examples/README.md to include basic descriptions of the basic examples as well as hints on how examples build off of each other. * Remove `capture` example. See changelog entry for reasoning. * Fix typo in hello-workgroups/shader.wgsl * Change the method of vertex generation in the shader code of render-to-texture to make it more clear. * Modify/correct message in repeated-compute/main.rs regarding the output staging buffer. * Update message in uniform-values/main.rs about writing the app state struct to the input WGSL buffer. * Add notice in repeated-compute/main.rs about why async channels are necessary (portability to WASM). * Revise comment in uniform-values/main.rs about why we don't cast the struct using POD to be more clear. * Change uniform-values to use encase for translating AppState to WGSL bytes. * Cargo & Clippy: My two best friends. * Add MIT-0 to the list of allowed liscences. * Fix docs for wasm. --------- Co-authored-by: Alphyr <47725341+a1phyr@users.noreply.github.com>
171 lines
6.0 KiB
Rust
171 lines
6.0 KiB
Rust
#[cfg(not(target_arch = "wasm32"))]
|
|
use wgpu_example::utils::output_image_native;
|
|
#[cfg(target_arch = "wasm32")]
|
|
use wgpu_example::utils::output_image_wasm;
|
|
|
|
const TEXTURE_DIMS: (usize, usize) = (512, 512);
|
|
|
|
async fn run(_path: Option<String>) {
|
|
// This will later store the raw pixel value data locally. We'll create it now as
|
|
// a convenient size reference.
|
|
let mut texture_data = Vec::<u8>::with_capacity(TEXTURE_DIMS.0 * TEXTURE_DIMS.1 * 4);
|
|
|
|
let instance = wgpu::Instance::default();
|
|
let adapter = instance
|
|
.request_adapter(&wgpu::RequestAdapterOptions::default())
|
|
.await
|
|
.unwrap();
|
|
let (device, queue) = adapter
|
|
.request_device(
|
|
&wgpu::DeviceDescriptor {
|
|
label: None,
|
|
features: wgpu::Features::empty(),
|
|
limits: wgpu::Limits::downlevel_defaults(),
|
|
},
|
|
None,
|
|
)
|
|
.await
|
|
.unwrap();
|
|
|
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
|
label: None,
|
|
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("shader.wgsl"))),
|
|
});
|
|
|
|
let render_target = device.create_texture(&wgpu::TextureDescriptor {
|
|
label: None,
|
|
size: wgpu::Extent3d {
|
|
width: TEXTURE_DIMS.0 as u32,
|
|
height: TEXTURE_DIMS.1 as u32,
|
|
depth_or_array_layers: 1,
|
|
},
|
|
mip_level_count: 1,
|
|
sample_count: 1,
|
|
dimension: wgpu::TextureDimension::D2,
|
|
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
|
view_formats: &[wgpu::TextureFormat::Rgba8UnormSrgb],
|
|
});
|
|
let output_staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: None,
|
|
size: texture_data.capacity() as u64,
|
|
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
|
mapped_at_creation: false,
|
|
});
|
|
|
|
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
|
label: None,
|
|
layout: None,
|
|
vertex: wgpu::VertexState {
|
|
module: &shader,
|
|
entry_point: "vs_main",
|
|
buffers: &[],
|
|
},
|
|
fragment: Some(wgpu::FragmentState {
|
|
module: &shader,
|
|
entry_point: "fs_main",
|
|
targets: &[Some(wgpu::TextureFormat::Rgba8UnormSrgb.into())],
|
|
}),
|
|
primitive: wgpu::PrimitiveState::default(),
|
|
depth_stencil: None,
|
|
multisample: wgpu::MultisampleState::default(),
|
|
multiview: None,
|
|
});
|
|
|
|
log::info!("Wgpu context set up.");
|
|
|
|
//-----------------------------------------------
|
|
|
|
let texture_view = render_target.create_view(&wgpu::TextureViewDescriptor::default());
|
|
|
|
let mut command_encoder =
|
|
device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
|
|
{
|
|
let mut render_pass = command_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
|
label: None,
|
|
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
|
view: &texture_view,
|
|
resolve_target: None,
|
|
ops: wgpu::Operations {
|
|
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
|
|
store: wgpu::StoreOp::Store,
|
|
},
|
|
})],
|
|
depth_stencil_attachment: None,
|
|
occlusion_query_set: None,
|
|
timestamp_writes: None,
|
|
});
|
|
render_pass.set_pipeline(&pipeline);
|
|
render_pass.draw(0..3, 0..1);
|
|
}
|
|
// The texture now contains our rendered image
|
|
command_encoder.copy_texture_to_buffer(
|
|
wgpu::ImageCopyTexture {
|
|
texture: &render_target,
|
|
mip_level: 0,
|
|
origin: wgpu::Origin3d::ZERO,
|
|
aspect: wgpu::TextureAspect::All,
|
|
},
|
|
wgpu::ImageCopyBuffer {
|
|
buffer: &output_staging_buffer,
|
|
layout: wgpu::ImageDataLayout {
|
|
offset: 0,
|
|
// This needs to be a multiple of 256. Normally we would need to pad
|
|
// it but we here know it will work out anyways.
|
|
bytes_per_row: Some((TEXTURE_DIMS.0 * 4) as u32),
|
|
rows_per_image: Some(TEXTURE_DIMS.1 as u32),
|
|
},
|
|
},
|
|
wgpu::Extent3d {
|
|
width: TEXTURE_DIMS.0 as u32,
|
|
height: TEXTURE_DIMS.1 as u32,
|
|
depth_or_array_layers: 1,
|
|
},
|
|
);
|
|
queue.submit(Some(command_encoder.finish()));
|
|
log::info!("Commands submitted.");
|
|
|
|
//-----------------------------------------------
|
|
|
|
// Time to get our image.
|
|
let buffer_slice = output_staging_buffer.slice(..);
|
|
let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
|
|
buffer_slice.map_async(wgpu::MapMode::Read, move |r| sender.send(r).unwrap());
|
|
device.poll(wgpu::Maintain::Wait);
|
|
receiver.receive().await.unwrap().unwrap();
|
|
log::info!("Output buffer mapped.");
|
|
{
|
|
let view = buffer_slice.get_mapped_range();
|
|
texture_data.extend_from_slice(&view[..]);
|
|
}
|
|
log::info!("Image data copied to local.");
|
|
output_staging_buffer.unmap();
|
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
output_image_native(texture_data.to_vec(), TEXTURE_DIMS, _path.unwrap());
|
|
#[cfg(target_arch = "wasm32")]
|
|
output_image_wasm(texture_data.to_vec(), TEXTURE_DIMS);
|
|
log::info!("Done.");
|
|
}
|
|
|
|
fn main() {
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
{
|
|
env_logger::builder()
|
|
.filter_level(log::LevelFilter::Info)
|
|
.format_timestamp_nanos()
|
|
.init();
|
|
|
|
let path = std::env::args()
|
|
.nth(1)
|
|
.unwrap_or_else(|| "please_don't_git_push_me.png".to_string());
|
|
pollster::block_on(run(Some(path)));
|
|
}
|
|
#[cfg(target_arch = "wasm32")]
|
|
{
|
|
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
|
console_log::init_with_level(log::Level::Info).expect("could not initialize logger");
|
|
wasm_bindgen_futures::spawn_local(run(None));
|
|
}
|
|
}
|