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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use vulkano::device::{Device, Queue};
use vulkano::instance::{PhysicalDevice, QueueFamily};
use vulkano::pipeline::{GraphicsPipeline, GraphicsPipelineAbstract, GraphicsPipelineBuilder};
use std::sync::Arc;
use std::ffi::CStr;
use std::path::PathBuf;
use shade_runner as sr;
use vulkano::framebuffer::{Subpass, RenderPassAbstract, Framebuffer, FramebufferAbstract};
use vulkano::pipeline::shader::{GraphicsShaderType, ShaderModule, SpecializationConstants, SpecializationMapEntry};
use vulkano::swapchain::Capabilities;
use crate::vertex_2d::{ColoredVertex2D, Vertex2D};

/// Typed wrapper for a u32 shader handle (index id)
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct CanvasShaderHandle {
    pub handle: u32
}

/// CanvasShader holds the pipeline and render pass for the input shader source
#[derive(Clone)]
pub struct CanvasShader {

    graphics_pipeline: Option<Arc<dyn GraphicsPipelineAbstract + Sync + Send>>,

    device: Arc<Device>,
    pub(crate) handle: Arc<CanvasShaderHandle>,
    pub(crate) name: String,
}

impl CanvasShader {
    /// Takes the filename of a .vertex .fragment shader combo in resources/shaders/
    /// Returns pathbuffer of that vertex and fragment shader
    fn get_path(filename: String) -> (PathBuf, PathBuf) {
        let project_root =
            std::env::current_dir()
                .expect("failed to get root directory");

        let mut shader_path = project_root.clone();
        shader_path.push(PathBuf::from("resources/shaders/"));

        let mut vertex_shader_path = project_root.clone();
        vertex_shader_path.push(PathBuf::from("resources/shaders/"));
        vertex_shader_path.push(PathBuf::from(filename.clone() + ".vertex"));

        let mut fragment_shader_path = project_root.clone();
        fragment_shader_path.push(PathBuf::from("resources/shaders/"));
        fragment_shader_path.push(PathBuf::from(filename.clone() + ".fragment"));

        (vertex_shader_path, fragment_shader_path)
    }

    /// Clone and returns the compiled graphics pipeline
    pub fn get_pipeline(&self) -> Arc<dyn GraphicsPipelineAbstract + Sync + Send> {
        self.graphics_pipeline.clone().unwrap()
    }

    /// Create a new `Colored` shader. Which just means that it uses ColoredVertex2D's
    /// This will explode when the shader does not want to compile
    pub fn new_colored(filename: String,
                       capabilities: Capabilities,
                       queue: Arc<Queue>,
                       physical: PhysicalDevice,
                       device: Arc<Device>,
                       handle: Arc<CanvasShaderHandle>,
                       render_pass: Arc<dyn RenderPassAbstract + Send + Sync>,) -> CanvasShader {

        let format = capabilities.supported_formats[0].0;

        let filenames = CanvasShader::get_path(filename.clone());

        // TODO: better compile message, run til successful compile
        let shader = sr::load(filenames.0, filenames.1)
            .expect("Shader didn't compile");

        let vulkano_entry =
            sr::parse(&shader)
                .expect("failed to parse");

        let fragment_shader_module: Arc<ShaderModule> = unsafe {
            let filenames1 = CanvasShader::get_path(filename.clone());
            let shader1 = sr::load(filenames1.0, filenames1.1)
                .expect("Shader didn't compile");
            vulkano::pipeline::shader::ShaderModule::from_words(device.clone(), &shader1.fragment.clone())
        }.unwrap();

        let vertex_shader_module: Arc<ShaderModule> = unsafe {
            let filenames1 = CanvasShader::get_path(filename.clone());
            let shader1 = sr::load(filenames1.0, filenames1.1)
                .expect("Shader didn't compile");
            vulkano::pipeline::shader::ShaderModule::from_words(device.clone(), &shader1.vertex.clone())
        }.unwrap();

        let filenames = CanvasShader::get_path(filename.clone());


        let frag_entry_point = unsafe {
            Some(fragment_shader_module.graphics_entry_point(CStr::from_bytes_with_nul_unchecked(b"main\0"),
                                                             vulkano_entry.frag_input,
                                                             vulkano_entry.frag_output,
                                                             vulkano_entry.frag_layout,
                                                             GraphicsShaderType::Fragment))
        };

        let vertex_entry_point = unsafe {
            Some(vertex_shader_module.graphics_entry_point(CStr::from_bytes_with_nul_unchecked(b"main\0"),
                                                           vulkano_entry.vert_input,
                                                           vulkano_entry.vert_output,
                                                           vulkano_entry.vert_layout,
                                                           GraphicsShaderType::Vertex))
        };


        let render_pass = Arc::new(vulkano::single_pass_renderpass!(
            device.clone(),

            // Attachments are outgoing like f_color
            attachments: {
                // `color` is a custom name we give to the first and only attachment.
                color: {
                    // `load: Clear` means that we ask the GPU to clear the content of this
                    // attachment at the start of the drawing.
                    load: Clear,
                    // `store: Store` means that we ask the GPU to store the output of the draw
                    // in the actual image. We could also ask it to discard the result.
                    store: Store,
                    // `format: <ty>` indicates the type of the format of the image. This has to
                    // be one of the types of the `vulkano::format` module (or alternatively one
                    // of your structs that implements the `FormatDesc` trait). Here we use the
                    // same format as the swapchain.
                    format: format,
                    // TODO:
                    samples: 1,
                }
            },
            pass: {
                // We use the attachment named `color` as the one and only color attachment.
                color: [color],
                //color: [],
                // No depth-stencil attachment is indicated with empty brackets.
                depth_stencil: {}
            }
        ).unwrap());


        CanvasShader {
            graphics_pipeline: Some(Arc::new(GraphicsPipeline::start()

                .vertex_input_single_buffer::<ColoredVertex2D>()

                .vertex_shader(vertex_entry_point.clone().unwrap(), ShaderSpecializationConstants {
                    first_constant: 0,
                    second_constant: 0,
                    third_constant: 0.0,
                })

                .triangle_list()
                // Use a resizable viewport set to draw over the entire window
                .viewports_dynamic_scissors_irrelevant(1)

                .fragment_shader(frag_entry_point.clone().unwrap(), ShaderSpecializationConstants {
                    first_constant: 0,
                    second_constant: 0,
                    third_constant: 0.0,
                })
                // We have to indicate which subpass of which render pass this pipeline is going to be used
                // in. The pipeline will only be usable from this particular subpass.
                .render_pass(Subpass::from(render_pass.clone(), 0).unwrap())

                .build(device.clone())
                .unwrap())),

            device: device,
            handle: handle.clone(),
            name: filename.clone(),
        }
    }

