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
use gl;
use gl::types::*;
use std::mem;
use std::time;
use state::StateRef;
use std::cell::Cell;
#[derive(PartialEq, Eq)]
pub struct TimeStamp{
id: GLuint,
gl: StateRef,
}
impl TimeStamp{
pub(crate) fn new(gl: &StateRef) -> TimeStamp {
unsafe {
let mut id = mem::MaybeUninit::uninit();
gl.GenQueries(1, id.as_mut_ptr());
TimeStamp{
id: id.assume_init(),
gl: gl.clone(),
}
}
}
pub fn count(&mut self) {
unsafe {
self.gl.QueryCounter(self.id, gl::TIMESTAMP)
}
}
pub fn is_result_available(&self) -> bool{
unsafe {
let mut available = gl::FALSE as i32;
self.gl.GetQueryObjectiv(self.id, gl::QUERY_RESULT_AVAILABLE, &mut available);
available != gl::FALSE as i32
}
}
pub fn result(&self) -> Option<time::Duration> {
if self.is_result_available(){
let nanos = unsafe{ self.result_unchecked() };
let secs = nanos / 1_000_000_000;
let nanos_subsec = nanos - secs * 1_000_000_000;
Some(time::Duration::new(secs, nanos_subsec as u32))
}else{
None
}
}
pub unsafe fn result_unchecked(&self) -> u64 {
let mut time = mem::MaybeUninit::uninit();
self.gl.GetQueryObjectui64v(self.id, gl::QUERY_RESULT, time.as_mut_ptr());
time.assume_init()
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
enum DurationState{
Init,
Start,
Calculating,
Done,
}
pub struct Duration{
start: TimeStamp,
end: TimeStamp,
state: Cell<DurationState>,
}
impl Duration{
pub(crate) fn new(gl: &StateRef) -> Duration {
Duration{
start: TimeStamp::new(gl),
end: TimeStamp::new(gl),
state: Cell::new(DurationState::Init),
}
}
pub fn begin(&mut self){
if self.state.get() == DurationState::Init || self.state.get() == DurationState::Done{
self.start.count();
self.state.set(DurationState::Start);
}
}
pub fn end(&mut self){
if self.state.get() == DurationState::Start {
self.end.count();
self.state.set(DurationState::Calculating);
}
}
pub fn is_result_available(&self) -> bool{
self.state.get() == DurationState::Calculating &&
self.start.is_result_available() &&
self.end.is_result_available()
}
pub fn result(&self) -> Option<time::Duration> {
if self.is_result_available(){
let start = unsafe{ self.start.result_unchecked() };
let end = unsafe{ self.end.result_unchecked() };
self.state.set(DurationState::Done);
if end >= start{
let nanos = end - start;
let secs = nanos / 1_000_000_000;
let nanos_subsec = nanos - secs * 1_000_000_000;
Some(time::Duration::new(secs, nanos_subsec as u32))
}else{
None
}
}else{
None
}
}
pub unsafe fn result_unchecked(&self) -> u64 {
let start = self.start.result_unchecked();
let end = self.end.result_unchecked();
end - start
}
}