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
//! GPU fence synchronization (`GLsync`) and hardware performance/occlusion queries.
use std::fmt;
use std::rc::Rc;
use crate::context::{GlContext, GlInner};
use crate::error::{GlError, Result};
use crate::sys;
/// Outcome of waiting on a [`SyncFence`] from the CPU (`glClientWaitSync`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SyncWaitResult {
/// Fence was already signaled before the wait began (`GL_ALREADY_SIGNALED`).
AlreadySignaled,
/// Fence became signaled before the timeout elapsed (`GL_CONDITION_SATISFIED`).
ConditionSatisfied,
/// Timeout elapsed before the fence was signaled (`GL_TIMEOUT_EXPIRED`).
TimeoutExpired,
}
impl SyncWaitResult {
/// Returns `true` if the GPU work preceding the fence has completed.
#[inline]
pub const fn is_signaled(self) -> bool {
matches!(self, Self::AlreadySignaled | Self::ConditionSatisfied)
}
}
/// RAII wrapper around an OpenGL 3.2+ GPU fence sync object (`GLsync`).
pub struct SyncFence {
ctx: Rc<GlInner>,
raw: sys::GLsync,
}
impl fmt::Debug for SyncFence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SyncFence")
.field("raw", &(self.raw as usize))
.finish()
}
}
impl Drop for SyncFence {
fn drop(&mut self) {
if !self.raw.is_null() {
// SAFETY: `self.raw` was created by `glFenceSync` and is exclusively owned.
unsafe { (self.ctx.fns.delete_sync)(self.raw) };
}
}
}
impl SyncFence {
/// Inserts a GPU fence sync object into the OpenGL command stream (`glFenceSync`).
pub fn insert(ctx: &GlContext) -> Result<Self> {
// SAFETY: `GL_SYNC_GPU_COMMANDS_COMPLETE` and `0` are the standard GL 3.2+ arguments.
let raw = unsafe { (ctx.inner.fns.fence_sync)(sys::GL_SYNC_GPU_COMMANDS_COMPLETE, 0) };
if raw.is_null() {
return Err(GlError::ObjectCreationFailed {
object: "SyncFence",
});
}
Ok(Self {
ctx: Rc::clone(&ctx.inner),
raw,
})
}
/// Blocks the CPU until the fence is signaled or `timeout_ns` nanoseconds elapse.
///
/// When `flush` is `true`, passes `GL_SYNC_FLUSH_COMMANDS_BIT` to ensure queued
/// GPU commands are flushed before waiting.
pub fn client_wait(&self, timeout_ns: u64, flush: bool) -> Result<SyncWaitResult> {
let flags = if flush {
sys::GL_SYNC_FLUSH_COMMANDS_BIT
} else {
0
};
// SAFETY: `self.raw` is a live `GLsync` handle.
let status = unsafe { (self.ctx.fns.client_wait_sync)(self.raw, flags, timeout_ns) };
match status {
sys::GL_ALREADY_SIGNALED => Ok(SyncWaitResult::AlreadySignaled),
sys::GL_CONDITION_SATISFIED => Ok(SyncWaitResult::ConditionSatisfied),
sys::GL_TIMEOUT_EXPIRED => Ok(SyncWaitResult::TimeoutExpired),
_ => Err(GlError::SyncWaitFailed),
}
}
/// Instructs the GPU command processor to wait on this fence without blocking the CPU (`glWaitSync`).
pub fn gpu_wait(&self) {
// SAFETY: `GL_TIMEOUT_IGNORED` and `flags = 0` are required by the OpenGL specification.
unsafe { (self.ctx.fns.wait_sync)(self.raw, 0, sys::GL_TIMEOUT_IGNORED) };
}
}
/// Hardware query target type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum QueryTarget {
/// Counts fragments passing depth/stencil tests (`GL_SAMPLES_PASSED`).
SamplesPassed = sys::GL_SAMPLES_PASSED,
/// Boolean occlusion query (`GL_ANY_SAMPLES_PASSED`).
AnySamplesPassed = sys::GL_ANY_SAMPLES_PASSED,
/// Counts primitives emitted by geometry stage (`GL_PRIMITIVES_GENERATED`).
PrimitivesGenerated = sys::GL_PRIMITIVES_GENERATED,
/// GPU elapsed time in nanoseconds (`GL_TIME_ELAPSED`).
TimeElapsed = sys::GL_TIME_ELAPSED,
}
/// RAII wrapper around an OpenGL hardware query object.
pub struct Query {
ctx: Rc<GlInner>,
id: sys::GLuint,
target: QueryTarget,
}
impl fmt::Debug for Query {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Query")
.field("id", &self.id)
.field("target", &self.target)
.finish()
}
}
impl Drop for Query {
fn drop(&mut self) {
if self.id != 0 {
// SAFETY: `self.id` is exclusively owned by this `Query`.
unsafe { (self.ctx.fns.delete_queries)(1, &self.id) };
}
}
}
impl Query {
/// Allocates a new hardware query object for `target`.
pub fn new(ctx: &GlContext, target: QueryTarget) -> Result<Self> {
let mut id: sys::GLuint = 0;
// SAFETY: Generates one query name in valid stack storage.
unsafe { (ctx.inner.fns.gen_queries)(1, &mut id) };
if id == 0 {
return Err(GlError::ObjectCreationFailed { object: "Query" });
}
Ok(Self {
ctx: Rc::clone(&ctx.inner),
id,
target,
})
}
/// Returns the raw OpenGL query ID.
#[inline]
pub const fn raw_id(&self) -> u32 {
self.id
}
/// Begins recording hardware metrics for this query (`glBeginQuery`).
pub fn begin(&self) -> Result<()> {
// SAFETY: `self.target` and `self.id` are valid.
unsafe { (self.ctx.fns.begin_query)(self.target as sys::GLenum, self.id) };
self.ctx.check_gl_error("glBeginQuery")
}
/// Ends recording hardware metrics for this query (`glEndQuery`).
pub fn end(&self) -> Result<()> {
// SAFETY: `self.target` is valid.
unsafe { (self.ctx.fns.end_query)(self.target as sys::GLenum) };
self.ctx.check_gl_error("glEndQuery")
}
/// Returns `true` if the query result is ready without blocking (`GL_QUERY_RESULT_AVAILABLE`).
pub fn is_available(&self) -> bool {
let mut available: sys::GLuint = 0;
// SAFETY: Valid stack pointer for `glGetQueryObjectuiv`.
unsafe {
(self.ctx.fns.get_query_objectuiv)(
self.id,
sys::GL_QUERY_RESULT_AVAILABLE,
&mut available,
);
}
available != 0
}
/// Retrieves the 32-bit unsigned query result, blocking if not yet available.
pub fn result_u32(&self) -> u32 {
let mut val: sys::GLuint = 0;
// SAFETY: Valid stack pointer for `glGetQueryObjectuiv`.
unsafe {
(self.ctx.fns.get_query_objectuiv)(self.id, sys::GL_QUERY_RESULT, &mut val);
}
val
}
/// Retrieves the 64-bit unsigned query result (OpenGL 3.3+ `glGetQueryObjectui64v`).
pub fn result_u64(&self) -> Result<u64> {
let Some(get_ui64) = self.ctx.fns.get_query_objectui64v else {
return Err(GlError::MissingFunction {
name: "glGetQueryObjectui64v",
});
};
let mut val: sys::GLuint64 = 0;
// SAFETY: Valid stack pointer for `glGetQueryObjectui64v`.
unsafe { get_ui64(self.id, sys::GL_QUERY_RESULT, &mut val) };
Ok(val)
}
/// Records the current GPU timestamp into this query object (`glQueryCounter`, OpenGL 3.3+).
pub fn record_timestamp(&self) -> Result<()> {
let Some(query_counter) = self.ctx.fns.query_counter else {
return Err(GlError::MissingFunction {
name: "glQueryCounter",
});
};
// SAFETY: `self.id` is a valid query handle and `GL_TIMESTAMP` is the only valid target.
unsafe { query_counter(self.id, sys::GL_TIMESTAMP) };
self.ctx.check_gl_error("glQueryCounter")
}
}