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
This commit is contained in:
Dzmitry Malyshau authored and Dzmitry Malyshau committed 2021-01-30 01:02:04 -05:00
1 parent c45fbce8b4
commit 74eed253d8
57 files changed
+712 -476

No files matched your search

+12 -8
View File
@@ -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"
+1 -1
View File
@@ -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
-78
View File
@@ -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;
}
Binary file not shown.
+113
View File
@@ -0,0 +1,113 @@
// This should match `NUM_PARTICLES` on the Rust side.
const NUM_PARTICLES: u32 = 1500;
[[block]]
struct Particle {
pos : vec2<f32>;
vel : vec2<f32>;
};
[[block]]
struct SimParams {
deltaT : f32;
rule1Distance : f32;
rule2Distance : f32;
rule3Distance : f32;
rule1Scale : f32;
rule2Scale : f32;
rule3Scale : f32;
};
[[block]]
struct Particles {
particles : [[stride(16)]] array<Particle>;
};
[[group(0), binding(0)]] var<uniform> params : SimParams;
[[group(0), binding(1)]] var<storage> particlesSrc : [[access(read)]] Particles;
[[group(0), binding(2)]] var<storage> particlesDst : [[access(read_write)]] Particles;
[[builtin(global_invocation_id)]] var gl_GlobalInvocationID : vec3<u32>;
// 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<f32> = particlesSrc.particles[index].pos;
var vVel : vec2<f32> = particlesSrc.particles[index].vel;
var cMass : vec2<f32> = vec2<f32>(0.0, 0.0);
var cVel : vec2<f32> = vec2<f32>(0.0, 0.0);
var colVel : vec2<f32> = vec2<f32>(0.0, 0.0);
var cMassCount : i32 = 0;
var cVelCount : i32 = 0;
var pos : vec2<f32>;
var vel : vec2<f32>;
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;
}
+26
View File
@@ -0,0 +1,26 @@
[[location(0)]]
var<in> in_particle_pos: vec2<f32>;
[[location(1)]]
var<in> in_particle_vel: vec2<f32>;
[[location(2)]]
var<in> in_position: vec2<f32>;
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[stage(vertex)]]
fn main() {
const angle: f32 = -atan2(in_particle_vel.x, in_particle_vel.y);
const pos: vec2<f32> = vec2<f32>(
in_position.x * cos(angle) - in_position.y * sin(angle),
in_position.x * sin(angle) + in_position.y * cos(angle)
);
out_position = vec4<f32>(pos + in_particle_pos, 0.0, 1.0);
}
[[location(0)]]
var<out> out_color: vec4<f32>;
[[stage(fragment)]]
fn main() {
out_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
}
+25 -11
View File
@@ -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::<f32>()) as _,
(sim_param_data.len() * mem::size_of::<f32>()) 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",
});
-5
View File
@@ -1,5 +0,0 @@
#version 450
layout(location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(1.0);
}
Binary file not shown.
-11
View File
@@ -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);
}
Binary file not shown.
+22 -18
View File
@@ -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<Vertex>, Vec<u16>) {
}
fn create_texels(size: usize) -> Vec<u8> {
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::<Vertex>();
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 {
-12
View File
@@ -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);
}
Binary file not shown.
-14
View File
@@ -1,14 +0,0 @@
#version 450
layout(location = 0) in vec4 a_Pos;
layout(location = 1) in vec2 a_TexCoord;
layout(location = 0) out vec2 v_TexCoord;
layout(set = 0, binding = 0) uniform Locals {
mat4 u_Transform;
};
void main() {
v_TexCoord = a_TexCoord;
gl_Position = u_Transform * a_Pos;
}
Binary file not shown.
+44
View File
@@ -0,0 +1,44 @@
[[location(0)]]
var<in> in_position: vec4<f32>;
[[location(1)]]
var<in> in_tex_coord_vs: vec2<f32>;
[[location(0)]]
var<out> out_tex_coord: vec2<f32>;
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[block]]
struct Locals {
transform: mat4x4<f32>;
};
[[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> in_tex_coord_fs: vec2<f32>;
[[location(0)]]
var<out> out_color: vec4<f32>;
[[group(0), binding(1)]]
var r_color: texture_2d<f32>;
[[group(0), binding(2)]]
var r_sampler: sampler;
[[stage(fragment)]]
fn fs_main() {
var tex: vec4<f32> = 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<f32>(0.5, 0.5));
//out_color = vec4<f32>(mix(tex.xyz, vec3<f32>(0.0, 0.0, 0.0), mag*mag), 1.0);
}
[[stage(fragment)]]
fn fs_wire() {
out_color = vec4<f32>(0.0, 0.5, 0.0, 0.5);
}
-7
View File
@@ -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);
}
Binary file not shown.
+13 -2
View File
@@ -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<u32>) -> Vec<u32> {
.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::<u32>();
-31
View File
@@ -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]);
}
Binary file not shown.
+39
View File
@@ -0,0 +1,39 @@
[[builtin(global_invocation_id)]]
var global_id: vec3<u32>;
[[block]]
struct PrimeIndices {
data: [[stride(4)]] array<u32>;
}; // this is used as both input and output for convenience
[[group(0), binding(0)]]
var<storage> 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]);
}
+1 -1
View File
@@ -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 {
-10
View File
@@ -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);
}
Binary file not shown.
-16
View File
@@ -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);
}
Binary file not shown.
+36
View File
@@ -0,0 +1,36 @@
[[builtin(vertex_index)]]
var<in> in_vertex_index: u32;
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[location(0)]]
var<out> out_tex_coords_vs: vec2<f32>;
[[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>(
f32(x) * 2.0,
f32(y) * 2.0
);
out_position = vec4<f32>(
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> in_tex_coord_fs: vec2<f32>;
[[location(0)]]
var<out> out_color_fs: vec4<f32>;
[[group(0), binding(0)]]
var r_color: texture_2d<f32>;
[[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);
}
-10
View File
@@ -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);
}
Binary file not shown.
-13
View File
@@ -1,13 +0,0 @@
#version 450
layout(location = 0) in vec4 a_Pos;
layout(location = 0) out vec2 v_TexCoord;
layout(set = 0, binding = 0) uniform Locals {
mat4 u_Transform;
};
void main() {
v_TexCoord = a_Pos.xy / 20.0 + 0.5;
gl_Position = u_Transform * a_Pos;
}
Binary file not shown.
+34
View File
@@ -0,0 +1,34 @@
[[location(0)]]
var<in> in_position_vs: vec4<f32>;
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[location(0)]]
var<out> out_tex_coords_vs: vec2<f32>;
[[block]]
struct Locals {
transform: mat4x4<f32>;
};
[[group(0), binding(0)]]
var r_data: Locals;
[[stage(vertex)]]
fn vs_main() {
out_tex_coords_vs = 0.05 * in_position_vs.xy + vec2<f32>(0.5, 0.5);
out_position = r_data.transform * in_position_vs;
}
[[location(0)]]
var<in> in_tex_coord_fs: vec2<f32>;
[[location(0)]]
var<out> out_color_fs: vec4<f32>;
[[group(0), binding(1)]]
var r_color: texture_2d<f32>;
[[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);
}
+28 -13
View File
@@ -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<QuerySets>,
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()));
+23 -18
View File
@@ -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::<Vertex>() 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,
-8
View File
@@ -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;
}
Binary file not shown.
-10
View File
@@ -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;
}
Binary file not shown.
+24
View File
@@ -0,0 +1,24 @@
[[location(0)]]
var<in> in_position: vec2<f32>;
[[location(1)]]
var<in> in_color_vs: vec4<f32>;
[[location(0)]]
var<out> out_color_vs: vec4<f32>;
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[stage(vertex)]]
fn vs_main() {
out_position = vec4<f32>(in_position, 0.0, 1.0);
out_color_vs = in_color_vs;
}
[[location(0)]]
var<in> in_color_fs: vec4<f32>;
[[location(0)]]
var<out> out_color_fs: vec4<f32>;
[[stage(fragment)]]
fn fs_main() {
out_color_fs = in_color_fs;
}
-16
View File
@@ -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);
}
Binary file not shown.
-64
View File
@@ -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; i<int(u_NumLights.x) && i<MAX_LIGHTS; ++i) {
Light light = u_Lights[i];
// project into the light space
float shadow = fetch_shadow(i, light.proj * v_Position);
// compute Lambertian diffuse term
vec3 light_dir = normalize(light.pos.xyz - v_Position.xyz);
float diffuse = max(0.0, dot(normal, light_dir));
// add light contribution
color += shadow * diffuse * light.color.xyz;
}
// multiply the light by material color
o_Target = vec4(color, 1.0) * u_Color;
}
Binary file not shown.
-22
View File
@@ -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;
}
Binary file not shown.
+35 -34
View File
@@ -1,4 +1,4 @@
use std::{iter, mem, num::NonZeroU32, ops::Range, rc::Rc};
use std::{borrow::Cow, iter, mem, num::NonZeroU32, ops::Range, rc::Rc};
#[path = "../framework.rs"]
mod framework;
@@ -135,7 +135,7 @@ impl Light {
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct ForwardUniforms {
struct GlobalUniforms {
proj: [[f32; 4]; 4],
num_lights: [u32; 4],
}
@@ -147,11 +147,6 @@ struct EntityUniforms {
color: [f32; 4],
}
#[repr(C)]
struct ShadowUniforms {
proj: [[f32; 4]; 4],
}
struct Pass {
pipeline: wgpu::RenderPipeline,
bind_group: wgpu::BindGroup,
@@ -166,7 +161,7 @@ struct Example {
forward_pass: Pass,
forward_depth: wgpu::TextureView,
entity_bind_group: wgpu::BindGroup,
light_uniform_buf: wgpu::Buffer,
light_storage_buf: wgpu::Buffer,
entity_uniform_buf: wgpu::Buffer,
}
@@ -199,7 +194,7 @@ impl framework::Example for Example {
fn init(
sc_desc: &wgpu::SwapChainDescriptor,
_adapter: &wgpu::Adapter,
adapter: &wgpu::Adapter,
device: &wgpu::Device,
_queue: &wgpu::Queue,
) -> Self {
@@ -408,10 +403,10 @@ impl framework::Example for Example {
];
let light_uniform_size =
(Self::MAX_LIGHTS * mem::size_of::<LightRaw>()) 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::<ShadowUniforms>() as wgpu::BufferAddress;
let uniform_size = mem::size_of::<GlobalUniforms>() 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::<GlobalUniforms>() 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::<LightRaw>()) 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::<LightRaw>()) as wgpu::BufferAddress,
&self.shadow_pass.uniform_buf,
0,
+114
View File
@@ -0,0 +1,114 @@
[[location(0)]]
var<in> in_position: vec4<i32>;
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[block]]
struct Globals {
view_proj: mat4x4<f32>;
num_lights: vec4<u32>;
};
[[group(0), binding(0)]]
var<uniform> u_globals: Globals;
[[block]]
struct Entity {
world: mat4x4<f32>;
color: vec4<f32>;
};
[[group(1), binding(0)]]
var<uniform> u_entity: Entity;
[[stage(vertex)]]
fn vs_bake() {
out_position = u_globals.view_proj * u_entity.world * vec4<f32>(in_position);
}
[[location(1)]]
var<in> in_normal: vec4<i32>;
[[location(0)]]
var<out> out_normal_vs: vec3<f32>;
[[location(1)]]
var<out> out_position_vs: vec4<f32>;
[[stage(vertex)]]
fn vs_main() {
const w: mat4x4<f32> = u_entity.world;
out_normal_vs = mat3x3<f32>(w.x.xyz, w.y.xyz, w.z.xyz) * vec3<f32>(in_normal.xyz);
out_position_vs = u_entity.world * vec4<f32>(in_position);
out_position = u_globals.view_proj * out_position_vs;
}
// fragment shader
[[block]]
struct Light {
proj: mat4x4<f32>;
pos: vec4<f32>;
color: vec4<f32>;
};
[[block]]
struct Lights {
data: [[stride(96)]] array<Light>;
};
[[group(0), binding(1)]]
var<storage> 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>) -> 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<f32> = vec2<f32>(0.5, -0.5);
// compute texture coordinates for shadow lookup
const proj_correction: f32 = 1.0 / homogeneous_coords.w;
const light_local: vec2<f32> = homogeneous_coords.xy * flip_correction * proj_correction + vec2<f32>(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> in_normal_fs: vec3<f32>;
[[location(1)]]
var<in> in_position_fs: vec4<f32>;
[[location(0)]]
var<out> out_color_fs: vec4<f32>;
const c_ambient: vec3<f32> = vec3<f32>(0.05, 0.05, 0.05);
const c_max_lights: u32 = 10u;
[[stage(fragment)]]
fn fs_main() {
const normal: vec3<f32> = normalize(in_normal_fs);
// accumulate color
var color: vec3<f32> = 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<f32> = 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<f32>(color, 1.0) * u_entity.color;
}
+23 -9
View File
@@ -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 {
-11
View File
@@ -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);
}
Binary file not shown.
-22
View File
@@ -1,22 +0,0 @@
#version 450
layout(location = 0) out vec3 v_Uv;
layout(set = 0, binding = 0) uniform Data {
mat4 proj;
mat4 view;
};
void main() {
vec4 pos = vec4(0.0);
switch(gl_VertexIndex) {
case 0: pos = vec4(-1.0, -1.0, 0.0, 1.0); break;
case 1: pos = vec4( 3.0, -1.0, 0.0, 1.0); break;
case 2: pos = vec4(-1.0, 3.0, 0.0, 1.0); break;
}
mat3 invModelView = transpose(mat3(view));
vec3 unProjected = (inverse(proj) * pos).xyz;
v_Uv = invModelView * unProjected;
gl_Position = pos;
}
Binary file not shown.
+43
View File
@@ -0,0 +1,43 @@
[[builtin(position)]]
var<out> out_position: vec4<f32>;
[[location(0)]] var<out> out_uv: vec3<f32>;
[[builtin(vertex_index)]] var<in> in_vertex_index: u32;
[[block]]
struct Data {
proj_inv: mat4x4<f32>;
view: mat4x4<f32>;
};
[[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<f32> = vec4<f32>(
f32(tmp1) * 4.0 - 1.0,
f32(tmp2) * 4.0 - 1.0,
0.0,
1.0
);
const inv_model_view: mat3x3<f32> = transpose(mat3x3<f32>(r_data.view.x.xyz, r_data.view.y.xyz, r_data.view.z.xyz));
var unprojected: vec4<f32> = 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<f32>;
[[group(0), binding(2)]]
var r_sampler: sampler;
[[location(0)]] var<in> in_uv: vec3<f32>;
[[location(0)]] var<out> out_color: vec4<f32>;
[[stage(fragment)]]
fn fs_main() {
out_color = textureSample(r_texture, r_sampler, in_uv);
}
+9 -1
View File
@@ -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);
+47
View File
@@ -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();
}
}
}