summaryrefslogtreecommitdiff
path: root/engine/src/shader.rs
blob: 89f7b7c68094cb372f6f91968368f0fe6202a298 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use std::collections::hash_map::DefaultHasher;
use std::fs::read_to_string;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use ecs::Component;

use crate::shader_preprocessor::{Error as ShaderPreprocessorError, ShaderPreprocessor};

const VERTEX_SHADER_FILE: &str = "vertex.glsl";
const FRAGMENT_SHADER_FILE: &str = "fragment.glsl";

const SHADER_DIR: &str = "engine";

/// Shader program
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Component)]
pub struct Program
{
    shaders: Vec<Shader>,
}

impl Program
{
    /// Creates a new shader program with the default shaders.
    ///
    /// # Errors
    /// Returns `Err` if:
    /// - Reading a default shader file Fails
    /// - Preprocessing a shader fails.
    pub fn new() -> Result<Self, Error>
    {
        let mut program = Self { shaders: Vec::new() };

        program.push_shader(
            Shader::read_shader_file(
                Kind::Vertex,
                &Path::new(SHADER_DIR).join(VERTEX_SHADER_FILE),
            )?
            .preprocess()?,
        );

        program.push_shader(
            Shader::read_shader_file(
                Kind::Fragment,
                &Path::new(SHADER_DIR).join(FRAGMENT_SHADER_FILE),
            )?
            .preprocess()?,
        );

        Ok(program)
    }

    pub fn push_shader(&mut self, shader: Shader)
    {
        self.shaders.push(shader);
    }

    pub fn append_shaders(&mut self, shaders: impl IntoIterator<Item = Shader>)
    {
        self.shaders.extend(shaders);
    }

    #[must_use]
    pub fn shaders(&self) -> &[Shader]
    {
        &self.shaders
    }

    pub(crate) fn u64_hash(&self) -> u64
    {
        let mut hasher = DefaultHasher::new();

        self.hash(&mut hasher);

        hasher.finish()
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Shader
{
    kind: Kind,
    source: String,
    file: PathBuf,
}

impl Shader
{
    /// Reads a shader from the specified source file.
    ///
    /// # Errors
    /// Will return `Err` if:
    /// - Reading the file fails
    /// - The shader source is not ASCII
    pub fn read_shader_file(kind: Kind, shader_file: &Path) -> Result<Self, Error>
    {
        let source = read_to_string(shader_file).map_err(|err| Error::ReadFailed {
            source: err,
            shader_file: shader_file.to_path_buf(),
        })?;

        if !source.is_ascii() {
            return Err(Error::SourceNotAscii);
        }

        Ok(Self {
            kind,
            source,
            file: shader_file.to_path_buf(),
        })
    }

    /// Preprocesses the shaders.
    ///
    /// # Errors
    /// Returns `Err` if preprocessing fails.
    pub fn preprocess(self) -> Result<Self, Error>
    {
        let shader_preprocessor = ShaderPreprocessor::new(
            self.file
                .parent()
                .ok_or(Error::SourcePathHasNoParent)?
                .to_path_buf(),
        );

        let source_preprocessed = shader_preprocessor
            .preprocess(self.source, &self.file)
            .map_err(|err| Error::PreprocessFailed {
                source: err,
                shader_file: self.file.clone(),
            })?;

        Ok(Self {
            kind: self.kind,
            source: source_preprocessed,
            file: self.file.clone(),
        })
    }

    #[must_use]
    pub fn kind(&self) -> Kind
    {
        self.kind
    }

    #[must_use]
    pub fn source(&self) -> &str
    {
        &self.source
    }
}

/// Shader kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind
{
    Vertex,
    Fragment,
}

/// Shader error
#[derive(Debug, thiserror::Error)]
pub enum Error
{
    #[error("Failed to read shader {}", shader_file.display())]
    ReadFailed
    {
        #[source]
        source: std::io::Error,
        shader_file: PathBuf,
    },

    #[error("Shader source is not ASCII")]
    SourceNotAscii,

    #[error("Failed to preprocess shader {}", shader_file.display())]
    PreprocessFailed
    {
        #[source]
        source: ShaderPreprocessorError,
        shader_file: PathBuf,
    },

    #[error("Shader source path has no parent")]
    SourcePathHasNoParent,
}