mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-19 22:11:01 +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>
159 lines
6.4 KiB
Rust
159 lines
6.4 KiB
Rust
#[cfg(not(target_arch = "wasm32"))]
|
|
use std::io::Write;
|
|
#[cfg(target_arch = "wasm32")]
|
|
use wasm_bindgen::prelude::*;
|
|
|
|
/// Replaces the site body with a message telling the user to open the console and use that.
|
|
#[cfg(target_arch = "wasm32")]
|
|
pub fn add_web_nothing_to_see_msg() {
|
|
web_sys::window()
|
|
.and_then(|window| window.document())
|
|
.and_then(|document| document.body())
|
|
.expect("Could not get document / body.")
|
|
.set_inner_html("<h1>Nothing to see here! Open the console!</h1>");
|
|
}
|
|
|
|
/// Outputs a vector of RGBA bytes as a png image with the given dimensions on the given path.
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
pub fn output_image_native(image_data: Vec<u8>, texture_dims: (usize, usize), path: String) {
|
|
let mut png_data = Vec::<u8>::with_capacity(image_data.len());
|
|
let mut encoder = png::Encoder::new(
|
|
std::io::Cursor::new(&mut png_data),
|
|
texture_dims.0 as u32,
|
|
texture_dims.1 as u32,
|
|
);
|
|
encoder.set_color(png::ColorType::Rgba);
|
|
let mut png_writer = encoder.write_header().unwrap();
|
|
png_writer.write_image_data(&image_data[..]).unwrap();
|
|
png_writer.finish().unwrap();
|
|
log::info!("PNG file encoded in memory.");
|
|
|
|
let mut file = std::fs::File::create(&path).unwrap();
|
|
file.write_all(&png_data[..]).unwrap();
|
|
log::info!("PNG file written to disc as \"{}\".", path);
|
|
}
|
|
|
|
/// Effectively a version of `output_image_native` but meant for web browser contexts.
|
|
///
|
|
/// This is achieved via in `img` element on the page. If the target image element does
|
|
/// not exist, this function creates one. If it does, the image data is overridden.
|
|
///
|
|
/// This function makes use of a hidden staging canvas which the data is copied to in
|
|
/// order to create a data URL.
|
|
#[cfg(target_arch = "wasm32")]
|
|
pub fn output_image_wasm(image_data: Vec<u8>, texture_dims: (usize, usize)) {
|
|
let document = web_sys::window().unwrap().document().unwrap();
|
|
let body = document.body().unwrap();
|
|
|
|
let canvas = if let Some(found_canvas) = document.get_element_by_id("staging-canvas") {
|
|
match found_canvas.dyn_into::<web_sys::HtmlCanvasElement>() {
|
|
Ok(canvas_as_canvas) => canvas_as_canvas,
|
|
Err(e) => {
|
|
log::error!(
|
|
"In searching for a staging canvas for outputting an image \
|
|
(element with id \"staging-canvas\"), found non-canvas element: {:?}.
|
|
Replacing with standard staging canvas.",
|
|
e
|
|
);
|
|
e.remove();
|
|
create_staging_canvas(&document)
|
|
}
|
|
}
|
|
} else {
|
|
log::info!("Output image staging canvas element not found; creating.");
|
|
create_staging_canvas(&document)
|
|
};
|
|
// Having the size attributes the right size is so important, we should always do it
|
|
// just to be safe. Also, what if we might want the image size to be able to change?
|
|
let image_dimension_strings = (texture_dims.0.to_string(), texture_dims.1.to_string());
|
|
canvas
|
|
.set_attribute("width", image_dimension_strings.0.as_str())
|
|
.unwrap();
|
|
canvas
|
|
.set_attribute("height", image_dimension_strings.1.as_str())
|
|
.unwrap();
|
|
|
|
let context = canvas
|
|
.get_context("2d")
|
|
.unwrap()
|
|
.unwrap()
|
|
.dyn_into::<web_sys::CanvasRenderingContext2d>()
|
|
.unwrap();
|
|
let image_data = web_sys::ImageData::new_with_u8_clamped_array(
|
|
wasm_bindgen::Clamped(&image_data),
|
|
texture_dims.0 as u32,
|
|
)
|
|
.unwrap();
|
|
context.put_image_data(&image_data, 0.0, 0.0).unwrap();
|
|
|
|
// Get the img element that will act as our target for rendering from the canvas.
|
|
let image_element = if let Some(found_image_element) =
|
|
document.get_element_by_id("output-image-target")
|
|
{
|
|
match found_image_element.dyn_into::<web_sys::HtmlImageElement>() {
|
|
Ok(e) => e,
|
|
Err(e) => {
|
|
log::error!(
|
|
"Found an element with the id \"output-image-target\" but it was not an image: {:?}.
|
|
Replacing with default image output element.",
|
|
e
|
|
);
|
|
e.remove();
|
|
create_output_image_element(&document)
|
|
}
|
|
}
|
|
} else {
|
|
log::info!("Output image element not found; creating.");
|
|
create_output_image_element(&document)
|
|
};
|
|
// The canvas is currently the image we ultimately want. We can create a data url from it now.
|
|
let data_url = canvas.to_data_url().unwrap();
|
|
image_element.set_src(&data_url);
|
|
log::info!("Copied image from staging canvas to image element.");
|
|
|
|
if document.get_element_by_id("image-for-you-text").is_none() {
|
|
log::info!("\"Image for you\" text not found; creating.");
|
|
let p = document
|
|
.create_element("p")
|
|
.expect("Failed to create p element for \"image for you text\".");
|
|
p.set_text_content(Some(
|
|
"The above image is for you!
|
|
You can drag it to your desktop to download.",
|
|
));
|
|
p.set_id("image-for-you-text");
|
|
body.append_child(&p)
|
|
.expect("Failed to append \"image for you text\" to document body.");
|
|
}
|
|
}
|
|
|
|
#[cfg(target_arch = "wasm32")]
|
|
fn create_staging_canvas(document: &web_sys::Document) -> web_sys::HtmlCanvasElement {
|
|
let body = document.body().expect("Failed to get document body.");
|
|
let new_canvas = document
|
|
.create_element("canvas")
|
|
.expect("Failed to create staging canvas.")
|
|
.dyn_into::<web_sys::HtmlCanvasElement>()
|
|
.unwrap();
|
|
// We don't want to show the canvas, we just want it to exist in the background.
|
|
new_canvas.set_attribute("hidden", "true").unwrap();
|
|
new_canvas.set_attribute("background-color", "red").unwrap();
|
|
body.append_child(&new_canvas).unwrap();
|
|
log::info!("Created new staging canvas: {:?}", &new_canvas);
|
|
new_canvas
|
|
}
|
|
|
|
#[cfg(target_arch = "wasm32")]
|
|
fn create_output_image_element(document: &web_sys::Document) -> web_sys::HtmlImageElement {
|
|
let body = document.body().expect("Failed to get document body.");
|
|
let new_image = document
|
|
.create_element("img")
|
|
.expect("Failed to create output image element.")
|
|
.dyn_into::<web_sys::HtmlImageElement>()
|
|
.unwrap();
|
|
new_image.set_id("output-image-target");
|
|
body.append_child(&new_image)
|
|
.expect("Failed to append output image target to document body.");
|
|
log::info!("Created new output target image: {:?}", &new_image);
|
|
new_image
|
|
}
|