use crate::{
device::{Device, DeviceOwned},
macros::vulkan_bitflags,
DeviceSize, OomError, RequirementNotMet, RequiresOneOf, VulkanError, VulkanObject,
};
use std::{
error::Error,
ffi::c_void,
fmt::{Display, Error as FmtError, Formatter},
mem::{size_of_val, MaybeUninit},
num::NonZeroU64,
ops::Range,
ptr,
sync::Arc,
};
#[derive(Debug)]
pub struct QueryPool {
handle: ash::vk::QueryPool,
device: Arc<Device>,
id: NonZeroU64,
query_type: QueryType,
query_count: u32,
}
impl QueryPool {
pub fn new(
device: Arc<Device>,
create_info: QueryPoolCreateInfo,
) -> Result<Arc<QueryPool>, QueryPoolCreationError> {
let QueryPoolCreateInfo {
query_type,
query_count,
_ne: _,
} = create_info;
assert!(query_count != 0);
let pipeline_statistics = match query_type {
QueryType::PipelineStatistics(flags) => {
if !device.enabled_features().pipeline_statistics_query {
return Err(QueryPoolCreationError::PipelineStatisticsQueryFeatureNotEnabled);
}
flags.into()
}
QueryType::Occlusion | QueryType::Timestamp => {
ash::vk::QueryPipelineStatisticFlags::empty()
}
};
let create_info = ash::vk::QueryPoolCreateInfo {
flags: ash::vk::QueryPoolCreateFlags::empty(),
query_type: query_type.into(),
query_count,
pipeline_statistics,
..Default::default()
};
let handle = unsafe {
let fns = device.fns();
let mut output = MaybeUninit::uninit();
(fns.v1_0.create_query_pool)(
device.handle(),
&create_info,
ptr::null(),
output.as_mut_ptr(),
)
.result()
.map_err(VulkanError::from)?;
output.assume_init()
};
Ok(Arc::new(QueryPool {
handle,
device,
id: Self::next_id(),
query_type,
query_count,
}))
}
#[inline]
pub unsafe fn from_handle(
device: Arc<Device>,
handle: ash::vk::QueryPool,
create_info: QueryPoolCreateInfo,
) -> Arc<QueryPool> {
let QueryPoolCreateInfo {
query_type,
query_count,
_ne: _,
} = create_info;
Arc::new(QueryPool {
handle,
device,
id: Self::next_id(),
query_type,
query_count,
})
}
#[inline]
pub fn query_type(&self) -> QueryType {
self.query_type
}
#[inline]
pub fn query_count(&self) -> u32 {
self.query_count
}
#[inline]
pub fn query(&self, index: u32) -> Option<Query<'_>> {
if index < self.query_count {
Some(Query { pool: self, index })
} else {
None
}
}
#[inline]
pub fn queries_range(&self, range: Range<u32>) -> Option<QueriesRange<'_>> {
assert!(!range.is_empty());
if range.end <= self.query_count {
Some(QueriesRange { pool: self, range })
} else {
None
}
}
}
impl Drop for QueryPool {
#[inline]
fn drop(&mut self) {
unsafe {
let fns = self.device.fns();
(fns.v1_0.destroy_query_pool)(self.device.handle(), self.handle, ptr::null());
}
}
}
unsafe impl VulkanObject for QueryPool {
type Handle = ash::vk::QueryPool;
#[inline]
fn handle(&self) -> Self::Handle {
self.handle
}
}
unsafe impl DeviceOwned for QueryPool {
#[inline]
fn device(&self) -> &Arc<Device> {
&self.device
}
}
crate::impl_id_counter!(QueryPool);
#[derive(Clone, Debug)]
pub struct QueryPoolCreateInfo {
pub query_type: QueryType,
pub query_count: u32,
pub _ne: crate::NonExhaustive,
}
impl QueryPoolCreateInfo {
#[inline]
pub fn query_type(query_type: QueryType) -> Self {
Self {
query_type,
query_count: 0,
_ne: crate::NonExhaustive(()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum QueryPoolCreationError {
OomError(OomError),
PipelineStatisticsQueryFeatureNotEnabled,
}
impl Error for QueryPoolCreationError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
QueryPoolCreationError::OomError(err) => Some(err),
_ => None,
}
}
}
impl Display for QueryPoolCreationError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(
f,
"{}",
match self {
QueryPoolCreationError::OomError(_) => "not enough memory available",
QueryPoolCreationError::PipelineStatisticsQueryFeatureNotEnabled => {
"a pipeline statistics pool was requested but the corresponding feature \
wasn't enabled"
}
}
)
}
}
impl From<OomError> for QueryPoolCreationError {
fn from(err: OomError) -> QueryPoolCreationError {
QueryPoolCreationError::OomError(err)
}
}
impl From<VulkanError> for QueryPoolCreationError {
fn from(err: VulkanError) -> QueryPoolCreationError {
match err {
err @ VulkanError::OutOfHostMemory => {
QueryPoolCreationError::OomError(OomError::from(err))
}
err @ VulkanError::OutOfDeviceMemory => {
QueryPoolCreationError::OomError(OomError::from(err))
}
_ => panic!("unexpected error: {:?}", err),
}
}
}
#[derive(Clone, Debug)]
pub struct Query<'a> {
pool: &'a QueryPool,
index: u32,
}
impl<'a> Query<'a> {
#[inline]
pub fn pool(&self) -> &'a QueryPool {
self.pool
}
#[inline]
pub fn index(&self) -> u32 {
self.index
}
}
#[derive(Clone, Debug)]
pub struct QueriesRange<'a> {
pool: &'a QueryPool,
range: Range<u32>,
}
impl<'a> QueriesRange<'a> {
#[inline]
pub fn pool(&self) -> &'a QueryPool {
self.pool
}
#[inline]
pub fn range(&self) -> Range<u32> {
self.range.clone()
}
#[inline]
pub fn get_results<T>(
&self,
destination: &mut [T],
flags: QueryResultFlags,
) -> Result<bool, GetResultsError>
where
T: QueryResultElement,
{
let stride = self.check_query_pool_results::<T>(
destination.as_ptr() as DeviceSize,
destination.len() as DeviceSize,
flags,
)?;
let result = unsafe {
let fns = self.pool.device.fns();
(fns.v1_0.get_query_pool_results)(
self.pool.device.handle(),
self.pool.handle(),
self.range.start,
self.range.end - self.range.start,
size_of_val(destination),
destination.as_mut_ptr() as *mut c_void,
stride,
ash::vk::QueryResultFlags::from(flags) | T::FLAG,
)
};
match result {
ash::vk::Result::SUCCESS => Ok(true),
ash::vk::Result::NOT_READY => Ok(false),
err => Err(VulkanError::from(err).into()),
}
}
pub(crate) fn check_query_pool_results<T>(
&self,
buffer_start: DeviceSize,
buffer_len: DeviceSize,
flags: QueryResultFlags,
) -> Result<DeviceSize, GetResultsError>
where
T: QueryResultElement,
{
flags.validate_device(&self.pool.device)?;
assert!(buffer_len > 0);
debug_assert!(buffer_start % std::mem::size_of::<T>() as DeviceSize == 0);
let count = self.range.end - self.range.start;
let per_query_len =
self.pool.query_type.result_len() + flags.with_availability as DeviceSize;
let required_len = per_query_len * count as DeviceSize;
if buffer_len < required_len {
return Err(GetResultsError::BufferTooSmall {
required_len: required_len as DeviceSize,
actual_len: buffer_len as DeviceSize,
});
}
match self.pool.query_type {
QueryType::Occlusion => (),
QueryType::PipelineStatistics(_) => (),
QueryType::Timestamp => {
if flags.partial {
return Err(GetResultsError::InvalidFlags);
}
}
}
Ok(per_query_len * std::mem::size_of::<T>() as DeviceSize)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GetResultsError {
DeviceLost,
OomError(OomError),
RequirementNotMet {
required_for: &'static str,
requires_one_of: RequiresOneOf,
},
BufferTooSmall {
required_len: DeviceSize,
actual_len: DeviceSize,
},
InvalidFlags,
}
impl Error for GetResultsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::OomError(err) => Some(err),
_ => None,
}
}
}
impl Display for GetResultsError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
match self {
Self::OomError(_) => write!(f, "not enough memory available"),
Self::DeviceLost => write!(f, "the connection to the device has been lost"),
Self::RequirementNotMet {
required_for,
requires_one_of,
} => write!(
f,
"a requirement was not met for: {}; requires one of: {}",
required_for, requires_one_of,
),
Self::BufferTooSmall { .. } => write!(f, "the buffer is too small for the operation"),
Self::InvalidFlags => write!(
f,
"the provided flags are not allowed for this type of query"
),
}
}
}
impl From<VulkanError> for GetResultsError {
fn from(err: VulkanError) -> Self {
match err {
VulkanError::OutOfHostMemory | VulkanError::OutOfDeviceMemory => {
Self::OomError(OomError::from(err))
}
VulkanError::DeviceLost => Self::DeviceLost,
_ => panic!("unexpected error: {:?}", err),
}
}
}
impl From<OomError> for GetResultsError {
fn from(err: OomError) -> Self {
Self::OomError(err)
}
}
impl From<RequirementNotMet> for GetResultsError {
fn from(err: RequirementNotMet) -> Self {
Self::RequirementNotMet {
required_for: err.required_for,
requires_one_of: err.requires_one_of,
}
}
}
pub unsafe trait QueryResultElement {
const FLAG: ash::vk::QueryResultFlags;
}
unsafe impl QueryResultElement for u32 {
const FLAG: ash::vk::QueryResultFlags = ash::vk::QueryResultFlags::empty();
}
unsafe impl QueryResultElement for u64 {
const FLAG: ash::vk::QueryResultFlags = ash::vk::QueryResultFlags::TYPE_64;
}
#[derive(Debug, Copy, Clone)]
pub enum QueryType {
Occlusion,
PipelineStatistics(QueryPipelineStatisticFlags),
Timestamp,
}
impl QueryType {
#[inline]
pub const fn result_len(&self) -> DeviceSize {
match self {
Self::Occlusion | Self::Timestamp => 1,
Self::PipelineStatistics(flags) => flags.count(),
}
}
}
impl From<QueryType> for ash::vk::QueryType {
#[inline]
fn from(value: QueryType) -> Self {
match value {
QueryType::Occlusion => ash::vk::QueryType::OCCLUSION,
QueryType::PipelineStatistics(_) => ash::vk::QueryType::PIPELINE_STATISTICS,
QueryType::Timestamp => ash::vk::QueryType::TIMESTAMP,
}
}
}
vulkan_bitflags! {
#[non_exhaustive]
QueryControlFlags = QueryControlFlags(u32);
precise = PRECISE,
}
vulkan_bitflags! {
#[non_exhaustive]
QueryPipelineStatisticFlags = QueryPipelineStatisticFlags(u32);
input_assembly_vertices = INPUT_ASSEMBLY_VERTICES,
input_assembly_primitives = INPUT_ASSEMBLY_PRIMITIVES,
vertex_shader_invocations = VERTEX_SHADER_INVOCATIONS,
geometry_shader_invocations = GEOMETRY_SHADER_INVOCATIONS,
geometry_shader_primitives = GEOMETRY_SHADER_PRIMITIVES,
clipping_invocations = CLIPPING_INVOCATIONS,
clipping_primitives = CLIPPING_PRIMITIVES,
fragment_shader_invocations = FRAGMENT_SHADER_INVOCATIONS,
tessellation_control_shader_patches = TESSELLATION_CONTROL_SHADER_PATCHES,
tessellation_evaluation_shader_invocations = TESSELLATION_EVALUATION_SHADER_INVOCATIONS,
compute_shader_invocations = COMPUTE_SHADER_INVOCATIONS,
}
impl QueryPipelineStatisticFlags {
#[inline]
pub const fn count(&self) -> DeviceSize {
let &Self {
input_assembly_vertices,
input_assembly_primitives,
vertex_shader_invocations,
geometry_shader_invocations,
geometry_shader_primitives,
clipping_invocations,
clipping_primitives,
fragment_shader_invocations,
tessellation_control_shader_patches,
tessellation_evaluation_shader_invocations,
compute_shader_invocations,
_ne: _,
} = self;
input_assembly_vertices as DeviceSize
+ input_assembly_primitives as DeviceSize
+ vertex_shader_invocations as DeviceSize
+ geometry_shader_invocations as DeviceSize
+ geometry_shader_primitives as DeviceSize
+ clipping_invocations as DeviceSize
+ clipping_primitives as DeviceSize
+ fragment_shader_invocations as DeviceSize
+ tessellation_control_shader_patches as DeviceSize
+ tessellation_evaluation_shader_invocations as DeviceSize
+ compute_shader_invocations as DeviceSize
}
#[inline]
pub const fn is_compute(&self) -> bool {
let &Self {
compute_shader_invocations,
..
} = self;
compute_shader_invocations
}
#[inline]
pub const fn is_graphics(&self) -> bool {
let &Self {
input_assembly_vertices,
input_assembly_primitives,
vertex_shader_invocations,
geometry_shader_invocations,
geometry_shader_primitives,
clipping_invocations,
clipping_primitives,
fragment_shader_invocations,
tessellation_control_shader_patches,
tessellation_evaluation_shader_invocations,
..
} = self;
input_assembly_vertices
|| input_assembly_primitives
|| vertex_shader_invocations
|| geometry_shader_invocations
|| geometry_shader_primitives
|| clipping_invocations
|| clipping_primitives
|| fragment_shader_invocations
|| tessellation_control_shader_patches
|| tessellation_evaluation_shader_invocations
}
}
vulkan_bitflags! {
#[non_exhaustive]
QueryResultFlags = QueryResultFlags(u32);
wait = WAIT,
with_availability = WITH_AVAILABILITY,
partial = PARTIAL,
}
#[cfg(test)]
mod tests {
use super::QueryPoolCreateInfo;
use crate::query::{QueryPipelineStatisticFlags, QueryPool, QueryPoolCreationError, QueryType};
#[test]
fn pipeline_statistics_feature() {
let (device, _) = gfx_dev_and_queue!();
let query_type = QueryType::PipelineStatistics(QueryPipelineStatisticFlags::empty());
match QueryPool::new(
device,
QueryPoolCreateInfo {
query_count: 256,
..QueryPoolCreateInfo::query_type(query_type)
},
) {
Err(QueryPoolCreationError::PipelineStatisticsQueryFeatureNotEnabled) => (),
_ => panic!(),
};
}
}