Skip to main content

mtl_gpu/device/
depth_stencil.rs

1//! Device depth/stencil state creation methods.
2//!
3//! Corresponds to depth/stencil state creation methods in `Metal/MTLDevice.hpp`.
4
5use std::ffi::c_void;
6
7use mtl_foundation::Referencing;
8use mtl_sys::{msg_send_1, sel};
9
10use super::Device;
11use crate::depth_stencil::{DepthStencilDescriptor, DepthStencilState};
12
13impl Device {
14    // =========================================================================
15    // Depth/Stencil State Creation
16    // =========================================================================
17
18    /// Create a new depth/stencil state with the specified descriptor.
19    ///
20    /// C++ equivalent: `DepthStencilState* newDepthStencilState(const DepthStencilDescriptor*)`
21    pub fn new_depth_stencil_state(
22        &self,
23        descriptor: &DepthStencilDescriptor,
24    ) -> Option<DepthStencilState> {
25        unsafe {
26            let ptr: *mut c_void = msg_send_1(
27                self.as_ptr(),
28                sel!(newDepthStencilStateWithDescriptor:),
29                descriptor.as_ptr(),
30            );
31            DepthStencilState::from_raw(ptr)
32        }
33    }
34
35    /// Create a new depth/stencil state with a raw descriptor pointer.
36    ///
37    /// C++ equivalent: `DepthStencilState* newDepthStencilState(const DepthStencilDescriptor*)`
38    ///
39    /// # Safety
40    ///
41    /// The descriptor pointer must be valid.
42    pub unsafe fn new_depth_stencil_state_with_ptr(
43        &self,
44        descriptor: *const c_void,
45    ) -> Option<DepthStencilState> {
46        unsafe {
47            let ptr: *mut c_void = msg_send_1(
48                self.as_ptr(),
49                sel!(newDepthStencilStateWithDescriptor:),
50                descriptor,
51            );
52            DepthStencilState::from_raw(ptr)
53        }
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60    use crate::device::system_default;
61    use crate::enums::CompareFunction;
62
63    #[test]
64    fn test_new_depth_stencil_state() {
65        let device = system_default().expect("no Metal device");
66        let descriptor = DepthStencilDescriptor::new().expect("failed to create descriptor");
67
68        descriptor.set_depth_compare_function(CompareFunction::LESS);
69        descriptor.set_depth_write_enabled(true);
70
71        let state = device.new_depth_stencil_state(&descriptor);
72        assert!(state.is_some());
73    }
74}