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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use crate::core::*;
use std::collections::HashMap;
use std::sync::RwLock;

///
/// A shader program consisting of a programmable vertex shader followed by a programmable fragment shader.
/// Functionality includes transferring per vertex data to the vertex shader (see the use_attribute functionality)
/// and transferring uniform data to both shader stages (see the use_uniform and use_texture functionality)
/// and execute the shader program (see the draw functionality).
///
pub struct Program {
    context: Context,
    id: crate::context::Program,
    attributes: HashMap<String, u32>,
    textures: RwLock<HashMap<String, u32>>,
    uniforms: HashMap<String, crate::context::UniformLocation>,
    uniform_blocks: RwLock<HashMap<String, (u32, u32)>>,
}

impl Program {
    ///
    /// Creates a new shader program from the given vertex and fragment glsl shader source.
    ///
    pub fn from_source(
        context: &Context,
        vertex_shader_source: &str,
        fragment_shader_source: &str,
    ) -> Result<Self, CoreError> {
        unsafe {
            let vert_shader = context
                .create_shader(crate::context::VERTEX_SHADER)
                .expect("Failed creating vertex shader");
            let frag_shader = context
                .create_shader(crate::context::FRAGMENT_SHADER)
                .expect("Failed creating fragment shader");

            let header: &str = if context.version().is_embedded {
                "#version 300 es
                    #ifdef GL_FRAGMENT_PRECISION_HIGH
                        precision highp float;
                        precision highp int;
                        precision highp sampler2DArray;
                        precision highp sampler3D;
                    #else
                        precision mediump float;
                        precision mediump int;
                        precision mediump sampler2DArray;
                        precision mediump sampler3D;
                    #endif\n"
            } else {
                "#version 330 core\n"
            };
            let vertex_shader_source = format!("{}{}", header, vertex_shader_source);
            let fragment_shader_source = format!("{}{}", header, fragment_shader_source);

            context.shader_source(vert_shader, &vertex_shader_source);
            context.shader_source(frag_shader, &fragment_shader_source);
            context.compile_shader(vert_shader);
            context.compile_shader(frag_shader);

            let id = context.create_program().expect("Failed creating program");
            context.attach_shader(id, vert_shader);
            context.attach_shader(id, frag_shader);
            context.link_program(id);

            if !context.get_program_link_status(id) {
                let log = context.get_shader_info_log(vert_shader);
                if !log.is_empty() {
                    Err(CoreError::ShaderCompilation(
                        "vertex".to_string(),
                        log,
                        vertex_shader_source,
                    ))?;
                }
                let log = context.get_shader_info_log(frag_shader);
                if !log.is_empty() {
                    Err(CoreError::ShaderCompilation(
                        "fragment".to_string(),
                        log,
                        fragment_shader_source,
                    ))?;
                }
                let log = context.get_program_info_log(id);
                if !log.is_empty() {
                    Err(CoreError::ShaderLink(log))?;
                }
                unreachable!();
            }

            context.detach_shader(id, vert_shader);
            context.detach_shader(id, frag_shader);
            context.delete_shader(vert_shader);
            context.delete_shader(frag_shader);

            // Init vertex attributes
            let num_attribs = context.get_active_attributes(id);
            let mut attributes = HashMap::new();
            for i in 0..num_attribs {
                if let Some(crate::context::ActiveAttribute { name, .. }) = context
                    .get_active_attribute(id, i)
                    .filter(|a| !a.name.starts_with("gl_"))
                {
                    if let Some(location) = context.get_attrib_location(id, &name) {
                        attributes.insert(name, location);
                    }
                }
            }

            // Init uniforms
            let num_uniforms = context.get_active_uniforms(id);
            let mut uniforms = HashMap::new();
            for i in 0..num_uniforms {
                if let Some(crate::context::ActiveUniform { name, .. }) = context
                    .get_active_uniform(id, i)
                    .filter(|a| !a.name.starts_with("gl_"))
                {
                    if let Some(location) = context.get_uniform_location(id, &name) {
                        let name = name.split('[').next().unwrap().to_string();
                        uniforms.insert(name, location);
                    }
                }
            }

            Ok(Program {
                context: context.clone(),
                id,
                attributes,
                uniforms,
                uniform_blocks: RwLock::new(HashMap::new()),
                textures: RwLock::new(HashMap::new()),
            })
        }
    }

