Repository navigation
Expand file tree
/
Copy pathgraphics.rs
More file actions
1238 lines (1082 loc) · 35.8 KB
/
Copy pathgraphics.rs
File metadata and controls
1238 lines (1082 loc) · 35.8 KB
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{ffi::CString, mem};
mod texture;
use crate::sapp::*;
// workaround sapp::* also contains None on Android
use std::option::Option::None;
pub use texture::{
FilterMode, TextureParams, Texture, TextureFormat,
};
fn get_uniform_location(program: GLuint, name: &str) -> i32 {
let cname = CString::new(name).unwrap_or_else(|e| panic!(e));
let location = unsafe { glGetUniformLocation(program, cname.as_ptr()) };
assert!(
location != -1,
format!("Cant get \"{}\" uniform location", name)
);
location
}
#[derive(Clone, Copy, Debug)]
pub enum UniformType {
Float1,
Float2,
Float3,
Float4,
Int1,
Int2,
Int3,
Int4,
Mat4,
}
impl UniformType {
fn size(&self, count: usize) -> usize {
match self {
UniformType::Float1 => 4 * count,
UniformType::Float2 => 8 * count,
UniformType::Float3 => 12 * count,
UniformType::Float4 => 16 * count,
UniformType::Int1 => 4 * count,
UniformType::Int2 => 8 * count,
UniformType::Int3 => 12 * count,
UniformType::Int4 => 16 * count,
UniformType::Mat4 => 64 * count,
}
}
}
pub struct UniformBlockLayout {
pub uniforms: &'static [(&'static str, UniformType)],
}
pub struct ShaderMeta {
pub uniforms: UniformBlockLayout,
pub images: &'static [&'static str],
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum VertexFormat {
Float1,
Float2,
Float3,
Float4,
Byte1,
Byte2,
Byte3,
Byte4,
Short1,
Short2,
Short3,
Short4,
Mat4,
}
impl VertexFormat {
pub fn size(&self) -> i32 {
match self {
VertexFormat::Float1 => 1,
VertexFormat::Float2 => 2,
VertexFormat::Float3 => 3,
VertexFormat::Float4 => 4,
VertexFormat::Byte1 => 1,
VertexFormat::Byte2 => 2,
VertexFormat::Byte3 => 3,
VertexFormat::Byte4 => 4,
VertexFormat::Short1 => 1,
VertexFormat::Short2 => 2,
VertexFormat::Short3 => 3,
VertexFormat::Short4 => 4,
VertexFormat::Mat4 => 16,
}
}
pub fn byte_len(&self) -> i32 {
match self {
VertexFormat::Float1 => 1 * 4,
VertexFormat::Float2 => 2 * 4,
VertexFormat::Float3 => 3 * 4,
VertexFormat::Float4 => 4 * 4,
VertexFormat::Byte1 => 1,
VertexFormat::Byte2 => 2,
VertexFormat::Byte3 => 3,
VertexFormat::Byte4 => 4,
VertexFormat::Short1 => 1 * 2,
VertexFormat::Short2 => 2 * 2,
VertexFormat::Short3 => 3 * 2,
VertexFormat::Short4 => 4 * 2,
VertexFormat::Mat4 => 16 * 4,
}
}
fn type_(&self) -> GLuint {
match self {
VertexFormat::Float1 => GL_FLOAT,
VertexFormat::Float2 => GL_FLOAT,
VertexFormat::Float3 => GL_FLOAT,
VertexFormat::Float4 => GL_FLOAT,
VertexFormat::Byte1 => GL_UNSIGNED_BYTE,
VertexFormat::Byte2 => GL_UNSIGNED_BYTE,
VertexFormat::Byte3 => GL_UNSIGNED_BYTE,
VertexFormat::Byte4 => GL_UNSIGNED_BYTE,
VertexFormat::Short1 => GL_UNSIGNED_SHORT,
VertexFormat::Short2 => GL_UNSIGNED_SHORT,
VertexFormat::Short3 => GL_UNSIGNED_SHORT,
VertexFormat::Short4 => GL_UNSIGNED_SHORT,
VertexFormat::Mat4 => GL_FLOAT,
}
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum VertexStep {
PerVertex,
PerInstance,
}
impl Default for VertexStep {
fn default() -> VertexStep {
VertexStep::PerVertex
}
}
#[derive(Clone, Debug)]
pub struct BufferLayout {
pub stride: i32,
pub step_func: VertexStep,
pub step_rate: i32,
}
impl Default for BufferLayout {
fn default() -> BufferLayout {
BufferLayout {
stride: 0,
step_func: VertexStep::PerVertex,
step_rate: 1,
}
}
}
#[derive(Clone, Debug)]
pub struct VertexAttribute {
pub name: &'static str,
pub format: VertexFormat,
pub buffer_index: usize,
}
impl VertexAttribute {
pub fn new(name: &'static str, format: VertexFormat) -> VertexAttribute {
Self::with_buffer(name, format, 0)
}
pub fn with_buffer(
name: &'static str,
format: VertexFormat,
buffer_index: usize,
) -> VertexAttribute {
VertexAttribute {
name,
format,
buffer_index,
}
}
}
#[derive(Clone, Debug)]
pub struct PipelineLayout {
pub buffers: &'static [BufferLayout],
pub attributes: &'static [VertexAttribute],
}
pub struct Shader(usize);
impl Shader {
pub fn new(
ctx: &mut Context,
vertex_shader: &str,
fragment_shader: &str,
meta: ShaderMeta,
) -> Shader {
let shader = load_shader_internal(vertex_shader, fragment_shader, meta);
ctx.shaders.push(shader);
Shader(ctx.shaders.len() - 1)
}
}
pub struct ShaderImage {
gl_loc: GLint,
}
#[derive(Debug)]
pub struct ShaderUniform {
gl_loc: GLint,
offset: usize,
size: usize,
uniform_type: UniformType,
}
struct ShaderInternal {
program: GLuint,
images: Vec<ShaderImage>,
uniforms: Vec<ShaderUniform>,
}
type BlendState = Option<(Equation, BlendFactor, BlendFactor)>;
type ColorMask = (bool, bool, bool, bool);
#[derive(Default, Copy, Clone)]
struct CachedAttribute {
attribute: VertexAttributeInternal,
gl_vbuf: GLuint,
}
struct GlCache {
stored_index_buffer: GLuint,
stored_vertex_buffer: GLuint,
stored_texture: GLuint,
index_buffer: GLuint,
vertex_buffer: GLuint,
textures: [GLuint; MAX_SHADERSTAGE_IMAGES],
cur_pipeline: Option<Pipeline>,
blend: BlendState,
color_write: ColorMask,
attributes: [Option<CachedAttribute>; MAX_VERTEX_ATTRIBUTES],
}
impl GlCache {
fn bind_buffer(&mut self, target: GLenum, buffer: GLuint) {
if target == GL_ARRAY_BUFFER {
if self.vertex_buffer != buffer {
self.vertex_buffer = buffer;
unsafe {
glBindBuffer(target, buffer);
}
}
} else {
if self.index_buffer != buffer {
self.index_buffer = buffer;
unsafe {
glBindBuffer(target, buffer);
}
}
}
}
fn store_buffer_binding(&mut self, target: GLenum) {
if target == GL_ARRAY_BUFFER {
self.stored_vertex_buffer = self.vertex_buffer;
} else {
self.stored_index_buffer = self.index_buffer;
}
}
fn restore_buffer_binding(&mut self, target: GLenum) {
if target == GL_ARRAY_BUFFER {
self.bind_buffer(target, self.stored_vertex_buffer);
} else {
self.bind_buffer(target, self.stored_index_buffer);
}
}
fn bind_texture(&mut self, slot_index: usize, texture: GLuint) {
unsafe {
glActiveTexture(GL_TEXTURE0 + slot_index as GLuint);
if self.textures[slot_index] != texture {
glBindTexture(GL_TEXTURE_2D, texture);
self.textures[slot_index] = texture;
}
}
}
fn store_texture_binding(&mut self, slot_index: usize) {
self.stored_texture = self.textures[slot_index];
}
fn restore_texture_binding(&mut self, slot_index: usize) {
self.bind_texture(slot_index, self.stored_texture);
}
fn clear_buffer_bindings(&mut self) {
self.bind_buffer(GL_ARRAY_BUFFER, 0);
self.vertex_buffer = 0;
self.bind_buffer(GL_ELEMENT_ARRAY_BUFFER, 0);
self.index_buffer = 0;
}
fn clear_texture_bindings(&mut self) {
for ix in 0..MAX_SHADERSTAGE_IMAGES {
if self.textures[ix] != 0 {
self.bind_texture(ix, 0);
self.textures[ix] = 0;
}
}
}
}
pub enum PassAction {
Nothing,
Clear {
color: Option<(f32, f32, f32, f32)>,
depth: Option<f32>,
stencil: Option<i32>,
},
}
impl PassAction {
pub fn clear_color(r: f32, g: f32, b: f32, a: f32) -> PassAction {
PassAction::Clear {
color: Some((r, g, b, a)),
depth: Some(1.),
stencil: None,
}
}
}
impl Default for PassAction {
fn default() -> PassAction {
PassAction::Clear {
color: Some((0.0, 0.0, 0.0, 0.0)),
depth: Some(1.),
stencil: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RenderPass(usize);
struct RenderPassInternal {
gl_fb: GLuint,
texture: Texture,
}
impl RenderPass {
pub fn new(
context: &mut Context,
color_img: Texture,
depth_img: impl Into<Option<Texture>>,
) -> RenderPass {
A360
let mut gl_fb = 0;
unsafe {
glGenFramebuffers(1, &mut gl_fb as *mut _);
glBindFramebuffer(GL_FRAMEBUFFER, gl_fb);
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D,
color_img.texture,
0,
);
if let Some(depth_img) = depth_img.into() {
glFramebufferTexture2D(
GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D,
depth_img.texture,
0,
);
}
glBindFramebuffer(GL_FRAMEBUFFER, context.default_framebuffer);
}
let pass = RenderPassInternal {
gl_fb,
texture: color_img,
};
context.passes.push(pass);
RenderPass(context.passes.len() - 1)
}
}
pub const MAX_VERTEX_ATTRIBUTES: usize = 16;
pub const MAX_SHADERSTAGE_IMAGES: usize = 12;
pub struct Context {
shaders: Vec<ShaderInternal>,
pipelines: Vec<PipelineInternal>,
passes: Vec<RenderPassInternal>,
default_framebuffer: GLuint,
cache: GlCache,
}
impl Context {
pub fn new() -> Context {
unsafe {
let mut default_framebuffer: GLuint = 0;
glGetIntegerv(
GL_FRAMEBUFFER_BINDING,
&mut default_framebuffer as *mut _ as *mut _,
);
let mut vao = 0;
glGenVertexArrays(1, &mut vao as *mut _);
glBindVertexArray(vao);
Context {
default_framebuffer,
shaders: vec![],
pipelines: vec![],
passes: vec![],
cache: GlCache {
stored_index_buffer: 0,
stored_vertex_buffer: 0,
index_buffer: 0,
vertex_buffer: 0,
cur_pipeline: None,
blend: None,
color_write: (true, true, true, true),
stored_texture: 0,
textures: [0; MAX_SHADERSTAGE_IMAGES],
attributes: [None; MAX_VERTEX_ATTRIBUTES],
},
//attributes: [None; 16],
}
}
}
/// The current framebuffer size in pixels
/// NOTE: [High DPI Rendering](../conf/index.html#high-dpi-rendering)
pub fn screen_size(&self) -> (f32, f32) {
unsafe { (sapp_width() as f32, sapp_height() as f32) }
}
/// The dpi scaling factor (window pixels to framebuffer pixels)
/// NOTE: [High DPI Rendering](../conf/index.html#high-dpi-rendering)
pub fn dpi_scale(&self) -> f32 {
unsafe { sapp_dpi_scale() }
}
/// True when high_dpi was requested and actually running in a high-dpi scenario
/// NOTE: [High DPI Rendering](../conf/index.html#high-dpi-rendering)
pub fn high_dpi(&self) -> bool {
unsafe { sapp_high_dpi() }
}
pub fn apply_pipeline(&mut self, pipeline: &Pipeline) {
self.cache.cur_pipeline = Some(*pipeline);
let pipeline = &mut self.pipelines[pipeline.0];
let shader = &mut self.shaders[pipeline.shader.0];
unsafe {
glUseProgram(shader.program);
}
unsafe {
glEnable(GL_SCISSOR_TEST);
}
if pipeline.params.depth_write {
unsafe {
glEnable(GL_DEPTH_TEST);
glDepthFunc(pipeline.params.depth_test.into())
}
} else {
unsafe {
glDisable(GL_DEPTH_TEST);
}
}
if self.cache.blend != pipeline.params.color_blend {
unsafe {
if let Some((equation, src, dst)) = pipeline.params.color_blend {
if self.cache.blend.is_none() {
glEnable(GL_BLEND);
}
glBlendFunc(src.into(), dst.into());
glBlendEquationSeparate(equation.into(), equation.into());
} else if self.cache.blend.is_some() {
glDisable(GL_BLEND);
}
self.cache.blend = pipeline.params.color_blend;
}
}
if self.cache.color_write != pipeline.params.color_write {
let (r, g, b, a) = pipeline.params.color_write;
unsafe { glColorMask(r as _, g as _, b as _, a as _) }
self.cache.color_write = pipeline.params.color_write;
}
}
pub fn apply_scissor_rect(&mut self, x: i32, y: i32, w: i32, h: i32) {
unsafe {
glScissor(x, y, w, h);
}
}
pub fn apply_bindings(&mut self, bindings: &Bindings) {
let pip = &self.pipelines[self.cache.cur_pipeline.unwrap().0];
let shader = &self.shaders[pip.shader.0];
for (n, shader_image) in shader.images.iter().enumerate() {
let bindings_image = bindings
.images
.get(n)
.unwrap_or_else(|| panic!("Image count in bindings and shader did not match!"));
unsafe {
self.cache.bind_texture(n, bindings_image.texture);
glUniform1i(shader_image.gl_loc, n as i32);
}
}
self.cache
.bind_buffer(GL_ELEMENT_ARRAY_BUFFER, bindings.index_buffer.gl_buf);
let pip = &self.pipelines[self.cache.cur_pipeline.unwrap().0];
for attr_index in 0..MAX_VERTEX_ATTRIBUTES {
let cached_attr = &mut self.cache.attributes[attr_index];
let pip_attribute = pip.layout.get(attr_index).copied();
if let Some(attribute) = pip_attribute {
let vb = bindings.vertex_buffers[attribute.buffer_index];
if cached_attr.map_or(true, |cached_attr| {
attribute != cached_attr.attribute || cached_attr.gl_vbuf != vb.gl_buf
}) {
self.cache.bind_buffer(GL_ARRAY_BUFFER, vb.gl_buf);
unsafe {
glVertexAttribPointer(
attr_index as GLuint,
attribute.size,
attribute.type_,
GL_FALSE as u8,
attribute.stride,
attribute.offset as *mut _,
);
glVertexAttribDivisor(attr_index as GLuint, attribute.divisor as u32);
glEnableVertexAttribArray(attr_index as GLuint);
};
let cached_attr = &mut self.cache.attributes[attr_index];
*cached_attr = Some(CachedAttribute {
attribute,
gl_vbuf: vb.gl_buf,
});
}
} else {
if cached_attr.is_some() {
unsafe {
glDisableVertexAttribArray(attr_index as GLuint);
}
*cached_attr = None;
}
}
}
}
pub fn apply_uniforms<U>(&mut self, uniforms: &U) {
let pip = &self.pipelines[self.cache.cur_pipeline.unwrap().0];
let shader = &self.shaders[pip.shader.0];
let mut offset = 0;
for (_, uniform) in shader.uniforms.iter().enumerate() {
use UniformType::*;
assert!(offset < std::mem::size_of::<U>() - 4);
unsafe {
let data = (uniforms as *const _ as *const f32).offset(offset as isize);
let data_int = (uniforms as *const _ as *const i32).offset(offset as isize);
match uniform.uniform_type {
Float1 => {
glUniform1fv(uniform.gl_loc, 1, data);
}
Float2 => {
glUniform2fv(uniform.gl_loc, 1, data);
}
Float3 => {
glUniform3fv(uniform.gl_loc, 1, data);
}
Float4 => {
glUniform4fv(uniform.gl_loc, 1, data);
}
Int1 => {
glUniform1iv(uniform.gl_loc, 1, data_int);
}
Int2 => {
glUniform2iv(uniform.gl_loc, 1, data_int);
}
Int3 => {
glUniform3iv(uniform.gl_loc, 1, data_int);
}
Int4 => {
glUniform4iv(uniform.gl_loc, 1, data_int);
}
Mat4 => {
glUniformMatrix4fv(uniform.gl_loc, 1, 0, data);
}
}
}
offset += uniform.uniform_type.size(1) / 4;
}
}
pub fn clear(
&self,
color: Option<(f32, f32, f32, f32)>,
depth: Option<f32>,
stencil: Option<i32>,
) {
let mut bits = 0;
if let Some((r, g, b, a)) = color {
bits |= GL_COLOR_BUFFER_BIT;
unsafe {
glClearColor(r, g, b, a);
}
}
if let Some(v) = depth {
bits |= GL_DEPTH_BUFFER_BIT;
unsafe {
glClearDepthf(v);
}
}
if let Some(v) = stencil {
bits |= GL_STENCIL_BUFFER_BIT;
unsafe {
glClearStencil(v);
}
}
if bits != 0 {
unsafe {
glClear(bits);
}
}
}
/// start rendering to the default frame buffer
pub fn begin_default_pass(&mut self, action: PassAction) {
self.begin_pass(None, action);
}
/// start rendering to an offscreen framebuffer
pub fn begin_pass(&mut self, pass: impl Into<Option<RenderPass>>, action: PassAction) {
let (framebuffer, w, h) = match pass.into() {
None => (
self.default_framebuffer,
unsafe { sapp_width() } as i32,
unsafe { sapp_height() } as i32,
),
Some(pass) => {
let pass = &self.passes[pass.0];
(
pass.gl_fb,
pass.texture.width as i32,
pass.texture.height as i32,
)
}
};
unsafe {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
glViewport(0, 0, w, h);
glScissor(0, 0, w, h);
}
match action {
PassAction::Nothing => {}
PassAction::Clear {
color,
depth,
stencil,
} => {
self.clear(color, depth, stencil);
}
}
}
pub fn end_render_pass(&mut self) {
unsafe {
glBindFramebuffer(GL_FRAMEBUFFER, self.default_framebuffer);
self.cache.bind_buffer(GL_ARRAY_BUFFER, 0);
self.cache.bind_buffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
pub fn commit_frame(&mut self) {
self.cache.clear_buffer_bindings();
self.cache.clear_texture_bindings();
}
pub fn draw(&self, base_element: i32, num_elements: i32, num_instances: i32) {
unsafe {
glDrawElementsInstanced(
GL_TRIANGLES,
num_elements,
GL_UNSIGNED_SHORT,
(2 * base_element) as *mut _,
num_instances,
);
}
}
}
fn load_shader_internal(
vertex_shader: &str,
fragment_shader: &str,
meta: ShaderMeta,
) -> ShaderInternal {
unsafe {
let vertex_shader = load_shader(GL_VERTEX_SHADER, vertex_shader);
let fragment_shader = load_shader(GL_FRAGMENT_SHADER, fragment_shader);
let program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
let mut link_status = 0;
glGetProgramiv(program, GL_LINK_STATUS, &mut link_status as *mut _);
if link_status == 0 {
let mut max_length = 100;
let mut error_message = vec![0u8; max_length as usize + 1];
glGetProgramInfoLog(
program,
max_length,
&mut max_length as *mut _,
error_message.as_mut_ptr() as *mut _,
);
let error_message = std::string::String::from_utf8_lossy(&error_message);
panic!("{}", error_message);
}
glUseProgram(program);
#[rustfmt::skip]
let images = meta.images.iter().map(|name| ShaderImage {
gl_loc: get_uniform_location(program, name),
}).collect();
#[rustfmt::skip]
let uniforms = meta.uniforms.uniforms.iter().scan(0, |offset, uniform| {
let res = ShaderUniform {
gl_loc: get_uniform_location(program, uniform.0),
offset: *offset,
size: uniform.1.size(1),
uniform_type: uniform.1
};
*offset += uniform.1.size(1);
Some(res)
}).collect();
ShaderInternal {
program,
images,
uniforms,
}
}
}
pub fn load_shader(shader_type: GLenum, source: &str) -> GLuint {
unsafe {
let shader = glCreateShader(shader_type);
assert!(shader != 0);
let cstring = CString::new(source).unwrap_or_else(|e| panic!(e));
let csource = [cstring];
glShaderSource(shader, 1, csource.as_ptr() as *const _, std::ptr::null());
glCompileShader(shader);
let mut is_compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &mut is_compiled as *mut _);
if is_compiled == 0 {
let mut max_length: i32 = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &mut max_length as *mut _);
let mut error_message = vec![0u8; max_length as usize + 1];
glGetShaderInfoLog(
shader,
max_length,
&mut max_length as *mut _,
error_message.as_mut_ptr() as *mut _,
);
#[cfg(target_arch = "wasm32")]
console_log(error_message.as_ptr() as *const _);
let error_message = std::string::String::from_utf8_lossy(&error_message);
eprintln!("Shader error:\n{}", error_message);
glDeleteShader(shader);
panic!("cant compile shader!");
}
shader
}
}
/// Specify whether front- or back-facing polygons can be culled.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum CullFace {
Nothing,
Front,
Back,
}
/// Define front- and back-facing polygons.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum FrontFaceOrder {
Clockwise,
CounterClockwise,
}
/// A pixel-wise comparison function.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Comparison {
Never,
Less,
LessOrEqual,
Greater,
GreaterOrEqual,
Equal,
NotEqual,
Always,
}
impl From<Comparison> for GLenum {
fn from(cmp: Comparison) -> Self {
match cmp {
Comparison::Never => GL_NEVER,
Comparison::Less => GL_LESS,
Comparison::LessOrEqual => GL_LEQUAL,
Comparison::Greater => GL_GREATER,
Comparison::GreaterOrEqual => GL_GEQUAL,
Comparison::Equal => GL_EQUAL,
Comparison::NotEqual => GL_NOTEQUAL,
Comparison::Always => GL_ALWAYS,
}
}
}
/// Specifies how incoming RGBA values (source) and the RGBA in framebuffer (destination)
/// are combined.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Equation {
/// Adds source and destination. Source and destination are multiplied
/// by blending parameters before addition.
Add,
/// Subtracts destination from source. Source and destination are
/// multiplied by blending parameters before subtraction.
Subtract,
/// Subtracts source from destination. Source and destination are
/// multiplied by blending parameters before subtraction.
ReverseSubtract,
}
/// Blend values.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BlendValue {
SourceColor,
SourceAlpha,
DestinationColor,
DestinationAlpha,
}
/// Blend factors.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BlendFactor {
Zero,
One,
Value(BlendValue),
OneMinusValue(BlendValue),
}
impl From<Equation> for GLenum {
fn from(eq: Equation) -> Self {
match eq {
Equation::Add => GL_FUNC_ADD,
Equation::Subtract => GL_FUNC_SUBTRACT,
Equation::ReverseSubtract => GL_FUNC_REVERSE_SUBTRACT,
}
}
8D9B
div>}
impl From<BlendFactor> for GLenum {
fn from(factor: BlendFactor) -> GLenum {
match factor {
BlendFactor::Zero => GL_ZERO,
BlendFactor:: GL_ONE,
BlendFactor::Value(BlendValue::SourceColor) => GL_SRC_COLOR,
BlendFactor::Value(BlendValue::SourceAlpha) => GL_SRC_ALPHA,
BlendFactor::Value(BlendValue::DestinationColor) => GL_DST_COLOR,
BlendFactor::Value(BlendValue::DestinationAlpha) => GL_DST_ALPHA,
BlendFactor::OneMinusValue(BlendValue::SourceColor) => GL_ONE_MINUS_SRC_COLOR,
BlendFactor::OneMinusValue(BlendValue::SourceAlpha) => GL_ONE_MINUS_SRC_ALPHA,
BlendFactor::OneMinusValue(BlendValue::DestinationColor) => GL_ONE_MINUS_DST_COLOR,
BlendFactor::OneMinusValue(BlendValue::DestinationAlpha) => GL_ONE_MINUS_DST_ALPHA,
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct PipelineParams {
pub cull_face: CullFace,
pub front_face_order: FrontFaceOrder,
pub depth_test: Comparison,
pub depth_write: bool,
pub depth_write_offset: Option<(f32, f32)>,
pub color_blend: BlendState,
pub color_write: ColorMask,
}
#[derive(Copy, Clone, Debug)]
pub struct Pipeline(usize);
impl Default for PipelineParams {
fn default() -> PipelineParams {
PipelineParams {
cull_face: CullFace::Nothing,
front_face_order: FrontFaceOrder::CounterClockwise,
depth_test: Comparison::Always, // no depth test,
depth_write: false, // no depth write,
depth_write_offset: None,
color_blend: None,
color_write: (true, true, true, true),
}
}
}
impl Pipeline {
pub fn new(
ctx: &mut Context,
buffer_layout: &[BufferLayout],
attributes: &[VertexAttribute],
shader: Shader,
) -> Pipeline {
Self::with_params(ctx, buffer_layout, attributes, shader, Default::default())
}
pub fn with_params(
ctx: &mut Context,
buffer_layout: &[BufferLayout],
attributes: &[VertexAttribute],
shader: Shader,
params: PipelineParams,
) -> Pipeline {
#[derive(Clone, Copy, Default)]
struct BufferCacheData {
stride: i32,
offset: i64,
}
let mut buffer_cache: Vec<BufferCacheData> =
vec![BufferCacheData::default(); buffer_layout.len()];
for VertexAttribute {
format,
buffer_index,
..
} in attributes
{
let layout = buffer_layout.get(*buffer_index).unwrap_or_else(|| panic!());
let mut cache = buffer_cache
.get_mut(*buffer_index)
.unwrap_or_else(|| panic!());
if layout.stride == 0 {
cache.stride += format.byte_len();
} else {
cache.stride = layout.stride;
}
// WebGL 1 limitation
assert!(cache.stride <= 255);
}
let program = ctx.shaders[shader.0].program;