From 74eed253d84c4b507a8ee8f273612899f150acac Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Tue, 15 Dec 2020 01:36:51 -0500 Subject: [PATCH] Convert cube, skybox, msaa-line, and mipmap, to WGSL Validate example shaders in tests Support WGSL on the Web via Naga Port the shadow WGSL partially Convert hello-compute and boids to WGSL Conver the shadow's fragment shader to WGSL Shader entry point refactor --- Cargo.toml | 20 +++-- examples/README.md | 2 +- examples/boids/boids.comp | 78 ----------------- examples/boids/boids.comp.spv | Bin 5444 -> 0 bytes examples/boids/compute.wgsl | 113 ++++++++++++++++++++++++ examples/boids/draw.wgsl | 26 ++++++ examples/boids/main.rs | 36 +++++--- examples/boids/shader.frag | 5 -- examples/boids/shader.frag.spv | Bin 336 -> 0 bytes examples/boids/shader.vert | 11 --- examples/boids/shader.vert.spv | Bin 1684 -> 0 bytes examples/cube/main.rs | 40 +++++---- examples/cube/shader.frag | 12 --- examples/cube/shader.frag.spv | Bin 1208 -> 0 bytes examples/cube/shader.vert | 14 --- examples/cube/shader.vert.spv | Bin 1176 -> 0 bytes examples/cube/shader.wgsl | 44 ++++++++++ examples/cube/wire.frag | 7 -- examples/cube/wire.frag.spv | Bin 352 -> 0 bytes examples/hello-compute/main.rs | 15 +++- examples/hello-compute/shader.comp | 31 ------- examples/hello-compute/shader.comp.spv | Bin 1616 -> 0 bytes examples/hello-compute/shader.wgsl | 39 +++++++++ examples/hello-triangle/main.rs | 2 +- examples/mipmap/blit.frag | 10 --- examples/mipmap/blit.frag.spv | Bin 708 -> 0 bytes examples/mipmap/blit.vert | 16 ---- examples/mipmap/blit.vert.spv | Bin 1468 -> 0 bytes examples/mipmap/blit.wgsl | 36 ++++++++ examples/mipmap/draw.frag | 10 --- examples/mipmap/draw.frag.spv | Bin 684 -> 0 bytes examples/mipmap/draw.vert | 13 --- examples/mipmap/draw.vert.spv | Bin 1244 -> 0 bytes examples/mipmap/draw.wgsl | 34 ++++++++ examples/mipmap/main.rs | 41 ++++++--- examples/msaa-line/main.rs | 41 +++++---- examples/msaa-line/shader.frag | 8 -- examples/msaa-line/shader.frag.spv | Bin 372 -> 0 bytes examples/msaa-line/shader.vert | 10 --- examples/msaa-line/shader.vert.spv | Bin 968 -> 0 bytes examples/msaa-line/shader.wgsl | 24 ++++++ examples/shadow/bake.vert | 16 ---- examples/shadow/bake.vert.spv | Bin 1312 -> 0 bytes examples/shadow/forward.frag | 64 -------------- examples/shadow/forward.frag.spv | Bin 4612 -> 0 bytes examples/shadow/forward.vert | 22 ----- examples/shadow/forward.vert.spv | Bin 1948 -> 0 bytes examples/shadow/main.rs | 69 +++++++-------- examples/shadow/shader.wgsl | 114 +++++++++++++++++++++++++ examples/skybox/main.rs | 32 +++++-- examples/skybox/shader.frag | 11 --- examples/skybox/shader.frag.spv | Bin 684 -> 0 bytes examples/skybox/shader.vert | 22 ----- examples/skybox/shader.vert.spv | Bin 2076 -> 0 bytes examples/skybox/shader.wgsl | 43 ++++++++++ src/backend/web.rs | 10 ++- tests/example-wgsl.rs | 47 ++++++++++ 57 files changed, 712 insertions(+), 476 deletions(-) delete mode 100644 examples/boids/boids.comp delete mode 100644 examples/boids/boids.comp.spv create mode 100644 examples/boids/compute.wgsl create mode 100644 examples/boids/draw.wgsl delete mode 100644 examples/boids/shader.frag delete mode 100644 examples/boids/shader.frag.spv delete mode 100644 examples/boids/shader.vert delete mode 100644 examples/boids/shader.vert.spv delete mode 100644 examples/cube/shader.frag delete mode 100644 examples/cube/shader.frag.spv delete mode 100644 examples/cube/shader.vert delete mode 100644 examples/cube/shader.vert.spv create mode 100644 examples/cube/shader.wgsl delete mode 100644 examples/cube/wire.frag delete mode 100644 examples/cube/wire.frag.spv delete mode 100644 examples/hello-compute/shader.comp delete mode 100644 examples/hello-compute/shader.comp.spv create mode 100644 examples/hello-compute/shader.wgsl delete mode 100644 examples/mipmap/blit.frag delete mode 100644 examples/mipmap/blit.frag.spv delete mode 100644 examples/mipmap/blit.vert delete mode 100644 examples/mipmap/blit.vert.spv create mode 100644 examples/mipmap/blit.wgsl delete mode 100644 examples/mipmap/draw.frag delete mode 100644 examples/mipmap/draw.frag.spv delete mode 100644 examples/mipmap/draw.vert delete mode 100644 examples/mipmap/draw.vert.spv create mode 100644 examples/mipmap/draw.wgsl delete mode 100644 examples/msaa-line/shader.frag delete mode 100644 examples/msaa-line/shader.frag.spv delete mode 100644 examples/msaa-line/shader.vert delete mode 100644 examples/msaa-line/shader.vert.spv create mode 100644 examples/msaa-line/shader.wgsl delete mode 100644 examples/shadow/bake.vert delete mode 100644 examples/shadow/bake.vert.spv delete mode 100644 examples/shadow/forward.frag delete mode 100644 examples/shadow/forward.frag.spv delete mode 100644 examples/shadow/forward.vert delete mode 100644 examples/shadow/forward.vert.spv create mode 100644 examples/shadow/shader.wgsl delete mode 100644 examples/skybox/shader.frag delete mode 100644 examples/skybox/shader.frag.spv delete mode 100644 examples/skybox/shader.vert delete mode 100644 examples/skybox/shader.vert.spv create mode 100644 examples/skybox/shader.wgsl create mode 100644 tests/example-wgsl.rs diff --git a/Cargo.toml b/Cargo.toml index 96e6e3163..9d1c24922 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,21 +50,25 @@ tracing = { version = "0.1", default-features = false, features = ["std"] } serde = { version = "1", features = ["derive"], optional = true } [dev-dependencies] -cgmath = "0.18" -log = "0.4" -png = "0.16" -winit = { version = "0.24.0", features = ["web-sys"] } -rand = { version = "0.7.2", features = ["wasm-bindgen"] } bytemuck = { version = "1.4", features = ["derive"] } -noise = "0.7" +cgmath = "0.18" ddsfile = "0.4" +log = "0.4" +naga = { git = "https://github.com/gfx-rs/naga", tag = "gfx-8", features = ["wgsl-in"] } +noise = "0.7" +png = "0.16" +rand = { version = "0.7.2", features = ["wasm-bindgen"] } +winit = { version = "0.24.0", features = ["web-sys"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] async-executor = "1.0" pollster = "0.2" +wgpu-subscriber = "0.1" -[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies.wgpu-subscriber] -version = "0.1" +[target.'cfg(target_arch = "wasm32")'.dependencies.naga] +git = "https://github.com/gfx-rs/naga" +tag = "gfx-8" +features = ["wgsl-in", "spv-out"] [[example]] name="hello-compute" diff --git a/examples/README.md b/examples/README.md index 71bf215d1..270dcc92c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -39,7 +39,7 @@ All framework-based examples render to the window. | - compressed textures | | | | | | :star: | | | | - polygon mode | | :star: | | | | | | | | - queries | | | :star: | | | | | | -| WGSL shaders | | | | | | | | | +| WGSL shaders | :star: | :star: | :star: | :star: | :star: | :star: | | | ## Hacking diff --git a/examples/boids/boids.comp b/examples/boids/boids.comp deleted file mode 100644 index 69a4ca6dd..000000000 --- a/examples/boids/boids.comp +++ /dev/null @@ -1,78 +0,0 @@ -#version 450 - -// These should match the Rust constants defined in main.rs -#define NUM_PARTICLES 1500 -#define PARTICLES_PER_GROUP 64 - -layout(local_size_x = PARTICLES_PER_GROUP) in; - -struct Particle { - vec2 pos; - vec2 vel; -}; -layout(std140, set = 0, binding = 0) uniform SimParams { - float deltaT; - float rule1Distance; - float rule2Distance; - float rule3Distance; - float rule1Scale; - float rule2Scale; - float rule3Scale; -} params; -layout(std140, set = 0, binding = 1) buffer SrcParticles { - Particle particles[NUM_PARTICLES]; -} srcParticles; -layout(std140, set = 0, binding = 2) buffer DstParticles { - Particle particles[NUM_PARTICLES]; -} dstParticles; - -void main() { - // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp - uint index = gl_GlobalInvocationID.x; - - if (index >= NUM_PARTICLES) { return; } - vec2 vPos = srcParticles.particles[index].pos; - vec2 vVel = srcParticles.particles[index].vel; - vec2 cMass = vec2(0.0, 0.0); - vec2 cVel = vec2(0.0, 0.0); - vec2 colVel = vec2(0.0, 0.0); - int cMassCount = 0; - int cVelCount = 0; - vec2 pos; - vec2 vel; - for (int i = 0; i < NUM_PARTICLES; ++i) { - if (i == index) { continue; } - pos = srcParticles.particles[i].pos.xy; - vel = srcParticles.particles[i].vel.xy; - if (distance(pos, vPos) < params.rule1Distance) { - cMass += pos; - cMassCount++; - } - if (distance(pos, vPos) < params.rule2Distance) { - colVel -= (pos - vPos); - } - if (distance(pos, vPos) < params.rule3Distance) { - cVel += vel; - cVelCount++; - } - } - if (cMassCount > 0) { - cMass = cMass / cMassCount - vPos; - } - if (cVelCount > 0) { - cVel = cVel / cVelCount; - } - vVel += cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale; - // clamp velocity for a more pleasing simulation. - vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); - // kinematic update - vPos += vVel * params.deltaT; - // Wrap around boundary - if (vPos.x < -1.0) vPos.x = 1.0; - if (vPos.x > 1.0) vPos.x = -1.0; - if (vPos.y < -1.0) vPos.y = 1.0; - if (vPos.y > 1.0) vPos.y = -1.0; - dstParticles.particles[index].pos = vPos; - // Write back - dstParticles.particles[index].vel = vVel; -} diff --git a/examples/boids/boids.comp.spv b/examples/boids/boids.comp.spv deleted file mode 100644 index cadd91ef222be77360dfc232fc39d1b26de64356..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5444 zcmZ{n`Ipya6~{lrERu|h3W^)fU=azSETW|-1T<1m=qTDIew`U<>N_*Y45Q_STWX7@ z*+!c!E?JOR6uIP9uAsL5@`q5wAjfFL4ie;!f?wXTZIKL)@t`5r1&24I#bHA$k|ks`8WaF70$lMIg{=)-a4lv z#yB^w?CaqT4|AKvwqmaX4<-6JK ze(_As^t>*_)rHNERw?pFVt)WFc8~r8(JhGl>6Psna`Ul`wQnxt4?^pckKf;}R~gtD zRB;&i2(llE?m|4%-f3H-IjrBh}zr8osv*MozPP}z4KwJx$J>x!F;tAdyCu3WG7m^$w2it?$bkZ3y&-;lv zK8xQvjP)Mc&X1h_b1H0(oUy6mVh>^ajdj~l0X5M>{{rmPU_q<(T z@09b@yOE;U{4v&U*dLoNGCA??ZbpIq$0NY|ACrf50n{1!Q&> zopm|SP?m8M=Ig_CUm?qt7jzG#x|-<-PN zzc;Zxf7K+rr?OX4wcpXfh~Jvu*K%sMr-vZ&XL3XDqaELLu-q>8`<)$*$oZYTM*K{) z>rHa$^LI?nK8fGrwZwACIR|Xcl~nGx@j=AzsTp3&quJ6 zN8h|E);uR7`px5;Xp4OhzcsOM5$rnz`v%rzjQtO`_u@CW-%_;qRR5pam!VHZT>4K# z>sMQU7y4s}Id)gQJ-y=muI;DxDTuk;E6(0C!0x?@INxwNBA4Er3AQ&6RJqS8ecoZ> z-BzMqo}+ICBIh|`YqoxE`JB5N?74ZnHQ@AIUpHc`J^v)4-@ZAQ+R1Y^xSnS%cJk<} zzul*>^_$0e*3KE92AezfIYM9x}` z*C*#Y<$QI{|01}4{+F=peYprbeKA&l`f@SYzHCCwXI~n~#Yp;c3D_L+_N5=~vM>7j z5IOrIPF(}wdR>=dTh|R$Up9k{kBR_GKE2oiHix{u*ot=93w@U%a`r-;x<>G?2Epu5IOUR(}!!oeh~j{kBXS$6nYpgw%r#Hm%KNC>$7$vwsG?L2Iah8>QbkUo51!o_xlD|F88|y?DBs4Zbsz1pEz~g3id6N z_nTnz=6>G-%jJIG2FoeA-*>>~(U;kfv-X^+&Y8D??P=!vyI|+~cElL_dIutZTh+rm zOFY3R&-dW`-je70VDsFCB+n1P^2zf0gQ+dl%EUteAM?A{4c?Bo&0s3h5i-Nf~-OGCGOYY#M#5& zAjW+H(bvgeVflLzdEda81;{-}?r|U3GmJ|;ayjRIu;-*VzXjWyZp0YRcmR=4&fkIE zC!ajO2m1}A4?Dqf#(J(kInUXJ{sSV{iR7FID?Yz}4`IvgM*PnIgm(EI==&og=XW4Z z?mvT*+q1RzAkJ{&)rtR0Ek3pEg_D1ndJjYY6_GQKwLF4$S&P1h5jkrSC-sr@_`@Zu_F0z9e3q_`ib_ zpIZI_C!fAN1C~o)o&&qAMc=cCoVAFP`+0D3TZ?x3l6bY}cA#HErdGD!&C7`U^WTfF qfcGQLt+8tJ${U+J{{+|b{0n<7l05$gCy%l75c9|z>;HG0hP(|V*ZAlF diff --git a/examples/boids/compute.wgsl b/examples/boids/compute.wgsl new file mode 100644 index 000000000..8c1c505a2 --- /dev/null +++ b/examples/boids/compute.wgsl @@ -0,0 +1,113 @@ +// This should match `NUM_PARTICLES` on the Rust side. +const NUM_PARTICLES: u32 = 1500; + +[[block]] +struct Particle { + pos : vec2; + vel : vec2; +}; + +[[block]] +struct SimParams { + deltaT : f32; + rule1Distance : f32; + rule2Distance : f32; + rule3Distance : f32; + rule1Scale : f32; + rule2Scale : f32; + rule3Scale : f32; +}; + +[[block]] +struct Particles { + particles : [[stride(16)]] array; +}; + +[[group(0), binding(0)]] var params : SimParams; +[[group(0), binding(1)]] var particlesSrc : [[access(read)]] Particles; +[[group(0), binding(2)]] var particlesDst : [[access(read_write)]] Particles; + +[[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3; + +// https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp +[[stage(compute), workgroup_size(64)]] +fn main() { + const index : u32 = gl_GlobalInvocationID.x; + if (index >= NUM_PARTICLES) { + return; + } + + var vPos : vec2 = particlesSrc.particles[index].pos; + var vVel : vec2 = particlesSrc.particles[index].vel; + + var cMass : vec2 = vec2(0.0, 0.0); + var cVel : vec2 = vec2(0.0, 0.0); + var colVel : vec2 = vec2(0.0, 0.0); + var cMassCount : i32 = 0; + var cVelCount : i32 = 0; + + var pos : vec2; + var vel : vec2; + var i : u32 = 0u; + loop { + if (i >= NUM_PARTICLES) { + break; + } + if (i == index) { + continue; + } + + pos = particlesSrc.particles[i].pos; + vel = particlesSrc.particles[i].vel; + + if (distance(pos, vPos) < params.rule1Distance) { + cMass = cMass + pos; + cMassCount = cMassCount + 1; + } + if (distance(pos, vPos) < params.rule2Distance) { + colVel = colVel - (pos - vPos); + } + if (distance(pos, vPos) < params.rule3Distance) { + cVel = cVel + vel; + cVelCount = cVelCount + 1; + } + + continuing { + i = i + 1u; + } + } + if (cMassCount > 0) { + cMass = cMass * (1.0 / f32(cMassCount)) - vPos; + } + if (cVelCount > 0) { + cVel = cVel * (1.0 / f32(cVelCount)); + } + + vVel = vVel + (cMass * params.rule1Scale) + + (colVel * params.rule2Scale) + + (cVel * params.rule3Scale); + + // clamp velocity for a more pleasing simulation + vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1); + + // kinematic update + vPos = vPos + (vVel * params.deltaT); + + // Wrap around boundary + if (vPos.x < -1.0) { + vPos.x = 1.0; + } + if (vPos.x > 1.0) { + vPos.x = -1.0; + } + if (vPos.y < -1.0) { + vPos.y = 1.0; + } + if (vPos.y > 1.0) { + vPos.y = -1.0; + } + + // Write back + particlesDst.particles[index].pos = vPos; + particlesDst.particles[index].vel = vVel; +} diff --git a/examples/boids/draw.wgsl b/examples/boids/draw.wgsl new file mode 100644 index 000000000..cab88bdb3 --- /dev/null +++ b/examples/boids/draw.wgsl @@ -0,0 +1,26 @@ +[[location(0)]] +var in_particle_pos: vec2; +[[location(1)]] +var in_particle_vel: vec2; +[[location(2)]] +var in_position: vec2; +[[builtin(position)]] +var out_position: vec4; + +[[stage(vertex)]] +fn main() { + const angle: f32 = -atan2(in_particle_vel.x, in_particle_vel.y); + const pos: vec2 = vec2( + in_position.x * cos(angle) - in_position.y * sin(angle), + in_position.x * sin(angle) + in_position.y * cos(angle) + ); + out_position = vec4(pos + in_particle_pos, 0.0, 1.0); +} + +[[location(0)]] +var out_color: vec4; + +[[stage(fragment)]] +fn main() { + out_color = vec4(1.0, 1.0, 1.0, 1.0); +} diff --git a/examples/boids/main.rs b/examples/boids/main.rs index 08be4f475..f7587e39f 100644 --- a/examples/boids/main.rs +++ b/examples/boids/main.rs @@ -1,6 +1,7 @@ // Flocking boids example with gpu compute update pass // adapted from https://github.com/austinEng/webgpu-samples/blob/master/src/examples/computeBoids.ts +use std::{borrow::Cow, mem}; use wgpu::util::DeviceExt; #[path = "../framework.rs"] @@ -29,15 +30,28 @@ impl framework::Example for Example { /// constructs initial instance of Example struct fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, _queue: &wgpu::Queue, ) -> Self { - // load (and compile) shaders and create shader modules - - let boids_module = device.create_shader_module(&wgpu::include_spirv!("boids.comp.spv")); - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + // load and compile the shader + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgt::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION; + } + _ => {} //TODO + } + let compute_shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("compute.wgsl"))), + flags, + }); + let draw_shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("draw.wgsl"))), + flags, + }); // buffer for simulation parameters uniform @@ -69,7 +83,7 @@ impl framework::Example for Example { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new( - (sim_param_data.len() * std::mem::size_of::()) as _, + (sim_param_data.len() * mem::size_of::()) as _, ), }, count: None, @@ -78,7 +92,7 @@ impl framework::Example for Example { binding: 1, visibility: wgpu::ShaderStage::COMPUTE, ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, + ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new((NUM_PARTICLES * 16) as _), }, @@ -117,7 +131,7 @@ impl framework::Example for Example { label: None, layout: Some(&render_pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, + module: &draw_shader, entry_point: "main", buffers: &[ wgpu::VertexBufferLayout { @@ -133,7 +147,7 @@ impl framework::Example for Example { ], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, + module: &draw_shader, entry_point: "main", targets: &[sc_desc.format.into()], }), @@ -147,7 +161,7 @@ impl framework::Example for Example { let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("Compute pipeline"), layout: Some(&compute_pipeline_layout), - module: &boids_module, + module: &compute_shader, entry_point: "main", }); diff --git a/examples/boids/shader.frag b/examples/boids/shader.frag deleted file mode 100644 index a778506c3..000000000 --- a/examples/boids/shader.frag +++ /dev/null @@ -1,5 +0,0 @@ -#version 450 -layout(location = 0) out vec4 fragColor; -void main() { - fragColor = vec4(1.0); -} diff --git a/examples/boids/shader.frag.spv b/examples/boids/shader.frag.spv deleted file mode 100644 index 3b3d8fbd71aa5caddb46b0f72484b62483cbc60a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 336 zcmYk2%?`m(6od~|O2tnk?4)8z!~&5>SXgw^ohN7_M1m&e0X&+}vd@qeY;HU+0J`JK`PCbxY~1 rA6KTd5nSFHFnesqxa13gw0|tPpUzgUO8YMqpT34EQ+sdz)DnCE5W*4Y diff --git a/examples/boids/shader.vert b/examples/boids/shader.vert deleted file mode 100644 index b302b6cf3..000000000 --- a/examples/boids/shader.vert +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 -layout(location = 0) in vec2 a_particlePos; -layout(location = 1) in vec2 a_particleVel; -layout(location = 2) in vec2 a_pos; - -void main() { - float angle = -atan(a_particleVel.x, a_particleVel.y); - vec2 pos = vec2(a_pos.x * cos(angle) - a_pos.y * sin(angle), - a_pos.x * sin(angle) + a_pos.y * cos(angle)); - gl_Position = vec4(pos + a_particlePos, 0, 1); -} diff --git a/examples/boids/shader.vert.spv b/examples/boids/shader.vert.spv deleted file mode 100644 index 3e95e49fbd63255d50a8008f0b1a3f9ea2850516..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1684 zcmZ9LTTc^F6h@Df0t$kNfEUyv-ch^(qR356@PP*m39qEV37KRpgx19PqQ>~g{8he~ zxYp^M(r}vHz4!O+>zSEK&rE*^XZQ_-x1oJTLl1rkgP||#&8?lSxn}Fr-2B2*BZfmI z1{yOG&PKbJ|IhWjp)-hFM&^+vq{6QU{fC5V=;e13t3QBWZyXdEx=K&;>w8D_<5s?3 zWV=}r@k*FPA00Mh4eJww*Uov4J}CCKv*X?DxRrgyrBYuI_sAVK^HzS?0PT;s^G7^y zw081uw(oGx3-_+bkKX6aR=u&GbvU<|`%)AguF8(?>v0G7KG}iR_?ztNZZ{Bn>$``( z{XUSH<~7cfFyqD42{T8`c@m~A<{fXsSkE|nIg`CSW1!;G#F(Q!fz^kuMd{_1LKLw{ z@_o|U#@6u9p`Ay3x%AVF7Q@AF@G4_d}}6tw8X4Gf$a?4^}R21oX3~Z zTz8$~|5@o<;|7eorx-cKx-Zb~EbrX)6(ImPMYi_vg$W@xLHdw6)#W??J8a9r)hsZxH33jUe8$cez50{VpKlDdr-! zG2TUr8N(JIqMA9E5O=tOm@ogmtT&D=zsiKpqn~OU?{nzxe-&Rm^}2>_-VmMaHHFyA z`Q?7Ii}-cKT=`Vrchvgbv){xQPxWiq-SwyOt?x`VB-Ou#ZLa*UvgZu8edSWm+t{af zx&tPjdfvtE?s*SC^^{9J?_--QpXxurKE2aJF!5A>7Q4ItBYf+7XL70jV{CKff0jGV zVcS=38_aL!3F5ADK1bgpG5g8CM8uN+3VR8$ru=Kf81au~pOq3vb+FYEbJlI%E#LDs d#8^4M4ZjEPVm<2i_vSa{TpMWP|FP{7@*kECVD|t3 diff --git a/examples/cube/main.rs b/examples/cube/main.rs index 6b31988b1..e0e42c857 100644 --- a/examples/cube/main.rs +++ b/examples/cube/main.rs @@ -2,6 +2,7 @@ mod framework; use bytemuck::{Pod, Zeroable}; +use std::{borrow::Cow, iter, mem}; use wgpu::util::DeviceExt; #[repr(C)] @@ -65,8 +66,6 @@ fn create_vertices() -> (Vec, Vec) { } fn create_texels(size: usize) -> Vec { - use std::iter; - (0..size * size) .flat_map(|id| { // get high five for recognizing this ;) @@ -117,12 +116,10 @@ impl framework::Example for Example { fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, ) -> Self { - use std::mem; - // Create the vertex and index buffers let vertex_size = mem::size_of::(); let (vertex_data, index_data) = create_vertices(); @@ -251,9 +248,18 @@ impl framework::Example for Example { label: None, }); - // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); let vertex_buffers = [wgpu::VertexBufferLayout { array_stride: vertex_size as wgpu::BufferAddress, @@ -276,13 +282,13 @@ impl framework::Example for Example { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &vertex_buffers, }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -297,19 +303,17 @@ impl framework::Example for Example { .features() .contains(wgt::Features::NON_FILL_POLYGON_MODE) { - let fs_wire_module = - device.create_shader_module(&wgpu::include_spirv!("wire.frag.spv")); let pipeline_wire = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &vertex_buffers, }, fragment: Some(wgpu::FragmentState { - module: &fs_wire_module, - entry_point: "main", + module: &shader, + entry_point: "fs_wire", targets: &[wgpu::ColorTargetState { format: sc_desc.format, color_blend: wgpu::BlendState { diff --git a/examples/cube/shader.frag b/examples/cube/shader.frag deleted file mode 100644 index 966bfdb02..000000000 --- a/examples/cube/shader.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_Target; -layout(set = 0, binding = 1) uniform texture2D t_Color; -layout(set = 0, binding = 2) uniform sampler s_Color; - -void main() { - vec4 tex = texture(sampler2D(t_Color, s_Color), v_TexCoord); - float mag = length(v_TexCoord-vec2(0.5)); - o_Target = vec4(mix(tex.xyz, vec3(0.0), mag*mag), 1.0); -} diff --git a/examples/cube/shader.frag.spv b/examples/cube/shader.frag.spv deleted file mode 100644 index f41e3c9ecc1f4afb329f0ed1d0db1806b3db0900..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1208 zcmYk4T}xC^6o%J09krbN$kf!z8STrQCWDF~O2`XugcPMN2f;yv>cBXJmqPT%`c>Wt zKF^-B!wv83z25b%&pGvxwXuj=+=}sd6T>qTBQOyYF`Dk3-GklE+2FYI_T8q6$*3ox znyDBgHWGdwo&M4>4_aUvojwZis*^S1A3+7IeAXBEZetI6=gHUb-Q6yKl>KB+W1s!E ziWit2kq~hc~#=8&o=6nv!k?j|i z{g*!UuLCvmdobpF3FI>xRjmy;^LK!C{cqInSGivCR^!Q>+8md;*A-`|O?YoXuR@#J)JRL?JtUcP!^#Cqs9 zfyQivJI#5S-^(mzQ3_O7~{WB&$8>|vaBwQ={5J$|G0kG zB<^c5{ghRovud7Q1L?5kJ?ks$e4dvx*p(*U9veQN%}?{2%(&>YCw#|6{_SI4&(qm? zcI$IOeOE+3OxGbzroi=C9`X;HU*h?T49S(VP}FJ*N}TsJ&!>E@36NNp24CWo`j zDPs2~w(k>eII|+JL{7ilzj4kZXYVo2vz$90<1wFcCyV|$Ql*WL{f{IOb3~3u5+0!D zkTZwn=MgqR z&1)U;HmdA_cd+KQuK~B*shqj@u+A@MZn1lgJ9)A=$M|Pp>zL1YaePDO8-ndi|7-qJ z^H^7r{{`b4cn9kq@1gGSJzjS${y>CvpQ85SEXLczJ}NJ^#&gvAKe!`KP-EoHV?PI| Q`!bJp#0mPFN#3A;07fE7i2wiq diff --git a/examples/cube/shader.wgsl b/examples/cube/shader.wgsl new file mode 100644 index 000000000..cc9404240 --- /dev/null +++ b/examples/cube/shader.wgsl @@ -0,0 +1,44 @@ +[[location(0)]] +var in_position: vec4; +[[location(1)]] +var in_tex_coord_vs: vec2; +[[location(0)]] +var out_tex_coord: vec2; +[[builtin(position)]] +var out_position: vec4; + +[[block]] +struct Locals { + transform: mat4x4; +}; +[[group(0), binding(0)]] +var r_locals: Locals; + +[[stage(vertex)]] +fn vs_main() { + out_tex_coord = in_tex_coord_vs; + out_position = r_locals.transform * in_position; +} + +[[location(0)]] +var in_tex_coord_fs: vec2; +[[location(0)]] +var out_color: vec4; +[[group(0), binding(1)]] +var r_color: texture_2d; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[stage(fragment)]] +fn fs_main() { + var tex: vec4 = textureSample(r_color, r_sampler, in_tex_coord_fs); + out_color = tex; + //TODO: support `length` and `mix` functions + //var mag: f32 = length(in_tex_coord_fs-vec2(0.5, 0.5)); + //out_color = vec4(mix(tex.xyz, vec3(0.0, 0.0, 0.0), mag*mag), 1.0); +} + +[[stage(fragment)]] +fn fs_wire() { + out_color = vec4(0.0, 0.5, 0.0, 0.5); +} diff --git a/examples/cube/wire.frag b/examples/cube/wire.frag deleted file mode 100644 index dde4b20f6..000000000 --- a/examples/cube/wire.frag +++ /dev/null @@ -1,7 +0,0 @@ -#version 450 - -layout(location = 0) out vec4 o_Target; - -void main() { - o_Target = vec4(0.0, 0.5, 0.0, 0.5); -} diff --git a/examples/cube/wire.frag.spv b/examples/cube/wire.frag.spv deleted file mode 100644 index f2afd9aaef6d28f3dd391de08f64a2cb9d4c7b8c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 352 zcmYk2O$z~G6os!D!!SNm>@>0@Ss$2 diff --git a/examples/hello-compute/main.rs b/examples/hello-compute/main.rs index 022de1088..ad6c31c8d 100644 --- a/examples/hello-compute/main.rs +++ b/examples/hello-compute/main.rs @@ -1,4 +1,4 @@ -use std::{convert::TryInto, str::FromStr}; +use std::{borrow::Cow, convert::TryInto, str::FromStr}; use wgpu::util::DeviceExt; async fn run() { @@ -44,7 +44,18 @@ async fn execute_gpu(numbers: Vec) -> Vec { .unwrap(); // Loads the shader from the SPIR-V file.arrayvec - let cs_module = device.create_shader_module(&wgpu::include_spirv!("shader.comp.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Vulkan | wgpu::Backend::Metal => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION; + } + _ => {} + } + let cs_module = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); // Gets the size in bytes of the buffer. let slice_size = numbers.len() * std::mem::size_of::(); diff --git a/examples/hello-compute/shader.comp b/examples/hello-compute/shader.comp deleted file mode 100644 index b7b1edef8..000000000 --- a/examples/hello-compute/shader.comp +++ /dev/null @@ -1,31 +0,0 @@ -#version 450 -layout(local_size_x = 1) in; - -layout(set = 0, binding = 0) buffer PrimeIndices { - uint[] indices; -}; // this is used as both input and output for convenience - -// The Collatz Conjecture states that for any integer n: -// If n is even, n = n/2 -// If n is odd, n = 3n+1 -// And repeat this process for each new n, you will always eventually reach 1. -// Though the conjecture has not been proven, no counterexample has ever been found. -// This function returns how many times this recurrence needs to be applied to reach 1. -uint collatz_iterations(uint n) { - uint i = 0; - while(n > 1) { - if (mod(n, 2) == 0) { - n = n / 2; - } - else { - n = (3 * n) + 1; - } - i++; - } - return i; -} - -void main() { - uint index = gl_GlobalInvocationID.x; - indices[index] = collatz_iterations(indices[index]); -} \ No newline at end of file diff --git a/examples/hello-compute/shader.comp.spv b/examples/hello-compute/shader.comp.spv deleted file mode 100644 index 7bf37d71de44ae838b62ac8144d5f85bcefd14ca..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1616 zcmYk6*-leY6o!wKB8W1`~{xuJKA96i&XOrYi($C-Xq7-LzT3NlX z$54_>9rYQ;ClBw14l9k8h6m6HdUd0aenB~6dyv1Q$m4N3E>92VuvOd5W~KAtpwX!x zS2~S$>tz1z@|OO&WB|KG#OL9S6!#|g#I0KWeJb~-J-lfil$-6>mF8aSUAvlQ+H=M{ zy{*Gv9ybo_d#zfdT0cQdCsFSqSE{zoW>=N=yA3|799ItEWx99PLFig0ufh8u=Xyaz zlGkR0htR;NqrHyA1+qE zkojK#dqN%ub0x_*StsC=RJa5$K>CQUK%Cu>o!JvPieP&R`3BfN?ePx009ix3^4(0H zLiS zf2s@laVD3DwC5*~b2*E)@Y@AzGp9W$Z_@ns1k4o2Yqzwl_k2-hx;dB(uj_(~7mcj|Z1 zy_-Mem;?_)<}y|su~T4UkMQ$7`%S6)LN4X2na+3qEz3Wh>3!=z>Hj+1V=Zkn&>Unf zanve+t@SzE)ht+D5poaO)H$a)jW; + +[[block]] +struct PrimeIndices { + data: [[stride(4)]] array; +}; // this is used as both input and output for convenience + +[[group(0), binding(0)]] +var v_indices: [[access(read_write)]] PrimeIndices; + +// The Collatz Conjecture states that for any integer n: +// If n is even, n = n/2 +// If n is odd, n = 3n+1 +// And repeat this process for each new n, you will always eventually reach 1. +// Though the conjecture has not been proven, no counterexample has ever been found. +// This function returns how many times this recurrence needs to be applied to reach 1. +fn collatz_iterations(n_base: u32) -> u32{ + var n: u32 = n_base; + var i: u32 = 0u; + loop { + if (n <= 1u) { + break; + } + if (n % 2u == 0u) { + n = n / 2u; + } + else { + n = 3u * n + 1u; + } + i = i + 1u; + } + return i; +} + +[[stage(compute), workgroup_size(1)]] +fn main() { + v_indices.data[global_id.x] = collatz_iterations(v_indices.data[global_id.x]); +} diff --git a/examples/hello-triangle/main.rs b/examples/hello-triangle/main.rs index c87cafaf1..7d5ed6472 100644 --- a/examples/hello-triangle/main.rs +++ b/examples/hello-triangle/main.rs @@ -7,7 +7,7 @@ use winit::{ async fn run(event_loop: EventLoop<()>, window: Window) { let size = window.inner_size(); - let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); + let instance = wgpu::Instance::new(wgpu::BackendBit::all()); let surface = unsafe { instance.create_surface(&window) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { diff --git a/examples/mipmap/blit.frag b/examples/mipmap/blit.frag deleted file mode 100644 index cfe6499aa..000000000 --- a/examples/mipmap/blit.frag +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_Target; -layout(set = 0, binding = 0) uniform texture2D t_Color; -layout(set = 0, binding = 1) uniform sampler s_Color; - -void main() { - o_Target = textureLod(sampler2D(t_Color, s_Color), v_TexCoord, 0.0); -} diff --git a/examples/mipmap/blit.frag.spv b/examples/mipmap/blit.frag.spv deleted file mode 100644 index ff08dac769279e3b6e62a4464bc7ef0d70d435e9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 708 zcmYk3%}WAN6vb~&qn71ImZm|dEdyy$5kzfVxN(<6yFpMQs2+?%^!N2wwFx@EtJYk& zbKg1d+^;uL;jCn~WhEKi0av_?UGPf1+x7o`( z7d!Hnye=KQ8t4?Ms@a#4VzGIBEQXwrOlRryBGb_|dx}{y3a=q`To+#c;n;h8B-6#` zD1>xwHda;YoXRmUH3p9UaX*KtnZE~f&u-+i$EIFW8?Zy)w=qArbS{eP$=lMiE13Oy z`j!=WE%@6tW=6Py%z7)k)wmBAN}vujrZg3N7LQNe*x6vB3=Lh diff --git a/examples/mipmap/blit.vert b/examples/mipmap/blit.vert deleted file mode 100644 index d8ab87c76..000000000 --- a/examples/mipmap/blit.vert +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) out vec2 v_TexCoord; - -void main() { - vec2 tc = vec2(0.0); - switch(gl_VertexIndex) { - case 0: tc = vec2(1.0, 0.0); break; - case 1: tc = vec2(1.0, 1.0); break; - case 2: tc = vec2(0.0, 0.0); break; - case 3: tc = vec2(0.0, 1.0); break; - } - v_TexCoord = tc; - vec2 pos = tc * 2.0 - 1.0; - gl_Position = vec4(pos.x, -pos.y, 0.5, 1.0); -} diff --git a/examples/mipmap/blit.vert.spv b/examples/mipmap/blit.vert.spv deleted file mode 100644 index b2ad4687e9837e70827de9b58cc69c32e872bdf2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1468 zcmYk5U29W85Qf*pq-wRb)>c8OiSesVjbCl8idLymgoFpW_M1?rN&eUC&DTIo`!tQg%V5%)1jK}JG*LKCT3f$w z#7rn>fyT^o&UF%eJV<-mGvFGy3(EYJ*nbjSA!;(Nf_55hbf{L%&VA_azfT6EWc;?* zNyhS(EZ67#cgc9W-yd}3%AwA=qy8{E*Tm*rI~n9hamiK<@-DUhFde1+9_&=c+k3{R zz0qF!B{42)_KUXNO^;ru!_h(SFgez|x!R|0_gJ$Z@9Ns&hTeY~tQ5X)u>@Ri=s5Oe zj4N{XB*^yK(dUcdx@4qrHe#Wv_utoM70QuU5l%dUB$PZ|oW1 zTBTQcYsrZPV$QPHfPI?dTw%*UD}3KTJ?31%4&mEY%(;jsXU@o7E;#wfT`6MZtmQj; zH~X@dzV9m+Yc;T0FTL+=4DaMy+4~*#8gLn}zYOg4D*g()@p4O8zHQ8*ChTLCJ+GPf zp`U;6d0yY51zfStz1+>t`$O^$){1>^9^w zd3`^*SLn{_0g!Ws)^ctSfqaa4gl)_+h%sx}@?VQH>)3K_ZsKeo1M|o`e|s{Y^M3;T Qru>fVN#FQ?OlA}O2QnO8od5s; diff --git a/examples/mipmap/blit.wgsl b/examples/mipmap/blit.wgsl new file mode 100644 index 000000000..e5cb571f5 --- /dev/null +++ b/examples/mipmap/blit.wgsl @@ -0,0 +1,36 @@ +[[builtin(vertex_index)]] +var in_vertex_index: u32; +[[builtin(position)]] +var out_position: vec4; +[[location(0)]] +var out_tex_coords_vs: vec2; + +[[stage(vertex)]] +fn vs_main() { + var x: i32 = i32(in_vertex_index) / 2; + var y: i32 = i32(in_vertex_index) & 1; + out_tex_coords_vs = vec2( + f32(x) * 2.0, + f32(y) * 2.0 + ); + out_position = vec4( + out_tex_coords_vs.x * 2.0 - 1.0, + 1.0 - out_tex_coords_vs.y * 2.0, + 0.0, 1.0 + ); +} + +[[location(0)]] +var in_tex_coord_fs: vec2; +[[location(0)]] +var out_color_fs: vec4; + +[[group(0), binding(0)]] +var r_color: texture_2d; +[[group(0), binding(1)]] +var r_sampler: sampler; + +[[stage(fragment)]] +fn fs_main() { + out_color_fs = textureSample(r_color, r_sampler, in_tex_coord_fs); +} diff --git a/examples/mipmap/draw.frag b/examples/mipmap/draw.frag deleted file mode 100644 index c705c207c..000000000 --- a/examples/mipmap/draw.frag +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 v_TexCoord; -layout(location = 0) out vec4 o_Target; -layout(set = 0, binding = 1) uniform texture2D t_Color; -layout(set = 0, binding = 2) uniform sampler s_Color; - -void main() { - o_Target = texture(sampler2D(t_Color, s_Color), v_TexCoord); -} diff --git a/examples/mipmap/draw.frag.spv b/examples/mipmap/draw.frag.spv deleted file mode 100644 index 57d41137679dd4b19bcf840cdcecd848b9236b16..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 684 zcmYk3O-q7N5QT5rtCr7b;328-;4h+}tJ`Z{wGD z3p+%esGyU_fUhiFL-^uS0=ubCV7!x#hU3}ubirrT?2#9vUizBOBCdeve>jOAAEV*) zvzMl`NeF$q+UJb$i0#pd=pVPi&TieFn{}~uXSMDg>wYy@`F7l9sj2gwgKH5D^zJHl zzZSm*vacn7yTZ;W*JRpVvU=y)JZo%^;;Nw59%A?MoG?*|tgajx|DUB!>^`1T91qC$ zaLz-rzV74QBeI_IdWhX!?wZ$E=T07H|AtA(cd+){C!9&Ff0fYt5tY6*LXEr{eHw%w VPiTCfV?v$$JubeJ+z(US5Wm89}u3dIW*K~zeG^dexO#oG|tRTk2$B&ihdyz8z1 zz~ADp@<#A^cJ~xdc$t}Z-ZMKhIrUnn8Nys>hHK$jD9=i$!Gy3F77E+#9rgC6v(vp7 zFQ2Pe3iU#$W|@1Qd2lw&#`@R6O>iI7`PHz$5jRl%uWP`l{WdsGFAnm2a$0JLsxId2hupy^`}!f9 z&W7WY^eX3M=FUf>t6YN_oWnuj4IX6R^R3>l&L&h1FPP7)W;pj zt2cIsb6}TP?J@}A*M5xe6mfXJMt%)HDdR$Kybip-MScTo4Y?Mc`-?r86ZUZrYmesb z!?=9sfp5%*2gC`mu6-D90naA!L#%b3t3@SuENAU)toxC(ws8XD&f1k9^-qZH#d@#! z57k-MBmW1+|NJeinp?n~ePrwIeW~K)J@(w^MtlSAQ(RWu3ch!IA5pi8@1DhvN_Q7u zt+{t};{PhQPu>}JKmy#0y*W<@$j4qE;oIv^?%4Zdphn(0&i)j*d+YceV|9O- in_position_vs: vec4; +[[builtin(position)]] +var out_position: vec4; +[[location(0)]] +var out_tex_coords_vs: vec2; + +[[block]] +struct Locals { + transform: mat4x4; +}; +[[group(0), binding(0)]] +var r_data: Locals; + +[[stage(vertex)]] +fn vs_main() { + out_tex_coords_vs = 0.05 * in_position_vs.xy + vec2(0.5, 0.5); + out_position = r_data.transform * in_position_vs; +} + +[[location(0)]] +var in_tex_coord_fs: vec2; +[[location(0)]] +var out_color_fs: vec4; + +[[group(0), binding(1)]] +var r_color: texture_2d; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[stage(fragment)]] +fn fs_main() { + out_color_fs = textureSample(r_color, r_sampler, in_tex_coord_fs); +} diff --git a/examples/mipmap/main.rs b/examples/mipmap/main.rs index 8577a5f28..9994cf439 100644 --- a/examples/mipmap/main.rs +++ b/examples/mipmap/main.rs @@ -2,7 +2,7 @@ mod framework; use bytemuck::{Pod, Zeroable}; -use std::{mem, num::NonZeroU32}; +use std::{borrow::Cow, mem, num::NonZeroU32}; use wgpu::util::DeviceExt; const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb; @@ -102,21 +102,25 @@ impl Example { texture: &wgpu::Texture, query_sets: &Option, mip_count: u32, + shader_flags: wgpu::ShaderFlags, ) { - let vs_module = device.create_shader_module(&wgpu::include_spirv!("blit.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("blit.frag.spv")); + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("blit.wgsl"))), + flags: shader_flags, + }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("blit"), layout: None, vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[TEXTURE_FORMAT.into()], }), primitive: wgpu::PrimitiveState { @@ -307,15 +311,25 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("draw.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("draw.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("draw.wgsl"))), + flags, + }); let draw_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("draw"), layout: None, vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[wgpu::VertexBufferLayout { array_stride: vertex_size as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, @@ -323,8 +337,8 @@ impl framework::Example for Example { }], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -411,6 +425,7 @@ impl framework::Example for Example { &texture, &query_sets, MIP_LEVEL_COUNT, + flags, ); queue.submit(Some(init_encoder.finish())); diff --git a/examples/msaa-line/main.rs b/examples/msaa-line/main.rs index 64a55c1bb..2a7787135 100644 --- a/examples/msaa-line/main.rs +++ b/examples/msaa-line/main.rs @@ -10,7 +10,7 @@ #[path = "../framework.rs"] mod framework; -use std::iter; +use std::{borrow::Cow, iter}; use bytemuck::{Pod, Zeroable}; use wgpu::util::DeviceExt; @@ -24,8 +24,7 @@ struct Vertex { struct Example { bundle: wgpu::RenderBundle, - vs_module: wgpu::ShaderModule, - fs_module: wgpu::ShaderModule, + shader: wgpu::ShaderModule, pipeline_layout: wgpu::PipelineLayout, multisampled_framebuffer: wgpu::TextureView, vertex_buffer: wgpu::Buffer, @@ -39,8 +38,7 @@ impl Example { fn create_bundle( device: &wgpu::Device, sc_desc: &wgpu::SwapChainDescriptor, - vs_module: &wgpu::ShaderModule, - fs_module: &wgpu::ShaderModule, + shader: &wgpu::ShaderModule, pipeline_layout: &wgpu::PipelineLayout, sample_count: u32, vertex_buffer: &wgpu::Buffer, @@ -51,8 +49,8 @@ impl Example { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: vs_module, - entry_point: "main", + module: shader, + entry_point: "vs_main", buffers: &[wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, @@ -60,8 +58,8 @@ impl Example { }], }, fragment: Some(wgpu::FragmentState { - module: fs_module, - entry_point: "main", + module: shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -119,15 +117,25 @@ impl Example { impl framework::Example for Example { fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, _queue: &wgpu::Queue, ) -> Self { log::info!("Press left/right arrow keys to change sample_count."); let sample_count = 4; - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, @@ -164,8 +172,7 @@ impl framework::Example for Example { let bundle = Example::create_bundle( device, &sc_desc, - &vs_module, - &fs_module, + &shader, &pipeline_layout, sample_count, &vertex_buffer, @@ -174,8 +181,7 @@ impl framework::Example for Example { Example { bundle, - vs_module, - fs_module, + shader, pipeline_layout, multisampled_framebuffer, vertex_buffer, @@ -235,8 +241,7 @@ impl framework::Example for Example { self.bundle = Example::create_bundle( device, &self.sc_desc, - &self.vs_module, - &self.fs_module, + &self.shader, &self.pipeline_layout, self.sample_count, &self.vertex_buffer, diff --git a/examples/msaa-line/shader.frag b/examples/msaa-line/shader.frag deleted file mode 100644 index 1bb727606..000000000 --- a/examples/msaa-line/shader.frag +++ /dev/null @@ -1,8 +0,0 @@ -#version 450 - -layout(location = 0) in vec4 v_Color; -layout(location = 0) out vec4 f_Color; - -void main() { - f_Color = v_Color; -} diff --git a/examples/msaa-line/shader.frag.spv b/examples/msaa-line/shader.frag.spv deleted file mode 100644 index 46d3355b7c1a4ad700fd8da3b6ebbd6e7ea114ee..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 372 zcmYk1O$z~06o!u(W-vZe>_qmmKuT;ZW-~iKKuSts3i*M4m5uT~*N{7%d+z&jKF0S3 zp;=B}(W>@2P4k4!A`4uOlXWt@-gd+BWQ3z;zBA&fTWEP@;b1N8FM z)$F07g4lmQn40}&l^)ZJ)2Y8_IL`F0I1U*7i(BeU@4lO2?%mcq5Z6<5 diff --git a/examples/msaa-line/shader.vert b/examples/msaa-line/shader.vert deleted file mode 100644 index b42b54058..000000000 --- a/examples/msaa-line/shader.vert +++ /dev/null @@ -1,10 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 a_Pos; -layout(location = 1) in vec4 a_Color; -layout(location = 0) out vec4 v_Color; - -void main() { - gl_Position = vec4(a_Pos, 0.0, 1.0); - v_Color = a_Color; -} diff --git a/examples/msaa-line/shader.vert.spv b/examples/msaa-line/shader.vert.spv deleted file mode 100644 index f507020091202e12b8599deac2d06a10ef006cd7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 968 zcmYk4%}WAN6vbbDmz9~ReV7?718GqaL`4|b!i6EUm7#_hn4HilqE&xee^r~H^LsN- zd~v()ocnd=KC_vlqA^P*XG-S4B&TXJVvH%9g7y8uXwaR-&)w6r6EfCK)+UluG0XOz z)Bjg5m;lyfo3cIGzAUT1jQo!Z@|v`mo7ar8VlUx%=uaR0Y3zRricNU##G+Xc2hl`q z(dIMT^1&n?1z$dSF2*dydSUQ(7tCUB^5oBBC@1zFhVxin`q0clAKE=erkL;e826$u zn%X$udD=baU8B&^nFA9j_%AxEA?P@2S>am zPcIh-vrD*hy(v1_5r>*zF?snbv1qEv(DNV`Esd0un{&;SqvueQn6)h in_position: vec2; +[[location(1)]] +var in_color_vs: vec4; +[[location(0)]] +var out_color_vs: vec4; +[[builtin(position)]] +var out_position: vec4; + +[[stage(vertex)]] +fn vs_main() { + out_position = vec4(in_position, 0.0, 1.0); + out_color_vs = in_color_vs; +} + +[[location(0)]] +var in_color_fs: vec4; +[[location(0)]] +var out_color_fs: vec4; + +[[stage(fragment)]] +fn fs_main() { + out_color_fs = in_color_fs; +} diff --git a/examples/shadow/bake.vert b/examples/shadow/bake.vert deleted file mode 100644 index e4426b745..000000000 --- a/examples/shadow/bake.vert +++ /dev/null @@ -1,16 +0,0 @@ -#version 450 - -layout(location = 0) in ivec4 a_Pos; - -layout(set = 0, binding = 0) uniform Globals { - mat4 u_ViewProj; -}; - -layout(set = 1, binding = 0) uniform Entity { - mat4 u_World; - vec4 u_Color; -}; - -void main() { - gl_Position = u_ViewProj * u_World * vec4(a_Pos); -} diff --git a/examples/shadow/bake.vert.spv b/examples/shadow/bake.vert.spv deleted file mode 100644 index 26f1000fddfaddd480e9ef0bcf3de4eefd0ddaa3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1312 zcmYk4TWb?x5QaY!lT@p%wf3OaxM}rDC|;-tq9|3;i(V88^)f`e$jZ7an++cRh5jUe zl{bRVv&k1SWjZtOymR0=pd zq1_PWtW&96M!$@+LjO8?A8qs3!v2BSfw9c#(0i5Kr+jppR_AF|r{4)dXSlw(a+1|q zS%CH$zB3y9^CW{4B2>HU$xDcChb?I;(%UN2iI+O-Jv`D!*7@?mZnHm3dh;J#I@v z?BT7(J{5Zm;$4(zBW4dVZNz-DnD2|2zL@tOlF^rUJbxoDQ)YbMtQ^ct(<5Sj*&C=m z#OyJohwtARhon*PA(4j&qIUTx0LpN0m*g ztQ*k7d+2ZDb+HM$1K-)k-f4^fE7$~89?jz`_|DrSzKWGE*2nX%v4=S|fp-n-O!F`1 zvA;7h=d589)V|I!UPqN(VsCC=_v%yS?ZxbU6YE>V>}~A#5Ho*k?#u5Jd%xJv{O&w2 zZoRR0wBDQC!@7^N<$F)}6qj%8oyE-it$dgJKI0qO$67`FFNnW`H~e?EE!2H|?@O5O zwvCEM&K-PrTISp(7XM8jYxYp<#O>pL3F>YovHJ|r1pP&g@jhyuxU<~-0qVDL)+;tP LmiLbrK1crphS^Qc diff --git a/examples/shadow/forward.frag b/examples/shadow/forward.frag deleted file mode 100644 index 8a3e2579d..000000000 --- a/examples/shadow/forward.frag +++ /dev/null @@ -1,64 +0,0 @@ -#version 450 - -const int MAX_LIGHTS = 10; - -layout(location = 0) in vec3 v_Normal; -layout(location = 1) in vec4 v_Position; - -layout(location = 0) out vec4 o_Target; - -struct Light { - mat4 proj; - vec4 pos; - vec4 color; -}; - -layout(set = 0, binding = 0) uniform Globals { - mat4 u_ViewProj; - uvec4 u_NumLights; -}; -layout(set = 0, binding = 1) uniform Lights { - Light u_Lights[MAX_LIGHTS]; -}; -layout(set = 0, binding = 2) uniform texture2DArray t_Shadow; -layout(set = 0, binding = 3) uniform samplerShadow s_Shadow; - -layout(set = 1, binding = 0) uniform Entity { - mat4 u_World; - vec4 u_Color; -}; - -float fetch_shadow(int light_id, vec4 homogeneous_coords) { - if (homogeneous_coords.w <= 0.0) { - return 1.0; - } - // compensate for the Y-flip difference between the NDC and texture coordinates - const vec2 flip_correction = vec2(0.5, -0.5); - // compute texture coordinates for shadow lookup - vec4 light_local = vec4( - homogeneous_coords.xy * flip_correction/homogeneous_coords.w + 0.5, - light_id, - homogeneous_coords.z / homogeneous_coords.w - ); - // do the lookup, using HW PCF and comparison - return texture(sampler2DArrayShadow(t_Shadow, s_Shadow), light_local); -} - -void main() { - vec3 normal = normalize(v_Normal); - vec3 ambient = vec3(0.05, 0.05, 0.05); - // accumulate color - vec3 color = ambient; - for (int i=0; iT;d|fWd4Y~FvC(XS9-x42) z+A3P#wbl42#oEsF_s(?2pY`AIHKXI_bM9XDkUjHdt@T}xz4qGs+|YH-n)z8aFPon& z$o`#m*0Sszm@HeA^%Qc~;NHRYt@gQ=^i(LF+88JKG62 zkxz}2R^)l6qt)Gs>GXdWTy6Ytqdw6lraRk>J)Af5DP)DS4j~(b-ksfx+||qv*P1P+ z+Edt2*>v?lqke2?Dt{>ZiFdBk)!ozMgC4e3)Vkkbmivq$3m38nM%y)6RFUh%SZ6YK zzfO#^|9^ko8C!PdiL~zTk>$GDu5w+ua$W7Yb$tY>_2Nv$qkx;P2HTm>B%I5=pFnnQ zUAt1epQF{GywzwoatavpEHRU{soHqTIdPU<$xdQ7i}x|o=-fefb_#B!F*-Wksuy)< zvGeM_+SHMH8?~r=8hOV=yU~86Gf!>TboHKmsyR~3Pp)$>w--0;{hleJxL11fU0pWE z?#FgE`h8<%zqWqAB>ldxUf>$Q_Pw|&V1R$aUQ@7VbADS(OL6vT+;*^w9n6hBd`IOz zwC%&?zH#TVZ`kF1gDdYVSKim2<=od?zXi|f-SvP&z?gU&QQv;$qF>)gxnFJjbua79 zAe~#-v&lvj=ZU+F^MoDy*+X#U^T=7#xb48c~C>ub@}Y z-3QF+!*)L*zmmuW1)pUX;`HF%2VB=Adl|YtSmS)8 z@#g7Qt^ls(bh#24{HlUIzRg}PK{wWOguf4+wJq%aj{U!N^k%%X=>zh{*xNc_jf*+O zMx-_8m4I5D_e$`#6YnCfdFH z>o;nQynWnn#Z}o|iZTzz(+xed;+3tU`WSf5~*<0yv2l}tU z09c&f?Vae(&Rl)Baw^XtuWtXo?a1GQE~n44Xsde;-}<-A_EN*^ISk zc`ns{3*8v`nBCjx&d&ReS-gWTAG3HDT~4@S7B8n+`~}V!>&H3YL-)I%Nily#mowJh z^~w32???LWD9!Id{tfs(j+3wbe&W1i^YzJ+zRB^>~k^F z!*98uy-`v~K&6VE{yni|0>W^Zecl-bV diff --git a/examples/shadow/forward.vert b/examples/shadow/forward.vert deleted file mode 100644 index 5e0293939..000000000 --- a/examples/shadow/forward.vert +++ /dev/null @@ -1,22 +0,0 @@ -#version 450 - -layout(location = 0) in ivec4 a_Pos; -layout(location = 1) in ivec4 a_Normal; - -layout(location = 0) out vec3 v_Normal; -layout(location = 1) out vec4 v_Position; - -layout(set = 0, binding = 0) uniform Globals { - mat4 u_ViewProj; - uvec4 u_NumLights; -}; -layout(set = 1, binding = 0) uniform Entity { - mat4 u_World; - vec4 u_Color; -}; - -void main() { - v_Normal = mat3(u_World) * vec3(a_Normal.xyz); - v_Position = u_World * vec4(a_Pos); - gl_Position = u_ViewProj * v_Position; -} diff --git a/examples/shadow/forward.vert.spv b/examples/shadow/forward.vert.spv deleted file mode 100644 index 9bd02dfae3d0d07909d3d1c8ba557d06fb346247..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1948 zcmZ9MX-^YT6oxO|Kv5Bq#jQ@MJ6bnDlxQSq%7+GPNbuvNN`qsj9W$Nc@-O^L{wlwi z_&zgpO64|Z&N=Tr+kNkaVxd0i+=QESQ*P5`Yt|KnI5+JoscyFRT8%++&{$o2M8r8) zOaqCTai>$eq;Ibi^l?r}s*;x44Xm^0FE z`$>@eaGIp-@L5CuLllPxBaAtQ{&o~bv7(BaFI&`Qj?RB|%jsN4emfcjNf2pb=3&kb zm~>f{A4(sFe!Cm*cjKh{U9Qj!$7at8RKyug{nn17FWG$H86UgDUMo2KoD7s- zbZcp}YN(do573T$s8NlGyFl;d19k z^Mc`5_2qsHquyEh^aZCLKKBMTFMmeblT1ifa-aKWkv}U1f$LF1}Z~43vYBKMAX-~ppUi=4=tY^tJWWx_wRTgi+ zIAafCPX5u+gMIqoXaC1Co}b94w(-iH!vQ$?tJ3fSPCh<&54Ntij3$>wpFcu)dt3U# z=>-Y*0M{=SN$oia_yf@vm_fFVV%smB#a#D zSk7hH;0Vid+TxTqa7Dr_)FzfQaOa+c`=${)@peo0N#1S?1GgFO%I3|`10L^5!03U$A|VHy9=ta&>#;7IyBxopXY#@6L5&Rw cc~ Self { @@ -408,10 +403,10 @@ impl framework::Example for Example { ]; let light_uniform_size = (Self::MAX_LIGHTS * mem::size_of::()) as wgpu::BufferAddress; - let light_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { + let light_storage_buf = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: light_uniform_size, - usage: wgpu::BufferUsage::UNIFORM + usage: wgpu::BufferUsage::STORAGE | wgpu::BufferUsage::COPY_SRC | wgpu::BufferUsage::COPY_DST, mapped_at_creation: false, @@ -424,8 +419,21 @@ impl framework::Example for Example { attributes: &vertex_attr, }; + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION; + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); + let shadow_pass = { - let uniform_size = mem::size_of::() as wgpu::BufferAddress; + let uniform_size = mem::size_of::() as wgpu::BufferAddress; // Create pipeline layout let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -465,14 +473,12 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("bake.vert.spv")); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("shadow"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_bake", buffers: &[vb_desc.clone()], }, fragment: None, @@ -515,11 +521,9 @@ impl framework::Example for Example { ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, - min_binding_size: wgpu::BufferSize::new(mem::size_of::< - ForwardUniforms, - >( - ) - as _), + min_binding_size: wgpu::BufferSize::new( + mem::size_of::() as _, + ), }, count: None, }, @@ -527,7 +531,7 @@ impl framework::Example for Example { binding: 1, // lights visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, + ty: wgpu::BufferBindingType::Storage { read_only: true }, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(light_uniform_size), }, @@ -562,7 +566,7 @@ impl framework::Example for Example { }); let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32); - let forward_uniforms = ForwardUniforms { + let forward_uniforms = GlobalUniforms { proj: *mx_total.as_ref(), num_lights: [lights.len() as u32, 0, 0, 0], }; @@ -582,7 +586,7 @@ impl framework::Example for Example { }, wgpu::BindGroupEntry { binding: 1, - resource: light_uniform_buf.as_entire_binding(), + resource: light_storage_buf.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 2, @@ -597,20 +601,17 @@ impl framework::Example for Example { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("forward.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("forward.frag.spv")); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("main"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[vb_desc], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { @@ -657,7 +658,7 @@ impl framework::Example for Example { shadow_pass, forward_pass, forward_depth: depth_texture.create_view(&wgpu::TextureViewDescriptor::default()), - light_uniform_buf, + light_storage_buf, entity_uniform_buf, entity_bind_group, } @@ -731,7 +732,7 @@ impl framework::Example for Example { self.lights_are_dirty = false; for (i, light) in self.lights.iter().enumerate() { queue.write_buffer( - &self.light_uniform_buf, + &self.light_storage_buf, (i * mem::size_of::()) as wgpu::BufferAddress, bytemuck::bytes_of(&light.to_raw()), ); @@ -751,7 +752,7 @@ impl framework::Example for Example { // The light uniform buffer already has the projection, // let's just copy it over to the shadow uniform buffer. encoder.copy_buffer_to_buffer( - &self.light_uniform_buf, + &self.light_storage_buf, (i * mem::size_of::()) as wgpu::BufferAddress, &self.shadow_pass.uniform_buf, 0, diff --git a/examples/shadow/shader.wgsl b/examples/shadow/shader.wgsl new file mode 100644 index 000000000..a9244df63 --- /dev/null +++ b/examples/shadow/shader.wgsl @@ -0,0 +1,114 @@ +[[location(0)]] +var in_position: vec4; +[[builtin(position)]] +var out_position: vec4; + +[[block]] +struct Globals { + view_proj: mat4x4; + num_lights: vec4; +}; + +[[group(0), binding(0)]] +var u_globals: Globals; + +[[block]] +struct Entity { + world: mat4x4; + color: vec4; +}; + +[[group(1), binding(0)]] +var u_entity: Entity; + +[[stage(vertex)]] +fn vs_bake() { + out_position = u_globals.view_proj * u_entity.world * vec4(in_position); +} + + +[[location(1)]] +var in_normal: vec4; + +[[location(0)]] +var out_normal_vs: vec3; +[[location(1)]] +var out_position_vs: vec4; + +[[stage(vertex)]] +fn vs_main() { + const w: mat4x4 = u_entity.world; + out_normal_vs = mat3x3(w.x.xyz, w.y.xyz, w.z.xyz) * vec3(in_normal.xyz); + out_position_vs = u_entity.world * vec4(in_position); + out_position = u_globals.view_proj * out_position_vs; +} + +// fragment shader + +[[block]] +struct Light { + proj: mat4x4; + pos: vec4; + color: vec4; +}; + +[[block]] +struct Lights { + data: [[stride(96)]] array; +}; + +[[group(0), binding(1)]] +var s_lights: [[access(read)]] Lights; +[[group(0), binding(2)]] +var t_shadow: texture_depth_2d_array; +[[group(0), binding(3)]] +var sampler_shadow: sampler; + +fn fetch_shadow(light_id: u32, homogeneous_coords: vec4) -> f32 { + if (homogeneous_coords.w <= 0.0) { + return 1.0; + } + // compensate for the Y-flip difference between the NDC and texture coordinates + const flip_correction: vec2 = vec2(0.5, -0.5); + // compute texture coordinates for shadow lookup + const proj_correction: f32 = 1.0 / homogeneous_coords.w; + const light_local: vec2 = homogeneous_coords.xy * flip_correction * proj_correction + vec2(0.5, 0.5); + // do the lookup, using HW PCF and comparison + return textureSampleCompare(t_shadow, sampler_shadow, light_local, i32(light_id), homogeneous_coords.z * proj_correction); +} + +[[location(0)]] +var in_normal_fs: vec3; +[[location(1)]] +var in_position_fs: vec4; +[[location(0)]] +var out_color_fs: vec4; + +const c_ambient: vec3 = vec3(0.05, 0.05, 0.05); +const c_max_lights: u32 = 10u; + +[[stage(fragment)]] +fn fs_main() { + const normal: vec3 = normalize(in_normal_fs); + // accumulate color + var color: vec3 = c_ambient; + var i: u32 = 0u; + loop { + if (i >= min(u_globals.num_lights.x, c_max_lights)) { + break; + } + const light: Light = s_lights.data[i]; + // project into the light space + const shadow: f32 = fetch_shadow(i, light.proj * in_position_fs); + // compute Lambertian diffuse term + const light_dir: vec3 = normalize(light.pos.xyz - in_position_fs.xyz); + const diffuse: f32 = max(0.0, dot(normal, light_dir)); + // add light contribution + color = color + shadow * diffuse * light.color.xyz; + continuing { + i = i + 1u; + } + } + // multiply the light by material color + out_color_fs = vec4(color, 1.0) * u_entity.color; +} diff --git a/examples/skybox/main.rs b/examples/skybox/main.rs index c6b6145f9..e5a8a4367 100644 --- a/examples/skybox/main.rs +++ b/examples/skybox/main.rs @@ -1,6 +1,7 @@ #[path = "../framework.rs"] mod framework; +use std::borrow::Cow; use wgpu::util::DeviceExt; const IMAGE_SIZE: u32 = 128; @@ -26,6 +27,8 @@ pub struct Skybox { impl Skybox { fn generate_uniforms(aspect_ratio: f32) -> Uniforms { + use cgmath::SquareMatrix; + let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 10.0); let mx_view = cgmath::Matrix4::look_at_rh( cgmath::Point3::new(1.5f32, -5.0, 3.0), @@ -33,7 +36,8 @@ impl Skybox { cgmath::Vector3::unit_z(), ); let mx_correction = framework::OPENGL_TO_WGPU_MATRIX; - [mx_correction * mx_projection, mx_correction * mx_view] + let proj_inv = (mx_correction * mx_projection).invert().unwrap(); + [proj_inv, mx_correction * mx_view] } } @@ -46,7 +50,7 @@ impl framework::Example for Skybox { fn init( sc_desc: &wgpu::SwapChainDescriptor, - _adapter: &wgpu::Adapter, + adapter: &wgpu::Adapter, device: &wgpu::Device, queue: &wgpu::Queue, ) -> Self { @@ -86,13 +90,23 @@ impl framework::Example for Skybox { }); // Create the render pipeline - let vs_module = device.create_shader_module(&wgpu::include_spirv!("shader.vert.spv")); - let fs_module = device.create_shader_module(&wgpu::include_spirv!("shader.frag.spv")); + let mut flags = wgpu::ShaderFlags::VALIDATION; + match adapter.get_info().backend { + wgpu::Backend::Metal | wgpu::Backend::Vulkan => { + flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION + } + _ => (), //TODO + } + let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))), + flags, + }); let aspect = sc_desc.width as f32 / sc_desc.height as f32; let uniforms = Self::generate_uniforms(aspect); let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some(" Buffer"), + label: Some("Buffer"), contents: bytemuck::cast_slice(&raw_uniforms(&uniforms)), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); @@ -108,13 +122,13 @@ impl framework::Example for Skybox { label: None, layout: Some(&pipeline_layout), vertex: wgpu::VertexState { - module: &vs_module, - entry_point: "main", + module: &shader, + entry_point: "vs_main", buffers: &[], }, fragment: Some(wgpu::FragmentState { - module: &fs_module, - entry_point: "main", + module: &shader, + entry_point: "fs_main", targets: &[sc_desc.format.into()], }), primitive: wgpu::PrimitiveState { diff --git a/examples/skybox/shader.frag b/examples/skybox/shader.frag deleted file mode 100644 index 8c0cee397..000000000 --- a/examples/skybox/shader.frag +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -layout(set = 0, binding = 1) uniform textureCube t_Cubemap; -layout(set = 0, binding = 2) uniform sampler s_Cubemap; - -layout(location = 0) in vec3 v_Uv; -layout(location = 0) out vec4 f_Color; - -void main() { - f_Color = texture(samplerCube(t_Cubemap, s_Cubemap), v_Uv); -} diff --git a/examples/skybox/shader.frag.spv b/examples/skybox/shader.frag.spv deleted file mode 100644 index 65ab23b9adf8b6282447b16eb5467515562ce877..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 684 zcmY+BO-q7N5QQhd%hJr!EC{W=w5SN8HZI(>i)txG1wm${`2+h^ZGxWXeUMFu9K9EBwJuWzoqlj&pkA=f@)&T-(lz3XkMgj~da>U;4|?O*@dx#Mtb?b6-si*9X!y=uZj(Iu$K?{A+2D3Y zDf;t12Lg`RK8FeV!yT}*Tes(OU2NT1t-HsfUmaGylWdb}8r%zTZK8?ZUB&L#=C?%l zwd616*j?pXY`sQSpS~!U`EfpvJ<91d(b_}oUY}XCH?xvVP9F zO5QYyeT~rW61Th+HK|}%ZgAY*z3N02Aj2M)^q@f$LrfvycD)E=M;1!v8 zQ)-Nf@3Xsu8&C6gX5N`OXJ*bRNqN29(F@7CzR45WQb`A#4eGeR7iD6*sSA|)(50<)Y&=D%ezUOS_OUP zB~QaWW%x&t--!36_RitEP7>p}iWJqg=bt2{!F&3^v+%XrK@_w?u{|-*nK2)P(SGpR zC(eA#L%vEgIIafms2(2q=e~UEJ8d@4eawkjvTB+j^X(O;g>Bi^cOka_&B6F>b!ECP z+g-`zQD-&}o7l2od2p6jQ!V)Efm$Xd#|4(zrNoSFW;vGH>{m&3>Sr0p8E{DBI0G)9 z;n3lDN7TZ8#0}{iSrSJK`iL}7vM5|v20dVtThuo%7Y@wG#&=0z&5DKREVwL&727AS zC{QnZT~2lQmDJ{*@Y~+kq&xTJo7uyOy>4fX$R-AG9)61*mF`@*Y_T_F!DVC3cQfVj z+dlNqJ out_position: vec4; +[[location(0)]] var out_uv: vec3; +[[builtin(vertex_index)]] var in_vertex_index: u32; + +[[block]] +struct Data { + proj_inv: mat4x4; + view: mat4x4; +}; +[[group(0), binding(0)]] +var r_data: Data; + +[[stage(vertex)]] +fn vs_main() { + // hacky way to draw a large triangle + var tmp1: i32 = i32(in_vertex_index) / 2; + var tmp2: i32 = i32(in_vertex_index) & 1; + const pos: vec4 = vec4( + f32(tmp1) * 4.0 - 1.0, + f32(tmp2) * 4.0 - 1.0, + 0.0, + 1.0 + ); + + const inv_model_view: mat3x3 = transpose(mat3x3(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz)); + var unprojected: vec4 = r_data.proj_inv * pos; //TODO: const + out_uv = inv_model_view * unprojected.xyz; + out_position = pos; +} + +[[group(0), binding(1)]] +var r_texture: texture_cube; +[[group(0), binding(2)]] +var r_sampler: sampler; + +[[location(0)]] var in_uv: vec3; +[[location(0)]] var out_color: vec4; + +[[stage(fragment)]] +fn fs_main() { + out_color = textureSample(r_texture, r_sampler, in_uv); +} diff --git a/src/backend/web.rs b/src/backend/web.rs index 60eead872..22502bdfa 100644 --- a/src/backend/web.rs +++ b/src/backend/web.rs @@ -1,4 +1,5 @@ use std::{ + collections::HashSet, fmt, future::Future, marker::PhantomData, @@ -1045,7 +1046,14 @@ impl crate::Context for Context { crate::ShaderSource::SpirV(ref spv) => { web_sys::GpuShaderModuleDescriptor::new(&js_sys::Uint32Array::from(&**spv)) } - crate::ShaderSource::Wgsl(_) => panic!("WGSL is not yet supported by the Web backend"), + crate::ShaderSource::Wgsl(ref code) => { + use naga::{back::spv, front::wgsl}; + let module = wgsl::parse_str(code).unwrap(); + let mut capabilities = HashSet::default(); + capabilities.insert(spv::Capability::Shader); + let words = spv::write_vec(&module, spv::WriterFlags::NONE, capabilities).unwrap(); + web_sys::GpuShaderModuleDescriptor::new(&js_sys::Uint32Array::from(&words[..])) + } }; if let Some(ref label) = desc.label { descriptor.label(label); diff --git a/tests/example-wgsl.rs b/tests/example-wgsl.rs new file mode 100644 index 000000000..545987cb8 --- /dev/null +++ b/tests/example-wgsl.rs @@ -0,0 +1,47 @@ +use naga::{front::wgsl, proc::Validator}; +use std::{fs, path::PathBuf}; + +#[test] +fn parse_example_wgsl() { + let read_dir = match PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples") + .read_dir() + { + Ok(iter) => iter, + Err(e) => { + log::error!("Unable to open the examples folder: {:?}", e); + return; + } + }; + for example_entry in read_dir { + let read_files = match example_entry { + Ok(dir_entry) => match dir_entry.path().read_dir() { + Ok(iter) => iter, + Err(_) => continue, + }, + Err(e) => { + log::warn!("Skipping example: {:?}", e); + continue; + } + }; + for file_entry in read_files { + let shader = match file_entry { + Ok(entry) => match entry.path().extension() { + Some(ostr) if &*ostr == "wgsl" => { + println!("Validating {:?}", entry.path()); + fs::read_to_string(entry.path()).unwrap_or_default() + } + _ => continue, + }, + Err(e) => { + log::warn!("Skipping file: {:?}", e); + continue; + } + }; + + let module = wgsl::parse_str(&shader).unwrap(); + //TODO: re-use the validator + Validator::new().validate(&module).unwrap(); + } + } +}