forked from servo/webrender
-
Notifications
You must be signed in to change notification settings - Fork 3
/
device.rs
2144 lines (1802 loc) · 73.3 KB
/
device.rs
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use euclid::Transform3D;
use gleam::gl;
use internal_types::{PackedVertex, RenderTargetMode, TextureSampler, DEFAULT_TEXTURE};
use internal_types::{BlurAttribute, ClipAttribute, VertexAttribute};
use internal_types::{DebugFontVertex, DebugColorVertex, FastHashMap};
//use notify::{self, Watcher};
use super::shader_source;
use std::fs::File;
use std::io::Read;
use std::iter::repeat;
use std::mem;
use std::ops::Add;
use std::path::PathBuf;
use std::ptr;
use std::rc::Rc;
//use std::sync::mpsc::{channel, Sender};
//use std::thread;
use api::{ColorF, ImageFormat};
use api::{DeviceIntPoint, DeviceIntRect, DeviceIntSize, DeviceUintSize};
#[derive(Debug, Copy, Clone, PartialEq, Ord, Eq, PartialOrd)]
pub struct FrameId(usize);
impl FrameId {
pub fn new(value: usize) -> FrameId {
FrameId(value)
}
}
impl Add<usize> for FrameId {
type Output = FrameId;
fn add(self, other: usize) -> FrameId {
FrameId(self.0 + other)
}
}
#[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))]
const GL_FORMAT_A: gl::GLuint = gl::RED;
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
const GL_FORMAT_A: gl::GLuint = gl::ALPHA;
const GL_FORMAT_BGRA_GL: gl::GLuint = gl::BGRA;
const GL_FORMAT_BGRA_GLES: gl::GLuint = gl::BGRA_EXT;
const SHADER_VERSION_GL: &str = "#version 150\n";
const SHADER_VERSION_GLES: &str = "#version 300 es\n";
static SHADER_PREAMBLE: &str = "shared";
#[repr(u32)]
pub enum DepthFunction {
Less = gl::LESS,
LessEqual = gl::LEQUAL,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TextureTarget {
Default,
Array,
Rect,
External,
}
impl TextureTarget {
pub fn to_gl_target(&self) -> gl::GLuint {
match *self {
TextureTarget::Default => gl::TEXTURE_2D,
TextureTarget::Array => gl::TEXTURE_2D_ARRAY,
TextureTarget::Rect => gl::TEXTURE_RECTANGLE,
TextureTarget::External => gl::TEXTURE_EXTERNAL_OES,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TextureFilter {
Nearest,
Linear,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum VertexFormat {
Triangles,
DebugFont,
DebugColor,
Blur,
Clip,
}
enum FBOTarget {
Read,
Draw,
}
pub fn get_gl_format_bgra(gl: &gl::Gl) -> gl::GLuint {
match gl.get_type() {
gl::GlType::Gl => {
GL_FORMAT_BGRA_GL
}
gl::GlType::Gles => {
GL_FORMAT_BGRA_GLES
}
}
}
fn get_shader_version(gl: &gl::Gl) -> &'static str {
match gl.get_type() {
gl::GlType::Gl => {
SHADER_VERSION_GL
}
gl::GlType::Gles => {
SHADER_VERSION_GLES
}
}
}
fn get_optional_shader_source(shader_name: &str, base_path: &Option<PathBuf>) -> Option<String> {
if let Some(ref base) = *base_path {
let shader_path = base.join(&format!("{}.glsl", shader_name));
if shader_path.exists() {
let mut source = String::new();
File::open(&shader_path).unwrap().read_to_string(&mut source).unwrap();
return Some(source);
}
}
shader_source::SHADERS.get(shader_name).and_then(|s| Some((*s).to_owned()))
}
fn get_shader_source(shader_name: &str, base_path: &Option<PathBuf>) -> String {
get_optional_shader_source(shader_name, base_path)
.expect(&format!("Couldn't get required shader: {}", shader_name))
}
pub trait FileWatcherHandler : Send {
fn file_changed(&self, path: PathBuf);
}
impl VertexFormat {
fn bind(&self, gl: &gl::Gl, main: VBOId, instance: VBOId, offset: gl::GLuint, instance_stride: gl::GLint) {
main.bind(gl);
match *self {
VertexFormat::DebugFont => {
gl.enable_vertex_attrib_array(VertexAttribute::Position as gl::GLuint);
gl.enable_vertex_attrib_array(VertexAttribute::Color as gl::GLuint);
gl.enable_vertex_attrib_array(VertexAttribute::ColorTexCoord as gl::GLuint);
gl.vertex_attrib_divisor(VertexAttribute::Position as gl::GLuint, 0);
gl.vertex_attrib_divisor(VertexAttribute::Color as gl::GLuint, 0);
gl.vertex_attrib_divisor(VertexAttribute::ColorTexCoord as gl::GLuint, 0);
let vertex_stride = mem::size_of::<DebugFontVertex>() as gl::GLuint;
gl.vertex_attrib_pointer(VertexAttribute::Position as gl::GLuint,
2,
gl::FLOAT,
false,
vertex_stride as gl::GLint,
0 + vertex_stride * offset);
gl.vertex_attrib_pointer(VertexAttribute::Color as gl::GLuint,
4,
gl::UNSIGNED_BYTE,
true,
vertex_stride as gl::GLint,
8 + vertex_stride * offset);
gl.vertex_attrib_pointer(VertexAttribute::ColorTexCoord as gl::GLuint,
2,
gl::FLOAT,
false,
vertex_stride as gl::GLint,
12 + vertex_stride * offset);
}
VertexFormat::DebugColor => {
gl.enable_vertex_attrib_array(VertexAttribute::Position as gl::GLuint);
gl.enable_vertex_attrib_array(VertexAttribute::Color as gl::GLuint);
gl.vertex_attrib_divisor(VertexAttribute::Position as gl::GLuint, 0);
gl.vertex_attrib_divisor(VertexAttribute::Color as gl::GLuint, 0);
let vertex_stride = mem::size_of::<DebugColorVertex>() as gl::GLuint;
gl.vertex_attrib_pointer(VertexAttribute::Position as gl::GLuint,
2,
gl::FLOAT,
false,
vertex_stride as gl::GLint,
0 + vertex_stride * offset);
gl.vertex_attrib_pointer(VertexAttribute::Color as gl::GLuint,
4,
gl::UNSIGNED_BYTE,
true,
vertex_stride as gl::GLint,
8 + vertex_stride * offset);
}
VertexFormat::Triangles => {
let vertex_stride = mem::size_of::<PackedVertex>() as gl::GLuint;
gl.enable_vertex_attrib_array(VertexAttribute::Position as gl::GLuint);
gl.vertex_attrib_divisor(VertexAttribute::Position as gl::GLuint, 0);
gl.vertex_attrib_pointer(VertexAttribute::Position as gl::GLuint,
2,
gl::FLOAT,
false,
vertex_stride as gl::GLint,
0);
instance.bind(gl);
let mut offset = 0;
for &attrib in [VertexAttribute::Data0,
VertexAttribute::Data1,
].into_iter() {
gl.enable_vertex_attrib_array(attrib as gl::GLuint);
gl.vertex_attrib_divisor(attrib as gl::GLuint, 1);
gl.vertex_attrib_i_pointer(attrib as gl::GLuint,
4,
gl::INT,
instance_stride,
offset);
offset += 16;
}
}
VertexFormat::Blur => {
let vertex_stride = mem::size_of::<PackedVertex>() as gl::GLuint;
gl.enable_vertex_attrib_array(BlurAttribute::Position as gl::GLuint);
gl.vertex_attrib_divisor(BlurAttribute::Position as gl::GLuint, 0);
gl.vertex_attrib_pointer(BlurAttribute::Position as gl::GLuint,
2,
gl::FLOAT,
false,
vertex_stride as gl::GLint,
0);
instance.bind(gl);
for (i, &attrib) in [BlurAttribute::RenderTaskIndex,
BlurAttribute::SourceTaskIndex,
BlurAttribute::Direction,
].into_iter().enumerate() {
gl.enable_vertex_attrib_array(attrib as gl::GLuint);
gl.vertex_attrib_divisor(attrib as gl::GLuint, 1);
gl.vertex_attrib_i_pointer(attrib as gl::GLuint,
1,
gl::INT,
instance_stride,
(i * 4) as gl::GLuint);
}
}
VertexFormat::Clip => {
let vertex_stride = mem::size_of::<PackedVertex>() as gl::GLuint;
gl.enable_vertex_attrib_array(ClipAttribute::Position as gl::GLuint);
gl.vertex_attrib_divisor(ClipAttribute::Position as gl::GLuint, 0);
gl.vertex_attrib_pointer(ClipAttribute::Position as gl::GLuint,
2,
gl::FLOAT,
false,
vertex_stride as gl::GLint,
0);
instance.bind(gl);
for (i, &attrib) in [ClipAttribute::RenderTaskIndex,
ClipAttribute::LayerIndex,
ClipAttribute::DataIndex,
ClipAttribute::SegmentIndex,
ClipAttribute::ResourceAddress,
].into_iter().enumerate() {
gl.enable_vertex_attrib_array(attrib as gl::GLuint);
gl.vertex_attrib_divisor(attrib as gl::GLuint, 1);
gl.vertex_attrib_i_pointer(attrib as gl::GLuint,
1,
gl::INT,
instance_stride,
(i * 4) as gl::GLuint);
}
}
}
}
}
impl TextureId {
pub fn bind(&self, gl: &gl::Gl) {
gl.bind_texture(self.target, self.name);
}
pub fn new(name: gl::GLuint, texture_target: TextureTarget) -> TextureId {
TextureId {
name,
target: texture_target.to_gl_target(),
}
}
pub fn invalid() -> TextureId {
TextureId {
name: 0,
target: gl::TEXTURE_2D,
}
}
pub fn is_valid(&self) -> bool { *self != TextureId::invalid() }
}
impl ProgramId {
fn bind(&self, gl: &gl::Gl) {
gl.use_program(self.0);
}
}
impl VBOId {
fn bind(&self, gl: &gl::Gl) {
gl.bind_buffer(gl::ARRAY_BUFFER, self.0);
}
}
impl IBOId {
fn bind(&self, gl: &gl::Gl) {
gl.bind_buffer(gl::ELEMENT_ARRAY_BUFFER, self.0);
}
}
impl UBOId {
fn _bind(&self, gl: &gl::Gl) {
gl.bind_buffer(gl::UNIFORM_BUFFER, self.0);
}
}
impl FBOId {
fn bind(&self, gl: &gl::Gl, target: FBOTarget) {
let target = match target {
FBOTarget::Read => gl::READ_FRAMEBUFFER,
FBOTarget::Draw => gl::DRAW_FRAMEBUFFER,
};
gl.bind_framebuffer(target, self.0);
}
}
struct Texture {
gl: Rc<gl::Gl>,
id: gl::GLuint,
format: ImageFormat,
width: u32,
height: u32,
filter: TextureFilter,
mode: RenderTargetMode,
fbo_ids: Vec<FBOId>,
depth_rb: Option<RBOId>,
}
impl Drop for Texture {
fn drop(&mut self) {
if !self.fbo_ids.is_empty() {
let fbo_ids: Vec<_> = self.fbo_ids.iter().map(|&FBOId(fbo_id)| fbo_id).collect();
self.gl.delete_framebuffers(&fbo_ids[..]);
}
self.gl.delete_textures(&[self.id]);
}
}
struct Program {
gl: Rc<gl::Gl>,
id: gl::GLuint,
u_transform: gl::GLint,
u_device_pixel_ratio: gl::GLint,
name: String,
vs_source: String,
fs_source: String,
prefix: Option<String>,
vs_id: Option<gl::GLuint>,
fs_id: Option<gl::GLuint>,
}
impl Program {
fn attach_and_bind_shaders(&mut self,
vs_id: gl::GLuint,
fs_id: gl::GLuint,
vertex_format: VertexFormat) -> Result<(), ShaderError> {
self.gl.attach_shader(self.id, vs_id);
self.gl.attach_shader(self.id, fs_id);
match vertex_format {
VertexFormat::Triangles |
VertexFormat::DebugFont |
VertexFormat::DebugColor => {
self.gl.bind_attrib_location(self.id, VertexAttribute::Position as gl::GLuint, "aPosition");
self.gl.bind_attrib_location(self.id, VertexAttribute::Color as gl::GLuint, "aColor");
self.gl.bind_attrib_location(self.id, VertexAttribute::ColorTexCoord as gl::GLuint, "aColorTexCoord");
self.gl.bind_attrib_location(self.id, VertexAttribute::Data0 as gl::GLuint, "aData0");
self.gl.bind_attrib_location(self.id, VertexAttribute::Data1 as gl::GLuint, "aData1");
}
VertexFormat::Blur => {
self.gl.bind_attrib_location(self.id, BlurAttribute::Position as gl::GLuint, "aPosition");
self.gl.bind_attrib_location(self.id, BlurAttribute::RenderTaskIndex as gl::GLuint, "aBlurRenderTaskIndex");
self.gl.bind_attrib_location(self.id, BlurAttribute::SourceTaskIndex as gl::GLuint, "aBlurSourceTaskIndex");
self.gl.bind_attrib_location(self.id, BlurAttribute::Direction as gl::GLuint, "aBlurDirection");
}
VertexFormat::Clip => {
self.gl.bind_attrib_location(self.id, ClipAttribute::Position as gl::GLuint, "aPosition");
self.gl.bind_attrib_location(self.id, ClipAttribute::RenderTaskIndex as gl::GLuint, "aClipRenderTaskIndex");
self.gl.bind_attrib_location(self.id, ClipAttribute::LayerIndex as gl::GLuint, "aClipLayerIndex");
self.gl.bind_attrib_location(self.id, ClipAttribute::DataIndex as gl::GLuint, "aClipDataIndex");
self.gl.bind_attrib_location(self.id, ClipAttribute::SegmentIndex as gl::GLuint, "aClipSegmentIndex");
self.gl.bind_attrib_location(self.id, ClipAttribute::ResourceAddress as gl::GLuint, "aClipResourceAddress");
}
}
self.gl.link_program(self.id);
if self.gl.get_program_iv(self.id, gl::LINK_STATUS) == (0 as gl::GLint) {
let error_log = self.gl.get_program_info_log(self.id);
println!("Failed to link shader program: {:?}\n{}", self.name, error_log);
self.gl.detach_shader(self.id, vs_id);
self.gl.detach_shader(self.id, fs_id);
return Err(ShaderError::Link(self.name.clone(), error_log));
}
Ok(())
}
}
impl Drop for Program {
fn drop(&mut self) {
self.gl.delete_program(self.id);
}
}
struct VAO {
gl: Rc<gl::Gl>,
id: gl::GLuint,
ibo_id: IBOId,
main_vbo_id: VBOId,
instance_vbo_id: VBOId,
instance_stride: gl::GLint,
owns_indices: bool,
owns_vertices: bool,
owns_instances: bool,
}
impl Drop for VAO {
fn drop(&mut self) {
self.gl.delete_vertex_arrays(&[self.id]);
if self.owns_indices {
// todo(gw): maybe make these their own type with hashmap?
self.gl.delete_buffers(&[self.ibo_id.0]);
}
if self.owns_vertices {
self.gl.delete_buffers(&[self.main_vbo_id.0]);
}
if self.owns_instances {
self.gl.delete_buffers(&[self.instance_vbo_id.0])
}
}
}
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Copy, Clone)]
pub struct TextureId {
name: gl::GLuint,
target: gl::GLuint,
}
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct ProgramId(pub gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct VAOId(gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct FBOId(gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct RBOId(gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct VBOId(gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
struct IBOId(gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct UBOId(gl::GLuint);
#[derive(PartialEq, Eq, Hash, Debug, Copy, Clone)]
pub struct PBOId(gl::GLuint);
const MAX_EVENTS_PER_FRAME: usize = 256;
const MAX_PROFILE_FRAMES: usize = 4;
pub trait NamedTag {
fn get_label(&self) -> &str;
}
#[derive(Debug, Clone)]
pub struct GpuSample<T> {
pub tag: T,
pub time_ns: u64,
}
pub struct GpuFrameProfile<T> {
gl: Rc<gl::Gl>,
queries: Vec<gl::GLuint>,
samples: Vec<GpuSample<T>>,
next_query: usize,
pending_query: gl::GLuint,
frame_id: FrameId,
inside_frame: bool,
}
impl<T> GpuFrameProfile<T> {
fn new(gl: Rc<gl::Gl>) -> Self {
match gl.get_type() {
gl::GlType::Gl => {
let queries = gl.gen_queries(MAX_EVENTS_PER_FRAME as gl::GLint);
GpuFrameProfile {
gl,
queries,
samples: Vec::new(),
next_query: 0,
pending_query: 0,
frame_id: FrameId(0),
inside_frame: false,
}
}
gl::GlType::Gles => {
GpuFrameProfile {
gl,
queries: Vec::new(),
samples: Vec::new(),
next_query: 0,
pending_query: 0,
frame_id: FrameId(0),
inside_frame: false,
}
}
}
}
fn begin_frame(&mut self, frame_id: FrameId) {
self.frame_id = frame_id;
self.next_query = 0;
self.pending_query = 0;
self.samples.clear();
self.inside_frame = true;
}
fn end_frame(&mut self) {
self.inside_frame = false;
match self.gl.get_type() {
gl::GlType::Gl => {
if self.pending_query != 0 {
self.gl.end_query(gl::TIME_ELAPSED);
}
}
gl::GlType::Gles => {},
}
}
fn add_marker(&mut self, tag: T) -> GpuMarker
where T: NamedTag {
debug_assert!(self.inside_frame);
match self.gl.get_type() {
gl::GlType::Gl => {
self.add_marker_gl(tag)
}
gl::GlType::Gles => {
self.add_marker_gles(tag)
}
}
}
fn add_marker_gl(&mut self, tag: T) -> GpuMarker
where T: NamedTag {
if self.pending_query != 0 {
self.gl.end_query(gl::TIME_ELAPSED);
}
let marker = GpuMarker::new(&self.gl, tag.get_label());
if self.next_query < MAX_EVENTS_PER_FRAME {
self.pending_query = self.queries[self.next_query];
self.gl.begin_query(gl::TIME_ELAPSED, self.pending_query);
self.samples.push(GpuSample {
tag,
time_ns: 0,
});
} else {
self.pending_query = 0;
}
self.next_query += 1;
marker
}
fn add_marker_gles(&mut self, tag: T) -> GpuMarker
where T: NamedTag {
let marker = GpuMarker::new(&self.gl, tag.get_label());
self.samples.push(GpuSample {
tag,
time_ns: 0,
});
marker
}
fn is_valid(&self) -> bool {
self.next_query > 0 && self.next_query <= MAX_EVENTS_PER_FRAME
}
fn build_samples(&mut self) -> Vec<GpuSample<T>> {
debug_assert!(!self.inside_frame);
match self.gl.get_type() {
gl::GlType::Gl => {
self.build_samples_gl()
}
gl::GlType::Gles => {
self.build_samples_gles()
}
}
}
fn build_samples_gl(&mut self) -> Vec<GpuSample<T>> {
for (index, sample) in self.samples.iter_mut().enumerate() {
sample.time_ns = self.gl.get_query_object_ui64v(self.queries[index], gl::QUERY_RESULT)
}
mem::replace(&mut self.samples, Vec::new())
}
fn build_samples_gles(&mut self) -> Vec<GpuSample<T>> {
mem::replace(&mut self.samples, Vec::new())
}
}
impl<T> Drop for GpuFrameProfile<T> {
fn drop(&mut self) {
match self.gl.get_type() {
gl::GlType::Gl => {
self.gl.delete_queries(&self.queries);
}
gl::GlType::Gles => {},
}
}
}
pub struct GpuProfiler<T> {
frames: [GpuFrameProfile<T>; MAX_PROFILE_FRAMES],
next_frame: usize,
}
impl<T> GpuProfiler<T> {
pub fn new(gl: &Rc<gl::Gl>) -> GpuProfiler<T> {
GpuProfiler {
next_frame: 0,
frames: [
GpuFrameProfile::new(Rc::clone(gl)),
GpuFrameProfile::new(Rc::clone(gl)),
GpuFrameProfile::new(Rc::clone(gl)),
GpuFrameProfile::new(Rc::clone(gl)),
],
}
}
pub fn build_samples(&mut self) -> Option<(FrameId, Vec<GpuSample<T>>)> {
let frame = &mut self.frames[self.next_frame];
if frame.is_valid() {
Some((frame.frame_id, frame.build_samples()))
} else {
None
}
}
pub fn begin_frame(&mut self, frame_id: FrameId) {
let frame = &mut self.frames[self.next_frame];
frame.begin_frame(frame_id);
}
pub fn end_frame(&mut self) {
let frame = &mut self.frames[self.next_frame];
frame.end_frame();
self.next_frame = (self.next_frame + 1) % MAX_PROFILE_FRAMES;
}
pub fn add_marker(&mut self, tag: T) -> GpuMarker
where T: NamedTag {
self.frames[self.next_frame].add_marker(tag)
}
}
#[must_use]
pub struct GpuMarker{
gl: Rc<gl::Gl>,
}
impl GpuMarker {
pub fn new(gl: &Rc<gl::Gl>, message: &str) -> GpuMarker {
match gl.get_type() {
gl::GlType::Gl => {
gl.push_group_marker_ext(message);
GpuMarker{
gl: Rc::clone(gl),
}
}
gl::GlType::Gles => {
GpuMarker{
gl: Rc::clone(gl),
}
}
}
}
pub fn fire(gl: &gl::Gl, message: &str) {
match gl.get_type() {
gl::GlType::Gl => {
gl.insert_event_marker_ext(message);
}
gl::GlType::Gles => {},
}
}
}
#[cfg(not(any(target_arch="arm", target_arch="aarch64")))]
impl Drop for GpuMarker {
fn drop(&mut self) {
match self.gl.get_type() {
gl::GlType::Gl => {
self.gl.pop_group_marker_ext();
}
gl::GlType::Gles => {},
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum VertexUsageHint {
Static,
Dynamic,
Stream,
}
impl VertexUsageHint {
fn to_gl(&self) -> gl::GLuint {
match *self {
VertexUsageHint::Static => gl::STATIC_DRAW,
VertexUsageHint::Dynamic => gl::DYNAMIC_DRAW,
VertexUsageHint::Stream => gl::STREAM_DRAW,
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct UniformLocation(gl::GLint);
impl UniformLocation {
pub fn invalid() -> UniformLocation {
UniformLocation(-1)
}
}
// TODO(gw): Fix up notify cargo deps and re-enable this!
/*
enum FileWatcherCmd {
AddWatch(PathBuf),
Exit,
}
struct FileWatcherThread {
api_tx: Sender<FileWatcherCmd>,
}
impl FileWatcherThread {
fn new(handler: Box<FileWatcherHandler>) -> FileWatcherThread {
let (api_tx, api_rx) = channel();
thread::spawn(move || {
let (watch_tx, watch_rx) = channel();
enum Request {
Watcher(notify::Event),
Command(FileWatcherCmd),
}
let mut file_watcher: notify::RecommendedWatcher = notify::Watcher::new(watch_tx).unwrap();
loop {
let request = {
let receiver_from_api = &api_rx;
let receiver_from_watcher = &watch_rx;
select! {
msg = receiver_from_api.recv() => Request::Command(msg.unwrap()),
msg = receiver_from_watcher.recv() => Request::Watcher(msg.unwrap())
}
};
match request {
Request::Watcher(event) => {
handler.file_changed(event.path.unwrap());
}
Request::Command(cmd) => {
match cmd {
FileWatcherCmd::AddWatch(path) => {
file_watcher.watch(path).ok();
}
FileWatcherCmd::Exit => {
break;
}
}
}
}
}
});
FileWatcherThread {
api_tx,
}
}
fn exit(&self) {
self.api_tx.send(FileWatcherCmd::Exit).ok();
}
fn add_watch(&self, path: PathBuf) {
self.api_tx.send(FileWatcherCmd::AddWatch(path)).ok();
}
}
*/
pub struct Capabilities {
pub max_ubo_size: usize,
pub supports_multisampling: bool,
}
#[derive(Clone, Debug)]
pub enum ShaderError {
Compilation(String, String), // name, error mssage
Link(String, String), // name, error message
}
pub struct Device {
gl: Rc<gl::Gl>,
// device state
bound_textures: [TextureId; 16],
bound_program: ProgramId,
bound_vao: VAOId,
bound_pbo: PBOId,
bound_read_fbo: FBOId,
bound_draw_fbo: FBOId,
default_read_fbo: gl::GLuint,
default_draw_fbo: gl::GLuint,
device_pixel_ratio: f32,
// HW or API capabilties
capabilities: Capabilities,
// debug
inside_frame: bool,
// resources
resource_override_path: Option<PathBuf>,
textures: FastHashMap<TextureId, Texture>,
programs: FastHashMap<ProgramId, Program>,
vaos: FastHashMap<VAOId, VAO>,
// misc.
shader_preamble: String,
//file_watcher: FileWatcherThread,
// Used on android only
#[allow(dead_code)]
next_vao_id: gl::GLuint,
max_texture_size: u32,
// Frame counter. This is used to map between CPU
// frames and GPU frames.
frame_id: FrameId,
}
impl Device {
pub fn new(gl: Rc<gl::Gl>,
resource_override_path: Option<PathBuf>,
_file_changed_handler: Box<FileWatcherHandler>) -> Device {
//let file_watcher = FileWatcherThread::new(file_changed_handler);
let shader_preamble = get_shader_source(SHADER_PREAMBLE, &resource_override_path);
//file_watcher.add_watch(resource_path);
let max_ubo_size = gl.get_integer_v(gl::MAX_UNIFORM_BLOCK_SIZE) as usize;
let max_texture_size = gl.get_integer_v(gl::MAX_TEXTURE_SIZE) as u32;
Device {
gl,
resource_override_path,
// This is initialized to 1 by default, but it is set
// every frame by the call to begin_frame().
device_pixel_ratio: 1.0,
inside_frame: false,
capabilities: Capabilities {
max_ubo_size,
supports_multisampling: false, //TODO
},
bound_textures: [ TextureId::invalid(); 16 ],
bound_program: ProgramId(0),
bound_vao: VAOId(0),
bound_pbo: PBOId(0),
bound_read_fbo: FBOId(0),
bound_draw_fbo: FBOId(0),
default_read_fbo: 0,
default_draw_fbo: 0,
textures: FastHashMap::default(),
programs: FastHashMap::default(),
vaos: FastHashMap::default(),
shader_preamble,
next_vao_id: 1,
//file_watcher: file_watcher,
max_texture_size,
frame_id: FrameId(0),
}
}
pub fn gl(&self) -> &gl::Gl {
&*self.gl
}
pub fn rc_gl(&self) -> &Rc<gl::Gl> {
&self.gl
}
pub fn max_texture_size(&self) -> u32 {
self.max_texture_size
}
pub fn get_capabilities(&self) -> &Capabilities {
&self.capabilities
}
pub fn compile_shader(gl: &gl::Gl,
name: &str,
source_str: &str,
shader_type: gl::GLenum,
shader_preamble: &[String])
-> Result<gl::GLuint, ShaderError> {
debug!("compile {:?}", name);
let mut s = String::new();
s.push_str(get_shader_version(gl));
for prefix in shader_preamble {
s.push_str(prefix);
}
s.push_str(source_str);
let id = gl.create_shader(shader_type);
let mut source = Vec::new();
source.extend_from_slice(s.as_bytes());
gl.shader_source(id, &[&source[..]]);
gl.compile_shader(id);
let log = gl.get_shader_info_log(id);
if gl.get_shader_iv(id, gl::COMPILE_STATUS) == (0 as gl::GLint) {
println!("Failed to compile shader: {:?}\n{}", name, log);
Err(ShaderError::Compilation(name.to_string(), log))
} else {
if !log.is_empty() {
println!("Warnings detected on shader: {:?}\n{}", name, log);
}
Ok(id)
}
}
pub fn begin_frame(&mut self, device_pixel_ratio: f32) -> FrameId {
debug_assert!(!self.inside_frame);
self.inside_frame = true;
self.device_pixel_ratio = device_pixel_ratio;
// Retrive the currently set FBO.
let default_read_fbo = self.gl.get_integer_v(gl::READ_FRAMEBUFFER_BINDING);
self.default_read_fbo = default_read_fbo as gl::GLuint;
let default_draw_fbo = self.gl.get_integer_v(gl::DRAW_FRAMEBUFFER_BINDING);
self.default_draw_fbo = default_draw_fbo as gl::GLuint;
// Texture state
for i in 0..self.bound_textures.len() {
self.bound_textures[i] = TextureId::invalid();
self.gl.active_texture(gl::TEXTURE0 + i as gl::GLuint);
self.gl.bind_texture(gl::TEXTURE_2D, 0);