    ///
    /// Send the given uniform data to this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform int` if the data is an integer, `uniform vec2` if it is of type [Vec2] etc.
    /// The uniform variable is uniformly available across all processing of vertices and fragments.
    ///
    /// # Panic
    /// Will panic if the uniform is not defined or not used in the shader code.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_uniform<T: UniformDataType>(&self, name: &str, data: T) {
        let location = self.get_uniform_location(name);
        T::send_uniform(&self.context, location, &[data]);
        self.unuse_program();
    }

    ///
    /// Calls [Self::use_uniform] if [Self::requires_uniform] returns true.
    ///
    pub fn use_uniform_if_required<T: UniformDataType>(&self, name: &str, data: T) {
        if self.requires_uniform(name) {
            self.use_uniform(name, data);
        }
    }

    ///
    /// Send the given array of uniform data to this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of same type and length as the data, so if the data is an array of three [Vec2], the variable must be `uniform vec2[3]`.
    /// The uniform variable is uniformly available across all processing of vertices and fragments.
    ///
    /// # Panic
    /// Will panic if the uniform is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_uniform_array<T: UniformDataType>(&self, name: &str, data: &[T]) {
        let location = self.get_uniform_location(name);
        T::send_uniform(&self.context, location, data);
        self.unuse_program();
    }

    fn get_uniform_location(&self, name: &str) -> &crate::context::UniformLocation {
        self.use_program();
        self.uniforms.get(name).unwrap_or_else(|| {
            panic!(
                "the uniform {} is sent to the shader but not defined or never used",
                name
            )
        })
    }

    ///
    /// Use the given [Texture2D] in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform sampler2D` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_texture(&self, name: &str, texture: &Texture2D) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use the given [DepthTexture2D] in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform sampler2D` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_depth_texture(&self, name: &str, texture: &DepthTexture2D) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use the given texture array in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform sampler2DArray` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_texture_array(&self, name: &str, texture: &Texture2DArray) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use the given texture array in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform sampler2DArray` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_depth_texture_array(&self, name: &str, texture: &DepthTexture2DArray) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use the given texture cube map in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform samplerCube` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_texture_cube(&self, name: &str, texture: &TextureCubeMap) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use the given texture cube map in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform samplerCube` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_depth_texture_cube(&self, name: &str, texture: &DepthTextureCubeMap) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use the given 3D texture in this shader program and associate it with the given named variable.
    /// The glsl shader variable must be of type `uniform sampler3D` and can only be accessed in the fragment shader.
    ///
    /// # Panic
    /// Will panic if the texture is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_texture_3d(&self, name: &str, texture: &Texture3D) {
        self.use_texture_internal(name);
        texture.bind();
    }

    ///
    /// Use this function if you want to use a texture which was created using low-level context calls and not using the functionality in the [texture] module.
    /// This function is only needed in special cases for example if you have a special source of texture data.
    ///
    pub fn use_raw_texture(&self, name: &str, target: u32, id: crate::context::Texture) {
        self.use_texture_internal(name);
        unsafe {
            self.context.bind_texture(target, Some(id));
        }
    }

    fn use_texture_internal(&self, name: &str) -> u32 {
        if !self.textures.read().unwrap().contains_key(name) {
            let mut map = self.textures.write().unwrap();
            let index = map.len() as u32;
            map.insert(name.to_owned(), index);
        };
        let index = *self.textures.read().unwrap().get(name).unwrap();
        self.use_uniform(name, index as i32);
        unsafe {
            self.context
                .active_texture(crate::context::TEXTURE0 + index);
        }
        index
    }

    ///
    /// Use the given [UniformBuffer] in this shader program and associate it with the given named variable.
    ///
    pub fn use_uniform_block(&self, name: &str, buffer: &UniformBuffer) {
        if !self.uniform_blocks.read().unwrap().contains_key(name) {
            let mut map = self.uniform_blocks.write().unwrap();
            let location = unsafe {
                self.context
                    .get_uniform_block_index(self.id, name)
                    .unwrap_or_else(|| panic!("the uniform block {} is sent to the shader but not defined or never used",
                        name))
            };
            let index = map.len() as u32;
            map.insert(name.to_owned(), (location, index));
        };
        let (location, index) = *self.uniform_blocks.read().unwrap().get(name).unwrap();
        unsafe {
            self.context.uniform_block_binding(self.id, location, index);
            buffer.bind(index);
            self.context
                .bind_buffer(crate::context::UNIFORM_BUFFER, None);
        }
    }

    ///
    /// Uses the given [VertexBuffer] data in this shader program and associates it with the given named variable.
    /// Each value in the buffer is used when rendering one vertex using the [Program::draw_arrays] or [Program::draw_elements] methods.
    /// Therefore the buffer must contain the same number of values as the number of vertices specified in those draw calls.
    ///
    /// # Panic
    /// Will panic if the attribute is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_vertex_attribute(&self, name: &str, buffer: &VertexBuffer) {
        if buffer.count() > 0 {
            buffer.bind();
            let loc = self.location(name);
            unsafe {
                self.context.bind_vertex_array(Some(self.context.vao));
                self.context.enable_vertex_attrib_array(loc);
                if !buffer.normalized()
                    && (buffer.data_type() == crate::context::UNSIGNED_BYTE
                        || buffer.data_type() == crate::context::BYTE
                        || buffer.data_type() == crate::context::UNSIGNED_SHORT
                        || buffer.data_type() == crate::context::SHORT
                        || buffer.data_type() == crate::context::UNSIGNED_INT
                        || buffer.data_type() == crate::context::INT)
                {
                    self.context.vertex_attrib_pointer_i32(
                        loc,
                        buffer.data_size() as i32,
                        buffer.data_type(),
                        0,
                        0,
                    );
                } else {
                    self.context.vertex_attrib_pointer_f32(
                        loc,
                        buffer.data_size() as i32,
                        buffer.data_type(),
                        buffer.normalized(),
                        0,
                        0,
                    );
                }
                self.context.vertex_attrib_divisor(loc, 0);
                self.context.bind_buffer(crate::context::ARRAY_BUFFER, None);
            }
            self.unuse_program();
        }
    }

    ///
    /// Uses the given [InstanceBuffer] data in this shader program and associates it with the given named variable.
    /// Each value in the buffer is used when rendering one instance using the [Program::draw_arrays_instanced] or [Program::draw_elements_instanced] methods.
    /// Therefore the buffer must contain the same number of values as the number of instances specified in those draw calls.
    ///
    /// # Panic
    /// Will panic if the attribute is not defined in the shader code or not used.
    /// In the latter case the variable is removed by the shader compiler.
    ///
    pub fn use_instance_attribute(&self, name: &str, buffer: &InstanceBuffer) {
        if buffer.count() > 0 {
            buffer.bind();
            let loc = self.location(name);
            unsafe {
                self.context.bind_vertex_array(Some(self.context.vao));
                self.context.enable_vertex_attrib_array(loc);
                if !buffer.normalized()
                    && (buffer.data_type() == crate::context::UNSIGNED_BYTE
                        || buffer.data_type() == crate::context::BYTE
                        || buffer.data_type() == crate::context::UNSIGNED_SHORT
                        || buffer.data_type() == crate::context::SHORT
                        || buffer.data_type() == crate::context::UNSIGNED_INT
                        || buffer.data_type() == crate::context::INT)
                {
                    self.context.vertex_attrib_pointer_i32(
                        loc,
                        buffer.data_size() as i32,
                        buffer.data_type(),
                        0,
                        0,
                    );
                } else {
                    self.context.vertex_attrib_pointer_f32(
                        loc,
                        buffer.data_size() as i32,
                        buffer.data_type(),
                        buffer.normalized(),
                        0,
                        0,
                    );
                }
                self.context.vertex_attrib_divisor(loc, 1);
                self.context.bind_buffer(crate::context::ARRAY_BUFFER, None);
            }
            self.unuse_program();
        }
    }

    ///
    /// Draws `count` number of triangles with the given render states and viewport using this shader program.
    /// Requires that all attributes and uniforms have been defined using the use_attribute and use_uniform methods.
    /// Assumes that the data for the three vertices in a triangle is defined contiguous in each vertex buffer.
    /// If you want to use an [ElementBuffer], see [Program::draw_elements].
    ///
    pub fn draw_arrays(&self, render_states: RenderStates, viewport: Viewport, count: u32) {
        self.context.set_viewport(viewport);
        self.context.set_render_states(render_states);
        self.use_program();
        unsafe {
            self.context
                .draw_arrays(crate::context::TRIANGLES, 0, count as i32);
            for location in self.attributes.values() {
                self.context.disable_vertex_attrib_array(*location);
            }
            self.context.bind_vertex_array(None);
        }
        self.unuse_program();

        #[cfg(debug_assertions)]
        self.context
            .error_check()
            .expect("Unexpected rendering error occured")
    }

    ///
    /// Same as [Program::draw_arrays] except it renders 'instance_count' instances of the same set of triangles.
    /// Use the [Program::use_instance_attribute], method to send unique data for each instance to the shader.
    ///
    pub fn draw_arrays_instanced(
        &self,
        render_states: RenderStates,
        viewport: Viewport,
        count: u32,
        instance_count: u32,
    ) {
        self.context.set_viewport(viewport);
        self.context.set_render_states(render_states);
        self.use_program();
        unsafe {
            self.context.draw_arrays_instanced(
                crate::context::TRIANGLES,
                0,
                count as i32,
                instance_count as i32,
            );
            self.context
                .bind_buffer(crate::context::ELEMENT_ARRAY_BUFFER, None);
            for location in self.attributes.values() {
                self.context.disable_vertex_attrib_array(*location);
            }
            self.context.bind_vertex_array(None);
        }
        self.unuse_program();

        #[cfg(debug_assertions)]
        self.context
            .error_check()
            .expect("Unexpected rendering error occured")
    }

    ///
    /// Draws the triangles defined by the given [ElementBuffer] with the given render states and viewport using this shader program.
    /// Requires that all attributes and uniforms have been defined using the use_attribute and use_uniform methods.
    /// If you do not want to use an [ElementBuffer], see [Program::draw_arrays]. If you only want to draw a subset of the triangles in the given [ElementBuffer], see [Program::draw_subset_of_elements].
    ///
    pub fn draw_elements(
        &self,
        render_states: RenderStates,
        viewport: Viewport,
        element_buffer: &ElementBuffer,
    ) {
        self.draw_subset_of_elements(
            render_states,
            viewport,
            element_buffer,
            0,
            element_buffer.count() as u32,
        )
    }

    ///
    /// Draws a subset of the triangles defined by the given [ElementBuffer] with the given render states and viewport using this shader program.
    /// Requires that all attributes and uniforms have been defined using the use_attribute and use_uniform methods.
    /// If you do not want to use an [ElementBuffer], see [Program::draw_arrays].
    ///
    pub fn draw_subset_of_elements(
        &self,
        render_states: RenderStates,
        viewport: Viewport,
        element_buffer: &ElementBuffer,
        first: u32,
        count: u32,
    ) {
        self.context.set_viewport(viewport);
        self.context.set_render_states(render_states);
        self.use_program();
        element_buffer.bind();
        unsafe {
            self.context.draw_elements(
                crate::context::TRIANGLES,
                count as i32,
                element_buffer.data_type(),
                first as i32,
            );
            self.context
                .bind_buffer(crate::context::ELEMENT_ARRAY_BUFFER, None);

            for location in self.attributes.values() {
                self.context.disable_vertex_attrib_array(*location);
            }
            self.context.bind_vertex_array(None);
        }
        self.unuse_program();

        #[cfg(debug_assertions)]
        self.context
            .error_check()
            .expect("Unexpected rendering error occured")
    }

    ///
    /// Same as [Program::draw_elements] except it renders 'instance_count' instances of the same set of triangles.
    /// Use the [Program::use_instance_attribute] method to send unique data for each instance to the shader.
    ///
    pub fn draw_elements_instanced(
        &self,
        render_states: RenderStates,
        viewport: Viewport,
        element_buffer: &ElementBuffer,
        instance_count: u32,
    ) {
        self.draw_subset_of_elements_instanced(
            render_states,
            viewport,
            element_buffer,
            0,
            element_buffer.count() as u32,
            instance_count,
        )
    }

    ///
    /// Same as [Program::draw_subset_of_elements] except it renders 'instance_count' instances of the same set of triangles.
    /// Use the [Program::use_instance_attribute] method to send unique data for each instance to the shader.
    ///
    pub fn draw_subset_of_elements_instanced(
        &self,
        render_states: RenderStates,
        viewport: Viewport,
        element_buffer: &ElementBuffer,
        first: u32,
        count: u32,
        instance_count: u32,
    ) {
        self.context.set_viewport(viewport);
        self.context.set_render_states(render_states);
        self.use_program();
        element_buffer.bind();
        unsafe {
            self.context.draw_elements_instanced(
                crate::context::TRIANGLES,
                count as i32,
                element_buffer.data_type(),
                first as i32,
                instance_count as i32,
            );
            self.context
                .bind_buffer(crate::context::ELEMENT_ARRAY_BUFFER, None);
            for location in self.attributes.values() {
                self.context.disable_vertex_attrib_array(*location);
            }
            self.context.bind_vertex_array(None);
        }
        self.unuse_program();

        #[cfg(debug_assertions)]
        self.context
            .error_check()
            .expect("Unexpected rendering error occured")
    }

    ///
    /// Returns true if this program uses the uniform with the given name.
    ///
    pub fn requires_uniform(&self, name: &str) -> bool {
        self.uniforms.contains_key(name)
    }

    ///
    /// Returns true if this program uses the attribute with the given name.
    ///
    pub fn requires_attribute(&self, name: &str) -> bool {
        self.attributes.contains_key(name)
    }

    fn location(&self, name: &str) -> u32 {
        self.use_program();
        *self.attributes.get(name).unwrap_or_else(|| {
            panic!(
                "the attribute {} is sent to the shader but not defined or never used",
                name
            )
        })
    }

    fn use_program(&self) {
        unsafe {
            self.context.use_program(Some(self.id));
        }
    }

    fn unuse_program(&self) {
        unsafe {
            self.context.use_program(None);
        }
    }
}

impl Drop for Program {
    fn drop(&mut self) {
        unsafe {
            self.context.delete_program(self.id);
        }
    }
}