lambda_platform/shaderc/
mod.rs1use std::io::Read;
2
3use shaderc;
4pub use shaderc::ShaderKind;
6
7pub struct ShaderCompilerBuilder {}
9
10impl ShaderCompilerBuilder {
11 pub fn new() -> Self {
12 return Self {};
13 }
14
15 pub fn build(self) -> ShaderCompiler {
16 let compiler =
17 shaderc::Compiler::new().expect("Failed to create shaderc compiler.");
18
19 let options = shaderc::CompileOptions::new()
20 .expect("Failed to create shaderc compile options.");
21
22 return ShaderCompiler {
23 compiler,
24 default_options: options,
25 };
26 }
27}
28
29pub struct ShaderCompiler {
31 compiler: shaderc::Compiler,
32 default_options: shaderc::CompileOptions<'static>,
33}
34
35#[derive(Debug, Clone)]
37pub enum VirtualShader {
38 File {
39 path: String,
40 kind: ShaderKind,
41 name: String,
42 entry_point: String,
43 },
44 Source {
45 source: String,
46 kind: ShaderKind,
47 name: String,
48 entry_point: String,
49 },
50}
51
52impl ShaderCompiler {
53 pub fn compile_into_binary(&mut self, shader: &VirtualShader) -> Vec<u32> {
55 return match shader {
56 VirtualShader::File {
57 path,
58 kind,
59 name,
60 entry_point,
61 } => {
62 return self.compile_file_into_binary(
63 path.as_str(),
64 name.as_str(),
65 entry_point.as_str(),
66 kind.clone(),
67 )
68 }
69 VirtualShader::Source {
70 source,
71 kind,
72 name,
73 entry_point,
74 } => self.compile_string_into_binary(
75 source.as_str(),
76 name.as_str(),
77 entry_point.as_str(),
78 kind.clone(),
79 ),
80 };
81 }
82
83 fn compile_file_into_binary(
85 &mut self,
86 path: &str,
87 name: &str,
88 entry_point: &str,
89 shader_kind: ShaderKind,
90 ) -> Vec<u32> {
91 let mut opened_shader_file = std::fs::File::open(path).unwrap();
92 let mut shader_source = String::new();
93 opened_shader_file
94 .read_to_string(&mut shader_source)
95 .unwrap();
96
97 let compiled_shader = self
98 .compiler
99 .compile_into_spirv(
100 &shader_source,
101 shader_kind,
102 path,
103 entry_point,
104 Some(&self.default_options),
105 )
106 .expect("Failed to compile the shader.");
107 return compiled_shader.as_binary().to_vec();
108 }
109
110 fn compile_string_into_binary(
112 &mut self,
113 shader_source: &str,
114 name: &str,
115 entry_point: &str,
116 shader_kind: ShaderKind,
117 ) -> Vec<u32> {
118 let compiled_shader = self
119 .compiler
120 .compile_into_spirv(
121 shader_source,
122 shader_kind,
123 name,
124 entry_point,
125 Some(&self.default_options),
126 )
127 .expect("Failed to compile the shader.");
128
129 return compiled_shader.as_binary().to_vec();
130 }
131}