    /// Create a new `Textured` shader. Which just means that it uses plain Vertex2D's
    /// This will explode when the shader does not want to compile
    pub fn new_textured(filename: String,
                        capabilities: Capabilities,
                        queue: Arc<Queue>,
                        physical: PhysicalDevice,
                        device: Arc<Device>,
                        handle: Arc<CanvasShaderHandle>,
                        render_pass: Arc<dyn RenderPassAbstract + Send + Sync>,) -> CanvasShader {

        let format = capabilities.supported_formats[0].0;

        let filenames = CanvasShader::get_path(filename.clone());

        // TODO: better compile message, run til successful compile
        let shader = sr::load(filenames.0, filenames.1)
            .expect("Shader didn't compile");

        let vulkano_entry =
            sr::parse(&shader)
                .expect("failed to parse");

        let fragment_shader_module: Arc<ShaderModule> = unsafe {
            let filenames1 = CanvasShader::get_path(filename.clone());
            let shader1 = sr::load(filenames1.0, filenames1.1)
                .expect("Shader didn't compile");
            vulkano::pipeline::shader::ShaderModule::from_words(device.clone(), &shader1.fragment.clone())
        }.unwrap();

        let vertex_shader_module: Arc<ShaderModule> = unsafe {
            let filenames1 = CanvasShader::get_path(filename.clone());
            let shader1 = sr::load(filenames1.0, filenames1.1)
                .expect("Shader didn't compile");
            vulkano::pipeline::shader::ShaderModule::from_words(device.clone(), &shader1.vertex.clone())
        }.unwrap();

        let filenames = CanvasShader::get_path(filename.clone());


        let frag_entry_point = unsafe {
            Some(fragment_shader_module.graphics_entry_point(CStr::from_bytes_with_nul_unchecked(b"main\0"),
                                                             vulkano_entry.frag_input,
                                                             vulkano_entry.frag_output,
                                                             vulkano_entry.frag_layout,
                                                             GraphicsShaderType::Fragment))
        };

        let vertex_entry_point = unsafe {
            Some(vertex_shader_module.graphics_entry_point(CStr::from_bytes_with_nul_unchecked(b"main\0"),
                                                           vulkano_entry.vert_input,
                                                           vulkano_entry.vert_output,
                                                           vulkano_entry.vert_layout,
                                                           GraphicsShaderType::Vertex))
        };

        CanvasShader {
            graphics_pipeline: Some(Arc::new(GraphicsPipeline::start()

                .vertex_input_single_buffer::<Vertex2D>()

                .vertex_shader(vertex_entry_point.clone().unwrap(), ShaderSpecializationConstants {
                    first_constant: 0,
                    second_constant: 0,
                    third_constant: 0.0,
                })

                .triangle_list()
                // Use a resizable viewport set to draw over the entire window
                .viewports_dynamic_scissors_irrelevant(1)

                .fragment_shader(frag_entry_point.clone().unwrap(), ShaderSpecializationConstants {
                    first_constant: 0,
                    second_constant: 0,
                    third_constant: 0.0,
                })
                // We have to indicate which subpass of which render pass this pipeline is going to be used
                // in. The pipeline will only be usable from this particular subpass.
                .render_pass(Subpass::from(render_pass.clone(), 0).unwrap())

                .build(device.clone())
                .unwrap())),

            device: device,
            handle: handle.clone(),
            name: filename.clone(),
        }
    }
}

#[repr(C)]
#[derive(Default, Debug, Clone)]
/// Specialization constants which can be passed to the shader. Pretty much placeholder ATM
struct ShaderSpecializationConstants {
    first_constant: i32,
    second_constant: u32,
    third_constant: f32,
}

unsafe impl SpecializationConstants for ShaderSpecializationConstants {
    fn descriptors() -> &'static [SpecializationMapEntry] {
        static DESCRIPTORS: [SpecializationMapEntry; 3] = [
            SpecializationMapEntry {
                constant_id: 0,
                offset: 0,
                size: 4,
            },
            SpecializationMapEntry {
                constant_id: 1,
                offset: 4,
                size: 4,
            },
            SpecializationMapEntry {
                constant_id: 2,
                offset: 8,
                size: 4,
            },
        ];

        &DESCRIPTORS
    }
}