1use std::borrow::Cow;
4
5use wgpu::{Device, ShaderModule, ShaderModuleDescriptor, ShaderSource};
6
7#[derive(Debug)]
9pub struct Shader {
10 module: ShaderModule,
11}
12
13impl Shader {
14 #[must_use]
16 pub fn from_wgsl(device: &Device, source: &str, label: Option<&str>) -> Self {
17 let module = device.create_shader_module(ShaderModuleDescriptor {
18 label,
19 source: ShaderSource::Wgsl(Cow::Borrowed(source)),
20 });
21
22 Self { module }
23 }
24
25 #[must_use]
27 pub fn from_wgsl_owned(device: &Device, source: String, label: Option<&str>) -> Self {
28 let module = device.create_shader_module(ShaderModuleDescriptor {
29 label,
30 source: ShaderSource::Wgsl(Cow::Owned(source)),
31 });
32
33 Self { module }
34 }
35
36 #[must_use]
38 pub fn module(&self) -> &ShaderModule {
39 &self.module
40 }
41}
42
43pub const TRIANGLE_SHADER: &str = r"
45struct VertexInput {
46 @location(0) position: vec3<f32>,
47 @location(1) color: vec3<f32>,
48}
49
50struct VertexOutput {
51 @builtin(position) clip_position: vec4<f32>,
52 @location(0) color: vec3<f32>,
53}
54
55@vertex
56fn vs_main(in: VertexInput) -> VertexOutput {
57 var out: VertexOutput;
58 out.clip_position = vec4<f32>(in.position, 1.0);
59 out.color = in.color;
60 return out;
61}
62
63@fragment
64fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
65 return vec4<f32>(in.color, 1.0);
66}
67";